5e24f9148211215a087dad882740706d158b6c63
[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/Object/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                             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 static const MCSymbol *getBaseSymbol(const MCAsmLayout &Layout,
580                                      const MCSymbol &Symbol) {
581   if (!Symbol.isVariable())
582     return &Symbol;
583
584   const MCExpr *Expr = Symbol.getVariableValue();
585   MCValue Value;
586   if (!Expr->EvaluateAsValue(Value, &Layout))
587     llvm_unreachable("Invalid Expression");
588
589   const MCSymbolRefExpr *RefB = Value.getSymB();
590   if (RefB)
591     Layout.getAssembler().getContext().FatalError(
592         SMLoc(), Twine("symbol '") + RefB->getSymbol().getName() +
593                      "' could not be evaluated in a subtraction expression");
594
595   const MCSymbolRefExpr *A = Value.getSymA();
596   if (!A)
597     return nullptr;
598
599   return &A->getSymbol();
600 }
601
602 void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
603                                   const MCAsmLayout &Layout) {
604   MCSymbolData &OrigData = *MSD.SymbolData;
605   assert((!OrigData.getFragment() ||
606           (&OrigData.getFragment()->getParent()->getSection() ==
607            &OrigData.getSymbol().getSection())) &&
608          "The symbol's section doesn't match the fragment's symbol");
609   const MCSymbol *Base = getBaseSymbol(Layout, OrigData.getSymbol());
610
611   // This has to be in sync with when computeSymbolTable uses SHN_ABS or
612   // SHN_COMMON.
613   bool IsReserved = !Base || OrigData.isCommon();
614
615   // Binding and Type share the same byte as upper and lower nibbles
616   uint8_t Binding = MCELF::GetBinding(OrigData);
617   uint8_t Type = MCELF::GetType(OrigData);
618   MCSymbolData *BaseSD = nullptr;
619   if (Base) {
620     BaseSD = &Layout.getAssembler().getSymbolData(*Base);
621     Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
622   }
623   uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
624
625   // Other and Visibility share the same byte with Visibility using the lower
626   // 2 bits
627   uint8_t Visibility = MCELF::GetVisibility(OrigData);
628   uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
629   Other |= Visibility;
630
631   uint64_t Value = SymbolValue(OrigData, Layout);
632   uint64_t Size = 0;
633
634   const MCExpr *ESize = OrigData.getSize();
635   if (!ESize && Base)
636     ESize = BaseSD->getSize();
637
638   if (ESize) {
639     int64_t Res;
640     if (!ESize->EvaluateAsAbsolute(Res, Layout))
641       report_fatal_error("Size expression must be absolute.");
642     Size = Res;
643   }
644
645   // Write out the symbol table entry
646   Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
647                      MSD.SectionIndex, IsReserved);
648 }
649
650 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
651                                        MCAssembler &Asm,
652                                        const MCAsmLayout &Layout,
653                                        SectionIndexMapTy &SectionIndexMap) {
654   // The string table must be emitted first because we need the index
655   // into the string table for all the symbol names.
656
657   // FIXME: Make sure the start of the symbol table is aligned.
658
659   SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
660
661   // The first entry is the undefined symbol entry.
662   Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
663
664   for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
665     Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
666                        ELF::STV_DEFAULT, ELF::SHN_ABS, true);
667   }
668
669   // Write the symbol table entries.
670   LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
671
672   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
673     ELFSymbolData &MSD = LocalSymbolData[i];
674     WriteSymbol(Writer, MSD, Layout);
675   }
676
677   // Write out a symbol table entry for each regular section.
678   for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
679        ++i) {
680     const MCSectionELF &Section =
681       static_cast<const MCSectionELF&>(i->getSection());
682     if (Section.getType() == ELF::SHT_RELA ||
683         Section.getType() == ELF::SHT_REL ||
684         Section.getType() == ELF::SHT_STRTAB ||
685         Section.getType() == ELF::SHT_SYMTAB ||
686         Section.getType() == ELF::SHT_SYMTAB_SHNDX)
687       continue;
688     Writer.writeSymbol(0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT,
689                        SectionIndexMap.lookup(&Section), false);
690     LastLocalSymbolIndex++;
691   }
692
693   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
694     ELFSymbolData &MSD = ExternalSymbolData[i];
695     MCSymbolData &Data = *MSD.SymbolData;
696     assert(((Data.getFlags() & ELF_STB_Global) ||
697             (Data.getFlags() & ELF_STB_Weak)) &&
698            "External symbol requires STB_GLOBAL or STB_WEAK flag");
699     WriteSymbol(Writer, MSD, Layout);
700     if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
701       LastLocalSymbolIndex++;
702   }
703
704   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
705     ELFSymbolData &MSD = UndefinedSymbolData[i];
706     MCSymbolData &Data = *MSD.SymbolData;
707     WriteSymbol(Writer, MSD, Layout);
708     if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
709       LastLocalSymbolIndex++;
710   }
711 }
712
713 // It is always valid to create a relocation with a symbol. It is preferable
714 // to use a relocation with a section if that is possible. Using the section
715 // allows us to omit some local symbols from the symbol table.
716 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
717                                                const MCSymbolRefExpr *RefA,
718                                                const MCSymbolData *SD,
719                                                uint64_t C,
720                                                unsigned Type) const {
721   // A PCRel relocation to an absolute value has no symbol (or section). We
722   // represent that with a relocation to a null section.
723   if (!RefA)
724     return false;
725
726   MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
727   switch (Kind) {
728   default:
729     break;
730   // The .odp creation emits a relocation against the symbol ".TOC." which
731   // create a R_PPC64_TOC relocation. However the relocation symbol name
732   // in final object creation should be NULL, since the symbol does not
733   // really exist, it is just the reference to TOC base for the current
734   // object file. Since the symbol is undefined, returning false results
735   // in a relocation with a null section which is the desired result.
736   case MCSymbolRefExpr::VK_PPC_TOCBASE:
737     return false;
738
739   // These VariantKind cause the relocation to refer to something other than
740   // the symbol itself, like a linker generated table. Since the address of
741   // symbol is not relevant, we cannot replace the symbol with the
742   // section and patch the difference in the addend.
743   case MCSymbolRefExpr::VK_GOT:
744   case MCSymbolRefExpr::VK_PLT:
745   case MCSymbolRefExpr::VK_GOTPCREL:
746   case MCSymbolRefExpr::VK_Mips_GOT:
747   case MCSymbolRefExpr::VK_PPC_GOT_LO:
748   case MCSymbolRefExpr::VK_PPC_GOT_HI:
749   case MCSymbolRefExpr::VK_PPC_GOT_HA:
750     return true;
751   }
752
753   // An undefined symbol is not in any section, so the relocation has to point
754   // to the symbol itself.
755   const MCSymbol &Sym = SD->getSymbol();
756   if (Sym.isUndefined())
757     return true;
758
759   unsigned Binding = MCELF::GetBinding(*SD);
760   switch(Binding) {
761   default:
762     llvm_unreachable("Invalid Binding");
763   case ELF::STB_LOCAL:
764     break;
765   case ELF::STB_WEAK:
766     // If the symbol is weak, it might be overridden by a symbol in another
767     // file. The relocation has to point to the symbol so that the linker
768     // can update it.
769     return true;
770   case ELF::STB_GLOBAL:
771     // Global ELF symbols can be preempted by the dynamic linker. The relocation
772     // has to point to the symbol for a reason analogous to the STB_WEAK case.
773     return true;
774   }
775
776   // If a relocation points to a mergeable section, we have to be careful.
777   // If the offset is zero, a relocation with the section will encode the
778   // same information. With a non-zero offset, the situation is different.
779   // For example, a relocation can point 42 bytes past the end of a string.
780   // If we change such a relocation to use the section, the linker would think
781   // that it pointed to another string and subtracting 42 at runtime will
782   // produce the wrong value.
783   auto &Sec = cast<MCSectionELF>(Sym.getSection());
784   unsigned Flags = Sec.getFlags();
785   if (Flags & ELF::SHF_MERGE) {
786     if (C != 0)
787       return true;
788
789     // It looks like gold has a bug (http://sourceware.org/PR16794) and can
790     // only handle section relocations to mergeable sections if using RELA.
791     if (!hasRelocationAddend())
792       return true;
793   }
794
795   // Most TLS relocations use a got, so they need the symbol. Even those that
796   // are just an offset (@tpoff), require a symbol in some linkers (gold,
797   // but not bfd ld).
798   if (Flags & ELF::SHF_TLS)
799     return true;
800
801   // If the symbol is a thumb function the final relocation must set the lowest
802   // bit. With a symbol that is done by just having the symbol have that bit
803   // set, so we would lose the bit if we relocated with the section.
804   // FIXME: We could use the section but add the bit to the relocation value.
805   if (Asm.isThumbFunc(&Sym))
806     return true;
807
808   if (TargetObjectWriter->needsRelocateWithSymbol(Type))
809     return true;
810   return false;
811 }
812
813 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
814                                        const MCAsmLayout &Layout,
815                                        const MCFragment *Fragment,
816                                        const MCFixup &Fixup,
817                                        MCValue Target,
818                                        bool &IsPCRel,
819                                        uint64_t &FixedValue) {
820   const MCSectionData *FixupSection = Fragment->getParent();
821   uint64_t C = Target.getConstant();
822   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
823
824   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
825     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
826            "Should not have constructed this");
827
828     // Let A, B and C being the components of Target and R be the location of
829     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
830     // If it is pcrel, we want to compute (A - B + C - R).
831
832     // In general, ELF has no relocations for -B. It can only represent (A + C)
833     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
834     // replace B to implement it: (A - R - K + C)
835     if (IsPCRel)
836       Asm.getContext().FatalError(
837           Fixup.getLoc(),
838           "No relocation available to represent this relative expression");
839
840     const MCSymbol &SymB = RefB->getSymbol();
841
842     if (SymB.isUndefined())
843       Asm.getContext().FatalError(
844           Fixup.getLoc(),
845           Twine("symbol '") + SymB.getName() +
846               "' can not be undefined in a subtraction expression");
847
848     assert(!SymB.isAbsolute() && "Should have been folded");
849     const MCSection &SecB = SymB.getSection();
850     if (&SecB != &FixupSection->getSection())
851       Asm.getContext().FatalError(
852           Fixup.getLoc(), "Cannot represent a difference across sections");
853
854     const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
855     uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
856     uint64_t K = SymBOffset - FixupOffset;
857     IsPCRel = true;
858     C -= K;
859   }
860
861   // We either rejected the fixup or folded B into C at this point.
862   const MCSymbolRefExpr *RefA = Target.getSymA();
863   const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
864   const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
865
866   unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
867   bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
868   if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
869     C += Layout.getSymbolOffset(SymAD);
870
871   uint64_t Addend = 0;
872   if (hasRelocationAddend()) {
873     Addend = C;
874     C = 0;
875   }
876
877   FixedValue = C;
878
879   // FIXME: What is this!?!?
880   MCSymbolRefExpr::VariantKind Modifier =
881       RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
882   if (RelocNeedsGOT(Modifier))
883     NeedsGOT = true;
884
885   if (!RelocateWithSymbol) {
886     const MCSection *SecA =
887         (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
888     const MCSectionData *SecAD = SecA ? &Asm.getSectionData(*SecA) : nullptr;
889     ELFRelocationEntry Rec(FixupOffset, SecAD, Type, Addend);
890     Relocations[FixupSection].push_back(Rec);
891     return;
892   }
893
894   if (SymA) {
895     if (const MCSymbol *R = Renames.lookup(SymA))
896       SymA = R;
897
898     if (RefA->getKind() == MCSymbolRefExpr::VK_WEAKREF)
899       WeakrefUsedInReloc.insert(SymA);
900     else
901       UsedInReloc.insert(SymA);
902   }
903   ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
904   Relocations[FixupSection].push_back(Rec);
905   return;
906 }
907
908
909 uint64_t
910 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
911                                              const MCSymbol *S) {
912   const MCSymbolData &SD = Asm.getSymbolData(*S);
913   return SD.getIndex();
914 }
915
916 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
917                                  const MCSymbolData &Data, bool Used,
918                                  bool Renamed) {
919   const MCSymbol &Symbol = Data.getSymbol();
920   if (Symbol.isVariable()) {
921     const MCExpr *Expr = Symbol.getVariableValue();
922     if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
923       if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
924         return false;
925     }
926   }
927
928   if (Used)
929     return true;
930
931   if (Renamed)
932     return false;
933
934   if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
935     return true;
936
937   if (Symbol.isVariable()) {
938     const MCSymbol *Base = getBaseSymbol(Layout, Symbol);
939     if (Base && Base->isUndefined())
940       return false;
941   }
942
943   bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
944   if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
945     return false;
946
947   if (Symbol.isTemporary())
948     return false;
949
950   return true;
951 }
952
953 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
954   if (Data.isExternal())
955     return false;
956
957   const MCSymbol &Symbol = Data.getSymbol();
958   if (Symbol.isDefined())
959     return true;
960
961   if (isUsedInReloc)
962     return false;
963
964   return true;
965 }
966
967 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
968                                       SectionIndexMapTy &SectionIndexMap,
969                                       const RelMapTy &RelMap) {
970   unsigned Index = 1;
971   for (MCAssembler::iterator it = Asm.begin(),
972          ie = Asm.end(); it != ie; ++it) {
973     const MCSectionELF &Section =
974       static_cast<const MCSectionELF &>(it->getSection());
975     if (Section.getType() != ELF::SHT_GROUP)
976       continue;
977     SectionIndexMap[&Section] = Index++;
978   }
979
980   for (MCAssembler::iterator it = Asm.begin(),
981          ie = Asm.end(); it != ie; ++it) {
982     const MCSectionELF &Section =
983       static_cast<const MCSectionELF &>(it->getSection());
984     if (Section.getType() == ELF::SHT_GROUP ||
985         Section.getType() == ELF::SHT_REL ||
986         Section.getType() == ELF::SHT_RELA)
987       continue;
988     SectionIndexMap[&Section] = Index++;
989     const MCSectionELF *RelSection = RelMap.lookup(&Section);
990     if (RelSection)
991       SectionIndexMap[RelSection] = Index++;
992   }
993 }
994
995 void
996 ELFObjectWriter::computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
997                                     const SectionIndexMapTy &SectionIndexMap,
998                                     RevGroupMapTy RevGroupMap,
999                                     unsigned NumRegularSections) {
1000   // FIXME: Is this the correct place to do this?
1001   // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
1002   if (NeedsGOT) {
1003     StringRef Name = "_GLOBAL_OFFSET_TABLE_";
1004     MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
1005     MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
1006     Data.setExternal(true);
1007     MCELF::SetBinding(Data, ELF::STB_GLOBAL);
1008   }
1009
1010   // Add the data for the symbols.
1011   for (MCSymbolData &SD : Asm.symbols()) {
1012     const MCSymbol &Symbol = SD.getSymbol();
1013
1014     bool Used = UsedInReloc.count(&Symbol);
1015     bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
1016     bool isSignature = RevGroupMap.count(&Symbol);
1017
1018     if (!isInSymtab(Layout, SD,
1019                     Used || WeakrefUsed || isSignature,
1020                     Renames.count(&Symbol)))
1021       continue;
1022
1023     ELFSymbolData MSD;
1024     MSD.SymbolData = &SD;
1025     const MCSymbol *BaseSymbol = getBaseSymbol(Layout, Symbol);
1026
1027     // Undefined symbols are global, but this is the first place we
1028     // are able to set it.
1029     bool Local = isLocal(SD, Used);
1030     if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
1031       assert(BaseSymbol);
1032       MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
1033       MCELF::SetBinding(SD, ELF::STB_GLOBAL);
1034       MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
1035     }
1036
1037     if (!BaseSymbol) {
1038       MSD.SectionIndex = ELF::SHN_ABS;
1039     } else if (SD.isCommon()) {
1040       assert(!Local);
1041       MSD.SectionIndex = ELF::SHN_COMMON;
1042     } else if (BaseSymbol->isUndefined()) {
1043       if (isSignature && !Used)
1044         MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
1045       else
1046         MSD.SectionIndex = ELF::SHN_UNDEF;
1047       if (!Used && WeakrefUsed)
1048         MCELF::SetBinding(SD, ELF::STB_WEAK);
1049     } else {
1050       const MCSectionELF &Section =
1051         static_cast<const MCSectionELF&>(BaseSymbol->getSection());
1052       MSD.SectionIndex = SectionIndexMap.lookup(&Section);
1053       assert(MSD.SectionIndex && "Invalid section index!");
1054     }
1055
1056     // The @@@ in symbol version is replaced with @ in undefined symbols and
1057     // @@ in defined ones.
1058     StringRef Name = Symbol.getName();
1059     SmallString<32> Buf;
1060     size_t Pos = Name.find("@@@");
1061     if (Pos != StringRef::npos) {
1062       Buf += Name.substr(0, Pos);
1063       unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1064       Buf += Name.substr(Pos + Skip);
1065       Name = Buf;
1066     }
1067     MSD.Name = StrTabBuilder.add(Name);
1068
1069     if (MSD.SectionIndex == ELF::SHN_UNDEF)
1070       UndefinedSymbolData.push_back(MSD);
1071     else if (Local)
1072       LocalSymbolData.push_back(MSD);
1073     else
1074       ExternalSymbolData.push_back(MSD);
1075   }
1076
1077   for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1078     StrTabBuilder.add(*i);
1079
1080   StrTabBuilder.finalize();
1081
1082   for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1083     FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1084
1085   for (ELFSymbolData& MSD : LocalSymbolData)
1086     MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1087   for (ELFSymbolData& MSD : ExternalSymbolData)
1088     MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1089   for (ELFSymbolData& MSD : UndefinedSymbolData)
1090     MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1091
1092   // Symbols are required to be in lexicographic order.
1093   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1094   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1095   array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1096
1097   // Set the symbol indices. Local symbols must come before all other
1098   // symbols with non-local bindings.
1099   unsigned Index = FileSymbolData.size() + 1;
1100   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1101     LocalSymbolData[i].SymbolData->setIndex(Index++);
1102
1103   Index += NumRegularSections;
1104
1105   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1106     ExternalSymbolData[i].SymbolData->setIndex(Index++);
1107   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1108     UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1109 }
1110
1111 void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
1112                                                MCAsmLayout &Layout,
1113                                                RelMapTy &RelMap) {
1114   for (MCAssembler::const_iterator it = Asm.begin(),
1115          ie = Asm.end(); it != ie; ++it) {
1116     const MCSectionData &SD = *it;
1117     if (Relocations[&SD].empty())
1118       continue;
1119
1120     MCContext &Ctx = Asm.getContext();
1121     const MCSectionELF &Section =
1122       static_cast<const MCSectionELF&>(SD.getSection());
1123
1124     const StringRef SectionName = Section.getSectionName();
1125     std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1126     RelaSectionName += SectionName;
1127
1128     unsigned EntrySize;
1129     if (hasRelocationAddend())
1130       EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1131     else
1132       EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1133
1134     unsigned Flags = 0;
1135     StringRef Group = "";
1136     if (Section.getFlags() & ELF::SHF_GROUP) {
1137       Flags = ELF::SHF_GROUP;
1138       Group = Section.getGroup()->getName();
1139     }
1140
1141     const MCSectionELF *RelaSection =
1142       Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1143                         ELF::SHT_RELA : ELF::SHT_REL, Flags,
1144                         SectionKind::getReadOnly(),
1145                         EntrySize, Group);
1146     RelMap[&Section] = RelaSection;
1147     Asm.getOrCreateSectionData(*RelaSection);
1148   }
1149 }
1150
1151 static SmallVector<char, 128>
1152 getUncompressedData(MCAsmLayout &Layout,
1153                     MCSectionData::FragmentListType &Fragments) {
1154   SmallVector<char, 128> UncompressedData;
1155   for (const MCFragment &F : Fragments) {
1156     const SmallVectorImpl<char> *Contents;
1157     switch (F.getKind()) {
1158     case MCFragment::FT_Data:
1159       Contents = &cast<MCDataFragment>(F).getContents();
1160       break;
1161     case MCFragment::FT_Dwarf:
1162       Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1163       break;
1164     case MCFragment::FT_DwarfFrame:
1165       Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1166       break;
1167     default:
1168       llvm_unreachable(
1169           "Not expecting any other fragment types in a debug_* section");
1170     }
1171     UncompressedData.append(Contents->begin(), Contents->end());
1172   }
1173   return UncompressedData;
1174 }
1175
1176 // Include the debug info compression header:
1177 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1178 // useful for consumers to preallocate a buffer to decompress into.
1179 static bool
1180 prependCompressionHeader(uint64_t Size,
1181                          SmallVectorImpl<char> &CompressedContents) {
1182   static const StringRef Magic = "ZLIB";
1183   if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1184     return false;
1185   if (sys::IsLittleEndianHost)
1186     Size = sys::SwapByteOrder(Size);
1187   CompressedContents.insert(CompressedContents.begin(),
1188                             Magic.size() + sizeof(Size), 0);
1189   std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1190   std::copy(reinterpret_cast<char *>(&Size),
1191             reinterpret_cast<char *>(&Size + 1),
1192             CompressedContents.begin() + Magic.size());
1193   return true;
1194 }
1195
1196 // Return a single fragment containing the compressed contents of the whole
1197 // section. Null if the section was not compressed for any reason.
1198 static std::unique_ptr<MCDataFragment>
1199 getCompressedFragment(MCAsmLayout &Layout,
1200                       MCSectionData::FragmentListType &Fragments) {
1201   std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1202
1203   // Gather the uncompressed data from all the fragments, recording the
1204   // alignment fragment, if seen, and any fixups.
1205   SmallVector<char, 128> UncompressedData =
1206       getUncompressedData(Layout, Fragments);
1207
1208   SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1209
1210   zlib::Status Success = zlib::compress(
1211       StringRef(UncompressedData.data(), UncompressedData.size()),
1212       CompressedContents);
1213   if (Success != zlib::StatusOK)
1214     return nullptr;
1215
1216   if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1217     return nullptr;
1218
1219   return CompressedFragment;
1220 }
1221
1222 typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1223 DefiningSymbolMap;
1224
1225 static void UpdateSymbols(const MCAsmLayout &Layout,
1226                           const std::vector<MCSymbolData *> &Symbols,
1227                           MCFragment &NewFragment) {
1228   for (MCSymbolData *Sym : Symbols) {
1229     Sym->setOffset(Sym->getOffset() +
1230                    Layout.getFragmentOffset(Sym->getFragment()));
1231     Sym->setFragment(&NewFragment);
1232   }
1233 }
1234
1235 static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
1236                                  const DefiningSymbolMap &DefiningSymbols,
1237                                  const MCSectionELF &Section,
1238                                  MCSectionData &SD) {
1239   StringRef SectionName = Section.getSectionName();
1240   MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1241
1242   std::unique_ptr<MCDataFragment> CompressedFragment =
1243       getCompressedFragment(Layout, Fragments);
1244
1245   // Leave the section as-is if the fragments could not be compressed.
1246   if (!CompressedFragment)
1247     return;
1248
1249   // Update the fragment+offsets of any symbols referring to fragments in this
1250   // section to refer to the new fragment.
1251   auto I = DefiningSymbols.find(&SD);
1252   if (I != DefiningSymbols.end())
1253     UpdateSymbols(Layout, I->second, *CompressedFragment);
1254
1255   // Invalidate the layout for the whole section since it will have new and
1256   // different fragments now.
1257   Layout.invalidateFragmentsFrom(&Fragments.front());
1258   Fragments.clear();
1259
1260   // Complete the initialization of the new fragment
1261   CompressedFragment->setParent(&SD);
1262   CompressedFragment->setLayoutOrder(0);
1263   Fragments.push_back(CompressedFragment.release());
1264
1265   // Rename from .debug_* to .zdebug_*
1266   Asm.getContext().renameELFSection(&Section,
1267                                     (".z" + SectionName.drop_front(1)).str());
1268 }
1269
1270 void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1271                                             MCAsmLayout &Layout) {
1272   if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1273     return;
1274
1275   DefiningSymbolMap DefiningSymbols;
1276
1277   for (MCSymbolData &SD : Asm.symbols())
1278     if (MCFragment *F = SD.getFragment())
1279       DefiningSymbols[F->getParent()].push_back(&SD);
1280
1281   for (MCSectionData &SD : Asm) {
1282     const MCSectionELF &Section =
1283         static_cast<const MCSectionELF &>(SD.getSection());
1284     StringRef SectionName = Section.getSectionName();
1285
1286     // Compressing debug_frame requires handling alignment fragments which is
1287     // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1288     // for writing to arbitrary buffers) for little benefit.
1289     if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1290       continue;
1291
1292     CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
1293   }
1294 }
1295
1296 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1297                                        const RelMapTy &RelMap) {
1298   for (MCAssembler::const_iterator it = Asm.begin(),
1299          ie = Asm.end(); it != ie; ++it) {
1300     const MCSectionData &SD = *it;
1301     const MCSectionELF &Section =
1302       static_cast<const MCSectionELF&>(SD.getSection());
1303
1304     const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1305     if (!RelaSection)
1306       continue;
1307     MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1308     RelaSD.setAlignment(is64Bit() ? 8 : 4);
1309
1310     MCDataFragment *F = new MCDataFragment(&RelaSD);
1311     WriteRelocationsFragment(Asm, F, &*it);
1312   }
1313 }
1314
1315 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1316                                        uint64_t Flags, uint64_t Address,
1317                                        uint64_t Offset, uint64_t Size,
1318                                        uint32_t Link, uint32_t Info,
1319                                        uint64_t Alignment,
1320                                        uint64_t EntrySize) {
1321   Write32(Name);        // sh_name: index into string table
1322   Write32(Type);        // sh_type
1323   WriteWord(Flags);     // sh_flags
1324   WriteWord(Address);   // sh_addr
1325   WriteWord(Offset);    // sh_offset
1326   WriteWord(Size);      // sh_size
1327   Write32(Link);        // sh_link
1328   Write32(Info);        // sh_info
1329   WriteWord(Alignment); // sh_addralign
1330   WriteWord(EntrySize); // sh_entsize
1331 }
1332
1333 // ELF doesn't require relocations to be in any order. We sort by the r_offset,
1334 // just to match gnu as for easier comparison. The use type is an arbitrary way
1335 // of making the sort deterministic.
1336 static int cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
1337   const ELFRelocationEntry &A = *AP;
1338   const ELFRelocationEntry &B = *BP;
1339   if (A.Offset != B.Offset)
1340     return B.Offset - A.Offset;
1341   if (B.Type != A.Type)
1342     return A.Type - B.Type;
1343   llvm_unreachable("ELFRelocs might be unstable!");
1344 }
1345
1346 static void sortRelocs(const MCAssembler &Asm,
1347                        std::vector<ELFRelocationEntry> &Relocs) {
1348   array_pod_sort(Relocs.begin(), Relocs.end(), cmpRel);
1349 }
1350
1351 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1352                                                MCDataFragment *F,
1353                                                const MCSectionData *SD) {
1354   std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1355
1356   sortRelocs(Asm, Relocs);
1357
1358   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1359     const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1360
1361     unsigned Index;
1362     if (Entry.UseSymbol) {
1363       Index = getSymbolIndexInSymbolTable(Asm, Entry.Symbol);
1364     } else {
1365       const MCSectionData *Sec = Entry.Section;
1366       if (Sec)
1367         Index = Sec->getOrdinal() + FileSymbolData.size() +
1368                 LocalSymbolData.size() + 1;
1369       else
1370         Index = 0;
1371     }
1372
1373     if (is64Bit()) {
1374       write(*F, Entry.Offset);
1375       if (TargetObjectWriter->isN64()) {
1376         write(*F, uint32_t(Index));
1377
1378         write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1379         write(*F, TargetObjectWriter->getRType3(Entry.Type));
1380         write(*F, TargetObjectWriter->getRType2(Entry.Type));
1381         write(*F, TargetObjectWriter->getRType(Entry.Type));
1382       } else {
1383         struct ELF::Elf64_Rela ERE64;
1384         ERE64.setSymbolAndType(Index, Entry.Type);
1385         write(*F, ERE64.r_info);
1386       }
1387       if (hasRelocationAddend())
1388         write(*F, Entry.Addend);
1389     } else {
1390       write(*F, uint32_t(Entry.Offset));
1391
1392       struct ELF::Elf32_Rela ERE32;
1393       ERE32.setSymbolAndType(Index, Entry.Type);
1394       write(*F, ERE32.r_info);
1395
1396       if (hasRelocationAddend())
1397         write(*F, uint32_t(Entry.Addend));
1398     }
1399   }
1400 }
1401
1402 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1403                                              MCAsmLayout &Layout,
1404                                              SectionIndexMapTy &SectionIndexMap,
1405                                              const RelMapTy &RelMap) {
1406   MCContext &Ctx = Asm.getContext();
1407   MCDataFragment *F;
1408
1409   unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1410
1411   // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1412   const MCSectionELF *ShstrtabSection =
1413     Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1414                       SectionKind::getReadOnly());
1415   MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1416   ShstrtabSD.setAlignment(1);
1417
1418   const MCSectionELF *SymtabSection =
1419     Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1420                       SectionKind::getReadOnly(),
1421                       EntrySize, "");
1422   MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1423   SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1424
1425   const MCSectionELF *StrtabSection;
1426   StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1427                                     SectionKind::getReadOnly());
1428   MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1429   StrtabSD.setAlignment(1);
1430
1431   ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1432
1433   ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1434   SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1435   StringTableIndex = SectionIndexMap.lookup(StrtabSection);
1436
1437   // Symbol table
1438   F = new MCDataFragment(&SymtabSD);
1439   WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
1440
1441   F = new MCDataFragment(&StrtabSD);
1442   F->getContents().append(StrTabBuilder.data().begin(),
1443                           StrTabBuilder.data().end());
1444
1445   F = new MCDataFragment(&ShstrtabSD);
1446
1447   // Section header string table.
1448   for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1449     const MCSectionELF &Section =
1450       static_cast<const MCSectionELF&>(it->getSection());
1451     ShStrTabBuilder.add(Section.getSectionName());
1452   }
1453   ShStrTabBuilder.finalize();
1454   F->getContents().append(ShStrTabBuilder.data().begin(),
1455                           ShStrTabBuilder.data().end());
1456 }
1457
1458 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1459                                             MCAsmLayout &Layout,
1460                                             GroupMapTy &GroupMap,
1461                                             RevGroupMapTy &RevGroupMap,
1462                                             SectionIndexMapTy &SectionIndexMap,
1463                                             const RelMapTy &RelMap) {
1464   // Create the .note.GNU-stack section if needed.
1465   MCContext &Ctx = Asm.getContext();
1466   if (Asm.getNoExecStack()) {
1467     const MCSectionELF *GnuStackSection =
1468       Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1469                         SectionKind::getReadOnly());
1470     Asm.getOrCreateSectionData(*GnuStackSection);
1471   }
1472
1473   // Build the groups
1474   for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1475        it != ie; ++it) {
1476     const MCSectionELF &Section =
1477       static_cast<const MCSectionELF&>(it->getSection());
1478     if (!(Section.getFlags() & ELF::SHF_GROUP))
1479       continue;
1480
1481     const MCSymbol *SignatureSymbol = Section.getGroup();
1482     Asm.getOrCreateSymbolData(*SignatureSymbol);
1483     const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1484     if (!Group) {
1485       Group = Ctx.CreateELFGroupSection();
1486       MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1487       Data.setAlignment(4);
1488       MCDataFragment *F = new MCDataFragment(&Data);
1489       write(*F, uint32_t(ELF::GRP_COMDAT));
1490     }
1491     GroupMap[Group] = SignatureSymbol;
1492   }
1493
1494   ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1495
1496   // Add sections to the groups
1497   for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1498        it != ie; ++it) {
1499     const MCSectionELF &Section =
1500       static_cast<const MCSectionELF&>(it->getSection());
1501     if (!(Section.getFlags() & ELF::SHF_GROUP))
1502       continue;
1503     const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1504     MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1505     // FIXME: we could use the previous fragment
1506     MCDataFragment *F = new MCDataFragment(&Data);
1507     uint32_t Index = SectionIndexMap.lookup(&Section);
1508     write(*F, Index);
1509   }
1510 }
1511
1512 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1513                                    const SectionIndexMapTy &SectionIndexMap,
1514                                    uint32_t GroupSymbolIndex,
1515                                    uint64_t Offset, uint64_t Size,
1516                                    uint64_t Alignment,
1517                                    const MCSectionELF &Section) {
1518   uint64_t sh_link = 0;
1519   uint64_t sh_info = 0;
1520
1521   switch(Section.getType()) {
1522   case ELF::SHT_DYNAMIC:
1523     sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
1524     sh_info = 0;
1525     break;
1526
1527   case ELF::SHT_REL:
1528   case ELF::SHT_RELA: {
1529     const MCSectionELF *SymtabSection;
1530     const MCSectionELF *InfoSection;
1531     SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1532                                                    0,
1533                                                    SectionKind::getReadOnly());
1534     sh_link = SectionIndexMap.lookup(SymtabSection);
1535     assert(sh_link && ".symtab not found");
1536
1537     // Remove ".rel" and ".rela" prefixes.
1538     unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1539     StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1540     StringRef GroupName =
1541         Section.getGroup() ? Section.getGroup()->getName() : "";
1542
1543     InfoSection = Asm.getContext().getELFSection(SectionName, ELF::SHT_PROGBITS,
1544                                                  0, SectionKind::getReadOnly(),
1545                                                  0, GroupName);
1546     sh_info = SectionIndexMap.lookup(InfoSection);
1547     break;
1548   }
1549
1550   case ELF::SHT_SYMTAB:
1551   case ELF::SHT_DYNSYM:
1552     sh_link = StringTableIndex;
1553     sh_info = LastLocalSymbolIndex;
1554     break;
1555
1556   case ELF::SHT_SYMTAB_SHNDX:
1557     sh_link = SymbolTableIndex;
1558     break;
1559
1560   case ELF::SHT_PROGBITS:
1561   case ELF::SHT_STRTAB:
1562   case ELF::SHT_NOBITS:
1563   case ELF::SHT_NOTE:
1564   case ELF::SHT_NULL:
1565   case ELF::SHT_ARM_ATTRIBUTES:
1566   case ELF::SHT_INIT_ARRAY:
1567   case ELF::SHT_FINI_ARRAY:
1568   case ELF::SHT_PREINIT_ARRAY:
1569   case ELF::SHT_X86_64_UNWIND:
1570   case ELF::SHT_MIPS_REGINFO:
1571   case ELF::SHT_MIPS_OPTIONS:
1572     // Nothing to do.
1573     break;
1574
1575   case ELF::SHT_GROUP:
1576     sh_link = SymbolTableIndex;
1577     sh_info = GroupSymbolIndex;
1578     break;
1579
1580   default:
1581     assert(0 && "FIXME: sh_type value not supported!");
1582     break;
1583   }
1584
1585   if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1586       Section.getType() == ELF::SHT_ARM_EXIDX) {
1587     StringRef SecName(Section.getSectionName());
1588     if (SecName == ".ARM.exidx") {
1589       sh_link = SectionIndexMap.lookup(
1590         Asm.getContext().getELFSection(".text",
1591                                        ELF::SHT_PROGBITS,
1592                                        ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
1593                                        SectionKind::getText()));
1594     } else if (SecName.startswith(".ARM.exidx")) {
1595       StringRef GroupName =
1596           Section.getGroup() ? Section.getGroup()->getName() : "";
1597       sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1598           SecName.substr(sizeof(".ARM.exidx") - 1), ELF::SHT_PROGBITS,
1599           ELF::SHF_EXECINSTR | ELF::SHF_ALLOC, SectionKind::getText(), 0,
1600           GroupName));
1601     }
1602   }
1603
1604   WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1605                    Section.getType(),
1606                    Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1607                    Alignment, Section.getEntrySize());
1608 }
1609
1610 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1611   return SD.getOrdinal() == ~UINT32_C(0) &&
1612     !SD.getSection().isVirtualSection();
1613 }
1614
1615 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1616   uint64_t Ret = 0;
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     Ret += cast<MCDataFragment>(F).getContents().size();
1622   }
1623   return Ret;
1624 }
1625
1626 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1627                                              const MCSectionData &SD) {
1628   if (IsELFMetaDataSection(SD))
1629     return DataSectionSize(SD);
1630   return Layout.getSectionFileSize(&SD);
1631 }
1632
1633 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1634                                                 const MCSectionData &SD) {
1635   if (IsELFMetaDataSection(SD))
1636     return DataSectionSize(SD);
1637   return Layout.getSectionAddressSize(&SD);
1638 }
1639
1640 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1641                                            const MCAsmLayout &Layout,
1642                                            const MCSectionELF &Section) {
1643   const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1644
1645   uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1646   WriteZeros(Padding);
1647
1648   if (IsELFMetaDataSection(SD)) {
1649     for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1650          ++i) {
1651       const MCFragment &F = *i;
1652       assert(F.getKind() == MCFragment::FT_Data);
1653       WriteBytes(cast<MCDataFragment>(F).getContents());
1654     }
1655   } else {
1656     Asm.writeSectionData(&SD, Layout);
1657   }
1658 }
1659
1660 void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1661                                          const GroupMapTy &GroupMap,
1662                                          const MCAsmLayout &Layout,
1663                                       const SectionIndexMapTy &SectionIndexMap,
1664                                    const SectionOffsetMapTy &SectionOffsetMap) {
1665   const unsigned NumSections = Asm.size() + 1;
1666
1667   std::vector<const MCSectionELF*> Sections;
1668   Sections.resize(NumSections - 1);
1669
1670   for (SectionIndexMapTy::const_iterator i=
1671          SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1672     const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1673     Sections[p.second - 1] = p.first;
1674   }
1675
1676   // Null section first.
1677   uint64_t FirstSectionSize =
1678     NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1679   uint32_t FirstSectionLink =
1680     ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1681   WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1682
1683   for (unsigned i = 0; i < NumSections - 1; ++i) {
1684     const MCSectionELF &Section = *Sections[i];
1685     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1686     uint32_t GroupSymbolIndex;
1687     if (Section.getType() != ELF::SHT_GROUP)
1688       GroupSymbolIndex = 0;
1689     else
1690       GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1691                                                      GroupMap.lookup(&Section));
1692
1693     uint64_t Size = GetSectionAddressSize(Layout, SD);
1694
1695     WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1696                  SectionOffsetMap.lookup(&Section), Size,
1697                  SD.getAlignment(), Section);
1698   }
1699 }
1700
1701 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1702                                   std::vector<const MCSectionELF*> &Sections) {
1703   for (MCAssembler::iterator it = Asm.begin(),
1704          ie = Asm.end(); it != ie; ++it) {
1705     const MCSectionELF &Section =
1706       static_cast<const MCSectionELF &>(it->getSection());
1707     if (Section.getType() == ELF::SHT_GROUP)
1708       Sections.push_back(&Section);
1709   }
1710
1711   for (MCAssembler::iterator it = Asm.begin(),
1712          ie = Asm.end(); it != ie; ++it) {
1713     const MCSectionELF &Section =
1714       static_cast<const MCSectionELF &>(it->getSection());
1715     if (Section.getType() != ELF::SHT_GROUP &&
1716         Section.getType() != ELF::SHT_REL &&
1717         Section.getType() != ELF::SHT_RELA)
1718       Sections.push_back(&Section);
1719   }
1720
1721   for (MCAssembler::iterator it = Asm.begin(),
1722          ie = Asm.end(); it != ie; ++it) {
1723     const MCSectionELF &Section =
1724       static_cast<const MCSectionELF &>(it->getSection());
1725     if (Section.getType() == ELF::SHT_REL ||
1726         Section.getType() == ELF::SHT_RELA)
1727       Sections.push_back(&Section);
1728   }
1729 }
1730
1731 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1732                                   const MCAsmLayout &Layout) {
1733   GroupMapTy GroupMap;
1734   RevGroupMapTy RevGroupMap;
1735   SectionIndexMapTy SectionIndexMap;
1736
1737   unsigned NumUserSections = Asm.size();
1738
1739   CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
1740
1741   DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1742   CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1743
1744   const unsigned NumUserAndRelocSections = Asm.size();
1745   CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1746                         RevGroupMap, SectionIndexMap, RelMap);
1747   const unsigned AllSections = Asm.size();
1748   const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1749
1750   unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1751
1752   // Compute symbol table information.
1753   computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1754                      NumRegularSections);
1755
1756   WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1757
1758   CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1759                          const_cast<MCAsmLayout&>(Layout),
1760                          SectionIndexMap,
1761                          RelMap);
1762
1763   uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1764   uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1765                                     sizeof(ELF::Elf32_Ehdr);
1766   uint64_t FileOff = HeaderSize;
1767
1768   std::vector<const MCSectionELF*> Sections;
1769   ComputeSectionOrder(Asm, Sections);
1770   unsigned NumSections = Sections.size();
1771   SectionOffsetMapTy SectionOffsetMap;
1772   for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1773     const MCSectionELF &Section = *Sections[i];
1774     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1775
1776     FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1777
1778     // Remember the offset into the file for this section.
1779     SectionOffsetMap[&Section] = FileOff;
1780
1781     // Get the size of the section in the output file (including padding).
1782     FileOff += GetSectionFileSize(Layout, SD);
1783   }
1784
1785   FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1786
1787   const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1788
1789   uint64_t SectionHeaderEntrySize = is64Bit() ?
1790     sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1791   FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1792
1793   for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1794     const MCSectionELF &Section = *Sections[i];
1795     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1796
1797     FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1798
1799     // Remember the offset into the file for this section.
1800     SectionOffsetMap[&Section] = FileOff;
1801
1802     // Get the size of the section in the output file (including padding).
1803     FileOff += GetSectionFileSize(Layout, SD);
1804   }
1805
1806   // Write out the ELF header ...
1807   WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
1808
1809   // ... then the regular sections ...
1810   // + because of .shstrtab
1811   for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1812     WriteDataSectionData(Asm, Layout, *Sections[i]);
1813
1814   uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1815   WriteZeros(Padding);
1816
1817   // ... then the section header table ...
1818   WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1819                      SectionOffsetMap);
1820
1821   // ... and then the remaining sections ...
1822   for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1823     WriteDataSectionData(Asm, Layout, *Sections[i]);
1824 }
1825
1826 bool
1827 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1828                                                       const MCSymbolData &DataA,
1829                                                       const MCFragment &FB,
1830                                                       bool InSet,
1831                                                       bool IsPCRel) const {
1832   if (DataA.getFlags() & ELF_STB_Weak || MCELF::GetType(DataA) == ELF::STT_GNU_IFUNC)
1833     return false;
1834   return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1835                                                  Asm, DataA, FB,InSet, IsPCRel);
1836 }
1837
1838 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1839                                             raw_ostream &OS,
1840                                             bool IsLittleEndian) {
1841   return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
1842 }