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