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     sh_link = SymbolTableIndex;
980     break;
981 
982   case ELF::SHT_GROUP:
983     sh_link = SymbolTableIndex;
984     sh_info = GroupSymbolIndex;
985     break;
986   }
987 
988   if (Section.getFlags() & ELF::SHF_LINK_ORDER) {
989     const MCSymbol *Sym = Section.getAssociatedSymbol();
990     const MCSectionELF *Sec = cast<MCSectionELF>(&Sym->getSection());
991     sh_link = SectionIndexMap.lookup(Sec);
992   }
993 
994   WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getSectionName()),
995                    Section.getType(), Section.getFlags(), 0, Offset, Size,
996                    sh_link, sh_info, Section.getAlignment(),
997                    Section.getEntrySize());
998 }
999 
1000 void ELFWriter::writeSectionHeader(
1001     const MCAsmLayout &Layout, const SectionIndexMapTy &SectionIndexMap,
1002     const SectionOffsetsTy &SectionOffsets) {
1003   const unsigned NumSections = SectionTable.size();
1004 
1005   // Null section first.
1006   uint64_t FirstSectionSize =
1007       (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
1008   WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
1009 
1010   for (const MCSectionELF *Section : SectionTable) {
1011     uint32_t GroupSymbolIndex;
1012     unsigned Type = Section->getType();
1013     if (Type != ELF::SHT_GROUP)
1014       GroupSymbolIndex = 0;
1015     else
1016       GroupSymbolIndex = Section->getGroup()->getIndex();
1017 
1018     const std::pair<uint64_t, uint64_t> &Offsets =
1019         SectionOffsets.find(Section)->second;
1020     uint64_t Size;
1021     if (Type == ELF::SHT_NOBITS)
1022       Size = Layout.getSectionAddressSize(Section);
1023     else
1024       Size = Offsets.second - Offsets.first;
1025 
1026     writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1027                  *Section);
1028   }
1029 }
1030 
1031 uint64_t ELFWriter::writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) {
1032   uint64_t StartOffset = W.OS.tell();
1033 
1034   MCContext &Ctx = Asm.getContext();
1035   MCSectionELF *StrtabSection =
1036       Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1037   StringTableIndex = addToSectionTable(StrtabSection);
1038 
1039   RevGroupMapTy RevGroupMap;
1040   SectionIndexMapTy SectionIndexMap;
1041 
1042   std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers;
1043 
1044   // Write out the ELF header ...
1045   writeHeader(Asm);
1046 
1047   // ... then the sections ...
1048   SectionOffsetsTy SectionOffsets;
1049   std::vector<MCSectionELF *> Groups;
1050   std::vector<MCSectionELF *> Relocations;
1051   for (MCSection &Sec : Asm) {
1052     MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
1053     if (Mode == NonDwoOnly && isDwoSection(Section))
1054       continue;
1055     if (Mode == DwoOnly && !isDwoSection(Section))
1056       continue;
1057 
1058     align(Section.getAlignment());
1059 
1060     // Remember the offset into the file for this section.
1061     uint64_t SecStart = W.OS.tell();
1062 
1063     const MCSymbolELF *SignatureSymbol = Section.getGroup();
1064     writeSectionData(Asm, Section, Layout);
1065 
1066     uint64_t SecEnd = W.OS.tell();
1067     SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd);
1068 
1069     MCSectionELF *RelSection = createRelocationSection(Ctx, Section);
1070 
1071     if (SignatureSymbol) {
1072       Asm.registerSymbol(*SignatureSymbol);
1073       unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1074       if (!GroupIdx) {
1075         MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
1076         GroupIdx = addToSectionTable(Group);
1077         Group->setAlignment(4);
1078         Groups.push_back(Group);
1079       }
1080       std::vector<const MCSectionELF *> &Members =
1081           GroupMembers[SignatureSymbol];
1082       Members.push_back(&Section);
1083       if (RelSection)
1084         Members.push_back(RelSection);
1085     }
1086 
1087     SectionIndexMap[&Section] = addToSectionTable(&Section);
1088     if (RelSection) {
1089       SectionIndexMap[RelSection] = addToSectionTable(RelSection);
1090       Relocations.push_back(RelSection);
1091     }
1092   }
1093 
1094   for (MCSectionELF *Group : Groups) {
1095     align(Group->getAlignment());
1096 
1097     // Remember the offset into the file for this section.
1098     uint64_t SecStart = W.OS.tell();
1099 
1100     const MCSymbol *SignatureSymbol = Group->getGroup();
1101     assert(SignatureSymbol);
1102     write(uint32_t(ELF::GRP_COMDAT));
1103     for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) {
1104       uint32_t SecIndex = SectionIndexMap.lookup(Member);
1105       write(SecIndex);
1106     }
1107 
1108     uint64_t SecEnd = W.OS.tell();
1109     SectionOffsets[Group] = std::make_pair(SecStart, SecEnd);
1110   }
1111 
1112   if (Mode == DwoOnly) {
1113     // dwo files don't have symbol tables or relocations, but they do have
1114     // string tables.
1115     StrTabBuilder.finalize();
1116   } else {
1117     // Compute symbol table information.
1118     computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1119                        SectionOffsets);
1120 
1121     for (MCSectionELF *RelSection : Relocations) {
1122       align(RelSection->getAlignment());
1123 
1124       // Remember the offset into the file for this section.
1125       uint64_t SecStart = W.OS.tell();
1126 
1127       writeRelocations(Asm,
1128                        cast<MCSectionELF>(*RelSection->getAssociatedSection()));
1129 
1130       uint64_t SecEnd = W.OS.tell();
1131       SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd);
1132     }
1133   }
1134 
1135   {
1136     uint64_t SecStart = W.OS.tell();
1137     const MCSectionELF *Sec = createStringTable(Ctx);
1138     uint64_t SecEnd = W.OS.tell();
1139     SectionOffsets[Sec] = std::make_pair(SecStart, SecEnd);
1140   }
1141 
1142   uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1143   align(NaturalAlignment);
1144 
1145   const uint64_t SectionHeaderOffset = W.OS.tell();
1146 
1147   // ... then the section header table ...
1148   writeSectionHeader(Layout, SectionIndexMap, SectionOffsets);
1149 
1150   uint16_t NumSections = support::endian::byte_swap<uint16_t>(
1151       (SectionTable.size() + 1 >= ELF::SHN_LORESERVE) ? (uint16_t)ELF::SHN_UNDEF
1152                                                       : SectionTable.size() + 1,
1153       W.Endian);
1154   unsigned NumSectionsOffset;
1155 
1156   auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
1157   if (is64Bit()) {
1158     uint64_t Val =
1159         support::endian::byte_swap<uint64_t>(SectionHeaderOffset, W.Endian);
1160     Stream.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1161                   offsetof(ELF::Elf64_Ehdr, e_shoff));
1162     NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
1163   } else {
1164     uint32_t Val =
1165         support::endian::byte_swap<uint32_t>(SectionHeaderOffset, W.Endian);
1166     Stream.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1167                   offsetof(ELF::Elf32_Ehdr, e_shoff));
1168     NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
1169   }
1170   Stream.pwrite(reinterpret_cast<char *>(&NumSections), sizeof(NumSections),
1171                 NumSectionsOffset);
1172 
1173   return W.OS.tell() - StartOffset;
1174 }
1175 
1176 bool ELFObjectWriter::hasRelocationAddend() const {
1177   return TargetObjectWriter->hasRelocationAddend();
1178 }
1179 
1180 void ELFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
1181                                                const MCAsmLayout &Layout) {
1182   // The presence of symbol versions causes undefined symbols and
1183   // versions declared with @@@ to be renamed.
1184   for (const std::pair<StringRef, const MCSymbol *> &P : Asm.Symvers) {
1185     StringRef AliasName = P.first;
1186     const auto &Symbol = cast<MCSymbolELF>(*P.second);
1187     size_t Pos = AliasName.find('@');
1188     assert(Pos != StringRef::npos);
1189 
1190     StringRef Prefix = AliasName.substr(0, Pos);
1191     StringRef Rest = AliasName.substr(Pos);
1192     StringRef Tail = Rest;
1193     if (Rest.startswith("@@@"))
1194       Tail = Rest.substr(Symbol.isUndefined() ? 2 : 1);
1195 
1196     auto *Alias =
1197         cast<MCSymbolELF>(Asm.getContext().getOrCreateSymbol(Prefix + Tail));
1198     Asm.registerSymbol(*Alias);
1199     const MCExpr *Value = MCSymbolRefExpr::create(&Symbol, Asm.getContext());
1200     Alias->setVariableValue(Value);
1201 
1202     // Aliases defined with .symvar copy the binding from the symbol they alias.
1203     // This is the first place we are able to copy this information.
1204     Alias->setExternal(Symbol.isExternal());
1205     Alias->setBinding(Symbol.getBinding());
1206 
1207     if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
1208       continue;
1209 
1210     // FIXME: produce a better error message.
1211     if (Symbol.isUndefined() && Rest.startswith("@@") &&
1212         !Rest.startswith("@@@"))
1213       report_fatal_error("A @@ version cannot be undefined");
1214 
1215     if (Renames.count(&Symbol) && Renames[&Symbol] != Alias)
1216       report_fatal_error(llvm::Twine("Multiple symbol versions defined for ") +
1217                          Symbol.getName());
1218 
1219     Renames.insert(std::make_pair(&Symbol, Alias));
1220   }
1221 }
1222 
1223 // It is always valid to create a relocation with a symbol. It is preferable
1224 // to use a relocation with a section if that is possible. Using the section
1225 // allows us to omit some local symbols from the symbol table.
1226 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
1227                                                const MCSymbolRefExpr *RefA,
1228                                                const MCSymbolELF *Sym,
1229                                                uint64_t C,
1230                                                unsigned Type) const {
1231   // A PCRel relocation to an absolute value has no symbol (or section). We
1232   // represent that with a relocation to a null section.
1233   if (!RefA)
1234     return false;
1235 
1236   MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
1237   switch (Kind) {
1238   default:
1239     break;
1240   // The .odp creation emits a relocation against the symbol ".TOC." which
1241   // create a R_PPC64_TOC relocation. However the relocation symbol name
1242   // in final object creation should be NULL, since the symbol does not
1243   // really exist, it is just the reference to TOC base for the current
1244   // object file. Since the symbol is undefined, returning false results
1245   // in a relocation with a null section which is the desired result.
1246   case MCSymbolRefExpr::VK_PPC_TOCBASE:
1247     return false;
1248 
1249   // These VariantKind cause the relocation to refer to something other than
1250   // the symbol itself, like a linker generated table. Since the address of
1251   // symbol is not relevant, we cannot replace the symbol with the
1252   // section and patch the difference in the addend.
1253   case MCSymbolRefExpr::VK_GOT:
1254   case MCSymbolRefExpr::VK_PLT:
1255   case MCSymbolRefExpr::VK_GOTPCREL:
1256   case MCSymbolRefExpr::VK_PPC_GOT_LO:
1257   case MCSymbolRefExpr::VK_PPC_GOT_HI:
1258   case MCSymbolRefExpr::VK_PPC_GOT_HA:
1259     return true;
1260   }
1261 
1262   // An undefined symbol is not in any section, so the relocation has to point
1263   // to the symbol itself.
1264   assert(Sym && "Expected a symbol");
1265   if (Sym->isUndefined())
1266     return true;
1267 
1268   unsigned Binding = Sym->getBinding();
1269   switch(Binding) {
1270   default:
1271     llvm_unreachable("Invalid Binding");
1272   case ELF::STB_LOCAL:
1273     break;
1274   case ELF::STB_WEAK:
1275     // If the symbol is weak, it might be overridden by a symbol in another
1276     // file. The relocation has to point to the symbol so that the linker
1277     // can update it.
1278     return true;
1279   case ELF::STB_GLOBAL:
1280     // Global ELF symbols can be preempted by the dynamic linker. The relocation
1281     // has to point to the symbol for a reason analogous to the STB_WEAK case.
1282     return true;
1283   }
1284 
1285   // If a relocation points to a mergeable section, we have to be careful.
1286   // If the offset is zero, a relocation with the section will encode the
1287   // same information. With a non-zero offset, the situation is different.
1288   // For example, a relocation can point 42 bytes past the end of a string.
1289   // If we change such a relocation to use the section, the linker would think
1290   // that it pointed to another string and subtracting 42 at runtime will
1291   // produce the wrong value.
1292   if (Sym->isInSection()) {
1293     auto &Sec = cast<MCSectionELF>(Sym->getSection());
1294     unsigned Flags = Sec.getFlags();
1295     if (Flags & ELF::SHF_MERGE) {
1296       if (C != 0)
1297         return true;
1298 
1299       // It looks like gold has a bug (http://sourceware.org/PR16794) and can
1300       // only handle section relocations to mergeable sections if using RELA.
1301       if (!hasRelocationAddend())
1302         return true;
1303     }
1304 
1305     // Most TLS relocations use a got, so they need the symbol. Even those that
1306     // are just an offset (@tpoff), require a symbol in gold versions before
1307     // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
1308     // http://sourceware.org/PR16773.
1309     if (Flags & ELF::SHF_TLS)
1310       return true;
1311   }
1312 
1313   // If the symbol is a thumb function the final relocation must set the lowest
1314   // bit. With a symbol that is done by just having the symbol have that bit
1315   // set, so we would lose the bit if we relocated with the section.
1316   // FIXME: We could use the section but add the bit to the relocation value.
1317   if (Asm.isThumbFunc(Sym))
1318     return true;
1319 
1320   if (TargetObjectWriter->needsRelocateWithSymbol(*Sym, Type))
1321     return true;
1322   return false;
1323 }
1324 
1325 void ELFObjectWriter::recordRelocation(MCAssembler &Asm,
1326                                        const MCAsmLayout &Layout,
1327                                        const MCFragment *Fragment,
1328                                        const MCFixup &Fixup, MCValue Target,
1329                                        uint64_t &FixedValue) {
1330   MCAsmBackend &Backend = Asm.getBackend();
1331   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
1332                  MCFixupKindInfo::FKF_IsPCRel;
1333   const MCSectionELF &FixupSection = cast<MCSectionELF>(*Fragment->getParent());
1334   uint64_t C = Target.getConstant();
1335   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
1336   MCContext &Ctx = Asm.getContext();
1337 
1338   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
1339     // Let A, B and C being the components of Target and R be the location of
1340     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
1341     // If it is pcrel, we want to compute (A - B + C - R).
1342 
1343     // In general, ELF has no relocations for -B. It can only represent (A + C)
1344     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
1345     // replace B to implement it: (A - R - K + C)
1346     if (IsPCRel) {
1347       Ctx.reportError(
1348           Fixup.getLoc(),
1349           "No relocation available to represent this relative expression");
1350       return;
1351     }
1352 
1353     const auto &SymB = cast<MCSymbolELF>(RefB->getSymbol());
1354 
1355     if (SymB.isUndefined()) {
1356       Ctx.reportError(Fixup.getLoc(),
1357                       Twine("symbol '") + SymB.getName() +
1358                           "' can not be undefined in a subtraction expression");
1359       return;
1360     }
1361 
1362     assert(!SymB.isAbsolute() && "Should have been folded");
1363     const MCSection &SecB = SymB.getSection();
1364     if (&SecB != &FixupSection) {
1365       Ctx.reportError(Fixup.getLoc(),
1366                       "Cannot represent a difference across sections");
1367       return;
1368     }
1369 
1370     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
1371     uint64_t K = SymBOffset - FixupOffset;
1372     IsPCRel = true;
1373     C -= K;
1374   }
1375 
1376   // We either rejected the fixup or folded B into C at this point.
1377   const MCSymbolRefExpr *RefA = Target.getSymA();
1378   const auto *SymA = RefA ? cast<MCSymbolELF>(&RefA->getSymbol()) : nullptr;
1379 
1380   bool ViaWeakRef = false;
1381   if (SymA && SymA->isVariable()) {
1382     const MCExpr *Expr = SymA->getVariableValue();
1383     if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) {
1384       if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) {
1385         SymA = cast<MCSymbolELF>(&Inner->getSymbol());
1386         ViaWeakRef = true;
1387       }
1388     }
1389   }
1390 
1391   unsigned Type = TargetObjectWriter->getRelocType(Ctx, Target, Fixup, IsPCRel);
1392   uint64_t OriginalC = C;
1393   bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymA, C, Type);
1394   if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
1395     C += Layout.getSymbolOffset(*SymA);
1396 
1397   uint64_t Addend = 0;
1398   if (hasRelocationAddend()) {
1399     Addend = C;
1400     C = 0;
1401   }
1402 
1403   FixedValue = C;
1404 
1405   const MCSectionELF *SecA = (SymA && SymA->isInSection())
1406                                  ? cast<MCSectionELF>(&SymA->getSection())
1407                                  : nullptr;
1408   if (!checkRelocation(Ctx, Fixup.getLoc(), &FixupSection, SecA))
1409     return;
1410 
1411   if (!RelocateWithSymbol) {
1412     const auto *SectionSymbol =
1413         SecA ? cast<MCSymbolELF>(SecA->getBeginSymbol()) : nullptr;
1414     if (SectionSymbol)
1415       SectionSymbol->setUsedInReloc();
1416     ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend, SymA,
1417                            OriginalC);
1418     Relocations[&FixupSection].push_back(Rec);
1419     return;
1420   }
1421 
1422   const auto *RenamedSymA = SymA;
1423   if (SymA) {
1424     if (const MCSymbolELF *R = Renames.lookup(SymA))
1425       RenamedSymA = R;
1426 
1427     if (ViaWeakRef)
1428       RenamedSymA->setIsWeakrefUsedInReloc();
1429     else
1430       RenamedSymA->setUsedInReloc();
1431   }
1432   ELFRelocationEntry Rec(FixupOffset, RenamedSymA, Type, Addend, SymA,
1433                          OriginalC);
1434   Relocations[&FixupSection].push_back(Rec);
1435 }
1436 
1437 bool ELFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
1438     const MCAssembler &Asm, const MCSymbol &SA, const MCFragment &FB,
1439     bool InSet, bool IsPCRel) const {
1440   const auto &SymA = cast<MCSymbolELF>(SA);
1441   if (IsPCRel) {
1442     assert(!InSet);
1443     if (isWeak(SymA))
1444       return false;
1445   }
1446   return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
1447                                                                 InSet, IsPCRel);
1448 }
1449 
1450 std::unique_ptr<MCObjectWriter>
1451 llvm::createELFObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
1452                             raw_pwrite_stream &OS, bool IsLittleEndian) {
1453   return llvm::make_unique<ELFSingleObjectWriter>(std::move(MOTW), OS,
1454                                                   IsLittleEndian);
1455 }
1456 
1457 std::unique_ptr<MCObjectWriter>
1458 llvm::createELFDwoObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
1459                                raw_pwrite_stream &OS, raw_pwrite_stream &DwoOS,
1460                                bool IsLittleEndian) {
1461   return llvm::make_unique<ELFDwoObjectWriter>(std::move(MOTW), OS, DwoOS,
1462                                                IsLittleEndian);
1463 }
1464