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