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