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