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