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