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