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