1 //===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements ELF object file writer information.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/ArrayRef.h"
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/BinaryFormat/ELF.h"
21 #include "llvm/MC/MCAsmBackend.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/MC/MCAsmLayout.h"
24 #include "llvm/MC/MCAssembler.h"
25 #include "llvm/MC/MCContext.h"
26 #include "llvm/MC/MCELFObjectWriter.h"
27 #include "llvm/MC/MCExpr.h"
28 #include "llvm/MC/MCFixup.h"
29 #include "llvm/MC/MCFixupKindInfo.h"
30 #include "llvm/MC/MCFragment.h"
31 #include "llvm/MC/MCObjectFileInfo.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/Alignment.h"
40 #include "llvm/Support/Allocator.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/Compression.h"
43 #include "llvm/Support/EndianStream.h"
44 #include "llvm/Support/Error.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/Host.h"
47 #include "llvm/Support/LEB128.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/SMLoc.h"
50 #include "llvm/Support/StringSaver.h"
51 #include "llvm/Support/SwapByteOrder.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include <algorithm>
54 #include <cassert>
55 #include <cstddef>
56 #include <cstdint>
57 #include <map>
58 #include <memory>
59 #include <string>
60 #include <utility>
61 #include <vector>
62 
63 using namespace llvm;
64 
65 #undef  DEBUG_TYPE
66 #define DEBUG_TYPE "reloc-info"
67 
68 namespace {
69 
70 using SectionIndexMapTy = DenseMap<const MCSectionELF *, uint32_t>;
71 
72 class ELFObjectWriter;
73 struct ELFWriter;
74 
75 bool isDwoSection(const MCSectionELF &Sec) {
76   return Sec.getName().endswith(".dwo");
77 }
78 
79 class SymbolTableWriter {
80   ELFWriter &EWriter;
81   bool Is64Bit;
82 
83   // indexes we are going to write to .symtab_shndx.
84   std::vector<uint32_t> ShndxIndexes;
85 
86   // The numbel of symbols written so far.
87   unsigned NumWritten;
88 
89   void createSymtabShndx();
90 
91   template <typename T> void write(T Value);
92 
93 public:
94   SymbolTableWriter(ELFWriter &EWriter, bool Is64Bit);
95 
96   void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
97                    uint8_t other, uint32_t shndx, bool Reserved);
98 
99   ArrayRef<uint32_t> getShndxIndexes() const { return ShndxIndexes; }
100 };
101 
102 struct ELFWriter {
103   ELFObjectWriter &OWriter;
104   support::endian::Writer W;
105 
106   enum DwoMode {
107     AllSections,
108     NonDwoOnly,
109     DwoOnly,
110   } Mode;
111 
112   static uint64_t SymbolValue(const MCSymbol &Sym, const MCAsmLayout &Layout);
113   static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolELF &Symbol,
114                          bool Used, bool Renamed);
115 
116   /// Helper struct for containing some precomputed information on symbols.
117   struct ELFSymbolData {
118     const MCSymbolELF *Symbol;
119     StringRef Name;
120     uint32_t SectionIndex;
121     uint32_t Order;
122 
123     // Support lexicographic sorting.
124     bool operator<(const ELFSymbolData &RHS) const {
125       unsigned LHSType = Symbol->getType();
126       unsigned RHSType = RHS.Symbol->getType();
127       if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
128         return false;
129       if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
130         return true;
131       if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
132         return SectionIndex < RHS.SectionIndex;
133       return Name < RHS.Name;
134     }
135   };
136 
137   /// @}
138   /// @name Symbol Table Data
139   /// @{
140 
141   StringTableBuilder StrTabBuilder{StringTableBuilder::ELF};
142 
143   /// @}
144 
145   // This holds the symbol table index of the last local symbol.
146   unsigned LastLocalSymbolIndex;
147   // This holds the .strtab section index.
148   unsigned StringTableIndex;
149   // This holds the .symtab section index.
150   unsigned SymbolTableIndex;
151 
152   // Sections in the order they are to be output in the section table.
153   std::vector<const MCSectionELF *> SectionTable;
154   unsigned addToSectionTable(const MCSectionELF *Sec);
155 
156   // TargetObjectWriter wrappers.
157   bool is64Bit() const;
158   bool hasRelocationAddend() const;
159 
160   void align(unsigned Alignment);
161 
162   bool maybeWriteCompression(uint64_t Size,
163                              SmallVectorImpl<char> &CompressedContents,
164                              bool ZLibStyle, unsigned Alignment);
165 
166 public:
167   ELFWriter(ELFObjectWriter &OWriter, raw_pwrite_stream &OS,
168             bool IsLittleEndian, DwoMode Mode)
169       : OWriter(OWriter),
170         W(OS, IsLittleEndian ? support::little : support::big), Mode(Mode) {}
171 
172   void WriteWord(uint64_t Word) {
173     if (is64Bit())
174       W.write<uint64_t>(Word);
175     else
176       W.write<uint32_t>(Word);
177   }
178 
179   template <typename T> void write(T Val) {
180     W.write(Val);
181   }
182 
183   void writeHeader(const MCAssembler &Asm);
184 
185   void writeSymbol(SymbolTableWriter &Writer, uint32_t StringIndex,
186                    ELFSymbolData &MSD, const MCAsmLayout &Layout);
187 
188   // Start and end offset of each section
189   using SectionOffsetsTy =
190       std::map<const MCSectionELF *, std::pair<uint64_t, uint64_t>>;
191 
192   // Map from a signature symbol to the group section index
193   using RevGroupMapTy = DenseMap<const MCSymbol *, unsigned>;
194 
195   /// Compute the symbol table data
196   ///
197   /// \param Asm - The assembler.
198   /// \param SectionIndexMap - Maps a section to its index.
199   /// \param RevGroupMap - Maps a signature symbol to the group section.
200   void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
201                           const SectionIndexMapTy &SectionIndexMap,
202                           const RevGroupMapTy &RevGroupMap,
203                           SectionOffsetsTy &SectionOffsets);
204 
205   void writeAddrsigSection();
206 
207   MCSectionELF *createRelocationSection(MCContext &Ctx,
208                                         const MCSectionELF &Sec);
209 
210   const MCSectionELF *createStringTable(MCContext &Ctx);
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   uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout);
227   void writeSection(const SectionIndexMapTy &SectionIndexMap,
228                     uint32_t GroupSymbolIndex, uint64_t Offset, uint64_t Size,
229                     const MCSectionELF &Section);
230 };
231 
232 class ELFObjectWriter : public MCObjectWriter {
233   /// The target specific ELF writer instance.
234   std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
235 
236   DenseMap<const MCSectionELF *, std::vector<ELFRelocationEntry>> Relocations;
237 
238   DenseMap<const MCSymbolELF *, const MCSymbolELF *> Renames;
239 
240   bool EmitAddrsigSection = false;
241   std::vector<const MCSymbol *> AddrsigSyms;
242 
243   bool hasRelocationAddend() const;
244 
245   bool shouldRelocateWithSymbol(const MCAssembler &Asm,
246                                 const MCSymbolRefExpr *RefA,
247                                 const MCSymbolELF *Sym, uint64_t C,
248                                 unsigned Type) const;
249 
250 public:
251   ELFObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW)
252       : TargetObjectWriter(std::move(MOTW)) {}
253 
254   void reset() override {
255     Relocations.clear();
256     Renames.clear();
257     MCObjectWriter::reset();
258   }
259 
260   bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
261                                               const MCSymbol &SymA,
262                                               const MCFragment &FB, bool InSet,
263                                               bool IsPCRel) const override;
264 
265   virtual bool checkRelocation(MCContext &Ctx, SMLoc Loc,
266                                const MCSectionELF *From,
267                                const MCSectionELF *To) {
268     return true;
269   }
270 
271   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
272                         const MCFragment *Fragment, const MCFixup &Fixup,
273                         MCValue Target, uint64_t &FixedValue) override;
274 
275   void executePostLayoutBinding(MCAssembler &Asm,
276                                 const MCAsmLayout &Layout) override;
277 
278   void emitAddrsigSection() override { EmitAddrsigSection = true; }
279   void addAddrsigSymbol(const MCSymbol *Sym) override {
280     AddrsigSyms.push_back(Sym);
281   }
282 
283   friend struct ELFWriter;
284 };
285 
286 class ELFSingleObjectWriter : public ELFObjectWriter {
287   raw_pwrite_stream &OS;
288   bool IsLittleEndian;
289 
290 public:
291   ELFSingleObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
292                         raw_pwrite_stream &OS, bool IsLittleEndian)
293       : ELFObjectWriter(std::move(MOTW)), OS(OS),
294         IsLittleEndian(IsLittleEndian) {}
295 
296   uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override {
297     return ELFWriter(*this, OS, IsLittleEndian, ELFWriter::AllSections)
298         .writeObject(Asm, Layout);
299   }
300 
301   friend struct ELFWriter;
302 };
303 
304 class ELFDwoObjectWriter : public ELFObjectWriter {
305   raw_pwrite_stream &OS, &DwoOS;
306   bool IsLittleEndian;
307 
308 public:
309   ELFDwoObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
310                      raw_pwrite_stream &OS, raw_pwrite_stream &DwoOS,
311                      bool IsLittleEndian)
312       : ELFObjectWriter(std::move(MOTW)), OS(OS), DwoOS(DwoOS),
313         IsLittleEndian(IsLittleEndian) {}
314 
315   virtual bool checkRelocation(MCContext &Ctx, SMLoc Loc,
316                                const MCSectionELF *From,
317                                const MCSectionELF *To) override {
318     if (isDwoSection(*From)) {
319       Ctx.reportError(Loc, "A dwo section may not contain relocations");
320       return false;
321     }
322     if (To && isDwoSection(*To)) {
323       Ctx.reportError(Loc, "A relocation may not refer to a dwo section");
324       return false;
325     }
326     return true;
327   }
328 
329   uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override {
330     uint64_t Size = ELFWriter(*this, OS, IsLittleEndian, ELFWriter::NonDwoOnly)
331                         .writeObject(Asm, Layout);
332     Size += ELFWriter(*this, DwoOS, IsLittleEndian, ELFWriter::DwoOnly)
333                 .writeObject(Asm, Layout);
334     return Size;
335   }
336 };
337 
338 } // end anonymous namespace
339 
340 void ELFWriter::align(unsigned Alignment) {
341   uint64_t Padding = offsetToAlignment(W.OS.tell(), Align(Alignment));
342   W.OS.write_zeros(Padding);
343 }
344 
345 unsigned ELFWriter::addToSectionTable(const MCSectionELF *Sec) {
346   SectionTable.push_back(Sec);
347   StrTabBuilder.add(Sec->getName());
348   return SectionTable.size();
349 }
350 
351 void SymbolTableWriter::createSymtabShndx() {
352   if (!ShndxIndexes.empty())
353     return;
354 
355   ShndxIndexes.resize(NumWritten);
356 }
357 
358 template <typename T> void SymbolTableWriter::write(T Value) {
359   EWriter.write(Value);
360 }
361 
362 SymbolTableWriter::SymbolTableWriter(ELFWriter &EWriter, bool Is64Bit)
363     : EWriter(EWriter), Is64Bit(Is64Bit), NumWritten(0) {}
364 
365 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
366                                     uint64_t size, uint8_t other,
367                                     uint32_t shndx, bool Reserved) {
368   bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
369 
370   if (LargeIndex)
371     createSymtabShndx();
372 
373   if (!ShndxIndexes.empty()) {
374     if (LargeIndex)
375       ShndxIndexes.push_back(shndx);
376     else
377       ShndxIndexes.push_back(0);
378   }
379 
380   uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
381 
382   if (Is64Bit) {
383     write(name);  // st_name
384     write(info);  // st_info
385     write(other); // st_other
386     write(Index); // st_shndx
387     write(value); // st_value
388     write(size);  // st_size
389   } else {
390     write(name);            // st_name
391     write(uint32_t(value)); // st_value
392     write(uint32_t(size));  // st_size
393     write(info);            // st_info
394     write(other);           // st_other
395     write(Index);           // st_shndx
396   }
397 
398   ++NumWritten;
399 }
400 
401 bool ELFWriter::is64Bit() const {
402   return OWriter.TargetObjectWriter->is64Bit();
403 }
404 
405 bool ELFWriter::hasRelocationAddend() const {
406   return OWriter.hasRelocationAddend();
407 }
408 
409 // Emit the ELF header.
410 void ELFWriter::writeHeader(const MCAssembler &Asm) {
411   // ELF Header
412   // ----------
413   //
414   // Note
415   // ----
416   // emitWord method behaves differently for ELF32 and ELF64, writing
417   // 4 bytes in the former and 8 in the latter.
418 
419   W.OS << ELF::ElfMagic; // e_ident[EI_MAG0] to e_ident[EI_MAG3]
420 
421   W.OS << char(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
422 
423   // e_ident[EI_DATA]
424   W.OS << char(W.Endian == support::little ? ELF::ELFDATA2LSB
425                                            : ELF::ELFDATA2MSB);
426 
427   W.OS << char(ELF::EV_CURRENT);        // e_ident[EI_VERSION]
428   // e_ident[EI_OSABI]
429   W.OS << char(OWriter.TargetObjectWriter->getOSABI());
430   // e_ident[EI_ABIVERSION]
431   W.OS << char(OWriter.TargetObjectWriter->getABIVersion());
432 
433   W.OS.write_zeros(ELF::EI_NIDENT - ELF::EI_PAD);
434 
435   W.write<uint16_t>(ELF::ET_REL);             // e_type
436 
437   W.write<uint16_t>(OWriter.TargetObjectWriter->getEMachine()); // e_machine = target
438 
439   W.write<uint32_t>(ELF::EV_CURRENT);         // e_version
440   WriteWord(0);                    // e_entry, no entry point in .o file
441   WriteWord(0);                    // e_phoff, no program header for .o
442   WriteWord(0);                     // e_shoff = sec hdr table off in bytes
443 
444   // e_flags = whatever the target wants
445   W.write<uint32_t>(Asm.getELFHeaderEFlags());
446 
447   // e_ehsize = ELF header size
448   W.write<uint16_t>(is64Bit() ? sizeof(ELF::Elf64_Ehdr)
449                               : sizeof(ELF::Elf32_Ehdr));
450 
451   W.write<uint16_t>(0);                  // e_phentsize = prog header entry size
452   W.write<uint16_t>(0);                  // e_phnum = # prog header entries = 0
453 
454   // e_shentsize = Section header entry size
455   W.write<uint16_t>(is64Bit() ? sizeof(ELF::Elf64_Shdr)
456                               : sizeof(ELF::Elf32_Shdr));
457 
458   // e_shnum     = # of section header ents
459   W.write<uint16_t>(0);
460 
461   // e_shstrndx  = Section # of '.shstrtab'
462   assert(StringTableIndex < ELF::SHN_LORESERVE);
463   W.write<uint16_t>(StringTableIndex);
464 }
465 
466 uint64_t ELFWriter::SymbolValue(const MCSymbol &Sym,
467                                 const MCAsmLayout &Layout) {
468   if (Sym.isCommon())
469     return Sym.getCommonAlignment();
470 
471   uint64_t Res;
472   if (!Layout.getSymbolOffset(Sym, Res))
473     return 0;
474 
475   if (Layout.getAssembler().isThumbFunc(&Sym))
476     Res |= 1;
477 
478   return Res;
479 }
480 
481 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
482   uint8_t Type = newType;
483 
484   // Propagation rules:
485   // IFUNC > FUNC > OBJECT > NOTYPE
486   // TLS_OBJECT > OBJECT > NOTYPE
487   //
488   // dont let the new type degrade the old type
489   switch (origType) {
490   default:
491     break;
492   case ELF::STT_GNU_IFUNC:
493     if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
494         Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
495       Type = ELF::STT_GNU_IFUNC;
496     break;
497   case ELF::STT_FUNC:
498     if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
499         Type == ELF::STT_TLS)
500       Type = ELF::STT_FUNC;
501     break;
502   case ELF::STT_OBJECT:
503     if (Type == ELF::STT_NOTYPE)
504       Type = ELF::STT_OBJECT;
505     break;
506   case ELF::STT_TLS:
507     if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
508         Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
509       Type = ELF::STT_TLS;
510     break;
511   }
512 
513   return Type;
514 }
515 
516 static bool isIFunc(const MCSymbolELF *Symbol) {
517   while (Symbol->getType() != ELF::STT_GNU_IFUNC) {
518     const MCSymbolRefExpr *Value;
519     if (!Symbol->isVariable() ||
520         !(Value = dyn_cast<MCSymbolRefExpr>(Symbol->getVariableValue())) ||
521         Value->getKind() != MCSymbolRefExpr::VK_None ||
522         mergeTypeForSet(Symbol->getType(), ELF::STT_GNU_IFUNC) != ELF::STT_GNU_IFUNC)
523       return false;
524     Symbol = &cast<MCSymbolELF>(Value->getSymbol());
525   }
526   return true;
527 }
528 
529 void ELFWriter::writeSymbol(SymbolTableWriter &Writer, uint32_t StringIndex,
530                             ELFSymbolData &MSD, const MCAsmLayout &Layout) {
531   const auto &Symbol = cast<MCSymbolELF>(*MSD.Symbol);
532   const MCSymbolELF *Base =
533       cast_or_null<MCSymbolELF>(Layout.getBaseSymbol(Symbol));
534 
535   // This has to be in sync with when computeSymbolTable uses SHN_ABS or
536   // SHN_COMMON.
537   bool IsReserved = !Base || Symbol.isCommon();
538 
539   // Binding and Type share the same byte as upper and lower nibbles
540   uint8_t Binding = Symbol.getBinding();
541   uint8_t Type = Symbol.getType();
542   if (isIFunc(&Symbol))
543     Type = ELF::STT_GNU_IFUNC;
544   if (Base) {
545     Type = mergeTypeForSet(Type, Base->getType());
546   }
547   uint8_t Info = (Binding << 4) | Type;
548 
549   // Other and Visibility share the same byte with Visibility using the lower
550   // 2 bits
551   uint8_t Visibility = Symbol.getVisibility();
552   uint8_t Other = Symbol.getOther() | Visibility;
553 
554   uint64_t Value = SymbolValue(*MSD.Symbol, Layout);
555   uint64_t Size = 0;
556 
557   const MCExpr *ESize = MSD.Symbol->getSize();
558   if (!ESize && Base)
559     ESize = Base->getSize();
560 
561   if (ESize) {
562     int64_t Res;
563     if (!ESize->evaluateKnownAbsolute(Res, Layout))
564       report_fatal_error("Size expression must be absolute.");
565     Size = Res;
566   }
567 
568   // Write out the symbol table entry
569   Writer.writeSymbol(StringIndex, Info, Value, Size, Other, MSD.SectionIndex,
570                      IsReserved);
571 }
572 
573 bool ELFWriter::isInSymtab(const MCAsmLayout &Layout, const MCSymbolELF &Symbol,
574                            bool Used, bool Renamed) {
575   if (Symbol.isVariable()) {
576     const MCExpr *Expr = Symbol.getVariableValue();
577     // Target Expressions that are always inlined do not appear in the symtab
578     if (const auto *T = dyn_cast<MCTargetExpr>(Expr))
579       if (T->inlineAssignedExpr())
580         return false;
581     if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
582       if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
583         return false;
584     }
585   }
586 
587   if (Used)
588     return true;
589 
590   if (Renamed)
591     return false;
592 
593   if (Symbol.isVariable() && Symbol.isUndefined()) {
594     // FIXME: this is here just to diagnose the case of a var = commmon_sym.
595     Layout.getBaseSymbol(Symbol);
596     return false;
597   }
598 
599   if (Symbol.isTemporary())
600     return false;
601 
602   if (Symbol.getType() == ELF::STT_SECTION)
603     return false;
604 
605   return true;
606 }
607 
608 void ELFWriter::computeSymbolTable(
609     MCAssembler &Asm, const MCAsmLayout &Layout,
610     const SectionIndexMapTy &SectionIndexMap, const RevGroupMapTy &RevGroupMap,
611     SectionOffsetsTy &SectionOffsets) {
612   MCContext &Ctx = Asm.getContext();
613   SymbolTableWriter Writer(*this, is64Bit());
614 
615   // Symbol table
616   unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
617   MCSectionELF *SymtabSection =
618       Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize, "");
619   SymtabSection->setAlignment(is64Bit() ? Align(8) : Align(4));
620   SymbolTableIndex = addToSectionTable(SymtabSection);
621 
622   align(SymtabSection->getAlignment());
623   uint64_t SecStart = W.OS.tell();
624 
625   // The first entry is the undefined symbol entry.
626   Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
627 
628   std::vector<ELFSymbolData> LocalSymbolData;
629   std::vector<ELFSymbolData> ExternalSymbolData;
630   MutableArrayRef<std::pair<std::string, size_t>> FileNames =
631       Asm.getFileNames();
632   for (const std::pair<std::string, size_t> &F : FileNames)
633     StrTabBuilder.add(F.first);
634 
635   // Add the data for the symbols.
636   bool HasLargeSectionIndex = false;
637   for (auto It : llvm::enumerate(Asm.symbols())) {
638     const auto &Symbol = cast<MCSymbolELF>(It.value());
639     bool Used = Symbol.isUsedInReloc();
640     bool WeakrefUsed = Symbol.isWeakrefUsedInReloc();
641     bool isSignature = Symbol.isSignature();
642 
643     if (!isInSymtab(Layout, Symbol, Used || WeakrefUsed || isSignature,
644                     OWriter.Renames.count(&Symbol)))
645       continue;
646 
647     if (Symbol.isTemporary() && Symbol.isUndefined()) {
648       Ctx.reportError(SMLoc(), "Undefined temporary symbol " + Symbol.getName());
649       continue;
650     }
651 
652     ELFSymbolData MSD;
653     MSD.Symbol = cast<MCSymbolELF>(&Symbol);
654     MSD.Order = It.index();
655 
656     bool Local = Symbol.getBinding() == ELF::STB_LOCAL;
657     assert(Local || !Symbol.isTemporary());
658 
659     if (Symbol.isAbsolute()) {
660       MSD.SectionIndex = ELF::SHN_ABS;
661     } else if (Symbol.isCommon()) {
662       if (Symbol.isTargetCommon()) {
663         MSD.SectionIndex = Symbol.getIndex();
664       } else {
665         assert(!Local);
666         MSD.SectionIndex = ELF::SHN_COMMON;
667       }
668     } else if (Symbol.isUndefined()) {
669       if (isSignature && !Used) {
670         MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
671         if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
672           HasLargeSectionIndex = true;
673       } else {
674         MSD.SectionIndex = ELF::SHN_UNDEF;
675       }
676     } else {
677       const MCSectionELF &Section =
678           static_cast<const MCSectionELF &>(Symbol.getSection());
679 
680       // We may end up with a situation when section symbol is technically
681       // defined, but should not be. That happens because we explicitly
682       // pre-create few .debug_* sections to have accessors.
683       // And if these sections were not really defined in the code, but were
684       // referenced, we simply error out.
685       if (!Section.isRegistered()) {
686         assert(static_cast<const MCSymbolELF &>(Symbol).getType() ==
687                ELF::STT_SECTION);
688         Ctx.reportError(SMLoc(),
689                         "Undefined section reference: " + Symbol.getName());
690         continue;
691       }
692 
693       if (Mode == NonDwoOnly && isDwoSection(Section))
694         continue;
695       MSD.SectionIndex = SectionIndexMap.lookup(&Section);
696       assert(MSD.SectionIndex && "Invalid section index!");
697       if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
698         HasLargeSectionIndex = true;
699     }
700 
701     StringRef Name = Symbol.getName();
702 
703     // Sections have their own string table
704     if (Symbol.getType() != ELF::STT_SECTION) {
705       MSD.Name = Name;
706       StrTabBuilder.add(Name);
707     }
708 
709     if (Local)
710       LocalSymbolData.push_back(MSD);
711     else
712       ExternalSymbolData.push_back(MSD);
713   }
714 
715   // This holds the .symtab_shndx section index.
716   unsigned SymtabShndxSectionIndex = 0;
717 
718   if (HasLargeSectionIndex) {
719     MCSectionELF *SymtabShndxSection =
720         Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
721     SymtabShndxSectionIndex = addToSectionTable(SymtabShndxSection);
722     SymtabShndxSection->setAlignment(Align(4));
723   }
724 
725   StrTabBuilder.finalize();
726 
727   // Symbols are required to be in lexicographic order.
728   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
729 
730   // Make the first STT_FILE precede previous local symbols.
731   unsigned Index = 1;
732   auto FileNameIt = FileNames.begin();
733   if (!FileNames.empty())
734     FileNames[0].second = 0;
735 
736   for (ELFSymbolData &MSD : LocalSymbolData) {
737     // Emit STT_FILE symbols before their associated local symbols.
738     for (; FileNameIt != FileNames.end() && FileNameIt->second <= MSD.Order;
739          ++FileNameIt) {
740       Writer.writeSymbol(StrTabBuilder.getOffset(FileNameIt->first),
741                          ELF::STT_FILE | ELF::STB_LOCAL, 0, 0, ELF::STV_DEFAULT,
742                          ELF::SHN_ABS, true);
743       ++Index;
744     }
745 
746     unsigned StringIndex = MSD.Symbol->getType() == ELF::STT_SECTION
747                                ? 0
748                                : StrTabBuilder.getOffset(MSD.Name);
749     MSD.Symbol->setIndex(Index++);
750     writeSymbol(Writer, StringIndex, MSD, Layout);
751   }
752   for (; FileNameIt != FileNames.end(); ++FileNameIt) {
753     Writer.writeSymbol(StrTabBuilder.getOffset(FileNameIt->first),
754                        ELF::STT_FILE | ELF::STB_LOCAL, 0, 0, ELF::STV_DEFAULT,
755                        ELF::SHN_ABS, true);
756     ++Index;
757   }
758 
759   // Write the symbol table entries.
760   LastLocalSymbolIndex = Index;
761 
762   for (ELFSymbolData &MSD : ExternalSymbolData) {
763     unsigned StringIndex = StrTabBuilder.getOffset(MSD.Name);
764     MSD.Symbol->setIndex(Index++);
765     writeSymbol(Writer, StringIndex, MSD, Layout);
766     assert(MSD.Symbol->getBinding() != ELF::STB_LOCAL);
767   }
768 
769   uint64_t SecEnd = W.OS.tell();
770   SectionOffsets[SymtabSection] = std::make_pair(SecStart, SecEnd);
771 
772   ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes();
773   if (ShndxIndexes.empty()) {
774     assert(SymtabShndxSectionIndex == 0);
775     return;
776   }
777   assert(SymtabShndxSectionIndex != 0);
778 
779   SecStart = W.OS.tell();
780   const MCSectionELF *SymtabShndxSection =
781       SectionTable[SymtabShndxSectionIndex - 1];
782   for (uint32_t Index : ShndxIndexes)
783     write(Index);
784   SecEnd = W.OS.tell();
785   SectionOffsets[SymtabShndxSection] = std::make_pair(SecStart, SecEnd);
786 }
787 
788 void ELFWriter::writeAddrsigSection() {
789   for (const MCSymbol *Sym : OWriter.AddrsigSyms)
790     encodeULEB128(Sym->getIndex(), W.OS);
791 }
792 
793 MCSectionELF *ELFWriter::createRelocationSection(MCContext &Ctx,
794                                                  const MCSectionELF &Sec) {
795   if (OWriter.Relocations[&Sec].empty())
796     return nullptr;
797 
798   const StringRef SectionName = Sec.getName();
799   std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
800   RelaSectionName += SectionName;
801 
802   unsigned EntrySize;
803   if (hasRelocationAddend())
804     EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
805   else
806     EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
807 
808   unsigned Flags = 0;
809   if (Sec.getFlags() & ELF::SHF_GROUP)
810     Flags = ELF::SHF_GROUP;
811 
812   MCSectionELF *RelaSection = Ctx.createELFRelSection(
813       RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
814       Flags, EntrySize, Sec.getGroup(), &Sec);
815   RelaSection->setAlignment(is64Bit() ? Align(8) : Align(4));
816   return RelaSection;
817 }
818 
819 // Include the debug info compression header.
820 bool ELFWriter::maybeWriteCompression(
821     uint64_t Size, SmallVectorImpl<char> &CompressedContents, bool ZLibStyle,
822     unsigned Alignment) {
823   if (ZLibStyle) {
824     uint64_t HdrSize =
825         is64Bit() ? sizeof(ELF::Elf32_Chdr) : sizeof(ELF::Elf64_Chdr);
826     if (Size <= HdrSize + CompressedContents.size())
827       return false;
828     // Platform specific header is followed by compressed data.
829     if (is64Bit()) {
830       // Write Elf64_Chdr header.
831       write(static_cast<ELF::Elf64_Word>(ELF::ELFCOMPRESS_ZLIB));
832       write(static_cast<ELF::Elf64_Word>(0)); // ch_reserved field.
833       write(static_cast<ELF::Elf64_Xword>(Size));
834       write(static_cast<ELF::Elf64_Xword>(Alignment));
835     } else {
836       // Write Elf32_Chdr header otherwise.
837       write(static_cast<ELF::Elf32_Word>(ELF::ELFCOMPRESS_ZLIB));
838       write(static_cast<ELF::Elf32_Word>(Size));
839       write(static_cast<ELF::Elf32_Word>(Alignment));
840     }
841     return true;
842   }
843 
844   // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
845   // useful for consumers to preallocate a buffer to decompress into.
846   const StringRef Magic = "ZLIB";
847   if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
848     return false;
849   W.OS << Magic;
850   support::endian::write(W.OS, Size, support::big);
851   return true;
852 }
853 
854 void ELFWriter::writeSectionData(const MCAssembler &Asm, MCSection &Sec,
855                                  const MCAsmLayout &Layout) {
856   MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
857   StringRef SectionName = Section.getName();
858 
859   auto &MC = Asm.getContext();
860   const auto &MAI = MC.getAsmInfo();
861 
862   // Compressing debug_frame requires handling alignment fragments which is
863   // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
864   // for writing to arbitrary buffers) for little benefit.
865   bool CompressionEnabled =
866       MAI->compressDebugSections() != DebugCompressionType::None;
867   if (!CompressionEnabled || !SectionName.startswith(".debug_") ||
868       SectionName == ".debug_frame") {
869     Asm.writeSectionData(W.OS, &Section, Layout);
870     return;
871   }
872 
873   assert((MAI->compressDebugSections() == DebugCompressionType::Z ||
874           MAI->compressDebugSections() == DebugCompressionType::GNU) &&
875          "expected zlib or zlib-gnu style compression");
876 
877   SmallVector<char, 128> UncompressedData;
878   raw_svector_ostream VecOS(UncompressedData);
879   Asm.writeSectionData(VecOS, &Section, Layout);
880 
881   SmallVector<char, 128> CompressedContents;
882   if (Error E = zlib::compress(
883           StringRef(UncompressedData.data(), UncompressedData.size()),
884           CompressedContents)) {
885     consumeError(std::move(E));
886     W.OS << UncompressedData;
887     return;
888   }
889 
890   bool ZlibStyle = MAI->compressDebugSections() == DebugCompressionType::Z;
891   if (!maybeWriteCompression(UncompressedData.size(), CompressedContents,
892                              ZlibStyle, Sec.getAlignment())) {
893     W.OS << UncompressedData;
894     return;
895   }
896 
897   if (ZlibStyle) {
898     // Set the compressed flag. That is zlib style.
899     Section.setFlags(Section.getFlags() | ELF::SHF_COMPRESSED);
900     // Alignment field should reflect the requirements of
901     // the compressed section header.
902     Section.setAlignment(is64Bit() ? Align(8) : Align(4));
903   } else {
904     // Add "z" prefix to section name. This is zlib-gnu style.
905     MC.renameELFSection(&Section, (".z" + SectionName.drop_front(1)).str());
906   }
907   W.OS << CompressedContents;
908 }
909 
910 void ELFWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
911                                  uint64_t Address, uint64_t Offset,
912                                  uint64_t Size, uint32_t Link, uint32_t Info,
913                                  uint64_t Alignment, uint64_t EntrySize) {
914   W.write<uint32_t>(Name);        // sh_name: index into string table
915   W.write<uint32_t>(Type);        // sh_type
916   WriteWord(Flags);     // sh_flags
917   WriteWord(Address);   // sh_addr
918   WriteWord(Offset);    // sh_offset
919   WriteWord(Size);      // sh_size
920   W.write<uint32_t>(Link);        // sh_link
921   W.write<uint32_t>(Info);        // sh_info
922   WriteWord(Alignment); // sh_addralign
923   WriteWord(EntrySize); // sh_entsize
924 }
925 
926 void ELFWriter::writeRelocations(const MCAssembler &Asm,
927                                        const MCSectionELF &Sec) {
928   std::vector<ELFRelocationEntry> &Relocs = OWriter.Relocations[&Sec];
929 
930   // We record relocations by pushing to the end of a vector. Reverse the vector
931   // to get the relocations in the order they were created.
932   // In most cases that is not important, but it can be for special sections
933   // (.eh_frame) or specific relocations (TLS optimizations on SystemZ).
934   std::reverse(Relocs.begin(), Relocs.end());
935 
936   // Sort the relocation entries. MIPS needs this.
937   OWriter.TargetObjectWriter->sortRelocs(Asm, Relocs);
938 
939   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
940     const ELFRelocationEntry &Entry = Relocs[e - i - 1];
941     unsigned Index = Entry.Symbol ? Entry.Symbol->getIndex() : 0;
942 
943     if (is64Bit()) {
944       write(Entry.Offset);
945       if (OWriter.TargetObjectWriter->getEMachine() == ELF::EM_MIPS) {
946         write(uint32_t(Index));
947 
948         write(OWriter.TargetObjectWriter->getRSsym(Entry.Type));
949         write(OWriter.TargetObjectWriter->getRType3(Entry.Type));
950         write(OWriter.TargetObjectWriter->getRType2(Entry.Type));
951         write(OWriter.TargetObjectWriter->getRType(Entry.Type));
952       } else {
953         struct ELF::Elf64_Rela ERE64;
954         ERE64.setSymbolAndType(Index, Entry.Type);
955         write(ERE64.r_info);
956       }
957       if (hasRelocationAddend())
958         write(Entry.Addend);
959     } else {
960       write(uint32_t(Entry.Offset));
961 
962       struct ELF::Elf32_Rela ERE32;
963       ERE32.setSymbolAndType(Index, Entry.Type);
964       write(ERE32.r_info);
965 
966       if (hasRelocationAddend())
967         write(uint32_t(Entry.Addend));
968 
969       if (OWriter.TargetObjectWriter->getEMachine() == ELF::EM_MIPS) {
970         if (uint32_t RType =
971                 OWriter.TargetObjectWriter->getRType2(Entry.Type)) {
972           write(uint32_t(Entry.Offset));
973 
974           ERE32.setSymbolAndType(0, RType);
975           write(ERE32.r_info);
976           write(uint32_t(0));
977         }
978         if (uint32_t RType =
979                 OWriter.TargetObjectWriter->getRType3(Entry.Type)) {
980           write(uint32_t(Entry.Offset));
981 
982           ERE32.setSymbolAndType(0, RType);
983           write(ERE32.r_info);
984           write(uint32_t(0));
985         }
986       }
987     }
988   }
989 }
990 
991 const MCSectionELF *ELFWriter::createStringTable(MCContext &Ctx) {
992   const MCSectionELF *StrtabSection = SectionTable[StringTableIndex - 1];
993   StrTabBuilder.write(W.OS);
994   return StrtabSection;
995 }
996 
997 void ELFWriter::writeSection(const SectionIndexMapTy &SectionIndexMap,
998                              uint32_t GroupSymbolIndex, uint64_t Offset,
999                              uint64_t Size, const MCSectionELF &Section) {
1000   uint64_t sh_link = 0;
1001   uint64_t sh_info = 0;
1002 
1003   switch(Section.getType()) {
1004   default:
1005     // Nothing to do.
1006     break;
1007 
1008   case ELF::SHT_DYNAMIC:
1009     llvm_unreachable("SHT_DYNAMIC in a relocatable object");
1010 
1011   case ELF::SHT_REL:
1012   case ELF::SHT_RELA: {
1013     sh_link = SymbolTableIndex;
1014     assert(sh_link && ".symtab not found");
1015     const MCSection *InfoSection = Section.getLinkedToSection();
1016     sh_info = SectionIndexMap.lookup(cast<MCSectionELF>(InfoSection));
1017     break;
1018   }
1019 
1020   case ELF::SHT_SYMTAB:
1021     sh_link = StringTableIndex;
1022     sh_info = LastLocalSymbolIndex;
1023     break;
1024 
1025   case ELF::SHT_SYMTAB_SHNDX:
1026   case ELF::SHT_LLVM_CALL_GRAPH_PROFILE:
1027   case ELF::SHT_LLVM_ADDRSIG:
1028     sh_link = SymbolTableIndex;
1029     break;
1030 
1031   case ELF::SHT_GROUP:
1032     sh_link = SymbolTableIndex;
1033     sh_info = GroupSymbolIndex;
1034     break;
1035   }
1036 
1037   if (Section.getFlags() & ELF::SHF_LINK_ORDER) {
1038     // If the value in the associated metadata is not a definition, Sym will be
1039     // undefined. Represent this with sh_link=0.
1040     const MCSymbol *Sym = Section.getLinkedToSymbol();
1041     if (Sym && Sym->isInSection()) {
1042       const MCSectionELF *Sec = cast<MCSectionELF>(&Sym->getSection());
1043       sh_link = SectionIndexMap.lookup(Sec);
1044     }
1045   }
1046 
1047   WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getName()),
1048                    Section.getType(), Section.getFlags(), 0, Offset, Size,
1049                    sh_link, sh_info, Section.getAlignment(),
1050                    Section.getEntrySize());
1051 }
1052 
1053 void ELFWriter::writeSectionHeader(
1054     const MCAsmLayout &Layout, const SectionIndexMapTy &SectionIndexMap,
1055     const SectionOffsetsTy &SectionOffsets) {
1056   const unsigned NumSections = SectionTable.size();
1057 
1058   // Null section first.
1059   uint64_t FirstSectionSize =
1060       (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
1061   WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
1062 
1063   for (const MCSectionELF *Section : SectionTable) {
1064     uint32_t GroupSymbolIndex;
1065     unsigned Type = Section->getType();
1066     if (Type != ELF::SHT_GROUP)
1067       GroupSymbolIndex = 0;
1068     else
1069       GroupSymbolIndex = Section->getGroup()->getIndex();
1070 
1071     const std::pair<uint64_t, uint64_t> &Offsets =
1072         SectionOffsets.find(Section)->second;
1073     uint64_t Size;
1074     if (Type == ELF::SHT_NOBITS)
1075       Size = Layout.getSectionAddressSize(Section);
1076     else
1077       Size = Offsets.second - Offsets.first;
1078 
1079     writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1080                  *Section);
1081   }
1082 }
1083 
1084 uint64_t ELFWriter::writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) {
1085   uint64_t StartOffset = W.OS.tell();
1086 
1087   MCContext &Ctx = Asm.getContext();
1088   MCSectionELF *StrtabSection =
1089       Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1090   StringTableIndex = addToSectionTable(StrtabSection);
1091 
1092   RevGroupMapTy RevGroupMap;
1093   SectionIndexMapTy SectionIndexMap;
1094 
1095   std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers;
1096 
1097   // Write out the ELF header ...
1098   writeHeader(Asm);
1099 
1100   // ... then the sections ...
1101   SectionOffsetsTy SectionOffsets;
1102   std::vector<MCSectionELF *> Groups;
1103   std::vector<MCSectionELF *> Relocations;
1104   for (MCSection &Sec : Asm) {
1105     MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
1106     if (Mode == NonDwoOnly && isDwoSection(Section))
1107       continue;
1108     if (Mode == DwoOnly && !isDwoSection(Section))
1109       continue;
1110 
1111     align(Section.getAlignment());
1112 
1113     // Remember the offset into the file for this section.
1114     uint64_t SecStart = W.OS.tell();
1115 
1116     const MCSymbolELF *SignatureSymbol = Section.getGroup();
1117     writeSectionData(Asm, Section, Layout);
1118 
1119     uint64_t SecEnd = W.OS.tell();
1120     SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd);
1121 
1122     MCSectionELF *RelSection = createRelocationSection(Ctx, Section);
1123 
1124     if (SignatureSymbol) {
1125       Asm.registerSymbol(*SignatureSymbol);
1126       unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1127       if (!GroupIdx) {
1128         MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
1129         GroupIdx = addToSectionTable(Group);
1130         Group->setAlignment(Align(4));
1131         Groups.push_back(Group);
1132       }
1133       std::vector<const MCSectionELF *> &Members =
1134           GroupMembers[SignatureSymbol];
1135       Members.push_back(&Section);
1136       if (RelSection)
1137         Members.push_back(RelSection);
1138     }
1139 
1140     SectionIndexMap[&Section] = addToSectionTable(&Section);
1141     if (RelSection) {
1142       SectionIndexMap[RelSection] = addToSectionTable(RelSection);
1143       Relocations.push_back(RelSection);
1144     }
1145 
1146     OWriter.TargetObjectWriter->addTargetSectionFlags(Ctx, Section);
1147   }
1148 
1149   MCSectionELF *CGProfileSection = nullptr;
1150   if (!Asm.CGProfile.empty()) {
1151     CGProfileSection = Ctx.getELFSection(".llvm.call-graph-profile",
1152                                          ELF::SHT_LLVM_CALL_GRAPH_PROFILE,
1153                                          ELF::SHF_EXCLUDE, 16, "");
1154     SectionIndexMap[CGProfileSection] = addToSectionTable(CGProfileSection);
1155   }
1156 
1157   for (MCSectionELF *Group : Groups) {
1158     align(Group->getAlignment());
1159 
1160     // Remember the offset into the file for this section.
1161     uint64_t SecStart = W.OS.tell();
1162 
1163     const MCSymbol *SignatureSymbol = Group->getGroup();
1164     assert(SignatureSymbol);
1165     write(uint32_t(ELF::GRP_COMDAT));
1166     for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) {
1167       uint32_t SecIndex = SectionIndexMap.lookup(Member);
1168       write(SecIndex);
1169     }
1170 
1171     uint64_t SecEnd = W.OS.tell();
1172     SectionOffsets[Group] = std::make_pair(SecStart, SecEnd);
1173   }
1174 
1175   if (Mode == DwoOnly) {
1176     // dwo files don't have symbol tables or relocations, but they do have
1177     // string tables.
1178     StrTabBuilder.finalize();
1179   } else {
1180     MCSectionELF *AddrsigSection;
1181     if (OWriter.EmitAddrsigSection) {
1182       AddrsigSection = Ctx.getELFSection(".llvm_addrsig", ELF::SHT_LLVM_ADDRSIG,
1183                                          ELF::SHF_EXCLUDE);
1184       addToSectionTable(AddrsigSection);
1185     }
1186 
1187     // Compute symbol table information.
1188     computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1189                        SectionOffsets);
1190 
1191     for (MCSectionELF *RelSection : Relocations) {
1192       align(RelSection->getAlignment());
1193 
1194       // Remember the offset into the file for this section.
1195       uint64_t SecStart = W.OS.tell();
1196 
1197       writeRelocations(Asm,
1198                        cast<MCSectionELF>(*RelSection->getLinkedToSection()));
1199 
1200       uint64_t SecEnd = W.OS.tell();
1201       SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd);
1202     }
1203 
1204     if (OWriter.EmitAddrsigSection) {
1205       uint64_t SecStart = W.OS.tell();
1206       writeAddrsigSection();
1207       uint64_t SecEnd = W.OS.tell();
1208       SectionOffsets[AddrsigSection] = std::make_pair(SecStart, SecEnd);
1209     }
1210   }
1211 
1212   if (CGProfileSection) {
1213     uint64_t SecStart = W.OS.tell();
1214     for (const MCAssembler::CGProfileEntry &CGPE : Asm.CGProfile) {
1215       W.write<uint32_t>(CGPE.From->getSymbol().getIndex());
1216       W.write<uint32_t>(CGPE.To->getSymbol().getIndex());
1217       W.write<uint64_t>(CGPE.Count);
1218     }
1219     uint64_t SecEnd = W.OS.tell();
1220     SectionOffsets[CGProfileSection] = std::make_pair(SecStart, SecEnd);
1221   }
1222 
1223   {
1224     uint64_t SecStart = W.OS.tell();
1225     const MCSectionELF *Sec = createStringTable(Ctx);
1226     uint64_t SecEnd = W.OS.tell();
1227     SectionOffsets[Sec] = std::make_pair(SecStart, SecEnd);
1228   }
1229 
1230   uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1231   align(NaturalAlignment);
1232 
1233   const uint64_t SectionHeaderOffset = W.OS.tell();
1234 
1235   // ... then the section header table ...
1236   writeSectionHeader(Layout, SectionIndexMap, SectionOffsets);
1237 
1238   uint16_t NumSections = support::endian::byte_swap<uint16_t>(
1239       (SectionTable.size() + 1 >= ELF::SHN_LORESERVE) ? (uint16_t)ELF::SHN_UNDEF
1240                                                       : SectionTable.size() + 1,
1241       W.Endian);
1242   unsigned NumSectionsOffset;
1243 
1244   auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
1245   if (is64Bit()) {
1246     uint64_t Val =
1247         support::endian::byte_swap<uint64_t>(SectionHeaderOffset, W.Endian);
1248     Stream.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1249                   offsetof(ELF::Elf64_Ehdr, e_shoff));
1250     NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
1251   } else {
1252     uint32_t Val =
1253         support::endian::byte_swap<uint32_t>(SectionHeaderOffset, W.Endian);
1254     Stream.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1255                   offsetof(ELF::Elf32_Ehdr, e_shoff));
1256     NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
1257   }
1258   Stream.pwrite(reinterpret_cast<char *>(&NumSections), sizeof(NumSections),
1259                 NumSectionsOffset);
1260 
1261   return W.OS.tell() - StartOffset;
1262 }
1263 
1264 bool ELFObjectWriter::hasRelocationAddend() const {
1265   return TargetObjectWriter->hasRelocationAddend();
1266 }
1267 
1268 void ELFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
1269                                                const MCAsmLayout &Layout) {
1270   // The presence of symbol versions causes undefined symbols and
1271   // versions declared with @@@ to be renamed.
1272   for (const MCAssembler::Symver &S : Asm.Symvers) {
1273     StringRef AliasName = S.Name;
1274     const auto &Symbol = cast<MCSymbolELF>(*S.Sym);
1275     size_t Pos = AliasName.find('@');
1276     assert(Pos != StringRef::npos);
1277 
1278     StringRef Prefix = AliasName.substr(0, Pos);
1279     StringRef Rest = AliasName.substr(Pos);
1280     StringRef Tail = Rest;
1281     if (Rest.startswith("@@@"))
1282       Tail = Rest.substr(Symbol.isUndefined() ? 2 : 1);
1283 
1284     auto *Alias =
1285         cast<MCSymbolELF>(Asm.getContext().getOrCreateSymbol(Prefix + Tail));
1286     Asm.registerSymbol(*Alias);
1287     const MCExpr *Value = MCSymbolRefExpr::create(&Symbol, Asm.getContext());
1288     Alias->setVariableValue(Value);
1289 
1290     // Aliases defined with .symvar copy the binding from the symbol they alias.
1291     // This is the first place we are able to copy this information.
1292     Alias->setBinding(Symbol.getBinding());
1293     Alias->setVisibility(Symbol.getVisibility());
1294     Alias->setOther(Symbol.getOther());
1295 
1296     if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
1297       continue;
1298 
1299     if (Symbol.isUndefined() && Rest.startswith("@@") &&
1300         !Rest.startswith("@@@")) {
1301       Asm.getContext().reportError(S.Loc, "default version symbol " +
1302                                               AliasName + " must be defined");
1303       continue;
1304     }
1305 
1306     if (Renames.count(&Symbol) && Renames[&Symbol] != Alias) {
1307       Asm.getContext().reportError(S.Loc, Twine("multiple versions for ") +
1308                                               Symbol.getName());
1309       continue;
1310     }
1311 
1312     Renames.insert(std::make_pair(&Symbol, Alias));
1313   }
1314 
1315   for (const MCSymbol *&Sym : AddrsigSyms) {
1316     if (const MCSymbol *R = Renames.lookup(cast<MCSymbolELF>(Sym)))
1317       Sym = R;
1318     if (Sym->isInSection() && Sym->getName().startswith(".L"))
1319       Sym = Sym->getSection().getBeginSymbol();
1320     Sym->setUsedInReloc();
1321   }
1322 }
1323 
1324 // It is always valid to create a relocation with a symbol. It is preferable
1325 // to use a relocation with a section if that is possible. Using the section
1326 // allows us to omit some local symbols from the symbol table.
1327 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
1328                                                const MCSymbolRefExpr *RefA,
1329                                                const MCSymbolELF *Sym,
1330                                                uint64_t C,
1331                                                unsigned Type) const {
1332   // A PCRel relocation to an absolute value has no symbol (or section). We
1333   // represent that with a relocation to a null section.
1334   if (!RefA)
1335     return false;
1336 
1337   MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
1338   switch (Kind) {
1339   default:
1340     break;
1341   // The .odp creation emits a relocation against the symbol ".TOC." which
1342   // create a R_PPC64_TOC relocation. However the relocation symbol name
1343   // in final object creation should be NULL, since the symbol does not
1344   // really exist, it is just the reference to TOC base for the current
1345   // object file. Since the symbol is undefined, returning false results
1346   // in a relocation with a null section which is the desired result.
1347   case MCSymbolRefExpr::VK_PPC_TOCBASE:
1348     return false;
1349 
1350   // These VariantKind cause the relocation to refer to something other than
1351   // the symbol itself, like a linker generated table. Since the address of
1352   // symbol is not relevant, we cannot replace the symbol with the
1353   // section and patch the difference in the addend.
1354   case MCSymbolRefExpr::VK_GOT:
1355   case MCSymbolRefExpr::VK_PLT:
1356   case MCSymbolRefExpr::VK_GOTPCREL:
1357   case MCSymbolRefExpr::VK_PPC_GOT_LO:
1358   case MCSymbolRefExpr::VK_PPC_GOT_HI:
1359   case MCSymbolRefExpr::VK_PPC_GOT_HA:
1360     return true;
1361   }
1362 
1363   // An undefined symbol is not in any section, so the relocation has to point
1364   // to the symbol itself.
1365   assert(Sym && "Expected a symbol");
1366   if (Sym->isUndefined())
1367     return true;
1368 
1369   unsigned Binding = Sym->getBinding();
1370   switch(Binding) {
1371   default:
1372     llvm_unreachable("Invalid Binding");
1373   case ELF::STB_LOCAL:
1374     break;
1375   case ELF::STB_WEAK:
1376     // If the symbol is weak, it might be overridden by a symbol in another
1377     // file. The relocation has to point to the symbol so that the linker
1378     // can update it.
1379     return true;
1380   case ELF::STB_GLOBAL:
1381     // Global ELF symbols can be preempted by the dynamic linker. The relocation
1382     // has to point to the symbol for a reason analogous to the STB_WEAK case.
1383     return true;
1384   }
1385 
1386   // Keep symbol type for a local ifunc because it may result in an IRELATIVE
1387   // reloc that the dynamic loader will use to resolve the address at startup
1388   // time.
1389   if (Sym->getType() == ELF::STT_GNU_IFUNC)
1390     return true;
1391 
1392   // If a relocation points to a mergeable section, we have to be careful.
1393   // If the offset is zero, a relocation with the section will encode the
1394   // same information. With a non-zero offset, the situation is different.
1395   // For example, a relocation can point 42 bytes past the end of a string.
1396   // If we change such a relocation to use the section, the linker would think
1397   // that it pointed to another string and subtracting 42 at runtime will
1398   // produce the wrong value.
1399   if (Sym->isInSection()) {
1400     auto &Sec = cast<MCSectionELF>(Sym->getSection());
1401     unsigned Flags = Sec.getFlags();
1402     if (Flags & ELF::SHF_MERGE) {
1403       if (C != 0)
1404         return true;
1405 
1406       // gold<2.34 incorrectly ignored the addend for R_386_GOTOFF (9)
1407       // (http://sourceware.org/PR16794).
1408       if (TargetObjectWriter->getEMachine() == ELF::EM_386 &&
1409           Type == ELF::R_386_GOTOFF)
1410         return true;
1411     }
1412 
1413     // Most TLS relocations use a got, so they need the symbol. Even those that
1414     // are just an offset (@tpoff), require a symbol in gold versions before
1415     // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
1416     // http://sourceware.org/PR16773.
1417     if (Flags & ELF::SHF_TLS)
1418       return true;
1419   }
1420 
1421   // If the symbol is a thumb function the final relocation must set the lowest
1422   // bit. With a symbol that is done by just having the symbol have that bit
1423   // set, so we would lose the bit if we relocated with the section.
1424   // FIXME: We could use the section but add the bit to the relocation value.
1425   if (Asm.isThumbFunc(Sym))
1426     return true;
1427 
1428   if (TargetObjectWriter->needsRelocateWithSymbol(*Sym, Type))
1429     return true;
1430   return false;
1431 }
1432 
1433 void ELFObjectWriter::recordRelocation(MCAssembler &Asm,
1434                                        const MCAsmLayout &Layout,
1435                                        const MCFragment *Fragment,
1436                                        const MCFixup &Fixup, MCValue Target,
1437                                        uint64_t &FixedValue) {
1438   MCAsmBackend &Backend = Asm.getBackend();
1439   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
1440                  MCFixupKindInfo::FKF_IsPCRel;
1441   const MCSectionELF &FixupSection = cast<MCSectionELF>(*Fragment->getParent());
1442   uint64_t C = Target.getConstant();
1443   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
1444   MCContext &Ctx = Asm.getContext();
1445 
1446   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
1447     const auto &SymB = cast<MCSymbolELF>(RefB->getSymbol());
1448     if (SymB.isUndefined()) {
1449       Ctx.reportError(Fixup.getLoc(),
1450                       Twine("symbol '") + SymB.getName() +
1451                           "' can not be undefined in a subtraction expression");
1452       return;
1453     }
1454 
1455     assert(!SymB.isAbsolute() && "Should have been folded");
1456     const MCSection &SecB = SymB.getSection();
1457     if (&SecB != &FixupSection) {
1458       Ctx.reportError(Fixup.getLoc(),
1459                       "Cannot represent a difference across sections");
1460       return;
1461     }
1462 
1463     assert(!IsPCRel && "should have been folded");
1464     IsPCRel = true;
1465     C += FixupOffset - Layout.getSymbolOffset(SymB);
1466   }
1467 
1468   // We either rejected the fixup or folded B into C at this point.
1469   const MCSymbolRefExpr *RefA = Target.getSymA();
1470   const auto *SymA = RefA ? cast<MCSymbolELF>(&RefA->getSymbol()) : nullptr;
1471 
1472   bool ViaWeakRef = false;
1473   if (SymA && SymA->isVariable()) {
1474     const MCExpr *Expr = SymA->getVariableValue();
1475     if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) {
1476       if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) {
1477         SymA = cast<MCSymbolELF>(&Inner->getSymbol());
1478         ViaWeakRef = true;
1479       }
1480     }
1481   }
1482 
1483   const MCSectionELF *SecA = (SymA && SymA->isInSection())
1484                                  ? cast<MCSectionELF>(&SymA->getSection())
1485                                  : nullptr;
1486   if (!checkRelocation(Ctx, Fixup.getLoc(), &FixupSection, SecA))
1487     return;
1488 
1489   unsigned Type = TargetObjectWriter->getRelocType(Ctx, Target, Fixup, IsPCRel);
1490   bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymA, C, Type);
1491   uint64_t Addend = 0;
1492 
1493   FixedValue = !RelocateWithSymbol && SymA && !SymA->isUndefined()
1494                    ? C + Layout.getSymbolOffset(*SymA)
1495                    : C;
1496   if (hasRelocationAddend()) {
1497     Addend = FixedValue;
1498     FixedValue = 0;
1499   }
1500 
1501   if (!RelocateWithSymbol) {
1502     const auto *SectionSymbol =
1503         SecA ? cast<MCSymbolELF>(SecA->getBeginSymbol()) : nullptr;
1504     if (SectionSymbol)
1505       SectionSymbol->setUsedInReloc();
1506     ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend, SymA, C);
1507     Relocations[&FixupSection].push_back(Rec);
1508     return;
1509   }
1510 
1511   const MCSymbolELF *RenamedSymA = SymA;
1512   if (SymA) {
1513     if (const MCSymbolELF *R = Renames.lookup(SymA))
1514       RenamedSymA = R;
1515 
1516     if (ViaWeakRef)
1517       RenamedSymA->setIsWeakrefUsedInReloc();
1518     else
1519       RenamedSymA->setUsedInReloc();
1520   }
1521   ELFRelocationEntry Rec(FixupOffset, RenamedSymA, Type, Addend, SymA, C);
1522   Relocations[&FixupSection].push_back(Rec);
1523 }
1524 
1525 bool ELFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
1526     const MCAssembler &Asm, const MCSymbol &SA, const MCFragment &FB,
1527     bool InSet, bool IsPCRel) const {
1528   const auto &SymA = cast<MCSymbolELF>(SA);
1529   if (IsPCRel) {
1530     assert(!InSet);
1531     if (SymA.getBinding() != ELF::STB_LOCAL ||
1532         SymA.getType() == ELF::STT_GNU_IFUNC)
1533       return false;
1534   }
1535   return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
1536                                                                 InSet, IsPCRel);
1537 }
1538 
1539 std::unique_ptr<MCObjectWriter>
1540 llvm::createELFObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
1541                             raw_pwrite_stream &OS, bool IsLittleEndian) {
1542   return std::make_unique<ELFSingleObjectWriter>(std::move(MOTW), OS,
1543                                                   IsLittleEndian);
1544 }
1545 
1546 std::unique_ptr<MCObjectWriter>
1547 llvm::createELFDwoObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
1548                                raw_pwrite_stream &OS, raw_pwrite_stream &DwoOS,
1549                                bool IsLittleEndian) {
1550   return std::make_unique<ELFDwoObjectWriter>(std::move(MOTW), OS, DwoOS,
1551                                                IsLittleEndian);
1552 }
1553