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