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