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