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