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