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