39 StringMap<unsigned> Map;
43 bool addName(StringRef Name,
unsigned Ndx) {
44 return Map.insert({
Name, Ndx}).second;
47 bool lookup(StringRef Name,
unsigned &Idx)
const {
48 auto I = Map.find(Name);
55 unsigned get(StringRef Name)
const {
59 assert(
false &&
"Expected section not found in index");
62 unsigned size()
const {
return Map.size(); }
77template <
class ELFT>
class ELFState {
97 StringRef SectionHeaderStringTableName =
".shstrtab";
98 StringTableBuilder *ShStrtabStrings = &DotShStrtab;
102 NameToIdxMap DynSymN2I;
103 ELFYAML::Object &Doc;
105 std::vector<std::pair<Elf_Shdr *, ELFYAML::Section>>
106 SectionHeadersOverrideHelper;
108 StringSet<> ExcludedSectionHeaders;
111 bool HasError =
false;
117 const StringTableBuilder &Strtab);
118 unsigned toSectionIndex(StringRef S, StringRef LocSec, StringRef LocSym =
"");
119 unsigned toSymbolIndex(StringRef S, StringRef LocSec,
bool IsDynamic);
121 void buildSectionIndex();
122 void buildSymbolIndexes();
123 void initProgramHeaders(std::vector<Elf_Phdr> &PHeaders);
124 bool initImplicitHeader(ContiguousBlobAccumulator &CBA, Elf_Shdr &Header,
125 StringRef SecName, ELFYAML::Section *YAMLSec);
126 void initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
127 ContiguousBlobAccumulator &CBA);
128 void overrideSectionHeaders(std::vector<Elf_Shdr> &SHeaders);
129 void initSymtabSectionHeader(Elf_Shdr &SHeader, SymtabType STType,
130 ContiguousBlobAccumulator &CBA,
131 ELFYAML::Section *YAMLSec);
132 void initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
133 StringTableBuilder &STB,
134 ContiguousBlobAccumulator &CBA,
135 ELFYAML::Section *YAMLSec);
136 void initDWARFSectionHeader(Elf_Shdr &SHeader, StringRef Name,
137 ContiguousBlobAccumulator &CBA,
138 ELFYAML::Section *YAMLSec);
139 void setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
140 std::vector<Elf_Shdr> &SHeaders);
142 std::vector<Fragment>
143 getPhdrFragments(
const ELFYAML::ProgramHeader &Phdr,
146 void finalizeStrings();
147 void writeELFHeader(raw_ostream &OS);
149 const ELFYAML::NoBitsSection &Section,
150 ContiguousBlobAccumulator &CBA);
152 const ELFYAML::RawContentSection &Section,
153 ContiguousBlobAccumulator &CBA);
155 const ELFYAML::RelocationSection &Section,
156 ContiguousBlobAccumulator &CBA);
158 const ELFYAML::RelrSection &Section,
159 ContiguousBlobAccumulator &CBA);
161 const ELFYAML::GroupSection &Group,
162 ContiguousBlobAccumulator &CBA);
164 const ELFYAML::SymtabShndxSection &Shndx,
165 ContiguousBlobAccumulator &CBA);
167 const ELFYAML::SymverSection &Section,
168 ContiguousBlobAccumulator &CBA);
170 const ELFYAML::VerneedSection &Section,
171 ContiguousBlobAccumulator &CBA);
173 const ELFYAML::VerdefSection &Section,
174 ContiguousBlobAccumulator &CBA);
176 const ELFYAML::ARMIndexTableSection &Section,
177 ContiguousBlobAccumulator &CBA);
179 const ELFYAML::MipsABIFlags &Section,
180 ContiguousBlobAccumulator &CBA);
182 const ELFYAML::DynamicSection &Section,
183 ContiguousBlobAccumulator &CBA);
185 const ELFYAML::StackSizesSection &Section,
186 ContiguousBlobAccumulator &CBA);
188 const ELFYAML::BBAddrMapSection &Section,
189 ContiguousBlobAccumulator &CBA);
191 const ELFYAML::HashSection &Section,
192 ContiguousBlobAccumulator &CBA);
194 const ELFYAML::AddrsigSection &Section,
195 ContiguousBlobAccumulator &CBA);
197 const ELFYAML::NoteSection &Section,
198 ContiguousBlobAccumulator &CBA);
200 const ELFYAML::GnuHashSection &Section,
201 ContiguousBlobAccumulator &CBA);
203 const ELFYAML::LinkerOptionsSection &Section,
204 ContiguousBlobAccumulator &CBA);
206 const ELFYAML::DependentLibrariesSection &Section,
207 ContiguousBlobAccumulator &CBA);
209 const ELFYAML::CallGraphProfileSection &Section,
210 ContiguousBlobAccumulator &CBA);
212 void writeFill(ELFYAML::Fill &Fill, ContiguousBlobAccumulator &CBA);
216 void assignSectionAddress(Elf_Shdr &SHeader, ELFYAML::Section *YAMLSec);
218 DenseMap<StringRef, size_t> buildSectionHeaderReorderMap();
222 std::optional<llvm::yaml::Hex64>
Offset);
224 uint64_t getSectionNameOffset(StringRef Name);
227 static bool writeELF(raw_ostream &OS, ELFYAML::Object &Doc,
233 return A.size() *
sizeof(
T);
240template <
class T>
static void zero(
T &Obj) { memset(&Obj, 0,
sizeof(Obj)); }
244 : Doc(
D), ErrHandler(EH) {
248 if (Doc.Header.SectionHeaderStringTable) {
249 SectionHeaderStringTableName = *Doc.Header.SectionHeaderStringTable;
250 if (*Doc.Header.SectionHeaderStringTable ==
".strtab")
251 ShStrtabStrings = &DotStrtab;
252 else if (*Doc.Header.SectionHeaderStringTable ==
".dynstr")
253 ShStrtabStrings = &DotDynstr;
257 std::vector<ELFYAML::Section *> Sections = Doc.getSections();
262 std::make_unique<ELFYAML::Section>(
267 bool HasProgramHeaderTable =
false;
268 for (
size_t I = 0;
I < Doc.Chunks.size(); ++
I) {
269 const std::unique_ptr<ELFYAML::Chunk> &
C = Doc.Chunks[
I];
274 reportError(
"multiple section header tables are not allowed");
281 if (HasProgramHeaderTable)
282 reportError(
"multiple program header tables are not allowed");
283 HasProgramHeaderTable =
true;
289 if (
C->Name.empty()) {
296 if (!DocSections.insert(
C->Name).second)
298 "' at YAML section/fill number " +
Twine(
I));
302 if (Doc.DynamicSymbols) {
303 if (SectionHeaderStringTableName ==
".dynsym")
304 reportError(
"cannot use '.dynsym' as the section header name table when "
305 "there are dynamic symbols");
306 ImplicitSections.insert(
".dynsym");
307 ImplicitSections.insert(
".dynstr");
310 if (SectionHeaderStringTableName ==
".symtab")
311 reportError(
"cannot use '.symtab' as the section header name table when "
312 "there are symbols");
313 ImplicitSections.insert(
".symtab");
316 for (
StringRef DebugSecName : Doc.DWARF->getNonEmptySectionNames()) {
317 std::string SecName = (
"." + DebugSecName).str();
320 if (SectionHeaderStringTableName == SecName)
321 reportError(
"cannot use '" + SecName +
322 "' as the section header name table when it is needed for "
324 ImplicitSections.insert(StringRef(SecName).copy(StringAlloc));
327 ImplicitSections.
insert(
".strtab");
328 if (!SecHdrTable || !SecHdrTable->NoHeaders.value_or(
false))
329 ImplicitSections.
insert(SectionHeaderStringTableName);
334 if (DocSections.count(SecName))
337 std::unique_ptr<ELFYAML::Section> Sec = std::make_unique<ELFYAML::Section>(
341 if (SecName == SectionHeaderStringTableName)
343 else if (SecName ==
".dynsym")
345 else if (SecName ==
".symtab")
355 if (Doc.Chunks.back().get() == SecHdrTable)
356 Doc.Chunks.insert(Doc.Chunks.end() - 1, std::move(Sec));
358 Doc.Chunks.push_back(std::move(Sec));
364 Doc.Chunks.push_back(
365 std::make_unique<ELFYAML::SectionHeaderTable>(
true));
369void ELFState<ELFT>::writeELFHeader(
raw_ostream &OS) {
374 Header.e_ident[
EI_MAG0] = 0x7f;
379 Header.e_ident[
EI_DATA] = Doc.Header.Data;
381 Header.e_ident[
EI_OSABI] = Doc.Header.OSABI;
383 Header.e_type = Doc.Header.Type;
385 if (Doc.Header.Machine)
386 Header.e_machine = *Doc.Header.Machine;
388 Header.e_machine = EM_NONE;
391 Header.e_entry = Doc.Header.Entry;
392 if (Doc.Header.Flags)
393 Header.e_flags = *Doc.Header.Flags;
397 Header.e_ehsize =
sizeof(Elf_Ehdr);
399 if (Doc.Header.EPhOff)
400 Header.e_phoff = *Doc.Header.EPhOff;
402 Header.e_phoff = *PHT->Offset;
403 else if (!Doc.ProgramHeaders.empty())
404 Header.e_phoff =
sizeof(Header);
408 if (Doc.Header.EPhEntSize)
409 Header.e_phentsize = *Doc.Header.EPhEntSize;
410 else if (!Doc.ProgramHeaders.empty())
411 Header.e_phentsize =
sizeof(Elf_Phdr);
413 Header.e_phentsize = 0;
415 if (Doc.Header.EPhNum)
416 Header.e_phnum = *Doc.Header.EPhNum;
417 else if (!Doc.ProgramHeaders.empty())
418 Header.e_phnum = Doc.ProgramHeaders.size();
422 Header.e_shentsize = Doc.Header.EShEntSize ? (
uint16_t)*Doc.Header.EShEntSize
426 Doc.getSectionHeaderTable();
428 if (Doc.Header.EShOff)
429 Header.e_shoff = *Doc.Header.EShOff;
431 Header.e_shoff = *SectionHeaders.
Offset;
435 if (Doc.Header.EShNum)
436 Header.e_shnum = *Doc.Header.EShNum;
438 Header.e_shnum = SectionHeaders.
getNumHeaders(Doc.getSections().size());
440 if (Doc.Header.EShStrNdx)
441 Header.e_shstrndx = *Doc.Header.EShStrNdx;
443 !ExcludedSectionHeaders.count(SectionHeaderStringTableName))
444 Header.e_shstrndx = SN2I.get(SectionHeaderStringTableName);
446 Header.e_shstrndx = 0;
448 OS.
write((
const char *)&Header,
sizeof(Header));
452void ELFState<ELFT>::initProgramHeaders(std::vector<Elf_Phdr> &PHeaders) {
454 for (
size_t I = 0,
E = Doc.Chunks.size();
I !=
E; ++
I) {
455 NameToIndex[Doc.Chunks[
I]->Name] =
I + 1;
458 for (
size_t I = 0,
E = Doc.ProgramHeaders.size();
I !=
E; ++
I) {
462 Phdr.p_type = YamlPhdr.
Type;
463 Phdr.p_flags = YamlPhdr.
Flags;
464 Phdr.p_vaddr = YamlPhdr.
VAddr;
465 Phdr.p_paddr = YamlPhdr.
PAddr;
466 PHeaders.push_back(Phdr);
475 "' by the 'FirstSec' key of the program header with index " +
480 "' by the 'LastSec' key of the program header with index " +
487 ": the section index of " + *YamlPhdr.
FirstSec +
488 " is greater than the index of " + *YamlPhdr.
LastSec);
491 YamlPhdr.
Chunks.push_back(Doc.Chunks[
I - 1].get());
501 if (!SN2I.lookup(S, Index) && !
to_integer(S, Index)) {
503 reportError(
"unknown section referenced: '" + S +
"' by YAML symbol '" +
506 reportError(
"unknown section referenced: '" + S +
"' by YAML section '" +
512 Doc.getSectionHeaderTable();
519 size_t FirstExcluded =
521 if (Index > FirstExcluded) {
523 reportError(
"unable to link '" + LocSec +
"' to excluded section '" + S +
526 reportError(
"excluded section referenced: '" + S +
"' by symbol '" +
535 const NameToIdxMap &
SymMap = IsDynamic ? DynSymN2I : SymN2I;
540 reportError(
"unknown symbol referenced: '" + S +
"' by YAML section '" +
556 To.sh_name = *From->
ShName;
560 To.sh_size = *From->
ShSize;
562 To.sh_type = *From->
ShType;
570 if (Header.sh_offset)
573 if (SecName ==
".strtab")
574 initStrtabSectionHeader(Header, SecName, DotStrtab, CBA, YAMLSec);
575 else if (SecName ==
".dynstr")
576 initStrtabSectionHeader(Header, SecName, DotDynstr, CBA, YAMLSec);
577 else if (SecName == SectionHeaderStringTableName)
578 initStrtabSectionHeader(Header, SecName, *ShStrtabStrings, CBA, YAMLSec);
579 else if (SecName ==
".symtab")
580 initSymtabSectionHeader(Header, SymtabType::Static, CBA, YAMLSec);
581 else if (SecName ==
".dynsym")
582 initSymtabSectionHeader(Header, SymtabType::Dynamic, CBA, YAMLSec);
588 initDWARFSectionHeader(Header, SecName, CBA, YAMLSec);
592 LocationCounter += Header.sh_size;
605 std::string Ret = Name.empty() ?
"" : Name.str() +
' ';
620 return S.
substr(0, SuffixPos - 1);
624uint64_t ELFState<ELFT>::getSectionNameOffset(
StringRef Name) {
627 if (ExcludedSectionHeaders.count(Name))
629 return ShStrtabStrings->getOffset(Name);
633 const std::optional<yaml::BinaryRef> &Content,
634 const std::optional<llvm::yaml::Hex64> &
Size) {
635 size_t ContentSize = 0;
638 ContentSize = Content->binary_size();
672void ELFState<ELFT>::initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
676 SHeaders.resize(Doc.getSections().size());
678 for (
const std::unique_ptr<ELFYAML::Chunk> &
D : Doc.Chunks) {
680 S->Offset = alignToOffset(CBA, 1, S->Offset);
682 LocationCounter += S->Size;
688 if (S->NoHeaders.value_or(
false))
692 S->Offset = alignToOffset(CBA,
sizeof(
typename ELFT::uint),
695 S->Offset = alignToOffset(CBA, 1, S->Offset);
697 uint64_t Size = S->getNumHeaders(SHeaders.size()) *
sizeof(Elf_Shdr);
701 LocationCounter +=
Size;
708 PHT->Offset = alignToOffset(CBA,
sizeof(
typename ELFT::uint),
711 PHT->Offset = alignToOffset(CBA, 1, PHT->Offset);
712 uint64_t Size = Doc.ProgramHeaders.size() *
sizeof(Elf_Phdr);
715 LocationCounter +=
Size;
720 bool IsFirstUndefSection = Sec == Doc.getSections().front();
724 Elf_Shdr &SHeader = SHeaders[SN2I.get(Sec->
Name)];
726 SHeader.sh_link = toSectionIndex(*Sec->
Link, Sec->
Name);
730 if (!LinkSec.
empty() && !ExcludedSectionHeaders.count(LinkSec) &&
731 SN2I.lookup(LinkSec, Link))
732 SHeader.sh_link = Link;
736 SHeader.sh_entsize = *Sec->
EntSize;
739 Doc.Header.Machine.value_or(ELF::EM_NONE), Sec->
Type, Sec->
Name);
745 if (initImplicitHeader(CBA, SHeader, Sec->
Name,
749 assert(Sec &&
"It can't be null unless it is an implicit section. But all "
750 "implicit sections should already have been handled above.");
754 SHeader.sh_type = Sec->
Type;
756 SHeader.sh_flags = *Sec->
Flags;
761 if (!IsFirstUndefSection || Sec->
Offset)
762 SHeader.sh_offset = alignToOffset(CBA, SHeader.sh_addralign, Sec->
Offset);
764 assignSectionAddress(SHeader, Sec);
766 if (IsFirstUndefSection) {
770 SHeader.sh_size = *RawSec->Size;
772 SHeader.sh_info = *RawSec->Info;
775 LocationCounter += SHeader.sh_size;
776 SectionHeadersOverrideHelper.push_back({&SHeader, *Sec});
829 LocationCounter += SHeader.sh_size;
830 SectionHeadersOverrideHelper.push_back({&SHeader, *Sec});
835void ELFState<ELFT>::overrideSectionHeaders(std::vector<Elf_Shdr> &SHeaders) {
836 for (std::pair<Elf_Shdr *, ELFYAML::Section> &HeaderAndSec :
837 SectionHeadersOverrideHelper)
842void ELFState<ELFT>::assignSectionAddress(Elf_Shdr &SHeader,
844 if (YAMLSec && YAMLSec->
Address) {
845 SHeader.sh_addr = *YAMLSec->
Address;
846 LocationCounter = *YAMLSec->
Address;
858 alignTo(LocationCounter, SHeader.sh_addralign ? SHeader.sh_addralign : 1);
859 SHeader.sh_addr = LocationCounter;
863 for (
size_t I = 0;
I < Symbols.size(); ++
I)
866 return Symbols.size();
870std::vector<typename ELFT::Sym>
873 std::vector<Elf_Sym> Ret;
874 Ret.resize(
Symbols.size() + 1);
878 Elf_Sym &Symbol = Ret[++
I];
884 Symbol.st_name = *Sym.StName;
885 else if (!Sym.Name.empty())
888 Symbol.setBindingAndType(Sym.Binding, Sym.Type);
890 Symbol.st_shndx = toSectionIndex(*Sym.Section,
"", Sym.Name);
892 Symbol.st_shndx = *Sym.Index;
894 Symbol.st_value = Sym.Value.value_or(yaml::Hex64(0));
895 Symbol.st_other = Sym.Other.value_or(0);
896 Symbol.st_size = Sym.Size.value_or(yaml::Hex64(0));
903void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
908 bool IsStatic = STType == SymtabType::Static;
910 if (IsStatic && Doc.Symbols)
912 else if (!IsStatic && Doc.DynamicSymbols)
918 bool HasSymbolsDescription =
919 (IsStatic && Doc.Symbols) || (!IsStatic && Doc.DynamicSymbols);
920 if (HasSymbolsDescription) {
923 reportError(
"cannot specify both `Content` and " + Property +
924 " for symbol table section '" + RawSec->
Name +
"'");
926 reportError(
"cannot specify both `Size` and " + Property +
927 " for symbol table section '" + RawSec->
Name +
"'");
932 SHeader.sh_name = getSectionNameOffset(IsStatic ?
".symtab" :
".dynsym");
935 SHeader.sh_type = YAMLSec->
Type;
939 if (YAMLSec && YAMLSec->
Flags)
940 SHeader.sh_flags = *YAMLSec->
Flags;
946 SHeader.sh_info = (RawSec && RawSec->
Info) ? (
unsigned)(*RawSec->
Info)
950 assignSectionAddress(SHeader, YAMLSec);
952 SHeader.sh_offset = alignToOffset(CBA, SHeader.sh_addralign,
953 RawSec ? RawSec->
Offset : std::nullopt);
961 std::vector<Elf_Sym> Syms =
962 toELFSymbols(Symbols, IsStatic ? DotStrtab : DotDynstr);
963 SHeader.sh_size = Syms.size() *
sizeof(Elf_Sym);
964 CBA.
write((
const char *)Syms.data(), SHeader.sh_size);
968void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader,
StringRef Name,
979 SHeader.sh_offset = alignToOffset(CBA, SHeader.sh_addralign,
980 YAMLSec ? YAMLSec->
Offset : std::nullopt);
987 SHeader.sh_size = STB.
getSize();
990 if (RawSec && RawSec->
Info)
991 SHeader.sh_info = *RawSec->
Info;
993 if (YAMLSec && YAMLSec->
Flags)
994 SHeader.sh_flags = *YAMLSec->
Flags;
995 else if (Name ==
".dynstr")
998 assignSectionAddress(SHeader, YAMLSec);
1003 return Name.consume_front(
".") && DebugSecNames.
count(Name);
1006template <
class ELFT>
1020 if (
Error Err = EmitFunc(*OS, DWARF))
1021 return std::move(Err);
1023 return CBA.
tell() - BeginOffset;
1026template <
class ELFT>
1027void ELFState<ELFT>::initDWARFSectionHeader(Elf_Shdr &SHeader,
StringRef Name,
1033 SHeader.sh_offset = alignToOffset(CBA, SHeader.sh_addralign,
1034 YAMLSec ? YAMLSec->
Offset : std::nullopt);
1041 "' contents in the 'DWARF' entry and the 'Content' "
1042 "or 'Size' in the 'Sections' entry at the same time");
1046 SHeader.sh_size = *ShSizeOrErr;
1054 "entry or a RawContentSection");
1056 if (RawSec && RawSec->
Info)
1057 SHeader.sh_info = *RawSec->
Info;
1059 if (YAMLSec && YAMLSec->
Flags)
1060 SHeader.sh_flags = *YAMLSec->
Flags;
1061 else if (Name ==
".debug_str")
1064 assignSectionAddress(SHeader, YAMLSec);
1067template <
class ELFT>
void ELFState<ELFT>::reportError(
const Twine &
Msg) {
1072template <
class ELFT>
void ELFState<ELFT>::reportError(
Error Err) {
1078template <
class ELFT>
1079std::vector<Fragment>
1082 std::vector<Fragment> Ret;
1092 Ret.push_back({*PHT->Offset, Doc.ProgramHeaders.size() *
sizeof(Elf_Phdr),
1094 sizeof(
typename ELFT::uint)});
1099 const Elf_Shdr &
H = SHeaders[SN2I.get(S->
Name)];
1100 Ret.push_back({
H.sh_offset,
H.sh_size,
H.sh_type,
H.sh_addralign});
1105template <
class ELFT>
1106void ELFState<ELFT>::setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
1107 std::vector<Elf_Shdr> &SHeaders) {
1109 for (
auto &YamlPhdr : Doc.ProgramHeaders) {
1110 Elf_Phdr &PHeader = PHeaders[PhdrIdx++];
1111 std::vector<Fragment> Fragments = getPhdrFragments(YamlPhdr, SHeaders);
1113 return A.Offset <
B.Offset;
1115 reportError(
"sections in the program header with index " +
1116 Twine(PhdrIdx) +
" are not sorted by their file offset");
1119 if (!Fragments.empty() && *YamlPhdr.
Offset > Fragments.front().Offset)
1121 " must be less than or equal to the minimum file offset of "
1122 "all included sections (0x" +
1124 PHeader.p_offset = *YamlPhdr.
Offset;
1125 }
else if (!Fragments.empty()) {
1126 PHeader.p_offset = Fragments.front().Offset;
1131 PHeader.p_filesz = *YamlPhdr.
FileSize;
1132 }
else if (!Fragments.empty()) {
1133 uint64_t FileSize = Fragments.back().Offset - PHeader.p_offset;
1138 FileSize += Fragments.back().Size;
1139 PHeader.p_filesz = FileSize;
1143 uint64_t MemOffset = PHeader.p_offset;
1145 MemOffset = std::max(MemOffset,
F.Offset +
F.Size);
1148 : MemOffset - PHeader.p_offset;
1150 if (YamlPhdr.
Align) {
1151 PHeader.p_align = *YamlPhdr.
Align;
1156 PHeader.p_align = 1;
1158 PHeader.p_align = std::max((
uint64_t)PHeader.p_align,
F.AddrAlign);
1169 return (isa<ELFYAML::Fill, ELFYAML::ProgramHeaderTable>(C) ||
1170 cast<ELFYAML::Section>(C)->Type != ELF::SHT_NOBITS);
1177template <
class ELFT>
1178void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1184 SHeader.sh_size = *S.
Size;
1189 if (shouldAllocateFileSpace(Doc.ProgramHeaders, S))
1193template <
class ELFT>
1194void ELFState<ELFT>::writeSectionContent(
1198 SHeader.sh_info = *Section.Info;
1202 return Obj.getMachine() == llvm::ELF::EM_MIPS &&
1207template <
class ELFT>
1208void ELFState<ELFT>::writeSectionContent(
1214 "Section type is not SHT_REL nor SHT_RELA");
1216 if (!
Section.RelocatableSec.empty())
1217 SHeader.sh_info = toSectionIndex(
Section.RelocatableSec,
Section.Name);
1224 typename ELFT::uint OffsetMask = 8,
Offset = 0, Addend = 0;
1229 OffsetMask |= Rel.
Offset;
1235 const bool IsDynamic =
Section.Link && (*
Section.Link ==
".dynsym");
1243 (
static_cast<typename ELFT::uint
>(Rel.
Offset) -
Offset) >> Shift;
1246 DeltaOffset * 8 + (SymIdx != CurSymIdx) + (
Type != Rel.
Type ? 2 : 0) +
1247 (Addend !=
static_cast<typename ELFT::uint
>(Rel.
Addend) ? 4 : 0);
1248 if (DeltaOffset < 0x10) {
1257 std::make_signed_t<typename ELFT::uint>(CurSymIdx - SymIdx));
1266 std::make_signed_t<typename ELFT::uint>(Rel.
Addend - Addend));
1269 }
else if (IsRela) {
1272 REntry.r_offset = Rel.
Offset;
1273 REntry.r_addend = Rel.
Addend;
1275 CBA.
write((
const char *)&REntry,
sizeof(REntry));
1279 REntry.r_offset = Rel.
Offset;
1281 CBA.
write((
const char *)&REntry,
sizeof(REntry));
1285 SHeader.sh_size = CBA.
getOffset() - CurrentOffset;
1288template <
class ELFT>
1289void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1295 for (llvm::yaml::Hex64
E : *
Section.Entries) {
1296 if (!ELFT::Is64Bits &&
E > UINT32_MAX)
1299 CBA.
write<uintX_t>(
E, ELFT::Endianness);
1302 SHeader.sh_size =
sizeof(uintX_t) *
Section.Entries->size();
1305template <
class ELFT>
1306void ELFState<ELFT>::writeSectionContent(
1319 SHeader.sh_size = Shndx.
Entries->size() * SHeader.sh_entsize;
1322template <
class ELFT>
1323void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1327 "Section type is not SHT_GROUP");
1337 unsigned int SectionIndex = 0;
1338 if (
Member.sectionNameOrType ==
"GRP_COMDAT")
1341 SectionIndex = toSectionIndex(
Member.sectionNameOrType,
Section.Name);
1344 SHeader.sh_size = SHeader.sh_entsize *
Section.Members->size();
1347template <
class ELFT>
1348void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1356 SHeader.sh_size =
Section.Entries->size() * SHeader.sh_entsize;
1359template <
class ELFT>
1360void ELFState<ELFT>::writeSectionContent(
1367 CBA.
write<uintX_t>(
E.Address, ELFT::Endianness);
1368 SHeader.sh_size +=
sizeof(uintX_t) + CBA.
writeULEB128(
E.Size);
1372template <
class ELFT>
1373void ELFState<ELFT>::writeSectionContent(
1379 <<
"PGOAnalyses should not exist in SHT_LLVM_BB_ADDR_MAP when "
1380 "Entries does not exist";
1384 const std::vector<BBAddrMapYAML::PGOAnalysisMapEntry> *PGOAnalyses =
nullptr;
1388 "in SHT_LLVM_BB_ADDR_MAP";
1390 PGOAnalyses = &
Section.PGOAnalyses.value();
1395 ELFT::Endianness,
sizeof(uintX_t));
1396 SHeader.sh_size += CBA.
getOffset() - CurrentOffset;
1399template <
class ELFT>
1400void ELFState<ELFT>::writeSectionContent(
1407 CBA.
write(
LO.Key.data(),
LO.Key.size());
1409 CBA.
write(
LO.Value.data(),
LO.Value.size());
1411 SHeader.sh_size += (
LO.Key.size() +
LO.Value.size() + 2);
1415template <
class ELFT>
1416void ELFState<ELFT>::writeSectionContent(
1425 SHeader.sh_size +=
Lib.size() + 1;
1429template <
class ELFT>
1432 std::optional<llvm::yaml::Hex64>
Offset) {
1440 return CurrentOffset;
1449 CBA.
writeZeros(AlignedOffset - CurrentOffset);
1450 return AlignedOffset;
1453template <
class ELFT>
1454void ELFState<ELFT>::writeSectionContent(
1466template <
class ELFT>
1467void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1474 Section.NBucket.value_or(llvm::yaml::Hex64(
Section.Bucket->size())),
1477 Section.NChain.value_or(llvm::yaml::Hex64(
Section.Chain->size())),
1485 SHeader.sh_size = (2 +
Section.Bucket->size() +
Section.Chain->size()) * 4;
1488template <
class ELFT>
1489void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1494 SHeader.sh_info = *
Section.Info;
1496 SHeader.sh_info =
Section.Entries->size();
1502 for (
size_t I = 0;
I <
Section.Entries->size(); ++
I) {
1506 VerDef.vd_version =
E.Version.value_or(1);
1507 VerDef.vd_flags =
E.Flags.value_or(0);
1508 VerDef.vd_ndx =
E.VersionNdx.value_or(0);
1509 VerDef.vd_hash =
E.Hash.value_or(0);
1510 VerDef.vd_aux =
E.VDAux.value_or(
sizeof(Elf_Verdef));
1511 VerDef.vd_cnt =
E.VerNames.size();
1512 if (
I ==
Section.Entries->size() - 1)
1516 sizeof(Elf_Verdef) +
E.VerNames.size() *
sizeof(Elf_Verdaux);
1517 CBA.
write((
const char *)&VerDef,
sizeof(Elf_Verdef));
1519 for (
size_t J = 0; J <
E.VerNames.size(); ++J, ++AuxCnt) {
1520 Elf_Verdaux VerdAux;
1521 VerdAux.vda_name = DotDynstr.getOffset(
E.VerNames[J]);
1522 if (J ==
E.VerNames.size() - 1)
1523 VerdAux.vda_next = 0;
1525 VerdAux.vda_next =
sizeof(Elf_Verdaux);
1526 CBA.
write((
const char *)&VerdAux,
sizeof(Elf_Verdaux));
1530 SHeader.sh_size =
Section.Entries->size() *
sizeof(Elf_Verdef) +
1531 AuxCnt *
sizeof(Elf_Verdaux);
1534template <
class ELFT>
1535void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1539 SHeader.sh_info = *
Section.Info;
1541 SHeader.sh_info =
Section.VerneedV->size();
1547 for (
size_t I = 0;
I <
Section.VerneedV->size(); ++
I) {
1550 Elf_Verneed VerNeed;
1551 VerNeed.vn_version =
VE.Version;
1552 VerNeed.vn_file = DotDynstr.getOffset(
VE.File);
1553 if (
I ==
Section.VerneedV->size() - 1)
1554 VerNeed.vn_next = 0;
1557 sizeof(Elf_Verneed) +
VE.AuxV.size() *
sizeof(Elf_Vernaux);
1558 VerNeed.vn_cnt =
VE.AuxV.size();
1559 VerNeed.vn_aux =
sizeof(Elf_Verneed);
1560 CBA.
write((
const char *)&VerNeed,
sizeof(Elf_Verneed));
1562 for (
size_t J = 0; J <
VE.AuxV.size(); ++J, ++AuxCnt) {
1565 Elf_Vernaux VernAux;
1566 VernAux.vna_hash = VAuxE.
Hash;
1567 VernAux.vna_flags = VAuxE.
Flags;
1568 VernAux.vna_other = VAuxE.
Other;
1569 VernAux.vna_name = DotDynstr.getOffset(VAuxE.
Name);
1570 if (J ==
VE.AuxV.size() - 1)
1571 VernAux.vna_next = 0;
1573 VernAux.vna_next =
sizeof(Elf_Vernaux);
1574 CBA.
write((
const char *)&VernAux,
sizeof(Elf_Vernaux));
1578 SHeader.sh_size =
Section.VerneedV->size() *
sizeof(Elf_Verneed) +
1579 AuxCnt *
sizeof(Elf_Vernaux);
1582template <
class ELFT>
1583void ELFState<ELFT>::writeSectionContent(
1593 SHeader.sh_size =
Section.Entries->size() * 8;
1596template <
class ELFT>
1597void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1601 "Section type is not SHT_MIPS_ABIFLAGS");
1605 SHeader.sh_size = SHeader.sh_entsize;
1607 Flags.version =
Section.Version;
1608 Flags.isa_level =
Section.ISALevel;
1609 Flags.isa_rev =
Section.ISARevision;
1610 Flags.gpr_size =
Section.GPRSize;
1611 Flags.cpr1_size =
Section.CPR1Size;
1612 Flags.cpr2_size =
Section.CPR2Size;
1614 Flags.isa_ext =
Section.ISAExtension;
1616 Flags.flags1 =
Section.Flags1;
1617 Flags.flags2 =
Section.Flags2;
1618 CBA.
write((
const char *)&Flags,
sizeof(Flags));
1621template <
class ELFT>
1622void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1626 "Section type is not SHT_DYNAMIC");
1632 CBA.
write<uintX_t>(DE.
Tag, ELFT::Endianness);
1633 CBA.
write<uintX_t>(DE.
Val, ELFT::Endianness);
1635 SHeader.sh_size = 2 *
sizeof(uintX_t) *
Section.Entries->size();
1638template <
class ELFT>
1639void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1650template <
class ELFT>
1651void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1658 switch (
Section.AddressAlign) {
1682 if (
NE.Name.empty())
1688 if (
NE.Desc.binary_size() == 0)
1697 if (!
NE.Name.empty()) {
1698 CBA.
write(
NE.Name.data(),
NE.Name.size());
1703 if (
NE.Desc.binary_size() != 0) {
1714template <
class ELFT>
1715void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1739 if (
Section.Header->MaskWords)
1748 for (llvm::yaml::Hex64 Val : *
Section.BloomFilter)
1749 CBA.
write<uintX_t>(Val, ELFT::Endianness);
1752 for (llvm::yaml::Hex32 Val : *
Section.HashBuckets)
1756 for (llvm::yaml::Hex32 Val : *
Section.HashValues)
1759 SHeader.sh_size = 16 +
1760 Section.BloomFilter->size() *
sizeof(
typename ELFT::uint) +
1761 Section.HashBuckets->size() * 4 +
1762 Section.HashValues->size() * 4;
1765template <
class ELFT>
1768 size_t PatternSize = Fill.
Pattern ? Fill.
Pattern->binary_size() : 0;
1776 for (; Written + PatternSize <= Fill.
Size; Written += PatternSize)
1781template <
class ELFT>
1784 Doc.getSectionHeaderTable();
1795 reportError(
"repeated section name: '" + Hdr.Name +
1796 "' in the section header description");
1810 if (S == Doc.getSections().front())
1814 "' should be present in the 'Sections' or 'Excluded' lists");
1818 for (
const auto &It : Seen)
1819 reportError(
"section header contains undefined section '" + It.getKey() +
1824template <
class ELFT>
void ELFState<ELFT>::buildSectionIndex() {
1833 std::vector<ELFYAML::Section *> Sections = Doc.getSections();
1835 Doc.getSectionHeaderTable();
1838 if (!ExcludedSectionHeaders.insert(Hdr.
Name).second)
1841 if (SectionHeaders.
NoHeaders.value_or(
false))
1843 if (!ExcludedSectionHeaders.insert(S->
Name).second)
1850 size_t Index = ReorderMap.
empty() ? SecNdx : ReorderMap.
lookup(S->
Name);
1851 if (!SN2I.addName(S->
Name, Index))
1854 if (!ExcludedSectionHeaders.count(S->
Name))
1859template <
class ELFT>
void ELFState<ELFT>::buildSymbolIndexes() {
1861 for (
size_t I = 0, S =
V.size();
I < S; ++
I) {
1869 Build(*Doc.Symbols, SymN2I);
1870 if (Doc.DynamicSymbols)
1871 Build(*Doc.DynamicSymbols, DynSymN2I);
1874template <
class ELFT>
void ELFState<ELFT>::finalizeStrings() {
1879 DotStrtab.finalize();
1882 if (Doc.DynamicSymbols)
1890 if (VerNeed->VerneedV) {
1892 DotDynstr.add(
VE.File);
1894 DotDynstr.add(Aux.
Name);
1898 if (VerDef->Entries)
1901 DotDynstr.add(Name);
1905 DotDynstr.finalize();
1909 if (ShStrtabStrings != &DotStrtab && ShStrtabStrings != &DotDynstr)
1910 ShStrtabStrings->finalize();
1913template <
class ELFT>
1916 ELFState<ELFT> State(Doc, EH);
1922 State.buildSectionIndex();
1923 State.buildSymbolIndexes();
1928 State.finalizeStrings();
1933 std::vector<Elf_Phdr> PHeaders;
1934 State.initProgramHeaders(PHeaders);
1939 const size_t SectionContentBeginOffset =
1948 std::vector<Elf_Shdr> SHeaders;
1949 State.initSectionHeaders(SHeaders, CBA);
1952 State.setProgramHeaderLayout(PHeaders, SHeaders);
1957 State.overrideSectionHeaders(SHeaders);
1959 bool ReachedLimit = CBA.
getOffset() > MaxSize;
1963 ReachedLimit =
true;
1968 "the desired output size is greater than permitted. Use the "
1969 "--max-size option to change the limit");
1974 State.writeELFHeader(OS);
1977 PHeaders.size() *
sizeof(Elf_Phdr));
1999 return ELFState<object::ELF64LE>::writeELF(Out, Doc, EH, MaxSize);
2000 return ELFState<object::ELF64BE>::writeELF(Out, Doc, EH, MaxSize);
2003 return ELFState<object::ELF32LE>::writeELF(Out, Doc, EH, MaxSize);
2004 return ELFState<object::ELF32BE>::writeELF(Out, Doc, EH, MaxSize);
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< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool writeSectionContent(COFFParser &CP, COFFYAML::Section &S, ContiguousBlobAccumulator &CBA)
This file defines ContiguousBlobAccumulator, the size-limited output buffer shared by the yaml2obj em...
Common declarations for yaml2obj.
This file declares classes for handling the YAML representation of DWARF Debug Info.
DXIL Resource Implicit Binding
This file defines the DenseMap class.
static StringRef getDefaultLinkSec(unsigned SecType)
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 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)
This file declares classes for handling the YAML representation of ELF.
static bool lookup(const GsymReader &GR, GsymDataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr, uint64_t Addr, SourceLocations &SrcLocs, llvm::Error &Err)
A Lookup helper functions.
This file implements a set that has insertion order iteration characteristics.
StringSet - A set-like wrapper for the StringMap.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Base class for error info classes.
Lightweight error class with error context and mandatory checking.
Tagged union holding either a T or a Error.
A vector that has set insertion semantics.
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
bool insert(const value_type &X)
Insert a new element into the SetVector.
A SetVector that performs no allocations if smaller than a certain size.
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Represent a constant reference to a string, i.e.
static constexpr size_t npos
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
constexpr bool empty() const
Check if the string is empty.
LLVM_ABI size_t rfind(char C, size_t From=npos) const
Search for the last character C in the string.
char back() const
Get the last character in the string.
StringRef copy(Allocator &A) const
StringSet - A wrapper for StringMap that provides set-like functionality.
std::pair< typename Base::iterator, bool > insert(StringRef key)
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...
static Twine utohexstr(uint64_t Val)
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI raw_ostream & warning()
Convenience method for printing "warning: " to stderr.
This class implements an extremely fast bulk output stream that can only output to a stream.
raw_ostream & write(unsigned char C)
LLVM_ABI uint64_t padToAlignment(unsigned Align)
LLVM_ABI unsigned writeSLEB128(int64_t Val)
LLVM_ABI void writeAsBinary(const BinaryRef &Bin, uint64_t N=UINT64_MAX)
void writeBlobToStream(raw_ostream &Out) const
void write(const char *Ptr, size_t Size)
uint64_t getOffset() const
void writeZeros(uint64_t Num)
LLVM_ABI unsigned writeULEB128(uint64_t Val)
raw_ostream * getRawOS(uint64_t Size)
void updateDataAt(uint64_t Pos, T Val, llvm::endianness E)
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI void encodePayload(ArrayRef< BBAddrMapEntry > Entries, const std::vector< PGOAnalysisMapEntry > *PGOAnalyses, yaml::ContiguousBlobAccumulator &CBA, llvm::endianness Endian, unsigned AddressSize)
Encodes the BBAddrMap payload into CBA.
LLVM_ABI std::function< Error(raw_ostream &, const Data &)> getDWARFEmitterByName(StringRef SecName)
LLVM_ABI std::string appendUniqueSuffix(StringRef Name, const Twine &Msg)
unsigned getDefaultShEntSize(unsigned EMachine, ELF_SHT SecType, StringRef SecName)
LLVM_ABI StringRef dropUniqueSuffix(StringRef S)
LLVM_ABI bool shouldAllocateFileSpace(ArrayRef< ProgramHeader > Phdrs, const NoBitsSection &S)
constexpr unsigned CREL_HDR_ADDEND
@ SHT_LLVM_CALL_GRAPH_PROFILE
LLVM_ABI bool yaml2elf(ELFYAML::Object &Doc, raw_ostream &Out, ErrorHandler EH, uint64_t MaxSize)
llvm::function_ref< void(const Twine &Msg)> ErrorHandler
This is an optimization pass for GlobalISel generic memory operations.
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.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
auto dyn_cast_or_null(const Y &Val)
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
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...
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...
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
@ Dynamic
Denotes mode unknown at compile time.
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
bool to_integer(StringRef S, N &Num, unsigned Base=0)
Convert the string S to an integer of the specified type using the radix Base. If Base is 0,...
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
void consumeError(Error Err)
Consume a Error without doing anything.
This struct is a compact representation of a valid (non-zero power of two) alignment.
LLVM_ABI SetVector< StringRef > getNonEmptySectionNames() const
std::optional< llvm::yaml::Hex64 > Offset
std::optional< yaml::BinaryRef > Pattern
const SectionHeaderTable & getSectionHeaderTable() const
std::vector< ProgramHeader > ProgramHeaders
const ProgramHeaderTable * getProgramHeaderTable() const
std::optional< llvm::yaml::Hex64 > Info
std::optional< StringRef > Symbol
std::optional< llvm::yaml::Hex64 > Address
std::optional< StringRef > Link
std::optional< llvm::yaml::Hex64 > Size
std::optional< llvm::yaml::Hex64 > ShAddrAlign
llvm::yaml::Hex64 AddressAlign
std::optional< ELF_SHF > Flags
std::optional< ELF_SHT > ShType
std::optional< llvm::yaml::Hex64 > ShOffset
std::optional< llvm::yaml::Hex64 > ShFlags
std::optional< llvm::yaml::Hex64 > ShName
std::optional< yaml::BinaryRef > Content
std::optional< llvm::yaml::Hex64 > EntSize
std::optional< llvm::yaml::Hex64 > ShSize
std::optional< std::vector< uint32_t > > Entries
Common declarations for yaml2obj.