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