1 //===- yaml2elf - Convert YAML to a ELF object file -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// The ELF component of yaml2obj.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/StringSet.h"
16 #include "llvm/BinaryFormat/ELF.h"
17 #include "llvm/MC/StringTableBuilder.h"
18 #include "llvm/Object/ELFObjectFile.h"
19 #include "llvm/ObjectYAML/ELFYAML.h"
20 #include "llvm/ObjectYAML/yaml2obj.h"
21 #include "llvm/Support/EndianStream.h"
22 #include "llvm/Support/LEB128.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/WithColor.h"
25 #include "llvm/Support/YAMLTraits.h"
26 #include "llvm/Support/raw_ostream.h"
27 
28 using namespace llvm;
29 
30 // This class is used to build up a contiguous binary blob while keeping
31 // track of an offset in the output (which notionally begins at
32 // `InitialOffset`).
33 namespace {
34 class ContiguousBlobAccumulator {
35   const uint64_t InitialOffset;
36   SmallVector<char, 128> Buf;
37   raw_svector_ostream OS;
38 
39 public:
40   ContiguousBlobAccumulator(uint64_t InitialOffset_)
41       : InitialOffset(InitialOffset_), Buf(), OS(Buf) {}
42 
43   template <class Integer>
44   raw_ostream &getOSAndAlignedOffset(Integer &Offset, unsigned Align) {
45     Offset = padToAlignment(Align);
46     return OS;
47   }
48 
49   /// \returns The new offset.
50   uint64_t padToAlignment(unsigned Align) {
51     if (Align == 0)
52       Align = 1;
53     uint64_t CurrentOffset = InitialOffset + OS.tell();
54     uint64_t AlignedOffset = alignTo(CurrentOffset, Align);
55     OS.write_zeros(AlignedOffset - CurrentOffset);
56     return AlignedOffset; // == CurrentOffset;
57   }
58 
59   void writeBlobToStream(raw_ostream &Out) { Out << OS.str(); }
60 };
61 
62 // Used to keep track of section and symbol names, so that in the YAML file
63 // sections and symbols can be referenced by name instead of by index.
64 class NameToIdxMap {
65   StringMap<unsigned> Map;
66 
67 public:
68   /// \Returns false if name is already present in the map.
69   bool addName(StringRef Name, unsigned Ndx) {
70     return Map.insert({Name, Ndx}).second;
71   }
72   /// \Returns false if name is not present in the map.
73   bool lookup(StringRef Name, unsigned &Idx) const {
74     auto I = Map.find(Name);
75     if (I == Map.end())
76       return false;
77     Idx = I->getValue();
78     return true;
79   }
80   /// Asserts if name is not present in the map.
81   unsigned get(StringRef Name) const {
82     unsigned Idx;
83     if (lookup(Name, Idx))
84       return Idx;
85     assert(false && "Expected section not found in index");
86     return 0;
87   }
88   unsigned size() const { return Map.size(); }
89 };
90 
91 /// "Single point of truth" for the ELF file construction.
92 /// TODO: This class still has a ways to go before it is truly a "single
93 /// point of truth".
94 template <class ELFT> class ELFState {
95   typedef typename ELFT::Ehdr Elf_Ehdr;
96   typedef typename ELFT::Phdr Elf_Phdr;
97   typedef typename ELFT::Shdr Elf_Shdr;
98   typedef typename ELFT::Sym Elf_Sym;
99   typedef typename ELFT::Rel Elf_Rel;
100   typedef typename ELFT::Rela Elf_Rela;
101   typedef typename ELFT::Relr Elf_Relr;
102   typedef typename ELFT::Dyn Elf_Dyn;
103 
104   enum class SymtabType { Static, Dynamic };
105 
106   /// The future ".strtab" section.
107   StringTableBuilder DotStrtab{StringTableBuilder::ELF};
108 
109   /// The future ".shstrtab" section.
110   StringTableBuilder DotShStrtab{StringTableBuilder::ELF};
111 
112   /// The future ".dynstr" section.
113   StringTableBuilder DotDynstr{StringTableBuilder::ELF};
114 
115   NameToIdxMap SN2I;
116   NameToIdxMap SymN2I;
117   NameToIdxMap DynSymN2I;
118   ELFYAML::Object &Doc;
119 
120   bool HasError = false;
121   yaml::ErrorHandler ErrHandler;
122   void reportError(const Twine &Msg);
123 
124   std::vector<Elf_Sym> toELFSymbols(ArrayRef<ELFYAML::Symbol> Symbols,
125                                     const StringTableBuilder &Strtab);
126   unsigned toSectionIndex(StringRef S, StringRef LocSec, StringRef LocSym = "");
127   unsigned toSymbolIndex(StringRef S, StringRef LocSec, bool IsDynamic);
128 
129   void buildSectionIndex();
130   void buildSymbolIndexes();
131   void initProgramHeaders(std::vector<Elf_Phdr> &PHeaders);
132   bool initImplicitHeader(ContiguousBlobAccumulator &CBA, Elf_Shdr &Header,
133                           StringRef SecName, ELFYAML::Section *YAMLSec);
134   void initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
135                           ContiguousBlobAccumulator &CBA);
136   void initSymtabSectionHeader(Elf_Shdr &SHeader, SymtabType STType,
137                                ContiguousBlobAccumulator &CBA,
138                                ELFYAML::Section *YAMLSec);
139   void initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
140                                StringTableBuilder &STB,
141                                ContiguousBlobAccumulator &CBA,
142                                ELFYAML::Section *YAMLSec);
143   void setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
144                               std::vector<Elf_Shdr> &SHeaders);
145   void finalizeStrings();
146   void writeELFHeader(ContiguousBlobAccumulator &CBA, raw_ostream &OS);
147   void writeSectionContent(Elf_Shdr &SHeader,
148                            const ELFYAML::RawContentSection &Section,
149                            ContiguousBlobAccumulator &CBA);
150   void writeSectionContent(Elf_Shdr &SHeader,
151                            const ELFYAML::RelocationSection &Section,
152                            ContiguousBlobAccumulator &CBA);
153   void writeSectionContent(Elf_Shdr &SHeader, const ELFYAML::Group &Group,
154                            ContiguousBlobAccumulator &CBA);
155   void writeSectionContent(Elf_Shdr &SHeader,
156                            const ELFYAML::SymtabShndxSection &Shndx,
157                            ContiguousBlobAccumulator &CBA);
158   void writeSectionContent(Elf_Shdr &SHeader,
159                            const ELFYAML::SymverSection &Section,
160                            ContiguousBlobAccumulator &CBA);
161   void writeSectionContent(Elf_Shdr &SHeader,
162                            const ELFYAML::VerneedSection &Section,
163                            ContiguousBlobAccumulator &CBA);
164   void writeSectionContent(Elf_Shdr &SHeader,
165                            const ELFYAML::VerdefSection &Section,
166                            ContiguousBlobAccumulator &CBA);
167   void writeSectionContent(Elf_Shdr &SHeader,
168                            const ELFYAML::MipsABIFlags &Section,
169                            ContiguousBlobAccumulator &CBA);
170   void writeSectionContent(Elf_Shdr &SHeader,
171                            const ELFYAML::DynamicSection &Section,
172                            ContiguousBlobAccumulator &CBA);
173   void writeSectionContent(Elf_Shdr &SHeader,
174                            const ELFYAML::StackSizesSection &Section,
175                            ContiguousBlobAccumulator &CBA);
176   void writeSectionContent(Elf_Shdr &SHeader,
177                            const ELFYAML::HashSection &Section,
178                            ContiguousBlobAccumulator &CBA);
179   void writeSectionContent(Elf_Shdr &SHeader,
180                            const ELFYAML::AddrsigSection &Section,
181                            ContiguousBlobAccumulator &CBA);
182   void writeSectionContent(Elf_Shdr &SHeader,
183                            const ELFYAML::NoteSection &Section,
184                            ContiguousBlobAccumulator &CBA);
185   void writeSectionContent(Elf_Shdr &SHeader,
186                            const ELFYAML::GnuHashSection &Section,
187                            ContiguousBlobAccumulator &CBA);
188 
189   ELFState(ELFYAML::Object &D, yaml::ErrorHandler EH);
190 
191 public:
192   static bool writeELF(raw_ostream &OS, ELFYAML::Object &Doc,
193                        yaml::ErrorHandler EH);
194 };
195 } // end anonymous namespace
196 
197 template <class T> static size_t arrayDataSize(ArrayRef<T> A) {
198   return A.size() * sizeof(T);
199 }
200 
201 template <class T> static void writeArrayData(raw_ostream &OS, ArrayRef<T> A) {
202   OS.write((const char *)A.data(), arrayDataSize(A));
203 }
204 
205 template <class T> static void zero(T &Obj) { memset(&Obj, 0, sizeof(Obj)); }
206 
207 template <class ELFT>
208 ELFState<ELFT>::ELFState(ELFYAML::Object &D, yaml::ErrorHandler EH)
209     : Doc(D), ErrHandler(EH) {
210   StringSet<> DocSections;
211   for (std::unique_ptr<ELFYAML::Section> &D : Doc.Sections)
212     if (!D->Name.empty())
213       DocSections.insert(D->Name);
214 
215   // Insert SHT_NULL section implicitly when it is not defined in YAML.
216   if (Doc.Sections.empty() || Doc.Sections.front()->Type != ELF::SHT_NULL)
217     Doc.Sections.insert(
218         Doc.Sections.begin(),
219         std::make_unique<ELFYAML::Section>(
220             ELFYAML::Section::SectionKind::RawContent, /*IsImplicit=*/true));
221 
222   std::vector<StringRef> ImplicitSections;
223   if (Doc.Symbols)
224     ImplicitSections.push_back(".symtab");
225   ImplicitSections.insert(ImplicitSections.end(), {".strtab", ".shstrtab"});
226 
227   if (!Doc.DynamicSymbols.empty())
228     ImplicitSections.insert(ImplicitSections.end(), {".dynsym", ".dynstr"});
229 
230   // Insert placeholders for implicit sections that are not
231   // defined explicitly in YAML.
232   for (StringRef SecName : ImplicitSections) {
233     if (DocSections.count(SecName))
234       continue;
235 
236     std::unique_ptr<ELFYAML::Section> Sec = std::make_unique<ELFYAML::Section>(
237         ELFYAML::Section::SectionKind::RawContent, true /*IsImplicit*/);
238     Sec->Name = SecName;
239     Doc.Sections.push_back(std::move(Sec));
240   }
241 }
242 
243 template <class ELFT>
244 void ELFState<ELFT>::writeELFHeader(ContiguousBlobAccumulator &CBA, raw_ostream &OS) {
245   using namespace llvm::ELF;
246 
247   Elf_Ehdr Header;
248   zero(Header);
249   Header.e_ident[EI_MAG0] = 0x7f;
250   Header.e_ident[EI_MAG1] = 'E';
251   Header.e_ident[EI_MAG2] = 'L';
252   Header.e_ident[EI_MAG3] = 'F';
253   Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
254   Header.e_ident[EI_DATA] = Doc.Header.Data;
255   Header.e_ident[EI_VERSION] = EV_CURRENT;
256   Header.e_ident[EI_OSABI] = Doc.Header.OSABI;
257   Header.e_ident[EI_ABIVERSION] = Doc.Header.ABIVersion;
258   Header.e_type = Doc.Header.Type;
259   Header.e_machine = Doc.Header.Machine;
260   Header.e_version = EV_CURRENT;
261   Header.e_entry = Doc.Header.Entry;
262   Header.e_phoff = Doc.ProgramHeaders.size() ? sizeof(Header) : 0;
263   Header.e_flags = Doc.Header.Flags;
264   Header.e_ehsize = sizeof(Elf_Ehdr);
265   Header.e_phentsize = Doc.ProgramHeaders.size() ? sizeof(Elf_Phdr) : 0;
266   Header.e_phnum = Doc.ProgramHeaders.size();
267 
268   Header.e_shentsize =
269       Doc.Header.SHEntSize ? (uint16_t)*Doc.Header.SHEntSize : sizeof(Elf_Shdr);
270   // Immediately following the ELF header and program headers.
271   // Align the start of the section header and write the ELF header.
272   uint64_t SHOff;
273   CBA.getOSAndAlignedOffset(SHOff, sizeof(typename ELFT::uint));
274   Header.e_shoff =
275       Doc.Header.SHOff ? typename ELFT::uint(*Doc.Header.SHOff) : SHOff;
276   Header.e_shnum =
277       Doc.Header.SHNum ? (uint16_t)*Doc.Header.SHNum : Doc.Sections.size();
278   Header.e_shstrndx = Doc.Header.SHStrNdx ? (uint16_t)*Doc.Header.SHStrNdx
279                                           : SN2I.get(".shstrtab");
280 
281   OS.write((const char *)&Header, sizeof(Header));
282 }
283 
284 template <class ELFT>
285 void ELFState<ELFT>::initProgramHeaders(std::vector<Elf_Phdr> &PHeaders) {
286   for (const auto &YamlPhdr : Doc.ProgramHeaders) {
287     Elf_Phdr Phdr;
288     Phdr.p_type = YamlPhdr.Type;
289     Phdr.p_flags = YamlPhdr.Flags;
290     Phdr.p_vaddr = YamlPhdr.VAddr;
291     Phdr.p_paddr = YamlPhdr.PAddr;
292     PHeaders.push_back(Phdr);
293   }
294 }
295 
296 template <class ELFT>
297 unsigned ELFState<ELFT>::toSectionIndex(StringRef S, StringRef LocSec,
298                                         StringRef LocSym) {
299   unsigned Index;
300   if (SN2I.lookup(S, Index) || to_integer(S, Index))
301     return Index;
302 
303   assert(LocSec.empty() || LocSym.empty());
304   if (!LocSym.empty())
305     reportError("unknown section referenced: '" + S + "' by YAML symbol '" +
306                 LocSym + "'");
307   else
308     reportError("unknown section referenced: '" + S + "' by YAML section '" +
309                 LocSec + "'");
310   return 0;
311 }
312 
313 template <class ELFT>
314 unsigned ELFState<ELFT>::toSymbolIndex(StringRef S, StringRef LocSec,
315                                        bool IsDynamic) {
316   const NameToIdxMap &SymMap = IsDynamic ? DynSymN2I : SymN2I;
317   unsigned Index;
318   // Here we try to look up S in the symbol table. If it is not there,
319   // treat its value as a symbol index.
320   if (!SymMap.lookup(S, Index) && !to_integer(S, Index)) {
321     reportError("unknown symbol referenced: '" + S + "' by YAML section '" +
322                 LocSec + "'");
323     return 0;
324   }
325   return Index;
326 }
327 
328 template <class ELFT>
329 bool ELFState<ELFT>::initImplicitHeader(ContiguousBlobAccumulator &CBA,
330                                         Elf_Shdr &Header, StringRef SecName,
331                                         ELFYAML::Section *YAMLSec) {
332   // Check if the header was already initialized.
333   if (Header.sh_offset)
334     return false;
335 
336   if (SecName == ".symtab")
337     initSymtabSectionHeader(Header, SymtabType::Static, CBA, YAMLSec);
338   else if (SecName == ".strtab")
339     initStrtabSectionHeader(Header, SecName, DotStrtab, CBA, YAMLSec);
340   else if (SecName == ".shstrtab")
341     initStrtabSectionHeader(Header, SecName, DotShStrtab, CBA, YAMLSec);
342   else if (SecName == ".dynsym")
343     initSymtabSectionHeader(Header, SymtabType::Dynamic, CBA, YAMLSec);
344   else if (SecName == ".dynstr")
345     initStrtabSectionHeader(Header, SecName, DotDynstr, CBA, YAMLSec);
346   else
347     return false;
348 
349   // Override the fields if requested.
350   if (YAMLSec) {
351     if (YAMLSec->ShName)
352       Header.sh_name = *YAMLSec->ShName;
353     if (YAMLSec->ShOffset)
354       Header.sh_offset = *YAMLSec->ShOffset;
355     if (YAMLSec->ShSize)
356       Header.sh_size = *YAMLSec->ShSize;
357   }
358 
359   return true;
360 }
361 
362 StringRef llvm::ELFYAML::dropUniqueSuffix(StringRef S) {
363   size_t SuffixPos = S.rfind(" [");
364   if (SuffixPos == StringRef::npos)
365     return S;
366   return S.substr(0, SuffixPos);
367 }
368 
369 template <class ELFT>
370 void ELFState<ELFT>::initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
371                                         ContiguousBlobAccumulator &CBA) {
372   // Ensure SHN_UNDEF entry is present. An all-zero section header is a
373   // valid SHN_UNDEF entry since SHT_NULL == 0.
374   SHeaders.resize(Doc.Sections.size());
375 
376   for (size_t I = 0; I < Doc.Sections.size(); ++I) {
377     ELFYAML::Section *Sec = Doc.Sections[I].get();
378     if (I == 0 && Sec->IsImplicit)
379       continue;
380 
381     // We have a few sections like string or symbol tables that are usually
382     // added implicitly to the end. However, if they are explicitly specified
383     // in the YAML, we need to write them here. This ensures the file offset
384     // remains correct.
385     Elf_Shdr &SHeader = SHeaders[I];
386     if (initImplicitHeader(CBA, SHeader, Sec->Name,
387                            Sec->IsImplicit ? nullptr : Sec))
388       continue;
389 
390     assert(Sec && "It can't be null unless it is an implicit section. But all "
391                   "implicit sections should already have been handled above.");
392 
393     SHeader.sh_name =
394         DotShStrtab.getOffset(ELFYAML::dropUniqueSuffix(Sec->Name));
395     SHeader.sh_type = Sec->Type;
396     if (Sec->Flags)
397       SHeader.sh_flags = *Sec->Flags;
398     SHeader.sh_addr = Sec->Address;
399     SHeader.sh_addralign = Sec->AddressAlign;
400 
401     if (!Sec->Link.empty())
402       SHeader.sh_link = toSectionIndex(Sec->Link, Sec->Name);
403 
404     if (I == 0) {
405       if (auto RawSec = dyn_cast<ELFYAML::RawContentSection>(Sec)) {
406         // We do not write any content for special SHN_UNDEF section.
407         if (RawSec->Size)
408           SHeader.sh_size = *RawSec->Size;
409         if (RawSec->Info)
410           SHeader.sh_info = *RawSec->Info;
411       }
412       if (Sec->EntSize)
413         SHeader.sh_entsize = *Sec->EntSize;
414     } else if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec)) {
415       writeSectionContent(SHeader, *S, CBA);
416     } else if (auto S = dyn_cast<ELFYAML::SymtabShndxSection>(Sec)) {
417       writeSectionContent(SHeader, *S, CBA);
418     } else if (auto S = dyn_cast<ELFYAML::RelocationSection>(Sec)) {
419       writeSectionContent(SHeader, *S, CBA);
420     } else if (auto S = dyn_cast<ELFYAML::Group>(Sec)) {
421       writeSectionContent(SHeader, *S, CBA);
422     } else if (auto S = dyn_cast<ELFYAML::MipsABIFlags>(Sec)) {
423       writeSectionContent(SHeader, *S, CBA);
424     } else if (auto S = dyn_cast<ELFYAML::NoBitsSection>(Sec)) {
425       SHeader.sh_entsize = 0;
426       SHeader.sh_size = S->Size;
427       // SHT_NOBITS section does not have content
428       // so just to setup the section offset.
429       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
430     } else if (auto S = dyn_cast<ELFYAML::DynamicSection>(Sec)) {
431       writeSectionContent(SHeader, *S, CBA);
432     } else if (auto S = dyn_cast<ELFYAML::SymverSection>(Sec)) {
433       writeSectionContent(SHeader, *S, CBA);
434     } else if (auto S = dyn_cast<ELFYAML::VerneedSection>(Sec)) {
435       writeSectionContent(SHeader, *S, CBA);
436     } else if (auto S = dyn_cast<ELFYAML::VerdefSection>(Sec)) {
437       writeSectionContent(SHeader, *S, CBA);
438     } else if (auto S = dyn_cast<ELFYAML::StackSizesSection>(Sec)) {
439       writeSectionContent(SHeader, *S, CBA);
440     } else if (auto S = dyn_cast<ELFYAML::HashSection>(Sec)) {
441       writeSectionContent(SHeader, *S, CBA);
442     } else if (auto S = dyn_cast<ELFYAML::AddrsigSection>(Sec)) {
443       writeSectionContent(SHeader, *S, CBA);
444     } else if (auto S = dyn_cast<ELFYAML::NoteSection>(Sec)) {
445       writeSectionContent(SHeader, *S, CBA);
446     } else if (auto S = dyn_cast<ELFYAML::GnuHashSection>(Sec)) {
447       writeSectionContent(SHeader, *S, CBA);
448     } else {
449       llvm_unreachable("Unknown section type");
450     }
451 
452     // Override the fields if requested.
453     if (Sec) {
454       if (Sec->ShName)
455         SHeader.sh_name = *Sec->ShName;
456       if (Sec->ShOffset)
457         SHeader.sh_offset = *Sec->ShOffset;
458       if (Sec->ShSize)
459         SHeader.sh_size = *Sec->ShSize;
460     }
461   }
462 }
463 
464 static size_t findFirstNonGlobal(ArrayRef<ELFYAML::Symbol> Symbols) {
465   for (size_t I = 0; I < Symbols.size(); ++I)
466     if (Symbols[I].Binding.value != ELF::STB_LOCAL)
467       return I;
468   return Symbols.size();
469 }
470 
471 static uint64_t writeContent(raw_ostream &OS,
472                              const Optional<yaml::BinaryRef> &Content,
473                              const Optional<llvm::yaml::Hex64> &Size) {
474   size_t ContentSize = 0;
475   if (Content) {
476     Content->writeAsBinary(OS);
477     ContentSize = Content->binary_size();
478   }
479 
480   if (!Size)
481     return ContentSize;
482 
483   OS.write_zeros(*Size - ContentSize);
484   return *Size;
485 }
486 
487 template <class ELFT>
488 std::vector<typename ELFT::Sym>
489 ELFState<ELFT>::toELFSymbols(ArrayRef<ELFYAML::Symbol> Symbols,
490                              const StringTableBuilder &Strtab) {
491   std::vector<Elf_Sym> Ret;
492   Ret.resize(Symbols.size() + 1);
493 
494   size_t I = 0;
495   for (const ELFYAML::Symbol &Sym : Symbols) {
496     Elf_Sym &Symbol = Ret[++I];
497 
498     // If NameIndex, which contains the name offset, is explicitly specified, we
499     // use it. This is useful for preparing broken objects. Otherwise, we add
500     // the specified Name to the string table builder to get its offset.
501     if (Sym.NameIndex)
502       Symbol.st_name = *Sym.NameIndex;
503     else if (!Sym.Name.empty())
504       Symbol.st_name = Strtab.getOffset(ELFYAML::dropUniqueSuffix(Sym.Name));
505 
506     Symbol.setBindingAndType(Sym.Binding, Sym.Type);
507     if (!Sym.Section.empty())
508       Symbol.st_shndx = toSectionIndex(Sym.Section, "", Sym.Name);
509     else if (Sym.Index)
510       Symbol.st_shndx = *Sym.Index;
511 
512     Symbol.st_value = Sym.Value;
513     Symbol.st_other = Sym.Other ? *Sym.Other : 0;
514     Symbol.st_size = Sym.Size;
515   }
516 
517   return Ret;
518 }
519 
520 template <class ELFT>
521 void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
522                                              SymtabType STType,
523                                              ContiguousBlobAccumulator &CBA,
524                                              ELFYAML::Section *YAMLSec) {
525 
526   bool IsStatic = STType == SymtabType::Static;
527   ArrayRef<ELFYAML::Symbol> Symbols;
528   if (IsStatic && Doc.Symbols)
529     Symbols = *Doc.Symbols;
530   else if (!IsStatic)
531     Symbols = Doc.DynamicSymbols;
532 
533   ELFYAML::RawContentSection *RawSec =
534       dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec);
535   if (RawSec && !Symbols.empty() && (RawSec->Content || RawSec->Size)) {
536     if (RawSec->Content)
537       reportError("cannot specify both `Content` and " +
538                   (IsStatic ? Twine("`Symbols`") : Twine("`DynamicSymbols`")) +
539                   " for symbol table section '" + RawSec->Name + "'");
540     if (RawSec->Size)
541       reportError("cannot specify both `Size` and " +
542                   (IsStatic ? Twine("`Symbols`") : Twine("`DynamicSymbols`")) +
543                   " for symbol table section '" + RawSec->Name + "'");
544     return;
545   }
546 
547   zero(SHeader);
548   SHeader.sh_name = DotShStrtab.getOffset(IsStatic ? ".symtab" : ".dynsym");
549 
550   if (YAMLSec)
551     SHeader.sh_type = YAMLSec->Type;
552   else
553     SHeader.sh_type = IsStatic ? ELF::SHT_SYMTAB : ELF::SHT_DYNSYM;
554 
555   if (RawSec && !RawSec->Link.empty()) {
556     // If the Link field is explicitly defined in the document,
557     // we should use it.
558     SHeader.sh_link = toSectionIndex(RawSec->Link, RawSec->Name);
559   } else {
560     // When we describe the .dynsym section in the document explicitly, it is
561     // allowed to omit the "DynamicSymbols" tag. In this case .dynstr is not
562     // added implicitly and we should be able to leave the Link zeroed if
563     // .dynstr is not defined.
564     unsigned Link = 0;
565     if (IsStatic)
566       Link = SN2I.get(".strtab");
567     else
568       SN2I.lookup(".dynstr", Link);
569     SHeader.sh_link = Link;
570   }
571 
572   if (YAMLSec && YAMLSec->Flags)
573     SHeader.sh_flags = *YAMLSec->Flags;
574   else if (!IsStatic)
575     SHeader.sh_flags = ELF::SHF_ALLOC;
576 
577   // If the symbol table section is explicitly described in the YAML
578   // then we should set the fields requested.
579   SHeader.sh_info = (RawSec && RawSec->Info) ? (unsigned)(*RawSec->Info)
580                                              : findFirstNonGlobal(Symbols) + 1;
581   SHeader.sh_entsize = (YAMLSec && YAMLSec->EntSize)
582                            ? (uint64_t)(*YAMLSec->EntSize)
583                            : sizeof(Elf_Sym);
584   SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 8;
585   SHeader.sh_addr = YAMLSec ? (uint64_t)YAMLSec->Address : 0;
586 
587   auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
588   if (RawSec && (RawSec->Content || RawSec->Size)) {
589     assert(Symbols.empty());
590     SHeader.sh_size = writeContent(OS, RawSec->Content, RawSec->Size);
591     return;
592   }
593 
594   std::vector<Elf_Sym> Syms =
595       toELFSymbols(Symbols, IsStatic ? DotStrtab : DotDynstr);
596   writeArrayData(OS, makeArrayRef(Syms));
597   SHeader.sh_size = arrayDataSize(makeArrayRef(Syms));
598 }
599 
600 template <class ELFT>
601 void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
602                                              StringTableBuilder &STB,
603                                              ContiguousBlobAccumulator &CBA,
604                                              ELFYAML::Section *YAMLSec) {
605   zero(SHeader);
606   SHeader.sh_name = DotShStrtab.getOffset(Name);
607   SHeader.sh_type = YAMLSec ? YAMLSec->Type : ELF::SHT_STRTAB;
608   SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 1;
609 
610   ELFYAML::RawContentSection *RawSec =
611       dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec);
612 
613   auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
614   if (RawSec && (RawSec->Content || RawSec->Size)) {
615     SHeader.sh_size = writeContent(OS, RawSec->Content, RawSec->Size);
616   } else {
617     STB.write(OS);
618     SHeader.sh_size = STB.getSize();
619   }
620 
621   if (YAMLSec && YAMLSec->EntSize)
622     SHeader.sh_entsize = *YAMLSec->EntSize;
623 
624   if (RawSec && RawSec->Info)
625     SHeader.sh_info = *RawSec->Info;
626 
627   if (YAMLSec && YAMLSec->Flags)
628     SHeader.sh_flags = *YAMLSec->Flags;
629   else if (Name == ".dynstr")
630     SHeader.sh_flags = ELF::SHF_ALLOC;
631 
632   // If the section is explicitly described in the YAML
633   // then we want to use its section address.
634   if (YAMLSec)
635     SHeader.sh_addr = YAMLSec->Address;
636 }
637 
638 template <class ELFT> void ELFState<ELFT>::reportError(const Twine &Msg) {
639   ErrHandler(Msg);
640   HasError = true;
641 }
642 
643 template <class ELFT>
644 void ELFState<ELFT>::setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
645                                             std::vector<Elf_Shdr> &SHeaders) {
646   uint32_t PhdrIdx = 0;
647   for (auto &YamlPhdr : Doc.ProgramHeaders) {
648     Elf_Phdr &PHeader = PHeaders[PhdrIdx++];
649 
650     std::vector<Elf_Shdr *> Sections;
651     for (const ELFYAML::SectionName &SecName : YamlPhdr.Sections) {
652       unsigned Index;
653       if (!SN2I.lookup(SecName.Section, Index)) {
654         reportError("unknown section referenced: '" + SecName.Section +
655                     "' by program header");
656         continue;
657       }
658       Sections.push_back(&SHeaders[Index]);
659     }
660 
661     if (YamlPhdr.Offset) {
662       PHeader.p_offset = *YamlPhdr.Offset;
663     } else {
664       if (YamlPhdr.Sections.size())
665         PHeader.p_offset = UINT32_MAX;
666       else
667         PHeader.p_offset = 0;
668 
669       // Find the minimum offset for the program header.
670       for (Elf_Shdr *SHeader : Sections)
671         PHeader.p_offset = std::min(PHeader.p_offset, SHeader->sh_offset);
672     }
673 
674     // Find the maximum offset of the end of a section in order to set p_filesz
675     // and p_memsz. When setting p_filesz, trailing SHT_NOBITS sections are not
676     // counted.
677     uint64_t FileOffset = PHeader.p_offset, MemOffset = PHeader.p_offset;
678     for (Elf_Shdr *SHeader : Sections) {
679       uint64_t End = SHeader->sh_offset + SHeader->sh_size;
680       MemOffset = std::max(MemOffset, End);
681 
682       if (SHeader->sh_type != llvm::ELF::SHT_NOBITS)
683         FileOffset = std::max(FileOffset, End);
684     }
685 
686     // Set the file size and the memory size if not set explicitly.
687     PHeader.p_filesz = YamlPhdr.FileSize ? uint64_t(*YamlPhdr.FileSize)
688                                          : FileOffset - PHeader.p_offset;
689     PHeader.p_memsz = YamlPhdr.MemSize ? uint64_t(*YamlPhdr.MemSize)
690                                        : MemOffset - PHeader.p_offset;
691 
692     if (YamlPhdr.Align) {
693       PHeader.p_align = *YamlPhdr.Align;
694     } else {
695       // Set the alignment of the segment to be the maximum alignment of the
696       // sections so that by default the segment has a valid and sensible
697       // alignment.
698       PHeader.p_align = 1;
699       for (Elf_Shdr *SHeader : Sections)
700         PHeader.p_align = std::max(PHeader.p_align, SHeader->sh_addralign);
701     }
702   }
703 }
704 
705 template <class ELFT>
706 void ELFState<ELFT>::writeSectionContent(
707     Elf_Shdr &SHeader, const ELFYAML::RawContentSection &Section,
708     ContiguousBlobAccumulator &CBA) {
709   raw_ostream &OS =
710       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
711   SHeader.sh_size = writeContent(OS, Section.Content, Section.Size);
712 
713   if (Section.EntSize)
714     SHeader.sh_entsize = *Section.EntSize;
715   else if (Section.Type == llvm::ELF::SHT_RELR)
716     SHeader.sh_entsize = sizeof(Elf_Relr);
717   else
718     SHeader.sh_entsize = 0;
719 
720   if (Section.Info)
721     SHeader.sh_info = *Section.Info;
722 }
723 
724 static bool isMips64EL(const ELFYAML::Object &Doc) {
725   return Doc.Header.Machine == ELFYAML::ELF_EM(llvm::ELF::EM_MIPS) &&
726          Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64) &&
727          Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
728 }
729 
730 template <class ELFT>
731 void ELFState<ELFT>::writeSectionContent(
732     Elf_Shdr &SHeader, const ELFYAML::RelocationSection &Section,
733     ContiguousBlobAccumulator &CBA) {
734   assert((Section.Type == llvm::ELF::SHT_REL ||
735           Section.Type == llvm::ELF::SHT_RELA) &&
736          "Section type is not SHT_REL nor SHT_RELA");
737 
738   bool IsRela = Section.Type == llvm::ELF::SHT_RELA;
739   SHeader.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
740   SHeader.sh_size = SHeader.sh_entsize * Section.Relocations.size();
741 
742   // For relocation section set link to .symtab by default.
743   unsigned Link = 0;
744   if (Section.Link.empty() && SN2I.lookup(".symtab", Link))
745     SHeader.sh_link = Link;
746 
747   if (!Section.RelocatableSec.empty())
748     SHeader.sh_info = toSectionIndex(Section.RelocatableSec, Section.Name);
749 
750   auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
751   for (const auto &Rel : Section.Relocations) {
752     unsigned SymIdx = Rel.Symbol ? toSymbolIndex(*Rel.Symbol, Section.Name,
753                                                  Section.Link == ".dynsym")
754                                  : 0;
755     if (IsRela) {
756       Elf_Rela REntry;
757       zero(REntry);
758       REntry.r_offset = Rel.Offset;
759       REntry.r_addend = Rel.Addend;
760       REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
761       OS.write((const char *)&REntry, sizeof(REntry));
762     } else {
763       Elf_Rel REntry;
764       zero(REntry);
765       REntry.r_offset = Rel.Offset;
766       REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
767       OS.write((const char *)&REntry, sizeof(REntry));
768     }
769   }
770 }
771 
772 template <class ELFT>
773 void ELFState<ELFT>::writeSectionContent(
774     Elf_Shdr &SHeader, const ELFYAML::SymtabShndxSection &Shndx,
775     ContiguousBlobAccumulator &CBA) {
776   raw_ostream &OS =
777       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
778 
779   for (uint32_t E : Shndx.Entries)
780     support::endian::write<uint32_t>(OS, E, ELFT::TargetEndianness);
781 
782   SHeader.sh_entsize = Shndx.EntSize ? (uint64_t)*Shndx.EntSize : 4;
783   SHeader.sh_size = Shndx.Entries.size() * SHeader.sh_entsize;
784 }
785 
786 template <class ELFT>
787 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
788                                          const ELFYAML::Group &Section,
789                                          ContiguousBlobAccumulator &CBA) {
790   assert(Section.Type == llvm::ELF::SHT_GROUP &&
791          "Section type is not SHT_GROUP");
792 
793   unsigned Link = 0;
794   if (Section.Link.empty() && SN2I.lookup(".symtab", Link))
795     SHeader.sh_link = Link;
796 
797   SHeader.sh_entsize = 4;
798   SHeader.sh_size = SHeader.sh_entsize * Section.Members.size();
799 
800   if (Section.Signature)
801     SHeader.sh_info =
802         toSymbolIndex(*Section.Signature, Section.Name, /*IsDynamic=*/false);
803 
804   raw_ostream &OS =
805       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
806 
807   for (const ELFYAML::SectionOrType &Member : Section.Members) {
808     unsigned int SectionIndex = 0;
809     if (Member.sectionNameOrType == "GRP_COMDAT")
810       SectionIndex = llvm::ELF::GRP_COMDAT;
811     else
812       SectionIndex = toSectionIndex(Member.sectionNameOrType, Section.Name);
813     support::endian::write<uint32_t>(OS, SectionIndex, ELFT::TargetEndianness);
814   }
815 }
816 
817 template <class ELFT>
818 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
819                                          const ELFYAML::SymverSection &Section,
820                                          ContiguousBlobAccumulator &CBA) {
821   raw_ostream &OS =
822       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
823   for (uint16_t Version : Section.Entries)
824     support::endian::write<uint16_t>(OS, Version, ELFT::TargetEndianness);
825 
826   SHeader.sh_entsize = Section.EntSize ? (uint64_t)*Section.EntSize : 2;
827   SHeader.sh_size = Section.Entries.size() * SHeader.sh_entsize;
828 }
829 
830 template <class ELFT>
831 void ELFState<ELFT>::writeSectionContent(
832     Elf_Shdr &SHeader, const ELFYAML::StackSizesSection &Section,
833     ContiguousBlobAccumulator &CBA) {
834   using uintX_t = typename ELFT::uint;
835   raw_ostream &OS =
836       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
837 
838   if (Section.Content || Section.Size) {
839     SHeader.sh_size = writeContent(OS, Section.Content, Section.Size);
840     return;
841   }
842 
843   for (const ELFYAML::StackSizeEntry &E : *Section.Entries) {
844     support::endian::write<uintX_t>(OS, E.Address, ELFT::TargetEndianness);
845     SHeader.sh_size += sizeof(uintX_t) + encodeULEB128(E.Size, OS);
846   }
847 }
848 
849 template <class ELFT>
850 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
851                                          const ELFYAML::HashSection &Section,
852                                          ContiguousBlobAccumulator &CBA) {
853   raw_ostream &OS =
854       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
855 
856   unsigned Link = 0;
857   if (Section.Link.empty() && SN2I.lookup(".dynsym", Link))
858     SHeader.sh_link = Link;
859 
860   if (Section.Content || Section.Size) {
861     SHeader.sh_size = writeContent(OS, Section.Content, Section.Size);
862     return;
863   }
864 
865   support::endian::write<uint32_t>(OS, Section.Bucket->size(),
866                                    ELFT::TargetEndianness);
867   support::endian::write<uint32_t>(OS, Section.Chain->size(),
868                                    ELFT::TargetEndianness);
869   for (uint32_t Val : *Section.Bucket)
870     support::endian::write<uint32_t>(OS, Val, ELFT::TargetEndianness);
871   for (uint32_t Val : *Section.Chain)
872     support::endian::write<uint32_t>(OS, Val, ELFT::TargetEndianness);
873 
874   SHeader.sh_size = (2 + Section.Bucket->size() + Section.Chain->size()) * 4;
875 }
876 
877 template <class ELFT>
878 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
879                                          const ELFYAML::VerdefSection &Section,
880                                          ContiguousBlobAccumulator &CBA) {
881   typedef typename ELFT::Verdef Elf_Verdef;
882   typedef typename ELFT::Verdaux Elf_Verdaux;
883   raw_ostream &OS =
884       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
885 
886   uint64_t AuxCnt = 0;
887   for (size_t I = 0; I < Section.Entries.size(); ++I) {
888     const ELFYAML::VerdefEntry &E = Section.Entries[I];
889 
890     Elf_Verdef VerDef;
891     VerDef.vd_version = E.Version;
892     VerDef.vd_flags = E.Flags;
893     VerDef.vd_ndx = E.VersionNdx;
894     VerDef.vd_hash = E.Hash;
895     VerDef.vd_aux = sizeof(Elf_Verdef);
896     VerDef.vd_cnt = E.VerNames.size();
897     if (I == Section.Entries.size() - 1)
898       VerDef.vd_next = 0;
899     else
900       VerDef.vd_next =
901           sizeof(Elf_Verdef) + E.VerNames.size() * sizeof(Elf_Verdaux);
902     OS.write((const char *)&VerDef, sizeof(Elf_Verdef));
903 
904     for (size_t J = 0; J < E.VerNames.size(); ++J, ++AuxCnt) {
905       Elf_Verdaux VernAux;
906       VernAux.vda_name = DotDynstr.getOffset(E.VerNames[J]);
907       if (J == E.VerNames.size() - 1)
908         VernAux.vda_next = 0;
909       else
910         VernAux.vda_next = sizeof(Elf_Verdaux);
911       OS.write((const char *)&VernAux, sizeof(Elf_Verdaux));
912     }
913   }
914 
915   SHeader.sh_size = Section.Entries.size() * sizeof(Elf_Verdef) +
916                     AuxCnt * sizeof(Elf_Verdaux);
917   SHeader.sh_info = Section.Info;
918 }
919 
920 template <class ELFT>
921 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
922                                          const ELFYAML::VerneedSection &Section,
923                                          ContiguousBlobAccumulator &CBA) {
924   typedef typename ELFT::Verneed Elf_Verneed;
925   typedef typename ELFT::Vernaux Elf_Vernaux;
926 
927   auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
928 
929   uint64_t AuxCnt = 0;
930   for (size_t I = 0; I < Section.VerneedV.size(); ++I) {
931     const ELFYAML::VerneedEntry &VE = Section.VerneedV[I];
932 
933     Elf_Verneed VerNeed;
934     VerNeed.vn_version = VE.Version;
935     VerNeed.vn_file = DotDynstr.getOffset(VE.File);
936     if (I == Section.VerneedV.size() - 1)
937       VerNeed.vn_next = 0;
938     else
939       VerNeed.vn_next =
940           sizeof(Elf_Verneed) + VE.AuxV.size() * sizeof(Elf_Vernaux);
941     VerNeed.vn_cnt = VE.AuxV.size();
942     VerNeed.vn_aux = sizeof(Elf_Verneed);
943     OS.write((const char *)&VerNeed, sizeof(Elf_Verneed));
944 
945     for (size_t J = 0; J < VE.AuxV.size(); ++J, ++AuxCnt) {
946       const ELFYAML::VernauxEntry &VAuxE = VE.AuxV[J];
947 
948       Elf_Vernaux VernAux;
949       VernAux.vna_hash = VAuxE.Hash;
950       VernAux.vna_flags = VAuxE.Flags;
951       VernAux.vna_other = VAuxE.Other;
952       VernAux.vna_name = DotDynstr.getOffset(VAuxE.Name);
953       if (J == VE.AuxV.size() - 1)
954         VernAux.vna_next = 0;
955       else
956         VernAux.vna_next = sizeof(Elf_Vernaux);
957       OS.write((const char *)&VernAux, sizeof(Elf_Vernaux));
958     }
959   }
960 
961   SHeader.sh_size = Section.VerneedV.size() * sizeof(Elf_Verneed) +
962                     AuxCnt * sizeof(Elf_Vernaux);
963   SHeader.sh_info = Section.Info;
964 }
965 
966 template <class ELFT>
967 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
968                                          const ELFYAML::MipsABIFlags &Section,
969                                          ContiguousBlobAccumulator &CBA) {
970   assert(Section.Type == llvm::ELF::SHT_MIPS_ABIFLAGS &&
971          "Section type is not SHT_MIPS_ABIFLAGS");
972 
973   object::Elf_Mips_ABIFlags<ELFT> Flags;
974   zero(Flags);
975   SHeader.sh_entsize = sizeof(Flags);
976   SHeader.sh_size = SHeader.sh_entsize;
977 
978   auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
979   Flags.version = Section.Version;
980   Flags.isa_level = Section.ISALevel;
981   Flags.isa_rev = Section.ISARevision;
982   Flags.gpr_size = Section.GPRSize;
983   Flags.cpr1_size = Section.CPR1Size;
984   Flags.cpr2_size = Section.CPR2Size;
985   Flags.fp_abi = Section.FpABI;
986   Flags.isa_ext = Section.ISAExtension;
987   Flags.ases = Section.ASEs;
988   Flags.flags1 = Section.Flags1;
989   Flags.flags2 = Section.Flags2;
990   OS.write((const char *)&Flags, sizeof(Flags));
991 }
992 
993 template <class ELFT>
994 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
995                                          const ELFYAML::DynamicSection &Section,
996                                          ContiguousBlobAccumulator &CBA) {
997   typedef typename ELFT::uint uintX_t;
998 
999   assert(Section.Type == llvm::ELF::SHT_DYNAMIC &&
1000          "Section type is not SHT_DYNAMIC");
1001 
1002   if (!Section.Entries.empty() && Section.Content)
1003     reportError("cannot specify both raw content and explicit entries "
1004                 "for dynamic section '" +
1005                 Section.Name + "'");
1006 
1007   if (Section.Content)
1008     SHeader.sh_size = Section.Content->binary_size();
1009   else
1010     SHeader.sh_size = 2 * sizeof(uintX_t) * Section.Entries.size();
1011   if (Section.EntSize)
1012     SHeader.sh_entsize = *Section.EntSize;
1013   else
1014     SHeader.sh_entsize = sizeof(Elf_Dyn);
1015 
1016   raw_ostream &OS =
1017       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
1018   for (const ELFYAML::DynamicEntry &DE : Section.Entries) {
1019     support::endian::write<uintX_t>(OS, DE.Tag, ELFT::TargetEndianness);
1020     support::endian::write<uintX_t>(OS, DE.Val, ELFT::TargetEndianness);
1021   }
1022   if (Section.Content)
1023     Section.Content->writeAsBinary(OS);
1024 }
1025 
1026 template <class ELFT>
1027 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1028                                          const ELFYAML::AddrsigSection &Section,
1029                                          ContiguousBlobAccumulator &CBA) {
1030   raw_ostream &OS =
1031       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
1032 
1033   unsigned Link = 0;
1034   if (Section.Link.empty() && SN2I.lookup(".symtab", Link))
1035     SHeader.sh_link = Link;
1036 
1037   if (Section.Content || Section.Size) {
1038     SHeader.sh_size = writeContent(OS, Section.Content, Section.Size);
1039     return;
1040   }
1041 
1042   for (const ELFYAML::AddrsigSymbol &Sym : *Section.Symbols) {
1043     uint64_t Val =
1044         Sym.Name ? toSymbolIndex(*Sym.Name, Section.Name, /*IsDynamic=*/false)
1045                  : (uint32_t)*Sym.Index;
1046     SHeader.sh_size += encodeULEB128(Val, OS);
1047   }
1048 }
1049 
1050 template <class ELFT>
1051 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1052                                          const ELFYAML::NoteSection &Section,
1053                                          ContiguousBlobAccumulator &CBA) {
1054   raw_ostream &OS =
1055       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
1056   uint64_t Offset = OS.tell();
1057 
1058   if (Section.Content || Section.Size) {
1059     SHeader.sh_size = writeContent(OS, Section.Content, Section.Size);
1060     return;
1061   }
1062 
1063   for (const ELFYAML::NoteEntry &NE : *Section.Notes) {
1064     // Write name size.
1065     if (NE.Name.empty())
1066       support::endian::write<uint32_t>(OS, 0, ELFT::TargetEndianness);
1067     else
1068       support::endian::write<uint32_t>(OS, NE.Name.size() + 1,
1069                                        ELFT::TargetEndianness);
1070 
1071     // Write description size.
1072     if (NE.Desc.binary_size() == 0)
1073       support::endian::write<uint32_t>(OS, 0, ELFT::TargetEndianness);
1074     else
1075       support::endian::write<uint32_t>(OS, NE.Desc.binary_size(),
1076                                        ELFT::TargetEndianness);
1077 
1078     // Write type.
1079     support::endian::write<uint32_t>(OS, NE.Type, ELFT::TargetEndianness);
1080 
1081     // Write name, null terminator and padding.
1082     if (!NE.Name.empty()) {
1083       support::endian::write<uint8_t>(OS, arrayRefFromStringRef(NE.Name),
1084                                       ELFT::TargetEndianness);
1085       support::endian::write<uint8_t>(OS, 0, ELFT::TargetEndianness);
1086       CBA.padToAlignment(4);
1087     }
1088 
1089     // Write description and padding.
1090     if (NE.Desc.binary_size() != 0) {
1091       NE.Desc.writeAsBinary(OS);
1092       CBA.padToAlignment(4);
1093     }
1094   }
1095 
1096   SHeader.sh_size = OS.tell() - Offset;
1097 }
1098 
1099 template <class ELFT>
1100 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1101                                          const ELFYAML::GnuHashSection &Section,
1102                                          ContiguousBlobAccumulator &CBA) {
1103   raw_ostream &OS =
1104       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
1105 
1106   unsigned Link = 0;
1107   if (Section.Link.empty() && SN2I.lookup(".dynsym", Link))
1108     SHeader.sh_link = Link;
1109 
1110   if (Section.Content) {
1111     SHeader.sh_size = writeContent(OS, Section.Content, None);
1112     return;
1113   }
1114 
1115   // We write the header first, starting with the hash buckets count. Normally
1116   // it is the number of entries in HashBuckets, but the "NBuckets" property can
1117   // be used to override this field, which is useful for producing broken
1118   // objects.
1119   if (Section.Header->NBuckets)
1120     support::endian::write<uint32_t>(OS, *Section.Header->NBuckets,
1121                                      ELFT::TargetEndianness);
1122   else
1123     support::endian::write<uint32_t>(OS, Section.HashBuckets->size(),
1124                                      ELFT::TargetEndianness);
1125 
1126   // Write the index of the first symbol in the dynamic symbol table accessible
1127   // via the hash table.
1128   support::endian::write<uint32_t>(OS, Section.Header->SymNdx,
1129                                    ELFT::TargetEndianness);
1130 
1131   // Write the number of words in the Bloom filter. As above, the "MaskWords"
1132   // property can be used to set this field to any value.
1133   if (Section.Header->MaskWords)
1134     support::endian::write<uint32_t>(OS, *Section.Header->MaskWords,
1135                                      ELFT::TargetEndianness);
1136   else
1137     support::endian::write<uint32_t>(OS, Section.BloomFilter->size(),
1138                                      ELFT::TargetEndianness);
1139 
1140   // Write the shift constant used by the Bloom filter.
1141   support::endian::write<uint32_t>(OS, Section.Header->Shift2,
1142                                    ELFT::TargetEndianness);
1143 
1144   // We've finished writing the header. Now write the Bloom filter.
1145   for (llvm::yaml::Hex64 Val : *Section.BloomFilter)
1146     support::endian::write<typename ELFT::uint>(OS, Val,
1147                                                 ELFT::TargetEndianness);
1148 
1149   // Write an array of hash buckets.
1150   for (llvm::yaml::Hex32 Val : *Section.HashBuckets)
1151     support::endian::write<uint32_t>(OS, Val, ELFT::TargetEndianness);
1152 
1153   // Write an array of hash values.
1154   for (llvm::yaml::Hex32 Val : *Section.HashValues)
1155     support::endian::write<uint32_t>(OS, Val, ELFT::TargetEndianness);
1156 
1157   SHeader.sh_size = 16 /*Header size*/ +
1158                     Section.BloomFilter->size() * sizeof(typename ELFT::uint) +
1159                     Section.HashBuckets->size() * 4 +
1160                     Section.HashValues->size() * 4;
1161 }
1162 
1163 template <class ELFT> void ELFState<ELFT>::buildSectionIndex() {
1164   for (unsigned I = 0, E = Doc.Sections.size(); I != E; ++I) {
1165     StringRef Name = Doc.Sections[I]->Name;
1166     if (Name.empty())
1167       continue;
1168 
1169     DotShStrtab.add(ELFYAML::dropUniqueSuffix(Name));
1170     if (!SN2I.addName(Name, I))
1171       reportError("repeated section name: '" + Name +
1172                   "' at YAML section number " + Twine(I));
1173   }
1174 
1175   DotShStrtab.finalize();
1176 }
1177 
1178 template <class ELFT> void ELFState<ELFT>::buildSymbolIndexes() {
1179   auto Build = [this](ArrayRef<ELFYAML::Symbol> V, NameToIdxMap &Map) {
1180     for (size_t I = 0, S = V.size(); I < S; ++I) {
1181       const ELFYAML::Symbol &Sym = V[I];
1182       if (!Sym.Name.empty() && !Map.addName(Sym.Name, I + 1))
1183         reportError("repeated symbol name: '" + Sym.Name + "'");
1184     }
1185   };
1186 
1187   if (Doc.Symbols)
1188     Build(*Doc.Symbols, SymN2I);
1189   Build(Doc.DynamicSymbols, DynSymN2I);
1190 }
1191 
1192 template <class ELFT> void ELFState<ELFT>::finalizeStrings() {
1193   // Add the regular symbol names to .strtab section.
1194   if (Doc.Symbols)
1195     for (const ELFYAML::Symbol &Sym : *Doc.Symbols)
1196       DotStrtab.add(ELFYAML::dropUniqueSuffix(Sym.Name));
1197   DotStrtab.finalize();
1198 
1199   // Add the dynamic symbol names to .dynstr section.
1200   for (const ELFYAML::Symbol &Sym : Doc.DynamicSymbols)
1201     DotDynstr.add(ELFYAML::dropUniqueSuffix(Sym.Name));
1202 
1203   // SHT_GNU_verdef and SHT_GNU_verneed sections might also
1204   // add strings to .dynstr section.
1205   for (const std::unique_ptr<ELFYAML::Section> &Sec : Doc.Sections) {
1206     if (auto VerNeed = dyn_cast<ELFYAML::VerneedSection>(Sec.get())) {
1207       for (const ELFYAML::VerneedEntry &VE : VerNeed->VerneedV) {
1208         DotDynstr.add(VE.File);
1209         for (const ELFYAML::VernauxEntry &Aux : VE.AuxV)
1210           DotDynstr.add(Aux.Name);
1211       }
1212     } else if (auto VerDef = dyn_cast<ELFYAML::VerdefSection>(Sec.get())) {
1213       for (const ELFYAML::VerdefEntry &E : VerDef->Entries)
1214         for (StringRef Name : E.VerNames)
1215           DotDynstr.add(Name);
1216     }
1217   }
1218 
1219   DotDynstr.finalize();
1220 }
1221 
1222 template <class ELFT>
1223 bool ELFState<ELFT>::writeELF(raw_ostream &OS, ELFYAML::Object &Doc,
1224                               yaml::ErrorHandler EH) {
1225   ELFState<ELFT> State(Doc, EH);
1226 
1227   // Finalize .strtab and .dynstr sections. We do that early because want to
1228   // finalize the string table builders before writing the content of the
1229   // sections that might want to use them.
1230   State.finalizeStrings();
1231 
1232   State.buildSectionIndex();
1233   State.buildSymbolIndexes();
1234 
1235   std::vector<Elf_Phdr> PHeaders;
1236   State.initProgramHeaders(PHeaders);
1237 
1238   // XXX: This offset is tightly coupled with the order that we write
1239   // things to `OS`.
1240   const size_t SectionContentBeginOffset =
1241       sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * Doc.ProgramHeaders.size();
1242   ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
1243 
1244   std::vector<Elf_Shdr> SHeaders;
1245   State.initSectionHeaders(SHeaders, CBA);
1246 
1247   // Now we can decide segment offsets.
1248   State.setProgramHeaderLayout(PHeaders, SHeaders);
1249 
1250   if (State.HasError)
1251     return false;
1252 
1253   State.writeELFHeader(CBA, OS);
1254   writeArrayData(OS, makeArrayRef(PHeaders));
1255   CBA.writeBlobToStream(OS);
1256   writeArrayData(OS, makeArrayRef(SHeaders));
1257   return true;
1258 }
1259 
1260 namespace llvm {
1261 namespace yaml {
1262 
1263 bool yaml2elf(llvm::ELFYAML::Object &Doc, raw_ostream &Out, ErrorHandler EH) {
1264   bool IsLE = Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
1265   bool Is64Bit = Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
1266   if (Is64Bit) {
1267     if (IsLE)
1268       return ELFState<object::ELF64LE>::writeELF(Out, Doc, EH);
1269     return ELFState<object::ELF64BE>::writeELF(Out, Doc, EH);
1270   }
1271   if (IsLE)
1272     return ELFState<object::ELF32LE>::writeELF(Out, Doc, EH);
1273   return ELFState<object::ELF32BE>::writeELF(Out, Doc, EH);
1274 }
1275 
1276 } // namespace yaml
1277 } // namespace llvm
1278