OSDN Git Service

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