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