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