MachOEmitter.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  1. //===- yaml2macho - Convert YAML to a Mach object file --------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. ///
  9. /// \file
  10. /// The Mach component of yaml2obj.
  11. ///
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/BinaryFormat/MachO.h"
  14. #include "llvm/ObjectYAML/DWARFEmitter.h"
  15. #include "llvm/ObjectYAML/ObjectYAML.h"
  16. #include "llvm/ObjectYAML/yaml2obj.h"
  17. #include "llvm/Support/Errc.h"
  18. #include "llvm/Support/Error.h"
  19. #include "llvm/Support/LEB128.h"
  20. #include "llvm/Support/YAMLTraits.h"
  21. #include "llvm/Support/raw_ostream.h"
  22. #include "llvm/Support/Format.h"
  23. using namespace llvm;
  24. namespace {
  25. class MachOWriter {
  26. public:
  27. MachOWriter(MachOYAML::Object &Obj) : Obj(Obj), fileStart(0) {
  28. is64Bit = Obj.Header.magic == MachO::MH_MAGIC_64 ||
  29. Obj.Header.magic == MachO::MH_CIGAM_64;
  30. memset(reinterpret_cast<void *>(&Header), 0, sizeof(MachO::mach_header_64));
  31. }
  32. Error writeMachO(raw_ostream &OS);
  33. private:
  34. void writeHeader(raw_ostream &OS);
  35. void writeLoadCommands(raw_ostream &OS);
  36. Error writeSectionData(raw_ostream &OS);
  37. void writeRelocations(raw_ostream &OS);
  38. void writeLinkEditData(raw_ostream &OS);
  39. void writeBindOpcodes(raw_ostream &OS,
  40. std::vector<MachOYAML::BindOpcode> &BindOpcodes);
  41. // LinkEdit writers
  42. void writeRebaseOpcodes(raw_ostream &OS);
  43. void writeBasicBindOpcodes(raw_ostream &OS);
  44. void writeWeakBindOpcodes(raw_ostream &OS);
  45. void writeLazyBindOpcodes(raw_ostream &OS);
  46. void writeNameList(raw_ostream &OS);
  47. void writeStringTable(raw_ostream &OS);
  48. void writeExportTrie(raw_ostream &OS);
  49. void writeDynamicSymbolTable(raw_ostream &OS);
  50. void dumpExportEntry(raw_ostream &OS, MachOYAML::ExportEntry &Entry);
  51. void ZeroToOffset(raw_ostream &OS, size_t offset);
  52. MachOYAML::Object &Obj;
  53. bool is64Bit;
  54. uint64_t fileStart;
  55. MachO::mach_header_64 Header;
  56. // Old PPC Object Files didn't have __LINKEDIT segments, the data was just
  57. // stuck at the end of the file.
  58. bool FoundLinkEditSeg = false;
  59. };
  60. Error MachOWriter::writeMachO(raw_ostream &OS) {
  61. fileStart = OS.tell();
  62. writeHeader(OS);
  63. writeLoadCommands(OS);
  64. if (Error Err = writeSectionData(OS))
  65. return Err;
  66. writeRelocations(OS);
  67. if (!FoundLinkEditSeg)
  68. writeLinkEditData(OS);
  69. return Error::success();
  70. }
  71. void MachOWriter::writeHeader(raw_ostream &OS) {
  72. Header.magic = Obj.Header.magic;
  73. Header.cputype = Obj.Header.cputype;
  74. Header.cpusubtype = Obj.Header.cpusubtype;
  75. Header.filetype = Obj.Header.filetype;
  76. Header.ncmds = Obj.Header.ncmds;
  77. Header.sizeofcmds = Obj.Header.sizeofcmds;
  78. Header.flags = Obj.Header.flags;
  79. Header.reserved = Obj.Header.reserved;
  80. if (Obj.IsLittleEndian != sys::IsLittleEndianHost)
  81. MachO::swapStruct(Header);
  82. auto header_size =
  83. is64Bit ? sizeof(MachO::mach_header_64) : sizeof(MachO::mach_header);
  84. OS.write((const char *)&Header, header_size);
  85. }
  86. template <typename SectionType>
  87. SectionType constructSection(MachOYAML::Section Sec) {
  88. SectionType TempSec;
  89. memcpy(reinterpret_cast<void *>(&TempSec.sectname[0]), &Sec.sectname[0], 16);
  90. memcpy(reinterpret_cast<void *>(&TempSec.segname[0]), &Sec.segname[0], 16);
  91. TempSec.addr = Sec.addr;
  92. TempSec.size = Sec.size;
  93. TempSec.offset = Sec.offset;
  94. TempSec.align = Sec.align;
  95. TempSec.reloff = Sec.reloff;
  96. TempSec.nreloc = Sec.nreloc;
  97. TempSec.flags = Sec.flags;
  98. TempSec.reserved1 = Sec.reserved1;
  99. TempSec.reserved2 = Sec.reserved2;
  100. return TempSec;
  101. }
  102. template <typename StructType>
  103. size_t writeLoadCommandData(MachOYAML::LoadCommand &LC, raw_ostream &OS,
  104. bool IsLittleEndian) {
  105. return 0;
  106. }
  107. template <>
  108. size_t writeLoadCommandData<MachO::segment_command>(MachOYAML::LoadCommand &LC,
  109. raw_ostream &OS,
  110. bool IsLittleEndian) {
  111. size_t BytesWritten = 0;
  112. for (const auto &Sec : LC.Sections) {
  113. auto TempSec = constructSection<MachO::section>(Sec);
  114. if (IsLittleEndian != sys::IsLittleEndianHost)
  115. MachO::swapStruct(TempSec);
  116. OS.write(reinterpret_cast<const char *>(&(TempSec)),
  117. sizeof(MachO::section));
  118. BytesWritten += sizeof(MachO::section);
  119. }
  120. return BytesWritten;
  121. }
  122. template <>
  123. size_t writeLoadCommandData<MachO::segment_command_64>(
  124. MachOYAML::LoadCommand &LC, raw_ostream &OS, bool IsLittleEndian) {
  125. size_t BytesWritten = 0;
  126. for (const auto &Sec : LC.Sections) {
  127. auto TempSec = constructSection<MachO::section_64>(Sec);
  128. TempSec.reserved3 = Sec.reserved3;
  129. if (IsLittleEndian != sys::IsLittleEndianHost)
  130. MachO::swapStruct(TempSec);
  131. OS.write(reinterpret_cast<const char *>(&(TempSec)),
  132. sizeof(MachO::section_64));
  133. BytesWritten += sizeof(MachO::section_64);
  134. }
  135. return BytesWritten;
  136. }
  137. size_t writePayloadString(MachOYAML::LoadCommand &LC, raw_ostream &OS) {
  138. size_t BytesWritten = 0;
  139. if (!LC.Content.empty()) {
  140. OS.write(LC.Content.c_str(), LC.Content.length());
  141. BytesWritten = LC.Content.length();
  142. }
  143. return BytesWritten;
  144. }
  145. template <>
  146. size_t writeLoadCommandData<MachO::dylib_command>(MachOYAML::LoadCommand &LC,
  147. raw_ostream &OS,
  148. bool IsLittleEndian) {
  149. return writePayloadString(LC, OS);
  150. }
  151. template <>
  152. size_t writeLoadCommandData<MachO::dylinker_command>(MachOYAML::LoadCommand &LC,
  153. raw_ostream &OS,
  154. bool IsLittleEndian) {
  155. return writePayloadString(LC, OS);
  156. }
  157. template <>
  158. size_t writeLoadCommandData<MachO::rpath_command>(MachOYAML::LoadCommand &LC,
  159. raw_ostream &OS,
  160. bool IsLittleEndian) {
  161. return writePayloadString(LC, OS);
  162. }
  163. template <>
  164. size_t writeLoadCommandData<MachO::sub_framework_command>(
  165. MachOYAML::LoadCommand &LC, raw_ostream &OS, bool IsLittleEndian) {
  166. return writePayloadString(LC, OS);
  167. }
  168. template <>
  169. size_t writeLoadCommandData<MachO::sub_umbrella_command>(
  170. MachOYAML::LoadCommand &LC, raw_ostream &OS, bool IsLittleEndian) {
  171. return writePayloadString(LC, OS);
  172. }
  173. template <>
  174. size_t writeLoadCommandData<MachO::sub_client_command>(
  175. MachOYAML::LoadCommand &LC, raw_ostream &OS, bool IsLittleEndian) {
  176. return writePayloadString(LC, OS);
  177. }
  178. template <>
  179. size_t writeLoadCommandData<MachO::sub_library_command>(
  180. MachOYAML::LoadCommand &LC, raw_ostream &OS, bool IsLittleEndian) {
  181. return writePayloadString(LC, OS);
  182. }
  183. template <>
  184. size_t writeLoadCommandData<MachO::build_version_command>(
  185. MachOYAML::LoadCommand &LC, raw_ostream &OS, bool IsLittleEndian) {
  186. size_t BytesWritten = 0;
  187. for (const auto &T : LC.Tools) {
  188. struct MachO::build_tool_version tool = T;
  189. if (IsLittleEndian != sys::IsLittleEndianHost)
  190. MachO::swapStruct(tool);
  191. OS.write(reinterpret_cast<const char *>(&tool),
  192. sizeof(MachO::build_tool_version));
  193. BytesWritten += sizeof(MachO::build_tool_version);
  194. }
  195. return BytesWritten;
  196. }
  197. void ZeroFillBytes(raw_ostream &OS, size_t Size) {
  198. std::vector<uint8_t> FillData(Size, 0);
  199. OS.write(reinterpret_cast<char *>(FillData.data()), Size);
  200. }
  201. void Fill(raw_ostream &OS, size_t Size, uint32_t Data) {
  202. std::vector<uint32_t> FillData((Size / 4) + 1, Data);
  203. OS.write(reinterpret_cast<char *>(FillData.data()), Size);
  204. }
  205. void MachOWriter::ZeroToOffset(raw_ostream &OS, size_t Offset) {
  206. auto currOffset = OS.tell() - fileStart;
  207. if (currOffset < Offset)
  208. ZeroFillBytes(OS, Offset - currOffset);
  209. }
  210. void MachOWriter::writeLoadCommands(raw_ostream &OS) {
  211. for (auto &LC : Obj.LoadCommands) {
  212. size_t BytesWritten = 0;
  213. llvm::MachO::macho_load_command Data = LC.Data;
  214. #define HANDLE_LOAD_COMMAND(LCName, LCValue, LCStruct) \
  215. case MachO::LCName: \
  216. if (Obj.IsLittleEndian != sys::IsLittleEndianHost) \
  217. MachO::swapStruct(Data.LCStruct##_data); \
  218. OS.write(reinterpret_cast<const char *>(&(Data.LCStruct##_data)), \
  219. sizeof(MachO::LCStruct)); \
  220. BytesWritten = sizeof(MachO::LCStruct); \
  221. BytesWritten += \
  222. writeLoadCommandData<MachO::LCStruct>(LC, OS, Obj.IsLittleEndian); \
  223. break;
  224. switch (LC.Data.load_command_data.cmd) {
  225. default:
  226. if (Obj.IsLittleEndian != sys::IsLittleEndianHost)
  227. MachO::swapStruct(Data.load_command_data);
  228. OS.write(reinterpret_cast<const char *>(&(Data.load_command_data)),
  229. sizeof(MachO::load_command));
  230. BytesWritten = sizeof(MachO::load_command);
  231. BytesWritten +=
  232. writeLoadCommandData<MachO::load_command>(LC, OS, Obj.IsLittleEndian);
  233. break;
  234. #include "llvm/BinaryFormat/MachO.def"
  235. }
  236. if (LC.PayloadBytes.size() > 0) {
  237. OS.write(reinterpret_cast<const char *>(LC.PayloadBytes.data()),
  238. LC.PayloadBytes.size());
  239. BytesWritten += LC.PayloadBytes.size();
  240. }
  241. if (LC.ZeroPadBytes > 0) {
  242. ZeroFillBytes(OS, LC.ZeroPadBytes);
  243. BytesWritten += LC.ZeroPadBytes;
  244. }
  245. // Fill remaining bytes with 0. This will only get hit in partially
  246. // specified test cases.
  247. auto BytesRemaining = LC.Data.load_command_data.cmdsize - BytesWritten;
  248. if (BytesRemaining > 0) {
  249. ZeroFillBytes(OS, BytesRemaining);
  250. }
  251. }
  252. }
  253. Error MachOWriter::writeSectionData(raw_ostream &OS) {
  254. uint64_t LinkEditOff = 0;
  255. for (auto &LC : Obj.LoadCommands) {
  256. switch (LC.Data.load_command_data.cmd) {
  257. case MachO::LC_SEGMENT:
  258. case MachO::LC_SEGMENT_64:
  259. uint64_t segOff = is64Bit ? LC.Data.segment_command_64_data.fileoff
  260. : LC.Data.segment_command_data.fileoff;
  261. if (0 ==
  262. strncmp(&LC.Data.segment_command_data.segname[0], "__LINKEDIT", 16)) {
  263. FoundLinkEditSeg = true;
  264. LinkEditOff = segOff;
  265. if (Obj.RawLinkEditSegment)
  266. continue;
  267. writeLinkEditData(OS);
  268. }
  269. for (auto &Sec : LC.Sections) {
  270. ZeroToOffset(OS, Sec.offset);
  271. // Zero Fill any data between the end of the last thing we wrote and the
  272. // start of this section.
  273. if (OS.tell() - fileStart > Sec.offset && Sec.offset != (uint32_t)0)
  274. return createStringError(
  275. errc::invalid_argument,
  276. "wrote too much data somewhere, section offsets don't line up");
  277. StringRef SectName(Sec.sectname,
  278. strnlen(Sec.sectname, sizeof(Sec.sectname)));
  279. // If the section's content is specified in the 'DWARF' entry, we will
  280. // emit it regardless of the section's segname.
  281. if (Obj.DWARF.getNonEmptySectionNames().count(SectName.substr(2))) {
  282. if (Sec.content)
  283. return createStringError(errc::invalid_argument,
  284. "cannot specify section '" + SectName +
  285. "' contents in the 'DWARF' entry and "
  286. "the 'content' at the same time");
  287. auto EmitFunc = DWARFYAML::getDWARFEmitterByName(SectName.substr(2));
  288. if (Error Err = EmitFunc(OS, Obj.DWARF))
  289. return Err;
  290. continue;
  291. }
  292. // Skip if it's a virtual section.
  293. if (MachO::isVirtualSection(Sec.flags & MachO::SECTION_TYPE))
  294. continue;
  295. if (Sec.content) {
  296. yaml::BinaryRef Content = *Sec.content;
  297. Content.writeAsBinary(OS);
  298. ZeroFillBytes(OS, Sec.size - Content.binary_size());
  299. } else {
  300. // Fill section data with 0xDEADBEEF.
  301. Fill(OS, Sec.size, 0xDEADBEEFu);
  302. }
  303. }
  304. uint64_t segSize = is64Bit ? LC.Data.segment_command_64_data.filesize
  305. : LC.Data.segment_command_data.filesize;
  306. ZeroToOffset(OS, segOff + segSize);
  307. break;
  308. }
  309. }
  310. if (Obj.RawLinkEditSegment) {
  311. ZeroToOffset(OS, LinkEditOff);
  312. if (OS.tell() - fileStart > LinkEditOff || !LinkEditOff)
  313. return createStringError(errc::invalid_argument,
  314. "section offsets don't line up");
  315. Obj.RawLinkEditSegment->writeAsBinary(OS);
  316. }
  317. return Error::success();
  318. }
  319. // The implementation of makeRelocationInfo and makeScatteredRelocationInfo is
  320. // consistent with how libObject parses MachO binary files. For the reference
  321. // see getStruct, getRelocation, getPlainRelocationPCRel,
  322. // getPlainRelocationLength and related methods in MachOObjectFile.cpp
  323. static MachO::any_relocation_info
  324. makeRelocationInfo(const MachOYAML::Relocation &R, bool IsLE) {
  325. assert(!R.is_scattered && "non-scattered relocation expected");
  326. MachO::any_relocation_info MRE;
  327. MRE.r_word0 = R.address;
  328. if (IsLE)
  329. MRE.r_word1 = ((unsigned)R.symbolnum << 0) | ((unsigned)R.is_pcrel << 24) |
  330. ((unsigned)R.length << 25) | ((unsigned)R.is_extern << 27) |
  331. ((unsigned)R.type << 28);
  332. else
  333. MRE.r_word1 = ((unsigned)R.symbolnum << 8) | ((unsigned)R.is_pcrel << 7) |
  334. ((unsigned)R.length << 5) | ((unsigned)R.is_extern << 4) |
  335. ((unsigned)R.type << 0);
  336. return MRE;
  337. }
  338. static MachO::any_relocation_info
  339. makeScatteredRelocationInfo(const MachOYAML::Relocation &R) {
  340. assert(R.is_scattered && "scattered relocation expected");
  341. MachO::any_relocation_info MRE;
  342. MRE.r_word0 = (((unsigned)R.address << 0) | ((unsigned)R.type << 24) |
  343. ((unsigned)R.length << 28) | ((unsigned)R.is_pcrel << 30) |
  344. MachO::R_SCATTERED);
  345. MRE.r_word1 = R.value;
  346. return MRE;
  347. }
  348. void MachOWriter::writeRelocations(raw_ostream &OS) {
  349. for (const MachOYAML::LoadCommand &LC : Obj.LoadCommands) {
  350. switch (LC.Data.load_command_data.cmd) {
  351. case MachO::LC_SEGMENT:
  352. case MachO::LC_SEGMENT_64:
  353. for (const MachOYAML::Section &Sec : LC.Sections) {
  354. if (Sec.relocations.empty())
  355. continue;
  356. ZeroToOffset(OS, Sec.reloff);
  357. for (const MachOYAML::Relocation &R : Sec.relocations) {
  358. MachO::any_relocation_info MRE =
  359. R.is_scattered ? makeScatteredRelocationInfo(R)
  360. : makeRelocationInfo(R, Obj.IsLittleEndian);
  361. if (Obj.IsLittleEndian != sys::IsLittleEndianHost)
  362. MachO::swapStruct(MRE);
  363. OS.write(reinterpret_cast<const char *>(&MRE),
  364. sizeof(MachO::any_relocation_info));
  365. }
  366. }
  367. }
  368. }
  369. }
  370. void MachOWriter::writeBindOpcodes(
  371. raw_ostream &OS, std::vector<MachOYAML::BindOpcode> &BindOpcodes) {
  372. for (auto Opcode : BindOpcodes) {
  373. uint8_t OpByte = Opcode.Opcode | Opcode.Imm;
  374. OS.write(reinterpret_cast<char *>(&OpByte), 1);
  375. for (auto Data : Opcode.ULEBExtraData) {
  376. encodeULEB128(Data, OS);
  377. }
  378. for (auto Data : Opcode.SLEBExtraData) {
  379. encodeSLEB128(Data, OS);
  380. }
  381. if (!Opcode.Symbol.empty()) {
  382. OS.write(Opcode.Symbol.data(), Opcode.Symbol.size());
  383. OS.write('\0');
  384. }
  385. }
  386. }
  387. void MachOWriter::dumpExportEntry(raw_ostream &OS,
  388. MachOYAML::ExportEntry &Entry) {
  389. encodeSLEB128(Entry.TerminalSize, OS);
  390. if (Entry.TerminalSize > 0) {
  391. encodeSLEB128(Entry.Flags, OS);
  392. if (Entry.Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT) {
  393. encodeSLEB128(Entry.Other, OS);
  394. OS << Entry.ImportName;
  395. OS.write('\0');
  396. } else {
  397. encodeSLEB128(Entry.Address, OS);
  398. if (Entry.Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER)
  399. encodeSLEB128(Entry.Other, OS);
  400. }
  401. }
  402. OS.write(static_cast<uint8_t>(Entry.Children.size()));
  403. for (auto EE : Entry.Children) {
  404. OS << EE.Name;
  405. OS.write('\0');
  406. encodeSLEB128(EE.NodeOffset, OS);
  407. }
  408. for (auto EE : Entry.Children)
  409. dumpExportEntry(OS, EE);
  410. }
  411. void MachOWriter::writeExportTrie(raw_ostream &OS) {
  412. dumpExportEntry(OS, Obj.LinkEdit.ExportTrie);
  413. }
  414. template <typename NListType>
  415. void writeNListEntry(MachOYAML::NListEntry &NLE, raw_ostream &OS,
  416. bool IsLittleEndian) {
  417. NListType ListEntry;
  418. ListEntry.n_strx = NLE.n_strx;
  419. ListEntry.n_type = NLE.n_type;
  420. ListEntry.n_sect = NLE.n_sect;
  421. ListEntry.n_desc = NLE.n_desc;
  422. ListEntry.n_value = NLE.n_value;
  423. if (IsLittleEndian != sys::IsLittleEndianHost)
  424. MachO::swapStruct(ListEntry);
  425. OS.write(reinterpret_cast<const char *>(&ListEntry), sizeof(NListType));
  426. }
  427. void MachOWriter::writeLinkEditData(raw_ostream &OS) {
  428. typedef void (MachOWriter::*writeHandler)(raw_ostream &);
  429. typedef std::pair<uint64_t, writeHandler> writeOperation;
  430. std::vector<writeOperation> WriteQueue;
  431. MachO::dyld_info_command *DyldInfoOnlyCmd = nullptr;
  432. MachO::symtab_command *SymtabCmd = nullptr;
  433. MachO::dysymtab_command *DSymtabCmd = nullptr;
  434. for (auto &LC : Obj.LoadCommands) {
  435. switch (LC.Data.load_command_data.cmd) {
  436. case MachO::LC_SYMTAB:
  437. SymtabCmd = &LC.Data.symtab_command_data;
  438. WriteQueue.push_back(
  439. std::make_pair(SymtabCmd->symoff, &MachOWriter::writeNameList));
  440. WriteQueue.push_back(
  441. std::make_pair(SymtabCmd->stroff, &MachOWriter::writeStringTable));
  442. break;
  443. case MachO::LC_DYLD_INFO_ONLY:
  444. DyldInfoOnlyCmd = &LC.Data.dyld_info_command_data;
  445. WriteQueue.push_back(std::make_pair(DyldInfoOnlyCmd->rebase_off,
  446. &MachOWriter::writeRebaseOpcodes));
  447. WriteQueue.push_back(std::make_pair(DyldInfoOnlyCmd->bind_off,
  448. &MachOWriter::writeBasicBindOpcodes));
  449. WriteQueue.push_back(std::make_pair(DyldInfoOnlyCmd->weak_bind_off,
  450. &MachOWriter::writeWeakBindOpcodes));
  451. WriteQueue.push_back(std::make_pair(DyldInfoOnlyCmd->lazy_bind_off,
  452. &MachOWriter::writeLazyBindOpcodes));
  453. WriteQueue.push_back(std::make_pair(DyldInfoOnlyCmd->export_off,
  454. &MachOWriter::writeExportTrie));
  455. break;
  456. case MachO::LC_DYSYMTAB:
  457. DSymtabCmd = &LC.Data.dysymtab_command_data;
  458. WriteQueue.push_back(std::make_pair(
  459. DSymtabCmd->indirectsymoff, &MachOWriter::writeDynamicSymbolTable));
  460. break;
  461. }
  462. }
  463. llvm::sort(WriteQueue, [](const writeOperation &a, const writeOperation &b) {
  464. return a.first < b.first;
  465. });
  466. for (auto writeOp : WriteQueue) {
  467. ZeroToOffset(OS, writeOp.first);
  468. (this->*writeOp.second)(OS);
  469. }
  470. }
  471. void MachOWriter::writeRebaseOpcodes(raw_ostream &OS) {
  472. MachOYAML::LinkEditData &LinkEdit = Obj.LinkEdit;
  473. for (auto Opcode : LinkEdit.RebaseOpcodes) {
  474. uint8_t OpByte = Opcode.Opcode | Opcode.Imm;
  475. OS.write(reinterpret_cast<char *>(&OpByte), 1);
  476. for (auto Data : Opcode.ExtraData)
  477. encodeULEB128(Data, OS);
  478. }
  479. }
  480. void MachOWriter::writeBasicBindOpcodes(raw_ostream &OS) {
  481. writeBindOpcodes(OS, Obj.LinkEdit.BindOpcodes);
  482. }
  483. void MachOWriter::writeWeakBindOpcodes(raw_ostream &OS) {
  484. writeBindOpcodes(OS, Obj.LinkEdit.WeakBindOpcodes);
  485. }
  486. void MachOWriter::writeLazyBindOpcodes(raw_ostream &OS) {
  487. writeBindOpcodes(OS, Obj.LinkEdit.LazyBindOpcodes);
  488. }
  489. void MachOWriter::writeNameList(raw_ostream &OS) {
  490. for (auto NLE : Obj.LinkEdit.NameList) {
  491. if (is64Bit)
  492. writeNListEntry<MachO::nlist_64>(NLE, OS, Obj.IsLittleEndian);
  493. else
  494. writeNListEntry<MachO::nlist>(NLE, OS, Obj.IsLittleEndian);
  495. }
  496. }
  497. void MachOWriter::writeStringTable(raw_ostream &OS) {
  498. for (auto Str : Obj.LinkEdit.StringTable) {
  499. OS.write(Str.data(), Str.size());
  500. OS.write('\0');
  501. }
  502. }
  503. void MachOWriter::writeDynamicSymbolTable(raw_ostream &OS) {
  504. for (auto Data : Obj.LinkEdit.IndirectSymbols)
  505. OS.write(reinterpret_cast<const char *>(&Data),
  506. sizeof(yaml::Hex32::BaseType));
  507. }
  508. class UniversalWriter {
  509. public:
  510. UniversalWriter(yaml::YamlObjectFile &ObjectFile)
  511. : ObjectFile(ObjectFile), fileStart(0) {}
  512. Error writeMachO(raw_ostream &OS);
  513. private:
  514. void writeFatHeader(raw_ostream &OS);
  515. void writeFatArchs(raw_ostream &OS);
  516. void ZeroToOffset(raw_ostream &OS, size_t offset);
  517. yaml::YamlObjectFile &ObjectFile;
  518. uint64_t fileStart;
  519. };
  520. Error UniversalWriter::writeMachO(raw_ostream &OS) {
  521. fileStart = OS.tell();
  522. if (ObjectFile.MachO) {
  523. MachOWriter Writer(*ObjectFile.MachO);
  524. return Writer.writeMachO(OS);
  525. }
  526. writeFatHeader(OS);
  527. writeFatArchs(OS);
  528. auto &FatFile = *ObjectFile.FatMachO;
  529. if (FatFile.FatArchs.size() < FatFile.Slices.size())
  530. return createStringError(
  531. errc::invalid_argument,
  532. "cannot write 'Slices' if not described in 'FatArches'");
  533. for (size_t i = 0; i < FatFile.Slices.size(); i++) {
  534. ZeroToOffset(OS, FatFile.FatArchs[i].offset);
  535. MachOWriter Writer(FatFile.Slices[i]);
  536. if (Error Err = Writer.writeMachO(OS))
  537. return Err;
  538. auto SliceEnd = FatFile.FatArchs[i].offset + FatFile.FatArchs[i].size;
  539. ZeroToOffset(OS, SliceEnd);
  540. }
  541. return Error::success();
  542. }
  543. void UniversalWriter::writeFatHeader(raw_ostream &OS) {
  544. auto &FatFile = *ObjectFile.FatMachO;
  545. MachO::fat_header header;
  546. header.magic = FatFile.Header.magic;
  547. header.nfat_arch = FatFile.Header.nfat_arch;
  548. if (sys::IsLittleEndianHost)
  549. swapStruct(header);
  550. OS.write(reinterpret_cast<const char *>(&header), sizeof(MachO::fat_header));
  551. }
  552. template <typename FatArchType>
  553. FatArchType constructFatArch(MachOYAML::FatArch &Arch) {
  554. FatArchType FatArch;
  555. FatArch.cputype = Arch.cputype;
  556. FatArch.cpusubtype = Arch.cpusubtype;
  557. FatArch.offset = Arch.offset;
  558. FatArch.size = Arch.size;
  559. FatArch.align = Arch.align;
  560. return FatArch;
  561. }
  562. template <typename StructType>
  563. void writeFatArch(MachOYAML::FatArch &LC, raw_ostream &OS) {}
  564. template <>
  565. void writeFatArch<MachO::fat_arch>(MachOYAML::FatArch &Arch, raw_ostream &OS) {
  566. auto FatArch = constructFatArch<MachO::fat_arch>(Arch);
  567. if (sys::IsLittleEndianHost)
  568. swapStruct(FatArch);
  569. OS.write(reinterpret_cast<const char *>(&FatArch), sizeof(MachO::fat_arch));
  570. }
  571. template <>
  572. void writeFatArch<MachO::fat_arch_64>(MachOYAML::FatArch &Arch,
  573. raw_ostream &OS) {
  574. auto FatArch = constructFatArch<MachO::fat_arch_64>(Arch);
  575. FatArch.reserved = Arch.reserved;
  576. if (sys::IsLittleEndianHost)
  577. swapStruct(FatArch);
  578. OS.write(reinterpret_cast<const char *>(&FatArch),
  579. sizeof(MachO::fat_arch_64));
  580. }
  581. void UniversalWriter::writeFatArchs(raw_ostream &OS) {
  582. auto &FatFile = *ObjectFile.FatMachO;
  583. bool is64Bit = FatFile.Header.magic == MachO::FAT_MAGIC_64;
  584. for (auto Arch : FatFile.FatArchs) {
  585. if (is64Bit)
  586. writeFatArch<MachO::fat_arch_64>(Arch, OS);
  587. else
  588. writeFatArch<MachO::fat_arch>(Arch, OS);
  589. }
  590. }
  591. void UniversalWriter::ZeroToOffset(raw_ostream &OS, size_t Offset) {
  592. auto currOffset = OS.tell() - fileStart;
  593. if (currOffset < Offset)
  594. ZeroFillBytes(OS, Offset - currOffset);
  595. }
  596. } // end anonymous namespace
  597. namespace llvm {
  598. namespace yaml {
  599. bool yaml2macho(YamlObjectFile &Doc, raw_ostream &Out, ErrorHandler EH) {
  600. UniversalWriter Writer(Doc);
  601. if (Error Err = Writer.writeMachO(Out)) {
  602. handleAllErrors(std::move(Err),
  603. [&](const ErrorInfoBase &Err) { EH(Err.message()); });
  604. return false;
  605. }
  606. return true;
  607. }
  608. } // namespace yaml
  609. } // namespace llvm