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