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