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