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