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