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