1 //===- ELFObjHandler.cpp --------------------------------------------------===//
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
7 //===-----------------------------------------------------------------------===/
9 #include "llvm/InterfaceStub/ELFObjHandler.h"
10 #include "llvm/InterfaceStub/IFSStub.h"
11 #include "llvm/MC/StringTableBuilder.h"
12 #include "llvm/Object/Binary.h"
13 #include "llvm/Object/ELFObjectFile.h"
14 #include "llvm/Object/ELFTypes.h"
15 #include "llvm/Support/Errc.h"
16 #include "llvm/Support/Error.h"
17 #include "llvm/Support/FileOutputBuffer.h"
18 #include "llvm/Support/MathExtras.h"
19 #include "llvm/Support/MemoryBuffer.h"
20 #include "llvm/Support/Process.h"
22 using llvm::MemoryBufferRef
;
23 using llvm::object::ELFObjectFile
;
26 using namespace llvm::object
;
27 using namespace llvm::ELF
;
32 // Simple struct to hold relevant .dynamic entries.
33 struct DynamicEntries
{
34 uint64_t StrTabAddr
= 0;
36 Optional
<uint64_t> SONameOffset
;
37 std::vector
<uint64_t> NeededLibNames
;
39 uint64_t DynSymAddr
= 0;
41 Optional
<uint64_t> ElfHash
;
42 Optional
<uint64_t> GnuHash
;
45 /// This initializes an ELF file header with information specific to a binary
46 /// dynamic shared object.
47 /// Offsets, indexes, links, etc. for section and program headers are just
48 /// zero-initialized as they will be updated elsewhere.
50 /// @param ElfHeader Target ELFT::Ehdr to populate.
51 /// @param Machine Target architecture (e_machine from ELF specifications).
53 static void initELFHeader(typename
ELFT::Ehdr
&ElfHeader
, uint16_t Machine
) {
54 memset(&ElfHeader
, 0, sizeof(ElfHeader
));
55 // ELF identification.
56 ElfHeader
.e_ident
[EI_MAG0
] = ElfMagic
[EI_MAG0
];
57 ElfHeader
.e_ident
[EI_MAG1
] = ElfMagic
[EI_MAG1
];
58 ElfHeader
.e_ident
[EI_MAG2
] = ElfMagic
[EI_MAG2
];
59 ElfHeader
.e_ident
[EI_MAG3
] = ElfMagic
[EI_MAG3
];
60 ElfHeader
.e_ident
[EI_CLASS
] = ELFT::Is64Bits
? ELFCLASS64
: ELFCLASS32
;
61 bool IsLittleEndian
= ELFT::TargetEndianness
== support::little
;
62 ElfHeader
.e_ident
[EI_DATA
] = IsLittleEndian
? ELFDATA2LSB
: ELFDATA2MSB
;
63 ElfHeader
.e_ident
[EI_VERSION
] = EV_CURRENT
;
64 ElfHeader
.e_ident
[EI_OSABI
] = ELFOSABI_NONE
;
66 // Remainder of ELF header.
67 ElfHeader
.e_type
= ET_DYN
;
68 ElfHeader
.e_machine
= Machine
;
69 ElfHeader
.e_version
= EV_CURRENT
;
70 ElfHeader
.e_ehsize
= sizeof(typename
ELFT::Ehdr
);
71 ElfHeader
.e_phentsize
= sizeof(typename
ELFT::Phdr
);
72 ElfHeader
.e_shentsize
= sizeof(typename
ELFT::Shdr
);
76 template <class ELFT
> struct OutputSection
{
77 using Elf_Shdr
= typename
ELFT::Shdr
;
88 template <class T
, class ELFT
>
89 struct ContentSection
: public OutputSection
<ELFT
> {
91 ContentSection() { this->NoBits
= false; }
94 // This class just wraps StringTableBuilder for the purpose of adding a
95 // default constructor.
96 class ELFStringTableBuilder
: public StringTableBuilder
{
98 ELFStringTableBuilder() : StringTableBuilder(StringTableBuilder::ELF
) {}
101 template <class ELFT
> class ELFSymbolTableBuilder
{
103 using Elf_Sym
= typename
ELFT::Sym
;
105 ELFSymbolTableBuilder() { Symbols
.push_back({}); }
107 void add(size_t StNameOffset
, uint64_t StSize
, uint8_t StBind
, uint8_t StType
,
108 uint8_t StOther
, uint16_t StShndx
) {
110 S
.st_name
= StNameOffset
;
112 S
.st_info
= (StBind
<< 4) | (StType
& 0xf);
113 S
.st_other
= StOther
;
114 S
.st_shndx
= StShndx
;
115 Symbols
.push_back(S
);
118 size_t getSize() const { return Symbols
.size() * sizeof(Elf_Sym
); }
120 void write(uint8_t *Buf
) const {
121 memcpy(Buf
, Symbols
.data(), sizeof(Elf_Sym
) * Symbols
.size());
125 llvm::SmallVector
<Elf_Sym
, 8> Symbols
;
128 template <class ELFT
> class ELFDynamicTableBuilder
{
130 using Elf_Dyn
= typename
ELFT::Dyn
;
132 size_t addAddr(uint64_t Tag
, uint64_t Addr
) {
135 Entry
.d_un
.d_ptr
= Addr
;
136 Entries
.push_back(Entry
);
137 return Entries
.size() - 1;
140 void modifyAddr(size_t Index
, uint64_t Addr
) {
141 Entries
[Index
].d_un
.d_ptr
= Addr
;
144 size_t addValue(uint64_t Tag
, uint64_t Value
) {
147 Entry
.d_un
.d_val
= Value
;
148 Entries
.push_back(Entry
);
149 return Entries
.size() - 1;
152 void modifyValue(size_t Index
, uint64_t Value
) {
153 Entries
[Index
].d_un
.d_val
= Value
;
156 size_t getSize() const {
157 // Add DT_NULL entry at the end.
158 return (Entries
.size() + 1) * sizeof(Elf_Dyn
);
161 void write(uint8_t *Buf
) const {
162 memcpy(Buf
, Entries
.data(), sizeof(Elf_Dyn
) * Entries
.size());
163 // Add DT_NULL entry at the end.
164 memset(Buf
+ sizeof(Elf_Dyn
) * Entries
.size(), 0, sizeof(Elf_Dyn
));
168 llvm::SmallVector
<Elf_Dyn
, 8> Entries
;
171 template <class ELFT
> class ELFStubBuilder
{
173 using Elf_Ehdr
= typename
ELFT::Ehdr
;
174 using Elf_Shdr
= typename
ELFT::Shdr
;
175 using Elf_Phdr
= typename
ELFT::Phdr
;
176 using Elf_Sym
= typename
ELFT::Sym
;
177 using Elf_Addr
= typename
ELFT::Addr
;
178 using Elf_Dyn
= typename
ELFT::Dyn
;
180 ELFStubBuilder(const ELFStubBuilder
&) = delete;
181 ELFStubBuilder(ELFStubBuilder
&&) = default;
183 explicit ELFStubBuilder(const IFSStub
&Stub
) {
184 DynSym
.Name
= ".dynsym";
185 DynSym
.Align
= sizeof(Elf_Addr
);
186 DynStr
.Name
= ".dynstr";
188 DynTab
.Name
= ".dynamic";
189 DynTab
.Align
= sizeof(Elf_Addr
);
190 ShStrTab
.Name
= ".shstrtab";
193 // Populate string tables.
194 for (const IFSSymbol
&Sym
: Stub
.Symbols
)
195 DynStr
.Content
.add(Sym
.Name
);
196 for (const std::string
&Lib
: Stub
.NeededLibs
)
197 DynStr
.Content
.add(Lib
);
199 DynStr
.Content
.add(Stub
.SoName
.getValue());
201 std::vector
<OutputSection
<ELFT
> *> Sections
= {&DynSym
, &DynStr
, &DynTab
,
203 const OutputSection
<ELFT
> *LastSection
= Sections
.back();
204 // Now set the Index and put sections names into ".shstrtab".
206 for (OutputSection
<ELFT
> *Sec
: Sections
) {
207 Sec
->Index
= Index
++;
208 ShStrTab
.Content
.add(Sec
->Name
);
210 ShStrTab
.Content
.finalize();
211 ShStrTab
.Size
= ShStrTab
.Content
.getSize();
212 DynStr
.Content
.finalize();
213 DynStr
.Size
= DynStr
.Content
.getSize();
215 // Populate dynamic symbol table.
216 for (const IFSSymbol
&Sym
: Stub
.Symbols
) {
217 uint8_t Bind
= Sym
.Weak
? STB_WEAK
: STB_GLOBAL
;
218 // For non-undefined symbols, value of the shndx is not relevant at link
219 // time as long as it is not SHN_UNDEF. Set shndx to 1, which
220 // points to ".dynsym".
221 uint16_t Shndx
= Sym
.Undefined
? SHN_UNDEF
: 1;
222 DynSym
.Content
.add(DynStr
.Content
.getOffset(Sym
.Name
), Sym
.Size
, Bind
,
223 convertIFSSymbolTypeToELF(Sym
.Type
), 0, Shndx
);
225 DynSym
.Size
= DynSym
.Content
.getSize();
227 // Poplulate dynamic table.
228 size_t DynSymIndex
= DynTab
.Content
.addAddr(DT_SYMTAB
, 0);
229 size_t DynStrIndex
= DynTab
.Content
.addAddr(DT_STRTAB
, 0);
230 for (const std::string
&Lib
: Stub
.NeededLibs
)
231 DynTab
.Content
.addValue(DT_NEEDED
, DynStr
.Content
.getOffset(Lib
));
233 DynTab
.Content
.addValue(DT_SONAME
,
234 DynStr
.Content
.getOffset(Stub
.SoName
.getValue()));
235 DynTab
.Size
= DynTab
.Content
.getSize();
236 // Calculate sections' addresses and offsets.
237 uint64_t CurrentOffset
= sizeof(Elf_Ehdr
);
238 for (OutputSection
<ELFT
> *Sec
: Sections
) {
239 Sec
->Offset
= alignTo(CurrentOffset
, Sec
->Align
);
240 Sec
->Addr
= Sec
->Offset
;
241 CurrentOffset
= Sec
->Offset
+ Sec
->Size
;
243 // Fill Addr back to dynamic table.
244 DynTab
.Content
.modifyAddr(DynSymIndex
, DynSym
.Addr
);
245 DynTab
.Content
.modifyAddr(DynStrIndex
, DynStr
.Addr
);
246 // Write section headers of string tables.
247 fillSymTabShdr(DynSym
, SHT_DYNSYM
);
248 fillStrTabShdr(DynStr
, SHF_ALLOC
);
249 fillDynTabShdr(DynTab
);
250 fillStrTabShdr(ShStrTab
);
252 // Finish initializing the ELF header.
253 initELFHeader
<ELFT
>(ElfHeader
,
254 static_cast<uint16_t>(Stub
.Target
.Arch
.getValue()));
255 ElfHeader
.e_shstrndx
= ShStrTab
.Index
;
256 ElfHeader
.e_shnum
= LastSection
->Index
+ 1;
258 alignTo(LastSection
->Offset
+ LastSection
->Size
, sizeof(Elf_Addr
));
261 size_t getSize() const {
262 return ElfHeader
.e_shoff
+ ElfHeader
.e_shnum
* sizeof(Elf_Shdr
);
265 void write(uint8_t *Data
) const {
266 write(Data
, ElfHeader
);
267 DynSym
.Content
.write(Data
+ DynSym
.Shdr
.sh_offset
);
268 DynStr
.Content
.write(Data
+ DynStr
.Shdr
.sh_offset
);
269 DynTab
.Content
.write(Data
+ DynTab
.Shdr
.sh_offset
);
270 ShStrTab
.Content
.write(Data
+ ShStrTab
.Shdr
.sh_offset
);
271 writeShdr(Data
, DynSym
);
272 writeShdr(Data
, DynStr
);
273 writeShdr(Data
, DynTab
);
274 writeShdr(Data
, ShStrTab
);
279 ContentSection
<ELFStringTableBuilder
, ELFT
> DynStr
;
280 ContentSection
<ELFStringTableBuilder
, ELFT
> ShStrTab
;
281 ContentSection
<ELFSymbolTableBuilder
<ELFT
>, ELFT
> DynSym
;
282 ContentSection
<ELFDynamicTableBuilder
<ELFT
>, ELFT
> DynTab
;
284 template <class T
> static void write(uint8_t *Data
, const T
&Value
) {
285 *reinterpret_cast<T
*>(Data
) = Value
;
288 void fillStrTabShdr(ContentSection
<ELFStringTableBuilder
, ELFT
> &StrTab
,
289 uint32_t ShFlags
= 0) const {
290 StrTab
.Shdr
.sh_type
= SHT_STRTAB
;
291 StrTab
.Shdr
.sh_flags
= ShFlags
;
292 StrTab
.Shdr
.sh_addr
= StrTab
.Addr
;
293 StrTab
.Shdr
.sh_offset
= StrTab
.Offset
;
294 StrTab
.Shdr
.sh_info
= 0;
295 StrTab
.Shdr
.sh_size
= StrTab
.Size
;
296 StrTab
.Shdr
.sh_name
= ShStrTab
.Content
.getOffset(StrTab
.Name
);
297 StrTab
.Shdr
.sh_addralign
= StrTab
.Align
;
298 StrTab
.Shdr
.sh_entsize
= 0;
299 StrTab
.Shdr
.sh_link
= 0;
301 void fillSymTabShdr(ContentSection
<ELFSymbolTableBuilder
<ELFT
>, ELFT
> &SymTab
,
302 uint32_t ShType
) const {
303 SymTab
.Shdr
.sh_type
= ShType
;
304 SymTab
.Shdr
.sh_flags
= SHF_ALLOC
;
305 SymTab
.Shdr
.sh_addr
= SymTab
.Addr
;
306 SymTab
.Shdr
.sh_offset
= SymTab
.Offset
;
307 // Only non-local symbols are included in the tbe file, so .dynsym only
308 // contains 1 local symbol (the undefined symbol at index 0). The sh_info
309 // should always be 1.
310 SymTab
.Shdr
.sh_info
= 1;
311 SymTab
.Shdr
.sh_size
= SymTab
.Size
;
312 SymTab
.Shdr
.sh_name
= this->ShStrTab
.Content
.getOffset(SymTab
.Name
);
313 SymTab
.Shdr
.sh_addralign
= SymTab
.Align
;
314 SymTab
.Shdr
.sh_entsize
= sizeof(Elf_Sym
);
315 SymTab
.Shdr
.sh_link
= this->DynStr
.Index
;
318 ContentSection
<ELFDynamicTableBuilder
<ELFT
>, ELFT
> &DynTab
) const {
319 DynTab
.Shdr
.sh_type
= SHT_DYNAMIC
;
320 DynTab
.Shdr
.sh_flags
= SHF_ALLOC
;
321 DynTab
.Shdr
.sh_addr
= DynTab
.Addr
;
322 DynTab
.Shdr
.sh_offset
= DynTab
.Offset
;
323 DynTab
.Shdr
.sh_info
= 0;
324 DynTab
.Shdr
.sh_size
= DynTab
.Size
;
325 DynTab
.Shdr
.sh_name
= this->ShStrTab
.Content
.getOffset(DynTab
.Name
);
326 DynTab
.Shdr
.sh_addralign
= DynTab
.Align
;
327 DynTab
.Shdr
.sh_entsize
= sizeof(Elf_Dyn
);
328 DynTab
.Shdr
.sh_link
= this->DynStr
.Index
;
330 uint64_t shdrOffset(const OutputSection
<ELFT
> &Sec
) const {
331 return ElfHeader
.e_shoff
+ Sec
.Index
* sizeof(Elf_Shdr
);
334 void writeShdr(uint8_t *Data
, const OutputSection
<ELFT
> &Sec
) const {
335 write(Data
+ shdrOffset(Sec
), Sec
.Shdr
);
338 } // end anonymous namespace
340 /// This function behaves similarly to StringRef::substr(), but attempts to
341 /// terminate the returned StringRef at the first null terminator. If no null
342 /// terminator is found, an error is returned.
344 /// @param Str Source string to create a substring from.
345 /// @param Offset The start index of the desired substring.
346 static Expected
<StringRef
> terminatedSubstr(StringRef Str
, size_t Offset
) {
347 size_t StrEnd
= Str
.find('\0', Offset
);
348 if (StrEnd
== StringLiteral::npos
) {
350 "String overran bounds of string table (no null terminator)");
353 size_t StrLen
= StrEnd
- Offset
;
354 return Str
.substr(Offset
, StrLen
);
357 /// This function takes an error, and appends a string of text to the end of
358 /// that error. Since "appending" to an Error isn't supported behavior of an
359 /// Error, this function technically creates a new error with the combined
360 /// message and consumes the old error.
362 /// @param Err Source error.
363 /// @param After Text to append at the end of Err's error message.
364 Error
appendToError(Error Err
, StringRef After
) {
366 raw_string_ostream
Stream(Message
);
368 Stream
<< " " << After
;
369 consumeError(std::move(Err
));
370 return createError(Stream
.str().c_str());
373 /// This function populates a DynamicEntries struct using an ELFT::DynRange.
374 /// After populating the struct, the members are validated with
375 /// some basic sanity checks.
377 /// @param Dyn Target DynamicEntries struct to populate.
378 /// @param DynTable Source dynamic table.
379 template <class ELFT
>
380 static Error
populateDynamic(DynamicEntries
&Dyn
,
381 typename
ELFT::DynRange DynTable
) {
382 if (DynTable
.empty())
383 return createError("No .dynamic section found");
385 // Search .dynamic for relevant entries.
386 bool FoundDynStr
= false;
387 bool FoundDynStrSz
= false;
388 bool FoundDynSym
= false;
389 for (auto &Entry
: DynTable
) {
390 switch (Entry
.d_tag
) {
392 Dyn
.SONameOffset
= Entry
.d_un
.d_val
;
395 Dyn
.StrTabAddr
= Entry
.d_un
.d_ptr
;
399 Dyn
.StrSize
= Entry
.d_un
.d_val
;
400 FoundDynStrSz
= true;
403 Dyn
.NeededLibNames
.push_back(Entry
.d_un
.d_val
);
406 Dyn
.DynSymAddr
= Entry
.d_un
.d_ptr
;
410 Dyn
.ElfHash
= Entry
.d_un
.d_ptr
;
413 Dyn
.GnuHash
= Entry
.d_un
.d_ptr
;
419 "Couldn't locate dynamic string table (no DT_STRTAB entry)");
421 if (!FoundDynStrSz
) {
423 "Couldn't determine dynamic string table size (no DT_STRSZ entry)");
427 "Couldn't locate dynamic symbol table (no DT_SYMTAB entry)");
429 if (Dyn
.SONameOffset
.hasValue() && *Dyn
.SONameOffset
>= Dyn
.StrSize
) {
430 return createStringError(object_error::parse_failed
,
431 "DT_SONAME string offset (0x%016" PRIx64
432 ") outside of dynamic string table",
435 for (uint64_t Offset
: Dyn
.NeededLibNames
) {
436 if (Offset
>= Dyn
.StrSize
) {
437 return createStringError(object_error::parse_failed
,
438 "DT_NEEDED string offset (0x%016" PRIx64
439 ") outside of dynamic string table",
444 return Error::success();
447 /// This function creates an IFSSymbol and populates all members using
448 /// information from a binary ELFT::Sym.
450 /// @param SymName The desired name of the IFSSymbol.
451 /// @param RawSym ELFT::Sym to extract symbol information from.
452 template <class ELFT
>
453 static IFSSymbol
createELFSym(StringRef SymName
,
454 const typename
ELFT::Sym
&RawSym
) {
455 IFSSymbol TargetSym
{std::string(SymName
)};
456 uint8_t Binding
= RawSym
.getBinding();
457 if (Binding
== STB_WEAK
)
458 TargetSym
.Weak
= true;
460 TargetSym
.Weak
= false;
462 TargetSym
.Undefined
= RawSym
.isUndefined();
463 TargetSym
.Type
= convertELFSymbolTypeToIFS(RawSym
.st_info
);
465 if (TargetSym
.Type
== IFSSymbolType::Func
) {
468 TargetSym
.Size
= RawSym
.st_size
;
473 /// This function populates an IFSStub with symbols using information read
474 /// from an ELF binary.
476 /// @param TargetStub IFSStub to add symbols to.
477 /// @param DynSym Range of dynamic symbols to add to TargetStub.
478 /// @param DynStr StringRef to the dynamic string table.
479 template <class ELFT
>
480 static Error
populateSymbols(IFSStub
&TargetStub
,
481 const typename
ELFT::SymRange DynSym
,
483 // Skips the first symbol since it's the NULL symbol.
484 for (auto RawSym
: DynSym
.drop_front(1)) {
485 // If a symbol does not have global or weak binding, ignore it.
486 uint8_t Binding
= RawSym
.getBinding();
487 if (!(Binding
== STB_GLOBAL
|| Binding
== STB_WEAK
))
489 // If a symbol doesn't have default or protected visibility, ignore it.
490 uint8_t Visibility
= RawSym
.getVisibility();
491 if (!(Visibility
== STV_DEFAULT
|| Visibility
== STV_PROTECTED
))
493 // Create an IFSSymbol and populate it with information from the symbol
495 Expected
<StringRef
> SymName
= terminatedSubstr(DynStr
, RawSym
.st_name
);
497 return SymName
.takeError();
498 IFSSymbol Sym
= createELFSym
<ELFT
>(*SymName
, RawSym
);
499 TargetStub
.Symbols
.push_back(std::move(Sym
));
500 // TODO: Populate symbol warning.
502 return Error::success();
505 /// Returns a new IFSStub with all members populated from an ELFObjectFile.
506 /// @param ElfObj Source ELFObjectFile.
507 template <class ELFT
>
508 static Expected
<std::unique_ptr
<IFSStub
>>
509 buildStub(const ELFObjectFile
<ELFT
> &ElfObj
) {
510 using Elf_Dyn_Range
= typename
ELFT::DynRange
;
511 using Elf_Phdr_Range
= typename
ELFT::PhdrRange
;
512 using Elf_Sym_Range
= typename
ELFT::SymRange
;
513 using Elf_Sym
= typename
ELFT::Sym
;
514 std::unique_ptr
<IFSStub
> DestStub
= std::make_unique
<IFSStub
>();
515 const ELFFile
<ELFT
> &ElfFile
= ElfObj
.getELFFile();
516 // Fetch .dynamic table.
517 Expected
<Elf_Dyn_Range
> DynTable
= ElfFile
.dynamicEntries();
519 return DynTable
.takeError();
522 // Fetch program headers.
523 Expected
<Elf_Phdr_Range
> PHdrs
= ElfFile
.program_headers();
525 return PHdrs
.takeError();
528 // Collect relevant .dynamic entries.
529 DynamicEntries DynEnt
;
530 if (Error Err
= populateDynamic
<ELFT
>(DynEnt
, *DynTable
))
531 return std::move(Err
);
533 // Get pointer to in-memory location of .dynstr section.
534 Expected
<const uint8_t *> DynStrPtr
= ElfFile
.toMappedAddr(DynEnt
.StrTabAddr
);
536 return appendToError(DynStrPtr
.takeError(),
537 "when locating .dynstr section contents");
539 StringRef
DynStr(reinterpret_cast<const char *>(DynStrPtr
.get()),
542 // Populate Arch from ELF header.
543 DestStub
->Target
.Arch
= static_cast<IFSArch
>(ElfFile
.getHeader().e_machine
);
544 DestStub
->Target
.BitWidth
=
545 convertELFBitWidthToIFS(ElfFile
.getHeader().e_ident
[EI_CLASS
]);
546 DestStub
->Target
.Endianness
=
547 convertELFEndiannessToIFS(ElfFile
.getHeader().e_ident
[EI_DATA
]);
548 DestStub
->Target
.ObjectFormat
= "ELF";
550 // Populate SoName from .dynamic entries and dynamic string table.
551 if (DynEnt
.SONameOffset
.hasValue()) {
552 Expected
<StringRef
> NameOrErr
=
553 terminatedSubstr(DynStr
, *DynEnt
.SONameOffset
);
555 return appendToError(NameOrErr
.takeError(), "when reading DT_SONAME");
557 DestStub
->SoName
= std::string(*NameOrErr
);
560 // Populate NeededLibs from .dynamic entries and dynamic string table.
561 for (uint64_t NeededStrOffset
: DynEnt
.NeededLibNames
) {
562 Expected
<StringRef
> LibNameOrErr
=
563 terminatedSubstr(DynStr
, NeededStrOffset
);
565 return appendToError(LibNameOrErr
.takeError(), "when reading DT_NEEDED");
567 DestStub
->NeededLibs
.push_back(std::string(*LibNameOrErr
));
570 // Populate Symbols from .dynsym table and dynamic string table.
571 Expected
<uint64_t> SymCount
= ElfFile
.getDynSymtabSize();
573 return SymCount
.takeError();
575 // Get pointer to in-memory location of .dynsym section.
576 Expected
<const uint8_t *> DynSymPtr
=
577 ElfFile
.toMappedAddr(DynEnt
.DynSymAddr
);
579 return appendToError(DynSymPtr
.takeError(),
580 "when locating .dynsym section contents");
581 Elf_Sym_Range DynSyms
= ArrayRef
<Elf_Sym
>(
582 reinterpret_cast<const Elf_Sym
*>(*DynSymPtr
), *SymCount
);
583 Error SymReadError
= populateSymbols
<ELFT
>(*DestStub
, DynSyms
, DynStr
);
585 return appendToError(std::move(SymReadError
),
586 "when reading dynamic symbols");
589 return std::move(DestStub
);
592 /// This function opens a file for writing and then writes a binary ELF stub to
595 /// @param FilePath File path for writing the ELF binary.
596 /// @param Stub Source InterFace Stub to generate a binary ELF stub from.
597 template <class ELFT
>
598 static Error
writeELFBinaryToFile(StringRef FilePath
, const IFSStub
&Stub
,
599 bool WriteIfChanged
) {
600 ELFStubBuilder
<ELFT
> Builder
{Stub
};
601 // Write Stub to memory first.
602 std::vector
<uint8_t> Buf(Builder
.getSize());
603 Builder
.write(Buf
.data());
605 if (WriteIfChanged
) {
606 if (ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufOrError
=
607 MemoryBuffer::getFile(FilePath
)) {
608 // Compare Stub output with existing Stub file.
609 // If Stub file unchanged, abort updating.
610 if ((*BufOrError
)->getBufferSize() == Builder
.getSize() &&
611 !memcmp((*BufOrError
)->getBufferStart(), Buf
.data(),
613 return Error::success();
617 Expected
<std::unique_ptr
<FileOutputBuffer
>> BufOrError
=
618 FileOutputBuffer::create(FilePath
, Builder
.getSize());
620 return createStringError(errc::invalid_argument
,
621 toString(BufOrError
.takeError()) +
622 " when trying to open `" + FilePath
+
625 // Write binary to file.
626 std::unique_ptr
<FileOutputBuffer
> FileBuf
= std::move(*BufOrError
);
627 memcpy(FileBuf
->getBufferStart(), Buf
.data(), Buf
.size());
629 return FileBuf
->commit();
632 Expected
<std::unique_ptr
<IFSStub
>> readELFFile(MemoryBufferRef Buf
) {
633 Expected
<std::unique_ptr
<Binary
>> BinOrErr
= createBinary(Buf
);
635 return BinOrErr
.takeError();
638 Binary
*Bin
= BinOrErr
->get();
639 if (auto Obj
= dyn_cast
<ELFObjectFile
<ELF32LE
>>(Bin
)) {
640 return buildStub(*Obj
);
641 } else if (auto Obj
= dyn_cast
<ELFObjectFile
<ELF64LE
>>(Bin
)) {
642 return buildStub(*Obj
);
643 } else if (auto Obj
= dyn_cast
<ELFObjectFile
<ELF32BE
>>(Bin
)) {
644 return buildStub(*Obj
);
645 } else if (auto Obj
= dyn_cast
<ELFObjectFile
<ELF64BE
>>(Bin
)) {
646 return buildStub(*Obj
);
648 return createStringError(errc::not_supported
, "unsupported binary format");
651 // This function wraps the ELFT writeELFBinaryToFile() so writeBinaryStub()
652 // can be called without having to use ELFType templates directly.
653 Error
writeBinaryStub(StringRef FilePath
, const IFSStub
&Stub
,
654 bool WriteIfChanged
) {
655 assert(Stub
.Target
.Arch
);
656 assert(Stub
.Target
.BitWidth
);
657 assert(Stub
.Target
.Endianness
);
658 if (Stub
.Target
.BitWidth
== IFSBitWidthType::IFS32
) {
659 if (Stub
.Target
.Endianness
== IFSEndiannessType::Little
) {
660 return writeELFBinaryToFile
<ELF32LE
>(FilePath
, Stub
, WriteIfChanged
);
662 return writeELFBinaryToFile
<ELF32BE
>(FilePath
, Stub
, WriteIfChanged
);
665 if (Stub
.Target
.Endianness
== IFSEndiannessType::Little
) {
666 return writeELFBinaryToFile
<ELF64LE
>(FilePath
, Stub
, WriteIfChanged
);
668 return writeELFBinaryToFile
<ELF64BE
>(FilePath
, Stub
, WriteIfChanged
);
671 llvm_unreachable("invalid binary output target");
674 } // end namespace ifs
675 } // end namespace llvm