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