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