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