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/SetVector.h" 17 #include "llvm/ADT/StringSet.h" 18 #include "llvm/BinaryFormat/ELF.h" 19 #include "llvm/MC/StringTableBuilder.h" 20 #include "llvm/Object/ELFObjectFile.h" 21 #include "llvm/ObjectYAML/DWARFEmitter.h" 22 #include "llvm/ObjectYAML/DWARFYAML.h" 23 #include "llvm/ObjectYAML/ELFYAML.h" 24 #include "llvm/ObjectYAML/yaml2obj.h" 25 #include "llvm/Support/EndianStream.h" 26 #include "llvm/Support/Errc.h" 27 #include "llvm/Support/Error.h" 28 #include "llvm/Support/LEB128.h" 29 #include "llvm/Support/MemoryBuffer.h" 30 #include "llvm/Support/WithColor.h" 31 #include "llvm/Support/YAMLTraits.h" 32 #include "llvm/Support/raw_ostream.h" 33 34 using namespace llvm; 35 36 // This class is used to build up a contiguous binary blob while keeping 37 // track of an offset in the output (which notionally begins at 38 // `InitialOffset`). 39 // The blob might be limited to an arbitrary size. All attempts to write data 40 // are ignored and the error condition is remembered once the limit is reached. 41 // Such an approach allows us to simplify the code by delaying error reporting 42 // and doing it at a convenient time. 43 namespace { 44 class ContiguousBlobAccumulator { 45 const uint64_t InitialOffset; 46 const uint64_t MaxSize; 47 48 SmallVector<char, 128> Buf; 49 raw_svector_ostream OS; 50 Error ReachedLimitErr = Error::success(); 51 52 bool checkLimit(uint64_t Size) { 53 if (!ReachedLimitErr && getOffset() + Size <= MaxSize) 54 return true; 55 if (!ReachedLimitErr) 56 ReachedLimitErr = createStringError(errc::invalid_argument, 57 "reached the output size limit"); 58 return false; 59 } 60 61 public: 62 ContiguousBlobAccumulator(uint64_t BaseOffset, uint64_t SizeLimit) 63 : InitialOffset(BaseOffset), MaxSize(SizeLimit), OS(Buf) {} 64 65 uint64_t tell() const { return OS.tell(); } 66 uint64_t getOffset() const { return InitialOffset + OS.tell(); } 67 void writeBlobToStream(raw_ostream &Out) const { Out << OS.str(); } 68 69 Error takeLimitError() { 70 // Request to write 0 bytes to check we did not reach the limit. 71 checkLimit(0); 72 return std::move(ReachedLimitErr); 73 } 74 75 /// \returns The new offset. 76 uint64_t padToAlignment(unsigned Align) { 77 uint64_t CurrentOffset = getOffset(); 78 if (ReachedLimitErr) 79 return CurrentOffset; 80 81 uint64_t AlignedOffset = alignTo(CurrentOffset, Align == 0 ? 1 : Align); 82 uint64_t PaddingSize = AlignedOffset - CurrentOffset; 83 if (!checkLimit(PaddingSize)) 84 return CurrentOffset; 85 86 writeZeros(PaddingSize); 87 return AlignedOffset; 88 } 89 90 raw_ostream *getRawOS(uint64_t Size) { 91 if (checkLimit(Size)) 92 return &OS; 93 return nullptr; 94 } 95 96 void writeAsBinary(const yaml::BinaryRef &Bin, uint64_t N = UINT64_MAX) { 97 if (!checkLimit(Bin.binary_size())) 98 return; 99 Bin.writeAsBinary(OS, N); 100 } 101 102 void writeZeros(uint64_t Num) { 103 if (checkLimit(Num)) 104 OS.write_zeros(Num); 105 } 106 107 void write(const char *Ptr, size_t Size) { 108 if (checkLimit(Size)) 109 OS.write(Ptr, Size); 110 } 111 112 void write(unsigned char C) { 113 if (checkLimit(1)) 114 OS.write(C); 115 } 116 117 unsigned writeULEB128(uint64_t Val) { 118 if (!checkLimit(sizeof(uint64_t))) 119 return 0; 120 return encodeULEB128(Val, OS); 121 } 122 123 template <typename T> void write(T Val, support::endianness E) { 124 if (checkLimit(sizeof(T))) 125 support::endian::write<T>(OS, Val, E); 126 } 127 }; 128 129 // Used to keep track of section and symbol names, so that in the YAML file 130 // sections and symbols can be referenced by name instead of by index. 131 class NameToIdxMap { 132 StringMap<unsigned> Map; 133 134 public: 135 /// \Returns false if name is already present in the map. 136 bool addName(StringRef Name, unsigned Ndx) { 137 return Map.insert({Name, Ndx}).second; 138 } 139 /// \Returns false if name is not present in the map. 140 bool lookup(StringRef Name, unsigned &Idx) const { 141 auto I = Map.find(Name); 142 if (I == Map.end()) 143 return false; 144 Idx = I->getValue(); 145 return true; 146 } 147 /// Asserts if name is not present in the map. 148 unsigned get(StringRef Name) const { 149 unsigned Idx; 150 if (lookup(Name, Idx)) 151 return Idx; 152 assert(false && "Expected section not found in index"); 153 return 0; 154 } 155 unsigned size() const { return Map.size(); } 156 }; 157 158 namespace { 159 struct Fragment { 160 uint64_t Offset; 161 uint64_t Size; 162 uint32_t Type; 163 uint64_t AddrAlign; 164 }; 165 } // namespace 166 167 /// "Single point of truth" for the ELF file construction. 168 /// TODO: This class still has a ways to go before it is truly a "single 169 /// point of truth". 170 template <class ELFT> class ELFState { 171 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT) 172 173 enum class SymtabType { Static, Dynamic }; 174 175 /// The future ".strtab" section. 176 StringTableBuilder DotStrtab{StringTableBuilder::ELF}; 177 178 /// The future ".shstrtab" section. 179 StringTableBuilder DotShStrtab{StringTableBuilder::ELF}; 180 181 /// The future ".dynstr" section. 182 StringTableBuilder DotDynstr{StringTableBuilder::ELF}; 183 184 NameToIdxMap SN2I; 185 NameToIdxMap SymN2I; 186 NameToIdxMap DynSymN2I; 187 ELFYAML::Object &Doc; 188 189 StringSet<> ExcludedSectionHeaders; 190 191 uint64_t LocationCounter = 0; 192 bool HasError = false; 193 yaml::ErrorHandler ErrHandler; 194 void reportError(const Twine &Msg); 195 void reportError(Error Err); 196 197 std::vector<Elf_Sym> toELFSymbols(ArrayRef<ELFYAML::Symbol> Symbols, 198 const StringTableBuilder &Strtab); 199 unsigned toSectionIndex(StringRef S, StringRef LocSec, StringRef LocSym = ""); 200 unsigned toSymbolIndex(StringRef S, StringRef LocSec, bool IsDynamic); 201 202 void buildSectionIndex(); 203 void buildSymbolIndexes(); 204 void initProgramHeaders(std::vector<Elf_Phdr> &PHeaders); 205 bool initImplicitHeader(ContiguousBlobAccumulator &CBA, Elf_Shdr &Header, 206 StringRef SecName, ELFYAML::Section *YAMLSec); 207 void initSectionHeaders(std::vector<Elf_Shdr> &SHeaders, 208 ContiguousBlobAccumulator &CBA); 209 void initSymtabSectionHeader(Elf_Shdr &SHeader, SymtabType STType, 210 ContiguousBlobAccumulator &CBA, 211 ELFYAML::Section *YAMLSec); 212 void initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name, 213 StringTableBuilder &STB, 214 ContiguousBlobAccumulator &CBA, 215 ELFYAML::Section *YAMLSec); 216 void initDWARFSectionHeader(Elf_Shdr &SHeader, StringRef Name, 217 ContiguousBlobAccumulator &CBA, 218 ELFYAML::Section *YAMLSec); 219 void setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders, 220 std::vector<Elf_Shdr> &SHeaders); 221 222 std::vector<Fragment> 223 getPhdrFragments(const ELFYAML::ProgramHeader &Phdr, 224 ArrayRef<typename ELFT::Shdr> SHeaders); 225 226 void finalizeStrings(); 227 void writeELFHeader(raw_ostream &OS, Optional<uint64_t> SHOff); 228 void writeSectionContent(Elf_Shdr &SHeader, 229 const ELFYAML::NoBitsSection &Section, 230 ContiguousBlobAccumulator &CBA); 231 void writeSectionContent(Elf_Shdr &SHeader, 232 const ELFYAML::RawContentSection &Section, 233 ContiguousBlobAccumulator &CBA); 234 void writeSectionContent(Elf_Shdr &SHeader, 235 const ELFYAML::RelocationSection &Section, 236 ContiguousBlobAccumulator &CBA); 237 void writeSectionContent(Elf_Shdr &SHeader, 238 const ELFYAML::RelrSection &Section, 239 ContiguousBlobAccumulator &CBA); 240 void writeSectionContent(Elf_Shdr &SHeader, 241 const ELFYAML::GroupSection &Group, 242 ContiguousBlobAccumulator &CBA); 243 void writeSectionContent(Elf_Shdr &SHeader, 244 const ELFYAML::SymtabShndxSection &Shndx, 245 ContiguousBlobAccumulator &CBA); 246 void writeSectionContent(Elf_Shdr &SHeader, 247 const ELFYAML::SymverSection &Section, 248 ContiguousBlobAccumulator &CBA); 249 void writeSectionContent(Elf_Shdr &SHeader, 250 const ELFYAML::VerneedSection &Section, 251 ContiguousBlobAccumulator &CBA); 252 void writeSectionContent(Elf_Shdr &SHeader, 253 const ELFYAML::VerdefSection &Section, 254 ContiguousBlobAccumulator &CBA); 255 void writeSectionContent(Elf_Shdr &SHeader, 256 const ELFYAML::ARMIndexTableSection &Section, 257 ContiguousBlobAccumulator &CBA); 258 void writeSectionContent(Elf_Shdr &SHeader, 259 const ELFYAML::MipsABIFlags &Section, 260 ContiguousBlobAccumulator &CBA); 261 void writeSectionContent(Elf_Shdr &SHeader, 262 const ELFYAML::DynamicSection &Section, 263 ContiguousBlobAccumulator &CBA); 264 void writeSectionContent(Elf_Shdr &SHeader, 265 const ELFYAML::StackSizesSection &Section, 266 ContiguousBlobAccumulator &CBA); 267 void writeSectionContent(Elf_Shdr &SHeader, 268 const ELFYAML::BBAddrMapSection &Section, 269 ContiguousBlobAccumulator &CBA); 270 void writeSectionContent(Elf_Shdr &SHeader, 271 const ELFYAML::HashSection &Section, 272 ContiguousBlobAccumulator &CBA); 273 void writeSectionContent(Elf_Shdr &SHeader, 274 const ELFYAML::AddrsigSection &Section, 275 ContiguousBlobAccumulator &CBA); 276 void writeSectionContent(Elf_Shdr &SHeader, 277 const ELFYAML::NoteSection &Section, 278 ContiguousBlobAccumulator &CBA); 279 void writeSectionContent(Elf_Shdr &SHeader, 280 const ELFYAML::GnuHashSection &Section, 281 ContiguousBlobAccumulator &CBA); 282 void writeSectionContent(Elf_Shdr &SHeader, 283 const ELFYAML::LinkerOptionsSection &Section, 284 ContiguousBlobAccumulator &CBA); 285 void writeSectionContent(Elf_Shdr &SHeader, 286 const ELFYAML::DependentLibrariesSection &Section, 287 ContiguousBlobAccumulator &CBA); 288 void writeSectionContent(Elf_Shdr &SHeader, 289 const ELFYAML::CallGraphProfileSection &Section, 290 ContiguousBlobAccumulator &CBA); 291 292 void writeFill(ELFYAML::Fill &Fill, ContiguousBlobAccumulator &CBA); 293 294 ELFState(ELFYAML::Object &D, yaml::ErrorHandler EH); 295 296 void assignSectionAddress(Elf_Shdr &SHeader, ELFYAML::Section *YAMLSec); 297 298 DenseMap<StringRef, size_t> buildSectionHeaderReorderMap(); 299 300 BumpPtrAllocator StringAlloc; 301 uint64_t alignToOffset(ContiguousBlobAccumulator &CBA, uint64_t Align, 302 llvm::Optional<llvm::yaml::Hex64> Offset); 303 304 uint64_t getSectionNameOffset(StringRef Name); 305 306 public: 307 static bool writeELF(raw_ostream &OS, ELFYAML::Object &Doc, 308 yaml::ErrorHandler EH, uint64_t MaxSize); 309 }; 310 } // end anonymous namespace 311 312 template <class T> static size_t arrayDataSize(ArrayRef<T> A) { 313 return A.size() * sizeof(T); 314 } 315 316 template <class T> static void writeArrayData(raw_ostream &OS, ArrayRef<T> A) { 317 OS.write((const char *)A.data(), arrayDataSize(A)); 318 } 319 320 template <class T> static void zero(T &Obj) { memset(&Obj, 0, sizeof(Obj)); } 321 322 template <class ELFT> 323 ELFState<ELFT>::ELFState(ELFYAML::Object &D, yaml::ErrorHandler EH) 324 : Doc(D), ErrHandler(EH) { 325 std::vector<ELFYAML::Section *> Sections = Doc.getSections(); 326 // Insert SHT_NULL section implicitly when it is not defined in YAML. 327 if (Sections.empty() || Sections.front()->Type != ELF::SHT_NULL) 328 Doc.Chunks.insert( 329 Doc.Chunks.begin(), 330 std::make_unique<ELFYAML::Section>( 331 ELFYAML::Chunk::ChunkKind::RawContent, /*IsImplicit=*/true)); 332 333 // We add a technical suffix for each unnamed section/fill. It does not affect 334 // the output, but allows us to map them by name in the code and report better 335 // error messages. 336 StringSet<> DocSections; 337 for (size_t I = 0; I < Doc.Chunks.size(); ++I) { 338 const std::unique_ptr<ELFYAML::Chunk> &C = Doc.Chunks[I]; 339 if (C->Name.empty()) { 340 std::string NewName = ELFYAML::appendUniqueSuffix( 341 /*Name=*/"", "index " + Twine(I)); 342 C->Name = StringRef(NewName).copy(StringAlloc); 343 assert(ELFYAML::dropUniqueSuffix(C->Name).empty()); 344 } 345 346 if (!DocSections.insert(C->Name).second) 347 reportError("repeated section/fill name: '" + C->Name + 348 "' at YAML section/fill number " + Twine(I)); 349 } 350 351 std::vector<StringRef> ImplicitSections; 352 if (Doc.DynamicSymbols) 353 ImplicitSections.insert(ImplicitSections.end(), {".dynsym", ".dynstr"}); 354 if (Doc.Symbols) 355 ImplicitSections.push_back(".symtab"); 356 if (Doc.DWARF) 357 for (StringRef DebugSecName : Doc.DWARF->getNonEmptySectionNames()) { 358 std::string SecName = ("." + DebugSecName).str(); 359 ImplicitSections.push_back(StringRef(SecName).copy(StringAlloc)); 360 } 361 ImplicitSections.insert(ImplicitSections.end(), {".strtab"}); 362 if (!Doc.SectionHeaders || !Doc.SectionHeaders->NoHeaders.getValueOr(false)) 363 ImplicitSections.insert(ImplicitSections.end(), {".shstrtab"}); 364 365 // Insert placeholders for implicit sections that are not 366 // defined explicitly in YAML. 367 for (StringRef SecName : ImplicitSections) { 368 if (DocSections.count(SecName)) 369 continue; 370 371 std::unique_ptr<ELFYAML::Chunk> Sec = std::make_unique<ELFYAML::Section>( 372 ELFYAML::Chunk::ChunkKind::RawContent, true /*IsImplicit*/); 373 Sec->Name = SecName; 374 Doc.Chunks.push_back(std::move(Sec)); 375 } 376 } 377 378 template <class ELFT> 379 void ELFState<ELFT>::writeELFHeader(raw_ostream &OS, Optional<uint64_t> SHOff) { 380 using namespace llvm::ELF; 381 382 Elf_Ehdr Header; 383 zero(Header); 384 Header.e_ident[EI_MAG0] = 0x7f; 385 Header.e_ident[EI_MAG1] = 'E'; 386 Header.e_ident[EI_MAG2] = 'L'; 387 Header.e_ident[EI_MAG3] = 'F'; 388 Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32; 389 Header.e_ident[EI_DATA] = Doc.Header.Data; 390 Header.e_ident[EI_VERSION] = EV_CURRENT; 391 Header.e_ident[EI_OSABI] = Doc.Header.OSABI; 392 Header.e_ident[EI_ABIVERSION] = Doc.Header.ABIVersion; 393 Header.e_type = Doc.Header.Type; 394 395 if (Doc.Header.Machine) 396 Header.e_machine = *Doc.Header.Machine; 397 else 398 Header.e_machine = EM_NONE; 399 400 Header.e_version = EV_CURRENT; 401 Header.e_entry = Doc.Header.Entry; 402 Header.e_flags = Doc.Header.Flags; 403 Header.e_ehsize = sizeof(Elf_Ehdr); 404 405 if (Doc.Header.EPhOff) 406 Header.e_phoff = *Doc.Header.EPhOff; 407 else if (!Doc.ProgramHeaders.empty()) 408 Header.e_phoff = sizeof(Header); 409 else 410 Header.e_phoff = 0; 411 412 if (Doc.Header.EPhEntSize) 413 Header.e_phentsize = *Doc.Header.EPhEntSize; 414 else if (!Doc.ProgramHeaders.empty()) 415 Header.e_phentsize = sizeof(Elf_Phdr); 416 else 417 Header.e_phentsize = 0; 418 419 if (Doc.Header.EPhNum) 420 Header.e_phnum = *Doc.Header.EPhNum; 421 else if (!Doc.ProgramHeaders.empty()) 422 Header.e_phnum = Doc.ProgramHeaders.size(); 423 else 424 Header.e_phnum = 0; 425 426 Header.e_shentsize = Doc.Header.EShEntSize ? (uint16_t)*Doc.Header.EShEntSize 427 : sizeof(Elf_Shdr); 428 429 if (Doc.Header.EShOff) 430 Header.e_shoff = *Doc.Header.EShOff; 431 else if (SHOff) 432 Header.e_shoff = *SHOff; 433 else 434 Header.e_shoff = 0; 435 436 if (Doc.Header.EShNum) 437 Header.e_shnum = *Doc.Header.EShNum; 438 else if (!Doc.SectionHeaders || 439 (Doc.SectionHeaders->NoHeaders && !*Doc.SectionHeaders->NoHeaders)) 440 Header.e_shnum = Doc.getSections().size(); 441 else if (!SHOff) 442 Header.e_shnum = 0; 443 else 444 Header.e_shnum = 445 (Doc.SectionHeaders->Sections ? Doc.SectionHeaders->Sections->size() 446 : 0) + 447 /*Null section*/ 1; 448 449 if (Doc.Header.EShStrNdx) 450 Header.e_shstrndx = *Doc.Header.EShStrNdx; 451 else if (SHOff && !ExcludedSectionHeaders.count(".shstrtab")) 452 Header.e_shstrndx = SN2I.get(".shstrtab"); 453 else 454 Header.e_shstrndx = 0; 455 456 OS.write((const char *)&Header, sizeof(Header)); 457 } 458 459 template <class ELFT> 460 void ELFState<ELFT>::initProgramHeaders(std::vector<Elf_Phdr> &PHeaders) { 461 DenseMap<StringRef, ELFYAML::Fill *> NameToFill; 462 DenseMap<StringRef, size_t> NameToIndex; 463 for (size_t I = 0, E = Doc.Chunks.size(); I != E; ++I) { 464 if (auto S = dyn_cast<ELFYAML::Fill>(Doc.Chunks[I].get())) 465 NameToFill[S->Name] = S; 466 NameToIndex[Doc.Chunks[I]->Name] = I + 1; 467 } 468 469 std::vector<ELFYAML::Section *> Sections = Doc.getSections(); 470 for (size_t I = 0, E = Doc.ProgramHeaders.size(); I != E; ++I) { 471 ELFYAML::ProgramHeader &YamlPhdr = Doc.ProgramHeaders[I]; 472 Elf_Phdr Phdr; 473 zero(Phdr); 474 Phdr.p_type = YamlPhdr.Type; 475 Phdr.p_flags = YamlPhdr.Flags; 476 Phdr.p_vaddr = YamlPhdr.VAddr; 477 Phdr.p_paddr = YamlPhdr.PAddr; 478 PHeaders.push_back(Phdr); 479 480 if (!YamlPhdr.FirstSec && !YamlPhdr.LastSec) 481 continue; 482 483 // Get the index of the section, or 0 in the case when the section doesn't exist. 484 size_t First = NameToIndex[*YamlPhdr.FirstSec]; 485 if (!First) 486 reportError("unknown section or fill referenced: '" + *YamlPhdr.FirstSec + 487 "' by the 'FirstSec' key of the program header with index " + 488 Twine(I)); 489 size_t Last = NameToIndex[*YamlPhdr.LastSec]; 490 if (!Last) 491 reportError("unknown section or fill referenced: '" + *YamlPhdr.LastSec + 492 "' by the 'LastSec' key of the program header with index " + 493 Twine(I)); 494 if (!First || !Last) 495 continue; 496 497 if (First > Last) 498 reportError("program header with index " + Twine(I) + 499 ": the section index of " + *YamlPhdr.FirstSec + 500 " is greater than the index of " + *YamlPhdr.LastSec); 501 502 for (size_t I = First; I <= Last; ++I) 503 YamlPhdr.Chunks.push_back(Doc.Chunks[I - 1].get()); 504 } 505 } 506 507 template <class ELFT> 508 unsigned ELFState<ELFT>::toSectionIndex(StringRef S, StringRef LocSec, 509 StringRef LocSym) { 510 assert(LocSec.empty() || LocSym.empty()); 511 512 unsigned Index; 513 if (!SN2I.lookup(S, Index) && !to_integer(S, Index)) { 514 if (!LocSym.empty()) 515 reportError("unknown section referenced: '" + S + "' by YAML symbol '" + 516 LocSym + "'"); 517 else 518 reportError("unknown section referenced: '" + S + "' by YAML section '" + 519 LocSec + "'"); 520 return 0; 521 } 522 523 if (!Doc.SectionHeaders || (Doc.SectionHeaders->NoHeaders && 524 !Doc.SectionHeaders->NoHeaders.getValue())) 525 return Index; 526 527 assert(!Doc.SectionHeaders->NoHeaders.getValueOr(false) || 528 !Doc.SectionHeaders->Sections); 529 size_t FirstExcluded = 530 Doc.SectionHeaders->Sections ? Doc.SectionHeaders->Sections->size() : 0; 531 if (Index >= FirstExcluded) { 532 if (LocSym.empty()) 533 reportError("unable to link '" + LocSec + "' to excluded section '" + S + 534 "'"); 535 else 536 reportError("excluded section referenced: '" + S + "' by symbol '" + 537 LocSym + "'"); 538 } 539 return Index; 540 } 541 542 template <class ELFT> 543 unsigned ELFState<ELFT>::toSymbolIndex(StringRef S, StringRef LocSec, 544 bool IsDynamic) { 545 const NameToIdxMap &SymMap = IsDynamic ? DynSymN2I : SymN2I; 546 unsigned Index; 547 // Here we try to look up S in the symbol table. If it is not there, 548 // treat its value as a symbol index. 549 if (!SymMap.lookup(S, Index) && !to_integer(S, Index)) { 550 reportError("unknown symbol referenced: '" + S + "' by YAML section '" + 551 LocSec + "'"); 552 return 0; 553 } 554 return Index; 555 } 556 557 template <class ELFT> 558 static void overrideFields(ELFYAML::Section *From, typename ELFT::Shdr &To) { 559 if (!From) 560 return; 561 if (From->ShAddrAlign) 562 To.sh_addralign = *From->ShAddrAlign; 563 if (From->ShFlags) 564 To.sh_flags = *From->ShFlags; 565 if (From->ShName) 566 To.sh_name = *From->ShName; 567 if (From->ShOffset) 568 To.sh_offset = *From->ShOffset; 569 if (From->ShSize) 570 To.sh_size = *From->ShSize; 571 if (From->ShType) 572 To.sh_type = *From->ShType; 573 } 574 575 template <class ELFT> 576 bool ELFState<ELFT>::initImplicitHeader(ContiguousBlobAccumulator &CBA, 577 Elf_Shdr &Header, StringRef SecName, 578 ELFYAML::Section *YAMLSec) { 579 // Check if the header was already initialized. 580 if (Header.sh_offset) 581 return false; 582 583 if (SecName == ".symtab") 584 initSymtabSectionHeader(Header, SymtabType::Static, CBA, YAMLSec); 585 else if (SecName == ".strtab") 586 initStrtabSectionHeader(Header, SecName, DotStrtab, CBA, YAMLSec); 587 else if (SecName == ".shstrtab") 588 initStrtabSectionHeader(Header, SecName, DotShStrtab, CBA, YAMLSec); 589 else if (SecName == ".dynsym") 590 initSymtabSectionHeader(Header, SymtabType::Dynamic, CBA, YAMLSec); 591 else if (SecName == ".dynstr") 592 initStrtabSectionHeader(Header, SecName, DotDynstr, CBA, YAMLSec); 593 else if (SecName.startswith(".debug_")) { 594 // If a ".debug_*" section's type is a preserved one, e.g., SHT_DYNAMIC, we 595 // will not treat it as a debug section. 596 if (YAMLSec && !isa<ELFYAML::RawContentSection>(YAMLSec)) 597 return false; 598 initDWARFSectionHeader(Header, SecName, CBA, YAMLSec); 599 } else 600 return false; 601 602 LocationCounter += Header.sh_size; 603 604 // Override section fields if requested. 605 overrideFields<ELFT>(YAMLSec, Header); 606 return true; 607 } 608 609 constexpr char SuffixStart = '('; 610 constexpr char SuffixEnd = ')'; 611 612 std::string llvm::ELFYAML::appendUniqueSuffix(StringRef Name, 613 const Twine &Msg) { 614 // Do not add a space when a Name is empty. 615 std::string Ret = Name.empty() ? "" : Name.str() + ' '; 616 return Ret + (Twine(SuffixStart) + Msg + Twine(SuffixEnd)).str(); 617 } 618 619 StringRef llvm::ELFYAML::dropUniqueSuffix(StringRef S) { 620 if (S.empty() || S.back() != SuffixEnd) 621 return S; 622 623 // A special case for empty names. See appendUniqueSuffix() above. 624 size_t SuffixPos = S.rfind(SuffixStart); 625 if (SuffixPos == 0) 626 return ""; 627 628 if (SuffixPos == StringRef::npos || S[SuffixPos - 1] != ' ') 629 return S; 630 return S.substr(0, SuffixPos - 1); 631 } 632 633 template <class ELFT> 634 uint64_t ELFState<ELFT>::getSectionNameOffset(StringRef Name) { 635 // If a section is excluded from section headers, we do not save its name in 636 // the string table. 637 if (ExcludedSectionHeaders.count(Name)) 638 return 0; 639 return DotShStrtab.getOffset(Name); 640 } 641 642 static uint64_t writeContent(ContiguousBlobAccumulator &CBA, 643 const Optional<yaml::BinaryRef> &Content, 644 const Optional<llvm::yaml::Hex64> &Size) { 645 size_t ContentSize = 0; 646 if (Content) { 647 CBA.writeAsBinary(*Content); 648 ContentSize = Content->binary_size(); 649 } 650 651 if (!Size) 652 return ContentSize; 653 654 CBA.writeZeros(*Size - ContentSize); 655 return *Size; 656 } 657 658 template <class ELFT> 659 void ELFState<ELFT>::initSectionHeaders(std::vector<Elf_Shdr> &SHeaders, 660 ContiguousBlobAccumulator &CBA) { 661 // Ensure SHN_UNDEF entry is present. An all-zero section header is a 662 // valid SHN_UNDEF entry since SHT_NULL == 0. 663 SHeaders.resize(Doc.getSections().size()); 664 665 for (const std::unique_ptr<ELFYAML::Chunk> &D : Doc.Chunks) { 666 if (ELFYAML::Fill *S = dyn_cast<ELFYAML::Fill>(D.get())) { 667 S->Offset = alignToOffset(CBA, /*Align=*/1, S->Offset); 668 writeFill(*S, CBA); 669 LocationCounter += S->Size; 670 continue; 671 } 672 673 ELFYAML::Section *Sec = cast<ELFYAML::Section>(D.get()); 674 bool IsFirstUndefSection = D == Doc.Chunks.front(); 675 if (IsFirstUndefSection && Sec->IsImplicit) 676 continue; 677 678 // We have a few sections like string or symbol tables that are usually 679 // added implicitly to the end. However, if they are explicitly specified 680 // in the YAML, we need to write them here. This ensures the file offset 681 // remains correct. 682 Elf_Shdr &SHeader = SHeaders[SN2I.get(Sec->Name)]; 683 if (initImplicitHeader(CBA, SHeader, Sec->Name, 684 Sec->IsImplicit ? nullptr : Sec)) 685 continue; 686 687 assert(Sec && "It can't be null unless it is an implicit section. But all " 688 "implicit sections should already have been handled above."); 689 690 SHeader.sh_name = 691 getSectionNameOffset(ELFYAML::dropUniqueSuffix(Sec->Name)); 692 SHeader.sh_type = Sec->Type; 693 if (Sec->Flags) 694 SHeader.sh_flags = *Sec->Flags; 695 SHeader.sh_addralign = Sec->AddressAlign; 696 697 // Set the offset for all sections, except the SHN_UNDEF section with index 698 // 0 when not explicitly requested. 699 if (!IsFirstUndefSection || Sec->Offset) 700 SHeader.sh_offset = alignToOffset(CBA, SHeader.sh_addralign, Sec->Offset); 701 702 assignSectionAddress(SHeader, Sec); 703 704 if (Sec->Link) 705 SHeader.sh_link = toSectionIndex(*Sec->Link, Sec->Name); 706 707 if (Sec->EntSize) 708 SHeader.sh_entsize = *Sec->EntSize; 709 else 710 SHeader.sh_entsize = ELFYAML::getDefaultShEntSize<ELFT>( 711 Doc.Header.Machine.getValueOr(ELF::EM_NONE), Sec->Type, Sec->Name); 712 713 if (IsFirstUndefSection) { 714 if (auto RawSec = dyn_cast<ELFYAML::RawContentSection>(Sec)) { 715 // We do not write any content for special SHN_UNDEF section. 716 if (RawSec->Size) 717 SHeader.sh_size = *RawSec->Size; 718 if (RawSec->Info) 719 SHeader.sh_info = *RawSec->Info; 720 } 721 722 LocationCounter += SHeader.sh_size; 723 overrideFields<ELFT>(Sec, SHeader); 724 continue; 725 } 726 727 if (!isa<ELFYAML::NoBitsSection>(Sec) && (Sec->Content || Sec->Size)) 728 SHeader.sh_size = writeContent(CBA, Sec->Content, Sec->Size); 729 730 if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec)) { 731 writeSectionContent(SHeader, *S, CBA); 732 } else if (auto S = dyn_cast<ELFYAML::SymtabShndxSection>(Sec)) { 733 writeSectionContent(SHeader, *S, CBA); 734 } else if (auto S = dyn_cast<ELFYAML::RelocationSection>(Sec)) { 735 writeSectionContent(SHeader, *S, CBA); 736 } else if (auto S = dyn_cast<ELFYAML::RelrSection>(Sec)) { 737 writeSectionContent(SHeader, *S, CBA); 738 } else if (auto S = dyn_cast<ELFYAML::GroupSection>(Sec)) { 739 writeSectionContent(SHeader, *S, CBA); 740 } else if (auto S = dyn_cast<ELFYAML::ARMIndexTableSection>(Sec)) { 741 writeSectionContent(SHeader, *S, CBA); 742 } else if (auto S = dyn_cast<ELFYAML::MipsABIFlags>(Sec)) { 743 writeSectionContent(SHeader, *S, CBA); 744 } else if (auto S = dyn_cast<ELFYAML::NoBitsSection>(Sec)) { 745 writeSectionContent(SHeader, *S, CBA); 746 } else if (auto S = dyn_cast<ELFYAML::DynamicSection>(Sec)) { 747 writeSectionContent(SHeader, *S, CBA); 748 } else if (auto S = dyn_cast<ELFYAML::SymverSection>(Sec)) { 749 writeSectionContent(SHeader, *S, CBA); 750 } else if (auto S = dyn_cast<ELFYAML::VerneedSection>(Sec)) { 751 writeSectionContent(SHeader, *S, CBA); 752 } else if (auto S = dyn_cast<ELFYAML::VerdefSection>(Sec)) { 753 writeSectionContent(SHeader, *S, CBA); 754 } else if (auto S = dyn_cast<ELFYAML::StackSizesSection>(Sec)) { 755 writeSectionContent(SHeader, *S, CBA); 756 } else if (auto S = dyn_cast<ELFYAML::HashSection>(Sec)) { 757 writeSectionContent(SHeader, *S, CBA); 758 } else if (auto S = dyn_cast<ELFYAML::AddrsigSection>(Sec)) { 759 writeSectionContent(SHeader, *S, CBA); 760 } else if (auto S = dyn_cast<ELFYAML::LinkerOptionsSection>(Sec)) { 761 writeSectionContent(SHeader, *S, CBA); 762 } else if (auto S = dyn_cast<ELFYAML::NoteSection>(Sec)) { 763 writeSectionContent(SHeader, *S, CBA); 764 } else if (auto S = dyn_cast<ELFYAML::GnuHashSection>(Sec)) { 765 writeSectionContent(SHeader, *S, CBA); 766 } else if (auto S = dyn_cast<ELFYAML::DependentLibrariesSection>(Sec)) { 767 writeSectionContent(SHeader, *S, CBA); 768 } else if (auto S = dyn_cast<ELFYAML::CallGraphProfileSection>(Sec)) { 769 writeSectionContent(SHeader, *S, CBA); 770 } else if (auto S = dyn_cast<ELFYAML::BBAddrMapSection>(Sec)) { 771 writeSectionContent(SHeader, *S, CBA); 772 } else { 773 llvm_unreachable("Unknown section type"); 774 } 775 776 LocationCounter += SHeader.sh_size; 777 778 // Override section fields if requested. 779 overrideFields<ELFT>(Sec, SHeader); 780 } 781 } 782 783 template <class ELFT> 784 void ELFState<ELFT>::assignSectionAddress(Elf_Shdr &SHeader, 785 ELFYAML::Section *YAMLSec) { 786 if (YAMLSec && YAMLSec->Address) { 787 SHeader.sh_addr = *YAMLSec->Address; 788 LocationCounter = *YAMLSec->Address; 789 return; 790 } 791 792 // sh_addr represents the address in the memory image of a process. Sections 793 // in a relocatable object file or non-allocatable sections do not need 794 // sh_addr assignment. 795 if (Doc.Header.Type.value == ELF::ET_REL || 796 !(SHeader.sh_flags & ELF::SHF_ALLOC)) 797 return; 798 799 LocationCounter = 800 alignTo(LocationCounter, SHeader.sh_addralign ? SHeader.sh_addralign : 1); 801 SHeader.sh_addr = LocationCounter; 802 } 803 804 static size_t findFirstNonGlobal(ArrayRef<ELFYAML::Symbol> Symbols) { 805 for (size_t I = 0; I < Symbols.size(); ++I) 806 if (Symbols[I].Binding.value != ELF::STB_LOCAL) 807 return I; 808 return Symbols.size(); 809 } 810 811 template <class ELFT> 812 std::vector<typename ELFT::Sym> 813 ELFState<ELFT>::toELFSymbols(ArrayRef<ELFYAML::Symbol> Symbols, 814 const StringTableBuilder &Strtab) { 815 std::vector<Elf_Sym> Ret; 816 Ret.resize(Symbols.size() + 1); 817 818 size_t I = 0; 819 for (const ELFYAML::Symbol &Sym : Symbols) { 820 Elf_Sym &Symbol = Ret[++I]; 821 822 // If NameIndex, which contains the name offset, is explicitly specified, we 823 // use it. This is useful for preparing broken objects. Otherwise, we add 824 // the specified Name to the string table builder to get its offset. 825 if (Sym.StName) 826 Symbol.st_name = *Sym.StName; 827 else if (!Sym.Name.empty()) 828 Symbol.st_name = Strtab.getOffset(ELFYAML::dropUniqueSuffix(Sym.Name)); 829 830 Symbol.setBindingAndType(Sym.Binding, Sym.Type); 831 if (Sym.Section) 832 Symbol.st_shndx = toSectionIndex(*Sym.Section, "", Sym.Name); 833 else if (Sym.Index) 834 Symbol.st_shndx = *Sym.Index; 835 836 Symbol.st_value = Sym.Value.getValueOr(yaml::Hex64(0)); 837 Symbol.st_other = Sym.Other ? *Sym.Other : 0; 838 Symbol.st_size = Sym.Size.getValueOr(yaml::Hex64(0)); 839 } 840 841 return Ret; 842 } 843 844 template <class ELFT> 845 void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader, 846 SymtabType STType, 847 ContiguousBlobAccumulator &CBA, 848 ELFYAML::Section *YAMLSec) { 849 850 bool IsStatic = STType == SymtabType::Static; 851 ArrayRef<ELFYAML::Symbol> Symbols; 852 if (IsStatic && Doc.Symbols) 853 Symbols = *Doc.Symbols; 854 else if (!IsStatic && Doc.DynamicSymbols) 855 Symbols = *Doc.DynamicSymbols; 856 857 ELFYAML::RawContentSection *RawSec = 858 dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec); 859 if (RawSec && (RawSec->Content || RawSec->Size)) { 860 bool HasSymbolsDescription = 861 (IsStatic && Doc.Symbols) || (!IsStatic && Doc.DynamicSymbols); 862 if (HasSymbolsDescription) { 863 StringRef Property = (IsStatic ? "`Symbols`" : "`DynamicSymbols`"); 864 if (RawSec->Content) 865 reportError("cannot specify both `Content` and " + Property + 866 " for symbol table section '" + RawSec->Name + "'"); 867 if (RawSec->Size) 868 reportError("cannot specify both `Size` and " + Property + 869 " for symbol table section '" + RawSec->Name + "'"); 870 return; 871 } 872 } 873 874 zero(SHeader); 875 SHeader.sh_name = getSectionNameOffset(IsStatic ? ".symtab" : ".dynsym"); 876 877 if (YAMLSec) 878 SHeader.sh_type = YAMLSec->Type; 879 else 880 SHeader.sh_type = IsStatic ? ELF::SHT_SYMTAB : ELF::SHT_DYNSYM; 881 882 if (RawSec && RawSec->Link) { 883 // If the Link field is explicitly defined in the document, 884 // we should use it. 885 SHeader.sh_link = toSectionIndex(*RawSec->Link, RawSec->Name); 886 } else { 887 // When we describe the .dynsym section in the document explicitly, it is 888 // allowed to omit the "DynamicSymbols" tag. In this case .dynstr is not 889 // added implicitly and we should be able to leave the Link zeroed if 890 // .dynstr is not defined. 891 unsigned Link = 0; 892 if (IsStatic) { 893 if (!ExcludedSectionHeaders.count(".strtab")) 894 Link = SN2I.get(".strtab"); 895 } else { 896 if (!ExcludedSectionHeaders.count(".dynstr")) 897 SN2I.lookup(".dynstr", Link); 898 } 899 SHeader.sh_link = Link; 900 } 901 902 if (YAMLSec && YAMLSec->Flags) 903 SHeader.sh_flags = *YAMLSec->Flags; 904 else if (!IsStatic) 905 SHeader.sh_flags = ELF::SHF_ALLOC; 906 907 // If the symbol table section is explicitly described in the YAML 908 // then we should set the fields requested. 909 SHeader.sh_info = (RawSec && RawSec->Info) ? (unsigned)(*RawSec->Info) 910 : findFirstNonGlobal(Symbols) + 1; 911 SHeader.sh_entsize = (YAMLSec && YAMLSec->EntSize) 912 ? (uint64_t)(*YAMLSec->EntSize) 913 : sizeof(Elf_Sym); 914 SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 8; 915 916 assignSectionAddress(SHeader, YAMLSec); 917 918 SHeader.sh_offset = 919 alignToOffset(CBA, SHeader.sh_addralign, RawSec ? RawSec->Offset : None); 920 921 if (RawSec && (RawSec->Content || RawSec->Size)) { 922 assert(Symbols.empty()); 923 SHeader.sh_size = writeContent(CBA, RawSec->Content, RawSec->Size); 924 return; 925 } 926 927 std::vector<Elf_Sym> Syms = 928 toELFSymbols(Symbols, IsStatic ? DotStrtab : DotDynstr); 929 SHeader.sh_size = Syms.size() * sizeof(Elf_Sym); 930 CBA.write((const char *)Syms.data(), SHeader.sh_size); 931 } 932 933 template <class ELFT> 934 void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name, 935 StringTableBuilder &STB, 936 ContiguousBlobAccumulator &CBA, 937 ELFYAML::Section *YAMLSec) { 938 zero(SHeader); 939 SHeader.sh_name = getSectionNameOffset(Name); 940 SHeader.sh_type = YAMLSec ? YAMLSec->Type : ELF::SHT_STRTAB; 941 SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 1; 942 943 ELFYAML::RawContentSection *RawSec = 944 dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec); 945 946 SHeader.sh_offset = alignToOffset(CBA, SHeader.sh_addralign, 947 YAMLSec ? YAMLSec->Offset : None); 948 949 if (RawSec && (RawSec->Content || RawSec->Size)) { 950 SHeader.sh_size = writeContent(CBA, RawSec->Content, RawSec->Size); 951 } else { 952 if (raw_ostream *OS = CBA.getRawOS(STB.getSize())) 953 STB.write(*OS); 954 SHeader.sh_size = STB.getSize(); 955 } 956 957 if (YAMLSec && YAMLSec->EntSize) 958 SHeader.sh_entsize = *YAMLSec->EntSize; 959 960 if (RawSec && RawSec->Info) 961 SHeader.sh_info = *RawSec->Info; 962 963 if (YAMLSec && YAMLSec->Flags) 964 SHeader.sh_flags = *YAMLSec->Flags; 965 else if (Name == ".dynstr") 966 SHeader.sh_flags = ELF::SHF_ALLOC; 967 968 assignSectionAddress(SHeader, YAMLSec); 969 } 970 971 static bool shouldEmitDWARF(DWARFYAML::Data &DWARF, StringRef Name) { 972 SetVector<StringRef> DebugSecNames = DWARF.getNonEmptySectionNames(); 973 return Name.consume_front(".") && DebugSecNames.count(Name); 974 } 975 976 template <class ELFT> 977 Expected<uint64_t> emitDWARF(typename ELFT::Shdr &SHeader, StringRef Name, 978 const DWARFYAML::Data &DWARF, 979 ContiguousBlobAccumulator &CBA) { 980 // We are unable to predict the size of debug data, so we request to write 0 981 // bytes. This should always return us an output stream unless CBA is already 982 // in an error state. 983 raw_ostream *OS = CBA.getRawOS(0); 984 if (!OS) 985 return 0; 986 987 uint64_t BeginOffset = CBA.tell(); 988 989 auto EmitFunc = DWARFYAML::getDWARFEmitterByName(Name.substr(1)); 990 if (Error Err = EmitFunc(*OS, DWARF)) 991 return std::move(Err); 992 993 return CBA.tell() - BeginOffset; 994 } 995 996 template <class ELFT> 997 void ELFState<ELFT>::initDWARFSectionHeader(Elf_Shdr &SHeader, StringRef Name, 998 ContiguousBlobAccumulator &CBA, 999 ELFYAML::Section *YAMLSec) { 1000 zero(SHeader); 1001 SHeader.sh_name = getSectionNameOffset(ELFYAML::dropUniqueSuffix(Name)); 1002 SHeader.sh_type = YAMLSec ? YAMLSec->Type : ELF::SHT_PROGBITS; 1003 SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 1; 1004 SHeader.sh_offset = alignToOffset(CBA, SHeader.sh_addralign, 1005 YAMLSec ? YAMLSec->Offset : None); 1006 1007 ELFYAML::RawContentSection *RawSec = 1008 dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec); 1009 if (Doc.DWARF && shouldEmitDWARF(*Doc.DWARF, Name)) { 1010 if (RawSec && (RawSec->Content || RawSec->Size)) 1011 reportError("cannot specify section '" + Name + 1012 "' contents in the 'DWARF' entry and the 'Content' " 1013 "or 'Size' in the 'Sections' entry at the same time"); 1014 else { 1015 if (Expected<uint64_t> ShSizeOrErr = 1016 emitDWARF<ELFT>(SHeader, Name, *Doc.DWARF, CBA)) 1017 SHeader.sh_size = *ShSizeOrErr; 1018 else 1019 reportError(ShSizeOrErr.takeError()); 1020 } 1021 } else if (RawSec) 1022 SHeader.sh_size = writeContent(CBA, RawSec->Content, RawSec->Size); 1023 else 1024 llvm_unreachable("debug sections can only be initialized via the 'DWARF' " 1025 "entry or a RawContentSection"); 1026 1027 if (YAMLSec && YAMLSec->EntSize) 1028 SHeader.sh_entsize = *YAMLSec->EntSize; 1029 else if (Name == ".debug_str") 1030 SHeader.sh_entsize = 1; 1031 1032 if (RawSec && RawSec->Info) 1033 SHeader.sh_info = *RawSec->Info; 1034 1035 if (YAMLSec && YAMLSec->Flags) 1036 SHeader.sh_flags = *YAMLSec->Flags; 1037 else if (Name == ".debug_str") 1038 SHeader.sh_flags = ELF::SHF_MERGE | ELF::SHF_STRINGS; 1039 1040 if (YAMLSec && YAMLSec->Link) 1041 SHeader.sh_link = toSectionIndex(*YAMLSec->Link, Name); 1042 1043 assignSectionAddress(SHeader, YAMLSec); 1044 } 1045 1046 template <class ELFT> void ELFState<ELFT>::reportError(const Twine &Msg) { 1047 ErrHandler(Msg); 1048 HasError = true; 1049 } 1050 1051 template <class ELFT> void ELFState<ELFT>::reportError(Error Err) { 1052 handleAllErrors(std::move(Err), [&](const ErrorInfoBase &Err) { 1053 reportError(Err.message()); 1054 }); 1055 } 1056 1057 template <class ELFT> 1058 std::vector<Fragment> 1059 ELFState<ELFT>::getPhdrFragments(const ELFYAML::ProgramHeader &Phdr, 1060 ArrayRef<Elf_Shdr> SHeaders) { 1061 std::vector<Fragment> Ret; 1062 for (const ELFYAML::Chunk *C : Phdr.Chunks) { 1063 if (const ELFYAML::Fill *F = dyn_cast<ELFYAML::Fill>(C)) { 1064 Ret.push_back({*F->Offset, F->Size, llvm::ELF::SHT_PROGBITS, 1065 /*ShAddrAlign=*/1}); 1066 continue; 1067 } 1068 1069 const ELFYAML::Section *S = cast<ELFYAML::Section>(C); 1070 const Elf_Shdr &H = SHeaders[SN2I.get(S->Name)]; 1071 Ret.push_back({H.sh_offset, H.sh_size, H.sh_type, H.sh_addralign}); 1072 } 1073 return Ret; 1074 } 1075 1076 template <class ELFT> 1077 void ELFState<ELFT>::setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders, 1078 std::vector<Elf_Shdr> &SHeaders) { 1079 uint32_t PhdrIdx = 0; 1080 for (auto &YamlPhdr : Doc.ProgramHeaders) { 1081 Elf_Phdr &PHeader = PHeaders[PhdrIdx++]; 1082 std::vector<Fragment> Fragments = getPhdrFragments(YamlPhdr, SHeaders); 1083 if (!llvm::is_sorted(Fragments, [](const Fragment &A, const Fragment &B) { 1084 return A.Offset < B.Offset; 1085 })) 1086 reportError("sections in the program header with index " + 1087 Twine(PhdrIdx) + " are not sorted by their file offset"); 1088 1089 if (YamlPhdr.Offset) { 1090 if (!Fragments.empty() && *YamlPhdr.Offset > Fragments.front().Offset) 1091 reportError("'Offset' for segment with index " + Twine(PhdrIdx) + 1092 " must be less than or equal to the minimum file offset of " 1093 "all included sections (0x" + 1094 Twine::utohexstr(Fragments.front().Offset) + ")"); 1095 PHeader.p_offset = *YamlPhdr.Offset; 1096 } else if (!Fragments.empty()) { 1097 PHeader.p_offset = Fragments.front().Offset; 1098 } 1099 1100 // Set the file size if not set explicitly. 1101 if (YamlPhdr.FileSize) { 1102 PHeader.p_filesz = *YamlPhdr.FileSize; 1103 } else if (!Fragments.empty()) { 1104 uint64_t FileSize = Fragments.back().Offset - PHeader.p_offset; 1105 // SHT_NOBITS sections occupy no physical space in a file, we should not 1106 // take their sizes into account when calculating the file size of a 1107 // segment. 1108 if (Fragments.back().Type != llvm::ELF::SHT_NOBITS) 1109 FileSize += Fragments.back().Size; 1110 PHeader.p_filesz = FileSize; 1111 } 1112 1113 // Find the maximum offset of the end of a section in order to set p_memsz. 1114 uint64_t MemOffset = PHeader.p_offset; 1115 for (const Fragment &F : Fragments) 1116 MemOffset = std::max(MemOffset, F.Offset + F.Size); 1117 // Set the memory size if not set explicitly. 1118 PHeader.p_memsz = YamlPhdr.MemSize ? uint64_t(*YamlPhdr.MemSize) 1119 : MemOffset - PHeader.p_offset; 1120 1121 if (YamlPhdr.Align) { 1122 PHeader.p_align = *YamlPhdr.Align; 1123 } else { 1124 // Set the alignment of the segment to be the maximum alignment of the 1125 // sections so that by default the segment has a valid and sensible 1126 // alignment. 1127 PHeader.p_align = 1; 1128 for (const Fragment &F : Fragments) 1129 PHeader.p_align = std::max((uint64_t)PHeader.p_align, F.AddrAlign); 1130 } 1131 } 1132 } 1133 1134 bool llvm::ELFYAML::shouldAllocateFileSpace( 1135 ArrayRef<ELFYAML::ProgramHeader> Phdrs, const ELFYAML::NoBitsSection &S) { 1136 for (const ELFYAML::ProgramHeader &PH : Phdrs) { 1137 auto It = llvm::find_if( 1138 PH.Chunks, [&](ELFYAML::Chunk *C) { return C->Name == S.Name; }); 1139 if (std::any_of(It, PH.Chunks.end(), [](ELFYAML::Chunk *C) { 1140 return (isa<ELFYAML::Fill>(C) || 1141 cast<ELFYAML::Section>(C)->Type != ELF::SHT_NOBITS); 1142 })) 1143 return true; 1144 } 1145 return false; 1146 } 1147 1148 template <class ELFT> 1149 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader, 1150 const ELFYAML::NoBitsSection &S, 1151 ContiguousBlobAccumulator &CBA) { 1152 if (!S.Size) 1153 return; 1154 1155 SHeader.sh_size = *S.Size; 1156 1157 // When a nobits section is followed by a non-nobits section or fill 1158 // in the same segment, we allocate the file space for it. This behavior 1159 // matches linkers. 1160 if (shouldAllocateFileSpace(Doc.ProgramHeaders, S)) 1161 CBA.writeZeros(*S.Size); 1162 } 1163 1164 template <class ELFT> 1165 void ELFState<ELFT>::writeSectionContent( 1166 Elf_Shdr &SHeader, const ELFYAML::RawContentSection &Section, 1167 ContiguousBlobAccumulator &CBA) { 1168 if (Section.Info) 1169 SHeader.sh_info = *Section.Info; 1170 } 1171 1172 static bool isMips64EL(const ELFYAML::Object &Obj) { 1173 return Obj.getMachine() == llvm::ELF::EM_MIPS && 1174 Obj.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64) && 1175 Obj.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB); 1176 } 1177 1178 template <class ELFT> 1179 void ELFState<ELFT>::writeSectionContent( 1180 Elf_Shdr &SHeader, const ELFYAML::RelocationSection &Section, 1181 ContiguousBlobAccumulator &CBA) { 1182 assert((Section.Type == llvm::ELF::SHT_REL || 1183 Section.Type == llvm::ELF::SHT_RELA) && 1184 "Section type is not SHT_REL nor SHT_RELA"); 1185 1186 // For relocation section set link to .symtab by default. 1187 unsigned Link = 0; 1188 if (!Section.Link && !ExcludedSectionHeaders.count(".symtab") && 1189 SN2I.lookup(".symtab", Link)) 1190 SHeader.sh_link = Link; 1191 1192 if (!Section.RelocatableSec.empty()) 1193 SHeader.sh_info = toSectionIndex(Section.RelocatableSec, Section.Name); 1194 1195 if (!Section.Relocations) 1196 return; 1197 1198 const bool IsRela = Section.Type == llvm::ELF::SHT_RELA; 1199 for (const ELFYAML::Relocation &Rel : *Section.Relocations) { 1200 const bool IsDynamic = Section.Link && (*Section.Link == ".dynsym"); 1201 unsigned SymIdx = 1202 Rel.Symbol ? toSymbolIndex(*Rel.Symbol, Section.Name, IsDynamic) : 0; 1203 if (IsRela) { 1204 Elf_Rela REntry; 1205 zero(REntry); 1206 REntry.r_offset = Rel.Offset; 1207 REntry.r_addend = Rel.Addend; 1208 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc)); 1209 CBA.write((const char *)&REntry, sizeof(REntry)); 1210 } else { 1211 Elf_Rel REntry; 1212 zero(REntry); 1213 REntry.r_offset = Rel.Offset; 1214 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc)); 1215 CBA.write((const char *)&REntry, sizeof(REntry)); 1216 } 1217 } 1218 1219 SHeader.sh_size = (IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel)) * 1220 Section.Relocations->size(); 1221 } 1222 1223 template <class ELFT> 1224 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader, 1225 const ELFYAML::RelrSection &Section, 1226 ContiguousBlobAccumulator &CBA) { 1227 if (!Section.Entries) 1228 return; 1229 1230 for (llvm::yaml::Hex64 E : *Section.Entries) { 1231 if (!ELFT::Is64Bits && E > UINT32_MAX) 1232 reportError(Section.Name + ": the value is too large for 32-bits: 0x" + 1233 Twine::utohexstr(E)); 1234 CBA.write<uintX_t>(E, ELFT::TargetEndianness); 1235 } 1236 1237 SHeader.sh_size = sizeof(uintX_t) * Section.Entries->size(); 1238 } 1239 1240 template <class ELFT> 1241 void ELFState<ELFT>::writeSectionContent( 1242 Elf_Shdr &SHeader, const ELFYAML::SymtabShndxSection &Shndx, 1243 ContiguousBlobAccumulator &CBA) { 1244 if (Shndx.Content || Shndx.Size) { 1245 SHeader.sh_size = writeContent(CBA, Shndx.Content, Shndx.Size); 1246 return; 1247 } 1248 1249 if (!Shndx.Entries) 1250 return; 1251 1252 for (uint32_t E : *Shndx.Entries) 1253 CBA.write<uint32_t>(E, ELFT::TargetEndianness); 1254 SHeader.sh_size = Shndx.Entries->size() * SHeader.sh_entsize; 1255 } 1256 1257 template <class ELFT> 1258 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader, 1259 const ELFYAML::GroupSection &Section, 1260 ContiguousBlobAccumulator &CBA) { 1261 assert(Section.Type == llvm::ELF::SHT_GROUP && 1262 "Section type is not SHT_GROUP"); 1263 1264 unsigned Link = 0; 1265 if (!Section.Link && !ExcludedSectionHeaders.count(".symtab") && 1266 SN2I.lookup(".symtab", Link)) 1267 SHeader.sh_link = Link; 1268 1269 if (Section.Signature) 1270 SHeader.sh_info = 1271 toSymbolIndex(*Section.Signature, Section.Name, /*IsDynamic=*/false); 1272 1273 if (!Section.Members) 1274 return; 1275 1276 for (const ELFYAML::SectionOrType &Member : *Section.Members) { 1277 unsigned int SectionIndex = 0; 1278 if (Member.sectionNameOrType == "GRP_COMDAT") 1279 SectionIndex = llvm::ELF::GRP_COMDAT; 1280 else 1281 SectionIndex = toSectionIndex(Member.sectionNameOrType, Section.Name); 1282 CBA.write<uint32_t>(SectionIndex, ELFT::TargetEndianness); 1283 } 1284 SHeader.sh_size = SHeader.sh_entsize * Section.Members->size(); 1285 } 1286 1287 template <class ELFT> 1288 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader, 1289 const ELFYAML::SymverSection &Section, 1290 ContiguousBlobAccumulator &CBA) { 1291 unsigned Link = 0; 1292 if (!Section.Link && !ExcludedSectionHeaders.count(".dynsym") && 1293 SN2I.lookup(".dynsym", Link)) 1294 SHeader.sh_link = Link; 1295 1296 if (!Section.Entries) 1297 return; 1298 1299 for (uint16_t Version : *Section.Entries) 1300 CBA.write<uint16_t>(Version, ELFT::TargetEndianness); 1301 SHeader.sh_size = Section.Entries->size() * SHeader.sh_entsize; 1302 } 1303 1304 template <class ELFT> 1305 void ELFState<ELFT>::writeSectionContent( 1306 Elf_Shdr &SHeader, const ELFYAML::StackSizesSection &Section, 1307 ContiguousBlobAccumulator &CBA) { 1308 if (!Section.Entries) 1309 return; 1310 1311 if (!Section.Entries) 1312 return; 1313 1314 for (const ELFYAML::StackSizeEntry &E : *Section.Entries) { 1315 CBA.write<uintX_t>(E.Address, ELFT::TargetEndianness); 1316 SHeader.sh_size += sizeof(uintX_t) + CBA.writeULEB128(E.Size); 1317 } 1318 } 1319 1320 template <class ELFT> 1321 void ELFState<ELFT>::writeSectionContent( 1322 Elf_Shdr &SHeader, const ELFYAML::BBAddrMapSection &Section, 1323 ContiguousBlobAccumulator &CBA) { 1324 if (!Section.Entries) 1325 return; 1326 1327 for (const ELFYAML::BBAddrMapEntry &E : *Section.Entries) { 1328 // Write the address of the function. 1329 CBA.write<uintX_t>(E.Address, ELFT::TargetEndianness); 1330 // Write number of BBEntries (number of basic blocks in the function). 1331 size_t NumBlocks = E.BBEntries ? E.BBEntries->size() : 0; 1332 SHeader.sh_size += sizeof(uintX_t) + CBA.writeULEB128(NumBlocks); 1333 if (!NumBlocks) 1334 continue; 1335 // Write all BBEntries. 1336 for (const ELFYAML::BBAddrMapEntry::BBEntry &BBE : *E.BBEntries) 1337 SHeader.sh_size += CBA.writeULEB128(BBE.AddressOffset) + 1338 CBA.writeULEB128(BBE.Size) + 1339 CBA.writeULEB128(BBE.Metadata); 1340 } 1341 } 1342 1343 template <class ELFT> 1344 void ELFState<ELFT>::writeSectionContent( 1345 Elf_Shdr &SHeader, const ELFYAML::LinkerOptionsSection &Section, 1346 ContiguousBlobAccumulator &CBA) { 1347 if (!Section.Options) 1348 return; 1349 1350 for (const ELFYAML::LinkerOption &LO : *Section.Options) { 1351 CBA.write(LO.Key.data(), LO.Key.size()); 1352 CBA.write('\0'); 1353 CBA.write(LO.Value.data(), LO.Value.size()); 1354 CBA.write('\0'); 1355 SHeader.sh_size += (LO.Key.size() + LO.Value.size() + 2); 1356 } 1357 } 1358 1359 template <class ELFT> 1360 void ELFState<ELFT>::writeSectionContent( 1361 Elf_Shdr &SHeader, const ELFYAML::DependentLibrariesSection &Section, 1362 ContiguousBlobAccumulator &CBA) { 1363 if (!Section.Libs) 1364 return; 1365 1366 for (StringRef Lib : *Section.Libs) { 1367 CBA.write(Lib.data(), Lib.size()); 1368 CBA.write('\0'); 1369 SHeader.sh_size += Lib.size() + 1; 1370 } 1371 } 1372 1373 template <class ELFT> 1374 uint64_t 1375 ELFState<ELFT>::alignToOffset(ContiguousBlobAccumulator &CBA, uint64_t Align, 1376 llvm::Optional<llvm::yaml::Hex64> Offset) { 1377 uint64_t CurrentOffset = CBA.getOffset(); 1378 uint64_t AlignedOffset; 1379 1380 if (Offset) { 1381 if ((uint64_t)*Offset < CurrentOffset) { 1382 reportError("the 'Offset' value (0x" + 1383 Twine::utohexstr((uint64_t)*Offset) + ") goes backward"); 1384 return CurrentOffset; 1385 } 1386 1387 // We ignore an alignment when an explicit offset has been requested. 1388 AlignedOffset = *Offset; 1389 } else { 1390 AlignedOffset = alignTo(CurrentOffset, std::max(Align, (uint64_t)1)); 1391 } 1392 1393 CBA.writeZeros(AlignedOffset - CurrentOffset); 1394 return AlignedOffset; 1395 } 1396 1397 template <class ELFT> 1398 void ELFState<ELFT>::writeSectionContent( 1399 Elf_Shdr &SHeader, const ELFYAML::CallGraphProfileSection &Section, 1400 ContiguousBlobAccumulator &CBA) { 1401 unsigned Link = 0; 1402 if (!Section.Link && !ExcludedSectionHeaders.count(".symtab") && 1403 SN2I.lookup(".symtab", Link)) 1404 SHeader.sh_link = Link; 1405 1406 if (!Section.Entries) 1407 return; 1408 1409 for (const ELFYAML::CallGraphEntry &E : *Section.Entries) { 1410 unsigned From = toSymbolIndex(E.From, Section.Name, /*IsDynamic=*/false); 1411 unsigned To = toSymbolIndex(E.To, Section.Name, /*IsDynamic=*/false); 1412 1413 CBA.write<uint32_t>(From, ELFT::TargetEndianness); 1414 CBA.write<uint32_t>(To, ELFT::TargetEndianness); 1415 CBA.write<uint64_t>(E.Weight, ELFT::TargetEndianness); 1416 SHeader.sh_size += 16; 1417 } 1418 } 1419 1420 template <class ELFT> 1421 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader, 1422 const ELFYAML::HashSection &Section, 1423 ContiguousBlobAccumulator &CBA) { 1424 unsigned Link = 0; 1425 if (!Section.Link && !ExcludedSectionHeaders.count(".dynsym") && 1426 SN2I.lookup(".dynsym", Link)) 1427 SHeader.sh_link = Link; 1428 1429 if (!Section.Bucket) 1430 return; 1431 1432 if (!Section.Bucket) 1433 return; 1434 1435 CBA.write<uint32_t>( 1436 Section.NBucket.getValueOr(llvm::yaml::Hex64(Section.Bucket->size())), 1437 ELFT::TargetEndianness); 1438 CBA.write<uint32_t>( 1439 Section.NChain.getValueOr(llvm::yaml::Hex64(Section.Chain->size())), 1440 ELFT::TargetEndianness); 1441 1442 for (uint32_t Val : *Section.Bucket) 1443 CBA.write<uint32_t>(Val, ELFT::TargetEndianness); 1444 for (uint32_t Val : *Section.Chain) 1445 CBA.write<uint32_t>(Val, ELFT::TargetEndianness); 1446 1447 SHeader.sh_size = (2 + Section.Bucket->size() + Section.Chain->size()) * 4; 1448 } 1449 1450 template <class ELFT> 1451 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader, 1452 const ELFYAML::VerdefSection &Section, 1453 ContiguousBlobAccumulator &CBA) { 1454 1455 if (Section.Info) 1456 SHeader.sh_info = *Section.Info; 1457 else if (Section.Entries) 1458 SHeader.sh_info = Section.Entries->size(); 1459 1460 unsigned Link = 0; 1461 if (!Section.Link && !ExcludedSectionHeaders.count(".dynstr") && 1462 SN2I.lookup(".dynstr", Link)) 1463 SHeader.sh_link = Link; 1464 1465 if (!Section.Entries) 1466 return; 1467 1468 uint64_t AuxCnt = 0; 1469 for (size_t I = 0; I < Section.Entries->size(); ++I) { 1470 const ELFYAML::VerdefEntry &E = (*Section.Entries)[I]; 1471 1472 Elf_Verdef VerDef; 1473 VerDef.vd_version = E.Version.getValueOr(1); 1474 VerDef.vd_flags = E.Flags.getValueOr(0); 1475 VerDef.vd_ndx = E.VersionNdx.getValueOr(0); 1476 VerDef.vd_hash = E.Hash.getValueOr(0); 1477 VerDef.vd_aux = sizeof(Elf_Verdef); 1478 VerDef.vd_cnt = E.VerNames.size(); 1479 if (I == Section.Entries->size() - 1) 1480 VerDef.vd_next = 0; 1481 else 1482 VerDef.vd_next = 1483 sizeof(Elf_Verdef) + E.VerNames.size() * sizeof(Elf_Verdaux); 1484 CBA.write((const char *)&VerDef, sizeof(Elf_Verdef)); 1485 1486 for (size_t J = 0; J < E.VerNames.size(); ++J, ++AuxCnt) { 1487 Elf_Verdaux VernAux; 1488 VernAux.vda_name = DotDynstr.getOffset(E.VerNames[J]); 1489 if (J == E.VerNames.size() - 1) 1490 VernAux.vda_next = 0; 1491 else 1492 VernAux.vda_next = sizeof(Elf_Verdaux); 1493 CBA.write((const char *)&VernAux, sizeof(Elf_Verdaux)); 1494 } 1495 } 1496 1497 SHeader.sh_size = Section.Entries->size() * sizeof(Elf_Verdef) + 1498 AuxCnt * sizeof(Elf_Verdaux); 1499 } 1500 1501 template <class ELFT> 1502 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader, 1503 const ELFYAML::VerneedSection &Section, 1504 ContiguousBlobAccumulator &CBA) { 1505 if (Section.Info) 1506 SHeader.sh_info = *Section.Info; 1507 else if (Section.VerneedV) 1508 SHeader.sh_info = Section.VerneedV->size(); 1509 1510 unsigned Link = 0; 1511 if (!Section.Link && !ExcludedSectionHeaders.count(".dynstr") && 1512 SN2I.lookup(".dynstr", Link)) 1513 SHeader.sh_link = Link; 1514 1515 if (!Section.VerneedV) 1516 return; 1517 1518 uint64_t AuxCnt = 0; 1519 for (size_t I = 0; I < Section.VerneedV->size(); ++I) { 1520 const ELFYAML::VerneedEntry &VE = (*Section.VerneedV)[I]; 1521 1522 Elf_Verneed VerNeed; 1523 VerNeed.vn_version = VE.Version; 1524 VerNeed.vn_file = DotDynstr.getOffset(VE.File); 1525 if (I == Section.VerneedV->size() - 1) 1526 VerNeed.vn_next = 0; 1527 else 1528 VerNeed.vn_next = 1529 sizeof(Elf_Verneed) + VE.AuxV.size() * sizeof(Elf_Vernaux); 1530 VerNeed.vn_cnt = VE.AuxV.size(); 1531 VerNeed.vn_aux = sizeof(Elf_Verneed); 1532 CBA.write((const char *)&VerNeed, sizeof(Elf_Verneed)); 1533 1534 for (size_t J = 0; J < VE.AuxV.size(); ++J, ++AuxCnt) { 1535 const ELFYAML::VernauxEntry &VAuxE = VE.AuxV[J]; 1536 1537 Elf_Vernaux VernAux; 1538 VernAux.vna_hash = VAuxE.Hash; 1539 VernAux.vna_flags = VAuxE.Flags; 1540 VernAux.vna_other = VAuxE.Other; 1541 VernAux.vna_name = DotDynstr.getOffset(VAuxE.Name); 1542 if (J == VE.AuxV.size() - 1) 1543 VernAux.vna_next = 0; 1544 else 1545 VernAux.vna_next = sizeof(Elf_Vernaux); 1546 CBA.write((const char *)&VernAux, sizeof(Elf_Vernaux)); 1547 } 1548 } 1549 1550 SHeader.sh_size = Section.VerneedV->size() * sizeof(Elf_Verneed) + 1551 AuxCnt * sizeof(Elf_Vernaux); 1552 } 1553 1554 template <class ELFT> 1555 void ELFState<ELFT>::writeSectionContent( 1556 Elf_Shdr &SHeader, const ELFYAML::ARMIndexTableSection &Section, 1557 ContiguousBlobAccumulator &CBA) { 1558 if (!Section.Entries) 1559 return; 1560 1561 for (const ELFYAML::ARMIndexTableEntry &E : *Section.Entries) { 1562 CBA.write<uint32_t>(E.Offset, ELFT::TargetEndianness); 1563 CBA.write<uint32_t>(E.Value, ELFT::TargetEndianness); 1564 } 1565 SHeader.sh_size = Section.Entries->size() * 8; 1566 } 1567 1568 template <class ELFT> 1569 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader, 1570 const ELFYAML::MipsABIFlags &Section, 1571 ContiguousBlobAccumulator &CBA) { 1572 assert(Section.Type == llvm::ELF::SHT_MIPS_ABIFLAGS && 1573 "Section type is not SHT_MIPS_ABIFLAGS"); 1574 1575 object::Elf_Mips_ABIFlags<ELFT> Flags; 1576 zero(Flags); 1577 SHeader.sh_size = SHeader.sh_entsize; 1578 1579 Flags.version = Section.Version; 1580 Flags.isa_level = Section.ISALevel; 1581 Flags.isa_rev = Section.ISARevision; 1582 Flags.gpr_size = Section.GPRSize; 1583 Flags.cpr1_size = Section.CPR1Size; 1584 Flags.cpr2_size = Section.CPR2Size; 1585 Flags.fp_abi = Section.FpABI; 1586 Flags.isa_ext = Section.ISAExtension; 1587 Flags.ases = Section.ASEs; 1588 Flags.flags1 = Section.Flags1; 1589 Flags.flags2 = Section.Flags2; 1590 CBA.write((const char *)&Flags, sizeof(Flags)); 1591 } 1592 1593 template <class ELFT> 1594 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader, 1595 const ELFYAML::DynamicSection &Section, 1596 ContiguousBlobAccumulator &CBA) { 1597 assert(Section.Type == llvm::ELF::SHT_DYNAMIC && 1598 "Section type is not SHT_DYNAMIC"); 1599 1600 if (!Section.Entries) 1601 return; 1602 1603 for (const ELFYAML::DynamicEntry &DE : *Section.Entries) { 1604 CBA.write<uintX_t>(DE.Tag, ELFT::TargetEndianness); 1605 CBA.write<uintX_t>(DE.Val, ELFT::TargetEndianness); 1606 } 1607 SHeader.sh_size = 2 * sizeof(uintX_t) * Section.Entries->size(); 1608 } 1609 1610 template <class ELFT> 1611 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader, 1612 const ELFYAML::AddrsigSection &Section, 1613 ContiguousBlobAccumulator &CBA) { 1614 unsigned Link = 0; 1615 if (!Section.Link && !ExcludedSectionHeaders.count(".symtab") && 1616 SN2I.lookup(".symtab", Link)) 1617 SHeader.sh_link = Link; 1618 1619 if (!Section.Symbols) 1620 return; 1621 1622 if (!Section.Symbols) 1623 return; 1624 1625 for (StringRef Sym : *Section.Symbols) 1626 SHeader.sh_size += 1627 CBA.writeULEB128(toSymbolIndex(Sym, Section.Name, /*IsDynamic=*/false)); 1628 } 1629 1630 template <class ELFT> 1631 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader, 1632 const ELFYAML::NoteSection &Section, 1633 ContiguousBlobAccumulator &CBA) { 1634 if (!Section.Notes) 1635 return; 1636 1637 uint64_t Offset = CBA.tell(); 1638 for (const ELFYAML::NoteEntry &NE : *Section.Notes) { 1639 // Write name size. 1640 if (NE.Name.empty()) 1641 CBA.write<uint32_t>(0, ELFT::TargetEndianness); 1642 else 1643 CBA.write<uint32_t>(NE.Name.size() + 1, ELFT::TargetEndianness); 1644 1645 // Write description size. 1646 if (NE.Desc.binary_size() == 0) 1647 CBA.write<uint32_t>(0, ELFT::TargetEndianness); 1648 else 1649 CBA.write<uint32_t>(NE.Desc.binary_size(), ELFT::TargetEndianness); 1650 1651 // Write type. 1652 CBA.write<uint32_t>(NE.Type, ELFT::TargetEndianness); 1653 1654 // Write name, null terminator and padding. 1655 if (!NE.Name.empty()) { 1656 CBA.write(NE.Name.data(), NE.Name.size()); 1657 CBA.write('\0'); 1658 CBA.padToAlignment(4); 1659 } 1660 1661 // Write description and padding. 1662 if (NE.Desc.binary_size() != 0) { 1663 CBA.writeAsBinary(NE.Desc); 1664 CBA.padToAlignment(4); 1665 } 1666 } 1667 1668 SHeader.sh_size = CBA.tell() - Offset; 1669 } 1670 1671 template <class ELFT> 1672 void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader, 1673 const ELFYAML::GnuHashSection &Section, 1674 ContiguousBlobAccumulator &CBA) { 1675 unsigned Link = 0; 1676 if (!Section.Link && !ExcludedSectionHeaders.count(".dynsym") && 1677 SN2I.lookup(".dynsym", Link)) 1678 SHeader.sh_link = Link; 1679 1680 if (!Section.HashBuckets) 1681 return; 1682 1683 if (!Section.Header) 1684 return; 1685 1686 // We write the header first, starting with the hash buckets count. Normally 1687 // it is the number of entries in HashBuckets, but the "NBuckets" property can 1688 // be used to override this field, which is useful for producing broken 1689 // objects. 1690 if (Section.Header->NBuckets) 1691 CBA.write<uint32_t>(*Section.Header->NBuckets, ELFT::TargetEndianness); 1692 else 1693 CBA.write<uint32_t>(Section.HashBuckets->size(), ELFT::TargetEndianness); 1694 1695 // Write the index of the first symbol in the dynamic symbol table accessible 1696 // via the hash table. 1697 CBA.write<uint32_t>(Section.Header->SymNdx, ELFT::TargetEndianness); 1698 1699 // Write the number of words in the Bloom filter. As above, the "MaskWords" 1700 // property can be used to set this field to any value. 1701 if (Section.Header->MaskWords) 1702 CBA.write<uint32_t>(*Section.Header->MaskWords, ELFT::TargetEndianness); 1703 else 1704 CBA.write<uint32_t>(Section.BloomFilter->size(), ELFT::TargetEndianness); 1705 1706 // Write the shift constant used by the Bloom filter. 1707 CBA.write<uint32_t>(Section.Header->Shift2, ELFT::TargetEndianness); 1708 1709 // We've finished writing the header. Now write the Bloom filter. 1710 for (llvm::yaml::Hex64 Val : *Section.BloomFilter) 1711 CBA.write<uintX_t>(Val, ELFT::TargetEndianness); 1712 1713 // Write an array of hash buckets. 1714 for (llvm::yaml::Hex32 Val : *Section.HashBuckets) 1715 CBA.write<uint32_t>(Val, ELFT::TargetEndianness); 1716 1717 // Write an array of hash values. 1718 for (llvm::yaml::Hex32 Val : *Section.HashValues) 1719 CBA.write<uint32_t>(Val, ELFT::TargetEndianness); 1720 1721 SHeader.sh_size = 16 /*Header size*/ + 1722 Section.BloomFilter->size() * sizeof(typename ELFT::uint) + 1723 Section.HashBuckets->size() * 4 + 1724 Section.HashValues->size() * 4; 1725 } 1726 1727 template <class ELFT> 1728 void ELFState<ELFT>::writeFill(ELFYAML::Fill &Fill, 1729 ContiguousBlobAccumulator &CBA) { 1730 size_t PatternSize = Fill.Pattern ? Fill.Pattern->binary_size() : 0; 1731 if (!PatternSize) { 1732 CBA.writeZeros(Fill.Size); 1733 return; 1734 } 1735 1736 // Fill the content with the specified pattern. 1737 uint64_t Written = 0; 1738 for (; Written + PatternSize <= Fill.Size; Written += PatternSize) 1739 CBA.writeAsBinary(*Fill.Pattern); 1740 CBA.writeAsBinary(*Fill.Pattern, Fill.Size - Written); 1741 } 1742 1743 template <class ELFT> 1744 DenseMap<StringRef, size_t> ELFState<ELFT>::buildSectionHeaderReorderMap() { 1745 if (!Doc.SectionHeaders || Doc.SectionHeaders->NoHeaders) 1746 return DenseMap<StringRef, size_t>(); 1747 1748 DenseMap<StringRef, size_t> Ret; 1749 size_t SecNdx = 0; 1750 StringSet<> Seen; 1751 1752 auto AddSection = [&](const ELFYAML::SectionHeader &Hdr) { 1753 if (!Ret.try_emplace(Hdr.Name, ++SecNdx).second) 1754 reportError("repeated section name: '" + Hdr.Name + 1755 "' in the section header description"); 1756 Seen.insert(Hdr.Name); 1757 }; 1758 1759 if (Doc.SectionHeaders->Sections) 1760 for (const ELFYAML::SectionHeader &Hdr : *Doc.SectionHeaders->Sections) 1761 AddSection(Hdr); 1762 1763 if (Doc.SectionHeaders->Excluded) 1764 for (const ELFYAML::SectionHeader &Hdr : *Doc.SectionHeaders->Excluded) 1765 AddSection(Hdr); 1766 1767 for (const ELFYAML::Section *S : Doc.getSections()) { 1768 // Ignore special first SHT_NULL section. 1769 if (S == Doc.getSections().front()) 1770 continue; 1771 if (!Seen.count(S->Name)) 1772 reportError("section '" + S->Name + 1773 "' should be present in the 'Sections' or 'Excluded' lists"); 1774 Seen.erase(S->Name); 1775 } 1776 1777 for (const auto &It : Seen) 1778 reportError("section header contains undefined section '" + It.getKey() + 1779 "'"); 1780 return Ret; 1781 } 1782 1783 template <class ELFT> void ELFState<ELFT>::buildSectionIndex() { 1784 // A YAML description can have an explicit section header declaration that 1785 // allows to change the order of section headers. 1786 DenseMap<StringRef, size_t> ReorderMap = buildSectionHeaderReorderMap(); 1787 1788 if (HasError) 1789 return; 1790 1791 // Build excluded section headers map. 1792 std::vector<ELFYAML::Section *> Sections = Doc.getSections(); 1793 if (Doc.SectionHeaders) { 1794 if (Doc.SectionHeaders->Excluded) 1795 for (const ELFYAML::SectionHeader &Hdr : *Doc.SectionHeaders->Excluded) 1796 if (!ExcludedSectionHeaders.insert(Hdr.Name).second) 1797 llvm_unreachable("buildSectionIndex() failed"); 1798 1799 if (Doc.SectionHeaders->NoHeaders.getValueOr(false)) 1800 for (const ELFYAML::Section *S : Sections) 1801 if (!ExcludedSectionHeaders.insert(S->Name).second) 1802 llvm_unreachable("buildSectionIndex() failed"); 1803 } 1804 1805 size_t SecNdx = -1; 1806 for (const ELFYAML::Section *S : Sections) { 1807 ++SecNdx; 1808 1809 size_t Index = ReorderMap.empty() ? SecNdx : ReorderMap.lookup(S->Name); 1810 if (!SN2I.addName(S->Name, Index)) 1811 llvm_unreachable("buildSectionIndex() failed"); 1812 1813 if (!ExcludedSectionHeaders.count(S->Name)) 1814 DotShStrtab.add(ELFYAML::dropUniqueSuffix(S->Name)); 1815 } 1816 1817 DotShStrtab.finalize(); 1818 } 1819 1820 template <class ELFT> void ELFState<ELFT>::buildSymbolIndexes() { 1821 auto Build = [this](ArrayRef<ELFYAML::Symbol> V, NameToIdxMap &Map) { 1822 for (size_t I = 0, S = V.size(); I < S; ++I) { 1823 const ELFYAML::Symbol &Sym = V[I]; 1824 if (!Sym.Name.empty() && !Map.addName(Sym.Name, I + 1)) 1825 reportError("repeated symbol name: '" + Sym.Name + "'"); 1826 } 1827 }; 1828 1829 if (Doc.Symbols) 1830 Build(*Doc.Symbols, SymN2I); 1831 if (Doc.DynamicSymbols) 1832 Build(*Doc.DynamicSymbols, DynSymN2I); 1833 } 1834 1835 template <class ELFT> void ELFState<ELFT>::finalizeStrings() { 1836 // Add the regular symbol names to .strtab section. 1837 if (Doc.Symbols) 1838 for (const ELFYAML::Symbol &Sym : *Doc.Symbols) 1839 DotStrtab.add(ELFYAML::dropUniqueSuffix(Sym.Name)); 1840 DotStrtab.finalize(); 1841 1842 // Add the dynamic symbol names to .dynstr section. 1843 if (Doc.DynamicSymbols) 1844 for (const ELFYAML::Symbol &Sym : *Doc.DynamicSymbols) 1845 DotDynstr.add(ELFYAML::dropUniqueSuffix(Sym.Name)); 1846 1847 // SHT_GNU_verdef and SHT_GNU_verneed sections might also 1848 // add strings to .dynstr section. 1849 for (const ELFYAML::Chunk *Sec : Doc.getSections()) { 1850 if (auto VerNeed = dyn_cast<ELFYAML::VerneedSection>(Sec)) { 1851 if (VerNeed->VerneedV) { 1852 for (const ELFYAML::VerneedEntry &VE : *VerNeed->VerneedV) { 1853 DotDynstr.add(VE.File); 1854 for (const ELFYAML::VernauxEntry &Aux : VE.AuxV) 1855 DotDynstr.add(Aux.Name); 1856 } 1857 } 1858 } else if (auto VerDef = dyn_cast<ELFYAML::VerdefSection>(Sec)) { 1859 if (VerDef->Entries) 1860 for (const ELFYAML::VerdefEntry &E : *VerDef->Entries) 1861 for (StringRef Name : E.VerNames) 1862 DotDynstr.add(Name); 1863 } 1864 } 1865 1866 DotDynstr.finalize(); 1867 } 1868 1869 template <class ELFT> 1870 bool ELFState<ELFT>::writeELF(raw_ostream &OS, ELFYAML::Object &Doc, 1871 yaml::ErrorHandler EH, uint64_t MaxSize) { 1872 ELFState<ELFT> State(Doc, EH); 1873 if (State.HasError) 1874 return false; 1875 1876 // Finalize .strtab and .dynstr sections. We do that early because want to 1877 // finalize the string table builders before writing the content of the 1878 // sections that might want to use them. 1879 State.finalizeStrings(); 1880 1881 State.buildSectionIndex(); 1882 State.buildSymbolIndexes(); 1883 1884 if (State.HasError) 1885 return false; 1886 1887 std::vector<Elf_Phdr> PHeaders; 1888 State.initProgramHeaders(PHeaders); 1889 1890 // XXX: This offset is tightly coupled with the order that we write 1891 // things to `OS`. 1892 const size_t SectionContentBeginOffset = 1893 sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * Doc.ProgramHeaders.size(); 1894 // It is quite easy to accidentally create output with yaml2obj that is larger 1895 // than intended, for example, due to an issue in the YAML description. 1896 // We limit the maximum allowed output size, but also provide a command line 1897 // option to change this limitation. 1898 ContiguousBlobAccumulator CBA(SectionContentBeginOffset, MaxSize); 1899 1900 std::vector<Elf_Shdr> SHeaders; 1901 State.initSectionHeaders(SHeaders, CBA); 1902 1903 // Now we can decide segment offsets. 1904 State.setProgramHeaderLayout(PHeaders, SHeaders); 1905 1906 // If needed, align the start of the section header table, which is written 1907 // after all section data. 1908 const bool HasSectionHeaders = 1909 !Doc.SectionHeaders || !Doc.SectionHeaders->NoHeaders.getValueOr(false); 1910 Optional<uint64_t> SHOff; 1911 if (HasSectionHeaders) 1912 SHOff = State.alignToOffset(CBA, sizeof(typename ELFT::uint), 1913 /*Offset=*/None); 1914 bool ReachedLimit = SHOff.getValueOr(CBA.getOffset()) + 1915 arrayDataSize(makeArrayRef(SHeaders)) > 1916 MaxSize; 1917 if (Error E = CBA.takeLimitError()) { 1918 // We report a custom error message instead below. 1919 consumeError(std::move(E)); 1920 ReachedLimit = true; 1921 } 1922 1923 if (ReachedLimit) 1924 State.reportError( 1925 "the desired output size is greater than permitted. Use the " 1926 "--max-size option to change the limit"); 1927 1928 if (State.HasError) 1929 return false; 1930 1931 State.writeELFHeader(OS, SHOff); 1932 writeArrayData(OS, makeArrayRef(PHeaders)); 1933 CBA.writeBlobToStream(OS); 1934 if (HasSectionHeaders) 1935 writeArrayData(OS, makeArrayRef(SHeaders)); 1936 return true; 1937 } 1938 1939 namespace llvm { 1940 namespace yaml { 1941 1942 bool yaml2elf(llvm::ELFYAML::Object &Doc, raw_ostream &Out, ErrorHandler EH, 1943 uint64_t MaxSize) { 1944 bool IsLE = Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB); 1945 bool Is64Bit = Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64); 1946 if (Is64Bit) { 1947 if (IsLE) 1948 return ELFState<object::ELF64LE>::writeELF(Out, Doc, EH, MaxSize); 1949 return ELFState<object::ELF64BE>::writeELF(Out, Doc, EH, MaxSize); 1950 } 1951 if (IsLE) 1952 return ELFState<object::ELF32LE>::writeELF(Out, Doc, EH, MaxSize); 1953 return ELFState<object::ELF32BE>::writeELF(Out, Doc, EH, MaxSize); 1954 } 1955 1956 } // namespace yaml 1957 } // namespace llvm 1958