LCOV - code coverage report
Current view: top level - lib/MC - ELFObjectWriter.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 577 589 98.0 %
Date: 2017-09-14 15:23:50 Functions: 34 34 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13