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