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