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