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