MachOReader.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. //===- MachOReader.cpp ------------------------------------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "MachOReader.h"
  9. #include "Object.h"
  10. #include "llvm/BinaryFormat/MachO.h"
  11. #include "llvm/Object/MachO.h"
  12. #include "llvm/Support/Errc.h"
  13. #include <memory>
  14. using namespace llvm;
  15. using namespace llvm::objcopy;
  16. using namespace llvm::objcopy::macho;
  17. void MachOReader::readHeader(Object &O) const {
  18. O.Header.Magic = MachOObj.getHeader().magic;
  19. O.Header.CPUType = MachOObj.getHeader().cputype;
  20. O.Header.CPUSubType = MachOObj.getHeader().cpusubtype;
  21. O.Header.FileType = MachOObj.getHeader().filetype;
  22. O.Header.NCmds = MachOObj.getHeader().ncmds;
  23. O.Header.SizeOfCmds = MachOObj.getHeader().sizeofcmds;
  24. O.Header.Flags = MachOObj.getHeader().flags;
  25. }
  26. template <typename SectionType>
  27. static Section constructSectionCommon(const SectionType &Sec, uint32_t Index) {
  28. StringRef SegName(Sec.segname, strnlen(Sec.segname, sizeof(Sec.segname)));
  29. StringRef SectName(Sec.sectname, strnlen(Sec.sectname, sizeof(Sec.sectname)));
  30. Section S(SegName, SectName);
  31. S.Index = Index;
  32. S.Addr = Sec.addr;
  33. S.Size = Sec.size;
  34. S.OriginalOffset = Sec.offset;
  35. S.Align = Sec.align;
  36. S.RelOff = Sec.reloff;
  37. S.NReloc = Sec.nreloc;
  38. S.Flags = Sec.flags;
  39. S.Reserved1 = Sec.reserved1;
  40. S.Reserved2 = Sec.reserved2;
  41. S.Reserved3 = 0;
  42. return S;
  43. }
  44. Section constructSection(const MachO::section &Sec, uint32_t Index) {
  45. return constructSectionCommon(Sec, Index);
  46. }
  47. Section constructSection(const MachO::section_64 &Sec, uint32_t Index) {
  48. Section S = constructSectionCommon(Sec, Index);
  49. S.Reserved3 = Sec.reserved3;
  50. return S;
  51. }
  52. template <typename SectionType, typename SegmentType>
  53. Expected<std::vector<std::unique_ptr<Section>>> static extractSections(
  54. const object::MachOObjectFile::LoadCommandInfo &LoadCmd,
  55. const object::MachOObjectFile &MachOObj, uint32_t &NextSectionIndex) {
  56. std::vector<std::unique_ptr<Section>> Sections;
  57. for (auto Curr = reinterpret_cast<const SectionType *>(LoadCmd.Ptr +
  58. sizeof(SegmentType)),
  59. End = reinterpret_cast<const SectionType *>(LoadCmd.Ptr +
  60. LoadCmd.C.cmdsize);
  61. Curr < End; ++Curr) {
  62. SectionType Sec;
  63. memcpy((void *)&Sec, Curr, sizeof(SectionType));
  64. if (MachOObj.isLittleEndian() != sys::IsLittleEndianHost)
  65. MachO::swapStruct(Sec);
  66. Sections.push_back(
  67. std::make_unique<Section>(constructSection(Sec, NextSectionIndex)));
  68. Section &S = *Sections.back();
  69. Expected<object::SectionRef> SecRef =
  70. MachOObj.getSection(NextSectionIndex++);
  71. if (!SecRef)
  72. return SecRef.takeError();
  73. Expected<ArrayRef<uint8_t>> Data =
  74. MachOObj.getSectionContents(SecRef->getRawDataRefImpl());
  75. if (!Data)
  76. return Data.takeError();
  77. S.Content =
  78. StringRef(reinterpret_cast<const char *>(Data->data()), Data->size());
  79. const uint32_t CPUType = MachOObj.getHeader().cputype;
  80. S.Relocations.reserve(S.NReloc);
  81. for (auto RI = MachOObj.section_rel_begin(SecRef->getRawDataRefImpl()),
  82. RE = MachOObj.section_rel_end(SecRef->getRawDataRefImpl());
  83. RI != RE; ++RI) {
  84. RelocationInfo R;
  85. R.Symbol = nullptr; // We'll fill this field later.
  86. R.Info = MachOObj.getRelocation(RI->getRawDataRefImpl());
  87. R.Scattered = MachOObj.isRelocationScattered(R.Info);
  88. unsigned Type = MachOObj.getAnyRelocationType(R.Info);
  89. // TODO Support CPU_TYPE_ARM.
  90. R.IsAddend = !R.Scattered && (CPUType == MachO::CPU_TYPE_ARM64 &&
  91. Type == MachO::ARM64_RELOC_ADDEND);
  92. R.Extern = !R.Scattered && MachOObj.getPlainRelocationExternal(R.Info);
  93. S.Relocations.push_back(R);
  94. }
  95. assert(S.NReloc == S.Relocations.size() &&
  96. "Incorrect number of relocations");
  97. }
  98. return std::move(Sections);
  99. }
  100. Error MachOReader::readLoadCommands(Object &O) const {
  101. // For MachO sections indices start from 1.
  102. uint32_t NextSectionIndex = 1;
  103. static constexpr char TextSegmentName[] = "__TEXT";
  104. for (auto LoadCmd : MachOObj.load_commands()) {
  105. LoadCommand LC;
  106. switch (LoadCmd.C.cmd) {
  107. case MachO::LC_CODE_SIGNATURE:
  108. O.CodeSignatureCommandIndex = O.LoadCommands.size();
  109. break;
  110. case MachO::LC_SEGMENT:
  111. // LoadCmd.Ptr might not be aligned temporarily as
  112. // MachO::segment_command requires, but the segname char pointer do not
  113. // have alignment restrictions.
  114. if (StringRef(reinterpret_cast<const char *>(
  115. LoadCmd.Ptr + offsetof(MachO::segment_command, segname))) ==
  116. TextSegmentName)
  117. O.TextSegmentCommandIndex = O.LoadCommands.size();
  118. if (Expected<std::vector<std::unique_ptr<Section>>> Sections =
  119. extractSections<MachO::section, MachO::segment_command>(
  120. LoadCmd, MachOObj, NextSectionIndex))
  121. LC.Sections = std::move(*Sections);
  122. else
  123. return Sections.takeError();
  124. break;
  125. case MachO::LC_SEGMENT_64:
  126. // LoadCmd.Ptr might not be aligned temporarily as
  127. // MachO::segment_command_64 requires, but the segname char pointer do
  128. // not have alignment restrictions.
  129. if (StringRef(reinterpret_cast<const char *>(
  130. LoadCmd.Ptr + offsetof(MachO::segment_command_64, segname))) ==
  131. TextSegmentName)
  132. O.TextSegmentCommandIndex = O.LoadCommands.size();
  133. if (Expected<std::vector<std::unique_ptr<Section>>> Sections =
  134. extractSections<MachO::section_64, MachO::segment_command_64>(
  135. LoadCmd, MachOObj, NextSectionIndex))
  136. LC.Sections = std::move(*Sections);
  137. else
  138. return Sections.takeError();
  139. break;
  140. case MachO::LC_SYMTAB:
  141. O.SymTabCommandIndex = O.LoadCommands.size();
  142. break;
  143. case MachO::LC_DYSYMTAB:
  144. O.DySymTabCommandIndex = O.LoadCommands.size();
  145. break;
  146. case MachO::LC_DYLD_INFO:
  147. case MachO::LC_DYLD_INFO_ONLY:
  148. O.DyLdInfoCommandIndex = O.LoadCommands.size();
  149. break;
  150. case MachO::LC_DATA_IN_CODE:
  151. O.DataInCodeCommandIndex = O.LoadCommands.size();
  152. break;
  153. case MachO::LC_LINKER_OPTIMIZATION_HINT:
  154. O.LinkerOptimizationHintCommandIndex = O.LoadCommands.size();
  155. break;
  156. case MachO::LC_FUNCTION_STARTS:
  157. O.FunctionStartsCommandIndex = O.LoadCommands.size();
  158. break;
  159. case MachO::LC_DYLD_EXPORTS_TRIE:
  160. O.ExportsTrieCommandIndex = O.LoadCommands.size();
  161. break;
  162. case MachO::LC_DYLD_CHAINED_FIXUPS:
  163. O.ChainedFixupsCommandIndex = O.LoadCommands.size();
  164. break;
  165. }
  166. #define HANDLE_LOAD_COMMAND(LCName, LCValue, LCStruct) \
  167. case MachO::LCName: \
  168. memcpy((void *)&(LC.MachOLoadCommand.LCStruct##_data), LoadCmd.Ptr, \
  169. sizeof(MachO::LCStruct)); \
  170. if (MachOObj.isLittleEndian() != sys::IsLittleEndianHost) \
  171. MachO::swapStruct(LC.MachOLoadCommand.LCStruct##_data); \
  172. if (LoadCmd.C.cmdsize > sizeof(MachO::LCStruct)) \
  173. LC.Payload = ArrayRef<uint8_t>( \
  174. reinterpret_cast<uint8_t *>(const_cast<char *>(LoadCmd.Ptr)) + \
  175. sizeof(MachO::LCStruct), \
  176. LoadCmd.C.cmdsize - sizeof(MachO::LCStruct)); \
  177. break;
  178. switch (LoadCmd.C.cmd) {
  179. default:
  180. memcpy((void *)&(LC.MachOLoadCommand.load_command_data), LoadCmd.Ptr,
  181. sizeof(MachO::load_command));
  182. if (MachOObj.isLittleEndian() != sys::IsLittleEndianHost)
  183. MachO::swapStruct(LC.MachOLoadCommand.load_command_data);
  184. if (LoadCmd.C.cmdsize > sizeof(MachO::load_command))
  185. LC.Payload = ArrayRef<uint8_t>(
  186. reinterpret_cast<uint8_t *>(const_cast<char *>(LoadCmd.Ptr)) +
  187. sizeof(MachO::load_command),
  188. LoadCmd.C.cmdsize - sizeof(MachO::load_command));
  189. break;
  190. #include "llvm/BinaryFormat/MachO.def"
  191. }
  192. O.LoadCommands.push_back(std::move(LC));
  193. }
  194. return Error::success();
  195. }
  196. template <typename nlist_t>
  197. SymbolEntry constructSymbolEntry(StringRef StrTable, const nlist_t &nlist) {
  198. assert(nlist.n_strx < StrTable.size() &&
  199. "n_strx exceeds the size of the string table");
  200. SymbolEntry SE;
  201. SE.Name = StringRef(StrTable.data() + nlist.n_strx).str();
  202. SE.n_type = nlist.n_type;
  203. SE.n_sect = nlist.n_sect;
  204. SE.n_desc = nlist.n_desc;
  205. SE.n_value = nlist.n_value;
  206. return SE;
  207. }
  208. void MachOReader::readSymbolTable(Object &O) const {
  209. StringRef StrTable = MachOObj.getStringTableData();
  210. for (auto Symbol : MachOObj.symbols()) {
  211. SymbolEntry SE =
  212. (MachOObj.is64Bit()
  213. ? constructSymbolEntry(StrTable, MachOObj.getSymbol64TableEntry(
  214. Symbol.getRawDataRefImpl()))
  215. : constructSymbolEntry(StrTable, MachOObj.getSymbolTableEntry(
  216. Symbol.getRawDataRefImpl())));
  217. O.SymTable.Symbols.push_back(std::make_unique<SymbolEntry>(SE));
  218. }
  219. }
  220. void MachOReader::setSymbolInRelocationInfo(Object &O) const {
  221. std::vector<const Section *> Sections;
  222. for (auto &LC : O.LoadCommands)
  223. for (std::unique_ptr<Section> &Sec : LC.Sections)
  224. Sections.push_back(Sec.get());
  225. for (LoadCommand &LC : O.LoadCommands)
  226. for (std::unique_ptr<Section> &Sec : LC.Sections)
  227. for (auto &Reloc : Sec->Relocations)
  228. if (!Reloc.Scattered && !Reloc.IsAddend) {
  229. const uint32_t SymbolNum =
  230. Reloc.getPlainRelocationSymbolNum(MachOObj.isLittleEndian());
  231. if (Reloc.Extern) {
  232. Reloc.Symbol = O.SymTable.getSymbolByIndex(SymbolNum);
  233. } else {
  234. // FIXME: Refactor error handling in MachOReader and report an error
  235. // if we encounter an invalid relocation.
  236. assert(SymbolNum >= 1 && SymbolNum <= Sections.size() &&
  237. "Invalid section index.");
  238. Reloc.Sec = Sections[SymbolNum - 1];
  239. }
  240. }
  241. }
  242. void MachOReader::readRebaseInfo(Object &O) const {
  243. O.Rebases.Opcodes = MachOObj.getDyldInfoRebaseOpcodes();
  244. }
  245. void MachOReader::readBindInfo(Object &O) const {
  246. O.Binds.Opcodes = MachOObj.getDyldInfoBindOpcodes();
  247. }
  248. void MachOReader::readWeakBindInfo(Object &O) const {
  249. O.WeakBinds.Opcodes = MachOObj.getDyldInfoWeakBindOpcodes();
  250. }
  251. void MachOReader::readLazyBindInfo(Object &O) const {
  252. O.LazyBinds.Opcodes = MachOObj.getDyldInfoLazyBindOpcodes();
  253. }
  254. void MachOReader::readExportInfo(Object &O) const {
  255. O.Exports.Trie = MachOObj.getDyldInfoExportsTrie();
  256. }
  257. void MachOReader::readLinkData(Object &O, Optional<size_t> LCIndex,
  258. LinkData &LD) const {
  259. if (!LCIndex)
  260. return;
  261. const MachO::linkedit_data_command &LC =
  262. O.LoadCommands[*LCIndex].MachOLoadCommand.linkedit_data_command_data;
  263. LD.Data =
  264. arrayRefFromStringRef(MachOObj.getData().substr(LC.dataoff, LC.datasize));
  265. }
  266. void MachOReader::readDataInCodeData(Object &O) const {
  267. return readLinkData(O, O.DataInCodeCommandIndex, O.DataInCode);
  268. }
  269. void MachOReader::readLinkerOptimizationHint(Object &O) const {
  270. return readLinkData(O, O.LinkerOptimizationHintCommandIndex,
  271. O.LinkerOptimizationHint);
  272. }
  273. void MachOReader::readFunctionStartsData(Object &O) const {
  274. return readLinkData(O, O.FunctionStartsCommandIndex, O.FunctionStarts);
  275. }
  276. void MachOReader::readExportsTrie(Object &O) const {
  277. return readLinkData(O, O.ExportsTrieCommandIndex, O.ExportsTrie);
  278. }
  279. void MachOReader::readChainedFixups(Object &O) const {
  280. return readLinkData(O, O.ChainedFixupsCommandIndex, O.ChainedFixups);
  281. }
  282. void MachOReader::readIndirectSymbolTable(Object &O) const {
  283. MachO::dysymtab_command DySymTab = MachOObj.getDysymtabLoadCommand();
  284. constexpr uint32_t AbsOrLocalMask =
  285. MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS;
  286. for (uint32_t i = 0; i < DySymTab.nindirectsyms; ++i) {
  287. uint32_t Index = MachOObj.getIndirectSymbolTableEntry(DySymTab, i);
  288. if ((Index & AbsOrLocalMask) != 0)
  289. O.IndirectSymTable.Symbols.emplace_back(Index, None);
  290. else
  291. O.IndirectSymTable.Symbols.emplace_back(
  292. Index, O.SymTable.getSymbolByIndex(Index));
  293. }
  294. }
  295. void MachOReader::readSwiftVersion(Object &O) const {
  296. struct ObjCImageInfo {
  297. uint32_t Version;
  298. uint32_t Flags;
  299. } ImageInfo;
  300. for (const LoadCommand &LC : O.LoadCommands)
  301. for (const std::unique_ptr<Section> &Sec : LC.Sections)
  302. if (Sec->Sectname == "__objc_imageinfo" &&
  303. (Sec->Segname == "__DATA" || Sec->Segname == "__DATA_CONST" ||
  304. Sec->Segname == "__DATA_DIRTY") &&
  305. Sec->Content.size() >= sizeof(ObjCImageInfo)) {
  306. memcpy(&ImageInfo, Sec->Content.data(), sizeof(ObjCImageInfo));
  307. if (MachOObj.isLittleEndian() != sys::IsLittleEndianHost) {
  308. sys::swapByteOrder(ImageInfo.Version);
  309. sys::swapByteOrder(ImageInfo.Flags);
  310. }
  311. O.SwiftVersion = (ImageInfo.Flags >> 8) & 0xff;
  312. return;
  313. }
  314. }
  315. Expected<std::unique_ptr<Object>> MachOReader::create() const {
  316. auto Obj = std::make_unique<Object>();
  317. readHeader(*Obj);
  318. if (Error E = readLoadCommands(*Obj))
  319. return std::move(E);
  320. readSymbolTable(*Obj);
  321. setSymbolInRelocationInfo(*Obj);
  322. readRebaseInfo(*Obj);
  323. readBindInfo(*Obj);
  324. readWeakBindInfo(*Obj);
  325. readLazyBindInfo(*Obj);
  326. readExportInfo(*Obj);
  327. readDataInCodeData(*Obj);
  328. readLinkerOptimizationHint(*Obj);
  329. readFunctionStartsData(*Obj);
  330. readExportsTrie(*Obj);
  331. readChainedFixups(*Obj);
  332. readIndirectSymbolTable(*Obj);
  333. readSwiftVersion(*Obj);
  334. return std::move(Obj);
  335. }