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