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