LLVM 23.0.0git
ELFEmitter.cpp
Go to the documentation of this file.
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"
27#include "llvm/Support/Errc.h"
28#include "llvm/Support/Error.h"
29#include "llvm/Support/LEB128.h"
33#include <optional>
34
35using namespace llvm;
37
38namespace {
39// Used to keep track of section and symbol names, so that in the YAML file
40// sections and symbols can be referenced by name instead of by index.
41class NameToIdxMap {
42 StringMap<unsigned> Map;
43
44public:
45 /// \Returns false if name is already present in the map.
46 bool addName(StringRef Name, unsigned Ndx) {
47 return Map.insert({Name, Ndx}).second;
48 }
49 /// \Returns false if name is not present in the map.
50 bool lookup(StringRef Name, unsigned &Idx) const {
51 auto I = Map.find(Name);
52 if (I == Map.end())
53 return false;
54 Idx = I->getValue();
55 return true;
56 }
57 /// Asserts if name is not present in the map.
58 unsigned get(StringRef Name) const {
59 unsigned Idx;
60 if (lookup(Name, Idx))
61 return Idx;
62 assert(false && "Expected section not found in index");
63 return 0;
64 }
65 unsigned size() const { return Map.size(); }
66};
67
68namespace {
69struct Fragment {
70 uint64_t Offset;
71 uint64_t Size;
72 uint32_t Type;
73 uint64_t AddrAlign;
74};
75} // namespace
76
77/// "Single point of truth" for the ELF file construction.
78/// TODO: This class still has a ways to go before it is truly a "single
79/// point of truth".
80template <class ELFT> class ELFState {
82
83 enum class SymtabType { Static, Dynamic };
84
85 /// The future symbol table string section.
86 StringTableBuilder DotStrtab{StringTableBuilder::ELF};
87
88 /// The future section header string table section, if a unique string table
89 /// is needed. Don't reference this variable direectly: use the
90 /// ShStrtabStrings member instead.
91 StringTableBuilder DotShStrtab{StringTableBuilder::ELF};
92
93 /// The future dynamic symbol string section.
94 StringTableBuilder DotDynstr{StringTableBuilder::ELF};
95
96 /// The name of the section header string table section. If it is .strtab or
97 /// .dynstr, the section header strings will be written to the same string
98 /// table as the static/dynamic symbols respectively. Otherwise a dedicated
99 /// section will be created with that name.
100 StringRef SectionHeaderStringTableName = ".shstrtab";
101 StringTableBuilder *ShStrtabStrings = &DotShStrtab;
102
103 NameToIdxMap SN2I;
104 NameToIdxMap SymN2I;
105 NameToIdxMap DynSymN2I;
106 ELFYAML::Object &Doc;
107
108 std::vector<std::pair<Elf_Shdr *, ELFYAML::Section>>
109 SectionHeadersOverrideHelper;
110
111 StringSet<> ExcludedSectionHeaders;
112
113 uint64_t LocationCounter = 0;
114 bool HasError = false;
115 yaml::ErrorHandler ErrHandler;
116 void reportError(const Twine &Msg);
117 void reportError(Error Err);
118
119 std::vector<Elf_Sym> toELFSymbols(ArrayRef<ELFYAML::Symbol> Symbols,
120 const StringTableBuilder &Strtab);
121 unsigned toSectionIndex(StringRef S, StringRef LocSec, StringRef LocSym = "");
122 unsigned toSymbolIndex(StringRef S, StringRef LocSec, bool IsDynamic);
123
124 void buildSectionIndex();
125 void buildSymbolIndexes();
126 void initProgramHeaders(std::vector<Elf_Phdr> &PHeaders);
127 bool initImplicitHeader(ContiguousBlobAccumulator &CBA, Elf_Shdr &Header,
128 StringRef SecName, ELFYAML::Section *YAMLSec);
129 void initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
130 ContiguousBlobAccumulator &CBA);
131 void overrideSectionHeaders(std::vector<Elf_Shdr> &SHeaders);
132 void initSymtabSectionHeader(Elf_Shdr &SHeader, SymtabType STType,
133 ContiguousBlobAccumulator &CBA,
134 ELFYAML::Section *YAMLSec);
135 void initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
136 StringTableBuilder &STB,
137 ContiguousBlobAccumulator &CBA,
138 ELFYAML::Section *YAMLSec);
139 void initDWARFSectionHeader(Elf_Shdr &SHeader, StringRef Name,
140 ContiguousBlobAccumulator &CBA,
141 ELFYAML::Section *YAMLSec);
142 void setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
143 std::vector<Elf_Shdr> &SHeaders);
144
145 std::vector<Fragment>
146 getPhdrFragments(const ELFYAML::ProgramHeader &Phdr,
148
149 void finalizeStrings();
150 void writeELFHeader(raw_ostream &OS);
151 void writeSectionContent(Elf_Shdr &SHeader,
152 const ELFYAML::NoBitsSection &Section,
153 ContiguousBlobAccumulator &CBA);
154 void writeSectionContent(Elf_Shdr &SHeader,
155 const ELFYAML::RawContentSection &Section,
156 ContiguousBlobAccumulator &CBA);
157 void writeSectionContent(Elf_Shdr &SHeader,
158 const ELFYAML::RelocationSection &Section,
159 ContiguousBlobAccumulator &CBA);
160 void writeSectionContent(Elf_Shdr &SHeader,
161 const ELFYAML::RelrSection &Section,
162 ContiguousBlobAccumulator &CBA);
163 void writeSectionContent(Elf_Shdr &SHeader,
164 const ELFYAML::GroupSection &Group,
165 ContiguousBlobAccumulator &CBA);
166 void writeSectionContent(Elf_Shdr &SHeader,
167 const ELFYAML::SymtabShndxSection &Shndx,
168 ContiguousBlobAccumulator &CBA);
169 void writeSectionContent(Elf_Shdr &SHeader,
170 const ELFYAML::SymverSection &Section,
171 ContiguousBlobAccumulator &CBA);
172 void writeSectionContent(Elf_Shdr &SHeader,
173 const ELFYAML::VerneedSection &Section,
174 ContiguousBlobAccumulator &CBA);
175 void writeSectionContent(Elf_Shdr &SHeader,
176 const ELFYAML::VerdefSection &Section,
177 ContiguousBlobAccumulator &CBA);
178 void writeSectionContent(Elf_Shdr &SHeader,
179 const ELFYAML::ARMIndexTableSection &Section,
180 ContiguousBlobAccumulator &CBA);
181 void writeSectionContent(Elf_Shdr &SHeader,
182 const ELFYAML::MipsABIFlags &Section,
183 ContiguousBlobAccumulator &CBA);
184 void writeSectionContent(Elf_Shdr &SHeader,
185 const ELFYAML::DynamicSection &Section,
186 ContiguousBlobAccumulator &CBA);
187 void writeSectionContent(Elf_Shdr &SHeader,
188 const ELFYAML::StackSizesSection &Section,
189 ContiguousBlobAccumulator &CBA);
190 void writeSectionContent(Elf_Shdr &SHeader,
191 const ELFYAML::BBAddrMapSection &Section,
192 ContiguousBlobAccumulator &CBA);
193 void writeSectionContent(Elf_Shdr &SHeader,
194 const ELFYAML::HashSection &Section,
195 ContiguousBlobAccumulator &CBA);
196 void writeSectionContent(Elf_Shdr &SHeader,
197 const ELFYAML::AddrsigSection &Section,
198 ContiguousBlobAccumulator &CBA);
199 void writeSectionContent(Elf_Shdr &SHeader,
200 const ELFYAML::NoteSection &Section,
201 ContiguousBlobAccumulator &CBA);
202 void writeSectionContent(Elf_Shdr &SHeader,
203 const ELFYAML::GnuHashSection &Section,
204 ContiguousBlobAccumulator &CBA);
205 void writeSectionContent(Elf_Shdr &SHeader,
206 const ELFYAML::LinkerOptionsSection &Section,
207 ContiguousBlobAccumulator &CBA);
208 void writeSectionContent(Elf_Shdr &SHeader,
209 const ELFYAML::DependentLibrariesSection &Section,
210 ContiguousBlobAccumulator &CBA);
211 void writeSectionContent(Elf_Shdr &SHeader,
212 const ELFYAML::CallGraphProfileSection &Section,
213 ContiguousBlobAccumulator &CBA);
214
215 void writeFill(ELFYAML::Fill &Fill, ContiguousBlobAccumulator &CBA);
216
217 ELFState(ELFYAML::Object &D, yaml::ErrorHandler EH);
218
219 void assignSectionAddress(Elf_Shdr &SHeader, ELFYAML::Section *YAMLSec);
220
221 DenseMap<StringRef, size_t> buildSectionHeaderReorderMap();
222
223 BumpPtrAllocator StringAlloc;
224 uint64_t alignToOffset(ContiguousBlobAccumulator &CBA, uint64_t Align,
225 std::optional<llvm::yaml::Hex64> Offset);
226
227 uint64_t getSectionNameOffset(StringRef Name);
228
229public:
230 static bool writeELF(raw_ostream &OS, ELFYAML::Object &Doc,
231 yaml::ErrorHandler EH, uint64_t MaxSize);
232};
233} // end anonymous namespace
234
235template <class T> static size_t arrayDataSize(ArrayRef<T> A) {
236 return A.size() * sizeof(T);
237}
238
239template <class T> static void writeArrayData(raw_ostream &OS, ArrayRef<T> A) {
240 OS.write((const char *)A.data(), arrayDataSize(A));
241}
242
243template <class T> static void zero(T &Obj) { memset(&Obj, 0, sizeof(Obj)); }
244
245template <class ELFT>
246ELFState<ELFT>::ELFState(ELFYAML::Object &D, yaml::ErrorHandler EH)
247 : Doc(D), ErrHandler(EH) {
248 // The input may explicitly request to store the section header table strings
249 // in the same string table as dynamic or static symbol names. Set the
250 // ShStrtabStrings member accordingly.
251 if (Doc.Header.SectionHeaderStringTable) {
252 SectionHeaderStringTableName = *Doc.Header.SectionHeaderStringTable;
253 if (*Doc.Header.SectionHeaderStringTable == ".strtab")
254 ShStrtabStrings = &DotStrtab;
255 else if (*Doc.Header.SectionHeaderStringTable == ".dynstr")
256 ShStrtabStrings = &DotDynstr;
257 // Otherwise, the unique table will be used.
258 }
259
260 std::vector<ELFYAML::Section *> Sections = Doc.getSections();
261 // Insert SHT_NULL section implicitly when it is not defined in YAML.
262 if (Sections.empty() || Sections.front()->Type != ELF::SHT_NULL)
263 Doc.Chunks.insert(
264 Doc.Chunks.begin(),
265 std::make_unique<ELFYAML::Section>(
266 ELFYAML::Chunk::ChunkKind::RawContent, /*IsImplicit=*/true));
267
268 StringSet<> DocSections;
269 ELFYAML::SectionHeaderTable *SecHdrTable = nullptr;
270 for (size_t I = 0; I < Doc.Chunks.size(); ++I) {
271 const std::unique_ptr<ELFYAML::Chunk> &C = Doc.Chunks[I];
272
273 // We might have an explicit section header table declaration.
274 if (auto S = dyn_cast<ELFYAML::SectionHeaderTable>(C.get())) {
275 if (SecHdrTable)
276 reportError("multiple section header tables are not allowed");
277 SecHdrTable = S;
278 continue;
279 }
280
281 // We add a technical suffix for each unnamed section/fill. It does not
282 // affect the output, but allows us to map them by name in the code and
283 // report better error messages.
284 if (C->Name.empty()) {
285 std::string NewName = ELFYAML::appendUniqueSuffix(
286 /*Name=*/"", "index " + Twine(I));
287 C->Name = StringRef(NewName).copy(StringAlloc);
288 assert(ELFYAML::dropUniqueSuffix(C->Name).empty());
289 }
290
291 if (!DocSections.insert(C->Name).second)
292 reportError("repeated section/fill name: '" + C->Name +
293 "' at YAML section/fill number " + Twine(I));
294 }
295
296 SmallSetVector<StringRef, 8> ImplicitSections;
297 if (Doc.DynamicSymbols) {
298 if (SectionHeaderStringTableName == ".dynsym")
299 reportError("cannot use '.dynsym' as the section header name table when "
300 "there are dynamic symbols");
301 ImplicitSections.insert(".dynsym");
302 ImplicitSections.insert(".dynstr");
303 }
304 if (Doc.Symbols) {
305 if (SectionHeaderStringTableName == ".symtab")
306 reportError("cannot use '.symtab' as the section header name table when "
307 "there are symbols");
308 ImplicitSections.insert(".symtab");
309 }
310 if (Doc.DWARF)
311 for (StringRef DebugSecName : Doc.DWARF->getNonEmptySectionNames()) {
312 std::string SecName = ("." + DebugSecName).str();
313 // TODO: For .debug_str it should be possible to share the string table,
314 // in the same manner as the symbol string tables.
315 if (SectionHeaderStringTableName == SecName)
316 reportError("cannot use '" + SecName +
317 "' as the section header name table when it is needed for "
318 "DWARF output");
319 ImplicitSections.insert(StringRef(SecName).copy(StringAlloc));
320 }
321 // TODO: Only create the .strtab here if any symbols have been requested.
322 ImplicitSections.insert(".strtab");
323 if (!SecHdrTable || !SecHdrTable->NoHeaders.value_or(false))
324 ImplicitSections.insert(SectionHeaderStringTableName);
325
326 // Insert placeholders for implicit sections that are not
327 // defined explicitly in YAML.
328 for (StringRef SecName : ImplicitSections) {
329 if (DocSections.count(SecName))
330 continue;
331
332 std::unique_ptr<ELFYAML::Section> Sec = std::make_unique<ELFYAML::Section>(
333 ELFYAML::Chunk::ChunkKind::RawContent, true /*IsImplicit*/);
334 Sec->Name = SecName;
335
336 if (SecName == SectionHeaderStringTableName)
337 Sec->Type = ELF::SHT_STRTAB;
338 else if (SecName == ".dynsym")
339 Sec->Type = ELF::SHT_DYNSYM;
340 else if (SecName == ".symtab")
341 Sec->Type = ELF::SHT_SYMTAB;
342 else
343 Sec->Type = ELF::SHT_STRTAB;
344
345 // When the section header table is explicitly defined at the end of the
346 // sections list, it is reasonable to assume that the user wants to reorder
347 // section headers, but still wants to place the section header table after
348 // all sections, like it normally happens. In this case we want to insert
349 // other implicit sections right before the section header table.
350 if (Doc.Chunks.back().get() == SecHdrTable)
351 Doc.Chunks.insert(Doc.Chunks.end() - 1, std::move(Sec));
352 else
353 Doc.Chunks.push_back(std::move(Sec));
354 }
355
356 // Insert the section header table implicitly at the end, when it is not
357 // explicitly defined.
358 if (!SecHdrTable)
359 Doc.Chunks.push_back(
360 std::make_unique<ELFYAML::SectionHeaderTable>(/*IsImplicit=*/true));
361}
362
363template <class ELFT>
364void ELFState<ELFT>::writeELFHeader(raw_ostream &OS) {
365 using namespace llvm::ELF;
366
367 Elf_Ehdr Header;
368 zero(Header);
369 Header.e_ident[EI_MAG0] = 0x7f;
370 Header.e_ident[EI_MAG1] = 'E';
371 Header.e_ident[EI_MAG2] = 'L';
372 Header.e_ident[EI_MAG3] = 'F';
373 Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
374 Header.e_ident[EI_DATA] = Doc.Header.Data;
375 Header.e_ident[EI_VERSION] = EV_CURRENT;
376 Header.e_ident[EI_OSABI] = Doc.Header.OSABI;
377 Header.e_ident[EI_ABIVERSION] = Doc.Header.ABIVersion;
378 Header.e_type = Doc.Header.Type;
379
380 if (Doc.Header.Machine)
381 Header.e_machine = *Doc.Header.Machine;
382 else
383 Header.e_machine = EM_NONE;
384
385 Header.e_version = EV_CURRENT;
386 Header.e_entry = Doc.Header.Entry;
387 if (Doc.Header.Flags)
388 Header.e_flags = *Doc.Header.Flags;
389 else
390 Header.e_flags = 0;
391
392 Header.e_ehsize = sizeof(Elf_Ehdr);
393
394 if (Doc.Header.EPhOff)
395 Header.e_phoff = *Doc.Header.EPhOff;
396 else if (!Doc.ProgramHeaders.empty())
397 Header.e_phoff = sizeof(Header);
398 else
399 Header.e_phoff = 0;
400
401 if (Doc.Header.EPhEntSize)
402 Header.e_phentsize = *Doc.Header.EPhEntSize;
403 else if (!Doc.ProgramHeaders.empty())
404 Header.e_phentsize = sizeof(Elf_Phdr);
405 else
406 Header.e_phentsize = 0;
407
408 if (Doc.Header.EPhNum)
409 Header.e_phnum = *Doc.Header.EPhNum;
410 else if (!Doc.ProgramHeaders.empty())
411 Header.e_phnum = Doc.ProgramHeaders.size();
412 else
413 Header.e_phnum = 0;
414
415 Header.e_shentsize = Doc.Header.EShEntSize ? (uint16_t)*Doc.Header.EShEntSize
416 : sizeof(Elf_Shdr);
417
418 const ELFYAML::SectionHeaderTable &SectionHeaders =
419 Doc.getSectionHeaderTable();
420
421 if (Doc.Header.EShOff)
422 Header.e_shoff = *Doc.Header.EShOff;
423 else if (SectionHeaders.Offset)
424 Header.e_shoff = *SectionHeaders.Offset;
425 else
426 Header.e_shoff = 0;
427
428 if (Doc.Header.EShNum)
429 Header.e_shnum = *Doc.Header.EShNum;
430 else
431 Header.e_shnum = SectionHeaders.getNumHeaders(Doc.getSections().size());
432
433 if (Doc.Header.EShStrNdx)
434 Header.e_shstrndx = *Doc.Header.EShStrNdx;
435 else if (SectionHeaders.Offset &&
436 !ExcludedSectionHeaders.count(SectionHeaderStringTableName))
437 Header.e_shstrndx = SN2I.get(SectionHeaderStringTableName);
438 else
439 Header.e_shstrndx = 0;
440
441 OS.write((const char *)&Header, sizeof(Header));
442}
443
444template <class ELFT>
445void ELFState<ELFT>::initProgramHeaders(std::vector<Elf_Phdr> &PHeaders) {
446 DenseMap<StringRef, size_t> NameToIndex;
447 for (size_t I = 0, E = Doc.Chunks.size(); I != E; ++I) {
448 NameToIndex[Doc.Chunks[I]->Name] = I + 1;
449 }
450
451 for (size_t I = 0, E = Doc.ProgramHeaders.size(); I != E; ++I) {
452 ELFYAML::ProgramHeader &YamlPhdr = Doc.ProgramHeaders[I];
453 Elf_Phdr Phdr;
454 zero(Phdr);
455 Phdr.p_type = YamlPhdr.Type;
456 Phdr.p_flags = YamlPhdr.Flags;
457 Phdr.p_vaddr = YamlPhdr.VAddr;
458 Phdr.p_paddr = YamlPhdr.PAddr;
459 PHeaders.push_back(Phdr);
460
461 if (!YamlPhdr.FirstSec && !YamlPhdr.LastSec)
462 continue;
463
464 // Get the index of the section, or 0 in the case when the section doesn't exist.
465 size_t First = NameToIndex[*YamlPhdr.FirstSec];
466 if (!First)
467 reportError("unknown section or fill referenced: '" + *YamlPhdr.FirstSec +
468 "' by the 'FirstSec' key of the program header with index " +
469 Twine(I));
470 size_t Last = NameToIndex[*YamlPhdr.LastSec];
471 if (!Last)
472 reportError("unknown section or fill referenced: '" + *YamlPhdr.LastSec +
473 "' by the 'LastSec' key of the program header with index " +
474 Twine(I));
475 if (!First || !Last)
476 continue;
477
478 if (First > Last)
479 reportError("program header with index " + Twine(I) +
480 ": the section index of " + *YamlPhdr.FirstSec +
481 " is greater than the index of " + *YamlPhdr.LastSec);
482
483 for (size_t I = First; I <= Last; ++I)
484 YamlPhdr.Chunks.push_back(Doc.Chunks[I - 1].get());
485 }
486}
487
488template <class ELFT>
489unsigned ELFState<ELFT>::toSectionIndex(StringRef S, StringRef LocSec,
490 StringRef LocSym) {
491 assert(LocSec.empty() || LocSym.empty());
492
493 unsigned Index;
494 if (!SN2I.lookup(S, Index) && !to_integer(S, Index)) {
495 if (!LocSym.empty())
496 reportError("unknown section referenced: '" + S + "' by YAML symbol '" +
497 LocSym + "'");
498 else
499 reportError("unknown section referenced: '" + S + "' by YAML section '" +
500 LocSec + "'");
501 return 0;
502 }
503
504 const ELFYAML::SectionHeaderTable &SectionHeaders =
505 Doc.getSectionHeaderTable();
506 if (SectionHeaders.IsImplicit ||
507 (SectionHeaders.NoHeaders && !*SectionHeaders.NoHeaders) ||
508 SectionHeaders.isDefault())
509 return Index;
510
511 assert(!SectionHeaders.NoHeaders.value_or(false) || !SectionHeaders.Sections);
512 size_t FirstExcluded =
513 SectionHeaders.Sections ? SectionHeaders.Sections->size() : 0;
514 if (Index > FirstExcluded) {
515 if (LocSym.empty())
516 reportError("unable to link '" + LocSec + "' to excluded section '" + S +
517 "'");
518 else
519 reportError("excluded section referenced: '" + S + "' by symbol '" +
520 LocSym + "'");
521 }
522 return Index;
523}
524
525template <class ELFT>
526unsigned ELFState<ELFT>::toSymbolIndex(StringRef S, StringRef LocSec,
527 bool IsDynamic) {
528 const NameToIdxMap &SymMap = IsDynamic ? DynSymN2I : SymN2I;
529 unsigned Index;
530 // Here we try to look up S in the symbol table. If it is not there,
531 // treat its value as a symbol index.
532 if (!SymMap.lookup(S, Index) && !to_integer(S, Index)) {
533 reportError("unknown symbol referenced: '" + S + "' by YAML section '" +
534 LocSec + "'");
535 return 0;
536 }
537 return Index;
538}
539
540template <class ELFT>
541static void overrideFields(ELFYAML::Section *From, typename ELFT::Shdr &To) {
542 if (!From)
543 return;
544 if (From->ShAddrAlign)
545 To.sh_addralign = *From->ShAddrAlign;
546 if (From->ShFlags)
547 To.sh_flags = *From->ShFlags;
548 if (From->ShName)
549 To.sh_name = *From->ShName;
550 if (From->ShOffset)
551 To.sh_offset = *From->ShOffset;
552 if (From->ShSize)
553 To.sh_size = *From->ShSize;
554 if (From->ShType)
555 To.sh_type = *From->ShType;
556}
557
558template <class ELFT>
559bool ELFState<ELFT>::initImplicitHeader(ContiguousBlobAccumulator &CBA,
560 Elf_Shdr &Header, StringRef SecName,
561 ELFYAML::Section *YAMLSec) {
562 // Check if the header was already initialized.
563 if (Header.sh_offset)
564 return false;
565
566 if (SecName == ".strtab")
567 initStrtabSectionHeader(Header, SecName, DotStrtab, CBA, YAMLSec);
568 else if (SecName == ".dynstr")
569 initStrtabSectionHeader(Header, SecName, DotDynstr, CBA, YAMLSec);
570 else if (SecName == SectionHeaderStringTableName)
571 initStrtabSectionHeader(Header, SecName, *ShStrtabStrings, CBA, YAMLSec);
572 else if (SecName == ".symtab")
573 initSymtabSectionHeader(Header, SymtabType::Static, CBA, YAMLSec);
574 else if (SecName == ".dynsym")
575 initSymtabSectionHeader(Header, SymtabType::Dynamic, CBA, YAMLSec);
576 else if (SecName.starts_with(".debug_")) {
577 // If a ".debug_*" section's type is a preserved one, e.g., SHT_DYNAMIC, we
578 // will not treat it as a debug section.
579 if (YAMLSec && !isa<ELFYAML::RawContentSection>(YAMLSec))
580 return false;
581 initDWARFSectionHeader(Header, SecName, CBA, YAMLSec);
582 } else
583 return false;
584
585 LocationCounter += Header.sh_size;
586
587 // Override section fields if requested.
588 overrideFields<ELFT>(YAMLSec, Header);
589 return true;
590}
591
592constexpr char SuffixStart = '(';
593constexpr char SuffixEnd = ')';
594
596 const Twine &Msg) {
597 // Do not add a space when a Name is empty.
598 std::string Ret = Name.empty() ? "" : Name.str() + ' ';
599 return Ret + (Twine(SuffixStart) + Msg + Twine(SuffixEnd)).str();
600}
601
603 if (S.empty() || S.back() != SuffixEnd)
604 return S;
605
606 // A special case for empty names. See appendUniqueSuffix() above.
607 size_t SuffixPos = S.rfind(SuffixStart);
608 if (SuffixPos == 0)
609 return "";
610
611 if (SuffixPos == StringRef::npos || S[SuffixPos - 1] != ' ')
612 return S;
613 return S.substr(0, SuffixPos - 1);
614}
615
616template <class ELFT>
617uint64_t ELFState<ELFT>::getSectionNameOffset(StringRef Name) {
618 // If a section is excluded from section headers, we do not save its name in
619 // the string table.
620 if (ExcludedSectionHeaders.count(Name))
621 return 0;
622 return ShStrtabStrings->getOffset(Name);
623}
624
626 const std::optional<yaml::BinaryRef> &Content,
627 const std::optional<llvm::yaml::Hex64> &Size) {
628 size_t ContentSize = 0;
629 if (Content) {
630 CBA.writeAsBinary(*Content);
631 ContentSize = Content->binary_size();
632 }
633
634 if (!Size)
635 return ContentSize;
636
637 CBA.writeZeros(*Size - ContentSize);
638 return *Size;
639}
640
642 switch (SecType) {
643 case ELF::SHT_REL:
644 case ELF::SHT_RELA:
645 case ELF::SHT_GROUP:
648 return ".symtab";
650 case ELF::SHT_HASH:
652 return ".dynsym";
653 case ELF::SHT_DYNSYM:
656 return ".dynstr";
657 case ELF::SHT_SYMTAB:
658 return ".strtab";
659 default:
660 return "";
661 }
662}
663
664template <class ELFT>
665void ELFState<ELFT>::initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
667 // Ensure SHN_UNDEF entry is present. An all-zero section header is a
668 // valid SHN_UNDEF entry since SHT_NULL == 0.
669 SHeaders.resize(Doc.getSections().size());
670
671 for (const std::unique_ptr<ELFYAML::Chunk> &D : Doc.Chunks) {
672 if (ELFYAML::Fill *S = dyn_cast<ELFYAML::Fill>(D.get())) {
673 S->Offset = alignToOffset(CBA, /*Align=*/1, S->Offset);
674 writeFill(*S, CBA);
675 LocationCounter += S->Size;
676 continue;
677 }
678
681 if (S->NoHeaders.value_or(false))
682 continue;
683
684 if (!S->Offset)
685 S->Offset = alignToOffset(CBA, sizeof(typename ELFT::uint),
686 /*Offset=*/std::nullopt);
687 else
688 S->Offset = alignToOffset(CBA, /*Align=*/1, S->Offset);
689
690 uint64_t Size = S->getNumHeaders(SHeaders.size()) * sizeof(Elf_Shdr);
691 // The full section header information might be not available here, so
692 // fill the space with zeroes as a placeholder.
693 CBA.writeZeros(Size);
694 LocationCounter += Size;
695 continue;
696 }
697
699 bool IsFirstUndefSection = Sec == Doc.getSections().front();
700 if (IsFirstUndefSection && Sec->IsImplicit)
701 continue;
702
703 Elf_Shdr &SHeader = SHeaders[SN2I.get(Sec->Name)];
704 if (Sec->Link) {
705 SHeader.sh_link = toSectionIndex(*Sec->Link, Sec->Name);
706 } else {
707 StringRef LinkSec = getDefaultLinkSec(Sec->Type);
708 unsigned Link = 0;
709 if (!LinkSec.empty() && !ExcludedSectionHeaders.count(LinkSec) &&
710 SN2I.lookup(LinkSec, Link))
711 SHeader.sh_link = Link;
712 }
713
714 if (Sec->EntSize)
715 SHeader.sh_entsize = *Sec->EntSize;
716 else
717 SHeader.sh_entsize = ELFYAML::getDefaultShEntSize<ELFT>(
718 Doc.Header.Machine.value_or(ELF::EM_NONE), Sec->Type, Sec->Name);
719
720 // We have a few sections like string or symbol tables that are usually
721 // added implicitly to the end. However, if they are explicitly specified
722 // in the YAML, we need to write them here. This ensures the file offset
723 // remains correct.
724 if (initImplicitHeader(CBA, SHeader, Sec->Name,
725 Sec->IsImplicit ? nullptr : Sec))
726 continue;
727
728 assert(Sec && "It can't be null unless it is an implicit section. But all "
729 "implicit sections should already have been handled above.");
730
731 SHeader.sh_name =
732 getSectionNameOffset(ELFYAML::dropUniqueSuffix(Sec->Name));
733 SHeader.sh_type = Sec->Type;
734 if (Sec->Flags)
735 SHeader.sh_flags = *Sec->Flags;
736 SHeader.sh_addralign = Sec->AddressAlign;
737
738 // Set the offset for all sections, except the SHN_UNDEF section with index
739 // 0 when not explicitly requested.
740 if (!IsFirstUndefSection || Sec->Offset)
741 SHeader.sh_offset = alignToOffset(CBA, SHeader.sh_addralign, Sec->Offset);
742
743 assignSectionAddress(SHeader, Sec);
744
745 if (IsFirstUndefSection) {
746 if (auto RawSec = dyn_cast<ELFYAML::RawContentSection>(Sec)) {
747 // We do not write any content for special SHN_UNDEF section.
748 if (RawSec->Size)
749 SHeader.sh_size = *RawSec->Size;
750 if (RawSec->Info)
751 SHeader.sh_info = *RawSec->Info;
752 }
753
754 LocationCounter += SHeader.sh_size;
755 SectionHeadersOverrideHelper.push_back({&SHeader, *Sec});
756 continue;
757 }
758
759 if (!isa<ELFYAML::NoBitsSection>(Sec) && (Sec->Content || Sec->Size))
760 SHeader.sh_size = writeContent(CBA, Sec->Content, Sec->Size);
761
762 if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec)) {
763 writeSectionContent(SHeader, *S, CBA);
764 } else if (auto S = dyn_cast<ELFYAML::SymtabShndxSection>(Sec)) {
765 writeSectionContent(SHeader, *S, CBA);
766 } else if (auto S = dyn_cast<ELFYAML::RelocationSection>(Sec)) {
767 writeSectionContent(SHeader, *S, CBA);
768 } else if (auto S = dyn_cast<ELFYAML::RelrSection>(Sec)) {
769 writeSectionContent(SHeader, *S, CBA);
770 } else if (auto S = dyn_cast<ELFYAML::GroupSection>(Sec)) {
771 writeSectionContent(SHeader, *S, CBA);
772 } else if (auto S = dyn_cast<ELFYAML::ARMIndexTableSection>(Sec)) {
773 writeSectionContent(SHeader, *S, CBA);
774 } else if (auto S = dyn_cast<ELFYAML::MipsABIFlags>(Sec)) {
775 writeSectionContent(SHeader, *S, CBA);
776 } else if (auto S = dyn_cast<ELFYAML::NoBitsSection>(Sec)) {
777 writeSectionContent(SHeader, *S, CBA);
778 } else if (auto S = dyn_cast<ELFYAML::DynamicSection>(Sec)) {
779 writeSectionContent(SHeader, *S, CBA);
780 } else if (auto S = dyn_cast<ELFYAML::SymverSection>(Sec)) {
781 writeSectionContent(SHeader, *S, CBA);
782 } else if (auto S = dyn_cast<ELFYAML::VerneedSection>(Sec)) {
783 writeSectionContent(SHeader, *S, CBA);
784 } else if (auto S = dyn_cast<ELFYAML::VerdefSection>(Sec)) {
785 writeSectionContent(SHeader, *S, CBA);
786 } else if (auto S = dyn_cast<ELFYAML::StackSizesSection>(Sec)) {
787 writeSectionContent(SHeader, *S, CBA);
788 } else if (auto S = dyn_cast<ELFYAML::HashSection>(Sec)) {
789 writeSectionContent(SHeader, *S, CBA);
790 } else if (auto S = dyn_cast<ELFYAML::AddrsigSection>(Sec)) {
791 writeSectionContent(SHeader, *S, CBA);
792 } else if (auto S = dyn_cast<ELFYAML::LinkerOptionsSection>(Sec)) {
793 writeSectionContent(SHeader, *S, CBA);
794 } else if (auto S = dyn_cast<ELFYAML::NoteSection>(Sec)) {
795 writeSectionContent(SHeader, *S, CBA);
796 } else if (auto S = dyn_cast<ELFYAML::GnuHashSection>(Sec)) {
797 writeSectionContent(SHeader, *S, CBA);
798 } else if (auto S = dyn_cast<ELFYAML::DependentLibrariesSection>(Sec)) {
799 writeSectionContent(SHeader, *S, CBA);
800 } else if (auto S = dyn_cast<ELFYAML::CallGraphProfileSection>(Sec)) {
801 writeSectionContent(SHeader, *S, CBA);
802 } else if (auto S = dyn_cast<ELFYAML::BBAddrMapSection>(Sec)) {
803 writeSectionContent(SHeader, *S, CBA);
804 } else {
805 llvm_unreachable("Unknown section type");
806 }
807
808 LocationCounter += SHeader.sh_size;
809 SectionHeadersOverrideHelper.push_back({&SHeader, *Sec});
810 }
811}
812
813template <class ELFT>
814void ELFState<ELFT>::overrideSectionHeaders(std::vector<Elf_Shdr> &SHeaders) {
815 for (std::pair<Elf_Shdr *, ELFYAML::Section> &HeaderAndSec :
816 SectionHeadersOverrideHelper)
817 overrideFields<ELFT>(&HeaderAndSec.second, *HeaderAndSec.first);
818}
819
820template <class ELFT>
821void ELFState<ELFT>::assignSectionAddress(Elf_Shdr &SHeader,
822 ELFYAML::Section *YAMLSec) {
823 if (YAMLSec && YAMLSec->Address) {
824 SHeader.sh_addr = *YAMLSec->Address;
825 LocationCounter = *YAMLSec->Address;
826 return;
827 }
828
829 // sh_addr represents the address in the memory image of a process. Sections
830 // in a relocatable object file or non-allocatable sections do not need
831 // sh_addr assignment.
832 if (Doc.Header.Type.value == ELF::ET_REL ||
833 !(SHeader.sh_flags & ELF::SHF_ALLOC))
834 return;
835
836 LocationCounter =
837 alignTo(LocationCounter, SHeader.sh_addralign ? SHeader.sh_addralign : 1);
838 SHeader.sh_addr = LocationCounter;
839}
840
842 for (size_t I = 0; I < Symbols.size(); ++I)
843 if (Symbols[I].Binding.value != ELF::STB_LOCAL)
844 return I;
845 return Symbols.size();
846}
847
848template <class ELFT>
849std::vector<typename ELFT::Sym>
850ELFState<ELFT>::toELFSymbols(ArrayRef<ELFYAML::Symbol> Symbols,
851 const StringTableBuilder &Strtab) {
852 std::vector<Elf_Sym> Ret;
853 Ret.resize(Symbols.size() + 1);
854
855 size_t I = 0;
856 for (const ELFYAML::Symbol &Sym : Symbols) {
857 Elf_Sym &Symbol = Ret[++I];
858
859 // If NameIndex, which contains the name offset, is explicitly specified, we
860 // use it. This is useful for preparing broken objects. Otherwise, we add
861 // the specified Name to the string table builder to get its offset.
862 if (Sym.StName)
863 Symbol.st_name = *Sym.StName;
864 else if (!Sym.Name.empty())
865 Symbol.st_name = Strtab.getOffset(ELFYAML::dropUniqueSuffix(Sym.Name));
866
867 Symbol.setBindingAndType(Sym.Binding, Sym.Type);
868 if (Sym.Section)
869 Symbol.st_shndx = toSectionIndex(*Sym.Section, "", Sym.Name);
870 else if (Sym.Index)
871 Symbol.st_shndx = *Sym.Index;
872
873 Symbol.st_value = Sym.Value.value_or(yaml::Hex64(0));
874 Symbol.st_other = Sym.Other.value_or(0);
875 Symbol.st_size = Sym.Size.value_or(yaml::Hex64(0));
876 }
877
878 return Ret;
879}
880
881template <class ELFT>
882void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
883 SymtabType STType,
885 ELFYAML::Section *YAMLSec) {
886
887 bool IsStatic = STType == SymtabType::Static;
889 if (IsStatic && Doc.Symbols)
890 Symbols = *Doc.Symbols;
891 else if (!IsStatic && Doc.DynamicSymbols)
892 Symbols = *Doc.DynamicSymbols;
893
896 if (RawSec && (RawSec->Content || RawSec->Size)) {
897 bool HasSymbolsDescription =
898 (IsStatic && Doc.Symbols) || (!IsStatic && Doc.DynamicSymbols);
899 if (HasSymbolsDescription) {
900 StringRef Property = (IsStatic ? "`Symbols`" : "`DynamicSymbols`");
901 if (RawSec->Content)
902 reportError("cannot specify both `Content` and " + Property +
903 " for symbol table section '" + RawSec->Name + "'");
904 if (RawSec->Size)
905 reportError("cannot specify both `Size` and " + Property +
906 " for symbol table section '" + RawSec->Name + "'");
907 return;
908 }
909 }
910
911 SHeader.sh_name = getSectionNameOffset(IsStatic ? ".symtab" : ".dynsym");
912
913 if (YAMLSec)
914 SHeader.sh_type = YAMLSec->Type;
915 else
916 SHeader.sh_type = IsStatic ? ELF::SHT_SYMTAB : ELF::SHT_DYNSYM;
917
918 if (YAMLSec && YAMLSec->Flags)
919 SHeader.sh_flags = *YAMLSec->Flags;
920 else if (!IsStatic)
921 SHeader.sh_flags = ELF::SHF_ALLOC;
922
923 // If the symbol table section is explicitly described in the YAML
924 // then we should set the fields requested.
925 SHeader.sh_info = (RawSec && RawSec->Info) ? (unsigned)(*RawSec->Info)
927 SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 8;
928
929 assignSectionAddress(SHeader, YAMLSec);
930
931 SHeader.sh_offset = alignToOffset(CBA, SHeader.sh_addralign,
932 RawSec ? RawSec->Offset : std::nullopt);
933
934 if (RawSec && (RawSec->Content || RawSec->Size)) {
935 assert(Symbols.empty());
936 SHeader.sh_size = writeContent(CBA, RawSec->Content, RawSec->Size);
937 return;
938 }
939
940 std::vector<Elf_Sym> Syms =
941 toELFSymbols(Symbols, IsStatic ? DotStrtab : DotDynstr);
942 SHeader.sh_size = Syms.size() * sizeof(Elf_Sym);
943 CBA.write((const char *)Syms.data(), SHeader.sh_size);
944}
945
946template <class ELFT>
947void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
950 ELFYAML::Section *YAMLSec) {
951 SHeader.sh_name = getSectionNameOffset(ELFYAML::dropUniqueSuffix(Name));
952 SHeader.sh_type = YAMLSec ? YAMLSec->Type : ELF::SHT_STRTAB;
953 SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 1;
954
957
958 SHeader.sh_offset = alignToOffset(CBA, SHeader.sh_addralign,
959 YAMLSec ? YAMLSec->Offset : std::nullopt);
960
961 if (RawSec && (RawSec->Content || RawSec->Size)) {
962 SHeader.sh_size = writeContent(CBA, RawSec->Content, RawSec->Size);
963 } else {
964 if (raw_ostream *OS = CBA.getRawOS(STB.getSize()))
965 STB.write(*OS);
966 SHeader.sh_size = STB.getSize();
967 }
968
969 if (RawSec && RawSec->Info)
970 SHeader.sh_info = *RawSec->Info;
971
972 if (YAMLSec && YAMLSec->Flags)
973 SHeader.sh_flags = *YAMLSec->Flags;
974 else if (Name == ".dynstr")
975 SHeader.sh_flags = ELF::SHF_ALLOC;
976
977 assignSectionAddress(SHeader, YAMLSec);
978}
979
980static bool shouldEmitDWARF(DWARFYAML::Data &DWARF, StringRef Name) {
981 SetVector<StringRef> DebugSecNames = DWARF.getNonEmptySectionNames();
982 return Name.consume_front(".") && DebugSecNames.count(Name);
983}
984
985template <class ELFT>
986Expected<uint64_t> emitDWARF(typename ELFT::Shdr &SHeader, StringRef Name,
987 const DWARFYAML::Data &DWARF,
989 // We are unable to predict the size of debug data, so we request to write 0
990 // bytes. This should always return us an output stream unless CBA is already
991 // in an error state.
992 raw_ostream *OS = CBA.getRawOS(0);
993 if (!OS)
994 return 0;
995
996 uint64_t BeginOffset = CBA.tell();
997
998 auto EmitFunc = DWARFYAML::getDWARFEmitterByName(Name.substr(1));
999 if (Error Err = EmitFunc(*OS, DWARF))
1000 return std::move(Err);
1001
1002 return CBA.tell() - BeginOffset;
1003}
1004
1005template <class ELFT>
1006void ELFState<ELFT>::initDWARFSectionHeader(Elf_Shdr &SHeader, StringRef Name,
1008 ELFYAML::Section *YAMLSec) {
1009 SHeader.sh_name = getSectionNameOffset(ELFYAML::dropUniqueSuffix(Name));
1010 SHeader.sh_type = YAMLSec ? YAMLSec->Type : ELF::SHT_PROGBITS;
1011 SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 1;
1012 SHeader.sh_offset = alignToOffset(CBA, SHeader.sh_addralign,
1013 YAMLSec ? YAMLSec->Offset : std::nullopt);
1014
1017 if (Doc.DWARF && shouldEmitDWARF(*Doc.DWARF, Name)) {
1018 if (RawSec && (RawSec->Content || RawSec->Size))
1019 reportError("cannot specify section '" + Name +
1020 "' contents in the 'DWARF' entry and the 'Content' "
1021 "or 'Size' in the 'Sections' entry at the same time");
1022 else {
1023 if (Expected<uint64_t> ShSizeOrErr =
1024 emitDWARF<ELFT>(SHeader, Name, *Doc.DWARF, CBA))
1025 SHeader.sh_size = *ShSizeOrErr;
1026 else
1027 reportError(ShSizeOrErr.takeError());
1028 }
1029 } else if (RawSec)
1030 SHeader.sh_size = writeContent(CBA, RawSec->Content, RawSec->Size);
1031 else
1032 llvm_unreachable("debug sections can only be initialized via the 'DWARF' "
1033 "entry or a RawContentSection");
1034
1035 if (RawSec && RawSec->Info)
1036 SHeader.sh_info = *RawSec->Info;
1037
1038 if (YAMLSec && YAMLSec->Flags)
1039 SHeader.sh_flags = *YAMLSec->Flags;
1040 else if (Name == ".debug_str")
1041 SHeader.sh_flags = ELF::SHF_MERGE | ELF::SHF_STRINGS;
1042
1043 assignSectionAddress(SHeader, YAMLSec);
1044}
1045
1046template <class ELFT> void ELFState<ELFT>::reportError(const Twine &Msg) {
1047 ErrHandler(Msg);
1048 HasError = true;
1049}
1050
1051template <class ELFT> void ELFState<ELFT>::reportError(Error Err) {
1052 handleAllErrors(std::move(Err), [&](const ErrorInfoBase &Err) {
1053 reportError(Err.message());
1054 });
1055}
1056
1057template <class ELFT>
1058std::vector<Fragment>
1059ELFState<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
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
1076template <class ELFT>
1077void 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
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
1148template <class ELFT>
1149void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1150 const ELFYAML::NoBitsSection &S,
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
1164template <class ELFT>
1165void ELFState<ELFT>::writeSectionContent(
1166 Elf_Shdr &SHeader, const ELFYAML::RawContentSection &Section,
1168 if (Section.Info)
1169 SHeader.sh_info = *Section.Info;
1170}
1171
1172static 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
1178template <class ELFT>
1179void ELFState<ELFT>::writeSectionContent(
1180 Elf_Shdr &SHeader, const ELFYAML::RelocationSection &Section,
1183 Section.Type == llvm::ELF::SHT_RELA ||
1184 Section.Type == llvm::ELF::SHT_CREL) &&
1185 "Section type is not SHT_REL nor SHT_RELA");
1186
1187 if (!Section.RelocatableSec.empty())
1188 SHeader.sh_info = toSectionIndex(Section.RelocatableSec, Section.Name);
1189
1190 if (!Section.Relocations)
1191 return;
1192
1193 const bool IsCrel = Section.Type == llvm::ELF::SHT_CREL;
1194 const bool IsRela = Section.Type == llvm::ELF::SHT_RELA;
1195 typename ELFT::uint OffsetMask = 8, Offset = 0, Addend = 0;
1196 uint32_t SymIdx = 0, Type = 0;
1197 uint64_t CurrentOffset = CBA.getOffset();
1198 if (IsCrel)
1199 for (const ELFYAML::Relocation &Rel : *Section.Relocations)
1200 OffsetMask |= Rel.Offset;
1201 const int Shift = llvm::countr_zero(OffsetMask);
1202 if (IsCrel)
1203 CBA.writeULEB128(Section.Relocations->size() * 8 + ELF::CREL_HDR_ADDEND +
1204 Shift);
1205 for (const ELFYAML::Relocation &Rel : *Section.Relocations) {
1206 const bool IsDynamic = Section.Link && (*Section.Link == ".dynsym");
1207 uint32_t CurSymIdx =
1208 Rel.Symbol ? toSymbolIndex(*Rel.Symbol, Section.Name, IsDynamic) : 0;
1209 if (IsCrel) {
1210 // The delta offset and flags member may be larger than uint64_t. Special
1211 // case the first byte (3 flag bits and 4 offset bits). Other ULEB128
1212 // bytes encode the remaining delta offset bits.
1213 auto DeltaOffset =
1214 (static_cast<typename ELFT::uint>(Rel.Offset) - Offset) >> Shift;
1215 Offset = Rel.Offset;
1216 uint8_t B =
1217 DeltaOffset * 8 + (SymIdx != CurSymIdx) + (Type != Rel.Type ? 2 : 0) +
1218 (Addend != static_cast<typename ELFT::uint>(Rel.Addend) ? 4 : 0);
1219 if (DeltaOffset < 0x10) {
1220 CBA.write(B);
1221 } else {
1222 CBA.write(B | 0x80);
1223 CBA.writeULEB128(DeltaOffset >> 4);
1224 }
1225 // Delta symidx/type/addend members (SLEB128).
1226 if (B & 1) {
1227 CBA.writeSLEB128(
1228 std::make_signed_t<typename ELFT::uint>(CurSymIdx - SymIdx));
1229 SymIdx = CurSymIdx;
1230 }
1231 if (B & 2) {
1232 CBA.writeSLEB128(static_cast<int32_t>(Rel.Type - Type));
1233 Type = Rel.Type;
1234 }
1235 if (B & 4) {
1236 CBA.writeSLEB128(
1237 std::make_signed_t<typename ELFT::uint>(Rel.Addend - Addend));
1238 Addend = Rel.Addend;
1239 }
1240 } else if (IsRela) {
1241 Elf_Rela REntry;
1242 zero(REntry);
1243 REntry.r_offset = Rel.Offset;
1244 REntry.r_addend = Rel.Addend;
1245 REntry.setSymbolAndType(CurSymIdx, Rel.Type, isMips64EL(Doc));
1246 CBA.write((const char *)&REntry, sizeof(REntry));
1247 } else {
1248 Elf_Rel REntry;
1249 zero(REntry);
1250 REntry.r_offset = Rel.Offset;
1251 REntry.setSymbolAndType(CurSymIdx, Rel.Type, isMips64EL(Doc));
1252 CBA.write((const char *)&REntry, sizeof(REntry));
1253 }
1254 }
1255
1256 SHeader.sh_size = CBA.getOffset() - CurrentOffset;
1257}
1258
1259template <class ELFT>
1260void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1261 const ELFYAML::RelrSection &Section,
1263 if (!Section.Entries)
1264 return;
1265
1266 for (llvm::yaml::Hex64 E : *Section.Entries) {
1267 if (!ELFT::Is64Bits && E > UINT32_MAX)
1268 reportError(Section.Name + ": the value is too large for 32-bits: 0x" +
1270 CBA.write<uintX_t>(E, ELFT::Endianness);
1271 }
1272
1273 SHeader.sh_size = sizeof(uintX_t) * Section.Entries->size();
1274}
1275
1276template <class ELFT>
1277void ELFState<ELFT>::writeSectionContent(
1278 Elf_Shdr &SHeader, const ELFYAML::SymtabShndxSection &Shndx,
1280 if (Shndx.Content || Shndx.Size) {
1281 SHeader.sh_size = writeContent(CBA, Shndx.Content, Shndx.Size);
1282 return;
1283 }
1284
1285 if (!Shndx.Entries)
1286 return;
1287
1288 for (uint32_t E : *Shndx.Entries)
1289 CBA.write<uint32_t>(E, ELFT::Endianness);
1290 SHeader.sh_size = Shndx.Entries->size() * SHeader.sh_entsize;
1291}
1292
1293template <class ELFT>
1294void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1295 const ELFYAML::GroupSection &Section,
1298 "Section type is not SHT_GROUP");
1299
1300 if (Section.Signature)
1301 SHeader.sh_info =
1302 toSymbolIndex(*Section.Signature, Section.Name, /*IsDynamic=*/false);
1303
1304 if (!Section.Members)
1305 return;
1306
1307 for (const ELFYAML::SectionOrType &Member : *Section.Members) {
1308 unsigned int SectionIndex = 0;
1309 if (Member.sectionNameOrType == "GRP_COMDAT")
1310 SectionIndex = llvm::ELF::GRP_COMDAT;
1311 else
1312 SectionIndex = toSectionIndex(Member.sectionNameOrType, Section.Name);
1313 CBA.write<uint32_t>(SectionIndex, ELFT::Endianness);
1314 }
1315 SHeader.sh_size = SHeader.sh_entsize * Section.Members->size();
1316}
1317
1318template <class ELFT>
1319void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1320 const ELFYAML::SymverSection &Section,
1322 if (!Section.Entries)
1323 return;
1324
1325 for (uint16_t Version : *Section.Entries)
1326 CBA.write<uint16_t>(Version, ELFT::Endianness);
1327 SHeader.sh_size = Section.Entries->size() * SHeader.sh_entsize;
1328}
1329
1330template <class ELFT>
1331void ELFState<ELFT>::writeSectionContent(
1332 Elf_Shdr &SHeader, const ELFYAML::StackSizesSection &Section,
1334 if (!Section.Entries)
1335 return;
1336
1337 for (const ELFYAML::StackSizeEntry &E : *Section.Entries) {
1338 CBA.write<uintX_t>(E.Address, ELFT::Endianness);
1339 SHeader.sh_size += sizeof(uintX_t) + CBA.writeULEB128(E.Size);
1340 }
1341}
1342
1343template <class ELFT>
1344void ELFState<ELFT>::writeSectionContent(
1345 Elf_Shdr &SHeader, const ELFYAML::BBAddrMapSection &Section,
1347 if (!Section.Entries) {
1348 if (Section.PGOAnalyses)
1350 << "PGOAnalyses should not exist in SHT_LLVM_BB_ADDR_MAP when "
1351 "Entries does not exist";
1352 return;
1353 }
1354
1355 const std::vector<BBAddrMapYAML::PGOAnalysisMapEntry> *PGOAnalyses = nullptr;
1356 if (Section.PGOAnalyses) {
1357 if (Section.Entries->size() != Section.PGOAnalyses->size())
1358 WithColor::warning() << "PGOAnalyses must be the same length as Entries "
1359 "in SHT_LLVM_BB_ADDR_MAP";
1360 else
1361 PGOAnalyses = &Section.PGOAnalyses.value();
1362 }
1363
1364 uint64_t CurrentOffset = CBA.getOffset();
1365 for (const auto &[Idx, E] : llvm::enumerate(*Section.Entries)) {
1366 // Write version and feature values.
1367 if (E.Version > 5)
1368 WithColor::warning() << "unsupported BB address map version: "
1369 << static_cast<int>(E.Version)
1370 << "; encoding using the most recent version";
1371 CBA.write(E.Version);
1372 if (E.Version < 5)
1373 CBA.write(static_cast<uint8_t>(E.Feature));
1374 else
1375 CBA.write<uint16_t>(E.Feature, ELFT::Endianness);
1376 auto FeatureOrErr = llvm::object::BBAddrMap::Features::decode(E.Feature);
1377 if (!FeatureOrErr) {
1378 // Invalid feature: warn and skip the entry.
1379 WithColor::warning() << toString(FeatureOrErr.takeError());
1380 continue;
1381 }
1382 bool MultiBBRangeFeatureEnabled = FeatureOrErr->MultiBBRange;
1383 bool MultiBBRange =
1384 MultiBBRangeFeatureEnabled ||
1385 (E.NumBBRanges.has_value() && E.NumBBRanges.value() != 1) ||
1386 (E.BBRanges && E.BBRanges->size() != 1);
1387 if (MultiBBRange && !MultiBBRangeFeatureEnabled)
1388 WithColor::warning() << "feature value(" << E.Feature
1389 << ") does not support multiple BB ranges.";
1390 if (MultiBBRange) {
1391 // Write the number of basic block ranges, which is overridden by the
1392 // 'NumBBRanges' field when specified.
1393 uint64_t NumBBRanges =
1394 E.NumBBRanges.value_or(E.BBRanges ? E.BBRanges->size() : 0);
1395 CBA.writeULEB128(NumBBRanges);
1396 }
1397 if (!E.BBRanges)
1398 continue;
1399 uint64_t TotalNumBlocks = 0;
1400 bool EmitCallsiteEndOffsets =
1401 FeatureOrErr->CallsiteEndOffsets || E.hasAnyCallsiteEndOffsets();
1402 for (const BBAddrMapYAML::BBAddrMapEntry::BBRangeEntry &BBR : *E.BBRanges) {
1403 // Write the base address of the range.
1404 CBA.write<uintX_t>(BBR.BaseAddress, ELFT::Endianness);
1405 // Write number of BBEntries (number of basic blocks in this basic block
1406 // range). This is overridden by the 'NumBlocks' YAML field when
1407 // specified.
1408 uint64_t NumBlocks =
1409 BBR.NumBlocks.value_or(BBR.BBEntries ? BBR.BBEntries->size() : 0);
1410 CBA.writeULEB128(NumBlocks);
1411 // Write all BBEntries in this BBRange.
1412 if (!BBR.BBEntries || FeatureOrErr->OmitBBEntries)
1413 continue;
1414 for (const BBAddrMapYAML::BBAddrMapEntry::BBEntry &BBE : *BBR.BBEntries) {
1415 ++TotalNumBlocks;
1416 if (E.Version > 1)
1417 CBA.writeULEB128(BBE.ID);
1418 CBA.writeULEB128(BBE.AddressOffset);
1419 if (EmitCallsiteEndOffsets) {
1420 size_t NumCallsiteEndOffsets =
1421 BBE.CallsiteEndOffsets ? BBE.CallsiteEndOffsets->size() : 0;
1422 CBA.writeULEB128(NumCallsiteEndOffsets);
1423 if (BBE.CallsiteEndOffsets) {
1425 CBA.writeULEB128(Offset);
1426 }
1427 }
1428 CBA.writeULEB128(BBE.Size);
1429 CBA.writeULEB128(BBE.Metadata);
1430 if (FeatureOrErr->BBHash || BBE.Hash.has_value()) {
1431 uint64_t Hash =
1432 BBE.Hash.has_value() ? BBE.Hash.value() : llvm::yaml::Hex64(0);
1433 CBA.write<uint64_t>(Hash, ELFT::Endianness);
1434 }
1435 }
1436 }
1437 if (!PGOAnalyses)
1438 continue;
1439 const BBAddrMapYAML::PGOAnalysisMapEntry &PGOEntry = PGOAnalyses->at(Idx);
1440
1441 if (PGOEntry.FuncEntryCount)
1442 CBA.writeULEB128(*PGOEntry.FuncEntryCount);
1443
1444 if (!PGOEntry.PGOBBEntries)
1445 continue;
1446
1447 const auto &PGOBBEntries = PGOEntry.PGOBBEntries.value();
1448 if (TotalNumBlocks != PGOBBEntries.size()) {
1449 WithColor::warning() << "PGOBBEntries must be the same length as "
1450 "BBEntries in the BB address map.\n"
1451 << "Mismatch on function with address: "
1452 << E.getFunctionAddress();
1453 continue;
1454 }
1455
1456 for (const auto &PGOBBE : PGOBBEntries) {
1457 if (PGOBBE.BBFreq)
1458 CBA.writeULEB128(*PGOBBE.BBFreq);
1459 if (FeatureOrErr->PostLinkCfg || PGOBBE.PostLinkBBFreq.has_value())
1460 CBA.writeULEB128(PGOBBE.PostLinkBBFreq.value_or(0));
1461 if (PGOBBE.Successors) {
1462 CBA.writeULEB128(PGOBBE.Successors->size());
1463 for (const auto &[ID, BrProb, PostLinkBrFreq] : *PGOBBE.Successors) {
1464 CBA.writeULEB128(ID);
1465 CBA.writeULEB128(BrProb);
1466 if (FeatureOrErr->PostLinkCfg || PostLinkBrFreq.has_value())
1467 CBA.writeULEB128(PostLinkBrFreq.value_or(0));
1468 }
1469 }
1470 }
1471 }
1472 SHeader.sh_size += CBA.getOffset() - CurrentOffset;
1473}
1474
1475template <class ELFT>
1476void ELFState<ELFT>::writeSectionContent(
1477 Elf_Shdr &SHeader, const ELFYAML::LinkerOptionsSection &Section,
1479 if (!Section.Options)
1480 return;
1481
1482 for (const ELFYAML::LinkerOption &LO : *Section.Options) {
1483 CBA.write(LO.Key.data(), LO.Key.size());
1484 CBA.write('\0');
1485 CBA.write(LO.Value.data(), LO.Value.size());
1486 CBA.write('\0');
1487 SHeader.sh_size += (LO.Key.size() + LO.Value.size() + 2);
1488 }
1489}
1490
1491template <class ELFT>
1492void ELFState<ELFT>::writeSectionContent(
1493 Elf_Shdr &SHeader, const ELFYAML::DependentLibrariesSection &Section,
1495 if (!Section.Libs)
1496 return;
1497
1498 for (StringRef Lib : *Section.Libs) {
1499 CBA.write(Lib.data(), Lib.size());
1500 CBA.write('\0');
1501 SHeader.sh_size += Lib.size() + 1;
1502 }
1503}
1504
1505template <class ELFT>
1507ELFState<ELFT>::alignToOffset(ContiguousBlobAccumulator &CBA, uint64_t Align,
1508 std::optional<llvm::yaml::Hex64> Offset) {
1509 uint64_t CurrentOffset = CBA.getOffset();
1510 uint64_t AlignedOffset;
1511
1512 if (Offset) {
1513 if ((uint64_t)*Offset < CurrentOffset) {
1514 reportError("the 'Offset' value (0x" +
1515 Twine::utohexstr((uint64_t)*Offset) + ") goes backward");
1516 return CurrentOffset;
1517 }
1518
1519 // We ignore an alignment when an explicit offset has been requested.
1520 AlignedOffset = *Offset;
1521 } else {
1522 AlignedOffset = alignTo(CurrentOffset, std::max(Align, (uint64_t)1));
1523 }
1524
1525 CBA.writeZeros(AlignedOffset - CurrentOffset);
1526 return AlignedOffset;
1527}
1528
1529template <class ELFT>
1530void ELFState<ELFT>::writeSectionContent(
1531 Elf_Shdr &SHeader, const ELFYAML::CallGraphProfileSection &Section,
1533 if (!Section.Entries)
1534 return;
1535
1536 for (const ELFYAML::CallGraphEntryWeight &E : *Section.Entries) {
1537 CBA.write<uint64_t>(E.Weight, ELFT::Endianness);
1538 SHeader.sh_size += sizeof(object::Elf_CGProfile_Impl<ELFT>);
1539 }
1540}
1541
1542template <class ELFT>
1543void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1544 const ELFYAML::HashSection &Section,
1546 if (!Section.Bucket)
1547 return;
1548
1549 CBA.write<uint32_t>(
1550 Section.NBucket.value_or(llvm::yaml::Hex64(Section.Bucket->size())),
1551 ELFT::Endianness);
1552 CBA.write<uint32_t>(
1553 Section.NChain.value_or(llvm::yaml::Hex64(Section.Chain->size())),
1554 ELFT::Endianness);
1555
1556 for (uint32_t Val : *Section.Bucket)
1557 CBA.write<uint32_t>(Val, ELFT::Endianness);
1558 for (uint32_t Val : *Section.Chain)
1559 CBA.write<uint32_t>(Val, ELFT::Endianness);
1560
1561 SHeader.sh_size = (2 + Section.Bucket->size() + Section.Chain->size()) * 4;
1562}
1563
1564template <class ELFT>
1565void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1566 const ELFYAML::VerdefSection &Section,
1568
1569 if (Section.Info)
1570 SHeader.sh_info = *Section.Info;
1571 else if (Section.Entries)
1572 SHeader.sh_info = Section.Entries->size();
1573
1574 if (!Section.Entries)
1575 return;
1576
1577 uint64_t AuxCnt = 0;
1578 for (size_t I = 0; I < Section.Entries->size(); ++I) {
1579 const ELFYAML::VerdefEntry &E = (*Section.Entries)[I];
1580
1581 Elf_Verdef VerDef;
1582 VerDef.vd_version = E.Version.value_or(1);
1583 VerDef.vd_flags = E.Flags.value_or(0);
1584 VerDef.vd_ndx = E.VersionNdx.value_or(0);
1585 VerDef.vd_hash = E.Hash.value_or(0);
1586 VerDef.vd_aux = E.VDAux.value_or(sizeof(Elf_Verdef));
1587 VerDef.vd_cnt = E.VerNames.size();
1588 if (I == Section.Entries->size() - 1)
1589 VerDef.vd_next = 0;
1590 else
1591 VerDef.vd_next =
1592 sizeof(Elf_Verdef) + E.VerNames.size() * sizeof(Elf_Verdaux);
1593 CBA.write((const char *)&VerDef, sizeof(Elf_Verdef));
1594
1595 for (size_t J = 0; J < E.VerNames.size(); ++J, ++AuxCnt) {
1596 Elf_Verdaux VerdAux;
1597 VerdAux.vda_name = DotDynstr.getOffset(E.VerNames[J]);
1598 if (J == E.VerNames.size() - 1)
1599 VerdAux.vda_next = 0;
1600 else
1601 VerdAux.vda_next = sizeof(Elf_Verdaux);
1602 CBA.write((const char *)&VerdAux, sizeof(Elf_Verdaux));
1603 }
1604 }
1605
1606 SHeader.sh_size = Section.Entries->size() * sizeof(Elf_Verdef) +
1607 AuxCnt * sizeof(Elf_Verdaux);
1608}
1609
1610template <class ELFT>
1611void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1612 const ELFYAML::VerneedSection &Section,
1614 if (Section.Info)
1615 SHeader.sh_info = *Section.Info;
1616 else if (Section.VerneedV)
1617 SHeader.sh_info = Section.VerneedV->size();
1618
1619 if (!Section.VerneedV)
1620 return;
1621
1622 uint64_t AuxCnt = 0;
1623 for (size_t I = 0; I < Section.VerneedV->size(); ++I) {
1624 const ELFYAML::VerneedEntry &VE = (*Section.VerneedV)[I];
1625
1626 Elf_Verneed VerNeed;
1627 VerNeed.vn_version = VE.Version;
1628 VerNeed.vn_file = DotDynstr.getOffset(VE.File);
1629 if (I == Section.VerneedV->size() - 1)
1630 VerNeed.vn_next = 0;
1631 else
1632 VerNeed.vn_next =
1633 sizeof(Elf_Verneed) + VE.AuxV.size() * sizeof(Elf_Vernaux);
1634 VerNeed.vn_cnt = VE.AuxV.size();
1635 VerNeed.vn_aux = sizeof(Elf_Verneed);
1636 CBA.write((const char *)&VerNeed, sizeof(Elf_Verneed));
1637
1638 for (size_t J = 0; J < VE.AuxV.size(); ++J, ++AuxCnt) {
1639 const ELFYAML::VernauxEntry &VAuxE = VE.AuxV[J];
1640
1641 Elf_Vernaux VernAux;
1642 VernAux.vna_hash = VAuxE.Hash;
1643 VernAux.vna_flags = VAuxE.Flags;
1644 VernAux.vna_other = VAuxE.Other;
1645 VernAux.vna_name = DotDynstr.getOffset(VAuxE.Name);
1646 if (J == VE.AuxV.size() - 1)
1647 VernAux.vna_next = 0;
1648 else
1649 VernAux.vna_next = sizeof(Elf_Vernaux);
1650 CBA.write((const char *)&VernAux, sizeof(Elf_Vernaux));
1651 }
1652 }
1653
1654 SHeader.sh_size = Section.VerneedV->size() * sizeof(Elf_Verneed) +
1655 AuxCnt * sizeof(Elf_Vernaux);
1656}
1657
1658template <class ELFT>
1659void ELFState<ELFT>::writeSectionContent(
1660 Elf_Shdr &SHeader, const ELFYAML::ARMIndexTableSection &Section,
1662 if (!Section.Entries)
1663 return;
1664
1665 for (const ELFYAML::ARMIndexTableEntry &E : *Section.Entries) {
1666 CBA.write<uint32_t>(E.Offset, ELFT::Endianness);
1667 CBA.write<uint32_t>(E.Value, ELFT::Endianness);
1668 }
1669 SHeader.sh_size = Section.Entries->size() * 8;
1670}
1671
1672template <class ELFT>
1673void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1674 const ELFYAML::MipsABIFlags &Section,
1677 "Section type is not SHT_MIPS_ABIFLAGS");
1678
1680 zero(Flags);
1681 SHeader.sh_size = SHeader.sh_entsize;
1682
1683 Flags.version = Section.Version;
1684 Flags.isa_level = Section.ISALevel;
1685 Flags.isa_rev = Section.ISARevision;
1686 Flags.gpr_size = Section.GPRSize;
1687 Flags.cpr1_size = Section.CPR1Size;
1688 Flags.cpr2_size = Section.CPR2Size;
1689 Flags.fp_abi = Section.FpABI;
1690 Flags.isa_ext = Section.ISAExtension;
1691 Flags.ases = Section.ASEs;
1692 Flags.flags1 = Section.Flags1;
1693 Flags.flags2 = Section.Flags2;
1694 CBA.write((const char *)&Flags, sizeof(Flags));
1695}
1696
1697template <class ELFT>
1698void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1699 const ELFYAML::DynamicSection &Section,
1702 "Section type is not SHT_DYNAMIC");
1703
1704 if (!Section.Entries)
1705 return;
1706
1707 for (const ELFYAML::DynamicEntry &DE : *Section.Entries) {
1708 CBA.write<uintX_t>(DE.Tag, ELFT::Endianness);
1709 CBA.write<uintX_t>(DE.Val, ELFT::Endianness);
1710 }
1711 SHeader.sh_size = 2 * sizeof(uintX_t) * Section.Entries->size();
1712}
1713
1714template <class ELFT>
1715void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1716 const ELFYAML::AddrsigSection &Section,
1718 if (!Section.Symbols)
1719 return;
1720
1721 for (StringRef Sym : *Section.Symbols)
1722 SHeader.sh_size +=
1723 CBA.writeULEB128(toSymbolIndex(Sym, Section.Name, /*IsDynamic=*/false));
1724}
1725
1726template <class ELFT>
1727void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1728 const ELFYAML::NoteSection &Section,
1730 if (!Section.Notes || Section.Notes->empty())
1731 return;
1732
1733 unsigned Align;
1734 switch (Section.AddressAlign) {
1735 case 0:
1736 case 4:
1737 Align = 4;
1738 break;
1739 case 8:
1740 Align = 8;
1741 break;
1742 default:
1743 reportError(Section.Name + ": invalid alignment for a note section: 0x" +
1744 Twine::utohexstr(Section.AddressAlign));
1745 return;
1746 }
1747
1748 if (CBA.getOffset() != alignTo(CBA.getOffset(), Align)) {
1749 reportError(Section.Name + ": invalid offset of a note section: 0x" +
1750 Twine::utohexstr(CBA.getOffset()) + ", should be aligned to " +
1751 Twine(Align));
1752 return;
1753 }
1754
1755 uint64_t Offset = CBA.tell();
1756 for (const ELFYAML::NoteEntry &NE : *Section.Notes) {
1757 // Write name size.
1758 if (NE.Name.empty())
1759 CBA.write<uint32_t>(0, ELFT::Endianness);
1760 else
1761 CBA.write<uint32_t>(NE.Name.size() + 1, ELFT::Endianness);
1762
1763 // Write description size.
1764 if (NE.Desc.binary_size() == 0)
1765 CBA.write<uint32_t>(0, ELFT::Endianness);
1766 else
1767 CBA.write<uint32_t>(NE.Desc.binary_size(), ELFT::Endianness);
1768
1769 // Write type.
1770 CBA.write<uint32_t>(NE.Type, ELFT::Endianness);
1771
1772 // Write name, null terminator and padding.
1773 if (!NE.Name.empty()) {
1774 CBA.write(NE.Name.data(), NE.Name.size());
1775 CBA.write('\0');
1776 }
1777
1778 // Write description and padding.
1779 if (NE.Desc.binary_size() != 0) {
1780 CBA.padToAlignment(Align);
1781 CBA.writeAsBinary(NE.Desc);
1782 }
1783
1784 CBA.padToAlignment(Align);
1785 }
1786
1787 SHeader.sh_size = CBA.tell() - Offset;
1788}
1789
1790template <class ELFT>
1791void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1792 const ELFYAML::GnuHashSection &Section,
1794 if (!Section.HashBuckets)
1795 return;
1796
1797 if (!Section.Header)
1798 return;
1799
1800 // We write the header first, starting with the hash buckets count. Normally
1801 // it is the number of entries in HashBuckets, but the "NBuckets" property can
1802 // be used to override this field, which is useful for producing broken
1803 // objects.
1804 if (Section.Header->NBuckets)
1805 CBA.write<uint32_t>(*Section.Header->NBuckets, ELFT::Endianness);
1806 else
1807 CBA.write<uint32_t>(Section.HashBuckets->size(), ELFT::Endianness);
1808
1809 // Write the index of the first symbol in the dynamic symbol table accessible
1810 // via the hash table.
1811 CBA.write<uint32_t>(Section.Header->SymNdx, ELFT::Endianness);
1812
1813 // Write the number of words in the Bloom filter. As above, the "MaskWords"
1814 // property can be used to set this field to any value.
1815 if (Section.Header->MaskWords)
1816 CBA.write<uint32_t>(*Section.Header->MaskWords, ELFT::Endianness);
1817 else
1818 CBA.write<uint32_t>(Section.BloomFilter->size(), ELFT::Endianness);
1819
1820 // Write the shift constant used by the Bloom filter.
1821 CBA.write<uint32_t>(Section.Header->Shift2, ELFT::Endianness);
1822
1823 // We've finished writing the header. Now write the Bloom filter.
1824 for (llvm::yaml::Hex64 Val : *Section.BloomFilter)
1825 CBA.write<uintX_t>(Val, ELFT::Endianness);
1826
1827 // Write an array of hash buckets.
1828 for (llvm::yaml::Hex32 Val : *Section.HashBuckets)
1829 CBA.write<uint32_t>(Val, ELFT::Endianness);
1830
1831 // Write an array of hash values.
1832 for (llvm::yaml::Hex32 Val : *Section.HashValues)
1833 CBA.write<uint32_t>(Val, ELFT::Endianness);
1834
1835 SHeader.sh_size = 16 /*Header size*/ +
1836 Section.BloomFilter->size() * sizeof(typename ELFT::uint) +
1837 Section.HashBuckets->size() * 4 +
1838 Section.HashValues->size() * 4;
1839}
1840
1841template <class ELFT>
1842void ELFState<ELFT>::writeFill(ELFYAML::Fill &Fill,
1844 size_t PatternSize = Fill.Pattern ? Fill.Pattern->binary_size() : 0;
1845 if (!PatternSize) {
1846 CBA.writeZeros(Fill.Size);
1847 return;
1848 }
1849
1850 // Fill the content with the specified pattern.
1851 uint64_t Written = 0;
1852 for (; Written + PatternSize <= Fill.Size; Written += PatternSize)
1853 CBA.writeAsBinary(*Fill.Pattern);
1854 CBA.writeAsBinary(*Fill.Pattern, Fill.Size - Written);
1855}
1856
1857template <class ELFT>
1858DenseMap<StringRef, size_t> ELFState<ELFT>::buildSectionHeaderReorderMap() {
1859 const ELFYAML::SectionHeaderTable &SectionHeaders =
1860 Doc.getSectionHeaderTable();
1861 if (SectionHeaders.IsImplicit || SectionHeaders.NoHeaders ||
1862 SectionHeaders.isDefault())
1864
1866 size_t SecNdx = 0;
1867 StringSet<> Seen;
1868
1869 auto AddSection = [&](const ELFYAML::SectionHeader &Hdr) {
1870 if (!Ret.try_emplace(Hdr.Name, ++SecNdx).second)
1871 reportError("repeated section name: '" + Hdr.Name +
1872 "' in the section header description");
1873 Seen.insert(Hdr.Name);
1874 };
1875
1876 if (SectionHeaders.Sections)
1877 for (const ELFYAML::SectionHeader &Hdr : *SectionHeaders.Sections)
1878 AddSection(Hdr);
1879
1880 if (SectionHeaders.Excluded)
1881 for (const ELFYAML::SectionHeader &Hdr : *SectionHeaders.Excluded)
1882 AddSection(Hdr);
1883
1884 for (const ELFYAML::Section *S : Doc.getSections()) {
1885 // Ignore special first SHT_NULL section.
1886 if (S == Doc.getSections().front())
1887 continue;
1888 if (!Seen.count(S->Name))
1889 reportError("section '" + S->Name +
1890 "' should be present in the 'Sections' or 'Excluded' lists");
1891 Seen.erase(S->Name);
1892 }
1893
1894 for (const auto &It : Seen)
1895 reportError("section header contains undefined section '" + It.getKey() +
1896 "'");
1897 return Ret;
1898}
1899
1900template <class ELFT> void ELFState<ELFT>::buildSectionIndex() {
1901 // A YAML description can have an explicit section header declaration that
1902 // allows to change the order of section headers.
1903 DenseMap<StringRef, size_t> ReorderMap = buildSectionHeaderReorderMap();
1904
1905 if (HasError)
1906 return;
1907
1908 // Build excluded section headers map.
1909 std::vector<ELFYAML::Section *> Sections = Doc.getSections();
1910 const ELFYAML::SectionHeaderTable &SectionHeaders =
1911 Doc.getSectionHeaderTable();
1912 if (SectionHeaders.Excluded)
1913 for (const ELFYAML::SectionHeader &Hdr : *SectionHeaders.Excluded)
1914 if (!ExcludedSectionHeaders.insert(Hdr.Name).second)
1915 llvm_unreachable("buildSectionIndex() failed");
1916
1917 if (SectionHeaders.NoHeaders.value_or(false))
1918 for (const ELFYAML::Section *S : Sections)
1919 if (!ExcludedSectionHeaders.insert(S->Name).second)
1920 llvm_unreachable("buildSectionIndex() failed");
1921
1922 size_t SecNdx = -1;
1923 for (const ELFYAML::Section *S : Sections) {
1924 ++SecNdx;
1925
1926 size_t Index = ReorderMap.empty() ? SecNdx : ReorderMap.lookup(S->Name);
1927 if (!SN2I.addName(S->Name, Index))
1928 llvm_unreachable("buildSectionIndex() failed");
1929
1930 if (!ExcludedSectionHeaders.count(S->Name))
1931 ShStrtabStrings->add(ELFYAML::dropUniqueSuffix(S->Name));
1932 }
1933}
1934
1935template <class ELFT> void ELFState<ELFT>::buildSymbolIndexes() {
1936 auto Build = [this](ArrayRef<ELFYAML::Symbol> V, NameToIdxMap &Map) {
1937 for (size_t I = 0, S = V.size(); I < S; ++I) {
1938 const ELFYAML::Symbol &Sym = V[I];
1939 if (!Sym.Name.empty() && !Map.addName(Sym.Name, I + 1))
1940 reportError("repeated symbol name: '" + Sym.Name + "'");
1941 }
1942 };
1943
1944 if (Doc.Symbols)
1945 Build(*Doc.Symbols, SymN2I);
1946 if (Doc.DynamicSymbols)
1947 Build(*Doc.DynamicSymbols, DynSymN2I);
1948}
1949
1950template <class ELFT> void ELFState<ELFT>::finalizeStrings() {
1951 // Add the regular symbol names to .strtab section.
1952 if (Doc.Symbols)
1953 for (const ELFYAML::Symbol &Sym : *Doc.Symbols)
1954 DotStrtab.add(ELFYAML::dropUniqueSuffix(Sym.Name));
1955 DotStrtab.finalize();
1956
1957 // Add the dynamic symbol names to .dynstr section.
1958 if (Doc.DynamicSymbols)
1959 for (const ELFYAML::Symbol &Sym : *Doc.DynamicSymbols)
1960 DotDynstr.add(ELFYAML::dropUniqueSuffix(Sym.Name));
1961
1962 // SHT_GNU_verdef and SHT_GNU_verneed sections might also
1963 // add strings to .dynstr section.
1964 for (const ELFYAML::Chunk *Sec : Doc.getSections()) {
1965 if (auto VerNeed = dyn_cast<ELFYAML::VerneedSection>(Sec)) {
1966 if (VerNeed->VerneedV) {
1967 for (const ELFYAML::VerneedEntry &VE : *VerNeed->VerneedV) {
1968 DotDynstr.add(VE.File);
1969 for (const ELFYAML::VernauxEntry &Aux : VE.AuxV)
1970 DotDynstr.add(Aux.Name);
1971 }
1972 }
1973 } else if (auto VerDef = dyn_cast<ELFYAML::VerdefSection>(Sec)) {
1974 if (VerDef->Entries)
1975 for (const ELFYAML::VerdefEntry &E : *VerDef->Entries)
1976 for (StringRef Name : E.VerNames)
1977 DotDynstr.add(Name);
1978 }
1979 }
1980
1981 DotDynstr.finalize();
1982
1983 // Don't finalize the section header string table a second time if it has
1984 // already been finalized due to being one of the symbol string tables.
1985 if (ShStrtabStrings != &DotStrtab && ShStrtabStrings != &DotDynstr)
1986 ShStrtabStrings->finalize();
1987}
1988
1989template <class ELFT>
1990bool ELFState<ELFT>::writeELF(raw_ostream &OS, ELFYAML::Object &Doc,
1991 yaml::ErrorHandler EH, uint64_t MaxSize) {
1992 ELFState<ELFT> State(Doc, EH);
1993 if (State.HasError)
1994 return false;
1995
1996 // Build the section index, which adds sections to the section header string
1997 // table first, so that we can finalize the section header string table.
1998 State.buildSectionIndex();
1999 State.buildSymbolIndexes();
2000
2001 // Finalize section header string table and the .strtab and .dynstr sections.
2002 // We do this early because we want to finalize the string table builders
2003 // before writing the content of the sections that might want to use them.
2004 State.finalizeStrings();
2005
2006 if (State.HasError)
2007 return false;
2008
2009 std::vector<Elf_Phdr> PHeaders;
2010 State.initProgramHeaders(PHeaders);
2011
2012 // XXX: This offset is tightly coupled with the order that we write
2013 // things to `OS`.
2014 const size_t SectionContentBeginOffset =
2015 sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * Doc.ProgramHeaders.size();
2016 // It is quite easy to accidentally create output with yaml2obj that is larger
2017 // than intended, for example, due to an issue in the YAML description.
2018 // We limit the maximum allowed output size, but also provide a command line
2019 // option to change this limitation.
2020 ContiguousBlobAccumulator CBA(SectionContentBeginOffset, MaxSize);
2021
2022 std::vector<Elf_Shdr> SHeaders;
2023 State.initSectionHeaders(SHeaders, CBA);
2024
2025 // Now we can decide segment offsets.
2026 State.setProgramHeaderLayout(PHeaders, SHeaders);
2027
2028 // Override section fields, if requested. This needs to happen after program
2029 // header layout happens, because otherwise the layout will use the new
2030 // values.
2031 State.overrideSectionHeaders(SHeaders);
2032
2033 bool ReachedLimit = CBA.getOffset() > MaxSize;
2034 if (Error E = CBA.takeLimitError()) {
2035 // We report a custom error message instead below.
2036 consumeError(std::move(E));
2037 ReachedLimit = true;
2038 }
2039
2040 if (ReachedLimit)
2041 State.reportError(
2042 "the desired output size is greater than permitted. Use the "
2043 "--max-size option to change the limit");
2044
2045 if (State.HasError)
2046 return false;
2047
2048 State.writeELFHeader(OS);
2049 writeArrayData(OS, ArrayRef(PHeaders));
2050
2052 if (!SHT.NoHeaders.value_or(false))
2053 CBA.updateDataAt(*SHT.Offset, SHeaders.data(),
2054 SHT.getNumHeaders(SHeaders.size()) * sizeof(Elf_Shdr));
2055
2056 CBA.writeBlobToStream(OS);
2057 return true;
2058}
2059
2060namespace llvm {
2061namespace yaml {
2062
2064 uint64_t MaxSize) {
2065 bool IsLE = Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
2066 bool Is64Bit = Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
2067 if (Is64Bit) {
2068 if (IsLE)
2069 return ELFState<object::ELF64LE>::writeELF(Out, Doc, EH, MaxSize);
2070 return ELFState<object::ELF64BE>::writeELF(Out, Doc, EH, MaxSize);
2071 }
2072 if (IsLE)
2073 return ELFState<object::ELF32LE>::writeELF(Out, Doc, EH, MaxSize);
2074 return ELFState<object::ELF32BE>::writeELF(Out, Doc, EH, MaxSize);
2075}
2076
2077} // namespace yaml
2078} // namespace llvm
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static Error reportError(StringRef Message)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines ContiguousBlobAccumulator, the size-limited output buffer shared by the yaml2obj em...
Common declarations for yaml2obj.
This file declares classes for handling the YAML representation of DWARF Debug Info.
DXIL Resource Implicit Binding
This file defines the DenseMap class.
static StringRef getDefaultLinkSec(unsigned SecType)
constexpr char SuffixEnd
static void overrideFields(ELFYAML::Section *From, typename ELFT::Shdr &To)
static void writeArrayData(raw_ostream &OS, ArrayRef< T > A)
static bool isMips64EL(const ELFYAML::Object &Obj)
static size_t arrayDataSize(ArrayRef< T > A)
constexpr char SuffixStart
static void zero(T &Obj)
static bool shouldEmitDWARF(DWARFYAML::Data &DWARF, StringRef Name)
static uint64_t writeContent(ContiguousBlobAccumulator &CBA, const std::optional< yaml::BinaryRef > &Content, const std::optional< llvm::yaml::Hex64 > &Size)
Expected< uint64_t > emitDWARF(typename ELFT::Shdr &SHeader, StringRef Name, const DWARFYAML::Data &DWARF, ContiguousBlobAccumulator &CBA)
static size_t findFirstNonGlobal(ArrayRef< ELFYAML::Symbol > Symbols)
#define LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
Definition ELFTypes.h:119
This file declares classes for handling the YAML representation of ELF.
static bool lookup(const GsymReader &GR, GsymDataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr, uint64_t Addr, SourceLocations &SrcLocs, llvm::Error &Err)
A Lookup helper functions.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define H(x, y, z)
Definition MD5.cpp:56
#define T
if(PassOpts->AAPipeline)
const char * Msg
This file implements a set that has insertion order iteration characteristics.
StringSet - A set-like wrapper for the StringMap.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:250
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:299
bool empty() const
Definition DenseMap.h:171
Base class for error info classes.
Definition Error.h:44
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Tagged union holding either a T or a Error.
Definition Error.h:485
A vector that has set insertion semantics.
Definition SetVector.h:57
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
Definition SetVector.h:262
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:151
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:339
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Definition StringMap.h:274
void erase(iterator I)
Definition StringMap.h:417
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static constexpr size_t npos
Definition StringRef.h:58
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
char back() const
Get the last character in the string.
Definition StringRef.h:153
size_t rfind(char C, size_t From=npos) const
Search for the last character C in the string.
Definition StringRef.h:365
StringRef copy(Allocator &A) const
Definition StringRef.h:160
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition StringSet.h:25
std::pair< typename Base::iterator, bool > insert(StringRef key)
Definition StringSet.h:39
Utility for building string tables with deduplicated suffixes.
LLVM_ABI size_t getOffset(CachedHashStringRef S) const
Get the offest of a string in the string table.
LLVM_ABI void write(raw_ostream &OS) const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static Twine utohexstr(uint64_t Val)
Definition Twine.h:385
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI raw_ostream & warning()
Convenience method for printing "warning: " to stderr.
Definition WithColor.cpp:86
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & write(unsigned char C)
LLVM_ABI uint64_t padToAlignment(unsigned Align)
LLVM_ABI void writeAsBinary(const BinaryRef &Bin, uint64_t N=UINT64_MAX)
void write(const char *Ptr, size_t Size)
LLVM_ABI void updateDataAt(uint64_t Pos, const void *Data, size_t Size)
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
LLVM_ABI std::function< Error(raw_ostream &, const Data &)> getDWARFEmitterByName(StringRef SecName)
LLVM_ABI std::string appendUniqueSuffix(StringRef Name, const Twine &Msg)
unsigned getDefaultShEntSize(unsigned EMachine, ELF_SHT SecType, StringRef SecName)
Definition ELFYAML.h:78
LLVM_ABI StringRef dropUniqueSuffix(StringRef S)
LLVM_ABI bool shouldAllocateFileSpace(ArrayRef< ProgramHeader > Phdrs, const NoBitsSection &S)
@ EV_CURRENT
Definition ELF.h:130
@ SHF_MERGE
Definition ELF.h:1262
@ SHF_STRINGS
Definition ELF.h:1265
@ SHF_ALLOC
Definition ELF.h:1256
@ EI_DATA
Definition ELF.h:56
@ EI_MAG3
Definition ELF.h:54
@ EI_MAG1
Definition ELF.h:52
@ EI_VERSION
Definition ELF.h:57
@ EI_MAG2
Definition ELF.h:53
@ EI_ABIVERSION
Definition ELF.h:59
@ EI_MAG0
Definition ELF.h:51
@ EI_CLASS
Definition ELF.h:55
@ EI_OSABI
Definition ELF.h:58
@ EM_NONE
Definition ELF.h:138
@ EM_MIPS
Definition ELF.h:146
@ SHT_STRTAB
Definition ELF.h:1157
@ SHT_GROUP
Definition ELF.h:1169
@ SHT_PROGBITS
Definition ELF.h:1155
@ SHT_REL
Definition ELF.h:1163
@ SHT_NULL
Definition ELF.h:1154
@ SHT_LLVM_CALL_GRAPH_PROFILE
Definition ELF.h:1192
@ SHT_NOBITS
Definition ELF.h:1162
@ SHT_SYMTAB
Definition ELF.h:1156
@ SHT_GNU_verneed
Definition ELF.h:1206
@ SHT_GNU_verdef
Definition ELF.h:1205
@ SHT_CREL
Definition ELF.h:1176
@ SHT_DYNAMIC
Definition ELF.h:1160
@ SHT_LLVM_ADDRSIG
Definition ELF.h:1184
@ SHT_GNU_HASH
Definition ELF.h:1204
@ SHT_RELA
Definition ELF.h:1158
@ SHT_DYNSYM
Definition ELF.h:1165
@ SHT_MIPS_ABIFLAGS
Definition ELF.h:1235
@ SHT_GNU_versym
Definition ELF.h:1207
@ SHT_HASH
Definition ELF.h:1159
@ STB_LOCAL
Definition ELF.h:1412
constexpr unsigned CREL_HDR_ADDEND
Definition ELF.h:2062
@ ELFDATA2LSB
Definition ELF.h:340
@ ELFCLASS64
Definition ELF.h:334
@ ELFCLASS32
Definition ELF.h:333
@ ET_REL
Definition ELF.h:119
@ GRP_COMDAT
Definition ELF.h:1359
LLVM_ABI bool yaml2elf(ELFYAML::Object &Doc, raw_ostream &Out, ErrorHandler EH, uint64_t MaxSize)
llvm::function_ref< void(const Twine &Msg)> ErrorHandler
Definition yaml2obj.h:68
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:573
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1669
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition Error.h:1013
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
bool is_sorted(R &&Range, Compare C)
Wrapper function around std::is_sorted to check if elements in a range R are sorted with respect to a...
Definition STLExtras.h:1970
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
@ Dynamic
Denotes mode unknown at compile time.
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1772
bool to_integer(StringRef S, N &Num, unsigned Base=0)
Convert the string S to an integer of the specified type using the radix Base. If Base is 0,...
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:390
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
std::optional< std::vector< llvm::yaml::Hex64 > > CallsiteEndOffsets
std::optional< llvm::yaml::Hex64 > Hash
std::optional< std::vector< BBEntry > > BBEntries
std::optional< uint64_t > FuncEntryCount
std::optional< std::vector< PGOBBEntry > > PGOBBEntries
LLVM_ABI SetVector< StringRef > getNonEmptySectionNames() const
Definition DWARFYAML.cpp:25
std::optional< llvm::yaml::Hex64 > Offset
Definition ELFYAML.h:203
llvm::yaml::Hex64 Val
Definition ELFYAML.h:157
llvm::yaml::Hex64 Size
Definition ELFYAML.h:273
std::optional< yaml::BinaryRef > Pattern
Definition ELFYAML.h:272
const SectionHeaderTable & getSectionHeaderTable() const
Definition ELFYAML.h:709
FileHeader Header
Definition ELFYAML.h:686
std::vector< ProgramHeader > ProgramHeaders
Definition ELFYAML.h:687
std::optional< llvm::yaml::Hex64 > Align
Definition ELFYAML.h:674
llvm::yaml::Hex64 PAddr
Definition ELFYAML.h:673
std::optional< llvm::yaml::Hex64 > Offset
Definition ELFYAML.h:677
llvm::yaml::Hex64 VAddr
Definition ELFYAML.h:672
std::optional< llvm::yaml::Hex64 > MemSize
Definition ELFYAML.h:676
std::optional< StringRef > FirstSec
Definition ELFYAML.h:678
std::optional< StringRef > LastSec
Definition ELFYAML.h:679
std::optional< llvm::yaml::Hex64 > FileSize
Definition ELFYAML.h:675
std::vector< Chunk * > Chunks
Definition ELFYAML.h:682
std::optional< llvm::yaml::Hex64 > Info
Definition ELFYAML.h:351
std::optional< StringRef > Symbol
Definition ELFYAML.h:583
llvm::yaml::Hex64 Offset
Definition ELFYAML.h:580
std::optional< std::vector< SectionHeader > > Excluded
Definition ELFYAML.h:289
std::optional< bool > NoHeaders
Definition ELFYAML.h:290
size_t getNumHeaders(size_t SectionsNum) const
Definition ELFYAML.h:292
std::optional< std::vector< SectionHeader > > Sections
Definition ELFYAML.h:288
std::optional< llvm::yaml::Hex64 > Address
Definition ELFYAML.h:216
std::optional< StringRef > Link
Definition ELFYAML.h:217
std::optional< llvm::yaml::Hex64 > Size
Definition ELFYAML.h:222
std::optional< llvm::yaml::Hex64 > ShAddrAlign
Definition ELFYAML.h:244
llvm::yaml::Hex64 AddressAlign
Definition ELFYAML.h:218
std::optional< ELF_SHF > Flags
Definition ELFYAML.h:215
std::optional< ELF_SHT > ShType
Definition ELFYAML.h:265
std::optional< llvm::yaml::Hex64 > ShOffset
Definition ELFYAML.h:252
std::optional< llvm::yaml::Hex64 > ShFlags
Definition ELFYAML.h:259
std::optional< llvm::yaml::Hex64 > ShName
Definition ELFYAML.h:248
std::optional< yaml::BinaryRef > Content
Definition ELFYAML.h:221
std::optional< llvm::yaml::Hex64 > EntSize
Definition ELFYAML.h:219
std::optional< llvm::yaml::Hex64 > ShSize
Definition ELFYAML.h:256
std::optional< std::vector< uint32_t > > Entries
Definition ELFYAML.h:616
static Expected< Features > decode(uint16_t Val)
Definition BBAddrMap.h:62
Common declarations for yaml2obj.