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