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