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