1 //===- yaml2elf - Convert YAML to a ELF object file -----------------------===//
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
7 //===----------------------------------------------------------------------===//
10 /// The ELF component of yaml2obj.
12 //===----------------------------------------------------------------------===//
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"
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
32 class ContiguousBlobAccumulator {
33 const uint64_t InitialOffset;
34 SmallVector<char, 128> Buf;
35 raw_svector_ostream OS;
37 /// \returns The new offset.
38 uint64_t padToAlignment(unsigned Align) {
41 uint64_t CurrentOffset = InitialOffset + OS.tell();
42 uint64_t AlignedOffset = alignTo(CurrentOffset, Align);
43 OS.write_zeros(AlignedOffset - CurrentOffset);
44 return AlignedOffset; // == CurrentOffset;
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);
55 void writeBlobToStream(raw_ostream &Out) { Out << OS.str(); }
57 } // end anonymous namespace
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.
63 StringMap<unsigned> Map;
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;
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);
78 /// Asserts if name is not present in the map.
79 unsigned get(StringRef Name) const {
81 if (lookup(Name, Idx))
83 assert(false && "Expected section not found in index");
86 unsigned size() const { return Map.size(); }
88 } // end anonymous namespace
91 static size_t arrayDataSize(ArrayRef<T> A) {
92 return A.size() * sizeof(T);
96 static void writeArrayData(raw_ostream &OS, ArrayRef<T> A) {
97 OS.write((const char *)A.data(), arrayDataSize(A));
101 static void zero(T &Obj) {
102 memset(&Obj, 0, sizeof(Obj));
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
109 template <class ELFT>
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;
120 enum class SymtabType { Static, Dynamic };
122 /// The future ".strtab" section.
123 StringTableBuilder DotStrtab{StringTableBuilder::ELF};
125 /// The future ".shstrtab" section.
126 StringTableBuilder DotShStrtab{StringTableBuilder::ELF};
128 /// The future ".dynstr" section.
129 StringTableBuilder DotDynstr{StringTableBuilder::ELF};
133 const ELFYAML::Object &Doc;
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;
179 ELFState(const ELFYAML::Object &D) : Doc(D) {}
182 static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc);
185 void finalizeStrings();
187 } // end anonymous namespace
189 template <class ELFT>
190 void ELFState<ELFT>::initELFHeader(Elf_Ehdr &Header) {
191 using namespace llvm::ELF;
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.
214 sizeof(Header) + sizeof(Elf_Phdr) * Doc.ProgramHeaders.size();
215 Header.e_shnum = SN2I.size() + 1;
216 Header.e_shstrndx = SN2I.get(".shstrtab");
219 template <class ELFT>
220 void ELFState<ELFT>::initProgramHeaders(std::vector<Elf_Phdr> &PHeaders) {
221 for (const auto &YamlPhdr : Doc.ProgramHeaders) {
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);
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";
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)
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,
255 else if (SecName == ".shstrtab")
256 State.initStrtabSectionHeader(Header, SecName, State.DotShStrtab, CBA,
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,
269 static StringRef dropUniqueSuffix(StringRef S) {
270 size_t SuffixPos = S.rfind(" [");
271 if (SuffixPos == StringRef::npos)
273 return S.substr(0, SuffixPos);
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);
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);
291 for (size_t I = 1; I < Doc.Sections.size() + ImplicitSections.size() + 1; ++I) {
292 Elf_Shdr &SHeader = SHeaders[I];
294 ELFYAML::Section *Sec =
295 I > Doc.Sections.size() ? nullptr : Doc.Sections[I - 1].get();
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
302 Sec ? Sec->Name : ImplicitSections[I - Doc.Sections.size() - 1];
303 if (initImplicitHeader(State, CBA, SHeader, SecName, Sec))
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.");
309 SHeader.sh_name = DotShStrtab.getOffset(dropUniqueSuffix(SecName));
310 SHeader.sh_type = Sec->Type;
312 SHeader.sh_flags = *Sec->Flags;
313 SHeader.sh_addr = Sec->Address;
314 SHeader.sh_addralign = Sec->AddressAlign;
316 if (!Sec->Link.empty()) {
318 if (!convertSectionIndex(SN2I, Sec->Name, Sec->Link, Index))
320 SHeader.sh_link = Index;
323 if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec)) {
324 if (!writeSectionContent(SHeader, *S, CBA))
326 } else if (auto S = dyn_cast<ELFYAML::RelocationSection>(Sec)) {
327 if (!writeSectionContent(SHeader, *S, CBA))
329 } else if (auto S = dyn_cast<ELFYAML::Group>(Sec)) {
330 if (!writeSectionContent(SHeader, *S, CBA))
332 } else if (auto S = dyn_cast<ELFYAML::MipsABIFlags>(Sec)) {
333 if (!writeSectionContent(SHeader, *S, CBA))
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))
344 } else if (auto S = dyn_cast<ELFYAML::SymverSection>(Sec)) {
345 if (!writeSectionContent(SHeader, *S, CBA))
347 } else if (auto S = dyn_cast<ELFYAML::VerneedSection>(Sec)) {
348 if (!writeSectionContent(SHeader, *S, CBA))
350 } else if (auto S = dyn_cast<ELFYAML::VerdefSection>(Sec)) {
351 if (!writeSectionContent(SHeader, *S, CBA))
354 llvm_unreachable("Unknown section type");
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)
364 return Symbols.size();
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();
378 OS.write_zeros(*RawSec.Size - ContentSize);
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;
388 std::vector<Elf_Sym> Ret;
389 Ret.resize(Symbols.size() + 1);
392 for (const auto &Sym : Symbols) {
393 Elf_Sym &Symbol = Ret[++I];
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.
399 Symbol.st_name = *Sym.NameIndex;
400 else if (!Sym.Name.empty())
401 Symbol.st_name = Strtab.getOffset(dropUniqueSuffix(Sym.Name));
403 Symbol.setBindingAndType(Sym.Binding, Sym.Type);
404 if (!Sym.Section.empty()) {
406 if (!SN2I.lookup(Sym.Section, Index)) {
407 WithColor::error() << "Unknown section referenced: '" << Sym.Section
408 << "' by YAML symbol " << Sym.Name << ".\n";
411 Symbol.st_shndx = Index;
412 } else if (Sym.Index) {
413 Symbol.st_shndx = *Sym.Index;
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;
424 template <class ELFT>
425 void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
427 ContiguousBlobAccumulator &CBA,
428 ELFYAML::Section *YAMLSec) {
430 bool IsStatic = STType == SymtabType::Static;
431 const auto &Symbols = IsStatic ? Doc.Symbols : Doc.DynamicSymbols;
433 ELFYAML::RawContentSection *RawSec =
434 dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec);
435 if (RawSec && !Symbols.empty() && (RawSec->Content || RawSec->Size)) {
437 WithColor::error() << "Cannot specify both `Content` and " +
438 (IsStatic ? Twine("`Symbols`")
439 : Twine("`DynamicSymbols`")) +
440 " for symbol table section '"
441 << RawSec->Name << "'.\n";
443 WithColor::error() << "Cannot specify both `Size` and " +
444 (IsStatic ? Twine("`Symbols`")
445 : Twine("`DynamicSymbols`")) +
446 " for symbol table section '"
447 << RawSec->Name << "'.\n";
452 SHeader.sh_name = DotShStrtab.getOffset(IsStatic ? ".symtab" : ".dynsym");
455 SHeader.sh_type = YAMLSec->Type;
457 SHeader.sh_type = IsStatic ? ELF::SHT_SYMTAB : ELF::SHT_DYNSYM;
459 if (RawSec && !RawSec->Link.empty()) {
460 // If the Link field is explicitly defined in the document,
463 if (!convertSectionIndex(SN2I, RawSec->Name, RawSec->Link, Index))
465 SHeader.sh_link = Index;
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.
473 Link = SN2I.get(".strtab");
475 SN2I.lookup(".dynstr", Link);
476 SHeader.sh_link = Link;
479 if (YAMLSec && YAMLSec->Flags)
480 SHeader.sh_flags = *YAMLSec->Flags;
482 SHeader.sh_flags = ELF::SHF_ALLOC;
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)
491 SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 8;
492 SHeader.sh_addr = YAMLSec ? (uint64_t)YAMLSec->Address : 0;
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);
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));
507 template <class ELFT>
508 void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
509 StringTableBuilder &STB,
510 ContiguousBlobAccumulator &CBA,
511 ELFYAML::Section *YAMLSec) {
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;
517 ELFYAML::RawContentSection *RawSec =
518 dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec);
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);
525 SHeader.sh_size = STB.getSize();
528 if (YAMLSec && YAMLSec->EntSize)
529 SHeader.sh_entsize = *YAMLSec->EntSize;
531 if (RawSec && RawSec->Info)
532 SHeader.sh_info = *RawSec->Info;
534 if (YAMLSec && YAMLSec->Flags)
535 SHeader.sh_flags = *YAMLSec->Flags;
536 else if (Name == ".dynstr")
537 SHeader.sh_flags = ELF::SHF_ALLOC;
539 // If the section is explicitly described in the YAML
540 // then we want to use its section address.
542 SHeader.sh_addr = YAMLSec->Address;
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++];
552 std::vector<Elf_Shdr *> Sections;
553 for (const ELFYAML::SectionName &SecName : YamlPhdr.Sections) {
555 if (!SN2I.lookup(SecName.Section, Index)) {
556 WithColor::error() << "Unknown section referenced: '" << SecName.Section
557 << "' by program header.\n";
560 Sections.push_back(&SHeaders[Index]);
563 if (YamlPhdr.Offset) {
564 PHeader.p_offset = *YamlPhdr.Offset;
566 if (YamlPhdr.Sections.size())
567 PHeader.p_offset = UINT32_MAX;
569 PHeader.p_offset = 0;
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);
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;
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;
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;
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;
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;
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;
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);
620 template <class ELFT>
621 bool ELFState<ELFT>::writeSectionContent(
622 Elf_Shdr &SHeader, const ELFYAML::RawContentSection &Section,
623 ContiguousBlobAccumulator &CBA) {
625 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
626 SHeader.sh_size = writeRawSectionData(OS, Section);
629 SHeader.sh_entsize = *Section.EntSize;
630 else if (Section.Type == llvm::ELF::SHT_RELR)
631 SHeader.sh_entsize = sizeof(Elf_Relr);
633 SHeader.sh_entsize = 0;
636 SHeader.sh_info = *Section.Info;
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);
647 template <class ELFT>
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");
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();
660 // For relocation section set link to .symtab by default.
661 if (Section.Link.empty())
662 SHeader.sh_link = SN2I.get(".symtab");
665 if (!Section.RelocatableSec.empty() &&
666 !convertSectionIndex(SN2I, Section.Name, Section.RelocatableSec, Index))
668 SHeader.sh_info = Index;
670 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
672 for (const auto &Rel : Section.Relocations) {
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";
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));
693 REntry.r_offset = Rel.Offset;
694 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
695 OS.write((const char *)&REntry, sizeof(REntry));
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");
708 SHeader.sh_entsize = 4;
709 SHeader.sh_size = SHeader.sh_entsize * Section.Members.size();
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";
718 SHeader.sh_info = SymIdx;
721 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
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,
730 support::endian::write<uint32_t>(OS, SectionIndex, ELFT::TargetEndianness);
735 template <class ELFT>
736 bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
737 const ELFYAML::SymverSection &Section,
738 ContiguousBlobAccumulator &CBA) {
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);
744 SHeader.sh_entsize = 2;
745 SHeader.sh_size = Section.Entries.size() * SHeader.sh_entsize;
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;
756 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
759 for (size_t I = 0; I < Section.Entries.size(); ++I) {
760 const ELFYAML::VerdefEntry &E = Section.Entries[I];
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)
773 sizeof(Elf_Verdef) + E.VerNames.size() * sizeof(Elf_Verdaux);
774 OS.write((const char *)&VerDef, sizeof(Elf_Verdef));
776 for (size_t J = 0; J < E.VerNames.size(); ++J, ++AuxCnt) {
778 VernAux.vda_name = DotDynstr.getOffset(E.VerNames[J]);
779 if (J == E.VerNames.size() - 1)
780 VernAux.vda_next = 0;
782 VernAux.vda_next = sizeof(Elf_Verdaux);
783 OS.write((const char *)&VernAux, sizeof(Elf_Verdaux));
787 SHeader.sh_size = Section.Entries.size() * sizeof(Elf_Verdef) +
788 AuxCnt * sizeof(Elf_Verdaux);
789 SHeader.sh_info = Section.Info;
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;
801 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
804 for (size_t I = 0; I < Section.VerneedV.size(); ++I) {
805 const ELFYAML::VerneedEntry &VE = Section.VerneedV[I];
808 VerNeed.vn_version = VE.Version;
809 VerNeed.vn_file = DotDynstr.getOffset(VE.File);
810 if (I == Section.VerneedV.size() - 1)
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));
819 for (size_t J = 0; J < VE.AuxV.size(); ++J, ++AuxCnt) {
820 const ELFYAML::VernauxEntry &VAuxE = VE.AuxV[J];
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;
830 VernAux.vna_next = sizeof(Elf_Vernaux);
831 OS.write((const char *)&VernAux, sizeof(Elf_Vernaux));
835 SHeader.sh_size = Section.VerneedV.size() * sizeof(Elf_Verneed) +
836 AuxCnt * sizeof(Elf_Vernaux);
837 SHeader.sh_info = Section.Info;
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");
849 object::Elf_Mips_ABIFlags<ELFT> Flags;
851 SHeader.sh_entsize = sizeof(Flags);
852 SHeader.sh_size = SHeader.sh_entsize;
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));
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;
877 assert(Section.Type == llvm::ELF::SHT_DYNAMIC &&
878 "Section type is not SHT_DYNAMIC");
880 if (!Section.Entries.empty() && Section.Content) {
882 << "Cannot specify both raw content and explicit entries "
883 "for dynamic section '"
884 << Section.Name << "'.\n";
889 SHeader.sh_size = Section.Content->binary_size();
891 SHeader.sh_size = 2 * sizeof(uintX_t) * Section.Entries.size();
893 SHeader.sh_entsize = *Section.EntSize;
895 SHeader.sh_entsize = sizeof(Elf_Dyn);
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);
903 Section.Content->writeAsBinary(OS);
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";
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
926 DotShStrtab.add(Name);
929 DotShStrtab.finalize();
933 template <class ELFT>
934 bool ELFState<ELFT>::buildSymbolIndex(ArrayRef<ELFYAML::Symbol> Symbols) {
935 bool GlobalSymbolSeen = false;
937 for (const auto &Sym : Symbols) {
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";
946 if (Sym.Binding.value != ELF::STB_LOCAL)
947 GlobalSymbolSeen = true;
949 if (!Name.empty() && !SymN2I.addName(Name, I)) {
950 WithColor::error() << "Repeated symbol name: '" << Name << "'.\n";
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();
963 // Add the dynamic symbol names to .dynstr section.
964 for (const ELFYAML::Symbol &Sym : Doc.DynamicSymbols)
965 DotDynstr.add(dropUniqueSuffix(Sym.Name));
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);
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)
983 DotDynstr.finalize();
986 template <class ELFT>
987 int ELFState<ELFT>::writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
988 ELFState<ELFT> State(Doc);
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();
995 if (!State.buildSectionIndex())
998 if (!State.buildSymbolIndex(Doc.Symbols))
1002 State.initELFHeader(Header);
1004 // TODO: Flesh out section header support.
1006 std::vector<Elf_Phdr> PHeaders;
1007 State.initProgramHeaders(PHeaders);
1009 // XXX: This offset is tightly coupled with the order that we write
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);
1016 std::vector<Elf_Shdr> SHeaders;
1017 if (!State.initSectionHeaders(State, SHeaders, CBA))
1020 // Now we can decide segment offsets
1021 State.setProgramHeaderLayout(PHeaders, SHeaders);
1023 OS.write((const char *)&Header, sizeof(Header));
1024 writeArrayData(OS, makeArrayRef(PHeaders));
1025 writeArrayData(OS, makeArrayRef(SHeaders));
1026 CBA.writeBlobToStream(OS);
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"};
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);
1042 return ELFState<object::ELF64LE>::writeELF(Out, Doc);
1043 return ELFState<object::ELF64BE>::writeELF(Out, Doc);
1046 return ELFState<object::ELF32LE>::writeELF(Out, Doc);
1047 return ELFState<object::ELF32BE>::writeELF(Out, Doc);