xref: /freebsd-src/contrib/llvm-project/llvm/lib/MC/WinCOFFObjectWriter.cpp (revision 5ffd83dbcc34f10e07f6d3e968ae6365869615f4)
1 //===- llvm/MC/WinCOFFObjectWriter.cpp ------------------------------------===//
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 // This file contains an implementation of a Win32 COFF object file writer.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/DenseMap.h"
14 #include "llvm/ADT/DenseSet.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/BinaryFormat/COFF.h"
21 #include "llvm/MC/MCAsmLayout.h"
22 #include "llvm/MC/MCAssembler.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCExpr.h"
25 #include "llvm/MC/MCFixup.h"
26 #include "llvm/MC/MCFragment.h"
27 #include "llvm/MC/MCObjectWriter.h"
28 #include "llvm/MC/MCSection.h"
29 #include "llvm/MC/MCSectionCOFF.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/MC/MCSymbolCOFF.h"
32 #include "llvm/MC/MCValue.h"
33 #include "llvm/MC/MCWinCOFFObjectWriter.h"
34 #include "llvm/MC/StringTableBuilder.h"
35 #include "llvm/Support/CRC.h"
36 #include "llvm/Support/Casting.h"
37 #include "llvm/Support/EndianStream.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/LEB128.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include <algorithm>
43 #include <cassert>
44 #include <cstddef>
45 #include <cstdint>
46 #include <cstring>
47 #include <ctime>
48 #include <memory>
49 #include <string>
50 #include <vector>
51 
52 using namespace llvm;
53 using llvm::support::endian::write32le;
54 
55 #define DEBUG_TYPE "WinCOFFObjectWriter"
56 
57 namespace {
58 
59 using name = SmallString<COFF::NameSize>;
60 
61 enum AuxiliaryType {
62   ATWeakExternal,
63   ATFile,
64   ATSectionDefinition
65 };
66 
67 struct AuxSymbol {
68   AuxiliaryType AuxType;
69   COFF::Auxiliary Aux;
70 };
71 
72 class COFFSection;
73 
74 class COFFSymbol {
75 public:
76   COFF::symbol Data = {};
77 
78   using AuxiliarySymbols = SmallVector<AuxSymbol, 1>;
79 
80   name Name;
81   int Index;
82   AuxiliarySymbols Aux;
83   COFFSymbol *Other = nullptr;
84   COFFSection *Section = nullptr;
85   int Relocations = 0;
86   const MCSymbol *MC = nullptr;
87 
88   COFFSymbol(StringRef Name) : Name(Name) {}
89 
90   void set_name_offset(uint32_t Offset);
91 
92   int64_t getIndex() const { return Index; }
93   void setIndex(int Value) {
94     Index = Value;
95     if (MC)
96       MC->setIndex(static_cast<uint32_t>(Value));
97   }
98 };
99 
100 // This class contains staging data for a COFF relocation entry.
101 struct COFFRelocation {
102   COFF::relocation Data;
103   COFFSymbol *Symb = nullptr;
104 
105   COFFRelocation() = default;
106 
107   static size_t size() { return COFF::RelocationSize; }
108 };
109 
110 using relocations = std::vector<COFFRelocation>;
111 
112 class COFFSection {
113 public:
114   COFF::section Header = {};
115 
116   std::string Name;
117   int Number;
118   MCSectionCOFF const *MCSection = nullptr;
119   COFFSymbol *Symbol = nullptr;
120   relocations Relocations;
121 
122   COFFSection(StringRef Name) : Name(std::string(Name)) {}
123 };
124 
125 class WinCOFFObjectWriter : public MCObjectWriter {
126 public:
127   support::endian::Writer W;
128 
129   using symbols = std::vector<std::unique_ptr<COFFSymbol>>;
130   using sections = std::vector<std::unique_ptr<COFFSection>>;
131 
132   using symbol_map = DenseMap<MCSymbol const *, COFFSymbol *>;
133   using section_map = DenseMap<MCSection const *, COFFSection *>;
134 
135   using symbol_list = DenseSet<COFFSymbol *>;
136 
137   std::unique_ptr<MCWinCOFFObjectTargetWriter> TargetObjectWriter;
138 
139   // Root level file contents.
140   COFF::header Header = {};
141   sections Sections;
142   symbols Symbols;
143   StringTableBuilder Strings{StringTableBuilder::WinCOFF};
144 
145   // Maps used during object file creation.
146   section_map SectionMap;
147   symbol_map SymbolMap;
148 
149   symbol_list WeakDefaults;
150 
151   bool UseBigObj;
152 
153   bool EmitAddrsigSection = false;
154   MCSectionCOFF *AddrsigSection;
155   std::vector<const MCSymbol *> AddrsigSyms;
156 
157   MCSectionCOFF *CGProfileSection = nullptr;
158 
159   WinCOFFObjectWriter(std::unique_ptr<MCWinCOFFObjectTargetWriter> MOTW,
160                       raw_pwrite_stream &OS);
161 
162   void reset() override {
163     memset(&Header, 0, sizeof(Header));
164     Header.Machine = TargetObjectWriter->getMachine();
165     Sections.clear();
166     Symbols.clear();
167     Strings.clear();
168     SectionMap.clear();
169     SymbolMap.clear();
170     MCObjectWriter::reset();
171   }
172 
173   COFFSymbol *createSymbol(StringRef Name);
174   COFFSymbol *GetOrCreateCOFFSymbol(const MCSymbol *Symbol);
175   COFFSection *createSection(StringRef Name);
176 
177   void defineSection(MCSectionCOFF const &Sec);
178 
179   COFFSymbol *getLinkedSymbol(const MCSymbol &Symbol);
180   void DefineSymbol(const MCSymbol &Symbol, MCAssembler &Assembler,
181                     const MCAsmLayout &Layout);
182 
183   void SetSymbolName(COFFSymbol &S);
184   void SetSectionName(COFFSection &S);
185 
186   bool IsPhysicalSection(COFFSection *S);
187 
188   // Entity writing methods.
189 
190   void WriteFileHeader(const COFF::header &Header);
191   void WriteSymbol(const COFFSymbol &S);
192   void WriteAuxiliarySymbols(const COFFSymbol::AuxiliarySymbols &S);
193   void writeSectionHeaders();
194   void WriteRelocation(const COFF::relocation &R);
195   uint32_t writeSectionContents(MCAssembler &Asm, const MCAsmLayout &Layout,
196                                 const MCSection &MCSec);
197   void writeSection(MCAssembler &Asm, const MCAsmLayout &Layout,
198                     const COFFSection &Sec, const MCSection &MCSec);
199 
200   // MCObjectWriter interface implementation.
201 
202   void executePostLayoutBinding(MCAssembler &Asm,
203                                 const MCAsmLayout &Layout) override;
204 
205   bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
206                                               const MCSymbol &SymA,
207                                               const MCFragment &FB, bool InSet,
208                                               bool IsPCRel) const override;
209 
210   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
211                         const MCFragment *Fragment, const MCFixup &Fixup,
212                         MCValue Target, uint64_t &FixedValue) override;
213 
214   void createFileSymbols(MCAssembler &Asm);
215   void setWeakDefaultNames();
216   void assignSectionNumbers();
217   void assignFileOffsets(MCAssembler &Asm, const MCAsmLayout &Layout);
218 
219   void emitAddrsigSection() override { EmitAddrsigSection = true; }
220   void addAddrsigSymbol(const MCSymbol *Sym) override {
221     AddrsigSyms.push_back(Sym);
222   }
223 
224   uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
225 };
226 
227 } // end anonymous namespace
228 
229 //------------------------------------------------------------------------------
230 // Symbol class implementation
231 
232 // In the case that the name does not fit within 8 bytes, the offset
233 // into the string table is stored in the last 4 bytes instead, leaving
234 // the first 4 bytes as 0.
235 void COFFSymbol::set_name_offset(uint32_t Offset) {
236   write32le(Data.Name + 0, 0);
237   write32le(Data.Name + 4, Offset);
238 }
239 
240 //------------------------------------------------------------------------------
241 // WinCOFFObjectWriter class implementation
242 
243 WinCOFFObjectWriter::WinCOFFObjectWriter(
244     std::unique_ptr<MCWinCOFFObjectTargetWriter> MOTW, raw_pwrite_stream &OS)
245     : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {
246   Header.Machine = TargetObjectWriter->getMachine();
247 }
248 
249 COFFSymbol *WinCOFFObjectWriter::createSymbol(StringRef Name) {
250   Symbols.push_back(std::make_unique<COFFSymbol>(Name));
251   return Symbols.back().get();
252 }
253 
254 COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(const MCSymbol *Symbol) {
255   COFFSymbol *&Ret = SymbolMap[Symbol];
256   if (!Ret)
257     Ret = createSymbol(Symbol->getName());
258   return Ret;
259 }
260 
261 COFFSection *WinCOFFObjectWriter::createSection(StringRef Name) {
262   Sections.emplace_back(std::make_unique<COFFSection>(Name));
263   return Sections.back().get();
264 }
265 
266 static uint32_t getAlignment(const MCSectionCOFF &Sec) {
267   switch (Sec.getAlignment()) {
268   case 1:
269     return COFF::IMAGE_SCN_ALIGN_1BYTES;
270   case 2:
271     return COFF::IMAGE_SCN_ALIGN_2BYTES;
272   case 4:
273     return COFF::IMAGE_SCN_ALIGN_4BYTES;
274   case 8:
275     return COFF::IMAGE_SCN_ALIGN_8BYTES;
276   case 16:
277     return COFF::IMAGE_SCN_ALIGN_16BYTES;
278   case 32:
279     return COFF::IMAGE_SCN_ALIGN_32BYTES;
280   case 64:
281     return COFF::IMAGE_SCN_ALIGN_64BYTES;
282   case 128:
283     return COFF::IMAGE_SCN_ALIGN_128BYTES;
284   case 256:
285     return COFF::IMAGE_SCN_ALIGN_256BYTES;
286   case 512:
287     return COFF::IMAGE_SCN_ALIGN_512BYTES;
288   case 1024:
289     return COFF::IMAGE_SCN_ALIGN_1024BYTES;
290   case 2048:
291     return COFF::IMAGE_SCN_ALIGN_2048BYTES;
292   case 4096:
293     return COFF::IMAGE_SCN_ALIGN_4096BYTES;
294   case 8192:
295     return COFF::IMAGE_SCN_ALIGN_8192BYTES;
296   }
297   llvm_unreachable("unsupported section alignment");
298 }
299 
300 /// This function takes a section data object from the assembler
301 /// and creates the associated COFF section staging object.
302 void WinCOFFObjectWriter::defineSection(const MCSectionCOFF &MCSec) {
303   COFFSection *Section = createSection(MCSec.getName());
304   COFFSymbol *Symbol = createSymbol(MCSec.getName());
305   Section->Symbol = Symbol;
306   Symbol->Section = Section;
307   Symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
308 
309   // Create a COMDAT symbol if needed.
310   if (MCSec.getSelection() != COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
311     if (const MCSymbol *S = MCSec.getCOMDATSymbol()) {
312       COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(S);
313       if (COMDATSymbol->Section)
314         report_fatal_error("two sections have the same comdat");
315       COMDATSymbol->Section = Section;
316     }
317   }
318 
319   // In this case the auxiliary symbol is a Section Definition.
320   Symbol->Aux.resize(1);
321   Symbol->Aux[0] = {};
322   Symbol->Aux[0].AuxType = ATSectionDefinition;
323   Symbol->Aux[0].Aux.SectionDefinition.Selection = MCSec.getSelection();
324 
325   // Set section alignment.
326   Section->Header.Characteristics = MCSec.getCharacteristics();
327   Section->Header.Characteristics |= getAlignment(MCSec);
328 
329   // Bind internal COFF section to MC section.
330   Section->MCSection = &MCSec;
331   SectionMap[&MCSec] = Section;
332 }
333 
334 static uint64_t getSymbolValue(const MCSymbol &Symbol,
335                                const MCAsmLayout &Layout) {
336   if (Symbol.isCommon() && Symbol.isExternal())
337     return Symbol.getCommonSize();
338 
339   uint64_t Res;
340   if (!Layout.getSymbolOffset(Symbol, Res))
341     return 0;
342 
343   return Res;
344 }
345 
346 COFFSymbol *WinCOFFObjectWriter::getLinkedSymbol(const MCSymbol &Symbol) {
347   if (!Symbol.isVariable())
348     return nullptr;
349 
350   const MCSymbolRefExpr *SymRef =
351       dyn_cast<MCSymbolRefExpr>(Symbol.getVariableValue());
352   if (!SymRef)
353     return nullptr;
354 
355   const MCSymbol &Aliasee = SymRef->getSymbol();
356   if (!Aliasee.isUndefined())
357     return nullptr;
358   return GetOrCreateCOFFSymbol(&Aliasee);
359 }
360 
361 /// This function takes a symbol data object from the assembler
362 /// and creates the associated COFF symbol staging object.
363 void WinCOFFObjectWriter::DefineSymbol(const MCSymbol &MCSym,
364                                        MCAssembler &Assembler,
365                                        const MCAsmLayout &Layout) {
366   COFFSymbol *Sym = GetOrCreateCOFFSymbol(&MCSym);
367   const MCSymbol *Base = Layout.getBaseSymbol(MCSym);
368   COFFSection *Sec = nullptr;
369   if (Base && Base->getFragment()) {
370     Sec = SectionMap[Base->getFragment()->getParent()];
371     if (Sym->Section && Sym->Section != Sec)
372       report_fatal_error("conflicting sections for symbol");
373   }
374 
375   COFFSymbol *Local = nullptr;
376   if (cast<MCSymbolCOFF>(MCSym).isWeakExternal()) {
377     Sym->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
378 
379     COFFSymbol *WeakDefault = getLinkedSymbol(MCSym);
380     if (!WeakDefault) {
381       std::string WeakName = (".weak." + MCSym.getName() + ".default").str();
382       WeakDefault = createSymbol(WeakName);
383       if (!Sec)
384         WeakDefault->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
385       else
386         WeakDefault->Section = Sec;
387       WeakDefaults.insert(WeakDefault);
388       Local = WeakDefault;
389     }
390 
391     Sym->Other = WeakDefault;
392 
393     // Setup the Weak External auxiliary symbol.
394     Sym->Aux.resize(1);
395     memset(&Sym->Aux[0], 0, sizeof(Sym->Aux[0]));
396     Sym->Aux[0].AuxType = ATWeakExternal;
397     Sym->Aux[0].Aux.WeakExternal.TagIndex = 0;
398     Sym->Aux[0].Aux.WeakExternal.Characteristics =
399         COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS;
400   } else {
401     if (!Base)
402       Sym->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
403     else
404       Sym->Section = Sec;
405     Local = Sym;
406   }
407 
408   if (Local) {
409     Local->Data.Value = getSymbolValue(MCSym, Layout);
410 
411     const MCSymbolCOFF &SymbolCOFF = cast<MCSymbolCOFF>(MCSym);
412     Local->Data.Type = SymbolCOFF.getType();
413     Local->Data.StorageClass = SymbolCOFF.getClass();
414 
415     // If no storage class was specified in the streamer, define it here.
416     if (Local->Data.StorageClass == COFF::IMAGE_SYM_CLASS_NULL) {
417       bool IsExternal = MCSym.isExternal() ||
418                         (!MCSym.getFragment() && !MCSym.isVariable());
419 
420       Local->Data.StorageClass = IsExternal ? COFF::IMAGE_SYM_CLASS_EXTERNAL
421                                             : COFF::IMAGE_SYM_CLASS_STATIC;
422     }
423   }
424 
425   Sym->MC = &MCSym;
426 }
427 
428 // Maximum offsets for different string table entry encodings.
429 enum : unsigned { Max7DecimalOffset = 9999999U };
430 enum : uint64_t { MaxBase64Offset = 0xFFFFFFFFFULL }; // 64^6, including 0
431 
432 // Encode a string table entry offset in base 64, padded to 6 chars, and
433 // prefixed with a double slash: '//AAAAAA', '//AAAAAB', ...
434 // Buffer must be at least 8 bytes large. No terminating null appended.
435 static void encodeBase64StringEntry(char *Buffer, uint64_t Value) {
436   assert(Value > Max7DecimalOffset && Value <= MaxBase64Offset &&
437          "Illegal section name encoding for value");
438 
439   static const char Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
440                                  "abcdefghijklmnopqrstuvwxyz"
441                                  "0123456789+/";
442 
443   Buffer[0] = '/';
444   Buffer[1] = '/';
445 
446   char *Ptr = Buffer + 7;
447   for (unsigned i = 0; i < 6; ++i) {
448     unsigned Rem = Value % 64;
449     Value /= 64;
450     *(Ptr--) = Alphabet[Rem];
451   }
452 }
453 
454 void WinCOFFObjectWriter::SetSectionName(COFFSection &S) {
455   if (S.Name.size() <= COFF::NameSize) {
456     std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
457     return;
458   }
459 
460   uint64_t StringTableEntry = Strings.getOffset(S.Name);
461   if (StringTableEntry <= Max7DecimalOffset) {
462     SmallVector<char, COFF::NameSize> Buffer;
463     Twine('/').concat(Twine(StringTableEntry)).toVector(Buffer);
464     assert(Buffer.size() <= COFF::NameSize && Buffer.size() >= 2);
465     std::memcpy(S.Header.Name, Buffer.data(), Buffer.size());
466     return;
467   }
468   if (StringTableEntry <= MaxBase64Offset) {
469     // Starting with 10,000,000, offsets are encoded as base64.
470     encodeBase64StringEntry(S.Header.Name, StringTableEntry);
471     return;
472   }
473   report_fatal_error("COFF string table is greater than 64 GB.");
474 }
475 
476 void WinCOFFObjectWriter::SetSymbolName(COFFSymbol &S) {
477   if (S.Name.size() > COFF::NameSize)
478     S.set_name_offset(Strings.getOffset(S.Name));
479   else
480     std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
481 }
482 
483 bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) {
484   return (S->Header.Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) ==
485          0;
486 }
487 
488 //------------------------------------------------------------------------------
489 // entity writing methods
490 
491 void WinCOFFObjectWriter::WriteFileHeader(const COFF::header &Header) {
492   if (UseBigObj) {
493     W.write<uint16_t>(COFF::IMAGE_FILE_MACHINE_UNKNOWN);
494     W.write<uint16_t>(0xFFFF);
495     W.write<uint16_t>(COFF::BigObjHeader::MinBigObjectVersion);
496     W.write<uint16_t>(Header.Machine);
497     W.write<uint32_t>(Header.TimeDateStamp);
498     W.OS.write(COFF::BigObjMagic, sizeof(COFF::BigObjMagic));
499     W.write<uint32_t>(0);
500     W.write<uint32_t>(0);
501     W.write<uint32_t>(0);
502     W.write<uint32_t>(0);
503     W.write<uint32_t>(Header.NumberOfSections);
504     W.write<uint32_t>(Header.PointerToSymbolTable);
505     W.write<uint32_t>(Header.NumberOfSymbols);
506   } else {
507     W.write<uint16_t>(Header.Machine);
508     W.write<uint16_t>(static_cast<int16_t>(Header.NumberOfSections));
509     W.write<uint32_t>(Header.TimeDateStamp);
510     W.write<uint32_t>(Header.PointerToSymbolTable);
511     W.write<uint32_t>(Header.NumberOfSymbols);
512     W.write<uint16_t>(Header.SizeOfOptionalHeader);
513     W.write<uint16_t>(Header.Characteristics);
514   }
515 }
516 
517 void WinCOFFObjectWriter::WriteSymbol(const COFFSymbol &S) {
518   W.OS.write(S.Data.Name, COFF::NameSize);
519   W.write<uint32_t>(S.Data.Value);
520   if (UseBigObj)
521     W.write<uint32_t>(S.Data.SectionNumber);
522   else
523     W.write<uint16_t>(static_cast<int16_t>(S.Data.SectionNumber));
524   W.write<uint16_t>(S.Data.Type);
525   W.OS << char(S.Data.StorageClass);
526   W.OS << char(S.Data.NumberOfAuxSymbols);
527   WriteAuxiliarySymbols(S.Aux);
528 }
529 
530 void WinCOFFObjectWriter::WriteAuxiliarySymbols(
531     const COFFSymbol::AuxiliarySymbols &S) {
532   for (const AuxSymbol &i : S) {
533     switch (i.AuxType) {
534     case ATWeakExternal:
535       W.write<uint32_t>(i.Aux.WeakExternal.TagIndex);
536       W.write<uint32_t>(i.Aux.WeakExternal.Characteristics);
537       W.OS.write_zeros(sizeof(i.Aux.WeakExternal.unused));
538       if (UseBigObj)
539         W.OS.write_zeros(COFF::Symbol32Size - COFF::Symbol16Size);
540       break;
541     case ATFile:
542       W.OS.write(reinterpret_cast<const char *>(&i.Aux),
543                         UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size);
544       break;
545     case ATSectionDefinition:
546       W.write<uint32_t>(i.Aux.SectionDefinition.Length);
547       W.write<uint16_t>(i.Aux.SectionDefinition.NumberOfRelocations);
548       W.write<uint16_t>(i.Aux.SectionDefinition.NumberOfLinenumbers);
549       W.write<uint32_t>(i.Aux.SectionDefinition.CheckSum);
550       W.write<uint16_t>(static_cast<int16_t>(i.Aux.SectionDefinition.Number));
551       W.OS << char(i.Aux.SectionDefinition.Selection);
552       W.OS.write_zeros(sizeof(i.Aux.SectionDefinition.unused));
553       W.write<uint16_t>(static_cast<int16_t>(i.Aux.SectionDefinition.Number >> 16));
554       if (UseBigObj)
555         W.OS.write_zeros(COFF::Symbol32Size - COFF::Symbol16Size);
556       break;
557     }
558   }
559 }
560 
561 // Write the section header.
562 void WinCOFFObjectWriter::writeSectionHeaders() {
563   // Section numbers must be monotonically increasing in the section
564   // header, but our Sections array is not sorted by section number,
565   // so make a copy of Sections and sort it.
566   std::vector<COFFSection *> Arr;
567   for (auto &Section : Sections)
568     Arr.push_back(Section.get());
569   llvm::sort(Arr, [](const COFFSection *A, const COFFSection *B) {
570     return A->Number < B->Number;
571   });
572 
573   for (auto &Section : Arr) {
574     if (Section->Number == -1)
575       continue;
576 
577     COFF::section &S = Section->Header;
578     if (Section->Relocations.size() >= 0xffff)
579       S.Characteristics |= COFF::IMAGE_SCN_LNK_NRELOC_OVFL;
580     W.OS.write(S.Name, COFF::NameSize);
581     W.write<uint32_t>(S.VirtualSize);
582     W.write<uint32_t>(S.VirtualAddress);
583     W.write<uint32_t>(S.SizeOfRawData);
584     W.write<uint32_t>(S.PointerToRawData);
585     W.write<uint32_t>(S.PointerToRelocations);
586     W.write<uint32_t>(S.PointerToLineNumbers);
587     W.write<uint16_t>(S.NumberOfRelocations);
588     W.write<uint16_t>(S.NumberOfLineNumbers);
589     W.write<uint32_t>(S.Characteristics);
590   }
591 }
592 
593 void WinCOFFObjectWriter::WriteRelocation(const COFF::relocation &R) {
594   W.write<uint32_t>(R.VirtualAddress);
595   W.write<uint32_t>(R.SymbolTableIndex);
596   W.write<uint16_t>(R.Type);
597 }
598 
599 // Write MCSec's contents. What this function does is essentially
600 // "Asm.writeSectionData(&MCSec, Layout)", but it's a bit complicated
601 // because it needs to compute a CRC.
602 uint32_t WinCOFFObjectWriter::writeSectionContents(MCAssembler &Asm,
603                                                    const MCAsmLayout &Layout,
604                                                    const MCSection &MCSec) {
605   // Save the contents of the section to a temporary buffer, we need this
606   // to CRC the data before we dump it into the object file.
607   SmallVector<char, 128> Buf;
608   raw_svector_ostream VecOS(Buf);
609   Asm.writeSectionData(VecOS, &MCSec, Layout);
610 
611   // Write the section contents to the object file.
612   W.OS << Buf;
613 
614   // Calculate our CRC with an initial value of '0', this is not how
615   // JamCRC is specified but it aligns with the expected output.
616   JamCRC JC(/*Init=*/0);
617   JC.update(makeArrayRef(reinterpret_cast<uint8_t*>(Buf.data()), Buf.size()));
618   return JC.getCRC();
619 }
620 
621 void WinCOFFObjectWriter::writeSection(MCAssembler &Asm,
622                                        const MCAsmLayout &Layout,
623                                        const COFFSection &Sec,
624                                        const MCSection &MCSec) {
625   if (Sec.Number == -1)
626     return;
627 
628   // Write the section contents.
629   if (Sec.Header.PointerToRawData != 0) {
630     assert(W.OS.tell() == Sec.Header.PointerToRawData &&
631            "Section::PointerToRawData is insane!");
632 
633     uint32_t CRC = writeSectionContents(Asm, Layout, MCSec);
634 
635     // Update the section definition auxiliary symbol to record the CRC.
636     COFFSection *Sec = SectionMap[&MCSec];
637     COFFSymbol::AuxiliarySymbols &AuxSyms = Sec->Symbol->Aux;
638     assert(AuxSyms.size() == 1 && AuxSyms[0].AuxType == ATSectionDefinition);
639     AuxSymbol &SecDef = AuxSyms[0];
640     SecDef.Aux.SectionDefinition.CheckSum = CRC;
641   }
642 
643   // Write relocations for this section.
644   if (Sec.Relocations.empty()) {
645     assert(Sec.Header.PointerToRelocations == 0 &&
646            "Section::PointerToRelocations is insane!");
647     return;
648   }
649 
650   assert(W.OS.tell() == Sec.Header.PointerToRelocations &&
651          "Section::PointerToRelocations is insane!");
652 
653   if (Sec.Relocations.size() >= 0xffff) {
654     // In case of overflow, write actual relocation count as first
655     // relocation. Including the synthetic reloc itself (+ 1).
656     COFF::relocation R;
657     R.VirtualAddress = Sec.Relocations.size() + 1;
658     R.SymbolTableIndex = 0;
659     R.Type = 0;
660     WriteRelocation(R);
661   }
662 
663   for (const auto &Relocation : Sec.Relocations)
664     WriteRelocation(Relocation.Data);
665 }
666 
667 ////////////////////////////////////////////////////////////////////////////////
668 // MCObjectWriter interface implementations
669 
670 void WinCOFFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
671                                                    const MCAsmLayout &Layout) {
672   if (EmitAddrsigSection) {
673     AddrsigSection = Asm.getContext().getCOFFSection(
674         ".llvm_addrsig", COFF::IMAGE_SCN_LNK_REMOVE,
675         SectionKind::getMetadata());
676     Asm.registerSection(*AddrsigSection);
677   }
678 
679   if (!Asm.CGProfile.empty()) {
680     CGProfileSection = Asm.getContext().getCOFFSection(
681         ".llvm.call-graph-profile", COFF::IMAGE_SCN_LNK_REMOVE,
682         SectionKind::getMetadata());
683     Asm.registerSection(*CGProfileSection);
684   }
685 
686   // "Define" each section & symbol. This creates section & symbol
687   // entries in the staging area.
688   for (const auto &Section : Asm)
689     defineSection(static_cast<const MCSectionCOFF &>(Section));
690 
691   for (const MCSymbol &Symbol : Asm.symbols())
692     if (!Symbol.isTemporary())
693       DefineSymbol(Symbol, Asm, Layout);
694 }
695 
696 bool WinCOFFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
697     const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
698     bool InSet, bool IsPCRel) const {
699   // Don't drop relocations between functions, even if they are in the same text
700   // section. Multiple Visual C++ linker features depend on having the
701   // relocations present. The /INCREMENTAL flag will cause these relocations to
702   // point to thunks, and the /GUARD:CF flag assumes that it can use relocations
703   // to approximate the set of all address taken functions. LLD's implementation
704   // of /GUARD:CF also relies on the existance of these relocations.
705   uint16_t Type = cast<MCSymbolCOFF>(SymA).getType();
706   if ((Type >> COFF::SCT_COMPLEX_TYPE_SHIFT) == COFF::IMAGE_SYM_DTYPE_FUNCTION)
707     return false;
708   return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
709                                                                 InSet, IsPCRel);
710 }
711 
712 void WinCOFFObjectWriter::recordRelocation(MCAssembler &Asm,
713                                            const MCAsmLayout &Layout,
714                                            const MCFragment *Fragment,
715                                            const MCFixup &Fixup, MCValue Target,
716                                            uint64_t &FixedValue) {
717   assert(Target.getSymA() && "Relocation must reference a symbol!");
718 
719   const MCSymbol &A = Target.getSymA()->getSymbol();
720   if (!A.isRegistered()) {
721     Asm.getContext().reportError(Fixup.getLoc(),
722                                       Twine("symbol '") + A.getName() +
723                                           "' can not be undefined");
724     return;
725   }
726   if (A.isTemporary() && A.isUndefined()) {
727     Asm.getContext().reportError(Fixup.getLoc(),
728                                       Twine("assembler label '") + A.getName() +
729                                           "' can not be undefined");
730     return;
731   }
732 
733   MCSection *MCSec = Fragment->getParent();
734 
735   // Mark this symbol as requiring an entry in the symbol table.
736   assert(SectionMap.find(MCSec) != SectionMap.end() &&
737          "Section must already have been defined in executePostLayoutBinding!");
738 
739   COFFSection *Sec = SectionMap[MCSec];
740   const MCSymbolRefExpr *SymB = Target.getSymB();
741 
742   if (SymB) {
743     const MCSymbol *B = &SymB->getSymbol();
744     if (!B->getFragment()) {
745       Asm.getContext().reportError(
746           Fixup.getLoc(),
747           Twine("symbol '") + B->getName() +
748               "' can not be undefined in a subtraction expression");
749       return;
750     }
751 
752     // Offset of the symbol in the section
753     int64_t OffsetOfB = Layout.getSymbolOffset(*B);
754 
755     // Offset of the relocation in the section
756     int64_t OffsetOfRelocation =
757         Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
758 
759     FixedValue = (OffsetOfRelocation - OffsetOfB) + Target.getConstant();
760   } else {
761     FixedValue = Target.getConstant();
762   }
763 
764   COFFRelocation Reloc;
765 
766   Reloc.Data.SymbolTableIndex = 0;
767   Reloc.Data.VirtualAddress = Layout.getFragmentOffset(Fragment);
768 
769   // Turn relocations for temporary symbols into section relocations.
770   if (A.isTemporary()) {
771     MCSection *TargetSection = &A.getSection();
772     assert(
773         SectionMap.find(TargetSection) != SectionMap.end() &&
774         "Section must already have been defined in executePostLayoutBinding!");
775     Reloc.Symb = SectionMap[TargetSection]->Symbol;
776     FixedValue += Layout.getSymbolOffset(A);
777   } else {
778     assert(
779         SymbolMap.find(&A) != SymbolMap.end() &&
780         "Symbol must already have been defined in executePostLayoutBinding!");
781     Reloc.Symb = SymbolMap[&A];
782   }
783 
784   ++Reloc.Symb->Relocations;
785 
786   Reloc.Data.VirtualAddress += Fixup.getOffset();
787   Reloc.Data.Type = TargetObjectWriter->getRelocType(
788       Asm.getContext(), Target, Fixup, SymB, Asm.getBackend());
789 
790   // FIXME: Can anyone explain what this does other than adjust for the size
791   // of the offset?
792   if ((Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64 &&
793        Reloc.Data.Type == COFF::IMAGE_REL_AMD64_REL32) ||
794       (Header.Machine == COFF::IMAGE_FILE_MACHINE_I386 &&
795        Reloc.Data.Type == COFF::IMAGE_REL_I386_REL32))
796     FixedValue += 4;
797 
798   if (Header.Machine == COFF::IMAGE_FILE_MACHINE_ARMNT) {
799     switch (Reloc.Data.Type) {
800     case COFF::IMAGE_REL_ARM_ABSOLUTE:
801     case COFF::IMAGE_REL_ARM_ADDR32:
802     case COFF::IMAGE_REL_ARM_ADDR32NB:
803     case COFF::IMAGE_REL_ARM_TOKEN:
804     case COFF::IMAGE_REL_ARM_SECTION:
805     case COFF::IMAGE_REL_ARM_SECREL:
806       break;
807     case COFF::IMAGE_REL_ARM_BRANCH11:
808     case COFF::IMAGE_REL_ARM_BLX11:
809     // IMAGE_REL_ARM_BRANCH11 and IMAGE_REL_ARM_BLX11 are only used for
810     // pre-ARMv7, which implicitly rules it out of ARMNT (it would be valid
811     // for Windows CE).
812     case COFF::IMAGE_REL_ARM_BRANCH24:
813     case COFF::IMAGE_REL_ARM_BLX24:
814     case COFF::IMAGE_REL_ARM_MOV32A:
815       // IMAGE_REL_ARM_BRANCH24, IMAGE_REL_ARM_BLX24, IMAGE_REL_ARM_MOV32A are
816       // only used for ARM mode code, which is documented as being unsupported
817       // by Windows on ARM.  Empirical proof indicates that masm is able to
818       // generate the relocations however the rest of the MSVC toolchain is
819       // unable to handle it.
820       llvm_unreachable("unsupported relocation");
821       break;
822     case COFF::IMAGE_REL_ARM_MOV32T:
823       break;
824     case COFF::IMAGE_REL_ARM_BRANCH20T:
825     case COFF::IMAGE_REL_ARM_BRANCH24T:
826     case COFF::IMAGE_REL_ARM_BLX23T:
827       // IMAGE_REL_BRANCH20T, IMAGE_REL_ARM_BRANCH24T, IMAGE_REL_ARM_BLX23T all
828       // perform a 4 byte adjustment to the relocation.  Relative branches are
829       // offset by 4 on ARM, however, because there is no RELA relocations, all
830       // branches are offset by 4.
831       FixedValue = FixedValue + 4;
832       break;
833     }
834   }
835 
836   // The fixed value never makes sense for section indices, ignore it.
837   if (Fixup.getKind() == FK_SecRel_2)
838     FixedValue = 0;
839 
840   if (TargetObjectWriter->recordRelocation(Fixup))
841     Sec->Relocations.push_back(Reloc);
842 }
843 
844 static std::time_t getTime() {
845   std::time_t Now = time(nullptr);
846   if (Now < 0 || !isUInt<32>(Now))
847     return UINT32_MAX;
848   return Now;
849 }
850 
851 // Create .file symbols.
852 void WinCOFFObjectWriter::createFileSymbols(MCAssembler &Asm) {
853   for (const std::string &Name : Asm.getFileNames()) {
854     // round up to calculate the number of auxiliary symbols required
855     unsigned SymbolSize = UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size;
856     unsigned Count = (Name.size() + SymbolSize - 1) / SymbolSize;
857 
858     COFFSymbol *File = createSymbol(".file");
859     File->Data.SectionNumber = COFF::IMAGE_SYM_DEBUG;
860     File->Data.StorageClass = COFF::IMAGE_SYM_CLASS_FILE;
861     File->Aux.resize(Count);
862 
863     unsigned Offset = 0;
864     unsigned Length = Name.size();
865     for (auto &Aux : File->Aux) {
866       Aux.AuxType = ATFile;
867 
868       if (Length > SymbolSize) {
869         memcpy(&Aux.Aux, Name.c_str() + Offset, SymbolSize);
870         Length = Length - SymbolSize;
871       } else {
872         memcpy(&Aux.Aux, Name.c_str() + Offset, Length);
873         memset((char *)&Aux.Aux + Length, 0, SymbolSize - Length);
874         break;
875       }
876 
877       Offset += SymbolSize;
878     }
879   }
880 }
881 
882 void WinCOFFObjectWriter::setWeakDefaultNames() {
883   if (WeakDefaults.empty())
884     return;
885 
886   // If multiple object files use a weak symbol (either with a regular
887   // defined default, or an absolute zero symbol as default), the defaults
888   // cause duplicate definitions unless their names are made unique. Look
889   // for a defined extern symbol, that isn't comdat - that should be unique
890   // unless there are other duplicate definitions. And if none is found,
891   // allow picking a comdat symbol, as that's still better than nothing.
892 
893   COFFSymbol *Unique = nullptr;
894   for (bool AllowComdat : {false, true}) {
895     for (auto &Sym : Symbols) {
896       // Don't include the names of the defaults themselves
897       if (WeakDefaults.count(Sym.get()))
898         continue;
899       // Only consider external symbols
900       if (Sym->Data.StorageClass != COFF::IMAGE_SYM_CLASS_EXTERNAL)
901         continue;
902       // Only consider symbols defined in a section or that are absolute
903       if (!Sym->Section && Sym->Data.SectionNumber != COFF::IMAGE_SYM_ABSOLUTE)
904         continue;
905       if (!AllowComdat && Sym->Section &&
906           Sym->Section->Header.Characteristics & COFF::IMAGE_SCN_LNK_COMDAT)
907         continue;
908       Unique = Sym.get();
909       break;
910     }
911     if (Unique)
912       break;
913   }
914   // If we didn't find any unique symbol to use for the names, just skip this.
915   if (!Unique)
916     return;
917   for (auto *Sym : WeakDefaults) {
918     Sym->Name.append(".");
919     Sym->Name.append(Unique->Name);
920   }
921 }
922 
923 static bool isAssociative(const COFFSection &Section) {
924   return Section.Symbol->Aux[0].Aux.SectionDefinition.Selection ==
925          COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
926 }
927 
928 void WinCOFFObjectWriter::assignSectionNumbers() {
929   size_t I = 1;
930   auto Assign = [&](COFFSection &Section) {
931     Section.Number = I;
932     Section.Symbol->Data.SectionNumber = I;
933     Section.Symbol->Aux[0].Aux.SectionDefinition.Number = I;
934     ++I;
935   };
936 
937   // Although it is not explicitly requested by the Microsoft COFF spec,
938   // we should avoid emitting forward associative section references,
939   // because MSVC link.exe as of 2017 cannot handle that.
940   for (const std::unique_ptr<COFFSection> &Section : Sections)
941     if (!isAssociative(*Section))
942       Assign(*Section);
943   for (const std::unique_ptr<COFFSection> &Section : Sections)
944     if (isAssociative(*Section))
945       Assign(*Section);
946 }
947 
948 // Assign file offsets to COFF object file structures.
949 void WinCOFFObjectWriter::assignFileOffsets(MCAssembler &Asm,
950                                             const MCAsmLayout &Layout) {
951   unsigned Offset = W.OS.tell();
952 
953   Offset += UseBigObj ? COFF::Header32Size : COFF::Header16Size;
954   Offset += COFF::SectionSize * Header.NumberOfSections;
955 
956   for (const auto &Section : Asm) {
957     COFFSection *Sec = SectionMap[&Section];
958 
959     if (Sec->Number == -1)
960       continue;
961 
962     Sec->Header.SizeOfRawData = Layout.getSectionAddressSize(&Section);
963 
964     if (IsPhysicalSection(Sec)) {
965       Sec->Header.PointerToRawData = Offset;
966       Offset += Sec->Header.SizeOfRawData;
967     }
968 
969     if (!Sec->Relocations.empty()) {
970       bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
971 
972       if (RelocationsOverflow) {
973         // Signal overflow by setting NumberOfRelocations to max value. Actual
974         // size is found in reloc #0. Microsoft tools understand this.
975         Sec->Header.NumberOfRelocations = 0xffff;
976       } else {
977         Sec->Header.NumberOfRelocations = Sec->Relocations.size();
978       }
979       Sec->Header.PointerToRelocations = Offset;
980 
981       if (RelocationsOverflow) {
982         // Reloc #0 will contain actual count, so make room for it.
983         Offset += COFF::RelocationSize;
984       }
985 
986       Offset += COFF::RelocationSize * Sec->Relocations.size();
987 
988       for (auto &Relocation : Sec->Relocations) {
989         assert(Relocation.Symb->getIndex() != -1);
990         Relocation.Data.SymbolTableIndex = Relocation.Symb->getIndex();
991       }
992     }
993 
994     assert(Sec->Symbol->Aux.size() == 1 &&
995            "Section's symbol must have one aux!");
996     AuxSymbol &Aux = Sec->Symbol->Aux[0];
997     assert(Aux.AuxType == ATSectionDefinition &&
998            "Section's symbol's aux symbol must be a Section Definition!");
999     Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
1000     Aux.Aux.SectionDefinition.NumberOfRelocations =
1001         Sec->Header.NumberOfRelocations;
1002     Aux.Aux.SectionDefinition.NumberOfLinenumbers =
1003         Sec->Header.NumberOfLineNumbers;
1004   }
1005 
1006   Header.PointerToSymbolTable = Offset;
1007 }
1008 
1009 uint64_t WinCOFFObjectWriter::writeObject(MCAssembler &Asm,
1010                                           const MCAsmLayout &Layout) {
1011   uint64_t StartOffset = W.OS.tell();
1012 
1013   if (Sections.size() > INT32_MAX)
1014     report_fatal_error(
1015         "PE COFF object files can't have more than 2147483647 sections");
1016 
1017   UseBigObj = Sections.size() > COFF::MaxNumberOfSections16;
1018   Header.NumberOfSections = Sections.size();
1019   Header.NumberOfSymbols = 0;
1020 
1021   setWeakDefaultNames();
1022   assignSectionNumbers();
1023   createFileSymbols(Asm);
1024 
1025   for (auto &Symbol : Symbols) {
1026     // Update section number & offset for symbols that have them.
1027     if (Symbol->Section)
1028       Symbol->Data.SectionNumber = Symbol->Section->Number;
1029     Symbol->setIndex(Header.NumberOfSymbols++);
1030     // Update auxiliary symbol info.
1031     Symbol->Data.NumberOfAuxSymbols = Symbol->Aux.size();
1032     Header.NumberOfSymbols += Symbol->Data.NumberOfAuxSymbols;
1033   }
1034 
1035   // Build string table.
1036   for (const auto &S : Sections)
1037     if (S->Name.size() > COFF::NameSize)
1038       Strings.add(S->Name);
1039   for (const auto &S : Symbols)
1040     if (S->Name.size() > COFF::NameSize)
1041       Strings.add(S->Name);
1042   Strings.finalize();
1043 
1044   // Set names.
1045   for (const auto &S : Sections)
1046     SetSectionName(*S);
1047   for (auto &S : Symbols)
1048     SetSymbolName(*S);
1049 
1050   // Fixup weak external references.
1051   for (auto &Symbol : Symbols) {
1052     if (Symbol->Other) {
1053       assert(Symbol->getIndex() != -1);
1054       assert(Symbol->Aux.size() == 1 && "Symbol must contain one aux symbol!");
1055       assert(Symbol->Aux[0].AuxType == ATWeakExternal &&
1056              "Symbol's aux symbol must be a Weak External!");
1057       Symbol->Aux[0].Aux.WeakExternal.TagIndex = Symbol->Other->getIndex();
1058     }
1059   }
1060 
1061   // Fixup associative COMDAT sections.
1062   for (auto &Section : Sections) {
1063     if (Section->Symbol->Aux[0].Aux.SectionDefinition.Selection !=
1064         COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1065       continue;
1066 
1067     const MCSectionCOFF &MCSec = *Section->MCSection;
1068     const MCSymbol *AssocMCSym = MCSec.getCOMDATSymbol();
1069     assert(AssocMCSym);
1070 
1071     // It's an error to try to associate with an undefined symbol or a symbol
1072     // without a section.
1073     if (!AssocMCSym->isInSection()) {
1074       Asm.getContext().reportError(
1075           SMLoc(), Twine("cannot make section ") + MCSec.getName() +
1076                        Twine(" associative with sectionless symbol ") +
1077                        AssocMCSym->getName());
1078       continue;
1079     }
1080 
1081     const auto *AssocMCSec = cast<MCSectionCOFF>(&AssocMCSym->getSection());
1082     assert(SectionMap.count(AssocMCSec));
1083     COFFSection *AssocSec = SectionMap[AssocMCSec];
1084 
1085     // Skip this section if the associated section is unused.
1086     if (AssocSec->Number == -1)
1087       continue;
1088 
1089     Section->Symbol->Aux[0].Aux.SectionDefinition.Number = AssocSec->Number;
1090   }
1091 
1092   // Create the contents of the .llvm_addrsig section.
1093   if (EmitAddrsigSection) {
1094     auto Frag = new MCDataFragment(AddrsigSection);
1095     Frag->setLayoutOrder(0);
1096     raw_svector_ostream OS(Frag->getContents());
1097     for (const MCSymbol *S : AddrsigSyms) {
1098       if (!S->isTemporary()) {
1099         encodeULEB128(S->getIndex(), OS);
1100         continue;
1101       }
1102 
1103       MCSection *TargetSection = &S->getSection();
1104       assert(SectionMap.find(TargetSection) != SectionMap.end() &&
1105              "Section must already have been defined in "
1106              "executePostLayoutBinding!");
1107       encodeULEB128(SectionMap[TargetSection]->Symbol->getIndex(), OS);
1108     }
1109   }
1110 
1111   // Create the contents of the .llvm.call-graph-profile section.
1112   if (CGProfileSection) {
1113     auto *Frag = new MCDataFragment(CGProfileSection);
1114     Frag->setLayoutOrder(0);
1115     raw_svector_ostream OS(Frag->getContents());
1116     for (const MCAssembler::CGProfileEntry &CGPE : Asm.CGProfile) {
1117       uint32_t FromIndex = CGPE.From->getSymbol().getIndex();
1118       uint32_t ToIndex = CGPE.To->getSymbol().getIndex();
1119       support::endian::write(OS, FromIndex, W.Endian);
1120       support::endian::write(OS, ToIndex, W.Endian);
1121       support::endian::write(OS, CGPE.Count, W.Endian);
1122     }
1123   }
1124 
1125   assignFileOffsets(Asm, Layout);
1126 
1127   // MS LINK expects to be able to use this timestamp to implement their
1128   // /INCREMENTAL feature.
1129   if (Asm.isIncrementalLinkerCompatible()) {
1130     Header.TimeDateStamp = getTime();
1131   } else {
1132     // Have deterministic output if /INCREMENTAL isn't needed. Also matches GNU.
1133     Header.TimeDateStamp = 0;
1134   }
1135 
1136   // Write it all to disk...
1137   WriteFileHeader(Header);
1138   writeSectionHeaders();
1139 
1140   // Write section contents.
1141   sections::iterator I = Sections.begin();
1142   sections::iterator IE = Sections.end();
1143   MCAssembler::iterator J = Asm.begin();
1144   MCAssembler::iterator JE = Asm.end();
1145   for (; I != IE && J != JE; ++I, ++J)
1146     writeSection(Asm, Layout, **I, *J);
1147 
1148   assert(W.OS.tell() == Header.PointerToSymbolTable &&
1149          "Header::PointerToSymbolTable is insane!");
1150 
1151   // Write a symbol table.
1152   for (auto &Symbol : Symbols)
1153     if (Symbol->getIndex() != -1)
1154       WriteSymbol(*Symbol);
1155 
1156   // Write a string table, which completes the entire COFF file.
1157   Strings.write(W.OS);
1158 
1159   return W.OS.tell() - StartOffset;
1160 }
1161 
1162 MCWinCOFFObjectTargetWriter::MCWinCOFFObjectTargetWriter(unsigned Machine_)
1163     : Machine(Machine_) {}
1164 
1165 // Pin the vtable to this file.
1166 void MCWinCOFFObjectTargetWriter::anchor() {}
1167 
1168 //------------------------------------------------------------------------------
1169 // WinCOFFObjectWriter factory function
1170 
1171 std::unique_ptr<MCObjectWriter> llvm::createWinCOFFObjectWriter(
1172     std::unique_ptr<MCWinCOFFObjectTargetWriter> MOTW, raw_pwrite_stream &OS) {
1173   return std::make_unique<WinCOFFObjectWriter>(std::move(MOTW), OS);
1174 }
1175