1 //===-- llvm/MC/WinCOFFObjectWriter.cpp -------------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains an implementation of a Win32 COFF object file writer. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/MC/MCWinCOFFObjectWriter.h" 15 #include "llvm/ADT/DenseMap.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/StringMap.h" 18 #include "llvm/ADT/StringRef.h" 19 #include "llvm/ADT/Twine.h" 20 #include "llvm/MC/MCAsmLayout.h" 21 #include "llvm/MC/MCAssembler.h" 22 #include "llvm/MC/MCContext.h" 23 #include "llvm/MC/MCExpr.h" 24 #include "llvm/MC/MCObjectWriter.h" 25 #include "llvm/MC/MCSection.h" 26 #include "llvm/MC/MCSectionCOFF.h" 27 #include "llvm/MC/MCSymbol.h" 28 #include "llvm/MC/MCValue.h" 29 #include "llvm/MC/StringTableBuilder.h" 30 #include "llvm/Support/COFF.h" 31 #include "llvm/Support/Debug.h" 32 #include "llvm/Support/Endian.h" 33 #include "llvm/Support/ErrorHandling.h" 34 #include "llvm/Support/TimeValue.h" 35 #include <cstdio> 36 37 using namespace llvm; 38 39 #define DEBUG_TYPE "WinCOFFObjectWriter" 40 41 namespace { 42 typedef SmallString<COFF::NameSize> name; 43 44 enum AuxiliaryType { 45 ATFunctionDefinition, 46 ATbfAndefSymbol, 47 ATWeakExternal, 48 ATFile, 49 ATSectionDefinition 50 }; 51 52 struct AuxSymbol { 53 AuxiliaryType AuxType; 54 COFF::Auxiliary Aux; 55 }; 56 57 class COFFSymbol; 58 class COFFSection; 59 60 class COFFSymbol { 61 public: 62 COFF::symbol Data; 63 64 typedef SmallVector<AuxSymbol, 1> AuxiliarySymbols; 65 66 name Name; 67 int Index; 68 AuxiliarySymbols Aux; 69 COFFSymbol *Other; 70 COFFSection *Section; 71 int Relocations; 72 73 MCSymbolData const *MCData; 74 75 COFFSymbol(StringRef name); 76 void set_name_offset(uint32_t Offset); 77 78 bool should_keep() const; 79 }; 80 81 // This class contains staging data for a COFF relocation entry. 82 struct COFFRelocation { 83 COFF::relocation Data; 84 COFFSymbol *Symb; 85 86 COFFRelocation() : Symb(nullptr) {} 87 static size_t size() { return COFF::RelocationSize; } 88 }; 89 90 typedef std::vector<COFFRelocation> relocations; 91 92 class COFFSection { 93 public: 94 COFF::section Header; 95 96 std::string Name; 97 int Number; 98 MCSectionData const *MCData; 99 COFFSymbol *Symbol; 100 relocations Relocations; 101 102 COFFSection(StringRef name); 103 static size_t size(); 104 }; 105 106 class WinCOFFObjectWriter : public MCObjectWriter { 107 public: 108 109 typedef std::vector<std::unique_ptr<COFFSymbol>> symbols; 110 typedef std::vector<std::unique_ptr<COFFSection>> sections; 111 112 typedef DenseMap<MCSymbol const *, COFFSymbol *> symbol_map; 113 typedef DenseMap<MCSection const *, COFFSection *> section_map; 114 115 std::unique_ptr<MCWinCOFFObjectTargetWriter> TargetObjectWriter; 116 117 // Root level file contents. 118 COFF::header Header; 119 sections Sections; 120 symbols Symbols; 121 StringTableBuilder Strings; 122 123 // Maps used during object file creation. 124 section_map SectionMap; 125 symbol_map SymbolMap; 126 127 bool UseBigObj; 128 129 WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW, raw_ostream &OS); 130 131 void reset() override { 132 memset(&Header, 0, sizeof(Header)); 133 Header.Machine = TargetObjectWriter->getMachine(); 134 Sections.clear(); 135 Symbols.clear(); 136 Strings.clear(); 137 SectionMap.clear(); 138 SymbolMap.clear(); 139 MCObjectWriter::reset(); 140 } 141 142 COFFSymbol *createSymbol(StringRef Name); 143 COFFSymbol *GetOrCreateCOFFSymbol(const MCSymbol * Symbol); 144 COFFSection *createSection(StringRef Name); 145 146 template <typename object_t, typename list_t> 147 object_t *createCOFFEntity(StringRef Name, list_t &List); 148 149 void DefineSection(MCSectionData const &SectionData); 150 void DefineSymbol(MCSymbolData const &SymbolData, MCAssembler &Assembler, 151 const MCAsmLayout &Layout); 152 153 void SetSymbolName(COFFSymbol &S); 154 void SetSectionName(COFFSection &S); 155 156 bool ExportSymbol(const MCSymbol &Symbol, MCAssembler &Asm); 157 158 bool IsPhysicalSection(COFFSection *S); 159 160 // Entity writing methods. 161 162 void WriteFileHeader(const COFF::header &Header); 163 void WriteSymbol(const COFFSymbol &S); 164 void WriteAuxiliarySymbols(const COFFSymbol::AuxiliarySymbols &S); 165 void WriteSectionHeader(const COFF::section &S); 166 void WriteRelocation(const COFF::relocation &R); 167 168 // MCObjectWriter interface implementation. 169 170 void ExecutePostLayoutBinding(MCAssembler &Asm, 171 const MCAsmLayout &Layout) override; 172 173 bool IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm, 174 const MCSymbolData &DataA, 175 const MCFragment &FB, bool InSet, 176 bool IsPCRel) const override; 177 178 void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout, 179 const MCFragment *Fragment, const MCFixup &Fixup, 180 MCValue Target, bool &IsPCRel, 181 uint64_t &FixedValue) override; 182 183 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override; 184 }; 185 } 186 187 static inline void write_uint32_le(void *Data, uint32_t Value) { 188 support::endian::write<uint32_t, support::little, support::unaligned>(Data, 189 Value); 190 } 191 192 //------------------------------------------------------------------------------ 193 // Symbol class implementation 194 195 COFFSymbol::COFFSymbol(StringRef name) 196 : Name(name.begin(), name.end()) 197 , Other(nullptr) 198 , Section(nullptr) 199 , Relocations(0) 200 , MCData(nullptr) { 201 memset(&Data, 0, sizeof(Data)); 202 } 203 204 // In the case that the name does not fit within 8 bytes, the offset 205 // into the string table is stored in the last 4 bytes instead, leaving 206 // the first 4 bytes as 0. 207 void COFFSymbol::set_name_offset(uint32_t Offset) { 208 write_uint32_le(Data.Name + 0, 0); 209 write_uint32_le(Data.Name + 4, Offset); 210 } 211 212 /// logic to decide if the symbol should be reported in the symbol table 213 bool COFFSymbol::should_keep() const { 214 // no section means its external, keep it 215 if (!Section) 216 return true; 217 218 // if it has relocations pointing at it, keep it 219 if (Relocations > 0) { 220 assert(Section->Number != -1 && "Sections with relocations must be real!"); 221 return true; 222 } 223 224 // if the section its in is being droped, drop it 225 if (Section->Number == -1) 226 return false; 227 228 // if it is the section symbol, keep it 229 if (Section->Symbol == this) 230 return true; 231 232 // if its temporary, drop it 233 if (MCData && MCData->getSymbol().isTemporary()) 234 return false; 235 236 // otherwise, keep it 237 return true; 238 } 239 240 //------------------------------------------------------------------------------ 241 // Section class implementation 242 243 COFFSection::COFFSection(StringRef name) 244 : Name(name) 245 , MCData(nullptr) 246 , Symbol(nullptr) { 247 memset(&Header, 0, sizeof(Header)); 248 } 249 250 size_t COFFSection::size() { 251 return COFF::SectionSize; 252 } 253 254 //------------------------------------------------------------------------------ 255 // WinCOFFObjectWriter class implementation 256 257 WinCOFFObjectWriter::WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW, 258 raw_ostream &OS) 259 : MCObjectWriter(OS, true), TargetObjectWriter(MOTW) { 260 memset(&Header, 0, sizeof(Header)); 261 262 Header.Machine = TargetObjectWriter->getMachine(); 263 } 264 265 COFFSymbol *WinCOFFObjectWriter::createSymbol(StringRef Name) { 266 return createCOFFEntity<COFFSymbol>(Name, Symbols); 267 } 268 269 COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(const MCSymbol *Symbol) { 270 symbol_map::iterator i = SymbolMap.find(Symbol); 271 if (i != SymbolMap.end()) 272 return i->second; 273 COFFSymbol *RetSymbol = 274 createCOFFEntity<COFFSymbol>(Symbol->getName(), Symbols); 275 SymbolMap[Symbol] = RetSymbol; 276 return RetSymbol; 277 } 278 279 COFFSection *WinCOFFObjectWriter::createSection(StringRef Name) { 280 return createCOFFEntity<COFFSection>(Name, Sections); 281 } 282 283 /// A template used to lookup or create a symbol/section, and initialize it if 284 /// needed. 285 template <typename object_t, typename list_t> 286 object_t *WinCOFFObjectWriter::createCOFFEntity(StringRef Name, 287 list_t &List) { 288 List.push_back(make_unique<object_t>(Name)); 289 290 return List.back().get(); 291 } 292 293 /// This function takes a section data object from the assembler 294 /// and creates the associated COFF section staging object. 295 void WinCOFFObjectWriter::DefineSection(MCSectionData const &SectionData) { 296 assert(SectionData.getSection().getVariant() == MCSection::SV_COFF 297 && "Got non-COFF section in the COFF backend!"); 298 // FIXME: Not sure how to verify this (at least in a debug build). 299 MCSectionCOFF const &Sec = 300 static_cast<MCSectionCOFF const &>(SectionData.getSection()); 301 302 COFFSection *coff_section = createSection(Sec.getSectionName()); 303 COFFSymbol *coff_symbol = createSymbol(Sec.getSectionName()); 304 if (Sec.getSelection() != COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) { 305 if (const MCSymbol *S = Sec.getCOMDATSymbol()) { 306 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(S); 307 if (COMDATSymbol->Section) 308 report_fatal_error("two sections have the same comdat"); 309 COMDATSymbol->Section = coff_section; 310 } 311 } 312 313 coff_section->Symbol = coff_symbol; 314 coff_symbol->Section = coff_section; 315 coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC; 316 317 // In this case the auxiliary symbol is a Section Definition. 318 coff_symbol->Aux.resize(1); 319 memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0])); 320 coff_symbol->Aux[0].AuxType = ATSectionDefinition; 321 coff_symbol->Aux[0].Aux.SectionDefinition.Selection = Sec.getSelection(); 322 323 coff_section->Header.Characteristics = Sec.getCharacteristics(); 324 325 uint32_t &Characteristics = coff_section->Header.Characteristics; 326 switch (SectionData.getAlignment()) { 327 case 1: Characteristics |= COFF::IMAGE_SCN_ALIGN_1BYTES; break; 328 case 2: Characteristics |= COFF::IMAGE_SCN_ALIGN_2BYTES; break; 329 case 4: Characteristics |= COFF::IMAGE_SCN_ALIGN_4BYTES; break; 330 case 8: Characteristics |= COFF::IMAGE_SCN_ALIGN_8BYTES; break; 331 case 16: Characteristics |= COFF::IMAGE_SCN_ALIGN_16BYTES; break; 332 case 32: Characteristics |= COFF::IMAGE_SCN_ALIGN_32BYTES; break; 333 case 64: Characteristics |= COFF::IMAGE_SCN_ALIGN_64BYTES; break; 334 case 128: Characteristics |= COFF::IMAGE_SCN_ALIGN_128BYTES; break; 335 case 256: Characteristics |= COFF::IMAGE_SCN_ALIGN_256BYTES; break; 336 case 512: Characteristics |= COFF::IMAGE_SCN_ALIGN_512BYTES; break; 337 case 1024: Characteristics |= COFF::IMAGE_SCN_ALIGN_1024BYTES; break; 338 case 2048: Characteristics |= COFF::IMAGE_SCN_ALIGN_2048BYTES; break; 339 case 4096: Characteristics |= COFF::IMAGE_SCN_ALIGN_4096BYTES; break; 340 case 8192: Characteristics |= COFF::IMAGE_SCN_ALIGN_8192BYTES; break; 341 default: 342 llvm_unreachable("unsupported section alignment"); 343 } 344 345 // Bind internal COFF section to MC section. 346 coff_section->MCData = &SectionData; 347 SectionMap[&SectionData.getSection()] = coff_section; 348 } 349 350 static uint64_t getSymbolValue(const MCSymbolData &Data, 351 const MCAsmLayout &Layout) { 352 if (Data.isCommon() && Data.isExternal()) 353 return Data.getCommonSize(); 354 355 uint64_t Res; 356 if (!Layout.getSymbolOffset(&Data, Res)) 357 return 0; 358 359 return Res; 360 } 361 362 /// This function takes a symbol data object from the assembler 363 /// and creates the associated COFF symbol staging object. 364 void WinCOFFObjectWriter::DefineSymbol(MCSymbolData const &SymbolData, 365 MCAssembler &Assembler, 366 const MCAsmLayout &Layout) { 367 MCSymbol const &Symbol = SymbolData.getSymbol(); 368 COFFSymbol *coff_symbol = GetOrCreateCOFFSymbol(&Symbol); 369 SymbolMap[&Symbol] = coff_symbol; 370 371 if (SymbolData.getFlags() & COFF::SF_WeakExternal) { 372 coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL; 373 374 if (Symbol.isVariable()) { 375 const MCSymbolRefExpr *SymRef = 376 dyn_cast<MCSymbolRefExpr>(Symbol.getVariableValue()); 377 378 if (!SymRef) 379 report_fatal_error("Weak externals may only alias symbols"); 380 381 coff_symbol->Other = GetOrCreateCOFFSymbol(&SymRef->getSymbol()); 382 } else { 383 std::string WeakName = std::string(".weak.") 384 + Symbol.getName().str() 385 + ".default"; 386 COFFSymbol *WeakDefault = createSymbol(WeakName); 387 WeakDefault->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE; 388 WeakDefault->Data.StorageClass = COFF::IMAGE_SYM_CLASS_EXTERNAL; 389 WeakDefault->Data.Type = 0; 390 WeakDefault->Data.Value = 0; 391 coff_symbol->Other = WeakDefault; 392 } 393 394 // Setup the Weak External auxiliary symbol. 395 coff_symbol->Aux.resize(1); 396 memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0])); 397 coff_symbol->Aux[0].AuxType = ATWeakExternal; 398 coff_symbol->Aux[0].Aux.WeakExternal.TagIndex = 0; 399 coff_symbol->Aux[0].Aux.WeakExternal.Characteristics = 400 COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY; 401 402 coff_symbol->MCData = &SymbolData; 403 } else { 404 const MCSymbolData &ResSymData = Assembler.getSymbolData(Symbol); 405 const MCSymbol *Base = Layout.getBaseSymbol(Symbol); 406 coff_symbol->Data.Value = getSymbolValue(ResSymData, Layout); 407 408 coff_symbol->Data.Type = (ResSymData.getFlags() & 0x0000FFFF) >> 0; 409 coff_symbol->Data.StorageClass = (ResSymData.getFlags() & 0x00FF0000) >> 16; 410 411 // If no storage class was specified in the streamer, define it here. 412 if (coff_symbol->Data.StorageClass == 0) { 413 bool IsExternal = 414 ResSymData.isExternal() || 415 (!ResSymData.getFragment() && !ResSymData.getSymbol().isVariable()); 416 417 coff_symbol->Data.StorageClass = IsExternal 418 ? COFF::IMAGE_SYM_CLASS_EXTERNAL 419 : COFF::IMAGE_SYM_CLASS_STATIC; 420 } 421 422 if (!Base) { 423 coff_symbol->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE; 424 } else { 425 const MCSymbolData &BaseData = Assembler.getSymbolData(*Base); 426 if (BaseData.getFragment()) { 427 COFFSection *Sec = 428 SectionMap[&BaseData.getFragment()->getParent()->getSection()]; 429 430 if (coff_symbol->Section && coff_symbol->Section != Sec) 431 report_fatal_error("conflicting sections for symbol"); 432 433 coff_symbol->Section = Sec; 434 } 435 } 436 437 coff_symbol->MCData = &ResSymData; 438 } 439 } 440 441 // Maximum offsets for different string table entry encodings. 442 static const unsigned Max6DecimalOffset = 999999; 443 static const unsigned Max7DecimalOffset = 9999999; 444 static const uint64_t MaxBase64Offset = 0xFFFFFFFFFULL; // 64^6, including 0 445 446 // Encode a string table entry offset in base 64, padded to 6 chars, and 447 // prefixed with a double slash: '//AAAAAA', '//AAAAAB', ... 448 // Buffer must be at least 8 bytes large. No terminating null appended. 449 static void encodeBase64StringEntry(char* Buffer, uint64_t Value) { 450 assert(Value > Max7DecimalOffset && Value <= MaxBase64Offset && 451 "Illegal section name encoding for value"); 452 453 static const char Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 454 "abcdefghijklmnopqrstuvwxyz" 455 "0123456789+/"; 456 457 Buffer[0] = '/'; 458 Buffer[1] = '/'; 459 460 char* Ptr = Buffer + 7; 461 for (unsigned i = 0; i < 6; ++i) { 462 unsigned Rem = Value % 64; 463 Value /= 64; 464 *(Ptr--) = Alphabet[Rem]; 465 } 466 } 467 468 void WinCOFFObjectWriter::SetSectionName(COFFSection &S) { 469 if (S.Name.size() > COFF::NameSize) { 470 uint64_t StringTableEntry = Strings.getOffset(S.Name); 471 472 if (StringTableEntry <= Max6DecimalOffset) { 473 std::sprintf(S.Header.Name, "/%d", unsigned(StringTableEntry)); 474 } else if (StringTableEntry <= Max7DecimalOffset) { 475 // With seven digits, we have to skip the terminating null. Because 476 // sprintf always appends it, we use a larger temporary buffer. 477 char buffer[9] = { }; 478 std::sprintf(buffer, "/%d", unsigned(StringTableEntry)); 479 std::memcpy(S.Header.Name, buffer, 8); 480 } else if (StringTableEntry <= MaxBase64Offset) { 481 // Starting with 10,000,000, offsets are encoded as base64. 482 encodeBase64StringEntry(S.Header.Name, StringTableEntry); 483 } else { 484 report_fatal_error("COFF string table is greater than 64 GB."); 485 } 486 } else 487 std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size()); 488 } 489 490 void WinCOFFObjectWriter::SetSymbolName(COFFSymbol &S) { 491 if (S.Name.size() > COFF::NameSize) 492 S.set_name_offset(Strings.getOffset(S.Name)); 493 else 494 std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size()); 495 } 496 497 bool WinCOFFObjectWriter::ExportSymbol(const MCSymbol &Symbol, 498 MCAssembler &Asm) { 499 // This doesn't seem to be right. Strings referred to from the .data section 500 // need symbols so they can be linked to code in the .text section right? 501 502 // return Asm.isSymbolLinkerVisible(Symbol); 503 504 // Non-temporary labels should always be visible to the linker. 505 if (!Symbol.isTemporary()) 506 return true; 507 508 // Absolute temporary labels are never visible. 509 if (!Symbol.isInSection()) 510 return false; 511 512 // For now, all non-variable symbols are exported, 513 // the linker will sort the rest out for us. 514 return !Symbol.isVariable(); 515 } 516 517 bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) { 518 return (S->Header.Characteristics 519 & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0; 520 } 521 522 //------------------------------------------------------------------------------ 523 // entity writing methods 524 525 void WinCOFFObjectWriter::WriteFileHeader(const COFF::header &Header) { 526 if (UseBigObj) { 527 WriteLE16(COFF::IMAGE_FILE_MACHINE_UNKNOWN); 528 WriteLE16(0xFFFF); 529 WriteLE16(COFF::BigObjHeader::MinBigObjectVersion); 530 WriteLE16(Header.Machine); 531 WriteLE32(Header.TimeDateStamp); 532 for (uint8_t MagicChar : COFF::BigObjMagic) 533 Write8(MagicChar); 534 WriteLE32(0); 535 WriteLE32(0); 536 WriteLE32(0); 537 WriteLE32(0); 538 WriteLE32(Header.NumberOfSections); 539 WriteLE32(Header.PointerToSymbolTable); 540 WriteLE32(Header.NumberOfSymbols); 541 } else { 542 WriteLE16(Header.Machine); 543 WriteLE16(static_cast<int16_t>(Header.NumberOfSections)); 544 WriteLE32(Header.TimeDateStamp); 545 WriteLE32(Header.PointerToSymbolTable); 546 WriteLE32(Header.NumberOfSymbols); 547 WriteLE16(Header.SizeOfOptionalHeader); 548 WriteLE16(Header.Characteristics); 549 } 550 } 551 552 void WinCOFFObjectWriter::WriteSymbol(const COFFSymbol &S) { 553 WriteBytes(StringRef(S.Data.Name, COFF::NameSize)); 554 WriteLE32(S.Data.Value); 555 if (UseBigObj) 556 WriteLE32(S.Data.SectionNumber); 557 else 558 WriteLE16(static_cast<int16_t>(S.Data.SectionNumber)); 559 WriteLE16(S.Data.Type); 560 Write8(S.Data.StorageClass); 561 Write8(S.Data.NumberOfAuxSymbols); 562 WriteAuxiliarySymbols(S.Aux); 563 } 564 565 void WinCOFFObjectWriter::WriteAuxiliarySymbols( 566 const COFFSymbol::AuxiliarySymbols &S) { 567 for(COFFSymbol::AuxiliarySymbols::const_iterator i = S.begin(), e = S.end(); 568 i != e; ++i) { 569 switch(i->AuxType) { 570 case ATFunctionDefinition: 571 WriteLE32(i->Aux.FunctionDefinition.TagIndex); 572 WriteLE32(i->Aux.FunctionDefinition.TotalSize); 573 WriteLE32(i->Aux.FunctionDefinition.PointerToLinenumber); 574 WriteLE32(i->Aux.FunctionDefinition.PointerToNextFunction); 575 WriteZeros(sizeof(i->Aux.FunctionDefinition.unused)); 576 if (UseBigObj) 577 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size); 578 break; 579 case ATbfAndefSymbol: 580 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused1)); 581 WriteLE16(i->Aux.bfAndefSymbol.Linenumber); 582 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused2)); 583 WriteLE32(i->Aux.bfAndefSymbol.PointerToNextFunction); 584 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused3)); 585 if (UseBigObj) 586 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size); 587 break; 588 case ATWeakExternal: 589 WriteLE32(i->Aux.WeakExternal.TagIndex); 590 WriteLE32(i->Aux.WeakExternal.Characteristics); 591 WriteZeros(sizeof(i->Aux.WeakExternal.unused)); 592 if (UseBigObj) 593 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size); 594 break; 595 case ATFile: 596 WriteBytes( 597 StringRef(reinterpret_cast<const char *>(&i->Aux), 598 UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size)); 599 break; 600 case ATSectionDefinition: 601 WriteLE32(i->Aux.SectionDefinition.Length); 602 WriteLE16(i->Aux.SectionDefinition.NumberOfRelocations); 603 WriteLE16(i->Aux.SectionDefinition.NumberOfLinenumbers); 604 WriteLE32(i->Aux.SectionDefinition.CheckSum); 605 WriteLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number)); 606 Write8(i->Aux.SectionDefinition.Selection); 607 WriteZeros(sizeof(i->Aux.SectionDefinition.unused)); 608 WriteLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number >> 16)); 609 if (UseBigObj) 610 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size); 611 break; 612 } 613 } 614 } 615 616 void WinCOFFObjectWriter::WriteSectionHeader(const COFF::section &S) { 617 WriteBytes(StringRef(S.Name, COFF::NameSize)); 618 619 WriteLE32(S.VirtualSize); 620 WriteLE32(S.VirtualAddress); 621 WriteLE32(S.SizeOfRawData); 622 WriteLE32(S.PointerToRawData); 623 WriteLE32(S.PointerToRelocations); 624 WriteLE32(S.PointerToLineNumbers); 625 WriteLE16(S.NumberOfRelocations); 626 WriteLE16(S.NumberOfLineNumbers); 627 WriteLE32(S.Characteristics); 628 } 629 630 void WinCOFFObjectWriter::WriteRelocation(const COFF::relocation &R) { 631 WriteLE32(R.VirtualAddress); 632 WriteLE32(R.SymbolTableIndex); 633 WriteLE16(R.Type); 634 } 635 636 //////////////////////////////////////////////////////////////////////////////// 637 // MCObjectWriter interface implementations 638 639 void WinCOFFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm, 640 const MCAsmLayout &Layout) { 641 // "Define" each section & symbol. This creates section & symbol 642 // entries in the staging area. 643 for (const auto &Section : Asm) 644 DefineSection(Section); 645 646 for (MCSymbolData &SD : Asm.symbols()) 647 if (ExportSymbol(SD.getSymbol(), Asm)) 648 DefineSymbol(SD, Asm, Layout); 649 } 650 651 bool WinCOFFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl( 652 const MCAssembler &Asm, const MCSymbolData &DataA, const MCFragment &FB, 653 bool InSet, bool IsPCRel) const { 654 // MS LINK expects to be able to replace all references to a function with a 655 // thunk to implement their /INCREMENTAL feature. Make sure we don't optimize 656 // away any relocations to functions. 657 if ((((DataA.getFlags() & COFF::SF_TypeMask) >> COFF::SF_TypeShift) >> 658 COFF::SCT_COMPLEX_TYPE_SHIFT) == COFF::IMAGE_SYM_DTYPE_FUNCTION) 659 return false; 660 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(Asm, DataA, FB, 661 InSet, IsPCRel); 662 } 663 664 void WinCOFFObjectWriter::RecordRelocation( 665 MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment *Fragment, 666 const MCFixup &Fixup, MCValue Target, bool &IsPCRel, uint64_t &FixedValue) { 667 assert(Target.getSymA() && "Relocation must reference a symbol!"); 668 669 const MCSymbol &Symbol = Target.getSymA()->getSymbol(); 670 const MCSymbol &A = Symbol.AliasedSymbol(); 671 if (!Asm.hasSymbolData(A)) 672 Asm.getContext().FatalError( 673 Fixup.getLoc(), 674 Twine("symbol '") + A.getName() + "' can not be undefined"); 675 676 const MCSymbolData &A_SD = Asm.getSymbolData(A); 677 678 MCSectionData const *SectionData = Fragment->getParent(); 679 680 // Mark this symbol as requiring an entry in the symbol table. 681 assert(SectionMap.find(&SectionData->getSection()) != SectionMap.end() && 682 "Section must already have been defined in ExecutePostLayoutBinding!"); 683 assert(SymbolMap.find(&A_SD.getSymbol()) != SymbolMap.end() && 684 "Symbol must already have been defined in ExecutePostLayoutBinding!"); 685 686 COFFSection *coff_section = SectionMap[&SectionData->getSection()]; 687 COFFSymbol *coff_symbol = SymbolMap[&A_SD.getSymbol()]; 688 const MCSymbolRefExpr *SymB = Target.getSymB(); 689 bool CrossSection = false; 690 691 if (SymB) { 692 const MCSymbol *B = &SymB->getSymbol(); 693 const MCSymbolData &B_SD = Asm.getSymbolData(*B); 694 if (!B_SD.getFragment()) 695 Asm.getContext().FatalError( 696 Fixup.getLoc(), 697 Twine("symbol '") + B->getName() + 698 "' can not be undefined in a subtraction expression"); 699 700 if (!A_SD.getFragment()) 701 Asm.getContext().FatalError( 702 Fixup.getLoc(), 703 Twine("symbol '") + Symbol.getName() + 704 "' can not be undefined in a subtraction expression"); 705 706 CrossSection = &Symbol.getSection() != &B->getSection(); 707 708 // Offset of the symbol in the section 709 int64_t OffsetOfB = Layout.getSymbolOffset(&B_SD); 710 711 // In the case where we have SymbA and SymB, we just need to store the delta 712 // between the two symbols. Update FixedValue to account for the delta, and 713 // skip recording the relocation. 714 if (!CrossSection) { 715 int64_t OffsetOfA = Layout.getSymbolOffset(&A_SD); 716 FixedValue = (OffsetOfA - OffsetOfB) + Target.getConstant(); 717 return; 718 } 719 720 // Offset of the relocation in the section 721 int64_t OffsetOfRelocation = 722 Layout.getFragmentOffset(Fragment) + Fixup.getOffset(); 723 724 FixedValue = OffsetOfRelocation - OffsetOfB; 725 } else { 726 FixedValue = Target.getConstant(); 727 } 728 729 COFFRelocation Reloc; 730 731 Reloc.Data.SymbolTableIndex = 0; 732 Reloc.Data.VirtualAddress = Layout.getFragmentOffset(Fragment); 733 734 // Turn relocations for temporary symbols into section relocations. 735 if (coff_symbol->MCData->getSymbol().isTemporary() || CrossSection) { 736 Reloc.Symb = coff_symbol->Section->Symbol; 737 FixedValue += Layout.getFragmentOffset(coff_symbol->MCData->getFragment()) + 738 coff_symbol->MCData->getOffset(); 739 } else 740 Reloc.Symb = coff_symbol; 741 742 ++Reloc.Symb->Relocations; 743 744 Reloc.Data.VirtualAddress += Fixup.getOffset(); 745 Reloc.Data.Type = 746 TargetObjectWriter->getRelocType(Target, Fixup, CrossSection, 747 Asm.getBackend()); 748 749 // FIXME: Can anyone explain what this does other than adjust for the size 750 // of the offset? 751 if ((Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64 && 752 Reloc.Data.Type == COFF::IMAGE_REL_AMD64_REL32) || 753 (Header.Machine == COFF::IMAGE_FILE_MACHINE_I386 && 754 Reloc.Data.Type == COFF::IMAGE_REL_I386_REL32)) 755 FixedValue += 4; 756 757 if (Header.Machine == COFF::IMAGE_FILE_MACHINE_ARMNT) { 758 switch (Reloc.Data.Type) { 759 case COFF::IMAGE_REL_ARM_ABSOLUTE: 760 case COFF::IMAGE_REL_ARM_ADDR32: 761 case COFF::IMAGE_REL_ARM_ADDR32NB: 762 case COFF::IMAGE_REL_ARM_TOKEN: 763 case COFF::IMAGE_REL_ARM_SECTION: 764 case COFF::IMAGE_REL_ARM_SECREL: 765 break; 766 case COFF::IMAGE_REL_ARM_BRANCH11: 767 case COFF::IMAGE_REL_ARM_BLX11: 768 // IMAGE_REL_ARM_BRANCH11 and IMAGE_REL_ARM_BLX11 are only used for 769 // pre-ARMv7, which implicitly rules it out of ARMNT (it would be valid 770 // for Windows CE). 771 case COFF::IMAGE_REL_ARM_BRANCH24: 772 case COFF::IMAGE_REL_ARM_BLX24: 773 case COFF::IMAGE_REL_ARM_MOV32A: 774 // IMAGE_REL_ARM_BRANCH24, IMAGE_REL_ARM_BLX24, IMAGE_REL_ARM_MOV32A are 775 // only used for ARM mode code, which is documented as being unsupported 776 // by Windows on ARM. Empirical proof indicates that masm is able to 777 // generate the relocations however the rest of the MSVC toolchain is 778 // unable to handle it. 779 llvm_unreachable("unsupported relocation"); 780 break; 781 case COFF::IMAGE_REL_ARM_MOV32T: 782 break; 783 case COFF::IMAGE_REL_ARM_BRANCH20T: 784 case COFF::IMAGE_REL_ARM_BRANCH24T: 785 case COFF::IMAGE_REL_ARM_BLX23T: 786 // IMAGE_REL_BRANCH20T, IMAGE_REL_ARM_BRANCH24T, IMAGE_REL_ARM_BLX23T all 787 // perform a 4 byte adjustment to the relocation. Relative branches are 788 // offset by 4 on ARM, however, because there is no RELA relocations, all 789 // branches are offset by 4. 790 FixedValue = FixedValue + 4; 791 break; 792 } 793 } 794 795 if (TargetObjectWriter->recordRelocation(Fixup)) 796 coff_section->Relocations.push_back(Reloc); 797 } 798 799 void WinCOFFObjectWriter::WriteObject(MCAssembler &Asm, 800 const MCAsmLayout &Layout) { 801 size_t SectionsSize = Sections.size(); 802 if (SectionsSize > static_cast<size_t>(INT32_MAX)) 803 report_fatal_error( 804 "PE COFF object files can't have more than 2147483647 sections"); 805 806 // Assign symbol and section indexes and offsets. 807 int32_t NumberOfSections = static_cast<int32_t>(SectionsSize); 808 809 UseBigObj = NumberOfSections > COFF::MaxNumberOfSections16; 810 811 DenseMap<COFFSection *, int32_t> SectionIndices( 812 NextPowerOf2(NumberOfSections)); 813 814 // Assign section numbers. 815 size_t Number = 1; 816 for (const auto &Section : Sections) { 817 SectionIndices[Section.get()] = Number; 818 Section->Number = Number; 819 Section->Symbol->Data.SectionNumber = Number; 820 Section->Symbol->Aux[0].Aux.SectionDefinition.Number = Number; 821 ++Number; 822 } 823 824 Header.NumberOfSections = NumberOfSections; 825 Header.NumberOfSymbols = 0; 826 827 for (auto FI = Asm.file_names_begin(), FE = Asm.file_names_end(); 828 FI != FE; ++FI) { 829 // round up to calculate the number of auxiliary symbols required 830 unsigned SymbolSize = UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size; 831 unsigned Count = (FI->size() + SymbolSize - 1) / SymbolSize; 832 833 COFFSymbol *file = createSymbol(".file"); 834 file->Data.SectionNumber = COFF::IMAGE_SYM_DEBUG; 835 file->Data.StorageClass = COFF::IMAGE_SYM_CLASS_FILE; 836 file->Aux.resize(Count); 837 838 unsigned Offset = 0; 839 unsigned Length = FI->size(); 840 for (auto &Aux : file->Aux) { 841 Aux.AuxType = ATFile; 842 843 if (Length > SymbolSize) { 844 memcpy(&Aux.Aux, FI->c_str() + Offset, SymbolSize); 845 Length = Length - SymbolSize; 846 } else { 847 memcpy(&Aux.Aux, FI->c_str() + Offset, Length); 848 memset((char *)&Aux.Aux + Length, 0, SymbolSize - Length); 849 break; 850 } 851 852 Offset += SymbolSize; 853 } 854 } 855 856 for (auto &Symbol : Symbols) { 857 // Update section number & offset for symbols that have them. 858 if (Symbol->Section) 859 Symbol->Data.SectionNumber = Symbol->Section->Number; 860 if (Symbol->should_keep()) { 861 Symbol->Index = Header.NumberOfSymbols++; 862 // Update auxiliary symbol info. 863 Symbol->Data.NumberOfAuxSymbols = Symbol->Aux.size(); 864 Header.NumberOfSymbols += Symbol->Data.NumberOfAuxSymbols; 865 } else 866 Symbol->Index = -1; 867 } 868 869 // Build string table. 870 for (const auto &S : Sections) 871 if (S->Name.size() > COFF::NameSize) 872 Strings.add(S->Name); 873 for (const auto &S : Symbols) 874 if (S->should_keep() && S->Name.size() > COFF::NameSize) 875 Strings.add(S->Name); 876 Strings.finalize(StringTableBuilder::WinCOFF); 877 878 // Set names. 879 for (const auto &S : Sections) 880 SetSectionName(*S); 881 for (auto &S : Symbols) 882 if (S->should_keep()) 883 SetSymbolName(*S); 884 885 // Fixup weak external references. 886 for (auto &Symbol : Symbols) { 887 if (Symbol->Other) { 888 assert(Symbol->Index != -1); 889 assert(Symbol->Aux.size() == 1 && "Symbol must contain one aux symbol!"); 890 assert(Symbol->Aux[0].AuxType == ATWeakExternal && 891 "Symbol's aux symbol must be a Weak External!"); 892 Symbol->Aux[0].Aux.WeakExternal.TagIndex = Symbol->Other->Index; 893 } 894 } 895 896 // Fixup associative COMDAT sections. 897 for (auto &Section : Sections) { 898 if (Section->Symbol->Aux[0].Aux.SectionDefinition.Selection != 899 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) 900 continue; 901 902 const MCSectionCOFF &MCSec = 903 static_cast<const MCSectionCOFF &>(Section->MCData->getSection()); 904 905 const MCSymbol *COMDAT = MCSec.getCOMDATSymbol(); 906 assert(COMDAT); 907 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(COMDAT); 908 assert(COMDATSymbol); 909 COFFSection *Assoc = COMDATSymbol->Section; 910 if (!Assoc) 911 report_fatal_error( 912 Twine("Missing associated COMDAT section for section ") + 913 MCSec.getSectionName()); 914 915 // Skip this section if the associated section is unused. 916 if (Assoc->Number == -1) 917 continue; 918 919 Section->Symbol->Aux[0].Aux.SectionDefinition.Number = SectionIndices[Assoc]; 920 } 921 922 923 // Assign file offsets to COFF object file structures. 924 925 unsigned offset = 0; 926 927 if (UseBigObj) 928 offset += COFF::Header32Size; 929 else 930 offset += COFF::Header16Size; 931 offset += COFF::SectionSize * Header.NumberOfSections; 932 933 for (const auto &Section : Asm) { 934 COFFSection *Sec = SectionMap[&Section.getSection()]; 935 936 if (Sec->Number == -1) 937 continue; 938 939 Sec->Header.SizeOfRawData = Layout.getSectionAddressSize(&Section); 940 941 if (IsPhysicalSection(Sec)) { 942 // Align the section data to a four byte boundary. 943 offset = RoundUpToAlignment(offset, 4); 944 Sec->Header.PointerToRawData = offset; 945 946 offset += Sec->Header.SizeOfRawData; 947 } 948 949 if (Sec->Relocations.size() > 0) { 950 bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff; 951 952 if (RelocationsOverflow) { 953 // Signal overflow by setting NumberOfRelocations to max value. Actual 954 // size is found in reloc #0. Microsoft tools understand this. 955 Sec->Header.NumberOfRelocations = 0xffff; 956 } else { 957 Sec->Header.NumberOfRelocations = Sec->Relocations.size(); 958 } 959 Sec->Header.PointerToRelocations = offset; 960 961 if (RelocationsOverflow) { 962 // Reloc #0 will contain actual count, so make room for it. 963 offset += COFF::RelocationSize; 964 } 965 966 offset += COFF::RelocationSize * Sec->Relocations.size(); 967 968 for (auto &Relocation : Sec->Relocations) { 969 assert(Relocation.Symb->Index != -1); 970 Relocation.Data.SymbolTableIndex = Relocation.Symb->Index; 971 } 972 } 973 974 assert(Sec->Symbol->Aux.size() == 1 && 975 "Section's symbol must have one aux!"); 976 AuxSymbol &Aux = Sec->Symbol->Aux[0]; 977 assert(Aux.AuxType == ATSectionDefinition && 978 "Section's symbol's aux symbol must be a Section Definition!"); 979 Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData; 980 Aux.Aux.SectionDefinition.NumberOfRelocations = 981 Sec->Header.NumberOfRelocations; 982 Aux.Aux.SectionDefinition.NumberOfLinenumbers = 983 Sec->Header.NumberOfLineNumbers; 984 } 985 986 Header.PointerToSymbolTable = offset; 987 988 // We want a deterministic output. It looks like GNU as also writes 0 in here. 989 Header.TimeDateStamp = 0; 990 991 // Write it all to disk... 992 WriteFileHeader(Header); 993 994 { 995 sections::iterator i, ie; 996 MCAssembler::const_iterator j, je; 997 998 for (auto &Section : Sections) { 999 if (Section->Number != -1) { 1000 if (Section->Relocations.size() >= 0xffff) 1001 Section->Header.Characteristics |= COFF::IMAGE_SCN_LNK_NRELOC_OVFL; 1002 WriteSectionHeader(Section->Header); 1003 } 1004 } 1005 1006 for (i = Sections.begin(), ie = Sections.end(), 1007 j = Asm.begin(), je = Asm.end(); 1008 (i != ie) && (j != je); ++i, ++j) { 1009 1010 if ((*i)->Number == -1) 1011 continue; 1012 1013 if ((*i)->Header.PointerToRawData != 0) { 1014 assert(OS.tell() <= (*i)->Header.PointerToRawData && 1015 "Section::PointerToRawData is insane!"); 1016 1017 unsigned SectionDataPadding = (*i)->Header.PointerToRawData - OS.tell(); 1018 assert(SectionDataPadding < 4 && 1019 "Should only need at most three bytes of padding!"); 1020 1021 WriteZeros(SectionDataPadding); 1022 1023 Asm.writeSectionData(j, Layout); 1024 } 1025 1026 if ((*i)->Relocations.size() > 0) { 1027 assert(OS.tell() == (*i)->Header.PointerToRelocations && 1028 "Section::PointerToRelocations is insane!"); 1029 1030 if ((*i)->Relocations.size() >= 0xffff) { 1031 // In case of overflow, write actual relocation count as first 1032 // relocation. Including the synthetic reloc itself (+ 1). 1033 COFF::relocation r; 1034 r.VirtualAddress = (*i)->Relocations.size() + 1; 1035 r.SymbolTableIndex = 0; 1036 r.Type = 0; 1037 WriteRelocation(r); 1038 } 1039 1040 for (const auto &Relocation : (*i)->Relocations) 1041 WriteRelocation(Relocation.Data); 1042 } else 1043 assert((*i)->Header.PointerToRelocations == 0 && 1044 "Section::PointerToRelocations is insane!"); 1045 } 1046 } 1047 1048 assert(OS.tell() == Header.PointerToSymbolTable && 1049 "Header::PointerToSymbolTable is insane!"); 1050 1051 for (auto &Symbol : Symbols) 1052 if (Symbol->Index != -1) 1053 WriteSymbol(*Symbol); 1054 1055 OS.write(Strings.data().data(), Strings.data().size()); 1056 } 1057 1058 MCWinCOFFObjectTargetWriter::MCWinCOFFObjectTargetWriter(unsigned Machine_) : 1059 Machine(Machine_) { 1060 } 1061 1062 // Pin the vtable to this file. 1063 void MCWinCOFFObjectTargetWriter::anchor() {} 1064 1065 //------------------------------------------------------------------------------ 1066 // WinCOFFObjectWriter factory function 1067 1068 namespace llvm { 1069 MCObjectWriter *createWinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW, 1070 raw_ostream &OS) { 1071 return new WinCOFFObjectWriter(MOTW, OS); 1072 } 1073 } 1074