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