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