1 //===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -----------------------===// 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 implements ELF object file writer information. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/MC/MCELFObjectWriter.h" 15 #include "llvm/ADT/STLExtras.h" 16 #include "llvm/ADT/SmallPtrSet.h" 17 #include "llvm/ADT/SmallString.h" 18 #include "llvm/ADT/StringMap.h" 19 #include "llvm/MC/MCAsmBackend.h" 20 #include "llvm/MC/MCAsmInfo.h" 21 #include "llvm/MC/MCAsmLayout.h" 22 #include "llvm/MC/MCAssembler.h" 23 #include "llvm/MC/MCContext.h" 24 #include "llvm/MC/MCExpr.h" 25 #include "llvm/MC/MCFixupKindInfo.h" 26 #include "llvm/MC/MCObjectWriter.h" 27 #include "llvm/MC/MCSectionELF.h" 28 #include "llvm/MC/MCSymbolELF.h" 29 #include "llvm/MC/MCValue.h" 30 #include "llvm/MC/StringTableBuilder.h" 31 #include "llvm/Support/Compression.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/ELF.h" 34 #include "llvm/Support/Endian.h" 35 #include "llvm/Support/ErrorHandling.h" 36 #include "llvm/Support/StringSaver.h" 37 #include <vector> 38 39 using namespace llvm; 40 41 #undef DEBUG_TYPE 42 #define DEBUG_TYPE "reloc-info" 43 44 namespace { 45 typedef DenseMap<const MCSectionELF *, uint32_t> SectionIndexMapTy; 46 47 class ELFObjectWriter; 48 49 class SymbolTableWriter { 50 ELFObjectWriter &EWriter; 51 bool Is64Bit; 52 53 // indexes we are going to write to .symtab_shndx. 54 std::vector<uint32_t> ShndxIndexes; 55 56 // The numbel of symbols written so far. 57 unsigned NumWritten; 58 59 void createSymtabShndx(); 60 61 template <typename T> void write(T Value); 62 63 public: 64 SymbolTableWriter(ELFObjectWriter &EWriter, bool Is64Bit); 65 66 void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size, 67 uint8_t other, uint32_t shndx, bool Reserved); 68 69 ArrayRef<uint32_t> getShndxIndexes() const { return ShndxIndexes; } 70 }; 71 72 class ELFObjectWriter : public MCObjectWriter { 73 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind); 74 static uint64_t SymbolValue(const MCSymbol &Sym, const MCAsmLayout &Layout); 75 static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolELF &Symbol, 76 bool Used, bool Renamed); 77 78 /// Helper struct for containing some precomputed information on symbols. 79 struct ELFSymbolData { 80 const MCSymbolELF *Symbol; 81 uint32_t SectionIndex; 82 StringRef Name; 83 84 // Support lexicographic sorting. 85 bool operator<(const ELFSymbolData &RHS) const { 86 unsigned LHSType = Symbol->getType(); 87 unsigned RHSType = RHS.Symbol->getType(); 88 if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION) 89 return false; 90 if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION) 91 return true; 92 if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION) 93 return SectionIndex < RHS.SectionIndex; 94 return Name < RHS.Name; 95 } 96 }; 97 98 /// The target specific ELF writer instance. 99 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter; 100 101 DenseMap<const MCSymbolELF *, const MCSymbolELF *> Renames; 102 103 llvm::DenseMap<const MCSectionELF *, std::vector<ELFRelocationEntry>> 104 Relocations; 105 106 /// @} 107 /// @name Symbol Table Data 108 /// @{ 109 110 BumpPtrAllocator Alloc; 111 StringSaver VersionSymSaver{Alloc}; 112 StringTableBuilder StrTabBuilder{StringTableBuilder::ELF}; 113 114 /// @} 115 116 // This holds the symbol table index of the last local symbol. 117 unsigned LastLocalSymbolIndex; 118 // This holds the .strtab section index. 119 unsigned StringTableIndex; 120 // This holds the .symtab section index. 121 unsigned SymbolTableIndex; 122 123 // Sections in the order they are to be output in the section table. 124 std::vector<const MCSectionELF *> SectionTable; 125 unsigned addToSectionTable(const MCSectionELF *Sec); 126 127 // TargetObjectWriter wrappers. 128 bool is64Bit() const { return TargetObjectWriter->is64Bit(); } 129 bool hasRelocationAddend() const { 130 return TargetObjectWriter->hasRelocationAddend(); 131 } 132 unsigned getRelocType(MCContext &Ctx, const MCValue &Target, 133 const MCFixup &Fixup, bool IsPCRel) const { 134 return TargetObjectWriter->getRelocType(Ctx, Target, Fixup, IsPCRel); 135 } 136 137 void align(unsigned Alignment); 138 139 public: 140 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_pwrite_stream &OS, 141 bool IsLittleEndian) 142 : MCObjectWriter(OS, IsLittleEndian), TargetObjectWriter(MOTW) {} 143 144 void reset() override { 145 Renames.clear(); 146 Relocations.clear(); 147 StrTabBuilder.clear(); 148 SectionTable.clear(); 149 MCObjectWriter::reset(); 150 } 151 152 ~ELFObjectWriter() override; 153 154 void WriteWord(uint64_t W) { 155 if (is64Bit()) 156 write64(W); 157 else 158 write32(W); 159 } 160 161 template <typename T> void write(T Val) { 162 if (IsLittleEndian) 163 support::endian::Writer<support::little>(getStream()).write(Val); 164 else 165 support::endian::Writer<support::big>(getStream()).write(Val); 166 } 167 168 void writeHeader(const MCAssembler &Asm); 169 170 void writeSymbol(SymbolTableWriter &Writer, uint32_t StringIndex, 171 ELFSymbolData &MSD, const MCAsmLayout &Layout); 172 173 // Start and end offset of each section 174 typedef std::map<const MCSectionELF *, std::pair<uint64_t, uint64_t>> 175 SectionOffsetsTy; 176 177 bool shouldRelocateWithSymbol(const MCAssembler &Asm, 178 const MCSymbolRefExpr *RefA, 179 const MCSymbol *Sym, uint64_t C, 180 unsigned Type) const; 181 182 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout, 183 const MCFragment *Fragment, const MCFixup &Fixup, 184 MCValue Target, bool &IsPCRel, 185 uint64_t &FixedValue) override; 186 187 // Map from a signature symbol to the group section index 188 typedef DenseMap<const MCSymbol *, unsigned> RevGroupMapTy; 189 190 /// Compute the symbol table data 191 /// 192 /// \param Asm - The assembler. 193 /// \param SectionIndexMap - Maps a section to its index. 194 /// \param RevGroupMap - Maps a signature symbol to the group section. 195 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout, 196 const SectionIndexMapTy &SectionIndexMap, 197 const RevGroupMapTy &RevGroupMap, 198 SectionOffsetsTy &SectionOffsets); 199 200 MCSectionELF *createRelocationSection(MCContext &Ctx, 201 const MCSectionELF &Sec); 202 203 const MCSectionELF *createStringTable(MCContext &Ctx); 204 205 void executePostLayoutBinding(MCAssembler &Asm, 206 const MCAsmLayout &Layout) override; 207 208 void writeSectionHeader(const MCAsmLayout &Layout, 209 const SectionIndexMapTy &SectionIndexMap, 210 const SectionOffsetsTy &SectionOffsets); 211 212 void writeSectionData(const MCAssembler &Asm, MCSection &Sec, 213 const MCAsmLayout &Layout); 214 215 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags, 216 uint64_t Address, uint64_t Offset, uint64_t Size, 217 uint32_t Link, uint32_t Info, uint64_t Alignment, 218 uint64_t EntrySize); 219 220 void writeRelocations(const MCAssembler &Asm, const MCSectionELF &Sec); 221 222 bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm, 223 const MCSymbol &SymA, 224 const MCFragment &FB, 225 bool InSet, 226 bool IsPCRel) const override; 227 228 bool isWeak(const MCSymbol &Sym) const override; 229 230 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override; 231 void writeSection(const SectionIndexMapTy &SectionIndexMap, 232 uint32_t GroupSymbolIndex, uint64_t Offset, uint64_t Size, 233 const MCSectionELF &Section); 234 }; 235 } // end anonymous namespace 236 237 void ELFObjectWriter::align(unsigned Alignment) { 238 uint64_t Padding = OffsetToAlignment(getStream().tell(), Alignment); 239 WriteZeros(Padding); 240 } 241 242 unsigned ELFObjectWriter::addToSectionTable(const MCSectionELF *Sec) { 243 SectionTable.push_back(Sec); 244 StrTabBuilder.add(Sec->getSectionName()); 245 return SectionTable.size(); 246 } 247 248 void SymbolTableWriter::createSymtabShndx() { 249 if (!ShndxIndexes.empty()) 250 return; 251 252 ShndxIndexes.resize(NumWritten); 253 } 254 255 template <typename T> void SymbolTableWriter::write(T Value) { 256 EWriter.write(Value); 257 } 258 259 SymbolTableWriter::SymbolTableWriter(ELFObjectWriter &EWriter, bool Is64Bit) 260 : EWriter(EWriter), Is64Bit(Is64Bit), NumWritten(0) {} 261 262 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value, 263 uint64_t size, uint8_t other, 264 uint32_t shndx, bool Reserved) { 265 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved; 266 267 if (LargeIndex) 268 createSymtabShndx(); 269 270 if (!ShndxIndexes.empty()) { 271 if (LargeIndex) 272 ShndxIndexes.push_back(shndx); 273 else 274 ShndxIndexes.push_back(0); 275 } 276 277 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx; 278 279 if (Is64Bit) { 280 write(name); // st_name 281 write(info); // st_info 282 write(other); // st_other 283 write(Index); // st_shndx 284 write(value); // st_value 285 write(size); // st_size 286 } else { 287 write(name); // st_name 288 write(uint32_t(value)); // st_value 289 write(uint32_t(size)); // st_size 290 write(info); // st_info 291 write(other); // st_other 292 write(Index); // st_shndx 293 } 294 295 ++NumWritten; 296 } 297 298 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) { 299 const MCFixupKindInfo &FKI = 300 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind); 301 302 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel; 303 } 304 305 ELFObjectWriter::~ELFObjectWriter() 306 {} 307 308 // Emit the ELF header. 309 void ELFObjectWriter::writeHeader(const MCAssembler &Asm) { 310 // ELF Header 311 // ---------- 312 // 313 // Note 314 // ---- 315 // emitWord method behaves differently for ELF32 and ELF64, writing 316 // 4 bytes in the former and 8 in the latter. 317 318 writeBytes(ELF::ElfMagic); // e_ident[EI_MAG0] to e_ident[EI_MAG3] 319 320 write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS] 321 322 // e_ident[EI_DATA] 323 write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB); 324 325 write8(ELF::EV_CURRENT); // e_ident[EI_VERSION] 326 // e_ident[EI_OSABI] 327 write8(TargetObjectWriter->getOSABI()); 328 write8(0); // e_ident[EI_ABIVERSION] 329 330 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD); 331 332 write16(ELF::ET_REL); // e_type 333 334 write16(TargetObjectWriter->getEMachine()); // e_machine = target 335 336 write32(ELF::EV_CURRENT); // e_version 337 WriteWord(0); // e_entry, no entry point in .o file 338 WriteWord(0); // e_phoff, no program header for .o 339 WriteWord(0); // e_shoff = sec hdr table off in bytes 340 341 // e_flags = whatever the target wants 342 write32(Asm.getELFHeaderEFlags()); 343 344 // e_ehsize = ELF header size 345 write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr)); 346 347 write16(0); // e_phentsize = prog header entry size 348 write16(0); // e_phnum = # prog header entries = 0 349 350 // e_shentsize = Section header entry size 351 write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr)); 352 353 // e_shnum = # of section header ents 354 write16(0); 355 356 // e_shstrndx = Section # of '.shstrtab' 357 assert(StringTableIndex < ELF::SHN_LORESERVE); 358 write16(StringTableIndex); 359 } 360 361 uint64_t ELFObjectWriter::SymbolValue(const MCSymbol &Sym, 362 const MCAsmLayout &Layout) { 363 if (Sym.isCommon() && Sym.isExternal()) 364 return Sym.getCommonAlignment(); 365 366 uint64_t Res; 367 if (!Layout.getSymbolOffset(Sym, Res)) 368 return 0; 369 370 if (Layout.getAssembler().isThumbFunc(&Sym)) 371 Res |= 1; 372 373 return Res; 374 } 375 376 void ELFObjectWriter::executePostLayoutBinding(MCAssembler &Asm, 377 const MCAsmLayout &Layout) { 378 // Section symbols are used as definitions for undefined symbols with matching 379 // names. If there are multiple sections with the same name, the first one is 380 // used. 381 for (const MCSection &Sec : Asm) { 382 const MCSymbol *Begin = Sec.getBeginSymbol(); 383 if (!Begin) 384 continue; 385 386 const MCSymbol *Alias = Asm.getContext().lookupSymbol(Begin->getName()); 387 if (!Alias || !Alias->isUndefined()) 388 continue; 389 390 Renames.insert( 391 std::make_pair(cast<MCSymbolELF>(Alias), cast<MCSymbolELF>(Begin))); 392 } 393 394 // The presence of symbol versions causes undefined symbols and 395 // versions declared with @@@ to be renamed. 396 for (const MCSymbol &A : Asm.symbols()) { 397 const auto &Alias = cast<MCSymbolELF>(A); 398 // Not an alias. 399 if (!Alias.isVariable()) 400 continue; 401 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue()); 402 if (!Ref) 403 continue; 404 const auto &Symbol = cast<MCSymbolELF>(Ref->getSymbol()); 405 406 StringRef AliasName = Alias.getName(); 407 size_t Pos = AliasName.find('@'); 408 if (Pos == StringRef::npos) 409 continue; 410 411 // Aliases defined with .symvar copy the binding from the symbol they alias. 412 // This is the first place we are able to copy this information. 413 Alias.setExternal(Symbol.isExternal()); 414 Alias.setBinding(Symbol.getBinding()); 415 416 StringRef Rest = AliasName.substr(Pos); 417 if (!Symbol.isUndefined() && !Rest.startswith("@@@")) 418 continue; 419 420 // FIXME: produce a better error message. 421 if (Symbol.isUndefined() && Rest.startswith("@@") && 422 !Rest.startswith("@@@")) 423 report_fatal_error("A @@ version cannot be undefined"); 424 425 Renames.insert(std::make_pair(&Symbol, &Alias)); 426 } 427 } 428 429 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) { 430 uint8_t Type = newType; 431 432 // Propagation rules: 433 // IFUNC > FUNC > OBJECT > NOTYPE 434 // TLS_OBJECT > OBJECT > NOTYPE 435 // 436 // dont let the new type degrade the old type 437 switch (origType) { 438 default: 439 break; 440 case ELF::STT_GNU_IFUNC: 441 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT || 442 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS) 443 Type = ELF::STT_GNU_IFUNC; 444 break; 445 case ELF::STT_FUNC: 446 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE || 447 Type == ELF::STT_TLS) 448 Type = ELF::STT_FUNC; 449 break; 450 case ELF::STT_OBJECT: 451 if (Type == ELF::STT_NOTYPE) 452 Type = ELF::STT_OBJECT; 453 break; 454 case ELF::STT_TLS: 455 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE || 456 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC) 457 Type = ELF::STT_TLS; 458 break; 459 } 460 461 return Type; 462 } 463 464 void ELFObjectWriter::writeSymbol(SymbolTableWriter &Writer, 465 uint32_t StringIndex, ELFSymbolData &MSD, 466 const MCAsmLayout &Layout) { 467 const auto &Symbol = cast<MCSymbolELF>(*MSD.Symbol); 468 const MCSymbolELF *Base = 469 cast_or_null<MCSymbolELF>(Layout.getBaseSymbol(Symbol)); 470 471 // This has to be in sync with when computeSymbolTable uses SHN_ABS or 472 // SHN_COMMON. 473 bool IsReserved = !Base || Symbol.isCommon(); 474 475 // Binding and Type share the same byte as upper and lower nibbles 476 uint8_t Binding = Symbol.getBinding(); 477 uint8_t Type = Symbol.getType(); 478 if (Base) { 479 Type = mergeTypeForSet(Type, Base->getType()); 480 } 481 uint8_t Info = (Binding << 4) | Type; 482 483 // Other and Visibility share the same byte with Visibility using the lower 484 // 2 bits 485 uint8_t Visibility = Symbol.getVisibility(); 486 uint8_t Other = Symbol.getOther() | Visibility; 487 488 uint64_t Value = SymbolValue(*MSD.Symbol, Layout); 489 uint64_t Size = 0; 490 491 const MCExpr *ESize = MSD.Symbol->getSize(); 492 if (!ESize && Base) 493 ESize = Base->getSize(); 494 495 if (ESize) { 496 int64_t Res; 497 if (!ESize->evaluateKnownAbsolute(Res, Layout)) 498 report_fatal_error("Size expression must be absolute."); 499 Size = Res; 500 } 501 502 // Write out the symbol table entry 503 Writer.writeSymbol(StringIndex, Info, Value, Size, Other, MSD.SectionIndex, 504 IsReserved); 505 } 506 507 // It is always valid to create a relocation with a symbol. It is preferable 508 // to use a relocation with a section if that is possible. Using the section 509 // allows us to omit some local symbols from the symbol table. 510 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm, 511 const MCSymbolRefExpr *RefA, 512 const MCSymbol *S, uint64_t C, 513 unsigned Type) const { 514 const auto *Sym = cast_or_null<MCSymbolELF>(S); 515 // A PCRel relocation to an absolute value has no symbol (or section). We 516 // represent that with a relocation to a null section. 517 if (!RefA) 518 return false; 519 520 MCSymbolRefExpr::VariantKind Kind = RefA->getKind(); 521 switch (Kind) { 522 default: 523 break; 524 // The .odp creation emits a relocation against the symbol ".TOC." which 525 // create a R_PPC64_TOC relocation. However the relocation symbol name 526 // in final object creation should be NULL, since the symbol does not 527 // really exist, it is just the reference to TOC base for the current 528 // object file. Since the symbol is undefined, returning false results 529 // in a relocation with a null section which is the desired result. 530 case MCSymbolRefExpr::VK_PPC_TOCBASE: 531 return false; 532 533 // These VariantKind cause the relocation to refer to something other than 534 // the symbol itself, like a linker generated table. Since the address of 535 // symbol is not relevant, we cannot replace the symbol with the 536 // section and patch the difference in the addend. 537 case MCSymbolRefExpr::VK_GOT: 538 case MCSymbolRefExpr::VK_PLT: 539 case MCSymbolRefExpr::VK_GOTPCREL: 540 case MCSymbolRefExpr::VK_Mips_GOT: 541 case MCSymbolRefExpr::VK_PPC_GOT_LO: 542 case MCSymbolRefExpr::VK_PPC_GOT_HI: 543 case MCSymbolRefExpr::VK_PPC_GOT_HA: 544 return true; 545 } 546 547 // An undefined symbol is not in any section, so the relocation has to point 548 // to the symbol itself. 549 assert(Sym && "Expected a symbol"); 550 if (Sym->isUndefined()) 551 return true; 552 553 unsigned Binding = Sym->getBinding(); 554 switch(Binding) { 555 default: 556 llvm_unreachable("Invalid Binding"); 557 case ELF::STB_LOCAL: 558 break; 559 case ELF::STB_WEAK: 560 // If the symbol is weak, it might be overridden by a symbol in another 561 // file. The relocation has to point to the symbol so that the linker 562 // can update it. 563 return true; 564 case ELF::STB_GLOBAL: 565 // Global ELF symbols can be preempted by the dynamic linker. The relocation 566 // has to point to the symbol for a reason analogous to the STB_WEAK case. 567 return true; 568 } 569 570 // If a relocation points to a mergeable section, we have to be careful. 571 // If the offset is zero, a relocation with the section will encode the 572 // same information. With a non-zero offset, the situation is different. 573 // For example, a relocation can point 42 bytes past the end of a string. 574 // If we change such a relocation to use the section, the linker would think 575 // that it pointed to another string and subtracting 42 at runtime will 576 // produce the wrong value. 577 auto &Sec = cast<MCSectionELF>(Sym->getSection()); 578 unsigned Flags = Sec.getFlags(); 579 if (Flags & ELF::SHF_MERGE) { 580 if (C != 0) 581 return true; 582 583 // It looks like gold has a bug (http://sourceware.org/PR16794) and can 584 // only handle section relocations to mergeable sections if using RELA. 585 if (!hasRelocationAddend()) 586 return true; 587 } 588 589 // Most TLS relocations use a got, so they need the symbol. Even those that 590 // are just an offset (@tpoff), require a symbol in gold versions before 591 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed 592 // http://sourceware.org/PR16773. 593 if (Flags & ELF::SHF_TLS) 594 return true; 595 596 // If the symbol is a thumb function the final relocation must set the lowest 597 // bit. With a symbol that is done by just having the symbol have that bit 598 // set, so we would lose the bit if we relocated with the section. 599 // FIXME: We could use the section but add the bit to the relocation value. 600 if (Asm.isThumbFunc(Sym)) 601 return true; 602 603 if (TargetObjectWriter->needsRelocateWithSymbol(*Sym, Type)) 604 return true; 605 return false; 606 } 607 608 // True if the assembler knows nothing about the final value of the symbol. 609 // This doesn't cover the comdat issues, since in those cases the assembler 610 // can at least know that all symbols in the section will move together. 611 static bool isWeak(const MCSymbolELF &Sym) { 612 if (Sym.getType() == ELF::STT_GNU_IFUNC) 613 return true; 614 615 switch (Sym.getBinding()) { 616 default: 617 llvm_unreachable("Unknown binding"); 618 case ELF::STB_LOCAL: 619 return false; 620 case ELF::STB_GLOBAL: 621 return false; 622 case ELF::STB_WEAK: 623 case ELF::STB_GNU_UNIQUE: 624 return true; 625 } 626 } 627 628 void ELFObjectWriter::recordRelocation(MCAssembler &Asm, 629 const MCAsmLayout &Layout, 630 const MCFragment *Fragment, 631 const MCFixup &Fixup, MCValue Target, 632 bool &IsPCRel, uint64_t &FixedValue) { 633 const MCSectionELF &FixupSection = cast<MCSectionELF>(*Fragment->getParent()); 634 uint64_t C = Target.getConstant(); 635 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset(); 636 MCContext &Ctx = Asm.getContext(); 637 638 if (const MCSymbolRefExpr *RefB = Target.getSymB()) { 639 assert(RefB->getKind() == MCSymbolRefExpr::VK_None && 640 "Should not have constructed this"); 641 642 // Let A, B and C being the components of Target and R be the location of 643 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C). 644 // If it is pcrel, we want to compute (A - B + C - R). 645 646 // In general, ELF has no relocations for -B. It can only represent (A + C) 647 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can 648 // replace B to implement it: (A - R - K + C) 649 if (IsPCRel) { 650 Ctx.reportError( 651 Fixup.getLoc(), 652 "No relocation available to represent this relative expression"); 653 return; 654 } 655 656 const auto &SymB = cast<MCSymbolELF>(RefB->getSymbol()); 657 658 if (SymB.isUndefined()) { 659 Ctx.reportError(Fixup.getLoc(), 660 Twine("symbol '") + SymB.getName() + 661 "' can not be undefined in a subtraction expression"); 662 return; 663 } 664 665 assert(!SymB.isAbsolute() && "Should have been folded"); 666 const MCSection &SecB = SymB.getSection(); 667 if (&SecB != &FixupSection) { 668 Ctx.reportError(Fixup.getLoc(), 669 "Cannot represent a difference across sections"); 670 return; 671 } 672 673 uint64_t SymBOffset = Layout.getSymbolOffset(SymB); 674 uint64_t K = SymBOffset - FixupOffset; 675 IsPCRel = true; 676 C -= K; 677 } 678 679 // We either rejected the fixup or folded B into C at this point. 680 const MCSymbolRefExpr *RefA = Target.getSymA(); 681 const auto *SymA = RefA ? cast<MCSymbolELF>(&RefA->getSymbol()) : nullptr; 682 683 bool ViaWeakRef = false; 684 if (SymA && SymA->isVariable()) { 685 const MCExpr *Expr = SymA->getVariableValue(); 686 if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) { 687 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) { 688 SymA = cast<MCSymbolELF>(&Inner->getSymbol()); 689 ViaWeakRef = true; 690 } 691 } 692 } 693 694 unsigned Type = getRelocType(Ctx, Target, Fixup, IsPCRel); 695 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymA, C, Type); 696 if (!RelocateWithSymbol && SymA && !SymA->isUndefined()) 697 C += Layout.getSymbolOffset(*SymA); 698 699 uint64_t Addend = 0; 700 if (hasRelocationAddend()) { 701 Addend = C; 702 C = 0; 703 } 704 705 FixedValue = C; 706 707 if (!RelocateWithSymbol) { 708 const MCSection *SecA = 709 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr; 710 auto *ELFSec = cast_or_null<MCSectionELF>(SecA); 711 const auto *SectionSymbol = 712 ELFSec ? cast<MCSymbolELF>(ELFSec->getBeginSymbol()) : nullptr; 713 if (SectionSymbol) 714 SectionSymbol->setUsedInReloc(); 715 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend); 716 Relocations[&FixupSection].push_back(Rec); 717 return; 718 } 719 720 if (SymA) { 721 if (const MCSymbolELF *R = Renames.lookup(SymA)) 722 SymA = R; 723 724 if (ViaWeakRef) 725 SymA->setIsWeakrefUsedInReloc(); 726 else 727 SymA->setUsedInReloc(); 728 } 729 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend); 730 Relocations[&FixupSection].push_back(Rec); 731 } 732 733 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout, 734 const MCSymbolELF &Symbol, bool Used, 735 bool Renamed) { 736 if (Symbol.isVariable()) { 737 const MCExpr *Expr = Symbol.getVariableValue(); 738 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) { 739 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF) 740 return false; 741 } 742 } 743 744 if (Used) 745 return true; 746 747 if (Renamed) 748 return false; 749 750 if (Symbol.isVariable() && Symbol.isUndefined()) { 751 // FIXME: this is here just to diagnose the case of a var = commmon_sym. 752 Layout.getBaseSymbol(Symbol); 753 return false; 754 } 755 756 if (Symbol.isUndefined() && !Symbol.isBindingSet()) 757 return false; 758 759 if (Symbol.isTemporary()) 760 return false; 761 762 if (Symbol.getType() == ELF::STT_SECTION) 763 return false; 764 765 return true; 766 } 767 768 void ELFObjectWriter::computeSymbolTable( 769 MCAssembler &Asm, const MCAsmLayout &Layout, 770 const SectionIndexMapTy &SectionIndexMap, const RevGroupMapTy &RevGroupMap, 771 SectionOffsetsTy &SectionOffsets) { 772 MCContext &Ctx = Asm.getContext(); 773 SymbolTableWriter Writer(*this, is64Bit()); 774 775 // Symbol table 776 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32; 777 MCSectionELF *SymtabSection = 778 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize, ""); 779 SymtabSection->setAlignment(is64Bit() ? 8 : 4); 780 SymbolTableIndex = addToSectionTable(SymtabSection); 781 782 align(SymtabSection->getAlignment()); 783 uint64_t SecStart = getStream().tell(); 784 785 // The first entry is the undefined symbol entry. 786 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false); 787 788 std::vector<ELFSymbolData> LocalSymbolData; 789 std::vector<ELFSymbolData> ExternalSymbolData; 790 791 // Add the data for the symbols. 792 bool HasLargeSectionIndex = false; 793 for (const MCSymbol &S : Asm.symbols()) { 794 const auto &Symbol = cast<MCSymbolELF>(S); 795 bool Used = Symbol.isUsedInReloc(); 796 bool WeakrefUsed = Symbol.isWeakrefUsedInReloc(); 797 bool isSignature = Symbol.isSignature(); 798 799 if (!isInSymtab(Layout, Symbol, Used || WeakrefUsed || isSignature, 800 Renames.count(&Symbol))) 801 continue; 802 803 if (Symbol.isTemporary() && Symbol.isUndefined()) { 804 Ctx.reportError(SMLoc(), "Undefined temporary symbol"); 805 continue; 806 } 807 808 ELFSymbolData MSD; 809 MSD.Symbol = cast<MCSymbolELF>(&Symbol); 810 811 bool Local = Symbol.getBinding() == ELF::STB_LOCAL; 812 assert(Local || !Symbol.isTemporary()); 813 814 if (Symbol.isAbsolute()) { 815 MSD.SectionIndex = ELF::SHN_ABS; 816 } else if (Symbol.isCommon()) { 817 assert(!Local); 818 MSD.SectionIndex = ELF::SHN_COMMON; 819 } else if (Symbol.isUndefined()) { 820 if (isSignature && !Used) { 821 MSD.SectionIndex = RevGroupMap.lookup(&Symbol); 822 if (MSD.SectionIndex >= ELF::SHN_LORESERVE) 823 HasLargeSectionIndex = true; 824 } else { 825 MSD.SectionIndex = ELF::SHN_UNDEF; 826 } 827 } else { 828 const MCSectionELF &Section = 829 static_cast<const MCSectionELF &>(Symbol.getSection()); 830 MSD.SectionIndex = SectionIndexMap.lookup(&Section); 831 assert(MSD.SectionIndex && "Invalid section index!"); 832 if (MSD.SectionIndex >= ELF::SHN_LORESERVE) 833 HasLargeSectionIndex = true; 834 } 835 836 // The @@@ in symbol version is replaced with @ in undefined symbols and @@ 837 // in defined ones. 838 // 839 // FIXME: All name handling should be done before we get to the writer, 840 // including dealing with GNU-style version suffixes. Fixing this isn't 841 // trivial. 842 // 843 // We thus have to be careful to not perform the symbol version replacement 844 // blindly: 845 // 846 // The ELF format is used on Windows by the MCJIT engine. Thus, on 847 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS 848 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC 849 // C++ name mangling can legally have "@@@" as a sub-string. In that case, 850 // the EFLObjectWriter should not interpret the "@@@" sub-string as 851 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore 852 // checks for the MSVC C++ name mangling prefix which is either "?", "@?", 853 // "__imp_?" or "__imp_@?". 854 // 855 // It would have been interesting to perform the MS mangling prefix check 856 // only when the target triple is of the form *-pc-windows-elf. But, it 857 // seems that this information is not easily accessible from the 858 // ELFObjectWriter. 859 StringRef Name = Symbol.getName(); 860 SmallString<32> Buf; 861 if (!Name.startswith("?") && !Name.startswith("@?") && 862 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) { 863 // This symbol isn't following the MSVC C++ name mangling convention. We 864 // can thus safely interpret the @@@ in symbol names as specifying symbol 865 // versioning. 866 size_t Pos = Name.find("@@@"); 867 if (Pos != StringRef::npos) { 868 Buf += Name.substr(0, Pos); 869 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1; 870 Buf += Name.substr(Pos + Skip); 871 Name = VersionSymSaver.save(Buf.c_str()); 872 } 873 } 874 875 // Sections have their own string table 876 if (Symbol.getType() != ELF::STT_SECTION) { 877 MSD.Name = Name; 878 StrTabBuilder.add(Name); 879 } 880 881 if (Local) 882 LocalSymbolData.push_back(MSD); 883 else 884 ExternalSymbolData.push_back(MSD); 885 } 886 887 // This holds the .symtab_shndx section index. 888 unsigned SymtabShndxSectionIndex = 0; 889 890 if (HasLargeSectionIndex) { 891 MCSectionELF *SymtabShndxSection = 892 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, ""); 893 SymtabShndxSectionIndex = addToSectionTable(SymtabShndxSection); 894 SymtabShndxSection->setAlignment(4); 895 } 896 897 ArrayRef<std::string> FileNames = Asm.getFileNames(); 898 for (const std::string &Name : FileNames) 899 StrTabBuilder.add(Name); 900 901 StrTabBuilder.finalize(); 902 903 for (const std::string &Name : FileNames) 904 Writer.writeSymbol(StrTabBuilder.getOffset(Name), 905 ELF::STT_FILE | ELF::STB_LOCAL, 0, 0, ELF::STV_DEFAULT, 906 ELF::SHN_ABS, true); 907 908 // Symbols are required to be in lexicographic order. 909 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end()); 910 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end()); 911 912 // Set the symbol indices. Local symbols must come before all other 913 // symbols with non-local bindings. 914 unsigned Index = FileNames.size() + 1; 915 916 for (ELFSymbolData &MSD : LocalSymbolData) { 917 unsigned StringIndex = MSD.Symbol->getType() == ELF::STT_SECTION 918 ? 0 919 : StrTabBuilder.getOffset(MSD.Name); 920 MSD.Symbol->setIndex(Index++); 921 writeSymbol(Writer, StringIndex, MSD, Layout); 922 } 923 924 // Write the symbol table entries. 925 LastLocalSymbolIndex = Index; 926 927 for (ELFSymbolData &MSD : ExternalSymbolData) { 928 unsigned StringIndex = StrTabBuilder.getOffset(MSD.Name); 929 MSD.Symbol->setIndex(Index++); 930 writeSymbol(Writer, StringIndex, MSD, Layout); 931 assert(MSD.Symbol->getBinding() != ELF::STB_LOCAL); 932 } 933 934 uint64_t SecEnd = getStream().tell(); 935 SectionOffsets[SymtabSection] = std::make_pair(SecStart, SecEnd); 936 937 ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes(); 938 if (ShndxIndexes.empty()) { 939 assert(SymtabShndxSectionIndex == 0); 940 return; 941 } 942 assert(SymtabShndxSectionIndex != 0); 943 944 SecStart = getStream().tell(); 945 const MCSectionELF *SymtabShndxSection = 946 SectionTable[SymtabShndxSectionIndex - 1]; 947 for (uint32_t Index : ShndxIndexes) 948 write(Index); 949 SecEnd = getStream().tell(); 950 SectionOffsets[SymtabShndxSection] = std::make_pair(SecStart, SecEnd); 951 } 952 953 MCSectionELF * 954 ELFObjectWriter::createRelocationSection(MCContext &Ctx, 955 const MCSectionELF &Sec) { 956 if (Relocations[&Sec].empty()) 957 return nullptr; 958 959 const StringRef SectionName = Sec.getSectionName(); 960 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel"; 961 RelaSectionName += SectionName; 962 963 unsigned EntrySize; 964 if (hasRelocationAddend()) 965 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela); 966 else 967 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel); 968 969 unsigned Flags = 0; 970 if (Sec.getFlags() & ELF::SHF_GROUP) 971 Flags = ELF::SHF_GROUP; 972 973 MCSectionELF *RelaSection = Ctx.createELFRelSection( 974 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL, 975 Flags, EntrySize, Sec.getGroup(), &Sec); 976 RelaSection->setAlignment(is64Bit() ? 8 : 4); 977 return RelaSection; 978 } 979 980 // Include the debug info compression header: 981 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section, 982 // useful for consumers to preallocate a buffer to decompress into. 983 static bool 984 prependCompressionHeader(uint64_t Size, 985 SmallVectorImpl<char> &CompressedContents) { 986 const StringRef Magic = "ZLIB"; 987 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size()) 988 return false; 989 if (sys::IsLittleEndianHost) 990 sys::swapByteOrder(Size); 991 CompressedContents.insert(CompressedContents.begin(), 992 Magic.size() + sizeof(Size), 0); 993 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin()); 994 std::copy(reinterpret_cast<char *>(&Size), 995 reinterpret_cast<char *>(&Size + 1), 996 CompressedContents.begin() + Magic.size()); 997 return true; 998 } 999 1000 void ELFObjectWriter::writeSectionData(const MCAssembler &Asm, MCSection &Sec, 1001 const MCAsmLayout &Layout) { 1002 MCSectionELF &Section = static_cast<MCSectionELF &>(Sec); 1003 StringRef SectionName = Section.getSectionName(); 1004 1005 // Compressing debug_frame requires handling alignment fragments which is 1006 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow 1007 // for writing to arbitrary buffers) for little benefit. 1008 if (!Asm.getContext().getAsmInfo()->compressDebugSections() || 1009 !SectionName.startswith(".debug_") || SectionName == ".debug_frame") { 1010 Asm.writeSectionData(&Section, Layout); 1011 return; 1012 } 1013 1014 SmallVector<char, 128> UncompressedData; 1015 raw_svector_ostream VecOS(UncompressedData); 1016 raw_pwrite_stream &OldStream = getStream(); 1017 setStream(VecOS); 1018 Asm.writeSectionData(&Section, Layout); 1019 setStream(OldStream); 1020 1021 SmallVector<char, 128> CompressedContents; 1022 zlib::Status Success = zlib::compress( 1023 StringRef(UncompressedData.data(), UncompressedData.size()), 1024 CompressedContents); 1025 if (Success != zlib::StatusOK) { 1026 getStream() << UncompressedData; 1027 return; 1028 } 1029 1030 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents)) { 1031 getStream() << UncompressedData; 1032 return; 1033 } 1034 Asm.getContext().renameELFSection(&Section, 1035 (".z" + SectionName.drop_front(1)).str()); 1036 getStream() << CompressedContents; 1037 } 1038 1039 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type, 1040 uint64_t Flags, uint64_t Address, 1041 uint64_t Offset, uint64_t Size, 1042 uint32_t Link, uint32_t Info, 1043 uint64_t Alignment, 1044 uint64_t EntrySize) { 1045 write32(Name); // sh_name: index into string table 1046 write32(Type); // sh_type 1047 WriteWord(Flags); // sh_flags 1048 WriteWord(Address); // sh_addr 1049 WriteWord(Offset); // sh_offset 1050 WriteWord(Size); // sh_size 1051 write32(Link); // sh_link 1052 write32(Info); // sh_info 1053 WriteWord(Alignment); // sh_addralign 1054 WriteWord(EntrySize); // sh_entsize 1055 } 1056 1057 void ELFObjectWriter::writeRelocations(const MCAssembler &Asm, 1058 const MCSectionELF &Sec) { 1059 std::vector<ELFRelocationEntry> &Relocs = Relocations[&Sec]; 1060 1061 // We record relocations by pushing to the end of a vector. Reverse the vector 1062 // to get the relocations in the order they were created. 1063 // In most cases that is not important, but it can be for special sections 1064 // (.eh_frame) or specific relocations (TLS optimizations on SystemZ). 1065 std::reverse(Relocs.begin(), Relocs.end()); 1066 1067 // Sort the relocation entries. MIPS needs this. 1068 TargetObjectWriter->sortRelocs(Asm, Relocs); 1069 1070 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) { 1071 const ELFRelocationEntry &Entry = Relocs[e - i - 1]; 1072 unsigned Index = Entry.Symbol ? Entry.Symbol->getIndex() : 0; 1073 1074 if (is64Bit()) { 1075 write(Entry.Offset); 1076 if (TargetObjectWriter->isN64()) { 1077 write(uint32_t(Index)); 1078 1079 write(TargetObjectWriter->getRSsym(Entry.Type)); 1080 write(TargetObjectWriter->getRType3(Entry.Type)); 1081 write(TargetObjectWriter->getRType2(Entry.Type)); 1082 write(TargetObjectWriter->getRType(Entry.Type)); 1083 } else { 1084 struct ELF::Elf64_Rela ERE64; 1085 ERE64.setSymbolAndType(Index, Entry.Type); 1086 write(ERE64.r_info); 1087 } 1088 if (hasRelocationAddend()) 1089 write(Entry.Addend); 1090 } else { 1091 write(uint32_t(Entry.Offset)); 1092 1093 struct ELF::Elf32_Rela ERE32; 1094 ERE32.setSymbolAndType(Index, Entry.Type); 1095 write(ERE32.r_info); 1096 1097 if (hasRelocationAddend()) 1098 write(uint32_t(Entry.Addend)); 1099 } 1100 } 1101 } 1102 1103 const MCSectionELF *ELFObjectWriter::createStringTable(MCContext &Ctx) { 1104 const MCSectionELF *StrtabSection = SectionTable[StringTableIndex - 1]; 1105 getStream() << StrTabBuilder.data(); 1106 return StrtabSection; 1107 } 1108 1109 void ELFObjectWriter::writeSection(const SectionIndexMapTy &SectionIndexMap, 1110 uint32_t GroupSymbolIndex, uint64_t Offset, 1111 uint64_t Size, const MCSectionELF &Section) { 1112 uint64_t sh_link = 0; 1113 uint64_t sh_info = 0; 1114 1115 switch(Section.getType()) { 1116 default: 1117 // Nothing to do. 1118 break; 1119 1120 case ELF::SHT_DYNAMIC: 1121 llvm_unreachable("SHT_DYNAMIC in a relocatable object"); 1122 1123 case ELF::SHT_REL: 1124 case ELF::SHT_RELA: { 1125 sh_link = SymbolTableIndex; 1126 assert(sh_link && ".symtab not found"); 1127 const MCSectionELF *InfoSection = Section.getAssociatedSection(); 1128 sh_info = SectionIndexMap.lookup(InfoSection); 1129 break; 1130 } 1131 1132 case ELF::SHT_SYMTAB: 1133 case ELF::SHT_DYNSYM: 1134 sh_link = StringTableIndex; 1135 sh_info = LastLocalSymbolIndex; 1136 break; 1137 1138 case ELF::SHT_SYMTAB_SHNDX: 1139 sh_link = SymbolTableIndex; 1140 break; 1141 1142 case ELF::SHT_GROUP: 1143 sh_link = SymbolTableIndex; 1144 sh_info = GroupSymbolIndex; 1145 break; 1146 } 1147 1148 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM && 1149 Section.getType() == ELF::SHT_ARM_EXIDX) 1150 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection()); 1151 1152 WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getSectionName()), 1153 Section.getType(), Section.getFlags(), 0, Offset, Size, 1154 sh_link, sh_info, Section.getAlignment(), 1155 Section.getEntrySize()); 1156 } 1157 1158 void ELFObjectWriter::writeSectionHeader( 1159 const MCAsmLayout &Layout, const SectionIndexMapTy &SectionIndexMap, 1160 const SectionOffsetsTy &SectionOffsets) { 1161 const unsigned NumSections = SectionTable.size(); 1162 1163 // Null section first. 1164 uint64_t FirstSectionSize = 1165 (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0; 1166 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0); 1167 1168 for (const MCSectionELF *Section : SectionTable) { 1169 uint32_t GroupSymbolIndex; 1170 unsigned Type = Section->getType(); 1171 if (Type != ELF::SHT_GROUP) 1172 GroupSymbolIndex = 0; 1173 else 1174 GroupSymbolIndex = Section->getGroup()->getIndex(); 1175 1176 const std::pair<uint64_t, uint64_t> &Offsets = 1177 SectionOffsets.find(Section)->second; 1178 uint64_t Size; 1179 if (Type == ELF::SHT_NOBITS) 1180 Size = Layout.getSectionAddressSize(Section); 1181 else 1182 Size = Offsets.second - Offsets.first; 1183 1184 writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size, 1185 *Section); 1186 } 1187 } 1188 1189 void ELFObjectWriter::writeObject(MCAssembler &Asm, 1190 const MCAsmLayout &Layout) { 1191 MCContext &Ctx = Asm.getContext(); 1192 MCSectionELF *StrtabSection = 1193 Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0); 1194 StringTableIndex = addToSectionTable(StrtabSection); 1195 1196 RevGroupMapTy RevGroupMap; 1197 SectionIndexMapTy SectionIndexMap; 1198 1199 std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers; 1200 1201 // Write out the ELF header ... 1202 writeHeader(Asm); 1203 1204 // ... then the sections ... 1205 SectionOffsetsTy SectionOffsets; 1206 std::vector<MCSectionELF *> Groups; 1207 std::vector<MCSectionELF *> Relocations; 1208 for (MCSection &Sec : Asm) { 1209 MCSectionELF &Section = static_cast<MCSectionELF &>(Sec); 1210 1211 align(Section.getAlignment()); 1212 1213 // Remember the offset into the file for this section. 1214 uint64_t SecStart = getStream().tell(); 1215 1216 const MCSymbolELF *SignatureSymbol = Section.getGroup(); 1217 writeSectionData(Asm, Section, Layout); 1218 1219 uint64_t SecEnd = getStream().tell(); 1220 SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd); 1221 1222 MCSectionELF *RelSection = createRelocationSection(Ctx, Section); 1223 1224 if (SignatureSymbol) { 1225 Asm.registerSymbol(*SignatureSymbol); 1226 unsigned &GroupIdx = RevGroupMap[SignatureSymbol]; 1227 if (!GroupIdx) { 1228 MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol); 1229 GroupIdx = addToSectionTable(Group); 1230 Group->setAlignment(4); 1231 Groups.push_back(Group); 1232 } 1233 std::vector<const MCSectionELF *> &Members = 1234 GroupMembers[SignatureSymbol]; 1235 Members.push_back(&Section); 1236 if (RelSection) 1237 Members.push_back(RelSection); 1238 } 1239 1240 SectionIndexMap[&Section] = addToSectionTable(&Section); 1241 if (RelSection) { 1242 SectionIndexMap[RelSection] = addToSectionTable(RelSection); 1243 Relocations.push_back(RelSection); 1244 } 1245 } 1246 1247 for (MCSectionELF *Group : Groups) { 1248 align(Group->getAlignment()); 1249 1250 // Remember the offset into the file for this section. 1251 uint64_t SecStart = getStream().tell(); 1252 1253 const MCSymbol *SignatureSymbol = Group->getGroup(); 1254 assert(SignatureSymbol); 1255 write(uint32_t(ELF::GRP_COMDAT)); 1256 for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) { 1257 uint32_t SecIndex = SectionIndexMap.lookup(Member); 1258 write(SecIndex); 1259 } 1260 1261 uint64_t SecEnd = getStream().tell(); 1262 SectionOffsets[Group] = std::make_pair(SecStart, SecEnd); 1263 } 1264 1265 // Compute symbol table information. 1266 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap, SectionOffsets); 1267 1268 for (MCSectionELF *RelSection : Relocations) { 1269 align(RelSection->getAlignment()); 1270 1271 // Remember the offset into the file for this section. 1272 uint64_t SecStart = getStream().tell(); 1273 1274 writeRelocations(Asm, *RelSection->getAssociatedSection()); 1275 1276 uint64_t SecEnd = getStream().tell(); 1277 SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd); 1278 } 1279 1280 { 1281 uint64_t SecStart = getStream().tell(); 1282 const MCSectionELF *Sec = createStringTable(Ctx); 1283 uint64_t SecEnd = getStream().tell(); 1284 SectionOffsets[Sec] = std::make_pair(SecStart, SecEnd); 1285 } 1286 1287 uint64_t NaturalAlignment = is64Bit() ? 8 : 4; 1288 align(NaturalAlignment); 1289 1290 const uint64_t SectionHeaderOffset = getStream().tell(); 1291 1292 // ... then the section header table ... 1293 writeSectionHeader(Layout, SectionIndexMap, SectionOffsets); 1294 1295 uint16_t NumSections = (SectionTable.size() + 1 >= ELF::SHN_LORESERVE) 1296 ? (uint16_t)ELF::SHN_UNDEF 1297 : SectionTable.size() + 1; 1298 if (sys::IsLittleEndianHost != IsLittleEndian) 1299 sys::swapByteOrder(NumSections); 1300 unsigned NumSectionsOffset; 1301 1302 if (is64Bit()) { 1303 uint64_t Val = SectionHeaderOffset; 1304 if (sys::IsLittleEndianHost != IsLittleEndian) 1305 sys::swapByteOrder(Val); 1306 getStream().pwrite(reinterpret_cast<char *>(&Val), sizeof(Val), 1307 offsetof(ELF::Elf64_Ehdr, e_shoff)); 1308 NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum); 1309 } else { 1310 uint32_t Val = SectionHeaderOffset; 1311 if (sys::IsLittleEndianHost != IsLittleEndian) 1312 sys::swapByteOrder(Val); 1313 getStream().pwrite(reinterpret_cast<char *>(&Val), sizeof(Val), 1314 offsetof(ELF::Elf32_Ehdr, e_shoff)); 1315 NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum); 1316 } 1317 getStream().pwrite(reinterpret_cast<char *>(&NumSections), 1318 sizeof(NumSections), NumSectionsOffset); 1319 } 1320 1321 bool ELFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl( 1322 const MCAssembler &Asm, const MCSymbol &SA, const MCFragment &FB, 1323 bool InSet, bool IsPCRel) const { 1324 const auto &SymA = cast<MCSymbolELF>(SA); 1325 if (IsPCRel) { 1326 assert(!InSet); 1327 if (::isWeak(SymA)) 1328 return false; 1329 } 1330 return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB, 1331 InSet, IsPCRel); 1332 } 1333 1334 bool ELFObjectWriter::isWeak(const MCSymbol &S) const { 1335 const auto &Sym = cast<MCSymbolELF>(S); 1336 if (::isWeak(Sym)) 1337 return true; 1338 1339 // It is invalid to replace a reference to a global in a comdat 1340 // with a reference to a local since out of comdat references 1341 // to a local are forbidden. 1342 // We could try to return false for more cases, like the reference 1343 // being in the same comdat or Sym being an alias to another global, 1344 // but it is not clear if it is worth the effort. 1345 if (Sym.getBinding() != ELF::STB_GLOBAL) 1346 return false; 1347 1348 if (!Sym.isInSection()) 1349 return false; 1350 1351 const auto &Sec = cast<MCSectionELF>(Sym.getSection()); 1352 return Sec.getGroup(); 1353 } 1354 1355 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW, 1356 raw_pwrite_stream &OS, 1357 bool IsLittleEndian) { 1358 return new ELFObjectWriter(MOTW, OS, IsLittleEndian); 1359 } 1360