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