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