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/ELFObjectWriter.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/MC/MCAssembler.h"
19 #include "llvm/MC/MCAsmLayout.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCELFSymbolFlags.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCObjectWriter.h"
24 #include "llvm/MC/MCSectionELF.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/MC/MCValue.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/ELF.h"
30 #include "llvm/Target/TargetAsmBackend.h"
31 
32 #include "../Target/X86/X86FixupKinds.h"
33 
34 #include <vector>
35 using namespace llvm;
36 
37 namespace {
38 
39   class ELFObjectWriterImpl {
isFixupKindX86PCRel(unsigned Kind)40     static bool isFixupKindX86PCRel(unsigned Kind) {
41       switch (Kind) {
42       default:
43         return false;
44       case X86::reloc_pcrel_1byte:
45       case X86::reloc_pcrel_4byte:
46       case X86::reloc_riprel_4byte:
47       case X86::reloc_riprel_4byte_movq_load:
48         return true;
49       }
50     }
51 
52     /*static bool isFixupKindX86RIPRel(unsigned Kind) {
53       return Kind == X86::reloc_riprel_4byte ||
54         Kind == X86::reloc_riprel_4byte_movq_load;
55     }*/
56 
57 
58     /// ELFSymbolData - Helper struct for containing some precomputed information
59     /// on symbols.
60     struct ELFSymbolData {
61       MCSymbolData *SymbolData;
62       uint64_t StringIndex;
63       uint32_t SectionIndex;
64 
65       // Support lexicographic sorting.
operator <__anone67bd8060111::ELFObjectWriterImpl::ELFSymbolData66       bool operator<(const ELFSymbolData &RHS) const {
67         return SymbolData->getSymbol().getName() <
68                RHS.SymbolData->getSymbol().getName();
69       }
70     };
71 
72     /// @name Relocation Data
73     /// @{
74 
75     struct ELFRelocationEntry {
76       // Make these big enough for both 32-bit and 64-bit
77       uint64_t r_offset;
78       uint64_t r_info;
79       uint64_t r_addend;
80 
81       // Support lexicographic sorting.
operator <__anone67bd8060111::ELFObjectWriterImpl::ELFRelocationEntry82       bool operator<(const ELFRelocationEntry &RE) const {
83         return RE.r_offset < r_offset;
84       }
85     };
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<ELFSymbolData> LocalSymbolData;
97     std::vector<ELFSymbolData> ExternalSymbolData;
98     std::vector<ELFSymbolData> UndefinedSymbolData;
99 
100     /// @}
101 
102     ELFObjectWriter *Writer;
103 
104     raw_ostream &OS;
105 
106     // This holds the current offset into the object file.
107     size_t FileOff;
108 
109     unsigned Is64Bit : 1;
110 
111     bool HasRelocationAddend;
112 
113     // This holds the symbol table index of the last local symbol.
114     unsigned LastLocalSymbolIndex;
115     // This holds the .strtab section index.
116     unsigned StringTableIndex;
117 
118     unsigned ShstrtabIndex;
119 
120   public:
ELFObjectWriterImpl(ELFObjectWriter * _Writer,bool _Is64Bit,bool _HasRelAddend)121     ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
122                         bool _HasRelAddend)
123       : Writer(_Writer), OS(Writer->getStream()), FileOff(0),
124         Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend) {
125     }
126 
Write8(uint8_t Value)127     void Write8(uint8_t Value) { Writer->Write8(Value); }
Write16(uint16_t Value)128     void Write16(uint16_t Value) { Writer->Write16(Value); }
Write32(uint32_t Value)129     void Write32(uint32_t Value) { Writer->Write32(Value); }
130     //void Write64(uint64_t Value) { Writer->Write64(Value); }
WriteZeros(unsigned N)131     void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
132     //void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
133     //  Writer->WriteBytes(Str, ZeroFillSize);
134     //}
135 
WriteWord(uint64_t W)136     void WriteWord(uint64_t W) {
137       if (Is64Bit)
138         Writer->Write64(W);
139       else
140         Writer->Write32(W);
141     }
142 
String8(char * buf,uint8_t Value)143     void String8(char *buf, uint8_t Value) {
144       buf[0] = Value;
145     }
146 
StringLE16(char * buf,uint16_t Value)147     void StringLE16(char *buf, uint16_t Value) {
148       buf[0] = char(Value >> 0);
149       buf[1] = char(Value >> 8);
150     }
151 
StringLE32(char * buf,uint32_t Value)152     void StringLE32(char *buf, uint32_t Value) {
153       StringLE16(buf, uint16_t(Value >> 0));
154       StringLE16(buf + 2, uint16_t(Value >> 16));
155     }
156 
StringLE64(char * buf,uint64_t Value)157     void StringLE64(char *buf, uint64_t Value) {
158       StringLE32(buf, uint32_t(Value >> 0));
159       StringLE32(buf + 4, uint32_t(Value >> 32));
160     }
161 
StringBE16(char * buf,uint16_t Value)162     void StringBE16(char *buf ,uint16_t Value) {
163       buf[0] = char(Value >> 8);
164       buf[1] = char(Value >> 0);
165     }
166 
StringBE32(char * buf,uint32_t Value)167     void StringBE32(char *buf, uint32_t Value) {
168       StringBE16(buf, uint16_t(Value >> 16));
169       StringBE16(buf + 2, uint16_t(Value >> 0));
170     }
171 
StringBE64(char * buf,uint64_t Value)172     void StringBE64(char *buf, uint64_t Value) {
173       StringBE32(buf, uint32_t(Value >> 32));
174       StringBE32(buf + 4, uint32_t(Value >> 0));
175     }
176 
String16(char * buf,uint16_t Value)177     void String16(char *buf, uint16_t Value) {
178       if (Writer->isLittleEndian())
179         StringLE16(buf, Value);
180       else
181         StringBE16(buf, Value);
182     }
183 
String32(char * buf,uint32_t Value)184     void String32(char *buf, uint32_t Value) {
185       if (Writer->isLittleEndian())
186         StringLE32(buf, Value);
187       else
188         StringBE32(buf, Value);
189     }
190 
String64(char * buf,uint64_t Value)191     void String64(char *buf, uint64_t Value) {
192       if (Writer->isLittleEndian())
193         StringLE64(buf, Value);
194       else
195         StringBE64(buf, Value);
196     }
197 
198     void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
199 
200     void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
201                           uint64_t value, uint64_t size,
202                           uint8_t other, uint16_t shndx);
203 
204     void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
205                      const MCAsmLayout &Layout);
206 
207     void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
208                           const MCAsmLayout &Layout);
209 
210     void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
211                           const MCFragment *Fragment, const MCFixup &Fixup,
212                           MCValue Target, uint64_t &FixedValue);
213 
214     uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
215                                          const MCSymbol *S);
216 
217     /// ComputeSymbolTable - Compute the symbol table data
218     ///
219     /// \param StringTable [out] - The string table data.
220     /// \param StringIndexMap [out] - Map from symbol names to offsets in the
221     /// string table.
222     void ComputeSymbolTable(MCAssembler &Asm);
223 
224     void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
225                          const MCSectionData &SD);
226 
WriteRelocations(MCAssembler & Asm,MCAsmLayout & Layout)227     void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
228       for (MCAssembler::const_iterator it = Asm.begin(),
229              ie = Asm.end(); it != ie; ++it) {
230         WriteRelocation(Asm, Layout, *it);
231       }
232     }
233 
234     void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
235 
ExecutePostLayoutBinding(MCAssembler & Asm)236     void ExecutePostLayoutBinding(MCAssembler &Asm) {
237       // Compute symbol table information.
238       ComputeSymbolTable(Asm);
239     }
240 
241     void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
242                           uint64_t Address, uint64_t Offset,
243                           uint64_t Size, uint32_t Link, uint32_t Info,
244                           uint64_t Alignment, uint64_t EntrySize);
245 
246     void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
247                                   const MCSectionData *SD);
248 
249     void WriteObject(const MCAssembler &Asm, const MCAsmLayout &Layout);
250   };
251 
252 }
253 
254 // Emit the ELF header.
WriteHeader(uint64_t SectionDataSize,unsigned NumberOfSections)255 void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
256                                       unsigned NumberOfSections) {
257   // ELF Header
258   // ----------
259   //
260   // Note
261   // ----
262   // emitWord method behaves differently for ELF32 and ELF64, writing
263   // 4 bytes in the former and 8 in the latter.
264 
265   Write8(0x7f); // e_ident[EI_MAG0]
266   Write8('E');  // e_ident[EI_MAG1]
267   Write8('L');  // e_ident[EI_MAG2]
268   Write8('F');  // e_ident[EI_MAG3]
269 
270   Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
271 
272   // e_ident[EI_DATA]
273   Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
274 
275   Write8(ELF::EV_CURRENT);        // e_ident[EI_VERSION]
276   Write8(ELF::ELFOSABI_LINUX);    // e_ident[EI_OSABI]
277   Write8(0);                  // e_ident[EI_ABIVERSION]
278 
279   WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
280 
281   Write16(ELF::ET_REL);             // e_type
282 
283   // FIXME: Make this configurable
284   Write16(Is64Bit ? ELF::EM_X86_64 : ELF::EM_386); // e_machine = target
285 
286   Write32(ELF::EV_CURRENT);         // e_version
287   WriteWord(0);                    // e_entry, no entry point in .o file
288   WriteWord(0);                    // e_phoff, no program header for .o
289   WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
290             sizeof(ELF::Elf32_Ehdr)));  // e_shoff = sec hdr table off in bytes
291 
292   // FIXME: Make this configurable.
293   Write32(0);   // e_flags = whatever the target wants
294 
295   // e_ehsize = ELF header size
296   Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
297 
298   Write16(0);                  // e_phentsize = prog header entry size
299   Write16(0);                  // e_phnum = # prog header entries = 0
300 
301   // e_shentsize = Section header entry size
302   Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
303 
304   // e_shnum     = # of section header ents
305   Write16(NumberOfSections);
306 
307   // e_shstrndx  = Section # of '.shstrtab'
308   Write16(ShstrtabIndex);
309 }
310 
WriteSymbolEntry(MCDataFragment * F,uint64_t name,uint8_t info,uint64_t value,uint64_t size,uint8_t other,uint16_t shndx)311 void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
312                                            uint8_t info, uint64_t value,
313                                            uint64_t size, uint8_t other,
314                                            uint16_t shndx) {
315   if (Is64Bit) {
316     char buf[8];
317 
318     String32(buf, name);
319     F->getContents() += StringRef(buf, 4); // st_name
320 
321     String8(buf, info);
322     F->getContents() += StringRef(buf, 1);  // st_info
323 
324     String8(buf, other);
325     F->getContents() += StringRef(buf, 1); // st_other
326 
327     String16(buf, shndx);
328     F->getContents() += StringRef(buf, 2); // st_shndx
329 
330     String64(buf, value);
331     F->getContents() += StringRef(buf, 8); // st_value
332 
333     String64(buf, size);
334     F->getContents() += StringRef(buf, 8);  // st_size
335   } else {
336     char buf[4];
337 
338     String32(buf, name);
339     F->getContents() += StringRef(buf, 4);  // st_name
340 
341     String32(buf, value);
342     F->getContents() += StringRef(buf, 4); // st_value
343 
344     String32(buf, size);
345     F->getContents() += StringRef(buf, 4);  // st_size
346 
347     String8(buf, info);
348     F->getContents() += StringRef(buf, 1);  // st_info
349 
350     String8(buf, other);
351     F->getContents() += StringRef(buf, 1); // st_other
352 
353     String16(buf, shndx);
354     F->getContents() += StringRef(buf, 2); // st_shndx
355   }
356 }
357 
WriteSymbol(MCDataFragment * F,ELFSymbolData & MSD,const MCAsmLayout & Layout)358 void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
359                                       const MCAsmLayout &Layout) {
360   MCSymbolData &Data = *MSD.SymbolData;
361   uint8_t Info = (Data.getFlags() & 0xff);
362   uint8_t Other = ((Data.getFlags() & 0xf00) >> ELF_STV_Shift);
363   uint64_t Value = 0;
364   uint64_t Size = 0;
365   const MCExpr *ESize;
366 
367   if (Data.isCommon() && Data.isExternal())
368     Value = Data.getCommonAlignment();
369 
370   if (!Data.isCommon())
371     if (MCFragment *FF = Data.getFragment())
372       Value = Layout.getSymbolAddress(&Data) -
373               Layout.getSectionAddress(FF->getParent());
374 
375   ESize = Data.getSize();
376   if (Data.getSize()) {
377     MCValue Res;
378     if (ESize->getKind() == MCExpr::Binary) {
379       const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
380 
381       if (BE->EvaluateAsRelocatable(Res, &Layout)) {
382         MCSymbolData &A =
383           Layout.getAssembler().getSymbolData(Res.getSymA()->getSymbol());
384         MCSymbolData &B =
385           Layout.getAssembler().getSymbolData(Res.getSymB()->getSymbol());
386 
387         Size = Layout.getSymbolAddress(&A) - Layout.getSymbolAddress(&B);
388       }
389     } else if (ESize->getKind() == MCExpr::Constant) {
390       Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
391     } else {
392       assert(0 && "Unsupported size expression");
393     }
394   }
395 
396   // Write out the symbol table entry
397   WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
398                    Size, Other, MSD.SectionIndex);
399 }
400 
WriteSymbolTable(MCDataFragment * F,const MCAssembler & Asm,const MCAsmLayout & Layout)401 void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
402                                            const MCAssembler &Asm,
403                                            const MCAsmLayout &Layout) {
404   // The string table must be emitted first because we need the index
405   // into the string table for all the symbol names.
406   assert(StringTable.size() && "Missing string table");
407 
408   // FIXME: Make sure the start of the symbol table is aligned.
409 
410   // The first entry is the undefined symbol entry.
411   unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
412   F->getContents().append(EntrySize, '\x00');
413 
414   // Write the symbol table entries.
415   LastLocalSymbolIndex = LocalSymbolData.size() + 1;
416   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
417     ELFSymbolData &MSD = LocalSymbolData[i];
418     WriteSymbol(F, MSD, Layout);
419   }
420 
421   // Write out a symbol table entry for each section.
422   // leaving out the just added .symtab which is at
423   // the very end
424   unsigned Index = 1;
425   for (MCAssembler::const_iterator it = Asm.begin(),
426        ie = Asm.end(); it != ie; ++it, ++Index) {
427     const MCSectionELF &Section =
428       static_cast<const MCSectionELF&>(it->getSection());
429     // Leave out relocations so we don't have indexes within
430     // the relocations messed up
431     if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
432       continue;
433     if (Index == Asm.size())
434       continue;
435     WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
436     LastLocalSymbolIndex++;
437   }
438 
439   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
440     ELFSymbolData &MSD = ExternalSymbolData[i];
441     MCSymbolData &Data = *MSD.SymbolData;
442     assert((Data.getFlags() & ELF_STB_Global) &&
443            "External symbol requires STB_GLOBAL flag");
444     WriteSymbol(F, MSD, Layout);
445     if (Data.getFlags() & ELF_STB_Local)
446       LastLocalSymbolIndex++;
447   }
448 
449   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
450     ELFSymbolData &MSD = UndefinedSymbolData[i];
451     MCSymbolData &Data = *MSD.SymbolData;
452     Data.setFlags(Data.getFlags() | ELF_STB_Global);
453     WriteSymbol(F, MSD, Layout);
454     if (Data.getFlags() & ELF_STB_Local)
455       LastLocalSymbolIndex++;
456   }
457 }
458 
459 // FIXME: this is currently X86/X86_64 only
RecordRelocation(const MCAssembler & Asm,const MCAsmLayout & Layout,const MCFragment * Fragment,const MCFixup & Fixup,MCValue Target,uint64_t & FixedValue)460 void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
461                                            const MCAsmLayout &Layout,
462                                            const MCFragment *Fragment,
463                                            const MCFixup &Fixup,
464                                            MCValue Target,
465                                            uint64_t &FixedValue) {
466   int64_t Addend = 0;
467   unsigned Index = 0;
468   int64_t Value = Target.getConstant();
469 
470   if (!Target.isAbsolute()) {
471     const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
472     MCSymbolData &SD = Asm.getSymbolData(*Symbol);
473     const MCSymbolData *Base = Asm.getAtom(Layout, &SD);
474     MCFragment *F = SD.getFragment();
475 
476     if (Base) {
477       if (F && (!Symbol->isInSection() || SD.isCommon()) && !SD.isExternal()) {
478         Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
479         Value += Layout.getSymbolAddress(&SD);
480       } else
481         Index = getSymbolIndexInSymbolTable(Asm, Symbol);
482       if (Base != &SD)
483         Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
484       Addend = Value;
485       // Compensate for the addend on i386.
486       if (Is64Bit)
487         Value = 0;
488     } else {
489       if (F) {
490         // Index of the section in .symtab against this symbol
491         // is being relocated + 2 (empty section + abs. symbols).
492         Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
493 
494         MCSectionData *FSD = F->getParent();
495         // Offset of the symbol in the section
496         Addend = Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
497       } else {
498         FixedValue = Value;
499         return;
500       }
501     }
502   }
503 
504   FixedValue = Value;
505 
506   // determine the type of the relocation
507   bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
508   unsigned Type;
509   if (Is64Bit) {
510     if (IsPCRel) {
511       Type = ELF::R_X86_64_PC32;
512     } else {
513       switch ((unsigned)Fixup.getKind()) {
514       default: llvm_unreachable("invalid fixup kind!");
515       case FK_Data_8: Type = ELF::R_X86_64_64; break;
516       case X86::reloc_pcrel_4byte:
517       case FK_Data_4:
518         // check that the offset fits within a signed long
519         if (isInt<32>(Target.getConstant()))
520           Type = ELF::R_X86_64_32S;
521         else
522           Type = ELF::R_X86_64_32;
523         break;
524       case FK_Data_2: Type = ELF::R_X86_64_16; break;
525       case X86::reloc_pcrel_1byte:
526       case FK_Data_1: Type = ELF::R_X86_64_8; break;
527       }
528     }
529   } else {
530     if (IsPCRel) {
531       Type = ELF::R_386_PC32;
532     } else {
533       switch ((unsigned)Fixup.getKind()) {
534       default: llvm_unreachable("invalid fixup kind!");
535       case X86::reloc_pcrel_4byte:
536       case FK_Data_4: Type = ELF::R_386_32; break;
537       case FK_Data_2: Type = ELF::R_386_16; break;
538       case X86::reloc_pcrel_1byte:
539       case FK_Data_1: Type = ELF::R_386_8; break;
540       }
541     }
542   }
543 
544   ELFRelocationEntry ERE;
545 
546   if (Is64Bit) {
547     struct ELF::Elf64_Rela ERE64;
548     ERE64.setSymbolAndType(Index, Type);
549     ERE.r_info = ERE64.r_info;
550   } else {
551     struct ELF::Elf32_Rela ERE32;
552     ERE32.setSymbolAndType(Index, Type);
553     ERE.r_info = ERE32.r_info;
554   }
555 
556   ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
557 
558   if (HasRelocationAddend)
559     ERE.r_addend = Addend;
560   else
561     ERE.r_addend = 0; // Silence compiler warning.
562 
563   Relocations[Fragment->getParent()].push_back(ERE);
564 }
565 
566 uint64_t
getSymbolIndexInSymbolTable(const MCAssembler & Asm,const MCSymbol * S)567 ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
568                                                  const MCSymbol *S) {
569   MCSymbolData &SD = Asm.getSymbolData(*S);
570 
571   // Local symbol.
572   if (!SD.isExternal() && !S->isUndefined())
573     return SD.getIndex() + /* empty symbol */ 1;
574 
575   // External or undefined symbol.
576   return SD.getIndex() + Asm.size() + /* empty symbol */ 1;
577 }
578 
ComputeSymbolTable(MCAssembler & Asm)579 void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
580   // Build section lookup table.
581   DenseMap<const MCSection*, uint8_t> SectionIndexMap;
582   unsigned Index = 1;
583   for (MCAssembler::iterator it = Asm.begin(),
584          ie = Asm.end(); it != ie; ++it, ++Index)
585     SectionIndexMap[&it->getSection()] = Index;
586 
587   // Index 0 is always the empty string.
588   StringMap<uint64_t> StringIndexMap;
589   StringTable += '\x00';
590 
591   // Add the data for local symbols.
592   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
593          ie = Asm.symbol_end(); it != ie; ++it) {
594     const MCSymbol &Symbol = it->getSymbol();
595 
596     // Ignore non-linker visible symbols.
597     if (!Asm.isSymbolLinkerVisible(Symbol))
598       continue;
599 
600     if (it->isExternal() || Symbol.isUndefined())
601       continue;
602 
603     uint64_t &Entry = StringIndexMap[Symbol.getName()];
604     if (!Entry) {
605       Entry = StringTable.size();
606       StringTable += Symbol.getName();
607       StringTable += '\x00';
608     }
609 
610     ELFSymbolData MSD;
611     MSD.SymbolData = it;
612     MSD.StringIndex = Entry;
613 
614     if (Symbol.isAbsolute()) {
615       MSD.SectionIndex = ELF::SHN_ABS;
616       LocalSymbolData.push_back(MSD);
617     } else {
618       MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
619       assert(MSD.SectionIndex && "Invalid section index!");
620       LocalSymbolData.push_back(MSD);
621     }
622   }
623 
624   // Now add non-local symbols.
625   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
626          ie = Asm.symbol_end(); it != ie; ++it) {
627     const MCSymbol &Symbol = it->getSymbol();
628 
629     // Ignore non-linker visible symbols.
630     if (!Asm.isSymbolLinkerVisible(Symbol))
631       continue;
632 
633     if (!it->isExternal() && !Symbol.isUndefined())
634       continue;
635 
636     uint64_t &Entry = StringIndexMap[Symbol.getName()];
637     if (!Entry) {
638       Entry = StringTable.size();
639       StringTable += Symbol.getName();
640       StringTable += '\x00';
641     }
642 
643     ELFSymbolData MSD;
644     MSD.SymbolData = it;
645     MSD.StringIndex = Entry;
646 
647     if (Symbol.isUndefined()) {
648       MSD.SectionIndex = ELF::SHN_UNDEF;
649       // XXX: for some reason we dont Emit* this
650       it->setFlags(it->getFlags() | ELF_STB_Global);
651       UndefinedSymbolData.push_back(MSD);
652     } else if (Symbol.isAbsolute()) {
653       MSD.SectionIndex = ELF::SHN_ABS;
654       ExternalSymbolData.push_back(MSD);
655     } else if (it->isCommon()) {
656       MSD.SectionIndex = ELF::SHN_COMMON;
657       ExternalSymbolData.push_back(MSD);
658     } else {
659       MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
660       assert(MSD.SectionIndex && "Invalid section index!");
661       ExternalSymbolData.push_back(MSD);
662     }
663   }
664 
665   // Symbols are required to be in lexicographic order.
666   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
667   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
668   array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
669 
670   // Set the symbol indices. Local symbols must come before all other
671   // symbols with non-local bindings.
672   Index = 0;
673   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
674     LocalSymbolData[i].SymbolData->setIndex(Index++);
675   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
676     ExternalSymbolData[i].SymbolData->setIndex(Index++);
677   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
678     UndefinedSymbolData[i].SymbolData->setIndex(Index++);
679 }
680 
WriteRelocation(MCAssembler & Asm,MCAsmLayout & Layout,const MCSectionData & SD)681 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
682                                           const MCSectionData &SD) {
683   if (!Relocations[&SD].empty()) {
684     MCContext &Ctx = Asm.getContext();
685     const MCSection *RelaSection;
686     const MCSectionELF &Section =
687       static_cast<const MCSectionELF&>(SD.getSection());
688 
689     const StringRef SectionName = Section.getSectionName();
690     std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
691     RelaSectionName += SectionName;
692 
693     unsigned EntrySize;
694     if (HasRelocationAddend)
695       EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
696     else
697       EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
698 
699     RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
700                                     ELF::SHT_RELA : ELF::SHT_REL, 0,
701                                     SectionKind::getReadOnly(),
702                                     false, EntrySize);
703 
704     MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
705     RelaSD.setAlignment(1);
706 
707     MCDataFragment *F = new MCDataFragment(&RelaSD);
708 
709     WriteRelocationsFragment(Asm, F, &SD);
710 
711     Asm.AddSectionToTheEnd(RelaSD, Layout);
712   }
713 }
714 
WriteSecHdrEntry(uint32_t Name,uint32_t Type,uint64_t Flags,uint64_t Address,uint64_t Offset,uint64_t Size,uint32_t Link,uint32_t Info,uint64_t Alignment,uint64_t EntrySize)715 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
716                                            uint64_t Flags, uint64_t Address,
717                                            uint64_t Offset, uint64_t Size,
718                                            uint32_t Link, uint32_t Info,
719                                            uint64_t Alignment,
720                                            uint64_t EntrySize) {
721   Write32(Name);        // sh_name: index into string table
722   Write32(Type);        // sh_type
723   WriteWord(Flags);     // sh_flags
724   WriteWord(Address);   // sh_addr
725   WriteWord(Offset);    // sh_offset
726   WriteWord(Size);      // sh_size
727   Write32(Link);        // sh_link
728   Write32(Info);        // sh_info
729   WriteWord(Alignment); // sh_addralign
730   WriteWord(EntrySize); // sh_entsize
731 }
732 
WriteRelocationsFragment(const MCAssembler & Asm,MCDataFragment * F,const MCSectionData * SD)733 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
734                                                    MCDataFragment *F,
735                                                    const MCSectionData *SD) {
736   std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
737   // sort by the r_offset just like gnu as does
738   array_pod_sort(Relocs.begin(), Relocs.end());
739 
740   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
741     ELFRelocationEntry entry = Relocs[e - i - 1];
742 
743     unsigned WordSize = Is64Bit ? 8 : 4;
744     F->getContents() += StringRef((const char *)&entry.r_offset, WordSize);
745     F->getContents() += StringRef((const char *)&entry.r_info, WordSize);
746 
747     if (HasRelocationAddend)
748       F->getContents() += StringRef((const char *)&entry.r_addend, WordSize);
749   }
750 }
751 
CreateMetadataSections(MCAssembler & Asm,MCAsmLayout & Layout)752 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
753                                                  MCAsmLayout &Layout) {
754   MCContext &Ctx = Asm.getContext();
755   MCDataFragment *F;
756 
757   WriteRelocations(Asm, Layout);
758 
759   const MCSection *SymtabSection;
760   unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
761 
762   SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
763                                     SectionKind::getReadOnly(),
764                                     false, EntrySize);
765 
766   MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
767 
768   SymtabSD.setAlignment(Is64Bit ? 8 : 4);
769 
770   F = new MCDataFragment(&SymtabSD);
771 
772   // Symbol table
773   WriteSymbolTable(F, Asm, Layout);
774   Asm.AddSectionToTheEnd(SymtabSD, Layout);
775 
776   const MCSection *StrtabSection;
777   StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
778                                     SectionKind::getReadOnly(), false);
779 
780   MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
781   StrtabSD.setAlignment(1);
782 
783   // FIXME: This isn't right. If the sections get rearranged this will
784   // be wrong. We need a proper lookup.
785   StringTableIndex = Asm.size();
786 
787   F = new MCDataFragment(&StrtabSD);
788   F->getContents().append(StringTable.begin(), StringTable.end());
789   Asm.AddSectionToTheEnd(StrtabSD, Layout);
790 
791   const MCSection *ShstrtabSection;
792   ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
793                                       SectionKind::getReadOnly(), false);
794 
795   MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
796   ShstrtabSD.setAlignment(1);
797 
798   F = new MCDataFragment(&ShstrtabSD);
799 
800   // FIXME: This isn't right. If the sections get rearranged this will
801   // be wrong. We need a proper lookup.
802   ShstrtabIndex = Asm.size();
803 
804   // Section header string table.
805   //
806   // The first entry of a string table holds a null character so skip
807   // section 0.
808   uint64_t Index = 1;
809   F->getContents() += '\x00';
810 
811   for (MCAssembler::const_iterator it = Asm.begin(),
812          ie = Asm.end(); it != ie; ++it) {
813     const MCSectionELF &Section =
814       static_cast<const MCSectionELF&>(it->getSection());
815 
816     // Remember the index into the string table so we can write it
817     // into the sh_name field of the section header table.
818     SectionStringTableIndex[&it->getSection()] = Index;
819 
820     Index += Section.getSectionName().size() + 1;
821     F->getContents() += Section.getSectionName();
822     F->getContents() += '\x00';
823   }
824 
825   Asm.AddSectionToTheEnd(ShstrtabSD, Layout);
826 }
827 
WriteObject(const MCAssembler & Asm,const MCAsmLayout & Layout)828 void ELFObjectWriterImpl::WriteObject(const MCAssembler &Asm,
829                                       const MCAsmLayout &Layout) {
830   CreateMetadataSections(const_cast<MCAssembler&>(Asm),
831                          const_cast<MCAsmLayout&>(Layout));
832 
833   // Add 1 for the null section.
834   unsigned NumSections = Asm.size() + 1;
835 
836   uint64_t SectionDataSize = 0;
837 
838   for (MCAssembler::const_iterator it = Asm.begin(),
839          ie = Asm.end(); it != ie; ++it) {
840     const MCSectionData &SD = *it;
841 
842     // Get the size of the section in the output file (including padding).
843     uint64_t Size = Layout.getSectionFileSize(&SD);
844     SectionDataSize += Size;
845   }
846 
847   // Write out the ELF header ...
848   WriteHeader(SectionDataSize, NumSections);
849   FileOff = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
850 
851   // ... then all of the sections ...
852   DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
853 
854   DenseMap<const MCSection*, uint8_t> SectionIndexMap;
855 
856   unsigned Index = 1;
857   for (MCAssembler::const_iterator it = Asm.begin(),
858          ie = Asm.end(); it != ie; ++it) {
859     // Remember the offset into the file for this section.
860     SectionOffsetMap[&it->getSection()] = FileOff;
861 
862     SectionIndexMap[&it->getSection()] = Index++;
863 
864     const MCSectionData &SD = *it;
865     FileOff += Layout.getSectionFileSize(&SD);
866 
867     Asm.WriteSectionData(it, Layout, Writer);
868   }
869 
870   // ... and then the section header table.
871   // Should we align the section header table?
872   //
873   // Null section first.
874   WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
875 
876   for (MCAssembler::const_iterator it = Asm.begin(),
877          ie = Asm.end(); it != ie; ++it) {
878     const MCSectionData &SD = *it;
879     const MCSectionELF &Section =
880       static_cast<const MCSectionELF&>(SD.getSection());
881 
882     uint64_t sh_link = 0;
883     uint64_t sh_info = 0;
884 
885     switch(Section.getType()) {
886     case ELF::SHT_DYNAMIC:
887       sh_link = SectionStringTableIndex[&it->getSection()];
888       sh_info = 0;
889       break;
890 
891     case ELF::SHT_REL:
892     case ELF::SHT_RELA: {
893       const MCSection *SymtabSection;
894       const MCSection *InfoSection;
895 
896       SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
897                                                      SectionKind::getReadOnly(),
898                                                      false);
899       sh_link = SectionIndexMap[SymtabSection];
900 
901       // Remove ".rel" and ".rela" prefixes.
902       unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
903       StringRef SectionName = Section.getSectionName().substr(SecNameLen);
904 
905       InfoSection = Asm.getContext().getELFSection(SectionName,
906                                                    ELF::SHT_PROGBITS, 0,
907                                                    SectionKind::getReadOnly(),
908                                                    false);
909       sh_info = SectionIndexMap[InfoSection];
910       break;
911     }
912 
913     case ELF::SHT_SYMTAB:
914     case ELF::SHT_DYNSYM:
915       sh_link = StringTableIndex;
916       sh_info = LastLocalSymbolIndex;
917       break;
918 
919     case ELF::SHT_PROGBITS:
920     case ELF::SHT_STRTAB:
921     case ELF::SHT_NOBITS:
922     case ELF::SHT_NULL:
923       // Nothing to do.
924       break;
925 
926     case ELF::SHT_HASH:
927     case ELF::SHT_GROUP:
928     case ELF::SHT_SYMTAB_SHNDX:
929     default:
930       assert(0 && "FIXME: sh_type value not supported!");
931       break;
932     }
933 
934     WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
935                      Section.getType(), Section.getFlags(),
936                      Layout.getSectionAddress(&SD),
937                      SectionOffsetMap.lookup(&SD.getSection()),
938                      Layout.getSectionSize(&SD), sh_link,
939                      sh_info, SD.getAlignment(),
940                      Section.getEntrySize());
941   }
942 }
943 
ELFObjectWriter(raw_ostream & OS,bool Is64Bit,bool IsLittleEndian,bool HasRelocationAddend)944 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
945                                  bool Is64Bit,
946                                  bool IsLittleEndian,
947                                  bool HasRelocationAddend)
948   : MCObjectWriter(OS, IsLittleEndian)
949 {
950   Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend);
951 }
952 
~ELFObjectWriter()953 ELFObjectWriter::~ELFObjectWriter() {
954   delete (ELFObjectWriterImpl*) Impl;
955 }
956 
ExecutePostLayoutBinding(MCAssembler & Asm)957 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
958   ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
959 }
960 
RecordRelocation(const MCAssembler & Asm,const MCAsmLayout & Layout,const MCFragment * Fragment,const MCFixup & Fixup,MCValue Target,uint64_t & FixedValue)961 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
962                                        const MCAsmLayout &Layout,
963                                        const MCFragment *Fragment,
964                                        const MCFixup &Fixup, MCValue Target,
965                                        uint64_t &FixedValue) {
966   ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
967                                                   Target, FixedValue);
968 }
969 
WriteObject(const MCAssembler & Asm,const MCAsmLayout & Layout)970 void ELFObjectWriter::WriteObject(const MCAssembler &Asm,
971                                   const MCAsmLayout &Layout) {
972   ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
973 }
974