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