1 //===- MachOWriter.cpp ------------------------------------------*- 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 #include "MachOWriter.h"
10 #include "MachOLayoutBuilder.h"
11 #include "Object.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/BinaryFormat/MachO.h"
14 #include "llvm/Object/MachO.h"
15 #include "llvm/Support/Errc.h"
16 #include "llvm/Support/ErrorHandling.h"
17 #include <memory>
18 
19 using namespace llvm;
20 using namespace llvm::objcopy::macho;
21 
headerSize() const22 size_t MachOWriter::headerSize() const {
23   return Is64Bit ? sizeof(MachO::mach_header_64) : sizeof(MachO::mach_header);
24 }
25 
loadCommandsSize() const26 size_t MachOWriter::loadCommandsSize() const { return O.Header.SizeOfCmds; }
27 
symTableSize() const28 size_t MachOWriter::symTableSize() const {
29   return O.SymTable.Symbols.size() *
30          (Is64Bit ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist));
31 }
32 
totalSize() const33 size_t MachOWriter::totalSize() const {
34   // Going from tail to head and looking for an appropriate "anchor" to
35   // calculate the total size assuming that all the offsets are either valid
36   // ("true") or 0 (0 indicates that the corresponding part is missing).
37 
38   SmallVector<size_t, 7> Ends;
39   if (O.SymTabCommandIndex) {
40     const MachO::symtab_command &SymTabCommand =
41         O.LoadCommands[*O.SymTabCommandIndex]
42             .MachOLoadCommand.symtab_command_data;
43     if (SymTabCommand.symoff)
44       Ends.push_back(SymTabCommand.symoff + symTableSize());
45     if (SymTabCommand.stroff)
46       Ends.push_back(SymTabCommand.stroff + SymTabCommand.strsize);
47   }
48   if (O.DyLdInfoCommandIndex) {
49     const MachO::dyld_info_command &DyLdInfoCommand =
50         O.LoadCommands[*O.DyLdInfoCommandIndex]
51             .MachOLoadCommand.dyld_info_command_data;
52     if (DyLdInfoCommand.rebase_off) {
53       assert((DyLdInfoCommand.rebase_size == O.Rebases.Opcodes.size()) &&
54              "Incorrect rebase opcodes size");
55       Ends.push_back(DyLdInfoCommand.rebase_off + DyLdInfoCommand.rebase_size);
56     }
57     if (DyLdInfoCommand.bind_off) {
58       assert((DyLdInfoCommand.bind_size == O.Binds.Opcodes.size()) &&
59              "Incorrect bind opcodes size");
60       Ends.push_back(DyLdInfoCommand.bind_off + DyLdInfoCommand.bind_size);
61     }
62     if (DyLdInfoCommand.weak_bind_off) {
63       assert((DyLdInfoCommand.weak_bind_size == O.WeakBinds.Opcodes.size()) &&
64              "Incorrect weak bind opcodes size");
65       Ends.push_back(DyLdInfoCommand.weak_bind_off +
66                      DyLdInfoCommand.weak_bind_size);
67     }
68     if (DyLdInfoCommand.lazy_bind_off) {
69       assert((DyLdInfoCommand.lazy_bind_size == O.LazyBinds.Opcodes.size()) &&
70              "Incorrect lazy bind opcodes size");
71       Ends.push_back(DyLdInfoCommand.lazy_bind_off +
72                      DyLdInfoCommand.lazy_bind_size);
73     }
74     if (DyLdInfoCommand.export_off) {
75       assert((DyLdInfoCommand.export_size == O.Exports.Trie.size()) &&
76              "Incorrect trie size");
77       Ends.push_back(DyLdInfoCommand.export_off + DyLdInfoCommand.export_size);
78     }
79   }
80 
81   if (O.DySymTabCommandIndex) {
82     const MachO::dysymtab_command &DySymTabCommand =
83         O.LoadCommands[*O.DySymTabCommandIndex]
84             .MachOLoadCommand.dysymtab_command_data;
85 
86     if (DySymTabCommand.indirectsymoff)
87       Ends.push_back(DySymTabCommand.indirectsymoff +
88                      sizeof(uint32_t) * O.IndirectSymTable.Symbols.size());
89   }
90 
91   if (O.CodeSignatureCommandIndex) {
92     const MachO::linkedit_data_command &LinkEditDataCommand =
93         O.LoadCommands[*O.CodeSignatureCommandIndex]
94             .MachOLoadCommand.linkedit_data_command_data;
95     if (LinkEditDataCommand.dataoff)
96       Ends.push_back(LinkEditDataCommand.dataoff +
97                      LinkEditDataCommand.datasize);
98   }
99 
100   if (O.DataInCodeCommandIndex) {
101     const MachO::linkedit_data_command &LinkEditDataCommand =
102         O.LoadCommands[*O.DataInCodeCommandIndex]
103             .MachOLoadCommand.linkedit_data_command_data;
104 
105     if (LinkEditDataCommand.dataoff)
106       Ends.push_back(LinkEditDataCommand.dataoff +
107                      LinkEditDataCommand.datasize);
108   }
109 
110   if (O.LinkerOptimizationHintCommandIndex) {
111     const MachO::linkedit_data_command &LinkEditDataCommand =
112         O.LoadCommands[*O.LinkerOptimizationHintCommandIndex]
113             .MachOLoadCommand.linkedit_data_command_data;
114 
115     if (LinkEditDataCommand.dataoff)
116       Ends.push_back(LinkEditDataCommand.dataoff +
117                      LinkEditDataCommand.datasize);
118   }
119 
120   if (O.FunctionStartsCommandIndex) {
121     const MachO::linkedit_data_command &LinkEditDataCommand =
122         O.LoadCommands[*O.FunctionStartsCommandIndex]
123             .MachOLoadCommand.linkedit_data_command_data;
124 
125     if (LinkEditDataCommand.dataoff)
126       Ends.push_back(LinkEditDataCommand.dataoff +
127                      LinkEditDataCommand.datasize);
128   }
129 
130   // Otherwise, use the last section / reloction.
131   for (const LoadCommand &LC : O.LoadCommands)
132     for (const std::unique_ptr<Section> &S : LC.Sections) {
133       if (!S->hasValidOffset()) {
134         assert((S->Offset == 0) && "Skipped section's offset must be zero");
135         assert((S->isVirtualSection() || S->Size == 0) &&
136                "Non-zero-fill sections with zero offset must have zero size");
137         continue;
138       }
139       assert((S->Offset != 0) &&
140              "Non-zero-fill section's offset cannot be zero");
141       Ends.push_back(S->Offset + S->Size);
142       if (S->RelOff)
143         Ends.push_back(S->RelOff +
144                        S->NReloc * sizeof(MachO::any_relocation_info));
145     }
146 
147   if (!Ends.empty())
148     return *std::max_element(Ends.begin(), Ends.end());
149 
150   // Otherwise, we have only Mach header and load commands.
151   return headerSize() + loadCommandsSize();
152 }
153 
writeHeader()154 void MachOWriter::writeHeader() {
155   MachO::mach_header_64 Header;
156 
157   Header.magic = O.Header.Magic;
158   Header.cputype = O.Header.CPUType;
159   Header.cpusubtype = O.Header.CPUSubType;
160   Header.filetype = O.Header.FileType;
161   Header.ncmds = O.Header.NCmds;
162   Header.sizeofcmds = O.Header.SizeOfCmds;
163   Header.flags = O.Header.Flags;
164   Header.reserved = O.Header.Reserved;
165 
166   if (IsLittleEndian != sys::IsLittleEndianHost)
167     MachO::swapStruct(Header);
168 
169   auto HeaderSize =
170       Is64Bit ? sizeof(MachO::mach_header_64) : sizeof(MachO::mach_header);
171   memcpy(Buf->getBufferStart(), &Header, HeaderSize);
172 }
173 
writeLoadCommands()174 void MachOWriter::writeLoadCommands() {
175   uint8_t *Begin =
176       reinterpret_cast<uint8_t *>(Buf->getBufferStart()) + headerSize();
177   for (const LoadCommand &LC : O.LoadCommands) {
178     // Construct a load command.
179     MachO::macho_load_command MLC = LC.MachOLoadCommand;
180     switch (MLC.load_command_data.cmd) {
181     case MachO::LC_SEGMENT:
182       if (IsLittleEndian != sys::IsLittleEndianHost)
183         MachO::swapStruct(MLC.segment_command_data);
184       memcpy(Begin, &MLC.segment_command_data, sizeof(MachO::segment_command));
185       Begin += sizeof(MachO::segment_command);
186 
187       for (const std::unique_ptr<Section> &Sec : LC.Sections)
188         writeSectionInLoadCommand<MachO::section>(*Sec, Begin);
189       continue;
190     case MachO::LC_SEGMENT_64:
191       if (IsLittleEndian != sys::IsLittleEndianHost)
192         MachO::swapStruct(MLC.segment_command_64_data);
193       memcpy(Begin, &MLC.segment_command_64_data,
194              sizeof(MachO::segment_command_64));
195       Begin += sizeof(MachO::segment_command_64);
196 
197       for (const std::unique_ptr<Section> &Sec : LC.Sections)
198         writeSectionInLoadCommand<MachO::section_64>(*Sec, Begin);
199       continue;
200     }
201 
202 #define HANDLE_LOAD_COMMAND(LCName, LCValue, LCStruct)                         \
203   case MachO::LCName:                                                          \
204     assert(sizeof(MachO::LCStruct) + LC.Payload.size() ==                      \
205            MLC.load_command_data.cmdsize);                                     \
206     if (IsLittleEndian != sys::IsLittleEndianHost)                             \
207       MachO::swapStruct(MLC.LCStruct##_data);                                  \
208     memcpy(Begin, &MLC.LCStruct##_data, sizeof(MachO::LCStruct));              \
209     Begin += sizeof(MachO::LCStruct);                                          \
210     if (!LC.Payload.empty())                                                   \
211       memcpy(Begin, LC.Payload.data(), LC.Payload.size());                     \
212     Begin += LC.Payload.size();                                                \
213     break;
214 
215     // Copy the load command as it is.
216     switch (MLC.load_command_data.cmd) {
217     default:
218       assert(sizeof(MachO::load_command) + LC.Payload.size() ==
219              MLC.load_command_data.cmdsize);
220       if (IsLittleEndian != sys::IsLittleEndianHost)
221         MachO::swapStruct(MLC.load_command_data);
222       memcpy(Begin, &MLC.load_command_data, sizeof(MachO::load_command));
223       Begin += sizeof(MachO::load_command);
224       if (!LC.Payload.empty())
225         memcpy(Begin, LC.Payload.data(), LC.Payload.size());
226       Begin += LC.Payload.size();
227       break;
228 #include "llvm/BinaryFormat/MachO.def"
229     }
230   }
231 }
232 
233 template <typename StructType>
writeSectionInLoadCommand(const Section & Sec,uint8_t * & Out)234 void MachOWriter::writeSectionInLoadCommand(const Section &Sec, uint8_t *&Out) {
235   StructType Temp;
236   assert(Sec.Segname.size() <= sizeof(Temp.segname) && "too long segment name");
237   assert(Sec.Sectname.size() <= sizeof(Temp.sectname) &&
238          "too long section name");
239   memset(&Temp, 0, sizeof(StructType));
240   memcpy(Temp.segname, Sec.Segname.data(), Sec.Segname.size());
241   memcpy(Temp.sectname, Sec.Sectname.data(), Sec.Sectname.size());
242   Temp.addr = Sec.Addr;
243   Temp.size = Sec.Size;
244   Temp.offset = Sec.Offset;
245   Temp.align = Sec.Align;
246   Temp.reloff = Sec.RelOff;
247   Temp.nreloc = Sec.NReloc;
248   Temp.flags = Sec.Flags;
249   Temp.reserved1 = Sec.Reserved1;
250   Temp.reserved2 = Sec.Reserved2;
251 
252   if (IsLittleEndian != sys::IsLittleEndianHost)
253     MachO::swapStruct(Temp);
254   memcpy(Out, &Temp, sizeof(StructType));
255   Out += sizeof(StructType);
256 }
257 
writeSections()258 void MachOWriter::writeSections() {
259   for (const LoadCommand &LC : O.LoadCommands)
260     for (const std::unique_ptr<Section> &Sec : LC.Sections) {
261       if (!Sec->hasValidOffset()) {
262         assert((Sec->Offset == 0) && "Skipped section's offset must be zero");
263         assert((Sec->isVirtualSection() || Sec->Size == 0) &&
264                "Non-zero-fill sections with zero offset must have zero size");
265         continue;
266       }
267 
268       assert(Sec->Offset && "Section offset can not be zero");
269       assert((Sec->Size == Sec->Content.size()) && "Incorrect section size");
270       memcpy(Buf->getBufferStart() + Sec->Offset, Sec->Content.data(),
271              Sec->Content.size());
272       for (size_t Index = 0; Index < Sec->Relocations.size(); ++Index) {
273         RelocationInfo RelocInfo = Sec->Relocations[Index];
274         if (!RelocInfo.Scattered && !RelocInfo.IsAddend) {
275           const uint32_t SymbolNum = RelocInfo.Extern
276                                          ? (*RelocInfo.Symbol)->Index
277                                          : (*RelocInfo.Sec)->Index;
278           RelocInfo.setPlainRelocationSymbolNum(SymbolNum, IsLittleEndian);
279         }
280         if (IsLittleEndian != sys::IsLittleEndianHost)
281           MachO::swapStruct(
282               reinterpret_cast<MachO::any_relocation_info &>(RelocInfo.Info));
283         memcpy(Buf->getBufferStart() + Sec->RelOff +
284                    Index * sizeof(MachO::any_relocation_info),
285                &RelocInfo.Info, sizeof(RelocInfo.Info));
286       }
287     }
288 }
289 
290 template <typename NListType>
writeNListEntry(const SymbolEntry & SE,bool IsLittleEndian,char * & Out,uint32_t Nstrx)291 void writeNListEntry(const SymbolEntry &SE, bool IsLittleEndian, char *&Out,
292                      uint32_t Nstrx) {
293   NListType ListEntry;
294   ListEntry.n_strx = Nstrx;
295   ListEntry.n_type = SE.n_type;
296   ListEntry.n_sect = SE.n_sect;
297   ListEntry.n_desc = SE.n_desc;
298   ListEntry.n_value = SE.n_value;
299 
300   if (IsLittleEndian != sys::IsLittleEndianHost)
301     MachO::swapStruct(ListEntry);
302   memcpy(Out, reinterpret_cast<const char *>(&ListEntry), sizeof(NListType));
303   Out += sizeof(NListType);
304 }
305 
writeStringTable()306 void MachOWriter::writeStringTable() {
307   if (!O.SymTabCommandIndex)
308     return;
309   const MachO::symtab_command &SymTabCommand =
310       O.LoadCommands[*O.SymTabCommandIndex]
311           .MachOLoadCommand.symtab_command_data;
312 
313   uint8_t *StrTable = (uint8_t *)Buf->getBufferStart() + SymTabCommand.stroff;
314   LayoutBuilder.getStringTableBuilder().write(StrTable);
315 }
316 
writeSymbolTable()317 void MachOWriter::writeSymbolTable() {
318   if (!O.SymTabCommandIndex)
319     return;
320   const MachO::symtab_command &SymTabCommand =
321       O.LoadCommands[*O.SymTabCommandIndex]
322           .MachOLoadCommand.symtab_command_data;
323 
324   char *SymTable = (char *)Buf->getBufferStart() + SymTabCommand.symoff;
325   for (auto Iter = O.SymTable.Symbols.begin(), End = O.SymTable.Symbols.end();
326        Iter != End; Iter++) {
327     SymbolEntry *Sym = Iter->get();
328     uint32_t Nstrx = LayoutBuilder.getStringTableBuilder().getOffset(Sym->Name);
329 
330     if (Is64Bit)
331       writeNListEntry<MachO::nlist_64>(*Sym, IsLittleEndian, SymTable, Nstrx);
332     else
333       writeNListEntry<MachO::nlist>(*Sym, IsLittleEndian, SymTable, Nstrx);
334   }
335 }
336 
writeRebaseInfo()337 void MachOWriter::writeRebaseInfo() {
338   if (!O.DyLdInfoCommandIndex)
339     return;
340   const MachO::dyld_info_command &DyLdInfoCommand =
341       O.LoadCommands[*O.DyLdInfoCommandIndex]
342           .MachOLoadCommand.dyld_info_command_data;
343   char *Out = (char *)Buf->getBufferStart() + DyLdInfoCommand.rebase_off;
344   assert((DyLdInfoCommand.rebase_size == O.Rebases.Opcodes.size()) &&
345          "Incorrect rebase opcodes size");
346   memcpy(Out, O.Rebases.Opcodes.data(), O.Rebases.Opcodes.size());
347 }
348 
writeBindInfo()349 void MachOWriter::writeBindInfo() {
350   if (!O.DyLdInfoCommandIndex)
351     return;
352   const MachO::dyld_info_command &DyLdInfoCommand =
353       O.LoadCommands[*O.DyLdInfoCommandIndex]
354           .MachOLoadCommand.dyld_info_command_data;
355   char *Out = (char *)Buf->getBufferStart() + DyLdInfoCommand.bind_off;
356   assert((DyLdInfoCommand.bind_size == O.Binds.Opcodes.size()) &&
357          "Incorrect bind opcodes size");
358   memcpy(Out, O.Binds.Opcodes.data(), O.Binds.Opcodes.size());
359 }
360 
writeWeakBindInfo()361 void MachOWriter::writeWeakBindInfo() {
362   if (!O.DyLdInfoCommandIndex)
363     return;
364   const MachO::dyld_info_command &DyLdInfoCommand =
365       O.LoadCommands[*O.DyLdInfoCommandIndex]
366           .MachOLoadCommand.dyld_info_command_data;
367   char *Out = (char *)Buf->getBufferStart() + DyLdInfoCommand.weak_bind_off;
368   assert((DyLdInfoCommand.weak_bind_size == O.WeakBinds.Opcodes.size()) &&
369          "Incorrect weak bind opcodes size");
370   memcpy(Out, O.WeakBinds.Opcodes.data(), O.WeakBinds.Opcodes.size());
371 }
372 
writeLazyBindInfo()373 void MachOWriter::writeLazyBindInfo() {
374   if (!O.DyLdInfoCommandIndex)
375     return;
376   const MachO::dyld_info_command &DyLdInfoCommand =
377       O.LoadCommands[*O.DyLdInfoCommandIndex]
378           .MachOLoadCommand.dyld_info_command_data;
379   char *Out = (char *)Buf->getBufferStart() + DyLdInfoCommand.lazy_bind_off;
380   assert((DyLdInfoCommand.lazy_bind_size == O.LazyBinds.Opcodes.size()) &&
381          "Incorrect lazy bind opcodes size");
382   memcpy(Out, O.LazyBinds.Opcodes.data(), O.LazyBinds.Opcodes.size());
383 }
384 
writeExportInfo()385 void MachOWriter::writeExportInfo() {
386   if (!O.DyLdInfoCommandIndex)
387     return;
388   const MachO::dyld_info_command &DyLdInfoCommand =
389       O.LoadCommands[*O.DyLdInfoCommandIndex]
390           .MachOLoadCommand.dyld_info_command_data;
391   char *Out = (char *)Buf->getBufferStart() + DyLdInfoCommand.export_off;
392   assert((DyLdInfoCommand.export_size == O.Exports.Trie.size()) &&
393          "Incorrect export trie size");
394   memcpy(Out, O.Exports.Trie.data(), O.Exports.Trie.size());
395 }
396 
writeIndirectSymbolTable()397 void MachOWriter::writeIndirectSymbolTable() {
398   if (!O.DySymTabCommandIndex)
399     return;
400 
401   const MachO::dysymtab_command &DySymTabCommand =
402       O.LoadCommands[*O.DySymTabCommandIndex]
403           .MachOLoadCommand.dysymtab_command_data;
404 
405   uint32_t *Out =
406       (uint32_t *)(Buf->getBufferStart() + DySymTabCommand.indirectsymoff);
407   for (const IndirectSymbolEntry &Sym : O.IndirectSymTable.Symbols) {
408     uint32_t Entry = (Sym.Symbol) ? (*Sym.Symbol)->Index : Sym.OriginalIndex;
409     if (IsLittleEndian != sys::IsLittleEndianHost)
410       sys::swapByteOrder(Entry);
411     *Out++ = Entry;
412   }
413 }
414 
writeLinkData(Optional<size_t> LCIndex,const LinkData & LD)415 void MachOWriter::writeLinkData(Optional<size_t> LCIndex, const LinkData &LD) {
416   if (!LCIndex)
417     return;
418   const MachO::linkedit_data_command &LinkEditDataCommand =
419       O.LoadCommands[*LCIndex].MachOLoadCommand.linkedit_data_command_data;
420   char *Out = (char *)Buf->getBufferStart() + LinkEditDataCommand.dataoff;
421   assert((LinkEditDataCommand.datasize == LD.Data.size()) &&
422          "Incorrect data size");
423   memcpy(Out, LD.Data.data(), LD.Data.size());
424 }
425 
writeCodeSignatureData()426 void MachOWriter::writeCodeSignatureData() {
427   return writeLinkData(O.CodeSignatureCommandIndex, O.CodeSignature);
428 }
429 
writeDataInCodeData()430 void MachOWriter::writeDataInCodeData() {
431   return writeLinkData(O.DataInCodeCommandIndex, O.DataInCode);
432 }
433 
writeLinkerOptimizationHint()434 void MachOWriter::writeLinkerOptimizationHint() {
435   return writeLinkData(O.LinkerOptimizationHintCommandIndex,
436                        O.LinkerOptimizationHint);
437 }
438 
writeFunctionStartsData()439 void MachOWriter::writeFunctionStartsData() {
440   return writeLinkData(O.FunctionStartsCommandIndex, O.FunctionStarts);
441 }
442 
writeTail()443 void MachOWriter::writeTail() {
444   typedef void (MachOWriter::*WriteHandlerType)(void);
445   typedef std::pair<uint64_t, WriteHandlerType> WriteOperation;
446   SmallVector<WriteOperation, 7> Queue;
447 
448   if (O.SymTabCommandIndex) {
449     const MachO::symtab_command &SymTabCommand =
450         O.LoadCommands[*O.SymTabCommandIndex]
451             .MachOLoadCommand.symtab_command_data;
452     if (SymTabCommand.symoff)
453       Queue.push_back({SymTabCommand.symoff, &MachOWriter::writeSymbolTable});
454     if (SymTabCommand.stroff)
455       Queue.push_back({SymTabCommand.stroff, &MachOWriter::writeStringTable});
456   }
457 
458   if (O.DyLdInfoCommandIndex) {
459     const MachO::dyld_info_command &DyLdInfoCommand =
460         O.LoadCommands[*O.DyLdInfoCommandIndex]
461             .MachOLoadCommand.dyld_info_command_data;
462     if (DyLdInfoCommand.rebase_off)
463       Queue.push_back(
464           {DyLdInfoCommand.rebase_off, &MachOWriter::writeRebaseInfo});
465     if (DyLdInfoCommand.bind_off)
466       Queue.push_back({DyLdInfoCommand.bind_off, &MachOWriter::writeBindInfo});
467     if (DyLdInfoCommand.weak_bind_off)
468       Queue.push_back(
469           {DyLdInfoCommand.weak_bind_off, &MachOWriter::writeWeakBindInfo});
470     if (DyLdInfoCommand.lazy_bind_off)
471       Queue.push_back(
472           {DyLdInfoCommand.lazy_bind_off, &MachOWriter::writeLazyBindInfo});
473     if (DyLdInfoCommand.export_off)
474       Queue.push_back(
475           {DyLdInfoCommand.export_off, &MachOWriter::writeExportInfo});
476   }
477 
478   if (O.DySymTabCommandIndex) {
479     const MachO::dysymtab_command &DySymTabCommand =
480         O.LoadCommands[*O.DySymTabCommandIndex]
481             .MachOLoadCommand.dysymtab_command_data;
482 
483     if (DySymTabCommand.indirectsymoff)
484       Queue.emplace_back(DySymTabCommand.indirectsymoff,
485                          &MachOWriter::writeIndirectSymbolTable);
486   }
487 
488   if (O.CodeSignatureCommandIndex) {
489     const MachO::linkedit_data_command &LinkEditDataCommand =
490         O.LoadCommands[*O.CodeSignatureCommandIndex]
491             .MachOLoadCommand.linkedit_data_command_data;
492 
493     if (LinkEditDataCommand.dataoff)
494       Queue.emplace_back(LinkEditDataCommand.dataoff,
495                          &MachOWriter::writeCodeSignatureData);
496   }
497 
498   if (O.DataInCodeCommandIndex) {
499     const MachO::linkedit_data_command &LinkEditDataCommand =
500         O.LoadCommands[*O.DataInCodeCommandIndex]
501             .MachOLoadCommand.linkedit_data_command_data;
502 
503     if (LinkEditDataCommand.dataoff)
504       Queue.emplace_back(LinkEditDataCommand.dataoff,
505                          &MachOWriter::writeDataInCodeData);
506   }
507 
508   if (O.LinkerOptimizationHintCommandIndex) {
509     const MachO::linkedit_data_command &LinkEditDataCommand =
510         O.LoadCommands[*O.LinkerOptimizationHintCommandIndex]
511             .MachOLoadCommand.linkedit_data_command_data;
512 
513     if (LinkEditDataCommand.dataoff)
514       Queue.emplace_back(LinkEditDataCommand.dataoff,
515                          &MachOWriter::writeLinkerOptimizationHint);
516   }
517 
518   if (O.FunctionStartsCommandIndex) {
519     const MachO::linkedit_data_command &LinkEditDataCommand =
520         O.LoadCommands[*O.FunctionStartsCommandIndex]
521             .MachOLoadCommand.linkedit_data_command_data;
522 
523     if (LinkEditDataCommand.dataoff)
524       Queue.emplace_back(LinkEditDataCommand.dataoff,
525                          &MachOWriter::writeFunctionStartsData);
526   }
527 
528   llvm::sort(Queue, [](const WriteOperation &LHS, const WriteOperation &RHS) {
529     return LHS.first < RHS.first;
530   });
531 
532   for (auto WriteOp : Queue)
533     (this->*WriteOp.second)();
534 }
535 
finalize()536 Error MachOWriter::finalize() { return LayoutBuilder.layout(); }
537 
write()538 Error MachOWriter::write() {
539   size_t TotalSize = totalSize();
540   Buf = WritableMemoryBuffer::getNewMemBuffer(TotalSize);
541   if (!Buf)
542     return createStringError(errc::not_enough_memory,
543                              "failed to allocate memory buffer of " +
544                                  Twine::utohexstr(TotalSize) + " bytes");
545   memset(Buf->getBufferStart(), 0, totalSize());
546   writeHeader();
547   writeLoadCommands();
548   writeSections();
549   writeTail();
550 
551   // TODO: Implement direct writing to the output stream (without intermediate
552   // memory buffer Buf).
553   Out.write(Buf->getBufferStart(), Buf->getBufferSize());
554   return Error::success();
555 }
556