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