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