xref: /llvm-project-15.0.7/lld/COFF/Writer.cpp (revision a2e270fa)
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   ScopedTimer t2(diskCommitTimer);
632   if (auto e = buffer->commit())
633     fatal("failed to write the output file: " + toString(std::move(e)));
634 }
635 
636 static StringRef getOutputSectionName(StringRef name) {
637   StringRef s = name.split('$').first;
638 
639   // Treat a later period as a separator for MinGW, for sections like
640   // ".ctors.01234".
641   return s.substr(0, s.find('.', 1));
642 }
643 
644 // For /order.
645 static void sortBySectionOrder(std::vector<Chunk *> &chunks) {
646   auto getPriority = [](const Chunk *c) {
647     if (auto *sec = dyn_cast<SectionChunk>(c))
648       if (sec->sym)
649         return config->order.lookup(sec->sym->getName());
650     return 0;
651   };
652 
653   llvm::stable_sort(chunks, [=](const Chunk *a, const Chunk *b) {
654     return getPriority(a) < getPriority(b);
655   });
656 }
657 
658 // Change the characteristics of existing PartialSections that belong to the
659 // section Name to Chars.
660 void Writer::fixPartialSectionChars(StringRef name, uint32_t chars) {
661   for (auto it : partialSections) {
662     PartialSection *pSec = it.second;
663     StringRef curName = pSec->name;
664     if (!curName.consume_front(name) ||
665         (!curName.empty() && !curName.startswith("$")))
666       continue;
667     if (pSec->characteristics == chars)
668       continue;
669     PartialSection *destSec = createPartialSection(pSec->name, chars);
670     destSec->chunks.insert(destSec->chunks.end(), pSec->chunks.begin(),
671                            pSec->chunks.end());
672     pSec->chunks.clear();
673   }
674 }
675 
676 // Sort concrete section chunks from GNU import libraries.
677 //
678 // GNU binutils doesn't use short import files, but instead produces import
679 // libraries that consist of object files, with section chunks for the .idata$*
680 // sections. These are linked just as regular static libraries. Each import
681 // library consists of one header object, one object file for every imported
682 // symbol, and one trailer object. In order for the .idata tables/lists to
683 // be formed correctly, the section chunks within each .idata$* section need
684 // to be grouped by library, and sorted alphabetically within each library
685 // (which makes sure the header comes first and the trailer last).
686 bool Writer::fixGnuImportChunks() {
687   uint32_t rdata = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ;
688 
689   // Make sure all .idata$* section chunks are mapped as RDATA in order to
690   // be sorted into the same sections as our own synthesized .idata chunks.
691   fixPartialSectionChars(".idata", rdata);
692 
693   bool hasIdata = false;
694   // Sort all .idata$* chunks, grouping chunks from the same library,
695   // with alphabetical ordering of the object fils within a library.
696   for (auto it : partialSections) {
697     PartialSection *pSec = it.second;
698     if (!pSec->name.startswith(".idata"))
699       continue;
700 
701     if (!pSec->chunks.empty())
702       hasIdata = true;
703     llvm::stable_sort(pSec->chunks, [&](Chunk *s, Chunk *t) {
704       SectionChunk *sc1 = dyn_cast_or_null<SectionChunk>(s);
705       SectionChunk *sc2 = dyn_cast_or_null<SectionChunk>(t);
706       if (!sc1 || !sc2) {
707         // if SC1, order them ascending. If SC2 or both null,
708         // S is not less than T.
709         return sc1 != nullptr;
710       }
711       // Make a string with "libraryname/objectfile" for sorting, achieving
712       // both grouping by library and sorting of objects within a library,
713       // at once.
714       std::string key1 =
715           (sc1->file->parentName + "/" + sc1->file->getName()).str();
716       std::string key2 =
717           (sc2->file->parentName + "/" + sc2->file->getName()).str();
718       return key1 < key2;
719     });
720   }
721   return hasIdata;
722 }
723 
724 // Add generated idata chunks, for imported symbols and DLLs, and a
725 // terminator in .idata$2.
726 void Writer::addSyntheticIdata() {
727   uint32_t rdata = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ;
728   idata.create();
729 
730   // Add the .idata content in the right section groups, to allow
731   // chunks from other linked in object files to be grouped together.
732   // See Microsoft PE/COFF spec 5.4 for details.
733   auto add = [&](StringRef n, std::vector<Chunk *> &v) {
734     PartialSection *pSec = createPartialSection(n, rdata);
735     pSec->chunks.insert(pSec->chunks.end(), v.begin(), v.end());
736   };
737 
738   // The loader assumes a specific order of data.
739   // Add each type in the correct order.
740   add(".idata$2", idata.dirs);
741   add(".idata$4", idata.lookups);
742   add(".idata$5", idata.addresses);
743   add(".idata$6", idata.hints);
744   add(".idata$7", idata.dllNames);
745 }
746 
747 // Locate the first Chunk and size of the import directory list and the
748 // IAT.
749 void Writer::locateImportTables() {
750   uint32_t rdata = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ;
751 
752   if (PartialSection *importDirs = findPartialSection(".idata$2", rdata)) {
753     if (!importDirs->chunks.empty())
754       importTableStart = importDirs->chunks.front();
755     for (Chunk *c : importDirs->chunks)
756       importTableSize += c->getSize();
757   }
758 
759   if (PartialSection *importAddresses = findPartialSection(".idata$5", rdata)) {
760     if (!importAddresses->chunks.empty())
761       iatStart = importAddresses->chunks.front();
762     for (Chunk *c : importAddresses->chunks)
763       iatSize += c->getSize();
764   }
765 }
766 
767 // Return whether a SectionChunk's suffix (the dollar and any trailing
768 // suffix) should be removed and sorted into the main suffixless
769 // PartialSection.
770 static bool shouldStripSectionSuffix(SectionChunk *sc, StringRef name) {
771   // On MinGW, comdat groups are formed by putting the comdat group name
772   // after the '$' in the section name. For .eh_frame$<symbol>, that must
773   // still be sorted before the .eh_frame trailer from crtend.o, thus just
774   // strip the section name trailer. For other sections, such as
775   // .tls$$<symbol> (where non-comdat .tls symbols are otherwise stored in
776   // ".tls$"), they must be strictly sorted after .tls. And for the
777   // hypothetical case of comdat .CRT$XCU, we definitely need to keep the
778   // suffix for sorting. Thus, to play it safe, only strip the suffix for
779   // the standard sections.
780   if (!config->mingw)
781     return false;
782   if (!sc || !sc->isCOMDAT())
783     return false;
784   return name.startswith(".text$") || name.startswith(".data$") ||
785          name.startswith(".rdata$") || name.startswith(".pdata$") ||
786          name.startswith(".xdata$") || name.startswith(".eh_frame$");
787 }
788 
789 // Create output section objects and add them to OutputSections.
790 void Writer::createSections() {
791   // First, create the builtin sections.
792   const uint32_t data = IMAGE_SCN_CNT_INITIALIZED_DATA;
793   const uint32_t bss = IMAGE_SCN_CNT_UNINITIALIZED_DATA;
794   const uint32_t code = IMAGE_SCN_CNT_CODE;
795   const uint32_t discardable = IMAGE_SCN_MEM_DISCARDABLE;
796   const uint32_t r = IMAGE_SCN_MEM_READ;
797   const uint32_t w = IMAGE_SCN_MEM_WRITE;
798   const uint32_t x = IMAGE_SCN_MEM_EXECUTE;
799 
800   SmallDenseMap<std::pair<StringRef, uint32_t>, OutputSection *> sections;
801   auto createSection = [&](StringRef name, uint32_t outChars) {
802     OutputSection *&sec = sections[{name, outChars}];
803     if (!sec) {
804       sec = make<OutputSection>(name, outChars);
805       outputSections.push_back(sec);
806     }
807     return sec;
808   };
809 
810   // Try to match the section order used by link.exe.
811   textSec = createSection(".text", code | r | x);
812   createSection(".bss", bss | r | w);
813   rdataSec = createSection(".rdata", data | r);
814   buildidSec = createSection(".buildid", data | r);
815   dataSec = createSection(".data", data | r | w);
816   pdataSec = createSection(".pdata", data | r);
817   idataSec = createSection(".idata", data | r);
818   edataSec = createSection(".edata", data | r);
819   didatSec = createSection(".didat", data | r);
820   rsrcSec = createSection(".rsrc", data | r);
821   relocSec = createSection(".reloc", data | discardable | r);
822   ctorsSec = createSection(".ctors", data | r | w);
823   dtorsSec = createSection(".dtors", data | r | w);
824 
825   // Then bin chunks by name and output characteristics.
826   for (Chunk *c : symtab->getChunks()) {
827     auto *sc = dyn_cast<SectionChunk>(c);
828     if (sc && !sc->live) {
829       if (config->verbose)
830         sc->printDiscardedMessage();
831       continue;
832     }
833     StringRef name = c->getSectionName();
834     if (shouldStripSectionSuffix(sc, name))
835       name = name.split('$').first;
836     PartialSection *pSec = createPartialSection(name,
837                                                 c->getOutputCharacteristics());
838     pSec->chunks.push_back(c);
839   }
840 
841   fixPartialSectionChars(".rsrc", data | r);
842   fixPartialSectionChars(".edata", data | r);
843   // Even in non MinGW cases, we might need to link against GNU import
844   // libraries.
845   bool hasIdata = fixGnuImportChunks();
846   if (!idata.empty())
847     hasIdata = true;
848 
849   if (hasIdata)
850     addSyntheticIdata();
851 
852   // Process an /order option.
853   if (!config->order.empty())
854     for (auto it : partialSections)
855       sortBySectionOrder(it.second->chunks);
856 
857   if (hasIdata)
858     locateImportTables();
859 
860   // Then create an OutputSection for each section.
861   // '$' and all following characters in input section names are
862   // discarded when determining output section. So, .text$foo
863   // contributes to .text, for example. See PE/COFF spec 3.2.
864   for (auto it : partialSections) {
865     PartialSection *pSec = it.second;
866     StringRef name = getOutputSectionName(pSec->name);
867     uint32_t outChars = pSec->characteristics;
868 
869     if (name == ".CRT") {
870       // In link.exe, there is a special case for the I386 target where .CRT
871       // sections are treated as if they have output characteristics DATA | R if
872       // their characteristics are DATA | R | W. This implements the same
873       // special case for all architectures.
874       outChars = data | r;
875 
876       log("Processing section " + pSec->name + " -> " + name);
877 
878       sortCRTSectionChunks(pSec->chunks);
879     }
880 
881     OutputSection *sec = createSection(name, outChars);
882     for (Chunk *c : pSec->chunks)
883       sec->addChunk(c);
884 
885     sec->addContributingPartialSection(pSec);
886   }
887 
888   // Finally, move some output sections to the end.
889   auto sectionOrder = [&](const OutputSection *s) {
890     // Move DISCARDABLE (or non-memory-mapped) sections to the end of file
891     // because the loader cannot handle holes. Stripping can remove other
892     // discardable ones than .reloc, which is first of them (created early).
893     if (s->header.Characteristics & IMAGE_SCN_MEM_DISCARDABLE)
894       return 2;
895     // .rsrc should come at the end of the non-discardable sections because its
896     // size may change by the Win32 UpdateResources() function, causing
897     // subsequent sections to move (see https://crbug.com/827082).
898     if (s == rsrcSec)
899       return 1;
900     return 0;
901   };
902   llvm::stable_sort(outputSections,
903                     [&](const OutputSection *s, const OutputSection *t) {
904                       return sectionOrder(s) < sectionOrder(t);
905                     });
906 }
907 
908 void Writer::createMiscChunks() {
909   for (MergeChunk *p : MergeChunk::instances) {
910     if (p) {
911       p->finalizeContents();
912       rdataSec->addChunk(p);
913     }
914   }
915 
916   // Create thunks for locally-dllimported symbols.
917   if (!symtab->localImportChunks.empty()) {
918     for (Chunk *c : symtab->localImportChunks)
919       rdataSec->addChunk(c);
920   }
921 
922   // Create Debug Information Chunks
923   OutputSection *debugInfoSec = config->mingw ? buildidSec : rdataSec;
924   if (config->debug || config->repro) {
925     debugDirectory = make<DebugDirectoryChunk>(debugRecords, config->repro);
926     debugInfoSec->addChunk(debugDirectory);
927   }
928 
929   if (config->debug) {
930     // Make a CVDebugRecordChunk even when /DEBUG:CV is not specified.  We
931     // output a PDB no matter what, and this chunk provides the only means of
932     // allowing a debugger to match a PDB and an executable.  So we need it even
933     // if we're ultimately not going to write CodeView data to the PDB.
934     buildId = make<CVDebugRecordChunk>();
935     debugRecords.push_back(buildId);
936 
937     for (Chunk *c : debugRecords)
938       debugInfoSec->addChunk(c);
939   }
940 
941   // Create SEH table. x86-only.
942   if (config->safeSEH)
943     createSEHTable();
944 
945   // Create /guard:cf tables if requested.
946   if (config->guardCF != GuardCFLevel::Off)
947     createGuardCFTables();
948 
949   if (config->mingw) {
950     createRuntimePseudoRelocs();
951 
952     insertCtorDtorSymbols();
953   }
954 }
955 
956 // Create .idata section for the DLL-imported symbol table.
957 // The format of this section is inherently Windows-specific.
958 // IdataContents class abstracted away the details for us,
959 // so we just let it create chunks and add them to the section.
960 void Writer::createImportTables() {
961   // Initialize DLLOrder so that import entries are ordered in
962   // the same order as in the command line. (That affects DLL
963   // initialization order, and this ordering is MSVC-compatible.)
964   for (ImportFile *file : ImportFile::instances) {
965     if (!file->live)
966       continue;
967 
968     std::string dll = StringRef(file->dllName).lower();
969     if (config->dllOrder.count(dll) == 0)
970       config->dllOrder[dll] = config->dllOrder.size();
971 
972     if (file->impSym && !isa<DefinedImportData>(file->impSym))
973       fatal(toString(*file->impSym) + " was replaced");
974     DefinedImportData *impSym = cast_or_null<DefinedImportData>(file->impSym);
975     if (config->delayLoads.count(StringRef(file->dllName).lower())) {
976       if (!file->thunkSym)
977         fatal("cannot delay-load " + toString(file) +
978               " due to import of data: " + toString(*impSym));
979       delayIdata.add(impSym);
980     } else {
981       idata.add(impSym);
982     }
983   }
984 }
985 
986 void Writer::appendImportThunks() {
987   if (ImportFile::instances.empty())
988     return;
989 
990   for (ImportFile *file : ImportFile::instances) {
991     if (!file->live)
992       continue;
993 
994     if (!file->thunkSym)
995       continue;
996 
997     if (!isa<DefinedImportThunk>(file->thunkSym))
998       fatal(toString(*file->thunkSym) + " was replaced");
999     DefinedImportThunk *thunk = cast<DefinedImportThunk>(file->thunkSym);
1000     if (file->thunkLive)
1001       textSec->addChunk(thunk->getChunk());
1002   }
1003 
1004   if (!delayIdata.empty()) {
1005     Defined *helper = cast<Defined>(config->delayLoadHelper);
1006     delayIdata.create(helper);
1007     for (Chunk *c : delayIdata.getChunks())
1008       didatSec->addChunk(c);
1009     for (Chunk *c : delayIdata.getDataChunks())
1010       dataSec->addChunk(c);
1011     for (Chunk *c : delayIdata.getCodeChunks())
1012       textSec->addChunk(c);
1013   }
1014 }
1015 
1016 void Writer::createExportTable() {
1017   if (!edataSec->chunks.empty()) {
1018     // Allow using a custom built export table from input object files, instead
1019     // of having the linker synthesize the tables.
1020     if (config->hadExplicitExports)
1021       warn("literal .edata sections override exports");
1022   } else if (!config->exports.empty()) {
1023     for (Chunk *c : edata.chunks)
1024       edataSec->addChunk(c);
1025   }
1026   if (!edataSec->chunks.empty()) {
1027     edataStart = edataSec->chunks.front();
1028     edataEnd = edataSec->chunks.back();
1029   }
1030 }
1031 
1032 void Writer::removeUnusedSections() {
1033   // Remove sections that we can be sure won't get content, to avoid
1034   // allocating space for their section headers.
1035   auto isUnused = [this](OutputSection *s) {
1036     if (s == relocSec)
1037       return false; // This section is populated later.
1038     // MergeChunks have zero size at this point, as their size is finalized
1039     // later. Only remove sections that have no Chunks at all.
1040     return s->chunks.empty();
1041   };
1042   outputSections.erase(
1043       std::remove_if(outputSections.begin(), outputSections.end(), isUnused),
1044       outputSections.end());
1045 }
1046 
1047 // The Windows loader doesn't seem to like empty sections,
1048 // so we remove them if any.
1049 void Writer::removeEmptySections() {
1050   auto isEmpty = [](OutputSection *s) { return s->getVirtualSize() == 0; };
1051   outputSections.erase(
1052       std::remove_if(outputSections.begin(), outputSections.end(), isEmpty),
1053       outputSections.end());
1054 }
1055 
1056 void Writer::assignOutputSectionIndices() {
1057   // Assign final output section indices, and assign each chunk to its output
1058   // section.
1059   uint32_t idx = 1;
1060   for (OutputSection *os : outputSections) {
1061     os->sectionIndex = idx;
1062     for (Chunk *c : os->chunks)
1063       c->setOutputSectionIdx(idx);
1064     ++idx;
1065   }
1066 
1067   // Merge chunks are containers of chunks, so assign those an output section
1068   // too.
1069   for (MergeChunk *mc : MergeChunk::instances)
1070     if (mc)
1071       for (SectionChunk *sc : mc->sections)
1072         if (sc && sc->live)
1073           sc->setOutputSectionIdx(mc->getOutputSectionIdx());
1074 }
1075 
1076 size_t Writer::addEntryToStringTable(StringRef str) {
1077   assert(str.size() > COFF::NameSize);
1078   size_t offsetOfEntry = strtab.size() + 4; // +4 for the size field
1079   strtab.insert(strtab.end(), str.begin(), str.end());
1080   strtab.push_back('\0');
1081   return offsetOfEntry;
1082 }
1083 
1084 Optional<coff_symbol16> Writer::createSymbol(Defined *def) {
1085   coff_symbol16 sym;
1086   switch (def->kind()) {
1087   case Symbol::DefinedAbsoluteKind:
1088     sym.Value = def->getRVA();
1089     sym.SectionNumber = IMAGE_SYM_ABSOLUTE;
1090     break;
1091   case Symbol::DefinedSyntheticKind:
1092     // Relative symbols are unrepresentable in a COFF symbol table.
1093     return None;
1094   default: {
1095     // Don't write symbols that won't be written to the output to the symbol
1096     // table.
1097     Chunk *c = def->getChunk();
1098     if (!c)
1099       return None;
1100     OutputSection *os = c->getOutputSection();
1101     if (!os)
1102       return None;
1103 
1104     sym.Value = def->getRVA() - os->getRVA();
1105     sym.SectionNumber = os->sectionIndex;
1106     break;
1107   }
1108   }
1109 
1110   // Symbols that are runtime pseudo relocations don't point to the actual
1111   // symbol data itself (as they are imported), but points to the IAT entry
1112   // instead. Avoid emitting them to the symbol table, as they can confuse
1113   // debuggers.
1114   if (def->isRuntimePseudoReloc)
1115     return None;
1116 
1117   StringRef name = def->getName();
1118   if (name.size() > COFF::NameSize) {
1119     sym.Name.Offset.Zeroes = 0;
1120     sym.Name.Offset.Offset = addEntryToStringTable(name);
1121   } else {
1122     memset(sym.Name.ShortName, 0, COFF::NameSize);
1123     memcpy(sym.Name.ShortName, name.data(), name.size());
1124   }
1125 
1126   if (auto *d = dyn_cast<DefinedCOFF>(def)) {
1127     COFFSymbolRef ref = d->getCOFFSymbol();
1128     sym.Type = ref.getType();
1129     sym.StorageClass = ref.getStorageClass();
1130   } else {
1131     sym.Type = IMAGE_SYM_TYPE_NULL;
1132     sym.StorageClass = IMAGE_SYM_CLASS_EXTERNAL;
1133   }
1134   sym.NumberOfAuxSymbols = 0;
1135   return sym;
1136 }
1137 
1138 void Writer::createSymbolAndStringTable() {
1139   // PE/COFF images are limited to 8 byte section names. Longer names can be
1140   // supported by writing a non-standard string table, but this string table is
1141   // not mapped at runtime and the long names will therefore be inaccessible.
1142   // link.exe always truncates section names to 8 bytes, whereas binutils always
1143   // preserves long section names via the string table. LLD adopts a hybrid
1144   // solution where discardable sections have long names preserved and
1145   // non-discardable sections have their names truncated, to ensure that any
1146   // section which is mapped at runtime also has its name mapped at runtime.
1147   for (OutputSection *sec : outputSections) {
1148     if (sec->name.size() <= COFF::NameSize)
1149       continue;
1150     if ((sec->header.Characteristics & IMAGE_SCN_MEM_DISCARDABLE) == 0)
1151       continue;
1152     sec->setStringTableOff(addEntryToStringTable(sec->name));
1153   }
1154 
1155   if (config->debugDwarf || config->debugSymtab) {
1156     for (ObjFile *file : ObjFile::instances) {
1157       for (Symbol *b : file->getSymbols()) {
1158         auto *d = dyn_cast_or_null<Defined>(b);
1159         if (!d || d->writtenToSymtab)
1160           continue;
1161         d->writtenToSymtab = true;
1162 
1163         if (Optional<coff_symbol16> sym = createSymbol(d))
1164           outputSymtab.push_back(*sym);
1165       }
1166     }
1167   }
1168 
1169   if (outputSymtab.empty() && strtab.empty())
1170     return;
1171 
1172   // We position the symbol table to be adjacent to the end of the last section.
1173   uint64_t fileOff = fileSize;
1174   pointerToSymbolTable = fileOff;
1175   fileOff += outputSymtab.size() * sizeof(coff_symbol16);
1176   fileOff += 4 + strtab.size();
1177   fileSize = alignTo(fileOff, config->fileAlign);
1178 }
1179 
1180 void Writer::mergeSections() {
1181   if (!pdataSec->chunks.empty()) {
1182     firstPdata = pdataSec->chunks.front();
1183     lastPdata = pdataSec->chunks.back();
1184   }
1185 
1186   for (auto &p : config->merge) {
1187     StringRef toName = p.second;
1188     if (p.first == toName)
1189       continue;
1190     StringSet<> names;
1191     while (1) {
1192       if (!names.insert(toName).second)
1193         fatal("/merge: cycle found for section '" + p.first + "'");
1194       auto i = config->merge.find(toName);
1195       if (i == config->merge.end())
1196         break;
1197       toName = i->second;
1198     }
1199     OutputSection *from = findSection(p.first);
1200     OutputSection *to = findSection(toName);
1201     if (!from)
1202       continue;
1203     if (!to) {
1204       from->name = toName;
1205       continue;
1206     }
1207     to->merge(from);
1208   }
1209 }
1210 
1211 // Visits all sections to assign incremental, non-overlapping RVAs and
1212 // file offsets.
1213 void Writer::assignAddresses() {
1214   sizeOfHeaders = dosStubSize + sizeof(PEMagic) + sizeof(coff_file_header) +
1215                   sizeof(data_directory) * numberOfDataDirectory +
1216                   sizeof(coff_section) * outputSections.size();
1217   sizeOfHeaders +=
1218       config->is64() ? sizeof(pe32plus_header) : sizeof(pe32_header);
1219   sizeOfHeaders = alignTo(sizeOfHeaders, config->fileAlign);
1220   fileSize = sizeOfHeaders;
1221 
1222   // The first page is kept unmapped.
1223   uint64_t rva = alignTo(sizeOfHeaders, config->align);
1224 
1225   for (OutputSection *sec : outputSections) {
1226     if (sec == relocSec)
1227       addBaserels();
1228     uint64_t rawSize = 0, virtualSize = 0;
1229     sec->header.VirtualAddress = rva;
1230 
1231     // If /FUNCTIONPADMIN is used, functions are padded in order to create a
1232     // hotpatchable image.
1233     const bool isCodeSection =
1234         (sec->header.Characteristics & IMAGE_SCN_CNT_CODE) &&
1235         (sec->header.Characteristics & IMAGE_SCN_MEM_READ) &&
1236         (sec->header.Characteristics & IMAGE_SCN_MEM_EXECUTE);
1237     uint32_t padding = isCodeSection ? config->functionPadMin : 0;
1238 
1239     for (Chunk *c : sec->chunks) {
1240       if (padding && c->isHotPatchable())
1241         virtualSize += padding;
1242       virtualSize = alignTo(virtualSize, c->getAlignment());
1243       c->setRVA(rva + virtualSize);
1244       virtualSize += c->getSize();
1245       if (c->hasData)
1246         rawSize = alignTo(virtualSize, config->fileAlign);
1247     }
1248     if (virtualSize > UINT32_MAX)
1249       error("section larger than 4 GiB: " + sec->name);
1250     sec->header.VirtualSize = virtualSize;
1251     sec->header.SizeOfRawData = rawSize;
1252     if (rawSize != 0)
1253       sec->header.PointerToRawData = fileSize;
1254     rva += alignTo(virtualSize, config->align);
1255     fileSize += alignTo(rawSize, config->fileAlign);
1256   }
1257   sizeOfImage = alignTo(rva, config->align);
1258 
1259   // Assign addresses to sections in MergeChunks.
1260   for (MergeChunk *mc : MergeChunk::instances)
1261     if (mc)
1262       mc->assignSubsectionRVAs();
1263 }
1264 
1265 template <typename PEHeaderTy> void Writer::writeHeader() {
1266   // Write DOS header. For backwards compatibility, the first part of a PE/COFF
1267   // executable consists of an MS-DOS MZ executable. If the executable is run
1268   // under DOS, that program gets run (usually to just print an error message).
1269   // When run under Windows, the loader looks at AddressOfNewExeHeader and uses
1270   // the PE header instead.
1271   uint8_t *buf = buffer->getBufferStart();
1272   auto *dos = reinterpret_cast<dos_header *>(buf);
1273   buf += sizeof(dos_header);
1274   dos->Magic[0] = 'M';
1275   dos->Magic[1] = 'Z';
1276   dos->UsedBytesInTheLastPage = dosStubSize % 512;
1277   dos->FileSizeInPages = divideCeil(dosStubSize, 512);
1278   dos->HeaderSizeInParagraphs = sizeof(dos_header) / 16;
1279 
1280   dos->AddressOfRelocationTable = sizeof(dos_header);
1281   dos->AddressOfNewExeHeader = dosStubSize;
1282 
1283   // Write DOS program.
1284   memcpy(buf, dosProgram, sizeof(dosProgram));
1285   buf += sizeof(dosProgram);
1286 
1287   // Write PE magic
1288   memcpy(buf, PEMagic, sizeof(PEMagic));
1289   buf += sizeof(PEMagic);
1290 
1291   // Write COFF header
1292   auto *coff = reinterpret_cast<coff_file_header *>(buf);
1293   buf += sizeof(*coff);
1294   coff->Machine = config->machine;
1295   coff->NumberOfSections = outputSections.size();
1296   coff->Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE;
1297   if (config->largeAddressAware)
1298     coff->Characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
1299   if (!config->is64())
1300     coff->Characteristics |= IMAGE_FILE_32BIT_MACHINE;
1301   if (config->dll)
1302     coff->Characteristics |= IMAGE_FILE_DLL;
1303   if (!config->relocatable)
1304     coff->Characteristics |= IMAGE_FILE_RELOCS_STRIPPED;
1305   if (config->swaprunCD)
1306     coff->Characteristics |= IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP;
1307   if (config->swaprunNet)
1308     coff->Characteristics |= IMAGE_FILE_NET_RUN_FROM_SWAP;
1309   coff->SizeOfOptionalHeader =
1310       sizeof(PEHeaderTy) + sizeof(data_directory) * numberOfDataDirectory;
1311 
1312   // Write PE header
1313   auto *pe = reinterpret_cast<PEHeaderTy *>(buf);
1314   buf += sizeof(*pe);
1315   pe->Magic = config->is64() ? PE32Header::PE32_PLUS : PE32Header::PE32;
1316 
1317   // If {Major,Minor}LinkerVersion is left at 0.0, then for some
1318   // reason signing the resulting PE file with Authenticode produces a
1319   // signature that fails to validate on Windows 7 (but is OK on 10).
1320   // Set it to 14.0, which is what VS2015 outputs, and which avoids
1321   // that problem.
1322   pe->MajorLinkerVersion = 14;
1323   pe->MinorLinkerVersion = 0;
1324 
1325   pe->ImageBase = config->imageBase;
1326   pe->SectionAlignment = config->align;
1327   pe->FileAlignment = config->fileAlign;
1328   pe->MajorImageVersion = config->majorImageVersion;
1329   pe->MinorImageVersion = config->minorImageVersion;
1330   pe->MajorOperatingSystemVersion = config->majorOSVersion;
1331   pe->MinorOperatingSystemVersion = config->minorOSVersion;
1332   pe->MajorSubsystemVersion = config->majorOSVersion;
1333   pe->MinorSubsystemVersion = config->minorOSVersion;
1334   pe->Subsystem = config->subsystem;
1335   pe->SizeOfImage = sizeOfImage;
1336   pe->SizeOfHeaders = sizeOfHeaders;
1337   if (!config->noEntry) {
1338     Defined *entry = cast<Defined>(config->entry);
1339     pe->AddressOfEntryPoint = entry->getRVA();
1340     // Pointer to thumb code must have the LSB set, so adjust it.
1341     if (config->machine == ARMNT)
1342       pe->AddressOfEntryPoint |= 1;
1343   }
1344   pe->SizeOfStackReserve = config->stackReserve;
1345   pe->SizeOfStackCommit = config->stackCommit;
1346   pe->SizeOfHeapReserve = config->heapReserve;
1347   pe->SizeOfHeapCommit = config->heapCommit;
1348   if (config->appContainer)
1349     pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_APPCONTAINER;
1350   if (config->dynamicBase)
1351     pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
1352   if (config->highEntropyVA)
1353     pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA;
1354   if (!config->allowBind)
1355     pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_BIND;
1356   if (config->nxCompat)
1357     pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
1358   if (!config->allowIsolation)
1359     pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION;
1360   if (config->guardCF != GuardCFLevel::Off)
1361     pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_GUARD_CF;
1362   if (config->integrityCheck)
1363     pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY;
1364   if (setNoSEHCharacteristic)
1365     pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_SEH;
1366   if (config->terminalServerAware)
1367     pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE;
1368   pe->NumberOfRvaAndSize = numberOfDataDirectory;
1369   if (textSec->getVirtualSize()) {
1370     pe->BaseOfCode = textSec->getRVA();
1371     pe->SizeOfCode = textSec->getRawSize();
1372   }
1373   pe->SizeOfInitializedData = getSizeOfInitializedData();
1374 
1375   // Write data directory
1376   auto *dir = reinterpret_cast<data_directory *>(buf);
1377   buf += sizeof(*dir) * numberOfDataDirectory;
1378   if (edataStart) {
1379     dir[EXPORT_TABLE].RelativeVirtualAddress = edataStart->getRVA();
1380     dir[EXPORT_TABLE].Size =
1381         edataEnd->getRVA() + edataEnd->getSize() - edataStart->getRVA();
1382   }
1383   if (importTableStart) {
1384     dir[IMPORT_TABLE].RelativeVirtualAddress = importTableStart->getRVA();
1385     dir[IMPORT_TABLE].Size = importTableSize;
1386   }
1387   if (iatStart) {
1388     dir[IAT].RelativeVirtualAddress = iatStart->getRVA();
1389     dir[IAT].Size = iatSize;
1390   }
1391   if (rsrcSec->getVirtualSize()) {
1392     dir[RESOURCE_TABLE].RelativeVirtualAddress = rsrcSec->getRVA();
1393     dir[RESOURCE_TABLE].Size = rsrcSec->getVirtualSize();
1394   }
1395   if (firstPdata) {
1396     dir[EXCEPTION_TABLE].RelativeVirtualAddress = firstPdata->getRVA();
1397     dir[EXCEPTION_TABLE].Size =
1398         lastPdata->getRVA() + lastPdata->getSize() - firstPdata->getRVA();
1399   }
1400   if (relocSec->getVirtualSize()) {
1401     dir[BASE_RELOCATION_TABLE].RelativeVirtualAddress = relocSec->getRVA();
1402     dir[BASE_RELOCATION_TABLE].Size = relocSec->getVirtualSize();
1403   }
1404   if (Symbol *sym = symtab->findUnderscore("_tls_used")) {
1405     if (Defined *b = dyn_cast<Defined>(sym)) {
1406       dir[TLS_TABLE].RelativeVirtualAddress = b->getRVA();
1407       dir[TLS_TABLE].Size = config->is64()
1408                                 ? sizeof(object::coff_tls_directory64)
1409                                 : sizeof(object::coff_tls_directory32);
1410     }
1411   }
1412   if (debugDirectory) {
1413     dir[DEBUG_DIRECTORY].RelativeVirtualAddress = debugDirectory->getRVA();
1414     dir[DEBUG_DIRECTORY].Size = debugDirectory->getSize();
1415   }
1416   if (Symbol *sym = symtab->findUnderscore("_load_config_used")) {
1417     if (auto *b = dyn_cast<DefinedRegular>(sym)) {
1418       SectionChunk *sc = b->getChunk();
1419       assert(b->getRVA() >= sc->getRVA());
1420       uint64_t offsetInChunk = b->getRVA() - sc->getRVA();
1421       if (!sc->hasData || offsetInChunk + 4 > sc->getSize())
1422         fatal("_load_config_used is malformed");
1423 
1424       ArrayRef<uint8_t> secContents = sc->getContents();
1425       uint32_t loadConfigSize =
1426           *reinterpret_cast<const ulittle32_t *>(&secContents[offsetInChunk]);
1427       if (offsetInChunk + loadConfigSize > sc->getSize())
1428         fatal("_load_config_used is too large");
1429       dir[LOAD_CONFIG_TABLE].RelativeVirtualAddress = b->getRVA();
1430       dir[LOAD_CONFIG_TABLE].Size = loadConfigSize;
1431     }
1432   }
1433   if (!delayIdata.empty()) {
1434     dir[DELAY_IMPORT_DESCRIPTOR].RelativeVirtualAddress =
1435         delayIdata.getDirRVA();
1436     dir[DELAY_IMPORT_DESCRIPTOR].Size = delayIdata.getDirSize();
1437   }
1438 
1439   // Write section table
1440   for (OutputSection *sec : outputSections) {
1441     sec->writeHeaderTo(buf);
1442     buf += sizeof(coff_section);
1443   }
1444   sectionTable = ArrayRef<uint8_t>(
1445       buf - outputSections.size() * sizeof(coff_section), buf);
1446 
1447   if (outputSymtab.empty() && strtab.empty())
1448     return;
1449 
1450   coff->PointerToSymbolTable = pointerToSymbolTable;
1451   uint32_t numberOfSymbols = outputSymtab.size();
1452   coff->NumberOfSymbols = numberOfSymbols;
1453   auto *symbolTable = reinterpret_cast<coff_symbol16 *>(
1454       buffer->getBufferStart() + coff->PointerToSymbolTable);
1455   for (size_t i = 0; i != numberOfSymbols; ++i)
1456     symbolTable[i] = outputSymtab[i];
1457   // Create the string table, it follows immediately after the symbol table.
1458   // The first 4 bytes is length including itself.
1459   buf = reinterpret_cast<uint8_t *>(&symbolTable[numberOfSymbols]);
1460   write32le(buf, strtab.size() + 4);
1461   if (!strtab.empty())
1462     memcpy(buf + 4, strtab.data(), strtab.size());
1463 }
1464 
1465 void Writer::openFile(StringRef path) {
1466   buffer = CHECK(
1467       FileOutputBuffer::create(path, fileSize, FileOutputBuffer::F_executable),
1468       "failed to open " + path);
1469 }
1470 
1471 void Writer::createSEHTable() {
1472   SymbolRVASet handlers;
1473   for (ObjFile *file : ObjFile::instances) {
1474     if (!file->hasSafeSEH())
1475       error("/safeseh: " + file->getName() + " is not compatible with SEH");
1476     markSymbolsForRVATable(file, file->getSXDataChunks(), handlers);
1477   }
1478 
1479   // Set the "no SEH" characteristic if there really were no handlers, or if
1480   // there is no load config object to point to the table of handlers.
1481   setNoSEHCharacteristic =
1482       handlers.empty() || !symtab->findUnderscore("_load_config_used");
1483 
1484   maybeAddRVATable(std::move(handlers), "__safe_se_handler_table",
1485                    "__safe_se_handler_count");
1486 }
1487 
1488 // Add a symbol to an RVA set. Two symbols may have the same RVA, but an RVA set
1489 // cannot contain duplicates. Therefore, the set is uniqued by Chunk and the
1490 // symbol's offset into that Chunk.
1491 static void addSymbolToRVASet(SymbolRVASet &rvaSet, Defined *s) {
1492   Chunk *c = s->getChunk();
1493   if (auto *sc = dyn_cast<SectionChunk>(c))
1494     c = sc->repl; // Look through ICF replacement.
1495   uint32_t off = s->getRVA() - (c ? c->getRVA() : 0);
1496   rvaSet.insert({c, off});
1497 }
1498 
1499 // Given a symbol, add it to the GFIDs table if it is a live, defined, function
1500 // symbol in an executable section.
1501 static void maybeAddAddressTakenFunction(SymbolRVASet &addressTakenSyms,
1502                                          Symbol *s) {
1503   if (!s)
1504     return;
1505 
1506   switch (s->kind()) {
1507   case Symbol::DefinedLocalImportKind:
1508   case Symbol::DefinedImportDataKind:
1509     // Defines an __imp_ pointer, so it is data, so it is ignored.
1510     break;
1511   case Symbol::DefinedCommonKind:
1512     // Common is always data, so it is ignored.
1513     break;
1514   case Symbol::DefinedAbsoluteKind:
1515   case Symbol::DefinedSyntheticKind:
1516     // Absolute is never code, synthetic generally isn't and usually isn't
1517     // determinable.
1518     break;
1519   case Symbol::LazyKind:
1520   case Symbol::UndefinedKind:
1521     // Undefined symbols resolve to zero, so they don't have an RVA. Lazy
1522     // symbols shouldn't have relocations.
1523     break;
1524 
1525   case Symbol::DefinedImportThunkKind:
1526     // Thunks are always code, include them.
1527     addSymbolToRVASet(addressTakenSyms, cast<Defined>(s));
1528     break;
1529 
1530   case Symbol::DefinedRegularKind: {
1531     // This is a regular, defined, symbol from a COFF file. Mark the symbol as
1532     // address taken if the symbol type is function and it's in an executable
1533     // section.
1534     auto *d = cast<DefinedRegular>(s);
1535     if (d->getCOFFSymbol().getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION) {
1536       SectionChunk *sc = dyn_cast<SectionChunk>(d->getChunk());
1537       if (sc && sc->live &&
1538           sc->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE)
1539         addSymbolToRVASet(addressTakenSyms, d);
1540     }
1541     break;
1542   }
1543   }
1544 }
1545 
1546 // Visit all relocations from all section contributions of this object file and
1547 // mark the relocation target as address-taken.
1548 static void markSymbolsWithRelocations(ObjFile *file,
1549                                        SymbolRVASet &usedSymbols) {
1550   for (Chunk *c : file->getChunks()) {
1551     // We only care about live section chunks. Common chunks and other chunks
1552     // don't generally contain relocations.
1553     SectionChunk *sc = dyn_cast<SectionChunk>(c);
1554     if (!sc || !sc->live)
1555       continue;
1556 
1557     for (const coff_relocation &reloc : sc->getRelocs()) {
1558       if (config->machine == I386 && reloc.Type == COFF::IMAGE_REL_I386_REL32)
1559         // Ignore relative relocations on x86. On x86_64 they can't be ignored
1560         // since they're also used to compute absolute addresses.
1561         continue;
1562 
1563       Symbol *ref = sc->file->getSymbol(reloc.SymbolTableIndex);
1564       maybeAddAddressTakenFunction(usedSymbols, ref);
1565     }
1566   }
1567 }
1568 
1569 // Create the guard function id table. This is a table of RVAs of all
1570 // address-taken functions. It is sorted and uniqued, just like the safe SEH
1571 // table.
1572 void Writer::createGuardCFTables() {
1573   SymbolRVASet addressTakenSyms;
1574   SymbolRVASet longJmpTargets;
1575   for (ObjFile *file : ObjFile::instances) {
1576     // If the object was compiled with /guard:cf, the address taken symbols
1577     // are in .gfids$y sections, and the longjmp targets are in .gljmp$y
1578     // sections. If the object was not compiled with /guard:cf, we assume there
1579     // were no setjmp targets, and that all code symbols with relocations are
1580     // possibly address-taken.
1581     if (file->hasGuardCF()) {
1582       markSymbolsForRVATable(file, file->getGuardFidChunks(), addressTakenSyms);
1583       markSymbolsForRVATable(file, file->getGuardLJmpChunks(), longJmpTargets);
1584     } else {
1585       markSymbolsWithRelocations(file, addressTakenSyms);
1586     }
1587   }
1588 
1589   // Mark the image entry as address-taken.
1590   if (config->entry)
1591     maybeAddAddressTakenFunction(addressTakenSyms, config->entry);
1592 
1593   // Mark exported symbols in executable sections as address-taken.
1594   for (Export &e : config->exports)
1595     maybeAddAddressTakenFunction(addressTakenSyms, e.sym);
1596 
1597   // Ensure sections referenced in the gfid table are 16-byte aligned.
1598   for (const ChunkAndOffset &c : addressTakenSyms)
1599     if (c.inputChunk->getAlignment() < 16)
1600       c.inputChunk->setAlignment(16);
1601 
1602   maybeAddRVATable(std::move(addressTakenSyms), "__guard_fids_table",
1603                    "__guard_fids_count");
1604 
1605   // Add the longjmp target table unless the user told us not to.
1606   if (config->guardCF == GuardCFLevel::Full)
1607     maybeAddRVATable(std::move(longJmpTargets), "__guard_longjmp_table",
1608                      "__guard_longjmp_count");
1609 
1610   // Set __guard_flags, which will be used in the load config to indicate that
1611   // /guard:cf was enabled.
1612   uint32_t guardFlags = uint32_t(coff_guard_flags::CFInstrumented) |
1613                         uint32_t(coff_guard_flags::HasFidTable);
1614   if (config->guardCF == GuardCFLevel::Full)
1615     guardFlags |= uint32_t(coff_guard_flags::HasLongJmpTable);
1616   Symbol *flagSym = symtab->findUnderscore("__guard_flags");
1617   cast<DefinedAbsolute>(flagSym)->setVA(guardFlags);
1618 }
1619 
1620 // Take a list of input sections containing symbol table indices and add those
1621 // symbols to an RVA table. The challenge is that symbol RVAs are not known and
1622 // depend on the table size, so we can't directly build a set of integers.
1623 void Writer::markSymbolsForRVATable(ObjFile *file,
1624                                     ArrayRef<SectionChunk *> symIdxChunks,
1625                                     SymbolRVASet &tableSymbols) {
1626   for (SectionChunk *c : symIdxChunks) {
1627     // Skip sections discarded by linker GC. This comes up when a .gfids section
1628     // is associated with something like a vtable and the vtable is discarded.
1629     // In this case, the associated gfids section is discarded, and we don't
1630     // mark the virtual member functions as address-taken by the vtable.
1631     if (!c->live)
1632       continue;
1633 
1634     // Validate that the contents look like symbol table indices.
1635     ArrayRef<uint8_t> data = c->getContents();
1636     if (data.size() % 4 != 0) {
1637       warn("ignoring " + c->getSectionName() +
1638            " symbol table index section in object " + toString(file));
1639       continue;
1640     }
1641 
1642     // Read each symbol table index and check if that symbol was included in the
1643     // final link. If so, add it to the table symbol set.
1644     ArrayRef<ulittle32_t> symIndices(
1645         reinterpret_cast<const ulittle32_t *>(data.data()), data.size() / 4);
1646     ArrayRef<Symbol *> objSymbols = file->getSymbols();
1647     for (uint32_t symIndex : symIndices) {
1648       if (symIndex >= objSymbols.size()) {
1649         warn("ignoring invalid symbol table index in section " +
1650              c->getSectionName() + " in object " + toString(file));
1651         continue;
1652       }
1653       if (Symbol *s = objSymbols[symIndex]) {
1654         if (s->isLive())
1655           addSymbolToRVASet(tableSymbols, cast<Defined>(s));
1656       }
1657     }
1658   }
1659 }
1660 
1661 // Replace the absolute table symbol with a synthetic symbol pointing to
1662 // tableChunk so that we can emit base relocations for it and resolve section
1663 // relative relocations.
1664 void Writer::maybeAddRVATable(SymbolRVASet tableSymbols, StringRef tableSym,
1665                               StringRef countSym) {
1666   if (tableSymbols.empty())
1667     return;
1668 
1669   RVATableChunk *tableChunk = make<RVATableChunk>(std::move(tableSymbols));
1670   rdataSec->addChunk(tableChunk);
1671 
1672   Symbol *t = symtab->findUnderscore(tableSym);
1673   Symbol *c = symtab->findUnderscore(countSym);
1674   replaceSymbol<DefinedSynthetic>(t, t->getName(), tableChunk);
1675   cast<DefinedAbsolute>(c)->setVA(tableChunk->getSize() / 4);
1676 }
1677 
1678 // MinGW specific. Gather all relocations that are imported from a DLL even
1679 // though the code didn't expect it to, produce the table that the runtime
1680 // uses for fixing them up, and provide the synthetic symbols that the
1681 // runtime uses for finding the table.
1682 void Writer::createRuntimePseudoRelocs() {
1683   std::vector<RuntimePseudoReloc> rels;
1684 
1685   for (Chunk *c : symtab->getChunks()) {
1686     auto *sc = dyn_cast<SectionChunk>(c);
1687     if (!sc || !sc->live)
1688       continue;
1689     sc->getRuntimePseudoRelocs(rels);
1690   }
1691 
1692   if (!rels.empty())
1693     log("Writing " + Twine(rels.size()) + " runtime pseudo relocations");
1694   PseudoRelocTableChunk *table = make<PseudoRelocTableChunk>(rels);
1695   rdataSec->addChunk(table);
1696   EmptyChunk *endOfList = make<EmptyChunk>();
1697   rdataSec->addChunk(endOfList);
1698 
1699   Symbol *headSym = symtab->findUnderscore("__RUNTIME_PSEUDO_RELOC_LIST__");
1700   Symbol *endSym = symtab->findUnderscore("__RUNTIME_PSEUDO_RELOC_LIST_END__");
1701   replaceSymbol<DefinedSynthetic>(headSym, headSym->getName(), table);
1702   replaceSymbol<DefinedSynthetic>(endSym, endSym->getName(), endOfList);
1703 }
1704 
1705 // MinGW specific.
1706 // The MinGW .ctors and .dtors lists have sentinels at each end;
1707 // a (uintptr_t)-1 at the start and a (uintptr_t)0 at the end.
1708 // There's a symbol pointing to the start sentinel pointer, __CTOR_LIST__
1709 // and __DTOR_LIST__ respectively.
1710 void Writer::insertCtorDtorSymbols() {
1711   AbsolutePointerChunk *ctorListHead = make<AbsolutePointerChunk>(-1);
1712   AbsolutePointerChunk *ctorListEnd = make<AbsolutePointerChunk>(0);
1713   AbsolutePointerChunk *dtorListHead = make<AbsolutePointerChunk>(-1);
1714   AbsolutePointerChunk *dtorListEnd = make<AbsolutePointerChunk>(0);
1715   ctorsSec->insertChunkAtStart(ctorListHead);
1716   ctorsSec->addChunk(ctorListEnd);
1717   dtorsSec->insertChunkAtStart(dtorListHead);
1718   dtorsSec->addChunk(dtorListEnd);
1719 
1720   Symbol *ctorListSym = symtab->findUnderscore("__CTOR_LIST__");
1721   Symbol *dtorListSym = symtab->findUnderscore("__DTOR_LIST__");
1722   replaceSymbol<DefinedSynthetic>(ctorListSym, ctorListSym->getName(),
1723                                   ctorListHead);
1724   replaceSymbol<DefinedSynthetic>(dtorListSym, dtorListSym->getName(),
1725                                   dtorListHead);
1726 }
1727 
1728 // Handles /section options to allow users to overwrite
1729 // section attributes.
1730 void Writer::setSectionPermissions() {
1731   for (auto &p : config->section) {
1732     StringRef name = p.first;
1733     uint32_t perm = p.second;
1734     for (OutputSection *sec : outputSections)
1735       if (sec->name == name)
1736         sec->setPermissions(perm);
1737   }
1738 }
1739 
1740 // Write section contents to a mmap'ed file.
1741 void Writer::writeSections() {
1742   // Record the number of sections to apply section index relocations
1743   // against absolute symbols. See applySecIdx in Chunks.cpp..
1744   DefinedAbsolute::numOutputSections = outputSections.size();
1745 
1746   uint8_t *buf = buffer->getBufferStart();
1747   for (OutputSection *sec : outputSections) {
1748     uint8_t *secBuf = buf + sec->getFileOff();
1749     // Fill gaps between functions in .text with INT3 instructions
1750     // instead of leaving as NUL bytes (which can be interpreted as
1751     // ADD instructions).
1752     if (sec->header.Characteristics & IMAGE_SCN_CNT_CODE)
1753       memset(secBuf, 0xCC, sec->getRawSize());
1754     parallelForEach(sec->chunks, [&](Chunk *c) {
1755       c->writeTo(secBuf + c->getRVA() - sec->getRVA());
1756     });
1757   }
1758 }
1759 
1760 void Writer::writeBuildId() {
1761   // There are two important parts to the build ID.
1762   // 1) If building with debug info, the COFF debug directory contains a
1763   //    timestamp as well as a Guid and Age of the PDB.
1764   // 2) In all cases, the PE COFF file header also contains a timestamp.
1765   // For reproducibility, instead of a timestamp we want to use a hash of the
1766   // PE contents.
1767   if (config->debug) {
1768     assert(buildId && "BuildId is not set!");
1769     // BuildId->BuildId was filled in when the PDB was written.
1770   }
1771 
1772   // At this point the only fields in the COFF file which remain unset are the
1773   // "timestamp" in the COFF file header, and the ones in the coff debug
1774   // directory.  Now we can hash the file and write that hash to the various
1775   // timestamp fields in the file.
1776   StringRef outputFileData(
1777       reinterpret_cast<const char *>(buffer->getBufferStart()),
1778       buffer->getBufferSize());
1779 
1780   uint32_t timestamp = config->timestamp;
1781   uint64_t hash = 0;
1782   bool generateSyntheticBuildId =
1783       config->mingw && config->debug && config->pdbPath.empty();
1784 
1785   if (config->repro || generateSyntheticBuildId)
1786     hash = xxHash64(outputFileData);
1787 
1788   if (config->repro)
1789     timestamp = static_cast<uint32_t>(hash);
1790 
1791   if (generateSyntheticBuildId) {
1792     // For MinGW builds without a PDB file, we still generate a build id
1793     // to allow associating a crash dump to the executable.
1794     buildId->buildId->PDB70.CVSignature = OMF::Signature::PDB70;
1795     buildId->buildId->PDB70.Age = 1;
1796     memcpy(buildId->buildId->PDB70.Signature, &hash, 8);
1797     // xxhash only gives us 8 bytes, so put some fixed data in the other half.
1798     memcpy(&buildId->buildId->PDB70.Signature[8], "LLD PDB.", 8);
1799   }
1800 
1801   if (debugDirectory)
1802     debugDirectory->setTimeDateStamp(timestamp);
1803 
1804   uint8_t *buf = buffer->getBufferStart();
1805   buf += dosStubSize + sizeof(PEMagic);
1806   object::coff_file_header *coffHeader =
1807       reinterpret_cast<coff_file_header *>(buf);
1808   coffHeader->TimeDateStamp = timestamp;
1809 }
1810 
1811 // Sort .pdata section contents according to PE/COFF spec 5.5.
1812 void Writer::sortExceptionTable() {
1813   if (!firstPdata)
1814     return;
1815   // We assume .pdata contains function table entries only.
1816   auto bufAddr = [&](Chunk *c) {
1817     OutputSection *os = c->getOutputSection();
1818     return buffer->getBufferStart() + os->getFileOff() + c->getRVA() -
1819            os->getRVA();
1820   };
1821   uint8_t *begin = bufAddr(firstPdata);
1822   uint8_t *end = bufAddr(lastPdata) + lastPdata->getSize();
1823   if (config->machine == AMD64) {
1824     struct Entry { ulittle32_t begin, end, unwind; };
1825     parallelSort(
1826         MutableArrayRef<Entry>((Entry *)begin, (Entry *)end),
1827         [](const Entry &a, const Entry &b) { return a.begin < b.begin; });
1828     return;
1829   }
1830   if (config->machine == ARMNT || config->machine == ARM64) {
1831     struct Entry { ulittle32_t begin, unwind; };
1832     parallelSort(
1833         MutableArrayRef<Entry>((Entry *)begin, (Entry *)end),
1834         [](const Entry &a, const Entry &b) { return a.begin < b.begin; });
1835     return;
1836   }
1837   errs() << "warning: don't know how to handle .pdata.\n";
1838 }
1839 
1840 // The CRT section contains, among other things, the array of function
1841 // pointers that initialize every global variable that is not trivially
1842 // constructed. The CRT calls them one after the other prior to invoking
1843 // main().
1844 //
1845 // As per C++ spec, 3.6.2/2.3,
1846 // "Variables with ordered initialization defined within a single
1847 // translation unit shall be initialized in the order of their definitions
1848 // in the translation unit"
1849 //
1850 // It is therefore critical to sort the chunks containing the function
1851 // pointers in the order that they are listed in the object file (top to
1852 // bottom), otherwise global objects might not be initialized in the
1853 // correct order.
1854 void Writer::sortCRTSectionChunks(std::vector<Chunk *> &chunks) {
1855   auto sectionChunkOrder = [](const Chunk *a, const Chunk *b) {
1856     auto sa = dyn_cast<SectionChunk>(a);
1857     auto sb = dyn_cast<SectionChunk>(b);
1858     assert(sa && sb && "Non-section chunks in CRT section!");
1859 
1860     StringRef sAObj = sa->file->mb.getBufferIdentifier();
1861     StringRef sBObj = sb->file->mb.getBufferIdentifier();
1862 
1863     return sAObj == sBObj && sa->getSectionNumber() < sb->getSectionNumber();
1864   };
1865   llvm::stable_sort(chunks, sectionChunkOrder);
1866 
1867   if (config->verbose) {
1868     for (auto &c : chunks) {
1869       auto sc = dyn_cast<SectionChunk>(c);
1870       log("  " + sc->file->mb.getBufferIdentifier().str() +
1871           ", SectionID: " + Twine(sc->getSectionNumber()));
1872     }
1873   }
1874 }
1875 
1876 OutputSection *Writer::findSection(StringRef name) {
1877   for (OutputSection *sec : outputSections)
1878     if (sec->name == name)
1879       return sec;
1880   return nullptr;
1881 }
1882 
1883 uint32_t Writer::getSizeOfInitializedData() {
1884   uint32_t res = 0;
1885   for (OutputSection *s : outputSections)
1886     if (s->header.Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)
1887       res += s->getRawSize();
1888   return res;
1889 }
1890 
1891 // Add base relocations to .reloc section.
1892 void Writer::addBaserels() {
1893   if (!config->relocatable)
1894     return;
1895   relocSec->chunks.clear();
1896   std::vector<Baserel> v;
1897   for (OutputSection *sec : outputSections) {
1898     if (sec->header.Characteristics & IMAGE_SCN_MEM_DISCARDABLE)
1899       continue;
1900     // Collect all locations for base relocations.
1901     for (Chunk *c : sec->chunks)
1902       c->getBaserels(&v);
1903     // Add the addresses to .reloc section.
1904     if (!v.empty())
1905       addBaserelBlocks(v);
1906     v.clear();
1907   }
1908 }
1909 
1910 // Add addresses to .reloc section. Note that addresses are grouped by page.
1911 void Writer::addBaserelBlocks(std::vector<Baserel> &v) {
1912   const uint32_t mask = ~uint32_t(pageSize - 1);
1913   uint32_t page = v[0].rva & mask;
1914   size_t i = 0, j = 1;
1915   for (size_t e = v.size(); j < e; ++j) {
1916     uint32_t p = v[j].rva & mask;
1917     if (p == page)
1918       continue;
1919     relocSec->addChunk(make<BaserelChunk>(page, &v[i], &v[0] + j));
1920     i = j;
1921     page = p;
1922   }
1923   if (i == j)
1924     return;
1925   relocSec->addChunk(make<BaserelChunk>(page, &v[i], &v[0] + j));
1926 }
1927 
1928 PartialSection *Writer::createPartialSection(StringRef name,
1929                                              uint32_t outChars) {
1930   PartialSection *&pSec = partialSections[{name, outChars}];
1931   if (pSec)
1932     return pSec;
1933   pSec = make<PartialSection>(name, outChars);
1934   return pSec;
1935 }
1936 
1937 PartialSection *Writer::findPartialSection(StringRef name, uint32_t outChars) {
1938   auto it = partialSections.find({name, outChars});
1939   if (it != partialSections.end())
1940     return it->second;
1941   return nullptr;
1942 }
1943