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