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