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