xref: /llvm-project-15.0.7/lld/COFF/Writer.cpp (revision 68f58a75)
1 //===- Writer.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 #include "Writer.h"
10 #include "Config.h"
11 #include "DLL.h"
12 #include "InputFiles.h"
13 #include "MapFile.h"
14 #include "PDB.h"
15 #include "SymbolTable.h"
16 #include "Symbols.h"
17 #include "lld/Common/ErrorHandler.h"
18 #include "lld/Common/Memory.h"
19 #include "lld/Common/Threads.h"
20 #include "lld/Common/Timer.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/Support/BinaryStreamReader.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Endian.h"
27 #include "llvm/Support/FileOutputBuffer.h"
28 #include "llvm/Support/Parallel.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/RandomNumberGenerator.h"
31 #include "llvm/Support/xxhash.h"
32 #include <algorithm>
33 #include <cstdio>
34 #include <map>
35 #include <memory>
36 #include <utility>
37 
38 using namespace llvm;
39 using namespace llvm::COFF;
40 using namespace llvm::object;
41 using namespace llvm::support;
42 using namespace llvm::support::endian;
43 using namespace lld;
44 using namespace lld::coff;
45 
46 /* To re-generate DOSProgram:
47 $ cat > /tmp/DOSProgram.asm
48 org 0
49         ; Copy cs to ds.
50         push cs
51         pop ds
52         ; Point ds:dx at the $-terminated string.
53         mov dx, str
54         ; Int 21/AH=09h: Write string to standard output.
55         mov ah, 0x9
56         int 0x21
57         ; Int 21/AH=4Ch: Exit with return code (in AL).
58         mov ax, 0x4C01
59         int 0x21
60 str:
61         db 'This program cannot be run in DOS mode.$'
62 align 8, db 0
63 $ nasm -fbin /tmp/DOSProgram.asm -o /tmp/DOSProgram.bin
64 $ xxd -i /tmp/DOSProgram.bin
65 */
66 static unsigned char dosProgram[] = {
67   0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09, 0xcd, 0x21, 0xb8, 0x01, 0x4c,
68   0xcd, 0x21, 0x54, 0x68, 0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72,
69   0x61, 0x6d, 0x20, 0x63, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x20, 0x62, 0x65,
70   0x20, 0x72, 0x75, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20,
71   0x6d, 0x6f, 0x64, 0x65, 0x2e, 0x24, 0x00, 0x00
72 };
73 static_assert(sizeof(dosProgram) % 8 == 0,
74               "DOSProgram size must be multiple of 8");
75 
76 static const int dosStubSize = sizeof(dos_header) + sizeof(dosProgram);
77 static_assert(dosStubSize % 8 == 0, "DOSStub size must be multiple of 8");
78 
79 static const int numberOfDataDirectory = 16;
80 
81 // Global vector of all output sections. After output sections are finalized,
82 // this can be indexed by Chunk::getOutputSection.
83 static std::vector<OutputSection *> outputSections;
84 
85 OutputSection *Chunk::getOutputSection() const {
86   return osidx == 0 ? nullptr : outputSections[osidx - 1];
87 }
88 
89 namespace {
90 
91 class DebugDirectoryChunk : public NonSectionChunk {
92 public:
93   DebugDirectoryChunk(const std::vector<Chunk *> &r, bool writeRepro)
94       : records(r), writeRepro(writeRepro) {}
95 
96   size_t getSize() const override {
97     return (records.size() + int(writeRepro)) * sizeof(debug_directory);
98   }
99 
100   void writeTo(uint8_t *b) const override {
101     auto *d = reinterpret_cast<debug_directory *>(b);
102 
103     for (const Chunk *record : records) {
104       OutputSection *os = record->getOutputSection();
105       uint64_t offs = os->getFileOff() + (record->getRVA() - os->getRVA());
106       fillEntry(d, COFF::IMAGE_DEBUG_TYPE_CODEVIEW, record->getSize(),
107                 record->getRVA(), offs);
108       ++d;
109     }
110 
111     if (writeRepro) {
112       // FIXME: The COFF spec allows either a 0-sized entry to just say
113       // "the timestamp field is really a hash", or a 4-byte size field
114       // followed by that many bytes containing a longer hash (with the
115       // lowest 4 bytes usually being the timestamp in little-endian order).
116       // Consider storing the full 8 bytes computed by xxHash64 here.
117       fillEntry(d, COFF::IMAGE_DEBUG_TYPE_REPRO, 0, 0, 0);
118     }
119   }
120 
121   void setTimeDateStamp(uint32_t timeDateStamp) {
122     for (support::ulittle32_t *tds : timeDateStamps)
123       *tds = timeDateStamp;
124   }
125 
126 private:
127   void fillEntry(debug_directory *d, COFF::DebugType debugType, size_t size,
128                  uint64_t rva, uint64_t offs) const {
129     d->Characteristics = 0;
130     d->TimeDateStamp = 0;
131     d->MajorVersion = 0;
132     d->MinorVersion = 0;
133     d->Type = debugType;
134     d->SizeOfData = size;
135     d->AddressOfRawData = rva;
136     d->PointerToRawData = offs;
137 
138     timeDateStamps.push_back(&d->TimeDateStamp);
139   }
140 
141   mutable std::vector<support::ulittle32_t *> timeDateStamps;
142   const std::vector<Chunk *> &records;
143   bool writeRepro;
144 };
145 
146 class CVDebugRecordChunk : public NonSectionChunk {
147 public:
148   size_t getSize() const override {
149     return sizeof(codeview::DebugInfo) + config->pdbAltPath.size() + 1;
150   }
151 
152   void writeTo(uint8_t *b) const override {
153     // Save off the DebugInfo entry to backfill the file signature (build id)
154     // in Writer::writeBuildId
155     buildId = reinterpret_cast<codeview::DebugInfo *>(b);
156 
157     // variable sized field (PDB Path)
158     char *p = reinterpret_cast<char *>(b + sizeof(*buildId));
159     if (!config->pdbAltPath.empty())
160       memcpy(p, config->pdbAltPath.data(), config->pdbAltPath.size());
161     p[config->pdbAltPath.size()] = '\0';
162   }
163 
164   mutable codeview::DebugInfo *buildId = nullptr;
165 };
166 
167 // PartialSection represents a group of chunks that contribute to an
168 // OutputSection. Collating a collection of PartialSections of same name and
169 // characteristics constitutes the OutputSection.
170 class PartialSectionKey {
171 public:
172   StringRef name;
173   unsigned characteristics;
174 
175   bool operator<(const PartialSectionKey &other) const {
176     int c = name.compare(other.name);
177     if (c == 1)
178       return false;
179     if (c == 0)
180       return characteristics < other.characteristics;
181     return true;
182   }
183 };
184 
185 // The writer writes a SymbolTable result to a file.
186 class Writer {
187 public:
188   Writer() : buffer(errorHandler().outputBuffer) {}
189   void run();
190 
191 private:
192   void createSections();
193   void createMiscChunks();
194   void createImportTables();
195   void appendImportThunks();
196   void locateImportTables();
197   void createExportTable();
198   void mergeSections();
199   void removeUnusedSections();
200   void assignAddresses();
201   void finalizeAddresses();
202   void removeEmptySections();
203   void assignOutputSectionIndices();
204   void createSymbolAndStringTable();
205   void openFile(StringRef outputPath);
206   template <typename PEHeaderTy> void writeHeader();
207   void createSEHTable();
208   void createRuntimePseudoRelocs();
209   void insertCtorDtorSymbols();
210   void createGuardCFTables();
211   void markSymbolsForRVATable(ObjFile *file,
212                               ArrayRef<SectionChunk *> symIdxChunks,
213                               SymbolRVASet &tableSymbols);
214   void maybeAddRVATable(SymbolRVASet tableSymbols, StringRef tableSym,
215                         StringRef countSym);
216   void setSectionPermissions();
217   void writeSections();
218   void writeBuildId();
219   void sortExceptionTable();
220   void sortCRTSectionChunks(std::vector<Chunk *> &chunks);
221   void addSyntheticIdata();
222   void fixPartialSectionChars(StringRef name, uint32_t chars);
223   bool fixGnuImportChunks();
224   PartialSection *createPartialSection(StringRef name, uint32_t outChars);
225   PartialSection *findPartialSection(StringRef name, uint32_t outChars);
226 
227   llvm::Optional<coff_symbol16> createSymbol(Defined *d);
228   size_t addEntryToStringTable(StringRef str);
229 
230   OutputSection *findSection(StringRef name);
231   void addBaserels();
232   void addBaserelBlocks(std::vector<Baserel> &v);
233 
234   uint32_t getSizeOfInitializedData();
235 
236   std::unique_ptr<FileOutputBuffer> &buffer;
237   std::map<PartialSectionKey, PartialSection *> partialSections;
238   std::vector<char> strtab;
239   std::vector<llvm::object::coff_symbol16> outputSymtab;
240   IdataContents idata;
241   Chunk *importTableStart = nullptr;
242   uint64_t importTableSize = 0;
243   Chunk *edataStart = nullptr;
244   Chunk *edataEnd = nullptr;
245   Chunk *iatStart = nullptr;
246   uint64_t iatSize = 0;
247   DelayLoadContents delayIdata;
248   EdataContents edata;
249   bool setNoSEHCharacteristic = false;
250 
251   DebugDirectoryChunk *debugDirectory = nullptr;
252   std::vector<Chunk *> debugRecords;
253   CVDebugRecordChunk *buildId = nullptr;
254   ArrayRef<uint8_t> sectionTable;
255 
256   uint64_t fileSize;
257   uint32_t pointerToSymbolTable = 0;
258   uint64_t sizeOfImage;
259   uint64_t sizeOfHeaders;
260 
261   OutputSection *textSec;
262   OutputSection *rdataSec;
263   OutputSection *buildidSec;
264   OutputSection *dataSec;
265   OutputSection *pdataSec;
266   OutputSection *idataSec;
267   OutputSection *edataSec;
268   OutputSection *didatSec;
269   OutputSection *rsrcSec;
270   OutputSection *relocSec;
271   OutputSection *ctorsSec;
272   OutputSection *dtorsSec;
273 
274   // The first and last .pdata sections in the output file.
275   //
276   // We need to keep track of the location of .pdata in whichever section it
277   // gets merged into so that we can sort its contents and emit a correct data
278   // directory entry for the exception table. This is also the case for some
279   // other sections (such as .edata) but because the contents of those sections
280   // are entirely linker-generated we can keep track of their locations using
281   // the chunks that the linker creates. All .pdata chunks come from input
282   // files, so we need to keep track of them separately.
283   Chunk *firstPdata = nullptr;
284   Chunk *lastPdata;
285 };
286 } // anonymous namespace
287 
288 namespace lld {
289 namespace coff {
290 
291 static Timer codeLayoutTimer("Code Layout", Timer::root());
292 static Timer diskCommitTimer("Commit Output File", Timer::root());
293 
294 void writeResult() { Writer().run(); }
295 
296 void OutputSection::addChunk(Chunk *c) {
297   chunks.push_back(c);
298 }
299 
300 void OutputSection::insertChunkAtStart(Chunk *c) {
301   chunks.insert(chunks.begin(), c);
302 }
303 
304 void OutputSection::setPermissions(uint32_t c) {
305   header.Characteristics &= ~permMask;
306   header.Characteristics |= c;
307 }
308 
309 void OutputSection::merge(OutputSection *other) {
310   chunks.insert(chunks.end(), other->chunks.begin(), other->chunks.end());
311   other->chunks.clear();
312   contribSections.insert(contribSections.end(), other->contribSections.begin(),
313                          other->contribSections.end());
314   other->contribSections.clear();
315 }
316 
317 // Write the section header to a given buffer.
318 void OutputSection::writeHeaderTo(uint8_t *buf) {
319   auto *hdr = reinterpret_cast<coff_section *>(buf);
320   *hdr = header;
321   if (stringTableOff) {
322     // If name is too long, write offset into the string table as a name.
323     sprintf(hdr->Name, "/%d", stringTableOff);
324   } else {
325     assert(!config->debug || name.size() <= COFF::NameSize ||
326            (hdr->Characteristics & IMAGE_SCN_MEM_DISCARDABLE) == 0);
327     strncpy(hdr->Name, name.data(),
328             std::min(name.size(), (size_t)COFF::NameSize));
329   }
330 }
331 
332 void OutputSection::addContributingPartialSection(PartialSection *sec) {
333   contribSections.push_back(sec);
334 }
335 
336 } // namespace coff
337 } // namespace lld
338 
339 // Check whether the target address S is in range from a relocation
340 // of type relType at address P.
341 static bool isInRange(uint16_t relType, uint64_t s, uint64_t p, int margin) {
342   if (config->machine == ARMNT) {
343     int64_t diff = AbsoluteDifference(s, p + 4) + margin;
344     switch (relType) {
345     case IMAGE_REL_ARM_BRANCH20T:
346       return isInt<21>(diff);
347     case IMAGE_REL_ARM_BRANCH24T:
348     case IMAGE_REL_ARM_BLX23T:
349       return isInt<25>(diff);
350     default:
351       return true;
352     }
353   } else if (config->machine == ARM64) {
354     int64_t diff = AbsoluteDifference(s, p) + margin;
355     switch (relType) {
356     case IMAGE_REL_ARM64_BRANCH26:
357       return isInt<28>(diff);
358     case IMAGE_REL_ARM64_BRANCH19:
359       return isInt<21>(diff);
360     case IMAGE_REL_ARM64_BRANCH14:
361       return isInt<16>(diff);
362     default:
363       return true;
364     }
365   } else {
366     llvm_unreachable("Unexpected architecture");
367   }
368 }
369 
370 // Return the last thunk for the given target if it is in range,
371 // or create a new one.
372 static std::pair<Defined *, bool>
373 getThunk(DenseMap<uint64_t, Defined *> &lastThunks, Defined *target, uint64_t p,
374          uint16_t type, int margin) {
375   Defined *&lastThunk = lastThunks[target->getRVA()];
376   if (lastThunk && isInRange(type, lastThunk->getRVA(), p, margin))
377     return {lastThunk, false};
378   Chunk *c;
379   switch (config->machine) {
380   case ARMNT:
381     c = make<RangeExtensionThunkARM>(target);
382     break;
383   case ARM64:
384     c = make<RangeExtensionThunkARM64>(target);
385     break;
386   default:
387     llvm_unreachable("Unexpected architecture");
388   }
389   Defined *d = make<DefinedSynthetic>("", c);
390   lastThunk = d;
391   return {d, true};
392 }
393 
394 // This checks all relocations, and for any relocation which isn't in range
395 // it adds a thunk after the section chunk that contains the relocation.
396 // If the latest thunk for the specific target is in range, that is used
397 // instead of creating a new thunk. All range checks are done with the
398 // specified margin, to make sure that relocations that originally are in
399 // range, but only barely, also get thunks - in case other added thunks makes
400 // the target go out of range.
401 //
402 // After adding thunks, we verify that all relocations are in range (with
403 // no extra margin requirements). If this failed, we restart (throwing away
404 // the previously created thunks) and retry with a wider margin.
405 static bool createThunks(OutputSection *os, int margin) {
406   bool addressesChanged = false;
407   DenseMap<uint64_t, Defined *> lastThunks;
408   DenseMap<std::pair<ObjFile *, Defined *>, uint32_t> thunkSymtabIndices;
409   size_t thunksSize = 0;
410   // Recheck Chunks.size() each iteration, since we can insert more
411   // elements into it.
412   for (size_t i = 0; i != os->chunks.size(); ++i) {
413     SectionChunk *sc = dyn_cast_or_null<SectionChunk>(os->chunks[i]);
414     if (!sc)
415       continue;
416     size_t thunkInsertionSpot = i + 1;
417 
418     // Try to get a good enough estimate of where new thunks will be placed.
419     // Offset this by the size of the new thunks added so far, to make the
420     // estimate slightly better.
421     size_t thunkInsertionRVA = sc->getRVA() + sc->getSize() + thunksSize;
422     ObjFile *file = sc->file;
423     std::vector<std::pair<uint32_t, uint32_t>> relocReplacements;
424     ArrayRef<coff_relocation> originalRelocs =
425         file->getCOFFObj()->getRelocations(sc->header);
426     for (size_t j = 0, e = originalRelocs.size(); j < e; ++j) {
427       const coff_relocation &rel = originalRelocs[j];
428       Symbol *relocTarget = file->getSymbol(rel.SymbolTableIndex);
429 
430       // The estimate of the source address P should be pretty accurate,
431       // but we don't know whether the target Symbol address should be
432       // offset by thunksSize or not (or by some of thunksSize but not all of
433       // it), giving us some uncertainty once we have added one thunk.
434       uint64_t p = sc->getRVA() + rel.VirtualAddress + thunksSize;
435 
436       Defined *sym = dyn_cast_or_null<Defined>(relocTarget);
437       if (!sym)
438         continue;
439 
440       uint64_t s = sym->getRVA();
441 
442       if (isInRange(rel.Type, s, p, margin))
443         continue;
444 
445       // If the target isn't in range, hook it up to an existing or new
446       // thunk.
447       Defined *thunk;
448       bool wasNew;
449       std::tie(thunk, wasNew) = getThunk(lastThunks, sym, p, rel.Type, margin);
450       if (wasNew) {
451         Chunk *thunkChunk = thunk->getChunk();
452         thunkChunk->setRVA(
453             thunkInsertionRVA); // Estimate of where it will be located.
454         os->chunks.insert(os->chunks.begin() + thunkInsertionSpot, thunkChunk);
455         thunkInsertionSpot++;
456         thunksSize += thunkChunk->getSize();
457         thunkInsertionRVA += thunkChunk->getSize();
458         addressesChanged = true;
459       }
460 
461       // To redirect the relocation, add a symbol to the parent object file's
462       // symbol table, and replace the relocation symbol table index with the
463       // new index.
464       auto insertion = thunkSymtabIndices.insert({{file, thunk}, ~0U});
465       uint32_t &thunkSymbolIndex = insertion.first->second;
466       if (insertion.second)
467         thunkSymbolIndex = file->addRangeThunkSymbol(thunk);
468       relocReplacements.push_back({j, thunkSymbolIndex});
469     }
470 
471     // Get a writable copy of this section's relocations so they can be
472     // modified. If the relocations point into the object file, allocate new
473     // memory. Otherwise, this must be previously allocated memory that can be
474     // modified in place.
475     ArrayRef<coff_relocation> curRelocs = sc->getRelocs();
476     MutableArrayRef<coff_relocation> newRelocs;
477     if (originalRelocs.data() == curRelocs.data()) {
478       newRelocs = makeMutableArrayRef(
479           bAlloc.Allocate<coff_relocation>(originalRelocs.size()),
480           originalRelocs.size());
481     } else {
482       newRelocs = makeMutableArrayRef(
483           const_cast<coff_relocation *>(curRelocs.data()), curRelocs.size());
484     }
485 
486     // Copy each relocation, but replace the symbol table indices which need
487     // thunks.
488     auto nextReplacement = relocReplacements.begin();
489     auto endReplacement = relocReplacements.end();
490     for (size_t i = 0, e = originalRelocs.size(); i != e; ++i) {
491       newRelocs[i] = originalRelocs[i];
492       if (nextReplacement != endReplacement && nextReplacement->first == i) {
493         newRelocs[i].SymbolTableIndex = nextReplacement->second;
494         ++nextReplacement;
495       }
496     }
497 
498     sc->setRelocs(newRelocs);
499   }
500   return addressesChanged;
501 }
502 
503 // Verify that all relocations are in range, with no extra margin requirements.
504 static bool verifyRanges(const std::vector<Chunk *> chunks) {
505   for (Chunk *c : chunks) {
506     SectionChunk *sc = dyn_cast_or_null<SectionChunk>(c);
507     if (!sc)
508       continue;
509 
510     ArrayRef<coff_relocation> relocs = sc->getRelocs();
511     for (size_t j = 0, e = relocs.size(); j < e; ++j) {
512       const coff_relocation &rel = relocs[j];
513       Symbol *relocTarget = sc->file->getSymbol(rel.SymbolTableIndex);
514 
515       Defined *sym = dyn_cast_or_null<Defined>(relocTarget);
516       if (!sym)
517         continue;
518 
519       uint64_t p = sc->getRVA() + rel.VirtualAddress;
520       uint64_t s = sym->getRVA();
521 
522       if (!isInRange(rel.Type, s, p, 0))
523         return false;
524     }
525   }
526   return true;
527 }
528 
529 // Assign addresses and add thunks if necessary.
530 void Writer::finalizeAddresses() {
531   assignAddresses();
532   if (config->machine != ARMNT && config->machine != ARM64)
533     return;
534 
535   size_t origNumChunks = 0;
536   for (OutputSection *sec : outputSections) {
537     sec->origChunks = sec->chunks;
538     origNumChunks += sec->chunks.size();
539   }
540 
541   int pass = 0;
542   int margin = 1024 * 100;
543   while (true) {
544     // First check whether we need thunks at all, or if the previous pass of
545     // adding them turned out ok.
546     bool rangesOk = true;
547     size_t numChunks = 0;
548     for (OutputSection *sec : outputSections) {
549       if (!verifyRanges(sec->chunks)) {
550         rangesOk = false;
551         break;
552       }
553       numChunks += sec->chunks.size();
554     }
555     if (rangesOk) {
556       if (pass > 0)
557         log("Added " + Twine(numChunks - origNumChunks) + " thunks with " +
558             "margin " + Twine(margin) + " in " + Twine(pass) + " passes");
559       return;
560     }
561 
562     if (pass >= 10)
563       fatal("adding thunks hasn't converged after " + Twine(pass) + " passes");
564 
565     if (pass > 0) {
566       // If the previous pass didn't work out, reset everything back to the
567       // original conditions before retrying with a wider margin. This should
568       // ideally never happen under real circumstances.
569       for (OutputSection *sec : outputSections)
570         sec->chunks = sec->origChunks;
571       margin *= 2;
572     }
573 
574     // Try adding thunks everywhere where it is needed, with a margin
575     // to avoid things going out of range due to the added thunks.
576     bool addressesChanged = false;
577     for (OutputSection *sec : outputSections)
578       addressesChanged |= createThunks(sec, margin);
579     // If the verification above thought we needed thunks, we should have
580     // added some.
581     assert(addressesChanged);
582 
583     // Recalculate the layout for the whole image (and verify the ranges at
584     // the start of the next round).
585     assignAddresses();
586 
587     pass++;
588   }
589 }
590 
591 // The main function of the writer.
592 void Writer::run() {
593   ScopedTimer t1(codeLayoutTimer);
594 
595   createImportTables();
596   createSections();
597   createMiscChunks();
598   appendImportThunks();
599   createExportTable();
600   mergeSections();
601   removeUnusedSections();
602   finalizeAddresses();
603   removeEmptySections();
604   assignOutputSectionIndices();
605   setSectionPermissions();
606   createSymbolAndStringTable();
607 
608   if (fileSize > UINT32_MAX)
609     fatal("image size (" + Twine(fileSize) + ") " +
610         "exceeds maximum allowable size (" + Twine(UINT32_MAX) + ")");
611 
612   openFile(config->outputFile);
613   if (config->is64()) {
614     writeHeader<pe32plus_header>();
615   } else {
616     writeHeader<pe32_header>();
617   }
618   writeSections();
619   sortExceptionTable();
620 
621   t1.stop();
622 
623   if (!config->pdbPath.empty() && config->debug) {
624     assert(buildId);
625     createPDB(symtab, outputSections, sectionTable, buildId->buildId);
626   }
627   writeBuildId();
628 
629   writeMapFile(outputSections);
630 
631   if (errorCount())
632     return;
633 
634   ScopedTimer t2(diskCommitTimer);
635   if (auto e = buffer->commit())
636     fatal("failed to write the output file: " + toString(std::move(e)));
637 }
638 
639 static StringRef getOutputSectionName(StringRef name) {
640   StringRef s = name.split('$').first;
641 
642   // Treat a later period as a separator for MinGW, for sections like
643   // ".ctors.01234".
644   return s.substr(0, s.find('.', 1));
645 }
646 
647 // For /order.
648 static void sortBySectionOrder(std::vector<Chunk *> &chunks) {
649   auto getPriority = [](const Chunk *c) {
650     if (auto *sec = dyn_cast<SectionChunk>(c))
651       if (sec->sym)
652         return config->order.lookup(sec->sym->getName());
653     return 0;
654   };
655 
656   llvm::stable_sort(chunks, [=](const Chunk *a, const Chunk *b) {
657     return getPriority(a) < getPriority(b);
658   });
659 }
660 
661 // Change the characteristics of existing PartialSections that belong to the
662 // section Name to Chars.
663 void Writer::fixPartialSectionChars(StringRef name, uint32_t chars) {
664   for (auto it : partialSections) {
665     PartialSection *pSec = it.second;
666     StringRef curName = pSec->name;
667     if (!curName.consume_front(name) ||
668         (!curName.empty() && !curName.startswith("$")))
669       continue;
670     if (pSec->characteristics == chars)
671       continue;
672     PartialSection *destSec = createPartialSection(pSec->name, chars);
673     destSec->chunks.insert(destSec->chunks.end(), pSec->chunks.begin(),
674                            pSec->chunks.end());
675     pSec->chunks.clear();
676   }
677 }
678 
679 // Sort concrete section chunks from GNU import libraries.
680 //
681 // GNU binutils doesn't use short import files, but instead produces import
682 // libraries that consist of object files, with section chunks for the .idata$*
683 // sections. These are linked just as regular static libraries. Each import
684 // library consists of one header object, one object file for every imported
685 // symbol, and one trailer object. In order for the .idata tables/lists to
686 // be formed correctly, the section chunks within each .idata$* section need
687 // to be grouped by library, and sorted alphabetically within each library
688 // (which makes sure the header comes first and the trailer last).
689 bool Writer::fixGnuImportChunks() {
690   uint32_t rdata = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ;
691 
692   // Make sure all .idata$* section chunks are mapped as RDATA in order to
693   // be sorted into the same sections as our own synthesized .idata chunks.
694   fixPartialSectionChars(".idata", rdata);
695 
696   bool hasIdata = false;
697   // Sort all .idata$* chunks, grouping chunks from the same library,
698   // with alphabetical ordering of the object fils within a library.
699   for (auto it : partialSections) {
700     PartialSection *pSec = it.second;
701     if (!pSec->name.startswith(".idata"))
702       continue;
703 
704     if (!pSec->chunks.empty())
705       hasIdata = true;
706     llvm::stable_sort(pSec->chunks, [&](Chunk *s, Chunk *t) {
707       SectionChunk *sc1 = dyn_cast_or_null<SectionChunk>(s);
708       SectionChunk *sc2 = dyn_cast_or_null<SectionChunk>(t);
709       if (!sc1 || !sc2) {
710         // if SC1, order them ascending. If SC2 or both null,
711         // S is not less than T.
712         return sc1 != nullptr;
713       }
714       // Make a string with "libraryname/objectfile" for sorting, achieving
715       // both grouping by library and sorting of objects within a library,
716       // at once.
717       std::string key1 =
718           (sc1->file->parentName + "/" + sc1->file->getName()).str();
719       std::string key2 =
720           (sc2->file->parentName + "/" + sc2->file->getName()).str();
721       return key1 < key2;
722     });
723   }
724   return hasIdata;
725 }
726 
727 // Add generated idata chunks, for imported symbols and DLLs, and a
728 // terminator in .idata$2.
729 void Writer::addSyntheticIdata() {
730   uint32_t rdata = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ;
731   idata.create();
732 
733   // Add the .idata content in the right section groups, to allow
734   // chunks from other linked in object files to be grouped together.
735   // See Microsoft PE/COFF spec 5.4 for details.
736   auto add = [&](StringRef n, std::vector<Chunk *> &v) {
737     PartialSection *pSec = createPartialSection(n, rdata);
738     pSec->chunks.insert(pSec->chunks.end(), v.begin(), v.end());
739   };
740 
741   // The loader assumes a specific order of data.
742   // Add each type in the correct order.
743   add(".idata$2", idata.dirs);
744   add(".idata$4", idata.lookups);
745   add(".idata$5", idata.addresses);
746   add(".idata$6", idata.hints);
747   add(".idata$7", idata.dllNames);
748 }
749 
750 // Locate the first Chunk and size of the import directory list and the
751 // IAT.
752 void Writer::locateImportTables() {
753   uint32_t rdata = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ;
754 
755   if (PartialSection *importDirs = findPartialSection(".idata$2", rdata)) {
756     if (!importDirs->chunks.empty())
757       importTableStart = importDirs->chunks.front();
758     for (Chunk *c : importDirs->chunks)
759       importTableSize += c->getSize();
760   }
761 
762   if (PartialSection *importAddresses = findPartialSection(".idata$5", rdata)) {
763     if (!importAddresses->chunks.empty())
764       iatStart = importAddresses->chunks.front();
765     for (Chunk *c : importAddresses->chunks)
766       iatSize += c->getSize();
767   }
768 }
769 
770 // Return whether a SectionChunk's suffix (the dollar and any trailing
771 // suffix) should be removed and sorted into the main suffixless
772 // PartialSection.
773 static bool shouldStripSectionSuffix(SectionChunk *sc, StringRef name) {
774   // On MinGW, comdat groups are formed by putting the comdat group name
775   // after the '$' in the section name. For .eh_frame$<symbol>, that must
776   // still be sorted before the .eh_frame trailer from crtend.o, thus just
777   // strip the section name trailer. For other sections, such as
778   // .tls$$<symbol> (where non-comdat .tls symbols are otherwise stored in
779   // ".tls$"), they must be strictly sorted after .tls. And for the
780   // hypothetical case of comdat .CRT$XCU, we definitely need to keep the
781   // suffix for sorting. Thus, to play it safe, only strip the suffix for
782   // the standard sections.
783   if (!config->mingw)
784     return false;
785   if (!sc || !sc->isCOMDAT())
786     return false;
787   return name.startswith(".text$") || name.startswith(".data$") ||
788          name.startswith(".rdata$") || name.startswith(".pdata$") ||
789          name.startswith(".xdata$") || name.startswith(".eh_frame$");
790 }
791 
792 // Create output section objects and add them to OutputSections.
793 void Writer::createSections() {
794   // First, create the builtin sections.
795   const uint32_t data = IMAGE_SCN_CNT_INITIALIZED_DATA;
796   const uint32_t bss = IMAGE_SCN_CNT_UNINITIALIZED_DATA;
797   const uint32_t code = IMAGE_SCN_CNT_CODE;
798   const uint32_t discardable = IMAGE_SCN_MEM_DISCARDABLE;
799   const uint32_t r = IMAGE_SCN_MEM_READ;
800   const uint32_t w = IMAGE_SCN_MEM_WRITE;
801   const uint32_t x = IMAGE_SCN_MEM_EXECUTE;
802 
803   SmallDenseMap<std::pair<StringRef, uint32_t>, OutputSection *> sections;
804   auto createSection = [&](StringRef name, uint32_t outChars) {
805     OutputSection *&sec = sections[{name, outChars}];
806     if (!sec) {
807       sec = make<OutputSection>(name, outChars);
808       outputSections.push_back(sec);
809     }
810     return sec;
811   };
812 
813   // Try to match the section order used by link.exe.
814   textSec = createSection(".text", code | r | x);
815   createSection(".bss", bss | r | w);
816   rdataSec = createSection(".rdata", data | r);
817   buildidSec = createSection(".buildid", data | r);
818   dataSec = createSection(".data", data | r | w);
819   pdataSec = createSection(".pdata", data | r);
820   idataSec = createSection(".idata", data | r);
821   edataSec = createSection(".edata", data | r);
822   didatSec = createSection(".didat", data | r);
823   rsrcSec = createSection(".rsrc", data | r);
824   relocSec = createSection(".reloc", data | discardable | r);
825   ctorsSec = createSection(".ctors", data | r | w);
826   dtorsSec = createSection(".dtors", data | r | w);
827 
828   // Then bin chunks by name and output characteristics.
829   for (Chunk *c : symtab->getChunks()) {
830     auto *sc = dyn_cast<SectionChunk>(c);
831     if (sc && !sc->live) {
832       if (config->verbose)
833         sc->printDiscardedMessage();
834       continue;
835     }
836     StringRef name = c->getSectionName();
837     if (shouldStripSectionSuffix(sc, name))
838       name = name.split('$').first;
839     PartialSection *pSec = createPartialSection(name,
840                                                 c->getOutputCharacteristics());
841     pSec->chunks.push_back(c);
842   }
843 
844   fixPartialSectionChars(".rsrc", data | r);
845   fixPartialSectionChars(".edata", data | r);
846   // Even in non MinGW cases, we might need to link against GNU import
847   // libraries.
848   bool hasIdata = fixGnuImportChunks();
849   if (!idata.empty())
850     hasIdata = true;
851 
852   if (hasIdata)
853     addSyntheticIdata();
854 
855   // Process an /order option.
856   if (!config->order.empty())
857     for (auto it : partialSections)
858       sortBySectionOrder(it.second->chunks);
859 
860   if (hasIdata)
861     locateImportTables();
862 
863   // Then create an OutputSection for each section.
864   // '$' and all following characters in input section names are
865   // discarded when determining output section. So, .text$foo
866   // contributes to .text, for example. See PE/COFF spec 3.2.
867   for (auto it : partialSections) {
868     PartialSection *pSec = it.second;
869     StringRef name = getOutputSectionName(pSec->name);
870     uint32_t outChars = pSec->characteristics;
871 
872     if (name == ".CRT") {
873       // In link.exe, there is a special case for the I386 target where .CRT
874       // sections are treated as if they have output characteristics DATA | R if
875       // their characteristics are DATA | R | W. This implements the same
876       // special case for all architectures.
877       outChars = data | r;
878 
879       log("Processing section " + pSec->name + " -> " + name);
880 
881       sortCRTSectionChunks(pSec->chunks);
882     }
883 
884     OutputSection *sec = createSection(name, outChars);
885     for (Chunk *c : pSec->chunks)
886       sec->addChunk(c);
887 
888     sec->addContributingPartialSection(pSec);
889   }
890 
891   // Finally, move some output sections to the end.
892   auto sectionOrder = [&](const OutputSection *s) {
893     // Move DISCARDABLE (or non-memory-mapped) sections to the end of file
894     // because the loader cannot handle holes. Stripping can remove other
895     // discardable ones than .reloc, which is first of them (created early).
896     if (s->header.Characteristics & IMAGE_SCN_MEM_DISCARDABLE)
897       return 2;
898     // .rsrc should come at the end of the non-discardable sections because its
899     // size may change by the Win32 UpdateResources() function, causing
900     // subsequent sections to move (see https://crbug.com/827082).
901     if (s == rsrcSec)
902       return 1;
903     return 0;
904   };
905   llvm::stable_sort(outputSections,
906                     [&](const OutputSection *s, const OutputSection *t) {
907                       return sectionOrder(s) < sectionOrder(t);
908                     });
909 }
910 
911 void Writer::createMiscChunks() {
912   for (MergeChunk *p : MergeChunk::instances) {
913     if (p) {
914       p->finalizeContents();
915       rdataSec->addChunk(p);
916     }
917   }
918 
919   // Create thunks for locally-dllimported symbols.
920   if (!symtab->localImportChunks.empty()) {
921     for (Chunk *c : symtab->localImportChunks)
922       rdataSec->addChunk(c);
923   }
924 
925   // Create Debug Information Chunks
926   OutputSection *debugInfoSec = config->mingw ? buildidSec : rdataSec;
927   if (config->debug || config->repro) {
928     debugDirectory = make<DebugDirectoryChunk>(debugRecords, config->repro);
929     debugInfoSec->addChunk(debugDirectory);
930   }
931 
932   if (config->debug) {
933     // Make a CVDebugRecordChunk even when /DEBUG:CV is not specified.  We
934     // output a PDB no matter what, and this chunk provides the only means of
935     // allowing a debugger to match a PDB and an executable.  So we need it even
936     // if we're ultimately not going to write CodeView data to the PDB.
937     buildId = make<CVDebugRecordChunk>();
938     debugRecords.push_back(buildId);
939 
940     for (Chunk *c : debugRecords)
941       debugInfoSec->addChunk(c);
942   }
943 
944   // Create SEH table. x86-only.
945   if (config->safeSEH)
946     createSEHTable();
947 
948   // Create /guard:cf tables if requested.
949   if (config->guardCF != GuardCFLevel::Off)
950     createGuardCFTables();
951 
952   if (config->mingw) {
953     createRuntimePseudoRelocs();
954 
955     insertCtorDtorSymbols();
956   }
957 }
958 
959 // Create .idata section for the DLL-imported symbol table.
960 // The format of this section is inherently Windows-specific.
961 // IdataContents class abstracted away the details for us,
962 // so we just let it create chunks and add them to the section.
963 void Writer::createImportTables() {
964   // Initialize DLLOrder so that import entries are ordered in
965   // the same order as in the command line. (That affects DLL
966   // initialization order, and this ordering is MSVC-compatible.)
967   for (ImportFile *file : ImportFile::instances) {
968     if (!file->live)
969       continue;
970 
971     std::string dll = StringRef(file->dllName).lower();
972     if (config->dllOrder.count(dll) == 0)
973       config->dllOrder[dll] = config->dllOrder.size();
974 
975     if (file->impSym && !isa<DefinedImportData>(file->impSym))
976       fatal(toString(*file->impSym) + " was replaced");
977     DefinedImportData *impSym = cast_or_null<DefinedImportData>(file->impSym);
978     if (config->delayLoads.count(StringRef(file->dllName).lower())) {
979       if (!file->thunkSym)
980         fatal("cannot delay-load " + toString(file) +
981               " due to import of data: " + toString(*impSym));
982       delayIdata.add(impSym);
983     } else {
984       idata.add(impSym);
985     }
986   }
987 }
988 
989 void Writer::appendImportThunks() {
990   if (ImportFile::instances.empty())
991     return;
992 
993   for (ImportFile *file : ImportFile::instances) {
994     if (!file->live)
995       continue;
996 
997     if (!file->thunkSym)
998       continue;
999 
1000     if (!isa<DefinedImportThunk>(file->thunkSym))
1001       fatal(toString(*file->thunkSym) + " was replaced");
1002     DefinedImportThunk *thunk = cast<DefinedImportThunk>(file->thunkSym);
1003     if (file->thunkLive)
1004       textSec->addChunk(thunk->getChunk());
1005   }
1006 
1007   if (!delayIdata.empty()) {
1008     Defined *helper = cast<Defined>(config->delayLoadHelper);
1009     delayIdata.create(helper);
1010     for (Chunk *c : delayIdata.getChunks())
1011       didatSec->addChunk(c);
1012     for (Chunk *c : delayIdata.getDataChunks())
1013       dataSec->addChunk(c);
1014     for (Chunk *c : delayIdata.getCodeChunks())
1015       textSec->addChunk(c);
1016   }
1017 }
1018 
1019 void Writer::createExportTable() {
1020   if (!edataSec->chunks.empty()) {
1021     // Allow using a custom built export table from input object files, instead
1022     // of having the linker synthesize the tables.
1023     if (config->hadExplicitExports)
1024       warn("literal .edata sections override exports");
1025   } else if (!config->exports.empty()) {
1026     for (Chunk *c : edata.chunks)
1027       edataSec->addChunk(c);
1028   }
1029   if (!edataSec->chunks.empty()) {
1030     edataStart = edataSec->chunks.front();
1031     edataEnd = edataSec->chunks.back();
1032   }
1033 }
1034 
1035 void Writer::removeUnusedSections() {
1036   // Remove sections that we can be sure won't get content, to avoid
1037   // allocating space for their section headers.
1038   auto isUnused = [this](OutputSection *s) {
1039     if (s == relocSec)
1040       return false; // This section is populated later.
1041     // MergeChunks have zero size at this point, as their size is finalized
1042     // later. Only remove sections that have no Chunks at all.
1043     return s->chunks.empty();
1044   };
1045   outputSections.erase(
1046       std::remove_if(outputSections.begin(), outputSections.end(), isUnused),
1047       outputSections.end());
1048 }
1049 
1050 // The Windows loader doesn't seem to like empty sections,
1051 // so we remove them if any.
1052 void Writer::removeEmptySections() {
1053   auto isEmpty = [](OutputSection *s) { return s->getVirtualSize() == 0; };
1054   outputSections.erase(
1055       std::remove_if(outputSections.begin(), outputSections.end(), isEmpty),
1056       outputSections.end());
1057 }
1058 
1059 void Writer::assignOutputSectionIndices() {
1060   // Assign final output section indices, and assign each chunk to its output
1061   // section.
1062   uint32_t idx = 1;
1063   for (OutputSection *os : outputSections) {
1064     os->sectionIndex = idx;
1065     for (Chunk *c : os->chunks)
1066       c->setOutputSectionIdx(idx);
1067     ++idx;
1068   }
1069 
1070   // Merge chunks are containers of chunks, so assign those an output section
1071   // too.
1072   for (MergeChunk *mc : MergeChunk::instances)
1073     if (mc)
1074       for (SectionChunk *sc : mc->sections)
1075         if (sc && sc->live)
1076           sc->setOutputSectionIdx(mc->getOutputSectionIdx());
1077 }
1078 
1079 size_t Writer::addEntryToStringTable(StringRef str) {
1080   assert(str.size() > COFF::NameSize);
1081   size_t offsetOfEntry = strtab.size() + 4; // +4 for the size field
1082   strtab.insert(strtab.end(), str.begin(), str.end());
1083   strtab.push_back('\0');
1084   return offsetOfEntry;
1085 }
1086 
1087 Optional<coff_symbol16> Writer::createSymbol(Defined *def) {
1088   coff_symbol16 sym;
1089   switch (def->kind()) {
1090   case Symbol::DefinedAbsoluteKind:
1091     sym.Value = def->getRVA();
1092     sym.SectionNumber = IMAGE_SYM_ABSOLUTE;
1093     break;
1094   case Symbol::DefinedSyntheticKind:
1095     // Relative symbols are unrepresentable in a COFF symbol table.
1096     return None;
1097   default: {
1098     // Don't write symbols that won't be written to the output to the symbol
1099     // table.
1100     Chunk *c = def->getChunk();
1101     if (!c)
1102       return None;
1103     OutputSection *os = c->getOutputSection();
1104     if (!os)
1105       return None;
1106 
1107     sym.Value = def->getRVA() - os->getRVA();
1108     sym.SectionNumber = os->sectionIndex;
1109     break;
1110   }
1111   }
1112 
1113   // Symbols that are runtime pseudo relocations don't point to the actual
1114   // symbol data itself (as they are imported), but points to the IAT entry
1115   // instead. Avoid emitting them to the symbol table, as they can confuse
1116   // debuggers.
1117   if (def->isRuntimePseudoReloc)
1118     return None;
1119 
1120   StringRef name = def->getName();
1121   if (name.size() > COFF::NameSize) {
1122     sym.Name.Offset.Zeroes = 0;
1123     sym.Name.Offset.Offset = addEntryToStringTable(name);
1124   } else {
1125     memset(sym.Name.ShortName, 0, COFF::NameSize);
1126     memcpy(sym.Name.ShortName, name.data(), name.size());
1127   }
1128 
1129   if (auto *d = dyn_cast<DefinedCOFF>(def)) {
1130     COFFSymbolRef ref = d->getCOFFSymbol();
1131     sym.Type = ref.getType();
1132     sym.StorageClass = ref.getStorageClass();
1133   } else {
1134     sym.Type = IMAGE_SYM_TYPE_NULL;
1135     sym.StorageClass = IMAGE_SYM_CLASS_EXTERNAL;
1136   }
1137   sym.NumberOfAuxSymbols = 0;
1138   return sym;
1139 }
1140 
1141 void Writer::createSymbolAndStringTable() {
1142   // PE/COFF images are limited to 8 byte section names. Longer names can be
1143   // supported by writing a non-standard string table, but this string table is
1144   // not mapped at runtime and the long names will therefore be inaccessible.
1145   // link.exe always truncates section names to 8 bytes, whereas binutils always
1146   // preserves long section names via the string table. LLD adopts a hybrid
1147   // solution where discardable sections have long names preserved and
1148   // non-discardable sections have their names truncated, to ensure that any
1149   // section which is mapped at runtime also has its name mapped at runtime.
1150   for (OutputSection *sec : outputSections) {
1151     if (sec->name.size() <= COFF::NameSize)
1152       continue;
1153     if ((sec->header.Characteristics & IMAGE_SCN_MEM_DISCARDABLE) == 0)
1154       continue;
1155     sec->setStringTableOff(addEntryToStringTable(sec->name));
1156   }
1157 
1158   if (config->debugDwarf || config->debugSymtab) {
1159     for (ObjFile *file : ObjFile::instances) {
1160       for (Symbol *b : file->getSymbols()) {
1161         auto *d = dyn_cast_or_null<Defined>(b);
1162         if (!d || d->writtenToSymtab)
1163           continue;
1164         d->writtenToSymtab = true;
1165 
1166         if (Optional<coff_symbol16> sym = createSymbol(d))
1167           outputSymtab.push_back(*sym);
1168       }
1169     }
1170   }
1171 
1172   if (outputSymtab.empty() && strtab.empty())
1173     return;
1174 
1175   // We position the symbol table to be adjacent to the end of the last section.
1176   uint64_t fileOff = fileSize;
1177   pointerToSymbolTable = fileOff;
1178   fileOff += outputSymtab.size() * sizeof(coff_symbol16);
1179   fileOff += 4 + strtab.size();
1180   fileSize = alignTo(fileOff, config->fileAlign);
1181 }
1182 
1183 void Writer::mergeSections() {
1184   if (!pdataSec->chunks.empty()) {
1185     firstPdata = pdataSec->chunks.front();
1186     lastPdata = pdataSec->chunks.back();
1187   }
1188 
1189   for (auto &p : config->merge) {
1190     StringRef toName = p.second;
1191     if (p.first == toName)
1192       continue;
1193     StringSet<> names;
1194     while (1) {
1195       if (!names.insert(toName).second)
1196         fatal("/merge: cycle found for section '" + p.first + "'");
1197       auto i = config->merge.find(toName);
1198       if (i == config->merge.end())
1199         break;
1200       toName = i->second;
1201     }
1202     OutputSection *from = findSection(p.first);
1203     OutputSection *to = findSection(toName);
1204     if (!from)
1205       continue;
1206     if (!to) {
1207       from->name = toName;
1208       continue;
1209     }
1210     to->merge(from);
1211   }
1212 }
1213 
1214 // Visits all sections to assign incremental, non-overlapping RVAs and
1215 // file offsets.
1216 void Writer::assignAddresses() {
1217   sizeOfHeaders = dosStubSize + sizeof(PEMagic) + sizeof(coff_file_header) +
1218                   sizeof(data_directory) * numberOfDataDirectory +
1219                   sizeof(coff_section) * outputSections.size();
1220   sizeOfHeaders +=
1221       config->is64() ? sizeof(pe32plus_header) : sizeof(pe32_header);
1222   sizeOfHeaders = alignTo(sizeOfHeaders, config->fileAlign);
1223   fileSize = sizeOfHeaders;
1224 
1225   // The first page is kept unmapped.
1226   uint64_t rva = alignTo(sizeOfHeaders, config->align);
1227 
1228   for (OutputSection *sec : outputSections) {
1229     if (sec == relocSec)
1230       addBaserels();
1231     uint64_t rawSize = 0, virtualSize = 0;
1232     sec->header.VirtualAddress = rva;
1233 
1234     // If /FUNCTIONPADMIN is used, functions are padded in order to create a
1235     // hotpatchable image.
1236     const bool isCodeSection =
1237         (sec->header.Characteristics & IMAGE_SCN_CNT_CODE) &&
1238         (sec->header.Characteristics & IMAGE_SCN_MEM_READ) &&
1239         (sec->header.Characteristics & IMAGE_SCN_MEM_EXECUTE);
1240     uint32_t padding = isCodeSection ? config->functionPadMin : 0;
1241 
1242     for (Chunk *c : sec->chunks) {
1243       if (padding && c->isHotPatchable())
1244         virtualSize += padding;
1245       virtualSize = alignTo(virtualSize, c->getAlignment());
1246       c->setRVA(rva + virtualSize);
1247       virtualSize += c->getSize();
1248       if (c->hasData)
1249         rawSize = alignTo(virtualSize, config->fileAlign);
1250     }
1251     if (virtualSize > UINT32_MAX)
1252       error("section larger than 4 GiB: " + sec->name);
1253     sec->header.VirtualSize = virtualSize;
1254     sec->header.SizeOfRawData = rawSize;
1255     if (rawSize != 0)
1256       sec->header.PointerToRawData = fileSize;
1257     rva += alignTo(virtualSize, config->align);
1258     fileSize += alignTo(rawSize, config->fileAlign);
1259   }
1260   sizeOfImage = alignTo(rva, config->align);
1261 
1262   // Assign addresses to sections in MergeChunks.
1263   for (MergeChunk *mc : MergeChunk::instances)
1264     if (mc)
1265       mc->assignSubsectionRVAs();
1266 }
1267 
1268 template <typename PEHeaderTy> void Writer::writeHeader() {
1269   // Write DOS header. For backwards compatibility, the first part of a PE/COFF
1270   // executable consists of an MS-DOS MZ executable. If the executable is run
1271   // under DOS, that program gets run (usually to just print an error message).
1272   // When run under Windows, the loader looks at AddressOfNewExeHeader and uses
1273   // the PE header instead.
1274   uint8_t *buf = buffer->getBufferStart();
1275   auto *dos = reinterpret_cast<dos_header *>(buf);
1276   buf += sizeof(dos_header);
1277   dos->Magic[0] = 'M';
1278   dos->Magic[1] = 'Z';
1279   dos->UsedBytesInTheLastPage = dosStubSize % 512;
1280   dos->FileSizeInPages = divideCeil(dosStubSize, 512);
1281   dos->HeaderSizeInParagraphs = sizeof(dos_header) / 16;
1282 
1283   dos->AddressOfRelocationTable = sizeof(dos_header);
1284   dos->AddressOfNewExeHeader = dosStubSize;
1285 
1286   // Write DOS program.
1287   memcpy(buf, dosProgram, sizeof(dosProgram));
1288   buf += sizeof(dosProgram);
1289 
1290   // Write PE magic
1291   memcpy(buf, PEMagic, sizeof(PEMagic));
1292   buf += sizeof(PEMagic);
1293 
1294   // Write COFF header
1295   auto *coff = reinterpret_cast<coff_file_header *>(buf);
1296   buf += sizeof(*coff);
1297   coff->Machine = config->machine;
1298   coff->NumberOfSections = outputSections.size();
1299   coff->Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE;
1300   if (config->largeAddressAware)
1301     coff->Characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
1302   if (!config->is64())
1303     coff->Characteristics |= IMAGE_FILE_32BIT_MACHINE;
1304   if (config->dll)
1305     coff->Characteristics |= IMAGE_FILE_DLL;
1306   if (!config->relocatable)
1307     coff->Characteristics |= IMAGE_FILE_RELOCS_STRIPPED;
1308   if (config->swaprunCD)
1309     coff->Characteristics |= IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP;
1310   if (config->swaprunNet)
1311     coff->Characteristics |= IMAGE_FILE_NET_RUN_FROM_SWAP;
1312   coff->SizeOfOptionalHeader =
1313       sizeof(PEHeaderTy) + sizeof(data_directory) * numberOfDataDirectory;
1314 
1315   // Write PE header
1316   auto *pe = reinterpret_cast<PEHeaderTy *>(buf);
1317   buf += sizeof(*pe);
1318   pe->Magic = config->is64() ? PE32Header::PE32_PLUS : PE32Header::PE32;
1319 
1320   // If {Major,Minor}LinkerVersion is left at 0.0, then for some
1321   // reason signing the resulting PE file with Authenticode produces a
1322   // signature that fails to validate on Windows 7 (but is OK on 10).
1323   // Set it to 14.0, which is what VS2015 outputs, and which avoids
1324   // that problem.
1325   pe->MajorLinkerVersion = 14;
1326   pe->MinorLinkerVersion = 0;
1327 
1328   pe->ImageBase = config->imageBase;
1329   pe->SectionAlignment = config->align;
1330   pe->FileAlignment = config->fileAlign;
1331   pe->MajorImageVersion = config->majorImageVersion;
1332   pe->MinorImageVersion = config->minorImageVersion;
1333   pe->MajorOperatingSystemVersion = config->majorOSVersion;
1334   pe->MinorOperatingSystemVersion = config->minorOSVersion;
1335   pe->MajorSubsystemVersion = config->majorOSVersion;
1336   pe->MinorSubsystemVersion = config->minorOSVersion;
1337   pe->Subsystem = config->subsystem;
1338   pe->SizeOfImage = sizeOfImage;
1339   pe->SizeOfHeaders = sizeOfHeaders;
1340   if (!config->noEntry) {
1341     Defined *entry = cast<Defined>(config->entry);
1342     pe->AddressOfEntryPoint = entry->getRVA();
1343     // Pointer to thumb code must have the LSB set, so adjust it.
1344     if (config->machine == ARMNT)
1345       pe->AddressOfEntryPoint |= 1;
1346   }
1347   pe->SizeOfStackReserve = config->stackReserve;
1348   pe->SizeOfStackCommit = config->stackCommit;
1349   pe->SizeOfHeapReserve = config->heapReserve;
1350   pe->SizeOfHeapCommit = config->heapCommit;
1351   if (config->appContainer)
1352     pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_APPCONTAINER;
1353   if (config->dynamicBase)
1354     pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
1355   if (config->highEntropyVA)
1356     pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA;
1357   if (!config->allowBind)
1358     pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_BIND;
1359   if (config->nxCompat)
1360     pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
1361   if (!config->allowIsolation)
1362     pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION;
1363   if (config->guardCF != GuardCFLevel::Off)
1364     pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_GUARD_CF;
1365   if (config->integrityCheck)
1366     pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY;
1367   if (setNoSEHCharacteristic)
1368     pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_SEH;
1369   if (config->terminalServerAware)
1370     pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE;
1371   pe->NumberOfRvaAndSize = numberOfDataDirectory;
1372   if (textSec->getVirtualSize()) {
1373     pe->BaseOfCode = textSec->getRVA();
1374     pe->SizeOfCode = textSec->getRawSize();
1375   }
1376   pe->SizeOfInitializedData = getSizeOfInitializedData();
1377 
1378   // Write data directory
1379   auto *dir = reinterpret_cast<data_directory *>(buf);
1380   buf += sizeof(*dir) * numberOfDataDirectory;
1381   if (edataStart) {
1382     dir[EXPORT_TABLE].RelativeVirtualAddress = edataStart->getRVA();
1383     dir[EXPORT_TABLE].Size =
1384         edataEnd->getRVA() + edataEnd->getSize() - edataStart->getRVA();
1385   }
1386   if (importTableStart) {
1387     dir[IMPORT_TABLE].RelativeVirtualAddress = importTableStart->getRVA();
1388     dir[IMPORT_TABLE].Size = importTableSize;
1389   }
1390   if (iatStart) {
1391     dir[IAT].RelativeVirtualAddress = iatStart->getRVA();
1392     dir[IAT].Size = iatSize;
1393   }
1394   if (rsrcSec->getVirtualSize()) {
1395     dir[RESOURCE_TABLE].RelativeVirtualAddress = rsrcSec->getRVA();
1396     dir[RESOURCE_TABLE].Size = rsrcSec->getVirtualSize();
1397   }
1398   if (firstPdata) {
1399     dir[EXCEPTION_TABLE].RelativeVirtualAddress = firstPdata->getRVA();
1400     dir[EXCEPTION_TABLE].Size =
1401         lastPdata->getRVA() + lastPdata->getSize() - firstPdata->getRVA();
1402   }
1403   if (relocSec->getVirtualSize()) {
1404     dir[BASE_RELOCATION_TABLE].RelativeVirtualAddress = relocSec->getRVA();
1405     dir[BASE_RELOCATION_TABLE].Size = relocSec->getVirtualSize();
1406   }
1407   if (Symbol *sym = symtab->findUnderscore("_tls_used")) {
1408     if (Defined *b = dyn_cast<Defined>(sym)) {
1409       dir[TLS_TABLE].RelativeVirtualAddress = b->getRVA();
1410       dir[TLS_TABLE].Size = config->is64()
1411                                 ? sizeof(object::coff_tls_directory64)
1412                                 : sizeof(object::coff_tls_directory32);
1413     }
1414   }
1415   if (debugDirectory) {
1416     dir[DEBUG_DIRECTORY].RelativeVirtualAddress = debugDirectory->getRVA();
1417     dir[DEBUG_DIRECTORY].Size = debugDirectory->getSize();
1418   }
1419   if (Symbol *sym = symtab->findUnderscore("_load_config_used")) {
1420     if (auto *b = dyn_cast<DefinedRegular>(sym)) {
1421       SectionChunk *sc = b->getChunk();
1422       assert(b->getRVA() >= sc->getRVA());
1423       uint64_t offsetInChunk = b->getRVA() - sc->getRVA();
1424       if (!sc->hasData || offsetInChunk + 4 > sc->getSize())
1425         fatal("_load_config_used is malformed");
1426 
1427       ArrayRef<uint8_t> secContents = sc->getContents();
1428       uint32_t loadConfigSize =
1429           *reinterpret_cast<const ulittle32_t *>(&secContents[offsetInChunk]);
1430       if (offsetInChunk + loadConfigSize > sc->getSize())
1431         fatal("_load_config_used is too large");
1432       dir[LOAD_CONFIG_TABLE].RelativeVirtualAddress = b->getRVA();
1433       dir[LOAD_CONFIG_TABLE].Size = loadConfigSize;
1434     }
1435   }
1436   if (!delayIdata.empty()) {
1437     dir[DELAY_IMPORT_DESCRIPTOR].RelativeVirtualAddress =
1438         delayIdata.getDirRVA();
1439     dir[DELAY_IMPORT_DESCRIPTOR].Size = delayIdata.getDirSize();
1440   }
1441 
1442   // Write section table
1443   for (OutputSection *sec : outputSections) {
1444     sec->writeHeaderTo(buf);
1445     buf += sizeof(coff_section);
1446   }
1447   sectionTable = ArrayRef<uint8_t>(
1448       buf - outputSections.size() * sizeof(coff_section), buf);
1449 
1450   if (outputSymtab.empty() && strtab.empty())
1451     return;
1452 
1453   coff->PointerToSymbolTable = pointerToSymbolTable;
1454   uint32_t numberOfSymbols = outputSymtab.size();
1455   coff->NumberOfSymbols = numberOfSymbols;
1456   auto *symbolTable = reinterpret_cast<coff_symbol16 *>(
1457       buffer->getBufferStart() + coff->PointerToSymbolTable);
1458   for (size_t i = 0; i != numberOfSymbols; ++i)
1459     symbolTable[i] = outputSymtab[i];
1460   // Create the string table, it follows immediately after the symbol table.
1461   // The first 4 bytes is length including itself.
1462   buf = reinterpret_cast<uint8_t *>(&symbolTable[numberOfSymbols]);
1463   write32le(buf, strtab.size() + 4);
1464   if (!strtab.empty())
1465     memcpy(buf + 4, strtab.data(), strtab.size());
1466 }
1467 
1468 void Writer::openFile(StringRef path) {
1469   buffer = CHECK(
1470       FileOutputBuffer::create(path, fileSize, FileOutputBuffer::F_executable),
1471       "failed to open " + path);
1472 }
1473 
1474 void Writer::createSEHTable() {
1475   SymbolRVASet handlers;
1476   for (ObjFile *file : ObjFile::instances) {
1477     if (!file->hasSafeSEH())
1478       error("/safeseh: " + file->getName() + " is not compatible with SEH");
1479     markSymbolsForRVATable(file, file->getSXDataChunks(), handlers);
1480   }
1481 
1482   // Set the "no SEH" characteristic if there really were no handlers, or if
1483   // there is no load config object to point to the table of handlers.
1484   setNoSEHCharacteristic =
1485       handlers.empty() || !symtab->findUnderscore("_load_config_used");
1486 
1487   maybeAddRVATable(std::move(handlers), "__safe_se_handler_table",
1488                    "__safe_se_handler_count");
1489 }
1490 
1491 // Add a symbol to an RVA set. Two symbols may have the same RVA, but an RVA set
1492 // cannot contain duplicates. Therefore, the set is uniqued by Chunk and the
1493 // symbol's offset into that Chunk.
1494 static void addSymbolToRVASet(SymbolRVASet &rvaSet, Defined *s) {
1495   Chunk *c = s->getChunk();
1496   if (auto *sc = dyn_cast<SectionChunk>(c))
1497     c = sc->repl; // Look through ICF replacement.
1498   uint32_t off = s->getRVA() - (c ? c->getRVA() : 0);
1499   rvaSet.insert({c, off});
1500 }
1501 
1502 // Given a symbol, add it to the GFIDs table if it is a live, defined, function
1503 // symbol in an executable section.
1504 static void maybeAddAddressTakenFunction(SymbolRVASet &addressTakenSyms,
1505                                          Symbol *s) {
1506   if (!s)
1507     return;
1508 
1509   switch (s->kind()) {
1510   case Symbol::DefinedLocalImportKind:
1511   case Symbol::DefinedImportDataKind:
1512     // Defines an __imp_ pointer, so it is data, so it is ignored.
1513     break;
1514   case Symbol::DefinedCommonKind:
1515     // Common is always data, so it is ignored.
1516     break;
1517   case Symbol::DefinedAbsoluteKind:
1518   case Symbol::DefinedSyntheticKind:
1519     // Absolute is never code, synthetic generally isn't and usually isn't
1520     // determinable.
1521     break;
1522   case Symbol::LazyArchiveKind:
1523   case Symbol::LazyObjectKind:
1524   case Symbol::UndefinedKind:
1525     // Undefined symbols resolve to zero, so they don't have an RVA. Lazy
1526     // symbols shouldn't have relocations.
1527     break;
1528 
1529   case Symbol::DefinedImportThunkKind:
1530     // Thunks are always code, include them.
1531     addSymbolToRVASet(addressTakenSyms, cast<Defined>(s));
1532     break;
1533 
1534   case Symbol::DefinedRegularKind: {
1535     // This is a regular, defined, symbol from a COFF file. Mark the symbol as
1536     // address taken if the symbol type is function and it's in an executable
1537     // section.
1538     auto *d = cast<DefinedRegular>(s);
1539     if (d->getCOFFSymbol().getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION) {
1540       SectionChunk *sc = dyn_cast<SectionChunk>(d->getChunk());
1541       if (sc && sc->live &&
1542           sc->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE)
1543         addSymbolToRVASet(addressTakenSyms, d);
1544     }
1545     break;
1546   }
1547   }
1548 }
1549 
1550 // Visit all relocations from all section contributions of this object file and
1551 // mark the relocation target as address-taken.
1552 static void markSymbolsWithRelocations(ObjFile *file,
1553                                        SymbolRVASet &usedSymbols) {
1554   for (Chunk *c : file->getChunks()) {
1555     // We only care about live section chunks. Common chunks and other chunks
1556     // don't generally contain relocations.
1557     SectionChunk *sc = dyn_cast<SectionChunk>(c);
1558     if (!sc || !sc->live)
1559       continue;
1560 
1561     for (const coff_relocation &reloc : sc->getRelocs()) {
1562       if (config->machine == I386 && reloc.Type == COFF::IMAGE_REL_I386_REL32)
1563         // Ignore relative relocations on x86. On x86_64 they can't be ignored
1564         // since they're also used to compute absolute addresses.
1565         continue;
1566 
1567       Symbol *ref = sc->file->getSymbol(reloc.SymbolTableIndex);
1568       maybeAddAddressTakenFunction(usedSymbols, ref);
1569     }
1570   }
1571 }
1572 
1573 // Create the guard function id table. This is a table of RVAs of all
1574 // address-taken functions. It is sorted and uniqued, just like the safe SEH
1575 // table.
1576 void Writer::createGuardCFTables() {
1577   SymbolRVASet addressTakenSyms;
1578   SymbolRVASet longJmpTargets;
1579   for (ObjFile *file : ObjFile::instances) {
1580     // If the object was compiled with /guard:cf, the address taken symbols
1581     // are in .gfids$y sections, and the longjmp targets are in .gljmp$y
1582     // sections. If the object was not compiled with /guard:cf, we assume there
1583     // were no setjmp targets, and that all code symbols with relocations are
1584     // possibly address-taken.
1585     if (file->hasGuardCF()) {
1586       markSymbolsForRVATable(file, file->getGuardFidChunks(), addressTakenSyms);
1587       markSymbolsForRVATable(file, file->getGuardLJmpChunks(), longJmpTargets);
1588     } else {
1589       markSymbolsWithRelocations(file, addressTakenSyms);
1590     }
1591   }
1592 
1593   // Mark the image entry as address-taken.
1594   if (config->entry)
1595     maybeAddAddressTakenFunction(addressTakenSyms, config->entry);
1596 
1597   // Mark exported symbols in executable sections as address-taken.
1598   for (Export &e : config->exports)
1599     maybeAddAddressTakenFunction(addressTakenSyms, e.sym);
1600 
1601   // Ensure sections referenced in the gfid table are 16-byte aligned.
1602   for (const ChunkAndOffset &c : addressTakenSyms)
1603     if (c.inputChunk->getAlignment() < 16)
1604       c.inputChunk->setAlignment(16);
1605 
1606   maybeAddRVATable(std::move(addressTakenSyms), "__guard_fids_table",
1607                    "__guard_fids_count");
1608 
1609   // Add the longjmp target table unless the user told us not to.
1610   if (config->guardCF == GuardCFLevel::Full)
1611     maybeAddRVATable(std::move(longJmpTargets), "__guard_longjmp_table",
1612                      "__guard_longjmp_count");
1613 
1614   // Set __guard_flags, which will be used in the load config to indicate that
1615   // /guard:cf was enabled.
1616   uint32_t guardFlags = uint32_t(coff_guard_flags::CFInstrumented) |
1617                         uint32_t(coff_guard_flags::HasFidTable);
1618   if (config->guardCF == GuardCFLevel::Full)
1619     guardFlags |= uint32_t(coff_guard_flags::HasLongJmpTable);
1620   Symbol *flagSym = symtab->findUnderscore("__guard_flags");
1621   cast<DefinedAbsolute>(flagSym)->setVA(guardFlags);
1622 }
1623 
1624 // Take a list of input sections containing symbol table indices and add those
1625 // symbols to an RVA table. The challenge is that symbol RVAs are not known and
1626 // depend on the table size, so we can't directly build a set of integers.
1627 void Writer::markSymbolsForRVATable(ObjFile *file,
1628                                     ArrayRef<SectionChunk *> symIdxChunks,
1629                                     SymbolRVASet &tableSymbols) {
1630   for (SectionChunk *c : symIdxChunks) {
1631     // Skip sections discarded by linker GC. This comes up when a .gfids section
1632     // is associated with something like a vtable and the vtable is discarded.
1633     // In this case, the associated gfids section is discarded, and we don't
1634     // mark the virtual member functions as address-taken by the vtable.
1635     if (!c->live)
1636       continue;
1637 
1638     // Validate that the contents look like symbol table indices.
1639     ArrayRef<uint8_t> data = c->getContents();
1640     if (data.size() % 4 != 0) {
1641       warn("ignoring " + c->getSectionName() +
1642            " symbol table index section in object " + toString(file));
1643       continue;
1644     }
1645 
1646     // Read each symbol table index and check if that symbol was included in the
1647     // final link. If so, add it to the table symbol set.
1648     ArrayRef<ulittle32_t> symIndices(
1649         reinterpret_cast<const ulittle32_t *>(data.data()), data.size() / 4);
1650     ArrayRef<Symbol *> objSymbols = file->getSymbols();
1651     for (uint32_t symIndex : symIndices) {
1652       if (symIndex >= objSymbols.size()) {
1653         warn("ignoring invalid symbol table index in section " +
1654              c->getSectionName() + " in object " + toString(file));
1655         continue;
1656       }
1657       if (Symbol *s = objSymbols[symIndex]) {
1658         if (s->isLive())
1659           addSymbolToRVASet(tableSymbols, cast<Defined>(s));
1660       }
1661     }
1662   }
1663 }
1664 
1665 // Replace the absolute table symbol with a synthetic symbol pointing to
1666 // tableChunk so that we can emit base relocations for it and resolve section
1667 // relative relocations.
1668 void Writer::maybeAddRVATable(SymbolRVASet tableSymbols, StringRef tableSym,
1669                               StringRef countSym) {
1670   if (tableSymbols.empty())
1671     return;
1672 
1673   RVATableChunk *tableChunk = make<RVATableChunk>(std::move(tableSymbols));
1674   rdataSec->addChunk(tableChunk);
1675 
1676   Symbol *t = symtab->findUnderscore(tableSym);
1677   Symbol *c = symtab->findUnderscore(countSym);
1678   replaceSymbol<DefinedSynthetic>(t, t->getName(), tableChunk);
1679   cast<DefinedAbsolute>(c)->setVA(tableChunk->getSize() / 4);
1680 }
1681 
1682 // MinGW specific. Gather all relocations that are imported from a DLL even
1683 // though the code didn't expect it to, produce the table that the runtime
1684 // uses for fixing them up, and provide the synthetic symbols that the
1685 // runtime uses for finding the table.
1686 void Writer::createRuntimePseudoRelocs() {
1687   std::vector<RuntimePseudoReloc> rels;
1688 
1689   for (Chunk *c : symtab->getChunks()) {
1690     auto *sc = dyn_cast<SectionChunk>(c);
1691     if (!sc || !sc->live)
1692       continue;
1693     sc->getRuntimePseudoRelocs(rels);
1694   }
1695 
1696   if (!rels.empty())
1697     log("Writing " + Twine(rels.size()) + " runtime pseudo relocations");
1698   PseudoRelocTableChunk *table = make<PseudoRelocTableChunk>(rels);
1699   rdataSec->addChunk(table);
1700   EmptyChunk *endOfList = make<EmptyChunk>();
1701   rdataSec->addChunk(endOfList);
1702 
1703   Symbol *headSym = symtab->findUnderscore("__RUNTIME_PSEUDO_RELOC_LIST__");
1704   Symbol *endSym = symtab->findUnderscore("__RUNTIME_PSEUDO_RELOC_LIST_END__");
1705   replaceSymbol<DefinedSynthetic>(headSym, headSym->getName(), table);
1706   replaceSymbol<DefinedSynthetic>(endSym, endSym->getName(), endOfList);
1707 }
1708 
1709 // MinGW specific.
1710 // The MinGW .ctors and .dtors lists have sentinels at each end;
1711 // a (uintptr_t)-1 at the start and a (uintptr_t)0 at the end.
1712 // There's a symbol pointing to the start sentinel pointer, __CTOR_LIST__
1713 // and __DTOR_LIST__ respectively.
1714 void Writer::insertCtorDtorSymbols() {
1715   AbsolutePointerChunk *ctorListHead = make<AbsolutePointerChunk>(-1);
1716   AbsolutePointerChunk *ctorListEnd = make<AbsolutePointerChunk>(0);
1717   AbsolutePointerChunk *dtorListHead = make<AbsolutePointerChunk>(-1);
1718   AbsolutePointerChunk *dtorListEnd = make<AbsolutePointerChunk>(0);
1719   ctorsSec->insertChunkAtStart(ctorListHead);
1720   ctorsSec->addChunk(ctorListEnd);
1721   dtorsSec->insertChunkAtStart(dtorListHead);
1722   dtorsSec->addChunk(dtorListEnd);
1723 
1724   Symbol *ctorListSym = symtab->findUnderscore("__CTOR_LIST__");
1725   Symbol *dtorListSym = symtab->findUnderscore("__DTOR_LIST__");
1726   replaceSymbol<DefinedSynthetic>(ctorListSym, ctorListSym->getName(),
1727                                   ctorListHead);
1728   replaceSymbol<DefinedSynthetic>(dtorListSym, dtorListSym->getName(),
1729                                   dtorListHead);
1730 }
1731 
1732 // Handles /section options to allow users to overwrite
1733 // section attributes.
1734 void Writer::setSectionPermissions() {
1735   for (auto &p : config->section) {
1736     StringRef name = p.first;
1737     uint32_t perm = p.second;
1738     for (OutputSection *sec : outputSections)
1739       if (sec->name == name)
1740         sec->setPermissions(perm);
1741   }
1742 }
1743 
1744 // Write section contents to a mmap'ed file.
1745 void Writer::writeSections() {
1746   // Record the number of sections to apply section index relocations
1747   // against absolute symbols. See applySecIdx in Chunks.cpp..
1748   DefinedAbsolute::numOutputSections = outputSections.size();
1749 
1750   uint8_t *buf = buffer->getBufferStart();
1751   for (OutputSection *sec : outputSections) {
1752     uint8_t *secBuf = buf + sec->getFileOff();
1753     // Fill gaps between functions in .text with INT3 instructions
1754     // instead of leaving as NUL bytes (which can be interpreted as
1755     // ADD instructions).
1756     if (sec->header.Characteristics & IMAGE_SCN_CNT_CODE)
1757       memset(secBuf, 0xCC, sec->getRawSize());
1758     parallelForEach(sec->chunks, [&](Chunk *c) {
1759       c->writeTo(secBuf + c->getRVA() - sec->getRVA());
1760     });
1761   }
1762 }
1763 
1764 void Writer::writeBuildId() {
1765   // There are two important parts to the build ID.
1766   // 1) If building with debug info, the COFF debug directory contains a
1767   //    timestamp as well as a Guid and Age of the PDB.
1768   // 2) In all cases, the PE COFF file header also contains a timestamp.
1769   // For reproducibility, instead of a timestamp we want to use a hash of the
1770   // PE contents.
1771   if (config->debug) {
1772     assert(buildId && "BuildId is not set!");
1773     // BuildId->BuildId was filled in when the PDB was written.
1774   }
1775 
1776   // At this point the only fields in the COFF file which remain unset are the
1777   // "timestamp" in the COFF file header, and the ones in the coff debug
1778   // directory.  Now we can hash the file and write that hash to the various
1779   // timestamp fields in the file.
1780   StringRef outputFileData(
1781       reinterpret_cast<const char *>(buffer->getBufferStart()),
1782       buffer->getBufferSize());
1783 
1784   uint32_t timestamp = config->timestamp;
1785   uint64_t hash = 0;
1786   bool generateSyntheticBuildId =
1787       config->mingw && config->debug && config->pdbPath.empty();
1788 
1789   if (config->repro || generateSyntheticBuildId)
1790     hash = xxHash64(outputFileData);
1791 
1792   if (config->repro)
1793     timestamp = static_cast<uint32_t>(hash);
1794 
1795   if (generateSyntheticBuildId) {
1796     // For MinGW builds without a PDB file, we still generate a build id
1797     // to allow associating a crash dump to the executable.
1798     buildId->buildId->PDB70.CVSignature = OMF::Signature::PDB70;
1799     buildId->buildId->PDB70.Age = 1;
1800     memcpy(buildId->buildId->PDB70.Signature, &hash, 8);
1801     // xxhash only gives us 8 bytes, so put some fixed data in the other half.
1802     memcpy(&buildId->buildId->PDB70.Signature[8], "LLD PDB.", 8);
1803   }
1804 
1805   if (debugDirectory)
1806     debugDirectory->setTimeDateStamp(timestamp);
1807 
1808   uint8_t *buf = buffer->getBufferStart();
1809   buf += dosStubSize + sizeof(PEMagic);
1810   object::coff_file_header *coffHeader =
1811       reinterpret_cast<coff_file_header *>(buf);
1812   coffHeader->TimeDateStamp = timestamp;
1813 }
1814 
1815 // Sort .pdata section contents according to PE/COFF spec 5.5.
1816 void Writer::sortExceptionTable() {
1817   if (!firstPdata)
1818     return;
1819   // We assume .pdata contains function table entries only.
1820   auto bufAddr = [&](Chunk *c) {
1821     OutputSection *os = c->getOutputSection();
1822     return buffer->getBufferStart() + os->getFileOff() + c->getRVA() -
1823            os->getRVA();
1824   };
1825   uint8_t *begin = bufAddr(firstPdata);
1826   uint8_t *end = bufAddr(lastPdata) + lastPdata->getSize();
1827   if (config->machine == AMD64) {
1828     struct Entry { ulittle32_t begin, end, unwind; };
1829     parallelSort(
1830         MutableArrayRef<Entry>((Entry *)begin, (Entry *)end),
1831         [](const Entry &a, const Entry &b) { return a.begin < b.begin; });
1832     return;
1833   }
1834   if (config->machine == ARMNT || config->machine == ARM64) {
1835     struct Entry { ulittle32_t begin, unwind; };
1836     parallelSort(
1837         MutableArrayRef<Entry>((Entry *)begin, (Entry *)end),
1838         [](const Entry &a, const Entry &b) { return a.begin < b.begin; });
1839     return;
1840   }
1841   errs() << "warning: don't know how to handle .pdata.\n";
1842 }
1843 
1844 // The CRT section contains, among other things, the array of function
1845 // pointers that initialize every global variable that is not trivially
1846 // constructed. The CRT calls them one after the other prior to invoking
1847 // main().
1848 //
1849 // As per C++ spec, 3.6.2/2.3,
1850 // "Variables with ordered initialization defined within a single
1851 // translation unit shall be initialized in the order of their definitions
1852 // in the translation unit"
1853 //
1854 // It is therefore critical to sort the chunks containing the function
1855 // pointers in the order that they are listed in the object file (top to
1856 // bottom), otherwise global objects might not be initialized in the
1857 // correct order.
1858 void Writer::sortCRTSectionChunks(std::vector<Chunk *> &chunks) {
1859   auto sectionChunkOrder = [](const Chunk *a, const Chunk *b) {
1860     auto sa = dyn_cast<SectionChunk>(a);
1861     auto sb = dyn_cast<SectionChunk>(b);
1862     assert(sa && sb && "Non-section chunks in CRT section!");
1863 
1864     StringRef sAObj = sa->file->mb.getBufferIdentifier();
1865     StringRef sBObj = sb->file->mb.getBufferIdentifier();
1866 
1867     return sAObj == sBObj && sa->getSectionNumber() < sb->getSectionNumber();
1868   };
1869   llvm::stable_sort(chunks, sectionChunkOrder);
1870 
1871   if (config->verbose) {
1872     for (auto &c : chunks) {
1873       auto sc = dyn_cast<SectionChunk>(c);
1874       log("  " + sc->file->mb.getBufferIdentifier().str() +
1875           ", SectionID: " + Twine(sc->getSectionNumber()));
1876     }
1877   }
1878 }
1879 
1880 OutputSection *Writer::findSection(StringRef name) {
1881   for (OutputSection *sec : outputSections)
1882     if (sec->name == name)
1883       return sec;
1884   return nullptr;
1885 }
1886 
1887 uint32_t Writer::getSizeOfInitializedData() {
1888   uint32_t res = 0;
1889   for (OutputSection *s : outputSections)
1890     if (s->header.Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)
1891       res += s->getRawSize();
1892   return res;
1893 }
1894 
1895 // Add base relocations to .reloc section.
1896 void Writer::addBaserels() {
1897   if (!config->relocatable)
1898     return;
1899   relocSec->chunks.clear();
1900   std::vector<Baserel> v;
1901   for (OutputSection *sec : outputSections) {
1902     if (sec->header.Characteristics & IMAGE_SCN_MEM_DISCARDABLE)
1903       continue;
1904     // Collect all locations for base relocations.
1905     for (Chunk *c : sec->chunks)
1906       c->getBaserels(&v);
1907     // Add the addresses to .reloc section.
1908     if (!v.empty())
1909       addBaserelBlocks(v);
1910     v.clear();
1911   }
1912 }
1913 
1914 // Add addresses to .reloc section. Note that addresses are grouped by page.
1915 void Writer::addBaserelBlocks(std::vector<Baserel> &v) {
1916   const uint32_t mask = ~uint32_t(pageSize - 1);
1917   uint32_t page = v[0].rva & mask;
1918   size_t i = 0, j = 1;
1919   for (size_t e = v.size(); j < e; ++j) {
1920     uint32_t p = v[j].rva & mask;
1921     if (p == page)
1922       continue;
1923     relocSec->addChunk(make<BaserelChunk>(page, &v[i], &v[0] + j));
1924     i = j;
1925     page = p;
1926   }
1927   if (i == j)
1928     return;
1929   relocSec->addChunk(make<BaserelChunk>(page, &v[i], &v[0] + j));
1930 }
1931 
1932 PartialSection *Writer::createPartialSection(StringRef name,
1933                                              uint32_t outChars) {
1934   PartialSection *&pSec = partialSections[{name, outChars}];
1935   if (pSec)
1936     return pSec;
1937   pSec = make<PartialSection>(name, outChars);
1938   return pSec;
1939 }
1940 
1941 PartialSection *Writer::findPartialSection(StringRef name, uint32_t outChars) {
1942   auto it = partialSections.find({name, outChars});
1943   if (it != partialSections.end())
1944     return it->second;
1945   return nullptr;
1946 }
1947