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