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~svn301135/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~svn301135/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->AppContainer)
606 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_APPCONTAINER;
607 if (Config->DynamicBase)
608 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
609 if (Config->HighEntropyVA)
610 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA;
611 if (!Config->AllowBind)
612 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_BIND;
613 if (Config->NxCompat)
614 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
615 if (!Config->AllowIsolation)
616 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION;
617 if (Config->TerminalServerAware)
618 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE;
619 PE->NumberOfRvaAndSize = NumberfOfDataDirectory;
620 if (OutputSection *Text = findSection(".text")) {
621 PE->BaseOfCode = Text->getRVA();
622 PE->SizeOfCode = Text->getRawSize();
623 }
624 PE->SizeOfInitializedData = getSizeOfInitializedData();
625
626 // Write data directory
627 auto *Dir = reinterpret_cast<data_directory *>(Buf);
628 Buf += sizeof(*Dir) * NumberfOfDataDirectory;
629 if (OutputSection *Sec = findSection(".edata")) {
630 Dir[EXPORT_TABLE].RelativeVirtualAddress = Sec->getRVA();
631 Dir[EXPORT_TABLE].Size = Sec->getVirtualSize();
632 }
633 if (!Idata.empty()) {
634 Dir[IMPORT_TABLE].RelativeVirtualAddress = Idata.getDirRVA();
635 Dir[IMPORT_TABLE].Size = Idata.getDirSize();
636 Dir[IAT].RelativeVirtualAddress = Idata.getIATRVA();
637 Dir[IAT].Size = Idata.getIATSize();
638 }
639 if (OutputSection *Sec = findSection(".rsrc")) {
640 Dir[RESOURCE_TABLE].RelativeVirtualAddress = Sec->getRVA();
641 Dir[RESOURCE_TABLE].Size = Sec->getVirtualSize();
642 }
643 if (OutputSection *Sec = findSection(".pdata")) {
644 Dir[EXCEPTION_TABLE].RelativeVirtualAddress = Sec->getRVA();
645 Dir[EXCEPTION_TABLE].Size = Sec->getVirtualSize();
646 }
647 if (OutputSection *Sec = findSection(".reloc")) {
648 Dir[BASE_RELOCATION_TABLE].RelativeVirtualAddress = Sec->getRVA();
649 Dir[BASE_RELOCATION_TABLE].Size = Sec->getVirtualSize();
650 }
651 if (Symbol *Sym = Symtab->findUnderscore("_tls_used")) {
652 if (Defined *B = dyn_cast<Defined>(Sym->body())) {
653 Dir[TLS_TABLE].RelativeVirtualAddress = B->getRVA();
654 Dir[TLS_TABLE].Size = Config->is64()
655 ? sizeof(object::coff_tls_directory64)
656 : sizeof(object::coff_tls_directory32);
657 }
658 }
659 if (Config->Debug) {
660 Dir[DEBUG_DIRECTORY].RelativeVirtualAddress = DebugDirectory->getRVA();
661 Dir[DEBUG_DIRECTORY].Size = DebugDirectory->getSize();
662 }
663 if (Symbol *Sym = Symtab->findUnderscore("_load_config_used")) {
664 if (auto *B = dyn_cast<DefinedRegular>(Sym->body())) {
665 SectionChunk *SC = B->getChunk();
666 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~svn301135/tools/lld/COFF/Writer.cpp"
, 666, __PRETTY_FUNCTION__))
;
667 uint64_t OffsetInChunk = B->getRVA() - SC->getRVA();
668 if (!SC->hasData() || OffsetInChunk + 4 > SC->getSize())
669 fatal("_load_config_used is malformed");
670
671 ArrayRef<uint8_t> SecContents = SC->getContents();
672 uint32_t LoadConfigSize =
673 *reinterpret_cast<const ulittle32_t *>(&SecContents[OffsetInChunk]);
674 if (OffsetInChunk + LoadConfigSize > SC->getSize())
675 fatal("_load_config_used is too large");
676 Dir[LOAD_CONFIG_TABLE].RelativeVirtualAddress = B->getRVA();
677 Dir[LOAD_CONFIG_TABLE].Size = LoadConfigSize;
678 }
679 }
680 if (!DelayIdata.empty()) {
681 Dir[DELAY_IMPORT_DESCRIPTOR].RelativeVirtualAddress =
682 DelayIdata.getDirRVA();
683 Dir[DELAY_IMPORT_DESCRIPTOR].Size = DelayIdata.getDirSize();
684 }
685
686 // Write section table
687 for (OutputSection *Sec : OutputSections) {
688 Sec->writeHeaderTo(Buf);
689 Buf += sizeof(coff_section);
690 }
691 SectionTable = ArrayRef<uint8_t>(
692 Buf - OutputSections.size() * sizeof(coff_section), Buf);
693
694 if (OutputSymtab.empty())
695 return;
696
697 COFF->PointerToSymbolTable = PointerToSymbolTable;
698 uint32_t NumberOfSymbols = OutputSymtab.size();
699 COFF->NumberOfSymbols = NumberOfSymbols;
700 auto *SymbolTable = reinterpret_cast<coff_symbol16 *>(
701 Buffer->getBufferStart() + COFF->PointerToSymbolTable);
702 for (size_t I = 0; I != NumberOfSymbols; ++I)
703 SymbolTable[I] = OutputSymtab[I];
704 // Create the string table, it follows immediately after the symbol table.
705 // The first 4 bytes is length including itself.
706 Buf = reinterpret_cast<uint8_t *>(&SymbolTable[NumberOfSymbols]);
707 write32le(Buf, Strtab.size() + 4);
708 if (!Strtab.empty())
709 memcpy(Buf + 4, Strtab.data(), Strtab.size());
710}
711
712void Writer::openFile(StringRef Path) {
713 Buffer = check(
714 FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable),
715 "failed to open " + Path);
716}
717
718void Writer::fixSafeSEHSymbols() {
719 if (!SEHTable)
720 return;
721 if (auto *T = dyn_cast<DefinedRelative>(Config->SEHTable->body()))
722 T->setRVA(SEHTable->getRVA());
723 if (auto *C = dyn_cast<DefinedAbsolute>(Config->SEHCount->body()))
724 C->setVA(SEHTable->getSize() / 4);
725}
726
727// Handles /section options to allow users to overwrite
728// section attributes.
729void Writer::setSectionPermissions() {
730 for (auto &P : Config->Section) {
731 StringRef Name = P.first;
732 uint32_t Perm = P.second;
733 if (auto *Sec = findSection(Name))
734 Sec->setPermissions(Perm);
735 }
736}
737
738// Write section contents to a mmap'ed file.
739void Writer::writeSections() {
740 uint8_t *Buf = Buffer->getBufferStart();
741 for (OutputSection *Sec : OutputSections) {
742 uint8_t *SecBuf = Buf + Sec->getFileOff();
743 // Fill gaps between functions in .text with INT3 instructions
744 // instead of leaving as NUL bytes (which can be interpreted as
745 // ADD instructions).
746 if (Sec->getPermissions() & IMAGE_SCN_CNT_CODE)
747 memset(SecBuf, 0xCC, Sec->getRawSize());
748 parallel_for_each(Sec->getChunks().begin(), Sec->getChunks().end(),
749 [&](Chunk *C) { C->writeTo(SecBuf); });
750 }
751}
752
753// Sort .pdata section contents according to PE/COFF spec 5.5.
754void Writer::sortExceptionTable() {
755 OutputSection *Sec = findSection(".pdata");
756 if (!Sec)
757 return;
758 // We assume .pdata contains function table entries only.
759 uint8_t *Begin = Buffer->getBufferStart() + Sec->getFileOff();
760 uint8_t *End = Begin + Sec->getVirtualSize();
761 if (Config->Machine == AMD64) {
762 struct Entry { ulittle32_t Begin, End, Unwind; };
763 parallel_sort(
764 (Entry *)Begin, (Entry *)End,
765 [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
766 return;
767 }
768 if (Config->Machine == ARMNT) {
769 struct Entry { ulittle32_t Begin, Unwind; };
770 parallel_sort(
771 (Entry *)Begin, (Entry *)End,
772 [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
773 return;
774 }
775 errs() << "warning: don't know how to handle .pdata.\n";
776}
777
778// Backfill the CVSignature in a PDB70 Debug Record. This backfilling allows us
779// to get reproducible builds.
780void Writer::writeBuildId() {
781 // There is nothing to backfill if BuildId was not setup.
782 if (BuildId == nullptr)
783 return;
784
785 MD5 Hash;
786 MD5::MD5Result Res;
787
788 Hash.update(ArrayRef<uint8_t>{Buffer->getBufferStart(),
789 Buffer->getBufferEnd()});
790 Hash.final(Res);
791
792 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~svn301135/tools/lld/COFF/Writer.cpp"
, 793, __PRETTY_FUNCTION__))
793 "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~svn301135/tools/lld/COFF/Writer.cpp"
, 793, __PRETTY_FUNCTION__))
;
794 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~svn301135/tools/lld/COFF/Writer.cpp"
, 795, __PRETTY_FUNCTION__))
795 "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~svn301135/tools/lld/COFF/Writer.cpp"
, 795, __PRETTY_FUNCTION__))
;
796 memcpy(BuildId->DI->PDB70.Signature, Res.Bytes.data(),
797 sizeof(codeview::PDB70DebugInfo::Signature));
798 // TODO(compnerd) track the Age
799 BuildId->DI->PDB70.Age = 1;
800}
801
802OutputSection *Writer::findSection(StringRef Name) {
803 for (OutputSection *Sec : OutputSections)
804 if (Sec->getName() == Name)
805 return Sec;
806 return nullptr;
807}
808
809uint32_t Writer::getSizeOfInitializedData() {
810 uint32_t Res = 0;
811 for (OutputSection *S : OutputSections)
812 if (S->getPermissions() & IMAGE_SCN_CNT_INITIALIZED_DATA)
813 Res += S->getRawSize();
814 return Res;
815}
816
817// Returns an existing section or create a new one if not found.
818OutputSection *Writer::createSection(StringRef Name) {
819 if (auto *Sec = findSection(Name))
820 return Sec;
821 const auto DATA = IMAGE_SCN_CNT_INITIALIZED_DATA;
822 const auto BSS = IMAGE_SCN_CNT_UNINITIALIZED_DATA;
823 const auto CODE = IMAGE_SCN_CNT_CODE;
824 const auto DISCARDABLE = IMAGE_SCN_MEM_DISCARDABLE;
825 const auto R = IMAGE_SCN_MEM_READ;
826 const auto W = IMAGE_SCN_MEM_WRITE;
827 const auto X = IMAGE_SCN_MEM_EXECUTE;
828 uint32_t Perms = StringSwitch<uint32_t>(Name)
829 .Case(".bss", BSS | R | W)
830 .Case(".data", DATA | R | W)
831 .Cases(".didat", ".edata", ".idata", ".rdata", DATA | R)
832 .Case(".reloc", DATA | DISCARDABLE | R)
833 .Case(".text", CODE | R | X)
834 .Default(0);
835 if (!Perms)
836 llvm_unreachable("unknown section name")::llvm::llvm_unreachable_internal("unknown section name", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn301135/tools/lld/COFF/Writer.cpp"
, 836)
;
837 auto Sec = make<OutputSection>(Name);
838 Sec->addPermissions(Perms);
839 OutputSections.push_back(Sec);
840 return Sec;
841}
842
843// Dest is .reloc section. Add contents to that section.
844void Writer::addBaserels(OutputSection *Dest) {
845 std::vector<Baserel> V;
846 for (OutputSection *Sec : OutputSections) {
847 if (Sec == Dest)
848 continue;
849 // Collect all locations for base relocations.
850 for (Chunk *C : Sec->getChunks())
851 C->getBaserels(&V);
852 // Add the addresses to .reloc section.
853 if (!V.empty())
854 addBaserelBlocks(Dest, V);
855 V.clear();
856 }
857}
858
859// Add addresses to .reloc section. Note that addresses are grouped by page.
860void Writer::addBaserelBlocks(OutputSection *Dest, std::vector<Baserel> &V) {
861 const uint32_t Mask = ~uint32_t(PageSize - 1);
862 uint32_t Page = V[0].RVA & Mask;
863 size_t I = 0, J = 1;
864 for (size_t E = V.size(); J < E; ++J) {
865 uint32_t P = V[J].RVA & Mask;
866 if (P == Page)
867 continue;
868 Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));
869 I = J;
870 Page = P;
871 }
872 if (I == J)
873 return;
874 Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));
875}