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