Don't special case undefined symbol when deciding the symbol order.
[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
809   // Add the data for the symbols.
810   bool HasLargeSectionIndex = false;
811   for (const MCSymbol &Symbol : Asm.symbols()) {
812     MCSymbolData &SD = Symbol.getData();
813
814     bool Used = UsedInReloc.count(&Symbol);
815     bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
816     bool isSignature = RevGroupMap.count(&Symbol);
817
818     if (!isInSymtab(Layout, Symbol, Used || WeakrefUsed || isSignature,
819                     Renames.count(&Symbol)))
820       continue;
821
822     ELFSymbolData MSD;
823     MSD.Symbol = &Symbol;
824     const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
825
826     // Undefined symbols are global, but this is the first place we
827     // are able to set it.
828     bool Local = isLocal(Symbol, Used);
829     if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
830       assert(BaseSymbol);
831       MCSymbolData &BaseData = BaseSymbol->getData();
832       MCELF::SetBinding(SD, ELF::STB_GLOBAL);
833       MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
834     }
835
836     if (!BaseSymbol) {
837       MSD.SectionIndex = ELF::SHN_ABS;
838     } else if (SD.isCommon()) {
839       assert(!Local);
840       MSD.SectionIndex = ELF::SHN_COMMON;
841     } else if (BaseSymbol->isUndefined()) {
842       if (isSignature && !Used) {
843         MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
844         if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
845           HasLargeSectionIndex = true;
846       } else {
847         MSD.SectionIndex = ELF::SHN_UNDEF;
848       }
849       if (!Used && WeakrefUsed)
850         MCELF::SetBinding(SD, ELF::STB_WEAK);
851     } else {
852       const MCSectionELF &Section =
853         static_cast<const MCSectionELF&>(BaseSymbol->getSection());
854       MSD.SectionIndex = SectionIndexMap.lookup(&Section);
855       assert(MSD.SectionIndex && "Invalid section index!");
856       if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
857         HasLargeSectionIndex = true;
858     }
859
860     // The @@@ in symbol version is replaced with @ in undefined symbols and @@
861     // in defined ones.
862     //
863     // FIXME: All name handling should be done before we get to the writer,
864     // including dealing with GNU-style version suffixes.  Fixing this isn't
865     // trivial.
866     //
867     // We thus have to be careful to not perform the symbol version replacement
868     // blindly:
869     //
870     // The ELF format is used on Windows by the MCJIT engine.  Thus, on
871     // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
872     // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
873     // C++ name mangling can legally have "@@@" as a sub-string. In that case,
874     // the EFLObjectWriter should not interpret the "@@@" sub-string as
875     // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
876     // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
877     // "__imp_?" or "__imp_@?".
878     //
879     // It would have been interesting to perform the MS mangling prefix check
880     // only when the target triple is of the form *-pc-windows-elf. But, it
881     // seems that this information is not easily accessible from the
882     // ELFObjectWriter.
883     StringRef Name = Symbol.getName();
884     if (!Name.startswith("?") && !Name.startswith("@?") &&
885         !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
886       // This symbol isn't following the MSVC C++ name mangling convention. We
887       // can thus safely interpret the @@@ in symbol names as specifying symbol
888       // versioning.
889       SmallString<32> Buf;
890       size_t Pos = Name.find("@@@");
891       if (Pos != StringRef::npos) {
892         Buf += Name.substr(0, Pos);
893         unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
894         Buf += Name.substr(Pos + Skip);
895         Name = Buf;
896       }
897     }
898
899     // Sections have their own string table
900     if (MCELF::GetType(SD) != ELF::STT_SECTION)
901       MSD.Name = StrTabBuilder.add(Name);
902
903     if (MSD.SectionIndex == ELF::SHN_UNDEF)
904       ExternalSymbolData.push_back(MSD);
905     else if (Local)
906       LocalSymbolData.push_back(MSD);
907     else
908       ExternalSymbolData.push_back(MSD);
909   }
910
911   if (HasLargeSectionIndex) {
912     MCSectionELF *SymtabShndxSection =
913         Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
914     SymtabShndxSectionIndex = addToSectionTable(SymtabShndxSection);
915     SymtabShndxSection->setAlignment(4);
916   }
917
918   ArrayRef<std::string> FileNames = Asm.getFileNames();
919   for (const std::string &Name : FileNames)
920     StrTabBuilder.add(Name);
921
922   StrTabBuilder.finalize(StringTableBuilder::ELF);
923
924   for (const std::string &Name : FileNames)
925     Writer.writeSymbol(StrTabBuilder.getOffset(Name),
926                        ELF::STT_FILE | ELF::STB_LOCAL, 0, 0, ELF::STV_DEFAULT,
927                        ELF::SHN_ABS, true);
928
929   // Symbols are required to be in lexicographic order.
930   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
931   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
932
933   // Set the symbol indices. Local symbols must come before all other
934   // symbols with non-local bindings.
935   unsigned Index = FileNames.size() + 1;
936
937   for (ELFSymbolData &MSD : LocalSymbolData) {
938     unsigned StringIndex =
939         MCELF::GetType(MSD.Symbol->getData()) == ELF::STT_SECTION
940             ? 0
941             : StrTabBuilder.getOffset(MSD.Name);
942     MSD.Symbol->setIndex(Index++);
943     writeSymbol(Writer, StringIndex, MSD, Layout);
944   }
945
946   // Write the symbol table entries.
947   LastLocalSymbolIndex = Index;
948
949   for (ELFSymbolData &MSD : ExternalSymbolData) {
950     unsigned StringIndex = StrTabBuilder.getOffset(MSD.Name);
951     MSD.Symbol->setIndex(Index++);
952     writeSymbol(Writer, StringIndex, MSD, Layout);
953     assert(MCELF::GetBinding(MSD.Symbol->getData()) != ELF::STB_LOCAL);
954   }
955
956   uint64_t SecEnd = OS.tell();
957   SectionOffsets[SymtabSection] = std::make_pair(SecStart, SecEnd);
958
959   ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes();
960   if (ShndxIndexes.empty()) {
961     assert(SymtabShndxSectionIndex == 0);
962     return;
963   }
964   assert(SymtabShndxSectionIndex != 0);
965
966   SecStart = OS.tell();
967   const MCSectionELF *SymtabShndxSection =
968       SectionTable[SymtabShndxSectionIndex - 1];
969   for (uint32_t Index : ShndxIndexes)
970     write(Index);
971   SecEnd = OS.tell();
972   SectionOffsets[SymtabShndxSection] = std::make_pair(SecStart, SecEnd);
973 }
974
975 MCSectionELF *
976 ELFObjectWriter::createRelocationSection(MCContext &Ctx,
977                                          const MCSectionELF &Sec) {
978   if (Relocations[&Sec].empty())
979     return nullptr;
980
981   const StringRef SectionName = Sec.getSectionName();
982   std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
983   RelaSectionName += SectionName;
984
985   unsigned EntrySize;
986   if (hasRelocationAddend())
987     EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
988   else
989     EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
990
991   unsigned Flags = 0;
992   if (Sec.getFlags() & ELF::SHF_GROUP)
993     Flags = ELF::SHF_GROUP;
994
995   MCSectionELF *RelaSection = Ctx.createELFRelSection(
996       RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
997       Flags, EntrySize, Sec.getGroup(), &Sec);
998   RelaSection->setAlignment(is64Bit() ? 8 : 4);
999   return RelaSection;
1000 }
1001
1002 static SmallVector<char, 128>
1003 getUncompressedData(const MCAsmLayout &Layout,
1004                     const MCSection::FragmentListType &Fragments) {
1005   SmallVector<char, 128> UncompressedData;
1006   for (const MCFragment &F : Fragments) {
1007     const SmallVectorImpl<char> *Contents;
1008     switch (F.getKind()) {
1009     case MCFragment::FT_Data:
1010       Contents = &cast<MCDataFragment>(F).getContents();
1011       break;
1012     case MCFragment::FT_Dwarf:
1013       Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1014       break;
1015     case MCFragment::FT_DwarfFrame:
1016       Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1017       break;
1018     default:
1019       llvm_unreachable(
1020           "Not expecting any other fragment types in a debug_* section");
1021     }
1022     UncompressedData.append(Contents->begin(), Contents->end());
1023   }
1024   return UncompressedData;
1025 }
1026
1027 // Include the debug info compression header:
1028 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1029 // useful for consumers to preallocate a buffer to decompress into.
1030 static bool
1031 prependCompressionHeader(uint64_t Size,
1032                          SmallVectorImpl<char> &CompressedContents) {
1033   const StringRef Magic = "ZLIB";
1034   if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1035     return false;
1036   if (sys::IsLittleEndianHost)
1037     sys::swapByteOrder(Size);
1038   CompressedContents.insert(CompressedContents.begin(),
1039                             Magic.size() + sizeof(Size), 0);
1040   std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1041   std::copy(reinterpret_cast<char *>(&Size),
1042             reinterpret_cast<char *>(&Size + 1),
1043             CompressedContents.begin() + Magic.size());
1044   return true;
1045 }
1046
1047 void ELFObjectWriter::writeSectionData(const MCAssembler &Asm, MCSection &Sec,
1048                                        const MCAsmLayout &Layout) {
1049   MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
1050   StringRef SectionName = Section.getSectionName();
1051
1052   // Compressing debug_frame requires handling alignment fragments which is
1053   // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1054   // for writing to arbitrary buffers) for little benefit.
1055   if (!Asm.getContext().getAsmInfo()->compressDebugSections() ||
1056       !SectionName.startswith(".debug_") || SectionName == ".debug_frame") {
1057     Asm.writeSectionData(&Section, Layout);
1058     return;
1059   }
1060
1061   // Gather the uncompressed data from all the fragments.
1062   const MCSection::FragmentListType &Fragments = Section.getFragmentList();
1063   SmallVector<char, 128> UncompressedData =
1064       getUncompressedData(Layout, Fragments);
1065
1066   SmallVector<char, 128> CompressedContents;
1067   zlib::Status Success = zlib::compress(
1068       StringRef(UncompressedData.data(), UncompressedData.size()),
1069       CompressedContents);
1070   if (Success != zlib::StatusOK) {
1071     Asm.writeSectionData(&Section, Layout);
1072     return;
1073   }
1074
1075   if (!prependCompressionHeader(UncompressedData.size(), CompressedContents)) {
1076     Asm.writeSectionData(&Section, Layout);
1077     return;
1078   }
1079   Asm.getContext().renameELFSection(&Section,
1080                                     (".z" + SectionName.drop_front(1)).str());
1081   OS << CompressedContents;
1082 }
1083
1084 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1085                                        uint64_t Flags, uint64_t Address,
1086                                        uint64_t Offset, uint64_t Size,
1087                                        uint32_t Link, uint32_t Info,
1088                                        uint64_t Alignment,
1089                                        uint64_t EntrySize) {
1090   Write32(Name);        // sh_name: index into string table
1091   Write32(Type);        // sh_type
1092   WriteWord(Flags);     // sh_flags
1093   WriteWord(Address);   // sh_addr
1094   WriteWord(Offset);    // sh_offset
1095   WriteWord(Size);      // sh_size
1096   Write32(Link);        // sh_link
1097   Write32(Info);        // sh_info
1098   WriteWord(Alignment); // sh_addralign
1099   WriteWord(EntrySize); // sh_entsize
1100 }
1101
1102 void ELFObjectWriter::writeRelocations(const MCAssembler &Asm,
1103                                        const MCSectionELF &Sec) {
1104   std::vector<ELFRelocationEntry> &Relocs = Relocations[&Sec];
1105
1106   // Sort the relocation entries. Most targets just sort by Offset, but some
1107   // (e.g., MIPS) have additional constraints.
1108   TargetObjectWriter->sortRelocs(Asm, Relocs);
1109
1110   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1111     const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1112     unsigned Index = Entry.Symbol ? Entry.Symbol->getIndex() : 0;
1113
1114     if (is64Bit()) {
1115       write(Entry.Offset);
1116       if (TargetObjectWriter->isN64()) {
1117         write(uint32_t(Index));
1118
1119         write(TargetObjectWriter->getRSsym(Entry.Type));
1120         write(TargetObjectWriter->getRType3(Entry.Type));
1121         write(TargetObjectWriter->getRType2(Entry.Type));
1122         write(TargetObjectWriter->getRType(Entry.Type));
1123       } else {
1124         struct ELF::Elf64_Rela ERE64;
1125         ERE64.setSymbolAndType(Index, Entry.Type);
1126         write(ERE64.r_info);
1127       }
1128       if (hasRelocationAddend())
1129         write(Entry.Addend);
1130     } else {
1131       write(uint32_t(Entry.Offset));
1132
1133       struct ELF::Elf32_Rela ERE32;
1134       ERE32.setSymbolAndType(Index, Entry.Type);
1135       write(ERE32.r_info);
1136
1137       if (hasRelocationAddend())
1138         write(uint32_t(Entry.Addend));
1139     }
1140   }
1141 }
1142
1143 const MCSectionELF *ELFObjectWriter::createStringTable(MCContext &Ctx) {
1144   const MCSectionELF *StrtabSection = SectionTable[StringTableIndex - 1];
1145   OS << StrTabBuilder.data();
1146   return StrtabSection;
1147 }
1148
1149 void ELFObjectWriter::writeSection(const SectionIndexMapTy &SectionIndexMap,
1150                                    uint32_t GroupSymbolIndex, uint64_t Offset,
1151                                    uint64_t Size, const MCSectionELF &Section) {
1152   uint64_t sh_link = 0;
1153   uint64_t sh_info = 0;
1154
1155   switch(Section.getType()) {
1156   default:
1157     // Nothing to do.
1158     break;
1159
1160   case ELF::SHT_DYNAMIC:
1161     llvm_unreachable("SHT_DYNAMIC in a relocatable object");
1162
1163   case ELF::SHT_REL:
1164   case ELF::SHT_RELA: {
1165     sh_link = SymbolTableIndex;
1166     assert(sh_link && ".symtab not found");
1167     const MCSectionELF *InfoSection = Section.getAssociatedSection();
1168     sh_info = SectionIndexMap.lookup(InfoSection);
1169     break;
1170   }
1171
1172   case ELF::SHT_SYMTAB:
1173   case ELF::SHT_DYNSYM:
1174     sh_link = StringTableIndex;
1175     sh_info = LastLocalSymbolIndex;
1176     break;
1177
1178   case ELF::SHT_SYMTAB_SHNDX:
1179     sh_link = SymbolTableIndex;
1180     break;
1181
1182   case ELF::SHT_GROUP:
1183     sh_link = SymbolTableIndex;
1184     sh_info = GroupSymbolIndex;
1185     break;
1186   }
1187
1188   if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1189       Section.getType() == ELF::SHT_ARM_EXIDX)
1190     sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1191
1192   WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getSectionName()),
1193                    Section.getType(), Section.getFlags(), 0, Offset, Size,
1194                    sh_link, sh_info, Section.getAlignment(),
1195                    Section.getEntrySize());
1196 }
1197
1198 void ELFObjectWriter::writeSectionHeader(
1199     const MCAssembler &Asm, const MCAsmLayout &Layout,
1200     const SectionIndexMapTy &SectionIndexMap,
1201     const SectionOffsetsTy &SectionOffsets) {
1202   const unsigned NumSections = SectionTable.size();
1203
1204   // Null section first.
1205   uint64_t FirstSectionSize =
1206       (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
1207   WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
1208
1209   for (const MCSectionELF *Section : SectionTable) {
1210     uint32_t GroupSymbolIndex;
1211     unsigned Type = Section->getType();
1212     if (Type != ELF::SHT_GROUP)
1213       GroupSymbolIndex = 0;
1214     else
1215       GroupSymbolIndex = Section->getGroup()->getIndex();
1216
1217     const std::pair<uint64_t, uint64_t> &Offsets =
1218         SectionOffsets.find(Section)->second;
1219     uint64_t Size;
1220     if (Type == ELF::SHT_NOBITS)
1221       Size = Layout.getSectionAddressSize(Section);
1222     else
1223       Size = Offsets.second - Offsets.first;
1224
1225     writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1226                  *Section);
1227   }
1228 }
1229
1230 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1231                                   const MCAsmLayout &Layout) {
1232   MCContext &Ctx = Asm.getContext();
1233   MCSectionELF *StrtabSection =
1234       Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1235   StringTableIndex = addToSectionTable(StrtabSection);
1236
1237   RevGroupMapTy RevGroupMap;
1238   SectionIndexMapTy SectionIndexMap;
1239
1240   std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers;
1241
1242   // Write out the ELF header ...
1243   writeHeader(Asm);
1244
1245   // ... then the sections ...
1246   SectionOffsetsTy SectionOffsets;
1247   std::vector<MCSectionELF *> Groups;
1248   std::vector<MCSectionELF *> Relocations;
1249   for (MCSection &Sec : Asm) {
1250     MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
1251
1252     uint64_t Padding = OffsetToAlignment(OS.tell(), Section.getAlignment());
1253     WriteZeros(Padding);
1254
1255     // Remember the offset into the file for this section.
1256     uint64_t SecStart = OS.tell();
1257
1258     const MCSymbol *SignatureSymbol = Section.getGroup();
1259     writeSectionData(Asm, Section, Layout);
1260
1261     uint64_t SecEnd = OS.tell();
1262     SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd);
1263
1264     MCSectionELF *RelSection = createRelocationSection(Ctx, Section);
1265
1266     if (SignatureSymbol) {
1267       Asm.getOrCreateSymbolData(*SignatureSymbol);
1268       unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1269       if (!GroupIdx) {
1270         MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
1271         GroupIdx = addToSectionTable(Group);
1272         Group->setAlignment(4);
1273         Groups.push_back(Group);
1274       }
1275       GroupMembers[SignatureSymbol].push_back(&Section);
1276       if (RelSection)
1277         GroupMembers[SignatureSymbol].push_back(RelSection);
1278     }
1279
1280     SectionIndexMap[&Section] = addToSectionTable(&Section);
1281     if (RelSection) {
1282       SectionIndexMap[RelSection] = addToSectionTable(RelSection);
1283       Relocations.push_back(RelSection);
1284     }
1285   }
1286
1287   for (MCSectionELF *Group : Groups) {
1288     uint64_t Padding = OffsetToAlignment(OS.tell(), Group->getAlignment());
1289     WriteZeros(Padding);
1290
1291     // Remember the offset into the file for this section.
1292     uint64_t SecStart = OS.tell();
1293
1294     const MCSymbol *SignatureSymbol = Group->getGroup();
1295     assert(SignatureSymbol);
1296     write(uint32_t(ELF::GRP_COMDAT));
1297     for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) {
1298       uint32_t SecIndex = SectionIndexMap.lookup(Member);
1299       write(SecIndex);
1300     }
1301
1302     uint64_t SecEnd = OS.tell();
1303     SectionOffsets[Group] = std::make_pair(SecStart, SecEnd);
1304   }
1305
1306   // Compute symbol table information.
1307   computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap, SectionOffsets);
1308
1309   for (MCSectionELF *RelSection : Relocations) {
1310     uint64_t Padding = OffsetToAlignment(OS.tell(), RelSection->getAlignment());
1311     WriteZeros(Padding);
1312
1313     // Remember the offset into the file for this section.
1314     uint64_t SecStart = OS.tell();
1315
1316     writeRelocations(Asm, *RelSection->getAssociatedSection());
1317
1318     uint64_t SecEnd = OS.tell();
1319     SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd);
1320   }
1321
1322   {
1323     uint64_t SecStart = OS.tell();
1324     const MCSectionELF *Sec = createStringTable(Ctx);
1325     uint64_t SecEnd = OS.tell();
1326     SectionOffsets[Sec] = std::make_pair(SecStart, SecEnd);
1327   }
1328
1329   uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1330   uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1331   WriteZeros(Padding);
1332
1333   const unsigned SectionHeaderOffset = OS.tell();
1334
1335   // ... then the section header table ...
1336   writeSectionHeader(Asm, Layout, SectionIndexMap, SectionOffsets);
1337
1338   uint16_t NumSections = (SectionTable.size() + 1 >= ELF::SHN_LORESERVE)
1339                              ? (uint16_t)ELF::SHN_UNDEF
1340                              : SectionTable.size() + 1;
1341   if (sys::IsLittleEndianHost != IsLittleEndian)
1342     sys::swapByteOrder(NumSections);
1343   unsigned NumSectionsOffset;
1344
1345   if (is64Bit()) {
1346     uint64_t Val = SectionHeaderOffset;
1347     if (sys::IsLittleEndianHost != IsLittleEndian)
1348       sys::swapByteOrder(Val);
1349     OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1350               offsetof(ELF::Elf64_Ehdr, e_shoff));
1351     NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
1352   } else {
1353     uint32_t Val = SectionHeaderOffset;
1354     if (sys::IsLittleEndianHost != IsLittleEndian)
1355       sys::swapByteOrder(Val);
1356     OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1357               offsetof(ELF::Elf32_Ehdr, e_shoff));
1358     NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
1359   }
1360   OS.pwrite(reinterpret_cast<char *>(&NumSections), sizeof(NumSections),
1361             NumSectionsOffset);
1362 }
1363
1364 bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1365     const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
1366     bool InSet, bool IsPCRel) const {
1367   if (IsPCRel) {
1368     assert(!InSet);
1369     if (::isWeak(SymA.getData()))
1370       return false;
1371   }
1372   return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
1373                                                                 InSet, IsPCRel);
1374 }
1375
1376 bool ELFObjectWriter::isWeak(const MCSymbol &Sym) const {
1377   const MCSymbolData &SD = Sym.getData();
1378   if (::isWeak(SD))
1379     return true;
1380
1381   // It is invalid to replace a reference to a global in a comdat
1382   // with a reference to a local since out of comdat references
1383   // to a local are forbidden.
1384   // We could try to return false for more cases, like the reference
1385   // being in the same comdat or Sym being an alias to another global,
1386   // but it is not clear if it is worth the effort.
1387   if (MCELF::GetBinding(SD) != ELF::STB_GLOBAL)
1388     return false;
1389
1390   if (!Sym.isInSection())
1391     return false;
1392
1393   const auto &Sec = cast<MCSectionELF>(Sym.getSection());
1394   return Sec.getGroup();
1395 }
1396
1397 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1398                                             raw_pwrite_stream &OS,
1399                                             bool IsLittleEndian) {
1400   return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
1401 }