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