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