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