Use 'override/final' instead of 'virtual' for overridden methods
[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     /// Helper struct for containing some precomputed information on symbols.
116     struct ELFSymbolData {
117       MCSymbolData *SymbolData;
118       uint64_t StringIndex;
119       uint32_t SectionIndex;
120       StringRef Name;
121
122       // Support lexicographic sorting.
123       bool operator<(const ELFSymbolData &RHS) const {
124         unsigned LHSType = MCELF::GetType(*SymbolData);
125         unsigned RHSType = MCELF::GetType(*RHS.SymbolData);
126         if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
127           return false;
128         if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
129           return true;
130         if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
131           return SectionIndex < RHS.SectionIndex;
132         return Name < RHS.Name;
133       }
134     };
135
136     /// The target specific ELF writer instance.
137     std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
138
139     SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
140     SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
141     DenseMap<const MCSymbol *, const MCSymbol *> Renames;
142
143     llvm::DenseMap<const MCSectionData *, std::vector<ELFRelocationEntry>>
144     Relocations;
145     StringTableBuilder ShStrTabBuilder;
146
147     /// @}
148     /// @name Symbol Table Data
149     /// @{
150
151     StringTableBuilder StrTabBuilder;
152     std::vector<uint64_t> FileSymbolData;
153     std::vector<ELFSymbolData> LocalSymbolData;
154     std::vector<ELFSymbolData> ExternalSymbolData;
155     std::vector<ELFSymbolData> UndefinedSymbolData;
156
157     /// @}
158
159     bool NeedsGOT;
160
161     // This holds the symbol table index of the last local symbol.
162     unsigned LastLocalSymbolIndex;
163     // This holds the .strtab section index.
164     unsigned StringTableIndex;
165     // This holds the .symtab section index.
166     unsigned SymbolTableIndex;
167
168     unsigned ShstrtabIndex;
169
170
171     // TargetObjectWriter wrappers.
172     bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
173     bool hasRelocationAddend() const {
174       return TargetObjectWriter->hasRelocationAddend();
175     }
176     unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
177                           bool IsPCRel) const {
178       return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
179     }
180
181   public:
182     ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_ostream &OS,
183                     bool IsLittleEndian)
184         : MCObjectWriter(OS, IsLittleEndian), FWriter(IsLittleEndian),
185           TargetObjectWriter(MOTW), NeedsGOT(false) {}
186
187     void reset() override {
188       UsedInReloc.clear();
189       WeakrefUsedInReloc.clear();
190       Renames.clear();
191       Relocations.clear();
192       ShStrTabBuilder.clear();
193       StrTabBuilder.clear();
194       FileSymbolData.clear();
195       LocalSymbolData.clear();
196       ExternalSymbolData.clear();
197       UndefinedSymbolData.clear();
198       MCObjectWriter::reset();
199     }
200
201     ~ELFObjectWriter() override;
202
203     void WriteWord(uint64_t W) {
204       if (is64Bit())
205         Write64(W);
206       else
207         Write32(W);
208     }
209
210     template <typename T> void write(MCDataFragment &F, T Value) {
211       FWriter.write(F, Value);
212     }
213
214     void WriteHeader(const MCAssembler &Asm,
215                      uint64_t SectionHeaderOffset,
216                      unsigned NumberOfSections);
217
218     void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
219                      const MCAsmLayout &Layout);
220
221     void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
222                           const MCAsmLayout &Layout,
223                           SectionIndexMapTy &SectionIndexMap);
224
225     bool shouldRelocateWithSymbol(const MCAssembler &Asm,
226                                   const MCSymbolRefExpr *RefA,
227                                   const MCSymbolData *SD, uint64_t C,
228                                   unsigned Type) const;
229
230     void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
231                           const MCFragment *Fragment, const MCFixup &Fixup,
232                           MCValue Target, bool &IsPCRel,
233                           uint64_t &FixedValue) override;
234
235     uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
236                                          const MCSymbol *S);
237
238     // Map from a group section to the signature symbol
239     typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
240     // Map from a signature symbol to the group section
241     typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
242     // Map from a section to its offset
243     typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
244
245     /// Compute the symbol table data
246     ///
247     /// \param Asm - The assembler.
248     /// \param SectionIndexMap - Maps a section to its index.
249     /// \param RevGroupMap - Maps a signature symbol to the group section.
250     void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
251                             const SectionIndexMapTy &SectionIndexMap,
252                             const RevGroupMapTy &RevGroupMap);
253
254     void computeIndexMap(MCAssembler &Asm, SectionIndexMapTy &SectionIndexMap);
255
256     MCSectionData *createRelocationSection(MCAssembler &Asm,
257                                            const MCSectionData &SD);
258
259     void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
260
261     void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout);
262
263     void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
264                                 SectionIndexMapTy &SectionIndexMap);
265
266     // Create the sections that show up in the symbol table. Currently
267     // those are the .note.GNU-stack section and the group sections.
268     void createIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
269                                GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap,
270                                SectionIndexMapTy &SectionIndexMap);
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 MCSymbolData *DataB,
296                                            const MCFragment &FB,
297                                            bool InSet,
298                                            bool IsPCRel) const override;
299
300     bool isWeak(const MCSymbolData &SD) const override;
301
302     void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
303     void writeSection(MCAssembler &Asm,
304                       const SectionIndexMapTy &SectionIndexMap,
305                       uint32_t GroupSymbolIndex,
306                       uint64_t Offset, uint64_t Size, uint64_t Alignment,
307                       const MCSectionELF &Section);
308   };
309 }
310
311 FragmentWriter::FragmentWriter(bool IsLittleEndian)
312     : IsLittleEndian(IsLittleEndian) {}
313
314 template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
315   if (IsLittleEndian)
316     Val = support::endian::byte_swap<T, support::little>(Val);
317   else
318     Val = support::endian::byte_swap<T, support::big>(Val);
319   const char *Start = (const char *)&Val;
320   F.getContents().append(Start, Start + sizeof(T));
321 }
322
323 void SymbolTableWriter::createSymtabShndx() {
324   if (ShndxF)
325     return;
326
327   MCContext &Ctx = Asm.getContext();
328   const MCSectionELF *SymtabShndxSection =
329       Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
330   MCSectionData *SymtabShndxSD =
331       &Asm.getOrCreateSectionData(*SymtabShndxSection);
332   SymtabShndxSD->setAlignment(4);
333   ShndxF = new MCDataFragment(SymtabShndxSD);
334   unsigned Index = SectionIndexMap.size() + 1;
335   SectionIndexMap[SymtabShndxSection] = Index;
336
337   for (unsigned I = 0; I < NumWritten; ++I)
338     write(*ShndxF, uint32_t(0));
339 }
340
341 template <typename T>
342 void SymbolTableWriter::write(MCDataFragment &F, T Value) {
343   FWriter.write(F, Value);
344 }
345
346 SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
347                                      bool Is64Bit,
348                                      SectionIndexMapTy &SectionIndexMap,
349                                      MCDataFragment *SymtabF)
350     : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
351       SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
352       NumWritten(0) {}
353
354 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
355                                     uint64_t size, uint8_t other,
356                                     uint32_t shndx, bool Reserved) {
357   bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
358
359   if (LargeIndex)
360     createSymtabShndx();
361
362   if (ShndxF) {
363     if (LargeIndex)
364       write(*ShndxF, shndx);
365     else
366       write(*ShndxF, uint32_t(0));
367   }
368
369   uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
370
371   if (Is64Bit) {
372     write(*SymtabF, name);  // st_name
373     write(*SymtabF, info);  // st_info
374     write(*SymtabF, other); // st_other
375     write(*SymtabF, Index); // st_shndx
376     write(*SymtabF, value); // st_value
377     write(*SymtabF, size);  // st_size
378   } else {
379     write(*SymtabF, name);            // st_name
380     write(*SymtabF, uint32_t(value)); // st_value
381     write(*SymtabF, uint32_t(size));  // st_size
382     write(*SymtabF, info);            // st_info
383     write(*SymtabF, other);           // st_other
384     write(*SymtabF, Index);           // st_shndx
385   }
386
387   ++NumWritten;
388 }
389
390 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
391   const MCFixupKindInfo &FKI =
392     Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
393
394   return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
395 }
396
397 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
398   switch (Variant) {
399   default:
400     return false;
401   case MCSymbolRefExpr::VK_GOT:
402   case MCSymbolRefExpr::VK_PLT:
403   case MCSymbolRefExpr::VK_GOTPCREL:
404   case MCSymbolRefExpr::VK_GOTOFF:
405   case MCSymbolRefExpr::VK_TPOFF:
406   case MCSymbolRefExpr::VK_TLSGD:
407   case MCSymbolRefExpr::VK_GOTTPOFF:
408   case MCSymbolRefExpr::VK_INDNTPOFF:
409   case MCSymbolRefExpr::VK_NTPOFF:
410   case MCSymbolRefExpr::VK_GOTNTPOFF:
411   case MCSymbolRefExpr::VK_TLSLDM:
412   case MCSymbolRefExpr::VK_DTPOFF:
413   case MCSymbolRefExpr::VK_TLSLD:
414     return true;
415   }
416 }
417
418 ELFObjectWriter::~ELFObjectWriter()
419 {}
420
421 // Emit the ELF header.
422 void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
423                                   uint64_t SectionHeaderOffset,
424                                   unsigned NumberOfSections) {
425   // ELF Header
426   // ----------
427   //
428   // Note
429   // ----
430   // emitWord method behaves differently for ELF32 and ELF64, writing
431   // 4 bytes in the former and 8 in the latter.
432
433   Write8(0x7f); // e_ident[EI_MAG0]
434   Write8('E');  // e_ident[EI_MAG1]
435   Write8('L');  // e_ident[EI_MAG2]
436   Write8('F');  // e_ident[EI_MAG3]
437
438   Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
439
440   // e_ident[EI_DATA]
441   Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
442
443   Write8(ELF::EV_CURRENT);        // e_ident[EI_VERSION]
444   // e_ident[EI_OSABI]
445   Write8(TargetObjectWriter->getOSABI());
446   Write8(0);                  // e_ident[EI_ABIVERSION]
447
448   WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
449
450   Write16(ELF::ET_REL);             // e_type
451
452   Write16(TargetObjectWriter->getEMachine()); // e_machine = target
453
454   Write32(ELF::EV_CURRENT);         // e_version
455   WriteWord(0);                    // e_entry, no entry point in .o file
456   WriteWord(0);                    // e_phoff, no program header for .o
457   WriteWord(SectionHeaderOffset);  // 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->evaluateKnownAbsolute(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 static bool isWeak(const MCSymbolData &D) {
790   return D.getFlags() & ELF_STB_Weak || MCELF::GetType(D) == ELF::STT_GNU_IFUNC;
791 }
792
793 void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
794                                        const MCAsmLayout &Layout,
795                                        const MCFragment *Fragment,
796                                        const MCFixup &Fixup, MCValue Target,
797                                        bool &IsPCRel, uint64_t &FixedValue) {
798   const MCSectionData *FixupSection = Fragment->getParent();
799   uint64_t C = Target.getConstant();
800   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
801
802   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
803     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
804            "Should not have constructed this");
805
806     // Let A, B and C being the components of Target and R be the location of
807     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
808     // If it is pcrel, we want to compute (A - B + C - R).
809
810     // In general, ELF has no relocations for -B. It can only represent (A + C)
811     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
812     // replace B to implement it: (A - R - K + C)
813     if (IsPCRel)
814       Asm.getContext().FatalError(
815           Fixup.getLoc(),
816           "No relocation available to represent this relative expression");
817
818     const MCSymbol &SymB = RefB->getSymbol();
819
820     if (SymB.isUndefined())
821       Asm.getContext().FatalError(
822           Fixup.getLoc(),
823           Twine("symbol '") + SymB.getName() +
824               "' can not be undefined in a subtraction expression");
825
826     assert(!SymB.isAbsolute() && "Should have been folded");
827     const MCSection &SecB = SymB.getSection();
828     if (&SecB != &FixupSection->getSection())
829       Asm.getContext().FatalError(
830           Fixup.getLoc(), "Cannot represent a difference across sections");
831
832     const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
833     if (::isWeak(SymBD))
834       Asm.getContext().FatalError(
835           Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
836
837     uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
838     uint64_t K = SymBOffset - FixupOffset;
839     IsPCRel = true;
840     C -= K;
841   }
842
843   // We either rejected the fixup or folded B into C at this point.
844   const MCSymbolRefExpr *RefA = Target.getSymA();
845   const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
846   const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
847
848   unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
849   bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
850   if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
851     C += Layout.getSymbolOffset(SymAD);
852
853   uint64_t Addend = 0;
854   if (hasRelocationAddend()) {
855     Addend = C;
856     C = 0;
857   }
858
859   FixedValue = C;
860
861   // FIXME: What is this!?!?
862   MCSymbolRefExpr::VariantKind Modifier =
863       RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
864   if (RelocNeedsGOT(Modifier))
865     NeedsGOT = true;
866
867   if (!RelocateWithSymbol) {
868     const MCSection *SecA =
869         (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
870     auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
871     MCSymbol *SectionSymbol =
872         ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
873                : nullptr;
874     ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
875     Relocations[FixupSection].push_back(Rec);
876     return;
877   }
878
879   if (SymA) {
880     if (const MCSymbol *R = Renames.lookup(SymA))
881       SymA = R;
882
883     if (const MCSymbol *WeakRef = getWeakRef(*RefA))
884       WeakrefUsedInReloc.insert(WeakRef);
885     else
886       UsedInReloc.insert(SymA);
887   }
888   ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
889   Relocations[FixupSection].push_back(Rec);
890   return;
891 }
892
893
894 uint64_t
895 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
896                                              const MCSymbol *S) {
897   const MCSymbolData &SD = Asm.getSymbolData(*S);
898   return SD.getIndex();
899 }
900
901 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
902                                  const MCSymbolData &Data, bool Used,
903                                  bool Renamed) {
904   const MCSymbol &Symbol = Data.getSymbol();
905   if (Symbol.isVariable()) {
906     const MCExpr *Expr = Symbol.getVariableValue();
907     if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
908       if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
909         return false;
910     }
911   }
912
913   if (Used)
914     return true;
915
916   if (Renamed)
917     return false;
918
919   if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
920     return true;
921
922   if (Symbol.isVariable()) {
923     const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
924     if (Base && Base->isUndefined())
925       return false;
926   }
927
928   bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
929   if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
930     return false;
931
932   if (Symbol.isTemporary())
933     return false;
934
935   return true;
936 }
937
938 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
939   if (Data.isExternal())
940     return false;
941
942   const MCSymbol &Symbol = Data.getSymbol();
943   if (Symbol.isDefined())
944     return true;
945
946   if (isUsedInReloc)
947     return false;
948
949   return true;
950 }
951
952 void ELFObjectWriter::computeIndexMap(MCAssembler &Asm,
953                                       SectionIndexMapTy &SectionIndexMap) {
954   unsigned Index = 1;
955   for (MCAssembler::iterator it = Asm.begin(),
956          ie = Asm.end(); it != ie; ++it) {
957     const MCSectionELF &Section =
958       static_cast<const MCSectionELF &>(it->getSection());
959     if (Section.getType() != ELF::SHT_GROUP)
960       continue;
961     SectionIndexMap[&Section] = Index++;
962   }
963
964   for (MCAssembler::iterator it = Asm.begin(),
965          ie = Asm.end(); it != ie; ++it) {
966     const MCSectionData &SD = *it;
967     const MCSectionELF &Section =
968       static_cast<const MCSectionELF &>(SD.getSection());
969     if (Section.getType() == ELF::SHT_GROUP ||
970         Section.getType() == ELF::SHT_REL ||
971         Section.getType() == ELF::SHT_RELA)
972       continue;
973     SectionIndexMap[&Section] = Index++;
974     if (MCSectionData *RelSD = createRelocationSection(Asm, SD)) {
975       const MCSectionELF *RelSection =
976           static_cast<const MCSectionELF *>(&RelSD->getSection());
977       SectionIndexMap[RelSection] = Index++;
978     }
979   }
980 }
981
982 void ELFObjectWriter::computeSymbolTable(
983     MCAssembler &Asm, const MCAsmLayout &Layout,
984     const SectionIndexMapTy &SectionIndexMap,
985     const RevGroupMapTy &RevGroupMap) {
986   // FIXME: Is this the correct place to do this?
987   // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
988   if (NeedsGOT) {
989     StringRef Name = "_GLOBAL_OFFSET_TABLE_";
990     MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
991     MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
992     Data.setExternal(true);
993     MCELF::SetBinding(Data, ELF::STB_GLOBAL);
994   }
995
996   // Add the data for the symbols.
997   for (MCSymbolData &SD : Asm.symbols()) {
998     const MCSymbol &Symbol = SD.getSymbol();
999
1000     bool Used = UsedInReloc.count(&Symbol);
1001     bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
1002     bool isSignature = RevGroupMap.count(&Symbol);
1003
1004     if (!isInSymtab(Layout, SD,
1005                     Used || WeakrefUsed || isSignature,
1006                     Renames.count(&Symbol)))
1007       continue;
1008
1009     ELFSymbolData MSD;
1010     MSD.SymbolData = &SD;
1011     const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
1012
1013     // Undefined symbols are global, but this is the first place we
1014     // are able to set it.
1015     bool Local = isLocal(SD, Used);
1016     if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
1017       assert(BaseSymbol);
1018       MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
1019       MCELF::SetBinding(SD, ELF::STB_GLOBAL);
1020       MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
1021     }
1022
1023     if (!BaseSymbol) {
1024       MSD.SectionIndex = ELF::SHN_ABS;
1025     } else if (SD.isCommon()) {
1026       assert(!Local);
1027       MSD.SectionIndex = ELF::SHN_COMMON;
1028     } else if (BaseSymbol->isUndefined()) {
1029       if (isSignature && !Used)
1030         MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap.lookup(&Symbol));
1031       else
1032         MSD.SectionIndex = ELF::SHN_UNDEF;
1033       if (!Used && WeakrefUsed)
1034         MCELF::SetBinding(SD, ELF::STB_WEAK);
1035     } else {
1036       const MCSectionELF &Section =
1037         static_cast<const MCSectionELF&>(BaseSymbol->getSection());
1038       MSD.SectionIndex = SectionIndexMap.lookup(&Section);
1039       assert(MSD.SectionIndex && "Invalid section index!");
1040     }
1041
1042     // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1043     // in defined ones.
1044     //
1045     // FIXME: All name handling should be done before we get to the writer,
1046     // including dealing with GNU-style version suffixes.  Fixing this isn't
1047     // trivial.
1048     //
1049     // We thus have to be careful to not perform the symbol version replacement
1050     // blindly:
1051     //
1052     // The ELF format is used on Windows by the MCJIT engine.  Thus, on
1053     // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1054     // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1055     // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1056     // the EFLObjectWriter should not interpret the "@@@" sub-string as
1057     // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1058     // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1059     // "__imp_?" or "__imp_@?".
1060     //
1061     // It would have been interesting to perform the MS mangling prefix check
1062     // only when the target triple is of the form *-pc-windows-elf. But, it
1063     // seems that this information is not easily accessible from the
1064     // ELFObjectWriter.
1065     StringRef Name = Symbol.getName();
1066     if (!Name.startswith("?") && !Name.startswith("@?") &&
1067         !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1068       // This symbol isn't following the MSVC C++ name mangling convention. We
1069       // can thus safely interpret the @@@ in symbol names as specifying symbol
1070       // versioning.
1071       SmallString<32> Buf;
1072       size_t Pos = Name.find("@@@");
1073       if (Pos != StringRef::npos) {
1074         Buf += Name.substr(0, Pos);
1075         unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1076         Buf += Name.substr(Pos + Skip);
1077         Name = Buf;
1078       }
1079     }
1080
1081     // Sections have their own string table
1082     if (MCELF::GetType(SD) != ELF::STT_SECTION)
1083       MSD.Name = StrTabBuilder.add(Name);
1084
1085     if (MSD.SectionIndex == ELF::SHN_UNDEF)
1086       UndefinedSymbolData.push_back(MSD);
1087     else if (Local)
1088       LocalSymbolData.push_back(MSD);
1089     else
1090       ExternalSymbolData.push_back(MSD);
1091   }
1092
1093   for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1094     StrTabBuilder.add(*i);
1095
1096   StrTabBuilder.finalize(StringTableBuilder::ELF);
1097
1098   for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1099     FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1100
1101   for (ELFSymbolData &MSD : LocalSymbolData)
1102     MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1103                           ? 0
1104                           : StrTabBuilder.getOffset(MSD.Name);
1105   for (ELFSymbolData &MSD : ExternalSymbolData)
1106     MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1107   for (ELFSymbolData& MSD : UndefinedSymbolData)
1108     MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1109
1110   // Symbols are required to be in lexicographic order.
1111   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1112   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1113   array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1114
1115   // Set the symbol indices. Local symbols must come before all other
1116   // symbols with non-local bindings.
1117   unsigned Index = FileSymbolData.size() + 1;
1118   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1119     LocalSymbolData[i].SymbolData->setIndex(Index++);
1120
1121   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1122     ExternalSymbolData[i].SymbolData->setIndex(Index++);
1123   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1124     UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1125 }
1126
1127 MCSectionData *
1128 ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
1129                                          const MCSectionData &SD) {
1130   if (Relocations[&SD].empty())
1131     return nullptr;
1132
1133   MCContext &Ctx = Asm.getContext();
1134   const MCSectionELF &Section =
1135       static_cast<const MCSectionELF &>(SD.getSection());
1136
1137   const StringRef SectionName = Section.getSectionName();
1138   std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1139   RelaSectionName += SectionName;
1140
1141   unsigned EntrySize;
1142   if (hasRelocationAddend())
1143     EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1144   else
1145     EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1146
1147   unsigned Flags = 0;
1148   if (Section.getFlags() & ELF::SHF_GROUP)
1149     Flags = ELF::SHF_GROUP;
1150
1151   const MCSectionELF *RelaSection = Ctx.createELFRelSection(
1152       RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
1153       Flags, EntrySize, Section.getGroup(), &Section);
1154   return &Asm.getOrCreateSectionData(*RelaSection);
1155 }
1156
1157 static SmallVector<char, 128>
1158 getUncompressedData(MCAsmLayout &Layout,
1159                     MCSectionData::FragmentListType &Fragments) {
1160   SmallVector<char, 128> UncompressedData;
1161   for (const MCFragment &F : Fragments) {
1162     const SmallVectorImpl<char> *Contents;
1163     switch (F.getKind()) {
1164     case MCFragment::FT_Data:
1165       Contents = &cast<MCDataFragment>(F).getContents();
1166       break;
1167     case MCFragment::FT_Dwarf:
1168       Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1169       break;
1170     case MCFragment::FT_DwarfFrame:
1171       Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1172       break;
1173     default:
1174       llvm_unreachable(
1175           "Not expecting any other fragment types in a debug_* section");
1176     }
1177     UncompressedData.append(Contents->begin(), Contents->end());
1178   }
1179   return UncompressedData;
1180 }
1181
1182 // Include the debug info compression header:
1183 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1184 // useful for consumers to preallocate a buffer to decompress into.
1185 static bool
1186 prependCompressionHeader(uint64_t Size,
1187                          SmallVectorImpl<char> &CompressedContents) {
1188   const StringRef Magic = "ZLIB";
1189   if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1190     return false;
1191   if (sys::IsLittleEndianHost)
1192     sys::swapByteOrder(Size);
1193   CompressedContents.insert(CompressedContents.begin(),
1194                             Magic.size() + sizeof(Size), 0);
1195   std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1196   std::copy(reinterpret_cast<char *>(&Size),
1197             reinterpret_cast<char *>(&Size + 1),
1198             CompressedContents.begin() + Magic.size());
1199   return true;
1200 }
1201
1202 // Return a single fragment containing the compressed contents of the whole
1203 // section. Null if the section was not compressed for any reason.
1204 static std::unique_ptr<MCDataFragment>
1205 getCompressedFragment(MCAsmLayout &Layout,
1206                       MCSectionData::FragmentListType &Fragments) {
1207   std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1208
1209   // Gather the uncompressed data from all the fragments, recording the
1210   // alignment fragment, if seen, and any fixups.
1211   SmallVector<char, 128> UncompressedData =
1212       getUncompressedData(Layout, Fragments);
1213
1214   SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1215
1216   zlib::Status Success = zlib::compress(
1217       StringRef(UncompressedData.data(), UncompressedData.size()),
1218       CompressedContents);
1219   if (Success != zlib::StatusOK)
1220     return nullptr;
1221
1222   if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1223     return nullptr;
1224
1225   return CompressedFragment;
1226 }
1227
1228 typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1229 DefiningSymbolMap;
1230
1231 static void UpdateSymbols(const MCAsmLayout &Layout,
1232                           const std::vector<MCSymbolData *> &Symbols,
1233                           MCFragment &NewFragment) {
1234   for (MCSymbolData *Sym : Symbols) {
1235     Sym->setOffset(Sym->getOffset() +
1236                    Layout.getFragmentOffset(Sym->getFragment()));
1237     Sym->setFragment(&NewFragment);
1238   }
1239 }
1240
1241 static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
1242                                  const DefiningSymbolMap &DefiningSymbols,
1243                                  const MCSectionELF &Section,
1244                                  MCSectionData &SD) {
1245   StringRef SectionName = Section.getSectionName();
1246   MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1247
1248   std::unique_ptr<MCDataFragment> CompressedFragment =
1249       getCompressedFragment(Layout, Fragments);
1250
1251   // Leave the section as-is if the fragments could not be compressed.
1252   if (!CompressedFragment)
1253     return;
1254
1255   // Update the fragment+offsets of any symbols referring to fragments in this
1256   // section to refer to the new fragment.
1257   auto I = DefiningSymbols.find(&SD);
1258   if (I != DefiningSymbols.end())
1259     UpdateSymbols(Layout, I->second, *CompressedFragment);
1260
1261   // Invalidate the layout for the whole section since it will have new and
1262   // different fragments now.
1263   Layout.invalidateFragmentsFrom(&Fragments.front());
1264   Fragments.clear();
1265
1266   // Complete the initialization of the new fragment
1267   CompressedFragment->setParent(&SD);
1268   CompressedFragment->setLayoutOrder(0);
1269   Fragments.push_back(CompressedFragment.release());
1270
1271   // Rename from .debug_* to .zdebug_*
1272   Asm.getContext().renameELFSection(&Section,
1273                                     (".z" + SectionName.drop_front(1)).str());
1274 }
1275
1276 void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1277                                             MCAsmLayout &Layout) {
1278   if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1279     return;
1280
1281   DefiningSymbolMap DefiningSymbols;
1282
1283   for (MCSymbolData &SD : Asm.symbols())
1284     if (MCFragment *F = SD.getFragment())
1285       DefiningSymbols[F->getParent()].push_back(&SD);
1286
1287   for (MCSectionData &SD : Asm) {
1288     const MCSectionELF &Section =
1289         static_cast<const MCSectionELF &>(SD.getSection());
1290     StringRef SectionName = Section.getSectionName();
1291
1292     // Compressing debug_frame requires handling alignment fragments which is
1293     // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1294     // for writing to arbitrary buffers) for little benefit.
1295     if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1296       continue;
1297
1298     CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
1299   }
1300 }
1301
1302 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
1303   for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1304     MCSectionData &RelSD = *it;
1305     const MCSectionELF &RelSection =
1306         static_cast<const MCSectionELF &>(RelSD.getSection());
1307
1308     unsigned Type = RelSection.getType();
1309     if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
1310       continue;
1311
1312     const MCSectionELF *Section = RelSection.getAssociatedSection();
1313     MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1314     RelSD.setAlignment(is64Bit() ? 8 : 4);
1315
1316     MCDataFragment *F = new MCDataFragment(&RelSD);
1317     WriteRelocationsFragment(Asm, F, &SD);
1318   }
1319 }
1320
1321 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1322                                        uint64_t Flags, uint64_t Address,
1323                                        uint64_t Offset, uint64_t Size,
1324                                        uint32_t Link, uint32_t Info,
1325                                        uint64_t Alignment,
1326                                        uint64_t EntrySize) {
1327   Write32(Name);        // sh_name: index into string table
1328   Write32(Type);        // sh_type
1329   WriteWord(Flags);     // sh_flags
1330   WriteWord(Address);   // sh_addr
1331   WriteWord(Offset);    // sh_offset
1332   WriteWord(Size);      // sh_size
1333   Write32(Link);        // sh_link
1334   Write32(Info);        // sh_info
1335   WriteWord(Alignment); // sh_addralign
1336   WriteWord(EntrySize); // sh_entsize
1337 }
1338
1339 // ELF doesn't require relocations to be in any order. We sort by the r_offset,
1340 // just to match gnu as for easier comparison. The use type is an arbitrary way
1341 // of making the sort deterministic.
1342 static int cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
1343   const ELFRelocationEntry &A = *AP;
1344   const ELFRelocationEntry &B = *BP;
1345   if (A.Offset != B.Offset)
1346     return B.Offset - A.Offset;
1347   if (B.Type != A.Type)
1348     return A.Type - B.Type;
1349   //llvm_unreachable("ELFRelocs might be unstable!");
1350   return 0;
1351 }
1352
1353 static void sortRelocs(const MCAssembler &Asm,
1354                        std::vector<ELFRelocationEntry> &Relocs) {
1355   array_pod_sort(Relocs.begin(), Relocs.end(), cmpRel);
1356 }
1357
1358 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1359                                                MCDataFragment *F,
1360                                                const MCSectionData *SD) {
1361   std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1362
1363   sortRelocs(Asm, Relocs);
1364
1365   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1366     const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1367     unsigned Index =
1368         Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
1369
1370     if (is64Bit()) {
1371       write(*F, Entry.Offset);
1372       if (TargetObjectWriter->isN64()) {
1373         write(*F, uint32_t(Index));
1374
1375         write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1376         write(*F, TargetObjectWriter->getRType3(Entry.Type));
1377         write(*F, TargetObjectWriter->getRType2(Entry.Type));
1378         write(*F, TargetObjectWriter->getRType(Entry.Type));
1379       } else {
1380         struct ELF::Elf64_Rela ERE64;
1381         ERE64.setSymbolAndType(Index, Entry.Type);
1382         write(*F, ERE64.r_info);
1383       }
1384       if (hasRelocationAddend())
1385         write(*F, Entry.Addend);
1386     } else {
1387       write(*F, uint32_t(Entry.Offset));
1388
1389       struct ELF::Elf32_Rela ERE32;
1390       ERE32.setSymbolAndType(Index, Entry.Type);
1391       write(*F, ERE32.r_info);
1392
1393       if (hasRelocationAddend())
1394         write(*F, uint32_t(Entry.Addend));
1395     }
1396   }
1397 }
1398
1399 void ELFObjectWriter::CreateMetadataSections(
1400     MCAssembler &Asm, MCAsmLayout &Layout, SectionIndexMapTy &SectionIndexMap) {
1401   MCContext &Ctx = Asm.getContext();
1402   MCDataFragment *F;
1403
1404   unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1405
1406   // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1407   const MCSectionELF *ShstrtabSection =
1408       Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
1409   MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1410   ShstrtabSD.setAlignment(1);
1411   ShstrtabIndex = SectionIndexMap.size() + 1;
1412   SectionIndexMap[ShstrtabSection] = ShstrtabIndex;
1413
1414   const MCSectionELF *SymtabSection =
1415     Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1416                       EntrySize, "");
1417   MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1418   SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1419   SymbolTableIndex = SectionIndexMap.size() + 1;
1420   SectionIndexMap[SymtabSection] = SymbolTableIndex;
1421
1422   const MCSectionELF *StrtabSection;
1423   StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1424   MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1425   StrtabSD.setAlignment(1);
1426   StringTableIndex = SectionIndexMap.size() + 1;
1427   SectionIndexMap[StrtabSection] = StringTableIndex;
1428
1429   // Symbol table
1430   F = new MCDataFragment(&SymtabSD);
1431   WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
1432
1433   F = new MCDataFragment(&StrtabSD);
1434   F->getContents().append(StrTabBuilder.data().begin(),
1435                           StrTabBuilder.data().end());
1436
1437   F = new MCDataFragment(&ShstrtabSD);
1438
1439   // Section header string table.
1440   for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1441     const MCSectionELF &Section =
1442       static_cast<const MCSectionELF&>(it->getSection());
1443     ShStrTabBuilder.add(Section.getSectionName());
1444   }
1445   ShStrTabBuilder.finalize(StringTableBuilder::ELF);
1446   F->getContents().append(ShStrTabBuilder.data().begin(),
1447                           ShStrTabBuilder.data().end());
1448 }
1449
1450 void ELFObjectWriter::createIndexedSections(
1451     MCAssembler &Asm, MCAsmLayout &Layout, GroupMapTy &GroupMap,
1452     RevGroupMapTy &RevGroupMap, SectionIndexMapTy &SectionIndexMap) {
1453   MCContext &Ctx = Asm.getContext();
1454
1455   // Build the groups
1456   for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1457        it != ie; ++it) {
1458     const MCSectionELF &Section =
1459       static_cast<const MCSectionELF&>(it->getSection());
1460     if (!(Section.getFlags() & ELF::SHF_GROUP))
1461       continue;
1462
1463     const MCSymbol *SignatureSymbol = Section.getGroup();
1464     Asm.getOrCreateSymbolData(*SignatureSymbol);
1465     const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1466     if (!Group) {
1467       Group = Ctx.CreateELFGroupSection();
1468       MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1469       Data.setAlignment(4);
1470       MCDataFragment *F = new MCDataFragment(&Data);
1471       write(*F, uint32_t(ELF::GRP_COMDAT));
1472     }
1473     GroupMap[Group] = SignatureSymbol;
1474   }
1475
1476   computeIndexMap(Asm, SectionIndexMap);
1477
1478   // Add sections to the groups
1479   for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1480        it != ie; ++it) {
1481     const MCSectionELF &Section =
1482       static_cast<const MCSectionELF&>(it->getSection());
1483     if (!(Section.getFlags() & ELF::SHF_GROUP))
1484       continue;
1485     const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1486     MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1487     // FIXME: we could use the previous fragment
1488     MCDataFragment *F = new MCDataFragment(&Data);
1489     uint32_t Index = SectionIndexMap.lookup(&Section);
1490     write(*F, Index);
1491   }
1492 }
1493
1494 void ELFObjectWriter::writeSection(MCAssembler &Asm,
1495                                    const SectionIndexMapTy &SectionIndexMap,
1496                                    uint32_t GroupSymbolIndex,
1497                                    uint64_t Offset, uint64_t Size,
1498                                    uint64_t Alignment,
1499                                    const MCSectionELF &Section) {
1500   uint64_t sh_link = 0;
1501   uint64_t sh_info = 0;
1502
1503   switch(Section.getType()) {
1504   default:
1505     // Nothing to do.
1506     break;
1507
1508   case ELF::SHT_DYNAMIC:
1509     sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
1510     break;
1511
1512   case ELF::SHT_REL:
1513   case ELF::SHT_RELA: {
1514     sh_link = SymbolTableIndex;
1515     assert(sh_link && ".symtab not found");
1516     const MCSectionELF *InfoSection = Section.getAssociatedSection();
1517     sh_info = SectionIndexMap.lookup(InfoSection);
1518     break;
1519   }
1520
1521   case ELF::SHT_SYMTAB:
1522   case ELF::SHT_DYNSYM:
1523     sh_link = StringTableIndex;
1524     sh_info = LastLocalSymbolIndex;
1525     break;
1526
1527   case ELF::SHT_SYMTAB_SHNDX:
1528     sh_link = SymbolTableIndex;
1529     break;
1530
1531   case ELF::SHT_GROUP:
1532     sh_link = SymbolTableIndex;
1533     sh_info = GroupSymbolIndex;
1534     break;
1535   }
1536
1537   if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1538       Section.getType() == ELF::SHT_ARM_EXIDX)
1539     sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1540
1541   WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1542                    Section.getType(),
1543                    Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1544                    Alignment, Section.getEntrySize());
1545 }
1546
1547 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1548   return SD.getOrdinal() == ~UINT32_C(0) &&
1549     !SD.getSection().isVirtualSection();
1550 }
1551
1552 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1553   uint64_t Ret = 0;
1554   for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1555        ++i) {
1556     const MCFragment &F = *i;
1557     assert(F.getKind() == MCFragment::FT_Data);
1558     Ret += cast<MCDataFragment>(F).getContents().size();
1559   }
1560   return Ret;
1561 }
1562
1563 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1564                                              const MCSectionData &SD) {
1565   if (IsELFMetaDataSection(SD))
1566     return DataSectionSize(SD);
1567   return Layout.getSectionFileSize(&SD);
1568 }
1569
1570 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1571                                                 const MCSectionData &SD) {
1572   if (IsELFMetaDataSection(SD))
1573     return DataSectionSize(SD);
1574   return Layout.getSectionAddressSize(&SD);
1575 }
1576
1577 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1578                                            const MCAsmLayout &Layout,
1579                                            const MCSectionELF &Section) {
1580   const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1581
1582   uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1583   WriteZeros(Padding);
1584
1585   if (IsELFMetaDataSection(SD)) {
1586     for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1587          ++i) {
1588       const MCFragment &F = *i;
1589       assert(F.getKind() == MCFragment::FT_Data);
1590       WriteBytes(cast<MCDataFragment>(F).getContents());
1591     }
1592   } else {
1593     Asm.writeSectionData(&SD, Layout);
1594   }
1595 }
1596
1597 void ELFObjectWriter::writeSectionHeader(
1598     MCAssembler &Asm, const GroupMapTy &GroupMap, const MCAsmLayout &Layout,
1599     const SectionIndexMapTy &SectionIndexMap,
1600     const SectionOffsetMapTy &SectionOffsetMap) {
1601   const unsigned NumSections = Asm.size() + 1;
1602
1603   std::vector<const MCSectionELF*> Sections;
1604   Sections.resize(NumSections - 1);
1605
1606   for (SectionIndexMapTy::const_iterator i=
1607          SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1608     const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1609     Sections[p.second - 1] = p.first;
1610   }
1611
1612   // Null section first.
1613   uint64_t FirstSectionSize =
1614     NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1615   uint32_t FirstSectionLink =
1616     ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1617   WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1618
1619   for (unsigned i = 0; i < NumSections - 1; ++i) {
1620     const MCSectionELF &Section = *Sections[i];
1621     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1622     uint32_t GroupSymbolIndex;
1623     if (Section.getType() != ELF::SHT_GROUP)
1624       GroupSymbolIndex = 0;
1625     else
1626       GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1627                                                      GroupMap.lookup(&Section));
1628
1629     uint64_t Size = GetSectionAddressSize(Layout, SD);
1630
1631     writeSection(Asm, SectionIndexMap, GroupSymbolIndex,
1632                  SectionOffsetMap.lookup(&Section), Size, SD.getAlignment(),
1633                  Section);
1634   }
1635 }
1636
1637 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1638                                   std::vector<const MCSectionELF*> &Sections) {
1639   for (MCAssembler::iterator it = Asm.begin(),
1640          ie = Asm.end(); it != ie; ++it) {
1641     const MCSectionELF &Section =
1642       static_cast<const MCSectionELF &>(it->getSection());
1643     if (Section.getType() == ELF::SHT_GROUP)
1644       Sections.push_back(&Section);
1645   }
1646
1647   for (MCAssembler::iterator it = Asm.begin(),
1648          ie = Asm.end(); it != ie; ++it) {
1649     const MCSectionELF &Section =
1650       static_cast<const MCSectionELF &>(it->getSection());
1651     if (Section.getType() != ELF::SHT_GROUP &&
1652         Section.getType() != ELF::SHT_REL &&
1653         Section.getType() != ELF::SHT_RELA)
1654       Sections.push_back(&Section);
1655   }
1656
1657   for (MCAssembler::iterator it = Asm.begin(),
1658          ie = Asm.end(); it != ie; ++it) {
1659     const MCSectionELF &Section =
1660       static_cast<const MCSectionELF &>(it->getSection());
1661     if (Section.getType() == ELF::SHT_REL ||
1662         Section.getType() == ELF::SHT_RELA)
1663       Sections.push_back(&Section);
1664   }
1665 }
1666
1667 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1668                                   const MCAsmLayout &Layout) {
1669   GroupMapTy GroupMap;
1670   RevGroupMapTy RevGroupMap;
1671   SectionIndexMapTy SectionIndexMap;
1672
1673   CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
1674   createIndexedSections(Asm, const_cast<MCAsmLayout &>(Layout), GroupMap,
1675                         RevGroupMap, SectionIndexMap);
1676
1677   // Compute symbol table information.
1678   computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
1679
1680   WriteRelocations(Asm, const_cast<MCAsmLayout &>(Layout));
1681
1682   CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1683                          const_cast<MCAsmLayout&>(Layout),
1684                          SectionIndexMap);
1685
1686   uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1687   uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1688                                     sizeof(ELF::Elf32_Ehdr);
1689   uint64_t FileOff = HeaderSize;
1690
1691   std::vector<const MCSectionELF*> Sections;
1692   ComputeSectionOrder(Asm, Sections);
1693   unsigned NumSections = Sections.size();
1694   SectionOffsetMapTy SectionOffsetMap;
1695   for (unsigned i = 0; i < NumSections; ++i) {
1696
1697     const MCSectionELF &Section = *Sections[i];
1698     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1699
1700     FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1701
1702     // Remember the offset into the file for this section.
1703     SectionOffsetMap[&Section] = FileOff;
1704
1705     // Get the size of the section in the output file (including padding).
1706     FileOff += GetSectionFileSize(Layout, SD);
1707   }
1708
1709   FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1710
1711   const unsigned SectionHeaderOffset = FileOff;
1712
1713   // Write out the ELF header ...
1714   WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
1715
1716   // ... then the sections ...
1717   for (unsigned i = 0; i < NumSections; ++i)
1718     WriteDataSectionData(Asm, Layout, *Sections[i]);
1719
1720   uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1721   WriteZeros(Padding);
1722
1723   // ... then the section header table ...
1724   writeSectionHeader(Asm, GroupMap, Layout, SectionIndexMap, SectionOffsetMap);
1725 }
1726
1727 bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1728     const MCAssembler &Asm, const MCSymbolData &DataA,
1729     const MCSymbolData *DataB, const MCFragment &FB, bool InSet,
1730     bool IsPCRel) const {
1731   if (!InSet && (::isWeak(DataA) || (DataB && ::isWeak(*DataB))))
1732     return false;
1733   return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1734       Asm, DataA, DataB, FB, InSet, IsPCRel);
1735 }
1736
1737 bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
1738   return ::isWeak(SD);
1739 }
1740
1741 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1742                                             raw_ostream &OS,
1743                                             bool IsLittleEndian) {
1744   return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
1745 }