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