a484c1bf44c3410f39e8e9250f239a4126f00967
[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/MCAsmLayout.h"
21 #include "llvm/MC/MCAssembler.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCELF.h"
24 #include "llvm/MC/MCELFSymbolFlags.h"
25 #include "llvm/MC/MCExpr.h"
26 #include "llvm/MC/MCFixupKindInfo.h"
27 #include "llvm/MC/MCObjectWriter.h"
28 #include "llvm/MC/MCSectionELF.h"
29 #include "llvm/MC/MCValue.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/Endian.h"
32 #include "llvm/Support/ELF.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include <vector>
35 using namespace llvm;
36
37 #undef  DEBUG_TYPE
38 #define DEBUG_TYPE "reloc-info"
39
40 namespace {
41
42 class FragmentWriter {
43   bool IsLittleEndian;
44
45 public:
46   FragmentWriter(bool IsLittleEndian);
47   template <typename T> void write(MCDataFragment &F, T Val);
48 };
49
50 class ELFObjectWriter : public MCObjectWriter {
51   FragmentWriter FWriter;
52
53   protected:
54
55     static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
56     static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
57     static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
58     static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
59                            bool Used, bool Renamed);
60     static bool isLocal(const MCSymbolData &Data, bool isSignature,
61                         bool isUsedInReloc);
62     static bool IsELFMetaDataSection(const MCSectionData &SD);
63     static uint64_t DataSectionSize(const MCSectionData &SD);
64     static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
65                                        const MCSectionData &SD);
66     static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
67                                           const MCSectionData &SD);
68
69     void WriteDataSectionData(MCAssembler &Asm,
70                               const MCAsmLayout &Layout,
71                               const MCSectionELF &Section);
72
73     /*static bool isFixupKindX86RIPRel(unsigned Kind) {
74       return Kind == X86::reloc_riprel_4byte ||
75         Kind == X86::reloc_riprel_4byte_movq_load;
76     }*/
77
78     /// ELFSymbolData - Helper struct for containing some precomputed
79     /// information on symbols.
80     struct ELFSymbolData {
81       MCSymbolData *SymbolData;
82       uint64_t StringIndex;
83       uint32_t SectionIndex;
84
85       // Support lexicographic sorting.
86       bool operator<(const ELFSymbolData &RHS) const {
87         return SymbolData->getSymbol().getName() <
88                RHS.SymbolData->getSymbol().getName();
89       }
90     };
91
92     /// The target specific ELF writer instance.
93     std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
94
95     SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
96     SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
97     DenseMap<const MCSymbol *, const MCSymbol *> Renames;
98
99     llvm::DenseMap<const MCSectionData*,
100                    std::vector<ELFRelocationEntry> > Relocations;
101     DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
102
103     /// @}
104     /// @name Symbol Table Data
105     /// @{
106
107     SmallString<256> StringTable;
108     std::vector<uint64_t> FileSymbolData;
109     std::vector<ELFSymbolData> LocalSymbolData;
110     std::vector<ELFSymbolData> ExternalSymbolData;
111     std::vector<ELFSymbolData> UndefinedSymbolData;
112
113     /// @}
114
115     bool NeedsGOT;
116
117     bool NeedsSymtabShndx;
118
119     // This holds the symbol table index of the last local symbol.
120     unsigned LastLocalSymbolIndex;
121     // This holds the .strtab section index.
122     unsigned StringTableIndex;
123     // This holds the .symtab section index.
124     unsigned SymbolTableIndex;
125
126     unsigned ShstrtabIndex;
127
128
129     const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
130                                   const MCValue &Target,
131                                   const MCFragment &F,
132                                   const MCFixup &Fixup,
133                                   bool IsPCRel) const;
134
135     // TargetObjectWriter wrappers.
136     const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
137                                    const MCValue &Target,
138                                    const MCFragment &F,
139                                    const MCFixup &Fixup,
140                                    bool IsPCRel) const {
141       return TargetObjectWriter->ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
142     }
143     const MCSymbol *undefinedExplicitRelSym(const MCValue &Target,
144                                             const MCFixup &Fixup,
145                                             bool IsPCRel) const {
146       return TargetObjectWriter->undefinedExplicitRelSym(Target, Fixup,
147                                                          IsPCRel);
148     }
149
150     bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
151     bool hasRelocationAddend() const {
152       return TargetObjectWriter->hasRelocationAddend();
153     }
154     unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
155                           bool IsPCRel, bool IsRelocWithSymbol,
156                           int64_t Addend) const {
157       return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel,
158                                               IsRelocWithSymbol, Addend);
159     }
160
161   public:
162     ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_ostream &_OS,
163                     bool IsLittleEndian)
164         : MCObjectWriter(_OS, IsLittleEndian), FWriter(IsLittleEndian),
165           TargetObjectWriter(MOTW), NeedsGOT(false), NeedsSymtabShndx(false) {}
166
167     virtual ~ELFObjectWriter();
168
169     void WriteWord(uint64_t W) {
170       if (is64Bit())
171         Write64(W);
172       else
173         Write32(W);
174     }
175
176     template <typename T> void write(MCDataFragment &F, T Value) {
177       FWriter.write(F, Value);
178     }
179
180     void WriteHeader(const MCAssembler &Asm,
181                      uint64_t SectionDataSize,
182                      unsigned NumberOfSections);
183
184     void WriteSymbolEntry(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
185                           uint32_t name, uint8_t info, uint64_t value,
186                           uint64_t size, uint8_t other, uint32_t shndx,
187                           bool Reserved);
188
189     void WriteSymbol(MCDataFragment *SymtabF,  MCDataFragment *ShndxF,
190                      ELFSymbolData &MSD,
191                      const MCAsmLayout &Layout);
192
193     typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
194     void WriteSymbolTable(MCDataFragment *SymtabF,
195                           MCDataFragment *ShndxF,
196                           const MCAssembler &Asm,
197                           const MCAsmLayout &Layout,
198                           const SectionIndexMapTy &SectionIndexMap);
199
200     void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
201                           const MCFragment *Fragment, const MCFixup &Fixup,
202                           MCValue Target, uint64_t &FixedValue) override;
203
204     uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
205                                          const MCSymbol *S);
206
207     // Map from a group section to the signature symbol
208     typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
209     // Map from a signature symbol to the group section
210     typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
211     // Map from a section to the section with the relocations
212     typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
213     // Map from a section to its offset
214     typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
215
216     /// Compute the symbol table data
217     ///
218     /// \param Asm - The assembler.
219     /// \param SectionIndexMap - Maps a section to its index.
220     /// \param RevGroupMap - Maps a signature symbol to the group section.
221     /// \param NumRegularSections - Number of non-relocation sections.
222     void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
223                             const SectionIndexMapTy &SectionIndexMap,
224                             RevGroupMapTy RevGroupMap,
225                             unsigned NumRegularSections);
226
227     void ComputeIndexMap(MCAssembler &Asm,
228                          SectionIndexMapTy &SectionIndexMap,
229                          const RelMapTy &RelMap);
230
231     void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
232                                   RelMapTy &RelMap);
233
234     void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
235                           const RelMapTy &RelMap);
236
237     void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
238                                 SectionIndexMapTy &SectionIndexMap,
239                                 const RelMapTy &RelMap);
240
241     // Create the sections that show up in the symbol table. Currently
242     // those are the .note.GNU-stack section and the group sections.
243     void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
244                                GroupMapTy &GroupMap,
245                                RevGroupMapTy &RevGroupMap,
246                                SectionIndexMapTy &SectionIndexMap,
247                                const RelMapTy &RelMap);
248
249     void ExecutePostLayoutBinding(MCAssembler &Asm,
250                                   const MCAsmLayout &Layout) override;
251
252     void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
253                             const MCAsmLayout &Layout,
254                             const SectionIndexMapTy &SectionIndexMap,
255                             const SectionOffsetMapTy &SectionOffsetMap);
256
257     void ComputeSectionOrder(MCAssembler &Asm,
258                              std::vector<const MCSectionELF*> &Sections);
259
260     void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
261                           uint64_t Address, uint64_t Offset,
262                           uint64_t Size, uint32_t Link, uint32_t Info,
263                           uint64_t Alignment, uint64_t EntrySize);
264
265     void WriteRelocationsFragment(const MCAssembler &Asm,
266                                   MCDataFragment *F,
267                                   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     void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
277     void WriteSection(MCAssembler &Asm,
278                       const SectionIndexMapTy &SectionIndexMap,
279                       uint32_t GroupSymbolIndex,
280                       uint64_t Offset, uint64_t Size, uint64_t Alignment,
281                       const MCSectionELF &Section);
282   };
283 }
284
285 FragmentWriter::FragmentWriter(bool IsLittleEndian)
286     : IsLittleEndian(IsLittleEndian) {}
287
288 template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
289   if (IsLittleEndian)
290     Val = support::endian::byte_swap<T, support::little>(Val);
291   else
292     Val = support::endian::byte_swap<T, support::big>(Val);
293   const char *Start = (const char *)&Val;
294   F.getContents().append(Start, Start + sizeof(T));
295 }
296
297 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
298   const MCFixupKindInfo &FKI =
299     Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
300
301   return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
302 }
303
304 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
305   switch (Variant) {
306   default:
307     return false;
308   case MCSymbolRefExpr::VK_GOT:
309   case MCSymbolRefExpr::VK_PLT:
310   case MCSymbolRefExpr::VK_GOTPCREL:
311   case MCSymbolRefExpr::VK_GOTOFF:
312   case MCSymbolRefExpr::VK_TPOFF:
313   case MCSymbolRefExpr::VK_TLSGD:
314   case MCSymbolRefExpr::VK_GOTTPOFF:
315   case MCSymbolRefExpr::VK_INDNTPOFF:
316   case MCSymbolRefExpr::VK_NTPOFF:
317   case MCSymbolRefExpr::VK_GOTNTPOFF:
318   case MCSymbolRefExpr::VK_TLSLDM:
319   case MCSymbolRefExpr::VK_DTPOFF:
320   case MCSymbolRefExpr::VK_TLSLD:
321     return true;
322   }
323 }
324
325 ELFObjectWriter::~ELFObjectWriter()
326 {}
327
328 // Emit the ELF header.
329 void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
330                                   uint64_t SectionDataSize,
331                                   unsigned NumberOfSections) {
332   // ELF Header
333   // ----------
334   //
335   // Note
336   // ----
337   // emitWord method behaves differently for ELF32 and ELF64, writing
338   // 4 bytes in the former and 8 in the latter.
339
340   Write8(0x7f); // e_ident[EI_MAG0]
341   Write8('E');  // e_ident[EI_MAG1]
342   Write8('L');  // e_ident[EI_MAG2]
343   Write8('F');  // e_ident[EI_MAG3]
344
345   Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
346
347   // e_ident[EI_DATA]
348   Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
349
350   Write8(ELF::EV_CURRENT);        // e_ident[EI_VERSION]
351   // e_ident[EI_OSABI]
352   Write8(TargetObjectWriter->getOSABI());
353   Write8(0);                  // e_ident[EI_ABIVERSION]
354
355   WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
356
357   Write16(ELF::ET_REL);             // e_type
358
359   Write16(TargetObjectWriter->getEMachine()); // e_machine = target
360
361   Write32(ELF::EV_CURRENT);         // e_version
362   WriteWord(0);                    // e_entry, no entry point in .o file
363   WriteWord(0);                    // e_phoff, no program header for .o
364   WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
365             sizeof(ELF::Elf32_Ehdr)));  // e_shoff = sec hdr table off in bytes
366
367   // e_flags = whatever the target wants
368   Write32(Asm.getELFHeaderEFlags());
369
370   // e_ehsize = ELF header size
371   Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
372
373   Write16(0);                  // e_phentsize = prog header entry size
374   Write16(0);                  // e_phnum = # prog header entries = 0
375
376   // e_shentsize = Section header entry size
377   Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
378
379   // e_shnum     = # of section header ents
380   if (NumberOfSections >= ELF::SHN_LORESERVE)
381     Write16(ELF::SHN_UNDEF);
382   else
383     Write16(NumberOfSections);
384
385   // e_shstrndx  = Section # of '.shstrtab'
386   if (ShstrtabIndex >= ELF::SHN_LORESERVE)
387     Write16(ELF::SHN_XINDEX);
388   else
389     Write16(ShstrtabIndex);
390 }
391
392 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
393                                        MCDataFragment *ShndxF, uint32_t name,
394                                        uint8_t info, uint64_t value,
395                                        uint64_t size, uint8_t other,
396                                        uint32_t shndx, bool Reserved) {
397   if (ShndxF) {
398     if (shndx >= ELF::SHN_LORESERVE && !Reserved)
399       write(*ShndxF, shndx);
400     else
401       write(*ShndxF, uint32_t(0));
402   }
403
404   uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
405     uint16_t(ELF::SHN_XINDEX) : shndx;
406
407   if (is64Bit()) {
408     write(*SymtabF, name);  // st_name
409     write(*SymtabF, info);  // st_info
410     write(*SymtabF, other); // st_other
411     write(*SymtabF, Index); // st_shndx
412     write(*SymtabF, value); // st_value
413     write(*SymtabF, size);  // st_size
414   } else {
415     write(*SymtabF, name);            // st_name
416     write(*SymtabF, uint32_t(value)); // st_value
417     write(*SymtabF, uint32_t(size));  // st_size
418     write(*SymtabF, info);            // st_info
419     write(*SymtabF, other);           // st_other
420     write(*SymtabF, Index);           // st_shndx
421   }
422 }
423
424 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &OrigData,
425                                       const MCAsmLayout &Layout) {
426   MCSymbolData *Data = &OrigData;
427   if (Data->isCommon() && Data->isExternal())
428     return Data->getCommonAlignment();
429
430   const MCSymbol *Symbol = &Data->getSymbol();
431   bool IsThumbFunc = OrigData.getFlags() & ELF_Other_ThumbFunc;
432
433   uint64_t Res = 0;
434   if (Symbol->isVariable()) {
435     const MCExpr *Expr = Symbol->getVariableValue();
436     MCValue Value;
437     if (!Expr->EvaluateAsRelocatable(Value, &Layout))
438       llvm_unreachable("Invalid expression");
439
440     assert(!Value.getSymB());
441
442     Res = Value.getConstant();
443
444     if (const MCSymbolRefExpr *A = Value.getSymA()) {
445       Symbol = &A->getSymbol();
446       Data = &Layout.getAssembler().getSymbolData(*Symbol);
447     } else {
448       Symbol = 0;
449       Data = 0;
450     }
451   }
452
453   if (IsThumbFunc)
454     Res |= 1;
455
456   if (!Symbol || !Symbol->isInSection())
457     return Res;
458
459   Res += Layout.getSymbolOffset(Data);
460
461   return Res;
462 }
463
464 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
465                                                const MCAsmLayout &Layout) {
466   // The presence of symbol versions causes undefined symbols and
467   // versions declared with @@@ to be renamed.
468
469   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
470          ie = Asm.symbol_end(); it != ie; ++it) {
471     const MCSymbol &Alias = it->getSymbol();
472     const MCSymbol &Symbol = Alias.AliasedSymbol();
473     MCSymbolData &SD = Asm.getSymbolData(Symbol);
474
475     // Not an alias.
476     if (&Symbol == &Alias)
477       continue;
478
479     StringRef AliasName = Alias.getName();
480     size_t Pos = AliasName.find('@');
481     if (Pos == StringRef::npos)
482       continue;
483
484     // Aliases defined with .symvar copy the binding from the symbol they alias.
485     // This is the first place we are able to copy this information.
486     it->setExternal(SD.isExternal());
487     MCELF::SetBinding(*it, MCELF::GetBinding(SD));
488
489     StringRef Rest = AliasName.substr(Pos);
490     if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
491       continue;
492
493     // FIXME: produce a better error message.
494     if (Symbol.isUndefined() && Rest.startswith("@@") &&
495         !Rest.startswith("@@@"))
496       report_fatal_error("A @@ version cannot be undefined");
497
498     Renames.insert(std::make_pair(&Symbol, &Alias));
499   }
500 }
501
502 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
503   uint8_t Type = newType;
504
505   // Propagation rules:
506   // IFUNC > FUNC > OBJECT > NOTYPE
507   // TLS_OBJECT > OBJECT > NOTYPE
508   //
509   // dont let the new type degrade the old type
510   switch (origType) {
511   default:
512     break;
513   case ELF::STT_GNU_IFUNC:
514     if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
515         Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
516       Type = ELF::STT_GNU_IFUNC;
517     break;
518   case ELF::STT_FUNC:
519     if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
520         Type == ELF::STT_TLS)
521       Type = ELF::STT_FUNC;
522     break;
523   case ELF::STT_OBJECT:
524     if (Type == ELF::STT_NOTYPE)
525       Type = ELF::STT_OBJECT;
526     break;
527   case ELF::STT_TLS:
528     if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
529         Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
530       Type = ELF::STT_TLS;
531     break;
532   }
533
534   return Type;
535 }
536
537 static const MCSymbol *getBaseSymbol(const MCAsmLayout &Layout,
538                                      const MCSymbol &Symbol) {
539   if (!Symbol.isVariable())
540     return &Symbol;
541
542   const MCExpr *Expr = Symbol.getVariableValue();
543   MCValue Value;
544   if (!Expr->EvaluateAsRelocatable(Value, &Layout))
545     llvm_unreachable("Invalid Expression");
546   assert(!Value.getSymB());
547   const MCSymbolRefExpr *A = Value.getSymA();
548   if (!A)
549     return nullptr;
550   return getBaseSymbol(Layout, A->getSymbol());
551 }
552
553 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
554                                   MCDataFragment *ShndxF,
555                                   ELFSymbolData &MSD,
556                                   const MCAsmLayout &Layout) {
557   MCSymbolData &OrigData = *MSD.SymbolData;
558   MCSymbolData &Data =
559     Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
560
561   bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
562     Data.getSymbol().isVariable();
563
564   // Binding and Type share the same byte as upper and lower nibbles
565   uint8_t Binding = MCELF::GetBinding(OrigData);
566   uint8_t Type = MCELF::GetType(OrigData);
567   const MCSymbol *Base = getBaseSymbol(Layout, OrigData.getSymbol());
568   if (Base) {
569     MCSymbolData BaseSD = Layout.getAssembler().getSymbolData(*Base);
570     Type = mergeTypeForSet(Type, MCELF::GetType(BaseSD));
571   }
572   if (OrigData.getFlags() & ELF_Other_ThumbFunc)
573     Type = ELF::STT_FUNC;
574   uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
575
576   // Other and Visibility share the same byte with Visibility using the lower
577   // 2 bits
578   uint8_t Visibility = MCELF::GetVisibility(OrigData);
579   uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
580   Other |= Visibility;
581
582   uint64_t Value = SymbolValue(OrigData, Layout);
583   if (OrigData.getFlags() & ELF_Other_ThumbFunc)
584     Value |= 1;
585   uint64_t Size = 0;
586
587   assert(!(Data.isCommon() && !Data.isExternal()));
588
589   const MCExpr *ESize = Data.getSize();
590   if (ESize) {
591     int64_t Res;
592     if (!ESize->EvaluateAsAbsolute(Res, Layout))
593       report_fatal_error("Size expression must be absolute.");
594     Size = Res;
595   }
596
597   // Write out the symbol table entry
598   WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
599                    Size, Other, MSD.SectionIndex, IsReserved);
600 }
601
602 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
603                                        MCDataFragment *ShndxF,
604                                        const MCAssembler &Asm,
605                                        const MCAsmLayout &Layout,
606                                     const SectionIndexMapTy &SectionIndexMap) {
607   // The string table must be emitted first because we need the index
608   // into the string table for all the symbol names.
609   assert(StringTable.size() && "Missing string table");
610
611   // FIXME: Make sure the start of the symbol table is aligned.
612
613   // The first entry is the undefined symbol entry.
614   WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
615
616   for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
617     WriteSymbolEntry(SymtabF, ShndxF, FileSymbolData[i],
618                      ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
619                      ELF::STV_DEFAULT, ELF::SHN_ABS, true);
620   }
621
622   // Write the symbol table entries.
623   LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
624
625   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
626     ELFSymbolData &MSD = LocalSymbolData[i];
627     WriteSymbol(SymtabF, ShndxF, MSD, Layout);
628   }
629
630   // Write out a symbol table entry for each regular section.
631   for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
632        ++i) {
633     const MCSectionELF &Section =
634       static_cast<const MCSectionELF&>(i->getSection());
635     if (Section.getType() == ELF::SHT_RELA ||
636         Section.getType() == ELF::SHT_REL ||
637         Section.getType() == ELF::SHT_STRTAB ||
638         Section.getType() == ELF::SHT_SYMTAB ||
639         Section.getType() == ELF::SHT_SYMTAB_SHNDX)
640       continue;
641     WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
642                      ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section),
643                      false);
644     LastLocalSymbolIndex++;
645   }
646
647   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
648     ELFSymbolData &MSD = ExternalSymbolData[i];
649     MCSymbolData &Data = *MSD.SymbolData;
650     assert(((Data.getFlags() & ELF_STB_Global) ||
651             (Data.getFlags() & ELF_STB_Weak)) &&
652            "External symbol requires STB_GLOBAL or STB_WEAK flag");
653     WriteSymbol(SymtabF, ShndxF, MSD, Layout);
654     if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
655       LastLocalSymbolIndex++;
656   }
657
658   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
659     ELFSymbolData &MSD = UndefinedSymbolData[i];
660     MCSymbolData &Data = *MSD.SymbolData;
661     WriteSymbol(SymtabF, ShndxF, MSD, Layout);
662     if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
663       LastLocalSymbolIndex++;
664   }
665 }
666
667 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
668                                                const MCValue &Target,
669                                                const MCFragment &F,
670                                                const MCFixup &Fixup,
671                                                bool IsPCRel) const {
672   const MCSymbol &Symbol = Target.getSymA()->getSymbol();
673   const MCSymbol &ASymbol = Symbol.AliasedSymbol();
674   const MCSymbol *Renamed = Renames.lookup(&Symbol);
675   const MCSymbolData &SD = Asm.getSymbolData(Symbol);
676
677   if (ASymbol.isUndefined()) {
678     if (Renamed)
679       return Renamed;
680     return undefinedExplicitRelSym(Target, Fixup, IsPCRel);
681   }
682
683   if (SD.isExternal()) {
684     if (Renamed)
685       return Renamed;
686     return &Symbol;
687   }
688
689   const MCSectionELF &Section =
690     static_cast<const MCSectionELF&>(ASymbol.getSection());
691   const SectionKind secKind = Section.getKind();
692
693   if (secKind.isBSS())
694     return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
695
696   if (secKind.isThreadLocal()) {
697     if (Renamed)
698       return Renamed;
699     return &Symbol;
700   }
701
702   MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
703   const MCSectionELF &Sec2 =
704     static_cast<const MCSectionELF&>(F.getParent()->getSection());
705
706   if (&Sec2 != &Section &&
707       (Kind == MCSymbolRefExpr::VK_PLT ||
708        Kind == MCSymbolRefExpr::VK_GOTPCREL ||
709        Kind == MCSymbolRefExpr::VK_GOTOFF)) {
710     if (Renamed)
711       return Renamed;
712     return &Symbol;
713   }
714
715   if (Section.getFlags() & ELF::SHF_MERGE) {
716     if (Target.getConstant() == 0)
717       return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
718     if (Renamed)
719       return Renamed;
720     return &Symbol;
721   }
722
723   return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
724
725 }
726
727
728 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
729                                        const MCAsmLayout &Layout,
730                                        const MCFragment *Fragment,
731                                        const MCFixup &Fixup,
732                                        MCValue Target,
733                                        uint64_t &FixedValue) {
734   int64_t Addend = 0;
735   int Index = 0;
736   int64_t Value = Target.getConstant();
737   const MCSymbol *RelocSymbol = NULL;
738
739   bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
740   if (!Target.isAbsolute()) {
741     const MCSymbol &Symbol = Target.getSymA()->getSymbol();
742     const MCSymbol &ASymbol = Symbol.AliasedSymbol();
743     RelocSymbol = SymbolToReloc(Asm, Target, *Fragment, Fixup, IsPCRel);
744
745     if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
746       const MCSymbol &SymbolB = RefB->getSymbol();
747       MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
748       IsPCRel = true;
749
750       if (!SDB.getFragment())
751         Asm.getContext().FatalError(
752             Fixup.getLoc(),
753             Twine("symbol '") + SymbolB.getName() +
754                 "' can not be undefined in a subtraction expression");
755
756       // Offset of the symbol in the section
757       int64_t a = Layout.getSymbolOffset(&SDB);
758
759       // Offset of the relocation in the section
760       int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
761       Value += b - a;
762     }
763
764     if (!RelocSymbol) {
765       MCSymbolData &SD = Asm.getSymbolData(ASymbol);
766       MCFragment *F = SD.getFragment();
767
768       if (F) {
769         Index = F->getParent()->getOrdinal() + 1;
770         // Offset of the symbol in the section
771         Value += Layout.getSymbolOffset(&SD);
772       } else {
773         Index = 0;
774       }
775     } else {
776       if (Target.getSymA()->getKind() == MCSymbolRefExpr::VK_WEAKREF)
777         WeakrefUsedInReloc.insert(RelocSymbol);
778       else
779         UsedInReloc.insert(RelocSymbol);
780       Index = -1;
781     }
782     Addend = Value;
783     if (hasRelocationAddend())
784       Value = 0;
785   }
786
787   FixedValue = Value;
788   unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
789                                (RelocSymbol != 0), Addend);
790   MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
791     MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
792   if (RelocNeedsGOT(Modifier))
793     NeedsGOT = true;
794
795   uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
796     Fixup.getOffset();
797
798   if (!hasRelocationAddend())
799     Addend = 0;
800
801   if (is64Bit())
802     assert(isInt<64>(Addend));
803   else
804     assert(isInt<32>(Addend));
805
806   ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend, Fixup);
807   Relocations[Fragment->getParent()].push_back(ERE);
808 }
809
810
811 uint64_t
812 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
813                                              const MCSymbol *S) {
814   MCSymbolData &SD = Asm.getSymbolData(*S);
815   return SD.getIndex();
816 }
817
818 bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
819                                  const MCSymbolData &Data,
820                                  bool Used, bool Renamed) {
821   const MCSymbol &Symbol = Data.getSymbol();
822   if (Symbol.isVariable()) {
823     const MCExpr *Expr = Symbol.getVariableValue();
824     if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
825       if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
826         return false;
827     }
828   }
829
830   if (Used)
831     return true;
832
833   if (Renamed)
834     return false;
835
836   if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
837     return true;
838
839   const MCSymbol &A = Symbol.AliasedSymbol();
840   if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
841     return false;
842
843   bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
844   if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
845     return false;
846
847   if (Symbol.isTemporary())
848     return false;
849
850   return true;
851 }
852
853 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
854                               bool isUsedInReloc) {
855   if (Data.isExternal())
856     return false;
857
858   const MCSymbol &Symbol = Data.getSymbol();
859   const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
860
861   if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
862     if (isSignature && !isUsedInReloc)
863       return true;
864
865     return false;
866   }
867
868   return true;
869 }
870
871 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
872                                       SectionIndexMapTy &SectionIndexMap,
873                                       const RelMapTy &RelMap) {
874   unsigned Index = 1;
875   for (MCAssembler::iterator it = Asm.begin(),
876          ie = Asm.end(); it != ie; ++it) {
877     const MCSectionELF &Section =
878       static_cast<const MCSectionELF &>(it->getSection());
879     if (Section.getType() != ELF::SHT_GROUP)
880       continue;
881     SectionIndexMap[&Section] = Index++;
882   }
883
884   for (MCAssembler::iterator it = Asm.begin(),
885          ie = Asm.end(); it != ie; ++it) {
886     const MCSectionELF &Section =
887       static_cast<const MCSectionELF &>(it->getSection());
888     if (Section.getType() == ELF::SHT_GROUP ||
889         Section.getType() == ELF::SHT_REL ||
890         Section.getType() == ELF::SHT_RELA)
891       continue;
892     SectionIndexMap[&Section] = Index++;
893     const MCSectionELF *RelSection = RelMap.lookup(&Section);
894     if (RelSection)
895       SectionIndexMap[RelSection] = Index++;
896   }
897 }
898
899 void
900 ELFObjectWriter::computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
901                                     const SectionIndexMapTy &SectionIndexMap,
902                                     RevGroupMapTy RevGroupMap,
903                                     unsigned NumRegularSections) {
904   // FIXME: Is this the correct place to do this?
905   // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
906   if (NeedsGOT) {
907     StringRef Name = "_GLOBAL_OFFSET_TABLE_";
908     MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
909     MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
910     Data.setExternal(true);
911     MCELF::SetBinding(Data, ELF::STB_GLOBAL);
912   }
913
914   // Index 0 is always the empty string.
915   StringMap<uint64_t> StringIndexMap;
916   StringTable += '\x00';
917
918   // FIXME: We could optimize suffixes in strtab in the same way we
919   // optimize them in shstrtab.
920
921   for (MCAssembler::const_file_name_iterator it = Asm.file_names_begin(),
922                                             ie = Asm.file_names_end();
923                                             it != ie;
924                                             ++it) {
925     StringRef Name = *it;
926     uint64_t &Entry = StringIndexMap[Name];
927     if (!Entry) {
928       Entry = StringTable.size();
929       StringTable += Name;
930       StringTable += '\x00';
931     }
932     FileSymbolData.push_back(Entry);
933   }
934
935   // Add the data for the symbols.
936   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
937          ie = Asm.symbol_end(); it != ie; ++it) {
938     const MCSymbol &Symbol = it->getSymbol();
939
940     bool Used = UsedInReloc.count(&Symbol);
941     bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
942     bool isSignature = RevGroupMap.count(&Symbol);
943
944     if (!isInSymtab(Asm, *it,
945                     Used || WeakrefUsed || isSignature,
946                     Renames.count(&Symbol)))
947       continue;
948
949     ELFSymbolData MSD;
950     MSD.SymbolData = it;
951     const MCSymbol *BaseSymbol = getBaseSymbol(Layout, Symbol);
952
953     // Undefined symbols are global, but this is the first place we
954     // are able to set it.
955     bool Local = isLocal(*it, isSignature, Used);
956     if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
957       assert(BaseSymbol);
958       MCSymbolData &SD = Asm.getSymbolData(*BaseSymbol);
959       MCELF::SetBinding(*it, ELF::STB_GLOBAL);
960       MCELF::SetBinding(SD, ELF::STB_GLOBAL);
961     }
962
963     if (!BaseSymbol) {
964       MSD.SectionIndex = ELF::SHN_ABS;
965     } else if (it->isCommon()) {
966       assert(!Local);
967       MSD.SectionIndex = ELF::SHN_COMMON;
968     } else if (BaseSymbol->isUndefined()) {
969       if (isSignature && !Used)
970         MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
971       else
972         MSD.SectionIndex = ELF::SHN_UNDEF;
973       if (!Used && WeakrefUsed)
974         MCELF::SetBinding(*it, ELF::STB_WEAK);
975     } else {
976       const MCSectionELF &Section =
977         static_cast<const MCSectionELF&>(BaseSymbol->getSection());
978       MSD.SectionIndex = SectionIndexMap.lookup(&Section);
979       if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
980         NeedsSymtabShndx = true;
981       assert(MSD.SectionIndex && "Invalid section index!");
982     }
983
984     // The @@@ in symbol version is replaced with @ in undefined symbols and
985     // @@ in defined ones.
986     StringRef Name = Symbol.getName();
987     SmallString<32> Buf;
988
989     size_t Pos = Name.find("@@@");
990     if (Pos != StringRef::npos) {
991       Buf += Name.substr(0, Pos);
992       unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
993       Buf += Name.substr(Pos + Skip);
994       Name = Buf;
995     }
996
997     uint64_t &Entry = StringIndexMap[Name];
998     if (!Entry) {
999       Entry = StringTable.size();
1000       StringTable += Name;
1001       StringTable += '\x00';
1002     }
1003     MSD.StringIndex = Entry;
1004     if (MSD.SectionIndex == ELF::SHN_UNDEF)
1005       UndefinedSymbolData.push_back(MSD);
1006     else if (Local)
1007       LocalSymbolData.push_back(MSD);
1008     else
1009       ExternalSymbolData.push_back(MSD);
1010   }
1011
1012   // Symbols are required to be in lexicographic order.
1013   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1014   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1015   array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1016
1017   // Set the symbol indices. Local symbols must come before all other
1018   // symbols with non-local bindings.
1019   unsigned Index = FileSymbolData.size() + 1;
1020   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1021     LocalSymbolData[i].SymbolData->setIndex(Index++);
1022
1023   Index += NumRegularSections;
1024
1025   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1026     ExternalSymbolData[i].SymbolData->setIndex(Index++);
1027   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1028     UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1029
1030   if (Index >= ELF::SHN_LORESERVE)
1031     NeedsSymtabShndx = true;
1032 }
1033
1034 void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
1035                                                MCAsmLayout &Layout,
1036                                                RelMapTy &RelMap) {
1037   for (MCAssembler::const_iterator it = Asm.begin(),
1038          ie = Asm.end(); it != ie; ++it) {
1039     const MCSectionData &SD = *it;
1040     if (Relocations[&SD].empty())
1041       continue;
1042
1043     MCContext &Ctx = Asm.getContext();
1044     const MCSectionELF &Section =
1045       static_cast<const MCSectionELF&>(SD.getSection());
1046
1047     const StringRef SectionName = Section.getSectionName();
1048     std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1049     RelaSectionName += SectionName;
1050
1051     unsigned EntrySize;
1052     if (hasRelocationAddend())
1053       EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1054     else
1055       EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1056
1057     unsigned Flags = 0;
1058     StringRef Group = "";
1059     if (Section.getFlags() & ELF::SHF_GROUP) {
1060       Flags = ELF::SHF_GROUP;
1061       Group = Section.getGroup()->getName();
1062     }
1063
1064     const MCSectionELF *RelaSection =
1065       Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1066                         ELF::SHT_RELA : ELF::SHT_REL, Flags,
1067                         SectionKind::getReadOnly(),
1068                         EntrySize, Group);
1069     RelMap[&Section] = RelaSection;
1070     Asm.getOrCreateSectionData(*RelaSection);
1071   }
1072 }
1073
1074 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1075                                        const RelMapTy &RelMap) {
1076   for (MCAssembler::const_iterator it = Asm.begin(),
1077          ie = Asm.end(); it != ie; ++it) {
1078     const MCSectionData &SD = *it;
1079     const MCSectionELF &Section =
1080       static_cast<const MCSectionELF&>(SD.getSection());
1081
1082     const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1083     if (!RelaSection)
1084       continue;
1085     MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1086     RelaSD.setAlignment(is64Bit() ? 8 : 4);
1087
1088     MCDataFragment *F = new MCDataFragment(&RelaSD);
1089     WriteRelocationsFragment(Asm, F, &*it);
1090   }
1091 }
1092
1093 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1094                                        uint64_t Flags, uint64_t Address,
1095                                        uint64_t Offset, uint64_t Size,
1096                                        uint32_t Link, uint32_t Info,
1097                                        uint64_t Alignment,
1098                                        uint64_t EntrySize) {
1099   Write32(Name);        // sh_name: index into string table
1100   Write32(Type);        // sh_type
1101   WriteWord(Flags);     // sh_flags
1102   WriteWord(Address);   // sh_addr
1103   WriteWord(Offset);    // sh_offset
1104   WriteWord(Size);      // sh_size
1105   Write32(Link);        // sh_link
1106   Write32(Info);        // sh_info
1107   WriteWord(Alignment); // sh_addralign
1108   WriteWord(EntrySize); // sh_entsize
1109 }
1110
1111 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1112                                                MCDataFragment *F,
1113                                                const MCSectionData *SD) {
1114   std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1115
1116   // Sort the relocation entries. Most targets just sort by r_offset, but some
1117   // (e.g., MIPS) have additional constraints.
1118   TargetObjectWriter->sortRelocs(Asm, Relocs);
1119
1120   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1121     ELFRelocationEntry entry = Relocs[e - i - 1];
1122
1123     if (!entry.Index)
1124       ;
1125     // FIXME: this is most likely a bug if index overflows.
1126     else if (entry.Index < 0)
1127       entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1128     else
1129       entry.Index += FileSymbolData.size() + LocalSymbolData.size();
1130     if (is64Bit()) {
1131       write(*F, entry.r_offset);
1132       if (TargetObjectWriter->isN64()) {
1133         write(*F, uint32_t(entry.Index));
1134
1135         write(*F, TargetObjectWriter->getRSsym(entry.Type));
1136         write(*F, TargetObjectWriter->getRType3(entry.Type));
1137         write(*F, TargetObjectWriter->getRType2(entry.Type));
1138         write(*F, TargetObjectWriter->getRType(entry.Type));
1139       }
1140       else {
1141         struct ELF::Elf64_Rela ERE64;
1142         ERE64.setSymbolAndType(entry.Index, entry.Type);
1143         write(*F, ERE64.r_info);
1144       }
1145       if (hasRelocationAddend())
1146         write(*F, entry.r_addend);
1147     } else {
1148       write(*F, uint32_t(entry.r_offset));
1149
1150       struct ELF::Elf32_Rela ERE32;
1151       ERE32.setSymbolAndType(entry.Index, entry.Type);
1152       write(*F, ERE32.r_info);
1153
1154       if (hasRelocationAddend())
1155         write(*F, uint32_t(entry.r_addend));
1156     }
1157   }
1158 }
1159
1160 static int compareBySuffix(const MCSectionELF *const *a,
1161                            const MCSectionELF *const *b) {
1162   const StringRef &NameA = (*a)->getSectionName();
1163   const StringRef &NameB = (*b)->getSectionName();
1164   const unsigned sizeA = NameA.size();
1165   const unsigned sizeB = NameB.size();
1166   const unsigned len = std::min(sizeA, sizeB);
1167   for (unsigned int i = 0; i < len; ++i) {
1168     char ca = NameA[sizeA - i - 1];
1169     char cb = NameB[sizeB - i - 1];
1170     if (ca != cb)
1171       return cb - ca;
1172   }
1173
1174   return sizeB - sizeA;
1175 }
1176
1177 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1178                                              MCAsmLayout &Layout,
1179                                              SectionIndexMapTy &SectionIndexMap,
1180                                              const RelMapTy &RelMap) {
1181   MCContext &Ctx = Asm.getContext();
1182   MCDataFragment *F;
1183
1184   unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1185
1186   // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1187   const MCSectionELF *ShstrtabSection =
1188     Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1189                       SectionKind::getReadOnly());
1190   MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1191   ShstrtabSD.setAlignment(1);
1192
1193   const MCSectionELF *SymtabSection =
1194     Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1195                       SectionKind::getReadOnly(),
1196                       EntrySize, "");
1197   MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1198   SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1199
1200   MCSectionData *SymtabShndxSD = NULL;
1201
1202   if (NeedsSymtabShndx) {
1203     const MCSectionELF *SymtabShndxSection =
1204       Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1205                         SectionKind::getReadOnly(), 4, "");
1206     SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1207     SymtabShndxSD->setAlignment(4);
1208   }
1209
1210   const MCSectionELF *StrtabSection;
1211   StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1212                                     SectionKind::getReadOnly());
1213   MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1214   StrtabSD.setAlignment(1);
1215
1216   ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1217
1218   ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1219   SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1220   StringTableIndex = SectionIndexMap.lookup(StrtabSection);
1221
1222   // Symbol table
1223   F = new MCDataFragment(&SymtabSD);
1224   MCDataFragment *ShndxF = NULL;
1225   if (NeedsSymtabShndx) {
1226     ShndxF = new MCDataFragment(SymtabShndxSD);
1227   }
1228   WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1229
1230   F = new MCDataFragment(&StrtabSD);
1231   F->getContents().append(StringTable.begin(), StringTable.end());
1232
1233   F = new MCDataFragment(&ShstrtabSD);
1234
1235   std::vector<const MCSectionELF*> Sections;
1236   for (MCAssembler::const_iterator it = Asm.begin(),
1237          ie = Asm.end(); it != ie; ++it) {
1238     const MCSectionELF &Section =
1239       static_cast<const MCSectionELF&>(it->getSection());
1240     Sections.push_back(&Section);
1241   }
1242   array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
1243
1244   // Section header string table.
1245   //
1246   // The first entry of a string table holds a null character so skip
1247   // section 0.
1248   uint64_t Index = 1;
1249   F->getContents().push_back('\x00');
1250
1251   for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
1252     const MCSectionELF &Section = *Sections[I];
1253
1254     StringRef Name = Section.getSectionName();
1255     if (I != 0) {
1256       StringRef PreviousName = Sections[I - 1]->getSectionName();
1257       if (PreviousName.endswith(Name)) {
1258         SectionStringTableIndex[&Section] = Index - Name.size() - 1;
1259         continue;
1260       }
1261     }
1262     // Remember the index into the string table so we can write it
1263     // into the sh_name field of the section header table.
1264     SectionStringTableIndex[&Section] = Index;
1265
1266     Index += Name.size() + 1;
1267     F->getContents().append(Name.begin(), Name.end());
1268     F->getContents().push_back('\x00');
1269   }
1270 }
1271
1272 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1273                                             MCAsmLayout &Layout,
1274                                             GroupMapTy &GroupMap,
1275                                             RevGroupMapTy &RevGroupMap,
1276                                             SectionIndexMapTy &SectionIndexMap,
1277                                             const RelMapTy &RelMap) {
1278   // Create the .note.GNU-stack section if needed.
1279   MCContext &Ctx = Asm.getContext();
1280   if (Asm.getNoExecStack()) {
1281     const MCSectionELF *GnuStackSection =
1282       Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1283                         SectionKind::getReadOnly());
1284     Asm.getOrCreateSectionData(*GnuStackSection);
1285   }
1286
1287   // Build the groups
1288   for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1289        it != ie; ++it) {
1290     const MCSectionELF &Section =
1291       static_cast<const MCSectionELF&>(it->getSection());
1292     if (!(Section.getFlags() & ELF::SHF_GROUP))
1293       continue;
1294
1295     const MCSymbol *SignatureSymbol = Section.getGroup();
1296     Asm.getOrCreateSymbolData(*SignatureSymbol);
1297     const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1298     if (!Group) {
1299       Group = Ctx.CreateELFGroupSection();
1300       MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1301       Data.setAlignment(4);
1302       MCDataFragment *F = new MCDataFragment(&Data);
1303       write(*F, uint32_t(ELF::GRP_COMDAT));
1304     }
1305     GroupMap[Group] = SignatureSymbol;
1306   }
1307
1308   ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1309
1310   // Add sections to the groups
1311   for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1312        it != ie; ++it) {
1313     const MCSectionELF &Section =
1314       static_cast<const MCSectionELF&>(it->getSection());
1315     if (!(Section.getFlags() & ELF::SHF_GROUP))
1316       continue;
1317     const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1318     MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1319     // FIXME: we could use the previous fragment
1320     MCDataFragment *F = new MCDataFragment(&Data);
1321     uint32_t Index = SectionIndexMap.lookup(&Section);
1322     write(*F, Index);
1323   }
1324 }
1325
1326 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1327                                    const SectionIndexMapTy &SectionIndexMap,
1328                                    uint32_t GroupSymbolIndex,
1329                                    uint64_t Offset, uint64_t Size,
1330                                    uint64_t Alignment,
1331                                    const MCSectionELF &Section) {
1332   uint64_t sh_link = 0;
1333   uint64_t sh_info = 0;
1334
1335   switch(Section.getType()) {
1336   case ELF::SHT_DYNAMIC:
1337     sh_link = SectionStringTableIndex[&Section];
1338     sh_info = 0;
1339     break;
1340
1341   case ELF::SHT_REL:
1342   case ELF::SHT_RELA: {
1343     const MCSectionELF *SymtabSection;
1344     const MCSectionELF *InfoSection;
1345     SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1346                                                    0,
1347                                                    SectionKind::getReadOnly());
1348     sh_link = SectionIndexMap.lookup(SymtabSection);
1349     assert(sh_link && ".symtab not found");
1350
1351     // Remove ".rel" and ".rela" prefixes.
1352     unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1353     StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1354     StringRef GroupName =
1355         Section.getGroup() ? Section.getGroup()->getName() : "";
1356
1357     InfoSection = Asm.getContext().getELFSection(SectionName, ELF::SHT_PROGBITS,
1358                                                  0, SectionKind::getReadOnly(),
1359                                                  0, GroupName);
1360     sh_info = SectionIndexMap.lookup(InfoSection);
1361     break;
1362   }
1363
1364   case ELF::SHT_SYMTAB:
1365   case ELF::SHT_DYNSYM:
1366     sh_link = StringTableIndex;
1367     sh_info = LastLocalSymbolIndex;
1368     break;
1369
1370   case ELF::SHT_SYMTAB_SHNDX:
1371     sh_link = SymbolTableIndex;
1372     break;
1373
1374   case ELF::SHT_PROGBITS:
1375   case ELF::SHT_STRTAB:
1376   case ELF::SHT_NOBITS:
1377   case ELF::SHT_NOTE:
1378   case ELF::SHT_NULL:
1379   case ELF::SHT_ARM_ATTRIBUTES:
1380   case ELF::SHT_INIT_ARRAY:
1381   case ELF::SHT_FINI_ARRAY:
1382   case ELF::SHT_PREINIT_ARRAY:
1383   case ELF::SHT_X86_64_UNWIND:
1384   case ELF::SHT_MIPS_REGINFO:
1385   case ELF::SHT_MIPS_OPTIONS:
1386     // Nothing to do.
1387     break;
1388
1389   case ELF::SHT_GROUP:
1390     sh_link = SymbolTableIndex;
1391     sh_info = GroupSymbolIndex;
1392     break;
1393
1394   default:
1395     assert(0 && "FIXME: sh_type value not supported!");
1396     break;
1397   }
1398
1399   if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1400       Section.getType() == ELF::SHT_ARM_EXIDX) {
1401     StringRef SecName(Section.getSectionName());
1402     if (SecName == ".ARM.exidx") {
1403       sh_link = SectionIndexMap.lookup(
1404         Asm.getContext().getELFSection(".text",
1405                                        ELF::SHT_PROGBITS,
1406                                        ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
1407                                        SectionKind::getText()));
1408     } else if (SecName.startswith(".ARM.exidx")) {
1409       StringRef GroupName =
1410           Section.getGroup() ? Section.getGroup()->getName() : "";
1411       sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1412           SecName.substr(sizeof(".ARM.exidx") - 1), ELF::SHT_PROGBITS,
1413           ELF::SHF_EXECINSTR | ELF::SHF_ALLOC, SectionKind::getText(), 0,
1414           GroupName));
1415     }
1416   }
1417
1418   WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1419                    Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1420                    Alignment, Section.getEntrySize());
1421 }
1422
1423 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1424   return SD.getOrdinal() == ~UINT32_C(0) &&
1425     !SD.getSection().isVirtualSection();
1426 }
1427
1428 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1429   uint64_t Ret = 0;
1430   for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1431        ++i) {
1432     const MCFragment &F = *i;
1433     assert(F.getKind() == MCFragment::FT_Data);
1434     Ret += cast<MCDataFragment>(F).getContents().size();
1435   }
1436   return Ret;
1437 }
1438
1439 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1440                                              const MCSectionData &SD) {
1441   if (IsELFMetaDataSection(SD))
1442     return DataSectionSize(SD);
1443   return Layout.getSectionFileSize(&SD);
1444 }
1445
1446 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1447                                                 const MCSectionData &SD) {
1448   if (IsELFMetaDataSection(SD))
1449     return DataSectionSize(SD);
1450   return Layout.getSectionAddressSize(&SD);
1451 }
1452
1453 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1454                                            const MCAsmLayout &Layout,
1455                                            const MCSectionELF &Section) {
1456   const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1457
1458   uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1459   WriteZeros(Padding);
1460
1461   if (IsELFMetaDataSection(SD)) {
1462     for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1463          ++i) {
1464       const MCFragment &F = *i;
1465       assert(F.getKind() == MCFragment::FT_Data);
1466       WriteBytes(cast<MCDataFragment>(F).getContents());
1467     }
1468   } else {
1469     Asm.writeSectionData(&SD, Layout);
1470   }
1471 }
1472
1473 void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1474                                          const GroupMapTy &GroupMap,
1475                                          const MCAsmLayout &Layout,
1476                                       const SectionIndexMapTy &SectionIndexMap,
1477                                    const SectionOffsetMapTy &SectionOffsetMap) {
1478   const unsigned NumSections = Asm.size() + 1;
1479
1480   std::vector<const MCSectionELF*> Sections;
1481   Sections.resize(NumSections - 1);
1482
1483   for (SectionIndexMapTy::const_iterator i=
1484          SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1485     const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1486     Sections[p.second - 1] = p.first;
1487   }
1488
1489   // Null section first.
1490   uint64_t FirstSectionSize =
1491     NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1492   uint32_t FirstSectionLink =
1493     ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1494   WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1495
1496   for (unsigned i = 0; i < NumSections - 1; ++i) {
1497     const MCSectionELF &Section = *Sections[i];
1498     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1499     uint32_t GroupSymbolIndex;
1500     if (Section.getType() != ELF::SHT_GROUP)
1501       GroupSymbolIndex = 0;
1502     else
1503       GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1504                                                      GroupMap.lookup(&Section));
1505
1506     uint64_t Size = GetSectionAddressSize(Layout, SD);
1507
1508     WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1509                  SectionOffsetMap.lookup(&Section), Size,
1510                  SD.getAlignment(), Section);
1511   }
1512 }
1513
1514 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1515                                   std::vector<const MCSectionELF*> &Sections) {
1516   for (MCAssembler::iterator it = Asm.begin(),
1517          ie = Asm.end(); it != ie; ++it) {
1518     const MCSectionELF &Section =
1519       static_cast<const MCSectionELF &>(it->getSection());
1520     if (Section.getType() == ELF::SHT_GROUP)
1521       Sections.push_back(&Section);
1522   }
1523
1524   for (MCAssembler::iterator it = Asm.begin(),
1525          ie = Asm.end(); it != ie; ++it) {
1526     const MCSectionELF &Section =
1527       static_cast<const MCSectionELF &>(it->getSection());
1528     if (Section.getType() != ELF::SHT_GROUP &&
1529         Section.getType() != ELF::SHT_REL &&
1530         Section.getType() != ELF::SHT_RELA)
1531       Sections.push_back(&Section);
1532   }
1533
1534   for (MCAssembler::iterator it = Asm.begin(),
1535          ie = Asm.end(); it != ie; ++it) {
1536     const MCSectionELF &Section =
1537       static_cast<const MCSectionELF &>(it->getSection());
1538     if (Section.getType() == ELF::SHT_REL ||
1539         Section.getType() == ELF::SHT_RELA)
1540       Sections.push_back(&Section);
1541   }
1542 }
1543
1544 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1545                                   const MCAsmLayout &Layout) {
1546   GroupMapTy GroupMap;
1547   RevGroupMapTy RevGroupMap;
1548   SectionIndexMapTy SectionIndexMap;
1549
1550   unsigned NumUserSections = Asm.size();
1551
1552   DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1553   CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1554
1555   const unsigned NumUserAndRelocSections = Asm.size();
1556   CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1557                         RevGroupMap, SectionIndexMap, RelMap);
1558   const unsigned AllSections = Asm.size();
1559   const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1560
1561   unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1562
1563   // Compute symbol table information.
1564   computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1565                      NumRegularSections);
1566
1567   WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1568
1569   CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1570                          const_cast<MCAsmLayout&>(Layout),
1571                          SectionIndexMap,
1572                          RelMap);
1573
1574   uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1575   uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1576                                     sizeof(ELF::Elf32_Ehdr);
1577   uint64_t FileOff = HeaderSize;
1578
1579   std::vector<const MCSectionELF*> Sections;
1580   ComputeSectionOrder(Asm, Sections);
1581   unsigned NumSections = Sections.size();
1582   SectionOffsetMapTy SectionOffsetMap;
1583   for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1584     const MCSectionELF &Section = *Sections[i];
1585     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1586
1587     FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1588
1589     // Remember the offset into the file for this section.
1590     SectionOffsetMap[&Section] = FileOff;
1591
1592     // Get the size of the section in the output file (including padding).
1593     FileOff += GetSectionFileSize(Layout, SD);
1594   }
1595
1596   FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1597
1598   const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1599
1600   uint64_t SectionHeaderEntrySize = is64Bit() ?
1601     sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1602   FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1603
1604   for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1605     const MCSectionELF &Section = *Sections[i];
1606     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1607
1608     FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1609
1610     // Remember the offset into the file for this section.
1611     SectionOffsetMap[&Section] = FileOff;
1612
1613     // Get the size of the section in the output file (including padding).
1614     FileOff += GetSectionFileSize(Layout, SD);
1615   }
1616
1617   // Write out the ELF header ...
1618   WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
1619
1620   // ... then the regular sections ...
1621   // + because of .shstrtab
1622   for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1623     WriteDataSectionData(Asm, Layout, *Sections[i]);
1624
1625   uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1626   WriteZeros(Padding);
1627
1628   // ... then the section header table ...
1629   WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1630                      SectionOffsetMap);
1631
1632   // ... and then the remaining sections ...
1633   for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1634     WriteDataSectionData(Asm, Layout, *Sections[i]);
1635 }
1636
1637 bool
1638 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1639                                                       const MCSymbolData &DataA,
1640                                                       const MCFragment &FB,
1641                                                       bool InSet,
1642                                                       bool IsPCRel) const {
1643   if (DataA.getFlags() & ELF_STB_Weak || MCELF::GetType(DataA) == ELF::STT_GNU_IFUNC)
1644     return false;
1645   return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1646                                                  Asm, DataA, FB,InSet, IsPCRel);
1647 }
1648
1649 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1650                                             raw_ostream &OS,
1651                                             bool IsLittleEndian) {
1652   return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
1653 }