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