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