Bug Summary

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

Annotated Source Code

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 "Memory.h"
16#include "PDB.h"
17#include "SymbolTable.h"
18#include "Symbols.h"
19#include "lld/Common/ErrorHandler.h"
20#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/StringSwitch.h"
23#include "llvm/Support/BinaryStreamReader.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/Endian.h"
26#include "llvm/Support/FileOutputBuffer.h"
27#include "llvm/Support/Parallel.h"
28#include "llvm/Support/RandomNumberGenerator.h"
29#include <algorithm>
30#include <cstdio>
31#include <map>
32#include <memory>
33#include <utility>
34
35using namespace llvm;
36using namespace llvm::COFF;
37using namespace llvm::object;
38using namespace llvm::support;
39using namespace llvm::support::endian;
40using namespace lld;
41using namespace lld::coff;
42
43static const int SectorSize = 512;
44static const int DOSStubSize = 64;
45static const int NumberfOfDataDirectory = 16;
46
47namespace {
48
49class DebugDirectoryChunk : public Chunk {
50public:
51 DebugDirectoryChunk(const std::vector<Chunk *> &R) : Records(R) {}
52
53 size_t getSize() const override {
54 return Records.size() * sizeof(debug_directory);
55 }
56
57 void writeTo(uint8_t *B) const override {
58 auto *D = reinterpret_cast<debug_directory *>(B + OutputSectionOff);
59
60 for (const Chunk *Record : Records) {
61 D->Characteristics = 0;
62 D->TimeDateStamp = 0;
63 D->MajorVersion = 0;
64 D->MinorVersion = 0;
65 D->Type = COFF::IMAGE_DEBUG_TYPE_CODEVIEW;
66 D->SizeOfData = Record->getSize();
67 D->AddressOfRawData = Record->getRVA();
68 OutputSection *OS = Record->getOutputSection();
69 uint64_t Offs = OS->getFileOff() + (Record->getRVA() - OS->getRVA());
70 D->PointerToRawData = Offs;
71
72 ++D;
73 }
74 }
75
76private:
77 const std::vector<Chunk *> &Records;
78};
79
80class CVDebugRecordChunk : public Chunk {
81public:
82 CVDebugRecordChunk() {
83 PDBAbsPath = Config->PDBPath;
84 if (!PDBAbsPath.empty())
85 llvm::sys::fs::make_absolute(PDBAbsPath);
86 }
87
88 size_t getSize() const override {
89 return sizeof(codeview::DebugInfo) + PDBAbsPath.size() + 1;
90 }
91
92 void writeTo(uint8_t *B) const override {
93 // Save off the DebugInfo entry to backfill the file signature (build id)
94 // in Writer::writeBuildId
95 BuildId = reinterpret_cast<codeview::DebugInfo *>(B + OutputSectionOff);
96
97 // variable sized field (PDB Path)
98 char *P = reinterpret_cast<char *>(B + OutputSectionOff + sizeof(*BuildId));
99 if (!PDBAbsPath.empty())
100 memcpy(P, PDBAbsPath.data(), PDBAbsPath.size());
101 P[PDBAbsPath.size()] = '\0';
102 }
103
104 SmallString<128> PDBAbsPath;
105 mutable codeview::DebugInfo *BuildId = nullptr;
106};
107
108// The writer writes a SymbolTable result to a file.
109class Writer {
110public:
111 Writer() : Buffer(errorHandler().OutputBuffer) {}
112 void run();
113
114private:
115 void createSections();
116 void createMiscChunks();
117 void createImportTables();
118 void createExportTable();
119 void assignAddresses();
120 void removeEmptySections();
121 void createSymbolAndStringTable();
122 void openFile(StringRef OutputPath);
123 template <typename PEHeaderTy> void writeHeader();
124 void createSEHTable(OutputSection *RData);
125 void setSectionPermissions();
126 void writeSections();
127 void writeBuildId();
128 void sortExceptionTable();
129
130 llvm::Optional<coff_symbol16> createSymbol(Defined *D);
131 size_t addEntryToStringTable(StringRef Str);
132
133 OutputSection *findSection(StringRef Name);
134 OutputSection *createSection(StringRef Name);
135 void addBaserels(OutputSection *Dest);
136 void addBaserelBlocks(OutputSection *Dest, std::vector<Baserel> &V);
137
138 uint32_t getSizeOfInitializedData();
139 std::map<StringRef, std::vector<DefinedImportData *>> binImports();
140
141 std::unique_ptr<FileOutputBuffer> &Buffer;
142 std::vector<OutputSection *> OutputSections;
143 std::vector<char> Strtab;
144 std::vector<llvm::object::coff_symbol16> OutputSymtab;
145 IdataContents Idata;
146 DelayLoadContents DelayIdata;
147 EdataContents Edata;
148 SEHTableChunk *SEHTable = nullptr;
149
150 Chunk *DebugDirectory = nullptr;
151 std::vector<Chunk *> DebugRecords;
152 CVDebugRecordChunk *BuildId = nullptr;
153 Optional<codeview::DebugInfo> PreviousBuildId;
154 ArrayRef<uint8_t> SectionTable;
155
156 uint64_t FileSize;
157 uint32_t PointerToSymbolTable = 0;
158 uint64_t SizeOfImage;
159 uint64_t SizeOfHeaders;
160};
161} // anonymous namespace
162
163namespace lld {
164namespace coff {
165
166void writeResult() { Writer().run(); }
167
168void OutputSection::setRVA(uint64_t RVA) {
169 Header.VirtualAddress = RVA;
170 for (Chunk *C : Chunks)
171 C->setRVA(C->getRVA() + RVA);
172}
173
174void OutputSection::setFileOffset(uint64_t Off) {
175 // If a section has no actual data (i.e. BSS section), we want to
176 // set 0 to its PointerToRawData. Otherwise the output is rejected
177 // by the loader.
178 if (Header.SizeOfRawData == 0)
179 return;
180 Header.PointerToRawData = Off;
181}
182
183void OutputSection::addChunk(Chunk *C) {
184 Chunks.push_back(C);
185 C->setOutputSection(this);
186 uint64_t Off = Header.VirtualSize;
187 Off = alignTo(Off, C->Alignment);
188 C->setRVA(Off);
189 C->OutputSectionOff = Off;
190 Off += C->getSize();
191 if (Off > UINT32_MAX(4294967295U))
192 error("section larger than 4 GiB: " + Name);
193 Header.VirtualSize = Off;
194 if (C->hasData())
195 Header.SizeOfRawData = alignTo(Off, SectorSize);
196}
197
198void OutputSection::addPermissions(uint32_t C) {
199 Header.Characteristics |= C & PermMask;
200}
201
202void OutputSection::setPermissions(uint32_t C) {
203 Header.Characteristics = C & PermMask;
204}
205
206// Write the section header to a given buffer.
207void OutputSection::writeHeaderTo(uint8_t *Buf) {
208 auto *Hdr = reinterpret_cast<coff_section *>(Buf);
209 *Hdr = Header;
210 if (StringTableOff) {
211 // If name is too long, write offset into the string table as a name.
212 sprintf(Hdr->Name, "/%d", StringTableOff);
213 } else {
214 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-6.0~svn318882/tools/lld/COFF/Writer.cpp"
, 215, __extension__ __PRETTY_FUNCTION__))
215 (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-6.0~svn318882/tools/lld/COFF/Writer.cpp"
, 215, __extension__ __PRETTY_FUNCTION__))
;
216 strncpy(Hdr->Name, Name.data(),
217 std::min(Name.size(), (size_t)COFF::NameSize));
218 }
219}
220
221} // namespace coff
222} // namespace lld
223
224// PDBs are matched against executables using a build id which consists of three
225// components:
226// 1. A 16-bit GUID
227// 2. An age
228// 3. A time stamp.
229//
230// Debuggers and symbol servers match executables against debug info by checking
231// each of these components of the EXE/DLL against the corresponding value in
232// the PDB and failing a match if any of the components differ. In the case of
233// symbol servers, symbols are cached in a folder that is a function of the
234// GUID. As a result, in order to avoid symbol cache pollution where every
235// incremental build copies a new PDB to the symbol cache, we must try to re-use
236// the existing GUID if one exists, but bump the age. This way the match will
237// fail, so the symbol cache knows to use the new PDB, but the GUID matches, so
238// it overwrites the existing item in the symbol cache rather than making a new
239// one.
240static Optional<codeview::DebugInfo> loadExistingBuildId(StringRef Path) {
241 // We don't need to incrementally update a previous build id if we're not
242 // writing codeview debug info.
243 if (!Config->Debug)
244 return None;
245
246 auto ExpectedBinary = llvm::object::createBinary(Path);
247 if (!ExpectedBinary) {
248 consumeError(ExpectedBinary.takeError());
249 return None;
250 }
251
252 auto Binary = std::move(*ExpectedBinary);
253 if (!Binary.getBinary()->isCOFF())
254 return None;
255
256 std::error_code EC;
257 COFFObjectFile File(Binary.getBinary()->getMemoryBufferRef(), EC);
258 if (EC)
259 return None;
260
261 // If the machine of the binary we're outputting doesn't match the machine
262 // of the existing binary, don't try to re-use the build id.
263 if (File.is64() != Config->is64() || File.getMachine() != Config->Machine)
264 return None;
265
266 for (const auto &DebugDir : File.debug_directories()) {
267 if (DebugDir.Type != IMAGE_DEBUG_TYPE_CODEVIEW)
268 continue;
269
270 const codeview::DebugInfo *ExistingDI = nullptr;
271 StringRef PDBFileName;
272 if (auto EC = File.getDebugPDBInfo(ExistingDI, PDBFileName)) {
273 (void)EC;
274 return None;
275 }
276 // We only support writing PDBs in v70 format. So if this is not a build
277 // id that we recognize / support, ignore it.
278 if (ExistingDI->Signature.CVSignature != OMF::Signature::PDB70)
279 return None;
280 return *ExistingDI;
281 }
282 return None;
283}
284
285// The main function of the writer.
286void Writer::run() {
287 createSections();
288 createMiscChunks();
289 createImportTables();
290 createExportTable();
291 if (Config->Relocatable)
292 createSection(".reloc");
293 assignAddresses();
294 removeEmptySections();
295 setSectionPermissions();
296 createSymbolAndStringTable();
297
298 // We must do this before opening the output file, as it depends on being able
299 // to read the contents of the existing output file.
300 PreviousBuildId = loadExistingBuildId(Config->OutputFile);
301 openFile(Config->OutputFile);
302 if (Config->is64()) {
303 writeHeader<pe32plus_header>();
304 } else {
305 writeHeader<pe32_header>();
306 }
307 writeSections();
308 sortExceptionTable();
309 writeBuildId();
310
311 if (!Config->PDBPath.empty() && Config->Debug) {
312
313 assert(BuildId)(static_cast <bool> (BuildId) ? void (0) : __assert_fail
("BuildId", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/lld/COFF/Writer.cpp"
, 313, __extension__ __PRETTY_FUNCTION__))
;
314 createPDB(Symtab, OutputSections, SectionTable, *BuildId->BuildId);
315 }
316
317 writeMapFile(OutputSections);
318
319 if (auto E = Buffer->commit())
320 fatal("failed to write the output file: " + toString(std::move(E)));
321}
322
323static StringRef getOutputSection(StringRef Name) {
324 StringRef S = Name.split('$').first;
325 auto It = Config->Merge.find(S);
326 if (It == Config->Merge.end())
327 return S;
328 return It->second;
329}
330
331// Create output section objects and add them to OutputSections.
332void Writer::createSections() {
333 // First, bin chunks by name.
334 std::map<StringRef, std::vector<Chunk *>> Map;
335 for (Chunk *C : Symtab->getChunks()) {
336 auto *SC = dyn_cast<SectionChunk>(C);
337 if (SC && !SC->isLive()) {
338 if (Config->Verbose)
339 SC->printDiscardedMessage();
340 continue;
341 }
342 Map[C->getSectionName()].push_back(C);
343 }
344
345 // Then create an OutputSection for each section.
346 // '$' and all following characters in input section names are
347 // discarded when determining output section. So, .text$foo
348 // contributes to .text, for example. See PE/COFF spec 3.2.
349 SmallDenseMap<StringRef, OutputSection *> Sections;
350 for (auto Pair : Map) {
351 StringRef Name = getOutputSection(Pair.first);
352 OutputSection *&Sec = Sections[Name];
353 if (!Sec) {
354 Sec = make<OutputSection>(Name);
355 OutputSections.push_back(Sec);
356 }
357 std::vector<Chunk *> &Chunks = Pair.second;
358 for (Chunk *C : Chunks) {
359 Sec->addChunk(C);
360 Sec->addPermissions(C->getPermissions());
361 }
362 }
363}
364
365void Writer::createMiscChunks() {
366 OutputSection *RData = createSection(".rdata");
367
368 // Create thunks for locally-dllimported symbols.
369 if (!Symtab->LocalImportChunks.empty()) {
370 for (Chunk *C : Symtab->LocalImportChunks)
371 RData->addChunk(C);
372 }
373
374 // Create Debug Information Chunks
375 if (Config->Debug) {
376 DebugDirectory = make<DebugDirectoryChunk>(DebugRecords);
377
378 // Make a CVDebugRecordChunk even when /DEBUG:CV is not specified. We
379 // output a PDB no matter what, and this chunk provides the only means of
380 // allowing a debugger to match a PDB and an executable. So we need it even
381 // if we're ultimately not going to write CodeView data to the PDB.
382 auto *CVChunk = make<CVDebugRecordChunk>();
383 BuildId = CVChunk;
384 DebugRecords.push_back(CVChunk);
385
386 RData->addChunk(DebugDirectory);
387 for (Chunk *C : DebugRecords)
388 RData->addChunk(C);
389 }
390
391 createSEHTable(RData);
392}
393
394// Create .idata section for the DLL-imported symbol table.
395// The format of this section is inherently Windows-specific.
396// IdataContents class abstracted away the details for us,
397// so we just let it create chunks and add them to the section.
398void Writer::createImportTables() {
399 if (ImportFile::Instances.empty())
400 return;
401
402 // Initialize DLLOrder so that import entries are ordered in
403 // the same order as in the command line. (That affects DLL
404 // initialization order, and this ordering is MSVC-compatible.)
405 for (ImportFile *File : ImportFile::Instances) {
406 if (!File->Live)
407 continue;
408
409 std::string DLL = StringRef(File->DLLName).lower();
410 if (Config->DLLOrder.count(DLL) == 0)
411 Config->DLLOrder[DLL] = Config->DLLOrder.size();
412 }
413
414 OutputSection *Text = createSection(".text");
415 for (ImportFile *File : ImportFile::Instances) {
416 if (!File->Live)
417 continue;
418
419 if (DefinedImportThunk *Thunk = File->ThunkSym)
420 Text->addChunk(Thunk->getChunk());
421
422 if (Config->DelayLoads.count(StringRef(File->DLLName).lower())) {
423 if (!File->ThunkSym)
424 fatal("cannot delay-load " + toString(File) +
425 " due to import of data: " + toString(*File->ImpSym));
426 DelayIdata.add(File->ImpSym);
427 } else {
428 Idata.add(File->ImpSym);
429 }
430 }
431
432 if (!Idata.empty()) {
433 OutputSection *Sec = createSection(".idata");
434 for (Chunk *C : Idata.getChunks())
435 Sec->addChunk(C);
436 }
437
438 if (!DelayIdata.empty()) {
439 Defined *Helper = cast<Defined>(Config->DelayLoadHelper);
440 DelayIdata.create(Helper);
441 OutputSection *Sec = createSection(".didat");
442 for (Chunk *C : DelayIdata.getChunks())
443 Sec->addChunk(C);
444 Sec = createSection(".data");
445 for (Chunk *C : DelayIdata.getDataChunks())
446 Sec->addChunk(C);
447 Sec = createSection(".text");
448 for (Chunk *C : DelayIdata.getCodeChunks())
449 Sec->addChunk(C);
450 }
451}
452
453void Writer::createExportTable() {
454 if (Config->Exports.empty())
455 return;
456 OutputSection *Sec = createSection(".edata");
457 for (Chunk *C : Edata.Chunks)
458 Sec->addChunk(C);
459}
460
461// The Windows loader doesn't seem to like empty sections,
462// so we remove them if any.
463void Writer::removeEmptySections() {
464 auto IsEmpty = [](OutputSection *S) { return S->getVirtualSize() == 0; };
465 OutputSections.erase(
466 std::remove_if(OutputSections.begin(), OutputSections.end(), IsEmpty),
467 OutputSections.end());
468 uint32_t Idx = 1;
469 for (OutputSection *Sec : OutputSections)
470 Sec->SectionIndex = Idx++;
471}
472
473size_t Writer::addEntryToStringTable(StringRef Str) {
474 assert(Str.size() > COFF::NameSize)(static_cast <bool> (Str.size() > COFF::NameSize) ? void
(0) : __assert_fail ("Str.size() > COFF::NameSize", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/lld/COFF/Writer.cpp"
, 474, __extension__ __PRETTY_FUNCTION__))
;
475 size_t OffsetOfEntry = Strtab.size() + 4; // +4 for the size field
476 Strtab.insert(Strtab.end(), Str.begin(), Str.end());
477 Strtab.push_back('\0');
478 return OffsetOfEntry;
479}
480
481Optional<coff_symbol16> Writer::createSymbol(Defined *Def) {
482 // Relative symbols are unrepresentable in a COFF symbol table.
483 if (isa<DefinedSynthetic>(Def))
1
Taking false branch
484 return None;
485
486 // Don't write dead symbols or symbols in codeview sections to the symbol
487 // table.
488 if (!Def->isLive())
2
Assuming the condition is false
3
Taking false branch
489 return None;
490 if (auto *D = dyn_cast<DefinedRegular>(Def))
4
Taking false branch
491 if (D->getChunk()->isCodeView())
492 return None;
493
494 coff_symbol16 Sym;
495 StringRef Name = Def->getName();
496 if (Name.size() > COFF::NameSize) {
5
Assuming the condition is false
6
Taking false branch
497 Sym.Name.Offset.Zeroes = 0;
498 Sym.Name.Offset.Offset = addEntryToStringTable(Name);
499 } else {
500 memset(Sym.Name.ShortName, 0, COFF::NameSize);
501 memcpy(Sym.Name.ShortName, Name.data(), Name.size());
502 }
503
504 if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
7
Taking false branch
505 COFFSymbolRef Ref = D->getCOFFSymbol();
506 Sym.Type = Ref.getType();
507 Sym.StorageClass = Ref.getStorageClass();
508 } else {
509 Sym.Type = IMAGE_SYM_TYPE_NULL;
510 Sym.StorageClass = IMAGE_SYM_CLASS_EXTERNAL;
511 }
512 Sym.NumberOfAuxSymbols = 0;
513
514 switch (Def->kind()) {
8
Control jumps to the 'default' case at line 519
515 case Symbol::DefinedAbsoluteKind:
516 Sym.Value = Def->getRVA();
517 Sym.SectionNumber = IMAGE_SYM_ABSOLUTE;
518 break;
519 default: {
520 uint64_t RVA = Def->getRVA();
521 OutputSection *Sec = nullptr;
9
'Sec' initialized to a null pointer value
522 for (OutputSection *S : OutputSections) {
523 if (S->getRVA() > RVA)
524 break;
525 Sec = S;
526 }
527 Sym.Value = RVA - Sec->getRVA();
10
Called C++ object pointer is null
528 Sym.SectionNumber = Sec->SectionIndex;
529 break;
530 }
531 }
532 return Sym;
533}
534
535void Writer::createSymbolAndStringTable() {
536 // Name field in the section table is 8 byte long. Longer names need
537 // to be written to the string table. First, construct string table.
538 for (OutputSection *Sec : OutputSections) {
539 StringRef Name = Sec->getName();
540 if (Name.size() <= COFF::NameSize)
541 continue;
542 // If a section isn't discardable (i.e. will be mapped at runtime),
543 // prefer a truncated section name over a long section name in
544 // the string table that is unavailable at runtime. This is different from
545 // what link.exe does, but finding ".eh_fram" instead of "/4" is useful
546 // to libunwind.
547 if ((Sec->getPermissions() & IMAGE_SCN_MEM_DISCARDABLE) == 0)
548 continue;
549 Sec->setStringTableOff(addEntryToStringTable(Name));
550 }
551
552 if (Config->DebugDwarf) {
553 for (ObjFile *File : ObjFile::Instances) {
554 for (Symbol *B : File->getSymbols()) {
555 auto *D = dyn_cast_or_null<Defined>(B);
556 if (!D || D->WrittenToSymtab)
557 continue;
558 D->WrittenToSymtab = true;
559
560 if (Optional<coff_symbol16> Sym = createSymbol(D))
561 OutputSymtab.push_back(*Sym);
562 }
563 }
564 }
565
566 if (OutputSymtab.empty() && Strtab.empty())
567 return;
568
569 OutputSection *LastSection = OutputSections.back();
570 // We position the symbol table to be adjacent to the end of the last section.
571 uint64_t FileOff = LastSection->getFileOff() +
572 alignTo(LastSection->getRawSize(), SectorSize);
573 PointerToSymbolTable = FileOff;
574 FileOff += OutputSymtab.size() * sizeof(coff_symbol16);
575 FileOff += 4 + Strtab.size();
576 FileSize = alignTo(FileOff, SectorSize);
577}
578
579// Visits all sections to assign incremental, non-overlapping RVAs and
580// file offsets.
581void Writer::assignAddresses() {
582 SizeOfHeaders = DOSStubSize + sizeof(PEMagic) + sizeof(coff_file_header) +
583 sizeof(data_directory) * NumberfOfDataDirectory +
584 sizeof(coff_section) * OutputSections.size();
585 SizeOfHeaders +=
586 Config->is64() ? sizeof(pe32plus_header) : sizeof(pe32_header);
587 SizeOfHeaders = alignTo(SizeOfHeaders, SectorSize);
588 uint64_t RVA = 0x1000; // The first page is kept unmapped.
589 FileSize = SizeOfHeaders;
590 // Move DISCARDABLE (or non-memory-mapped) sections to the end of file because
591 // the loader cannot handle holes.
592 std::stable_partition(
593 OutputSections.begin(), OutputSections.end(), [](OutputSection *S) {
594 return (S->getPermissions() & IMAGE_SCN_MEM_DISCARDABLE) == 0;
595 });
596 for (OutputSection *Sec : OutputSections) {
597 if (Sec->getName() == ".reloc")
598 addBaserels(Sec);
599 Sec->setRVA(RVA);
600 Sec->setFileOffset(FileSize);
601 RVA += alignTo(Sec->getVirtualSize(), PageSize);
602 FileSize += alignTo(Sec->getRawSize(), SectorSize);
603 }
604 SizeOfImage = alignTo(RVA, PageSize);
605}
606
607template <typename PEHeaderTy> void Writer::writeHeader() {
608 // Write DOS stub
609 uint8_t *Buf = Buffer->getBufferStart();
610 auto *DOS = reinterpret_cast<dos_header *>(Buf);
611 Buf += DOSStubSize;
612 DOS->Magic[0] = 'M';
613 DOS->Magic[1] = 'Z';
614 DOS->AddressOfRelocationTable = sizeof(dos_header);
615 DOS->AddressOfNewExeHeader = DOSStubSize;
616
617 // Write PE magic
618 memcpy(Buf, PEMagic, sizeof(PEMagic));
619 Buf += sizeof(PEMagic);
620
621 // Write COFF header
622 auto *COFF = reinterpret_cast<coff_file_header *>(Buf);
623 Buf += sizeof(*COFF);
624 COFF->Machine = Config->Machine;
625 COFF->NumberOfSections = OutputSections.size();
626 COFF->Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE;
627 if (Config->LargeAddressAware)
628 COFF->Characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
629 if (!Config->is64())
630 COFF->Characteristics |= IMAGE_FILE_32BIT_MACHINE;
631 if (Config->DLL)
632 COFF->Characteristics |= IMAGE_FILE_DLL;
633 if (!Config->Relocatable)
634 COFF->Characteristics |= IMAGE_FILE_RELOCS_STRIPPED;
635 COFF->SizeOfOptionalHeader =
636 sizeof(PEHeaderTy) + sizeof(data_directory) * NumberfOfDataDirectory;
637
638 // Write PE header
639 auto *PE = reinterpret_cast<PEHeaderTy *>(Buf);
640 Buf += sizeof(*PE);
641 PE->Magic = Config->is64() ? PE32Header::PE32_PLUS : PE32Header::PE32;
642
643 // If {Major,Minor}LinkerVersion is left at 0.0, then for some
644 // reason signing the resulting PE file with Authenticode produces a
645 // signature that fails to validate on Windows 7 (but is OK on 10).
646 // Set it to 14.0, which is what VS2015 outputs, and which avoids
647 // that problem.
648 PE->MajorLinkerVersion = 14;
649 PE->MinorLinkerVersion = 0;
650
651 PE->ImageBase = Config->ImageBase;
652 PE->SectionAlignment = PageSize;
653 PE->FileAlignment = SectorSize;
654 PE->MajorImageVersion = Config->MajorImageVersion;
655 PE->MinorImageVersion = Config->MinorImageVersion;
656 PE->MajorOperatingSystemVersion = Config->MajorOSVersion;
657 PE->MinorOperatingSystemVersion = Config->MinorOSVersion;
658 PE->MajorSubsystemVersion = Config->MajorOSVersion;
659 PE->MinorSubsystemVersion = Config->MinorOSVersion;
660 PE->Subsystem = Config->Subsystem;
661 PE->SizeOfImage = SizeOfImage;
662 PE->SizeOfHeaders = SizeOfHeaders;
663 if (!Config->NoEntry) {
664 Defined *Entry = cast<Defined>(Config->Entry);
665 PE->AddressOfEntryPoint = Entry->getRVA();
666 // Pointer to thumb code must have the LSB set, so adjust it.
667 if (Config->Machine == ARMNT)
668 PE->AddressOfEntryPoint |= 1;
669 }
670 PE->SizeOfStackReserve = Config->StackReserve;
671 PE->SizeOfStackCommit = Config->StackCommit;
672 PE->SizeOfHeapReserve = Config->HeapReserve;
673 PE->SizeOfHeapCommit = Config->HeapCommit;
674 if (Config->AppContainer)
675 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_APPCONTAINER;
676 if (Config->DynamicBase)
677 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
678 if (Config->HighEntropyVA)
679 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA;
680 if (!Config->AllowBind)
681 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_BIND;
682 if (Config->NxCompat)
683 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
684 if (!Config->AllowIsolation)
685 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION;
686 if (Config->TerminalServerAware)
687 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE;
688 PE->NumberOfRvaAndSize = NumberfOfDataDirectory;
689 if (OutputSection *Text = findSection(".text")) {
690 PE->BaseOfCode = Text->getRVA();
691 PE->SizeOfCode = Text->getRawSize();
692 }
693 PE->SizeOfInitializedData = getSizeOfInitializedData();
694
695 // Write data directory
696 auto *Dir = reinterpret_cast<data_directory *>(Buf);
697 Buf += sizeof(*Dir) * NumberfOfDataDirectory;
698 if (OutputSection *Sec = findSection(".edata")) {
699 Dir[EXPORT_TABLE].RelativeVirtualAddress = Sec->getRVA();
700 Dir[EXPORT_TABLE].Size = Sec->getVirtualSize();
701 }
702 if (!Idata.empty()) {
703 Dir[IMPORT_TABLE].RelativeVirtualAddress = Idata.getDirRVA();
704 Dir[IMPORT_TABLE].Size = Idata.getDirSize();
705 Dir[IAT].RelativeVirtualAddress = Idata.getIATRVA();
706 Dir[IAT].Size = Idata.getIATSize();
707 }
708 if (OutputSection *Sec = findSection(".rsrc")) {
709 Dir[RESOURCE_TABLE].RelativeVirtualAddress = Sec->getRVA();
710 Dir[RESOURCE_TABLE].Size = Sec->getVirtualSize();
711 }
712 if (OutputSection *Sec = findSection(".pdata")) {
713 Dir[EXCEPTION_TABLE].RelativeVirtualAddress = Sec->getRVA();
714 Dir[EXCEPTION_TABLE].Size = Sec->getVirtualSize();
715 }
716 if (OutputSection *Sec = findSection(".reloc")) {
717 Dir[BASE_RELOCATION_TABLE].RelativeVirtualAddress = Sec->getRVA();
718 Dir[BASE_RELOCATION_TABLE].Size = Sec->getVirtualSize();
719 }
720 if (Symbol *Sym = Symtab->findUnderscore("_tls_used")) {
721 if (Defined *B = dyn_cast<Defined>(Sym)) {
722 Dir[TLS_TABLE].RelativeVirtualAddress = B->getRVA();
723 Dir[TLS_TABLE].Size = Config->is64()
724 ? sizeof(object::coff_tls_directory64)
725 : sizeof(object::coff_tls_directory32);
726 }
727 }
728 if (Config->Debug) {
729 Dir[DEBUG_DIRECTORY].RelativeVirtualAddress = DebugDirectory->getRVA();
730 Dir[DEBUG_DIRECTORY].Size = DebugDirectory->getSize();
731 }
732 if (Symbol *Sym = Symtab->findUnderscore("_load_config_used")) {
733 if (auto *B = dyn_cast<DefinedRegular>(Sym)) {
734 SectionChunk *SC = B->getChunk();
735 assert(B->getRVA() >= SC->getRVA())(static_cast <bool> (B->getRVA() >= SC->getRVA
()) ? void (0) : __assert_fail ("B->getRVA() >= SC->getRVA()"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/lld/COFF/Writer.cpp"
, 735, __extension__ __PRETTY_FUNCTION__))
;
736 uint64_t OffsetInChunk = B->getRVA() - SC->getRVA();
737 if (!SC->hasData() || OffsetInChunk + 4 > SC->getSize())
738 fatal("_load_config_used is malformed");
739
740 ArrayRef<uint8_t> SecContents = SC->getContents();
741 uint32_t LoadConfigSize =
742 *reinterpret_cast<const ulittle32_t *>(&SecContents[OffsetInChunk]);
743 if (OffsetInChunk + LoadConfigSize > SC->getSize())
744 fatal("_load_config_used is too large");
745 Dir[LOAD_CONFIG_TABLE].RelativeVirtualAddress = B->getRVA();
746 Dir[LOAD_CONFIG_TABLE].Size = LoadConfigSize;
747 }
748 }
749 if (!DelayIdata.empty()) {
750 Dir[DELAY_IMPORT_DESCRIPTOR].RelativeVirtualAddress =
751 DelayIdata.getDirRVA();
752 Dir[DELAY_IMPORT_DESCRIPTOR].Size = DelayIdata.getDirSize();
753 }
754
755 // Write section table
756 for (OutputSection *Sec : OutputSections) {
757 Sec->writeHeaderTo(Buf);
758 Buf += sizeof(coff_section);
759 }
760 SectionTable = ArrayRef<uint8_t>(
761 Buf - OutputSections.size() * sizeof(coff_section), Buf);
762
763 if (OutputSymtab.empty() && Strtab.empty())
764 return;
765
766 COFF->PointerToSymbolTable = PointerToSymbolTable;
767 uint32_t NumberOfSymbols = OutputSymtab.size();
768 COFF->NumberOfSymbols = NumberOfSymbols;
769 auto *SymbolTable = reinterpret_cast<coff_symbol16 *>(
770 Buffer->getBufferStart() + COFF->PointerToSymbolTable);
771 for (size_t I = 0; I != NumberOfSymbols; ++I)
772 SymbolTable[I] = OutputSymtab[I];
773 // Create the string table, it follows immediately after the symbol table.
774 // The first 4 bytes is length including itself.
775 Buf = reinterpret_cast<uint8_t *>(&SymbolTable[NumberOfSymbols]);
776 write32le(Buf, Strtab.size() + 4);
777 if (!Strtab.empty())
778 memcpy(Buf + 4, Strtab.data(), Strtab.size());
779}
780
781void Writer::openFile(StringRef Path) {
782 Buffer = check(
783 FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable),
784 "failed to open " + Path);
785}
786
787void Writer::createSEHTable(OutputSection *RData) {
788 // Create SEH table. x86-only.
789 if (Config->Machine != I386)
790 return;
791
792 std::set<Defined *> Handlers;
793
794 for (ObjFile *File : ObjFile::Instances) {
795 if (!File->SEHCompat)
796 return;
797 for (Symbol *B : File->SEHandlers) {
798 // Make sure the handler is still live.
799 if (B->isLive())
800 Handlers.insert(cast<Defined>(B));
801 }
802 }
803
804 if (Handlers.empty())
805 return;
806
807 SEHTable = make<SEHTableChunk>(Handlers);
808 RData->addChunk(SEHTable);
809
810 // Replace the absolute table symbol with a synthetic symbol pointing to the
811 // SEHTable chunk so that we can emit base relocations for it and resolve
812 // section relative relocations.
813 Symbol *T = Symtab->find("___safe_se_handler_table");
814 Symbol *C = Symtab->find("___safe_se_handler_count");
815 replaceSymbol<DefinedSynthetic>(T, T->getName(), SEHTable);
816 cast<DefinedAbsolute>(C)->setVA(SEHTable->getSize() / 4);
817}
818
819// Handles /section options to allow users to overwrite
820// section attributes.
821void Writer::setSectionPermissions() {
822 for (auto &P : Config->Section) {
823 StringRef Name = P.first;
824 uint32_t Perm = P.second;
825 if (auto *Sec = findSection(Name))
826 Sec->setPermissions(Perm);
827 }
828}
829
830// Write section contents to a mmap'ed file.
831void Writer::writeSections() {
832 // Record the section index that should be used when resolving a section
833 // relocation against an absolute symbol.
834 DefinedAbsolute::OutputSectionIndex = OutputSections.size() + 1;
835
836 uint8_t *Buf = Buffer->getBufferStart();
837 for (OutputSection *Sec : OutputSections) {
838 uint8_t *SecBuf = Buf + Sec->getFileOff();
839 // Fill gaps between functions in .text with INT3 instructions
840 // instead of leaving as NUL bytes (which can be interpreted as
841 // ADD instructions).
842 if (Sec->getPermissions() & IMAGE_SCN_CNT_CODE)
843 memset(SecBuf, 0xCC, Sec->getRawSize());
844 for_each(parallel::par, Sec->getChunks().begin(), Sec->getChunks().end(),
845 [&](Chunk *C) { C->writeTo(SecBuf); });
846 }
847}
848
849void Writer::writeBuildId() {
850 // If we're not writing a build id (e.g. because /debug is not specified),
851 // then just return;
852 if (!Config->Debug)
853 return;
854
855 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-6.0~svn318882/tools/lld/COFF/Writer.cpp"
, 855, __extension__ __PRETTY_FUNCTION__))
;
856
857 if (PreviousBuildId.hasValue()) {
858 *BuildId->BuildId = *PreviousBuildId;
859 BuildId->BuildId->PDB70.Age = BuildId->BuildId->PDB70.Age + 1;
860 return;
861 }
862
863 BuildId->BuildId->Signature.CVSignature = OMF::Signature::PDB70;
864 BuildId->BuildId->PDB70.Age = 1;
865 llvm::getRandomBytes(BuildId->BuildId->PDB70.Signature, 16);
866}
867
868// Sort .pdata section contents according to PE/COFF spec 5.5.
869void Writer::sortExceptionTable() {
870 OutputSection *Sec = findSection(".pdata");
871 if (!Sec)
872 return;
873 // We assume .pdata contains function table entries only.
874 uint8_t *Begin = Buffer->getBufferStart() + Sec->getFileOff();
875 uint8_t *End = Begin + Sec->getVirtualSize();
876 if (Config->Machine == AMD64) {
877 struct Entry { ulittle32_t Begin, End, Unwind; };
878 sort(parallel::par, (Entry *)Begin, (Entry *)End,
879 [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
880 return;
881 }
882 if (Config->Machine == ARMNT) {
883 struct Entry { ulittle32_t Begin, Unwind; };
884 sort(parallel::par, (Entry *)Begin, (Entry *)End,
885 [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
886 return;
887 }
888 errs() << "warning: don't know how to handle .pdata.\n";
889}
890
891OutputSection *Writer::findSection(StringRef Name) {
892 for (OutputSection *Sec : OutputSections)
893 if (Sec->getName() == Name)
894 return Sec;
895 return nullptr;
896}
897
898uint32_t Writer::getSizeOfInitializedData() {
899 uint32_t Res = 0;
900 for (OutputSection *S : OutputSections)
901 if (S->getPermissions() & IMAGE_SCN_CNT_INITIALIZED_DATA)
902 Res += S->getRawSize();
903 return Res;
904}
905
906// Returns an existing section or create a new one if not found.
907OutputSection *Writer::createSection(StringRef Name) {
908 if (auto *Sec = findSection(Name))
909 return Sec;
910 const auto DATA = IMAGE_SCN_CNT_INITIALIZED_DATA;
911 const auto BSS = IMAGE_SCN_CNT_UNINITIALIZED_DATA;
912 const auto CODE = IMAGE_SCN_CNT_CODE;
913 const auto DISCARDABLE = IMAGE_SCN_MEM_DISCARDABLE;
914 const auto R = IMAGE_SCN_MEM_READ;
915 const auto W = IMAGE_SCN_MEM_WRITE;
916 const auto X = IMAGE_SCN_MEM_EXECUTE;
917 uint32_t Perms = StringSwitch<uint32_t>(Name)
918 .Case(".bss", BSS | R | W)
919 .Case(".data", DATA | R | W)
920 .Cases(".didat", ".edata", ".idata", ".rdata", DATA | R)
921 .Case(".reloc", DATA | DISCARDABLE | R)
922 .Case(".text", CODE | R | X)
923 .Default(0);
924 if (!Perms)
925 llvm_unreachable("unknown section name")::llvm::llvm_unreachable_internal("unknown section name", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/lld/COFF/Writer.cpp"
, 925)
;
926 auto Sec = make<OutputSection>(Name);
927 Sec->addPermissions(Perms);
928 OutputSections.push_back(Sec);
929 return Sec;
930}
931
932// Dest is .reloc section. Add contents to that section.
933void Writer::addBaserels(OutputSection *Dest) {
934 std::vector<Baserel> V;
935 for (OutputSection *Sec : OutputSections) {
936 if (Sec == Dest)
937 continue;
938 // Collect all locations for base relocations.
939 for (Chunk *C : Sec->getChunks())
940 C->getBaserels(&V);
941 // Add the addresses to .reloc section.
942 if (!V.empty())
943 addBaserelBlocks(Dest, V);
944 V.clear();
945 }
946}
947
948// Add addresses to .reloc section. Note that addresses are grouped by page.
949void Writer::addBaserelBlocks(OutputSection *Dest, std::vector<Baserel> &V) {
950 const uint32_t Mask = ~uint32_t(PageSize - 1);
951 uint32_t Page = V[0].RVA & Mask;
952 size_t I = 0, J = 1;
953 for (size_t E = V.size(); J < E; ++J) {
954 uint32_t P = V[J].RVA & Mask;
955 if (P == Page)
956 continue;
957 Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));
958 I = J;
959 Page = P;
960 }
961 if (I == J)
962 return;
963 Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));
964}