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