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