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 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;
181 ELFState(const ELFYAML::Object &D) : Doc(D) {}
184 static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc);
187 void finalizeStrings();
189 } // end anonymous namespace
191 template <class ELFT>
192 void ELFState<ELFT>::initELFHeader(Elf_Ehdr &Header) {
193 using namespace llvm::ELF;
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.
216 sizeof(Header) + sizeof(Elf_Phdr) * Doc.ProgramHeaders.size();
217 Header.e_shnum = SN2I.size() + 1;
218 Header.e_shstrndx = SN2I.get(".shstrtab");
221 template <class ELFT>
222 void ELFState<ELFT>::initProgramHeaders(std::vector<Elf_Phdr> &PHeaders) {
223 for (const auto &YamlPhdr : Doc.ProgramHeaders) {
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);
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";
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)
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,
257 else if (SecName == ".shstrtab")
258 State.initStrtabSectionHeader(Header, SecName, State.DotShStrtab, CBA,
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,
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);
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);
286 for (size_t I = 1; I < Doc.Sections.size() + ImplicitSections.size() + 1; ++I) {
287 Elf_Shdr &SHeader = SHeaders[I];
289 ELFYAML::Section *Sec =
290 I > Doc.Sections.size() ? nullptr : Doc.Sections[I - 1].get();
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
297 Sec ? Sec->Name : ImplicitSections[I - Doc.Sections.size() - 1];
298 if (initImplicitHeader(State, CBA, SHeader, SecName, Sec))
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.");
304 SHeader.sh_name = DotShStrtab.getOffset(SecName);
305 SHeader.sh_type = Sec->Type;
307 SHeader.sh_flags = *Sec->Flags;
308 SHeader.sh_addr = Sec->Address;
309 SHeader.sh_addralign = Sec->AddressAlign;
311 if (!Sec->Link.empty()) {
313 if (!convertSectionIndex(SN2I, Sec->Name, Sec->Link, Index))
315 SHeader.sh_link = Index;
318 if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec)) {
319 if (!writeSectionContent(SHeader, *S, CBA))
321 } else if (auto S = dyn_cast<ELFYAML::RelocationSection>(Sec)) {
322 if (!writeSectionContent(SHeader, *S, CBA))
324 } else if (auto S = dyn_cast<ELFYAML::Group>(Sec)) {
325 if (!writeSectionContent(SHeader, *S, CBA))
327 } else if (auto S = dyn_cast<ELFYAML::MipsABIFlags>(Sec)) {
328 if (!writeSectionContent(SHeader, *S, CBA))
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))
339 } else if (auto S = dyn_cast<ELFYAML::SymverSection>(Sec)) {
340 if (!writeSectionContent(SHeader, *S, CBA))
342 } else if (auto S = dyn_cast<ELFYAML::VerneedSection>(Sec)) {
343 if (!writeSectionContent(SHeader, *S, CBA))
345 } else if (auto S = dyn_cast<ELFYAML::VerdefSection>(Sec)) {
346 if (!writeSectionContent(SHeader, *S, CBA))
349 llvm_unreachable("Unknown section type");
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)
359 return Symbols.size();
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();
373 OS.write_zeros(*RawSec.Size - ContentSize);
377 template <class ELFT>
378 void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
380 ContiguousBlobAccumulator &CBA,
381 ELFYAML::Section *YAMLSec) {
383 bool IsStatic = STType == SymtabType::Static;
384 const auto &Symbols = IsStatic ? Doc.Symbols : Doc.DynamicSymbols;
386 ELFYAML::RawContentSection *RawSec =
387 dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec);
388 if (RawSec && !Symbols.empty() && (RawSec->Content || RawSec->Size)) {
390 WithColor::error() << "Cannot specify both `Content` and " +
391 (IsStatic ? Twine("`Symbols`")
392 : Twine("`DynamicSymbols`")) +
393 " for symbol table section '"
394 << RawSec->Name << "'.\n";
396 WithColor::error() << "Cannot specify both `Size` and " +
397 (IsStatic ? Twine("`Symbols`")
398 : Twine("`DynamicSymbols`")) +
399 " for symbol table section '"
400 << RawSec->Name << "'.\n";
405 SHeader.sh_name = DotShStrtab.getOffset(IsStatic ? ".symtab" : ".dynsym");
408 SHeader.sh_type = YAMLSec->Type;
410 SHeader.sh_type = IsStatic ? ELF::SHT_SYMTAB : ELF::SHT_DYNSYM;
412 if (RawSec && !RawSec->Link.empty()) {
413 // If the Link field is explicitly defined in the document,
416 if (!convertSectionIndex(SN2I, RawSec->Name, RawSec->Link, Index))
418 SHeader.sh_link = Index;
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.
426 Link = SN2I.get(".strtab");
428 SN2I.lookup(".dynstr", Link);
429 SHeader.sh_link = Link;
432 if (YAMLSec && YAMLSec->Flags)
433 SHeader.sh_flags = *YAMLSec->Flags;
435 SHeader.sh_flags = ELF::SHF_ALLOC;
437 // If the symbol table section is explicitly described in the YAML
438 // then we should set the fields requested.
440 RawSec ? (unsigned)RawSec->Info : findFirstNonGlobal(Symbols) + 1;
441 SHeader.sh_entsize = (YAMLSec && YAMLSec->EntSize)
442 ? (uint64_t)(*YAMLSec->EntSize)
444 SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 8;
445 SHeader.sh_addr = YAMLSec ? (uint64_t)YAMLSec->Address : 0;
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);
454 std::vector<Elf_Sym> Syms;
456 // Ensure STN_UNDEF is present
462 addSymbols(Symbols, Syms, IsStatic ? DotStrtab : DotDynstr);
463 writeArrayData(OS, makeArrayRef(Syms));
464 SHeader.sh_size = arrayDataSize(makeArrayRef(Syms));
467 template <class ELFT>
468 void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
469 StringTableBuilder &STB,
470 ContiguousBlobAccumulator &CBA,
471 ELFYAML::Section *YAMLSec) {
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;
477 ELFYAML::RawContentSection *RawSec =
478 dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec);
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);
485 SHeader.sh_size = STB.getSize();
488 if (YAMLSec && YAMLSec->EntSize)
489 SHeader.sh_entsize = *YAMLSec->EntSize;
491 if (YAMLSec && YAMLSec->Flags)
492 SHeader.sh_flags = *YAMLSec->Flags;
493 else if (Name == ".dynstr")
494 SHeader.sh_flags = ELF::SHF_ALLOC;
496 // If the section is explicitly described in the YAML
497 // then we want to use its section address.
499 SHeader.sh_addr = YAMLSec->Address;
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++];
509 std::vector<Elf_Shdr *> Sections;
510 for (const ELFYAML::SectionName &SecName : YamlPhdr.Sections) {
512 if (!SN2I.lookup(SecName.Section, Index)) {
513 WithColor::error() << "Unknown section referenced: '" << SecName.Section
514 << "' by program header.\n";
517 Sections.push_back(&SHeaders[Index]);
520 if (YamlPhdr.Offset) {
521 PHeader.p_offset = *YamlPhdr.Offset;
523 if (YamlPhdr.Sections.size())
524 PHeader.p_offset = UINT32_MAX;
526 PHeader.p_offset = 0;
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);
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;
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;
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;
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;
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;
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;
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);
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) {
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.
589 Symbol.st_name = *Sym.NameIndex;
590 else if (!Sym.Name.empty())
591 Symbol.st_name = Strtab.getOffset(Sym.Name);
593 Symbol.setBindingAndType(Sym.Binding, Sym.Type);
594 if (!Sym.Section.empty()) {
596 if (!SN2I.lookup(Sym.Section, Index)) {
597 WithColor::error() << "Unknown section referenced: '" << Sym.Section
598 << "' by YAML symbol " << Sym.Name << ".\n";
601 Symbol.st_shndx = Index;
602 } else if (Sym.Index) {
603 Symbol.st_shndx = *Sym.Index;
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);
613 template <class ELFT>
614 bool ELFState<ELFT>::writeSectionContent(
615 Elf_Shdr &SHeader, const ELFYAML::RawContentSection &Section,
616 ContiguousBlobAccumulator &CBA) {
618 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
619 SHeader.sh_size = writeRawSectionData(OS, Section);
622 SHeader.sh_entsize = *Section.EntSize;
623 else if (Section.Type == llvm::ELF::SHT_RELR)
624 SHeader.sh_entsize = sizeof(Elf_Relr);
626 SHeader.sh_entsize = 0;
627 SHeader.sh_info = Section.Info;
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);
637 template <class ELFT>
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");
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();
650 // For relocation section set link to .symtab by default.
651 if (Section.Link.empty())
652 SHeader.sh_link = SN2I.get(".symtab");
655 if (!Section.RelocatableSec.empty() &&
656 !convertSectionIndex(SN2I, Section.Name, Section.RelocatableSec, Index))
658 SHeader.sh_info = Index;
660 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
662 for (const auto &Rel : Section.Relocations) {
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";
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));
683 REntry.r_offset = Rel.Offset;
684 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
685 OS.write((const char *)&REntry, sizeof(REntry));
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");
698 SHeader.sh_entsize = 4;
699 SHeader.sh_size = SHeader.sh_entsize * Section.Members.size();
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";
708 SHeader.sh_info = SymIdx;
711 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
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,
720 support::endian::write<uint32_t>(OS, SectionIndex, ELFT::TargetEndianness);
725 template <class ELFT>
726 bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
727 const ELFYAML::SymverSection &Section,
728 ContiguousBlobAccumulator &CBA) {
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);
734 SHeader.sh_entsize = 2;
735 SHeader.sh_size = Section.Entries.size() * SHeader.sh_entsize;
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;
746 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
749 for (size_t I = 0; I < Section.Entries.size(); ++I) {
750 const ELFYAML::VerdefEntry &E = Section.Entries[I];
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)
763 sizeof(Elf_Verdef) + E.VerNames.size() * sizeof(Elf_Verdaux);
764 OS.write((const char *)&VerDef, sizeof(Elf_Verdef));
766 for (size_t J = 0; J < E.VerNames.size(); ++J, ++AuxCnt) {
768 VernAux.vda_name = DotDynstr.getOffset(E.VerNames[J]);
769 if (J == E.VerNames.size() - 1)
770 VernAux.vda_next = 0;
772 VernAux.vda_next = sizeof(Elf_Verdaux);
773 OS.write((const char *)&VernAux, sizeof(Elf_Verdaux));
777 SHeader.sh_size = Section.Entries.size() * sizeof(Elf_Verdef) +
778 AuxCnt * sizeof(Elf_Verdaux);
779 SHeader.sh_info = Section.Info;
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;
791 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
794 for (size_t I = 0; I < Section.VerneedV.size(); ++I) {
795 const ELFYAML::VerneedEntry &VE = Section.VerneedV[I];
798 VerNeed.vn_version = VE.Version;
799 VerNeed.vn_file = DotDynstr.getOffset(VE.File);
800 if (I == Section.VerneedV.size() - 1)
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));
809 for (size_t J = 0; J < VE.AuxV.size(); ++J, ++AuxCnt) {
810 const ELFYAML::VernauxEntry &VAuxE = VE.AuxV[J];
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;
820 VernAux.vna_next = sizeof(Elf_Vernaux);
821 OS.write((const char *)&VernAux, sizeof(Elf_Vernaux));
825 SHeader.sh_size = Section.VerneedV.size() * sizeof(Elf_Verneed) +
826 AuxCnt * sizeof(Elf_Vernaux);
827 SHeader.sh_info = Section.Info;
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");
839 object::Elf_Mips_ABIFlags<ELFT> Flags;
841 SHeader.sh_entsize = sizeof(Flags);
842 SHeader.sh_size = SHeader.sh_entsize;
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));
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;
867 assert(Section.Type == llvm::ELF::SHT_DYNAMIC &&
868 "Section type is not SHT_DYNAMIC");
870 if (!Section.Entries.empty() && Section.Content) {
872 << "Cannot specify both raw content and explicit entries "
873 "for dynamic section '"
874 << Section.Name << "'.\n";
879 SHeader.sh_size = Section.Content->binary_size();
881 SHeader.sh_size = 2 * sizeof(uintX_t) * Section.Entries.size();
883 SHeader.sh_entsize = *Section.EntSize;
885 SHeader.sh_entsize = sizeof(Elf_Dyn);
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);
893 Section.Content->writeAsBinary(OS);
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";
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
916 DotShStrtab.add(Name);
919 DotShStrtab.finalize();
923 template <class ELFT>
924 bool ELFState<ELFT>::buildSymbolIndex(ArrayRef<ELFYAML::Symbol> Symbols) {
925 bool GlobalSymbolSeen = false;
927 for (const auto &Sym : Symbols) {
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";
936 if (Sym.Binding.value != ELF::STB_LOCAL)
937 GlobalSymbolSeen = true;
939 if (!Name.empty() && !SymN2I.addName(Name, I)) {
940 WithColor::error() << "Repeated symbol name: '" << Name << "'.\n";
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();
953 // Add the dynamic symbol names to .dynstr section.
954 for (const ELFYAML::Symbol &Sym : Doc.DynamicSymbols)
955 DotDynstr.add(Sym.Name);
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);
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)
973 DotDynstr.finalize();
976 template <class ELFT>
977 int ELFState<ELFT>::writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
978 ELFState<ELFT> State(Doc);
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();
985 if (!State.buildSectionIndex())
988 if (!State.buildSymbolIndex(Doc.Symbols))
992 State.initELFHeader(Header);
994 // TODO: Flesh out section header support.
996 std::vector<Elf_Phdr> PHeaders;
997 State.initProgramHeaders(PHeaders);
999 // XXX: This offset is tightly coupled with the order that we write
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);
1006 std::vector<Elf_Shdr> SHeaders;
1007 if (!State.initSectionHeaders(State, SHeaders, CBA))
1010 // Now we can decide segment offsets
1011 State.setProgramHeaderLayout(PHeaders, SHeaders);
1013 OS.write((const char *)&Header, sizeof(Header));
1014 writeArrayData(OS, makeArrayRef(PHeaders));
1015 writeArrayData(OS, makeArrayRef(SHeaders));
1016 CBA.writeBlobToStream(OS);
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"};
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);
1032 return ELFState<object::ELF64LE>::writeELF(Out, Doc);
1033 return ELFState<object::ELF64BE>::writeELF(Out, Doc);
1036 return ELFState<object::ELF32LE>::writeELF(Out, Doc);
1037 return ELFState<object::ELF32BE>::writeELF(Out, Doc);