Misc cleanups.
[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/StringSwitch.h"
29
30 #include <vector>
31 using namespace llvm;
32
33 #undef  DEBUG_TYPE
34 #define DEBUG_TYPE "reloc-info"
35
36 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
37   const MCFixupKindInfo &FKI =
38     Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
39
40   return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
41 }
42
43 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
44   switch (Variant) {
45   default:
46     return false;
47   case MCSymbolRefExpr::VK_GOT:
48   case MCSymbolRefExpr::VK_PLT:
49   case MCSymbolRefExpr::VK_GOTPCREL:
50   case MCSymbolRefExpr::VK_GOTOFF:
51   case MCSymbolRefExpr::VK_TPOFF:
52   case MCSymbolRefExpr::VK_TLSGD:
53   case MCSymbolRefExpr::VK_GOTTPOFF:
54   case MCSymbolRefExpr::VK_INDNTPOFF:
55   case MCSymbolRefExpr::VK_NTPOFF:
56   case MCSymbolRefExpr::VK_GOTNTPOFF:
57   case MCSymbolRefExpr::VK_TLSLDM:
58   case MCSymbolRefExpr::VK_DTPOFF:
59   case MCSymbolRefExpr::VK_TLSLD:
60     return true;
61   }
62 }
63
64 ELFObjectWriter::~ELFObjectWriter()
65 {}
66
67 // Emit the ELF header.
68 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
69                                   unsigned NumberOfSections) {
70   // ELF Header
71   // ----------
72   //
73   // Note
74   // ----
75   // emitWord method behaves differently for ELF32 and ELF64, writing
76   // 4 bytes in the former and 8 in the latter.
77
78   Write8(0x7f); // e_ident[EI_MAG0]
79   Write8('E');  // e_ident[EI_MAG1]
80   Write8('L');  // e_ident[EI_MAG2]
81   Write8('F');  // e_ident[EI_MAG3]
82
83   Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
84
85   // e_ident[EI_DATA]
86   Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
87
88   Write8(ELF::EV_CURRENT);        // e_ident[EI_VERSION]
89   // e_ident[EI_OSABI]
90   Write8(TargetObjectWriter->getOSABI());
91   Write8(0);                  // e_ident[EI_ABIVERSION]
92
93   WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
94
95   Write16(ELF::ET_REL);             // e_type
96
97   Write16(TargetObjectWriter->getEMachine()); // e_machine = target
98
99   Write32(ELF::EV_CURRENT);         // e_version
100   WriteWord(0);                    // e_entry, no entry point in .o file
101   WriteWord(0);                    // e_phoff, no program header for .o
102   WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
103             sizeof(ELF::Elf32_Ehdr)));  // e_shoff = sec hdr table off in bytes
104
105   // e_flags = whatever the target wants
106   Write32(getEFlags());
107
108   // e_ehsize = ELF header size
109   Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
110
111   Write16(0);                  // e_phentsize = prog header entry size
112   Write16(0);                  // e_phnum = # prog header entries = 0
113
114   // e_shentsize = Section header entry size
115   Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
116
117   // e_shnum     = # of section header ents
118   if (NumberOfSections >= ELF::SHN_LORESERVE)
119     Write16(ELF::SHN_UNDEF);
120   else
121     Write16(NumberOfSections);
122
123   // e_shstrndx  = Section # of '.shstrtab'
124   if (ShstrtabIndex >= ELF::SHN_LORESERVE)
125     Write16(ELF::SHN_XINDEX);
126   else
127     Write16(ShstrtabIndex);
128 }
129
130 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
131                                        MCDataFragment *ShndxF,
132                                        uint64_t name,
133                                        uint8_t info, uint64_t value,
134                                        uint64_t size, uint8_t other,
135                                        uint32_t shndx,
136                                        bool Reserved) {
137   if (ShndxF) {
138     if (shndx >= ELF::SHN_LORESERVE && !Reserved)
139       String32(*ShndxF, shndx);
140     else
141       String32(*ShndxF, 0);
142   }
143
144   uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
145     uint16_t(ELF::SHN_XINDEX) : shndx;
146
147   if (is64Bit()) {
148     String32(*SymtabF, name);  // st_name
149     String8(*SymtabF, info);   // st_info
150     String8(*SymtabF, other);  // st_other
151     String16(*SymtabF, Index); // st_shndx
152     String64(*SymtabF, value); // st_value
153     String64(*SymtabF, size);  // st_size
154   } else {
155     String32(*SymtabF, name);  // st_name
156     String32(*SymtabF, value); // st_value
157     String32(*SymtabF, size);  // st_size
158     String8(*SymtabF, info);   // st_info
159     String8(*SymtabF, other);  // st_other
160     String16(*SymtabF, Index); // st_shndx
161   }
162 }
163
164 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
165                                       const MCAsmLayout &Layout) {
166   if (Data.isCommon() && Data.isExternal())
167     return Data.getCommonAlignment();
168
169   const MCSymbol &Symbol = Data.getSymbol();
170
171   if (Symbol.isAbsolute() && Symbol.isVariable()) {
172     if (const MCExpr *Value = Symbol.getVariableValue()) {
173       int64_t IntValue;
174       if (Value->EvaluateAsAbsolute(IntValue, Layout))
175         return (uint64_t)IntValue;
176     }
177   }
178
179   if (!Symbol.isInSection())
180     return 0;
181
182
183   if (Data.getFragment()) {
184     if (Data.getFlags() & ELF_Other_ThumbFunc)
185       return Layout.getSymbolOffset(&Data)+1;
186     else
187       return Layout.getSymbolOffset(&Data);
188   }
189
190   return 0;
191 }
192
193 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
194                                                const MCAsmLayout &Layout) {
195   // The presence of symbol versions causes undefined symbols and
196   // versions declared with @@@ to be renamed.
197
198   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
199          ie = Asm.symbol_end(); it != ie; ++it) {
200     const MCSymbol &Alias = it->getSymbol();
201     const MCSymbol &Symbol = Alias.AliasedSymbol();
202     MCSymbolData &SD = Asm.getSymbolData(Symbol);
203
204     // Not an alias.
205     if (&Symbol == &Alias)
206       continue;
207
208     StringRef AliasName = Alias.getName();
209     size_t Pos = AliasName.find('@');
210     if (Pos == StringRef::npos)
211       continue;
212
213     // Aliases defined with .symvar copy the binding from the symbol they alias.
214     // This is the first place we are able to copy this information.
215     it->setExternal(SD.isExternal());
216     MCELF::SetBinding(*it, MCELF::GetBinding(SD));
217
218     StringRef Rest = AliasName.substr(Pos);
219     if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
220       continue;
221
222     // FIXME: produce a better error message.
223     if (Symbol.isUndefined() && Rest.startswith("@@") &&
224         !Rest.startswith("@@@"))
225       report_fatal_error("A @@ version cannot be undefined");
226
227     Renames.insert(std::make_pair(&Symbol, &Alias));
228   }
229 }
230
231 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
232                                   MCDataFragment *ShndxF,
233                                   ELFSymbolData &MSD,
234                                   const MCAsmLayout &Layout) {
235   MCSymbolData &OrigData = *MSD.SymbolData;
236   MCSymbolData &Data =
237     Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
238
239   bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
240     Data.getSymbol().isVariable();
241
242   uint8_t Binding = MCELF::GetBinding(OrigData);
243   uint8_t Visibility = MCELF::GetVisibility(OrigData);
244   uint8_t Type = MCELF::GetType(Data);
245
246   uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
247   uint8_t Other = Visibility;
248
249   uint64_t Value = SymbolValue(Data, Layout);
250   uint64_t Size = 0;
251
252   assert(!(Data.isCommon() && !Data.isExternal()));
253
254   const MCExpr *ESize = Data.getSize();
255   if (ESize) {
256     int64_t Res;
257     if (!ESize->EvaluateAsAbsolute(Res, Layout))
258       report_fatal_error("Size expression must be absolute.");
259     Size = Res;
260   }
261
262   // Write out the symbol table entry
263   WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
264                    Size, Other, MSD.SectionIndex, IsReserved);
265 }
266
267 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
268                                        MCDataFragment *ShndxF,
269                                        const MCAssembler &Asm,
270                                        const MCAsmLayout &Layout,
271                                     const SectionIndexMapTy &SectionIndexMap) {
272   // The string table must be emitted first because we need the index
273   // into the string table for all the symbol names.
274   assert(StringTable.size() && "Missing string table");
275
276   // FIXME: Make sure the start of the symbol table is aligned.
277
278   // The first entry is the undefined symbol entry.
279   WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
280
281   // Write the symbol table entries.
282   LastLocalSymbolIndex = LocalSymbolData.size() + 1;
283   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
284     ELFSymbolData &MSD = LocalSymbolData[i];
285     WriteSymbol(SymtabF, ShndxF, MSD, Layout);
286   }
287
288   // Write out a symbol table entry for each regular section.
289   for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
290        ++i) {
291     const MCSectionELF &Section =
292       static_cast<const MCSectionELF&>(i->getSection());
293     if (Section.getType() == ELF::SHT_RELA ||
294         Section.getType() == ELF::SHT_REL ||
295         Section.getType() == ELF::SHT_STRTAB ||
296         Section.getType() == ELF::SHT_SYMTAB ||
297         Section.getType() == ELF::SHT_SYMTAB_SHNDX)
298       continue;
299     WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
300                      ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section),
301                      false);
302     LastLocalSymbolIndex++;
303   }
304
305   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
306     ELFSymbolData &MSD = ExternalSymbolData[i];
307     MCSymbolData &Data = *MSD.SymbolData;
308     assert(((Data.getFlags() & ELF_STB_Global) ||
309             (Data.getFlags() & ELF_STB_Weak)) &&
310            "External symbol requires STB_GLOBAL or STB_WEAK flag");
311     WriteSymbol(SymtabF, ShndxF, MSD, Layout);
312     if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
313       LastLocalSymbolIndex++;
314   }
315
316   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
317     ELFSymbolData &MSD = UndefinedSymbolData[i];
318     MCSymbolData &Data = *MSD.SymbolData;
319     WriteSymbol(SymtabF, ShndxF, MSD, Layout);
320     if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
321       LastLocalSymbolIndex++;
322   }
323 }
324
325 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
326                                                const MCValue &Target,
327                                                const MCFragment &F, 
328                                                const MCFixup &Fixup,
329                                                bool IsPCRel) const {
330   const MCSymbol &Symbol = Target.getSymA()->getSymbol();
331   const MCSymbol &ASymbol = Symbol.AliasedSymbol();
332   const MCSymbol *Renamed = Renames.lookup(&Symbol);
333   const MCSymbolData &SD = Asm.getSymbolData(Symbol);
334
335   if (ASymbol.isUndefined()) {
336     if (Renamed)
337       return Renamed;
338     return &ASymbol;
339   }
340
341   if (SD.isExternal()) {
342     if (Renamed)
343       return Renamed;
344     return &Symbol;
345   }
346
347   const MCSectionELF &Section =
348     static_cast<const MCSectionELF&>(ASymbol.getSection());
349   const SectionKind secKind = Section.getKind();
350
351   if (secKind.isBSS())
352     return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
353
354   if (secKind.isThreadLocal()) {
355     if (Renamed)
356       return Renamed;
357     return &Symbol;
358   }
359
360   MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
361   const MCSectionELF &Sec2 =
362     static_cast<const MCSectionELF&>(F.getParent()->getSection());
363
364   if (&Sec2 != &Section &&
365       (Kind == MCSymbolRefExpr::VK_PLT ||
366        Kind == MCSymbolRefExpr::VK_GOTPCREL ||
367        Kind == MCSymbolRefExpr::VK_GOTOFF)) {
368     if (Renamed)
369       return Renamed;
370     return &Symbol;
371   }
372
373   if (Section.getFlags() & ELF::SHF_MERGE) {
374     if (Target.getConstant() == 0)
375       return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
376     if (Renamed)
377       return Renamed;
378     return &Symbol;
379   }
380
381   return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
382
383 }
384
385
386 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
387                                        const MCAsmLayout &Layout,
388                                        const MCFragment *Fragment,
389                                        const MCFixup &Fixup,
390                                        MCValue Target,
391                                        uint64_t &FixedValue) {
392   int64_t Addend = 0;
393   int Index = 0;
394   int64_t Value = Target.getConstant();
395   const MCSymbol *RelocSymbol = NULL;
396
397   bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
398   if (!Target.isAbsolute()) {
399     const MCSymbol &Symbol = Target.getSymA()->getSymbol();
400     const MCSymbol &ASymbol = Symbol.AliasedSymbol();
401     RelocSymbol = SymbolToReloc(Asm, Target, *Fragment, Fixup, IsPCRel);
402
403     if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
404       const MCSymbol &SymbolB = RefB->getSymbol();
405       MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
406       IsPCRel = true;
407
408       // Offset of the symbol in the section
409       int64_t a = Layout.getSymbolOffset(&SDB);
410
411       // Offset of the relocation in the section
412       int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
413       Value += b - a;
414     }
415
416     if (!RelocSymbol) {
417       MCSymbolData &SD = Asm.getSymbolData(ASymbol);
418       MCFragment *F = SD.getFragment();
419
420       Index = F->getParent()->getOrdinal() + 1;
421
422       // Offset of the symbol in the section
423       Value += Layout.getSymbolOffset(&SD);
424     } else {
425       if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
426         WeakrefUsedInReloc.insert(RelocSymbol);
427       else
428         UsedInReloc.insert(RelocSymbol);
429       Index = -1;
430     }
431     Addend = Value;
432     // Compensate for the addend on i386.
433     if (is64Bit())
434       Value = 0;
435   }
436
437   FixedValue = Value;
438   unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
439                                (RelocSymbol != 0), Addend);
440   MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
441     MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
442   if (RelocNeedsGOT(Modifier))
443     NeedsGOT = true;
444
445   uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
446     Fixup.getOffset();
447
448   // FIXME: no tests cover this. Is adjustFixupOffset dead code?
449   TargetObjectWriter->adjustFixupOffset(Fixup, RelocOffset);
450
451   if (!hasRelocationAddend())
452     Addend = 0;
453
454   if (is64Bit())
455     assert(isInt<64>(Addend));
456   else
457     assert(isInt<32>(Addend));
458
459   ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
460   Relocations[Fragment->getParent()].push_back(ERE);
461 }
462
463
464 uint64_t
465 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
466                                              const MCSymbol *S) {
467   MCSymbolData &SD = Asm.getSymbolData(*S);
468   return SD.getIndex();
469 }
470
471 bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
472                                  const MCSymbolData &Data,
473                                  bool Used, bool Renamed) {
474   if (Data.getFlags() & ELF_Other_Weakref)
475     return false;
476
477   if (Used)
478     return true;
479
480   if (Renamed)
481     return false;
482
483   const MCSymbol &Symbol = Data.getSymbol();
484
485   if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
486     return true;
487
488   const MCSymbol &A = Symbol.AliasedSymbol();
489   if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
490     return false;
491
492   bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
493   if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
494     return false;
495
496   if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
497     return false;
498
499   if (Symbol.isTemporary())
500     return false;
501
502   return true;
503 }
504
505 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
506                               bool isUsedInReloc) {
507   if (Data.isExternal())
508     return false;
509
510   const MCSymbol &Symbol = Data.getSymbol();
511   const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
512
513   if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
514     if (isSignature && !isUsedInReloc)
515       return true;
516
517     return false;
518   }
519
520   return true;
521 }
522
523 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
524                                       SectionIndexMapTy &SectionIndexMap,
525                                       const RelMapTy &RelMap) {
526   unsigned Index = 1;
527   for (MCAssembler::iterator it = Asm.begin(),
528          ie = Asm.end(); it != ie; ++it) {
529     const MCSectionELF &Section =
530       static_cast<const MCSectionELF &>(it->getSection());
531     if (Section.getType() != ELF::SHT_GROUP)
532       continue;
533     SectionIndexMap[&Section] = Index++;
534   }
535
536   for (MCAssembler::iterator it = Asm.begin(),
537          ie = Asm.end(); it != ie; ++it) {
538     const MCSectionELF &Section =
539       static_cast<const MCSectionELF &>(it->getSection());
540     if (Section.getType() == ELF::SHT_GROUP ||
541         Section.getType() == ELF::SHT_REL ||
542         Section.getType() == ELF::SHT_RELA)
543       continue;
544     SectionIndexMap[&Section] = Index++;
545     const MCSectionELF *RelSection = RelMap.lookup(&Section);
546     if (RelSection)
547       SectionIndexMap[RelSection] = Index++;
548   }
549 }
550
551 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
552                                       const SectionIndexMapTy &SectionIndexMap,
553                                          RevGroupMapTy RevGroupMap,
554                                          unsigned NumRegularSections) {
555   // FIXME: Is this the correct place to do this?
556   // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
557   if (NeedsGOT) {
558     llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
559     MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
560     MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
561     Data.setExternal(true);
562     MCELF::SetBinding(Data, ELF::STB_GLOBAL);
563   }
564
565   // Index 0 is always the empty string.
566   StringMap<uint64_t> StringIndexMap;
567   StringTable += '\x00';
568
569   // FIXME: We could optimize suffixes in strtab in the same way we
570   // optimize them in shstrtab.
571
572   // Add the data for the symbols.
573   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
574          ie = Asm.symbol_end(); it != ie; ++it) {
575     const MCSymbol &Symbol = it->getSymbol();
576
577     bool Used = UsedInReloc.count(&Symbol);
578     bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
579     bool isSignature = RevGroupMap.count(&Symbol);
580
581     if (!isInSymtab(Asm, *it,
582                     Used || WeakrefUsed || isSignature,
583                     Renames.count(&Symbol)))
584       continue;
585
586     ELFSymbolData MSD;
587     MSD.SymbolData = it;
588     const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
589
590     // Undefined symbols are global, but this is the first place we
591     // are able to set it.
592     bool Local = isLocal(*it, isSignature, Used);
593     if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
594       MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
595       MCELF::SetBinding(*it, ELF::STB_GLOBAL);
596       MCELF::SetBinding(SD, ELF::STB_GLOBAL);
597     }
598
599     if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
600       MCELF::SetBinding(*it, ELF::STB_WEAK);
601
602     if (it->isCommon()) {
603       assert(!Local);
604       MSD.SectionIndex = ELF::SHN_COMMON;
605     } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
606       MSD.SectionIndex = ELF::SHN_ABS;
607     } else if (RefSymbol.isUndefined()) {
608       if (isSignature && !Used)
609         MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
610       else
611         MSD.SectionIndex = ELF::SHN_UNDEF;
612     } else {
613       const MCSectionELF &Section =
614         static_cast<const MCSectionELF&>(RefSymbol.getSection());
615       MSD.SectionIndex = SectionIndexMap.lookup(&Section);
616       if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
617         NeedsSymtabShndx = true;
618       assert(MSD.SectionIndex && "Invalid section index!");
619     }
620
621     // The @@@ in symbol version is replaced with @ in undefined symbols and
622     // @@ in defined ones.
623     StringRef Name = Symbol.getName();
624     SmallString<32> Buf;
625
626     size_t Pos = Name.find("@@@");
627     if (Pos != StringRef::npos) {
628       Buf += Name.substr(0, Pos);
629       unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
630       Buf += Name.substr(Pos + Skip);
631       Name = Buf;
632     }
633
634     uint64_t &Entry = StringIndexMap[Name];
635     if (!Entry) {
636       Entry = StringTable.size();
637       StringTable += Name;
638       StringTable += '\x00';
639     }
640     MSD.StringIndex = Entry;
641     if (MSD.SectionIndex == ELF::SHN_UNDEF)
642       UndefinedSymbolData.push_back(MSD);
643     else if (Local)
644       LocalSymbolData.push_back(MSD);
645     else
646       ExternalSymbolData.push_back(MSD);
647   }
648
649   // Symbols are required to be in lexicographic order.
650   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
651   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
652   array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
653
654   // Set the symbol indices. Local symbols must come before all other
655   // symbols with non-local bindings.
656   unsigned Index = 1;
657   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
658     LocalSymbolData[i].SymbolData->setIndex(Index++);
659
660   Index += NumRegularSections;
661
662   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
663     ExternalSymbolData[i].SymbolData->setIndex(Index++);
664   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
665     UndefinedSymbolData[i].SymbolData->setIndex(Index++);
666
667   if (NumRegularSections > ELF::SHN_LORESERVE)
668     NeedsSymtabShndx = true;
669 }
670
671 void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
672                                                MCAsmLayout &Layout,
673                                                RelMapTy &RelMap) {
674   for (MCAssembler::const_iterator it = Asm.begin(),
675          ie = Asm.end(); it != ie; ++it) {
676     const MCSectionData &SD = *it;
677     if (Relocations[&SD].empty())
678       continue;
679
680     MCContext &Ctx = Asm.getContext();
681     const MCSectionELF &Section =
682       static_cast<const MCSectionELF&>(SD.getSection());
683
684     const StringRef SectionName = Section.getSectionName();
685     std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
686     RelaSectionName += SectionName;
687
688     unsigned EntrySize;
689     if (hasRelocationAddend())
690       EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
691     else
692       EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
693
694     const MCSectionELF *RelaSection =
695       Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
696                         ELF::SHT_RELA : ELF::SHT_REL, 0,
697                         SectionKind::getReadOnly(),
698                         EntrySize, "");
699     RelMap[&Section] = RelaSection;
700     Asm.getOrCreateSectionData(*RelaSection);
701   }
702 }
703
704 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
705                                        const RelMapTy &RelMap) {
706   for (MCAssembler::const_iterator it = Asm.begin(),
707          ie = Asm.end(); it != ie; ++it) {
708     const MCSectionData &SD = *it;
709     const MCSectionELF &Section =
710       static_cast<const MCSectionELF&>(SD.getSection());
711
712     const MCSectionELF *RelaSection = RelMap.lookup(&Section);
713     if (!RelaSection)
714       continue;
715     MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
716     RelaSD.setAlignment(is64Bit() ? 8 : 4);
717
718     MCDataFragment *F = new MCDataFragment(&RelaSD);
719     WriteRelocationsFragment(Asm, F, &*it);
720   }
721 }
722
723 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
724                                        uint64_t Flags, uint64_t Address,
725                                        uint64_t Offset, uint64_t Size,
726                                        uint32_t Link, uint32_t Info,
727                                        uint64_t Alignment,
728                                        uint64_t EntrySize) {
729   Write32(Name);        // sh_name: index into string table
730   Write32(Type);        // sh_type
731   WriteWord(Flags);     // sh_flags
732   WriteWord(Address);   // sh_addr
733   WriteWord(Offset);    // sh_offset
734   WriteWord(Size);      // sh_size
735   Write32(Link);        // sh_link
736   Write32(Info);        // sh_info
737   WriteWord(Alignment); // sh_addralign
738   WriteWord(EntrySize); // sh_entsize
739 }
740
741 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
742                                                MCDataFragment *F,
743                                                const MCSectionData *SD) {
744   std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
745   // sort by the r_offset just like gnu as does
746   array_pod_sort(Relocs.begin(), Relocs.end());
747
748   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
749     ELFRelocationEntry entry = Relocs[e - i - 1];
750
751     if (!entry.Index)
752       ;
753     else if (entry.Index < 0)
754       entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
755     else
756       entry.Index += LocalSymbolData.size();
757     if (is64Bit()) {
758       String64(*F, entry.r_offset);
759
760       struct ELF::Elf64_Rela ERE64;
761       ERE64.setSymbolAndType(entry.Index, entry.Type);
762       String64(*F, ERE64.r_info);
763
764       if (hasRelocationAddend())
765         String64(*F, entry.r_addend);
766     } else {
767       String32(*F, entry.r_offset);
768
769       struct ELF::Elf32_Rela ERE32;
770       ERE32.setSymbolAndType(entry.Index, entry.Type);
771       String32(*F, ERE32.r_info);
772
773       if (hasRelocationAddend())
774         String32(*F, entry.r_addend);
775     }
776   }
777 }
778
779 static int compareBySuffix(const void *a, const void *b) {
780   const MCSectionELF *secA = *static_cast<const MCSectionELF* const *>(a);
781   const MCSectionELF *secB = *static_cast<const MCSectionELF* const *>(b);
782   const StringRef &NameA = secA->getSectionName();
783   const StringRef &NameB = secB->getSectionName();
784   const unsigned sizeA = NameA.size();
785   const unsigned sizeB = NameB.size();
786   const unsigned len = std::min(sizeA, sizeB);
787   for (unsigned int i = 0; i < len; ++i) {
788     char ca = NameA[sizeA - i - 1];
789     char cb = NameB[sizeB - i - 1];
790     if (ca != cb)
791       return cb - ca;
792   }
793
794   return sizeB - sizeA;
795 }
796
797 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
798                                              MCAsmLayout &Layout,
799                                              SectionIndexMapTy &SectionIndexMap,
800                                              const RelMapTy &RelMap) {
801   MCContext &Ctx = Asm.getContext();
802   MCDataFragment *F;
803
804   unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
805
806   // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
807   const MCSectionELF *ShstrtabSection =
808     Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
809                       SectionKind::getReadOnly());
810   MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
811   ShstrtabSD.setAlignment(1);
812
813   const MCSectionELF *SymtabSection =
814     Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
815                       SectionKind::getReadOnly(),
816                       EntrySize, "");
817   MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
818   SymtabSD.setAlignment(is64Bit() ? 8 : 4);
819
820   MCSectionData *SymtabShndxSD = NULL;
821
822   if (NeedsSymtabShndx) {
823     const MCSectionELF *SymtabShndxSection =
824       Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
825                         SectionKind::getReadOnly(), 4, "");
826     SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
827     SymtabShndxSD->setAlignment(4);
828   }
829
830   const MCSectionELF *StrtabSection;
831   StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
832                                     SectionKind::getReadOnly());
833   MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
834   StrtabSD.setAlignment(1);
835
836   ComputeIndexMap(Asm, SectionIndexMap, RelMap);
837
838   ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
839   SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
840   StringTableIndex = SectionIndexMap.lookup(StrtabSection);
841
842   // Symbol table
843   F = new MCDataFragment(&SymtabSD);
844   MCDataFragment *ShndxF = NULL;
845   if (NeedsSymtabShndx) {
846     ShndxF = new MCDataFragment(SymtabShndxSD);
847   }
848   WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
849
850   F = new MCDataFragment(&StrtabSD);
851   F->getContents().append(StringTable.begin(), StringTable.end());
852
853   F = new MCDataFragment(&ShstrtabSD);
854
855   std::vector<const MCSectionELF*> Sections;
856   for (MCAssembler::const_iterator it = Asm.begin(),
857          ie = Asm.end(); it != ie; ++it) {
858     const MCSectionELF &Section =
859       static_cast<const MCSectionELF&>(it->getSection());
860     Sections.push_back(&Section);
861   }
862   array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
863
864   // Section header string table.
865   //
866   // The first entry of a string table holds a null character so skip
867   // section 0.
868   uint64_t Index = 1;
869   F->getContents() += '\x00';
870
871   for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
872     const MCSectionELF &Section = *Sections[I];
873
874     StringRef Name = Section.getSectionName();
875     if (I != 0) {
876       StringRef PreviousName = Sections[I - 1]->getSectionName();
877       if (PreviousName.endswith(Name)) {
878         SectionStringTableIndex[&Section] = Index - Name.size() - 1;
879         continue;
880       }
881     }
882     // Remember the index into the string table so we can write it
883     // into the sh_name field of the section header table.
884     SectionStringTableIndex[&Section] = Index;
885
886     Index += Name.size() + 1;
887     F->getContents() += Name;
888     F->getContents() += '\x00';
889   }
890 }
891
892 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
893                                             MCAsmLayout &Layout,
894                                             GroupMapTy &GroupMap,
895                                             RevGroupMapTy &RevGroupMap,
896                                             SectionIndexMapTy &SectionIndexMap,
897                                             const RelMapTy &RelMap) {
898   // Create the .note.GNU-stack section if needed.
899   MCContext &Ctx = Asm.getContext();
900   if (Asm.getNoExecStack()) {
901     const MCSectionELF *GnuStackSection =
902       Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
903                         SectionKind::getReadOnly());
904     Asm.getOrCreateSectionData(*GnuStackSection);
905   }
906
907   // Build the groups
908   for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
909        it != ie; ++it) {
910     const MCSectionELF &Section =
911       static_cast<const MCSectionELF&>(it->getSection());
912     if (!(Section.getFlags() & ELF::SHF_GROUP))
913       continue;
914
915     const MCSymbol *SignatureSymbol = Section.getGroup();
916     Asm.getOrCreateSymbolData(*SignatureSymbol);
917     const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
918     if (!Group) {
919       Group = Ctx.CreateELFGroupSection();
920       MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
921       Data.setAlignment(4);
922       MCDataFragment *F = new MCDataFragment(&Data);
923       String32(*F, ELF::GRP_COMDAT);
924     }
925     GroupMap[Group] = SignatureSymbol;
926   }
927
928   ComputeIndexMap(Asm, SectionIndexMap, RelMap);
929
930   // Add sections to the groups
931   for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
932        it != ie; ++it) {
933     const MCSectionELF &Section =
934       static_cast<const MCSectionELF&>(it->getSection());
935     if (!(Section.getFlags() & ELF::SHF_GROUP))
936       continue;
937     const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
938     MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
939     // FIXME: we could use the previous fragment
940     MCDataFragment *F = new MCDataFragment(&Data);
941     unsigned Index = SectionIndexMap.lookup(&Section);
942     String32(*F, Index);
943   }
944 }
945
946 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
947                                    const SectionIndexMapTy &SectionIndexMap,
948                                    uint32_t GroupSymbolIndex,
949                                    uint64_t Offset, uint64_t Size,
950                                    uint64_t Alignment,
951                                    const MCSectionELF &Section) {
952   uint64_t sh_link = 0;
953   uint64_t sh_info = 0;
954
955   switch(Section.getType()) {
956   case ELF::SHT_DYNAMIC:
957     sh_link = SectionStringTableIndex[&Section];
958     sh_info = 0;
959     break;
960
961   case ELF::SHT_REL:
962   case ELF::SHT_RELA: {
963     const MCSectionELF *SymtabSection;
964     const MCSectionELF *InfoSection;
965     SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
966                                                    0,
967                                                    SectionKind::getReadOnly());
968     sh_link = SectionIndexMap.lookup(SymtabSection);
969     assert(sh_link && ".symtab not found");
970
971     // Remove ".rel" and ".rela" prefixes.
972     unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
973     StringRef SectionName = Section.getSectionName().substr(SecNameLen);
974
975     InfoSection = Asm.getContext().getELFSection(SectionName,
976                                                  ELF::SHT_PROGBITS, 0,
977                                                  SectionKind::getReadOnly());
978     sh_info = SectionIndexMap.lookup(InfoSection);
979     break;
980   }
981
982   case ELF::SHT_SYMTAB:
983   case ELF::SHT_DYNSYM:
984     sh_link = StringTableIndex;
985     sh_info = LastLocalSymbolIndex;
986     break;
987
988   case ELF::SHT_SYMTAB_SHNDX:
989     sh_link = SymbolTableIndex;
990     break;
991
992   case ELF::SHT_PROGBITS:
993   case ELF::SHT_STRTAB:
994   case ELF::SHT_NOBITS:
995   case ELF::SHT_NOTE:
996   case ELF::SHT_NULL:
997   case ELF::SHT_ARM_ATTRIBUTES:
998   case ELF::SHT_INIT_ARRAY:
999   case ELF::SHT_FINI_ARRAY:
1000   case ELF::SHT_PREINIT_ARRAY:
1001   case ELF::SHT_X86_64_UNWIND:
1002     // Nothing to do.
1003     break;
1004
1005   case ELF::SHT_GROUP:
1006     sh_link = SymbolTableIndex;
1007     sh_info = GroupSymbolIndex;
1008     break;
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 remaining 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   return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
1257 }