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