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