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