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