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