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