Don't walk aliases from global to local symbols in comdats.
[oota-llvm.git] / lib / MC / ELFObjectWriter.cpp
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/MC/MCELFObjectWriter.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/MC/MCAsmBackend.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/MC/MCAsmLayout.h"
22 #include "llvm/MC/MCAssembler.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCELF.h"
25 #include "llvm/MC/MCELFSymbolFlags.h"
26 #include "llvm/MC/MCExpr.h"
27 #include "llvm/MC/MCFixupKindInfo.h"
28 #include "llvm/MC/MCObjectWriter.h"
29 #include "llvm/MC/MCSectionELF.h"
30 #include "llvm/MC/MCValue.h"
31 #include "llvm/MC/StringTableBuilder.h"
32 #include "llvm/Support/Compression.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ELF.h"
35 #include "llvm/Support/Endian.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include <vector>
38 using namespace llvm;
39
40 #undef  DEBUG_TYPE
41 #define DEBUG_TYPE "reloc-info"
42
43 namespace {
44 class FragmentWriter {
45   bool IsLittleEndian;
46
47 public:
48   FragmentWriter(bool IsLittleEndian);
49   template <typename T> void write(MCDataFragment &F, T Val);
50 };
51
52 typedef DenseMap<const MCSectionELF *, uint32_t> SectionIndexMapTy;
53
54 class SymbolTableWriter {
55   MCAssembler &Asm;
56   FragmentWriter &FWriter;
57   bool Is64Bit;
58   SectionIndexMapTy &SectionIndexMap;
59
60   // The symbol .symtab fragment we are writting to.
61   MCDataFragment *SymtabF;
62
63   // .symtab_shndx fragment we are writting to.
64   MCDataFragment *ShndxF;
65
66   // The numbel of symbols written so far.
67   unsigned NumWritten;
68
69   void createSymtabShndx();
70
71   template <typename T> void write(MCDataFragment &F, T Value);
72
73 public:
74   SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter, bool Is64Bit,
75                     SectionIndexMapTy &SectionIndexMap,
76                     MCDataFragment *SymtabF);
77
78   void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
79                    uint8_t other, uint32_t shndx, bool Reserved);
80 };
81
82 class ELFObjectWriter : public MCObjectWriter {
83   FragmentWriter FWriter;
84
85   protected:
86
87     static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
88     static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
89     static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
90     static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolData &Data,
91                            bool Used, bool Renamed);
92     static bool isLocal(const MCSymbolData &Data, bool isUsedInReloc);
93     static bool IsELFMetaDataSection(const MCSectionData &SD);
94     static uint64_t DataSectionSize(const MCSectionData &SD);
95     static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
96                                           const MCSectionData &SD);
97
98     void writeDataSectionData(MCAssembler &Asm, const MCAsmLayout &Layout,
99                               const MCSectionData &SD);
100
101     /// Helper struct for containing some precomputed information on symbols.
102     struct ELFSymbolData {
103       MCSymbolData *SymbolData;
104       uint64_t StringIndex;
105       uint32_t SectionIndex;
106       StringRef Name;
107
108       // Support lexicographic sorting.
109       bool operator<(const ELFSymbolData &RHS) const {
110         unsigned LHSType = MCELF::GetType(*SymbolData);
111         unsigned RHSType = MCELF::GetType(*RHS.SymbolData);
112         if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
113           return false;
114         if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
115           return true;
116         if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
117           return SectionIndex < RHS.SectionIndex;
118         return Name < RHS.Name;
119       }
120     };
121
122     /// The target specific ELF writer instance.
123     std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
124
125     SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
126     SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
127     DenseMap<const MCSymbol *, const MCSymbol *> Renames;
128
129     llvm::DenseMap<const MCSectionData *, std::vector<ELFRelocationEntry>>
130     Relocations;
131     StringTableBuilder ShStrTabBuilder;
132
133     /// @}
134     /// @name Symbol Table Data
135     /// @{
136
137     StringTableBuilder StrTabBuilder;
138     std::vector<uint64_t> FileSymbolData;
139     std::vector<ELFSymbolData> LocalSymbolData;
140     std::vector<ELFSymbolData> ExternalSymbolData;
141     std::vector<ELFSymbolData> UndefinedSymbolData;
142
143     /// @}
144
145     bool NeedsGOT;
146
147     // This holds the symbol table index of the last local symbol.
148     unsigned LastLocalSymbolIndex;
149     // This holds the .strtab section index.
150     unsigned StringTableIndex;
151     // This holds the .symtab section index.
152     unsigned SymbolTableIndex;
153
154     unsigned ShstrtabIndex;
155
156
157     // TargetObjectWriter wrappers.
158     bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
159     bool hasRelocationAddend() const {
160       return TargetObjectWriter->hasRelocationAddend();
161     }
162     unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
163                           bool IsPCRel) const {
164       return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
165     }
166
167   public:
168     ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_pwrite_stream &OS,
169                     bool IsLittleEndian)
170         : MCObjectWriter(OS, IsLittleEndian), FWriter(IsLittleEndian),
171           TargetObjectWriter(MOTW), NeedsGOT(false) {}
172
173     void reset() override {
174       UsedInReloc.clear();
175       WeakrefUsedInReloc.clear();
176       Renames.clear();
177       Relocations.clear();
178       ShStrTabBuilder.clear();
179       StrTabBuilder.clear();
180       FileSymbolData.clear();
181       LocalSymbolData.clear();
182       ExternalSymbolData.clear();
183       UndefinedSymbolData.clear();
184       MCObjectWriter::reset();
185     }
186
187     ~ELFObjectWriter() override;
188
189     void WriteWord(uint64_t W) {
190       if (is64Bit())
191         Write64(W);
192       else
193         Write32(W);
194     }
195
196     template <typename T> void write(MCDataFragment &F, T Value) {
197       FWriter.write(F, Value);
198     }
199
200     void WriteHeader(const MCAssembler &Asm,
201                      unsigned NumberOfSections);
202
203     void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
204                      const MCAsmLayout &Layout);
205
206     void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
207                           const MCAsmLayout &Layout,
208                           SectionIndexMapTy &SectionIndexMap);
209
210     bool shouldRelocateWithSymbol(const MCAssembler &Asm,
211                                   const MCSymbolRefExpr *RefA,
212                                   const MCSymbolData *SD, uint64_t C,
213                                   unsigned Type) const;
214
215     void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
216                           const MCFragment *Fragment, const MCFixup &Fixup,
217                           MCValue Target, bool &IsPCRel,
218                           uint64_t &FixedValue) override;
219
220     uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
221                                          const MCSymbol *S);
222
223     // Map from a group section to the signature symbol
224     typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
225     // Map from a signature symbol to the group section
226     typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
227     // Map from a section to its offset
228     typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
229
230     /// Compute the symbol table data
231     ///
232     /// \param Asm - The assembler.
233     /// \param SectionIndexMap - Maps a section to its index.
234     /// \param RevGroupMap - Maps a signature symbol to the group section.
235     void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
236                             const SectionIndexMapTy &SectionIndexMap,
237                             const RevGroupMapTy &RevGroupMap);
238
239     void computeIndexMap(MCAssembler &Asm, SectionIndexMapTy &SectionIndexMap);
240
241     MCSectionData *createRelocationSection(MCAssembler &Asm,
242                                            const MCSectionData &SD);
243
244     void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
245
246     void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout);
247
248     void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
249                                 SectionIndexMapTy &SectionIndexMap);
250
251     // Create the sections that show up in the symbol table. Currently
252     // those are the .note.GNU-stack section and the group sections.
253     void createIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
254                                GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap,
255                                SectionIndexMapTy &SectionIndexMap);
256
257     void ExecutePostLayoutBinding(MCAssembler &Asm,
258                                   const MCAsmLayout &Layout) override;
259
260     void writeSectionHeader(ArrayRef<const MCSectionELF *> Sections,
261                             MCAssembler &Asm, const GroupMapTy &GroupMap,
262                             const MCAsmLayout &Layout,
263                             const SectionIndexMapTy &SectionIndexMap,
264                             const SectionOffsetMapTy &SectionOffsetMap);
265
266     void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
267                           uint64_t Address, uint64_t Offset,
268                           uint64_t Size, uint32_t Link, uint32_t Info,
269                           uint64_t Alignment, uint64_t EntrySize);
270
271     void WriteRelocationsFragment(const MCAssembler &Asm,
272                                   MCDataFragment *F,
273                                   const MCSectionData *SD);
274
275     bool
276     IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
277                                            const MCSymbolData &DataA,
278                                            const MCSymbolData *DataB,
279                                            const MCFragment &FB,
280                                            bool InSet,
281                                            bool IsPCRel) const override;
282
283     bool isWeak(const MCSymbolData &SD) const override;
284
285     void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
286     void writeSection(MCAssembler &Asm,
287                       const SectionIndexMapTy &SectionIndexMap,
288                       uint32_t GroupSymbolIndex,
289                       uint64_t Offset, uint64_t Size, uint64_t Alignment,
290                       const MCSectionELF &Section);
291   };
292 }
293
294 FragmentWriter::FragmentWriter(bool IsLittleEndian)
295     : IsLittleEndian(IsLittleEndian) {}
296
297 template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
298   if (IsLittleEndian)
299     Val = support::endian::byte_swap<T, support::little>(Val);
300   else
301     Val = support::endian::byte_swap<T, support::big>(Val);
302   const char *Start = (const char *)&Val;
303   F.getContents().append(Start, Start + sizeof(T));
304 }
305
306 void SymbolTableWriter::createSymtabShndx() {
307   if (ShndxF)
308     return;
309
310   MCContext &Ctx = Asm.getContext();
311   const MCSectionELF *SymtabShndxSection =
312       Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
313   MCSectionData *SymtabShndxSD =
314       &Asm.getOrCreateSectionData(*SymtabShndxSection);
315   SymtabShndxSD->setAlignment(4);
316   ShndxF = new MCDataFragment(SymtabShndxSD);
317   unsigned Index = SectionIndexMap.size() + 1;
318   SectionIndexMap[SymtabShndxSection] = Index;
319
320   for (unsigned I = 0; I < NumWritten; ++I)
321     write(*ShndxF, uint32_t(0));
322 }
323
324 template <typename T>
325 void SymbolTableWriter::write(MCDataFragment &F, T Value) {
326   FWriter.write(F, Value);
327 }
328
329 SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
330                                      bool Is64Bit,
331                                      SectionIndexMapTy &SectionIndexMap,
332                                      MCDataFragment *SymtabF)
333     : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
334       SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
335       NumWritten(0) {}
336
337 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
338                                     uint64_t size, uint8_t other,
339                                     uint32_t shndx, bool Reserved) {
340   bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
341
342   if (LargeIndex)
343     createSymtabShndx();
344
345   if (ShndxF) {
346     if (LargeIndex)
347       write(*ShndxF, shndx);
348     else
349       write(*ShndxF, uint32_t(0));
350   }
351
352   uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
353
354   if (Is64Bit) {
355     write(*SymtabF, name);  // st_name
356     write(*SymtabF, info);  // st_info
357     write(*SymtabF, other); // st_other
358     write(*SymtabF, Index); // st_shndx
359     write(*SymtabF, value); // st_value
360     write(*SymtabF, size);  // st_size
361   } else {
362     write(*SymtabF, name);            // st_name
363     write(*SymtabF, uint32_t(value)); // st_value
364     write(*SymtabF, uint32_t(size));  // st_size
365     write(*SymtabF, info);            // st_info
366     write(*SymtabF, other);           // st_other
367     write(*SymtabF, Index);           // st_shndx
368   }
369
370   ++NumWritten;
371 }
372
373 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
374   const MCFixupKindInfo &FKI =
375     Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
376
377   return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
378 }
379
380 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
381   switch (Variant) {
382   default:
383     return false;
384   case MCSymbolRefExpr::VK_GOT:
385   case MCSymbolRefExpr::VK_PLT:
386   case MCSymbolRefExpr::VK_GOTPCREL:
387   case MCSymbolRefExpr::VK_GOTOFF:
388   case MCSymbolRefExpr::VK_TPOFF:
389   case MCSymbolRefExpr::VK_TLSGD:
390   case MCSymbolRefExpr::VK_GOTTPOFF:
391   case MCSymbolRefExpr::VK_INDNTPOFF:
392   case MCSymbolRefExpr::VK_NTPOFF:
393   case MCSymbolRefExpr::VK_GOTNTPOFF:
394   case MCSymbolRefExpr::VK_TLSLDM:
395   case MCSymbolRefExpr::VK_DTPOFF:
396   case MCSymbolRefExpr::VK_TLSLD:
397     return true;
398   }
399 }
400
401 ELFObjectWriter::~ELFObjectWriter()
402 {}
403
404 // Emit the ELF header.
405 void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
406                                   unsigned NumberOfSections) {
407   // ELF Header
408   // ----------
409   //
410   // Note
411   // ----
412   // emitWord method behaves differently for ELF32 and ELF64, writing
413   // 4 bytes in the former and 8 in the latter.
414
415   Write8(0x7f); // e_ident[EI_MAG0]
416   Write8('E');  // e_ident[EI_MAG1]
417   Write8('L');  // e_ident[EI_MAG2]
418   Write8('F');  // e_ident[EI_MAG3]
419
420   Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
421
422   // e_ident[EI_DATA]
423   Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
424
425   Write8(ELF::EV_CURRENT);        // e_ident[EI_VERSION]
426   // e_ident[EI_OSABI]
427   Write8(TargetObjectWriter->getOSABI());
428   Write8(0);                  // e_ident[EI_ABIVERSION]
429
430   WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
431
432   Write16(ELF::ET_REL);             // e_type
433
434   Write16(TargetObjectWriter->getEMachine()); // e_machine = target
435
436   Write32(ELF::EV_CURRENT);         // e_version
437   WriteWord(0);                    // e_entry, no entry point in .o file
438   WriteWord(0);                    // e_phoff, no program header for .o
439   WriteWord(0);                     // e_shoff = sec hdr table off in bytes
440
441   // e_flags = whatever the target wants
442   Write32(Asm.getELFHeaderEFlags());
443
444   // e_ehsize = ELF header size
445   Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
446
447   Write16(0);                  // e_phentsize = prog header entry size
448   Write16(0);                  // e_phnum = # prog header entries = 0
449
450   // e_shentsize = Section header entry size
451   Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
452
453   // e_shnum     = # of section header ents
454   if (NumberOfSections >= ELF::SHN_LORESERVE)
455     Write16(ELF::SHN_UNDEF);
456   else
457     Write16(NumberOfSections);
458
459   // e_shstrndx  = Section # of '.shstrtab'
460   if (ShstrtabIndex >= ELF::SHN_LORESERVE)
461     Write16(ELF::SHN_XINDEX);
462   else
463     Write16(ShstrtabIndex);
464 }
465
466 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
467                                       const MCAsmLayout &Layout) {
468   if (Data.isCommon() && Data.isExternal())
469     return Data.getCommonAlignment();
470
471   uint64_t Res;
472   if (!Layout.getSymbolOffset(&Data, Res))
473     return 0;
474
475   if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
476     Res |= 1;
477
478   return Res;
479 }
480
481 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
482                                                const MCAsmLayout &Layout) {
483   // The presence of symbol versions causes undefined symbols and
484   // versions declared with @@@ to be renamed.
485
486   for (MCSymbolData &OriginalData : Asm.symbols()) {
487     const MCSymbol &Alias = OriginalData.getSymbol();
488
489     // Not an alias.
490     if (!Alias.isVariable())
491       continue;
492     auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
493     if (!Ref)
494       continue;
495     const MCSymbol &Symbol = Ref->getSymbol();
496     MCSymbolData &SD = Asm.getSymbolData(Symbol);
497
498     StringRef AliasName = Alias.getName();
499     size_t Pos = AliasName.find('@');
500     if (Pos == StringRef::npos)
501       continue;
502
503     // Aliases defined with .symvar copy the binding from the symbol they alias.
504     // This is the first place we are able to copy this information.
505     OriginalData.setExternal(SD.isExternal());
506     MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
507
508     StringRef Rest = AliasName.substr(Pos);
509     if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
510       continue;
511
512     // FIXME: produce a better error message.
513     if (Symbol.isUndefined() && Rest.startswith("@@") &&
514         !Rest.startswith("@@@"))
515       report_fatal_error("A @@ version cannot be undefined");
516
517     Renames.insert(std::make_pair(&Symbol, &Alias));
518   }
519 }
520
521 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
522   uint8_t Type = newType;
523
524   // Propagation rules:
525   // IFUNC > FUNC > OBJECT > NOTYPE
526   // TLS_OBJECT > OBJECT > NOTYPE
527   //
528   // dont let the new type degrade the old type
529   switch (origType) {
530   default:
531     break;
532   case ELF::STT_GNU_IFUNC:
533     if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
534         Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
535       Type = ELF::STT_GNU_IFUNC;
536     break;
537   case ELF::STT_FUNC:
538     if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
539         Type == ELF::STT_TLS)
540       Type = ELF::STT_FUNC;
541     break;
542   case ELF::STT_OBJECT:
543     if (Type == ELF::STT_NOTYPE)
544       Type = ELF::STT_OBJECT;
545     break;
546   case ELF::STT_TLS:
547     if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
548         Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
549       Type = ELF::STT_TLS;
550     break;
551   }
552
553   return Type;
554 }
555
556 void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
557                                   const MCAsmLayout &Layout) {
558   MCSymbolData &OrigData = *MSD.SymbolData;
559   assert((!OrigData.getFragment() ||
560           (&OrigData.getFragment()->getParent()->getSection() ==
561            &OrigData.getSymbol().getSection())) &&
562          "The symbol's section doesn't match the fragment's symbol");
563   const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
564
565   // This has to be in sync with when computeSymbolTable uses SHN_ABS or
566   // SHN_COMMON.
567   bool IsReserved = !Base || OrigData.isCommon();
568
569   // Binding and Type share the same byte as upper and lower nibbles
570   uint8_t Binding = MCELF::GetBinding(OrigData);
571   uint8_t Type = MCELF::GetType(OrigData);
572   MCSymbolData *BaseSD = nullptr;
573   if (Base) {
574     BaseSD = &Layout.getAssembler().getSymbolData(*Base);
575     Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
576   }
577   uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
578
579   // Other and Visibility share the same byte with Visibility using the lower
580   // 2 bits
581   uint8_t Visibility = MCELF::GetVisibility(OrigData);
582   uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
583   Other |= Visibility;
584
585   uint64_t Value = SymbolValue(OrigData, Layout);
586   uint64_t Size = 0;
587
588   const MCExpr *ESize = OrigData.getSize();
589   if (!ESize && Base)
590     ESize = BaseSD->getSize();
591
592   if (ESize) {
593     int64_t Res;
594     if (!ESize->evaluateKnownAbsolute(Res, Layout))
595       report_fatal_error("Size expression must be absolute.");
596     Size = Res;
597   }
598
599   // Write out the symbol table entry
600   Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
601                      MSD.SectionIndex, IsReserved);
602 }
603
604 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
605                                        MCAssembler &Asm,
606                                        const MCAsmLayout &Layout,
607                                        SectionIndexMapTy &SectionIndexMap) {
608   // The string table must be emitted first because we need the index
609   // into the string table for all the symbol names.
610
611   // FIXME: Make sure the start of the symbol table is aligned.
612
613   SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
614
615   // The first entry is the undefined symbol entry.
616   Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
617
618   for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
619     Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
620                        ELF::STV_DEFAULT, ELF::SHN_ABS, true);
621   }
622
623   // Write the symbol table entries.
624   LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
625
626   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
627     ELFSymbolData &MSD = LocalSymbolData[i];
628     WriteSymbol(Writer, MSD, Layout);
629   }
630
631   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
632     ELFSymbolData &MSD = ExternalSymbolData[i];
633     MCSymbolData &Data = *MSD.SymbolData;
634     assert(((Data.getFlags() & ELF_STB_Global) ||
635             (Data.getFlags() & ELF_STB_Weak)) &&
636            "External symbol requires STB_GLOBAL or STB_WEAK flag");
637     WriteSymbol(Writer, MSD, Layout);
638     if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
639       LastLocalSymbolIndex++;
640   }
641
642   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
643     ELFSymbolData &MSD = UndefinedSymbolData[i];
644     MCSymbolData &Data = *MSD.SymbolData;
645     WriteSymbol(Writer, MSD, Layout);
646     if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
647       LastLocalSymbolIndex++;
648   }
649 }
650
651 // It is always valid to create a relocation with a symbol. It is preferable
652 // to use a relocation with a section if that is possible. Using the section
653 // allows us to omit some local symbols from the symbol table.
654 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
655                                                const MCSymbolRefExpr *RefA,
656                                                const MCSymbolData *SD,
657                                                uint64_t C,
658                                                unsigned Type) const {
659   // A PCRel relocation to an absolute value has no symbol (or section). We
660   // represent that with a relocation to a null section.
661   if (!RefA)
662     return false;
663
664   MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
665   switch (Kind) {
666   default:
667     break;
668   // The .odp creation emits a relocation against the symbol ".TOC." which
669   // create a R_PPC64_TOC relocation. However the relocation symbol name
670   // in final object creation should be NULL, since the symbol does not
671   // really exist, it is just the reference to TOC base for the current
672   // object file. Since the symbol is undefined, returning false results
673   // in a relocation with a null section which is the desired result.
674   case MCSymbolRefExpr::VK_PPC_TOCBASE:
675     return false;
676
677   // These VariantKind cause the relocation to refer to something other than
678   // the symbol itself, like a linker generated table. Since the address of
679   // symbol is not relevant, we cannot replace the symbol with the
680   // section and patch the difference in the addend.
681   case MCSymbolRefExpr::VK_GOT:
682   case MCSymbolRefExpr::VK_PLT:
683   case MCSymbolRefExpr::VK_GOTPCREL:
684   case MCSymbolRefExpr::VK_Mips_GOT:
685   case MCSymbolRefExpr::VK_PPC_GOT_LO:
686   case MCSymbolRefExpr::VK_PPC_GOT_HI:
687   case MCSymbolRefExpr::VK_PPC_GOT_HA:
688     return true;
689   }
690
691   // An undefined symbol is not in any section, so the relocation has to point
692   // to the symbol itself.
693   const MCSymbol &Sym = SD->getSymbol();
694   if (Sym.isUndefined())
695     return true;
696
697   unsigned Binding = MCELF::GetBinding(*SD);
698   switch(Binding) {
699   default:
700     llvm_unreachable("Invalid Binding");
701   case ELF::STB_LOCAL:
702     break;
703   case ELF::STB_WEAK:
704     // If the symbol is weak, it might be overridden by a symbol in another
705     // file. The relocation has to point to the symbol so that the linker
706     // can update it.
707     return true;
708   case ELF::STB_GLOBAL:
709     // Global ELF symbols can be preempted by the dynamic linker. The relocation
710     // has to point to the symbol for a reason analogous to the STB_WEAK case.
711     return true;
712   }
713
714   // If a relocation points to a mergeable section, we have to be careful.
715   // If the offset is zero, a relocation with the section will encode the
716   // same information. With a non-zero offset, the situation is different.
717   // For example, a relocation can point 42 bytes past the end of a string.
718   // If we change such a relocation to use the section, the linker would think
719   // that it pointed to another string and subtracting 42 at runtime will
720   // produce the wrong value.
721   auto &Sec = cast<MCSectionELF>(Sym.getSection());
722   unsigned Flags = Sec.getFlags();
723   if (Flags & ELF::SHF_MERGE) {
724     if (C != 0)
725       return true;
726
727     // It looks like gold has a bug (http://sourceware.org/PR16794) and can
728     // only handle section relocations to mergeable sections if using RELA.
729     if (!hasRelocationAddend())
730       return true;
731   }
732
733   // Most TLS relocations use a got, so they need the symbol. Even those that
734   // are just an offset (@tpoff), require a symbol in gold versions before
735   // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
736   // http://sourceware.org/PR16773.
737   if (Flags & ELF::SHF_TLS)
738     return true;
739
740   // If the symbol is a thumb function the final relocation must set the lowest
741   // bit. With a symbol that is done by just having the symbol have that bit
742   // set, so we would lose the bit if we relocated with the section.
743   // FIXME: We could use the section but add the bit to the relocation value.
744   if (Asm.isThumbFunc(&Sym))
745     return true;
746
747   if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
748     return true;
749   return false;
750 }
751
752 static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
753   const MCSymbol &Sym = Ref.getSymbol();
754
755   if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
756     return &Sym;
757
758   if (!Sym.isVariable())
759     return nullptr;
760
761   const MCExpr *Expr = Sym.getVariableValue();
762   const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
763   if (!Inner)
764     return nullptr;
765
766   if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
767     return &Inner->getSymbol();
768   return nullptr;
769 }
770
771 static bool isWeak(const MCSymbolData &D) {
772   if (MCELF::GetType(D) == ELF::STT_GNU_IFUNC)
773     return true;
774
775   switch (MCELF::GetBinding(D)) {
776   default:
777     llvm_unreachable("Unknown binding");
778   case ELF::STB_LOCAL:
779     return false;
780   case ELF::STB_GLOBAL:
781     break;
782   case ELF::STB_WEAK:
783   case ELF::STB_GNU_UNIQUE:
784     return true;
785   }
786
787   const MCSymbol &Sym = D.getSymbol();
788   if (!Sym.isInSection())
789     return false;
790
791   const auto &Sec = cast<MCSectionELF>(Sym.getSection());
792   if (!Sec.getGroup())
793     return false;
794
795   // It is invalid to replace a reference to a global in a comdat
796   // with a reference to a local since out of comdat references
797   // to a local are forbidden.
798   // We could try to return false for more cases, like the reference
799   // being in the same comdat or Sym being an alias to another global,
800   // but it is not clear if it is worth the effort.
801   return true;
802 }
803
804 void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
805                                        const MCAsmLayout &Layout,
806                                        const MCFragment *Fragment,
807                                        const MCFixup &Fixup, MCValue Target,
808                                        bool &IsPCRel, uint64_t &FixedValue) {
809   const MCSectionData *FixupSection = Fragment->getParent();
810   uint64_t C = Target.getConstant();
811   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
812
813   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
814     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
815            "Should not have constructed this");
816
817     // Let A, B and C being the components of Target and R be the location of
818     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
819     // If it is pcrel, we want to compute (A - B + C - R).
820
821     // In general, ELF has no relocations for -B. It can only represent (A + C)
822     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
823     // replace B to implement it: (A - R - K + C)
824     if (IsPCRel)
825       Asm.getContext().FatalError(
826           Fixup.getLoc(),
827           "No relocation available to represent this relative expression");
828
829     const MCSymbol &SymB = RefB->getSymbol();
830
831     if (SymB.isUndefined())
832       Asm.getContext().FatalError(
833           Fixup.getLoc(),
834           Twine("symbol '") + SymB.getName() +
835               "' can not be undefined in a subtraction expression");
836
837     assert(!SymB.isAbsolute() && "Should have been folded");
838     const MCSection &SecB = SymB.getSection();
839     if (&SecB != &FixupSection->getSection())
840       Asm.getContext().FatalError(
841           Fixup.getLoc(), "Cannot represent a difference across sections");
842
843     const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
844     if (::isWeak(SymBD))
845       Asm.getContext().FatalError(
846           Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
847
848     uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
849     uint64_t K = SymBOffset - FixupOffset;
850     IsPCRel = true;
851     C -= K;
852   }
853
854   // We either rejected the fixup or folded B into C at this point.
855   const MCSymbolRefExpr *RefA = Target.getSymA();
856   const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
857   const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
858
859   unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
860   bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
861   if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
862     C += Layout.getSymbolOffset(SymAD);
863
864   uint64_t Addend = 0;
865   if (hasRelocationAddend()) {
866     Addend = C;
867     C = 0;
868   }
869
870   FixedValue = C;
871
872   // FIXME: What is this!?!?
873   MCSymbolRefExpr::VariantKind Modifier =
874       RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
875   if (RelocNeedsGOT(Modifier))
876     NeedsGOT = true;
877
878   if (!RelocateWithSymbol) {
879     const MCSection *SecA =
880         (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
881     auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
882     MCSymbol *SectionSymbol =
883         ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
884                : nullptr;
885     ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
886     Relocations[FixupSection].push_back(Rec);
887     return;
888   }
889
890   if (SymA) {
891     if (const MCSymbol *R = Renames.lookup(SymA))
892       SymA = R;
893
894     if (const MCSymbol *WeakRef = getWeakRef(*RefA))
895       WeakrefUsedInReloc.insert(WeakRef);
896     else
897       UsedInReloc.insert(SymA);
898   }
899   ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
900   Relocations[FixupSection].push_back(Rec);
901   return;
902 }
903
904
905 uint64_t
906 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
907                                              const MCSymbol *S) {
908   const MCSymbolData &SD = Asm.getSymbolData(*S);
909   return SD.getIndex();
910 }
911
912 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
913                                  const MCSymbolData &Data, bool Used,
914                                  bool Renamed) {
915   const MCSymbol &Symbol = Data.getSymbol();
916   if (Symbol.isVariable()) {
917     const MCExpr *Expr = Symbol.getVariableValue();
918     if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
919       if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
920         return false;
921     }
922   }
923
924   if (Used)
925     return true;
926
927   if (Renamed)
928     return false;
929
930   if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
931     return true;
932
933   if (Symbol.isVariable()) {
934     const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
935     if (Base && Base->isUndefined())
936       return false;
937   }
938
939   bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
940   if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
941     return false;
942
943   if (Symbol.isTemporary())
944     return false;
945
946   return true;
947 }
948
949 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
950   if (Data.isExternal())
951     return false;
952
953   const MCSymbol &Symbol = Data.getSymbol();
954   if (Symbol.isDefined())
955     return true;
956
957   if (isUsedInReloc)
958     return false;
959
960   return true;
961 }
962
963 void ELFObjectWriter::computeIndexMap(MCAssembler &Asm,
964                                       SectionIndexMapTy &SectionIndexMap) {
965   unsigned Index = 1;
966   for (MCAssembler::iterator it = Asm.begin(),
967          ie = Asm.end(); it != ie; ++it) {
968     const MCSectionELF &Section =
969       static_cast<const MCSectionELF &>(it->getSection());
970     if (Section.getType() != ELF::SHT_GROUP)
971       continue;
972     SectionIndexMap[&Section] = Index++;
973   }
974
975   std::vector<const MCSectionELF *> RelSections;
976
977   for (MCAssembler::iterator it = Asm.begin(),
978          ie = Asm.end(); it != ie; ++it) {
979     const MCSectionData &SD = *it;
980     const MCSectionELF &Section =
981       static_cast<const MCSectionELF &>(SD.getSection());
982     if (Section.getType() == ELF::SHT_GROUP ||
983         Section.getType() == ELF::SHT_REL ||
984         Section.getType() == ELF::SHT_RELA)
985       continue;
986     SectionIndexMap[&Section] = Index++;
987     if (MCSectionData *RelSD = createRelocationSection(Asm, SD)) {
988       const MCSectionELF *RelSection =
989           static_cast<const MCSectionELF *>(&RelSD->getSection());
990       RelSections.push_back(RelSection);
991     }
992   }
993
994   // Put relocation sections close together. The linker reads them
995   // first, so this improves cache locality.
996   for (const MCSectionELF * Sec: RelSections)
997     SectionIndexMap[Sec] = Index++;
998 }
999
1000 void ELFObjectWriter::computeSymbolTable(
1001     MCAssembler &Asm, const MCAsmLayout &Layout,
1002     const SectionIndexMapTy &SectionIndexMap,
1003     const RevGroupMapTy &RevGroupMap) {
1004   // FIXME: Is this the correct place to do this?
1005   // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
1006   if (NeedsGOT) {
1007     StringRef Name = "_GLOBAL_OFFSET_TABLE_";
1008     MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
1009     MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
1010     Data.setExternal(true);
1011     MCELF::SetBinding(Data, ELF::STB_GLOBAL);
1012   }
1013
1014   // Add the data for the symbols.
1015   for (MCSymbolData &SD : Asm.symbols()) {
1016     const MCSymbol &Symbol = SD.getSymbol();
1017
1018     bool Used = UsedInReloc.count(&Symbol);
1019     bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
1020     bool isSignature = RevGroupMap.count(&Symbol);
1021
1022     if (!isInSymtab(Layout, SD,
1023                     Used || WeakrefUsed || isSignature,
1024                     Renames.count(&Symbol)))
1025       continue;
1026
1027     ELFSymbolData MSD;
1028     MSD.SymbolData = &SD;
1029     const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
1030
1031     // Undefined symbols are global, but this is the first place we
1032     // are able to set it.
1033     bool Local = isLocal(SD, Used);
1034     if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
1035       assert(BaseSymbol);
1036       MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
1037       MCELF::SetBinding(SD, ELF::STB_GLOBAL);
1038       MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
1039     }
1040
1041     if (!BaseSymbol) {
1042       MSD.SectionIndex = ELF::SHN_ABS;
1043     } else if (SD.isCommon()) {
1044       assert(!Local);
1045       MSD.SectionIndex = ELF::SHN_COMMON;
1046     } else if (BaseSymbol->isUndefined()) {
1047       if (isSignature && !Used)
1048         MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap.lookup(&Symbol));
1049       else
1050         MSD.SectionIndex = ELF::SHN_UNDEF;
1051       if (!Used && WeakrefUsed)
1052         MCELF::SetBinding(SD, ELF::STB_WEAK);
1053     } else {
1054       const MCSectionELF &Section =
1055         static_cast<const MCSectionELF&>(BaseSymbol->getSection());
1056       MSD.SectionIndex = SectionIndexMap.lookup(&Section);
1057       assert(MSD.SectionIndex && "Invalid section index!");
1058     }
1059
1060     // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1061     // in defined ones.
1062     //
1063     // FIXME: All name handling should be done before we get to the writer,
1064     // including dealing with GNU-style version suffixes.  Fixing this isn't
1065     // trivial.
1066     //
1067     // We thus have to be careful to not perform the symbol version replacement
1068     // blindly:
1069     //
1070     // The ELF format is used on Windows by the MCJIT engine.  Thus, on
1071     // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1072     // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1073     // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1074     // the EFLObjectWriter should not interpret the "@@@" sub-string as
1075     // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1076     // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1077     // "__imp_?" or "__imp_@?".
1078     //
1079     // It would have been interesting to perform the MS mangling prefix check
1080     // only when the target triple is of the form *-pc-windows-elf. But, it
1081     // seems that this information is not easily accessible from the
1082     // ELFObjectWriter.
1083     StringRef Name = Symbol.getName();
1084     if (!Name.startswith("?") && !Name.startswith("@?") &&
1085         !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1086       // This symbol isn't following the MSVC C++ name mangling convention. We
1087       // can thus safely interpret the @@@ in symbol names as specifying symbol
1088       // versioning.
1089       SmallString<32> Buf;
1090       size_t Pos = Name.find("@@@");
1091       if (Pos != StringRef::npos) {
1092         Buf += Name.substr(0, Pos);
1093         unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1094         Buf += Name.substr(Pos + Skip);
1095         Name = Buf;
1096       }
1097     }
1098
1099     // Sections have their own string table
1100     if (MCELF::GetType(SD) != ELF::STT_SECTION)
1101       MSD.Name = StrTabBuilder.add(Name);
1102
1103     if (MSD.SectionIndex == ELF::SHN_UNDEF)
1104       UndefinedSymbolData.push_back(MSD);
1105     else if (Local)
1106       LocalSymbolData.push_back(MSD);
1107     else
1108       ExternalSymbolData.push_back(MSD);
1109   }
1110
1111   for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1112     StrTabBuilder.add(*i);
1113
1114   StrTabBuilder.finalize(StringTableBuilder::ELF);
1115
1116   for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1117     FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1118
1119   for (ELFSymbolData &MSD : LocalSymbolData)
1120     MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1121                           ? 0
1122                           : StrTabBuilder.getOffset(MSD.Name);
1123   for (ELFSymbolData &MSD : ExternalSymbolData)
1124     MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1125   for (ELFSymbolData& MSD : UndefinedSymbolData)
1126     MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1127
1128   // Symbols are required to be in lexicographic order.
1129   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1130   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1131   array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1132
1133   // Set the symbol indices. Local symbols must come before all other
1134   // symbols with non-local bindings.
1135   unsigned Index = FileSymbolData.size() + 1;
1136   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1137     LocalSymbolData[i].SymbolData->setIndex(Index++);
1138
1139   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1140     ExternalSymbolData[i].SymbolData->setIndex(Index++);
1141   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1142     UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1143 }
1144
1145 MCSectionData *
1146 ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
1147                                          const MCSectionData &SD) {
1148   if (Relocations[&SD].empty())
1149     return nullptr;
1150
1151   MCContext &Ctx = Asm.getContext();
1152   const MCSectionELF &Section =
1153       static_cast<const MCSectionELF &>(SD.getSection());
1154
1155   const StringRef SectionName = Section.getSectionName();
1156   std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1157   RelaSectionName += SectionName;
1158
1159   unsigned EntrySize;
1160   if (hasRelocationAddend())
1161     EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1162   else
1163     EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1164
1165   unsigned Flags = 0;
1166   if (Section.getFlags() & ELF::SHF_GROUP)
1167     Flags = ELF::SHF_GROUP;
1168
1169   const MCSectionELF *RelaSection = Ctx.createELFRelSection(
1170       RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
1171       Flags, EntrySize, Section.getGroup(), &Section);
1172   return &Asm.getOrCreateSectionData(*RelaSection);
1173 }
1174
1175 static SmallVector<char, 128>
1176 getUncompressedData(MCAsmLayout &Layout,
1177                     MCSectionData::FragmentListType &Fragments) {
1178   SmallVector<char, 128> UncompressedData;
1179   for (const MCFragment &F : Fragments) {
1180     const SmallVectorImpl<char> *Contents;
1181     switch (F.getKind()) {
1182     case MCFragment::FT_Data:
1183       Contents = &cast<MCDataFragment>(F).getContents();
1184       break;
1185     case MCFragment::FT_Dwarf:
1186       Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1187       break;
1188     case MCFragment::FT_DwarfFrame:
1189       Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1190       break;
1191     default:
1192       llvm_unreachable(
1193           "Not expecting any other fragment types in a debug_* section");
1194     }
1195     UncompressedData.append(Contents->begin(), Contents->end());
1196   }
1197   return UncompressedData;
1198 }
1199
1200 // Include the debug info compression header:
1201 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1202 // useful for consumers to preallocate a buffer to decompress into.
1203 static bool
1204 prependCompressionHeader(uint64_t Size,
1205                          SmallVectorImpl<char> &CompressedContents) {
1206   const StringRef Magic = "ZLIB";
1207   if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1208     return false;
1209   if (sys::IsLittleEndianHost)
1210     sys::swapByteOrder(Size);
1211   CompressedContents.insert(CompressedContents.begin(),
1212                             Magic.size() + sizeof(Size), 0);
1213   std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1214   std::copy(reinterpret_cast<char *>(&Size),
1215             reinterpret_cast<char *>(&Size + 1),
1216             CompressedContents.begin() + Magic.size());
1217   return true;
1218 }
1219
1220 // Return a single fragment containing the compressed contents of the whole
1221 // section. Null if the section was not compressed for any reason.
1222 static std::unique_ptr<MCDataFragment>
1223 getCompressedFragment(MCAsmLayout &Layout,
1224                       MCSectionData::FragmentListType &Fragments) {
1225   std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1226
1227   // Gather the uncompressed data from all the fragments, recording the
1228   // alignment fragment, if seen, and any fixups.
1229   SmallVector<char, 128> UncompressedData =
1230       getUncompressedData(Layout, Fragments);
1231
1232   SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1233
1234   zlib::Status Success = zlib::compress(
1235       StringRef(UncompressedData.data(), UncompressedData.size()),
1236       CompressedContents);
1237   if (Success != zlib::StatusOK)
1238     return nullptr;
1239
1240   if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1241     return nullptr;
1242
1243   return CompressedFragment;
1244 }
1245
1246 typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1247 DefiningSymbolMap;
1248
1249 static void UpdateSymbols(const MCAsmLayout &Layout,
1250                           const std::vector<MCSymbolData *> &Symbols,
1251                           MCFragment &NewFragment) {
1252   for (MCSymbolData *Sym : Symbols) {
1253     Sym->setOffset(Sym->getOffset() +
1254                    Layout.getFragmentOffset(Sym->getFragment()));
1255     Sym->setFragment(&NewFragment);
1256   }
1257 }
1258
1259 static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
1260                                  const DefiningSymbolMap &DefiningSymbols,
1261                                  const MCSectionELF &Section,
1262                                  MCSectionData &SD) {
1263   StringRef SectionName = Section.getSectionName();
1264   MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1265
1266   std::unique_ptr<MCDataFragment> CompressedFragment =
1267       getCompressedFragment(Layout, Fragments);
1268
1269   // Leave the section as-is if the fragments could not be compressed.
1270   if (!CompressedFragment)
1271     return;
1272
1273   // Update the fragment+offsets of any symbols referring to fragments in this
1274   // section to refer to the new fragment.
1275   auto I = DefiningSymbols.find(&SD);
1276   if (I != DefiningSymbols.end())
1277     UpdateSymbols(Layout, I->second, *CompressedFragment);
1278
1279   // Invalidate the layout for the whole section since it will have new and
1280   // different fragments now.
1281   Layout.invalidateFragmentsFrom(&Fragments.front());
1282   Fragments.clear();
1283
1284   // Complete the initialization of the new fragment
1285   CompressedFragment->setParent(&SD);
1286   CompressedFragment->setLayoutOrder(0);
1287   Fragments.push_back(CompressedFragment.release());
1288
1289   // Rename from .debug_* to .zdebug_*
1290   Asm.getContext().renameELFSection(&Section,
1291                                     (".z" + SectionName.drop_front(1)).str());
1292 }
1293
1294 void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1295                                             MCAsmLayout &Layout) {
1296   if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1297     return;
1298
1299   DefiningSymbolMap DefiningSymbols;
1300
1301   for (MCSymbolData &SD : Asm.symbols())
1302     if (MCFragment *F = SD.getFragment())
1303       DefiningSymbols[F->getParent()].push_back(&SD);
1304
1305   for (MCSectionData &SD : Asm) {
1306     const MCSectionELF &Section =
1307         static_cast<const MCSectionELF &>(SD.getSection());
1308     StringRef SectionName = Section.getSectionName();
1309
1310     // Compressing debug_frame requires handling alignment fragments which is
1311     // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1312     // for writing to arbitrary buffers) for little benefit.
1313     if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1314       continue;
1315
1316     CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
1317   }
1318 }
1319
1320 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
1321   for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1322     MCSectionData &RelSD = *it;
1323     const MCSectionELF &RelSection =
1324         static_cast<const MCSectionELF &>(RelSD.getSection());
1325
1326     unsigned Type = RelSection.getType();
1327     if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
1328       continue;
1329
1330     const MCSectionELF *Section = RelSection.getAssociatedSection();
1331     MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1332     RelSD.setAlignment(is64Bit() ? 8 : 4);
1333
1334     MCDataFragment *F = new MCDataFragment(&RelSD);
1335     WriteRelocationsFragment(Asm, F, &SD);
1336   }
1337 }
1338
1339 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1340                                        uint64_t Flags, uint64_t Address,
1341                                        uint64_t Offset, uint64_t Size,
1342                                        uint32_t Link, uint32_t Info,
1343                                        uint64_t Alignment,
1344                                        uint64_t EntrySize) {
1345   Write32(Name);        // sh_name: index into string table
1346   Write32(Type);        // sh_type
1347   WriteWord(Flags);     // sh_flags
1348   WriteWord(Address);   // sh_addr
1349   WriteWord(Offset);    // sh_offset
1350   WriteWord(Size);      // sh_size
1351   Write32(Link);        // sh_link
1352   Write32(Info);        // sh_info
1353   WriteWord(Alignment); // sh_addralign
1354   WriteWord(EntrySize); // sh_entsize
1355 }
1356
1357 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1358                                                MCDataFragment *F,
1359                                                const MCSectionData *SD) {
1360   std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1361
1362   // Sort the relocation entries. Most targets just sort by Offset, but some
1363   // (e.g., MIPS) have additional constraints.
1364   TargetObjectWriter->sortRelocs(Asm, Relocs);
1365
1366   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1367     const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1368     unsigned Index =
1369         Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
1370
1371     if (is64Bit()) {
1372       write(*F, Entry.Offset);
1373       if (TargetObjectWriter->isN64()) {
1374         write(*F, uint32_t(Index));
1375
1376         write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1377         write(*F, TargetObjectWriter->getRType3(Entry.Type));
1378         write(*F, TargetObjectWriter->getRType2(Entry.Type));
1379         write(*F, TargetObjectWriter->getRType(Entry.Type));
1380       } else {
1381         struct ELF::Elf64_Rela ERE64;
1382         ERE64.setSymbolAndType(Index, Entry.Type);
1383         write(*F, ERE64.r_info);
1384       }
1385       if (hasRelocationAddend())
1386         write(*F, Entry.Addend);
1387     } else {
1388       write(*F, uint32_t(Entry.Offset));
1389
1390       struct ELF::Elf32_Rela ERE32;
1391       ERE32.setSymbolAndType(Index, Entry.Type);
1392       write(*F, ERE32.r_info);
1393
1394       if (hasRelocationAddend())
1395         write(*F, uint32_t(Entry.Addend));
1396     }
1397   }
1398 }
1399
1400 void ELFObjectWriter::CreateMetadataSections(
1401     MCAssembler &Asm, MCAsmLayout &Layout, SectionIndexMapTy &SectionIndexMap) {
1402   MCContext &Ctx = Asm.getContext();
1403   MCDataFragment *F;
1404
1405   unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1406
1407   // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1408   const MCSectionELF *ShstrtabSection =
1409       Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
1410   MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1411   ShstrtabSD.setAlignment(1);
1412   ShstrtabIndex = SectionIndexMap.size() + 1;
1413   SectionIndexMap[ShstrtabSection] = ShstrtabIndex;
1414
1415   const MCSectionELF *SymtabSection =
1416     Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1417                       EntrySize, "");
1418   MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1419   SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1420   SymbolTableIndex = SectionIndexMap.size() + 1;
1421   SectionIndexMap[SymtabSection] = SymbolTableIndex;
1422
1423   const MCSectionELF *StrtabSection;
1424   StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1425   MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1426   StrtabSD.setAlignment(1);
1427   StringTableIndex = SectionIndexMap.size() + 1;
1428   SectionIndexMap[StrtabSection] = StringTableIndex;
1429
1430   // Symbol table
1431   F = new MCDataFragment(&SymtabSD);
1432   WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
1433
1434   F = new MCDataFragment(&StrtabSD);
1435   F->getContents().append(StrTabBuilder.data().begin(),
1436                           StrTabBuilder.data().end());
1437
1438   F = new MCDataFragment(&ShstrtabSD);
1439
1440   // Section header string table.
1441   for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1442     const MCSectionELF &Section =
1443       static_cast<const MCSectionELF&>(it->getSection());
1444     ShStrTabBuilder.add(Section.getSectionName());
1445   }
1446   ShStrTabBuilder.finalize(StringTableBuilder::ELF);
1447   F->getContents().append(ShStrTabBuilder.data().begin(),
1448                           ShStrTabBuilder.data().end());
1449 }
1450
1451 void ELFObjectWriter::createIndexedSections(
1452     MCAssembler &Asm, MCAsmLayout &Layout, GroupMapTy &GroupMap,
1453     RevGroupMapTy &RevGroupMap, SectionIndexMapTy &SectionIndexMap) {
1454   MCContext &Ctx = Asm.getContext();
1455
1456   // Build the groups
1457   for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1458        it != ie; ++it) {
1459     const MCSectionELF &Section =
1460       static_cast<const MCSectionELF&>(it->getSection());
1461     if (!(Section.getFlags() & ELF::SHF_GROUP))
1462       continue;
1463
1464     const MCSymbol *SignatureSymbol = Section.getGroup();
1465     Asm.getOrCreateSymbolData(*SignatureSymbol);
1466     const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1467     if (!Group) {
1468       Group = Ctx.CreateELFGroupSection();
1469       MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1470       Data.setAlignment(4);
1471       MCDataFragment *F = new MCDataFragment(&Data);
1472       write(*F, uint32_t(ELF::GRP_COMDAT));
1473     }
1474     GroupMap[Group] = SignatureSymbol;
1475   }
1476
1477   computeIndexMap(Asm, SectionIndexMap);
1478
1479   // Add sections to the groups
1480   for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1481        it != ie; ++it) {
1482     const MCSectionELF &Section =
1483       static_cast<const MCSectionELF&>(it->getSection());
1484     if (!(Section.getFlags() & ELF::SHF_GROUP))
1485       continue;
1486     const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1487     MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1488     // FIXME: we could use the previous fragment
1489     MCDataFragment *F = new MCDataFragment(&Data);
1490     uint32_t Index = SectionIndexMap.lookup(&Section);
1491     write(*F, Index);
1492   }
1493 }
1494
1495 void ELFObjectWriter::writeSection(MCAssembler &Asm,
1496                                    const SectionIndexMapTy &SectionIndexMap,
1497                                    uint32_t GroupSymbolIndex,
1498                                    uint64_t Offset, uint64_t Size,
1499                                    uint64_t Alignment,
1500                                    const MCSectionELF &Section) {
1501   uint64_t sh_link = 0;
1502   uint64_t sh_info = 0;
1503
1504   switch(Section.getType()) {
1505   default:
1506     // Nothing to do.
1507     break;
1508
1509   case ELF::SHT_DYNAMIC:
1510     sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
1511     break;
1512
1513   case ELF::SHT_REL:
1514   case ELF::SHT_RELA: {
1515     sh_link = SymbolTableIndex;
1516     assert(sh_link && ".symtab not found");
1517     const MCSectionELF *InfoSection = Section.getAssociatedSection();
1518     sh_info = SectionIndexMap.lookup(InfoSection);
1519     break;
1520   }
1521
1522   case ELF::SHT_SYMTAB:
1523   case ELF::SHT_DYNSYM:
1524     sh_link = StringTableIndex;
1525     sh_info = LastLocalSymbolIndex;
1526     break;
1527
1528   case ELF::SHT_SYMTAB_SHNDX:
1529     sh_link = SymbolTableIndex;
1530     break;
1531
1532   case ELF::SHT_GROUP:
1533     sh_link = SymbolTableIndex;
1534     sh_info = GroupSymbolIndex;
1535     break;
1536   }
1537
1538   if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1539       Section.getType() == ELF::SHT_ARM_EXIDX)
1540     sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1541
1542   WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1543                    Section.getType(),
1544                    Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1545                    Alignment, Section.getEntrySize());
1546 }
1547
1548 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1549   return SD.getOrdinal() == ~UINT32_C(0) &&
1550     !SD.getSection().isVirtualSection();
1551 }
1552
1553 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1554   uint64_t Ret = 0;
1555   for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1556        ++i) {
1557     const MCFragment &F = *i;
1558     assert(F.getKind() == MCFragment::FT_Data);
1559     Ret += cast<MCDataFragment>(F).getContents().size();
1560   }
1561   return Ret;
1562 }
1563
1564 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1565                                                 const MCSectionData &SD) {
1566   if (IsELFMetaDataSection(SD))
1567     return DataSectionSize(SD);
1568   return Layout.getSectionAddressSize(&SD);
1569 }
1570
1571 void ELFObjectWriter::writeDataSectionData(MCAssembler &Asm,
1572                                            const MCAsmLayout &Layout,
1573                                            const MCSectionData &SD) {
1574   if (IsELFMetaDataSection(SD)) {
1575     for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1576          ++i) {
1577       const MCFragment &F = *i;
1578       assert(F.getKind() == MCFragment::FT_Data);
1579       WriteBytes(cast<MCDataFragment>(F).getContents());
1580     }
1581   } else {
1582     Asm.writeSectionData(&SD, Layout);
1583   }
1584 }
1585
1586 void ELFObjectWriter::writeSectionHeader(
1587     ArrayRef<const MCSectionELF *> Sections, MCAssembler &Asm,
1588     const GroupMapTy &GroupMap, const MCAsmLayout &Layout,
1589     const SectionIndexMapTy &SectionIndexMap,
1590     const SectionOffsetMapTy &SectionOffsetMap) {
1591   const unsigned NumSections = Asm.size();
1592
1593   // Null section first.
1594   uint64_t FirstSectionSize =
1595       (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
1596   uint32_t FirstSectionLink =
1597     ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1598   WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1599
1600   for (unsigned i = 0; i < NumSections; ++i) {
1601     const MCSectionELF &Section = *Sections[i];
1602     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1603     uint32_t GroupSymbolIndex;
1604     if (Section.getType() != ELF::SHT_GROUP)
1605       GroupSymbolIndex = 0;
1606     else
1607       GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1608                                                      GroupMap.lookup(&Section));
1609
1610     uint64_t Size = GetSectionAddressSize(Layout, SD);
1611
1612     writeSection(Asm, SectionIndexMap, GroupSymbolIndex,
1613                  SectionOffsetMap.lookup(&Section), Size, SD.getAlignment(),
1614                  Section);
1615   }
1616 }
1617
1618 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1619                                   const MCAsmLayout &Layout) {
1620   GroupMapTy GroupMap;
1621   RevGroupMapTy RevGroupMap;
1622   SectionIndexMapTy SectionIndexMap;
1623
1624   CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
1625   createIndexedSections(Asm, const_cast<MCAsmLayout &>(Layout), GroupMap,
1626                         RevGroupMap, SectionIndexMap);
1627
1628   // Compute symbol table information.
1629   computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
1630
1631   WriteRelocations(Asm, const_cast<MCAsmLayout &>(Layout));
1632
1633   CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1634                          const_cast<MCAsmLayout&>(Layout),
1635                          SectionIndexMap);
1636
1637   unsigned NumSections = Asm.size();
1638   std::vector<const MCSectionELF*> Sections;
1639   Sections.resize(NumSections);
1640
1641   for (auto &Pair : SectionIndexMap)
1642     Sections[Pair.second - 1] = Pair.first;
1643
1644   SectionOffsetMapTy SectionOffsetMap;
1645
1646   // Write out the ELF header ...
1647   WriteHeader(Asm, NumSections + 1);
1648
1649   // ... then the sections ...
1650   for (unsigned i = 0; i < NumSections; ++i) {
1651     const MCSectionELF &Section = *Sections[i];
1652     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1653     uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1654     WriteZeros(Padding);
1655
1656     // Remember the offset into the file for this section.
1657     SectionOffsetMap[&Section] = OS.tell();
1658
1659     writeDataSectionData(Asm, Layout, SD);
1660   }
1661
1662   uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1663   uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1664   WriteZeros(Padding);
1665
1666   const unsigned SectionHeaderOffset = OS.tell();
1667
1668   // ... then the section header table ...
1669   writeSectionHeader(Sections, Asm, GroupMap, Layout, SectionIndexMap,
1670                      SectionOffsetMap);
1671
1672   if (is64Bit()) {
1673     uint64_t Val = SectionHeaderOffset;
1674     if (sys::IsLittleEndianHost != IsLittleEndian)
1675       sys::swapByteOrder(Val);
1676     OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1677               offsetof(ELF::Elf64_Ehdr, e_shoff));
1678   } else {
1679     uint32_t Val = SectionHeaderOffset;
1680     if (sys::IsLittleEndianHost != IsLittleEndian)
1681       sys::swapByteOrder(Val);
1682     OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1683               offsetof(ELF::Elf32_Ehdr, e_shoff));
1684   }
1685 }
1686
1687 bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1688     const MCAssembler &Asm, const MCSymbolData &DataA,
1689     const MCSymbolData *DataB, const MCFragment &FB, bool InSet,
1690     bool IsPCRel) const {
1691   if (!InSet && (::isWeak(DataA) || (DataB && ::isWeak(*DataB))))
1692     return false;
1693   return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1694       Asm, DataA, DataB, FB, InSet, IsPCRel);
1695 }
1696
1697 bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
1698   return ::isWeak(SD);
1699 }
1700
1701 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1702                                             raw_pwrite_stream &OS,
1703                                             bool IsLittleEndian) {
1704   return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
1705 }