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