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