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