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