Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/lld/COFF/Writer.cpp
Warning:line 1034, column 44
Forming reference to null pointer

Annotated Source Code

Press '?' to see keyboard shortcuts

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