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