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