ELFObjectWriter.cpp revision aa71428378c1cb491ca60041d8ba7aa110bc963d
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 "MCELF.h"
15#include "llvm/ADT/OwningPtr.h"
16#include "llvm/ADT/SmallPtrSet.h"
17#include "llvm/ADT/SmallString.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/StringMap.h"
20#include "llvm/MC/MCAsmBackend.h"
21#include "llvm/MC/MCAsmLayout.h"
22#include "llvm/MC/MCAssembler.h"
23#include "llvm/MC/MCContext.h"
24#include "llvm/MC/MCELFObjectWriter.h"
25#include "llvm/MC/MCELFSymbolFlags.h"
26#include "llvm/MC/MCExpr.h"
27#include "llvm/MC/MCFixupKindInfo.h"
28#include "llvm/MC/MCObjectWriter.h"
29#include "llvm/MC/MCSectionELF.h"
30#include "llvm/MC/MCValue.h"
31#include "llvm/Support/Debug.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/ELF.h"
34
35#include <vector>
36using namespace llvm;
37
38#undef  DEBUG_TYPE
39#define DEBUG_TYPE "reloc-info"
40
41namespace {
42class ELFObjectWriter : public MCObjectWriter {
43  protected:
44
45    static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
46    static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
47    static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
48    static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
49                           bool Used, bool Renamed);
50    static bool isLocal(const MCSymbolData &Data, bool isSignature,
51                        bool isUsedInReloc);
52    static bool IsELFMetaDataSection(const MCSectionData &SD);
53    static uint64_t DataSectionSize(const MCSectionData &SD);
54    static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
55                                       const MCSectionData &SD);
56    static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
57                                          const MCSectionData &SD);
58
59    void WriteDataSectionData(MCAssembler &Asm,
60                              const MCAsmLayout &Layout,
61                              const MCSectionELF &Section);
62
63    /*static bool isFixupKindX86RIPRel(unsigned Kind) {
64      return Kind == X86::reloc_riprel_4byte ||
65        Kind == X86::reloc_riprel_4byte_movq_load;
66    }*/
67
68    /// ELFSymbolData - Helper struct for containing some precomputed
69    /// information on symbols.
70    struct ELFSymbolData {
71      MCSymbolData *SymbolData;
72      uint64_t StringIndex;
73      uint32_t SectionIndex;
74
75      // Support lexicographic sorting.
76      bool operator<(const ELFSymbolData &RHS) const {
77        if (MCELF::GetType(*SymbolData) == ELF::STT_FILE)
78          return true;
79        if (MCELF::GetType(*RHS.SymbolData) == ELF::STT_FILE)
80          return false;
81        return SymbolData->getSymbol().getName() <
82               RHS.SymbolData->getSymbol().getName();
83      }
84    };
85
86    /// The target specific ELF writer instance.
87    llvm::OwningPtr<MCELFObjectTargetWriter> TargetObjectWriter;
88
89    SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
90    SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
91    DenseMap<const MCSymbol *, const MCSymbol *> Renames;
92
93    llvm::DenseMap<const MCSectionData*,
94                   std::vector<ELFRelocationEntry> > Relocations;
95    DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
96
97    /// @}
98    /// @name Symbol Table Data
99    /// @{
100
101    SmallString<256> StringTable;
102    std::vector<ELFSymbolData> LocalSymbolData;
103    std::vector<ELFSymbolData> ExternalSymbolData;
104    std::vector<ELFSymbolData> UndefinedSymbolData;
105
106    /// @}
107
108    bool NeedsGOT;
109
110    bool NeedsSymtabShndx;
111
112    // This holds the symbol table index of the last local symbol.
113    unsigned LastLocalSymbolIndex;
114    // This holds the .strtab section index.
115    unsigned StringTableIndex;
116    // This holds the .symtab section index.
117    unsigned SymbolTableIndex;
118
119    unsigned ShstrtabIndex;
120
121
122    const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
123                                  const MCValue &Target,
124                                  const MCFragment &F,
125                                  const MCFixup &Fixup,
126                                  bool IsPCRel) const;
127
128    // TargetObjectWriter wrappers.
129    const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
130                                   const MCValue &Target,
131                                   const MCFragment &F,
132                                   const MCFixup &Fixup,
133                                   bool IsPCRel) const {
134      return TargetObjectWriter->ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
135    }
136    const MCSymbol *undefinedExplicitRelSym(const MCValue &Target,
137                                            const MCFixup &Fixup,
138                                            bool IsPCRel) const {
139      return TargetObjectWriter->undefinedExplicitRelSym(Target, Fixup, IsPCRel);
140    }
141
142    bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
143    bool hasRelocationAddend() const {
144      return TargetObjectWriter->hasRelocationAddend();
145    }
146    unsigned getEFlags() const {
147      return TargetObjectWriter->getEFlags();
148    }
149    unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
150                          bool IsPCRel, bool IsRelocWithSymbol,
151                          int64_t Addend) const {
152      return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel,
153                                              IsRelocWithSymbol, Addend);
154    }
155
156
157  public:
158    ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
159                    raw_ostream &_OS, bool IsLittleEndian)
160      : MCObjectWriter(_OS, IsLittleEndian),
161        TargetObjectWriter(MOTW),
162        NeedsGOT(false), NeedsSymtabShndx(false){
163    }
164
165    virtual ~ELFObjectWriter();
166
167    void WriteWord(uint64_t W) {
168      if (is64Bit())
169        Write64(W);
170      else
171        Write32(W);
172    }
173
174    void StringLE16(char *buf, uint16_t Value) {
175      buf[0] = char(Value >> 0);
176      buf[1] = char(Value >> 8);
177    }
178
179    void StringLE32(char *buf, uint32_t Value) {
180      StringLE16(buf, uint16_t(Value >> 0));
181      StringLE16(buf + 2, uint16_t(Value >> 16));
182    }
183
184    void StringLE64(char *buf, uint64_t Value) {
185      StringLE32(buf, uint32_t(Value >> 0));
186      StringLE32(buf + 4, uint32_t(Value >> 32));
187    }
188
189    void StringBE16(char *buf ,uint16_t Value) {
190      buf[0] = char(Value >> 8);
191      buf[1] = char(Value >> 0);
192    }
193
194    void StringBE32(char *buf, uint32_t Value) {
195      StringBE16(buf, uint16_t(Value >> 16));
196      StringBE16(buf + 2, uint16_t(Value >> 0));
197    }
198
199    void StringBE64(char *buf, uint64_t Value) {
200      StringBE32(buf, uint32_t(Value >> 32));
201      StringBE32(buf + 4, uint32_t(Value >> 0));
202    }
203
204    void String8(MCDataFragment &F, uint8_t Value) {
205      char buf[1];
206      buf[0] = Value;
207      F.getContents() += StringRef(buf, 1);
208    }
209
210    void String16(MCDataFragment &F, uint16_t Value) {
211      char buf[2];
212      if (isLittleEndian())
213        StringLE16(buf, Value);
214      else
215        StringBE16(buf, Value);
216      F.getContents() += StringRef(buf, 2);
217    }
218
219    void String32(MCDataFragment &F, uint32_t Value) {
220      char buf[4];
221      if (isLittleEndian())
222        StringLE32(buf, Value);
223      else
224        StringBE32(buf, Value);
225      F.getContents() += StringRef(buf, 4);
226    }
227
228    void String64(MCDataFragment &F, uint64_t Value) {
229      char buf[8];
230      if (isLittleEndian())
231        StringLE64(buf, Value);
232      else
233        StringBE64(buf, Value);
234      F.getContents() += StringRef(buf, 8);
235    }
236
237    void WriteHeader(uint64_t SectionDataSize,
238                     unsigned NumberOfSections);
239
240    void WriteSymbolEntry(MCDataFragment *SymtabF,
241                          MCDataFragment *ShndxF,
242                          uint64_t name, uint8_t info,
243                          uint64_t value, uint64_t size,
244                          uint8_t other, uint32_t shndx,
245                          bool Reserved);
246
247    void WriteSymbol(MCDataFragment *SymtabF,  MCDataFragment *ShndxF,
248                     ELFSymbolData &MSD,
249                     const MCAsmLayout &Layout);
250
251    typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
252    void WriteSymbolTable(MCDataFragment *SymtabF,
253                          MCDataFragment *ShndxF,
254                          const MCAssembler &Asm,
255                          const MCAsmLayout &Layout,
256                          const SectionIndexMapTy &SectionIndexMap);
257
258    virtual void RecordRelocation(const MCAssembler &Asm,
259                                  const MCAsmLayout &Layout,
260                                  const MCFragment *Fragment,
261                                  const MCFixup &Fixup,
262                                  MCValue Target, uint64_t &FixedValue);
263
264    uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
265                                         const MCSymbol *S);
266
267    // Map from a group section to the signature symbol
268    typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
269    // Map from a signature symbol to the group section
270    typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
271    // Map from a section to the section with the relocations
272    typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
273    // Map from a section to its offset
274    typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
275
276    /// ComputeSymbolTable - Compute the symbol table data
277    ///
278    /// \param Asm - The assembler.
279    /// \param SectionIndexMap - Maps a section to its index.
280    /// \param RevGroupMap - Maps a signature symbol to the group section.
281    /// \param NumRegularSections - Number of non-relocation sections.
282    void ComputeSymbolTable(MCAssembler &Asm,
283                            const SectionIndexMapTy &SectionIndexMap,
284                            RevGroupMapTy RevGroupMap,
285                            unsigned NumRegularSections);
286
287    void ComputeIndexMap(MCAssembler &Asm,
288                         SectionIndexMapTy &SectionIndexMap,
289                         const RelMapTy &RelMap);
290
291    void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
292                                  RelMapTy &RelMap);
293
294    void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
295                          const RelMapTy &RelMap);
296
297    void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
298                                SectionIndexMapTy &SectionIndexMap,
299                                const RelMapTy &RelMap);
300
301    // Create the sections that show up in the symbol table. Currently
302    // those are the .note.GNU-stack section and the group sections.
303    void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
304                               GroupMapTy &GroupMap,
305                               RevGroupMapTy &RevGroupMap,
306                               SectionIndexMapTy &SectionIndexMap,
307                               const RelMapTy &RelMap);
308
309    virtual void ExecutePostLayoutBinding(MCAssembler &Asm,
310                                          const MCAsmLayout &Layout);
311
312    void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
313                            const MCAsmLayout &Layout,
314                            const SectionIndexMapTy &SectionIndexMap,
315                            const SectionOffsetMapTy &SectionOffsetMap);
316
317    void ComputeSectionOrder(MCAssembler &Asm,
318                             std::vector<const MCSectionELF*> &Sections);
319
320    void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
321                          uint64_t Address, uint64_t Offset,
322                          uint64_t Size, uint32_t Link, uint32_t Info,
323                          uint64_t Alignment, uint64_t EntrySize);
324
325    void WriteRelocationsFragment(const MCAssembler &Asm,
326                                  MCDataFragment *F,
327                                  const MCSectionData *SD);
328
329    virtual bool
330    IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
331                                           const MCSymbolData &DataA,
332                                           const MCFragment &FB,
333                                           bool InSet,
334                                           bool IsPCRel) const;
335
336    virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
337    void WriteSection(MCAssembler &Asm,
338                      const SectionIndexMapTy &SectionIndexMap,
339                      uint32_t GroupSymbolIndex,
340                      uint64_t Offset, uint64_t Size, uint64_t Alignment,
341                      const MCSectionELF &Section);
342  };
343}
344
345bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
346  const MCFixupKindInfo &FKI =
347    Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
348
349  return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
350}
351
352bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
353  switch (Variant) {
354  default:
355    return false;
356  case MCSymbolRefExpr::VK_GOT:
357  case MCSymbolRefExpr::VK_PLT:
358  case MCSymbolRefExpr::VK_GOTPCREL:
359  case MCSymbolRefExpr::VK_GOTOFF:
360  case MCSymbolRefExpr::VK_TPOFF:
361  case MCSymbolRefExpr::VK_TLSGD:
362  case MCSymbolRefExpr::VK_GOTTPOFF:
363  case MCSymbolRefExpr::VK_INDNTPOFF:
364  case MCSymbolRefExpr::VK_NTPOFF:
365  case MCSymbolRefExpr::VK_GOTNTPOFF:
366  case MCSymbolRefExpr::VK_TLSLDM:
367  case MCSymbolRefExpr::VK_DTPOFF:
368  case MCSymbolRefExpr::VK_TLSLD:
369    return true;
370  }
371}
372
373ELFObjectWriter::~ELFObjectWriter()
374{}
375
376// Emit the ELF header.
377void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
378                                  unsigned NumberOfSections) {
379  // ELF Header
380  // ----------
381  //
382  // Note
383  // ----
384  // emitWord method behaves differently for ELF32 and ELF64, writing
385  // 4 bytes in the former and 8 in the latter.
386
387  Write8(0x7f); // e_ident[EI_MAG0]
388  Write8('E');  // e_ident[EI_MAG1]
389  Write8('L');  // e_ident[EI_MAG2]
390  Write8('F');  // e_ident[EI_MAG3]
391
392  Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
393
394  // e_ident[EI_DATA]
395  Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
396
397  Write8(ELF::EV_CURRENT);        // e_ident[EI_VERSION]
398  // e_ident[EI_OSABI]
399  Write8(TargetObjectWriter->getOSABI());
400  Write8(0);                  // e_ident[EI_ABIVERSION]
401
402  WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
403
404  Write16(ELF::ET_REL);             // e_type
405
406  Write16(TargetObjectWriter->getEMachine()); // e_machine = target
407
408  Write32(ELF::EV_CURRENT);         // e_version
409  WriteWord(0);                    // e_entry, no entry point in .o file
410  WriteWord(0);                    // e_phoff, no program header for .o
411  WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
412            sizeof(ELF::Elf32_Ehdr)));  // e_shoff = sec hdr table off in bytes
413
414  // e_flags = whatever the target wants
415  Write32(getEFlags());
416
417  // e_ehsize = ELF header size
418  Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
419
420  Write16(0);                  // e_phentsize = prog header entry size
421  Write16(0);                  // e_phnum = # prog header entries = 0
422
423  // e_shentsize = Section header entry size
424  Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
425
426  // e_shnum     = # of section header ents
427  if (NumberOfSections >= ELF::SHN_LORESERVE)
428    Write16(ELF::SHN_UNDEF);
429  else
430    Write16(NumberOfSections);
431
432  // e_shstrndx  = Section # of '.shstrtab'
433  if (ShstrtabIndex >= ELF::SHN_LORESERVE)
434    Write16(ELF::SHN_XINDEX);
435  else
436    Write16(ShstrtabIndex);
437}
438
439void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
440                                       MCDataFragment *ShndxF,
441                                       uint64_t name,
442                                       uint8_t info, uint64_t value,
443                                       uint64_t size, uint8_t other,
444                                       uint32_t shndx,
445                                       bool Reserved) {
446  if (ShndxF) {
447    if (shndx >= ELF::SHN_LORESERVE && !Reserved)
448      String32(*ShndxF, shndx);
449    else
450      String32(*ShndxF, 0);
451  }
452
453  uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
454    uint16_t(ELF::SHN_XINDEX) : shndx;
455
456  if (is64Bit()) {
457    String32(*SymtabF, name);  // st_name
458    String8(*SymtabF, info);   // st_info
459    String8(*SymtabF, other);  // st_other
460    String16(*SymtabF, Index); // st_shndx
461    String64(*SymtabF, value); // st_value
462    String64(*SymtabF, size);  // st_size
463  } else {
464    String32(*SymtabF, name);  // st_name
465    String32(*SymtabF, value); // st_value
466    String32(*SymtabF, size);  // st_size
467    String8(*SymtabF, info);   // st_info
468    String8(*SymtabF, other);  // st_other
469    String16(*SymtabF, Index); // st_shndx
470  }
471}
472
473uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
474                                      const MCAsmLayout &Layout) {
475  if (Data.isCommon() && Data.isExternal())
476    return Data.getCommonAlignment();
477
478  const MCSymbol &Symbol = Data.getSymbol();
479
480  if (Symbol.isAbsolute() && Symbol.isVariable()) {
481    if (const MCExpr *Value = Symbol.getVariableValue()) {
482      int64_t IntValue;
483      if (Value->EvaluateAsAbsolute(IntValue, Layout))
484        return (uint64_t)IntValue;
485    }
486  }
487
488  if (!Symbol.isInSection())
489    return 0;
490
491
492  if (Data.getFragment()) {
493    if (Data.getFlags() & ELF_Other_ThumbFunc)
494      return Layout.getSymbolOffset(&Data)+1;
495    else
496      return Layout.getSymbolOffset(&Data);
497  }
498
499  return 0;
500}
501
502void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
503                                               const MCAsmLayout &Layout) {
504  // The presence of symbol versions causes undefined symbols and
505  // versions declared with @@@ to be renamed.
506
507  for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
508         ie = Asm.symbol_end(); it != ie; ++it) {
509    const MCSymbol &Alias = it->getSymbol();
510    const MCSymbol &Symbol = Alias.AliasedSymbol();
511    MCSymbolData &SD = Asm.getSymbolData(Symbol);
512
513    // Not an alias.
514    if (&Symbol == &Alias)
515      continue;
516
517    StringRef AliasName = Alias.getName();
518    size_t Pos = AliasName.find('@');
519    if (Pos == StringRef::npos)
520      continue;
521
522    // Aliases defined with .symvar copy the binding from the symbol they alias.
523    // This is the first place we are able to copy this information.
524    it->setExternal(SD.isExternal());
525    MCELF::SetBinding(*it, MCELF::GetBinding(SD));
526
527    StringRef Rest = AliasName.substr(Pos);
528    if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
529      continue;
530
531    // FIXME: produce a better error message.
532    if (Symbol.isUndefined() && Rest.startswith("@@") &&
533        !Rest.startswith("@@@"))
534      report_fatal_error("A @@ version cannot be undefined");
535
536    Renames.insert(std::make_pair(&Symbol, &Alias));
537  }
538}
539
540void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
541                                  MCDataFragment *ShndxF,
542                                  ELFSymbolData &MSD,
543                                  const MCAsmLayout &Layout) {
544  MCSymbolData &OrigData = *MSD.SymbolData;
545  MCSymbolData &Data =
546    Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
547
548  bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
549    Data.getSymbol().isVariable();
550
551  uint8_t Binding = MCELF::GetBinding(OrigData);
552  uint8_t Visibility = MCELF::GetVisibility(OrigData);
553  uint8_t Type = MCELF::GetType(Data);
554
555  uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
556  uint8_t Other = Visibility;
557
558  uint64_t Value = SymbolValue(Data, Layout);
559  uint64_t Size = 0;
560
561  assert(!(Data.isCommon() && !Data.isExternal()));
562
563  const MCExpr *ESize = Data.getSize();
564  if (ESize) {
565    int64_t Res;
566    if (!ESize->EvaluateAsAbsolute(Res, Layout))
567      report_fatal_error("Size expression must be absolute.");
568    Size = Res;
569  }
570
571  // Write out the symbol table entry
572  WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
573                   Size, Other, MSD.SectionIndex, IsReserved);
574}
575
576void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
577                                       MCDataFragment *ShndxF,
578                                       const MCAssembler &Asm,
579                                       const MCAsmLayout &Layout,
580                                    const SectionIndexMapTy &SectionIndexMap) {
581  // The string table must be emitted first because we need the index
582  // into the string table for all the symbol names.
583  assert(StringTable.size() && "Missing string table");
584
585  // FIXME: Make sure the start of the symbol table is aligned.
586
587  // The first entry is the undefined symbol entry.
588  WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
589
590  // Write the symbol table entries.
591  LastLocalSymbolIndex = LocalSymbolData.size() + 1;
592  for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
593    ELFSymbolData &MSD = LocalSymbolData[i];
594    WriteSymbol(SymtabF, ShndxF, MSD, Layout);
595  }
596
597  // Write out a symbol table entry for each regular section.
598  for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
599       ++i) {
600    const MCSectionELF &Section =
601      static_cast<const MCSectionELF&>(i->getSection());
602    if (Section.getType() == ELF::SHT_RELA ||
603        Section.getType() == ELF::SHT_REL ||
604        Section.getType() == ELF::SHT_STRTAB ||
605        Section.getType() == ELF::SHT_SYMTAB ||
606        Section.getType() == ELF::SHT_SYMTAB_SHNDX)
607      continue;
608    WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
609                     ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section),
610                     false);
611    LastLocalSymbolIndex++;
612  }
613
614  for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
615    ELFSymbolData &MSD = ExternalSymbolData[i];
616    MCSymbolData &Data = *MSD.SymbolData;
617    assert(((Data.getFlags() & ELF_STB_Global) ||
618            (Data.getFlags() & ELF_STB_Weak)) &&
619           "External symbol requires STB_GLOBAL or STB_WEAK flag");
620    WriteSymbol(SymtabF, ShndxF, MSD, Layout);
621    if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
622      LastLocalSymbolIndex++;
623  }
624
625  for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
626    ELFSymbolData &MSD = UndefinedSymbolData[i];
627    MCSymbolData &Data = *MSD.SymbolData;
628    WriteSymbol(SymtabF, ShndxF, MSD, Layout);
629    if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
630      LastLocalSymbolIndex++;
631  }
632}
633
634const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
635                                               const MCValue &Target,
636                                               const MCFragment &F,
637                                               const MCFixup &Fixup,
638                                               bool IsPCRel) const {
639  const MCSymbol &Symbol = Target.getSymA()->getSymbol();
640  const MCSymbol &ASymbol = Symbol.AliasedSymbol();
641  const MCSymbol *Renamed = Renames.lookup(&Symbol);
642  const MCSymbolData &SD = Asm.getSymbolData(Symbol);
643
644  if (ASymbol.isUndefined()) {
645    if (Renamed)
646      return Renamed;
647    return undefinedExplicitRelSym(Target, Fixup, IsPCRel);
648  }
649
650  if (SD.isExternal()) {
651    if (Renamed)
652      return Renamed;
653    return &Symbol;
654  }
655
656  const MCSectionELF &Section =
657    static_cast<const MCSectionELF&>(ASymbol.getSection());
658  const SectionKind secKind = Section.getKind();
659
660  if (secKind.isBSS())
661    return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
662
663  if (secKind.isThreadLocal()) {
664    if (Renamed)
665      return Renamed;
666    return &Symbol;
667  }
668
669  MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
670  const MCSectionELF &Sec2 =
671    static_cast<const MCSectionELF&>(F.getParent()->getSection());
672
673  if (&Sec2 != &Section &&
674      (Kind == MCSymbolRefExpr::VK_PLT ||
675       Kind == MCSymbolRefExpr::VK_GOTPCREL ||
676       Kind == MCSymbolRefExpr::VK_GOTOFF)) {
677    if (Renamed)
678      return Renamed;
679    return &Symbol;
680  }
681
682  if (Section.getFlags() & ELF::SHF_MERGE) {
683    if (Target.getConstant() == 0)
684      return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
685    if (Renamed)
686      return Renamed;
687    return &Symbol;
688  }
689
690  return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
691
692}
693
694
695void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
696                                       const MCAsmLayout &Layout,
697                                       const MCFragment *Fragment,
698                                       const MCFixup &Fixup,
699                                       MCValue Target,
700                                       uint64_t &FixedValue) {
701  int64_t Addend = 0;
702  int Index = 0;
703  int64_t Value = Target.getConstant();
704  const MCSymbol *RelocSymbol = NULL;
705
706  bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
707  if (!Target.isAbsolute()) {
708    const MCSymbol &Symbol = Target.getSymA()->getSymbol();
709    const MCSymbol &ASymbol = Symbol.AliasedSymbol();
710    RelocSymbol = SymbolToReloc(Asm, Target, *Fragment, Fixup, IsPCRel);
711
712    if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
713      const MCSymbol &SymbolB = RefB->getSymbol();
714      MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
715      IsPCRel = true;
716
717      // Offset of the symbol in the section
718      int64_t a = Layout.getSymbolOffset(&SDB);
719
720      // Offset of the relocation in the section
721      int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
722      Value += b - a;
723    }
724
725    if (!RelocSymbol) {
726      MCSymbolData &SD = Asm.getSymbolData(ASymbol);
727      MCFragment *F = SD.getFragment();
728
729      if (F) {
730        Index = F->getParent()->getOrdinal() + 1;
731        // Offset of the symbol in the section
732        Value += Layout.getSymbolOffset(&SD);
733      } else {
734        Index = 0;
735      }
736    } else {
737      if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
738        WeakrefUsedInReloc.insert(RelocSymbol);
739      else
740        UsedInReloc.insert(RelocSymbol);
741      Index = -1;
742    }
743    Addend = Value;
744    if (hasRelocationAddend())
745      Value = 0;
746  }
747
748  FixedValue = Value;
749  unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
750                               (RelocSymbol != 0), Addend);
751  MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
752    MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
753  if (RelocNeedsGOT(Modifier))
754    NeedsGOT = true;
755
756  uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
757    Fixup.getOffset();
758
759  // FIXME: no tests cover this. Is adjustFixupOffset dead code?
760  TargetObjectWriter->adjustFixupOffset(Fixup, RelocOffset);
761
762  if (!hasRelocationAddend())
763    Addend = 0;
764
765  if (is64Bit())
766    assert(isInt<64>(Addend));
767  else
768    assert(isInt<32>(Addend));
769
770  ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend, Fixup);
771  Relocations[Fragment->getParent()].push_back(ERE);
772}
773
774
775uint64_t
776ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
777                                             const MCSymbol *S) {
778  MCSymbolData &SD = Asm.getSymbolData(*S);
779  return SD.getIndex();
780}
781
782bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
783                                 const MCSymbolData &Data,
784                                 bool Used, bool Renamed) {
785  if (Data.getFlags() & ELF_Other_Weakref)
786    return false;
787
788  if (Used)
789    return true;
790
791  if (Renamed)
792    return false;
793
794  const MCSymbol &Symbol = Data.getSymbol();
795
796  if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
797    return true;
798
799  const MCSymbol &A = Symbol.AliasedSymbol();
800  if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
801    return false;
802
803  bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
804  if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
805    return false;
806
807  if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
808    return false;
809
810  if (Symbol.isTemporary())
811    return false;
812
813  return true;
814}
815
816bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
817                              bool isUsedInReloc) {
818  if (Data.isExternal())
819    return false;
820
821  const MCSymbol &Symbol = Data.getSymbol();
822  const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
823
824  if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
825    if (isSignature && !isUsedInReloc)
826      return true;
827
828    return false;
829  }
830
831  return true;
832}
833
834void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
835                                      SectionIndexMapTy &SectionIndexMap,
836                                      const RelMapTy &RelMap) {
837  unsigned Index = 1;
838  for (MCAssembler::iterator it = Asm.begin(),
839         ie = Asm.end(); it != ie; ++it) {
840    const MCSectionELF &Section =
841      static_cast<const MCSectionELF &>(it->getSection());
842    if (Section.getType() != ELF::SHT_GROUP)
843      continue;
844    SectionIndexMap[&Section] = Index++;
845  }
846
847  for (MCAssembler::iterator it = Asm.begin(),
848         ie = Asm.end(); it != ie; ++it) {
849    const MCSectionELF &Section =
850      static_cast<const MCSectionELF &>(it->getSection());
851    if (Section.getType() == ELF::SHT_GROUP ||
852        Section.getType() == ELF::SHT_REL ||
853        Section.getType() == ELF::SHT_RELA)
854      continue;
855    SectionIndexMap[&Section] = Index++;
856    const MCSectionELF *RelSection = RelMap.lookup(&Section);
857    if (RelSection)
858      SectionIndexMap[RelSection] = Index++;
859  }
860}
861
862void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
863                                      const SectionIndexMapTy &SectionIndexMap,
864                                         RevGroupMapTy RevGroupMap,
865                                         unsigned NumRegularSections) {
866  // FIXME: Is this the correct place to do this?
867  // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
868  if (NeedsGOT) {
869    llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
870    MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
871    MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
872    Data.setExternal(true);
873    MCELF::SetBinding(Data, ELF::STB_GLOBAL);
874  }
875
876  // Index 0 is always the empty string.
877  StringMap<uint64_t> StringIndexMap;
878  StringTable += '\x00';
879
880  // FIXME: We could optimize suffixes in strtab in the same way we
881  // optimize them in shstrtab.
882
883  // Add the data for the symbols.
884  for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
885         ie = Asm.symbol_end(); it != ie; ++it) {
886    const MCSymbol &Symbol = it->getSymbol();
887
888    bool Used = UsedInReloc.count(&Symbol);
889    bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
890    bool isSignature = RevGroupMap.count(&Symbol);
891
892    if (!isInSymtab(Asm, *it,
893                    Used || WeakrefUsed || isSignature,
894                    Renames.count(&Symbol)))
895      continue;
896
897    ELFSymbolData MSD;
898    MSD.SymbolData = it;
899    const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
900
901    // Undefined symbols are global, but this is the first place we
902    // are able to set it.
903    bool Local = isLocal(*it, isSignature, Used);
904    if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
905      MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
906      MCELF::SetBinding(*it, ELF::STB_GLOBAL);
907      MCELF::SetBinding(SD, ELF::STB_GLOBAL);
908    }
909
910    if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
911      MCELF::SetBinding(*it, ELF::STB_WEAK);
912
913    if (it->isCommon()) {
914      assert(!Local);
915      MSD.SectionIndex = ELF::SHN_COMMON;
916    } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
917      MSD.SectionIndex = ELF::SHN_ABS;
918    } else if (RefSymbol.isUndefined()) {
919      if (isSignature && !Used)
920        MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
921      else
922        MSD.SectionIndex = ELF::SHN_UNDEF;
923    } else {
924      const MCSectionELF &Section =
925        static_cast<const MCSectionELF&>(RefSymbol.getSection());
926      MSD.SectionIndex = SectionIndexMap.lookup(&Section);
927      if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
928        NeedsSymtabShndx = true;
929      assert(MSD.SectionIndex && "Invalid section index!");
930    }
931
932    // The @@@ in symbol version is replaced with @ in undefined symbols and
933    // @@ in defined ones.
934    StringRef Name = Symbol.getName();
935    SmallString<32> Buf;
936
937    size_t Pos = Name.find("@@@");
938    if (Pos != StringRef::npos) {
939      Buf += Name.substr(0, Pos);
940      unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
941      Buf += Name.substr(Pos + Skip);
942      Name = Buf;
943    }
944
945    uint64_t &Entry = StringIndexMap[Name];
946    if (!Entry) {
947      Entry = StringTable.size();
948      StringTable += Name;
949      StringTable += '\x00';
950    }
951    MSD.StringIndex = Entry;
952    if (MSD.SectionIndex == ELF::SHN_UNDEF)
953      UndefinedSymbolData.push_back(MSD);
954    else if (Local)
955      LocalSymbolData.push_back(MSD);
956    else
957      ExternalSymbolData.push_back(MSD);
958  }
959
960  // Symbols are required to be in lexicographic order.
961  array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
962  array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
963  array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
964
965  // Set the symbol indices. Local symbols must come before all other
966  // symbols with non-local bindings.
967  unsigned Index = 1;
968  for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
969    LocalSymbolData[i].SymbolData->setIndex(Index++);
970
971  Index += NumRegularSections;
972
973  for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
974    ExternalSymbolData[i].SymbolData->setIndex(Index++);
975  for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
976    UndefinedSymbolData[i].SymbolData->setIndex(Index++);
977
978  if (NumRegularSections > ELF::SHN_LORESERVE)
979    NeedsSymtabShndx = true;
980}
981
982void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
983                                               MCAsmLayout &Layout,
984                                               RelMapTy &RelMap) {
985  for (MCAssembler::const_iterator it = Asm.begin(),
986         ie = Asm.end(); it != ie; ++it) {
987    const MCSectionData &SD = *it;
988    if (Relocations[&SD].empty())
989      continue;
990
991    MCContext &Ctx = Asm.getContext();
992    const MCSectionELF &Section =
993      static_cast<const MCSectionELF&>(SD.getSection());
994
995    const StringRef SectionName = Section.getSectionName();
996    std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
997    RelaSectionName += SectionName;
998
999    unsigned EntrySize;
1000    if (hasRelocationAddend())
1001      EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1002    else
1003      EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1004
1005    const MCSectionELF *RelaSection =
1006      Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1007                        ELF::SHT_RELA : ELF::SHT_REL, 0,
1008                        SectionKind::getReadOnly(),
1009                        EntrySize, "");
1010    RelMap[&Section] = RelaSection;
1011    Asm.getOrCreateSectionData(*RelaSection);
1012  }
1013}
1014
1015void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1016                                       const RelMapTy &RelMap) {
1017  for (MCAssembler::const_iterator it = Asm.begin(),
1018         ie = Asm.end(); it != ie; ++it) {
1019    const MCSectionData &SD = *it;
1020    const MCSectionELF &Section =
1021      static_cast<const MCSectionELF&>(SD.getSection());
1022
1023    const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1024    if (!RelaSection)
1025      continue;
1026    MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1027    RelaSD.setAlignment(is64Bit() ? 8 : 4);
1028
1029    MCDataFragment *F = new MCDataFragment(&RelaSD);
1030    WriteRelocationsFragment(Asm, F, &*it);
1031  }
1032}
1033
1034void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1035                                       uint64_t Flags, uint64_t Address,
1036                                       uint64_t Offset, uint64_t Size,
1037                                       uint32_t Link, uint32_t Info,
1038                                       uint64_t Alignment,
1039                                       uint64_t EntrySize) {
1040  Write32(Name);        // sh_name: index into string table
1041  Write32(Type);        // sh_type
1042  WriteWord(Flags);     // sh_flags
1043  WriteWord(Address);   // sh_addr
1044  WriteWord(Offset);    // sh_offset
1045  WriteWord(Size);      // sh_size
1046  Write32(Link);        // sh_link
1047  Write32(Info);        // sh_info
1048  WriteWord(Alignment); // sh_addralign
1049  WriteWord(EntrySize); // sh_entsize
1050}
1051
1052void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1053                                               MCDataFragment *F,
1054                                               const MCSectionData *SD) {
1055  std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1056
1057  // Sort the relocation entries. Most targets just sort by r_offset, but some
1058  // (e.g., MIPS) have additional constraints.
1059  TargetObjectWriter->sortRelocs(Asm, Relocs);
1060
1061  for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1062    ELFRelocationEntry entry = Relocs[e - i - 1];
1063
1064    if (!entry.Index)
1065      ;
1066    else if (entry.Index < 0)
1067      entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1068    else
1069      entry.Index += LocalSymbolData.size();
1070    if (is64Bit()) {
1071      String64(*F, entry.r_offset);
1072      if (TargetObjectWriter->isN64()) {
1073        String32(*F, entry.Index);
1074
1075        String8(*F, TargetObjectWriter->getRSsym(entry.Type));
1076        String8(*F, TargetObjectWriter->getRType3(entry.Type));
1077        String8(*F, TargetObjectWriter->getRType2(entry.Type));
1078        String8(*F, TargetObjectWriter->getRType(entry.Type));
1079      }
1080      else {
1081        struct ELF::Elf64_Rela ERE64;
1082        ERE64.setSymbolAndType(entry.Index, entry.Type);
1083        String64(*F, ERE64.r_info);
1084      }
1085      if (hasRelocationAddend())
1086        String64(*F, entry.r_addend);
1087    } else {
1088      String32(*F, entry.r_offset);
1089
1090      struct ELF::Elf32_Rela ERE32;
1091      ERE32.setSymbolAndType(entry.Index, entry.Type);
1092      String32(*F, ERE32.r_info);
1093
1094      if (hasRelocationAddend())
1095        String32(*F, entry.r_addend);
1096    }
1097  }
1098}
1099
1100static int compareBySuffix(const void *a, const void *b) {
1101  const MCSectionELF *secA = *static_cast<const MCSectionELF* const *>(a);
1102  const MCSectionELF *secB = *static_cast<const MCSectionELF* const *>(b);
1103  const StringRef &NameA = secA->getSectionName();
1104  const StringRef &NameB = secB->getSectionName();
1105  const unsigned sizeA = NameA.size();
1106  const unsigned sizeB = NameB.size();
1107  const unsigned len = std::min(sizeA, sizeB);
1108  for (unsigned int i = 0; i < len; ++i) {
1109    char ca = NameA[sizeA - i - 1];
1110    char cb = NameB[sizeB - i - 1];
1111    if (ca != cb)
1112      return cb - ca;
1113  }
1114
1115  return sizeB - sizeA;
1116}
1117
1118void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1119                                             MCAsmLayout &Layout,
1120                                             SectionIndexMapTy &SectionIndexMap,
1121                                             const RelMapTy &RelMap) {
1122  MCContext &Ctx = Asm.getContext();
1123  MCDataFragment *F;
1124
1125  unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1126
1127  // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1128  const MCSectionELF *ShstrtabSection =
1129    Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1130                      SectionKind::getReadOnly());
1131  MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1132  ShstrtabSD.setAlignment(1);
1133
1134  const MCSectionELF *SymtabSection =
1135    Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1136                      SectionKind::getReadOnly(),
1137                      EntrySize, "");
1138  MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1139  SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1140
1141  MCSectionData *SymtabShndxSD = NULL;
1142
1143  if (NeedsSymtabShndx) {
1144    const MCSectionELF *SymtabShndxSection =
1145      Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1146                        SectionKind::getReadOnly(), 4, "");
1147    SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1148    SymtabShndxSD->setAlignment(4);
1149  }
1150
1151  const MCSectionELF *StrtabSection;
1152  StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1153                                    SectionKind::getReadOnly());
1154  MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1155  StrtabSD.setAlignment(1);
1156
1157  ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1158
1159  ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1160  SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1161  StringTableIndex = SectionIndexMap.lookup(StrtabSection);
1162
1163  // Symbol table
1164  F = new MCDataFragment(&SymtabSD);
1165  MCDataFragment *ShndxF = NULL;
1166  if (NeedsSymtabShndx) {
1167    ShndxF = new MCDataFragment(SymtabShndxSD);
1168  }
1169  WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1170
1171  F = new MCDataFragment(&StrtabSD);
1172  F->getContents().append(StringTable.begin(), StringTable.end());
1173
1174  F = new MCDataFragment(&ShstrtabSD);
1175
1176  std::vector<const MCSectionELF*> Sections;
1177  for (MCAssembler::const_iterator it = Asm.begin(),
1178         ie = Asm.end(); it != ie; ++it) {
1179    const MCSectionELF &Section =
1180      static_cast<const MCSectionELF&>(it->getSection());
1181    Sections.push_back(&Section);
1182  }
1183  array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
1184
1185  // Section header string table.
1186  //
1187  // The first entry of a string table holds a null character so skip
1188  // section 0.
1189  uint64_t Index = 1;
1190  F->getContents() += '\x00';
1191
1192  for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
1193    const MCSectionELF &Section = *Sections[I];
1194
1195    StringRef Name = Section.getSectionName();
1196    if (I != 0) {
1197      StringRef PreviousName = Sections[I - 1]->getSectionName();
1198      if (PreviousName.endswith(Name)) {
1199        SectionStringTableIndex[&Section] = Index - Name.size() - 1;
1200        continue;
1201      }
1202    }
1203    // Remember the index into the string table so we can write it
1204    // into the sh_name field of the section header table.
1205    SectionStringTableIndex[&Section] = Index;
1206
1207    Index += Name.size() + 1;
1208    F->getContents() += Name;
1209    F->getContents() += '\x00';
1210  }
1211}
1212
1213void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1214                                            MCAsmLayout &Layout,
1215                                            GroupMapTy &GroupMap,
1216                                            RevGroupMapTy &RevGroupMap,
1217                                            SectionIndexMapTy &SectionIndexMap,
1218                                            const RelMapTy &RelMap) {
1219  // Create the .note.GNU-stack section if needed.
1220  MCContext &Ctx = Asm.getContext();
1221  if (Asm.getNoExecStack()) {
1222    const MCSectionELF *GnuStackSection =
1223      Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1224                        SectionKind::getReadOnly());
1225    Asm.getOrCreateSectionData(*GnuStackSection);
1226  }
1227
1228  // Build the groups
1229  for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1230       it != ie; ++it) {
1231    const MCSectionELF &Section =
1232      static_cast<const MCSectionELF&>(it->getSection());
1233    if (!(Section.getFlags() & ELF::SHF_GROUP))
1234      continue;
1235
1236    const MCSymbol *SignatureSymbol = Section.getGroup();
1237    Asm.getOrCreateSymbolData(*SignatureSymbol);
1238    const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1239    if (!Group) {
1240      Group = Ctx.CreateELFGroupSection();
1241      MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1242      Data.setAlignment(4);
1243      MCDataFragment *F = new MCDataFragment(&Data);
1244      String32(*F, ELF::GRP_COMDAT);
1245    }
1246    GroupMap[Group] = SignatureSymbol;
1247  }
1248
1249  ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1250
1251  // Add sections to the groups
1252  for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1253       it != ie; ++it) {
1254    const MCSectionELF &Section =
1255      static_cast<const MCSectionELF&>(it->getSection());
1256    if (!(Section.getFlags() & ELF::SHF_GROUP))
1257      continue;
1258    const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1259    MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1260    // FIXME: we could use the previous fragment
1261    MCDataFragment *F = new MCDataFragment(&Data);
1262    unsigned Index = SectionIndexMap.lookup(&Section);
1263    String32(*F, Index);
1264  }
1265}
1266
1267void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1268                                   const SectionIndexMapTy &SectionIndexMap,
1269                                   uint32_t GroupSymbolIndex,
1270                                   uint64_t Offset, uint64_t Size,
1271                                   uint64_t Alignment,
1272                                   const MCSectionELF &Section) {
1273  uint64_t sh_link = 0;
1274  uint64_t sh_info = 0;
1275
1276  switch(Section.getType()) {
1277  case ELF::SHT_DYNAMIC:
1278    sh_link = SectionStringTableIndex[&Section];
1279    sh_info = 0;
1280    break;
1281
1282  case ELF::SHT_REL:
1283  case ELF::SHT_RELA: {
1284    const MCSectionELF *SymtabSection;
1285    const MCSectionELF *InfoSection;
1286    SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1287                                                   0,
1288                                                   SectionKind::getReadOnly());
1289    sh_link = SectionIndexMap.lookup(SymtabSection);
1290    assert(sh_link && ".symtab not found");
1291
1292    // Remove ".rel" and ".rela" prefixes.
1293    unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1294    StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1295
1296    InfoSection = Asm.getContext().getELFSection(SectionName,
1297                                                 ELF::SHT_PROGBITS, 0,
1298                                                 SectionKind::getReadOnly());
1299    sh_info = SectionIndexMap.lookup(InfoSection);
1300    break;
1301  }
1302
1303  case ELF::SHT_SYMTAB:
1304  case ELF::SHT_DYNSYM:
1305    sh_link = StringTableIndex;
1306    sh_info = LastLocalSymbolIndex;
1307    break;
1308
1309  case ELF::SHT_SYMTAB_SHNDX:
1310    sh_link = SymbolTableIndex;
1311    break;
1312
1313  case ELF::SHT_PROGBITS:
1314  case ELF::SHT_STRTAB:
1315  case ELF::SHT_NOBITS:
1316  case ELF::SHT_NOTE:
1317  case ELF::SHT_NULL:
1318  case ELF::SHT_ARM_ATTRIBUTES:
1319  case ELF::SHT_INIT_ARRAY:
1320  case ELF::SHT_FINI_ARRAY:
1321  case ELF::SHT_PREINIT_ARRAY:
1322  case ELF::SHT_X86_64_UNWIND:
1323    // Nothing to do.
1324    break;
1325
1326  case ELF::SHT_GROUP:
1327    sh_link = SymbolTableIndex;
1328    sh_info = GroupSymbolIndex;
1329    break;
1330
1331  default:
1332    assert(0 && "FIXME: sh_type value not supported!");
1333    break;
1334  }
1335
1336  WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1337                   Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1338                   Alignment, Section.getEntrySize());
1339}
1340
1341bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1342  return SD.getOrdinal() == ~UINT32_C(0) &&
1343    !SD.getSection().isVirtualSection();
1344}
1345
1346uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1347  uint64_t Ret = 0;
1348  for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1349       ++i) {
1350    const MCFragment &F = *i;
1351    assert(F.getKind() == MCFragment::FT_Data);
1352    Ret += cast<MCDataFragment>(F).getContents().size();
1353  }
1354  return Ret;
1355}
1356
1357uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1358                                             const MCSectionData &SD) {
1359  if (IsELFMetaDataSection(SD))
1360    return DataSectionSize(SD);
1361  return Layout.getSectionFileSize(&SD);
1362}
1363
1364uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1365                                                const MCSectionData &SD) {
1366  if (IsELFMetaDataSection(SD))
1367    return DataSectionSize(SD);
1368  return Layout.getSectionAddressSize(&SD);
1369}
1370
1371void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1372                                           const MCAsmLayout &Layout,
1373                                           const MCSectionELF &Section) {
1374  const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1375
1376  uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1377  WriteZeros(Padding);
1378
1379  if (IsELFMetaDataSection(SD)) {
1380    for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1381         ++i) {
1382      const MCFragment &F = *i;
1383      assert(F.getKind() == MCFragment::FT_Data);
1384      WriteBytes(cast<MCDataFragment>(F).getContents().str());
1385    }
1386  } else {
1387    Asm.writeSectionData(&SD, Layout);
1388  }
1389}
1390
1391void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1392                                         const GroupMapTy &GroupMap,
1393                                         const MCAsmLayout &Layout,
1394                                      const SectionIndexMapTy &SectionIndexMap,
1395                                   const SectionOffsetMapTy &SectionOffsetMap) {
1396  const unsigned NumSections = Asm.size() + 1;
1397
1398  std::vector<const MCSectionELF*> Sections;
1399  Sections.resize(NumSections - 1);
1400
1401  for (SectionIndexMapTy::const_iterator i=
1402         SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1403    const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1404    Sections[p.second - 1] = p.first;
1405  }
1406
1407  // Null section first.
1408  uint64_t FirstSectionSize =
1409    NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1410  uint32_t FirstSectionLink =
1411    ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1412  WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1413
1414  for (unsigned i = 0; i < NumSections - 1; ++i) {
1415    const MCSectionELF &Section = *Sections[i];
1416    const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1417    uint32_t GroupSymbolIndex;
1418    if (Section.getType() != ELF::SHT_GROUP)
1419      GroupSymbolIndex = 0;
1420    else
1421      GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1422                                                     GroupMap.lookup(&Section));
1423
1424    uint64_t Size = GetSectionAddressSize(Layout, SD);
1425
1426    WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1427                 SectionOffsetMap.lookup(&Section), Size,
1428                 SD.getAlignment(), Section);
1429  }
1430}
1431
1432void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1433                                  std::vector<const MCSectionELF*> &Sections) {
1434  for (MCAssembler::iterator it = Asm.begin(),
1435         ie = Asm.end(); it != ie; ++it) {
1436    const MCSectionELF &Section =
1437      static_cast<const MCSectionELF &>(it->getSection());
1438    if (Section.getType() == ELF::SHT_GROUP)
1439      Sections.push_back(&Section);
1440  }
1441
1442  for (MCAssembler::iterator it = Asm.begin(),
1443         ie = Asm.end(); it != ie; ++it) {
1444    const MCSectionELF &Section =
1445      static_cast<const MCSectionELF &>(it->getSection());
1446    if (Section.getType() != ELF::SHT_GROUP &&
1447        Section.getType() != ELF::SHT_REL &&
1448        Section.getType() != ELF::SHT_RELA)
1449      Sections.push_back(&Section);
1450  }
1451
1452  for (MCAssembler::iterator it = Asm.begin(),
1453         ie = Asm.end(); it != ie; ++it) {
1454    const MCSectionELF &Section =
1455      static_cast<const MCSectionELF &>(it->getSection());
1456    if (Section.getType() == ELF::SHT_REL ||
1457        Section.getType() == ELF::SHT_RELA)
1458      Sections.push_back(&Section);
1459  }
1460}
1461
1462void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1463                                  const MCAsmLayout &Layout) {
1464  GroupMapTy GroupMap;
1465  RevGroupMapTy RevGroupMap;
1466  SectionIndexMapTy SectionIndexMap;
1467
1468  unsigned NumUserSections = Asm.size();
1469
1470  DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1471  CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1472
1473  const unsigned NumUserAndRelocSections = Asm.size();
1474  CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1475                        RevGroupMap, SectionIndexMap, RelMap);
1476  const unsigned AllSections = Asm.size();
1477  const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1478
1479  unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1480
1481  // Compute symbol table information.
1482  ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap, NumRegularSections);
1483
1484
1485  WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1486
1487  CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1488                         const_cast<MCAsmLayout&>(Layout),
1489                         SectionIndexMap,
1490                         RelMap);
1491
1492  uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1493  uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1494                                    sizeof(ELF::Elf32_Ehdr);
1495  uint64_t FileOff = HeaderSize;
1496
1497  std::vector<const MCSectionELF*> Sections;
1498  ComputeSectionOrder(Asm, Sections);
1499  unsigned NumSections = Sections.size();
1500  SectionOffsetMapTy SectionOffsetMap;
1501  for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1502    const MCSectionELF &Section = *Sections[i];
1503    const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1504
1505    FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1506
1507    // Remember the offset into the file for this section.
1508    SectionOffsetMap[&Section] = FileOff;
1509
1510    // Get the size of the section in the output file (including padding).
1511    FileOff += GetSectionFileSize(Layout, SD);
1512  }
1513
1514  FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1515
1516  const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1517
1518  uint64_t SectionHeaderEntrySize = is64Bit() ?
1519    sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1520  FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1521
1522  for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1523    const MCSectionELF &Section = *Sections[i];
1524    const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1525
1526    FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1527
1528    // Remember the offset into the file for this section.
1529    SectionOffsetMap[&Section] = FileOff;
1530
1531    // Get the size of the section in the output file (including padding).
1532    FileOff += GetSectionFileSize(Layout, SD);
1533  }
1534
1535  // Write out the ELF header ...
1536  WriteHeader(SectionHeaderOffset, NumSections + 1);
1537
1538  // ... then the regular sections ...
1539  // + because of .shstrtab
1540  for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1541    WriteDataSectionData(Asm, Layout, *Sections[i]);
1542
1543  uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1544  WriteZeros(Padding);
1545
1546  // ... then the section header table ...
1547  WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1548                     SectionOffsetMap);
1549
1550  // ... and then the remaining sections ...
1551  for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1552    WriteDataSectionData(Asm, Layout, *Sections[i]);
1553}
1554
1555bool
1556ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1557                                                      const MCSymbolData &DataA,
1558                                                      const MCFragment &FB,
1559                                                      bool InSet,
1560                                                      bool IsPCRel) const {
1561  if (DataA.getFlags() & ELF_STB_Weak)
1562    return false;
1563  return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1564                                                 Asm, DataA, FB,InSet, IsPCRel);
1565}
1566
1567MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1568                                            raw_ostream &OS,
1569                                            bool IsLittleEndian) {
1570  return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
1571}
1572