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