MachOUniversalWriter.cpp 13 KB

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