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