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