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