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