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