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