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