LLVM 24.0.0git
ELFObjHandler.cpp
Go to the documentation of this file.
1//===- ELFObjHandler.cpp --------------------------------------------------===//
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
12#include "llvm/Object/Binary.h"
15#include "llvm/Support/Errc.h"
16#include "llvm/Support/Error.h"
20#include <optional>
21
23
24using namespace llvm;
25using namespace llvm::object;
26using namespace llvm::ELF;
27
28namespace llvm {
29namespace ifs {
30
31// Simple struct to hold relevant .dynamic entries.
33 uint64_t StrTabAddr = 0;
34 uint64_t StrSize = 0;
35 std::optional<uint64_t> SONameOffset;
36 std::vector<uint64_t> NeededLibNames;
37 // Symbol table:
38 uint64_t DynSymAddr = 0;
39 // Hash tables:
40 std::optional<uint64_t> ElfHash;
41 std::optional<uint64_t> GnuHash;
42};
43
44/// This initializes an ELF file header with information specific to a binary
45/// dynamic shared object.
46/// Offsets, indexes, links, etc. for section and program headers are just
47/// zero-initialized as they will be updated elsewhere.
48///
49/// @param ElfHeader Target ELFT::Ehdr to populate.
50/// @param Machine Target architecture (e_machine from ELF specifications).
51/// @param OSABI Target OS/ABI (EI_OSABI from ELF specifications).
52template <class ELFT>
53static void initELFHeader(typename ELFT::Ehdr &ElfHeader, uint16_t Machine,
54 uint8_t OSABI = ELFOSABI_NONE) {
55 memset(&ElfHeader, 0, sizeof(ElfHeader));
56 // ELF identification.
57 ElfHeader.e_ident[EI_MAG0] = ElfMagic[EI_MAG0];
58 ElfHeader.e_ident[EI_MAG1] = ElfMagic[EI_MAG1];
59 ElfHeader.e_ident[EI_MAG2] = ElfMagic[EI_MAG2];
60 ElfHeader.e_ident[EI_MAG3] = ElfMagic[EI_MAG3];
61 ElfHeader.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
62 bool IsLittleEndian = ELFT::Endianness == llvm::endianness::little;
63 ElfHeader.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
64 ElfHeader.e_ident[EI_VERSION] = EV_CURRENT;
65 ElfHeader.e_ident[EI_OSABI] = OSABI;
66
67 // Remainder of ELF header.
68 ElfHeader.e_type = ET_DYN;
69 ElfHeader.e_machine = Machine;
70 ElfHeader.e_version = EV_CURRENT;
71 ElfHeader.e_ehsize = sizeof(typename ELFT::Ehdr);
72 ElfHeader.e_phentsize = sizeof(typename ELFT::Phdr);
73 ElfHeader.e_shentsize = sizeof(typename ELFT::Shdr);
74}
75
76namespace {
77template <class ELFT> struct OutputSection {
78 using Elf_Shdr = typename ELFT::Shdr;
79 std::string Name;
80 Elf_Shdr Shdr;
81 uint64_t Addr;
82 uint64_t Offset;
83 uint64_t Size;
84 uint64_t Align;
85 uint32_t Index;
86 bool NoBits = true;
87};
88
89template <class T, class ELFT>
90struct ContentSection : public OutputSection<ELFT> {
91 T Content;
92 ContentSection() { this->NoBits = false; }
93};
94
95// This class just wraps StringTableBuilder for the purpose of adding a
96// default constructor.
97class ELFStringTableBuilder : public StringTableBuilder {
98public:
99 ELFStringTableBuilder() : StringTableBuilder(StringTableBuilder::ELF) {}
100};
101
102template <class ELFT> class ELFSymbolTableBuilder {
103public:
104 using Elf_Sym = typename ELFT::Sym;
105
106 ELFSymbolTableBuilder() { Symbols.push_back({}); }
107
108 void add(size_t StNameOffset, uint64_t StSize, uint8_t StBind, uint8_t StType,
109 uint8_t StOther, uint16_t StShndx) {
110 Elf_Sym S{};
111 S.st_name = StNameOffset;
112 S.st_size = StSize;
113 S.st_info = (StBind << 4) | (StType & 0xf);
114 S.st_other = StOther;
115 S.st_shndx = StShndx;
116 Symbols.push_back(S);
117 }
118
119 size_t getSize() const { return Symbols.size() * sizeof(Elf_Sym); }
120
121 void write(uint8_t *Buf) const {
122 memcpy(Buf, Symbols.data(), sizeof(Elf_Sym) * Symbols.size());
123 }
124
125private:
127};
128
129template <class ELFT> class ELFDynamicTableBuilder {
130public:
131 using Elf_Dyn = typename ELFT::Dyn;
132
133 size_t addAddr(uint64_t Tag, uint64_t Addr) {
134 Elf_Dyn Entry;
135 Entry.d_tag = Tag;
136 Entry.d_un.d_ptr = Addr;
137 Entries.push_back(Entry);
138 return Entries.size() - 1;
139 }
140
141 void modifyAddr(size_t Index, uint64_t Addr) {
142 Entries[Index].d_un.d_ptr = Addr;
143 }
144
145 size_t addValue(uint64_t Tag, uint64_t Value) {
146 Elf_Dyn Entry;
147 Entry.d_tag = Tag;
148 Entry.d_un.d_val = Value;
149 Entries.push_back(Entry);
150 return Entries.size() - 1;
151 }
152
153 void modifyValue(size_t Index, uint64_t Value) {
154 Entries[Index].d_un.d_val = Value;
155 }
156
157 size_t getSize() const {
158 // Add DT_NULL entry at the end.
159 return (Entries.size() + 1) * sizeof(Elf_Dyn);
160 }
161
162 void write(uint8_t *Buf) const {
163 memcpy(Buf, Entries.data(), sizeof(Elf_Dyn) * Entries.size());
164 // Add DT_NULL entry at the end.
165 memset(Buf + sizeof(Elf_Dyn) * Entries.size(), 0, sizeof(Elf_Dyn));
166 }
167
168private:
170};
171
172template <class ELFT> class ELFStubBuilder {
173public:
174 using Elf_Ehdr = typename ELFT::Ehdr;
175 using Elf_Shdr = typename ELFT::Shdr;
176 using Elf_Phdr = typename ELFT::Phdr;
177 using Elf_Sym = typename ELFT::Sym;
178 using Elf_Addr = typename ELFT::Addr;
179 using Elf_Dyn = typename ELFT::Dyn;
180
181 ELFStubBuilder(const ELFStubBuilder &) = delete;
182 ELFStubBuilder(ELFStubBuilder &&) = default;
183
184 explicit ELFStubBuilder(const IFSStub &Stub) {
185 DynSym.Name = ".dynsym";
186 DynSym.Align = sizeof(Elf_Addr);
187 DynStr.Name = ".dynstr";
188 DynStr.Align = 1;
189 DynTab.Name = ".dynamic";
190 DynTab.Align = sizeof(Elf_Addr);
191 ShStrTab.Name = ".shstrtab";
192 ShStrTab.Align = 1;
193
194 // Populate string tables.
195 for (const IFSSymbol &Sym : Stub.Symbols)
196 DynStr.Content.add(Sym.Name);
197 for (const std::string &Lib : Stub.NeededLibs)
198 DynStr.Content.add(Lib);
199 if (Stub.SoName)
200 DynStr.Content.add(*Stub.SoName);
201
202 std::vector<OutputSection<ELFT> *> Sections = {&DynSym, &DynStr, &DynTab,
203 &ShStrTab};
204 const OutputSection<ELFT> *LastSection = Sections.back();
205 // Now set the Index and put sections names into ".shstrtab".
206 uint64_t Index = 1;
207 for (OutputSection<ELFT> *Sec : Sections) {
208 Sec->Index = Index++;
209 ShStrTab.Content.add(Sec->Name);
210 }
211 ShStrTab.Content.finalize();
212 ShStrTab.Size = ShStrTab.Content.getSize();
213 DynStr.Content.finalize();
214 DynStr.Size = DynStr.Content.getSize();
215
216 // Populate dynamic symbol table.
217 bool HasUnique = false;
218 for (const IFSSymbol &Sym : Stub.Symbols) {
219 assert(!(Sym.Weak && Sym.Unique) &&
220 "IFS symbol cannot be both Weak and Unique");
221 uint8_t Bind = STB_GLOBAL;
222 if (Sym.Weak) {
223 Bind = STB_WEAK;
224 } else if (Sym.Unique) {
225 Bind = STB_GNU_UNIQUE;
226 HasUnique = true;
227 }
228 // For non-undefined symbols, value of the shndx is not relevant at link
229 // time as long as it is not SHN_UNDEF. Set shndx to 1, which
230 // points to ".dynsym".
231 uint16_t Shndx = Sym.Undefined ? SHN_UNDEF : 1;
232 uint64_t Size = Sym.Size.value_or(0);
233 DynSym.Content.add(DynStr.Content.getOffset(Sym.Name), Size, Bind,
234 convertIFSSymbolTypeToELF(Sym.Type), 0, Shndx);
235 }
236 DynSym.Size = DynSym.Content.getSize();
237
238 // Populate dynamic table.
239 size_t DynSymIndex = DynTab.Content.addAddr(DT_SYMTAB, 0);
240 size_t DynStrIndex = DynTab.Content.addAddr(DT_STRTAB, 0);
241 DynTab.Content.addValue(DT_STRSZ, DynStr.Size);
242 for (const std::string &Lib : Stub.NeededLibs)
243 DynTab.Content.addValue(DT_NEEDED, DynStr.Content.getOffset(Lib));
244 if (Stub.SoName)
245 DynTab.Content.addValue(DT_SONAME,
246 DynStr.Content.getOffset(*Stub.SoName));
247 DynTab.Size = DynTab.Content.getSize();
248 // Calculate sections' addresses and offsets.
249 uint64_t CurrentOffset = sizeof(Elf_Ehdr);
250 for (OutputSection<ELFT> *Sec : Sections) {
251 Sec->Offset = alignTo(CurrentOffset, Sec->Align);
252 Sec->Addr = Sec->Offset;
253 CurrentOffset = Sec->Offset + Sec->Size;
254 }
255 // Fill Addr back to dynamic table.
256 DynTab.Content.modifyAddr(DynSymIndex, DynSym.Addr);
257 DynTab.Content.modifyAddr(DynStrIndex, DynStr.Addr);
258 // Write section headers of string tables.
259 fillSymTabShdr(DynSym, SHT_DYNSYM);
260 fillStrTabShdr(DynStr, SHF_ALLOC);
261 fillDynTabShdr(DynTab);
262 fillStrTabShdr(ShStrTab);
263
264 // Finish initializing the ELF header.
265 uint8_t OSABI = HasUnique ? ELFOSABI_GNU : ELFOSABI_NONE;
266 initELFHeader<ELFT>(ElfHeader, static_cast<uint16_t>(*Stub.Target.Arch),
267 OSABI);
268 ElfHeader.e_shstrndx = ShStrTab.Index;
269 ElfHeader.e_shnum = LastSection->Index + 1;
270 ElfHeader.e_shoff =
271 alignTo(LastSection->Offset + LastSection->Size, sizeof(Elf_Addr));
272 }
273
274 size_t getSize() const {
275 return ElfHeader.e_shoff + ElfHeader.e_shnum * sizeof(Elf_Shdr);
276 }
277
278 void write(uint8_t *Data) const {
279 write(Data, ElfHeader);
280 DynSym.Content.write(Data + DynSym.Shdr.sh_offset);
281 DynStr.Content.write(Data + DynStr.Shdr.sh_offset);
282 DynTab.Content.write(Data + DynTab.Shdr.sh_offset);
283 ShStrTab.Content.write(Data + ShStrTab.Shdr.sh_offset);
284 writeShdr(Data, DynSym);
285 writeShdr(Data, DynStr);
286 writeShdr(Data, DynTab);
287 writeShdr(Data, ShStrTab);
288 }
289
290private:
291 Elf_Ehdr ElfHeader;
292 ContentSection<ELFStringTableBuilder, ELFT> DynStr;
293 ContentSection<ELFStringTableBuilder, ELFT> ShStrTab;
294 ContentSection<ELFSymbolTableBuilder<ELFT>, ELFT> DynSym;
295 ContentSection<ELFDynamicTableBuilder<ELFT>, ELFT> DynTab;
296
297 template <class T> static void write(uint8_t *Data, const T &Value) {
298 *reinterpret_cast<T *>(Data) = Value;
299 }
300
301 void fillStrTabShdr(ContentSection<ELFStringTableBuilder, ELFT> &StrTab,
302 uint32_t ShFlags = 0) const {
303 StrTab.Shdr.sh_type = SHT_STRTAB;
304 StrTab.Shdr.sh_flags = ShFlags;
305 StrTab.Shdr.sh_addr = StrTab.Addr;
306 StrTab.Shdr.sh_offset = StrTab.Offset;
307 StrTab.Shdr.sh_info = 0;
308 StrTab.Shdr.sh_size = StrTab.Size;
309 StrTab.Shdr.sh_name = ShStrTab.Content.getOffset(StrTab.Name);
310 StrTab.Shdr.sh_addralign = StrTab.Align;
311 StrTab.Shdr.sh_entsize = 0;
312 StrTab.Shdr.sh_link = 0;
313 }
314 void fillSymTabShdr(ContentSection<ELFSymbolTableBuilder<ELFT>, ELFT> &SymTab,
315 uint32_t ShType) const {
316 SymTab.Shdr.sh_type = ShType;
317 SymTab.Shdr.sh_flags = SHF_ALLOC;
318 SymTab.Shdr.sh_addr = SymTab.Addr;
319 SymTab.Shdr.sh_offset = SymTab.Offset;
320 // Only non-local symbols are included in the tbe file, so .dynsym only
321 // contains 1 local symbol (the undefined symbol at index 0). The sh_info
322 // should always be 1.
323 SymTab.Shdr.sh_info = 1;
324 SymTab.Shdr.sh_size = SymTab.Size;
325 SymTab.Shdr.sh_name = this->ShStrTab.Content.getOffset(SymTab.Name);
326 SymTab.Shdr.sh_addralign = SymTab.Align;
327 SymTab.Shdr.sh_entsize = sizeof(Elf_Sym);
328 SymTab.Shdr.sh_link = this->DynStr.Index;
329 }
330 void fillDynTabShdr(
331 ContentSection<ELFDynamicTableBuilder<ELFT>, ELFT> &DynTab) const {
332 DynTab.Shdr.sh_type = SHT_DYNAMIC;
333 DynTab.Shdr.sh_flags = SHF_ALLOC;
334 DynTab.Shdr.sh_addr = DynTab.Addr;
335 DynTab.Shdr.sh_offset = DynTab.Offset;
336 DynTab.Shdr.sh_info = 0;
337 DynTab.Shdr.sh_size = DynTab.Size;
338 DynTab.Shdr.sh_name = this->ShStrTab.Content.getOffset(DynTab.Name);
339 DynTab.Shdr.sh_addralign = DynTab.Align;
340 DynTab.Shdr.sh_entsize = sizeof(Elf_Dyn);
341 DynTab.Shdr.sh_link = this->DynStr.Index;
342 }
343 uint64_t shdrOffset(const OutputSection<ELFT> &Sec) const {
344 return ElfHeader.e_shoff + Sec.Index * sizeof(Elf_Shdr);
345 }
346
347 void writeShdr(uint8_t *Data, const OutputSection<ELFT> &Sec) const {
348 write(Data + shdrOffset(Sec), Sec.Shdr);
349 }
350};
351
352/// This function takes an error, and appends a string of text to the end of
353/// that error. Since "appending" to an Error isn't supported behavior of an
354/// Error, this function technically creates a new error with the combined
355/// message and consumes the old error.
356///
357/// @param Err Source error.
358/// @param After Text to append at the end of Err's error message.
359Error appendToError(Error Err, StringRef After) {
360 std::string Message;
361 raw_string_ostream Stream(Message);
362 Stream << Err;
363 Stream << " " << After;
364 consumeError(std::move(Err));
365 return createError(Stream.str());
366}
367
368template <class ELFT> class DynSym {
369 using Elf_Shdr_Range = typename ELFT::ShdrRange;
370 using Elf_Shdr = typename ELFT::Shdr;
371
372public:
373 static Expected<DynSym> create(const ELFFile<ELFT> &ElfFile,
374 const DynamicEntries &DynEnt) {
375 Expected<Elf_Shdr_Range> Shdrs = ElfFile.sections();
376 if (!Shdrs)
377 return Shdrs.takeError();
378 return DynSym(ElfFile, DynEnt, *Shdrs);
379 }
380
381 Expected<const uint8_t *> getDynSym() {
382 if (DynSymHdr)
383 return ElfFile.base() + DynSymHdr->sh_offset;
384 return getDynamicData(DynEnt.DynSymAddr, "dynamic symbol table");
385 }
386
387 Expected<StringRef> getDynStr() {
388 if (DynSymHdr)
389 return ElfFile.getStringTableForSymtab(*DynSymHdr, Shdrs);
390 Expected<const uint8_t *> DataOrErr = getDynamicData(
391 DynEnt.StrTabAddr, "dynamic string table", DynEnt.StrSize);
392 if (!DataOrErr)
393 return DataOrErr.takeError();
394 return StringRef(reinterpret_cast<const char *>(*DataOrErr),
395 DynEnt.StrSize);
396 }
397
398private:
399 DynSym(const ELFFile<ELFT> &ElfFile, const DynamicEntries &DynEnt,
400 Elf_Shdr_Range Shdrs)
401 : ElfFile(ElfFile), DynEnt(DynEnt), Shdrs(Shdrs),
402 DynSymHdr(findDynSymHdr()) {}
403
404 const Elf_Shdr *findDynSymHdr() {
405 for (const Elf_Shdr &Sec : Shdrs)
406 if (Sec.sh_type == SHT_DYNSYM) {
407 // If multiple .dynsym are present, use the first one.
408 // This behavior aligns with llvm::object::ELFFile::getDynSymtabSize()
409 return &Sec;
410 }
411 return nullptr;
412 }
413
414 Expected<const uint8_t *> getDynamicData(uint64_t EntAddr, StringRef Name,
415 uint64_t Size = 0) {
416 Expected<const uint8_t *> SecPtr = ElfFile.toMappedAddr(EntAddr);
417 if (!SecPtr)
418 return appendToError(
419 SecPtr.takeError(),
420 ("when locating " + Name + " section contents").str());
421 Expected<const uint8_t *> SecEndPtr = ElfFile.toMappedAddr(EntAddr + Size);
422 if (!SecEndPtr)
423 return appendToError(
424 SecEndPtr.takeError(),
425 ("when locating " + Name + " section contents").str());
426 return *SecPtr;
427 }
428
429 const ELFFile<ELFT> &ElfFile;
430 const DynamicEntries &DynEnt;
431 Elf_Shdr_Range Shdrs;
432 const Elf_Shdr *DynSymHdr;
433};
434} // end anonymous namespace
435
436/// This function behaves similarly to StringRef::substr(), but attempts to
437/// terminate the returned StringRef at the first null terminator. If no null
438/// terminator is found, an error is returned.
439///
440/// @param Str Source string to create a substring from.
441/// @param Offset The start index of the desired substring.
443 size_t StrEnd = Str.find('\0', Offset);
444 if (StrEnd == StringLiteral::npos) {
445 return createError(
446 "String overran bounds of string table (no null terminator)");
447 }
448
449 size_t StrLen = StrEnd - Offset;
450 return Str.substr(Offset, StrLen);
451}
452
453/// This function populates a DynamicEntries struct using an ELFT::DynRange.
454/// After populating the struct, the members are validated with
455/// some basic correctness checks.
456///
457/// @param Dyn Target DynamicEntries struct to populate.
458/// @param DynTable Source dynamic table.
459template <class ELFT>
461 typename ELFT::DynRange DynTable) {
462 if (DynTable.empty())
463 return createError("No .dynamic section found");
464
465 // Search .dynamic for relevant entries.
466 bool FoundDynStr = false;
467 bool FoundDynStrSz = false;
468 bool FoundDynSym = false;
469 for (auto &Entry : DynTable) {
470 switch (Entry.d_tag) {
471 case DT_SONAME:
472 Dyn.SONameOffset = Entry.d_un.d_val;
473 break;
474 case DT_STRTAB:
475 Dyn.StrTabAddr = Entry.d_un.d_ptr;
476 FoundDynStr = true;
477 break;
478 case DT_STRSZ:
479 Dyn.StrSize = Entry.d_un.d_val;
480 FoundDynStrSz = true;
481 break;
482 case DT_NEEDED:
483 Dyn.NeededLibNames.push_back(Entry.d_un.d_val);
484 break;
485 case DT_SYMTAB:
486 Dyn.DynSymAddr = Entry.d_un.d_ptr;
487 FoundDynSym = true;
488 break;
489 case DT_HASH:
490 Dyn.ElfHash = Entry.d_un.d_ptr;
491 break;
492 case DT_GNU_HASH:
493 Dyn.GnuHash = Entry.d_un.d_ptr;
494 }
495 }
496
497 if (!FoundDynStr) {
498 return createError(
499 "Couldn't locate dynamic string table (no DT_STRTAB entry)");
500 }
501 if (!FoundDynStrSz) {
502 return createError(
503 "Couldn't determine dynamic string table size (no DT_STRSZ entry)");
504 }
505 if (!FoundDynSym) {
506 return createError(
507 "Couldn't locate dynamic symbol table (no DT_SYMTAB entry)");
508 }
509 if (Dyn.SONameOffset && *Dyn.SONameOffset >= Dyn.StrSize) {
511 "DT_SONAME string offset (0x%016" PRIx64
512 ") outside of dynamic string table",
513 *Dyn.SONameOffset);
514 }
515 for (uint64_t Offset : Dyn.NeededLibNames) {
516 if (Offset >= Dyn.StrSize) {
518 "DT_NEEDED string offset (0x%016" PRIx64
519 ") outside of dynamic string table",
520 Offset);
521 }
522 }
523
524 return Error::success();
525}
526
527/// This function creates an IFSSymbol and populates all members using
528/// information from a binary ELFT::Sym.
529///
530/// @param SymName The desired name of the IFSSymbol.
531/// @param RawSym ELFT::Sym to extract symbol information from.
532template <class ELFT>
534 const typename ELFT::Sym &RawSym) {
535 IFSSymbol TargetSym{std::string(SymName)};
536 uint8_t Binding = RawSym.getBinding();
537 switch (Binding) {
538 case STB_GLOBAL:
539 TargetSym.Weak = false;
540 break;
541 case STB_GNU_UNIQUE:
542 TargetSym.Weak = false;
543 TargetSym.Unique = true;
544 break;
545 case STB_WEAK:
546 TargetSym.Weak = true;
547 break;
548 default:
550 "symbol '" + SymName +
551 "' has unsupported binding (" +
552 Twine(static_cast<unsigned>(Binding)) + ")");
553 }
554
555 TargetSym.Undefined = RawSym.isUndefined();
556 TargetSym.Type = convertELFSymbolTypeToIFS(RawSym.st_info);
557
558 if (TargetSym.Type == IFSSymbolType::Func) {
559 TargetSym.Size = 0;
560 } else {
561 TargetSym.Size = RawSym.st_size;
562 }
563 return TargetSym;
564}
565
566/// This function populates an IFSStub with symbols using information read
567/// from an ELF binary.
568///
569/// @param TargetStub IFSStub to add symbols to.
570/// @param DynSym Range of dynamic symbols to add to TargetStub.
571/// @param DynStr StringRef to the dynamic string table.
572template <class ELFT>
573static Error populateSymbols(IFSStub &TargetStub,
574 const typename ELFT::SymRange DynSym,
575 StringRef DynStr) {
576 // Skips the first symbol since it's the NULL symbol.
577 for (auto RawSym : DynSym.drop_front(1)) {
578 // If a symbol has local binding, ignore it.
579 if (RawSym.getBinding() == STB_LOCAL)
580 continue;
581 // If a symbol doesn't have default or protected visibility, ignore it.
582 uint8_t Visibility = RawSym.getVisibility();
583 if (!(Visibility == STV_DEFAULT || Visibility == STV_PROTECTED))
584 continue;
585 // Create an IFSSymbol and populate it with information from the symbol
586 // table entry.
587 Expected<StringRef> SymName = terminatedSubstr(DynStr, RawSym.st_name);
588 if (!SymName)
589 return SymName.takeError();
590 Expected<IFSSymbol> Sym = createELFSym<ELFT>(*SymName, RawSym);
591 if (!Sym)
592 return Sym.takeError();
593 TargetStub.Symbols.push_back(std::move(*Sym));
594 // TODO: Populate symbol warning.
595 }
596 return Error::success();
597}
598
599/// Returns a new IFSStub with all members populated from an ELFObjectFile.
600/// @param ElfObj Source ELFObjectFile.
601template <class ELFT>
604 using Elf_Dyn_Range = typename ELFT::DynRange;
605 using Elf_Sym_Range = typename ELFT::SymRange;
606 using Elf_Sym = typename ELFT::Sym;
607 std::unique_ptr<IFSStub> DestStub = std::make_unique<IFSStub>();
608 const ELFFile<ELFT> &ElfFile = ElfObj.getELFFile();
609 // Fetch .dynamic table.
610 Expected<Elf_Dyn_Range> DynTable = ElfFile.dynamicEntries();
611 if (!DynTable) {
612 return DynTable.takeError();
613 }
614
615 // Collect relevant .dynamic entries.
616 DynamicEntries DynEnt;
617 if (Error Err = populateDynamic<ELFT>(DynEnt, *DynTable))
618 return std::move(Err);
619 Expected<DynSym<ELFT>> EDynSym = DynSym<ELFT>::create(ElfFile, DynEnt);
620 if (!EDynSym)
621 return EDynSym.takeError();
622
623 Expected<StringRef> EDynStr = EDynSym->getDynStr();
624 if (!EDynStr)
625 return EDynStr.takeError();
626
627 StringRef DynStr = *EDynStr;
628
629 // Populate Arch from ELF header.
630 DestStub->Target.Arch = static_cast<IFSArch>(ElfFile.getHeader().e_machine);
631 DestStub->Target.BitWidth =
632 convertELFBitWidthToIFS(ElfFile.getHeader().e_ident[EI_CLASS]);
633 DestStub->Target.Endianness =
634 convertELFEndiannessToIFS(ElfFile.getHeader().e_ident[EI_DATA]);
635 DestStub->Target.ObjectFormat = "ELF";
636
637 // Populate SoName from .dynamic entries and dynamic string table.
638 if (DynEnt.SONameOffset) {
639 Expected<StringRef> NameOrErr =
640 terminatedSubstr(DynStr, *DynEnt.SONameOffset);
641 if (!NameOrErr) {
642 return appendToError(NameOrErr.takeError(), "when reading DT_SONAME");
643 }
644 DestStub->SoName = std::string(*NameOrErr);
645 }
646
647 // Populate NeededLibs from .dynamic entries and dynamic string table.
648 for (uint64_t NeededStrOffset : DynEnt.NeededLibNames) {
649 Expected<StringRef> LibNameOrErr =
650 terminatedSubstr(DynStr, NeededStrOffset);
651 if (!LibNameOrErr) {
652 return appendToError(LibNameOrErr.takeError(), "when reading DT_NEEDED");
653 }
654 DestStub->NeededLibs.push_back(std::string(*LibNameOrErr));
655 }
656
657 // Populate Symbols from .dynsym table and dynamic string table.
658 Expected<uint64_t> SymCount = ElfFile.getDynSymtabSize();
659 if (!SymCount)
660 return SymCount.takeError();
661 if (*SymCount > 0) {
662 // Get pointer to in-memory location of .dynsym section.
663 Expected<const uint8_t *> DynSymPtr = EDynSym->getDynSym();
664 if (!DynSymPtr)
665 return appendToError(DynSymPtr.takeError(),
666 "when locating .dynsym section contents");
667 Elf_Sym_Range DynSyms = ArrayRef<Elf_Sym>(
668 reinterpret_cast<const Elf_Sym *>(*DynSymPtr), *SymCount);
669 Error SymReadError = populateSymbols<ELFT>(*DestStub, DynSyms, DynStr);
670 if (SymReadError)
671 return appendToError(std::move(SymReadError),
672 "when reading dynamic symbols");
673 }
674
675 return std::move(DestStub);
676}
677
678/// This function opens a file for writing and then writes a binary ELF stub to
679/// the file.
680///
681/// @param FilePath File path for writing the ELF binary.
682/// @param Stub Source InterFace Stub to generate a binary ELF stub from.
683template <class ELFT>
684static Error writeELFBinaryToFile(StringRef FilePath, const IFSStub &Stub,
685 bool WriteIfChanged) {
686 ELFStubBuilder<ELFT> Builder{Stub};
687 // Write Stub to memory first.
688 std::vector<uint8_t> Buf(Builder.getSize());
689 Builder.write(Buf.data());
690
691 if (WriteIfChanged) {
692 if (ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrError =
693 MemoryBuffer::getFile(FilePath)) {
694 // Compare Stub output with existing Stub file.
695 // If Stub file unchanged, abort updating.
696 if ((*BufOrError)->getBufferSize() == Builder.getSize() &&
697 !memcmp((*BufOrError)->getBufferStart(), Buf.data(),
698 Builder.getSize()))
699 return Error::success();
700 }
701 }
702
704 FileOutputBuffer::create(FilePath, Builder.getSize());
705 if (!BufOrError)
707 toString(BufOrError.takeError()) +
708 " when trying to open `" + FilePath +
709 "` for writing");
710
711 // Write binary to file.
712 std::unique_ptr<FileOutputBuffer> FileBuf = std::move(*BufOrError);
713 memcpy(FileBuf->getBufferStart(), Buf.data(), Buf.size());
714
715 return FileBuf->commit();
716}
717
720 if (!BinOrErr) {
721 return BinOrErr.takeError();
722 }
723
724 Binary *Bin = BinOrErr->get();
725 if (auto Obj = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
726 return buildStub(*Obj);
727 } else if (auto Obj = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
728 return buildStub(*Obj);
729 } else if (auto Obj = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
730 return buildStub(*Obj);
731 } else if (auto Obj = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
732 return buildStub(*Obj);
733 }
734 return createStringError(errc::not_supported, "unsupported binary format");
735}
736
737// This function wraps the ELFT writeELFBinaryToFile() so writeBinaryStub()
738// can be called without having to use ELFType templates directly.
740 bool WriteIfChanged) {
741 assert(Stub.Target.Arch);
742 assert(Stub.Target.BitWidth);
744 for (const IFSSymbol &Sym : Stub.Symbols) {
745 if (Sym.Weak && Sym.Unique)
747 "IFS symbol '" + Sym.Name +
748 "' cannot be both Weak and Unique");
749 }
752 return writeELFBinaryToFile<ELF32LE>(FilePath, Stub, WriteIfChanged);
753 } else {
754 return writeELFBinaryToFile<ELF32BE>(FilePath, Stub, WriteIfChanged);
755 }
756 } else {
758 return writeELFBinaryToFile<ELF64LE>(FilePath, Stub, WriteIfChanged);
759 } else {
760 return writeELFBinaryToFile<ELF64BE>(FilePath, Stub, WriteIfChanged);
761 }
762 }
763 llvm_unreachable("invalid binary output target");
764}
765
766} // end namespace ifs
767} // end namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
This supports reading and writing of elf dynamic shared objects.
This file defines an internal representation of an InterFace Stub.
static cl::opt< bool > WriteIfChanged("write-if-changed", cl::desc("Only write output if it changed"))
#define T
Function const char TargetMachine * Machine
static unsigned getSize(unsigned Kind)
Represents either an error or a value T.
Definition ErrorOr.h:56
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
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
static LLVM_ABI Expected< std::unique_ptr< FileOutputBuffer > > create(StringRef FilePath, size_t Size, unsigned Flags=0)
Factory method to create an OutputBuffer object which manages a read/write buffer of the specified si...
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static constexpr size_t npos
Definition StringRef.h:58
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
const Elf_Ehdr & getHeader() const
Definition ELF.h:346
Expected< uint64_t > getDynSymtabSize() const
This function determines the number of dynamic symbols.
Definition ELF.h:892
Expected< Elf_Dyn_Range > dynamicEntries() const
Definition ELF.cpp:657
const ELFFile< ELFT > & getELFFile() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Entry
Definition COFF.h:862
@ EV_CURRENT
Definition ELF.h:130
@ EI_DATA
Definition ELF.h:56
@ EI_MAG3
Definition ELF.h:54
@ EI_MAG1
Definition ELF.h:52
@ EI_VERSION
Definition ELF.h:57
@ EI_MAG2
Definition ELF.h:53
@ EI_MAG0
Definition ELF.h:51
@ EI_CLASS
Definition ELF.h:55
@ EI_OSABI
Definition ELF.h:58
static const char ElfMagic[]
Definition ELF.h:47
@ ELFOSABI_GNU
Definition ELF.h:157
@ ELFOSABI_NONE
Definition ELF.h:154
@ ELFDATA2MSB
Definition ELF.h:149
@ ELFDATA2LSB
Definition ELF.h:148
@ STV_PROTECTED
Definition ELF.h:1296
@ STV_DEFAULT
Definition ELF.h:1293
@ SHF_ALLOC
Definition ELF.h:1098
@ ELFCLASS64
Definition ELF.h:142
@ ELFCLASS32
Definition ELF.h:141
@ ET_DYN
Definition ELF.h:121
@ SHN_UNDEF
Definition ELF.h:981
@ SHT_STRTAB
Definition ELF.h:998
@ SHT_DYNAMIC
Definition ELF.h:1001
@ SHT_DYNSYM
Definition ELF.h:1006
@ STB_GLOBAL
Definition ELF.h:1261
@ STB_LOCAL
Definition ELF.h:1260
@ STB_GNU_UNIQUE
Definition ELF.h:1263
@ STB_WEAK
Definition ELF.h:1262
static Error writeELFBinaryToFile(StringRef FilePath, const IFSStub &Stub, bool WriteIfChanged)
This function opens a file for writing and then writes a binary ELF stub to the file.
uint16_t IFSArch
Definition IFSStub.h:25
LLVM_ABI Expected< std::unique_ptr< IFSStub > > readELFFile(MemoryBufferRef Buf)
Attempt to read a binary ELF file from a MemoryBuffer.
LLVM_ABI Error writeBinaryStub(StringRef FilePath, const IFSStub &Stub, bool WriteIfChanged=false)
Attempt to write a binary ELF stub.
LLVM_ABI uint8_t convertIFSSymbolTypeToELF(IFSSymbolType SymbolType)
This function convert symbol type from IFS enum to ELF format Currently, STT_NOTYPE,...
Definition IFSStub.cpp:83
static Expected< IFSSymbol > createELFSym(StringRef SymName, const typename ELFT::Sym &RawSym)
This function creates an IFSSymbol and populates all members using information from a binary ELFT::Sy...
static void initELFHeader(typename ELFT::Ehdr &ElfHeader, uint16_t Machine, uint8_t OSABI=ELFOSABI_NONE)
This initializes an ELF file header with information specific to a binary dynamic shared object.
static Expected< std::unique_ptr< IFSStub > > buildStub(const ELFObjectFile< ELFT > &ElfObj)
Returns a new IFSStub with all members populated from an ELFObjectFile.
static Error populateSymbols(IFSStub &TargetStub, const typename ELFT::SymRange DynSym, StringRef DynStr)
This function populates an IFSStub with symbols using information read from an ELF binary.
LLVM_ABI IFSBitWidthType convertELFBitWidthToIFS(uint8_t BitWidth)
This function extracts ELF bit width from e_ident[EI_CLASS] of an ELF file Currently,...
Definition IFSStub.cpp:98
LLVM_ABI IFSEndiannessType convertELFEndiannessToIFS(uint8_t Endianness)
This function extracts ELF endianness from e_ident[EI_DATA] of an ELF file Currently,...
Definition IFSStub.cpp:109
static Error populateDynamic(DynamicEntries &Dyn, typename ELFT::DynRange DynTable)
This function populates a DynamicEntries struct using an ELFT::DynRange.
LLVM_ABI IFSSymbolType convertELFSymbolTypeToIFS(uint8_t SymbolType)
This function extracts symbol type from a symbol's st_info member and maps it to an IFSSymbolType enu...
Definition IFSStub.cpp:120
static Expected< StringRef > terminatedSubstr(StringRef Str, size_t Offset)
This function behaves similarly to StringRef::substr(), but attempts to terminate the returned String...
LLVM_ABI Expected< std::unique_ptr< Binary > > createBinary(MemoryBufferRef Source, LLVMContext *Context=nullptr, bool InitContent=true)
Create a Binary from Source, autodetecting the file type.
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
@ not_supported
Definition Errc.h:69
@ invalid_argument
Definition Errc.h:56
static Error createError(const Twine &Err)
Definition APFloat.cpp:700
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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)
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
LLVM_ABI Error write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
Definition DWP.cpp:746
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
std::optional< uint64_t > ElfHash
std::vector< uint64_t > NeededLibNames
std::optional< uint64_t > GnuHash
std::optional< uint64_t > SONameOffset
std::vector< IFSSymbol > Symbols
Definition IFSStub.h:100
IFSTarget Target
Definition IFSStub.h:98
IFSSymbolType Type
Definition IFSStub.h:58
std::string Name
Definition IFSStub.h:56
std::optional< uint64_t > Size
Definition IFSStub.h:57
std::optional< IFSEndiannessType > Endianness
Definition IFSStub.h:74
std::optional< IFSBitWidthType > BitWidth
Definition IFSStub.h:75
std::optional< IFSArch > Arch
Definition IFSStub.h:72