Correctly handle an ELF symbol defined with "a = b + expr".
[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
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       return 0;
480     if (Value.getSymB())
481       return 0;
482     Res = Value.getConstant();
483
484     const MCSymbolRefExpr *A = Value.getSymA();
485     if (!A)
486       return Res;
487
488     Symbol = &A->getSymbol();
489     Data = &Layout.getAssembler().getSymbolData(*Symbol);
490   }
491
492   if (!Symbol->isInSection())
493     return 0;
494
495   if (!Data->getFragment())
496     return 0;
497
498   Res += Layout.getSymbolOffset(Data);
499   if (Data->getFlags() & ELF_Other_ThumbFunc)
500     ++Res;
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 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
579                                   MCDataFragment *ShndxF,
580                                   ELFSymbolData &MSD,
581                                   const MCAsmLayout &Layout) {
582   MCSymbolData &OrigData = *MSD.SymbolData;
583   MCSymbolData &Data =
584     Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
585
586   bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
587     Data.getSymbol().isVariable();
588
589   // Binding and Type share the same byte as upper and lower nibbles
590   uint8_t Binding = MCELF::GetBinding(OrigData);
591   uint8_t Type = mergeTypeForSet(MCELF::GetType(OrigData), MCELF::GetType(Data));
592   uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
593
594   // Other and Visibility share the same byte with Visibility using the lower
595   // 2 bits
596   uint8_t Visibility = MCELF::GetVisibility(OrigData);
597   uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
598   Other |= Visibility;
599
600   uint64_t Value = SymbolValue(OrigData, Layout);
601   uint64_t Size = 0;
602
603   assert(!(Data.isCommon() && !Data.isExternal()));
604
605   const MCExpr *ESize = Data.getSize();
606   if (ESize) {
607     int64_t Res;
608     if (!ESize->EvaluateAsAbsolute(Res, Layout))
609       report_fatal_error("Size expression must be absolute.");
610     Size = Res;
611   }
612
613   // Write out the symbol table entry
614   WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
615                    Size, Other, MSD.SectionIndex, IsReserved);
616 }
617
618 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
619                                        MCDataFragment *ShndxF,
620                                        const MCAssembler &Asm,
621                                        const MCAsmLayout &Layout,
622                                     const SectionIndexMapTy &SectionIndexMap) {
623   // The string table must be emitted first because we need the index
624   // into the string table for all the symbol names.
625   assert(StringTable.size() && "Missing string table");
626
627   // FIXME: Make sure the start of the symbol table is aligned.
628
629   // The first entry is the undefined symbol entry.
630   WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
631
632   for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
633     WriteSymbolEntry(SymtabF, ShndxF, FileSymbolData[i],
634                      ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
635                      ELF::STV_DEFAULT, ELF::SHN_ABS, true);
636   }
637
638   // Write the symbol table entries.
639   LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
640
641   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
642     ELFSymbolData &MSD = LocalSymbolData[i];
643     WriteSymbol(SymtabF, ShndxF, MSD, Layout);
644   }
645
646   // Write out a symbol table entry for each regular section.
647   for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
648        ++i) {
649     const MCSectionELF &Section =
650       static_cast<const MCSectionELF&>(i->getSection());
651     if (Section.getType() == ELF::SHT_RELA ||
652         Section.getType() == ELF::SHT_REL ||
653         Section.getType() == ELF::SHT_STRTAB ||
654         Section.getType() == ELF::SHT_SYMTAB ||
655         Section.getType() == ELF::SHT_SYMTAB_SHNDX)
656       continue;
657     WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
658                      ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section),
659                      false);
660     LastLocalSymbolIndex++;
661   }
662
663   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
664     ELFSymbolData &MSD = ExternalSymbolData[i];
665     MCSymbolData &Data = *MSD.SymbolData;
666     assert(((Data.getFlags() & ELF_STB_Global) ||
667             (Data.getFlags() & ELF_STB_Weak)) &&
668            "External symbol requires STB_GLOBAL or STB_WEAK flag");
669     WriteSymbol(SymtabF, ShndxF, MSD, Layout);
670     if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
671       LastLocalSymbolIndex++;
672   }
673
674   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
675     ELFSymbolData &MSD = UndefinedSymbolData[i];
676     MCSymbolData &Data = *MSD.SymbolData;
677     WriteSymbol(SymtabF, ShndxF, MSD, Layout);
678     if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
679       LastLocalSymbolIndex++;
680   }
681 }
682
683 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
684                                                const MCValue &Target,
685                                                const MCFragment &F,
686                                                const MCFixup &Fixup,
687                                                bool IsPCRel) const {
688   const MCSymbol &Symbol = Target.getSymA()->getSymbol();
689   const MCSymbol &ASymbol = Symbol.AliasedSymbol();
690   const MCSymbol *Renamed = Renames.lookup(&Symbol);
691   const MCSymbolData &SD = Asm.getSymbolData(Symbol);
692
693   if (ASymbol.isUndefined()) {
694     if (Renamed)
695       return Renamed;
696     return undefinedExplicitRelSym(Target, Fixup, IsPCRel);
697   }
698
699   if (SD.isExternal()) {
700     if (Renamed)
701       return Renamed;
702     return &Symbol;
703   }
704
705   const MCSectionELF &Section =
706     static_cast<const MCSectionELF&>(ASymbol.getSection());
707   const SectionKind secKind = Section.getKind();
708
709   if (secKind.isBSS())
710     return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
711
712   if (secKind.isThreadLocal()) {
713     if (Renamed)
714       return Renamed;
715     return &Symbol;
716   }
717
718   MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
719   const MCSectionELF &Sec2 =
720     static_cast<const MCSectionELF&>(F.getParent()->getSection());
721
722   if (&Sec2 != &Section &&
723       (Kind == MCSymbolRefExpr::VK_PLT ||
724        Kind == MCSymbolRefExpr::VK_GOTPCREL ||
725        Kind == MCSymbolRefExpr::VK_GOTOFF)) {
726     if (Renamed)
727       return Renamed;
728     return &Symbol;
729   }
730
731   if (Section.getFlags() & ELF::SHF_MERGE) {
732     if (Target.getConstant() == 0)
733       return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
734     if (Renamed)
735       return Renamed;
736     return &Symbol;
737   }
738
739   return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
740
741 }
742
743
744 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
745                                        const MCAsmLayout &Layout,
746                                        const MCFragment *Fragment,
747                                        const MCFixup &Fixup,
748                                        MCValue Target,
749                                        uint64_t &FixedValue) {
750   int64_t Addend = 0;
751   int Index = 0;
752   int64_t Value = Target.getConstant();
753   const MCSymbol *RelocSymbol = NULL;
754
755   bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
756   if (!Target.isAbsolute()) {
757     const MCSymbol &Symbol = Target.getSymA()->getSymbol();
758     const MCSymbol &ASymbol = Symbol.AliasedSymbol();
759     RelocSymbol = SymbolToReloc(Asm, Target, *Fragment, Fixup, IsPCRel);
760
761     if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
762       const MCSymbol &SymbolB = RefB->getSymbol();
763       MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
764       IsPCRel = true;
765
766       if (!SDB.getFragment())
767         Asm.getContext().FatalError(
768             Fixup.getLoc(),
769             Twine("symbol '") + SymbolB.getName() +
770                 "' can not be undefined in a subtraction expression");
771
772       // Offset of the symbol in the section
773       int64_t a = Layout.getSymbolOffset(&SDB);
774
775       // Offset of the relocation in the section
776       int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
777       Value += b - a;
778     }
779
780     if (!RelocSymbol) {
781       MCSymbolData &SD = Asm.getSymbolData(ASymbol);
782       MCFragment *F = SD.getFragment();
783
784       if (F) {
785         Index = F->getParent()->getOrdinal() + 1;
786         // Offset of the symbol in the section
787         Value += Layout.getSymbolOffset(&SD);
788       } else {
789         Index = 0;
790       }
791     } else {
792       if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
793         WeakrefUsedInReloc.insert(RelocSymbol);
794       else
795         UsedInReloc.insert(RelocSymbol);
796       Index = -1;
797     }
798     Addend = Value;
799     if (hasRelocationAddend())
800       Value = 0;
801   }
802
803   FixedValue = Value;
804   unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
805                                (RelocSymbol != 0), Addend);
806   MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
807     MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
808   if (RelocNeedsGOT(Modifier))
809     NeedsGOT = true;
810
811   uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
812     Fixup.getOffset();
813
814   if (!hasRelocationAddend())
815     Addend = 0;
816
817   if (is64Bit())
818     assert(isInt<64>(Addend));
819   else
820     assert(isInt<32>(Addend));
821
822   ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend, Fixup);
823   Relocations[Fragment->getParent()].push_back(ERE);
824 }
825
826
827 uint64_t
828 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
829                                              const MCSymbol *S) {
830   MCSymbolData &SD = Asm.getSymbolData(*S);
831   return SD.getIndex();
832 }
833
834 bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
835                                  const MCSymbolData &Data,
836                                  bool Used, bool Renamed) {
837   if (Data.getFlags() & ELF_Other_Weakref)
838     return false;
839
840   if (Used)
841     return true;
842
843   if (Renamed)
844     return false;
845
846   const MCSymbol &Symbol = Data.getSymbol();
847
848   if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
849     return true;
850
851   const MCSymbol &A = Symbol.AliasedSymbol();
852   if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
853     return false;
854
855   bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
856   if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
857     return false;
858
859   if (Symbol.isTemporary())
860     return false;
861
862   return true;
863 }
864
865 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
866                               bool isUsedInReloc) {
867   if (Data.isExternal())
868     return false;
869
870   const MCSymbol &Symbol = Data.getSymbol();
871   const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
872
873   if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
874     if (isSignature && !isUsedInReloc)
875       return true;
876
877     return false;
878   }
879
880   return true;
881 }
882
883 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
884                                       SectionIndexMapTy &SectionIndexMap,
885                                       const RelMapTy &RelMap) {
886   unsigned Index = 1;
887   for (MCAssembler::iterator it = Asm.begin(),
888          ie = Asm.end(); it != ie; ++it) {
889     const MCSectionELF &Section =
890       static_cast<const MCSectionELF &>(it->getSection());
891     if (Section.getType() != ELF::SHT_GROUP)
892       continue;
893     SectionIndexMap[&Section] = Index++;
894   }
895
896   for (MCAssembler::iterator it = Asm.begin(),
897          ie = Asm.end(); it != ie; ++it) {
898     const MCSectionELF &Section =
899       static_cast<const MCSectionELF &>(it->getSection());
900     if (Section.getType() == ELF::SHT_GROUP ||
901         Section.getType() == ELF::SHT_REL ||
902         Section.getType() == ELF::SHT_RELA)
903       continue;
904     SectionIndexMap[&Section] = Index++;
905     const MCSectionELF *RelSection = RelMap.lookup(&Section);
906     if (RelSection)
907       SectionIndexMap[RelSection] = Index++;
908   }
909 }
910
911 void
912 ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
913                                     const SectionIndexMapTy &SectionIndexMap,
914                                     RevGroupMapTy RevGroupMap,
915                                     unsigned NumRegularSections) {
916   // FIXME: Is this the correct place to do this?
917   // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
918   if (NeedsGOT) {
919     StringRef Name = "_GLOBAL_OFFSET_TABLE_";
920     MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
921     MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
922     Data.setExternal(true);
923     MCELF::SetBinding(Data, ELF::STB_GLOBAL);
924   }
925
926   // Index 0 is always the empty string.
927   StringMap<uint64_t> StringIndexMap;
928   StringTable += '\x00';
929
930   // FIXME: We could optimize suffixes in strtab in the same way we
931   // optimize them in shstrtab.
932
933   for (MCAssembler::const_file_name_iterator it = Asm.file_names_begin(),
934                                             ie = Asm.file_names_end();
935                                             it != ie;
936                                             ++it) {
937     StringRef Name = *it;
938     uint64_t &Entry = StringIndexMap[Name];
939     if (!Entry) {
940       Entry = StringTable.size();
941       StringTable += Name;
942       StringTable += '\x00';
943     }
944     FileSymbolData.push_back(Entry);
945   }
946
947   // Add the data for the symbols.
948   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
949          ie = Asm.symbol_end(); it != ie; ++it) {
950     const MCSymbol &Symbol = it->getSymbol();
951
952     bool Used = UsedInReloc.count(&Symbol);
953     bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
954     bool isSignature = RevGroupMap.count(&Symbol);
955
956     if (!isInSymtab(Asm, *it,
957                     Used || WeakrefUsed || isSignature,
958                     Renames.count(&Symbol)))
959       continue;
960
961     ELFSymbolData MSD;
962     MSD.SymbolData = it;
963     const MCSymbol *BaseSymbol = Symbol.getBaseSymbol(Layout);
964
965     // Undefined symbols are global, but this is the first place we
966     // are able to set it.
967     bool Local = isLocal(*it, isSignature, Used);
968     if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
969       assert(BaseSymbol);
970       MCSymbolData &SD = Asm.getSymbolData(*BaseSymbol);
971       MCELF::SetBinding(*it, ELF::STB_GLOBAL);
972       MCELF::SetBinding(SD, ELF::STB_GLOBAL);
973     }
974
975     if (!BaseSymbol) {
976       MSD.SectionIndex = ELF::SHN_ABS;
977     } else if (it->isCommon()) {
978       assert(!Local);
979       MSD.SectionIndex = ELF::SHN_COMMON;
980     } else if (BaseSymbol->isUndefined()) {
981       if (isSignature && !Used)
982         MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
983       else
984         MSD.SectionIndex = ELF::SHN_UNDEF;
985       if (!Used && WeakrefUsed)
986         MCELF::SetBinding(*it, ELF::STB_WEAK);
987     } else {
988       const MCSectionELF &Section =
989         static_cast<const MCSectionELF&>(BaseSymbol->getSection());
990       MSD.SectionIndex = SectionIndexMap.lookup(&Section);
991       if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
992         NeedsSymtabShndx = true;
993       assert(MSD.SectionIndex && "Invalid section index!");
994     }
995
996     // The @@@ in symbol version is replaced with @ in undefined symbols and
997     // @@ in defined ones.
998     StringRef Name = Symbol.getName();
999     SmallString<32> Buf;
1000
1001     size_t Pos = Name.find("@@@");
1002     if (Pos != StringRef::npos) {
1003       Buf += Name.substr(0, Pos);
1004       unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1005       Buf += Name.substr(Pos + Skip);
1006       Name = Buf;
1007     }
1008
1009     uint64_t &Entry = StringIndexMap[Name];
1010     if (!Entry) {
1011       Entry = StringTable.size();
1012       StringTable += Name;
1013       StringTable += '\x00';
1014     }
1015     MSD.StringIndex = Entry;
1016     if (MSD.SectionIndex == ELF::SHN_UNDEF)
1017       UndefinedSymbolData.push_back(MSD);
1018     else if (Local)
1019       LocalSymbolData.push_back(MSD);
1020     else
1021       ExternalSymbolData.push_back(MSD);
1022   }
1023
1024   // Symbols are required to be in lexicographic order.
1025   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1026   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1027   array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1028
1029   // Set the symbol indices. Local symbols must come before all other
1030   // symbols with non-local bindings.
1031   unsigned Index = FileSymbolData.size() + 1;
1032   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1033     LocalSymbolData[i].SymbolData->setIndex(Index++);
1034
1035   Index += NumRegularSections;
1036
1037   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1038     ExternalSymbolData[i].SymbolData->setIndex(Index++);
1039   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1040     UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1041
1042   if (Index >= ELF::SHN_LORESERVE)
1043     NeedsSymtabShndx = true;
1044 }
1045
1046 void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
1047                                                MCAsmLayout &Layout,
1048                                                RelMapTy &RelMap) {
1049   for (MCAssembler::const_iterator it = Asm.begin(),
1050          ie = Asm.end(); it != ie; ++it) {
1051     const MCSectionData &SD = *it;
1052     if (Relocations[&SD].empty())
1053       continue;
1054
1055     MCContext &Ctx = Asm.getContext();
1056     const MCSectionELF &Section =
1057       static_cast<const MCSectionELF&>(SD.getSection());
1058
1059     const StringRef SectionName = Section.getSectionName();
1060     std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1061     RelaSectionName += SectionName;
1062
1063     unsigned EntrySize;
1064     if (hasRelocationAddend())
1065       EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1066     else
1067       EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1068
1069     unsigned Flags = 0;
1070     StringRef Group = "";
1071     if (Section.getFlags() & ELF::SHF_GROUP) {
1072       Flags = ELF::SHF_GROUP;
1073       Group = Section.getGroup()->getName();
1074     }
1075
1076     const MCSectionELF *RelaSection =
1077       Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1078                         ELF::SHT_RELA : ELF::SHT_REL, Flags,
1079                         SectionKind::getReadOnly(),
1080                         EntrySize, Group);
1081     RelMap[&Section] = RelaSection;
1082     Asm.getOrCreateSectionData(*RelaSection);
1083   }
1084 }
1085
1086 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1087                                        const RelMapTy &RelMap) {
1088   for (MCAssembler::const_iterator it = Asm.begin(),
1089          ie = Asm.end(); it != ie; ++it) {
1090     const MCSectionData &SD = *it;
1091     const MCSectionELF &Section =
1092       static_cast<const MCSectionELF&>(SD.getSection());
1093
1094     const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1095     if (!RelaSection)
1096       continue;
1097     MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1098     RelaSD.setAlignment(is64Bit() ? 8 : 4);
1099
1100     MCDataFragment *F = new MCDataFragment(&RelaSD);
1101     WriteRelocationsFragment(Asm, F, &*it);
1102   }
1103 }
1104
1105 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1106                                        uint64_t Flags, uint64_t Address,
1107                                        uint64_t Offset, uint64_t Size,
1108                                        uint32_t Link, uint32_t Info,
1109                                        uint64_t Alignment,
1110                                        uint64_t EntrySize) {
1111   Write32(Name);        // sh_name: index into string table
1112   Write32(Type);        // sh_type
1113   WriteWord(Flags);     // sh_flags
1114   WriteWord(Address);   // sh_addr
1115   WriteWord(Offset);    // sh_offset
1116   WriteWord(Size);      // sh_size
1117   Write32(Link);        // sh_link
1118   Write32(Info);        // sh_info
1119   WriteWord(Alignment); // sh_addralign
1120   WriteWord(EntrySize); // sh_entsize
1121 }
1122
1123 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1124                                                MCDataFragment *F,
1125                                                const MCSectionData *SD) {
1126   std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1127
1128   // Sort the relocation entries. Most targets just sort by r_offset, but some
1129   // (e.g., MIPS) have additional constraints.
1130   TargetObjectWriter->sortRelocs(Asm, Relocs);
1131
1132   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1133     ELFRelocationEntry entry = Relocs[e - i - 1];
1134
1135     if (!entry.Index)
1136       ;
1137     else if (entry.Index < 0)
1138       entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1139     else
1140       entry.Index += FileSymbolData.size() + LocalSymbolData.size();
1141     if (is64Bit()) {
1142       String64(*F, entry.r_offset);
1143       if (TargetObjectWriter->isN64()) {
1144         String32(*F, entry.Index);
1145
1146         String8(*F, TargetObjectWriter->getRSsym(entry.Type));
1147         String8(*F, TargetObjectWriter->getRType3(entry.Type));
1148         String8(*F, TargetObjectWriter->getRType2(entry.Type));
1149         String8(*F, TargetObjectWriter->getRType(entry.Type));
1150       }
1151       else {
1152         struct ELF::Elf64_Rela ERE64;
1153         ERE64.setSymbolAndType(entry.Index, entry.Type);
1154         String64(*F, ERE64.r_info);
1155       }
1156       if (hasRelocationAddend())
1157         String64(*F, entry.r_addend);
1158     } else {
1159       String32(*F, entry.r_offset);
1160
1161       struct ELF::Elf32_Rela ERE32;
1162       ERE32.setSymbolAndType(entry.Index, entry.Type);
1163       String32(*F, ERE32.r_info);
1164
1165       if (hasRelocationAddend())
1166         String32(*F, entry.r_addend);
1167     }
1168   }
1169 }
1170
1171 static int compareBySuffix(const MCSectionELF *const *a,
1172                            const MCSectionELF *const *b) {
1173   const StringRef &NameA = (*a)->getSectionName();
1174   const StringRef &NameB = (*b)->getSectionName();
1175   const unsigned sizeA = NameA.size();
1176   const unsigned sizeB = NameB.size();
1177   const unsigned len = std::min(sizeA, sizeB);
1178   for (unsigned int i = 0; i < len; ++i) {
1179     char ca = NameA[sizeA - i - 1];
1180     char cb = NameB[sizeB - i - 1];
1181     if (ca != cb)
1182       return cb - ca;
1183   }
1184
1185   return sizeB - sizeA;
1186 }
1187
1188 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1189                                              MCAsmLayout &Layout,
1190                                              SectionIndexMapTy &SectionIndexMap,
1191                                              const RelMapTy &RelMap) {
1192   MCContext &Ctx = Asm.getContext();
1193   MCDataFragment *F;
1194
1195   unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1196
1197   // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1198   const MCSectionELF *ShstrtabSection =
1199     Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1200                       SectionKind::getReadOnly());
1201   MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1202   ShstrtabSD.setAlignment(1);
1203
1204   const MCSectionELF *SymtabSection =
1205     Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1206                       SectionKind::getReadOnly(),
1207                       EntrySize, "");
1208   MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1209   SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1210
1211   MCSectionData *SymtabShndxSD = NULL;
1212
1213   if (NeedsSymtabShndx) {
1214     const MCSectionELF *SymtabShndxSection =
1215       Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1216                         SectionKind::getReadOnly(), 4, "");
1217     SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1218     SymtabShndxSD->setAlignment(4);
1219   }
1220
1221   const MCSectionELF *StrtabSection;
1222   StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1223                                     SectionKind::getReadOnly());
1224   MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1225   StrtabSD.setAlignment(1);
1226
1227   ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1228
1229   ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1230   SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1231   StringTableIndex = SectionIndexMap.lookup(StrtabSection);
1232
1233   // Symbol table
1234   F = new MCDataFragment(&SymtabSD);
1235   MCDataFragment *ShndxF = NULL;
1236   if (NeedsSymtabShndx) {
1237     ShndxF = new MCDataFragment(SymtabShndxSD);
1238   }
1239   WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1240
1241   F = new MCDataFragment(&StrtabSD);
1242   F->getContents().append(StringTable.begin(), StringTable.end());
1243
1244   F = new MCDataFragment(&ShstrtabSD);
1245
1246   std::vector<const MCSectionELF*> Sections;
1247   for (MCAssembler::const_iterator it = Asm.begin(),
1248          ie = Asm.end(); it != ie; ++it) {
1249     const MCSectionELF &Section =
1250       static_cast<const MCSectionELF&>(it->getSection());
1251     Sections.push_back(&Section);
1252   }
1253   array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
1254
1255   // Section header string table.
1256   //
1257   // The first entry of a string table holds a null character so skip
1258   // section 0.
1259   uint64_t Index = 1;
1260   F->getContents().push_back('\x00');
1261
1262   for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
1263     const MCSectionELF &Section = *Sections[I];
1264
1265     StringRef Name = Section.getSectionName();
1266     if (I != 0) {
1267       StringRef PreviousName = Sections[I - 1]->getSectionName();
1268       if (PreviousName.endswith(Name)) {
1269         SectionStringTableIndex[&Section] = Index - Name.size() - 1;
1270         continue;
1271       }
1272     }
1273     // Remember the index into the string table so we can write it
1274     // into the sh_name field of the section header table.
1275     SectionStringTableIndex[&Section] = Index;
1276
1277     Index += Name.size() + 1;
1278     F->getContents().append(Name.begin(), Name.end());
1279     F->getContents().push_back('\x00');
1280   }
1281 }
1282
1283 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1284                                             MCAsmLayout &Layout,
1285                                             GroupMapTy &GroupMap,
1286                                             RevGroupMapTy &RevGroupMap,
1287                                             SectionIndexMapTy &SectionIndexMap,
1288                                             const RelMapTy &RelMap) {
1289   // Create the .note.GNU-stack section if needed.
1290   MCContext &Ctx = Asm.getContext();
1291   if (Asm.getNoExecStack()) {
1292     const MCSectionELF *GnuStackSection =
1293       Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1294                         SectionKind::getReadOnly());
1295     Asm.getOrCreateSectionData(*GnuStackSection);
1296   }
1297
1298   // Build the groups
1299   for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1300        it != ie; ++it) {
1301     const MCSectionELF &Section =
1302       static_cast<const MCSectionELF&>(it->getSection());
1303     if (!(Section.getFlags() & ELF::SHF_GROUP))
1304       continue;
1305
1306     const MCSymbol *SignatureSymbol = Section.getGroup();
1307     Asm.getOrCreateSymbolData(*SignatureSymbol);
1308     const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1309     if (!Group) {
1310       Group = Ctx.CreateELFGroupSection();
1311       MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1312       Data.setAlignment(4);
1313       MCDataFragment *F = new MCDataFragment(&Data);
1314       String32(*F, ELF::GRP_COMDAT);
1315     }
1316     GroupMap[Group] = SignatureSymbol;
1317   }
1318
1319   ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1320
1321   // Add sections to the groups
1322   for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1323        it != ie; ++it) {
1324     const MCSectionELF &Section =
1325       static_cast<const MCSectionELF&>(it->getSection());
1326     if (!(Section.getFlags() & ELF::SHF_GROUP))
1327       continue;
1328     const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1329     MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1330     // FIXME: we could use the previous fragment
1331     MCDataFragment *F = new MCDataFragment(&Data);
1332     unsigned Index = SectionIndexMap.lookup(&Section);
1333     String32(*F, Index);
1334   }
1335 }
1336
1337 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1338                                    const SectionIndexMapTy &SectionIndexMap,
1339                                    uint32_t GroupSymbolIndex,
1340                                    uint64_t Offset, uint64_t Size,
1341                                    uint64_t Alignment,
1342                                    const MCSectionELF &Section) {
1343   uint64_t sh_link = 0;
1344   uint64_t sh_info = 0;
1345
1346   switch(Section.getType()) {
1347   case ELF::SHT_DYNAMIC:
1348     sh_link = SectionStringTableIndex[&Section];
1349     sh_info = 0;
1350     break;
1351
1352   case ELF::SHT_REL:
1353   case ELF::SHT_RELA: {
1354     const MCSectionELF *SymtabSection;
1355     const MCSectionELF *InfoSection;
1356     SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1357                                                    0,
1358                                                    SectionKind::getReadOnly());
1359     sh_link = SectionIndexMap.lookup(SymtabSection);
1360     assert(sh_link && ".symtab not found");
1361
1362     // Remove ".rel" and ".rela" prefixes.
1363     unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1364     StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1365     StringRef GroupName =
1366         Section.getGroup() ? Section.getGroup()->getName() : "";
1367
1368     InfoSection = Asm.getContext().getELFSection(SectionName, ELF::SHT_PROGBITS,
1369                                                  0, SectionKind::getReadOnly(),
1370                                                  0, GroupName);
1371     sh_info = SectionIndexMap.lookup(InfoSection);
1372     break;
1373   }
1374
1375   case ELF::SHT_SYMTAB:
1376   case ELF::SHT_DYNSYM:
1377     sh_link = StringTableIndex;
1378     sh_info = LastLocalSymbolIndex;
1379     break;
1380
1381   case ELF::SHT_SYMTAB_SHNDX:
1382     sh_link = SymbolTableIndex;
1383     break;
1384
1385   case ELF::SHT_PROGBITS:
1386   case ELF::SHT_STRTAB:
1387   case ELF::SHT_NOBITS:
1388   case ELF::SHT_NOTE:
1389   case ELF::SHT_NULL:
1390   case ELF::SHT_ARM_ATTRIBUTES:
1391   case ELF::SHT_INIT_ARRAY:
1392   case ELF::SHT_FINI_ARRAY:
1393   case ELF::SHT_PREINIT_ARRAY:
1394   case ELF::SHT_X86_64_UNWIND:
1395   case ELF::SHT_MIPS_REGINFO:
1396   case ELF::SHT_MIPS_OPTIONS:
1397     // Nothing to do.
1398     break;
1399
1400   case ELF::SHT_GROUP:
1401     sh_link = SymbolTableIndex;
1402     sh_info = GroupSymbolIndex;
1403     break;
1404
1405   default:
1406     assert(0 && "FIXME: sh_type value not supported!");
1407     break;
1408   }
1409
1410   if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1411       Section.getType() == ELF::SHT_ARM_EXIDX) {
1412     StringRef SecName(Section.getSectionName());
1413     if (SecName == ".ARM.exidx") {
1414       sh_link = SectionIndexMap.lookup(
1415         Asm.getContext().getELFSection(".text",
1416                                        ELF::SHT_PROGBITS,
1417                                        ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
1418                                        SectionKind::getText()));
1419     } else if (SecName.startswith(".ARM.exidx")) {
1420       StringRef GroupName =
1421           Section.getGroup() ? Section.getGroup()->getName() : "";
1422       sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1423           SecName.substr(sizeof(".ARM.exidx") - 1), ELF::SHT_PROGBITS,
1424           ELF::SHF_EXECINSTR | ELF::SHF_ALLOC, SectionKind::getText(), 0,
1425           GroupName));
1426     }
1427   }
1428
1429   WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1430                    Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1431                    Alignment, Section.getEntrySize());
1432 }
1433
1434 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1435   return SD.getOrdinal() == ~UINT32_C(0) &&
1436     !SD.getSection().isVirtualSection();
1437 }
1438
1439 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1440   uint64_t Ret = 0;
1441   for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1442        ++i) {
1443     const MCFragment &F = *i;
1444     assert(F.getKind() == MCFragment::FT_Data);
1445     Ret += cast<MCDataFragment>(F).getContents().size();
1446   }
1447   return Ret;
1448 }
1449
1450 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1451                                              const MCSectionData &SD) {
1452   if (IsELFMetaDataSection(SD))
1453     return DataSectionSize(SD);
1454   return Layout.getSectionFileSize(&SD);
1455 }
1456
1457 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1458                                                 const MCSectionData &SD) {
1459   if (IsELFMetaDataSection(SD))
1460     return DataSectionSize(SD);
1461   return Layout.getSectionAddressSize(&SD);
1462 }
1463
1464 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1465                                            const MCAsmLayout &Layout,
1466                                            const MCSectionELF &Section) {
1467   const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1468
1469   uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1470   WriteZeros(Padding);
1471
1472   if (IsELFMetaDataSection(SD)) {
1473     for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1474          ++i) {
1475       const MCFragment &F = *i;
1476       assert(F.getKind() == MCFragment::FT_Data);
1477       WriteBytes(cast<MCDataFragment>(F).getContents());
1478     }
1479   } else {
1480     Asm.writeSectionData(&SD, Layout);
1481   }
1482 }
1483
1484 void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1485                                          const GroupMapTy &GroupMap,
1486                                          const MCAsmLayout &Layout,
1487                                       const SectionIndexMapTy &SectionIndexMap,
1488                                    const SectionOffsetMapTy &SectionOffsetMap) {
1489   const unsigned NumSections = Asm.size() + 1;
1490
1491   std::vector<const MCSectionELF*> Sections;
1492   Sections.resize(NumSections - 1);
1493
1494   for (SectionIndexMapTy::const_iterator i=
1495          SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1496     const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1497     Sections[p.second - 1] = p.first;
1498   }
1499
1500   // Null section first.
1501   uint64_t FirstSectionSize =
1502     NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1503   uint32_t FirstSectionLink =
1504     ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1505   WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1506
1507   for (unsigned i = 0; i < NumSections - 1; ++i) {
1508     const MCSectionELF &Section = *Sections[i];
1509     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1510     uint32_t GroupSymbolIndex;
1511     if (Section.getType() != ELF::SHT_GROUP)
1512       GroupSymbolIndex = 0;
1513     else
1514       GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1515                                                      GroupMap.lookup(&Section));
1516
1517     uint64_t Size = GetSectionAddressSize(Layout, SD);
1518
1519     WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1520                  SectionOffsetMap.lookup(&Section), Size,
1521                  SD.getAlignment(), Section);
1522   }
1523 }
1524
1525 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1526                                   std::vector<const MCSectionELF*> &Sections) {
1527   for (MCAssembler::iterator it = Asm.begin(),
1528          ie = Asm.end(); it != ie; ++it) {
1529     const MCSectionELF &Section =
1530       static_cast<const MCSectionELF &>(it->getSection());
1531     if (Section.getType() == ELF::SHT_GROUP)
1532       Sections.push_back(&Section);
1533   }
1534
1535   for (MCAssembler::iterator it = Asm.begin(),
1536          ie = Asm.end(); it != ie; ++it) {
1537     const MCSectionELF &Section =
1538       static_cast<const MCSectionELF &>(it->getSection());
1539     if (Section.getType() != ELF::SHT_GROUP &&
1540         Section.getType() != ELF::SHT_REL &&
1541         Section.getType() != ELF::SHT_RELA)
1542       Sections.push_back(&Section);
1543   }
1544
1545   for (MCAssembler::iterator it = Asm.begin(),
1546          ie = Asm.end(); it != ie; ++it) {
1547     const MCSectionELF &Section =
1548       static_cast<const MCSectionELF &>(it->getSection());
1549     if (Section.getType() == ELF::SHT_REL ||
1550         Section.getType() == ELF::SHT_RELA)
1551       Sections.push_back(&Section);
1552   }
1553 }
1554
1555 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1556                                   const MCAsmLayout &Layout) {
1557   GroupMapTy GroupMap;
1558   RevGroupMapTy RevGroupMap;
1559   SectionIndexMapTy SectionIndexMap;
1560
1561   unsigned NumUserSections = Asm.size();
1562
1563   DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1564   CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1565
1566   const unsigned NumUserAndRelocSections = Asm.size();
1567   CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1568                         RevGroupMap, SectionIndexMap, RelMap);
1569   const unsigned AllSections = Asm.size();
1570   const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1571
1572   unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1573
1574   // Compute symbol table information.
1575   ComputeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1576                      NumRegularSections);
1577
1578   WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1579
1580   CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1581                          const_cast<MCAsmLayout&>(Layout),
1582                          SectionIndexMap,
1583                          RelMap);
1584
1585   uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1586   uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1587                                     sizeof(ELF::Elf32_Ehdr);
1588   uint64_t FileOff = HeaderSize;
1589
1590   std::vector<const MCSectionELF*> Sections;
1591   ComputeSectionOrder(Asm, Sections);
1592   unsigned NumSections = Sections.size();
1593   SectionOffsetMapTy SectionOffsetMap;
1594   for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1595     const MCSectionELF &Section = *Sections[i];
1596     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1597
1598     FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1599
1600     // Remember the offset into the file for this section.
1601     SectionOffsetMap[&Section] = FileOff;
1602
1603     // Get the size of the section in the output file (including padding).
1604     FileOff += GetSectionFileSize(Layout, SD);
1605   }
1606
1607   FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1608
1609   const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1610
1611   uint64_t SectionHeaderEntrySize = is64Bit() ?
1612     sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1613   FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1614
1615   for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1616     const MCSectionELF &Section = *Sections[i];
1617     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1618
1619     FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1620
1621     // Remember the offset into the file for this section.
1622     SectionOffsetMap[&Section] = FileOff;
1623
1624     // Get the size of the section in the output file (including padding).
1625     FileOff += GetSectionFileSize(Layout, SD);
1626   }
1627
1628   // Write out the ELF header ...
1629   WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
1630
1631   // ... then the regular sections ...
1632   // + because of .shstrtab
1633   for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1634     WriteDataSectionData(Asm, Layout, *Sections[i]);
1635
1636   uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1637   WriteZeros(Padding);
1638
1639   // ... then the section header table ...
1640   WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1641                      SectionOffsetMap);
1642
1643   // ... and then the remaining sections ...
1644   for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1645     WriteDataSectionData(Asm, Layout, *Sections[i]);
1646 }
1647
1648 bool
1649 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1650                                                       const MCSymbolData &DataA,
1651                                                       const MCFragment &FB,
1652                                                       bool InSet,
1653                                                       bool IsPCRel) const {
1654   if (DataA.getFlags() & ELF_STB_Weak || MCELF::GetType(DataA) == ELF::STT_GNU_IFUNC)
1655     return false;
1656   return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1657                                                  Asm, DataA, FB,InSet, IsPCRel);
1658 }
1659
1660 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1661                                             raw_ostream &OS,
1662                                             bool IsLittleEndian) {
1663   return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
1664 }