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