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   assignSectionAddress(SHeader, YAMLSec);
711 }
712 
713 template <class ELFT> void ELFState<ELFT>::reportError(const Twine &Msg) {
714   ErrHandler(Msg);
715   HasError = true;
716 }
717 
718 template <class ELFT>
719 std::vector<Fragment>
720 ELFState<ELFT>::getPhdrFragments(const ELFYAML::ProgramHeader &Phdr,
721                                  ArrayRef<typename ELFT::Shdr> SHeaders) {
722   DenseMap<StringRef, ELFYAML::Fill *> NameToFill;
723   for (const std::unique_ptr<ELFYAML::Chunk> &D : Doc.Chunks)
724     if (auto S = dyn_cast<ELFYAML::Fill>(D.get()))
725       NameToFill[S->Name] = S;
726 
727   std::vector<Fragment> Ret;
728   for (const ELFYAML::SectionName &SecName : Phdr.Sections) {
729     unsigned Index;
730     if (SN2I.lookup(SecName.Section, Index)) {
731       const typename ELFT::Shdr &H = SHeaders[Index];
732       Ret.push_back({H.sh_offset, H.sh_size, H.sh_type, H.sh_addralign});
733       continue;
734     }
735 
736     if (ELFYAML::Fill *Fill = NameToFill.lookup(SecName.Section)) {
737       Ret.push_back({Fill->ShOffset, Fill->Size, llvm::ELF::SHT_PROGBITS,
738                      /*ShAddrAlign=*/1});
739       continue;
740     }
741 
742     reportError("unknown section or fill referenced: '" + SecName.Section +
743                 "' by program header");
744   }
745 
746   return Ret;
747 }
748 
749 template <class ELFT>
750 void ELFState<ELFT>::setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
751                                             std::vector<Elf_Shdr> &SHeaders) {
752   uint32_t PhdrIdx = 0;
753   for (auto &YamlPhdr : Doc.ProgramHeaders) {
754     Elf_Phdr &PHeader = PHeaders[PhdrIdx++];
755     std::vector<Fragment> Fragments = getPhdrFragments(YamlPhdr, SHeaders);
756 
757     if (YamlPhdr.Offset) {
758       PHeader.p_offset = *YamlPhdr.Offset;
759     } else {
760       if (YamlPhdr.Sections.size())
761         PHeader.p_offset = UINT32_MAX;
762       else
763         PHeader.p_offset = 0;
764 
765       // Find the minimum offset for the program header.
766       for (const Fragment &F : Fragments)
767         PHeader.p_offset = std::min((uint64_t)PHeader.p_offset, F.Offset);
768     }
769 
770     // Find the maximum offset of the end of a section in order to set p_filesz
771     // and p_memsz. When setting p_filesz, trailing SHT_NOBITS sections are not
772     // counted.
773     uint64_t FileOffset = PHeader.p_offset, MemOffset = PHeader.p_offset;
774     for (const Fragment &F : Fragments) {
775       uint64_t End = F.Offset + F.Size;
776       MemOffset = std::max(MemOffset, End);
777 
778       if (F.Type != llvm::ELF::SHT_NOBITS)
779         FileOffset = std::max(FileOffset, End);
780     }
781 
782     // Set the file size and the memory size if not set explicitly.
783     PHeader.p_filesz = YamlPhdr.FileSize ? uint64_t(*YamlPhdr.FileSize)
784                                          : FileOffset - PHeader.p_offset;
785     PHeader.p_memsz = YamlPhdr.MemSize ? uint64_t(*YamlPhdr.MemSize)
786                                        : MemOffset - PHeader.p_offset;
787 
788     if (YamlPhdr.Align) {
789       PHeader.p_align = *YamlPhdr.Align;
790     } else {
791       // Set the alignment of the segment to be the maximum alignment of the
792       // sections so that by default the segment has a valid and sensible
793       // alignment.
794       PHeader.p_align = 1;
795       for (const Fragment &F : Fragments)
796         PHeader.p_align = std::max((uint64_t)PHeader.p_align, F.AddrAlign);
797     }
798   }
799 }
800 
801 template <class ELFT>
802 void ELFState<ELFT>::writeSectionContent(
803     Elf_Shdr &SHeader, const ELFYAML::RawContentSection &Section,
804     ContiguousBlobAccumulator &CBA) {
805   raw_ostream &OS =
806       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
807   SHeader.sh_size = writeContent(OS, Section.Content, Section.Size);
808 
809   if (Section.EntSize)
810     SHeader.sh_entsize = *Section.EntSize;
811 
812   if (Section.Info)
813     SHeader.sh_info = *Section.Info;
814 }
815 
816 static bool isMips64EL(const ELFYAML::Object &Doc) {
817   return Doc.Header.Machine == ELFYAML::ELF_EM(llvm::ELF::EM_MIPS) &&
818          Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64) &&
819          Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
820 }
821 
822 template <class ELFT>
823 void ELFState<ELFT>::writeSectionContent(
824     Elf_Shdr &SHeader, const ELFYAML::RelocationSection &Section,
825     ContiguousBlobAccumulator &CBA) {
826   assert((Section.Type == llvm::ELF::SHT_REL ||
827           Section.Type == llvm::ELF::SHT_RELA) &&
828          "Section type is not SHT_REL nor SHT_RELA");
829 
830   bool IsRela = Section.Type == llvm::ELF::SHT_RELA;
831   if (Section.EntSize)
832     SHeader.sh_entsize = *Section.EntSize;
833   else
834     SHeader.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
835   SHeader.sh_size = (IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel)) *
836                     Section.Relocations.size();
837 
838   // For relocation section set link to .symtab by default.
839   unsigned Link = 0;
840   if (Section.Link.empty() && SN2I.lookup(".symtab", Link))
841     SHeader.sh_link = Link;
842 
843   if (!Section.RelocatableSec.empty())
844     SHeader.sh_info = toSectionIndex(Section.RelocatableSec, Section.Name);
845 
846   auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
847   for (const auto &Rel : Section.Relocations) {
848     unsigned SymIdx = Rel.Symbol ? toSymbolIndex(*Rel.Symbol, Section.Name,
849                                                  Section.Link == ".dynsym")
850                                  : 0;
851     if (IsRela) {
852       Elf_Rela REntry;
853       zero(REntry);
854       REntry.r_offset = Rel.Offset;
855       REntry.r_addend = Rel.Addend;
856       REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
857       OS.write((const char *)&REntry, sizeof(REntry));
858     } else {
859       Elf_Rel REntry;
860       zero(REntry);
861       REntry.r_offset = Rel.Offset;
862       REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
863       OS.write((const char *)&REntry, sizeof(REntry));
864     }
865   }
866 }
867 
868 template <class ELFT>
869 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
870                                          const ELFYAML::RelrSection &Section,
871                                          ContiguousBlobAccumulator &CBA) {
872   raw_ostream &OS =
873       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
874   SHeader.sh_entsize =
875       Section.EntSize ? uint64_t(*Section.EntSize) : sizeof(Elf_Relr);
876 
877   if (Section.Content) {
878     SHeader.sh_size = writeContent(OS, Section.Content, None);
879     return;
880   }
881 
882   if (!Section.Entries)
883     return;
884 
885   for (llvm::yaml::Hex64 E : *Section.Entries) {
886     if (!ELFT::Is64Bits && E > UINT32_MAX)
887       reportError(Section.Name + ": the value is too large for 32-bits: 0x" +
888                   Twine::utohexstr(E));
889     support::endian::write<uintX_t>(OS, E, ELFT::TargetEndianness);
890   }
891 
892   SHeader.sh_size = sizeof(uintX_t) * Section.Entries->size();
893 }
894 
895 template <class ELFT>
896 void ELFState<ELFT>::writeSectionContent(
897     Elf_Shdr &SHeader, const ELFYAML::SymtabShndxSection &Shndx,
898     ContiguousBlobAccumulator &CBA) {
899   raw_ostream &OS =
900       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
901 
902   for (uint32_t E : Shndx.Entries)
903     support::endian::write<uint32_t>(OS, E, ELFT::TargetEndianness);
904 
905   SHeader.sh_entsize = Shndx.EntSize ? (uint64_t)*Shndx.EntSize : 4;
906   SHeader.sh_size = Shndx.Entries.size() * SHeader.sh_entsize;
907 }
908 
909 template <class ELFT>
910 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
911                                          const ELFYAML::Group &Section,
912                                          ContiguousBlobAccumulator &CBA) {
913   assert(Section.Type == llvm::ELF::SHT_GROUP &&
914          "Section type is not SHT_GROUP");
915 
916   unsigned Link = 0;
917   if (Section.Link.empty() && SN2I.lookup(".symtab", Link))
918     SHeader.sh_link = Link;
919 
920   SHeader.sh_entsize = 4;
921   SHeader.sh_size = SHeader.sh_entsize * Section.Members.size();
922 
923   if (Section.Signature)
924     SHeader.sh_info =
925         toSymbolIndex(*Section.Signature, Section.Name, /*IsDynamic=*/false);
926 
927   raw_ostream &OS =
928       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
929 
930   for (const ELFYAML::SectionOrType &Member : Section.Members) {
931     unsigned int SectionIndex = 0;
932     if (Member.sectionNameOrType == "GRP_COMDAT")
933       SectionIndex = llvm::ELF::GRP_COMDAT;
934     else
935       SectionIndex = toSectionIndex(Member.sectionNameOrType, Section.Name);
936     support::endian::write<uint32_t>(OS, SectionIndex, ELFT::TargetEndianness);
937   }
938 }
939 
940 template <class ELFT>
941 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
942                                          const ELFYAML::SymverSection &Section,
943                                          ContiguousBlobAccumulator &CBA) {
944   raw_ostream &OS =
945       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
946   for (uint16_t Version : Section.Entries)
947     support::endian::write<uint16_t>(OS, Version, ELFT::TargetEndianness);
948 
949   SHeader.sh_entsize = Section.EntSize ? (uint64_t)*Section.EntSize : 2;
950   SHeader.sh_size = Section.Entries.size() * SHeader.sh_entsize;
951 }
952 
953 template <class ELFT>
954 void ELFState<ELFT>::writeSectionContent(
955     Elf_Shdr &SHeader, const ELFYAML::StackSizesSection &Section,
956     ContiguousBlobAccumulator &CBA) {
957   raw_ostream &OS =
958       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
959 
960   if (Section.Content || Section.Size) {
961     SHeader.sh_size = writeContent(OS, Section.Content, Section.Size);
962     return;
963   }
964 
965   for (const ELFYAML::StackSizeEntry &E : *Section.Entries) {
966     support::endian::write<uintX_t>(OS, E.Address, ELFT::TargetEndianness);
967     SHeader.sh_size += sizeof(uintX_t) + encodeULEB128(E.Size, OS);
968   }
969 }
970 
971 template <class ELFT>
972 void ELFState<ELFT>::writeSectionContent(
973     Elf_Shdr &SHeader, const ELFYAML::LinkerOptionsSection &Section,
974     ContiguousBlobAccumulator &CBA) {
975   raw_ostream &OS =
976       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
977 
978   if (Section.Content) {
979     SHeader.sh_size = writeContent(OS, Section.Content, None);
980     return;
981   }
982 
983   if (!Section.Options)
984     return;
985 
986   for (const ELFYAML::LinkerOption &LO : *Section.Options) {
987     OS.write(LO.Key.data(), LO.Key.size());
988     OS.write('\0');
989     OS.write(LO.Value.data(), LO.Value.size());
990     OS.write('\0');
991     SHeader.sh_size += (LO.Key.size() + LO.Value.size() + 2);
992   }
993 }
994 
995 template <class ELFT>
996 void ELFState<ELFT>::writeSectionContent(
997     Elf_Shdr &SHeader, const ELFYAML::DependentLibrariesSection &Section,
998     ContiguousBlobAccumulator &CBA) {
999   raw_ostream &OS =
1000       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
1001 
1002   if (Section.Content) {
1003     SHeader.sh_size = writeContent(OS, Section.Content, None);
1004     return;
1005   }
1006 
1007   if (!Section.Libs)
1008     return;
1009 
1010   for (StringRef Lib : *Section.Libs) {
1011     OS.write(Lib.data(), Lib.size());
1012     OS.write('\0');
1013     SHeader.sh_size += Lib.size() + 1;
1014   }
1015 }
1016 
1017 template <class ELFT>
1018 void ELFState<ELFT>::writeSectionContent(
1019     Elf_Shdr &SHeader, const ELFYAML::CallGraphProfileSection &Section,
1020     ContiguousBlobAccumulator &CBA) {
1021   raw_ostream &OS =
1022       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
1023 
1024   if (Section.EntSize)
1025     SHeader.sh_entsize = *Section.EntSize;
1026   else
1027     SHeader.sh_entsize = 16;
1028 
1029   unsigned Link = 0;
1030   if (Section.Link.empty() && SN2I.lookup(".symtab", Link))
1031     SHeader.sh_link = Link;
1032 
1033   if (Section.Content) {
1034     SHeader.sh_size = writeContent(OS, Section.Content, None);
1035     return;
1036   }
1037 
1038   if (!Section.Entries)
1039     return;
1040 
1041   for (const ELFYAML::CallGraphEntry &E : *Section.Entries) {
1042     unsigned From = toSymbolIndex(E.From, Section.Name, /*IsDynamic=*/false);
1043     unsigned To = toSymbolIndex(E.To, Section.Name, /*IsDynamic=*/false);
1044 
1045     support::endian::write<uint32_t>(OS, From, ELFT::TargetEndianness);
1046     support::endian::write<uint32_t>(OS, To, ELFT::TargetEndianness);
1047     support::endian::write<uint64_t>(OS, E.Weight, ELFT::TargetEndianness);
1048     SHeader.sh_size += 16;
1049   }
1050 }
1051 
1052 template <class ELFT>
1053 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1054                                          const ELFYAML::HashSection &Section,
1055                                          ContiguousBlobAccumulator &CBA) {
1056   raw_ostream &OS =
1057       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
1058 
1059   unsigned Link = 0;
1060   if (Section.Link.empty() && SN2I.lookup(".dynsym", Link))
1061     SHeader.sh_link = Link;
1062 
1063   if (Section.Content || Section.Size) {
1064     SHeader.sh_size = writeContent(OS, Section.Content, Section.Size);
1065     return;
1066   }
1067 
1068   support::endian::write<uint32_t>(OS, Section.Bucket->size(),
1069                                    ELFT::TargetEndianness);
1070   support::endian::write<uint32_t>(OS, Section.Chain->size(),
1071                                    ELFT::TargetEndianness);
1072   for (uint32_t Val : *Section.Bucket)
1073     support::endian::write<uint32_t>(OS, Val, ELFT::TargetEndianness);
1074   for (uint32_t Val : *Section.Chain)
1075     support::endian::write<uint32_t>(OS, Val, ELFT::TargetEndianness);
1076 
1077   SHeader.sh_size = (2 + Section.Bucket->size() + Section.Chain->size()) * 4;
1078 }
1079 
1080 template <class ELFT>
1081 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1082                                          const ELFYAML::VerdefSection &Section,
1083                                          ContiguousBlobAccumulator &CBA) {
1084   typedef typename ELFT::Verdef Elf_Verdef;
1085   typedef typename ELFT::Verdaux Elf_Verdaux;
1086   raw_ostream &OS =
1087       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
1088 
1089   SHeader.sh_info = Section.Info;
1090 
1091   if (Section.Content) {
1092     SHeader.sh_size = writeContent(OS, Section.Content, None);
1093     return;
1094   }
1095 
1096   if (!Section.Entries)
1097     return;
1098 
1099   uint64_t AuxCnt = 0;
1100   for (size_t I = 0; I < Section.Entries->size(); ++I) {
1101     const ELFYAML::VerdefEntry &E = (*Section.Entries)[I];
1102 
1103     Elf_Verdef VerDef;
1104     VerDef.vd_version = E.Version;
1105     VerDef.vd_flags = E.Flags;
1106     VerDef.vd_ndx = E.VersionNdx;
1107     VerDef.vd_hash = E.Hash;
1108     VerDef.vd_aux = sizeof(Elf_Verdef);
1109     VerDef.vd_cnt = E.VerNames.size();
1110     if (I == Section.Entries->size() - 1)
1111       VerDef.vd_next = 0;
1112     else
1113       VerDef.vd_next =
1114           sizeof(Elf_Verdef) + E.VerNames.size() * sizeof(Elf_Verdaux);
1115     OS.write((const char *)&VerDef, sizeof(Elf_Verdef));
1116 
1117     for (size_t J = 0; J < E.VerNames.size(); ++J, ++AuxCnt) {
1118       Elf_Verdaux VernAux;
1119       VernAux.vda_name = DotDynstr.getOffset(E.VerNames[J]);
1120       if (J == E.VerNames.size() - 1)
1121         VernAux.vda_next = 0;
1122       else
1123         VernAux.vda_next = sizeof(Elf_Verdaux);
1124       OS.write((const char *)&VernAux, sizeof(Elf_Verdaux));
1125     }
1126   }
1127 
1128   SHeader.sh_size = Section.Entries->size() * sizeof(Elf_Verdef) +
1129                     AuxCnt * sizeof(Elf_Verdaux);
1130 }
1131 
1132 template <class ELFT>
1133 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1134                                          const ELFYAML::VerneedSection &Section,
1135                                          ContiguousBlobAccumulator &CBA) {
1136   typedef typename ELFT::Verneed Elf_Verneed;
1137   typedef typename ELFT::Vernaux Elf_Vernaux;
1138 
1139   auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
1140   SHeader.sh_info = Section.Info;
1141 
1142   if (Section.Content) {
1143     SHeader.sh_size = writeContent(OS, Section.Content, None);
1144     return;
1145   }
1146 
1147   if (!Section.VerneedV)
1148     return;
1149 
1150   uint64_t AuxCnt = 0;
1151   for (size_t I = 0; I < Section.VerneedV->size(); ++I) {
1152     const ELFYAML::VerneedEntry &VE = (*Section.VerneedV)[I];
1153 
1154     Elf_Verneed VerNeed;
1155     VerNeed.vn_version = VE.Version;
1156     VerNeed.vn_file = DotDynstr.getOffset(VE.File);
1157     if (I == Section.VerneedV->size() - 1)
1158       VerNeed.vn_next = 0;
1159     else
1160       VerNeed.vn_next =
1161           sizeof(Elf_Verneed) + VE.AuxV.size() * sizeof(Elf_Vernaux);
1162     VerNeed.vn_cnt = VE.AuxV.size();
1163     VerNeed.vn_aux = sizeof(Elf_Verneed);
1164     OS.write((const char *)&VerNeed, sizeof(Elf_Verneed));
1165 
1166     for (size_t J = 0; J < VE.AuxV.size(); ++J, ++AuxCnt) {
1167       const ELFYAML::VernauxEntry &VAuxE = VE.AuxV[J];
1168 
1169       Elf_Vernaux VernAux;
1170       VernAux.vna_hash = VAuxE.Hash;
1171       VernAux.vna_flags = VAuxE.Flags;
1172       VernAux.vna_other = VAuxE.Other;
1173       VernAux.vna_name = DotDynstr.getOffset(VAuxE.Name);
1174       if (J == VE.AuxV.size() - 1)
1175         VernAux.vna_next = 0;
1176       else
1177         VernAux.vna_next = sizeof(Elf_Vernaux);
1178       OS.write((const char *)&VernAux, sizeof(Elf_Vernaux));
1179     }
1180   }
1181 
1182   SHeader.sh_size = Section.VerneedV->size() * sizeof(Elf_Verneed) +
1183                     AuxCnt * sizeof(Elf_Vernaux);
1184 }
1185 
1186 template <class ELFT>
1187 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1188                                          const ELFYAML::MipsABIFlags &Section,
1189                                          ContiguousBlobAccumulator &CBA) {
1190   assert(Section.Type == llvm::ELF::SHT_MIPS_ABIFLAGS &&
1191          "Section type is not SHT_MIPS_ABIFLAGS");
1192 
1193   object::Elf_Mips_ABIFlags<ELFT> Flags;
1194   zero(Flags);
1195   SHeader.sh_entsize = sizeof(Flags);
1196   SHeader.sh_size = SHeader.sh_entsize;
1197 
1198   auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
1199   Flags.version = Section.Version;
1200   Flags.isa_level = Section.ISALevel;
1201   Flags.isa_rev = Section.ISARevision;
1202   Flags.gpr_size = Section.GPRSize;
1203   Flags.cpr1_size = Section.CPR1Size;
1204   Flags.cpr2_size = Section.CPR2Size;
1205   Flags.fp_abi = Section.FpABI;
1206   Flags.isa_ext = Section.ISAExtension;
1207   Flags.ases = Section.ASEs;
1208   Flags.flags1 = Section.Flags1;
1209   Flags.flags2 = Section.Flags2;
1210   OS.write((const char *)&Flags, sizeof(Flags));
1211 }
1212 
1213 template <class ELFT>
1214 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1215                                          const ELFYAML::DynamicSection &Section,
1216                                          ContiguousBlobAccumulator &CBA) {
1217   assert(Section.Type == llvm::ELF::SHT_DYNAMIC &&
1218          "Section type is not SHT_DYNAMIC");
1219 
1220   if (!Section.Entries.empty() && Section.Content)
1221     reportError("cannot specify both raw content and explicit entries "
1222                 "for dynamic section '" +
1223                 Section.Name + "'");
1224 
1225   if (Section.Content)
1226     SHeader.sh_size = Section.Content->binary_size();
1227   else
1228     SHeader.sh_size = 2 * sizeof(uintX_t) * Section.Entries.size();
1229   if (Section.EntSize)
1230     SHeader.sh_entsize = *Section.EntSize;
1231   else
1232     SHeader.sh_entsize = sizeof(Elf_Dyn);
1233 
1234   raw_ostream &OS =
1235       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
1236   for (const ELFYAML::DynamicEntry &DE : Section.Entries) {
1237     support::endian::write<uintX_t>(OS, DE.Tag, ELFT::TargetEndianness);
1238     support::endian::write<uintX_t>(OS, DE.Val, ELFT::TargetEndianness);
1239   }
1240   if (Section.Content)
1241     Section.Content->writeAsBinary(OS);
1242 }
1243 
1244 template <class ELFT>
1245 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1246                                          const ELFYAML::AddrsigSection &Section,
1247                                          ContiguousBlobAccumulator &CBA) {
1248   raw_ostream &OS =
1249       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
1250 
1251   unsigned Link = 0;
1252   if (Section.Link.empty() && SN2I.lookup(".symtab", Link))
1253     SHeader.sh_link = Link;
1254 
1255   if (Section.Content || Section.Size) {
1256     SHeader.sh_size = writeContent(OS, Section.Content, Section.Size);
1257     return;
1258   }
1259 
1260   for (StringRef Sym : *Section.Symbols)
1261     SHeader.sh_size += encodeULEB128(
1262         toSymbolIndex(Sym, Section.Name, /*IsDynamic=*/false), OS);
1263 }
1264 
1265 template <class ELFT>
1266 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1267                                          const ELFYAML::NoteSection &Section,
1268                                          ContiguousBlobAccumulator &CBA) {
1269   raw_ostream &OS =
1270       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
1271   uint64_t Offset = OS.tell();
1272 
1273   if (Section.Content || Section.Size) {
1274     SHeader.sh_size = writeContent(OS, Section.Content, Section.Size);
1275     return;
1276   }
1277 
1278   for (const ELFYAML::NoteEntry &NE : *Section.Notes) {
1279     // Write name size.
1280     if (NE.Name.empty())
1281       support::endian::write<uint32_t>(OS, 0, ELFT::TargetEndianness);
1282     else
1283       support::endian::write<uint32_t>(OS, NE.Name.size() + 1,
1284                                        ELFT::TargetEndianness);
1285 
1286     // Write description size.
1287     if (NE.Desc.binary_size() == 0)
1288       support::endian::write<uint32_t>(OS, 0, ELFT::TargetEndianness);
1289     else
1290       support::endian::write<uint32_t>(OS, NE.Desc.binary_size(),
1291                                        ELFT::TargetEndianness);
1292 
1293     // Write type.
1294     support::endian::write<uint32_t>(OS, NE.Type, ELFT::TargetEndianness);
1295 
1296     // Write name, null terminator and padding.
1297     if (!NE.Name.empty()) {
1298       support::endian::write<uint8_t>(OS, arrayRefFromStringRef(NE.Name),
1299                                       ELFT::TargetEndianness);
1300       support::endian::write<uint8_t>(OS, 0, ELFT::TargetEndianness);
1301       CBA.padToAlignment(4);
1302     }
1303 
1304     // Write description and padding.
1305     if (NE.Desc.binary_size() != 0) {
1306       NE.Desc.writeAsBinary(OS);
1307       CBA.padToAlignment(4);
1308     }
1309   }
1310 
1311   SHeader.sh_size = OS.tell() - Offset;
1312 }
1313 
1314 template <class ELFT>
1315 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1316                                          const ELFYAML::GnuHashSection &Section,
1317                                          ContiguousBlobAccumulator &CBA) {
1318   raw_ostream &OS =
1319       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
1320 
1321   unsigned Link = 0;
1322   if (Section.Link.empty() && SN2I.lookup(".dynsym", Link))
1323     SHeader.sh_link = Link;
1324 
1325   if (Section.Content) {
1326     SHeader.sh_size = writeContent(OS, Section.Content, None);
1327     return;
1328   }
1329 
1330   // We write the header first, starting with the hash buckets count. Normally
1331   // it is the number of entries in HashBuckets, but the "NBuckets" property can
1332   // be used to override this field, which is useful for producing broken
1333   // objects.
1334   if (Section.Header->NBuckets)
1335     support::endian::write<uint32_t>(OS, *Section.Header->NBuckets,
1336                                      ELFT::TargetEndianness);
1337   else
1338     support::endian::write<uint32_t>(OS, Section.HashBuckets->size(),
1339                                      ELFT::TargetEndianness);
1340 
1341   // Write the index of the first symbol in the dynamic symbol table accessible
1342   // via the hash table.
1343   support::endian::write<uint32_t>(OS, Section.Header->SymNdx,
1344                                    ELFT::TargetEndianness);
1345 
1346   // Write the number of words in the Bloom filter. As above, the "MaskWords"
1347   // property can be used to set this field to any value.
1348   if (Section.Header->MaskWords)
1349     support::endian::write<uint32_t>(OS, *Section.Header->MaskWords,
1350                                      ELFT::TargetEndianness);
1351   else
1352     support::endian::write<uint32_t>(OS, Section.BloomFilter->size(),
1353                                      ELFT::TargetEndianness);
1354 
1355   // Write the shift constant used by the Bloom filter.
1356   support::endian::write<uint32_t>(OS, Section.Header->Shift2,
1357                                    ELFT::TargetEndianness);
1358 
1359   // We've finished writing the header. Now write the Bloom filter.
1360   for (llvm::yaml::Hex64 Val : *Section.BloomFilter)
1361     support::endian::write<typename ELFT::uint>(OS, Val,
1362                                                 ELFT::TargetEndianness);
1363 
1364   // Write an array of hash buckets.
1365   for (llvm::yaml::Hex32 Val : *Section.HashBuckets)
1366     support::endian::write<uint32_t>(OS, Val, ELFT::TargetEndianness);
1367 
1368   // Write an array of hash values.
1369   for (llvm::yaml::Hex32 Val : *Section.HashValues)
1370     support::endian::write<uint32_t>(OS, Val, ELFT::TargetEndianness);
1371 
1372   SHeader.sh_size = 16 /*Header size*/ +
1373                     Section.BloomFilter->size() * sizeof(typename ELFT::uint) +
1374                     Section.HashBuckets->size() * 4 +
1375                     Section.HashValues->size() * 4;
1376 }
1377 
1378 template <class ELFT>
1379 void ELFState<ELFT>::writeFill(ELFYAML::Fill &Fill,
1380                                ContiguousBlobAccumulator &CBA) {
1381   raw_ostream &OS = CBA.getOSAndAlignedOffset(Fill.ShOffset, /*Align=*/1);
1382 
1383   size_t PatternSize = Fill.Pattern ? Fill.Pattern->binary_size() : 0;
1384   if (!PatternSize) {
1385     OS.write_zeros(Fill.Size);
1386     return;
1387   }
1388 
1389   // Fill the content with the specified pattern.
1390   uint64_t Written = 0;
1391   for (; Written + PatternSize <= Fill.Size; Written += PatternSize)
1392     Fill.Pattern->writeAsBinary(OS);
1393   Fill.Pattern->writeAsBinary(OS, Fill.Size - Written);
1394 }
1395 
1396 template <class ELFT> void ELFState<ELFT>::buildSectionIndex() {
1397   size_t SecNdx = -1;
1398   StringSet<> Seen;
1399   for (size_t I = 0; I < Doc.Chunks.size(); ++I) {
1400     const std::unique_ptr<ELFYAML::Chunk> &C = Doc.Chunks[I];
1401     bool IsSection = isa<ELFYAML::Section>(C.get());
1402     if (IsSection)
1403       ++SecNdx;
1404 
1405     if (C->Name.empty())
1406       continue;
1407 
1408     if (!Seen.insert(C->Name).second)
1409       reportError("repeated section/fill name: '" + C->Name +
1410                   "' at YAML section/fill number " + Twine(I));
1411     if (!IsSection || HasError)
1412       continue;
1413 
1414     if (!SN2I.addName(C->Name, SecNdx))
1415       llvm_unreachable("buildSectionIndex() failed");
1416     DotShStrtab.add(ELFYAML::dropUniqueSuffix(C->Name));
1417   }
1418 
1419   DotShStrtab.finalize();
1420 }
1421 
1422 template <class ELFT> void ELFState<ELFT>::buildSymbolIndexes() {
1423   auto Build = [this](ArrayRef<ELFYAML::Symbol> V, NameToIdxMap &Map) {
1424     for (size_t I = 0, S = V.size(); I < S; ++I) {
1425       const ELFYAML::Symbol &Sym = V[I];
1426       if (!Sym.Name.empty() && !Map.addName(Sym.Name, I + 1))
1427         reportError("repeated symbol name: '" + Sym.Name + "'");
1428     }
1429   };
1430 
1431   if (Doc.Symbols)
1432     Build(*Doc.Symbols, SymN2I);
1433   if (Doc.DynamicSymbols)
1434     Build(*Doc.DynamicSymbols, DynSymN2I);
1435 }
1436 
1437 template <class ELFT> void ELFState<ELFT>::finalizeStrings() {
1438   // Add the regular symbol names to .strtab section.
1439   if (Doc.Symbols)
1440     for (const ELFYAML::Symbol &Sym : *Doc.Symbols)
1441       DotStrtab.add(ELFYAML::dropUniqueSuffix(Sym.Name));
1442   DotStrtab.finalize();
1443 
1444   // Add the dynamic symbol names to .dynstr section.
1445   if (Doc.DynamicSymbols)
1446     for (const ELFYAML::Symbol &Sym : *Doc.DynamicSymbols)
1447       DotDynstr.add(ELFYAML::dropUniqueSuffix(Sym.Name));
1448 
1449   // SHT_GNU_verdef and SHT_GNU_verneed sections might also
1450   // add strings to .dynstr section.
1451   for (const ELFYAML::Chunk *Sec : Doc.getSections()) {
1452     if (auto VerNeed = dyn_cast<ELFYAML::VerneedSection>(Sec)) {
1453       if (VerNeed->VerneedV) {
1454         for (const ELFYAML::VerneedEntry &VE : *VerNeed->VerneedV) {
1455           DotDynstr.add(VE.File);
1456           for (const ELFYAML::VernauxEntry &Aux : VE.AuxV)
1457             DotDynstr.add(Aux.Name);
1458         }
1459       }
1460     } else if (auto VerDef = dyn_cast<ELFYAML::VerdefSection>(Sec)) {
1461       if (VerDef->Entries)
1462         for (const ELFYAML::VerdefEntry &E : *VerDef->Entries)
1463           for (StringRef Name : E.VerNames)
1464             DotDynstr.add(Name);
1465     }
1466   }
1467 
1468   DotDynstr.finalize();
1469 }
1470 
1471 template <class ELFT>
1472 bool ELFState<ELFT>::writeELF(raw_ostream &OS, ELFYAML::Object &Doc,
1473                               yaml::ErrorHandler EH) {
1474   ELFState<ELFT> State(Doc, EH);
1475 
1476   // Finalize .strtab and .dynstr sections. We do that early because want to
1477   // finalize the string table builders before writing the content of the
1478   // sections that might want to use them.
1479   State.finalizeStrings();
1480 
1481   State.buildSectionIndex();
1482   if (State.HasError)
1483     return false;
1484 
1485   State.buildSymbolIndexes();
1486 
1487   std::vector<Elf_Phdr> PHeaders;
1488   State.initProgramHeaders(PHeaders);
1489 
1490   // XXX: This offset is tightly coupled with the order that we write
1491   // things to `OS`.
1492   const size_t SectionContentBeginOffset =
1493       sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * Doc.ProgramHeaders.size();
1494   ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
1495 
1496   std::vector<Elf_Shdr> SHeaders;
1497   State.initSectionHeaders(SHeaders, CBA);
1498 
1499   // Now we can decide segment offsets.
1500   State.setProgramHeaderLayout(PHeaders, SHeaders);
1501 
1502   if (State.HasError)
1503     return false;
1504 
1505   State.writeELFHeader(CBA, OS);
1506   writeArrayData(OS, makeArrayRef(PHeaders));
1507   CBA.writeBlobToStream(OS);
1508   writeArrayData(OS, makeArrayRef(SHeaders));
1509   return true;
1510 }
1511 
1512 namespace llvm {
1513 namespace yaml {
1514 
1515 bool yaml2elf(llvm::ELFYAML::Object &Doc, raw_ostream &Out, ErrorHandler EH) {
1516   bool IsLE = Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
1517   bool Is64Bit = Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
1518   if (Is64Bit) {
1519     if (IsLE)
1520       return ELFState<object::ELF64LE>::writeELF(Out, Doc, EH);
1521     return ELFState<object::ELF64BE>::writeELF(Out, Doc, EH);
1522   }
1523   if (IsLE)
1524     return ELFState<object::ELF32LE>::writeELF(Out, Doc, EH);
1525   return ELFState<object::ELF32BE>::writeELF(Out, Doc, EH);
1526 }
1527 
1528 } // namespace yaml
1529 } // namespace llvm
1530