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