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