Make a few MCSectionELF& variables const. NFC.
[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()->getSection() ==
495            &MSD.Symbol->getSection())) &&
496          "The symbol's section doesn't match the fragment's symbol");
497   const MCSymbol *Base = Layout.getBaseSymbol(*MSD.Symbol);
498
499   // This has to be in sync with when computeSymbolTable uses SHN_ABS or
500   // SHN_COMMON.
501   bool IsReserved = !Base || OrigData.isCommon();
502
503   // Binding and Type share the same byte as upper and lower nibbles
504   uint8_t Binding = MCELF::GetBinding(OrigData);
505   uint8_t Type = MCELF::GetType(OrigData);
506   MCSymbolData *BaseSD = nullptr;
507   if (Base) {
508     BaseSD = &Layout.getAssembler().getSymbolData(*Base);
509     Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
510   }
511   uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
512
513   // Other and Visibility share the same byte with Visibility using the lower
514   // 2 bits
515   uint8_t Visibility = MCELF::GetVisibility(OrigData);
516   uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
517   Other |= Visibility;
518
519   uint64_t Value = SymbolValue(*MSD.Symbol, Layout);
520   uint64_t Size = 0;
521
522   const MCExpr *ESize = OrigData.getSize();
523   if (!ESize && Base)
524     ESize = BaseSD->getSize();
525
526   if (ESize) {
527     int64_t Res;
528     if (!ESize->evaluateKnownAbsolute(Res, Layout))
529       report_fatal_error("Size expression must be absolute.");
530     Size = Res;
531   }
532
533   // Write out the symbol table entry
534   Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
535                      MSD.SectionIndex, IsReserved);
536 }
537
538 void ELFObjectWriter::writeSymbolTable(MCContext &Ctx,
539                                        const MCAsmLayout &Layout,
540                                        SectionOffsetsTy &SectionOffsets) {
541   const MCSectionELF *SymtabSection = SectionTable[SymbolTableIndex - 1];
542
543   // The string table must be emitted first because we need the index
544   // into the string table for all the symbol names.
545
546   SymbolTableWriter Writer(*this, is64Bit());
547
548   uint64_t Padding =
549       OffsetToAlignment(OS.tell(), SymtabSection->getAlignment());
550   WriteZeros(Padding);
551
552   uint64_t SecStart = OS.tell();
553
554   // The first entry is the undefined symbol entry.
555   Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
556
557   for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
558     Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
559                        ELF::STV_DEFAULT, ELF::SHN_ABS, true);
560   }
561
562   // Write the symbol table entries.
563   LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
564
565   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
566     ELFSymbolData &MSD = LocalSymbolData[i];
567     WriteSymbol(Writer, MSD, Layout);
568   }
569
570   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
571     ELFSymbolData &MSD = ExternalSymbolData[i];
572     MCSymbolData &Data = MSD.Symbol->getData();
573     assert(((Data.getFlags() & ELF_STB_Global) ||
574             (Data.getFlags() & ELF_STB_Weak)) &&
575            "External symbol requires STB_GLOBAL or STB_WEAK flag");
576     WriteSymbol(Writer, MSD, Layout);
577     if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
578       LastLocalSymbolIndex++;
579   }
580
581   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
582     ELFSymbolData &MSD = UndefinedSymbolData[i];
583     MCSymbolData &Data = MSD.Symbol->getData();
584     WriteSymbol(Writer, MSD, Layout);
585     if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
586       LastLocalSymbolIndex++;
587   }
588
589   uint64_t SecEnd = OS.tell();
590   SectionOffsets[SymtabSection] = std::make_pair(SecStart, SecEnd);
591
592   ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes();
593   if (ShndxIndexes.empty()) {
594     assert(SymtabShndxSectionIndex == 0);
595     return;
596   }
597   assert(SymtabShndxSectionIndex != 0);
598
599   SecStart = OS.tell();
600   const MCSectionELF *SymtabShndxSection =
601       SectionTable[SymtabShndxSectionIndex - 1];
602   for (uint32_t Index : ShndxIndexes)
603     write(Index);
604   SecEnd = OS.tell();
605   SectionOffsets[SymtabShndxSection] = std::make_pair(SecStart, SecEnd);
606 }
607
608 // It is always valid to create a relocation with a symbol. It is preferable
609 // to use a relocation with a section if that is possible. Using the section
610 // allows us to omit some local symbols from the symbol table.
611 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
612                                                const MCSymbolRefExpr *RefA,
613                                                const MCSymbol *Sym, uint64_t C,
614                                                unsigned Type) const {
615   MCSymbolData *SD = Sym ? &Sym->getData() : nullptr;
616
617   // A PCRel relocation to an absolute value has no symbol (or section). We
618   // represent that with a relocation to a null section.
619   if (!RefA)
620     return false;
621
622   MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
623   switch (Kind) {
624   default:
625     break;
626   // The .odp creation emits a relocation against the symbol ".TOC." which
627   // create a R_PPC64_TOC relocation. However the relocation symbol name
628   // in final object creation should be NULL, since the symbol does not
629   // really exist, it is just the reference to TOC base for the current
630   // object file. Since the symbol is undefined, returning false results
631   // in a relocation with a null section which is the desired result.
632   case MCSymbolRefExpr::VK_PPC_TOCBASE:
633     return false;
634
635   // These VariantKind cause the relocation to refer to something other than
636   // the symbol itself, like a linker generated table. Since the address of
637   // symbol is not relevant, we cannot replace the symbol with the
638   // section and patch the difference in the addend.
639   case MCSymbolRefExpr::VK_GOT:
640   case MCSymbolRefExpr::VK_PLT:
641   case MCSymbolRefExpr::VK_GOTPCREL:
642   case MCSymbolRefExpr::VK_Mips_GOT:
643   case MCSymbolRefExpr::VK_PPC_GOT_LO:
644   case MCSymbolRefExpr::VK_PPC_GOT_HI:
645   case MCSymbolRefExpr::VK_PPC_GOT_HA:
646     return true;
647   }
648
649   // An undefined symbol is not in any section, so the relocation has to point
650   // to the symbol itself.
651   assert(Sym && "Expected a symbol");
652   if (Sym->isUndefined())
653     return true;
654
655   unsigned Binding = MCELF::GetBinding(*SD);
656   switch(Binding) {
657   default:
658     llvm_unreachable("Invalid Binding");
659   case ELF::STB_LOCAL:
660     break;
661   case ELF::STB_WEAK:
662     // If the symbol is weak, it might be overridden by a symbol in another
663     // file. The relocation has to point to the symbol so that the linker
664     // can update it.
665     return true;
666   case ELF::STB_GLOBAL:
667     // Global ELF symbols can be preempted by the dynamic linker. The relocation
668     // has to point to the symbol for a reason analogous to the STB_WEAK case.
669     return true;
670   }
671
672   // If a relocation points to a mergeable section, we have to be careful.
673   // If the offset is zero, a relocation with the section will encode the
674   // same information. With a non-zero offset, the situation is different.
675   // For example, a relocation can point 42 bytes past the end of a string.
676   // If we change such a relocation to use the section, the linker would think
677   // that it pointed to another string and subtracting 42 at runtime will
678   // produce the wrong value.
679   auto &Sec = cast<MCSectionELF>(Sym->getSection());
680   unsigned Flags = Sec.getFlags();
681   if (Flags & ELF::SHF_MERGE) {
682     if (C != 0)
683       return true;
684
685     // It looks like gold has a bug (http://sourceware.org/PR16794) and can
686     // only handle section relocations to mergeable sections if using RELA.
687     if (!hasRelocationAddend())
688       return true;
689   }
690
691   // Most TLS relocations use a got, so they need the symbol. Even those that
692   // are just an offset (@tpoff), require a symbol in gold versions before
693   // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
694   // http://sourceware.org/PR16773.
695   if (Flags & ELF::SHF_TLS)
696     return true;
697
698   // If the symbol is a thumb function the final relocation must set the lowest
699   // bit. With a symbol that is done by just having the symbol have that bit
700   // set, so we would lose the bit if we relocated with the section.
701   // FIXME: We could use the section but add the bit to the relocation value.
702   if (Asm.isThumbFunc(Sym))
703     return true;
704
705   if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
706     return true;
707   return false;
708 }
709
710 static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
711   const MCSymbol &Sym = Ref.getSymbol();
712
713   if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
714     return &Sym;
715
716   if (!Sym.isVariable())
717     return nullptr;
718
719   const MCExpr *Expr = Sym.getVariableValue();
720   const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
721   if (!Inner)
722     return nullptr;
723
724   if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
725     return &Inner->getSymbol();
726   return nullptr;
727 }
728
729 // True if the assembler knows nothing about the final value of the symbol.
730 // This doesn't cover the comdat issues, since in those cases the assembler
731 // can at least know that all symbols in the section will move together.
732 static bool isWeak(const MCSymbolData &D) {
733   if (MCELF::GetType(D) == ELF::STT_GNU_IFUNC)
734     return true;
735
736   switch (MCELF::GetBinding(D)) {
737   default:
738     llvm_unreachable("Unknown binding");
739   case ELF::STB_LOCAL:
740     return false;
741   case ELF::STB_GLOBAL:
742     return false;
743   case ELF::STB_WEAK:
744   case ELF::STB_GNU_UNIQUE:
745     return true;
746   }
747 }
748
749 void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
750                                        const MCAsmLayout &Layout,
751                                        const MCFragment *Fragment,
752                                        const MCFixup &Fixup, MCValue Target,
753                                        bool &IsPCRel, uint64_t &FixedValue) {
754   const MCSectionData *FixupSectionD = Fragment->getParent();
755   const MCSectionELF &FixupSection =
756       cast<MCSectionELF>(FixupSectionD->getSection());
757   uint64_t C = Target.getConstant();
758   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
759
760   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
761     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
762            "Should not have constructed this");
763
764     // Let A, B and C being the components of Target and R be the location of
765     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
766     // If it is pcrel, we want to compute (A - B + C - R).
767
768     // In general, ELF has no relocations for -B. It can only represent (A + C)
769     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
770     // replace B to implement it: (A - R - K + C)
771     if (IsPCRel)
772       Asm.getContext().reportFatalError(
773           Fixup.getLoc(),
774           "No relocation available to represent this relative expression");
775
776     const MCSymbol &SymB = RefB->getSymbol();
777
778     if (SymB.isUndefined())
779       Asm.getContext().reportFatalError(
780           Fixup.getLoc(),
781           Twine("symbol '") + SymB.getName() +
782               "' can not be undefined in a subtraction expression");
783
784     assert(!SymB.isAbsolute() && "Should have been folded");
785     const MCSection &SecB = SymB.getSection();
786     if (&SecB != &FixupSection)
787       Asm.getContext().reportFatalError(
788           Fixup.getLoc(), "Cannot represent a difference across sections");
789
790     if (::isWeak(SymB.getData()))
791       Asm.getContext().reportFatalError(
792           Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
793
794     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
795     uint64_t K = SymBOffset - FixupOffset;
796     IsPCRel = true;
797     C -= K;
798   }
799
800   // We either rejected the fixup or folded B into C at this point.
801   const MCSymbolRefExpr *RefA = Target.getSymA();
802   const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
803
804   unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
805   bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymA, C, Type);
806   if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
807     C += Layout.getSymbolOffset(*SymA);
808
809   uint64_t Addend = 0;
810   if (hasRelocationAddend()) {
811     Addend = C;
812     C = 0;
813   }
814
815   FixedValue = C;
816
817   // FIXME: What is this!?!?
818   MCSymbolRefExpr::VariantKind Modifier =
819       RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
820   if (RelocNeedsGOT(Modifier))
821     NeedsGOT = true;
822
823   if (!RelocateWithSymbol) {
824     const MCSection *SecA =
825         (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
826     auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
827     MCSymbol *SectionSymbol =
828         ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
829                : nullptr;
830     ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
831     Relocations[&FixupSection].push_back(Rec);
832     return;
833   }
834
835   if (SymA) {
836     if (const MCSymbol *R = Renames.lookup(SymA))
837       SymA = R;
838
839     if (const MCSymbol *WeakRef = getWeakRef(*RefA))
840       WeakrefUsedInReloc.insert(WeakRef);
841     else
842       UsedInReloc.insert(SymA);
843   }
844   ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
845   Relocations[&FixupSection].push_back(Rec);
846   return;
847 }
848
849
850 uint64_t
851 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
852                                              const MCSymbol *S) {
853   assert(S->hasData());
854   return S->getIndex();
855 }
856
857 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
858                                  const MCSymbol &Symbol, bool Used,
859                                  bool Renamed) {
860   const MCSymbolData &Data = Symbol.getData();
861   if (Symbol.isVariable()) {
862     const MCExpr *Expr = Symbol.getVariableValue();
863     if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
864       if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
865         return false;
866     }
867   }
868
869   if (Used)
870     return true;
871
872   if (Renamed)
873     return false;
874
875   if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
876     return true;
877
878   if (Symbol.isVariable()) {
879     const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
880     if (Base && Base->isUndefined())
881       return false;
882   }
883
884   bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
885   if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
886     return false;
887
888   if (Symbol.isTemporary())
889     return false;
890
891   return true;
892 }
893
894 bool ELFObjectWriter::isLocal(const MCSymbol &Symbol, bool isUsedInReloc) {
895   const MCSymbolData &Data = Symbol.getData();
896   if (Data.isExternal())
897     return false;
898
899   if (Symbol.isDefined())
900     return true;
901
902   if (isUsedInReloc)
903     return false;
904
905   return true;
906 }
907
908 void ELFObjectWriter::computeSymbolTable(
909     MCAssembler &Asm, const MCAsmLayout &Layout,
910     const SectionIndexMapTy &SectionIndexMap,
911     const RevGroupMapTy &RevGroupMap) {
912   MCContext &Ctx = Asm.getContext();
913   // Symbol table
914   unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
915   MCSectionELF *SymtabSection =
916       Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize, "");
917   SymtabSection->setAlignment(is64Bit() ? 8 : 4);
918   SymbolTableIndex = addToSectionTable(SymtabSection);
919
920   // FIXME: Is this the correct place to do this?
921   // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
922   if (NeedsGOT) {
923     StringRef Name = "_GLOBAL_OFFSET_TABLE_";
924     MCSymbol *Sym = Asm.getContext().getOrCreateSymbol(Name);
925     MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
926     Data.setExternal(true);
927     MCELF::SetBinding(Data, ELF::STB_GLOBAL);
928   }
929
930   // Add the data for the symbols.
931   bool HasLargeSectionIndex = false;
932   for (const MCSymbol &Symbol : Asm.symbols()) {
933     MCSymbolData &SD = Symbol.getData();
934
935     bool Used = UsedInReloc.count(&Symbol);
936     bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
937     bool isSignature = RevGroupMap.count(&Symbol);
938
939     if (!isInSymtab(Layout, Symbol, Used || WeakrefUsed || isSignature,
940                     Renames.count(&Symbol)))
941       continue;
942
943     ELFSymbolData MSD;
944     MSD.Symbol = &Symbol;
945     const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
946
947     // Undefined symbols are global, but this is the first place we
948     // are able to set it.
949     bool Local = isLocal(Symbol, Used);
950     if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
951       assert(BaseSymbol);
952       MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
953       MCELF::SetBinding(SD, ELF::STB_GLOBAL);
954       MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
955     }
956
957     if (!BaseSymbol) {
958       MSD.SectionIndex = ELF::SHN_ABS;
959     } else if (SD.isCommon()) {
960       assert(!Local);
961       MSD.SectionIndex = ELF::SHN_COMMON;
962     } else if (BaseSymbol->isUndefined()) {
963       if (isSignature && !Used) {
964         MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
965         if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
966           HasLargeSectionIndex = true;
967       } else {
968         MSD.SectionIndex = ELF::SHN_UNDEF;
969       }
970       if (!Used && WeakrefUsed)
971         MCELF::SetBinding(SD, ELF::STB_WEAK);
972     } else {
973       const MCSectionELF &Section =
974         static_cast<const MCSectionELF&>(BaseSymbol->getSection());
975       MSD.SectionIndex = SectionIndexMap.lookup(&Section);
976       assert(MSD.SectionIndex && "Invalid section index!");
977       if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
978         HasLargeSectionIndex = true;
979     }
980
981     // The @@@ in symbol version is replaced with @ in undefined symbols and @@
982     // in defined ones.
983     //
984     // FIXME: All name handling should be done before we get to the writer,
985     // including dealing with GNU-style version suffixes.  Fixing this isn't
986     // trivial.
987     //
988     // We thus have to be careful to not perform the symbol version replacement
989     // blindly:
990     //
991     // The ELF format is used on Windows by the MCJIT engine.  Thus, on
992     // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
993     // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
994     // C++ name mangling can legally have "@@@" as a sub-string. In that case,
995     // the EFLObjectWriter should not interpret the "@@@" sub-string as
996     // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
997     // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
998     // "__imp_?" or "__imp_@?".
999     //
1000     // It would have been interesting to perform the MS mangling prefix check
1001     // only when the target triple is of the form *-pc-windows-elf. But, it
1002     // seems that this information is not easily accessible from the
1003     // ELFObjectWriter.
1004     StringRef Name = Symbol.getName();
1005     if (!Name.startswith("?") && !Name.startswith("@?") &&
1006         !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1007       // This symbol isn't following the MSVC C++ name mangling convention. We
1008       // can thus safely interpret the @@@ in symbol names as specifying symbol
1009       // versioning.
1010       SmallString<32> Buf;
1011       size_t Pos = Name.find("@@@");
1012       if (Pos != StringRef::npos) {
1013         Buf += Name.substr(0, Pos);
1014         unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1015         Buf += Name.substr(Pos + Skip);
1016         Name = Buf;
1017       }
1018     }
1019
1020     // Sections have their own string table
1021     if (MCELF::GetType(SD) != ELF::STT_SECTION)
1022       MSD.Name = StrTabBuilder.add(Name);
1023
1024     if (MSD.SectionIndex == ELF::SHN_UNDEF)
1025       UndefinedSymbolData.push_back(MSD);
1026     else if (Local)
1027       LocalSymbolData.push_back(MSD);
1028     else
1029       ExternalSymbolData.push_back(MSD);
1030   }
1031
1032   if (HasLargeSectionIndex) {
1033     MCSectionELF *SymtabShndxSection =
1034         Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
1035     SymtabShndxSectionIndex = addToSectionTable(SymtabShndxSection);
1036     SymtabShndxSection->setAlignment(4);
1037   }
1038
1039   for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1040     StrTabBuilder.add(*i);
1041
1042   StrTabBuilder.finalize(StringTableBuilder::ELF);
1043
1044   for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1045     FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1046
1047   for (ELFSymbolData &MSD : LocalSymbolData)
1048     MSD.StringIndex = MCELF::GetType(MSD.Symbol->getData()) == ELF::STT_SECTION
1049                           ? 0
1050                           : StrTabBuilder.getOffset(MSD.Name);
1051   for (ELFSymbolData &MSD : ExternalSymbolData)
1052     MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1053   for (ELFSymbolData& MSD : UndefinedSymbolData)
1054     MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1055
1056   // Symbols are required to be in lexicographic order.
1057   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1058   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1059   array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1060
1061   // Set the symbol indices. Local symbols must come before all other
1062   // symbols with non-local bindings.
1063   unsigned Index = FileSymbolData.size() + 1;
1064   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1065     LocalSymbolData[i].Symbol->setIndex(Index++);
1066
1067   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1068     ExternalSymbolData[i].Symbol->setIndex(Index++);
1069   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1070     UndefinedSymbolData[i].Symbol->setIndex(Index++);
1071 }
1072
1073 MCSectionELF *
1074 ELFObjectWriter::createRelocationSection(MCContext &Ctx,
1075                                          const MCSectionELF &Sec) {
1076   if (Relocations[&Sec].empty())
1077     return nullptr;
1078
1079   const StringRef SectionName = Sec.getSectionName();
1080   std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1081   RelaSectionName += SectionName;
1082
1083   unsigned EntrySize;
1084   if (hasRelocationAddend())
1085     EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1086   else
1087     EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1088
1089   unsigned Flags = 0;
1090   if (Sec.getFlags() & ELF::SHF_GROUP)
1091     Flags = ELF::SHF_GROUP;
1092
1093   MCSectionELF *RelaSection = Ctx.createELFRelSection(
1094       RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
1095       Flags, EntrySize, Sec.getGroup(), &Sec);
1096   RelaSection->setAlignment(is64Bit() ? 8 : 4);
1097   return RelaSection;
1098 }
1099
1100 static SmallVector<char, 128>
1101 getUncompressedData(const MCAsmLayout &Layout,
1102                     const MCSectionData::FragmentListType &Fragments) {
1103   SmallVector<char, 128> UncompressedData;
1104   for (const MCFragment &F : Fragments) {
1105     const SmallVectorImpl<char> *Contents;
1106     switch (F.getKind()) {
1107     case MCFragment::FT_Data:
1108       Contents = &cast<MCDataFragment>(F).getContents();
1109       break;
1110     case MCFragment::FT_Dwarf:
1111       Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1112       break;
1113     case MCFragment::FT_DwarfFrame:
1114       Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1115       break;
1116     default:
1117       llvm_unreachable(
1118           "Not expecting any other fragment types in a debug_* section");
1119     }
1120     UncompressedData.append(Contents->begin(), Contents->end());
1121   }
1122   return UncompressedData;
1123 }
1124
1125 // Include the debug info compression header:
1126 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1127 // useful for consumers to preallocate a buffer to decompress into.
1128 static bool
1129 prependCompressionHeader(uint64_t Size,
1130                          SmallVectorImpl<char> &CompressedContents) {
1131   const StringRef Magic = "ZLIB";
1132   if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1133     return false;
1134   if (sys::IsLittleEndianHost)
1135     sys::swapByteOrder(Size);
1136   CompressedContents.insert(CompressedContents.begin(),
1137                             Magic.size() + sizeof(Size), 0);
1138   std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1139   std::copy(reinterpret_cast<char *>(&Size),
1140             reinterpret_cast<char *>(&Size + 1),
1141             CompressedContents.begin() + Magic.size());
1142   return true;
1143 }
1144
1145 void ELFObjectWriter::writeSectionData(const MCAssembler &Asm,
1146                                        const MCSectionData &SD,
1147                                        const MCAsmLayout &Layout) {
1148   MCSectionELF &Section = static_cast<MCSectionELF &>(SD.getSection());
1149   StringRef SectionName = Section.getSectionName();
1150
1151   // Compressing debug_frame requires handling alignment fragments which is
1152   // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1153   // for writing to arbitrary buffers) for little benefit.
1154   if (!Asm.getContext().getAsmInfo()->compressDebugSections() ||
1155       !SectionName.startswith(".debug_") || SectionName == ".debug_frame") {
1156     Asm.writeSectionData(&SD, Layout);
1157     return;
1158   }
1159
1160   // Gather the uncompressed data from all the fragments.
1161   const MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1162   SmallVector<char, 128> UncompressedData =
1163       getUncompressedData(Layout, Fragments);
1164
1165   SmallVector<char, 128> CompressedContents;
1166   zlib::Status Success = zlib::compress(
1167       StringRef(UncompressedData.data(), UncompressedData.size()),
1168       CompressedContents);
1169   if (Success != zlib::StatusOK) {
1170     Asm.writeSectionData(&SD, Layout);
1171     return;
1172   }
1173
1174   if (!prependCompressionHeader(UncompressedData.size(), CompressedContents)) {
1175     Asm.writeSectionData(&SD, Layout);
1176     return;
1177   }
1178   Asm.getContext().renameELFSection(&Section,
1179                                     (".z" + SectionName.drop_front(1)).str());
1180   OS << CompressedContents;
1181 }
1182
1183 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1184                                        uint64_t Flags, uint64_t Address,
1185                                        uint64_t Offset, uint64_t Size,
1186                                        uint32_t Link, uint32_t Info,
1187                                        uint64_t Alignment,
1188                                        uint64_t EntrySize) {
1189   Write32(Name);        // sh_name: index into string table
1190   Write32(Type);        // sh_type
1191   WriteWord(Flags);     // sh_flags
1192   WriteWord(Address);   // sh_addr
1193   WriteWord(Offset);    // sh_offset
1194   WriteWord(Size);      // sh_size
1195   Write32(Link);        // sh_link
1196   Write32(Info);        // sh_info
1197   WriteWord(Alignment); // sh_addralign
1198   WriteWord(EntrySize); // sh_entsize
1199 }
1200
1201 void ELFObjectWriter::writeRelocations(const MCAssembler &Asm,
1202                                        const MCSectionELF &Sec) {
1203   std::vector<ELFRelocationEntry> &Relocs = Relocations[&Sec];
1204
1205   // Sort the relocation entries. Most targets just sort by Offset, but some
1206   // (e.g., MIPS) have additional constraints.
1207   TargetObjectWriter->sortRelocs(Asm, Relocs);
1208
1209   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1210     const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1211     unsigned Index =
1212         Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
1213
1214     if (is64Bit()) {
1215       write(Entry.Offset);
1216       if (TargetObjectWriter->isN64()) {
1217         write(uint32_t(Index));
1218
1219         write(TargetObjectWriter->getRSsym(Entry.Type));
1220         write(TargetObjectWriter->getRType3(Entry.Type));
1221         write(TargetObjectWriter->getRType2(Entry.Type));
1222         write(TargetObjectWriter->getRType(Entry.Type));
1223       } else {
1224         struct ELF::Elf64_Rela ERE64;
1225         ERE64.setSymbolAndType(Index, Entry.Type);
1226         write(ERE64.r_info);
1227       }
1228       if (hasRelocationAddend())
1229         write(Entry.Addend);
1230     } else {
1231       write(uint32_t(Entry.Offset));
1232
1233       struct ELF::Elf32_Rela ERE32;
1234       ERE32.setSymbolAndType(Index, Entry.Type);
1235       write(ERE32.r_info);
1236
1237       if (hasRelocationAddend())
1238         write(uint32_t(Entry.Addend));
1239     }
1240   }
1241 }
1242
1243 const MCSectionELF *ELFObjectWriter::createStringTable(MCContext &Ctx) {
1244   const MCSectionELF *StrtabSection = SectionTable[StringTableIndex - 1];
1245   OS << StrTabBuilder.data();
1246   return StrtabSection;
1247 }
1248
1249 void ELFObjectWriter::writeSection(const SectionIndexMapTy &SectionIndexMap,
1250                                    uint32_t GroupSymbolIndex, uint64_t Offset,
1251                                    uint64_t Size, const MCSectionELF &Section) {
1252   uint64_t sh_link = 0;
1253   uint64_t sh_info = 0;
1254
1255   switch(Section.getType()) {
1256   default:
1257     // Nothing to do.
1258     break;
1259
1260   case ELF::SHT_DYNAMIC:
1261     llvm_unreachable("SHT_DYNAMIC in a relocatable object");
1262
1263   case ELF::SHT_REL:
1264   case ELF::SHT_RELA: {
1265     sh_link = SymbolTableIndex;
1266     assert(sh_link && ".symtab not found");
1267     const MCSectionELF *InfoSection = Section.getAssociatedSection();
1268     sh_info = SectionIndexMap.lookup(InfoSection);
1269     break;
1270   }
1271
1272   case ELF::SHT_SYMTAB:
1273   case ELF::SHT_DYNSYM:
1274     sh_link = StringTableIndex;
1275     sh_info = LastLocalSymbolIndex;
1276     break;
1277
1278   case ELF::SHT_SYMTAB_SHNDX:
1279     sh_link = SymbolTableIndex;
1280     break;
1281
1282   case ELF::SHT_GROUP:
1283     sh_link = SymbolTableIndex;
1284     sh_info = GroupSymbolIndex;
1285     break;
1286   }
1287
1288   if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1289       Section.getType() == ELF::SHT_ARM_EXIDX)
1290     sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1291
1292   WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getSectionName()),
1293                    Section.getType(), Section.getFlags(), 0, Offset, Size,
1294                    sh_link, sh_info, Section.getAlignment(),
1295                    Section.getEntrySize());
1296 }
1297
1298 void ELFObjectWriter::writeSectionHeader(
1299     const MCAssembler &Asm, const MCAsmLayout &Layout,
1300     const SectionIndexMapTy &SectionIndexMap,
1301     const SectionOffsetsTy &SectionOffsets) {
1302   const unsigned NumSections = SectionTable.size();
1303
1304   // Null section first.
1305   uint64_t FirstSectionSize =
1306       (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
1307   WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
1308
1309   for (const MCSectionELF *Section : SectionTable) {
1310     uint32_t GroupSymbolIndex;
1311     unsigned Type = Section->getType();
1312     if (Type != ELF::SHT_GROUP)
1313       GroupSymbolIndex = 0;
1314     else
1315       GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, Section->getGroup());
1316
1317     const std::pair<uint64_t, uint64_t> &Offsets =
1318         SectionOffsets.find(Section)->second;
1319     uint64_t Size;
1320     if (Type == ELF::SHT_NOBITS) {
1321       const MCSectionData &SD = Asm.getSectionData(*Section);
1322       Size = Layout.getSectionAddressSize(&SD);
1323     } else {
1324       Size = Offsets.second - Offsets.first;
1325     }
1326
1327     writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1328                  *Section);
1329   }
1330 }
1331
1332 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1333                                   const MCAsmLayout &Layout) {
1334   MCContext &Ctx = Asm.getContext();
1335   MCSectionELF *StrtabSection =
1336       Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1337   StringTableIndex = addToSectionTable(StrtabSection);
1338
1339   RevGroupMapTy RevGroupMap;
1340   SectionIndexMapTy SectionIndexMap;
1341
1342   std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers;
1343
1344   // Write out the ELF header ...
1345   writeHeader(Asm);
1346
1347   // ... then the sections ...
1348   SectionOffsetsTy SectionOffsets;
1349   std::vector<MCSectionELF *> Groups;
1350   std::vector<MCSectionELF *> Relocations;
1351   for (const MCSectionData &SD : Asm) {
1352     const MCSectionELF &Section = static_cast<MCSectionELF &>(SD.getSection());
1353
1354     uint64_t Padding = OffsetToAlignment(OS.tell(), Section.getAlignment());
1355     WriteZeros(Padding);
1356
1357     // Remember the offset into the file for this section.
1358     uint64_t SecStart = OS.tell();
1359
1360     const MCSymbol *SignatureSymbol = Section.getGroup();
1361     writeSectionData(Asm, SD, Layout);
1362
1363     uint64_t SecEnd = OS.tell();
1364     SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd);
1365
1366     MCSectionELF *RelSection = createRelocationSection(Ctx, Section);
1367
1368     if (SignatureSymbol) {
1369       Asm.getOrCreateSymbolData(*SignatureSymbol);
1370       unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1371       if (!GroupIdx) {
1372         MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
1373         GroupIdx = addToSectionTable(Group);
1374         Group->setAlignment(4);
1375         Groups.push_back(Group);
1376       }
1377       GroupMembers[SignatureSymbol].push_back(&Section);
1378       if (RelSection)
1379         GroupMembers[SignatureSymbol].push_back(RelSection);
1380     }
1381
1382     SectionIndexMap[&Section] = addToSectionTable(&Section);
1383     if (RelSection) {
1384       SectionIndexMap[RelSection] = addToSectionTable(RelSection);
1385       Relocations.push_back(RelSection);
1386     }
1387   }
1388
1389   for (MCSectionELF *Group : Groups) {
1390     uint64_t Padding = OffsetToAlignment(OS.tell(), Group->getAlignment());
1391     WriteZeros(Padding);
1392
1393     // Remember the offset into the file for this section.
1394     uint64_t SecStart = OS.tell();
1395
1396     const MCSymbol *SignatureSymbol = Group->getGroup();
1397     assert(SignatureSymbol);
1398     write(uint32_t(ELF::GRP_COMDAT));
1399     for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) {
1400       uint32_t SecIndex = SectionIndexMap.lookup(Member);
1401       write(SecIndex);
1402     }
1403
1404     uint64_t SecEnd = OS.tell();
1405     SectionOffsets[Group] = std::make_pair(SecStart, SecEnd);
1406   }
1407
1408   // Compute symbol table information.
1409   computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
1410
1411   for (MCSectionELF *RelSection : Relocations) {
1412     uint64_t Padding = OffsetToAlignment(OS.tell(), RelSection->getAlignment());
1413     WriteZeros(Padding);
1414
1415     // Remember the offset into the file for this section.
1416     uint64_t SecStart = OS.tell();
1417
1418     writeRelocations(Asm, *RelSection->getAssociatedSection());
1419
1420     uint64_t SecEnd = OS.tell();
1421     SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd);
1422   }
1423
1424   writeSymbolTable(Ctx, Layout, SectionOffsets);
1425
1426   {
1427     uint64_t SecStart = OS.tell();
1428     const MCSectionELF *Sec = createStringTable(Ctx);
1429     uint64_t SecEnd = OS.tell();
1430     SectionOffsets[Sec] = std::make_pair(SecStart, SecEnd);
1431   }
1432
1433   uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1434   uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1435   WriteZeros(Padding);
1436
1437   const unsigned SectionHeaderOffset = OS.tell();
1438
1439   // ... then the section header table ...
1440   writeSectionHeader(Asm, Layout, SectionIndexMap, SectionOffsets);
1441
1442   uint16_t NumSections = (SectionTable.size() + 1 >= ELF::SHN_LORESERVE)
1443                              ? (uint16_t)ELF::SHN_UNDEF
1444                              : SectionTable.size() + 1;
1445   if (sys::IsLittleEndianHost != IsLittleEndian)
1446     sys::swapByteOrder(NumSections);
1447   unsigned NumSectionsOffset;
1448
1449   if (is64Bit()) {
1450     uint64_t Val = SectionHeaderOffset;
1451     if (sys::IsLittleEndianHost != IsLittleEndian)
1452       sys::swapByteOrder(Val);
1453     OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1454               offsetof(ELF::Elf64_Ehdr, e_shoff));
1455     NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
1456   } else {
1457     uint32_t Val = SectionHeaderOffset;
1458     if (sys::IsLittleEndianHost != IsLittleEndian)
1459       sys::swapByteOrder(Val);
1460     OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1461               offsetof(ELF::Elf32_Ehdr, e_shoff));
1462     NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
1463   }
1464   OS.pwrite(reinterpret_cast<char *>(&NumSections), sizeof(NumSections),
1465             NumSectionsOffset);
1466 }
1467
1468 bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1469     const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
1470     bool InSet, bool IsPCRel) const {
1471   if (IsPCRel) {
1472     assert(!InSet);
1473     if (::isWeak(SymA.getData()))
1474       return false;
1475   }
1476   return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
1477                                                                 InSet, IsPCRel);
1478 }
1479
1480 bool ELFObjectWriter::isWeak(const MCSymbol &Sym) const {
1481   const MCSymbolData &SD = Sym.getData();
1482   if (::isWeak(SD))
1483     return true;
1484
1485   // It is invalid to replace a reference to a global in a comdat
1486   // with a reference to a local since out of comdat references
1487   // to a local are forbidden.
1488   // We could try to return false for more cases, like the reference
1489   // being in the same comdat or Sym being an alias to another global,
1490   // but it is not clear if it is worth the effort.
1491   if (MCELF::GetBinding(SD) != ELF::STB_GLOBAL)
1492     return false;
1493
1494   if (!Sym.isInSection())
1495     return false;
1496
1497   const auto &Sec = cast<MCSectionELF>(Sym.getSection());
1498   return Sec.getGroup();
1499 }
1500
1501 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1502                                             raw_pwrite_stream &OS,
1503                                             bool IsLittleEndian) {
1504   return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
1505 }