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