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