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