MachO.h 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  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. /// ChainedFixupTarget holds all the information about an external symbol
  229. /// necessary to bind this binary to that symbol. These values are referenced
  230. /// indirectly by chained fixup binds. This structure captures values from all
  231. /// import and symbol formats.
  232. ///
  233. /// Be aware there are two notions of weak here:
  234. /// WeakImport == true
  235. /// The associated bind may be set to 0 if this symbol is missing from its
  236. /// parent library. This is called a "weak import."
  237. /// LibOrdinal == BIND_SPECIAL_DYLIB_WEAK_LOOKUP
  238. /// This symbol may be coalesced with other libraries vending the same
  239. /// symbol. E.g., C++'s "operator new". This is called a "weak bind."
  240. struct ChainedFixupTarget {
  241. public:
  242. ChainedFixupTarget(int LibOrdinal, uint32_t NameOffset, StringRef Symbol,
  243. uint64_t Addend, bool WeakImport)
  244. : LibOrdinal(LibOrdinal), NameOffset(NameOffset), SymbolName(Symbol),
  245. Addend(Addend), WeakImport(WeakImport) {}
  246. int libOrdinal() { return LibOrdinal; }
  247. uint32_t nameOffset() { return NameOffset; }
  248. StringRef symbolName() { return SymbolName; }
  249. uint64_t addend() { return Addend; }
  250. bool weakImport() { return WeakImport; }
  251. bool weakBind() {
  252. return LibOrdinal == MachO::BIND_SPECIAL_DYLIB_WEAK_LOOKUP;
  253. }
  254. private:
  255. int LibOrdinal;
  256. uint32_t NameOffset;
  257. StringRef SymbolName;
  258. uint64_t Addend;
  259. bool WeakImport;
  260. };
  261. struct ChainedFixupsSegment {
  262. ChainedFixupsSegment(uint8_t SegIdx, uint32_t Offset,
  263. const MachO::dyld_chained_starts_in_segment &Header,
  264. std::vector<uint16_t> &&PageStarts)
  265. : SegIdx(SegIdx), Offset(Offset), Header(Header),
  266. PageStarts(PageStarts){};
  267. uint32_t SegIdx;
  268. uint32_t Offset; // dyld_chained_starts_in_image::seg_info_offset[SegIdx]
  269. MachO::dyld_chained_starts_in_segment Header;
  270. std::vector<uint16_t> PageStarts; // page_start[] entries, host endianness
  271. };
  272. /// MachOAbstractFixupEntry is an abstract class representing a fixup in a
  273. /// MH_DYLDLINK file. Fixups generally represent rebases and binds. Binds also
  274. /// subdivide into additional subtypes (weak, lazy, reexport).
  275. ///
  276. /// The two concrete subclasses of MachOAbstractFixupEntry are:
  277. ///
  278. /// MachORebaseBindEntry - for dyld opcode-based tables, including threaded-
  279. /// rebase, where rebases are mixed in with other
  280. /// bind opcodes.
  281. /// MachOChainedFixupEntry - for pointer chains embedded in data pages.
  282. class MachOAbstractFixupEntry {
  283. public:
  284. MachOAbstractFixupEntry(Error *Err, const MachOObjectFile *O);
  285. int32_t segmentIndex() const;
  286. uint64_t segmentOffset() const;
  287. uint64_t segmentAddress() const;
  288. StringRef segmentName() const;
  289. StringRef sectionName() const;
  290. StringRef typeName() const;
  291. StringRef symbolName() const;
  292. uint32_t flags() const;
  293. int64_t addend() const;
  294. int ordinal() const;
  295. /// \return the location of this fixup as a VM Address. For the VM
  296. /// Address this fixup is pointing to, use pointerValue().
  297. uint64_t address() const;
  298. /// \return the VM Address pointed to by this fixup. Use
  299. /// pointerValue() to compare against other VM Addresses, such as
  300. /// section addresses or segment vmaddrs.
  301. uint64_t pointerValue() const { return PointerValue; }
  302. /// \return the raw "on-disk" representation of the fixup. For
  303. /// Threaded rebases and Chained pointers these values are generally
  304. /// encoded into various different pointer formats. This value is
  305. /// exposed in API for tools that want to display and annotate the
  306. /// raw bits.
  307. uint64_t rawValue() const { return RawValue; }
  308. void moveNext();
  309. protected:
  310. Error *E;
  311. const MachOObjectFile *O;
  312. uint64_t SegmentOffset = 0;
  313. int32_t SegmentIndex = -1;
  314. StringRef SymbolName;
  315. int32_t Ordinal = 0;
  316. uint32_t Flags = 0;
  317. int64_t Addend = 0;
  318. uint64_t PointerValue = 0;
  319. uint64_t RawValue = 0;
  320. bool Done = false;
  321. void moveToFirst();
  322. void moveToEnd();
  323. /// \return the vm address of the start of __TEXT segment.
  324. uint64_t textAddress() const { return TextAddress; }
  325. private:
  326. uint64_t TextAddress;
  327. };
  328. class MachOChainedFixupEntry : public MachOAbstractFixupEntry {
  329. public:
  330. enum class FixupKind { Bind, Rebase };
  331. MachOChainedFixupEntry(Error *Err, const MachOObjectFile *O, bool Parse);
  332. bool operator==(const MachOChainedFixupEntry &) const;
  333. bool isBind() const { return Kind == FixupKind::Bind; }
  334. bool isRebase() const { return Kind == FixupKind::Rebase; }
  335. void moveNext();
  336. void moveToFirst();
  337. void moveToEnd();
  338. private:
  339. void findNextPageWithFixups();
  340. std::vector<ChainedFixupTarget> FixupTargets;
  341. std::vector<ChainedFixupsSegment> Segments;
  342. ArrayRef<uint8_t> SegmentData;
  343. FixupKind Kind;
  344. uint32_t InfoSegIndex = 0; // Index into Segments
  345. uint32_t PageIndex = 0; // Index into Segments[InfoSegIdx].PageStarts
  346. uint32_t PageOffset = 0; // Page offset of the current fixup
  347. };
  348. using fixup_iterator = content_iterator<MachOChainedFixupEntry>;
  349. class MachOObjectFile : public ObjectFile {
  350. public:
  351. struct LoadCommandInfo {
  352. const char *Ptr; // Where in memory the load command is.
  353. MachO::load_command C; // The command itself.
  354. };
  355. using LoadCommandList = SmallVector<LoadCommandInfo, 4>;
  356. using load_command_iterator = LoadCommandList::const_iterator;
  357. static Expected<std::unique_ptr<MachOObjectFile>>
  358. create(MemoryBufferRef Object, bool IsLittleEndian, bool Is64Bits,
  359. uint32_t UniversalCputype = 0, uint32_t UniversalIndex = 0);
  360. static bool isMachOPairedReloc(uint64_t RelocType, uint64_t Arch);
  361. void moveSymbolNext(DataRefImpl &Symb) const override;
  362. uint64_t getNValue(DataRefImpl Sym) const;
  363. Expected<StringRef> getSymbolName(DataRefImpl Symb) const override;
  364. // MachO specific.
  365. Error checkSymbolTable() const;
  366. std::error_code getIndirectName(DataRefImpl Symb, StringRef &Res) const;
  367. unsigned getSectionType(SectionRef Sec) const;
  368. Expected<uint64_t> getSymbolAddress(DataRefImpl Symb) const override;
  369. uint32_t getSymbolAlignment(DataRefImpl Symb) const override;
  370. uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override;
  371. Expected<SymbolRef::Type> getSymbolType(DataRefImpl Symb) const override;
  372. Expected<uint32_t> getSymbolFlags(DataRefImpl Symb) const override;
  373. Expected<section_iterator> getSymbolSection(DataRefImpl Symb) const override;
  374. unsigned getSymbolSectionID(SymbolRef Symb) const;
  375. unsigned getSectionID(SectionRef Sec) const;
  376. void moveSectionNext(DataRefImpl &Sec) const override;
  377. Expected<StringRef> getSectionName(DataRefImpl Sec) const override;
  378. uint64_t getSectionAddress(DataRefImpl Sec) const override;
  379. uint64_t getSectionIndex(DataRefImpl Sec) const override;
  380. uint64_t getSectionSize(DataRefImpl Sec) const override;
  381. ArrayRef<uint8_t> getSectionContents(uint32_t Offset, uint64_t Size) const;
  382. Expected<ArrayRef<uint8_t>>
  383. getSectionContents(DataRefImpl Sec) const override;
  384. uint64_t getSectionAlignment(DataRefImpl Sec) const override;
  385. Expected<SectionRef> getSection(unsigned SectionIndex) const;
  386. Expected<SectionRef> getSection(StringRef SectionName) const;
  387. bool isSectionCompressed(DataRefImpl Sec) const override;
  388. bool isSectionText(DataRefImpl Sec) const override;
  389. bool isSectionData(DataRefImpl Sec) const override;
  390. bool isSectionBSS(DataRefImpl Sec) const override;
  391. bool isSectionVirtual(DataRefImpl Sec) const override;
  392. bool isSectionBitcode(DataRefImpl Sec) const override;
  393. bool isDebugSection(DataRefImpl Sec) const override;
  394. /// Return the raw contents of an entire segment.
  395. ArrayRef<uint8_t> getSegmentContents(StringRef SegmentName) const;
  396. ArrayRef<uint8_t> getSegmentContents(size_t SegmentIndex) const;
  397. /// When dsymutil generates the companion file, it strips all unnecessary
  398. /// sections (e.g. everything in the _TEXT segment) by omitting their body
  399. /// and setting the offset in their corresponding load command to zero.
  400. ///
  401. /// While the load command itself is valid, reading the section corresponds
  402. /// to reading the number of bytes specified in the load command, starting
  403. /// from offset 0 (i.e. the Mach-O header at the beginning of the file).
  404. bool isSectionStripped(DataRefImpl Sec) const override;
  405. relocation_iterator section_rel_begin(DataRefImpl Sec) const override;
  406. relocation_iterator section_rel_end(DataRefImpl Sec) const override;
  407. relocation_iterator extrel_begin() const;
  408. relocation_iterator extrel_end() const;
  409. iterator_range<relocation_iterator> external_relocations() const {
  410. return make_range(extrel_begin(), extrel_end());
  411. }
  412. relocation_iterator locrel_begin() const;
  413. relocation_iterator locrel_end() const;
  414. void moveRelocationNext(DataRefImpl &Rel) const override;
  415. uint64_t getRelocationOffset(DataRefImpl Rel) const override;
  416. symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
  417. section_iterator getRelocationSection(DataRefImpl Rel) const;
  418. uint64_t getRelocationType(DataRefImpl Rel) const override;
  419. void getRelocationTypeName(DataRefImpl Rel,
  420. SmallVectorImpl<char> &Result) const override;
  421. uint8_t getRelocationLength(DataRefImpl Rel) const;
  422. // MachO specific.
  423. std::error_code getLibraryShortNameByIndex(unsigned Index, StringRef &) const;
  424. uint32_t getLibraryCount() const;
  425. section_iterator getRelocationRelocatedSection(relocation_iterator Rel) const;
  426. // TODO: Would be useful to have an iterator based version
  427. // of the load command interface too.
  428. basic_symbol_iterator symbol_begin() const override;
  429. basic_symbol_iterator symbol_end() const override;
  430. // MachO specific.
  431. symbol_iterator getSymbolByIndex(unsigned Index) const;
  432. uint64_t getSymbolIndex(DataRefImpl Symb) const;
  433. section_iterator section_begin() const override;
  434. section_iterator section_end() const override;
  435. uint8_t getBytesInAddress() const override;
  436. StringRef getFileFormatName() const override;
  437. Triple::ArchType getArch() const override;
  438. Expected<SubtargetFeatures> getFeatures() const override {
  439. return SubtargetFeatures();
  440. }
  441. Triple getArchTriple(const char **McpuDefault = nullptr) const;
  442. relocation_iterator section_rel_begin(unsigned Index) const;
  443. relocation_iterator section_rel_end(unsigned Index) const;
  444. dice_iterator begin_dices() const;
  445. dice_iterator end_dices() const;
  446. load_command_iterator begin_load_commands() const;
  447. load_command_iterator end_load_commands() const;
  448. iterator_range<load_command_iterator> load_commands() const;
  449. /// For use iterating over all exported symbols.
  450. iterator_range<export_iterator> exports(Error &Err) const;
  451. /// For use examining a trie not in a MachOObjectFile.
  452. static iterator_range<export_iterator> exports(Error &Err,
  453. ArrayRef<uint8_t> Trie,
  454. const MachOObjectFile *O =
  455. nullptr);
  456. /// For use iterating over all rebase table entries.
  457. iterator_range<rebase_iterator> rebaseTable(Error &Err);
  458. /// For use examining rebase opcodes in a MachOObjectFile.
  459. static iterator_range<rebase_iterator> rebaseTable(Error &Err,
  460. MachOObjectFile *O,
  461. ArrayRef<uint8_t> Opcodes,
  462. bool is64);
  463. /// For use iterating over all bind table entries.
  464. iterator_range<bind_iterator> bindTable(Error &Err);
  465. /// For iterating over all chained fixups.
  466. iterator_range<fixup_iterator> fixupTable(Error &Err);
  467. /// For use iterating over all lazy bind table entries.
  468. iterator_range<bind_iterator> lazyBindTable(Error &Err);
  469. /// For use iterating over all weak bind table entries.
  470. iterator_range<bind_iterator> weakBindTable(Error &Err);
  471. /// For use examining bind opcodes in a MachOObjectFile.
  472. static iterator_range<bind_iterator> bindTable(Error &Err,
  473. MachOObjectFile *O,
  474. ArrayRef<uint8_t> Opcodes,
  475. bool is64,
  476. MachOBindEntry::Kind);
  477. // Given a SegIndex, SegOffset, and PointerSize, verify a valid section exists
  478. // that fully contains a pointer at that location. Multiple fixups in a bind
  479. // (such as with the BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB opcode) can
  480. // be tested via the Count and Skip parameters.
  481. //
  482. // This is used by MachOBindEntry::moveNext() to validate a MachOBindEntry.
  483. const char *BindEntryCheckSegAndOffsets(int32_t SegIndex, uint64_t SegOffset,
  484. uint8_t PointerSize, uint32_t Count=1,
  485. uint32_t Skip=0) const {
  486. return BindRebaseSectionTable->checkSegAndOffsets(SegIndex, SegOffset,
  487. PointerSize, Count, Skip);
  488. }
  489. // Given a SegIndex, SegOffset, and PointerSize, verify a valid section exists
  490. // that fully contains a pointer at that location. Multiple fixups in a rebase
  491. // (such as with the REBASE_OPCODE_DO_*_TIMES* opcodes) can be tested via the
  492. // Count and Skip parameters.
  493. //
  494. // This is used by MachORebaseEntry::moveNext() to validate a MachORebaseEntry
  495. const char *RebaseEntryCheckSegAndOffsets(int32_t SegIndex,
  496. uint64_t SegOffset,
  497. uint8_t PointerSize,
  498. uint32_t Count=1,
  499. uint32_t Skip=0) const {
  500. return BindRebaseSectionTable->checkSegAndOffsets(SegIndex, SegOffset,
  501. PointerSize, Count, Skip);
  502. }
  503. /// For use with the SegIndex of a checked Mach-O Bind or Rebase entry to
  504. /// get the segment name.
  505. StringRef BindRebaseSegmentName(int32_t SegIndex) const {
  506. return BindRebaseSectionTable->segmentName(SegIndex);
  507. }
  508. /// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or
  509. /// Rebase entry to get the section name.
  510. StringRef BindRebaseSectionName(uint32_t SegIndex, uint64_t SegOffset) const {
  511. return BindRebaseSectionTable->sectionName(SegIndex, SegOffset);
  512. }
  513. /// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or
  514. /// Rebase entry to get the address.
  515. uint64_t BindRebaseAddress(uint32_t SegIndex, uint64_t SegOffset) const {
  516. return BindRebaseSectionTable->address(SegIndex, SegOffset);
  517. }
  518. // In a MachO file, sections have a segment name. This is used in the .o
  519. // files. They have a single segment, but this field specifies which segment
  520. // a section should be put in the final object.
  521. StringRef getSectionFinalSegmentName(DataRefImpl Sec) const;
  522. // Names are stored as 16 bytes. These returns the raw 16 bytes without
  523. // interpreting them as a C string.
  524. ArrayRef<char> getSectionRawName(DataRefImpl Sec) const;
  525. ArrayRef<char> getSectionRawFinalSegmentName(DataRefImpl Sec) const;
  526. // MachO specific Info about relocations.
  527. bool isRelocationScattered(const MachO::any_relocation_info &RE) const;
  528. unsigned getPlainRelocationSymbolNum(
  529. const MachO::any_relocation_info &RE) const;
  530. bool getPlainRelocationExternal(const MachO::any_relocation_info &RE) const;
  531. bool getScatteredRelocationScattered(
  532. const MachO::any_relocation_info &RE) const;
  533. uint32_t getScatteredRelocationValue(
  534. const MachO::any_relocation_info &RE) const;
  535. uint32_t getScatteredRelocationType(
  536. const MachO::any_relocation_info &RE) const;
  537. unsigned getAnyRelocationAddress(const MachO::any_relocation_info &RE) const;
  538. unsigned getAnyRelocationPCRel(const MachO::any_relocation_info &RE) const;
  539. unsigned getAnyRelocationLength(const MachO::any_relocation_info &RE) const;
  540. unsigned getAnyRelocationType(const MachO::any_relocation_info &RE) const;
  541. SectionRef getAnyRelocationSection(const MachO::any_relocation_info &RE) const;
  542. // MachO specific structures.
  543. MachO::section getSection(DataRefImpl DRI) const;
  544. MachO::section_64 getSection64(DataRefImpl DRI) const;
  545. MachO::section getSection(const LoadCommandInfo &L, unsigned Index) const;
  546. MachO::section_64 getSection64(const LoadCommandInfo &L,unsigned Index) const;
  547. MachO::nlist getSymbolTableEntry(DataRefImpl DRI) const;
  548. MachO::nlist_64 getSymbol64TableEntry(DataRefImpl DRI) const;
  549. MachO::linkedit_data_command
  550. getLinkeditDataLoadCommand(const LoadCommandInfo &L) const;
  551. MachO::segment_command
  552. getSegmentLoadCommand(const LoadCommandInfo &L) const;
  553. MachO::segment_command_64
  554. getSegment64LoadCommand(const LoadCommandInfo &L) const;
  555. MachO::linker_option_command
  556. getLinkerOptionLoadCommand(const LoadCommandInfo &L) const;
  557. MachO::version_min_command
  558. getVersionMinLoadCommand(const LoadCommandInfo &L) const;
  559. MachO::note_command
  560. getNoteLoadCommand(const LoadCommandInfo &L) const;
  561. MachO::build_version_command
  562. getBuildVersionLoadCommand(const LoadCommandInfo &L) const;
  563. MachO::build_tool_version
  564. getBuildToolVersion(unsigned index) const;
  565. MachO::dylib_command
  566. getDylibIDLoadCommand(const LoadCommandInfo &L) const;
  567. MachO::dyld_info_command
  568. getDyldInfoLoadCommand(const LoadCommandInfo &L) const;
  569. MachO::dylinker_command
  570. getDylinkerCommand(const LoadCommandInfo &L) const;
  571. MachO::uuid_command
  572. getUuidCommand(const LoadCommandInfo &L) const;
  573. MachO::rpath_command
  574. getRpathCommand(const LoadCommandInfo &L) const;
  575. MachO::source_version_command
  576. getSourceVersionCommand(const LoadCommandInfo &L) const;
  577. MachO::entry_point_command
  578. getEntryPointCommand(const LoadCommandInfo &L) const;
  579. MachO::encryption_info_command
  580. getEncryptionInfoCommand(const LoadCommandInfo &L) const;
  581. MachO::encryption_info_command_64
  582. getEncryptionInfoCommand64(const LoadCommandInfo &L) const;
  583. MachO::sub_framework_command
  584. getSubFrameworkCommand(const LoadCommandInfo &L) const;
  585. MachO::sub_umbrella_command
  586. getSubUmbrellaCommand(const LoadCommandInfo &L) const;
  587. MachO::sub_library_command
  588. getSubLibraryCommand(const LoadCommandInfo &L) const;
  589. MachO::sub_client_command
  590. getSubClientCommand(const LoadCommandInfo &L) const;
  591. MachO::routines_command
  592. getRoutinesCommand(const LoadCommandInfo &L) const;
  593. MachO::routines_command_64
  594. getRoutinesCommand64(const LoadCommandInfo &L) const;
  595. MachO::thread_command
  596. getThreadCommand(const LoadCommandInfo &L) const;
  597. MachO::any_relocation_info getRelocation(DataRefImpl Rel) const;
  598. MachO::data_in_code_entry getDice(DataRefImpl Rel) const;
  599. const MachO::mach_header &getHeader() const;
  600. const MachO::mach_header_64 &getHeader64() const;
  601. uint32_t
  602. getIndirectSymbolTableEntry(const MachO::dysymtab_command &DLC,
  603. unsigned Index) const;
  604. MachO::data_in_code_entry getDataInCodeTableEntry(uint32_t DataOffset,
  605. unsigned Index) const;
  606. MachO::symtab_command getSymtabLoadCommand() const;
  607. MachO::dysymtab_command getDysymtabLoadCommand() const;
  608. MachO::linkedit_data_command getDataInCodeLoadCommand() const;
  609. MachO::linkedit_data_command getLinkOptHintsLoadCommand() const;
  610. ArrayRef<uint8_t> getDyldInfoRebaseOpcodes() const;
  611. ArrayRef<uint8_t> getDyldInfoBindOpcodes() const;
  612. ArrayRef<uint8_t> getDyldInfoWeakBindOpcodes() const;
  613. ArrayRef<uint8_t> getDyldInfoLazyBindOpcodes() const;
  614. ArrayRef<uint8_t> getDyldInfoExportsTrie() const;
  615. /// If the optional is None, no header was found, but the object was
  616. /// well-formed.
  617. Expected<std::optional<MachO::dyld_chained_fixups_header>>
  618. getChainedFixupsHeader() const;
  619. Expected<std::vector<ChainedFixupTarget>> getDyldChainedFixupTargets() const;
  620. // Note: This is a limited, temporary API, which will be removed when Apple
  621. // upstreams their implementation. Please do not rely on this.
  622. Expected<std::optional<MachO::linkedit_data_command>>
  623. getChainedFixupsLoadCommand() const;
  624. // Returns the number of sections listed in dyld_chained_starts_in_image, and
  625. // a ChainedFixupsSegment for each segment that has fixups.
  626. Expected<std::pair<size_t, std::vector<ChainedFixupsSegment>>>
  627. getChainedFixupsSegments() const;
  628. ArrayRef<uint8_t> getDyldExportsTrie() const;
  629. SmallVector<uint64_t> getFunctionStarts() const;
  630. ArrayRef<uint8_t> getUuid() const;
  631. StringRef getStringTableData() const;
  632. bool is64Bit() const;
  633. void ReadULEB128s(uint64_t Index, SmallVectorImpl<uint64_t> &Out) const;
  634. static StringRef guessLibraryShortName(StringRef Name, bool &isFramework,
  635. StringRef &Suffix);
  636. static Triple::ArchType getArch(uint32_t CPUType, uint32_t CPUSubType);
  637. static Triple getArchTriple(uint32_t CPUType, uint32_t CPUSubType,
  638. const char **McpuDefault = nullptr,
  639. const char **ArchFlag = nullptr);
  640. static bool isValidArch(StringRef ArchFlag);
  641. static ArrayRef<StringRef> getValidArchs();
  642. static Triple getHostArch();
  643. bool isRelocatableObject() const override;
  644. StringRef mapDebugSectionName(StringRef Name) const override;
  645. llvm::binaryformat::Swift5ReflectionSectionKind
  646. mapReflectionSectionNameToEnumValue(StringRef SectionName) const override;
  647. bool hasPageZeroSegment() const { return HasPageZeroSegment; }
  648. static bool classof(const Binary *v) {
  649. return v->isMachO();
  650. }
  651. static uint32_t
  652. getVersionMinMajor(MachO::version_min_command &C, bool SDK) {
  653. uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version;
  654. return (VersionOrSDK >> 16) & 0xffff;
  655. }
  656. static uint32_t
  657. getVersionMinMinor(MachO::version_min_command &C, bool SDK) {
  658. uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version;
  659. return (VersionOrSDK >> 8) & 0xff;
  660. }
  661. static uint32_t
  662. getVersionMinUpdate(MachO::version_min_command &C, bool SDK) {
  663. uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version;
  664. return VersionOrSDK & 0xff;
  665. }
  666. static std::string getBuildPlatform(uint32_t platform) {
  667. switch (platform) {
  668. case MachO::PLATFORM_MACOS: return "macos";
  669. case MachO::PLATFORM_IOS: return "ios";
  670. case MachO::PLATFORM_TVOS: return "tvos";
  671. case MachO::PLATFORM_WATCHOS: return "watchos";
  672. case MachO::PLATFORM_BRIDGEOS: return "bridgeos";
  673. case MachO::PLATFORM_MACCATALYST: return "macCatalyst";
  674. case MachO::PLATFORM_IOSSIMULATOR: return "iossimulator";
  675. case MachO::PLATFORM_TVOSSIMULATOR: return "tvossimulator";
  676. case MachO::PLATFORM_WATCHOSSIMULATOR: return "watchossimulator";
  677. case MachO::PLATFORM_DRIVERKIT: return "driverkit";
  678. default:
  679. std::string ret;
  680. raw_string_ostream ss(ret);
  681. ss << format_hex(platform, 8, true);
  682. return ss.str();
  683. }
  684. }
  685. static std::string getBuildTool(uint32_t tools) {
  686. switch (tools) {
  687. case MachO::TOOL_CLANG: return "clang";
  688. case MachO::TOOL_SWIFT: return "swift";
  689. case MachO::TOOL_LD: return "ld";
  690. default:
  691. std::string ret;
  692. raw_string_ostream ss(ret);
  693. ss << format_hex(tools, 8, true);
  694. return ss.str();
  695. }
  696. }
  697. static std::string getVersionString(uint32_t version) {
  698. uint32_t major = (version >> 16) & 0xffff;
  699. uint32_t minor = (version >> 8) & 0xff;
  700. uint32_t update = version & 0xff;
  701. SmallString<32> Version;
  702. Version = utostr(major) + "." + utostr(minor);
  703. if (update != 0)
  704. Version += "." + utostr(update);
  705. return std::string(std::string(Version.str()));
  706. }
  707. /// If the input path is a .dSYM bundle (as created by the dsymutil tool),
  708. /// return the paths to the object files found in the bundle, otherwise return
  709. /// an empty vector. If the path appears to be a .dSYM bundle but no objects
  710. /// were found or there was a filesystem error, then return an error.
  711. static Expected<std::vector<std::string>>
  712. findDsymObjectMembers(StringRef Path);
  713. private:
  714. MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian, bool Is64Bits,
  715. Error &Err, uint32_t UniversalCputype = 0,
  716. uint32_t UniversalIndex = 0);
  717. uint64_t getSymbolValueImpl(DataRefImpl Symb) const override;
  718. union {
  719. MachO::mach_header_64 Header64;
  720. MachO::mach_header Header;
  721. };
  722. using SectionList = SmallVector<const char*, 1>;
  723. SectionList Sections;
  724. using LibraryList = SmallVector<const char*, 1>;
  725. LibraryList Libraries;
  726. LoadCommandList LoadCommands;
  727. using LibraryShortName = SmallVector<StringRef, 1>;
  728. using BuildToolList = SmallVector<const char*, 1>;
  729. BuildToolList BuildTools;
  730. mutable LibraryShortName LibrariesShortNames;
  731. std::unique_ptr<BindRebaseSegInfo> BindRebaseSectionTable;
  732. const char *SymtabLoadCmd = nullptr;
  733. const char *DysymtabLoadCmd = nullptr;
  734. const char *DataInCodeLoadCmd = nullptr;
  735. const char *LinkOptHintsLoadCmd = nullptr;
  736. const char *DyldInfoLoadCmd = nullptr;
  737. const char *FuncStartsLoadCmd = nullptr;
  738. const char *DyldChainedFixupsLoadCmd = nullptr;
  739. const char *DyldExportsTrieLoadCmd = nullptr;
  740. const char *UuidLoadCmd = nullptr;
  741. bool HasPageZeroSegment = false;
  742. };
  743. /// DiceRef
  744. inline DiceRef::DiceRef(DataRefImpl DiceP, const ObjectFile *Owner)
  745. : DicePimpl(DiceP) , OwningObject(Owner) {}
  746. inline bool DiceRef::operator==(const DiceRef &Other) const {
  747. return DicePimpl == Other.DicePimpl;
  748. }
  749. inline bool DiceRef::operator<(const DiceRef &Other) const {
  750. return DicePimpl < Other.DicePimpl;
  751. }
  752. inline void DiceRef::moveNext() {
  753. const MachO::data_in_code_entry *P =
  754. reinterpret_cast<const MachO::data_in_code_entry *>(DicePimpl.p);
  755. DicePimpl.p = reinterpret_cast<uintptr_t>(P + 1);
  756. }
  757. // Since a Mach-O data in code reference, a DiceRef, can only be created when
  758. // the OwningObject ObjectFile is a MachOObjectFile a static_cast<> is used for
  759. // the methods that get the values of the fields of the reference.
  760. inline std::error_code DiceRef::getOffset(uint32_t &Result) const {
  761. const MachOObjectFile *MachOOF =
  762. static_cast<const MachOObjectFile *>(OwningObject);
  763. MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
  764. Result = Dice.offset;
  765. return std::error_code();
  766. }
  767. inline std::error_code DiceRef::getLength(uint16_t &Result) const {
  768. const MachOObjectFile *MachOOF =
  769. static_cast<const MachOObjectFile *>(OwningObject);
  770. MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
  771. Result = Dice.length;
  772. return std::error_code();
  773. }
  774. inline std::error_code DiceRef::getKind(uint16_t &Result) const {
  775. const MachOObjectFile *MachOOF =
  776. static_cast<const MachOObjectFile *>(OwningObject);
  777. MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
  778. Result = Dice.kind;
  779. return std::error_code();
  780. }
  781. inline DataRefImpl DiceRef::getRawDataRefImpl() const {
  782. return DicePimpl;
  783. }
  784. inline const ObjectFile *DiceRef::getObjectFile() const {
  785. return OwningObject;
  786. }
  787. } // end namespace object
  788. } // end namespace llvm
  789. #endif // LLVM_OBJECT_MACHO_H
  790. #ifdef __GNUC__
  791. #pragma GCC diagnostic pop
  792. #endif