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