• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- yaml2elf - Convert YAML to a ELF object file -----------------------===//
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 /// \file
11 /// The ELF component of yaml2obj.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "yaml2obj.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/BinaryFormat/ELF.h"
18 #include "llvm/MC/StringTableBuilder.h"
19 #include "llvm/Object/ELFObjectFile.h"
20 #include "llvm/ObjectYAML/ELFYAML.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "llvm/Support/WithColor.h"
23 #include "llvm/Support/YAMLTraits.h"
24 #include "llvm/Support/raw_ostream.h"
25 
26 using namespace llvm;
27 
28 // This class is used to build up a contiguous binary blob while keeping
29 // track of an offset in the output (which notionally begins at
30 // `InitialOffset`).
31 namespace {
32 class ContiguousBlobAccumulator {
33   const uint64_t InitialOffset;
34   SmallVector<char, 128> Buf;
35   raw_svector_ostream OS;
36 
37   /// \returns The new offset.
padToAlignment(unsigned Align)38   uint64_t padToAlignment(unsigned Align) {
39     if (Align == 0)
40       Align = 1;
41     uint64_t CurrentOffset = InitialOffset + OS.tell();
42     uint64_t AlignedOffset = alignTo(CurrentOffset, Align);
43     for (; CurrentOffset != AlignedOffset; ++CurrentOffset)
44       OS.write('\0');
45     return AlignedOffset; // == CurrentOffset;
46   }
47 
48 public:
ContiguousBlobAccumulator(uint64_t InitialOffset_)49   ContiguousBlobAccumulator(uint64_t InitialOffset_)
50       : InitialOffset(InitialOffset_), Buf(), OS(Buf) {}
51   template <class Integer>
getOSAndAlignedOffset(Integer & Offset,unsigned Align)52   raw_ostream &getOSAndAlignedOffset(Integer &Offset, unsigned Align) {
53     Offset = padToAlignment(Align);
54     return OS;
55   }
writeBlobToStream(raw_ostream & Out)56   void writeBlobToStream(raw_ostream &Out) { Out << OS.str(); }
57 };
58 } // end anonymous namespace
59 
60 // Used to keep track of section and symbol names, so that in the YAML file
61 // sections and symbols can be referenced by name instead of by index.
62 namespace {
63 class NameToIdxMap {
64   StringMap<int> Map;
65 public:
66   /// \returns true if name is already present in the map.
addName(StringRef Name,unsigned i)67   bool addName(StringRef Name, unsigned i) {
68     return !Map.insert(std::make_pair(Name, (int)i)).second;
69   }
70   /// \returns true if name is not present in the map
lookup(StringRef Name,unsigned & Idx) const71   bool lookup(StringRef Name, unsigned &Idx) const {
72     StringMap<int>::const_iterator I = Map.find(Name);
73     if (I == Map.end())
74       return true;
75     Idx = I->getValue();
76     return false;
77   }
78   /// asserts if name is not present in the map
get(StringRef Name) const79   unsigned get(StringRef Name) const {
80     unsigned Idx = 0;
81     auto missing = lookup(Name, Idx);
82     (void)missing;
83     assert(!missing && "Expected section not found in index");
84     return Idx;
85   }
size() const86   unsigned size() const { return Map.size(); }
87 };
88 } // end anonymous namespace
89 
90 template <class T>
arrayDataSize(ArrayRef<T> A)91 static size_t arrayDataSize(ArrayRef<T> A) {
92   return A.size() * sizeof(T);
93 }
94 
95 template <class T>
writeArrayData(raw_ostream & OS,ArrayRef<T> A)96 static void writeArrayData(raw_ostream &OS, ArrayRef<T> A) {
97   OS.write((const char *)A.data(), arrayDataSize(A));
98 }
99 
100 template <class T>
zero(T & Obj)101 static void zero(T &Obj) {
102   memset(&Obj, 0, sizeof(Obj));
103 }
104 
105 namespace {
106 /// "Single point of truth" for the ELF file construction.
107 /// TODO: This class still has a ways to go before it is truly a "single
108 /// point of truth".
109 template <class ELFT>
110 class ELFState {
111   typedef typename ELFT::Ehdr Elf_Ehdr;
112   typedef typename ELFT::Phdr Elf_Phdr;
113   typedef typename ELFT::Shdr Elf_Shdr;
114   typedef typename ELFT::Sym Elf_Sym;
115   typedef typename ELFT::Rel Elf_Rel;
116   typedef typename ELFT::Rela Elf_Rela;
117   typedef typename ELFT::Relr Elf_Relr;
118   typedef typename ELFT::Dyn Elf_Dyn;
119 
120   enum class SymtabType { Static, Dynamic };
121 
122   /// The future ".strtab" section.
123   StringTableBuilder DotStrtab{StringTableBuilder::ELF};
124 
125   /// The future ".shstrtab" section.
126   StringTableBuilder DotShStrtab{StringTableBuilder::ELF};
127 
128   /// The future ".dynstr" section.
129   StringTableBuilder DotDynstr{StringTableBuilder::ELF};
130 
131   NameToIdxMap SN2I;
132   NameToIdxMap SymN2I;
133   const ELFYAML::Object &Doc;
134 
135   bool buildSectionIndex();
136   bool buildSymbolIndex(std::size_t &StartIndex,
137                         const std::vector<ELFYAML::Symbol> &Symbols);
138   void initELFHeader(Elf_Ehdr &Header);
139   void initProgramHeaders(std::vector<Elf_Phdr> &PHeaders);
140   bool initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
141                           ContiguousBlobAccumulator &CBA);
142   void initSymtabSectionHeader(Elf_Shdr &SHeader, SymtabType STType,
143                                ContiguousBlobAccumulator &CBA);
144   void initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
145                                StringTableBuilder &STB,
146                                ContiguousBlobAccumulator &CBA);
147   void setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
148                               std::vector<Elf_Shdr> &SHeaders);
149   void addSymbols(const std::vector<ELFYAML::Symbol> &Symbols,
150                   std::vector<Elf_Sym> &Syms, unsigned SymbolBinding,
151                   const StringTableBuilder &Strtab);
152   void writeSectionContent(Elf_Shdr &SHeader,
153                            const ELFYAML::RawContentSection &Section,
154                            ContiguousBlobAccumulator &CBA);
155   bool writeSectionContent(Elf_Shdr &SHeader,
156                            const ELFYAML::RelocationSection &Section,
157                            ContiguousBlobAccumulator &CBA);
158   bool writeSectionContent(Elf_Shdr &SHeader, const ELFYAML::Group &Group,
159                            ContiguousBlobAccumulator &CBA);
160   bool writeSectionContent(Elf_Shdr &SHeader,
161                            const ELFYAML::MipsABIFlags &Section,
162                            ContiguousBlobAccumulator &CBA);
163   bool hasDynamicSymbols() const;
164   SmallVector<const char *, 5> implicitSectionNames() const;
165 
166   // - SHT_NULL entry (placed first, i.e. 0'th entry)
167   // - symbol table (.symtab) (defaults to after last yaml section)
168   // - string table (.strtab) (defaults to after .symtab)
169   // - section header string table (.shstrtab) (defaults to after .strtab)
170   // - dynamic symbol table (.dynsym) (defaults to after .shstrtab)
171   // - dynamic string table (.dynstr) (defaults to after .dynsym)
getDotSymTabSecNo() const172   unsigned getDotSymTabSecNo() const { return SN2I.get(".symtab"); }
getDotStrTabSecNo() const173   unsigned getDotStrTabSecNo() const { return SN2I.get(".strtab"); }
getDotShStrTabSecNo() const174   unsigned getDotShStrTabSecNo() const { return SN2I.get(".shstrtab"); }
getDotDynSymSecNo() const175   unsigned getDotDynSymSecNo() const { return SN2I.get(".dynsym"); }
getDotDynStrSecNo() const176   unsigned getDotDynStrSecNo() const { return SN2I.get(".dynstr"); }
getSectionCount() const177   unsigned getSectionCount() const { return SN2I.size() + 1; }
178 
ELFState(const ELFYAML::Object & D)179   ELFState(const ELFYAML::Object &D) : Doc(D) {}
180 
181 public:
182   static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc);
183 };
184 } // end anonymous namespace
185 
186 template <class ELFT>
initELFHeader(Elf_Ehdr & Header)187 void ELFState<ELFT>::initELFHeader(Elf_Ehdr &Header) {
188   using namespace llvm::ELF;
189   zero(Header);
190   Header.e_ident[EI_MAG0] = 0x7f;
191   Header.e_ident[EI_MAG1] = 'E';
192   Header.e_ident[EI_MAG2] = 'L';
193   Header.e_ident[EI_MAG3] = 'F';
194   Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
195   bool IsLittleEndian = ELFT::TargetEndianness == support::little;
196   Header.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
197   Header.e_ident[EI_VERSION] = EV_CURRENT;
198   Header.e_ident[EI_OSABI] = Doc.Header.OSABI;
199   Header.e_ident[EI_ABIVERSION] = 0;
200   Header.e_type = Doc.Header.Type;
201   Header.e_machine = Doc.Header.Machine;
202   Header.e_version = EV_CURRENT;
203   Header.e_entry = Doc.Header.Entry;
204   Header.e_phoff = sizeof(Header);
205   Header.e_flags = Doc.Header.Flags;
206   Header.e_ehsize = sizeof(Elf_Ehdr);
207   Header.e_phentsize = sizeof(Elf_Phdr);
208   Header.e_phnum = Doc.ProgramHeaders.size();
209   Header.e_shentsize = sizeof(Elf_Shdr);
210   // Immediately following the ELF header and program headers.
211   Header.e_shoff =
212       sizeof(Header) + sizeof(Elf_Phdr) * Doc.ProgramHeaders.size();
213   Header.e_shnum = getSectionCount();
214   Header.e_shstrndx = getDotShStrTabSecNo();
215 }
216 
217 template <class ELFT>
initProgramHeaders(std::vector<Elf_Phdr> & PHeaders)218 void ELFState<ELFT>::initProgramHeaders(std::vector<Elf_Phdr> &PHeaders) {
219   for (const auto &YamlPhdr : Doc.ProgramHeaders) {
220     Elf_Phdr Phdr;
221     Phdr.p_type = YamlPhdr.Type;
222     Phdr.p_flags = YamlPhdr.Flags;
223     Phdr.p_vaddr = YamlPhdr.VAddr;
224     Phdr.p_paddr = YamlPhdr.PAddr;
225     PHeaders.push_back(Phdr);
226   }
227 }
228 
229 template <class ELFT>
initSectionHeaders(std::vector<Elf_Shdr> & SHeaders,ContiguousBlobAccumulator & CBA)230 bool ELFState<ELFT>::initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
231                                         ContiguousBlobAccumulator &CBA) {
232   // Ensure SHN_UNDEF entry is present. An all-zero section header is a
233   // valid SHN_UNDEF entry since SHT_NULL == 0.
234   Elf_Shdr SHeader;
235   zero(SHeader);
236   SHeaders.push_back(SHeader);
237 
238   for (const auto &Sec : Doc.Sections) {
239     zero(SHeader);
240     SHeader.sh_name = DotShStrtab.getOffset(Sec->Name);
241     SHeader.sh_type = Sec->Type;
242     SHeader.sh_flags = Sec->Flags;
243     SHeader.sh_addr = Sec->Address;
244     SHeader.sh_addralign = Sec->AddressAlign;
245 
246     if (!Sec->Link.empty()) {
247       unsigned Index;
248       if (SN2I.lookup(Sec->Link, Index)) {
249         WithColor::error() << "Unknown section referenced: '" << Sec->Link
250                            << "' at YAML section '" << Sec->Name << "'.\n";
251         return false;
252       }
253       SHeader.sh_link = Index;
254     }
255 
256     if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec.get()))
257       writeSectionContent(SHeader, *S, CBA);
258     else if (auto S = dyn_cast<ELFYAML::RelocationSection>(Sec.get())) {
259       if (S->Link.empty())
260         // For relocation section set link to .symtab by default.
261         SHeader.sh_link = getDotSymTabSecNo();
262 
263       unsigned Index;
264       if (SN2I.lookup(S->Info, Index)) {
265         if (S->Info.getAsInteger(0, Index)) {
266           WithColor::error() << "Unknown section referenced: '" << S->Info
267                              << "' at YAML section '" << S->Name << "'.\n";
268           return false;
269         }
270       }
271       SHeader.sh_info = Index;
272 
273       if (!writeSectionContent(SHeader, *S, CBA))
274         return false;
275     } else if (auto S = dyn_cast<ELFYAML::Group>(Sec.get())) {
276       unsigned SymIdx;
277       if (SymN2I.lookup(S->Info, SymIdx)) {
278         WithColor::error() << "Unknown symbol referenced: '" << S->Info
279                            << "' at YAML section '" << S->Name << "'.\n";
280         return false;
281       }
282       SHeader.sh_info = SymIdx;
283       if (!writeSectionContent(SHeader, *S, CBA))
284         return false;
285     } else if (auto S = dyn_cast<ELFYAML::MipsABIFlags>(Sec.get())) {
286       if (!writeSectionContent(SHeader, *S, CBA))
287         return false;
288     } else if (auto S = dyn_cast<ELFYAML::NoBitsSection>(Sec.get())) {
289       SHeader.sh_entsize = 0;
290       SHeader.sh_size = S->Size;
291       // SHT_NOBITS section does not have content
292       // so just to setup the section offset.
293       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
294     } else
295       llvm_unreachable("Unknown section type");
296 
297     SHeaders.push_back(SHeader);
298   }
299   return true;
300 }
301 
302 template <class ELFT>
initSymtabSectionHeader(Elf_Shdr & SHeader,SymtabType STType,ContiguousBlobAccumulator & CBA)303 void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
304                                              SymtabType STType,
305                                              ContiguousBlobAccumulator &CBA) {
306   zero(SHeader);
307   bool IsStatic = STType == SymtabType::Static;
308   SHeader.sh_name = DotShStrtab.getOffset(IsStatic ? ".symtab" : ".dynsym");
309   SHeader.sh_type = IsStatic ? ELF::SHT_SYMTAB : ELF::SHT_DYNSYM;
310   SHeader.sh_link = IsStatic ? getDotStrTabSecNo() : getDotDynStrSecNo();
311   const auto &Symbols = IsStatic ? Doc.Symbols : Doc.DynamicSymbols;
312   auto &Strtab = IsStatic ? DotStrtab : DotDynstr;
313   // One greater than symbol table index of the last local symbol.
314   SHeader.sh_info = Symbols.Local.size() + 1;
315   SHeader.sh_entsize = sizeof(Elf_Sym);
316   SHeader.sh_addralign = 8;
317 
318   std::vector<Elf_Sym> Syms;
319   {
320     // Ensure STN_UNDEF is present
321     Elf_Sym Sym;
322     zero(Sym);
323     Syms.push_back(Sym);
324   }
325 
326   // Add symbol names to .strtab or .dynstr.
327   for (const auto &Sym : Symbols.Local)
328     Strtab.add(Sym.Name);
329   for (const auto &Sym : Symbols.Global)
330     Strtab.add(Sym.Name);
331   for (const auto &Sym : Symbols.Weak)
332     Strtab.add(Sym.Name);
333   Strtab.finalize();
334 
335   addSymbols(Symbols.Local, Syms, ELF::STB_LOCAL, Strtab);
336   addSymbols(Symbols.Global, Syms, ELF::STB_GLOBAL, Strtab);
337   addSymbols(Symbols.Weak, Syms, ELF::STB_WEAK, Strtab);
338 
339   writeArrayData(
340       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign),
341       makeArrayRef(Syms));
342   SHeader.sh_size = arrayDataSize(makeArrayRef(Syms));
343 }
344 
345 template <class ELFT>
initStrtabSectionHeader(Elf_Shdr & SHeader,StringRef Name,StringTableBuilder & STB,ContiguousBlobAccumulator & CBA)346 void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
347                                              StringTableBuilder &STB,
348                                              ContiguousBlobAccumulator &CBA) {
349   zero(SHeader);
350   SHeader.sh_name = DotShStrtab.getOffset(Name);
351   SHeader.sh_type = ELF::SHT_STRTAB;
352   STB.write(CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign));
353   SHeader.sh_size = STB.getSize();
354   SHeader.sh_addralign = 1;
355 }
356 
357 template <class ELFT>
setProgramHeaderLayout(std::vector<Elf_Phdr> & PHeaders,std::vector<Elf_Shdr> & SHeaders)358 void ELFState<ELFT>::setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
359                                             std::vector<Elf_Shdr> &SHeaders) {
360   uint32_t PhdrIdx = 0;
361   for (auto &YamlPhdr : Doc.ProgramHeaders) {
362     auto &PHeader = PHeaders[PhdrIdx++];
363 
364     if (YamlPhdr.Sections.size())
365       PHeader.p_offset = UINT32_MAX;
366     else
367       PHeader.p_offset = 0;
368 
369     // Find the minimum offset for the program header.
370     for (auto SecName : YamlPhdr.Sections) {
371       uint32_t Index = 0;
372       SN2I.lookup(SecName.Section, Index);
373       const auto &SHeader = SHeaders[Index];
374       PHeader.p_offset = std::min(PHeader.p_offset, SHeader.sh_offset);
375     }
376 
377     // Find the maximum offset of the end of a section in order to set p_filesz.
378     PHeader.p_filesz = 0;
379     for (auto SecName : YamlPhdr.Sections) {
380       uint32_t Index = 0;
381       SN2I.lookup(SecName.Section, Index);
382       const auto &SHeader = SHeaders[Index];
383       uint64_t EndOfSection;
384       if (SHeader.sh_type == llvm::ELF::SHT_NOBITS)
385         EndOfSection = SHeader.sh_offset;
386       else
387         EndOfSection = SHeader.sh_offset + SHeader.sh_size;
388       uint64_t EndOfSegment = PHeader.p_offset + PHeader.p_filesz;
389       EndOfSegment = std::max(EndOfSegment, EndOfSection);
390       PHeader.p_filesz = EndOfSegment - PHeader.p_offset;
391     }
392 
393     // Find the memory size by adding the size of sections at the end of the
394     // segment. These should be empty (size of zero) and NOBITS sections.
395     PHeader.p_memsz = PHeader.p_filesz;
396     for (auto SecName : YamlPhdr.Sections) {
397       uint32_t Index = 0;
398       SN2I.lookup(SecName.Section, Index);
399       const auto &SHeader = SHeaders[Index];
400       if (SHeader.sh_offset == PHeader.p_offset + PHeader.p_filesz)
401         PHeader.p_memsz += SHeader.sh_size;
402     }
403 
404     // Set the alignment of the segment to be the same as the maximum alignment
405     // of the sections with the same offset so that by default the segment
406     // has a valid and sensible alignment.
407     if (YamlPhdr.Align) {
408       PHeader.p_align = *YamlPhdr.Align;
409     } else {
410       PHeader.p_align = 1;
411       for (auto SecName : YamlPhdr.Sections) {
412         uint32_t Index = 0;
413         SN2I.lookup(SecName.Section, Index);
414         const auto &SHeader = SHeaders[Index];
415         if (SHeader.sh_offset == PHeader.p_offset)
416           PHeader.p_align = std::max(PHeader.p_align, SHeader.sh_addralign);
417       }
418     }
419   }
420 }
421 
422 template <class ELFT>
addSymbols(const std::vector<ELFYAML::Symbol> & Symbols,std::vector<Elf_Sym> & Syms,unsigned SymbolBinding,const StringTableBuilder & Strtab)423 void ELFState<ELFT>::addSymbols(const std::vector<ELFYAML::Symbol> &Symbols,
424                                 std::vector<Elf_Sym> &Syms,
425                                 unsigned SymbolBinding,
426                                 const StringTableBuilder &Strtab) {
427   for (const auto &Sym : Symbols) {
428     Elf_Sym Symbol;
429     zero(Symbol);
430     if (!Sym.Name.empty())
431       Symbol.st_name = Strtab.getOffset(Sym.Name);
432     Symbol.setBindingAndType(SymbolBinding, Sym.Type);
433     if (!Sym.Section.empty()) {
434       unsigned Index;
435       if (SN2I.lookup(Sym.Section, Index)) {
436         WithColor::error() << "Unknown section referenced: '" << Sym.Section
437                            << "' by YAML symbol " << Sym.Name << ".\n";
438         exit(1);
439       }
440       Symbol.st_shndx = Index;
441     } else if (Sym.Index) {
442       Symbol.st_shndx = *Sym.Index;
443     }
444     // else Symbol.st_shndex == SHN_UNDEF (== 0), since it was zero'd earlier.
445     Symbol.st_value = Sym.Value;
446     Symbol.st_other = Sym.Other;
447     Symbol.st_size = Sym.Size;
448     Syms.push_back(Symbol);
449   }
450 }
451 
452 template <class ELFT>
453 void
writeSectionContent(Elf_Shdr & SHeader,const ELFYAML::RawContentSection & Section,ContiguousBlobAccumulator & CBA)454 ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
455                                     const ELFYAML::RawContentSection &Section,
456                                     ContiguousBlobAccumulator &CBA) {
457   assert(Section.Size >= Section.Content.binary_size() &&
458          "Section size and section content are inconsistent");
459   raw_ostream &OS =
460       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
461   Section.Content.writeAsBinary(OS);
462   for (auto i = Section.Content.binary_size(); i < Section.Size; ++i)
463     OS.write(0);
464   if (Section.Type == llvm::ELF::SHT_RELR)
465     SHeader.sh_entsize = sizeof(Elf_Relr);
466   else if (Section.Type == llvm::ELF::SHT_DYNAMIC)
467     SHeader.sh_entsize = sizeof(Elf_Dyn);
468   else
469     SHeader.sh_entsize = 0;
470   SHeader.sh_size = Section.Size;
471 }
472 
isMips64EL(const ELFYAML::Object & Doc)473 static bool isMips64EL(const ELFYAML::Object &Doc) {
474   return Doc.Header.Machine == ELFYAML::ELF_EM(llvm::ELF::EM_MIPS) &&
475          Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64) &&
476          Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
477 }
478 
479 template <class ELFT>
480 bool
writeSectionContent(Elf_Shdr & SHeader,const ELFYAML::RelocationSection & Section,ContiguousBlobAccumulator & CBA)481 ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
482                                     const ELFYAML::RelocationSection &Section,
483                                     ContiguousBlobAccumulator &CBA) {
484   assert((Section.Type == llvm::ELF::SHT_REL ||
485           Section.Type == llvm::ELF::SHT_RELA) &&
486          "Section type is not SHT_REL nor SHT_RELA");
487 
488   bool IsRela = Section.Type == llvm::ELF::SHT_RELA;
489   SHeader.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
490   SHeader.sh_size = SHeader.sh_entsize * Section.Relocations.size();
491 
492   auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
493 
494   for (const auto &Rel : Section.Relocations) {
495     unsigned SymIdx = 0;
496     // Some special relocation, R_ARM_v4BX for instance, does not have
497     // an external reference.  So it ignores the return value of lookup()
498     // here.
499     if (Rel.Symbol)
500       SymN2I.lookup(*Rel.Symbol, SymIdx);
501 
502     if (IsRela) {
503       Elf_Rela REntry;
504       zero(REntry);
505       REntry.r_offset = Rel.Offset;
506       REntry.r_addend = Rel.Addend;
507       REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
508       OS.write((const char *)&REntry, sizeof(REntry));
509     } else {
510       Elf_Rel REntry;
511       zero(REntry);
512       REntry.r_offset = Rel.Offset;
513       REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
514       OS.write((const char *)&REntry, sizeof(REntry));
515     }
516   }
517   return true;
518 }
519 
520 template <class ELFT>
writeSectionContent(Elf_Shdr & SHeader,const ELFYAML::Group & Section,ContiguousBlobAccumulator & CBA)521 bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
522                                          const ELFYAML::Group &Section,
523                                          ContiguousBlobAccumulator &CBA) {
524   typedef typename ELFT::Word Elf_Word;
525   assert(Section.Type == llvm::ELF::SHT_GROUP &&
526          "Section type is not SHT_GROUP");
527 
528   SHeader.sh_entsize = sizeof(Elf_Word);
529   SHeader.sh_size = SHeader.sh_entsize * Section.Members.size();
530 
531   auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
532 
533   for (auto member : Section.Members) {
534     Elf_Word SIdx;
535     unsigned int sectionIndex = 0;
536     if (member.sectionNameOrType == "GRP_COMDAT")
537       sectionIndex = llvm::ELF::GRP_COMDAT;
538     else if (SN2I.lookup(member.sectionNameOrType, sectionIndex)) {
539       WithColor::error() << "Unknown section referenced: '"
540                          << member.sectionNameOrType << "' at YAML section' "
541                          << Section.Name << "\n";
542       return false;
543     }
544     SIdx = sectionIndex;
545     OS.write((const char *)&SIdx, sizeof(SIdx));
546   }
547   return true;
548 }
549 
550 template <class ELFT>
writeSectionContent(Elf_Shdr & SHeader,const ELFYAML::MipsABIFlags & Section,ContiguousBlobAccumulator & CBA)551 bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
552                                          const ELFYAML::MipsABIFlags &Section,
553                                          ContiguousBlobAccumulator &CBA) {
554   assert(Section.Type == llvm::ELF::SHT_MIPS_ABIFLAGS &&
555          "Section type is not SHT_MIPS_ABIFLAGS");
556 
557   object::Elf_Mips_ABIFlags<ELFT> Flags;
558   zero(Flags);
559   SHeader.sh_entsize = sizeof(Flags);
560   SHeader.sh_size = SHeader.sh_entsize;
561 
562   auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
563   Flags.version = Section.Version;
564   Flags.isa_level = Section.ISALevel;
565   Flags.isa_rev = Section.ISARevision;
566   Flags.gpr_size = Section.GPRSize;
567   Flags.cpr1_size = Section.CPR1Size;
568   Flags.cpr2_size = Section.CPR2Size;
569   Flags.fp_abi = Section.FpABI;
570   Flags.isa_ext = Section.ISAExtension;
571   Flags.ases = Section.ASEs;
572   Flags.flags1 = Section.Flags1;
573   Flags.flags2 = Section.Flags2;
574   OS.write((const char *)&Flags, sizeof(Flags));
575 
576   return true;
577 }
578 
buildSectionIndex()579 template <class ELFT> bool ELFState<ELFT>::buildSectionIndex() {
580   for (unsigned i = 0, e = Doc.Sections.size(); i != e; ++i) {
581     StringRef Name = Doc.Sections[i]->Name;
582     DotShStrtab.add(Name);
583     // "+ 1" to take into account the SHT_NULL entry.
584     if (SN2I.addName(Name, i + 1)) {
585       WithColor::error() << "Repeated section name: '" << Name
586                          << "' at YAML section number " << i << ".\n";
587       return false;
588     }
589   }
590 
591   auto SecNo = 1 + Doc.Sections.size();
592   // Add special sections after input sections, if necessary.
593   for (const auto &Name : implicitSectionNames())
594     if (!SN2I.addName(Name, SecNo)) {
595       // Account for this section, since it wasn't in the Doc
596       ++SecNo;
597       DotShStrtab.add(Name);
598     }
599 
600   DotShStrtab.finalize();
601   return true;
602 }
603 
604 template <class ELFT>
605 bool
buildSymbolIndex(std::size_t & StartIndex,const std::vector<ELFYAML::Symbol> & Symbols)606 ELFState<ELFT>::buildSymbolIndex(std::size_t &StartIndex,
607                                  const std::vector<ELFYAML::Symbol> &Symbols) {
608   for (const auto &Sym : Symbols) {
609     ++StartIndex;
610     if (Sym.Name.empty())
611       continue;
612     if (SymN2I.addName(Sym.Name, StartIndex)) {
613       WithColor::error() << "Repeated symbol name: '" << Sym.Name << "'.\n";
614       return false;
615     }
616   }
617   return true;
618 }
619 
620 template <class ELFT>
writeELF(raw_ostream & OS,const ELFYAML::Object & Doc)621 int ELFState<ELFT>::writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
622   ELFState<ELFT> State(Doc);
623   if (!State.buildSectionIndex())
624     return 1;
625 
626   std::size_t StartSymIndex = 0;
627   if (!State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Local) ||
628       !State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Global) ||
629       !State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Weak))
630     return 1;
631 
632   Elf_Ehdr Header;
633   State.initELFHeader(Header);
634 
635   // TODO: Flesh out section header support.
636 
637   std::vector<Elf_Phdr> PHeaders;
638   State.initProgramHeaders(PHeaders);
639 
640   // XXX: This offset is tightly coupled with the order that we write
641   // things to `OS`.
642   const size_t SectionContentBeginOffset = Header.e_ehsize +
643                                            Header.e_phentsize * Header.e_phnum +
644                                            Header.e_shentsize * Header.e_shnum;
645   ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
646 
647   std::vector<Elf_Shdr> SHeaders;
648   if(!State.initSectionHeaders(SHeaders, CBA))
649     return 1;
650 
651   // Populate SHeaders with implicit sections not present in the Doc
652   for (const auto &Name : State.implicitSectionNames())
653     if (State.SN2I.get(Name) >= SHeaders.size())
654       SHeaders.push_back({});
655 
656   // Initialize the implicit sections
657   auto Index = State.SN2I.get(".symtab");
658   State.initSymtabSectionHeader(SHeaders[Index], SymtabType::Static, CBA);
659   Index = State.SN2I.get(".strtab");
660   State.initStrtabSectionHeader(SHeaders[Index], ".strtab", State.DotStrtab, CBA);
661   Index = State.SN2I.get(".shstrtab");
662   State.initStrtabSectionHeader(SHeaders[Index], ".shstrtab", State.DotShStrtab, CBA);
663   if (State.hasDynamicSymbols()) {
664     Index = State.SN2I.get(".dynsym");
665     State.initSymtabSectionHeader(SHeaders[Index], SymtabType::Dynamic, CBA);
666     SHeaders[Index].sh_flags |= ELF::SHF_ALLOC;
667     Index = State.SN2I.get(".dynstr");
668     State.initStrtabSectionHeader(SHeaders[Index], ".dynstr", State.DotDynstr, CBA);
669     SHeaders[Index].sh_flags |= ELF::SHF_ALLOC;
670   }
671 
672   // Now we can decide segment offsets
673   State.setProgramHeaderLayout(PHeaders, SHeaders);
674 
675   OS.write((const char *)&Header, sizeof(Header));
676   writeArrayData(OS, makeArrayRef(PHeaders));
677   writeArrayData(OS, makeArrayRef(SHeaders));
678   CBA.writeBlobToStream(OS);
679   return 0;
680 }
681 
hasDynamicSymbols() const682 template <class ELFT> bool ELFState<ELFT>::hasDynamicSymbols() const {
683   return Doc.DynamicSymbols.Global.size() > 0 ||
684          Doc.DynamicSymbols.Weak.size() > 0 ||
685          Doc.DynamicSymbols.Local.size() > 0;
686 }
687 
implicitSectionNames() const688 template <class ELFT> SmallVector<const char *, 5> ELFState<ELFT>::implicitSectionNames() const {
689   if (!hasDynamicSymbols())
690     return {".symtab", ".strtab", ".shstrtab"};
691   return {".symtab", ".strtab", ".shstrtab", ".dynsym", ".dynstr"};
692 }
693 
is64Bit(const ELFYAML::Object & Doc)694 static bool is64Bit(const ELFYAML::Object &Doc) {
695   return Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
696 }
697 
isLittleEndian(const ELFYAML::Object & Doc)698 static bool isLittleEndian(const ELFYAML::Object &Doc) {
699   return Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
700 }
701 
yaml2elf(llvm::ELFYAML::Object & Doc,raw_ostream & Out)702 int yaml2elf(llvm::ELFYAML::Object &Doc, raw_ostream &Out) {
703   if (is64Bit(Doc)) {
704     if (isLittleEndian(Doc))
705       return ELFState<object::ELF64LE>::writeELF(Out, Doc);
706     else
707       return ELFState<object::ELF64BE>::writeELF(Out, Doc);
708   } else {
709     if (isLittleEndian(Doc))
710       return ELFState<object::ELF32LE>::writeELF(Out, Doc);
711     else
712       return ELFState<object::ELF32BE>::writeELF(Out, Doc);
713   }
714 }
715