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