1 //===- Writer.cpp ---------------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
13 #include "InputFiles.h"
16 #include "SymbolTable.h"
18 #include "lld/Common/ErrorHandler.h"
19 #include "lld/Common/Memory.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"
36 using namespace llvm::COFF;
37 using namespace llvm::object;
38 using namespace llvm::support;
39 using namespace llvm::support::endian;
41 using namespace lld::coff;
43 static const int SectorSize = 512;
44 static const int DOSStubSize = 64;
45 static const int NumberfOfDataDirectory = 16;
49 class DebugDirectoryChunk : public Chunk {
51 DebugDirectoryChunk(const std::vector<Chunk *> &R) : Records(R) {}
53 size_t getSize() const override {
54 return Records.size() * sizeof(debug_directory);
57 void writeTo(uint8_t *B) const override {
58 auto *D = reinterpret_cast<debug_directory *>(B + OutputSectionOff);
60 for (const Chunk *Record : Records) {
61 D->Characteristics = 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;
77 const std::vector<Chunk *> &Records;
80 class CVDebugRecordChunk : public Chunk {
82 CVDebugRecordChunk() {
83 PDBAbsPath = Config->PDBPath;
84 if (!PDBAbsPath.empty())
85 llvm::sys::fs::make_absolute(PDBAbsPath);
88 size_t getSize() const override {
89 return sizeof(codeview::DebugInfo) + PDBAbsPath.size() + 1;
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);
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';
104 SmallString<128> PDBAbsPath;
105 mutable codeview::DebugInfo *BuildId = nullptr;
108 // The writer writes a SymbolTable result to a file.
111 Writer() : Buffer(errorHandler().OutputBuffer) {}
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();
128 void sortExceptionTable();
130 llvm::Optional<coff_symbol16> createSymbol(Defined *D);
131 size_t addEntryToStringTable(StringRef Str);
133 OutputSection *findSection(StringRef Name);
134 OutputSection *createSection(StringRef Name);
135 void addBaserels(OutputSection *Dest);
136 void addBaserelBlocks(OutputSection *Dest, std::vector<Baserel> &V);
138 uint32_t getSizeOfInitializedData();
139 std::map<StringRef, std::vector<DefinedImportData *>> binImports();
141 std::unique_ptr<FileOutputBuffer> &Buffer;
142 std::vector<OutputSection *> OutputSections;
143 std::vector<char> Strtab;
144 std::vector<llvm::object::coff_symbol16> OutputSymtab;
146 DelayLoadContents DelayIdata;
148 SEHTableChunk *SEHTable = nullptr;
150 Chunk *DebugDirectory = nullptr;
151 std::vector<Chunk *> DebugRecords;
152 CVDebugRecordChunk *BuildId = nullptr;
153 Optional<codeview::DebugInfo> PreviousBuildId;
154 ArrayRef<uint8_t> SectionTable;
157 uint32_t PointerToSymbolTable = 0;
158 uint64_t SizeOfImage;
159 uint64_t SizeOfHeaders;
161 } // anonymous namespace
166 void writeResult() { Writer().run(); }
168 void OutputSection::setRVA(uint64_t RVA) {
169 Header.VirtualAddress = RVA;
170 for (Chunk *C : Chunks)
171 C->setRVA(C->getRVA() + RVA);
174 void 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
178 if (Header.SizeOfRawData == 0)
180 Header.PointerToRawData = Off;
183 void OutputSection::addChunk(Chunk *C) {
185 C->setOutputSection(this);
186 uint64_t Off = Header.VirtualSize;
187 Off = alignTo(Off, C->Alignment);
189 C->OutputSectionOff = Off;
191 if (Off > UINT32_MAX)
192 error("section larger than 4 GiB: " + Name);
193 Header.VirtualSize = Off;
195 Header.SizeOfRawData = alignTo(Off, SectorSize);
198 void OutputSection::addPermissions(uint32_t C) {
199 Header.Characteristics |= C & PermMask;
202 void OutputSection::setPermissions(uint32_t C) {
203 Header.Characteristics = C & PermMask;
206 // Write the section header to a given buffer.
207 void OutputSection::writeHeaderTo(uint8_t *Buf) {
208 auto *Hdr = reinterpret_cast<coff_section *>(Buf);
210 if (StringTableOff) {
211 // If name is too long, write offset into the string table as a name.
212 sprintf(Hdr->Name, "/%d", StringTableOff);
214 assert(!Config->Debug || Name.size() <= COFF::NameSize ||
215 (Hdr->Characteristics & IMAGE_SCN_MEM_DISCARDABLE) == 0);
216 strncpy(Hdr->Name, Name.data(),
217 std::min(Name.size(), (size_t)COFF::NameSize));
224 // PDBs are matched against executables using a build id which consists of three
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
240 static 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.
246 auto ExpectedBinary = llvm::object::createBinary(Path);
247 if (!ExpectedBinary) {
248 consumeError(ExpectedBinary.takeError());
252 auto Binary = std::move(*ExpectedBinary);
253 if (!Binary.getBinary()->isCOFF())
257 COFFObjectFile File(Binary.getBinary()->getMemoryBufferRef(), EC);
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)
266 for (const auto &DebugDir : File.debug_directories()) {
267 if (DebugDir.Type != IMAGE_DEBUG_TYPE_CODEVIEW)
270 const codeview::DebugInfo *ExistingDI = nullptr;
271 StringRef PDBFileName;
272 if (auto EC = File.getDebugPDBInfo(ExistingDI, PDBFileName)) {
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)
285 // The main function of the writer.
289 createImportTables();
291 if (Config->Relocatable)
292 createSection(".reloc");
294 removeEmptySections();
295 setSectionPermissions();
296 createSymbolAndStringTable();
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>();
305 writeHeader<pe32_header>();
308 sortExceptionTable();
311 if (!Config->PDBPath.empty() && Config->Debug) {
314 createPDB(Symtab, OutputSections, SectionTable, *BuildId->BuildId);
317 writeMapFile(OutputSections);
319 if (auto E = Buffer->commit())
320 fatal("failed to write the output file: " + toString(std::move(E)));
323 static StringRef getOutputSection(StringRef Name) {
324 StringRef S = Name.split('$').first;
326 // Treat a later period as a separator for MinGW, for sections like
328 S = S.substr(0, S.find('.', 1));
330 auto It = Config->Merge.find(S);
331 if (It == Config->Merge.end())
336 // Create output section objects and add them to OutputSections.
337 void Writer::createSections() {
338 // First, bin chunks by name.
339 std::map<StringRef, std::vector<Chunk *>> Map;
340 for (Chunk *C : Symtab->getChunks()) {
341 auto *SC = dyn_cast<SectionChunk>(C);
342 if (SC && !SC->isLive()) {
344 SC->printDiscardedMessage();
347 Map[C->getSectionName()].push_back(C);
350 // Then create an OutputSection for each section.
351 // '$' and all following characters in input section names are
352 // discarded when determining output section. So, .text$foo
353 // contributes to .text, for example. See PE/COFF spec 3.2.
354 SmallDenseMap<StringRef, OutputSection *> Sections;
355 for (auto Pair : Map) {
356 StringRef Name = getOutputSection(Pair.first);
357 OutputSection *&Sec = Sections[Name];
359 Sec = make<OutputSection>(Name);
360 OutputSections.push_back(Sec);
362 std::vector<Chunk *> &Chunks = Pair.second;
363 for (Chunk *C : Chunks) {
365 Sec->addPermissions(C->getPermissions());
370 void Writer::createMiscChunks() {
371 OutputSection *RData = createSection(".rdata");
373 // Create thunks for locally-dllimported symbols.
374 if (!Symtab->LocalImportChunks.empty()) {
375 for (Chunk *C : Symtab->LocalImportChunks)
379 // Create Debug Information Chunks
381 DebugDirectory = make<DebugDirectoryChunk>(DebugRecords);
383 // Make a CVDebugRecordChunk even when /DEBUG:CV is not specified. We
384 // output a PDB no matter what, and this chunk provides the only means of
385 // allowing a debugger to match a PDB and an executable. So we need it even
386 // if we're ultimately not going to write CodeView data to the PDB.
387 auto *CVChunk = make<CVDebugRecordChunk>();
389 DebugRecords.push_back(CVChunk);
391 RData->addChunk(DebugDirectory);
392 for (Chunk *C : DebugRecords)
396 createSEHTable(RData);
399 // Create .idata section for the DLL-imported symbol table.
400 // The format of this section is inherently Windows-specific.
401 // IdataContents class abstracted away the details for us,
402 // so we just let it create chunks and add them to the section.
403 void Writer::createImportTables() {
404 if (ImportFile::Instances.empty())
407 // Initialize DLLOrder so that import entries are ordered in
408 // the same order as in the command line. (That affects DLL
409 // initialization order, and this ordering is MSVC-compatible.)
410 for (ImportFile *File : ImportFile::Instances) {
414 std::string DLL = StringRef(File->DLLName).lower();
415 if (Config->DLLOrder.count(DLL) == 0)
416 Config->DLLOrder[DLL] = Config->DLLOrder.size();
419 OutputSection *Text = createSection(".text");
420 for (ImportFile *File : ImportFile::Instances) {
424 if (DefinedImportThunk *Thunk = File->ThunkSym)
425 Text->addChunk(Thunk->getChunk());
427 if (Config->DelayLoads.count(StringRef(File->DLLName).lower())) {
429 fatal("cannot delay-load " + toString(File) +
430 " due to import of data: " + toString(*File->ImpSym));
431 DelayIdata.add(File->ImpSym);
433 Idata.add(File->ImpSym);
437 if (!Idata.empty()) {
438 OutputSection *Sec = createSection(".idata");
439 for (Chunk *C : Idata.getChunks())
443 if (!DelayIdata.empty()) {
444 Defined *Helper = cast<Defined>(Config->DelayLoadHelper);
445 DelayIdata.create(Helper);
446 OutputSection *Sec = createSection(".didat");
447 for (Chunk *C : DelayIdata.getChunks())
449 Sec = createSection(".data");
450 for (Chunk *C : DelayIdata.getDataChunks())
452 Sec = createSection(".text");
453 for (Chunk *C : DelayIdata.getCodeChunks())
458 void Writer::createExportTable() {
459 if (Config->Exports.empty())
461 OutputSection *Sec = createSection(".edata");
462 for (Chunk *C : Edata.Chunks)
466 // The Windows loader doesn't seem to like empty sections,
467 // so we remove them if any.
468 void Writer::removeEmptySections() {
469 auto IsEmpty = [](OutputSection *S) { return S->getVirtualSize() == 0; };
470 OutputSections.erase(
471 std::remove_if(OutputSections.begin(), OutputSections.end(), IsEmpty),
472 OutputSections.end());
474 for (OutputSection *Sec : OutputSections)
475 Sec->SectionIndex = Idx++;
478 size_t Writer::addEntryToStringTable(StringRef Str) {
479 assert(Str.size() > COFF::NameSize);
480 size_t OffsetOfEntry = Strtab.size() + 4; // +4 for the size field
481 Strtab.insert(Strtab.end(), Str.begin(), Str.end());
482 Strtab.push_back('\0');
483 return OffsetOfEntry;
486 Optional<coff_symbol16> Writer::createSymbol(Defined *Def) {
487 // Relative symbols are unrepresentable in a COFF symbol table.
488 if (isa<DefinedSynthetic>(Def))
491 // Don't write dead symbols or symbols in codeview sections to the symbol
495 if (auto *D = dyn_cast<DefinedRegular>(Def))
496 if (D->getChunk()->isCodeView())
500 StringRef Name = Def->getName();
501 if (Name.size() > COFF::NameSize) {
502 Sym.Name.Offset.Zeroes = 0;
503 Sym.Name.Offset.Offset = addEntryToStringTable(Name);
505 memset(Sym.Name.ShortName, 0, COFF::NameSize);
506 memcpy(Sym.Name.ShortName, Name.data(), Name.size());
509 if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
510 COFFSymbolRef Ref = D->getCOFFSymbol();
511 Sym.Type = Ref.getType();
512 Sym.StorageClass = Ref.getStorageClass();
514 Sym.Type = IMAGE_SYM_TYPE_NULL;
515 Sym.StorageClass = IMAGE_SYM_CLASS_EXTERNAL;
517 Sym.NumberOfAuxSymbols = 0;
519 switch (Def->kind()) {
520 case Symbol::DefinedAbsoluteKind:
521 Sym.Value = Def->getRVA();
522 Sym.SectionNumber = IMAGE_SYM_ABSOLUTE;
525 uint64_t RVA = Def->getRVA();
526 OutputSection *Sec = nullptr;
527 for (OutputSection *S : OutputSections) {
528 if (S->getRVA() > RVA)
532 Sym.Value = RVA - Sec->getRVA();
533 Sym.SectionNumber = Sec->SectionIndex;
540 void Writer::createSymbolAndStringTable() {
541 // Name field in the section table is 8 byte long. Longer names need
542 // to be written to the string table. First, construct string table.
543 for (OutputSection *Sec : OutputSections) {
544 StringRef Name = Sec->getName();
545 if (Name.size() <= COFF::NameSize)
547 // If a section isn't discardable (i.e. will be mapped at runtime),
548 // prefer a truncated section name over a long section name in
549 // the string table that is unavailable at runtime. This is different from
550 // what link.exe does, but finding ".eh_fram" instead of "/4" is useful
552 if ((Sec->getPermissions() & IMAGE_SCN_MEM_DISCARDABLE) == 0)
554 Sec->setStringTableOff(addEntryToStringTable(Name));
557 if (Config->DebugDwarf) {
558 for (ObjFile *File : ObjFile::Instances) {
559 for (Symbol *B : File->getSymbols()) {
560 auto *D = dyn_cast_or_null<Defined>(B);
561 if (!D || D->WrittenToSymtab)
563 D->WrittenToSymtab = true;
565 if (Optional<coff_symbol16> Sym = createSymbol(D))
566 OutputSymtab.push_back(*Sym);
571 if (OutputSymtab.empty() && Strtab.empty())
574 OutputSection *LastSection = OutputSections.back();
575 // We position the symbol table to be adjacent to the end of the last section.
576 uint64_t FileOff = LastSection->getFileOff() +
577 alignTo(LastSection->getRawSize(), SectorSize);
578 PointerToSymbolTable = FileOff;
579 FileOff += OutputSymtab.size() * sizeof(coff_symbol16);
580 FileOff += 4 + Strtab.size();
581 FileSize = alignTo(FileOff, SectorSize);
584 // Visits all sections to assign incremental, non-overlapping RVAs and
586 void Writer::assignAddresses() {
587 SizeOfHeaders = DOSStubSize + sizeof(PEMagic) + sizeof(coff_file_header) +
588 sizeof(data_directory) * NumberfOfDataDirectory +
589 sizeof(coff_section) * OutputSections.size();
591 Config->is64() ? sizeof(pe32plus_header) : sizeof(pe32_header);
592 SizeOfHeaders = alignTo(SizeOfHeaders, SectorSize);
593 uint64_t RVA = 0x1000; // The first page is kept unmapped.
594 FileSize = SizeOfHeaders;
595 // Move DISCARDABLE (or non-memory-mapped) sections to the end of file because
596 // the loader cannot handle holes.
597 std::stable_partition(
598 OutputSections.begin(), OutputSections.end(), [](OutputSection *S) {
599 return (S->getPermissions() & IMAGE_SCN_MEM_DISCARDABLE) == 0;
601 for (OutputSection *Sec : OutputSections) {
602 if (Sec->getName() == ".reloc")
605 Sec->setFileOffset(FileSize);
606 RVA += alignTo(Sec->getVirtualSize(), PageSize);
607 FileSize += alignTo(Sec->getRawSize(), SectorSize);
609 SizeOfImage = alignTo(RVA, PageSize);
612 template <typename PEHeaderTy> void Writer::writeHeader() {
614 uint8_t *Buf = Buffer->getBufferStart();
615 auto *DOS = reinterpret_cast<dos_header *>(Buf);
619 DOS->AddressOfRelocationTable = sizeof(dos_header);
620 DOS->AddressOfNewExeHeader = DOSStubSize;
623 memcpy(Buf, PEMagic, sizeof(PEMagic));
624 Buf += sizeof(PEMagic);
627 auto *COFF = reinterpret_cast<coff_file_header *>(Buf);
628 Buf += sizeof(*COFF);
629 COFF->Machine = Config->Machine;
630 COFF->NumberOfSections = OutputSections.size();
631 COFF->Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE;
632 if (Config->LargeAddressAware)
633 COFF->Characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
635 COFF->Characteristics |= IMAGE_FILE_32BIT_MACHINE;
637 COFF->Characteristics |= IMAGE_FILE_DLL;
638 if (!Config->Relocatable)
639 COFF->Characteristics |= IMAGE_FILE_RELOCS_STRIPPED;
640 COFF->SizeOfOptionalHeader =
641 sizeof(PEHeaderTy) + sizeof(data_directory) * NumberfOfDataDirectory;
644 auto *PE = reinterpret_cast<PEHeaderTy *>(Buf);
646 PE->Magic = Config->is64() ? PE32Header::PE32_PLUS : PE32Header::PE32;
648 // If {Major,Minor}LinkerVersion is left at 0.0, then for some
649 // reason signing the resulting PE file with Authenticode produces a
650 // signature that fails to validate on Windows 7 (but is OK on 10).
651 // Set it to 14.0, which is what VS2015 outputs, and which avoids
653 PE->MajorLinkerVersion = 14;
654 PE->MinorLinkerVersion = 0;
656 PE->ImageBase = Config->ImageBase;
657 PE->SectionAlignment = PageSize;
658 PE->FileAlignment = SectorSize;
659 PE->MajorImageVersion = Config->MajorImageVersion;
660 PE->MinorImageVersion = Config->MinorImageVersion;
661 PE->MajorOperatingSystemVersion = Config->MajorOSVersion;
662 PE->MinorOperatingSystemVersion = Config->MinorOSVersion;
663 PE->MajorSubsystemVersion = Config->MajorOSVersion;
664 PE->MinorSubsystemVersion = Config->MinorOSVersion;
665 PE->Subsystem = Config->Subsystem;
666 PE->SizeOfImage = SizeOfImage;
667 PE->SizeOfHeaders = SizeOfHeaders;
668 if (!Config->NoEntry) {
669 Defined *Entry = cast<Defined>(Config->Entry);
670 PE->AddressOfEntryPoint = Entry->getRVA();
671 // Pointer to thumb code must have the LSB set, so adjust it.
672 if (Config->Machine == ARMNT)
673 PE->AddressOfEntryPoint |= 1;
675 PE->SizeOfStackReserve = Config->StackReserve;
676 PE->SizeOfStackCommit = Config->StackCommit;
677 PE->SizeOfHeapReserve = Config->HeapReserve;
678 PE->SizeOfHeapCommit = Config->HeapCommit;
679 if (Config->AppContainer)
680 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_APPCONTAINER;
681 if (Config->DynamicBase)
682 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
683 if (Config->HighEntropyVA)
684 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA;
685 if (!Config->AllowBind)
686 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_BIND;
687 if (Config->NxCompat)
688 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
689 if (!Config->AllowIsolation)
690 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION;
691 if (Config->Machine == I386 && !SEHTable &&
692 !Symtab->findUnderscore("_load_config_used"))
693 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_SEH;
694 if (Config->TerminalServerAware)
695 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE;
696 PE->NumberOfRvaAndSize = NumberfOfDataDirectory;
697 if (OutputSection *Text = findSection(".text")) {
698 PE->BaseOfCode = Text->getRVA();
699 PE->SizeOfCode = Text->getRawSize();
701 PE->SizeOfInitializedData = getSizeOfInitializedData();
703 // Write data directory
704 auto *Dir = reinterpret_cast<data_directory *>(Buf);
705 Buf += sizeof(*Dir) * NumberfOfDataDirectory;
706 if (OutputSection *Sec = findSection(".edata")) {
707 Dir[EXPORT_TABLE].RelativeVirtualAddress = Sec->getRVA();
708 Dir[EXPORT_TABLE].Size = Sec->getVirtualSize();
710 if (!Idata.empty()) {
711 Dir[IMPORT_TABLE].RelativeVirtualAddress = Idata.getDirRVA();
712 Dir[IMPORT_TABLE].Size = Idata.getDirSize();
713 Dir[IAT].RelativeVirtualAddress = Idata.getIATRVA();
714 Dir[IAT].Size = Idata.getIATSize();
716 if (OutputSection *Sec = findSection(".rsrc")) {
717 Dir[RESOURCE_TABLE].RelativeVirtualAddress = Sec->getRVA();
718 Dir[RESOURCE_TABLE].Size = Sec->getVirtualSize();
720 if (OutputSection *Sec = findSection(".pdata")) {
721 Dir[EXCEPTION_TABLE].RelativeVirtualAddress = Sec->getRVA();
722 Dir[EXCEPTION_TABLE].Size = Sec->getVirtualSize();
724 if (OutputSection *Sec = findSection(".reloc")) {
725 Dir[BASE_RELOCATION_TABLE].RelativeVirtualAddress = Sec->getRVA();
726 Dir[BASE_RELOCATION_TABLE].Size = Sec->getVirtualSize();
728 if (Symbol *Sym = Symtab->findUnderscore("_tls_used")) {
729 if (Defined *B = dyn_cast<Defined>(Sym)) {
730 Dir[TLS_TABLE].RelativeVirtualAddress = B->getRVA();
731 Dir[TLS_TABLE].Size = Config->is64()
732 ? sizeof(object::coff_tls_directory64)
733 : sizeof(object::coff_tls_directory32);
737 Dir[DEBUG_DIRECTORY].RelativeVirtualAddress = DebugDirectory->getRVA();
738 Dir[DEBUG_DIRECTORY].Size = DebugDirectory->getSize();
740 if (Symbol *Sym = Symtab->findUnderscore("_load_config_used")) {
741 if (auto *B = dyn_cast<DefinedRegular>(Sym)) {
742 SectionChunk *SC = B->getChunk();
743 assert(B->getRVA() >= SC->getRVA());
744 uint64_t OffsetInChunk = B->getRVA() - SC->getRVA();
745 if (!SC->hasData() || OffsetInChunk + 4 > SC->getSize())
746 fatal("_load_config_used is malformed");
748 ArrayRef<uint8_t> SecContents = SC->getContents();
749 uint32_t LoadConfigSize =
750 *reinterpret_cast<const ulittle32_t *>(&SecContents[OffsetInChunk]);
751 if (OffsetInChunk + LoadConfigSize > SC->getSize())
752 fatal("_load_config_used is too large");
753 Dir[LOAD_CONFIG_TABLE].RelativeVirtualAddress = B->getRVA();
754 Dir[LOAD_CONFIG_TABLE].Size = LoadConfigSize;
757 if (!DelayIdata.empty()) {
758 Dir[DELAY_IMPORT_DESCRIPTOR].RelativeVirtualAddress =
759 DelayIdata.getDirRVA();
760 Dir[DELAY_IMPORT_DESCRIPTOR].Size = DelayIdata.getDirSize();
763 // Write section table
764 for (OutputSection *Sec : OutputSections) {
765 Sec->writeHeaderTo(Buf);
766 Buf += sizeof(coff_section);
768 SectionTable = ArrayRef<uint8_t>(
769 Buf - OutputSections.size() * sizeof(coff_section), Buf);
771 if (OutputSymtab.empty() && Strtab.empty())
774 COFF->PointerToSymbolTable = PointerToSymbolTable;
775 uint32_t NumberOfSymbols = OutputSymtab.size();
776 COFF->NumberOfSymbols = NumberOfSymbols;
777 auto *SymbolTable = reinterpret_cast<coff_symbol16 *>(
778 Buffer->getBufferStart() + COFF->PointerToSymbolTable);
779 for (size_t I = 0; I != NumberOfSymbols; ++I)
780 SymbolTable[I] = OutputSymtab[I];
781 // Create the string table, it follows immediately after the symbol table.
782 // The first 4 bytes is length including itself.
783 Buf = reinterpret_cast<uint8_t *>(&SymbolTable[NumberOfSymbols]);
784 write32le(Buf, Strtab.size() + 4);
786 memcpy(Buf + 4, Strtab.data(), Strtab.size());
789 void Writer::openFile(StringRef Path) {
791 FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable),
792 "failed to open " + Path);
795 void Writer::createSEHTable(OutputSection *RData) {
796 // Create SEH table. x86-only.
797 if (Config->Machine != I386)
800 std::set<Defined *> Handlers;
802 for (ObjFile *File : ObjFile::Instances) {
803 if (!File->SEHCompat)
805 for (uint32_t I : File->SXData)
806 if (Symbol *B = File->getSymbol(I))
808 Handlers.insert(cast<Defined>(B));
811 if (Handlers.empty())
814 SEHTable = make<SEHTableChunk>(Handlers);
815 RData->addChunk(SEHTable);
817 // Replace the absolute table symbol with a synthetic symbol pointing to the
818 // SEHTable chunk so that we can emit base relocations for it and resolve
819 // section relative relocations.
820 Symbol *T = Symtab->find("___safe_se_handler_table");
821 Symbol *C = Symtab->find("___safe_se_handler_count");
822 replaceSymbol<DefinedSynthetic>(T, T->getName(), SEHTable);
823 cast<DefinedAbsolute>(C)->setVA(SEHTable->getSize() / 4);
826 // Handles /section options to allow users to overwrite
827 // section attributes.
828 void Writer::setSectionPermissions() {
829 for (auto &P : Config->Section) {
830 StringRef Name = P.first;
831 uint32_t Perm = P.second;
832 if (auto *Sec = findSection(Name))
833 Sec->setPermissions(Perm);
837 // Write section contents to a mmap'ed file.
838 void Writer::writeSections() {
839 // Record the section index that should be used when resolving a section
840 // relocation against an absolute symbol.
841 DefinedAbsolute::OutputSectionIndex = OutputSections.size() + 1;
843 uint8_t *Buf = Buffer->getBufferStart();
844 for (OutputSection *Sec : OutputSections) {
845 uint8_t *SecBuf = Buf + Sec->getFileOff();
846 // Fill gaps between functions in .text with INT3 instructions
847 // instead of leaving as NUL bytes (which can be interpreted as
848 // ADD instructions).
849 if (Sec->getPermissions() & IMAGE_SCN_CNT_CODE)
850 memset(SecBuf, 0xCC, Sec->getRawSize());
851 for_each(parallel::par, Sec->getChunks().begin(), Sec->getChunks().end(),
852 [&](Chunk *C) { C->writeTo(SecBuf); });
856 void Writer::writeBuildId() {
857 // If we're not writing a build id (e.g. because /debug is not specified),
862 assert(BuildId && "BuildId is not set!");
864 if (PreviousBuildId.hasValue()) {
865 *BuildId->BuildId = *PreviousBuildId;
866 BuildId->BuildId->PDB70.Age = BuildId->BuildId->PDB70.Age + 1;
870 BuildId->BuildId->Signature.CVSignature = OMF::Signature::PDB70;
871 BuildId->BuildId->PDB70.Age = 1;
872 llvm::getRandomBytes(BuildId->BuildId->PDB70.Signature, 16);
875 // Sort .pdata section contents according to PE/COFF spec 5.5.
876 void Writer::sortExceptionTable() {
877 OutputSection *Sec = findSection(".pdata");
880 // We assume .pdata contains function table entries only.
881 uint8_t *Begin = Buffer->getBufferStart() + Sec->getFileOff();
882 uint8_t *End = Begin + Sec->getVirtualSize();
883 if (Config->Machine == AMD64) {
884 struct Entry { ulittle32_t Begin, End, Unwind; };
885 sort(parallel::par, (Entry *)Begin, (Entry *)End,
886 [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
889 if (Config->Machine == ARMNT || Config->Machine == ARM64) {
890 struct Entry { ulittle32_t Begin, Unwind; };
891 sort(parallel::par, (Entry *)Begin, (Entry *)End,
892 [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
895 errs() << "warning: don't know how to handle .pdata.\n";
898 OutputSection *Writer::findSection(StringRef Name) {
899 for (OutputSection *Sec : OutputSections)
900 if (Sec->getName() == Name)
905 uint32_t Writer::getSizeOfInitializedData() {
907 for (OutputSection *S : OutputSections)
908 if (S->getPermissions() & IMAGE_SCN_CNT_INITIALIZED_DATA)
909 Res += S->getRawSize();
913 // Returns an existing section or create a new one if not found.
914 OutputSection *Writer::createSection(StringRef Name) {
915 if (auto *Sec = findSection(Name))
917 const auto DATA = IMAGE_SCN_CNT_INITIALIZED_DATA;
918 const auto BSS = IMAGE_SCN_CNT_UNINITIALIZED_DATA;
919 const auto CODE = IMAGE_SCN_CNT_CODE;
920 const auto DISCARDABLE = IMAGE_SCN_MEM_DISCARDABLE;
921 const auto R = IMAGE_SCN_MEM_READ;
922 const auto W = IMAGE_SCN_MEM_WRITE;
923 const auto X = IMAGE_SCN_MEM_EXECUTE;
924 uint32_t Perms = StringSwitch<uint32_t>(Name)
925 .Case(".bss", BSS | R | W)
926 .Case(".data", DATA | R | W)
927 .Cases(".didat", ".edata", ".idata", ".rdata", DATA | R)
928 .Case(".reloc", DATA | DISCARDABLE | R)
929 .Case(".text", CODE | R | X)
932 llvm_unreachable("unknown section name");
933 auto Sec = make<OutputSection>(Name);
934 Sec->addPermissions(Perms);
935 OutputSections.push_back(Sec);
939 // Dest is .reloc section. Add contents to that section.
940 void Writer::addBaserels(OutputSection *Dest) {
941 std::vector<Baserel> V;
942 for (OutputSection *Sec : OutputSections) {
945 // Collect all locations for base relocations.
946 for (Chunk *C : Sec->getChunks())
948 // Add the addresses to .reloc section.
950 addBaserelBlocks(Dest, V);
955 // Add addresses to .reloc section. Note that addresses are grouped by page.
956 void Writer::addBaserelBlocks(OutputSection *Dest, std::vector<Baserel> &V) {
957 const uint32_t Mask = ~uint32_t(PageSize - 1);
958 uint32_t Page = V[0].RVA & Mask;
960 for (size_t E = V.size(); J < E; ++J) {
961 uint32_t P = V[J].RVA & Mask;
964 Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));
970 Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));