Produce a single string table in a ELF .o
[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<MCSectionELF *> SectionTable;
136     unsigned addToSectionTable(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(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   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   MCSectionELF *SymtabShndxSection = 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 MCSectionData *FixupSectionD = Fragment->getParent();
754   const MCSectionELF &FixupSection =
755       cast<MCSectionELF>(FixupSectionD->getSection());
756   uint64_t C = Target.getConstant();
757   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
758
759   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
760     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
761            "Should not have constructed this");
762
763     // Let A, B and C being the components of Target and R be the location of
764     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
765     // If it is pcrel, we want to compute (A - B + C - R).
766
767     // In general, ELF has no relocations for -B. It can only represent (A + C)
768     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
769     // replace B to implement it: (A - R - K + C)
770     if (IsPCRel)
771       Asm.getContext().reportFatalError(
772           Fixup.getLoc(),
773           "No relocation available to represent this relative expression");
774
775     const MCSymbol &SymB = RefB->getSymbol();
776
777     if (SymB.isUndefined())
778       Asm.getContext().reportFatalError(
779           Fixup.getLoc(),
780           Twine("symbol '") + SymB.getName() +
781               "' can not be undefined in a subtraction expression");
782
783     assert(!SymB.isAbsolute() && "Should have been folded");
784     const MCSection &SecB = SymB.getSection();
785     if (&SecB != &FixupSection)
786       Asm.getContext().reportFatalError(
787           Fixup.getLoc(), "Cannot represent a difference across sections");
788
789     if (::isWeak(SymB.getData()))
790       Asm.getContext().reportFatalError(
791           Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
792
793     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
794     uint64_t K = SymBOffset - FixupOffset;
795     IsPCRel = true;
796     C -= K;
797   }
798
799   // We either rejected the fixup or folded B into C at this point.
800   const MCSymbolRefExpr *RefA = Target.getSymA();
801   const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
802
803   unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
804   bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymA, C, Type);
805   if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
806     C += Layout.getSymbolOffset(*SymA);
807
808   uint64_t Addend = 0;
809   if (hasRelocationAddend()) {
810     Addend = C;
811     C = 0;
812   }
813
814   FixedValue = C;
815
816   // FIXME: What is this!?!?
817   MCSymbolRefExpr::VariantKind Modifier =
818       RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
819   if (RelocNeedsGOT(Modifier))
820     NeedsGOT = true;
821
822   if (!RelocateWithSymbol) {
823     const MCSection *SecA =
824         (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
825     auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
826     MCSymbol *SectionSymbol =
827         ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
828                : nullptr;
829     ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
830     Relocations[&FixupSection].push_back(Rec);
831     return;
832   }
833
834   if (SymA) {
835     if (const MCSymbol *R = Renames.lookup(SymA))
836       SymA = R;
837
838     if (const MCSymbol *WeakRef = getWeakRef(*RefA))
839       WeakrefUsedInReloc.insert(WeakRef);
840     else
841       UsedInReloc.insert(SymA);
842   }
843   ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
844   Relocations[&FixupSection].push_back(Rec);
845   return;
846 }
847
848
849 uint64_t
850 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
851                                              const MCSymbol *S) {
852   assert(S->hasData());
853   return S->getIndex();
854 }
855
856 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
857                                  const MCSymbol &Symbol, bool Used,
858                                  bool Renamed) {
859   const MCSymbolData &Data = Symbol.getData();
860   if (Symbol.isVariable()) {
861     const MCExpr *Expr = Symbol.getVariableValue();
862     if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
863       if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
864         return false;
865     }
866   }
867
868   if (Used)
869     return true;
870
871   if (Renamed)
872     return false;
873
874   if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
875     return true;
876
877   if (Symbol.isVariable()) {
878     const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
879     if (Base && Base->isUndefined())
880       return false;
881   }
882
883   bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
884   if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
885     return false;
886
887   if (Symbol.isTemporary())
888     return false;
889
890   return true;
891 }
892
893 bool ELFObjectWriter::isLocal(const MCSymbol &Symbol, bool isUsedInReloc) {
894   const MCSymbolData &Data = Symbol.getData();
895   if (Data.isExternal())
896     return false;
897
898   if (Symbol.isDefined())
899     return true;
900
901   if (isUsedInReloc)
902     return false;
903
904   return true;
905 }
906
907 void ELFObjectWriter::computeSymbolTable(
908     MCAssembler &Asm, const MCAsmLayout &Layout,
909     const SectionIndexMapTy &SectionIndexMap,
910     const RevGroupMapTy &RevGroupMap) {
911   MCContext &Ctx = Asm.getContext();
912   // Symbol table
913   unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
914   MCSectionELF *SymtabSection =
915       Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize, "");
916   SymtabSection->setAlignment(is64Bit() ? 8 : 4);
917   SymbolTableIndex = addToSectionTable(SymtabSection);
918
919   // FIXME: Is this the correct place to do this?
920   // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
921   if (NeedsGOT) {
922     StringRef Name = "_GLOBAL_OFFSET_TABLE_";
923     MCSymbol *Sym = Asm.getContext().getOrCreateSymbol(Name);
924     MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
925     Data.setExternal(true);
926     MCELF::SetBinding(Data, ELF::STB_GLOBAL);
927   }
928
929   // Add the data for the symbols.
930   bool HasLargeSectionIndex = false;
931   for (const MCSymbol &Symbol : Asm.symbols()) {
932     MCSymbolData &SD = Symbol.getData();
933
934     bool Used = UsedInReloc.count(&Symbol);
935     bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
936     bool isSignature = RevGroupMap.count(&Symbol);
937
938     if (!isInSymtab(Layout, Symbol, Used || WeakrefUsed || isSignature,
939                     Renames.count(&Symbol)))
940       continue;
941
942     ELFSymbolData MSD;
943     MSD.Symbol = &Symbol;
944     const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
945
946     // Undefined symbols are global, but this is the first place we
947     // are able to set it.
948     bool Local = isLocal(Symbol, Used);
949     if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
950       assert(BaseSymbol);
951       MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
952       MCELF::SetBinding(SD, ELF::STB_GLOBAL);
953       MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
954     }
955
956     if (!BaseSymbol) {
957       MSD.SectionIndex = ELF::SHN_ABS;
958     } else if (SD.isCommon()) {
959       assert(!Local);
960       MSD.SectionIndex = ELF::SHN_COMMON;
961     } else if (BaseSymbol->isUndefined()) {
962       if (isSignature && !Used) {
963         MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
964         if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
965           HasLargeSectionIndex = true;
966       } else {
967         MSD.SectionIndex = ELF::SHN_UNDEF;
968       }
969       if (!Used && WeakrefUsed)
970         MCELF::SetBinding(SD, ELF::STB_WEAK);
971     } else {
972       const MCSectionELF &Section =
973         static_cast<const MCSectionELF&>(BaseSymbol->getSection());
974       MSD.SectionIndex = SectionIndexMap.lookup(&Section);
975       assert(MSD.SectionIndex && "Invalid section index!");
976       if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
977         HasLargeSectionIndex = true;
978     }
979
980     // The @@@ in symbol version is replaced with @ in undefined symbols and @@
981     // in defined ones.
982     //
983     // FIXME: All name handling should be done before we get to the writer,
984     // including dealing with GNU-style version suffixes.  Fixing this isn't
985     // trivial.
986     //
987     // We thus have to be careful to not perform the symbol version replacement
988     // blindly:
989     //
990     // The ELF format is used on Windows by the MCJIT engine.  Thus, on
991     // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
992     // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
993     // C++ name mangling can legally have "@@@" as a sub-string. In that case,
994     // the EFLObjectWriter should not interpret the "@@@" sub-string as
995     // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
996     // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
997     // "__imp_?" or "__imp_@?".
998     //
999     // It would have been interesting to perform the MS mangling prefix check
1000     // only when the target triple is of the form *-pc-windows-elf. But, it
1001     // seems that this information is not easily accessible from the
1002     // ELFObjectWriter.
1003     StringRef Name = Symbol.getName();
1004     if (!Name.startswith("?") && !Name.startswith("@?") &&
1005         !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1006       // This symbol isn't following the MSVC C++ name mangling convention. We
1007       // can thus safely interpret the @@@ in symbol names as specifying symbol
1008       // versioning.
1009       SmallString<32> Buf;
1010       size_t Pos = Name.find("@@@");
1011       if (Pos != StringRef::npos) {
1012         Buf += Name.substr(0, Pos);
1013         unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1014         Buf += Name.substr(Pos + Skip);
1015         Name = Buf;
1016       }
1017     }
1018
1019     // Sections have their own string table
1020     if (MCELF::GetType(SD) != ELF::STT_SECTION)
1021       MSD.Name = StrTabBuilder.add(Name);
1022
1023     if (MSD.SectionIndex == ELF::SHN_UNDEF)
1024       UndefinedSymbolData.push_back(MSD);
1025     else if (Local)
1026       LocalSymbolData.push_back(MSD);
1027     else
1028       ExternalSymbolData.push_back(MSD);
1029   }
1030
1031   if (HasLargeSectionIndex) {
1032     MCSectionELF *SymtabShndxSection =
1033         Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
1034     SymtabShndxSectionIndex = addToSectionTable(SymtabShndxSection);
1035     SymtabShndxSection->setAlignment(4);
1036   }
1037
1038   for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1039     StrTabBuilder.add(*i);
1040
1041   StrTabBuilder.finalize(StringTableBuilder::ELF);
1042
1043   for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1044     FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1045
1046   for (ELFSymbolData &MSD : LocalSymbolData)
1047     MSD.StringIndex = MCELF::GetType(MSD.Symbol->getData()) == ELF::STT_SECTION
1048                           ? 0
1049                           : StrTabBuilder.getOffset(MSD.Name);
1050   for (ELFSymbolData &MSD : ExternalSymbolData)
1051     MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1052   for (ELFSymbolData& MSD : UndefinedSymbolData)
1053     MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1054
1055   // Symbols are required to be in lexicographic order.
1056   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1057   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1058   array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1059
1060   // Set the symbol indices. Local symbols must come before all other
1061   // symbols with non-local bindings.
1062   unsigned Index = FileSymbolData.size() + 1;
1063   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1064     LocalSymbolData[i].Symbol->setIndex(Index++);
1065
1066   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1067     ExternalSymbolData[i].Symbol->setIndex(Index++);
1068   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1069     UndefinedSymbolData[i].Symbol->setIndex(Index++);
1070 }
1071
1072 MCSectionELF *
1073 ELFObjectWriter::createRelocationSection(MCContext &Ctx,
1074                                          const MCSectionELF &Sec) {
1075   if (Relocations[&Sec].empty())
1076     return nullptr;
1077
1078   const StringRef SectionName = Sec.getSectionName();
1079   std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1080   RelaSectionName += SectionName;
1081
1082   unsigned EntrySize;
1083   if (hasRelocationAddend())
1084     EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1085   else
1086     EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1087
1088   unsigned Flags = 0;
1089   if (Sec.getFlags() & ELF::SHF_GROUP)
1090     Flags = ELF::SHF_GROUP;
1091
1092   MCSectionELF *RelaSection = Ctx.createELFRelSection(
1093       RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
1094       Flags, EntrySize, Sec.getGroup(), &Sec);
1095   RelaSection->setAlignment(is64Bit() ? 8 : 4);
1096   return RelaSection;
1097 }
1098
1099 static SmallVector<char, 128>
1100 getUncompressedData(const MCAsmLayout &Layout,
1101                     const MCSectionData::FragmentListType &Fragments) {
1102   SmallVector<char, 128> UncompressedData;
1103   for (const MCFragment &F : Fragments) {
1104     const SmallVectorImpl<char> *Contents;
1105     switch (F.getKind()) {
1106     case MCFragment::FT_Data:
1107       Contents = &cast<MCDataFragment>(F).getContents();
1108       break;
1109     case MCFragment::FT_Dwarf:
1110       Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1111       break;
1112     case MCFragment::FT_DwarfFrame:
1113       Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1114       break;
1115     default:
1116       llvm_unreachable(
1117           "Not expecting any other fragment types in a debug_* section");
1118     }
1119     UncompressedData.append(Contents->begin(), Contents->end());
1120   }
1121   return UncompressedData;
1122 }
1123
1124 // Include the debug info compression header:
1125 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1126 // useful for consumers to preallocate a buffer to decompress into.
1127 static bool
1128 prependCompressionHeader(uint64_t Size,
1129                          SmallVectorImpl<char> &CompressedContents) {
1130   const StringRef Magic = "ZLIB";
1131   if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1132     return false;
1133   if (sys::IsLittleEndianHost)
1134     sys::swapByteOrder(Size);
1135   CompressedContents.insert(CompressedContents.begin(),
1136                             Magic.size() + sizeof(Size), 0);
1137   std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1138   std::copy(reinterpret_cast<char *>(&Size),
1139             reinterpret_cast<char *>(&Size + 1),
1140             CompressedContents.begin() + Magic.size());
1141   return true;
1142 }
1143
1144 void ELFObjectWriter::writeSectionData(const MCAssembler &Asm,
1145                                        const MCSectionData &SD,
1146                                        const MCAsmLayout &Layout) {
1147   MCSectionELF &Section = static_cast<MCSectionELF &>(SD.getSection());
1148   StringRef SectionName = Section.getSectionName();
1149
1150   // Compressing debug_frame requires handling alignment fragments which is
1151   // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1152   // for writing to arbitrary buffers) for little benefit.
1153   if (!Asm.getContext().getAsmInfo()->compressDebugSections() ||
1154       !SectionName.startswith(".debug_") || SectionName == ".debug_frame") {
1155     Asm.writeSectionData(&SD, Layout);
1156     return;
1157   }
1158
1159   // Gather the uncompressed data from all the fragments.
1160   const MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1161   SmallVector<char, 128> UncompressedData =
1162       getUncompressedData(Layout, Fragments);
1163
1164   SmallVector<char, 128> CompressedContents;
1165   zlib::Status Success = zlib::compress(
1166       StringRef(UncompressedData.data(), UncompressedData.size()),
1167       CompressedContents);
1168   if (Success != zlib::StatusOK) {
1169     Asm.writeSectionData(&SD, Layout);
1170     return;
1171   }
1172
1173   if (!prependCompressionHeader(UncompressedData.size(), CompressedContents)) {
1174     Asm.writeSectionData(&SD, Layout);
1175     return;
1176   }
1177   Asm.getContext().renameELFSection(&Section,
1178                                     (".z" + SectionName.drop_front(1)).str());
1179   OS << CompressedContents;
1180 }
1181
1182 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1183                                        uint64_t Flags, uint64_t Address,
1184                                        uint64_t Offset, uint64_t Size,
1185                                        uint32_t Link, uint32_t Info,
1186                                        uint64_t Alignment,
1187                                        uint64_t EntrySize) {
1188   Write32(Name);        // sh_name: index into string table
1189   Write32(Type);        // sh_type
1190   WriteWord(Flags);     // sh_flags
1191   WriteWord(Address);   // sh_addr
1192   WriteWord(Offset);    // sh_offset
1193   WriteWord(Size);      // sh_size
1194   Write32(Link);        // sh_link
1195   Write32(Info);        // sh_info
1196   WriteWord(Alignment); // sh_addralign
1197   WriteWord(EntrySize); // sh_entsize
1198 }
1199
1200 void ELFObjectWriter::writeRelocations(const MCAssembler &Asm,
1201                                        const MCSectionELF &Sec) {
1202   std::vector<ELFRelocationEntry> &Relocs = Relocations[&Sec];
1203
1204   // Sort the relocation entries. Most targets just sort by Offset, but some
1205   // (e.g., MIPS) have additional constraints.
1206   TargetObjectWriter->sortRelocs(Asm, Relocs);
1207
1208   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1209     const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1210     unsigned Index =
1211         Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
1212
1213     if (is64Bit()) {
1214       write(Entry.Offset);
1215       if (TargetObjectWriter->isN64()) {
1216         write(uint32_t(Index));
1217
1218         write(TargetObjectWriter->getRSsym(Entry.Type));
1219         write(TargetObjectWriter->getRType3(Entry.Type));
1220         write(TargetObjectWriter->getRType2(Entry.Type));
1221         write(TargetObjectWriter->getRType(Entry.Type));
1222       } else {
1223         struct ELF::Elf64_Rela ERE64;
1224         ERE64.setSymbolAndType(Index, Entry.Type);
1225         write(ERE64.r_info);
1226       }
1227       if (hasRelocationAddend())
1228         write(Entry.Addend);
1229     } else {
1230       write(uint32_t(Entry.Offset));
1231
1232       struct ELF::Elf32_Rela ERE32;
1233       ERE32.setSymbolAndType(Index, Entry.Type);
1234       write(ERE32.r_info);
1235
1236       if (hasRelocationAddend())
1237         write(uint32_t(Entry.Addend));
1238     }
1239   }
1240 }
1241
1242 const MCSectionELF *ELFObjectWriter::createStringTable(MCContext &Ctx) {
1243   MCSectionELF *StrtabSection = SectionTable[StringTableIndex - 1];
1244   OS << StrTabBuilder.data();
1245   return StrtabSection;
1246 }
1247
1248 void ELFObjectWriter::writeSection(const SectionIndexMapTy &SectionIndexMap,
1249                                    uint32_t GroupSymbolIndex, uint64_t Offset,
1250                                    uint64_t Size, const MCSectionELF &Section) {
1251   uint64_t sh_link = 0;
1252   uint64_t sh_info = 0;
1253
1254   switch(Section.getType()) {
1255   default:
1256     // Nothing to do.
1257     break;
1258
1259   case ELF::SHT_DYNAMIC:
1260     llvm_unreachable("SHT_DYNAMIC in a relocatable object");
1261
1262   case ELF::SHT_REL:
1263   case ELF::SHT_RELA: {
1264     sh_link = SymbolTableIndex;
1265     assert(sh_link && ".symtab not found");
1266     const MCSectionELF *InfoSection = Section.getAssociatedSection();
1267     sh_info = SectionIndexMap.lookup(InfoSection);
1268     break;
1269   }
1270
1271   case ELF::SHT_SYMTAB:
1272   case ELF::SHT_DYNSYM:
1273     sh_link = StringTableIndex;
1274     sh_info = LastLocalSymbolIndex;
1275     break;
1276
1277   case ELF::SHT_SYMTAB_SHNDX:
1278     sh_link = SymbolTableIndex;
1279     break;
1280
1281   case ELF::SHT_GROUP:
1282     sh_link = SymbolTableIndex;
1283     sh_info = GroupSymbolIndex;
1284     break;
1285   }
1286
1287   if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1288       Section.getType() == ELF::SHT_ARM_EXIDX)
1289     sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1290
1291   WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getSectionName()),
1292                    Section.getType(), Section.getFlags(), 0, Offset, Size,
1293                    sh_link, sh_info, Section.getAlignment(),
1294                    Section.getEntrySize());
1295 }
1296
1297 void ELFObjectWriter::writeSectionHeader(
1298     const MCAssembler &Asm, const MCAsmLayout &Layout,
1299     const SectionIndexMapTy &SectionIndexMap,
1300     const SectionOffsetsTy &SectionOffsets) {
1301   const unsigned NumSections = SectionTable.size();
1302
1303   // Null section first.
1304   uint64_t FirstSectionSize =
1305       (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
1306   WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
1307
1308   for (MCSectionELF *Section : SectionTable) {
1309     uint32_t GroupSymbolIndex;
1310     unsigned Type = Section->getType();
1311     if (Type != ELF::SHT_GROUP)
1312       GroupSymbolIndex = 0;
1313     else
1314       GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, Section->getGroup());
1315
1316     const std::pair<uint64_t, uint64_t> &Offsets =
1317         SectionOffsets.find(Section)->second;
1318     uint64_t Size;
1319     if (Type == ELF::SHT_NOBITS) {
1320       const MCSectionData &SD = Asm.getSectionData(*Section);
1321       Size = Layout.getSectionAddressSize(&SD);
1322     } else {
1323       Size = Offsets.second - Offsets.first;
1324     }
1325
1326     writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1327                  *Section);
1328   }
1329 }
1330
1331 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1332                                   const MCAsmLayout &Layout) {
1333   MCContext &Ctx = Asm.getContext();
1334   MCSectionELF *StrtabSection =
1335       Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1336   StringTableIndex = addToSectionTable(StrtabSection);
1337
1338   RevGroupMapTy RevGroupMap;
1339   SectionIndexMapTy SectionIndexMap;
1340
1341   std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers;
1342
1343   // Write out the ELF header ...
1344   writeHeader(Asm);
1345
1346   // ... then the sections ...
1347   SectionOffsetsTy SectionOffsets;
1348   std::vector<MCSectionELF *> Groups;
1349   std::vector<MCSectionELF *> Relocations;
1350   for (const MCSectionData &SD : Asm) {
1351     MCSectionELF &Section = static_cast<MCSectionELF &>(SD.getSection());
1352
1353     uint64_t Padding = OffsetToAlignment(OS.tell(), Section.getAlignment());
1354     WriteZeros(Padding);
1355
1356     // Remember the offset into the file for this section.
1357     uint64_t SecStart = OS.tell();
1358
1359     const MCSymbol *SignatureSymbol = Section.getGroup();
1360     writeSectionData(Asm, SD, Layout);
1361
1362     uint64_t SecEnd = OS.tell();
1363     SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd);
1364
1365     MCSectionELF *RelSection = createRelocationSection(Ctx, Section);
1366
1367     if (SignatureSymbol) {
1368       Asm.getOrCreateSymbolData(*SignatureSymbol);
1369       unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1370       if (!GroupIdx) {
1371         MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
1372         GroupIdx = addToSectionTable(Group);
1373         Group->setAlignment(4);
1374         Groups.push_back(Group);
1375       }
1376       GroupMembers[SignatureSymbol].push_back(&Section);
1377       if (RelSection)
1378         GroupMembers[SignatureSymbol].push_back(RelSection);
1379     }
1380
1381     SectionIndexMap[&Section] = addToSectionTable(&Section);
1382     if (RelSection) {
1383       SectionIndexMap[RelSection] = addToSectionTable(RelSection);
1384       Relocations.push_back(RelSection);
1385     }
1386   }
1387
1388   for (MCSectionELF *Group : Groups) {
1389     uint64_t Padding = OffsetToAlignment(OS.tell(), Group->getAlignment());
1390     WriteZeros(Padding);
1391
1392     // Remember the offset into the file for this section.
1393     uint64_t SecStart = OS.tell();
1394
1395     const MCSymbol *SignatureSymbol = Group->getGroup();
1396     assert(SignatureSymbol);
1397     write(uint32_t(ELF::GRP_COMDAT));
1398     for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) {
1399       uint32_t SecIndex = SectionIndexMap.lookup(Member);
1400       write(SecIndex);
1401     }
1402
1403     uint64_t SecEnd = OS.tell();
1404     SectionOffsets[Group] = std::make_pair(SecStart, SecEnd);
1405   }
1406
1407   // Compute symbol table information.
1408   computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
1409
1410   for (MCSectionELF *RelSection : Relocations) {
1411     uint64_t Padding = OffsetToAlignment(OS.tell(), RelSection->getAlignment());
1412     WriteZeros(Padding);
1413
1414     // Remember the offset into the file for this section.
1415     uint64_t SecStart = OS.tell();
1416
1417     writeRelocations(Asm, *RelSection->getAssociatedSection());
1418
1419     uint64_t SecEnd = OS.tell();
1420     SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd);
1421   }
1422
1423   writeSymbolTable(Ctx, Layout, SectionOffsets);
1424
1425   {
1426     uint64_t SecStart = OS.tell();
1427     const MCSectionELF *Sec = createStringTable(Ctx);
1428     uint64_t SecEnd = OS.tell();
1429     SectionOffsets[Sec] = std::make_pair(SecStart, SecEnd);
1430   }
1431
1432   uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1433   uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1434   WriteZeros(Padding);
1435
1436   const unsigned SectionHeaderOffset = OS.tell();
1437
1438   // ... then the section header table ...
1439   writeSectionHeader(Asm, Layout, SectionIndexMap, SectionOffsets);
1440
1441   uint16_t NumSections = (SectionTable.size() + 1 >= ELF::SHN_LORESERVE)
1442                              ? (uint16_t)ELF::SHN_UNDEF
1443                              : SectionTable.size() + 1;
1444   if (sys::IsLittleEndianHost != IsLittleEndian)
1445     sys::swapByteOrder(NumSections);
1446   unsigned NumSectionsOffset;
1447
1448   if (is64Bit()) {
1449     uint64_t Val = SectionHeaderOffset;
1450     if (sys::IsLittleEndianHost != IsLittleEndian)
1451       sys::swapByteOrder(Val);
1452     OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1453               offsetof(ELF::Elf64_Ehdr, e_shoff));
1454     NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
1455   } else {
1456     uint32_t Val = SectionHeaderOffset;
1457     if (sys::IsLittleEndianHost != IsLittleEndian)
1458       sys::swapByteOrder(Val);
1459     OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1460               offsetof(ELF::Elf32_Ehdr, e_shoff));
1461     NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
1462   }
1463   OS.pwrite(reinterpret_cast<char *>(&NumSections), sizeof(NumSections),
1464             NumSectionsOffset);
1465 }
1466
1467 bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1468     const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
1469     bool InSet, bool IsPCRel) const {
1470   if (IsPCRel) {
1471     assert(!InSet);
1472     if (::isWeak(SymA.getData()))
1473       return false;
1474   }
1475   return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
1476                                                                 InSet, IsPCRel);
1477 }
1478
1479 bool ELFObjectWriter::isWeak(const MCSymbol &Sym) const {
1480   const MCSymbolData &SD = Sym.getData();
1481   if (::isWeak(SD))
1482     return true;
1483
1484   // It is invalid to replace a reference to a global in a comdat
1485   // with a reference to a local since out of comdat references
1486   // to a local are forbidden.
1487   // We could try to return false for more cases, like the reference
1488   // being in the same comdat or Sym being an alias to another global,
1489   // but it is not clear if it is worth the effort.
1490   if (MCELF::GetBinding(SD) != ELF::STB_GLOBAL)
1491     return false;
1492
1493   if (!Sym.isInSection())
1494     return false;
1495
1496   const auto &Sec = cast<MCSectionELF>(Sym.getSection());
1497   return Sec.getGroup();
1498 }
1499
1500 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1501                                             raw_pwrite_stream &OS,
1502                                             bool IsLittleEndian) {
1503   return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
1504 }