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