Pass MCSymbols to the helper functions in MCELF.h.
[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);
89         unsigned RHSType = MCELF::GetType(*RHS.Symbol);
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(Alias, MCELF::GetBinding(Symbol));
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(*MSD.Symbol);
466   uint8_t Type = MCELF::GetType(*MSD.Symbol);
467   MCSymbolData *BaseSD = nullptr;
468   if (Base) {
469     BaseSD = &Base->getData();
470     Type = mergeTypeForSet(Type, MCELF::GetType(*Base));
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(*MSD.Symbol);
477   uint8_t Other = MCELF::getOther(*MSD.Symbol)
478                   << (ELF_STO_Shift - ELF_STV_Shift);
479   Other |= Visibility;
480
481   uint64_t Value = SymbolValue(*MSD.Symbol, Layout);
482   uint64_t Size = 0;
483
484   const MCExpr *ESize = MSD.Symbol->getSize();
485   if (!ESize && Base)
486     ESize = Base->getSize();
487
488   if (ESize) {
489     int64_t Res;
490     if (!ESize->evaluateKnownAbsolute(Res, Layout))
491       report_fatal_error("Size expression must be absolute.");
492     Size = Res;
493   }
494
495   // Write out the symbol table entry
496   Writer.writeSymbol(StringIndex, Info, Value, Size, Other, MSD.SectionIndex,
497                      IsReserved);
498 }
499
500 // It is always valid to create a relocation with a symbol. It is preferable
501 // to use a relocation with a section if that is possible. Using the section
502 // allows us to omit some local symbols from the symbol table.
503 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
504                                                const MCSymbolRefExpr *RefA,
505                                                const MCSymbol *Sym, uint64_t C,
506                                                unsigned Type) const {
507   // A PCRel relocation to an absolute value has no symbol (or section). We
508   // represent that with a relocation to a null section.
509   if (!RefA)
510     return false;
511
512   MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
513   switch (Kind) {
514   default:
515     break;
516   // The .odp creation emits a relocation against the symbol ".TOC." which
517   // create a R_PPC64_TOC relocation. However the relocation symbol name
518   // in final object creation should be NULL, since the symbol does not
519   // really exist, it is just the reference to TOC base for the current
520   // object file. Since the symbol is undefined, returning false results
521   // in a relocation with a null section which is the desired result.
522   case MCSymbolRefExpr::VK_PPC_TOCBASE:
523     return false;
524
525   // These VariantKind cause the relocation to refer to something other than
526   // the symbol itself, like a linker generated table. Since the address of
527   // symbol is not relevant, we cannot replace the symbol with the
528   // section and patch the difference in the addend.
529   case MCSymbolRefExpr::VK_GOT:
530   case MCSymbolRefExpr::VK_PLT:
531   case MCSymbolRefExpr::VK_GOTPCREL:
532   case MCSymbolRefExpr::VK_Mips_GOT:
533   case MCSymbolRefExpr::VK_PPC_GOT_LO:
534   case MCSymbolRefExpr::VK_PPC_GOT_HI:
535   case MCSymbolRefExpr::VK_PPC_GOT_HA:
536     return true;
537   }
538
539   // An undefined symbol is not in any section, so the relocation has to point
540   // to the symbol itself.
541   assert(Sym && "Expected a symbol");
542   if (Sym->isUndefined())
543     return true;
544
545   unsigned Binding = MCELF::GetBinding(*Sym);
546   switch(Binding) {
547   default:
548     llvm_unreachable("Invalid Binding");
549   case ELF::STB_LOCAL:
550     break;
551   case ELF::STB_WEAK:
552     // If the symbol is weak, it might be overridden by a symbol in another
553     // file. The relocation has to point to the symbol so that the linker
554     // can update it.
555     return true;
556   case ELF::STB_GLOBAL:
557     // Global ELF symbols can be preempted by the dynamic linker. The relocation
558     // has to point to the symbol for a reason analogous to the STB_WEAK case.
559     return true;
560   }
561
562   // If a relocation points to a mergeable section, we have to be careful.
563   // If the offset is zero, a relocation with the section will encode the
564   // same information. With a non-zero offset, the situation is different.
565   // For example, a relocation can point 42 bytes past the end of a string.
566   // If we change such a relocation to use the section, the linker would think
567   // that it pointed to another string and subtracting 42 at runtime will
568   // produce the wrong value.
569   auto &Sec = cast<MCSectionELF>(Sym->getSection());
570   unsigned Flags = Sec.getFlags();
571   if (Flags & ELF::SHF_MERGE) {
572     if (C != 0)
573       return true;
574
575     // It looks like gold has a bug (http://sourceware.org/PR16794) and can
576     // only handle section relocations to mergeable sections if using RELA.
577     if (!hasRelocationAddend())
578       return true;
579   }
580
581   // Most TLS relocations use a got, so they need the symbol. Even those that
582   // are just an offset (@tpoff), require a symbol in gold versions before
583   // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
584   // http://sourceware.org/PR16773.
585   if (Flags & ELF::SHF_TLS)
586     return true;
587
588   // If the symbol is a thumb function the final relocation must set the lowest
589   // bit. With a symbol that is done by just having the symbol have that bit
590   // set, so we would lose the bit if we relocated with the section.
591   // FIXME: We could use the section but add the bit to the relocation value.
592   if (Asm.isThumbFunc(Sym))
593     return true;
594
595   if (TargetObjectWriter->needsRelocateWithSymbol(*Sym, Type))
596     return true;
597   return false;
598 }
599
600 static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
601   const MCSymbol &Sym = Ref.getSymbol();
602
603   if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
604     return &Sym;
605
606   if (!Sym.isVariable())
607     return nullptr;
608
609   const MCExpr *Expr = Sym.getVariableValue();
610   const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
611   if (!Inner)
612     return nullptr;
613
614   if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
615     return &Inner->getSymbol();
616   return nullptr;
617 }
618
619 // True if the assembler knows nothing about the final value of the symbol.
620 // This doesn't cover the comdat issues, since in those cases the assembler
621 // can at least know that all symbols in the section will move together.
622 static bool isWeak(const MCSymbol &Sym) {
623   if (MCELF::GetType(Sym) == ELF::STT_GNU_IFUNC)
624     return true;
625
626   switch (MCELF::GetBinding(Sym)) {
627   default:
628     llvm_unreachable("Unknown binding");
629   case ELF::STB_LOCAL:
630     return false;
631   case ELF::STB_GLOBAL:
632     return false;
633   case ELF::STB_WEAK:
634   case ELF::STB_GNU_UNIQUE:
635     return true;
636   }
637 }
638
639 void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
640                                        const MCAsmLayout &Layout,
641                                        const MCFragment *Fragment,
642                                        const MCFixup &Fixup, MCValue Target,
643                                        bool &IsPCRel, uint64_t &FixedValue) {
644   const MCSectionELF &FixupSection = cast<MCSectionELF>(*Fragment->getParent());
645   uint64_t C = Target.getConstant();
646   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
647
648   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
649     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
650            "Should not have constructed this");
651
652     // Let A, B and C being the components of Target and R be the location of
653     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
654     // If it is pcrel, we want to compute (A - B + C - R).
655
656     // In general, ELF has no relocations for -B. It can only represent (A + C)
657     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
658     // replace B to implement it: (A - R - K + C)
659     if (IsPCRel)
660       Asm.getContext().reportFatalError(
661           Fixup.getLoc(),
662           "No relocation available to represent this relative expression");
663
664     const MCSymbol &SymB = RefB->getSymbol();
665
666     if (SymB.isUndefined())
667       Asm.getContext().reportFatalError(
668           Fixup.getLoc(),
669           Twine("symbol '") + SymB.getName() +
670               "' can not be undefined in a subtraction expression");
671
672     assert(!SymB.isAbsolute() && "Should have been folded");
673     const MCSection &SecB = SymB.getSection();
674     if (&SecB != &FixupSection)
675       Asm.getContext().reportFatalError(
676           Fixup.getLoc(), "Cannot represent a difference across sections");
677
678     if (::isWeak(SymB))
679       Asm.getContext().reportFatalError(
680           Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
681
682     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
683     uint64_t K = SymBOffset - FixupOffset;
684     IsPCRel = true;
685     C -= K;
686   }
687
688   // We either rejected the fixup or folded B into C at this point.
689   const MCSymbolRefExpr *RefA = Target.getSymA();
690   const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
691
692   unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
693   bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymA, C, Type);
694   if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
695     C += Layout.getSymbolOffset(*SymA);
696
697   uint64_t Addend = 0;
698   if (hasRelocationAddend()) {
699     Addend = C;
700     C = 0;
701   }
702
703   FixedValue = C;
704
705   if (!RelocateWithSymbol) {
706     const MCSection *SecA =
707         (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
708     auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
709     const MCSymbol *SectionSymbol = ELFSec ? ELFSec->getBeginSymbol() : nullptr;
710     ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
711     Relocations[&FixupSection].push_back(Rec);
712     return;
713   }
714
715   if (SymA) {
716     if (const MCSymbol *R = Renames.lookup(SymA))
717       SymA = R;
718
719     if (const MCSymbol *WeakRef = getWeakRef(*RefA))
720       WeakrefUsedInReloc.insert(WeakRef);
721     else
722       UsedInReloc.insert(SymA);
723   }
724   ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
725   Relocations[&FixupSection].push_back(Rec);
726   return;
727 }
728
729 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
730                                  const MCSymbol &Symbol, bool Used,
731                                  bool Renamed) {
732   if (Symbol.isVariable()) {
733     const MCExpr *Expr = Symbol.getVariableValue();
734     if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
735       if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
736         return false;
737     }
738   }
739
740   if (Used)
741     return true;
742
743   if (Renamed)
744     return false;
745
746   if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
747     return true;
748
749   if (Symbol.isVariable()) {
750     const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
751     if (Base && Base->isUndefined())
752       return false;
753   }
754
755   bool IsGlobal = MCELF::GetBinding(Symbol) == ELF::STB_GLOBAL;
756   if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
757     return false;
758
759   if (MCELF::GetType(Symbol) == ELF::STT_SECTION)
760     return true;
761
762   if (Symbol.isTemporary())
763     return false;
764
765   return true;
766 }
767
768 bool ELFObjectWriter::isLocal(const MCSymbol &Symbol, bool IsUsedInReloc,
769                               bool IsSignature) {
770   const MCSymbolData &Data = Symbol.getData();
771   if (Data.isExternal())
772     return false;
773
774   if (Symbol.isDefined())
775     return true;
776
777   if (IsUsedInReloc)
778     return false;
779
780   return IsSignature;
781 }
782
783 void ELFObjectWriter::computeSymbolTable(
784     MCAssembler &Asm, const MCAsmLayout &Layout,
785     const SectionIndexMapTy &SectionIndexMap, const RevGroupMapTy &RevGroupMap,
786     SectionOffsetsTy &SectionOffsets) {
787   MCContext &Ctx = Asm.getContext();
788   SymbolTableWriter Writer(*this, is64Bit());
789
790   // Symbol table
791   unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
792   MCSectionELF *SymtabSection =
793       Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize, "");
794   SymtabSection->setAlignment(is64Bit() ? 8 : 4);
795   SymbolTableIndex = addToSectionTable(SymtabSection);
796
797   uint64_t Padding =
798       OffsetToAlignment(OS.tell(), SymtabSection->getAlignment());
799   WriteZeros(Padding);
800
801   uint64_t SecStart = OS.tell();
802
803   // The first entry is the undefined symbol entry.
804   Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
805
806   std::vector<ELFSymbolData> LocalSymbolData;
807   std::vector<ELFSymbolData> ExternalSymbolData;
808
809   // Add the data for the symbols.
810   bool HasLargeSectionIndex = false;
811   for (const MCSymbol &Symbol : Asm.symbols()) {
812     bool Used = UsedInReloc.count(&Symbol);
813     bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
814     bool isSignature = RevGroupMap.count(&Symbol);
815
816     if (!isInSymtab(Layout, Symbol, Used || WeakrefUsed || isSignature,
817                     Renames.count(&Symbol)))
818       continue;
819
820     ELFSymbolData MSD;
821     MSD.Symbol = &Symbol;
822
823     // Undefined symbols are global, but this is the first place we
824     // are able to set it.
825     bool Local = isLocal(Symbol, Used, isSignature);
826     if (!Local && MCELF::GetBinding(Symbol) == ELF::STB_LOCAL)
827       MCELF::SetBinding(Symbol, ELF::STB_GLOBAL);
828
829     if (Symbol.isAbsolute()) {
830       MSD.SectionIndex = ELF::SHN_ABS;
831     } else if (Symbol.isCommon()) {
832       assert(!Local);
833       MSD.SectionIndex = ELF::SHN_COMMON;
834     } else if (Symbol.isUndefined()) {
835       if (isSignature && !Used) {
836         MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
837         if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
838           HasLargeSectionIndex = true;
839       } else {
840         MSD.SectionIndex = ELF::SHN_UNDEF;
841       }
842       if (!Used && WeakrefUsed)
843         MCELF::SetBinding(Symbol, ELF::STB_WEAK);
844     } else {
845       const MCSectionELF &Section =
846           static_cast<const MCSectionELF &>(Symbol.getSection());
847       MSD.SectionIndex = SectionIndexMap.lookup(&Section);
848       assert(MSD.SectionIndex && "Invalid section index!");
849       if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
850         HasLargeSectionIndex = true;
851     }
852
853     // The @@@ in symbol version is replaced with @ in undefined symbols and @@
854     // in defined ones.
855     //
856     // FIXME: All name handling should be done before we get to the writer,
857     // including dealing with GNU-style version suffixes.  Fixing this isn't
858     // trivial.
859     //
860     // We thus have to be careful to not perform the symbol version replacement
861     // blindly:
862     //
863     // The ELF format is used on Windows by the MCJIT engine.  Thus, on
864     // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
865     // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
866     // C++ name mangling can legally have "@@@" as a sub-string. In that case,
867     // the EFLObjectWriter should not interpret the "@@@" sub-string as
868     // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
869     // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
870     // "__imp_?" or "__imp_@?".
871     //
872     // It would have been interesting to perform the MS mangling prefix check
873     // only when the target triple is of the form *-pc-windows-elf. But, it
874     // seems that this information is not easily accessible from the
875     // ELFObjectWriter.
876     StringRef Name = Symbol.getName();
877     if (!Name.startswith("?") && !Name.startswith("@?") &&
878         !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
879       // This symbol isn't following the MSVC C++ name mangling convention. We
880       // can thus safely interpret the @@@ in symbol names as specifying symbol
881       // versioning.
882       SmallString<32> Buf;
883       size_t Pos = Name.find("@@@");
884       if (Pos != StringRef::npos) {
885         Buf += Name.substr(0, Pos);
886         unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
887         Buf += Name.substr(Pos + Skip);
888         Name = Buf;
889       }
890     }
891
892     // Sections have their own string table
893     if (MCELF::GetType(Symbol) != ELF::STT_SECTION)
894       MSD.Name = StrTabBuilder.add(Name);
895
896     if (Local)
897       LocalSymbolData.push_back(MSD);
898     else
899       ExternalSymbolData.push_back(MSD);
900   }
901
902   if (HasLargeSectionIndex) {
903     MCSectionELF *SymtabShndxSection =
904         Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
905     SymtabShndxSectionIndex = addToSectionTable(SymtabShndxSection);
906     SymtabShndxSection->setAlignment(4);
907   }
908
909   ArrayRef<std::string> FileNames = Asm.getFileNames();
910   for (const std::string &Name : FileNames)
911     StrTabBuilder.add(Name);
912
913   StrTabBuilder.finalize(StringTableBuilder::ELF);
914
915   for (const std::string &Name : FileNames)
916     Writer.writeSymbol(StrTabBuilder.getOffset(Name),
917                        ELF::STT_FILE | ELF::STB_LOCAL, 0, 0, ELF::STV_DEFAULT,
918                        ELF::SHN_ABS, true);
919
920   // Symbols are required to be in lexicographic order.
921   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
922   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
923
924   // Set the symbol indices. Local symbols must come before all other
925   // symbols with non-local bindings.
926   unsigned Index = FileNames.size() + 1;
927
928   for (ELFSymbolData &MSD : LocalSymbolData) {
929     unsigned StringIndex = MCELF::GetType(*MSD.Symbol) == ELF::STT_SECTION
930                                ? 0
931                                : StrTabBuilder.getOffset(MSD.Name);
932     MSD.Symbol->setIndex(Index++);
933     writeSymbol(Writer, StringIndex, MSD, Layout);
934   }
935
936   // Write the symbol table entries.
937   LastLocalSymbolIndex = Index;
938
939   for (ELFSymbolData &MSD : ExternalSymbolData) {
940     unsigned StringIndex = StrTabBuilder.getOffset(MSD.Name);
941     MSD.Symbol->setIndex(Index++);
942     writeSymbol(Writer, StringIndex, MSD, Layout);
943     assert(MCELF::GetBinding(*MSD.Symbol) != ELF::STB_LOCAL);
944   }
945
946   uint64_t SecEnd = OS.tell();
947   SectionOffsets[SymtabSection] = std::make_pair(SecStart, SecEnd);
948
949   ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes();
950   if (ShndxIndexes.empty()) {
951     assert(SymtabShndxSectionIndex == 0);
952     return;
953   }
954   assert(SymtabShndxSectionIndex != 0);
955
956   SecStart = OS.tell();
957   const MCSectionELF *SymtabShndxSection =
958       SectionTable[SymtabShndxSectionIndex - 1];
959   for (uint32_t Index : ShndxIndexes)
960     write(Index);
961   SecEnd = OS.tell();
962   SectionOffsets[SymtabShndxSection] = std::make_pair(SecStart, SecEnd);
963 }
964
965 MCSectionELF *
966 ELFObjectWriter::createRelocationSection(MCContext &Ctx,
967                                          const MCSectionELF &Sec) {
968   if (Relocations[&Sec].empty())
969     return nullptr;
970
971   const StringRef SectionName = Sec.getSectionName();
972   std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
973   RelaSectionName += SectionName;
974
975   unsigned EntrySize;
976   if (hasRelocationAddend())
977     EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
978   else
979     EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
980
981   unsigned Flags = 0;
982   if (Sec.getFlags() & ELF::SHF_GROUP)
983     Flags = ELF::SHF_GROUP;
984
985   MCSectionELF *RelaSection = Ctx.createELFRelSection(
986       RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
987       Flags, EntrySize, Sec.getGroup(), &Sec);
988   RelaSection->setAlignment(is64Bit() ? 8 : 4);
989   return RelaSection;
990 }
991
992 static SmallVector<char, 128>
993 getUncompressedData(const MCAsmLayout &Layout,
994                     const MCSection::FragmentListType &Fragments) {
995   SmallVector<char, 128> UncompressedData;
996   for (const MCFragment &F : Fragments) {
997     const SmallVectorImpl<char> *Contents;
998     switch (F.getKind()) {
999     case MCFragment::FT_Data:
1000       Contents = &cast<MCDataFragment>(F).getContents();
1001       break;
1002     case MCFragment::FT_Dwarf:
1003       Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1004       break;
1005     case MCFragment::FT_DwarfFrame:
1006       Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1007       break;
1008     default:
1009       llvm_unreachable(
1010           "Not expecting any other fragment types in a debug_* section");
1011     }
1012     UncompressedData.append(Contents->begin(), Contents->end());
1013   }
1014   return UncompressedData;
1015 }
1016
1017 // Include the debug info compression header:
1018 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1019 // useful for consumers to preallocate a buffer to decompress into.
1020 static bool
1021 prependCompressionHeader(uint64_t Size,
1022                          SmallVectorImpl<char> &CompressedContents) {
1023   const StringRef Magic = "ZLIB";
1024   if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1025     return false;
1026   if (sys::IsLittleEndianHost)
1027     sys::swapByteOrder(Size);
1028   CompressedContents.insert(CompressedContents.begin(),
1029                             Magic.size() + sizeof(Size), 0);
1030   std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1031   std::copy(reinterpret_cast<char *>(&Size),
1032             reinterpret_cast<char *>(&Size + 1),
1033             CompressedContents.begin() + Magic.size());
1034   return true;
1035 }
1036
1037 void ELFObjectWriter::writeSectionData(const MCAssembler &Asm, MCSection &Sec,
1038                                        const MCAsmLayout &Layout) {
1039   MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
1040   StringRef SectionName = Section.getSectionName();
1041
1042   // Compressing debug_frame requires handling alignment fragments which is
1043   // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1044   // for writing to arbitrary buffers) for little benefit.
1045   if (!Asm.getContext().getAsmInfo()->compressDebugSections() ||
1046       !SectionName.startswith(".debug_") || SectionName == ".debug_frame") {
1047     Asm.writeSectionData(&Section, Layout);
1048     return;
1049   }
1050
1051   // Gather the uncompressed data from all the fragments.
1052   const MCSection::FragmentListType &Fragments = Section.getFragmentList();
1053   SmallVector<char, 128> UncompressedData =
1054       getUncompressedData(Layout, Fragments);
1055
1056   SmallVector<char, 128> CompressedContents;
1057   zlib::Status Success = zlib::compress(
1058       StringRef(UncompressedData.data(), UncompressedData.size()),
1059       CompressedContents);
1060   if (Success != zlib::StatusOK) {
1061     Asm.writeSectionData(&Section, Layout);
1062     return;
1063   }
1064
1065   if (!prependCompressionHeader(UncompressedData.size(), CompressedContents)) {
1066     Asm.writeSectionData(&Section, Layout);
1067     return;
1068   }
1069   Asm.getContext().renameELFSection(&Section,
1070                                     (".z" + SectionName.drop_front(1)).str());
1071   OS << CompressedContents;
1072 }
1073
1074 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1075                                        uint64_t Flags, uint64_t Address,
1076                                        uint64_t Offset, uint64_t Size,
1077                                        uint32_t Link, uint32_t Info,
1078                                        uint64_t Alignment,
1079                                        uint64_t EntrySize) {
1080   Write32(Name);        // sh_name: index into string table
1081   Write32(Type);        // sh_type
1082   WriteWord(Flags);     // sh_flags
1083   WriteWord(Address);   // sh_addr
1084   WriteWord(Offset);    // sh_offset
1085   WriteWord(Size);      // sh_size
1086   Write32(Link);        // sh_link
1087   Write32(Info);        // sh_info
1088   WriteWord(Alignment); // sh_addralign
1089   WriteWord(EntrySize); // sh_entsize
1090 }
1091
1092 void ELFObjectWriter::writeRelocations(const MCAssembler &Asm,
1093                                        const MCSectionELF &Sec) {
1094   std::vector<ELFRelocationEntry> &Relocs = Relocations[&Sec];
1095
1096   // Sort the relocation entries. Most targets just sort by Offset, but some
1097   // (e.g., MIPS) have additional constraints.
1098   TargetObjectWriter->sortRelocs(Asm, Relocs);
1099
1100   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1101     const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1102     unsigned Index = Entry.Symbol ? Entry.Symbol->getIndex() : 0;
1103
1104     if (is64Bit()) {
1105       write(Entry.Offset);
1106       if (TargetObjectWriter->isN64()) {
1107         write(uint32_t(Index));
1108
1109         write(TargetObjectWriter->getRSsym(Entry.Type));
1110         write(TargetObjectWriter->getRType3(Entry.Type));
1111         write(TargetObjectWriter->getRType2(Entry.Type));
1112         write(TargetObjectWriter->getRType(Entry.Type));
1113       } else {
1114         struct ELF::Elf64_Rela ERE64;
1115         ERE64.setSymbolAndType(Index, Entry.Type);
1116         write(ERE64.r_info);
1117       }
1118       if (hasRelocationAddend())
1119         write(Entry.Addend);
1120     } else {
1121       write(uint32_t(Entry.Offset));
1122
1123       struct ELF::Elf32_Rela ERE32;
1124       ERE32.setSymbolAndType(Index, Entry.Type);
1125       write(ERE32.r_info);
1126
1127       if (hasRelocationAddend())
1128         write(uint32_t(Entry.Addend));
1129     }
1130   }
1131 }
1132
1133 const MCSectionELF *ELFObjectWriter::createStringTable(MCContext &Ctx) {
1134   const MCSectionELF *StrtabSection = SectionTable[StringTableIndex - 1];
1135   OS << StrTabBuilder.data();
1136   return StrtabSection;
1137 }
1138
1139 void ELFObjectWriter::writeSection(const SectionIndexMapTy &SectionIndexMap,
1140                                    uint32_t GroupSymbolIndex, uint64_t Offset,
1141                                    uint64_t Size, const MCSectionELF &Section) {
1142   uint64_t sh_link = 0;
1143   uint64_t sh_info = 0;
1144
1145   switch(Section.getType()) {
1146   default:
1147     // Nothing to do.
1148     break;
1149
1150   case ELF::SHT_DYNAMIC:
1151     llvm_unreachable("SHT_DYNAMIC in a relocatable object");
1152
1153   case ELF::SHT_REL:
1154   case ELF::SHT_RELA: {
1155     sh_link = SymbolTableIndex;
1156     assert(sh_link && ".symtab not found");
1157     const MCSectionELF *InfoSection = Section.getAssociatedSection();
1158     sh_info = SectionIndexMap.lookup(InfoSection);
1159     break;
1160   }
1161
1162   case ELF::SHT_SYMTAB:
1163   case ELF::SHT_DYNSYM:
1164     sh_link = StringTableIndex;
1165     sh_info = LastLocalSymbolIndex;
1166     break;
1167
1168   case ELF::SHT_SYMTAB_SHNDX:
1169     sh_link = SymbolTableIndex;
1170     break;
1171
1172   case ELF::SHT_GROUP:
1173     sh_link = SymbolTableIndex;
1174     sh_info = GroupSymbolIndex;
1175     break;
1176   }
1177
1178   if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1179       Section.getType() == ELF::SHT_ARM_EXIDX)
1180     sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1181
1182   WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getSectionName()),
1183                    Section.getType(), Section.getFlags(), 0, Offset, Size,
1184                    sh_link, sh_info, Section.getAlignment(),
1185                    Section.getEntrySize());
1186 }
1187
1188 void ELFObjectWriter::writeSectionHeader(
1189     const MCAssembler &Asm, const MCAsmLayout &Layout,
1190     const SectionIndexMapTy &SectionIndexMap,
1191     const SectionOffsetsTy &SectionOffsets) {
1192   const unsigned NumSections = SectionTable.size();
1193
1194   // Null section first.
1195   uint64_t FirstSectionSize =
1196       (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
1197   WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
1198
1199   for (const MCSectionELF *Section : SectionTable) {
1200     uint32_t GroupSymbolIndex;
1201     unsigned Type = Section->getType();
1202     if (Type != ELF::SHT_GROUP)
1203       GroupSymbolIndex = 0;
1204     else
1205       GroupSymbolIndex = Section->getGroup()->getIndex();
1206
1207     const std::pair<uint64_t, uint64_t> &Offsets =
1208         SectionOffsets.find(Section)->second;
1209     uint64_t Size;
1210     if (Type == ELF::SHT_NOBITS)
1211       Size = Layout.getSectionAddressSize(Section);
1212     else
1213       Size = Offsets.second - Offsets.first;
1214
1215     writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1216                  *Section);
1217   }
1218 }
1219
1220 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1221                                   const MCAsmLayout &Layout) {
1222   MCContext &Ctx = Asm.getContext();
1223   MCSectionELF *StrtabSection =
1224       Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1225   StringTableIndex = addToSectionTable(StrtabSection);
1226
1227   RevGroupMapTy RevGroupMap;
1228   SectionIndexMapTy SectionIndexMap;
1229
1230   std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers;
1231
1232   // Write out the ELF header ...
1233   writeHeader(Asm);
1234
1235   // ... then the sections ...
1236   SectionOffsetsTy SectionOffsets;
1237   std::vector<MCSectionELF *> Groups;
1238   std::vector<MCSectionELF *> Relocations;
1239   for (MCSection &Sec : Asm) {
1240     MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
1241
1242     uint64_t Padding = OffsetToAlignment(OS.tell(), Section.getAlignment());
1243     WriteZeros(Padding);
1244
1245     // Remember the offset into the file for this section.
1246     uint64_t SecStart = OS.tell();
1247
1248     const MCSymbol *SignatureSymbol = Section.getGroup();
1249     writeSectionData(Asm, Section, Layout);
1250
1251     uint64_t SecEnd = OS.tell();
1252     SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd);
1253
1254     MCSectionELF *RelSection = createRelocationSection(Ctx, Section);
1255
1256     if (SignatureSymbol) {
1257       Asm.getOrCreateSymbolData(*SignatureSymbol);
1258       unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1259       if (!GroupIdx) {
1260         MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
1261         GroupIdx = addToSectionTable(Group);
1262         Group->setAlignment(4);
1263         Groups.push_back(Group);
1264       }
1265       GroupMembers[SignatureSymbol].push_back(&Section);
1266       if (RelSection)
1267         GroupMembers[SignatureSymbol].push_back(RelSection);
1268     }
1269
1270     SectionIndexMap[&Section] = addToSectionTable(&Section);
1271     if (RelSection) {
1272       SectionIndexMap[RelSection] = addToSectionTable(RelSection);
1273       Relocations.push_back(RelSection);
1274     }
1275   }
1276
1277   for (MCSectionELF *Group : Groups) {
1278     uint64_t Padding = OffsetToAlignment(OS.tell(), Group->getAlignment());
1279     WriteZeros(Padding);
1280
1281     // Remember the offset into the file for this section.
1282     uint64_t SecStart = OS.tell();
1283
1284     const MCSymbol *SignatureSymbol = Group->getGroup();
1285     assert(SignatureSymbol);
1286     write(uint32_t(ELF::GRP_COMDAT));
1287     for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) {
1288       uint32_t SecIndex = SectionIndexMap.lookup(Member);
1289       write(SecIndex);
1290     }
1291
1292     uint64_t SecEnd = OS.tell();
1293     SectionOffsets[Group] = std::make_pair(SecStart, SecEnd);
1294   }
1295
1296   // Compute symbol table information.
1297   computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap, SectionOffsets);
1298
1299   for (MCSectionELF *RelSection : Relocations) {
1300     uint64_t Padding = OffsetToAlignment(OS.tell(), RelSection->getAlignment());
1301     WriteZeros(Padding);
1302
1303     // Remember the offset into the file for this section.
1304     uint64_t SecStart = OS.tell();
1305
1306     writeRelocations(Asm, *RelSection->getAssociatedSection());
1307
1308     uint64_t SecEnd = OS.tell();
1309     SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd);
1310   }
1311
1312   {
1313     uint64_t SecStart = OS.tell();
1314     const MCSectionELF *Sec = createStringTable(Ctx);
1315     uint64_t SecEnd = OS.tell();
1316     SectionOffsets[Sec] = std::make_pair(SecStart, SecEnd);
1317   }
1318
1319   uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1320   uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1321   WriteZeros(Padding);
1322
1323   const unsigned SectionHeaderOffset = OS.tell();
1324
1325   // ... then the section header table ...
1326   writeSectionHeader(Asm, Layout, SectionIndexMap, SectionOffsets);
1327
1328   uint16_t NumSections = (SectionTable.size() + 1 >= ELF::SHN_LORESERVE)
1329                              ? (uint16_t)ELF::SHN_UNDEF
1330                              : SectionTable.size() + 1;
1331   if (sys::IsLittleEndianHost != IsLittleEndian)
1332     sys::swapByteOrder(NumSections);
1333   unsigned NumSectionsOffset;
1334
1335   if (is64Bit()) {
1336     uint64_t Val = SectionHeaderOffset;
1337     if (sys::IsLittleEndianHost != IsLittleEndian)
1338       sys::swapByteOrder(Val);
1339     OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1340               offsetof(ELF::Elf64_Ehdr, e_shoff));
1341     NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
1342   } else {
1343     uint32_t Val = SectionHeaderOffset;
1344     if (sys::IsLittleEndianHost != IsLittleEndian)
1345       sys::swapByteOrder(Val);
1346     OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1347               offsetof(ELF::Elf32_Ehdr, e_shoff));
1348     NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
1349   }
1350   OS.pwrite(reinterpret_cast<char *>(&NumSections), sizeof(NumSections),
1351             NumSectionsOffset);
1352 }
1353
1354 bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1355     const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
1356     bool InSet, bool IsPCRel) const {
1357   if (IsPCRel) {
1358     assert(!InSet);
1359     if (::isWeak(SymA))
1360       return false;
1361   }
1362   return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
1363                                                                 InSet, IsPCRel);
1364 }
1365
1366 bool ELFObjectWriter::isWeak(const MCSymbol &Sym) const {
1367   if (::isWeak(Sym))
1368     return true;
1369
1370   // It is invalid to replace a reference to a global in a comdat
1371   // with a reference to a local since out of comdat references
1372   // to a local are forbidden.
1373   // We could try to return false for more cases, like the reference
1374   // being in the same comdat or Sym being an alias to another global,
1375   // but it is not clear if it is worth the effort.
1376   if (MCELF::GetBinding(Sym) != ELF::STB_GLOBAL)
1377     return false;
1378
1379   if (!Sym.isInSection())
1380     return false;
1381
1382   const auto &Sec = cast<MCSectionELF>(Sym.getSection());
1383   return Sec.getGroup();
1384 }
1385
1386 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1387                                             raw_pwrite_stream &OS,
1388                                             bool IsLittleEndian) {
1389   return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
1390 }