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