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