MachOUniversalWriter.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. //===- MachOUniversalWriter.cpp - MachO universal binary writer---*- 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. //
  9. // Defines the Slice class and writeUniversalBinary function for writing a MachO
  10. // universal binary file.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Object/MachOUniversalWriter.h"
  14. #include "llvm/ADT/Triple.h"
  15. #include "llvm/Object/Archive.h"
  16. #include "llvm/Object/Binary.h"
  17. #include "llvm/Object/Error.h"
  18. #include "llvm/Object/IRObjectFile.h"
  19. #include "llvm/Object/MachO.h"
  20. #include "llvm/Object/MachOUniversal.h"
  21. using namespace llvm;
  22. using namespace object;
  23. // For compatibility with cctools lipo, a file's alignment is calculated as the
  24. // minimum aligment of all segments. For object files, the file's alignment is
  25. // the maximum alignment of its sections.
  26. static uint32_t calculateFileAlignment(const MachOObjectFile &O) {
  27. uint32_t P2CurrentAlignment;
  28. uint32_t P2MinAlignment = MachOUniversalBinary::MaxSectionAlignment;
  29. const bool Is64Bit = O.is64Bit();
  30. for (const auto &LC : O.load_commands()) {
  31. if (LC.C.cmd != (Is64Bit ? MachO::LC_SEGMENT_64 : MachO::LC_SEGMENT))
  32. continue;
  33. if (O.getHeader().filetype == MachO::MH_OBJECT) {
  34. unsigned NumberOfSections =
  35. (Is64Bit ? O.getSegment64LoadCommand(LC).nsects
  36. : O.getSegmentLoadCommand(LC).nsects);
  37. P2CurrentAlignment = NumberOfSections ? 2 : P2MinAlignment;
  38. for (unsigned SI = 0; SI < NumberOfSections; ++SI) {
  39. P2CurrentAlignment = std::max(P2CurrentAlignment,
  40. (Is64Bit ? O.getSection64(LC, SI).align
  41. : O.getSection(LC, SI).align));
  42. }
  43. } else {
  44. P2CurrentAlignment =
  45. countTrailingZeros(Is64Bit ? O.getSegment64LoadCommand(LC).vmaddr
  46. : O.getSegmentLoadCommand(LC).vmaddr);
  47. }
  48. P2MinAlignment = std::min(P2MinAlignment, P2CurrentAlignment);
  49. }
  50. // return a value >= 4 byte aligned, and less than MachO MaxSectionAlignment
  51. return std::max(
  52. static_cast<uint32_t>(2),
  53. std::min(P2MinAlignment, static_cast<uint32_t>(
  54. MachOUniversalBinary::MaxSectionAlignment)));
  55. }
  56. static uint32_t calculateAlignment(const MachOObjectFile &ObjectFile) {
  57. switch (ObjectFile.getHeader().cputype) {
  58. case MachO::CPU_TYPE_I386:
  59. case MachO::CPU_TYPE_X86_64:
  60. case MachO::CPU_TYPE_POWERPC:
  61. case MachO::CPU_TYPE_POWERPC64:
  62. return 12; // log2 value of page size(4k) for x86 and PPC
  63. case MachO::CPU_TYPE_ARM:
  64. case MachO::CPU_TYPE_ARM64:
  65. case MachO::CPU_TYPE_ARM64_32:
  66. return 14; // log2 value of page size(16k) for Darwin ARM
  67. default:
  68. return calculateFileAlignment(ObjectFile);
  69. }
  70. }
  71. Slice::Slice(const Archive &A, uint32_t CPUType, uint32_t CPUSubType,
  72. std::string ArchName, uint32_t Align)
  73. : B(&A), CPUType(CPUType), CPUSubType(CPUSubType),
  74. ArchName(std::move(ArchName)), P2Alignment(Align) {}
  75. Slice::Slice(const MachOObjectFile &O, uint32_t Align)
  76. : B(&O), CPUType(O.getHeader().cputype),
  77. CPUSubType(O.getHeader().cpusubtype),
  78. ArchName(std::string(O.getArchTriple().getArchName())),
  79. P2Alignment(Align) {}
  80. Slice::Slice(const IRObjectFile &IRO, uint32_t CPUType, uint32_t CPUSubType,
  81. std::string ArchName, uint32_t Align)
  82. : B(&IRO), CPUType(CPUType), CPUSubType(CPUSubType),
  83. ArchName(std::move(ArchName)), P2Alignment(Align) {}
  84. Slice::Slice(const MachOObjectFile &O) : Slice(O, calculateAlignment(O)) {}
  85. using MachoCPUTy = std::pair<unsigned, unsigned>;
  86. static Expected<MachoCPUTy> getMachoCPUFromTriple(Triple TT) {
  87. auto CPU = std::make_pair(MachO::getCPUType(TT), MachO::getCPUSubType(TT));
  88. if (!CPU.first) {
  89. return CPU.first.takeError();
  90. }
  91. if (!CPU.second) {
  92. return CPU.second.takeError();
  93. }
  94. return std::make_pair(*CPU.first, *CPU.second);
  95. }
  96. static Expected<MachoCPUTy> getMachoCPUFromTriple(StringRef TT) {
  97. return getMachoCPUFromTriple(Triple{TT});
  98. }
  99. Expected<Slice> Slice::create(const Archive &A, LLVMContext *LLVMCtx) {
  100. Error Err = Error::success();
  101. std::unique_ptr<MachOObjectFile> MFO = nullptr;
  102. std::unique_ptr<IRObjectFile> IRFO = nullptr;
  103. for (const Archive::Child &Child : A.children(Err)) {
  104. Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary(LLVMCtx);
  105. if (!ChildOrErr)
  106. return createFileError(A.getFileName(), ChildOrErr.takeError());
  107. Binary *Bin = ChildOrErr.get().get();
  108. if (Bin->isMachOUniversalBinary())
  109. return createStringError(std::errc::invalid_argument,
  110. ("archive member " + Bin->getFileName() +
  111. " is a fat file (not allowed in an archive)")
  112. .str()
  113. .c_str());
  114. if (Bin->isMachO()) {
  115. MachOObjectFile *O = cast<MachOObjectFile>(Bin);
  116. if (IRFO) {
  117. return createStringError(
  118. std::errc::invalid_argument,
  119. "archive member %s is a MachO, while previous archive member "
  120. "%s was an IR LLVM object",
  121. O->getFileName().str().c_str(), IRFO->getFileName().str().c_str());
  122. }
  123. if (MFO &&
  124. std::tie(MFO->getHeader().cputype, MFO->getHeader().cpusubtype) !=
  125. std::tie(O->getHeader().cputype, O->getHeader().cpusubtype)) {
  126. return createStringError(
  127. std::errc::invalid_argument,
  128. ("archive member " + O->getFileName() + " cputype (" +
  129. Twine(O->getHeader().cputype) + ") and cpusubtype(" +
  130. Twine(O->getHeader().cpusubtype) +
  131. ") does not match previous archive members cputype (" +
  132. Twine(MFO->getHeader().cputype) + ") and cpusubtype(" +
  133. Twine(MFO->getHeader().cpusubtype) +
  134. ") (all members must match) " + MFO->getFileName())
  135. .str()
  136. .c_str());
  137. }
  138. if (!MFO) {
  139. ChildOrErr.get().release();
  140. MFO.reset(O);
  141. }
  142. } else if (Bin->isIR()) {
  143. IRObjectFile *O = cast<IRObjectFile>(Bin);
  144. if (MFO) {
  145. return createStringError(std::errc::invalid_argument,
  146. "archive member '%s' is an LLVM IR object, "
  147. "while previous archive member "
  148. "'%s' was a MachO",
  149. O->getFileName().str().c_str(),
  150. MFO->getFileName().str().c_str());
  151. }
  152. if (IRFO) {
  153. Expected<MachoCPUTy> CPUO = getMachoCPUFromTriple(O->getTargetTriple());
  154. Expected<MachoCPUTy> CPUFO =
  155. getMachoCPUFromTriple(IRFO->getTargetTriple());
  156. if (!CPUO)
  157. return CPUO.takeError();
  158. if (!CPUFO)
  159. return CPUFO.takeError();
  160. if (*CPUO != *CPUFO) {
  161. return createStringError(
  162. std::errc::invalid_argument,
  163. ("archive member " + O->getFileName() + " cputype (" +
  164. Twine(CPUO->first) + ") and cpusubtype(" + Twine(CPUO->second) +
  165. ") does not match previous archive members cputype (" +
  166. Twine(CPUFO->first) + ") and cpusubtype(" +
  167. Twine(CPUFO->second) + ") (all members must match) " +
  168. IRFO->getFileName())
  169. .str()
  170. .c_str());
  171. }
  172. } else {
  173. ChildOrErr.get().release();
  174. IRFO.reset(O);
  175. }
  176. } else
  177. return createStringError(std::errc::invalid_argument,
  178. ("archive member " + Bin->getFileName() +
  179. " is neither a MachO file or an LLVM IR file "
  180. "(not allowed in an archive)")
  181. .str()
  182. .c_str());
  183. }
  184. if (Err)
  185. return createFileError(A.getFileName(), std::move(Err));
  186. if (!MFO && !IRFO)
  187. return createStringError(
  188. std::errc::invalid_argument,
  189. ("empty archive with no architecture specification: " +
  190. A.getFileName() + " (can't determine architecture for it)")
  191. .str()
  192. .c_str());
  193. if (MFO) {
  194. Slice ArchiveSlice(*(MFO.get()), MFO->is64Bit() ? 3 : 2);
  195. ArchiveSlice.B = &A;
  196. return ArchiveSlice;
  197. }
  198. // For IR objects
  199. Expected<Slice> ArchiveSliceOrErr = Slice::create(*IRFO, 0);
  200. if (!ArchiveSliceOrErr)
  201. return createFileError(A.getFileName(), ArchiveSliceOrErr.takeError());
  202. auto &ArchiveSlice = ArchiveSliceOrErr.get();
  203. ArchiveSlice.B = &A;
  204. return std::move(ArchiveSlice);
  205. }
  206. Expected<Slice> Slice::create(const IRObjectFile &IRO, uint32_t Align) {
  207. Expected<MachoCPUTy> CPUOrErr = getMachoCPUFromTriple(IRO.getTargetTriple());
  208. if (!CPUOrErr)
  209. return CPUOrErr.takeError();
  210. unsigned CPUType, CPUSubType;
  211. std::tie(CPUType, CPUSubType) = CPUOrErr.get();
  212. // We don't directly use the architecture name of the target triple T, as,
  213. // for instance, thumb is treated as ARM by the MachOUniversal object.
  214. std::string ArchName(
  215. MachOObjectFile::getArchTriple(CPUType, CPUSubType).getArchName());
  216. return Slice{IRO, CPUType, CPUSubType, std::move(ArchName), Align};
  217. }
  218. static Expected<SmallVector<MachO::fat_arch, 2>>
  219. buildFatArchList(ArrayRef<Slice> Slices) {
  220. SmallVector<MachO::fat_arch, 2> FatArchList;
  221. uint64_t Offset =
  222. sizeof(MachO::fat_header) + Slices.size() * sizeof(MachO::fat_arch);
  223. for (const auto &S : Slices) {
  224. Offset = alignTo(Offset, 1ull << S.getP2Alignment());
  225. if (Offset > UINT32_MAX)
  226. return createStringError(
  227. std::errc::invalid_argument,
  228. ("fat file too large to be created because the offset "
  229. "field in struct fat_arch is only 32-bits and the offset " +
  230. Twine(Offset) + " for " + S.getBinary()->getFileName() +
  231. " for architecture " + S.getArchString() + "exceeds that.")
  232. .str()
  233. .c_str());
  234. MachO::fat_arch FatArch;
  235. FatArch.cputype = S.getCPUType();
  236. FatArch.cpusubtype = S.getCPUSubType();
  237. FatArch.offset = Offset;
  238. FatArch.size = S.getBinary()->getMemoryBufferRef().getBufferSize();
  239. FatArch.align = S.getP2Alignment();
  240. Offset += FatArch.size;
  241. FatArchList.push_back(FatArch);
  242. }
  243. return FatArchList;
  244. }
  245. Error object::writeUniversalBinaryToStream(ArrayRef<Slice> Slices,
  246. raw_ostream &Out) {
  247. MachO::fat_header FatHeader;
  248. FatHeader.magic = MachO::FAT_MAGIC;
  249. FatHeader.nfat_arch = Slices.size();
  250. Expected<SmallVector<MachO::fat_arch, 2>> FatArchListOrErr =
  251. buildFatArchList(Slices);
  252. if (!FatArchListOrErr)
  253. return FatArchListOrErr.takeError();
  254. SmallVector<MachO::fat_arch, 2> FatArchList = *FatArchListOrErr;
  255. if (sys::IsLittleEndianHost)
  256. MachO::swapStruct(FatHeader);
  257. Out.write(reinterpret_cast<const char *>(&FatHeader),
  258. sizeof(MachO::fat_header));
  259. if (sys::IsLittleEndianHost)
  260. for (MachO::fat_arch &FA : FatArchList)
  261. MachO::swapStruct(FA);
  262. Out.write(reinterpret_cast<const char *>(FatArchList.data()),
  263. sizeof(MachO::fat_arch) * FatArchList.size());
  264. if (sys::IsLittleEndianHost)
  265. for (MachO::fat_arch &FA : FatArchList)
  266. MachO::swapStruct(FA);
  267. size_t Offset =
  268. sizeof(MachO::fat_header) + sizeof(MachO::fat_arch) * FatArchList.size();
  269. for (size_t Index = 0, Size = Slices.size(); Index < Size; ++Index) {
  270. MemoryBufferRef BufferRef = Slices[Index].getBinary()->getMemoryBufferRef();
  271. assert((Offset <= FatArchList[Index].offset) && "Incorrect slice offset");
  272. Out.write_zeros(FatArchList[Index].offset - Offset);
  273. Out.write(BufferRef.getBufferStart(), BufferRef.getBufferSize());
  274. Offset = FatArchList[Index].offset + BufferRef.getBufferSize();
  275. }
  276. Out.flush();
  277. return Error::success();
  278. }
  279. Error object::writeUniversalBinary(ArrayRef<Slice> Slices,
  280. StringRef OutputFileName) {
  281. const bool IsExecutable = any_of(Slices, [](Slice S) {
  282. return sys::fs::can_execute(S.getBinary()->getFileName());
  283. });
  284. unsigned Mode = sys::fs::all_read | sys::fs::all_write;
  285. if (IsExecutable)
  286. Mode |= sys::fs::all_exe;
  287. Expected<sys::fs::TempFile> Temp = sys::fs::TempFile::create(
  288. OutputFileName + ".temp-universal-%%%%%%", Mode);
  289. if (!Temp)
  290. return Temp.takeError();
  291. raw_fd_ostream Out(Temp->FD, false);
  292. if (Error E = writeUniversalBinaryToStream(Slices, Out)) {
  293. if (Error DiscardError = Temp->discard())
  294. return joinErrors(std::move(E), std::move(DiscardError));
  295. return E;
  296. }
  297. return Temp->keep(OutputFileName);
  298. }