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