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