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