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