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