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