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