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