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