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