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 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,
233 StringTableBuilder &STB,
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,
306 const ELFYAML::DependentLibrariesSection &Section,
307 ContiguousBlobAccumulator &CBA);
308 void writeSectionContent(Elf_Shdr &SHeader,
309 const ELFYAML::CallGraphProfileSection &Section,
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);
385 assert(ELFYAML::dropUniqueSuffix(C->Name).empty());
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 if (Doc.Header.Flags)
485 Header.e_flags = *Doc.Header.Flags;
486 else
487 Header.e_flags = 0;
488
489 Header.e_ehsize = sizeof(Elf_Ehdr);
490
491 if (Doc.Header.EPhOff)
492 Header.e_phoff = *Doc.Header.EPhOff;
493 else if (!Doc.ProgramHeaders.empty())
494 Header.e_phoff = sizeof(Header);
495 else
496 Header.e_phoff = 0;
497
498 if (Doc.Header.EPhEntSize)
499 Header.e_phentsize = *Doc.Header.EPhEntSize;
500 else if (!Doc.ProgramHeaders.empty())
501 Header.e_phentsize = sizeof(Elf_Phdr);
502 else
503 Header.e_phentsize = 0;
504
505 if (Doc.Header.EPhNum)
506 Header.e_phnum = *Doc.Header.EPhNum;
507 else if (!Doc.ProgramHeaders.empty())
508 Header.e_phnum = Doc.ProgramHeaders.size();
509 else
510 Header.e_phnum = 0;
511
512 Header.e_shentsize = Doc.Header.EShEntSize ? (uint16_t)*Doc.Header.EShEntSize
513 : sizeof(Elf_Shdr);
514
515 const ELFYAML::SectionHeaderTable &SectionHeaders =
516 Doc.getSectionHeaderTable();
517
518 if (Doc.Header.EShOff)
519 Header.e_shoff = *Doc.Header.EShOff;
520 else if (SectionHeaders.Offset)
521 Header.e_shoff = *SectionHeaders.Offset;
522 else
523 Header.e_shoff = 0;
524
525 if (Doc.Header.EShNum)
526 Header.e_shnum = *Doc.Header.EShNum;
527 else
528 Header.e_shnum = SectionHeaders.getNumHeaders(Doc.getSections().size());
529
530 if (Doc.Header.EShStrNdx)
531 Header.e_shstrndx = *Doc.Header.EShStrNdx;
532 else if (SectionHeaders.Offset &&
533 !ExcludedSectionHeaders.count(SectionHeaderStringTableName))
534 Header.e_shstrndx = SN2I.get(SectionHeaderStringTableName);
535 else
536 Header.e_shstrndx = 0;
537
538 OS.write((const char *)&Header, sizeof(Header));
539}
540
541template <class ELFT>
542void ELFState<ELFT>::initProgramHeaders(std::vector<Elf_Phdr> &PHeaders) {
543 DenseMap<StringRef, size_t> NameToIndex;
544 for (size_t I = 0, E = Doc.Chunks.size(); I != E; ++I) {
545 NameToIndex[Doc.Chunks[I]->Name] = I + 1;
546 }
547
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
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
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
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)
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
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
1072static bool shouldEmitDWARF(DWARFYAML::Data &DWARF, StringRef Name) {
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
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
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" +
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 > 3)
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 bool EmitCallsiteEndOffsets =
1491 FeatureOrErr->CallsiteEndOffsets || E.hasAnyCallsiteEndOffsets();
1492 for (const ELFYAML::BBAddrMapEntry::BBRangeEntry &BBR : *E.BBRanges) {
1493 // Write the base address of the range.
1494 CBA.write<uintX_t>(BBR.BaseAddress, ELFT::Endianness);
1495 // Write number of BBEntries (number of basic blocks in this basic block
1496 // range). This is overridden by the 'NumBlocks' YAML field when
1497 // specified.
1498 uint64_t NumBlocks =
1499 BBR.NumBlocks.value_or(BBR.BBEntries ? BBR.BBEntries->size() : 0);
1500 SHeader.sh_size += sizeof(uintX_t) + CBA.writeULEB128(NumBlocks);
1501 // Write all BBEntries in this BBRange.
1502 if (!BBR.BBEntries || FeatureOrErr->OmitBBEntries)
1503 continue;
1504 for (const ELFYAML::BBAddrMapEntry::BBEntry &BBE : *BBR.BBEntries) {
1505 ++TotalNumBlocks;
1506 if (Section.Type == llvm::ELF::SHT_LLVM_BB_ADDR_MAP && E.Version > 1)
1507 SHeader.sh_size += CBA.writeULEB128(BBE.ID);
1508 SHeader.sh_size += CBA.writeULEB128(BBE.AddressOffset);
1509 if (EmitCallsiteEndOffsets) {
1510 size_t NumCallsiteEndOffsets =
1511 BBE.CallsiteEndOffsets ? BBE.CallsiteEndOffsets->size() : 0;
1512 SHeader.sh_size += CBA.writeULEB128(NumCallsiteEndOffsets);
1513 if (BBE.CallsiteEndOffsets) {
1515 SHeader.sh_size += CBA.writeULEB128(Offset);
1516 }
1517 }
1518 SHeader.sh_size += CBA.writeULEB128(BBE.Size);
1519 SHeader.sh_size += CBA.writeULEB128(BBE.Metadata);
1520 }
1521 }
1522 if (!PGOAnalyses)
1523 continue;
1524 const ELFYAML::PGOAnalysisMapEntry &PGOEntry = PGOAnalyses->at(Idx);
1525
1526 if (PGOEntry.FuncEntryCount)
1527 SHeader.sh_size += CBA.writeULEB128(*PGOEntry.FuncEntryCount);
1528
1529 if (!PGOEntry.PGOBBEntries)
1530 continue;
1531
1532 const auto &PGOBBEntries = PGOEntry.PGOBBEntries.value();
1533 if (TotalNumBlocks != PGOBBEntries.size()) {
1534 WithColor::warning() << "PBOBBEntries must be the same length as "
1535 "BBEntries in SHT_LLVM_BB_ADDR_MAP.\n"
1536 << "Mismatch on function with address: "
1537 << E.getFunctionAddress();
1538 continue;
1539 }
1540
1541 for (const auto &PGOBBE : PGOBBEntries) {
1542 if (PGOBBE.BBFreq)
1543 SHeader.sh_size += CBA.writeULEB128(*PGOBBE.BBFreq);
1544 if (PGOBBE.Successors) {
1545 SHeader.sh_size += CBA.writeULEB128(PGOBBE.Successors->size());
1546 for (const auto &[ID, BrProb] : *PGOBBE.Successors) {
1547 SHeader.sh_size += CBA.writeULEB128(ID);
1548 SHeader.sh_size += CBA.writeULEB128(BrProb);
1549 }
1550 }
1551 }
1552 }
1553}
1554
1555template <class ELFT>
1556void ELFState<ELFT>::writeSectionContent(
1557 Elf_Shdr &SHeader, const ELFYAML::LinkerOptionsSection &Section,
1558 ContiguousBlobAccumulator &CBA) {
1559 if (!Section.Options)
1560 return;
1561
1562 for (const ELFYAML::LinkerOption &LO : *Section.Options) {
1563 CBA.write(LO.Key.data(), LO.Key.size());
1564 CBA.write('\0');
1565 CBA.write(LO.Value.data(), LO.Value.size());
1566 CBA.write('\0');
1567 SHeader.sh_size += (LO.Key.size() + LO.Value.size() + 2);
1568 }
1569}
1570
1571template <class ELFT>
1572void ELFState<ELFT>::writeSectionContent(
1573 Elf_Shdr &SHeader, const ELFYAML::DependentLibrariesSection &Section,
1574 ContiguousBlobAccumulator &CBA) {
1575 if (!Section.Libs)
1576 return;
1577
1578 for (StringRef Lib : *Section.Libs) {
1579 CBA.write(Lib.data(), Lib.size());
1580 CBA.write('\0');
1581 SHeader.sh_size += Lib.size() + 1;
1582 }
1583}
1584
1585template <class ELFT>
1587ELFState<ELFT>::alignToOffset(ContiguousBlobAccumulator &CBA, uint64_t Align,
1588 std::optional<llvm::yaml::Hex64> Offset) {
1589 uint64_t CurrentOffset = CBA.getOffset();
1590 uint64_t AlignedOffset;
1591
1592 if (Offset) {
1593 if ((uint64_t)*Offset < CurrentOffset) {
1594 reportError("the 'Offset' value (0x" +
1595 Twine::utohexstr((uint64_t)*Offset) + ") goes backward");
1596 return CurrentOffset;
1597 }
1598
1599 // We ignore an alignment when an explicit offset has been requested.
1600 AlignedOffset = *Offset;
1601 } else {
1602 AlignedOffset = alignTo(CurrentOffset, std::max(Align, (uint64_t)1));
1603 }
1604
1605 CBA.writeZeros(AlignedOffset - CurrentOffset);
1606 return AlignedOffset;
1607}
1608
1609template <class ELFT>
1610void ELFState<ELFT>::writeSectionContent(
1611 Elf_Shdr &SHeader, const ELFYAML::CallGraphProfileSection &Section,
1612 ContiguousBlobAccumulator &CBA) {
1613 if (!Section.Entries)
1614 return;
1615
1616 for (const ELFYAML::CallGraphEntryWeight &E : *Section.Entries) {
1617 CBA.write<uint64_t>(E.Weight, ELFT::Endianness);
1618 SHeader.sh_size += sizeof(object::Elf_CGProfile_Impl<ELFT>);
1619 }
1620}
1621
1622template <class ELFT>
1623void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1624 const ELFYAML::HashSection &Section,
1625 ContiguousBlobAccumulator &CBA) {
1626 if (!Section.Bucket)
1627 return;
1628
1629 CBA.write<uint32_t>(
1630 Section.NBucket.value_or(llvm::yaml::Hex64(Section.Bucket->size())),
1631 ELFT::Endianness);
1632 CBA.write<uint32_t>(
1633 Section.NChain.value_or(llvm::yaml::Hex64(Section.Chain->size())),
1634 ELFT::Endianness);
1635
1636 for (uint32_t Val : *Section.Bucket)
1637 CBA.write<uint32_t>(Val, ELFT::Endianness);
1638 for (uint32_t Val : *Section.Chain)
1639 CBA.write<uint32_t>(Val, ELFT::Endianness);
1640
1641 SHeader.sh_size = (2 + Section.Bucket->size() + Section.Chain->size()) * 4;
1642}
1643
1644template <class ELFT>
1645void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1646 const ELFYAML::VerdefSection &Section,
1647 ContiguousBlobAccumulator &CBA) {
1648
1649 if (Section.Info)
1650 SHeader.sh_info = *Section.Info;
1651 else if (Section.Entries)
1652 SHeader.sh_info = Section.Entries->size();
1653
1654 if (!Section.Entries)
1655 return;
1656
1657 uint64_t AuxCnt = 0;
1658 for (size_t I = 0; I < Section.Entries->size(); ++I) {
1659 const ELFYAML::VerdefEntry &E = (*Section.Entries)[I];
1660
1661 Elf_Verdef VerDef;
1662 VerDef.vd_version = E.Version.value_or(1);
1663 VerDef.vd_flags = E.Flags.value_or(0);
1664 VerDef.vd_ndx = E.VersionNdx.value_or(0);
1665 VerDef.vd_hash = E.Hash.value_or(0);
1666 VerDef.vd_aux = E.VDAux.value_or(sizeof(Elf_Verdef));
1667 VerDef.vd_cnt = E.VerNames.size();
1668 if (I == Section.Entries->size() - 1)
1669 VerDef.vd_next = 0;
1670 else
1671 VerDef.vd_next =
1672 sizeof(Elf_Verdef) + E.VerNames.size() * sizeof(Elf_Verdaux);
1673 CBA.write((const char *)&VerDef, sizeof(Elf_Verdef));
1674
1675 for (size_t J = 0; J < E.VerNames.size(); ++J, ++AuxCnt) {
1676 Elf_Verdaux VerdAux;
1677 VerdAux.vda_name = DotDynstr.getOffset(E.VerNames[J]);
1678 if (J == E.VerNames.size() - 1)
1679 VerdAux.vda_next = 0;
1680 else
1681 VerdAux.vda_next = sizeof(Elf_Verdaux);
1682 CBA.write((const char *)&VerdAux, sizeof(Elf_Verdaux));
1683 }
1684 }
1685
1686 SHeader.sh_size = Section.Entries->size() * sizeof(Elf_Verdef) +
1687 AuxCnt * sizeof(Elf_Verdaux);
1688}
1689
1690template <class ELFT>
1691void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1692 const ELFYAML::VerneedSection &Section,
1693 ContiguousBlobAccumulator &CBA) {
1694 if (Section.Info)
1695 SHeader.sh_info = *Section.Info;
1696 else if (Section.VerneedV)
1697 SHeader.sh_info = Section.VerneedV->size();
1698
1699 if (!Section.VerneedV)
1700 return;
1701
1702 uint64_t AuxCnt = 0;
1703 for (size_t I = 0; I < Section.VerneedV->size(); ++I) {
1704 const ELFYAML::VerneedEntry &VE = (*Section.VerneedV)[I];
1705
1706 Elf_Verneed VerNeed;
1707 VerNeed.vn_version = VE.Version;
1708 VerNeed.vn_file = DotDynstr.getOffset(VE.File);
1709 if (I == Section.VerneedV->size() - 1)
1710 VerNeed.vn_next = 0;
1711 else
1712 VerNeed.vn_next =
1713 sizeof(Elf_Verneed) + VE.AuxV.size() * sizeof(Elf_Vernaux);
1714 VerNeed.vn_cnt = VE.AuxV.size();
1715 VerNeed.vn_aux = sizeof(Elf_Verneed);
1716 CBA.write((const char *)&VerNeed, sizeof(Elf_Verneed));
1717
1718 for (size_t J = 0; J < VE.AuxV.size(); ++J, ++AuxCnt) {
1719 const ELFYAML::VernauxEntry &VAuxE = VE.AuxV[J];
1720
1721 Elf_Vernaux VernAux;
1722 VernAux.vna_hash = VAuxE.Hash;
1723 VernAux.vna_flags = VAuxE.Flags;
1724 VernAux.vna_other = VAuxE.Other;
1725 VernAux.vna_name = DotDynstr.getOffset(VAuxE.Name);
1726 if (J == VE.AuxV.size() - 1)
1727 VernAux.vna_next = 0;
1728 else
1729 VernAux.vna_next = sizeof(Elf_Vernaux);
1730 CBA.write((const char *)&VernAux, sizeof(Elf_Vernaux));
1731 }
1732 }
1733
1734 SHeader.sh_size = Section.VerneedV->size() * sizeof(Elf_Verneed) +
1735 AuxCnt * sizeof(Elf_Vernaux);
1736}
1737
1738template <class ELFT>
1739void ELFState<ELFT>::writeSectionContent(
1740 Elf_Shdr &SHeader, const ELFYAML::ARMIndexTableSection &Section,
1741 ContiguousBlobAccumulator &CBA) {
1742 if (!Section.Entries)
1743 return;
1744
1745 for (const ELFYAML::ARMIndexTableEntry &E : *Section.Entries) {
1746 CBA.write<uint32_t>(E.Offset, ELFT::Endianness);
1747 CBA.write<uint32_t>(E.Value, ELFT::Endianness);
1748 }
1749 SHeader.sh_size = Section.Entries->size() * 8;
1750}
1751
1752template <class ELFT>
1753void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1754 const ELFYAML::MipsABIFlags &Section,
1755 ContiguousBlobAccumulator &CBA) {
1757 "Section type is not SHT_MIPS_ABIFLAGS");
1758
1760 zero(Flags);
1761 SHeader.sh_size = SHeader.sh_entsize;
1762
1763 Flags.version = Section.Version;
1764 Flags.isa_level = Section.ISALevel;
1765 Flags.isa_rev = Section.ISARevision;
1766 Flags.gpr_size = Section.GPRSize;
1767 Flags.cpr1_size = Section.CPR1Size;
1768 Flags.cpr2_size = Section.CPR2Size;
1769 Flags.fp_abi = Section.FpABI;
1770 Flags.isa_ext = Section.ISAExtension;
1771 Flags.ases = Section.ASEs;
1772 Flags.flags1 = Section.Flags1;
1773 Flags.flags2 = Section.Flags2;
1774 CBA.write((const char *)&Flags, sizeof(Flags));
1775}
1776
1777template <class ELFT>
1778void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1779 const ELFYAML::DynamicSection &Section,
1780 ContiguousBlobAccumulator &CBA) {
1782 "Section type is not SHT_DYNAMIC");
1783
1784 if (!Section.Entries)
1785 return;
1786
1787 for (const ELFYAML::DynamicEntry &DE : *Section.Entries) {
1788 CBA.write<uintX_t>(DE.Tag, ELFT::Endianness);
1789 CBA.write<uintX_t>(DE.Val, ELFT::Endianness);
1790 }
1791 SHeader.sh_size = 2 * sizeof(uintX_t) * Section.Entries->size();
1792}
1793
1794template <class ELFT>
1795void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1796 const ELFYAML::AddrsigSection &Section,
1797 ContiguousBlobAccumulator &CBA) {
1798 if (!Section.Symbols)
1799 return;
1800
1801 for (StringRef Sym : *Section.Symbols)
1802 SHeader.sh_size +=
1803 CBA.writeULEB128(toSymbolIndex(Sym, Section.Name, /*IsDynamic=*/false));
1804}
1805
1806template <class ELFT>
1807void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1808 const ELFYAML::NoteSection &Section,
1809 ContiguousBlobAccumulator &CBA) {
1810 if (!Section.Notes || Section.Notes->empty())
1811 return;
1812
1813 unsigned Align;
1814 switch (Section.AddressAlign) {
1815 case 0:
1816 case 4:
1817 Align = 4;
1818 break;
1819 case 8:
1820 Align = 8;
1821 break;
1822 default:
1823 reportError(Section.Name + ": invalid alignment for a note section: 0x" +
1824 Twine::utohexstr(Section.AddressAlign));
1825 return;
1826 }
1827
1828 if (CBA.getOffset() != alignTo(CBA.getOffset(), Align)) {
1829 reportError(Section.Name + ": invalid offset of a note section: 0x" +
1830 Twine::utohexstr(CBA.getOffset()) + ", should be aligned to " +
1831 Twine(Align));
1832 return;
1833 }
1834
1835 uint64_t Offset = CBA.tell();
1836 for (const ELFYAML::NoteEntry &NE : *Section.Notes) {
1837 // Write name size.
1838 if (NE.Name.empty())
1839 CBA.write<uint32_t>(0, ELFT::Endianness);
1840 else
1841 CBA.write<uint32_t>(NE.Name.size() + 1, ELFT::Endianness);
1842
1843 // Write description size.
1844 if (NE.Desc.binary_size() == 0)
1845 CBA.write<uint32_t>(0, ELFT::Endianness);
1846 else
1847 CBA.write<uint32_t>(NE.Desc.binary_size(), ELFT::Endianness);
1848
1849 // Write type.
1850 CBA.write<uint32_t>(NE.Type, ELFT::Endianness);
1851
1852 // Write name, null terminator and padding.
1853 if (!NE.Name.empty()) {
1854 CBA.write(NE.Name.data(), NE.Name.size());
1855 CBA.write('\0');
1856 }
1857
1858 // Write description and padding.
1859 if (NE.Desc.binary_size() != 0) {
1860 CBA.padToAlignment(Align);
1861 CBA.writeAsBinary(NE.Desc);
1862 }
1863
1864 CBA.padToAlignment(Align);
1865 }
1866
1867 SHeader.sh_size = CBA.tell() - Offset;
1868}
1869
1870template <class ELFT>
1871void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1872 const ELFYAML::GnuHashSection &Section,
1873 ContiguousBlobAccumulator &CBA) {
1874 if (!Section.HashBuckets)
1875 return;
1876
1877 if (!Section.Header)
1878 return;
1879
1880 // We write the header first, starting with the hash buckets count. Normally
1881 // it is the number of entries in HashBuckets, but the "NBuckets" property can
1882 // be used to override this field, which is useful for producing broken
1883 // objects.
1884 if (Section.Header->NBuckets)
1885 CBA.write<uint32_t>(*Section.Header->NBuckets, ELFT::Endianness);
1886 else
1887 CBA.write<uint32_t>(Section.HashBuckets->size(), ELFT::Endianness);
1888
1889 // Write the index of the first symbol in the dynamic symbol table accessible
1890 // via the hash table.
1891 CBA.write<uint32_t>(Section.Header->SymNdx, ELFT::Endianness);
1892
1893 // Write the number of words in the Bloom filter. As above, the "MaskWords"
1894 // property can be used to set this field to any value.
1895 if (Section.Header->MaskWords)
1896 CBA.write<uint32_t>(*Section.Header->MaskWords, ELFT::Endianness);
1897 else
1898 CBA.write<uint32_t>(Section.BloomFilter->size(), ELFT::Endianness);
1899
1900 // Write the shift constant used by the Bloom filter.
1901 CBA.write<uint32_t>(Section.Header->Shift2, ELFT::Endianness);
1902
1903 // We've finished writing the header. Now write the Bloom filter.
1904 for (llvm::yaml::Hex64 Val : *Section.BloomFilter)
1905 CBA.write<uintX_t>(Val, ELFT::Endianness);
1906
1907 // Write an array of hash buckets.
1908 for (llvm::yaml::Hex32 Val : *Section.HashBuckets)
1909 CBA.write<uint32_t>(Val, ELFT::Endianness);
1910
1911 // Write an array of hash values.
1912 for (llvm::yaml::Hex32 Val : *Section.HashValues)
1913 CBA.write<uint32_t>(Val, ELFT::Endianness);
1914
1915 SHeader.sh_size = 16 /*Header size*/ +
1916 Section.BloomFilter->size() * sizeof(typename ELFT::uint) +
1917 Section.HashBuckets->size() * 4 +
1918 Section.HashValues->size() * 4;
1919}
1920
1921template <class ELFT>
1922void ELFState<ELFT>::writeFill(ELFYAML::Fill &Fill,
1923 ContiguousBlobAccumulator &CBA) {
1924 size_t PatternSize = Fill.Pattern ? Fill.Pattern->binary_size() : 0;
1925 if (!PatternSize) {
1926 CBA.writeZeros(Fill.Size);
1927 return;
1928 }
1929
1930 // Fill the content with the specified pattern.
1931 uint64_t Written = 0;
1932 for (; Written + PatternSize <= Fill.Size; Written += PatternSize)
1933 CBA.writeAsBinary(*Fill.Pattern);
1934 CBA.writeAsBinary(*Fill.Pattern, Fill.Size - Written);
1935}
1936
1937template <class ELFT>
1938DenseMap<StringRef, size_t> ELFState<ELFT>::buildSectionHeaderReorderMap() {
1939 const ELFYAML::SectionHeaderTable &SectionHeaders =
1940 Doc.getSectionHeaderTable();
1941 if (SectionHeaders.IsImplicit || SectionHeaders.NoHeaders ||
1942 SectionHeaders.isDefault())
1944
1946 size_t SecNdx = 0;
1947 StringSet<> Seen;
1948
1949 auto AddSection = [&](const ELFYAML::SectionHeader &Hdr) {
1950 if (!Ret.try_emplace(Hdr.Name, ++SecNdx).second)
1951 reportError("repeated section name: '" + Hdr.Name +
1952 "' in the section header description");
1953 Seen.insert(Hdr.Name);
1954 };
1955
1956 if (SectionHeaders.Sections)
1957 for (const ELFYAML::SectionHeader &Hdr : *SectionHeaders.Sections)
1958 AddSection(Hdr);
1959
1960 if (SectionHeaders.Excluded)
1961 for (const ELFYAML::SectionHeader &Hdr : *SectionHeaders.Excluded)
1962 AddSection(Hdr);
1963
1964 for (const ELFYAML::Section *S : Doc.getSections()) {
1965 // Ignore special first SHT_NULL section.
1966 if (S == Doc.getSections().front())
1967 continue;
1968 if (!Seen.count(S->Name))
1969 reportError("section '" + S->Name +
1970 "' should be present in the 'Sections' or 'Excluded' lists");
1971 Seen.erase(S->Name);
1972 }
1973
1974 for (const auto &It : Seen)
1975 reportError("section header contains undefined section '" + It.getKey() +
1976 "'");
1977 return Ret;
1978}
1979
1980template <class ELFT> void ELFState<ELFT>::buildSectionIndex() {
1981 // A YAML description can have an explicit section header declaration that
1982 // allows to change the order of section headers.
1983 DenseMap<StringRef, size_t> ReorderMap = buildSectionHeaderReorderMap();
1984
1985 if (HasError)
1986 return;
1987
1988 // Build excluded section headers map.
1989 std::vector<ELFYAML::Section *> Sections = Doc.getSections();
1990 const ELFYAML::SectionHeaderTable &SectionHeaders =
1991 Doc.getSectionHeaderTable();
1992 if (SectionHeaders.Excluded)
1993 for (const ELFYAML::SectionHeader &Hdr : *SectionHeaders.Excluded)
1994 if (!ExcludedSectionHeaders.insert(Hdr.Name).second)
1995 llvm_unreachable("buildSectionIndex() failed");
1996
1997 if (SectionHeaders.NoHeaders.value_or(false))
1998 for (const ELFYAML::Section *S : Sections)
1999 if (!ExcludedSectionHeaders.insert(S->Name).second)
2000 llvm_unreachable("buildSectionIndex() failed");
2001
2002 size_t SecNdx = -1;
2003 for (const ELFYAML::Section *S : Sections) {
2004 ++SecNdx;
2005
2006 size_t Index = ReorderMap.empty() ? SecNdx : ReorderMap.lookup(S->Name);
2007 if (!SN2I.addName(S->Name, Index))
2008 llvm_unreachable("buildSectionIndex() failed");
2009
2010 if (!ExcludedSectionHeaders.count(S->Name))
2011 ShStrtabStrings->add(ELFYAML::dropUniqueSuffix(S->Name));
2012 }
2013}
2014
2015template <class ELFT> void ELFState<ELFT>::buildSymbolIndexes() {
2016 auto Build = [this](ArrayRef<ELFYAML::Symbol> V, NameToIdxMap &Map) {
2017 for (size_t I = 0, S = V.size(); I < S; ++I) {
2018 const ELFYAML::Symbol &Sym = V[I];
2019 if (!Sym.Name.empty() && !Map.addName(Sym.Name, I + 1))
2020 reportError("repeated symbol name: '" + Sym.Name + "'");
2021 }
2022 };
2023
2024 if (Doc.Symbols)
2025 Build(*Doc.Symbols, SymN2I);
2026 if (Doc.DynamicSymbols)
2027 Build(*Doc.DynamicSymbols, DynSymN2I);
2028}
2029
2030template <class ELFT> void ELFState<ELFT>::finalizeStrings() {
2031 // Add the regular symbol names to .strtab section.
2032 if (Doc.Symbols)
2033 for (const ELFYAML::Symbol &Sym : *Doc.Symbols)
2034 DotStrtab.add(ELFYAML::dropUniqueSuffix(Sym.Name));
2035 DotStrtab.finalize();
2036
2037 // Add the dynamic symbol names to .dynstr section.
2038 if (Doc.DynamicSymbols)
2039 for (const ELFYAML::Symbol &Sym : *Doc.DynamicSymbols)
2040 DotDynstr.add(ELFYAML::dropUniqueSuffix(Sym.Name));
2041
2042 // SHT_GNU_verdef and SHT_GNU_verneed sections might also
2043 // add strings to .dynstr section.
2044 for (const ELFYAML::Chunk *Sec : Doc.getSections()) {
2045 if (auto VerNeed = dyn_cast<ELFYAML::VerneedSection>(Sec)) {
2046 if (VerNeed->VerneedV) {
2047 for (const ELFYAML::VerneedEntry &VE : *VerNeed->VerneedV) {
2048 DotDynstr.add(VE.File);
2049 for (const ELFYAML::VernauxEntry &Aux : VE.AuxV)
2050 DotDynstr.add(Aux.Name);
2051 }
2052 }
2053 } else if (auto VerDef = dyn_cast<ELFYAML::VerdefSection>(Sec)) {
2054 if (VerDef->Entries)
2055 for (const ELFYAML::VerdefEntry &E : *VerDef->Entries)
2056 for (StringRef Name : E.VerNames)
2057 DotDynstr.add(Name);
2058 }
2059 }
2060
2061 DotDynstr.finalize();
2062
2063 // Don't finalize the section header string table a second time if it has
2064 // already been finalized due to being one of the symbol string tables.
2065 if (ShStrtabStrings != &DotStrtab && ShStrtabStrings != &DotDynstr)
2066 ShStrtabStrings->finalize();
2067}
2068
2069template <class ELFT>
2070bool ELFState<ELFT>::writeELF(raw_ostream &OS, ELFYAML::Object &Doc,
2071 yaml::ErrorHandler EH, uint64_t MaxSize) {
2072 ELFState<ELFT> State(Doc, EH);
2073 if (State.HasError)
2074 return false;
2075
2076 // Build the section index, which adds sections to the section header string
2077 // table first, so that we can finalize the section header string table.
2078 State.buildSectionIndex();
2079 State.buildSymbolIndexes();
2080
2081 // Finalize section header string table and the .strtab and .dynstr sections.
2082 // We do this early because we want to finalize the string table builders
2083 // before writing the content of the sections that might want to use them.
2084 State.finalizeStrings();
2085
2086 if (State.HasError)
2087 return false;
2088
2089 std::vector<Elf_Phdr> PHeaders;
2090 State.initProgramHeaders(PHeaders);
2091
2092 // XXX: This offset is tightly coupled with the order that we write
2093 // things to `OS`.
2094 const size_t SectionContentBeginOffset =
2095 sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * Doc.ProgramHeaders.size();
2096 // It is quite easy to accidentally create output with yaml2obj that is larger
2097 // than intended, for example, due to an issue in the YAML description.
2098 // We limit the maximum allowed output size, but also provide a command line
2099 // option to change this limitation.
2100 ContiguousBlobAccumulator CBA(SectionContentBeginOffset, MaxSize);
2101
2102 std::vector<Elf_Shdr> SHeaders;
2103 State.initSectionHeaders(SHeaders, CBA);
2104
2105 // Now we can decide segment offsets.
2106 State.setProgramHeaderLayout(PHeaders, SHeaders);
2107
2108 bool ReachedLimit = CBA.getOffset() > MaxSize;
2109 if (Error E = CBA.takeLimitError()) {
2110 // We report a custom error message instead below.
2111 consumeError(std::move(E));
2112 ReachedLimit = true;
2113 }
2114
2115 if (ReachedLimit)
2116 State.reportError(
2117 "the desired output size is greater than permitted. Use the "
2118 "--max-size option to change the limit");
2119
2120 if (State.HasError)
2121 return false;
2122
2123 State.writeELFHeader(OS);
2124 writeArrayData(OS, ArrayRef(PHeaders));
2125
2127 if (!SHT.NoHeaders.value_or(false))
2128 CBA.updateDataAt(*SHT.Offset, SHeaders.data(),
2129 SHT.getNumHeaders(SHeaders.size()) * sizeof(Elf_Shdr));
2130
2131 CBA.writeBlobToStream(OS);
2132 return true;
2133}
2134
2135namespace llvm {
2136namespace yaml {
2137
2139 uint64_t MaxSize) {
2140 bool IsLE = Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
2141 bool Is64Bit = Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
2142 if (Is64Bit) {
2143 if (IsLE)
2144 return ELFState<object::ELF64LE>::writeELF(Out, Doc, EH, MaxSize);
2145 return ELFState<object::ELF64BE>::writeELF(Out, Doc, EH, MaxSize);
2146 }
2147 if (IsLE)
2148 return ELFState<object::ELF32LE>::writeELF(Out, Doc, EH, MaxSize);
2149 return ELFState<object::ELF32BE>::writeELF(Out, Doc, EH, MaxSize);
2150}
2151
2152} // namespace yaml
2153} // 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:388
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:1343
@ 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:1142
@ SHT_GROUP
Definition ELF.h:1154
@ SHT_PROGBITS
Definition ELF.h:1140
@ SHT_REL
Definition ELF.h:1148
@ SHT_NULL
Definition ELF.h:1139
@ SHT_LLVM_CALL_GRAPH_PROFILE
Definition ELF.h:1177
@ SHT_NOBITS
Definition ELF.h:1147
@ SHT_SYMTAB
Definition ELF.h:1141
@ SHT_GNU_verneed
Definition ELF.h:1190
@ SHT_GNU_verdef
Definition ELF.h:1189
@ SHT_CREL
Definition ELF.h:1161
@ SHT_DYNAMIC
Definition ELF.h:1145
@ SHT_LLVM_ADDRSIG
Definition ELF.h:1169
@ SHT_LLVM_BB_ADDR_MAP
Definition ELF.h:1178
@ SHT_GNU_HASH
Definition ELF.h:1188
@ SHT_RELA
Definition ELF.h:1143
@ SHT_DYNSYM
Definition ELF.h:1150
@ SHT_MIPS_ABIFLAGS
Definition ELF.h:1219
@ SHT_GNU_versym
Definition ELF.h:1191
@ SHT_HASH
Definition ELF.h:1144
@ SHF_MERGE
Definition ELF.h:1246
@ SHF_STRINGS
Definition ELF.h:1249
@ SHF_ALLOC
Definition ELF.h:1240
constexpr unsigned CREL_HDR_ADDEND
Definition ELF.h:2045
@ 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:1396
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:1665
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:2454
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:1902
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:1740
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.