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