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