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