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