Bug Summary

File:tools/lld/COFF/Writer.cpp
Warning:line 582, column 23
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name Writer.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -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 -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/tools/lld/COFF -I /build/llvm-toolchain-snapshot-7~svn325118/tools/lld/COFF -I /build/llvm-toolchain-snapshot-7~svn325118/tools/lld/include -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/tools/lld/include -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn325118/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/tools/lld/COFF -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-02-14-150435-17243-1 -x c++ /build/llvm-toolchain-snapshot-7~svn325118/tools/lld/COFF/Writer.cpp
1//===- Writer.cpp ---------------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "Writer.h"
11#include "Config.h"
12#include "DLL.h"
13#include "InputFiles.h"
14#include "MapFile.h"
15#include "PDB.h"
16#include "SymbolTable.h"
17#include "Symbols.h"
18#include "lld/Common/ErrorHandler.h"
19#include "lld/Common/Memory.h"
20#include "lld/Common/Timer.h"
21#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/StringSwitch.h"
24#include "llvm/Support/BinaryStreamReader.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/Endian.h"
27#include "llvm/Support/FileOutputBuffer.h"
28#include "llvm/Support/Parallel.h"
29#include "llvm/Support/Path.h"
30#include "llvm/Support/RandomNumberGenerator.h"
31#include <algorithm>
32#include <cstdio>
33#include <map>
34#include <memory>
35#include <utility>
36
37using namespace llvm;
38using namespace llvm::COFF;
39using namespace llvm::object;
40using namespace llvm::support;
41using namespace llvm::support::endian;
42using namespace lld;
43using namespace lld::coff;
44
45static const int SectorSize = 512;
46static const int DOSStubSize = 64;
47static const int NumberfOfDataDirectory = 16;
48
49namespace {
50
51class DebugDirectoryChunk : public Chunk {
52public:
53 DebugDirectoryChunk(const std::vector<Chunk *> &R) : Records(R) {}
54
55 size_t getSize() const override {
56 return Records.size() * sizeof(debug_directory);
57 }
58
59 void writeTo(uint8_t *B) const override {
60 auto *D = reinterpret_cast<debug_directory *>(B + OutputSectionOff);
61
62 for (const Chunk *Record : Records) {
63 D->Characteristics = 0;
64 D->TimeDateStamp = 0;
65 D->MajorVersion = 0;
66 D->MinorVersion = 0;
67 D->Type = COFF::IMAGE_DEBUG_TYPE_CODEVIEW;
68 D->SizeOfData = Record->getSize();
69 D->AddressOfRawData = Record->getRVA();
70 OutputSection *OS = Record->getOutputSection();
71 uint64_t Offs = OS->getFileOff() + (Record->getRVA() - OS->getRVA());
72 D->PointerToRawData = Offs;
73
74 ++D;
75 }
76 }
77
78private:
79 const std::vector<Chunk *> &Records;
80};
81
82class CVDebugRecordChunk : public Chunk {
83public:
84 CVDebugRecordChunk() {
85 PDBAbsPath = Config->PDBPath;
86 if (!PDBAbsPath.empty())
87 llvm::sys::fs::make_absolute(PDBAbsPath);
88 }
89
90 size_t getSize() const override {
91 return sizeof(codeview::DebugInfo) + PDBAbsPath.size() + 1;
92 }
93
94 void writeTo(uint8_t *B) const override {
95 // Save off the DebugInfo entry to backfill the file signature (build id)
96 // in Writer::writeBuildId
97 BuildId = reinterpret_cast<codeview::DebugInfo *>(B + OutputSectionOff);
98
99 // variable sized field (PDB Path)
100 char *P = reinterpret_cast<char *>(B + OutputSectionOff + sizeof(*BuildId));
101 if (!PDBAbsPath.empty())
102 memcpy(P, PDBAbsPath.data(), PDBAbsPath.size());
103 P[PDBAbsPath.size()] = '\0';
104 }
105
106 SmallString<128> PDBAbsPath;
107 mutable codeview::DebugInfo *BuildId = nullptr;
108};
109
110// The writer writes a SymbolTable result to a file.
111class Writer {
112public:
113 Writer() : Buffer(errorHandler().OutputBuffer) {}
114 void run();
115
116private:
117 void createSections();
118 void createMiscChunks();
119 void createImportTables();
120 void createExportTable();
121 void assignAddresses();
122 void removeEmptySections();
123 void createSymbolAndStringTable();
124 void openFile(StringRef OutputPath);
125 template <typename PEHeaderTy> void writeHeader();
126 void createSEHTable(OutputSection *RData);
127 void createGuardCFTables(OutputSection *RData);
128 void createGLJmpTable(OutputSection *RData);
129 void markSymbolsForRVATable(ObjFile *File,
130 ArrayRef<SectionChunk *> SymIdxChunks,
131 SymbolRVASet &TableSymbols);
132 void maybeAddRVATable(OutputSection *RData, SymbolRVASet TableSymbols,
133 StringRef TableSym, StringRef CountSym);
134 void setSectionPermissions();
135 void writeSections();
136 void writeBuildId();
137 void sortExceptionTable();
138
139 llvm::Optional<coff_symbol16> createSymbol(Defined *D);
140 size_t addEntryToStringTable(StringRef Str);
141
142 OutputSection *findSection(StringRef Name);
143 OutputSection *createSection(StringRef Name);
144 void addBaserels(OutputSection *Dest);
145 void addBaserelBlocks(OutputSection *Dest, std::vector<Baserel> &V);
146
147 uint32_t getSizeOfInitializedData();
148 std::map<StringRef, std::vector<DefinedImportData *>> binImports();
149
150 std::unique_ptr<FileOutputBuffer> &Buffer;
151 std::vector<OutputSection *> OutputSections;
152 std::vector<char> Strtab;
153 std::vector<llvm::object::coff_symbol16> OutputSymtab;
154 IdataContents Idata;
155 DelayLoadContents DelayIdata;
156 EdataContents Edata;
157 RVATableChunk *GuardFidsTable = nullptr;
158 RVATableChunk *SEHTable = nullptr;
159
160 Chunk *DebugDirectory = nullptr;
161 std::vector<Chunk *> DebugRecords;
162 CVDebugRecordChunk *BuildId = nullptr;
163 Optional<codeview::DebugInfo> PreviousBuildId;
164 ArrayRef<uint8_t> SectionTable;
165
166 uint64_t FileSize;
167 uint32_t PointerToSymbolTable = 0;
168 uint64_t SizeOfImage;
169 uint64_t SizeOfHeaders;
170};
171} // anonymous namespace
172
173namespace lld {
174namespace coff {
175
176static Timer CodeLayoutTimer("Code Layout", Timer::root());
177static Timer DiskCommitTimer("Commit Output File", Timer::root());
178
179void writeResult() { Writer().run(); }
180
181void OutputSection::setRVA(uint64_t RVA) {
182 Header.VirtualAddress = RVA;
183 for (Chunk *C : Chunks)
184 C->setRVA(C->getRVA() + RVA);
185}
186
187void OutputSection::setFileOffset(uint64_t Off) {
188 // If a section has no actual data (i.e. BSS section), we want to
189 // set 0 to its PointerToRawData. Otherwise the output is rejected
190 // by the loader.
191 if (Header.SizeOfRawData == 0)
192 return;
193
194 // It is possible that this assignment could cause an overflow of the u32,
195 // but that should be caught by the FileSize check in OutputSection::run().
196 Header.PointerToRawData = Off;
197}
198
199void OutputSection::addChunk(Chunk *C) {
200 Chunks.push_back(C);
201 C->setOutputSection(this);
202 uint64_t Off = Header.VirtualSize;
203 Off = alignTo(Off, C->Alignment);
204 C->setRVA(Off);
205 C->OutputSectionOff = Off;
206 Off += C->getSize();
207 if (Off > UINT32_MAX(4294967295U))
208 error("section larger than 4 GiB: " + Name);
209 Header.VirtualSize = Off;
210 if (C->hasData())
211 Header.SizeOfRawData = alignTo(Off, SectorSize);
212}
213
214void OutputSection::addPermissions(uint32_t C) {
215 Header.Characteristics |= C & PermMask;
216}
217
218void OutputSection::setPermissions(uint32_t C) {
219 Header.Characteristics = C & PermMask;
220}
221
222// Write the section header to a given buffer.
223void OutputSection::writeHeaderTo(uint8_t *Buf) {
224 auto *Hdr = reinterpret_cast<coff_section *>(Buf);
225 *Hdr = Header;
226 if (StringTableOff) {
227 // If name is too long, write offset into the string table as a name.
228 sprintf(Hdr->Name, "/%d", StringTableOff);
229 } else {
230 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"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/lld/COFF/Writer.cpp"
, 231, __extension__ __PRETTY_FUNCTION__))
231 (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"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/lld/COFF/Writer.cpp"
, 231, __extension__ __PRETTY_FUNCTION__))
;
232 strncpy(Hdr->Name, Name.data(),
233 std::min(Name.size(), (size_t)COFF::NameSize));
234 }
235}
236
237} // namespace coff
238} // namespace lld
239
240// PDBs are matched against executables using a build id which consists of three
241// components:
242// 1. A 16-bit GUID
243// 2. An age
244// 3. A time stamp.
245//
246// Debuggers and symbol servers match executables against debug info by checking
247// each of these components of the EXE/DLL against the corresponding value in
248// the PDB and failing a match if any of the components differ. In the case of
249// symbol servers, symbols are cached in a folder that is a function of the
250// GUID. As a result, in order to avoid symbol cache pollution where every
251// incremental build copies a new PDB to the symbol cache, we must try to re-use
252// the existing GUID if one exists, but bump the age. This way the match will
253// fail, so the symbol cache knows to use the new PDB, but the GUID matches, so
254// it overwrites the existing item in the symbol cache rather than making a new
255// one.
256static Optional<codeview::DebugInfo> loadExistingBuildId(StringRef Path) {
257 // We don't need to incrementally update a previous build id if we're not
258 // writing codeview debug info.
259 if (!Config->Debug)
260 return None;
261
262 auto ExpectedBinary = llvm::object::createBinary(Path);
263 if (!ExpectedBinary) {
264 consumeError(ExpectedBinary.takeError());
265 return None;
266 }
267
268 auto Binary = std::move(*ExpectedBinary);
269 if (!Binary.getBinary()->isCOFF())
270 return None;
271
272 std::error_code EC;
273 COFFObjectFile File(Binary.getBinary()->getMemoryBufferRef(), EC);
274 if (EC)
275 return None;
276
277 // If the machine of the binary we're outputting doesn't match the machine
278 // of the existing binary, don't try to re-use the build id.
279 if (File.is64() != Config->is64() || File.getMachine() != Config->Machine)
280 return None;
281
282 for (const auto &DebugDir : File.debug_directories()) {
283 if (DebugDir.Type != IMAGE_DEBUG_TYPE_CODEVIEW)
284 continue;
285
286 const codeview::DebugInfo *ExistingDI = nullptr;
287 StringRef PDBFileName;
288 if (auto EC = File.getDebugPDBInfo(ExistingDI, PDBFileName)) {
289 (void)EC;
290 return None;
291 }
292 // We only support writing PDBs in v70 format. So if this is not a build
293 // id that we recognize / support, ignore it.
294 if (ExistingDI->Signature.CVSignature != OMF::Signature::PDB70)
295 return None;
296 return *ExistingDI;
297 }
298 return None;
299}
300
301// The main function of the writer.
302void Writer::run() {
303 ScopedTimer T1(CodeLayoutTimer);
304
305 createSections();
306 createMiscChunks();
307 createImportTables();
308 createExportTable();
309 if (Config->Relocatable)
310 createSection(".reloc");
311 assignAddresses();
312 removeEmptySections();
313 setSectionPermissions();
314 createSymbolAndStringTable();
315
316 if (FileSize > UINT32_MAX(4294967295U))
317 fatal("image size (" + Twine(FileSize) + ") " +
318 "exceeds maximum allowable size (" + Twine(UINT32_MAX(4294967295U)) + ")");
319
320 // We must do this before opening the output file, as it depends on being able
321 // to read the contents of the existing output file.
322 PreviousBuildId = loadExistingBuildId(Config->OutputFile);
323 openFile(Config->OutputFile);
324 if (Config->is64()) {
325 writeHeader<pe32plus_header>();
326 } else {
327 writeHeader<pe32_header>();
328 }
329 writeSections();
330 sortExceptionTable();
331 writeBuildId();
332
333 T1.stop();
334
335 if (!Config->PDBPath.empty() && Config->Debug) {
336 assert(BuildId)(static_cast <bool> (BuildId) ? void (0) : __assert_fail
("BuildId", "/build/llvm-toolchain-snapshot-7~svn325118/tools/lld/COFF/Writer.cpp"
, 336, __extension__ __PRETTY_FUNCTION__))
;
337 createPDB(Symtab, OutputSections, SectionTable, *BuildId->BuildId);
338 }
339
340 writeMapFile(OutputSections);
341
342 ScopedTimer T2(DiskCommitTimer);
343 if (auto E = Buffer->commit())
344 fatal("failed to write the output file: " + toString(std::move(E)));
345}
346
347static StringRef getOutputSection(StringRef Name) {
348 StringRef S = Name.split('$').first;
349
350 // Treat a later period as a separator for MinGW, for sections like
351 // ".ctors.01234".
352 S = S.substr(0, S.find('.', 1));
353
354 auto It = Config->Merge.find(S);
355 if (It == Config->Merge.end())
356 return S;
357 return It->second;
358}
359
360// For /order.
361static void sortBySectionOrder(std::vector<Chunk *> &Chunks) {
362 auto GetPriority = [](const Chunk *C) {
363 if (auto *Sec = dyn_cast<SectionChunk>(C))
364 if (Sec->Sym)
365 return Config->Order.lookup(Sec->Sym->getName());
366 return 0;
367 };
368
369 std::stable_sort(Chunks.begin(), Chunks.end(),
370 [=](const Chunk *A, const Chunk *B) {
371 return GetPriority(A) < GetPriority(B);
372 });
373}
374
375// Create output section objects and add them to OutputSections.
376void Writer::createSections() {
377 // First, bin chunks by name.
378 std::map<StringRef, std::vector<Chunk *>> Map;
379 for (Chunk *C : Symtab->getChunks()) {
380 auto *SC = dyn_cast<SectionChunk>(C);
381 if (SC && !SC->isLive()) {
382 if (Config->Verbose)
383 SC->printDiscardedMessage();
384 continue;
385 }
386 Map[C->getSectionName()].push_back(C);
387 }
388
389 // Process an /order option.
390 if (!Config->Order.empty())
391 for (auto &Pair : Map)
392 sortBySectionOrder(Pair.second);
393
394 // Then create an OutputSection for each section.
395 // '$' and all following characters in input section names are
396 // discarded when determining output section. So, .text$foo
397 // contributes to .text, for example. See PE/COFF spec 3.2.
398 SmallDenseMap<StringRef, OutputSection *> Sections;
399 for (auto Pair : Map) {
400 StringRef Name = getOutputSection(Pair.first);
401 OutputSection *&Sec = Sections[Name];
402 if (!Sec) {
403 Sec = make<OutputSection>(Name);
404 OutputSections.push_back(Sec);
405 }
406 std::vector<Chunk *> &Chunks = Pair.second;
407 for (Chunk *C : Chunks) {
408 Sec->addChunk(C);
409 Sec->addPermissions(C->getPermissions());
410 }
411 }
412}
413
414void Writer::createMiscChunks() {
415 OutputSection *RData = createSection(".rdata");
416
417 // Create thunks for locally-dllimported symbols.
418 if (!Symtab->LocalImportChunks.empty()) {
419 for (Chunk *C : Symtab->LocalImportChunks)
420 RData->addChunk(C);
421 }
422
423 // Create Debug Information Chunks
424 if (Config->Debug) {
425 DebugDirectory = make<DebugDirectoryChunk>(DebugRecords);
426
427 // Make a CVDebugRecordChunk even when /DEBUG:CV is not specified. We
428 // output a PDB no matter what, and this chunk provides the only means of
429 // allowing a debugger to match a PDB and an executable. So we need it even
430 // if we're ultimately not going to write CodeView data to the PDB.
431 auto *CVChunk = make<CVDebugRecordChunk>();
432 BuildId = CVChunk;
433 DebugRecords.push_back(CVChunk);
434
435 RData->addChunk(DebugDirectory);
436 for (Chunk *C : DebugRecords)
437 RData->addChunk(C);
438 }
439
440 // Create SEH table. x86-only.
441 if (Config->Machine == I386)
442 createSEHTable(RData);
443
444 // Create /guard:cf tables if requested.
445 if (Config->GuardCF != GuardCFLevel::Off)
446 createGuardCFTables(RData);
447}
448
449// Create .idata section for the DLL-imported symbol table.
450// The format of this section is inherently Windows-specific.
451// IdataContents class abstracted away the details for us,
452// so we just let it create chunks and add them to the section.
453void Writer::createImportTables() {
454 if (ImportFile::Instances.empty())
455 return;
456
457 // Initialize DLLOrder so that import entries are ordered in
458 // the same order as in the command line. (That affects DLL
459 // initialization order, and this ordering is MSVC-compatible.)
460 for (ImportFile *File : ImportFile::Instances) {
461 if (!File->Live)
462 continue;
463
464 std::string DLL = StringRef(File->DLLName).lower();
465 if (Config->DLLOrder.count(DLL) == 0)
466 Config->DLLOrder[DLL] = Config->DLLOrder.size();
467 }
468
469 OutputSection *Text = createSection(".text");
470 for (ImportFile *File : ImportFile::Instances) {
471 if (!File->Live)
472 continue;
473
474 if (DefinedImportThunk *Thunk = File->ThunkSym)
475 Text->addChunk(Thunk->getChunk());
476
477 if (Config->DelayLoads.count(StringRef(File->DLLName).lower())) {
478 if (!File->ThunkSym)
479 fatal("cannot delay-load " + toString(File) +
480 " due to import of data: " + toString(*File->ImpSym));
481 DelayIdata.add(File->ImpSym);
482 } else {
483 Idata.add(File->ImpSym);
484 }
485 }
486
487 if (!Idata.empty()) {
488 OutputSection *Sec = createSection(".idata");
489 for (Chunk *C : Idata.getChunks())
490 Sec->addChunk(C);
491 }
492
493 if (!DelayIdata.empty()) {
494 Defined *Helper = cast<Defined>(Config->DelayLoadHelper);
495 DelayIdata.create(Helper);
496 OutputSection *Sec = createSection(".didat");
497 for (Chunk *C : DelayIdata.getChunks())
498 Sec->addChunk(C);
499 Sec = createSection(".data");
500 for (Chunk *C : DelayIdata.getDataChunks())
501 Sec->addChunk(C);
502 Sec = createSection(".text");
503 for (Chunk *C : DelayIdata.getCodeChunks())
504 Sec->addChunk(C);
505 }
506}
507
508void Writer::createExportTable() {
509 if (Config->Exports.empty())
510 return;
511 OutputSection *Sec = createSection(".edata");
512 for (Chunk *C : Edata.Chunks)
513 Sec->addChunk(C);
514}
515
516// The Windows loader doesn't seem to like empty sections,
517// so we remove them if any.
518void Writer::removeEmptySections() {
519 auto IsEmpty = [](OutputSection *S) { return S->getVirtualSize() == 0; };
520 OutputSections.erase(
521 std::remove_if(OutputSections.begin(), OutputSections.end(), IsEmpty),
522 OutputSections.end());
523 uint32_t Idx = 1;
524 for (OutputSection *Sec : OutputSections)
525 Sec->SectionIndex = Idx++;
526}
527
528size_t Writer::addEntryToStringTable(StringRef Str) {
529 assert(Str.size() > COFF::NameSize)(static_cast <bool> (Str.size() > COFF::NameSize) ? void
(0) : __assert_fail ("Str.size() > COFF::NameSize", "/build/llvm-toolchain-snapshot-7~svn325118/tools/lld/COFF/Writer.cpp"
, 529, __extension__ __PRETTY_FUNCTION__))
;
530 size_t OffsetOfEntry = Strtab.size() + 4; // +4 for the size field
531 Strtab.insert(Strtab.end(), Str.begin(), Str.end());
532 Strtab.push_back('\0');
533 return OffsetOfEntry;
534}
535
536Optional<coff_symbol16> Writer::createSymbol(Defined *Def) {
537 // Relative symbols are unrepresentable in a COFF symbol table.
538 if (isa<DefinedSynthetic>(Def))
1
Taking false branch
539 return None;
540
541 // Don't write dead symbols or symbols in codeview sections to the symbol
542 // table.
543 if (!Def->isLive())
2
Assuming the condition is false
3
Taking false branch
544 return None;
545 if (auto *D = dyn_cast<DefinedRegular>(Def))
4
Taking false branch
546 if (D->getChunk()->isCodeView())
547 return None;
548
549 coff_symbol16 Sym;
550 StringRef Name = Def->getName();
551 if (Name.size() > COFF::NameSize) {
5
Assuming the condition is false
6
Taking false branch
552 Sym.Name.Offset.Zeroes = 0;
553 Sym.Name.Offset.Offset = addEntryToStringTable(Name);
554 } else {
555 memset(Sym.Name.ShortName, 0, COFF::NameSize);
556 memcpy(Sym.Name.ShortName, Name.data(), Name.size());
557 }
558
559 if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
7
Taking false branch
560 COFFSymbolRef Ref = D->getCOFFSymbol();
561 Sym.Type = Ref.getType();
562 Sym.StorageClass = Ref.getStorageClass();
563 } else {
564 Sym.Type = IMAGE_SYM_TYPE_NULL;
565 Sym.StorageClass = IMAGE_SYM_CLASS_EXTERNAL;
566 }
567 Sym.NumberOfAuxSymbols = 0;
568
569 switch (Def->kind()) {
8
Control jumps to the 'default' case at line 574
570 case Symbol::DefinedAbsoluteKind:
571 Sym.Value = Def->getRVA();
572 Sym.SectionNumber = IMAGE_SYM_ABSOLUTE;
573 break;
574 default: {
575 uint64_t RVA = Def->getRVA();
576 OutputSection *Sec = nullptr;
9
'Sec' initialized to a null pointer value
577 for (OutputSection *S : OutputSections) {
578 if (S->getRVA() > RVA)
579 break;
580 Sec = S;
581 }
582 Sym.Value = RVA - Sec->getRVA();
10
Called C++ object pointer is null
583 Sym.SectionNumber = Sec->SectionIndex;
584 break;
585 }
586 }
587 return Sym;
588}
589
590void Writer::createSymbolAndStringTable() {
591 // Name field in the section table is 8 byte long. Longer names need
592 // to be written to the string table. First, construct string table.
593 for (OutputSection *Sec : OutputSections) {
594 StringRef Name = Sec->getName();
595 if (Name.size() <= COFF::NameSize)
596 continue;
597 // If a section isn't discardable (i.e. will be mapped at runtime),
598 // prefer a truncated section name over a long section name in
599 // the string table that is unavailable at runtime. Note that link.exe
600 // always truncates, even for discardable sections.
601 if ((Sec->getPermissions() & IMAGE_SCN_MEM_DISCARDABLE) == 0)
602 continue;
603 Sec->setStringTableOff(addEntryToStringTable(Name));
604 }
605
606 if (Config->DebugDwarf) {
607 for (ObjFile *File : ObjFile::Instances) {
608 for (Symbol *B : File->getSymbols()) {
609 auto *D = dyn_cast_or_null<Defined>(B);
610 if (!D || D->WrittenToSymtab)
611 continue;
612 D->WrittenToSymtab = true;
613
614 if (Optional<coff_symbol16> Sym = createSymbol(D))
615 OutputSymtab.push_back(*Sym);
616 }
617 }
618 }
619
620 if (OutputSymtab.empty() && Strtab.empty())
621 return;
622
623 // We position the symbol table to be adjacent to the end of the last section.
624 uint64_t FileOff = FileSize;
625 PointerToSymbolTable = FileOff;
626 FileOff += OutputSymtab.size() * sizeof(coff_symbol16);
627 FileOff += 4 + Strtab.size();
628 FileSize = alignTo(FileOff, SectorSize);
629}
630
631// Visits all sections to assign incremental, non-overlapping RVAs and
632// file offsets.
633void Writer::assignAddresses() {
634 SizeOfHeaders = DOSStubSize + sizeof(PEMagic) + sizeof(coff_file_header) +
635 sizeof(data_directory) * NumberfOfDataDirectory +
636 sizeof(coff_section) * OutputSections.size();
637 SizeOfHeaders +=
638 Config->is64() ? sizeof(pe32plus_header) : sizeof(pe32_header);
639 SizeOfHeaders = alignTo(SizeOfHeaders, SectorSize);
640 uint64_t RVA = PageSize; // The first page is kept unmapped.
641 FileSize = SizeOfHeaders;
642 // Move DISCARDABLE (or non-memory-mapped) sections to the end of file because
643 // the loader cannot handle holes.
644 std::stable_partition(
645 OutputSections.begin(), OutputSections.end(), [](OutputSection *S) {
646 return (S->getPermissions() & IMAGE_SCN_MEM_DISCARDABLE) == 0;
647 });
648 for (OutputSection *Sec : OutputSections) {
649 if (Sec->getName() == ".reloc")
650 addBaserels(Sec);
651 Sec->setRVA(RVA);
652 Sec->setFileOffset(FileSize);
653 RVA += alignTo(Sec->getVirtualSize(), PageSize);
654 FileSize += alignTo(Sec->getRawSize(), SectorSize);
655 }
656 SizeOfImage = alignTo(RVA, PageSize);
657}
658
659template <typename PEHeaderTy> void Writer::writeHeader() {
660 // Write DOS stub
661 uint8_t *Buf = Buffer->getBufferStart();
662 auto *DOS = reinterpret_cast<dos_header *>(Buf);
663 Buf += DOSStubSize;
664 DOS->Magic[0] = 'M';
665 DOS->Magic[1] = 'Z';
666 DOS->AddressOfRelocationTable = sizeof(dos_header);
667 DOS->AddressOfNewExeHeader = DOSStubSize;
668
669 // Write PE magic
670 memcpy(Buf, PEMagic, sizeof(PEMagic));
671 Buf += sizeof(PEMagic);
672
673 // Write COFF header
674 auto *COFF = reinterpret_cast<coff_file_header *>(Buf);
675 Buf += sizeof(*COFF);
676 COFF->Machine = Config->Machine;
677 COFF->NumberOfSections = OutputSections.size();
678 COFF->Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE;
679 if (Config->LargeAddressAware)
680 COFF->Characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
681 if (!Config->is64())
682 COFF->Characteristics |= IMAGE_FILE_32BIT_MACHINE;
683 if (Config->DLL)
684 COFF->Characteristics |= IMAGE_FILE_DLL;
685 if (!Config->Relocatable)
686 COFF->Characteristics |= IMAGE_FILE_RELOCS_STRIPPED;
687 COFF->SizeOfOptionalHeader =
688 sizeof(PEHeaderTy) + sizeof(data_directory) * NumberfOfDataDirectory;
689
690 // Write PE header
691 auto *PE = reinterpret_cast<PEHeaderTy *>(Buf);
692 Buf += sizeof(*PE);
693 PE->Magic = Config->is64() ? PE32Header::PE32_PLUS : PE32Header::PE32;
694
695 // If {Major,Minor}LinkerVersion is left at 0.0, then for some
696 // reason signing the resulting PE file with Authenticode produces a
697 // signature that fails to validate on Windows 7 (but is OK on 10).
698 // Set it to 14.0, which is what VS2015 outputs, and which avoids
699 // that problem.
700 PE->MajorLinkerVersion = 14;
701 PE->MinorLinkerVersion = 0;
702
703 PE->ImageBase = Config->ImageBase;
704 PE->SectionAlignment = PageSize;
705 PE->FileAlignment = SectorSize;
706 PE->MajorImageVersion = Config->MajorImageVersion;
707 PE->MinorImageVersion = Config->MinorImageVersion;
708 PE->MajorOperatingSystemVersion = Config->MajorOSVersion;
709 PE->MinorOperatingSystemVersion = Config->MinorOSVersion;
710 PE->MajorSubsystemVersion = Config->MajorOSVersion;
711 PE->MinorSubsystemVersion = Config->MinorOSVersion;
712 PE->Subsystem = Config->Subsystem;
713 PE->SizeOfImage = SizeOfImage;
714 PE->SizeOfHeaders = SizeOfHeaders;
715 if (!Config->NoEntry) {
716 Defined *Entry = cast<Defined>(Config->Entry);
717 PE->AddressOfEntryPoint = Entry->getRVA();
718 // Pointer to thumb code must have the LSB set, so adjust it.
719 if (Config->Machine == ARMNT)
720 PE->AddressOfEntryPoint |= 1;
721 }
722 PE->SizeOfStackReserve = Config->StackReserve;
723 PE->SizeOfStackCommit = Config->StackCommit;
724 PE->SizeOfHeapReserve = Config->HeapReserve;
725 PE->SizeOfHeapCommit = Config->HeapCommit;
726 if (Config->AppContainer)
727 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_APPCONTAINER;
728 if (Config->DynamicBase)
729 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
730 if (Config->HighEntropyVA)
731 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA;
732 if (!Config->AllowBind)
733 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_BIND;
734 if (Config->NxCompat)
735 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
736 if (!Config->AllowIsolation)
737 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION;
738 if (Config->GuardCF != GuardCFLevel::Off)
739 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_GUARD_CF;
740 if (Config->Machine == I386 && !SEHTable &&
741 !Symtab->findUnderscore("_load_config_used"))
742 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_SEH;
743 if (Config->TerminalServerAware)
744 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE;
745 PE->NumberOfRvaAndSize = NumberfOfDataDirectory;
746 if (OutputSection *Text = findSection(".text")) {
747 PE->BaseOfCode = Text->getRVA();
748 PE->SizeOfCode = Text->getRawSize();
749 }
750 PE->SizeOfInitializedData = getSizeOfInitializedData();
751
752 // Write data directory
753 auto *Dir = reinterpret_cast<data_directory *>(Buf);
754 Buf += sizeof(*Dir) * NumberfOfDataDirectory;
755 if (OutputSection *Sec = findSection(".edata")) {
756 Dir[EXPORT_TABLE].RelativeVirtualAddress = Sec->getRVA();
757 Dir[EXPORT_TABLE].Size = Sec->getVirtualSize();
758 }
759 if (!Idata.empty()) {
760 Dir[IMPORT_TABLE].RelativeVirtualAddress = Idata.getDirRVA();
761 Dir[IMPORT_TABLE].Size = Idata.getDirSize();
762 Dir[IAT].RelativeVirtualAddress = Idata.getIATRVA();
763 Dir[IAT].Size = Idata.getIATSize();
764 }
765 if (OutputSection *Sec = findSection(".rsrc")) {
766 Dir[RESOURCE_TABLE].RelativeVirtualAddress = Sec->getRVA();
767 Dir[RESOURCE_TABLE].Size = Sec->getVirtualSize();
768 }
769 if (OutputSection *Sec = findSection(".pdata")) {
770 Dir[EXCEPTION_TABLE].RelativeVirtualAddress = Sec->getRVA();
771 Dir[EXCEPTION_TABLE].Size = Sec->getVirtualSize();
772 }
773 if (OutputSection *Sec = findSection(".reloc")) {
774 Dir[BASE_RELOCATION_TABLE].RelativeVirtualAddress = Sec->getRVA();
775 Dir[BASE_RELOCATION_TABLE].Size = Sec->getVirtualSize();
776 }
777 if (Symbol *Sym = Symtab->findUnderscore("_tls_used")) {
778 if (Defined *B = dyn_cast<Defined>(Sym)) {
779 Dir[TLS_TABLE].RelativeVirtualAddress = B->getRVA();
780 Dir[TLS_TABLE].Size = Config->is64()
781 ? sizeof(object::coff_tls_directory64)
782 : sizeof(object::coff_tls_directory32);
783 }
784 }
785 if (Config->Debug) {
786 Dir[DEBUG_DIRECTORY].RelativeVirtualAddress = DebugDirectory->getRVA();
787 Dir[DEBUG_DIRECTORY].Size = DebugDirectory->getSize();
788 }
789 if (Symbol *Sym = Symtab->findUnderscore("_load_config_used")) {
790 if (auto *B = dyn_cast<DefinedRegular>(Sym)) {
791 SectionChunk *SC = B->getChunk();
792 assert(B->getRVA() >= SC->getRVA())(static_cast <bool> (B->getRVA() >= SC->getRVA
()) ? void (0) : __assert_fail ("B->getRVA() >= SC->getRVA()"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/lld/COFF/Writer.cpp"
, 792, __extension__ __PRETTY_FUNCTION__))
;
793 uint64_t OffsetInChunk = B->getRVA() - SC->getRVA();
794 if (!SC->hasData() || OffsetInChunk + 4 > SC->getSize())
795 fatal("_load_config_used is malformed");
796
797 ArrayRef<uint8_t> SecContents = SC->getContents();
798 uint32_t LoadConfigSize =
799 *reinterpret_cast<const ulittle32_t *>(&SecContents[OffsetInChunk]);
800 if (OffsetInChunk + LoadConfigSize > SC->getSize())
801 fatal("_load_config_used is too large");
802 Dir[LOAD_CONFIG_TABLE].RelativeVirtualAddress = B->getRVA();
803 Dir[LOAD_CONFIG_TABLE].Size = LoadConfigSize;
804 }
805 }
806 if (!DelayIdata.empty()) {
807 Dir[DELAY_IMPORT_DESCRIPTOR].RelativeVirtualAddress =
808 DelayIdata.getDirRVA();
809 Dir[DELAY_IMPORT_DESCRIPTOR].Size = DelayIdata.getDirSize();
810 }
811
812 // Write section table
813 for (OutputSection *Sec : OutputSections) {
814 Sec->writeHeaderTo(Buf);
815 Buf += sizeof(coff_section);
816 }
817 SectionTable = ArrayRef<uint8_t>(
818 Buf - OutputSections.size() * sizeof(coff_section), Buf);
819
820 if (OutputSymtab.empty() && Strtab.empty())
821 return;
822
823 COFF->PointerToSymbolTable = PointerToSymbolTable;
824 uint32_t NumberOfSymbols = OutputSymtab.size();
825 COFF->NumberOfSymbols = NumberOfSymbols;
826 auto *SymbolTable = reinterpret_cast<coff_symbol16 *>(
827 Buffer->getBufferStart() + COFF->PointerToSymbolTable);
828 for (size_t I = 0; I != NumberOfSymbols; ++I)
829 SymbolTable[I] = OutputSymtab[I];
830 // Create the string table, it follows immediately after the symbol table.
831 // The first 4 bytes is length including itself.
832 Buf = reinterpret_cast<uint8_t *>(&SymbolTable[NumberOfSymbols]);
833 write32le(Buf, Strtab.size() + 4);
834 if (!Strtab.empty())
835 memcpy(Buf + 4, Strtab.data(), Strtab.size());
836}
837
838void Writer::openFile(StringRef Path) {
839 Buffer = CHECK(check2(FileOutputBuffer::create(Path, FileSize, FileOutputBuffer
::F_executable), [&] { return toString("failed to open " +
Path); })
840 FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable),check2(FileOutputBuffer::create(Path, FileSize, FileOutputBuffer
::F_executable), [&] { return toString("failed to open " +
Path); })
841 "failed to open " + Path)check2(FileOutputBuffer::create(Path, FileSize, FileOutputBuffer
::F_executable), [&] { return toString("failed to open " +
Path); })
;
842}
843
844void Writer::createSEHTable(OutputSection *RData) {
845 SymbolRVASet Handlers;
846 for (ObjFile *File : ObjFile::Instances) {
847 // FIXME: We should error here instead of earlier unless /safeseh:no was
848 // passed.
849 if (!File->hasSafeSEH())
850 return;
851
852 markSymbolsForRVATable(File, File->getSXDataChunks(), Handlers);
853 }
854
855 maybeAddRVATable(RData, std::move(Handlers), "__safe_se_handler_table",
856 "__safe_se_handler_count");
857}
858
859// Add a symbol to an RVA set. Two symbols may have the same RVA, but an RVA set
860// cannot contain duplicates. Therefore, the set is uniqued by Chunk and the
861// symbol's offset into that Chunk.
862static void addSymbolToRVASet(SymbolRVASet &RVASet, Defined *S) {
863 Chunk *C = S->getChunk();
864 if (auto *SC = dyn_cast<SectionChunk>(C))
865 C = SC->Repl; // Look through ICF replacement.
866 uint32_t Off = S->getRVA() - (C ? C->getRVA() : 0);
867 RVASet.insert({C, Off});
868}
869
870// Visit all relocations from all section contributions of this object file and
871// mark the relocation target as address-taken.
872static void markSymbolsWithRelocations(ObjFile *File,
873 SymbolRVASet &UsedSymbols) {
874 for (Chunk *C : File->getChunks()) {
875 // We only care about live section chunks. Common chunks and other chunks
876 // don't generally contain relocations.
877 SectionChunk *SC = dyn_cast<SectionChunk>(C);
878 if (!SC || !SC->isLive())
879 continue;
880
881 // Look for relocations in this section against symbols in executable output
882 // sections.
883 for (Symbol *Ref : SC->symbols()) {
884 // FIXME: Do further testing to see if the relocation type matters,
885 // especially for 32-bit where taking the address of something usually
886 // uses an absolute relocation instead of a relative one.
887 if (auto *D = dyn_cast_or_null<Defined>(Ref)) {
888 Chunk *RefChunk = D->getChunk();
889 OutputSection *OS = RefChunk ? RefChunk->getOutputSection() : nullptr;
890 if (OS && OS->getPermissions() & IMAGE_SCN_MEM_EXECUTE)
891 addSymbolToRVASet(UsedSymbols, D);
892 }
893 }
894 }
895}
896
897// Create the guard function id table. This is a table of RVAs of all
898// address-taken functions. It is sorted and uniqued, just like the safe SEH
899// table.
900void Writer::createGuardCFTables(OutputSection *RData) {
901 SymbolRVASet AddressTakenSyms;
902 SymbolRVASet LongJmpTargets;
903 for (ObjFile *File : ObjFile::Instances) {
904 // If the object was compiled with /guard:cf, the address taken symbols
905 // are in .gfids$y sections, and the longjmp targets are in .gljmp$y
906 // sections. If the object was not compiled with /guard:cf, we assume there
907 // were no setjmp targets, and that all code symbols with relocations are
908 // possibly address-taken.
909 if (File->hasGuardCF()) {
910 markSymbolsForRVATable(File, File->getGuardFidChunks(), AddressTakenSyms);
911 markSymbolsForRVATable(File, File->getGuardLJmpChunks(), LongJmpTargets);
912 } else {
913 markSymbolsWithRelocations(File, AddressTakenSyms);
914 }
915 }
916
917 // Mark the image entry as address-taken.
918 if (Config->Entry)
919 addSymbolToRVASet(AddressTakenSyms, cast<Defined>(Config->Entry));
920
921 maybeAddRVATable(RData, std::move(AddressTakenSyms), "__guard_fids_table",
922 "__guard_fids_count");
923
924 // Add the longjmp target table unless the user told us not to.
925 if (Config->GuardCF == GuardCFLevel::Full)
926 maybeAddRVATable(RData, std::move(LongJmpTargets), "__guard_longjmp_table",
927 "__guard_longjmp_count");
928
929 // Set __guard_flags, which will be used in the load config to indicate that
930 // /guard:cf was enabled.
931 uint32_t GuardFlags = uint32_t(coff_guard_flags::CFInstrumented) |
932 uint32_t(coff_guard_flags::HasFidTable);
933 if (Config->GuardCF == GuardCFLevel::Full)
934 GuardFlags |= uint32_t(coff_guard_flags::HasLongJmpTable);
935 Symbol *FlagSym = Symtab->findUnderscore("__guard_flags");
936 cast<DefinedAbsolute>(FlagSym)->setVA(GuardFlags);
937}
938
939// Take a list of input sections containing symbol table indices and add those
940// symbols to an RVA table. The challenge is that symbol RVAs are not known and
941// depend on the table size, so we can't directly build a set of integers.
942void Writer::markSymbolsForRVATable(ObjFile *File,
943 ArrayRef<SectionChunk *> SymIdxChunks,
944 SymbolRVASet &TableSymbols) {
945 for (SectionChunk *C : SymIdxChunks) {
946 // Skip sections discarded by linker GC. This comes up when a .gfids section
947 // is associated with something like a vtable and the vtable is discarded.
948 // In this case, the associated gfids section is discarded, and we don't
949 // mark the virtual member functions as address-taken by the vtable.
950 if (!C->isLive())
951 continue;
952
953 // Validate that the contents look like symbol table indices.
954 ArrayRef<uint8_t> Data = C->getContents();
955 if (Data.size() % 4 != 0) {
956 warn("ignoring " + C->getSectionName() +
957 " symbol table index section in object " + toString(File));
958 continue;
959 }
960
961 // Read each symbol table index and check if that symbol was included in the
962 // final link. If so, add it to the table symbol set.
963 ArrayRef<ulittle32_t> SymIndices(
964 reinterpret_cast<const ulittle32_t *>(Data.data()), Data.size() / 4);
965 ArrayRef<Symbol *> ObjSymbols = File->getSymbols();
966 for (uint32_t SymIndex : SymIndices) {
967 if (SymIndex >= ObjSymbols.size()) {
968 warn("ignoring invalid symbol table index in section " +
969 C->getSectionName() + " in object " + toString(File));
970 continue;
971 }
972 if (Symbol *S = ObjSymbols[SymIndex]) {
973 if (S->isLive())
974 addSymbolToRVASet(TableSymbols, cast<Defined>(S));
975 }
976 }
977 }
978}
979
980// Replace the absolute table symbol with a synthetic symbol pointing to
981// TableChunk so that we can emit base relocations for it and resolve section
982// relative relocations.
983void Writer::maybeAddRVATable(OutputSection *RData,
984 SymbolRVASet TableSymbols,
985 StringRef TableSym, StringRef CountSym) {
986 if (TableSymbols.empty())
987 return;
988
989 RVATableChunk *TableChunk = make<RVATableChunk>(std::move(TableSymbols));
990 RData->addChunk(TableChunk);
991
992 Symbol *T = Symtab->findUnderscore(TableSym);
993 Symbol *C = Symtab->findUnderscore(CountSym);
994 replaceSymbol<DefinedSynthetic>(T, T->getName(), TableChunk);
995 cast<DefinedAbsolute>(C)->setVA(TableChunk->getSize() / 4);
996}
997
998// Handles /section options to allow users to overwrite
999// section attributes.
1000void Writer::setSectionPermissions() {
1001 for (auto &P : Config->Section) {
1002 StringRef Name = P.first;
1003 uint32_t Perm = P.second;
1004 if (auto *Sec = findSection(Name))
1005 Sec->setPermissions(Perm);
1006 }
1007}
1008
1009// Write section contents to a mmap'ed file.
1010void Writer::writeSections() {
1011 // Record the section index that should be used when resolving a section
1012 // relocation against an absolute symbol.
1013 DefinedAbsolute::OutputSectionIndex = OutputSections.size() + 1;
1014
1015 uint8_t *Buf = Buffer->getBufferStart();
1016 for (OutputSection *Sec : OutputSections) {
1017 uint8_t *SecBuf = Buf + Sec->getFileOff();
1018 // Fill gaps between functions in .text with INT3 instructions
1019 // instead of leaving as NUL bytes (which can be interpreted as
1020 // ADD instructions).
1021 if (Sec->getPermissions() & IMAGE_SCN_CNT_CODE)
1022 memset(SecBuf, 0xCC, Sec->getRawSize());
1023 for_each(parallel::par, Sec->getChunks().begin(), Sec->getChunks().end(),
1024 [&](Chunk *C) { C->writeTo(SecBuf); });
1025 }
1026}
1027
1028void Writer::writeBuildId() {
1029 // If we're not writing a build id (e.g. because /debug is not specified),
1030 // then just return;
1031 if (!Config->Debug)
1032 return;
1033
1034 assert(BuildId && "BuildId is not set!")(static_cast <bool> (BuildId && "BuildId is not set!"
) ? void (0) : __assert_fail ("BuildId && \"BuildId is not set!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/lld/COFF/Writer.cpp"
, 1034, __extension__ __PRETTY_FUNCTION__))
;
1035
1036 if (PreviousBuildId.hasValue()) {
1037 *BuildId->BuildId = *PreviousBuildId;
1038 BuildId->BuildId->PDB70.Age = BuildId->BuildId->PDB70.Age + 1;
1039 return;
1040 }
1041
1042 BuildId->BuildId->Signature.CVSignature = OMF::Signature::PDB70;
1043 BuildId->BuildId->PDB70.Age = 1;
1044 llvm::getRandomBytes(BuildId->BuildId->PDB70.Signature, 16);
1045}
1046
1047// Sort .pdata section contents according to PE/COFF spec 5.5.
1048void Writer::sortExceptionTable() {
1049 OutputSection *Sec = findSection(".pdata");
1050 if (!Sec)
1051 return;
1052 // We assume .pdata contains function table entries only.
1053 uint8_t *Begin = Buffer->getBufferStart() + Sec->getFileOff();
1054 uint8_t *End = Begin + Sec->getVirtualSize();
1055 if (Config->Machine == AMD64) {
1056 struct Entry { ulittle32_t Begin, End, Unwind; };
1057 sort(parallel::par, (Entry *)Begin, (Entry *)End,
1058 [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
1059 return;
1060 }
1061 if (Config->Machine == ARMNT || Config->Machine == ARM64) {
1062 struct Entry { ulittle32_t Begin, Unwind; };
1063 sort(parallel::par, (Entry *)Begin, (Entry *)End,
1064 [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
1065 return;
1066 }
1067 errs() << "warning: don't know how to handle .pdata.\n";
1068}
1069
1070OutputSection *Writer::findSection(StringRef Name) {
1071 for (OutputSection *Sec : OutputSections)
1072 if (Sec->getName() == Name)
1073 return Sec;
1074 return nullptr;
1075}
1076
1077uint32_t Writer::getSizeOfInitializedData() {
1078 uint32_t Res = 0;
1079 for (OutputSection *S : OutputSections)
1080 if (S->getPermissions() & IMAGE_SCN_CNT_INITIALIZED_DATA)
1081 Res += S->getRawSize();
1082 return Res;
1083}
1084
1085// Returns an existing section or create a new one if not found.
1086OutputSection *Writer::createSection(StringRef Name) {
1087 if (auto *Sec = findSection(Name))
1088 return Sec;
1089 const auto DATA = IMAGE_SCN_CNT_INITIALIZED_DATA;
1090 const auto BSS = IMAGE_SCN_CNT_UNINITIALIZED_DATA;
1091 const auto CODE = IMAGE_SCN_CNT_CODE;
1092 const auto DISCARDABLE = IMAGE_SCN_MEM_DISCARDABLE;
1093 const auto R = IMAGE_SCN_MEM_READ;
1094 const auto W = IMAGE_SCN_MEM_WRITE;
1095 const auto X = IMAGE_SCN_MEM_EXECUTE;
1096 uint32_t Perms = StringSwitch<uint32_t>(Name)
1097 .Case(".bss", BSS | R | W)
1098 .Case(".data", DATA | R | W)
1099 .Cases(".didat", ".edata", ".idata", ".rdata", DATA | R)
1100 .Case(".reloc", DATA | DISCARDABLE | R)
1101 .Case(".text", CODE | R | X)
1102 .Default(0);
1103 if (!Perms)
1104 llvm_unreachable("unknown section name")::llvm::llvm_unreachable_internal("unknown section name", "/build/llvm-toolchain-snapshot-7~svn325118/tools/lld/COFF/Writer.cpp"
, 1104)
;
1105 auto Sec = make<OutputSection>(Name);
1106 Sec->addPermissions(Perms);
1107 OutputSections.push_back(Sec);
1108 return Sec;
1109}
1110
1111// Dest is .reloc section. Add contents to that section.
1112void Writer::addBaserels(OutputSection *Dest) {
1113 std::vector<Baserel> V;
1114 for (OutputSection *Sec : OutputSections) {
1115 if (Sec == Dest)
1116 continue;
1117 // Collect all locations for base relocations.
1118 for (Chunk *C : Sec->getChunks())
1119 C->getBaserels(&V);
1120 // Add the addresses to .reloc section.
1121 if (!V.empty())
1122 addBaserelBlocks(Dest, V);
1123 V.clear();
1124 }
1125}
1126
1127// Add addresses to .reloc section. Note that addresses are grouped by page.
1128void Writer::addBaserelBlocks(OutputSection *Dest, std::vector<Baserel> &V) {
1129 const uint32_t Mask = ~uint32_t(PageSize - 1);
1130 uint32_t Page = V[0].RVA & Mask;
1131 size_t I = 0, J = 1;
1132 for (size_t E = V.size(); J < E; ++J) {
1133 uint32_t P = V[J].RVA & Mask;
1134 if (P == Page)
1135 continue;
1136 Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));
1137 I = J;
1138 Page = P;
1139 }
1140 if (I == J)
1141 return;
1142 Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));
1143}