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