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