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