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