Bug Summary

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