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