OSDN Git Service

[llvm-objcopy][llvm-strip] Fix help text typo for --allow-broken-links
[android-x86/external-llvm.git] / tools / yaml2obj / yaml2elf.cpp
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 "yaml2obj.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/BinaryFormat/ELF.h"
17 #include "llvm/MC/StringTableBuilder.h"
18 #include "llvm/Object/ELFObjectFile.h"
19 #include "llvm/ObjectYAML/ELFYAML.h"
20 #include "llvm/Support/EndianStream.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "llvm/Support/WithColor.h"
23 #include "llvm/Support/YAMLTraits.h"
24 #include "llvm/Support/raw_ostream.h"
25
26 using namespace llvm;
27
28 // This class is used to build up a contiguous binary blob while keeping
29 // track of an offset in the output (which notionally begins at
30 // `InitialOffset`).
31 namespace {
32 class ContiguousBlobAccumulator {
33   const uint64_t InitialOffset;
34   SmallVector<char, 128> Buf;
35   raw_svector_ostream OS;
36
37   /// \returns The new offset.
38   uint64_t padToAlignment(unsigned Align) {
39     if (Align == 0)
40       Align = 1;
41     uint64_t CurrentOffset = InitialOffset + OS.tell();
42     uint64_t AlignedOffset = alignTo(CurrentOffset, Align);
43     OS.write_zeros(AlignedOffset - CurrentOffset);
44     return AlignedOffset; // == CurrentOffset;
45   }
46
47 public:
48   ContiguousBlobAccumulator(uint64_t InitialOffset_)
49       : InitialOffset(InitialOffset_), Buf(), OS(Buf) {}
50   template <class Integer>
51   raw_ostream &getOSAndAlignedOffset(Integer &Offset, unsigned Align) {
52     Offset = padToAlignment(Align);
53     return OS;
54   }
55   void writeBlobToStream(raw_ostream &Out) { Out << OS.str(); }
56 };
57 } // end anonymous namespace
58
59 // Used to keep track of section and symbol names, so that in the YAML file
60 // sections and symbols can be referenced by name instead of by index.
61 namespace {
62 class NameToIdxMap {
63   StringMap<unsigned> Map;
64
65 public:
66   /// \Returns false if name is already present in the map.
67   bool addName(StringRef Name, unsigned Ndx) {
68     return Map.insert({Name, Ndx}).second;
69   }
70   /// \Returns false if name is not present in the map.
71   bool lookup(StringRef Name, unsigned &Idx) const {
72     auto I = Map.find(Name);
73     if (I == Map.end())
74       return false;
75     Idx = I->getValue();
76     return true;
77   }
78   /// Asserts if name is not present in the map.
79   unsigned get(StringRef Name) const {
80     unsigned Idx;
81     if (lookup(Name, Idx))
82       return Idx;
83     assert(false && "Expected section not found in index");
84     return 0;
85   }
86   unsigned size() const { return Map.size(); }
87 };
88 } // end anonymous namespace
89
90 template <class T>
91 static size_t arrayDataSize(ArrayRef<T> A) {
92   return A.size() * sizeof(T);
93 }
94
95 template <class T>
96 static void writeArrayData(raw_ostream &OS, ArrayRef<T> A) {
97   OS.write((const char *)A.data(), arrayDataSize(A));
98 }
99
100 template <class T>
101 static void zero(T &Obj) {
102   memset(&Obj, 0, sizeof(Obj));
103 }
104
105 namespace {
106 /// "Single point of truth" for the ELF file construction.
107 /// TODO: This class still has a ways to go before it is truly a "single
108 /// point of truth".
109 template <class ELFT>
110 class ELFState {
111   typedef typename ELFT::Ehdr Elf_Ehdr;
112   typedef typename ELFT::Phdr Elf_Phdr;
113   typedef typename ELFT::Shdr Elf_Shdr;
114   typedef typename ELFT::Sym Elf_Sym;
115   typedef typename ELFT::Rel Elf_Rel;
116   typedef typename ELFT::Rela Elf_Rela;
117   typedef typename ELFT::Relr Elf_Relr;
118   typedef typename ELFT::Dyn Elf_Dyn;
119
120   enum class SymtabType { Static, Dynamic };
121
122   /// The future ".strtab" section.
123   StringTableBuilder DotStrtab{StringTableBuilder::ELF};
124
125   /// The future ".shstrtab" section.
126   StringTableBuilder DotShStrtab{StringTableBuilder::ELF};
127
128   /// The future ".dynstr" section.
129   StringTableBuilder DotDynstr{StringTableBuilder::ELF};
130
131   NameToIdxMap SN2I;
132   NameToIdxMap SymN2I;
133   const ELFYAML::Object &Doc;
134
135   bool buildSectionIndex();
136   bool buildSymbolIndex(ArrayRef<ELFYAML::Symbol> Symbols);
137   void initELFHeader(Elf_Ehdr &Header);
138   void initProgramHeaders(std::vector<Elf_Phdr> &PHeaders);
139   bool initImplicitHeader(ELFState<ELFT> &State, ContiguousBlobAccumulator &CBA,
140                           Elf_Shdr &Header, StringRef SecName,
141                           ELFYAML::Section *YAMLSec);
142   bool initSectionHeaders(ELFState<ELFT> &State,
143                           std::vector<Elf_Shdr> &SHeaders,
144                           ContiguousBlobAccumulator &CBA);
145   void initSymtabSectionHeader(Elf_Shdr &SHeader, SymtabType STType,
146                                ContiguousBlobAccumulator &CBA,
147                                ELFYAML::Section *YAMLSec);
148   void initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
149                                StringTableBuilder &STB,
150                                ContiguousBlobAccumulator &CBA,
151                                ELFYAML::Section *YAMLSec);
152   void setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
153                               std::vector<Elf_Shdr> &SHeaders);
154   bool writeSectionContent(Elf_Shdr &SHeader,
155                            const ELFYAML::RawContentSection &Section,
156                            ContiguousBlobAccumulator &CBA);
157   bool writeSectionContent(Elf_Shdr &SHeader,
158                            const ELFYAML::RelocationSection &Section,
159                            ContiguousBlobAccumulator &CBA);
160   bool writeSectionContent(Elf_Shdr &SHeader, const ELFYAML::Group &Group,
161                            ContiguousBlobAccumulator &CBA);
162   bool writeSectionContent(Elf_Shdr &SHeader,
163                            const ELFYAML::SymverSection &Section,
164                            ContiguousBlobAccumulator &CBA);
165   bool writeSectionContent(Elf_Shdr &SHeader,
166                            const ELFYAML::VerneedSection &Section,
167                            ContiguousBlobAccumulator &CBA);
168   bool writeSectionContent(Elf_Shdr &SHeader,
169                            const ELFYAML::VerdefSection &Section,
170                            ContiguousBlobAccumulator &CBA);
171   bool writeSectionContent(Elf_Shdr &SHeader,
172                            const ELFYAML::MipsABIFlags &Section,
173                            ContiguousBlobAccumulator &CBA);
174   bool writeSectionContent(Elf_Shdr &SHeader,
175                            const ELFYAML::DynamicSection &Section,
176                            ContiguousBlobAccumulator &CBA);
177   std::vector<StringRef> implicitSectionNames() const;
178
179   ELFState(const ELFYAML::Object &D) : Doc(D) {}
180
181 public:
182   static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc);
183
184 private:
185   void finalizeStrings();
186 };
187 } // end anonymous namespace
188
189 template <class ELFT>
190 void ELFState<ELFT>::initELFHeader(Elf_Ehdr &Header) {
191   using namespace llvm::ELF;
192   zero(Header);
193   Header.e_ident[EI_MAG0] = 0x7f;
194   Header.e_ident[EI_MAG1] = 'E';
195   Header.e_ident[EI_MAG2] = 'L';
196   Header.e_ident[EI_MAG3] = 'F';
197   Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
198   Header.e_ident[EI_DATA] = Doc.Header.Data;
199   Header.e_ident[EI_VERSION] = EV_CURRENT;
200   Header.e_ident[EI_OSABI] = Doc.Header.OSABI;
201   Header.e_ident[EI_ABIVERSION] = Doc.Header.ABIVersion;
202   Header.e_type = Doc.Header.Type;
203   Header.e_machine = Doc.Header.Machine;
204   Header.e_version = EV_CURRENT;
205   Header.e_entry = Doc.Header.Entry;
206   Header.e_phoff = sizeof(Header);
207   Header.e_flags = Doc.Header.Flags;
208   Header.e_ehsize = sizeof(Elf_Ehdr);
209   Header.e_phentsize = sizeof(Elf_Phdr);
210   Header.e_phnum = Doc.ProgramHeaders.size();
211   Header.e_shentsize = sizeof(Elf_Shdr);
212   // Immediately following the ELF header and program headers.
213   Header.e_shoff =
214       sizeof(Header) + sizeof(Elf_Phdr) * Doc.ProgramHeaders.size();
215   Header.e_shnum = SN2I.size() + 1;
216   Header.e_shstrndx = SN2I.get(".shstrtab");
217 }
218
219 template <class ELFT>
220 void ELFState<ELFT>::initProgramHeaders(std::vector<Elf_Phdr> &PHeaders) {
221   for (const auto &YamlPhdr : Doc.ProgramHeaders) {
222     Elf_Phdr Phdr;
223     Phdr.p_type = YamlPhdr.Type;
224     Phdr.p_flags = YamlPhdr.Flags;
225     Phdr.p_vaddr = YamlPhdr.VAddr;
226     Phdr.p_paddr = YamlPhdr.PAddr;
227     PHeaders.push_back(Phdr);
228   }
229 }
230
231 static bool convertSectionIndex(NameToIdxMap &SN2I, StringRef SecName,
232                                 StringRef IndexSrc, unsigned &IndexDest) {
233   if (!SN2I.lookup(IndexSrc, IndexDest) && !to_integer(IndexSrc, IndexDest)) {
234     WithColor::error() << "Unknown section referenced: '" << IndexSrc
235                        << "' at YAML section '" << SecName << "'.\n";
236     return false;
237   }
238   return true;
239 }
240
241 template <class ELFT>
242 bool ELFState<ELFT>::initImplicitHeader(ELFState<ELFT> &State,
243                                         ContiguousBlobAccumulator &CBA,
244                                         Elf_Shdr &Header, StringRef SecName,
245                                         ELFYAML::Section *YAMLSec) {
246   // Check if the header was already initialized.
247   if (Header.sh_offset)
248     return false;
249
250   if (SecName == ".symtab")
251     State.initSymtabSectionHeader(Header, SymtabType::Static, CBA, YAMLSec);
252   else if (SecName == ".strtab")
253     State.initStrtabSectionHeader(Header, SecName, State.DotStrtab, CBA,
254                                   YAMLSec);
255   else if (SecName == ".shstrtab")
256     State.initStrtabSectionHeader(Header, SecName, State.DotShStrtab, CBA,
257                                   YAMLSec);
258
259   else if (SecName == ".dynsym")
260     State.initSymtabSectionHeader(Header, SymtabType::Dynamic, CBA, YAMLSec);
261   else if (SecName == ".dynstr")
262     State.initStrtabSectionHeader(Header, SecName, State.DotDynstr, CBA,
263                                   YAMLSec);
264   else
265     return false;
266   return true;
267 }
268
269 static StringRef dropUniqueSuffix(StringRef S) {
270   size_t SuffixPos = S.rfind(" [");
271   if (SuffixPos == StringRef::npos)
272     return S;
273   return S.substr(0, SuffixPos);
274 }
275
276 template <class ELFT>
277 bool ELFState<ELFT>::initSectionHeaders(ELFState<ELFT> &State,
278                                         std::vector<Elf_Shdr> &SHeaders,
279                                         ContiguousBlobAccumulator &CBA) {
280   // Build a list of sections we are going to add implicitly.
281   std::vector<StringRef> ImplicitSections;
282   for (StringRef Name : State.implicitSectionNames())
283     if (State.SN2I.get(Name) > Doc.Sections.size())
284       ImplicitSections.push_back(Name);
285
286   // Ensure SHN_UNDEF entry is present. An all-zero section header is a
287   // valid SHN_UNDEF entry since SHT_NULL == 0.
288   SHeaders.resize(Doc.Sections.size() + ImplicitSections.size() + 1);
289   zero(SHeaders[0]);
290
291   for (size_t I = 1; I < Doc.Sections.size() + ImplicitSections.size() + 1; ++I) {
292     Elf_Shdr &SHeader = SHeaders[I];
293     zero(SHeader);
294     ELFYAML::Section *Sec =
295         I > Doc.Sections.size() ? nullptr : Doc.Sections[I - 1].get();
296
297     // We have a few sections like string or symbol tables that are usually
298     // added implicitly to the end. However, if they are explicitly specified
299     // in the YAML, we need to write them here. This ensures the file offset
300     // remains correct.
301     StringRef SecName =
302         Sec ? Sec->Name : ImplicitSections[I - Doc.Sections.size() - 1];
303     if (initImplicitHeader(State, CBA, SHeader, SecName, Sec))
304       continue;
305
306     assert(Sec && "It can't be null unless it is an implicit section. But all "
307                   "implicit sections should already have been handled above.");
308
309     SHeader.sh_name = DotShStrtab.getOffset(dropUniqueSuffix(SecName));
310     SHeader.sh_type = Sec->Type;
311     if (Sec->Flags)
312       SHeader.sh_flags = *Sec->Flags;
313     SHeader.sh_addr = Sec->Address;
314     SHeader.sh_addralign = Sec->AddressAlign;
315
316     if (!Sec->Link.empty()) {
317       unsigned Index;
318       if (!convertSectionIndex(SN2I, Sec->Name, Sec->Link, Index))
319         return false;
320       SHeader.sh_link = Index;
321     }
322
323     if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec)) {
324       if (!writeSectionContent(SHeader, *S, CBA))
325         return false;
326     } else if (auto S = dyn_cast<ELFYAML::RelocationSection>(Sec)) {
327       if (!writeSectionContent(SHeader, *S, CBA))
328         return false;
329     } else if (auto S = dyn_cast<ELFYAML::Group>(Sec)) {
330       if (!writeSectionContent(SHeader, *S, CBA))
331         return false;
332     } else if (auto S = dyn_cast<ELFYAML::MipsABIFlags>(Sec)) {
333       if (!writeSectionContent(SHeader, *S, CBA))
334         return false;
335     } else if (auto S = dyn_cast<ELFYAML::NoBitsSection>(Sec)) {
336       SHeader.sh_entsize = 0;
337       SHeader.sh_size = S->Size;
338       // SHT_NOBITS section does not have content
339       // so just to setup the section offset.
340       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
341     } else if (auto S = dyn_cast<ELFYAML::DynamicSection>(Sec)) {
342       if (!writeSectionContent(SHeader, *S, CBA))
343         return false;
344     } else if (auto S = dyn_cast<ELFYAML::SymverSection>(Sec)) {
345       if (!writeSectionContent(SHeader, *S, CBA))
346         return false;
347     } else if (auto S = dyn_cast<ELFYAML::VerneedSection>(Sec)) {
348       if (!writeSectionContent(SHeader, *S, CBA))
349         return false;
350     } else if (auto S = dyn_cast<ELFYAML::VerdefSection>(Sec)) {
351       if (!writeSectionContent(SHeader, *S, CBA))
352         return false;
353     } else
354       llvm_unreachable("Unknown section type");
355   }
356
357   return true;
358 }
359
360 static size_t findFirstNonGlobal(ArrayRef<ELFYAML::Symbol> Symbols) {
361   for (size_t I = 0; I < Symbols.size(); ++I)
362     if (Symbols[I].Binding.value != ELF::STB_LOCAL)
363       return I;
364   return Symbols.size();
365 }
366
367 static uint64_t writeRawSectionData(raw_ostream &OS,
368                                     const ELFYAML::RawContentSection &RawSec) {
369   size_t ContentSize = 0;
370   if (RawSec.Content) {
371     RawSec.Content->writeAsBinary(OS);
372     ContentSize = RawSec.Content->binary_size();
373   }
374
375   if (!RawSec.Size)
376     return ContentSize;
377
378   OS.write_zeros(*RawSec.Size - ContentSize);
379   return *RawSec.Size;
380 }
381
382 template <class ELFT>
383 static std::vector<typename ELFT::Sym>
384 toELFSymbols(NameToIdxMap &SN2I, ArrayRef<ELFYAML::Symbol> Symbols,
385              const StringTableBuilder &Strtab) {
386   using Elf_Sym = typename ELFT::Sym;
387
388   std::vector<Elf_Sym> Ret;
389   Ret.resize(Symbols.size() + 1);
390
391   size_t I = 0;
392   for (const auto &Sym : Symbols) {
393     Elf_Sym &Symbol = Ret[++I];
394
395     // If NameIndex, which contains the name offset, is explicitly specified, we
396     // use it. This is useful for preparing broken objects. Otherwise, we add
397     // the specified Name to the string table builder to get its offset.
398     if (Sym.NameIndex)
399       Symbol.st_name = *Sym.NameIndex;
400     else if (!Sym.Name.empty())
401       Symbol.st_name = Strtab.getOffset(dropUniqueSuffix(Sym.Name));
402
403     Symbol.setBindingAndType(Sym.Binding, Sym.Type);
404     if (!Sym.Section.empty()) {
405       unsigned Index;
406       if (!SN2I.lookup(Sym.Section, Index)) {
407         WithColor::error() << "Unknown section referenced: '" << Sym.Section
408                            << "' by YAML symbol " << Sym.Name << ".\n";
409         exit(1);
410       }
411       Symbol.st_shndx = Index;
412     } else if (Sym.Index) {
413       Symbol.st_shndx = *Sym.Index;
414     }
415     // else Symbol.st_shndex == SHN_UNDEF (== 0), since it was zero'd earlier.
416     Symbol.st_value = Sym.Value;
417     Symbol.st_other = Sym.Other;
418     Symbol.st_size = Sym.Size;
419   }
420
421   return Ret;
422 }
423
424 template <class ELFT>
425 void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
426                                              SymtabType STType,
427                                              ContiguousBlobAccumulator &CBA,
428                                              ELFYAML::Section *YAMLSec) {
429
430   bool IsStatic = STType == SymtabType::Static;
431   const auto &Symbols = IsStatic ? Doc.Symbols : Doc.DynamicSymbols;
432
433   ELFYAML::RawContentSection *RawSec =
434       dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec);
435   if (RawSec && !Symbols.empty() && (RawSec->Content || RawSec->Size)) {
436     if (RawSec->Content)
437       WithColor::error() << "Cannot specify both `Content` and " +
438                                 (IsStatic ? Twine("`Symbols`")
439                                           : Twine("`DynamicSymbols`")) +
440                                 " for symbol table section '"
441                          << RawSec->Name << "'.\n";
442     if (RawSec->Size)
443       WithColor::error() << "Cannot specify both `Size` and " +
444                                 (IsStatic ? Twine("`Symbols`")
445                                           : Twine("`DynamicSymbols`")) +
446                                 " for symbol table section '"
447                          << RawSec->Name << "'.\n";
448     exit(1);
449   }
450
451   zero(SHeader);
452   SHeader.sh_name = DotShStrtab.getOffset(IsStatic ? ".symtab" : ".dynsym");
453
454   if (YAMLSec)
455     SHeader.sh_type = YAMLSec->Type;
456   else
457     SHeader.sh_type = IsStatic ? ELF::SHT_SYMTAB : ELF::SHT_DYNSYM;
458
459   if (RawSec && !RawSec->Link.empty()) {
460     // If the Link field is explicitly defined in the document,
461     // we should use it.
462     unsigned Index;
463     if (!convertSectionIndex(SN2I, RawSec->Name, RawSec->Link, Index))
464       return;
465     SHeader.sh_link = Index;
466   } else {
467     // When we describe the .dynsym section in the document explicitly, it is
468     // allowed to omit the "DynamicSymbols" tag. In this case .dynstr is not
469     // added implicitly and we should be able to leave the Link zeroed if
470     // .dynstr is not defined.
471     unsigned Link = 0;
472     if (IsStatic)
473       Link = SN2I.get(".strtab");
474     else
475       SN2I.lookup(".dynstr", Link);
476     SHeader.sh_link = Link;
477   }
478
479   if (YAMLSec && YAMLSec->Flags)
480     SHeader.sh_flags = *YAMLSec->Flags;
481   else if (!IsStatic)
482     SHeader.sh_flags = ELF::SHF_ALLOC;
483
484   // If the symbol table section is explicitly described in the YAML
485   // then we should set the fields requested.
486   SHeader.sh_info = (RawSec && RawSec->Info) ? (unsigned)(*RawSec->Info)
487                                              : findFirstNonGlobal(Symbols) + 1;
488   SHeader.sh_entsize = (YAMLSec && YAMLSec->EntSize)
489                            ? (uint64_t)(*YAMLSec->EntSize)
490                            : sizeof(Elf_Sym);
491   SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 8;
492   SHeader.sh_addr = YAMLSec ? (uint64_t)YAMLSec->Address : 0;
493
494   auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
495   if (RawSec && (RawSec->Content || RawSec->Size)) {
496     assert(Symbols.empty());
497     SHeader.sh_size = writeRawSectionData(OS, *RawSec);
498     return;
499   }
500
501   std::vector<Elf_Sym> Syms =
502       toELFSymbols<ELFT>(SN2I, Symbols, IsStatic ? DotStrtab : DotDynstr);
503   writeArrayData(OS, makeArrayRef(Syms));
504   SHeader.sh_size = arrayDataSize(makeArrayRef(Syms));
505 }
506
507 template <class ELFT>
508 void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
509                                              StringTableBuilder &STB,
510                                              ContiguousBlobAccumulator &CBA,
511                                              ELFYAML::Section *YAMLSec) {
512   zero(SHeader);
513   SHeader.sh_name = DotShStrtab.getOffset(Name);
514   SHeader.sh_type = YAMLSec ? YAMLSec->Type : ELF::SHT_STRTAB;
515   SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 1;
516
517   ELFYAML::RawContentSection *RawSec =
518       dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec);
519
520   auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
521   if (RawSec && (RawSec->Content || RawSec->Size)) {
522     SHeader.sh_size = writeRawSectionData(OS, *RawSec);
523   } else {
524     STB.write(OS);
525     SHeader.sh_size = STB.getSize();
526   }
527
528   if (YAMLSec && YAMLSec->EntSize)
529     SHeader.sh_entsize = *YAMLSec->EntSize;
530
531   if (RawSec && RawSec->Info)
532     SHeader.sh_info = *RawSec->Info;
533
534   if (YAMLSec && YAMLSec->Flags)
535     SHeader.sh_flags = *YAMLSec->Flags;
536   else if (Name == ".dynstr")
537     SHeader.sh_flags = ELF::SHF_ALLOC;
538
539   // If the section is explicitly described in the YAML
540   // then we want to use its section address.
541   if (YAMLSec)
542     SHeader.sh_addr = YAMLSec->Address;
543 }
544
545 template <class ELFT>
546 void ELFState<ELFT>::setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
547                                             std::vector<Elf_Shdr> &SHeaders) {
548   uint32_t PhdrIdx = 0;
549   for (auto &YamlPhdr : Doc.ProgramHeaders) {
550     Elf_Phdr &PHeader = PHeaders[PhdrIdx++];
551
552     std::vector<Elf_Shdr *> Sections;
553     for (const ELFYAML::SectionName &SecName : YamlPhdr.Sections) {
554       unsigned Index;
555       if (!SN2I.lookup(SecName.Section, Index)) {
556         WithColor::error() << "Unknown section referenced: '" << SecName.Section
557                            << "' by program header.\n";
558         exit(1);
559       }
560       Sections.push_back(&SHeaders[Index]);
561     }
562
563     if (YamlPhdr.Offset) {
564       PHeader.p_offset = *YamlPhdr.Offset;
565     } else {
566       if (YamlPhdr.Sections.size())
567         PHeader.p_offset = UINT32_MAX;
568       else
569         PHeader.p_offset = 0;
570
571       // Find the minimum offset for the program header.
572       for (Elf_Shdr *SHeader : Sections)
573         PHeader.p_offset = std::min(PHeader.p_offset, SHeader->sh_offset);
574     }
575
576     // Find the maximum offset of the end of a section in order to set p_filesz,
577     // if not set explicitly.
578     if (YamlPhdr.FileSize) {
579       PHeader.p_filesz = *YamlPhdr.FileSize;
580     } else {
581       PHeader.p_filesz = 0;
582       for (Elf_Shdr *SHeader : Sections) {
583         uint64_t EndOfSection;
584         if (SHeader->sh_type == llvm::ELF::SHT_NOBITS)
585           EndOfSection = SHeader->sh_offset;
586         else
587           EndOfSection = SHeader->sh_offset + SHeader->sh_size;
588         uint64_t EndOfSegment = PHeader.p_offset + PHeader.p_filesz;
589         EndOfSegment = std::max(EndOfSegment, EndOfSection);
590         PHeader.p_filesz = EndOfSegment - PHeader.p_offset;
591       }
592     }
593
594     // If not set explicitly, find the memory size by adding the size of
595     // sections at the end of the segment. These should be empty (size of zero)
596     // and NOBITS sections.
597     if (YamlPhdr.MemSize) {
598       PHeader.p_memsz = *YamlPhdr.MemSize;
599     } else {
600       PHeader.p_memsz = PHeader.p_filesz;
601       for (Elf_Shdr *SHeader : Sections)
602         if (SHeader->sh_offset == PHeader.p_offset + PHeader.p_filesz)
603           PHeader.p_memsz += SHeader->sh_size;
604     }
605
606     // Set the alignment of the segment to be the same as the maximum alignment
607     // of the sections with the same offset so that by default the segment
608     // has a valid and sensible alignment.
609     if (YamlPhdr.Align) {
610       PHeader.p_align = *YamlPhdr.Align;
611     } else {
612       PHeader.p_align = 1;
613       for (Elf_Shdr *SHeader : Sections)
614         if (SHeader->sh_offset == PHeader.p_offset)
615           PHeader.p_align = std::max(PHeader.p_align, SHeader->sh_addralign);
616     }
617   }
618 }
619
620 template <class ELFT>
621 bool ELFState<ELFT>::writeSectionContent(
622     Elf_Shdr &SHeader, const ELFYAML::RawContentSection &Section,
623     ContiguousBlobAccumulator &CBA) {
624   raw_ostream &OS =
625       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
626   SHeader.sh_size = writeRawSectionData(OS, Section);
627
628   if (Section.EntSize)
629     SHeader.sh_entsize = *Section.EntSize;
630   else if (Section.Type == llvm::ELF::SHT_RELR)
631     SHeader.sh_entsize = sizeof(Elf_Relr);
632   else
633     SHeader.sh_entsize = 0;
634
635   if (Section.Info)
636     SHeader.sh_info = *Section.Info;
637
638   return true;
639 }
640
641 static bool isMips64EL(const ELFYAML::Object &Doc) {
642   return Doc.Header.Machine == ELFYAML::ELF_EM(llvm::ELF::EM_MIPS) &&
643          Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64) &&
644          Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
645 }
646
647 template <class ELFT>
648 bool
649 ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
650                                     const ELFYAML::RelocationSection &Section,
651                                     ContiguousBlobAccumulator &CBA) {
652   assert((Section.Type == llvm::ELF::SHT_REL ||
653           Section.Type == llvm::ELF::SHT_RELA) &&
654          "Section type is not SHT_REL nor SHT_RELA");
655
656   bool IsRela = Section.Type == llvm::ELF::SHT_RELA;
657   SHeader.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
658   SHeader.sh_size = SHeader.sh_entsize * Section.Relocations.size();
659
660   // For relocation section set link to .symtab by default.
661   if (Section.Link.empty())
662     SHeader.sh_link = SN2I.get(".symtab");
663
664   unsigned Index = 0;
665   if (!Section.RelocatableSec.empty() &&
666       !convertSectionIndex(SN2I, Section.Name, Section.RelocatableSec, Index))
667     return false;
668   SHeader.sh_info = Index;
669
670   auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
671
672   for (const auto &Rel : Section.Relocations) {
673     unsigned SymIdx = 0;
674     // If a relocation references a symbol, try to look one up in the symbol
675     // table. If it is not there, treat the value as a symbol index.
676     if (Rel.Symbol && !SymN2I.lookup(*Rel.Symbol, SymIdx) &&
677         !to_integer(*Rel.Symbol, SymIdx)) {
678       WithColor::error() << "Unknown symbol referenced: '" << *Rel.Symbol
679                          << "' at YAML section '" << Section.Name << "'.\n";
680       return false;
681     }
682
683     if (IsRela) {
684       Elf_Rela REntry;
685       zero(REntry);
686       REntry.r_offset = Rel.Offset;
687       REntry.r_addend = Rel.Addend;
688       REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
689       OS.write((const char *)&REntry, sizeof(REntry));
690     } else {
691       Elf_Rel REntry;
692       zero(REntry);
693       REntry.r_offset = Rel.Offset;
694       REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
695       OS.write((const char *)&REntry, sizeof(REntry));
696     }
697   }
698   return true;
699 }
700
701 template <class ELFT>
702 bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
703                                          const ELFYAML::Group &Section,
704                                          ContiguousBlobAccumulator &CBA) {
705   assert(Section.Type == llvm::ELF::SHT_GROUP &&
706          "Section type is not SHT_GROUP");
707
708   SHeader.sh_entsize = 4;
709   SHeader.sh_size = SHeader.sh_entsize * Section.Members.size();
710
711   unsigned SymIdx;
712   if (!SymN2I.lookup(Section.Signature, SymIdx) &&
713       !to_integer(Section.Signature, SymIdx)) {
714     WithColor::error() << "Unknown symbol referenced: '" << Section.Signature
715                        << "' at YAML section '" << Section.Name << "'.\n";
716     return false;
717   }
718   SHeader.sh_info = SymIdx;
719
720   raw_ostream &OS =
721       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
722
723   for (const ELFYAML::SectionOrType &Member : Section.Members) {
724     unsigned int SectionIndex = 0;
725     if (Member.sectionNameOrType == "GRP_COMDAT")
726       SectionIndex = llvm::ELF::GRP_COMDAT;
727     else if (!convertSectionIndex(SN2I, Section.Name, Member.sectionNameOrType,
728                                   SectionIndex))
729       return false;
730     support::endian::write<uint32_t>(OS, SectionIndex, ELFT::TargetEndianness);
731   }
732   return true;
733 }
734
735 template <class ELFT>
736 bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
737                                          const ELFYAML::SymverSection &Section,
738                                          ContiguousBlobAccumulator &CBA) {
739   raw_ostream &OS =
740       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
741   for (uint16_t Version : Section.Entries)
742     support::endian::write<uint16_t>(OS, Version, ELFT::TargetEndianness);
743
744   SHeader.sh_entsize = 2;
745   SHeader.sh_size = Section.Entries.size() * SHeader.sh_entsize;
746   return true;
747 }
748
749 template <class ELFT>
750 bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
751                                          const ELFYAML::VerdefSection &Section,
752                                          ContiguousBlobAccumulator &CBA) {
753   typedef typename ELFT::Verdef Elf_Verdef;
754   typedef typename ELFT::Verdaux Elf_Verdaux;
755   raw_ostream &OS =
756       CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
757
758   uint64_t AuxCnt = 0;
759   for (size_t I = 0; I < Section.Entries.size(); ++I) {
760     const ELFYAML::VerdefEntry &E = Section.Entries[I];
761
762     Elf_Verdef VerDef;
763     VerDef.vd_version = E.Version;
764     VerDef.vd_flags = E.Flags;
765     VerDef.vd_ndx = E.VersionNdx;
766     VerDef.vd_hash = E.Hash;
767     VerDef.vd_aux = sizeof(Elf_Verdef);
768     VerDef.vd_cnt = E.VerNames.size();
769     if (I == Section.Entries.size() - 1)
770       VerDef.vd_next = 0;
771     else
772       VerDef.vd_next =
773           sizeof(Elf_Verdef) + E.VerNames.size() * sizeof(Elf_Verdaux);
774     OS.write((const char *)&VerDef, sizeof(Elf_Verdef));
775
776     for (size_t J = 0; J < E.VerNames.size(); ++J, ++AuxCnt) {
777       Elf_Verdaux VernAux;
778       VernAux.vda_name = DotDynstr.getOffset(E.VerNames[J]);
779       if (J == E.VerNames.size() - 1)
780         VernAux.vda_next = 0;
781       else
782         VernAux.vda_next = sizeof(Elf_Verdaux);
783       OS.write((const char *)&VernAux, sizeof(Elf_Verdaux));
784     }
785   }
786
787   SHeader.sh_size = Section.Entries.size() * sizeof(Elf_Verdef) +
788                     AuxCnt * sizeof(Elf_Verdaux);
789   SHeader.sh_info = Section.Info;
790
791   return true;
792 }
793
794 template <class ELFT>
795 bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
796                                          const ELFYAML::VerneedSection &Section,
797                                          ContiguousBlobAccumulator &CBA) {
798   typedef typename ELFT::Verneed Elf_Verneed;
799   typedef typename ELFT::Vernaux Elf_Vernaux;
800
801   auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
802
803   uint64_t AuxCnt = 0;
804   for (size_t I = 0; I < Section.VerneedV.size(); ++I) {
805     const ELFYAML::VerneedEntry &VE = Section.VerneedV[I];
806
807     Elf_Verneed VerNeed;
808     VerNeed.vn_version = VE.Version;
809     VerNeed.vn_file = DotDynstr.getOffset(VE.File);
810     if (I == Section.VerneedV.size() - 1)
811       VerNeed.vn_next = 0;
812     else
813       VerNeed.vn_next =
814           sizeof(Elf_Verneed) + VE.AuxV.size() * sizeof(Elf_Vernaux);
815     VerNeed.vn_cnt = VE.AuxV.size();
816     VerNeed.vn_aux = sizeof(Elf_Verneed);
817     OS.write((const char *)&VerNeed, sizeof(Elf_Verneed));
818
819     for (size_t J = 0; J < VE.AuxV.size(); ++J, ++AuxCnt) {
820       const ELFYAML::VernauxEntry &VAuxE = VE.AuxV[J];
821
822       Elf_Vernaux VernAux;
823       VernAux.vna_hash = VAuxE.Hash;
824       VernAux.vna_flags = VAuxE.Flags;
825       VernAux.vna_other = VAuxE.Other;
826       VernAux.vna_name = DotDynstr.getOffset(VAuxE.Name);
827       if (J == VE.AuxV.size() - 1)
828         VernAux.vna_next = 0;
829       else
830         VernAux.vna_next = sizeof(Elf_Vernaux);
831       OS.write((const char *)&VernAux, sizeof(Elf_Vernaux));
832     }
833   }
834
835   SHeader.sh_size = Section.VerneedV.size() * sizeof(Elf_Verneed) +
836                     AuxCnt * sizeof(Elf_Vernaux);
837   SHeader.sh_info = Section.Info;
838
839   return true;
840 }
841
842 template <class ELFT>
843 bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
844                                          const ELFYAML::MipsABIFlags &Section,
845                                          ContiguousBlobAccumulator &CBA) {
846   assert(Section.Type == llvm::ELF::SHT_MIPS_ABIFLAGS &&
847          "Section type is not SHT_MIPS_ABIFLAGS");
848
849   object::Elf_Mips_ABIFlags<ELFT> Flags;
850   zero(Flags);
851   SHeader.sh_entsize = sizeof(Flags);
852   SHeader.sh_size = SHeader.sh_entsize;
853
854   auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
855   Flags.version = Section.Version;
856   Flags.isa_level = Section.ISALevel;
857   Flags.isa_rev = Section.ISARevision;
858   Flags.gpr_size = Section.GPRSize;
859   Flags.cpr1_size = Section.CPR1Size;
860   Flags.cpr2_size = Section.CPR2Size;
861   Flags.fp_abi = Section.FpABI;
862   Flags.isa_ext = Section.ISAExtension;
863   Flags.ases = Section.ASEs;
864   Flags.flags1 = Section.Flags1;
865   Flags.flags2 = Section.Flags2;
866   OS.write((const char *)&Flags, sizeof(Flags));
867
868   return true;
869 }
870
871 template <class ELFT>
872 bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
873                                          const ELFYAML::DynamicSection &Section,
874                                          ContiguousBlobAccumulator &CBA) {
875   typedef typename ELFT::uint uintX_t;
876
877   assert(Section.Type == llvm::ELF::SHT_DYNAMIC &&
878          "Section type is not SHT_DYNAMIC");
879
880   if (!Section.Entries.empty() && Section.Content) {
881     WithColor::error()
882         << "Cannot specify both raw content and explicit entries "
883            "for dynamic section '"
884         << Section.Name << "'.\n";
885     return false;
886   }
887
888   if (Section.Content)
889     SHeader.sh_size = Section.Content->binary_size();
890   else
891     SHeader.sh_size = 2 * sizeof(uintX_t) * Section.Entries.size();
892   if (Section.EntSize)
893     SHeader.sh_entsize = *Section.EntSize;
894   else
895     SHeader.sh_entsize = sizeof(Elf_Dyn);
896
897   raw_ostream &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
898   for (const ELFYAML::DynamicEntry &DE : Section.Entries) {
899     support::endian::write<uintX_t>(OS, DE.Tag, ELFT::TargetEndianness);
900     support::endian::write<uintX_t>(OS, DE.Val, ELFT::TargetEndianness);
901   }
902   if (Section.Content)
903     Section.Content->writeAsBinary(OS);
904
905   return true;
906 }
907
908 template <class ELFT> bool ELFState<ELFT>::buildSectionIndex() {
909   for (unsigned i = 0, e = Doc.Sections.size(); i != e; ++i) {
910     StringRef Name = Doc.Sections[i]->Name;
911     DotShStrtab.add(dropUniqueSuffix(Name));
912     // "+ 1" to take into account the SHT_NULL entry.
913     if (!SN2I.addName(Name, i + 1)) {
914       WithColor::error() << "Repeated section name: '" << Name
915                          << "' at YAML section number " << i << ".\n";
916       return false;
917     }
918   }
919
920   auto SecNo = 1 + Doc.Sections.size();
921   // Add special sections after input sections, if necessary.
922   for (StringRef Name : implicitSectionNames())
923     if (SN2I.addName(Name, SecNo)) {
924       // Account for this section, since it wasn't in the Doc
925       ++SecNo;
926       DotShStrtab.add(Name);
927     }
928
929   DotShStrtab.finalize();
930   return true;
931 }
932
933 template <class ELFT>
934 bool ELFState<ELFT>::buildSymbolIndex(ArrayRef<ELFYAML::Symbol> Symbols) {
935   bool GlobalSymbolSeen = false;
936   std::size_t I = 0;
937   for (const auto &Sym : Symbols) {
938     ++I;
939
940     StringRef Name = Sym.Name;
941     if (Sym.Binding.value == ELF::STB_LOCAL && GlobalSymbolSeen) {
942       WithColor::error() << "Local symbol '" + Name +
943                                 "' after global in Symbols list.\n";
944       return false;
945     }
946     if (Sym.Binding.value != ELF::STB_LOCAL)
947       GlobalSymbolSeen = true;
948
949     if (!Name.empty() && !SymN2I.addName(Name, I)) {
950       WithColor::error() << "Repeated symbol name: '" << Name << "'.\n";
951       return false;
952     }
953   }
954   return true;
955 }
956
957 template <class ELFT> void ELFState<ELFT>::finalizeStrings() {
958   // Add the regular symbol names to .strtab section.
959   for (const ELFYAML::Symbol &Sym : Doc.Symbols)
960     DotStrtab.add(dropUniqueSuffix(Sym.Name));
961   DotStrtab.finalize();
962
963   // Add the dynamic symbol names to .dynstr section.
964   for (const ELFYAML::Symbol &Sym : Doc.DynamicSymbols)
965     DotDynstr.add(dropUniqueSuffix(Sym.Name));
966
967   // SHT_GNU_verdef and SHT_GNU_verneed sections might also
968   // add strings to .dynstr section.
969   for (const std::unique_ptr<ELFYAML::Section> &Sec : Doc.Sections) {
970     if (auto VerNeed = dyn_cast<ELFYAML::VerneedSection>(Sec.get())) {
971       for (const ELFYAML::VerneedEntry &VE : VerNeed->VerneedV) {
972         DotDynstr.add(VE.File);
973         for (const ELFYAML::VernauxEntry &Aux : VE.AuxV)
974           DotDynstr.add(Aux.Name);
975       }
976     } else if (auto VerDef = dyn_cast<ELFYAML::VerdefSection>(Sec.get())) {
977       for (const ELFYAML::VerdefEntry &E : VerDef->Entries)
978         for (StringRef Name : E.VerNames)
979           DotDynstr.add(Name);
980     }
981   }
982
983   DotDynstr.finalize();
984 }
985
986 template <class ELFT>
987 int ELFState<ELFT>::writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
988   ELFState<ELFT> State(Doc);
989
990   // Finalize .strtab and .dynstr sections. We do that early because want to
991   // finalize the string table builders before writing the content of the
992   // sections that might want to use them.
993   State.finalizeStrings();
994
995   if (!State.buildSectionIndex())
996     return 1;
997
998   if (!State.buildSymbolIndex(Doc.Symbols))
999     return 1;
1000
1001   Elf_Ehdr Header;
1002   State.initELFHeader(Header);
1003
1004   // TODO: Flesh out section header support.
1005
1006   std::vector<Elf_Phdr> PHeaders;
1007   State.initProgramHeaders(PHeaders);
1008
1009   // XXX: This offset is tightly coupled with the order that we write
1010   // things to `OS`.
1011   const size_t SectionContentBeginOffset = Header.e_ehsize +
1012                                            Header.e_phentsize * Header.e_phnum +
1013                                            Header.e_shentsize * Header.e_shnum;
1014   ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
1015
1016   std::vector<Elf_Shdr> SHeaders;
1017   if (!State.initSectionHeaders(State, SHeaders, CBA))
1018     return 1;
1019
1020   // Now we can decide segment offsets
1021   State.setProgramHeaderLayout(PHeaders, SHeaders);
1022
1023   OS.write((const char *)&Header, sizeof(Header));
1024   writeArrayData(OS, makeArrayRef(PHeaders));
1025   writeArrayData(OS, makeArrayRef(SHeaders));
1026   CBA.writeBlobToStream(OS);
1027   return 0;
1028 }
1029
1030 template <class ELFT>
1031 std::vector<StringRef> ELFState<ELFT>::implicitSectionNames() const {
1032   if (Doc.DynamicSymbols.empty())
1033     return {".symtab", ".strtab", ".shstrtab"};
1034   return {".symtab", ".strtab", ".shstrtab", ".dynsym", ".dynstr"};
1035 }
1036
1037 int yaml2elf(llvm::ELFYAML::Object &Doc, raw_ostream &Out) {
1038   bool IsLE = Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
1039   bool Is64Bit = Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
1040   if (Is64Bit) {
1041     if (IsLE)
1042       return ELFState<object::ELF64LE>::writeELF(Out, Doc);
1043     return ELFState<object::ELF64BE>::writeELF(Out, Doc);
1044   }
1045   if (IsLE)
1046     return ELFState<object::ELF32LE>::writeELF(Out, Doc);
1047   return ELFState<object::ELF32BE>::writeELF(Out, Doc);
1048 }