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