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