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
856     llvm_unreachable("unexpected emitDWARF() call");
857 
858   return OS.tell() - BeginOffset;
859 }
860 
861 template <class ELFT>
862 void ELFState<ELFT>::initDWARFSectionHeader(Elf_Shdr &SHeader, StringRef Name,
863                                             ContiguousBlobAccumulator &CBA,
864                                             ELFYAML::Section *YAMLSec) {
865   zero(SHeader);
866   SHeader.sh_name = getSectionNameOffset(ELFYAML::dropUniqueSuffix(Name));
867   SHeader.sh_type = YAMLSec ? YAMLSec->Type : ELF::SHT_PROGBITS;
868   SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 1;
869   SHeader.sh_offset = alignToOffset(CBA, SHeader.sh_addralign,
870                                     YAMLSec ? YAMLSec->Offset : None);
871 
872   ELFYAML::RawContentSection *RawSec =
873       dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec);
874   if (Doc.DWARF && shouldEmitDWARF(*Doc.DWARF, Name)) {
875     if (RawSec && (RawSec->Content || RawSec->Size))
876       reportError("cannot specify section '" + Name +
877                   "' contents in the 'DWARF' entry and the 'Content' "
878                   "or 'Size' in the 'Sections' entry at the same time");
879     else
880       SHeader.sh_size = emitDWARF<ELFT>(SHeader, Name, *Doc.DWARF, CBA.getOS());
881   } else if (RawSec)
882     SHeader.sh_size = writeContent(CBA.getOS(), RawSec->Content, RawSec->Size);
883   else
884     llvm_unreachable("debug sections can only be initialized via the 'DWARF' "
885                      "entry or a RawContentSection");
886 
887   if (YAMLSec && YAMLSec->EntSize)
888     SHeader.sh_entsize = *YAMLSec->EntSize;
889   else if (Name == ".debug_str")
890     SHeader.sh_entsize = 1;
891 
892   if (RawSec && RawSec->Info)
893     SHeader.sh_info = *RawSec->Info;
894 
895   if (YAMLSec && YAMLSec->Flags)
896     SHeader.sh_flags = *YAMLSec->Flags;
897   else if (Name == ".debug_str")
898     SHeader.sh_flags = ELF::SHF_MERGE | ELF::SHF_STRINGS;
899 
900   if (YAMLSec && !YAMLSec->Link.empty())
901     SHeader.sh_link = toSectionIndex(YAMLSec->Link, Name);
902 
903   assignSectionAddress(SHeader, YAMLSec);
904 }
905 
906 template <class ELFT> void ELFState<ELFT>::reportError(const Twine &Msg) {
907   ErrHandler(Msg);
908   HasError = true;
909 }
910 
911 template <class ELFT>
912 std::vector<Fragment>
913 ELFState<ELFT>::getPhdrFragments(const ELFYAML::ProgramHeader &Phdr,
914                                  ArrayRef<Elf_Shdr> SHeaders) {
915   std::vector<Fragment> Ret;
916   for (const ELFYAML::Chunk *C : Phdr.Chunks) {
917     if (const ELFYAML::Fill *F = dyn_cast<ELFYAML::Fill>(C)) {
918       Ret.push_back({*F->Offset, F->Size, llvm::ELF::SHT_PROGBITS,
919                      /*ShAddrAlign=*/1});
920       continue;
921     }
922 
923     const ELFYAML::Section *S = cast<ELFYAML::Section>(C);
924     const Elf_Shdr &H = SHeaders[SN2I.get(S->Name)];
925     Ret.push_back({H.sh_offset, H.sh_size, H.sh_type, H.sh_addralign});
926   }
927   return Ret;
928 }
929 
930 template <class ELFT>
931 void ELFState<ELFT>::setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
932                                             std::vector<Elf_Shdr> &SHeaders) {
933   uint32_t PhdrIdx = 0;
934   for (auto &YamlPhdr : Doc.ProgramHeaders) {
935     Elf_Phdr &PHeader = PHeaders[PhdrIdx++];
936     std::vector<Fragment> Fragments = getPhdrFragments(YamlPhdr, SHeaders);
937     if (!llvm::is_sorted(Fragments, [](const Fragment &A, const Fragment &B) {
938           return A.Offset < B.Offset;
939         }))
940       reportError("sections in the program header with index " +
941                   Twine(PhdrIdx) + " are not sorted by their file offset");
942 
943     if (YamlPhdr.Offset) {
944       if (!Fragments.empty() && *YamlPhdr.Offset > Fragments.front().Offset)
945         reportError("'Offset' for segment with index " + Twine(PhdrIdx) +
946                     " must be less than or equal to the minimum file offset of "
947                     "all included sections (0x" +
948                     Twine::utohexstr(Fragments.front().Offset) + ")");
949       PHeader.p_offset = *YamlPhdr.Offset;
950     } else if (!Fragments.empty()) {
951       PHeader.p_offset = Fragments.front().Offset;
952     }
953 
954     // Set the file size if not set explicitly.
955     if (YamlPhdr.FileSize) {
956       PHeader.p_filesz = *YamlPhdr.FileSize;
957     } else if (!Fragments.empty()) {
958       uint64_t FileSize = Fragments.back().Offset - PHeader.p_offset;
959       // SHT_NOBITS sections occupy no physical space in a file, we should not
960       // take their sizes into account when calculating the file size of a
961       // segment.
962       if (Fragments.back().Type != llvm::ELF::SHT_NOBITS)
963         FileSize += Fragments.back().Size;
964       PHeader.p_filesz = FileSize;
965     }
966 
967     // Find the maximum offset of the end of a section in order to set p_memsz.
968     uint64_t MemOffset = PHeader.p_offset;
969     for (const Fragment &F : Fragments)
970       MemOffset = std::max(MemOffset, F.Offset + F.Size);
971     // Set the memory size if not set explicitly.
972     PHeader.p_memsz = YamlPhdr.MemSize ? uint64_t(*YamlPhdr.MemSize)
973                                        : MemOffset - PHeader.p_offset;
974 
975     if (YamlPhdr.Align) {
976       PHeader.p_align = *YamlPhdr.Align;
977     } else {
978       // Set the alignment of the segment to be the maximum alignment of the
979       // sections so that by default the segment has a valid and sensible
980       // alignment.
981       PHeader.p_align = 1;
982       for (const Fragment &F : Fragments)
983         PHeader.p_align = std::max((uint64_t)PHeader.p_align, F.AddrAlign);
984     }
985   }
986 }
987 
988 template <class ELFT>
989 void ELFState<ELFT>::writeSectionContent(
990     Elf_Shdr &SHeader, const ELFYAML::RawContentSection &Section,
991     ContiguousBlobAccumulator &CBA) {
992   SHeader.sh_size = writeContent(CBA.getOS(), Section.Content, Section.Size);
993 
994   if (Section.EntSize)
995     SHeader.sh_entsize = *Section.EntSize;
996 
997   if (Section.Info)
998     SHeader.sh_info = *Section.Info;
999 }
1000 
1001 static bool isMips64EL(const ELFYAML::Object &Doc) {
1002   return Doc.Header.Machine == ELFYAML::ELF_EM(llvm::ELF::EM_MIPS) &&
1003          Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64) &&
1004          Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
1005 }
1006 
1007 template <class ELFT>
1008 void ELFState<ELFT>::writeSectionContent(
1009     Elf_Shdr &SHeader, const ELFYAML::RelocationSection &Section,
1010     ContiguousBlobAccumulator &CBA) {
1011   assert((Section.Type == llvm::ELF::SHT_REL ||
1012           Section.Type == llvm::ELF::SHT_RELA) &&
1013          "Section type is not SHT_REL nor SHT_RELA");
1014 
1015   bool IsRela = Section.Type == llvm::ELF::SHT_RELA;
1016   if (Section.EntSize)
1017     SHeader.sh_entsize = *Section.EntSize;
1018   else
1019     SHeader.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1020   SHeader.sh_size = (IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel)) *
1021                     Section.Relocations.size();
1022 
1023   // For relocation section set link to .symtab by default.
1024   unsigned Link = 0;
1025   if (Section.Link.empty() && !ExcludedSectionHeaders.count(".symtab") &&
1026       SN2I.lookup(".symtab", Link))
1027     SHeader.sh_link = Link;
1028 
1029   if (!Section.RelocatableSec.empty())
1030     SHeader.sh_info = toSectionIndex(Section.RelocatableSec, Section.Name);
1031 
1032   raw_ostream &OS = CBA.getOS();
1033   for (const auto &Rel : Section.Relocations) {
1034     unsigned SymIdx = Rel.Symbol ? toSymbolIndex(*Rel.Symbol, Section.Name,
1035                                                  Section.Link == ".dynsym")
1036                                  : 0;
1037     if (IsRela) {
1038       Elf_Rela REntry;
1039       zero(REntry);
1040       REntry.r_offset = Rel.Offset;
1041       REntry.r_addend = Rel.Addend;
1042       REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
1043       OS.write((const char *)&REntry, sizeof(REntry));
1044     } else {
1045       Elf_Rel REntry;
1046       zero(REntry);
1047       REntry.r_offset = Rel.Offset;
1048       REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
1049       OS.write((const char *)&REntry, sizeof(REntry));
1050     }
1051   }
1052 }
1053 
1054 template <class ELFT>
1055 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1056                                          const ELFYAML::RelrSection &Section,
1057                                          ContiguousBlobAccumulator &CBA) {
1058   SHeader.sh_entsize =
1059       Section.EntSize ? uint64_t(*Section.EntSize) : sizeof(Elf_Relr);
1060 
1061   raw_ostream &OS = CBA.getOS();
1062   if (Section.Content) {
1063     SHeader.sh_size = writeContent(OS, Section.Content, None);
1064     return;
1065   }
1066 
1067   if (!Section.Entries)
1068     return;
1069 
1070   for (llvm::yaml::Hex64 E : *Section.Entries) {
1071     if (!ELFT::Is64Bits && E > UINT32_MAX)
1072       reportError(Section.Name + ": the value is too large for 32-bits: 0x" +
1073                   Twine::utohexstr(E));
1074     support::endian::write<uintX_t>(OS, E, ELFT::TargetEndianness);
1075   }
1076 
1077   SHeader.sh_size = sizeof(uintX_t) * Section.Entries->size();
1078 }
1079 
1080 template <class ELFT>
1081 void ELFState<ELFT>::writeSectionContent(
1082     Elf_Shdr &SHeader, const ELFYAML::SymtabShndxSection &Shndx,
1083     ContiguousBlobAccumulator &CBA) {
1084   for (uint32_t E : Shndx.Entries)
1085     support::endian::write<uint32_t>(CBA.getOS(), E, ELFT::TargetEndianness);
1086 
1087   SHeader.sh_entsize = Shndx.EntSize ? (uint64_t)*Shndx.EntSize : 4;
1088   SHeader.sh_size = Shndx.Entries.size() * SHeader.sh_entsize;
1089 }
1090 
1091 template <class ELFT>
1092 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1093                                          const ELFYAML::Group &Section,
1094                                          ContiguousBlobAccumulator &CBA) {
1095   assert(Section.Type == llvm::ELF::SHT_GROUP &&
1096          "Section type is not SHT_GROUP");
1097 
1098   unsigned Link = 0;
1099   if (Section.Link.empty() && !ExcludedSectionHeaders.count(".symtab") &&
1100       SN2I.lookup(".symtab", Link))
1101     SHeader.sh_link = Link;
1102 
1103   SHeader.sh_entsize = 4;
1104   SHeader.sh_size = SHeader.sh_entsize * Section.Members.size();
1105 
1106   if (Section.Signature)
1107     SHeader.sh_info =
1108         toSymbolIndex(*Section.Signature, Section.Name, /*IsDynamic=*/false);
1109 
1110   raw_ostream &OS = CBA.getOS();
1111   for (const ELFYAML::SectionOrType &Member : Section.Members) {
1112     unsigned int SectionIndex = 0;
1113     if (Member.sectionNameOrType == "GRP_COMDAT")
1114       SectionIndex = llvm::ELF::GRP_COMDAT;
1115     else
1116       SectionIndex = toSectionIndex(Member.sectionNameOrType, Section.Name);
1117     support::endian::write<uint32_t>(OS, SectionIndex, ELFT::TargetEndianness);
1118   }
1119 }
1120 
1121 template <class ELFT>
1122 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1123                                          const ELFYAML::SymverSection &Section,
1124                                          ContiguousBlobAccumulator &CBA) {
1125   raw_ostream &OS = CBA.getOS();
1126   for (uint16_t Version : Section.Entries)
1127     support::endian::write<uint16_t>(OS, Version, ELFT::TargetEndianness);
1128 
1129   SHeader.sh_entsize = Section.EntSize ? (uint64_t)*Section.EntSize : 2;
1130   SHeader.sh_size = Section.Entries.size() * SHeader.sh_entsize;
1131 }
1132 
1133 template <class ELFT>
1134 void ELFState<ELFT>::writeSectionContent(
1135     Elf_Shdr &SHeader, const ELFYAML::StackSizesSection &Section,
1136     ContiguousBlobAccumulator &CBA) {
1137   raw_ostream &OS = CBA.getOS();
1138   if (Section.Content || Section.Size) {
1139     SHeader.sh_size = writeContent(OS, Section.Content, Section.Size);
1140     return;
1141   }
1142 
1143   for (const ELFYAML::StackSizeEntry &E : *Section.Entries) {
1144     support::endian::write<uintX_t>(OS, E.Address, ELFT::TargetEndianness);
1145     SHeader.sh_size += sizeof(uintX_t) + encodeULEB128(E.Size, OS);
1146   }
1147 }
1148 
1149 template <class ELFT>
1150 void ELFState<ELFT>::writeSectionContent(
1151     Elf_Shdr &SHeader, const ELFYAML::LinkerOptionsSection &Section,
1152     ContiguousBlobAccumulator &CBA) {
1153   raw_ostream &OS = CBA.getOS();
1154   if (Section.Content) {
1155     SHeader.sh_size = writeContent(OS, Section.Content, None);
1156     return;
1157   }
1158 
1159   if (!Section.Options)
1160     return;
1161 
1162   for (const ELFYAML::LinkerOption &LO : *Section.Options) {
1163     OS.write(LO.Key.data(), LO.Key.size());
1164     OS.write('\0');
1165     OS.write(LO.Value.data(), LO.Value.size());
1166     OS.write('\0');
1167     SHeader.sh_size += (LO.Key.size() + LO.Value.size() + 2);
1168   }
1169 }
1170 
1171 template <class ELFT>
1172 void ELFState<ELFT>::writeSectionContent(
1173     Elf_Shdr &SHeader, const ELFYAML::DependentLibrariesSection &Section,
1174     ContiguousBlobAccumulator &CBA) {
1175   raw_ostream &OS = CBA.getOS();
1176   if (Section.Content) {
1177     SHeader.sh_size = writeContent(OS, Section.Content, None);
1178     return;
1179   }
1180 
1181   if (!Section.Libs)
1182     return;
1183 
1184   for (StringRef Lib : *Section.Libs) {
1185     OS.write(Lib.data(), Lib.size());
1186     OS.write('\0');
1187     SHeader.sh_size += Lib.size() + 1;
1188   }
1189 }
1190 
1191 template <class ELFT>
1192 uint64_t
1193 ELFState<ELFT>::alignToOffset(ContiguousBlobAccumulator &CBA, uint64_t Align,
1194                               llvm::Optional<llvm::yaml::Hex64> Offset) {
1195   uint64_t CurrentOffset = CBA.getOffset();
1196   uint64_t AlignedOffset;
1197 
1198   if (Offset) {
1199     if ((uint64_t)*Offset < CurrentOffset) {
1200       reportError("the 'Offset' value (0x" +
1201                   Twine::utohexstr((uint64_t)*Offset) + ") goes backward");
1202       return CurrentOffset;
1203     }
1204 
1205     // We ignore an alignment when an explicit offset has been requested.
1206     AlignedOffset = *Offset;
1207   } else {
1208     AlignedOffset = alignTo(CurrentOffset, std::max(Align, (uint64_t)1));
1209   }
1210 
1211   CBA.getOS().write_zeros(AlignedOffset - CurrentOffset);
1212   return AlignedOffset;
1213 }
1214 
1215 template <class ELFT>
1216 void ELFState<ELFT>::writeSectionContent(
1217     Elf_Shdr &SHeader, const ELFYAML::CallGraphProfileSection &Section,
1218     ContiguousBlobAccumulator &CBA) {
1219   if (Section.EntSize)
1220     SHeader.sh_entsize = *Section.EntSize;
1221   else
1222     SHeader.sh_entsize = 16;
1223 
1224   unsigned Link = 0;
1225   if (Section.Link.empty() && !ExcludedSectionHeaders.count(".symtab") &&
1226       SN2I.lookup(".symtab", Link))
1227     SHeader.sh_link = Link;
1228 
1229   raw_ostream &OS = CBA.getOS();
1230   if (Section.Content) {
1231     SHeader.sh_size = writeContent(OS, Section.Content, None);
1232     return;
1233   }
1234 
1235   if (!Section.Entries)
1236     return;
1237 
1238   for (const ELFYAML::CallGraphEntry &E : *Section.Entries) {
1239     unsigned From = toSymbolIndex(E.From, Section.Name, /*IsDynamic=*/false);
1240     unsigned To = toSymbolIndex(E.To, Section.Name, /*IsDynamic=*/false);
1241 
1242     support::endian::write<uint32_t>(OS, From, ELFT::TargetEndianness);
1243     support::endian::write<uint32_t>(OS, To, ELFT::TargetEndianness);
1244     support::endian::write<uint64_t>(OS, E.Weight, ELFT::TargetEndianness);
1245     SHeader.sh_size += 16;
1246   }
1247 }
1248 
1249 template <class ELFT>
1250 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1251                                          const ELFYAML::HashSection &Section,
1252                                          ContiguousBlobAccumulator &CBA) {
1253   unsigned Link = 0;
1254   if (Section.Link.empty() && !ExcludedSectionHeaders.count(".dynsym") &&
1255       SN2I.lookup(".dynsym", Link))
1256     SHeader.sh_link = Link;
1257 
1258   raw_ostream &OS = CBA.getOS();
1259   if (Section.Content || Section.Size) {
1260     SHeader.sh_size = writeContent(OS, Section.Content, Section.Size);
1261     return;
1262   }
1263 
1264   support::endian::write<uint32_t>(
1265       OS, Section.NBucket.getValueOr(llvm::yaml::Hex64(Section.Bucket->size())),
1266       ELFT::TargetEndianness);
1267   support::endian::write<uint32_t>(
1268       OS, Section.NChain.getValueOr(llvm::yaml::Hex64(Section.Chain->size())),
1269       ELFT::TargetEndianness);
1270 
1271   for (uint32_t Val : *Section.Bucket)
1272     support::endian::write<uint32_t>(OS, Val, ELFT::TargetEndianness);
1273   for (uint32_t Val : *Section.Chain)
1274     support::endian::write<uint32_t>(OS, Val, ELFT::TargetEndianness);
1275 
1276   SHeader.sh_size = (2 + Section.Bucket->size() + Section.Chain->size()) * 4;
1277 }
1278 
1279 template <class ELFT>
1280 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1281                                          const ELFYAML::VerdefSection &Section,
1282                                          ContiguousBlobAccumulator &CBA) {
1283   typedef typename ELFT::Verdef Elf_Verdef;
1284   typedef typename ELFT::Verdaux Elf_Verdaux;
1285 
1286   SHeader.sh_info = Section.Info;
1287 
1288   raw_ostream &OS = CBA.getOS();
1289   if (Section.Content) {
1290     SHeader.sh_size = writeContent(OS, Section.Content, None);
1291     return;
1292   }
1293 
1294   if (!Section.Entries)
1295     return;
1296 
1297   uint64_t AuxCnt = 0;
1298   for (size_t I = 0; I < Section.Entries->size(); ++I) {
1299     const ELFYAML::VerdefEntry &E = (*Section.Entries)[I];
1300 
1301     Elf_Verdef VerDef;
1302     VerDef.vd_version = E.Version;
1303     VerDef.vd_flags = E.Flags;
1304     VerDef.vd_ndx = E.VersionNdx;
1305     VerDef.vd_hash = E.Hash;
1306     VerDef.vd_aux = sizeof(Elf_Verdef);
1307     VerDef.vd_cnt = E.VerNames.size();
1308     if (I == Section.Entries->size() - 1)
1309       VerDef.vd_next = 0;
1310     else
1311       VerDef.vd_next =
1312           sizeof(Elf_Verdef) + E.VerNames.size() * sizeof(Elf_Verdaux);
1313     OS.write((const char *)&VerDef, sizeof(Elf_Verdef));
1314 
1315     for (size_t J = 0; J < E.VerNames.size(); ++J, ++AuxCnt) {
1316       Elf_Verdaux VernAux;
1317       VernAux.vda_name = DotDynstr.getOffset(E.VerNames[J]);
1318       if (J == E.VerNames.size() - 1)
1319         VernAux.vda_next = 0;
1320       else
1321         VernAux.vda_next = sizeof(Elf_Verdaux);
1322       OS.write((const char *)&VernAux, sizeof(Elf_Verdaux));
1323     }
1324   }
1325 
1326   SHeader.sh_size = Section.Entries->size() * sizeof(Elf_Verdef) +
1327                     AuxCnt * sizeof(Elf_Verdaux);
1328 }
1329 
1330 template <class ELFT>
1331 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1332                                          const ELFYAML::VerneedSection &Section,
1333                                          ContiguousBlobAccumulator &CBA) {
1334   typedef typename ELFT::Verneed Elf_Verneed;
1335   typedef typename ELFT::Vernaux Elf_Vernaux;
1336 
1337   SHeader.sh_info = Section.Info;
1338 
1339   raw_ostream &OS = CBA.getOS();
1340   if (Section.Content) {
1341     SHeader.sh_size = writeContent(OS, Section.Content, None);
1342     return;
1343   }
1344 
1345   if (!Section.VerneedV)
1346     return;
1347 
1348   uint64_t AuxCnt = 0;
1349   for (size_t I = 0; I < Section.VerneedV->size(); ++I) {
1350     const ELFYAML::VerneedEntry &VE = (*Section.VerneedV)[I];
1351 
1352     Elf_Verneed VerNeed;
1353     VerNeed.vn_version = VE.Version;
1354     VerNeed.vn_file = DotDynstr.getOffset(VE.File);
1355     if (I == Section.VerneedV->size() - 1)
1356       VerNeed.vn_next = 0;
1357     else
1358       VerNeed.vn_next =
1359           sizeof(Elf_Verneed) + VE.AuxV.size() * sizeof(Elf_Vernaux);
1360     VerNeed.vn_cnt = VE.AuxV.size();
1361     VerNeed.vn_aux = sizeof(Elf_Verneed);
1362     OS.write((const char *)&VerNeed, sizeof(Elf_Verneed));
1363 
1364     for (size_t J = 0; J < VE.AuxV.size(); ++J, ++AuxCnt) {
1365       const ELFYAML::VernauxEntry &VAuxE = VE.AuxV[J];
1366 
1367       Elf_Vernaux VernAux;
1368       VernAux.vna_hash = VAuxE.Hash;
1369       VernAux.vna_flags = VAuxE.Flags;
1370       VernAux.vna_other = VAuxE.Other;
1371       VernAux.vna_name = DotDynstr.getOffset(VAuxE.Name);
1372       if (J == VE.AuxV.size() - 1)
1373         VernAux.vna_next = 0;
1374       else
1375         VernAux.vna_next = sizeof(Elf_Vernaux);
1376       OS.write((const char *)&VernAux, sizeof(Elf_Vernaux));
1377     }
1378   }
1379 
1380   SHeader.sh_size = Section.VerneedV->size() * sizeof(Elf_Verneed) +
1381                     AuxCnt * sizeof(Elf_Vernaux);
1382 }
1383 
1384 template <class ELFT>
1385 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1386                                          const ELFYAML::MipsABIFlags &Section,
1387                                          ContiguousBlobAccumulator &CBA) {
1388   assert(Section.Type == llvm::ELF::SHT_MIPS_ABIFLAGS &&
1389          "Section type is not SHT_MIPS_ABIFLAGS");
1390 
1391   object::Elf_Mips_ABIFlags<ELFT> Flags;
1392   zero(Flags);
1393   SHeader.sh_entsize = sizeof(Flags);
1394   SHeader.sh_size = SHeader.sh_entsize;
1395 
1396   Flags.version = Section.Version;
1397   Flags.isa_level = Section.ISALevel;
1398   Flags.isa_rev = Section.ISARevision;
1399   Flags.gpr_size = Section.GPRSize;
1400   Flags.cpr1_size = Section.CPR1Size;
1401   Flags.cpr2_size = Section.CPR2Size;
1402   Flags.fp_abi = Section.FpABI;
1403   Flags.isa_ext = Section.ISAExtension;
1404   Flags.ases = Section.ASEs;
1405   Flags.flags1 = Section.Flags1;
1406   Flags.flags2 = Section.Flags2;
1407   CBA.getOS().write((const char *)&Flags, sizeof(Flags));
1408 }
1409 
1410 template <class ELFT>
1411 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1412                                          const ELFYAML::DynamicSection &Section,
1413                                          ContiguousBlobAccumulator &CBA) {
1414   assert(Section.Type == llvm::ELF::SHT_DYNAMIC &&
1415          "Section type is not SHT_DYNAMIC");
1416 
1417   if (!Section.Entries.empty() && Section.Content)
1418     reportError("cannot specify both raw content and explicit entries "
1419                 "for dynamic section '" +
1420                 Section.Name + "'");
1421 
1422   if (Section.Content)
1423     SHeader.sh_size = Section.Content->binary_size();
1424   else
1425     SHeader.sh_size = 2 * sizeof(uintX_t) * Section.Entries.size();
1426   if (Section.EntSize)
1427     SHeader.sh_entsize = *Section.EntSize;
1428   else
1429     SHeader.sh_entsize = sizeof(Elf_Dyn);
1430 
1431   raw_ostream &OS = CBA.getOS();
1432   for (const ELFYAML::DynamicEntry &DE : Section.Entries) {
1433     support::endian::write<uintX_t>(OS, DE.Tag, ELFT::TargetEndianness);
1434     support::endian::write<uintX_t>(OS, DE.Val, ELFT::TargetEndianness);
1435   }
1436   if (Section.Content)
1437     Section.Content->writeAsBinary(OS);
1438 }
1439 
1440 template <class ELFT>
1441 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1442                                          const ELFYAML::AddrsigSection &Section,
1443                                          ContiguousBlobAccumulator &CBA) {
1444   unsigned Link = 0;
1445   if (Section.Link.empty() && !ExcludedSectionHeaders.count(".symtab") &&
1446       SN2I.lookup(".symtab", Link))
1447     SHeader.sh_link = Link;
1448 
1449   raw_ostream &OS = CBA.getOS();
1450   if (Section.Content || Section.Size) {
1451     SHeader.sh_size = writeContent(OS, Section.Content, Section.Size);
1452     return;
1453   }
1454 
1455   for (StringRef Sym : *Section.Symbols)
1456     SHeader.sh_size += encodeULEB128(
1457         toSymbolIndex(Sym, Section.Name, /*IsDynamic=*/false), OS);
1458 }
1459 
1460 template <class ELFT>
1461 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1462                                          const ELFYAML::NoteSection &Section,
1463                                          ContiguousBlobAccumulator &CBA) {
1464   raw_ostream &OS = CBA.getOS();
1465   uint64_t Offset = OS.tell();
1466   if (Section.Content || Section.Size) {
1467     SHeader.sh_size = writeContent(OS, Section.Content, Section.Size);
1468     return;
1469   }
1470 
1471   for (const ELFYAML::NoteEntry &NE : *Section.Notes) {
1472     // Write name size.
1473     if (NE.Name.empty())
1474       support::endian::write<uint32_t>(OS, 0, ELFT::TargetEndianness);
1475     else
1476       support::endian::write<uint32_t>(OS, NE.Name.size() + 1,
1477                                        ELFT::TargetEndianness);
1478 
1479     // Write description size.
1480     if (NE.Desc.binary_size() == 0)
1481       support::endian::write<uint32_t>(OS, 0, ELFT::TargetEndianness);
1482     else
1483       support::endian::write<uint32_t>(OS, NE.Desc.binary_size(),
1484                                        ELFT::TargetEndianness);
1485 
1486     // Write type.
1487     support::endian::write<uint32_t>(OS, NE.Type, ELFT::TargetEndianness);
1488 
1489     // Write name, null terminator and padding.
1490     if (!NE.Name.empty()) {
1491       support::endian::write<uint8_t>(OS, arrayRefFromStringRef(NE.Name),
1492                                       ELFT::TargetEndianness);
1493       support::endian::write<uint8_t>(OS, 0, ELFT::TargetEndianness);
1494       CBA.padToAlignment(4);
1495     }
1496 
1497     // Write description and padding.
1498     if (NE.Desc.binary_size() != 0) {
1499       NE.Desc.writeAsBinary(OS);
1500       CBA.padToAlignment(4);
1501     }
1502   }
1503 
1504   SHeader.sh_size = OS.tell() - Offset;
1505 }
1506 
1507 template <class ELFT>
1508 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1509                                          const ELFYAML::GnuHashSection &Section,
1510                                          ContiguousBlobAccumulator &CBA) {
1511   unsigned Link = 0;
1512   if (Section.Link.empty() && !ExcludedSectionHeaders.count(".dynsym") &&
1513       SN2I.lookup(".dynsym", Link))
1514     SHeader.sh_link = Link;
1515 
1516   raw_ostream &OS = CBA.getOS();
1517   if (Section.Content) {
1518     SHeader.sh_size = writeContent(OS, Section.Content, None);
1519     return;
1520   }
1521 
1522   // We write the header first, starting with the hash buckets count. Normally
1523   // it is the number of entries in HashBuckets, but the "NBuckets" property can
1524   // be used to override this field, which is useful for producing broken
1525   // objects.
1526   if (Section.Header->NBuckets)
1527     support::endian::write<uint32_t>(OS, *Section.Header->NBuckets,
1528                                      ELFT::TargetEndianness);
1529   else
1530     support::endian::write<uint32_t>(OS, Section.HashBuckets->size(),
1531                                      ELFT::TargetEndianness);
1532 
1533   // Write the index of the first symbol in the dynamic symbol table accessible
1534   // via the hash table.
1535   support::endian::write<uint32_t>(OS, Section.Header->SymNdx,
1536                                    ELFT::TargetEndianness);
1537 
1538   // Write the number of words in the Bloom filter. As above, the "MaskWords"
1539   // property can be used to set this field to any value.
1540   if (Section.Header->MaskWords)
1541     support::endian::write<uint32_t>(OS, *Section.Header->MaskWords,
1542                                      ELFT::TargetEndianness);
1543   else
1544     support::endian::write<uint32_t>(OS, Section.BloomFilter->size(),
1545                                      ELFT::TargetEndianness);
1546 
1547   // Write the shift constant used by the Bloom filter.
1548   support::endian::write<uint32_t>(OS, Section.Header->Shift2,
1549                                    ELFT::TargetEndianness);
1550 
1551   // We've finished writing the header. Now write the Bloom filter.
1552   for (llvm::yaml::Hex64 Val : *Section.BloomFilter)
1553     support::endian::write<typename ELFT::uint>(OS, Val,
1554                                                 ELFT::TargetEndianness);
1555 
1556   // Write an array of hash buckets.
1557   for (llvm::yaml::Hex32 Val : *Section.HashBuckets)
1558     support::endian::write<uint32_t>(OS, Val, ELFT::TargetEndianness);
1559 
1560   // Write an array of hash values.
1561   for (llvm::yaml::Hex32 Val : *Section.HashValues)
1562     support::endian::write<uint32_t>(OS, Val, ELFT::TargetEndianness);
1563 
1564   SHeader.sh_size = 16 /*Header size*/ +
1565                     Section.BloomFilter->size() * sizeof(typename ELFT::uint) +
1566                     Section.HashBuckets->size() * 4 +
1567                     Section.HashValues->size() * 4;
1568 }
1569 
1570 template <class ELFT>
1571 void ELFState<ELFT>::writeFill(ELFYAML::Fill &Fill,
1572                                ContiguousBlobAccumulator &CBA) {
1573   raw_ostream &OS = CBA.getOS();
1574   size_t PatternSize = Fill.Pattern ? Fill.Pattern->binary_size() : 0;
1575   if (!PatternSize) {
1576     OS.write_zeros(Fill.Size);
1577     return;
1578   }
1579 
1580   // Fill the content with the specified pattern.
1581   uint64_t Written = 0;
1582   for (; Written + PatternSize <= Fill.Size; Written += PatternSize)
1583     Fill.Pattern->writeAsBinary(OS);
1584   Fill.Pattern->writeAsBinary(OS, Fill.Size - Written);
1585 }
1586 
1587 template <class ELFT>
1588 DenseMap<StringRef, size_t> ELFState<ELFT>::buildSectionHeaderReorderMap() {
1589   if (!Doc.SectionHeaders || Doc.SectionHeaders->Sections.empty())
1590     return DenseMap<StringRef, size_t>();
1591 
1592   DenseMap<StringRef, size_t> Ret;
1593   size_t SecNdx = 0;
1594   StringSet<> Seen;
1595 
1596   auto AddSection = [&](const ELFYAML::SectionHeader &Hdr) {
1597     if (!Ret.try_emplace(Hdr.Name, ++SecNdx).second)
1598       reportError("repeated section name: '" + Hdr.Name +
1599                   "' in the section header description");
1600     Seen.insert(Hdr.Name);
1601   };
1602 
1603   for (const ELFYAML::SectionHeader &Hdr : Doc.SectionHeaders->Sections)
1604     AddSection(Hdr);
1605 
1606   if (Doc.SectionHeaders->Excluded)
1607     for (const ELFYAML::SectionHeader &Hdr : *Doc.SectionHeaders->Excluded)
1608       AddSection(Hdr);
1609 
1610   for (const ELFYAML::Section *S : Doc.getSections()) {
1611     // Ignore special first SHT_NULL section.
1612     if (S == Doc.getSections().front())
1613       continue;
1614     if (!Seen.count(S->Name))
1615       reportError("section '" + S->Name +
1616                   "' should be present in the 'Sections' or 'Excluded' lists");
1617     Seen.erase(S->Name);
1618   }
1619 
1620   for (const auto &It : Seen)
1621     reportError("section header contains undefined section '" + It.getKey() +
1622                 "'");
1623   return Ret;
1624 }
1625 
1626 template <class ELFT> void ELFState<ELFT>::buildSectionIndex() {
1627   // A YAML description can have an explicit section header declaration that
1628   // allows to change the order of section headers.
1629   DenseMap<StringRef, size_t> ReorderMap = buildSectionHeaderReorderMap();
1630 
1631   if (HasError)
1632     return;
1633 
1634   // Build excluded section headers map.
1635   if (Doc.SectionHeaders && Doc.SectionHeaders->Excluded)
1636     for (const ELFYAML::SectionHeader &Hdr : *Doc.SectionHeaders->Excluded)
1637       if (!ExcludedSectionHeaders.insert(Hdr.Name).second)
1638         llvm_unreachable("buildSectionIndex() failed");
1639 
1640   size_t SecNdx = -1;
1641   for (const ELFYAML::Section *S : Doc.getSections()) {
1642     ++SecNdx;
1643 
1644     size_t Index = ReorderMap.empty() ? SecNdx : ReorderMap.lookup(S->Name);
1645     if (!SN2I.addName(S->Name, Index))
1646       llvm_unreachable("buildSectionIndex() failed");
1647 
1648     if (!ExcludedSectionHeaders.count(S->Name))
1649       DotShStrtab.add(ELFYAML::dropUniqueSuffix(S->Name));
1650   }
1651 
1652   DotShStrtab.finalize();
1653 }
1654 
1655 template <class ELFT> void ELFState<ELFT>::buildSymbolIndexes() {
1656   auto Build = [this](ArrayRef<ELFYAML::Symbol> V, NameToIdxMap &Map) {
1657     for (size_t I = 0, S = V.size(); I < S; ++I) {
1658       const ELFYAML::Symbol &Sym = V[I];
1659       if (!Sym.Name.empty() && !Map.addName(Sym.Name, I + 1))
1660         reportError("repeated symbol name: '" + Sym.Name + "'");
1661     }
1662   };
1663 
1664   if (Doc.Symbols)
1665     Build(*Doc.Symbols, SymN2I);
1666   if (Doc.DynamicSymbols)
1667     Build(*Doc.DynamicSymbols, DynSymN2I);
1668 }
1669 
1670 template <class ELFT> void ELFState<ELFT>::finalizeStrings() {
1671   // Add the regular symbol names to .strtab section.
1672   if (Doc.Symbols)
1673     for (const ELFYAML::Symbol &Sym : *Doc.Symbols)
1674       DotStrtab.add(ELFYAML::dropUniqueSuffix(Sym.Name));
1675   DotStrtab.finalize();
1676 
1677   // Add the dynamic symbol names to .dynstr section.
1678   if (Doc.DynamicSymbols)
1679     for (const ELFYAML::Symbol &Sym : *Doc.DynamicSymbols)
1680       DotDynstr.add(ELFYAML::dropUniqueSuffix(Sym.Name));
1681 
1682   // SHT_GNU_verdef and SHT_GNU_verneed sections might also
1683   // add strings to .dynstr section.
1684   for (const ELFYAML::Chunk *Sec : Doc.getSections()) {
1685     if (auto VerNeed = dyn_cast<ELFYAML::VerneedSection>(Sec)) {
1686       if (VerNeed->VerneedV) {
1687         for (const ELFYAML::VerneedEntry &VE : *VerNeed->VerneedV) {
1688           DotDynstr.add(VE.File);
1689           for (const ELFYAML::VernauxEntry &Aux : VE.AuxV)
1690             DotDynstr.add(Aux.Name);
1691         }
1692       }
1693     } else if (auto VerDef = dyn_cast<ELFYAML::VerdefSection>(Sec)) {
1694       if (VerDef->Entries)
1695         for (const ELFYAML::VerdefEntry &E : *VerDef->Entries)
1696           for (StringRef Name : E.VerNames)
1697             DotDynstr.add(Name);
1698     }
1699   }
1700 
1701   DotDynstr.finalize();
1702 }
1703 
1704 template <class ELFT>
1705 bool ELFState<ELFT>::writeELF(raw_ostream &OS, ELFYAML::Object &Doc,
1706                               yaml::ErrorHandler EH) {
1707   ELFState<ELFT> State(Doc, EH);
1708   if (State.HasError)
1709     return false;
1710 
1711   // Finalize .strtab and .dynstr sections. We do that early because want to
1712   // finalize the string table builders before writing the content of the
1713   // sections that might want to use them.
1714   State.finalizeStrings();
1715 
1716   State.buildSectionIndex();
1717   State.buildSymbolIndexes();
1718 
1719   if (State.HasError)
1720     return false;
1721 
1722   std::vector<Elf_Phdr> PHeaders;
1723   State.initProgramHeaders(PHeaders);
1724 
1725   // XXX: This offset is tightly coupled with the order that we write
1726   // things to `OS`.
1727   const size_t SectionContentBeginOffset =
1728       sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * Doc.ProgramHeaders.size();
1729   ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
1730 
1731   std::vector<Elf_Shdr> SHeaders;
1732   State.initSectionHeaders(SHeaders, CBA);
1733 
1734   // Now we can decide segment offsets.
1735   State.setProgramHeaderLayout(PHeaders, SHeaders);
1736 
1737   if (State.HasError)
1738     return false;
1739 
1740   State.writeELFHeader(CBA, OS);
1741   writeArrayData(OS, makeArrayRef(PHeaders));
1742   CBA.writeBlobToStream(OS);
1743   writeArrayData(OS, makeArrayRef(SHeaders));
1744   return true;
1745 }
1746 
1747 namespace llvm {
1748 namespace yaml {
1749 
1750 bool yaml2elf(llvm::ELFYAML::Object &Doc, raw_ostream &Out, ErrorHandler EH) {
1751   bool IsLE = Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
1752   bool Is64Bit = Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
1753   if (Is64Bit) {
1754     if (IsLE)
1755       return ELFState<object::ELF64LE>::writeELF(Out, Doc, EH);
1756     return ELFState<object::ELF64BE>::writeELF(Out, Doc, EH);
1757   }
1758   if (IsLE)
1759     return ELFState<object::ELF32LE>::writeELF(Out, Doc, EH);
1760   return ELFState<object::ELF32BE>::writeELF(Out, Doc, EH);
1761 }
1762 
1763 } // namespace yaml
1764 } // namespace llvm
1765