xref: /freebsd/contrib/llvm-project/llvm/lib/InterfaceStub/ELFObjHandler.cpp (revision 8ddb146abcdf061be9f2c0db7e391697dafad85c)
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 
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"
21 
22 using llvm::object::ELFObjectFile;
23 
24 using namespace llvm;
25 using namespace llvm::object;
26 using namespace llvm::ELF;
27 
28 namespace llvm {
29 namespace ifs {
30 
31 // Simple struct to hold relevant .dynamic entries.
32 struct DynamicEntries {
33   uint64_t StrTabAddr = 0;
34   uint64_t StrSize = 0;
35   Optional<uint64_t> SONameOffset;
36   std::vector<uint64_t> NeededLibNames;
37   // Symbol table:
38   uint64_t DynSymAddr = 0;
39   // Hash tables:
40   Optional<uint64_t> ElfHash;
41   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 template <class ELFT>
52 static void initELFHeader(typename ELFT::Ehdr &ElfHeader, uint16_t Machine) {
53   memset(&ElfHeader, 0, sizeof(ElfHeader));
54   // ELF identification.
55   ElfHeader.e_ident[EI_MAG0] = ElfMagic[EI_MAG0];
56   ElfHeader.e_ident[EI_MAG1] = ElfMagic[EI_MAG1];
57   ElfHeader.e_ident[EI_MAG2] = ElfMagic[EI_MAG2];
58   ElfHeader.e_ident[EI_MAG3] = ElfMagic[EI_MAG3];
59   ElfHeader.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
60   bool IsLittleEndian = ELFT::TargetEndianness == support::little;
61   ElfHeader.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
62   ElfHeader.e_ident[EI_VERSION] = EV_CURRENT;
63   ElfHeader.e_ident[EI_OSABI] = ELFOSABI_NONE;
64 
65   // Remainder of ELF header.
66   ElfHeader.e_type = ET_DYN;
67   ElfHeader.e_machine = Machine;
68   ElfHeader.e_version = EV_CURRENT;
69   ElfHeader.e_ehsize = sizeof(typename ELFT::Ehdr);
70   ElfHeader.e_phentsize = sizeof(typename ELFT::Phdr);
71   ElfHeader.e_shentsize = sizeof(typename ELFT::Shdr);
72 }
73 
74 namespace {
75 template <class ELFT> struct OutputSection {
76   using Elf_Shdr = typename ELFT::Shdr;
77   std::string Name;
78   Elf_Shdr Shdr;
79   uint64_t Addr;
80   uint64_t Offset;
81   uint64_t Size;
82   uint64_t Align;
83   uint32_t Index;
84   bool NoBits = true;
85 };
86 
87 template <class T, class ELFT>
88 struct ContentSection : public OutputSection<ELFT> {
89   T Content;
90   ContentSection() { this->NoBits = false; }
91 };
92 
93 // This class just wraps StringTableBuilder for the purpose of adding a
94 // default constructor.
95 class ELFStringTableBuilder : public StringTableBuilder {
96 public:
97   ELFStringTableBuilder() : StringTableBuilder(StringTableBuilder::ELF) {}
98 };
99 
100 template <class ELFT> class ELFSymbolTableBuilder {
101 public:
102   using Elf_Sym = typename ELFT::Sym;
103 
104   ELFSymbolTableBuilder() { Symbols.push_back({}); }
105 
106   void add(size_t StNameOffset, uint64_t StSize, uint8_t StBind, uint8_t StType,
107            uint8_t StOther, uint16_t StShndx) {
108     Elf_Sym S{};
109     S.st_name = StNameOffset;
110     S.st_size = StSize;
111     S.st_info = (StBind << 4) | (StType & 0xf);
112     S.st_other = StOther;
113     S.st_shndx = StShndx;
114     Symbols.push_back(S);
115   }
116 
117   size_t getSize() const { return Symbols.size() * sizeof(Elf_Sym); }
118 
119   void write(uint8_t *Buf) const {
120     memcpy(Buf, Symbols.data(), sizeof(Elf_Sym) * Symbols.size());
121   }
122 
123 private:
124   llvm::SmallVector<Elf_Sym, 8> Symbols;
125 };
126 
127 template <class ELFT> class ELFDynamicTableBuilder {
128 public:
129   using Elf_Dyn = typename ELFT::Dyn;
130 
131   size_t addAddr(uint64_t Tag, uint64_t Addr) {
132     Elf_Dyn Entry;
133     Entry.d_tag = Tag;
134     Entry.d_un.d_ptr = Addr;
135     Entries.push_back(Entry);
136     return Entries.size() - 1;
137   }
138 
139   void modifyAddr(size_t Index, uint64_t Addr) {
140     Entries[Index].d_un.d_ptr = Addr;
141   }
142 
143   size_t addValue(uint64_t Tag, uint64_t Value) {
144     Elf_Dyn Entry;
145     Entry.d_tag = Tag;
146     Entry.d_un.d_val = Value;
147     Entries.push_back(Entry);
148     return Entries.size() - 1;
149   }
150 
151   void modifyValue(size_t Index, uint64_t Value) {
152     Entries[Index].d_un.d_val = Value;
153   }
154 
155   size_t getSize() const {
156     // Add DT_NULL entry at the end.
157     return (Entries.size() + 1) * sizeof(Elf_Dyn);
158   }
159 
160   void write(uint8_t *Buf) const {
161     memcpy(Buf, Entries.data(), sizeof(Elf_Dyn) * Entries.size());
162     // Add DT_NULL entry at the end.
163     memset(Buf + sizeof(Elf_Dyn) * Entries.size(), 0, sizeof(Elf_Dyn));
164   }
165 
166 private:
167   llvm::SmallVector<Elf_Dyn, 8> Entries;
168 };
169 
170 template <class ELFT> class ELFStubBuilder {
171 public:
172   using Elf_Ehdr = typename ELFT::Ehdr;
173   using Elf_Shdr = typename ELFT::Shdr;
174   using Elf_Phdr = typename ELFT::Phdr;
175   using Elf_Sym = typename ELFT::Sym;
176   using Elf_Addr = typename ELFT::Addr;
177   using Elf_Dyn = typename ELFT::Dyn;
178 
179   ELFStubBuilder(const ELFStubBuilder &) = delete;
180   ELFStubBuilder(ELFStubBuilder &&) = default;
181 
182   explicit ELFStubBuilder(const IFSStub &Stub) {
183     DynSym.Name = ".dynsym";
184     DynSym.Align = sizeof(Elf_Addr);
185     DynStr.Name = ".dynstr";
186     DynStr.Align = 1;
187     DynTab.Name = ".dynamic";
188     DynTab.Align = sizeof(Elf_Addr);
189     ShStrTab.Name = ".shstrtab";
190     ShStrTab.Align = 1;
191 
192     // Populate string tables.
193     for (const IFSSymbol &Sym : Stub.Symbols)
194       DynStr.Content.add(Sym.Name);
195     for (const std::string &Lib : Stub.NeededLibs)
196       DynStr.Content.add(Lib);
197     if (Stub.SoName)
198       DynStr.Content.add(Stub.SoName.getValue());
199 
200     std::vector<OutputSection<ELFT> *> Sections = {&DynSym, &DynStr, &DynTab,
201                                                    &ShStrTab};
202     const OutputSection<ELFT> *LastSection = Sections.back();
203     // Now set the Index and put sections names into ".shstrtab".
204     uint64_t Index = 1;
205     for (OutputSection<ELFT> *Sec : Sections) {
206       Sec->Index = Index++;
207       ShStrTab.Content.add(Sec->Name);
208     }
209     ShStrTab.Content.finalize();
210     ShStrTab.Size = ShStrTab.Content.getSize();
211     DynStr.Content.finalize();
212     DynStr.Size = DynStr.Content.getSize();
213 
214     // Populate dynamic symbol table.
215     for (const IFSSymbol &Sym : Stub.Symbols) {
216       uint8_t Bind = Sym.Weak ? STB_WEAK : STB_GLOBAL;
217       // For non-undefined symbols, value of the shndx is not relevant at link
218       // time as long as it is not SHN_UNDEF. Set shndx to 1, which
219       // points to ".dynsym".
220       uint16_t Shndx = Sym.Undefined ? SHN_UNDEF : 1;
221       DynSym.Content.add(DynStr.Content.getOffset(Sym.Name), Sym.Size, Bind,
222                          convertIFSSymbolTypeToELF(Sym.Type), 0, Shndx);
223     }
224     DynSym.Size = DynSym.Content.getSize();
225 
226     // Poplulate dynamic table.
227     size_t DynSymIndex = DynTab.Content.addAddr(DT_SYMTAB, 0);
228     size_t DynStrIndex = DynTab.Content.addAddr(DT_STRTAB, 0);
229     for (const std::string &Lib : Stub.NeededLibs)
230       DynTab.Content.addValue(DT_NEEDED, DynStr.Content.getOffset(Lib));
231     if (Stub.SoName)
232       DynTab.Content.addValue(DT_SONAME,
233                               DynStr.Content.getOffset(Stub.SoName.getValue()));
234     DynTab.Size = DynTab.Content.getSize();
235     // Calculate sections' addresses and offsets.
236     uint64_t CurrentOffset = sizeof(Elf_Ehdr);
237     for (OutputSection<ELFT> *Sec : Sections) {
238       Sec->Offset = alignTo(CurrentOffset, Sec->Align);
239       Sec->Addr = Sec->Offset;
240       CurrentOffset = Sec->Offset + Sec->Size;
241     }
242     // Fill Addr back to dynamic table.
243     DynTab.Content.modifyAddr(DynSymIndex, DynSym.Addr);
244     DynTab.Content.modifyAddr(DynStrIndex, DynStr.Addr);
245     // Write section headers of string tables.
246     fillSymTabShdr(DynSym, SHT_DYNSYM);
247     fillStrTabShdr(DynStr, SHF_ALLOC);
248     fillDynTabShdr(DynTab);
249     fillStrTabShdr(ShStrTab);
250 
251     // Finish initializing the ELF header.
252     initELFHeader<ELFT>(ElfHeader,
253                         static_cast<uint16_t>(Stub.Target.Arch.getValue()));
254     ElfHeader.e_shstrndx = ShStrTab.Index;
255     ElfHeader.e_shnum = LastSection->Index + 1;
256     ElfHeader.e_shoff =
257         alignTo(LastSection->Offset + LastSection->Size, sizeof(Elf_Addr));
258   }
259 
260   size_t getSize() const {
261     return ElfHeader.e_shoff + ElfHeader.e_shnum * sizeof(Elf_Shdr);
262   }
263 
264   void write(uint8_t *Data) const {
265     write(Data, ElfHeader);
266     DynSym.Content.write(Data + DynSym.Shdr.sh_offset);
267     DynStr.Content.write(Data + DynStr.Shdr.sh_offset);
268     DynTab.Content.write(Data + DynTab.Shdr.sh_offset);
269     ShStrTab.Content.write(Data + ShStrTab.Shdr.sh_offset);
270     writeShdr(Data, DynSym);
271     writeShdr(Data, DynStr);
272     writeShdr(Data, DynTab);
273     writeShdr(Data, ShStrTab);
274   }
275 
276 private:
277   Elf_Ehdr ElfHeader;
278   ContentSection<ELFStringTableBuilder, ELFT> DynStr;
279   ContentSection<ELFStringTableBuilder, ELFT> ShStrTab;
280   ContentSection<ELFSymbolTableBuilder<ELFT>, ELFT> DynSym;
281   ContentSection<ELFDynamicTableBuilder<ELFT>, ELFT> DynTab;
282 
283   template <class T> static void write(uint8_t *Data, const T &Value) {
284     *reinterpret_cast<T *>(Data) = Value;
285   }
286 
287   void fillStrTabShdr(ContentSection<ELFStringTableBuilder, ELFT> &StrTab,
288                       uint32_t ShFlags = 0) const {
289     StrTab.Shdr.sh_type = SHT_STRTAB;
290     StrTab.Shdr.sh_flags = ShFlags;
291     StrTab.Shdr.sh_addr = StrTab.Addr;
292     StrTab.Shdr.sh_offset = StrTab.Offset;
293     StrTab.Shdr.sh_info = 0;
294     StrTab.Shdr.sh_size = StrTab.Size;
295     StrTab.Shdr.sh_name = ShStrTab.Content.getOffset(StrTab.Name);
296     StrTab.Shdr.sh_addralign = StrTab.Align;
297     StrTab.Shdr.sh_entsize = 0;
298     StrTab.Shdr.sh_link = 0;
299   }
300   void fillSymTabShdr(ContentSection<ELFSymbolTableBuilder<ELFT>, ELFT> &SymTab,
301                       uint32_t ShType) const {
302     SymTab.Shdr.sh_type = ShType;
303     SymTab.Shdr.sh_flags = SHF_ALLOC;
304     SymTab.Shdr.sh_addr = SymTab.Addr;
305     SymTab.Shdr.sh_offset = SymTab.Offset;
306     // Only non-local symbols are included in the tbe file, so .dynsym only
307     // contains 1 local symbol (the undefined symbol at index 0). The sh_info
308     // should always be 1.
309     SymTab.Shdr.sh_info = 1;
310     SymTab.Shdr.sh_size = SymTab.Size;
311     SymTab.Shdr.sh_name = this->ShStrTab.Content.getOffset(SymTab.Name);
312     SymTab.Shdr.sh_addralign = SymTab.Align;
313     SymTab.Shdr.sh_entsize = sizeof(Elf_Sym);
314     SymTab.Shdr.sh_link = this->DynStr.Index;
315   }
316   void fillDynTabShdr(
317       ContentSection<ELFDynamicTableBuilder<ELFT>, ELFT> &DynTab) const {
318     DynTab.Shdr.sh_type = SHT_DYNAMIC;
319     DynTab.Shdr.sh_flags = SHF_ALLOC;
320     DynTab.Shdr.sh_addr = DynTab.Addr;
321     DynTab.Shdr.sh_offset = DynTab.Offset;
322     DynTab.Shdr.sh_info = 0;
323     DynTab.Shdr.sh_size = DynTab.Size;
324     DynTab.Shdr.sh_name = this->ShStrTab.Content.getOffset(DynTab.Name);
325     DynTab.Shdr.sh_addralign = DynTab.Align;
326     DynTab.Shdr.sh_entsize = sizeof(Elf_Dyn);
327     DynTab.Shdr.sh_link = this->DynStr.Index;
328   }
329   uint64_t shdrOffset(const OutputSection<ELFT> &Sec) const {
330     return ElfHeader.e_shoff + Sec.Index * sizeof(Elf_Shdr);
331   }
332 
333   void writeShdr(uint8_t *Data, const OutputSection<ELFT> &Sec) const {
334     write(Data + shdrOffset(Sec), Sec.Shdr);
335   }
336 };
337 } // end anonymous namespace
338 
339 /// This function behaves similarly to StringRef::substr(), but attempts to
340 /// terminate the returned StringRef at the first null terminator. If no null
341 /// terminator is found, an error is returned.
342 ///
343 /// @param Str Source string to create a substring from.
344 /// @param Offset The start index of the desired substring.
345 static Expected<StringRef> terminatedSubstr(StringRef Str, size_t Offset) {
346   size_t StrEnd = Str.find('\0', Offset);
347   if (StrEnd == StringLiteral::npos) {
348     return createError(
349         "String overran bounds of string table (no null terminator)");
350   }
351 
352   size_t StrLen = StrEnd - Offset;
353   return Str.substr(Offset, StrLen);
354 }
355 
356 /// This function takes an error, and appends a string of text to the end of
357 /// that error. Since "appending" to an Error isn't supported behavior of an
358 /// Error, this function technically creates a new error with the combined
359 /// message and consumes the old error.
360 ///
361 /// @param Err Source error.
362 /// @param After Text to append at the end of Err's error message.
363 Error appendToError(Error Err, StringRef After) {
364   std::string Message;
365   raw_string_ostream Stream(Message);
366   Stream << Err;
367   Stream << " " << After;
368   consumeError(std::move(Err));
369   return createError(Stream.str());
370 }
371 
372 /// This function populates a DynamicEntries struct using an ELFT::DynRange.
373 /// After populating the struct, the members are validated with
374 /// some basic correctness checks.
375 ///
376 /// @param Dyn Target DynamicEntries struct to populate.
377 /// @param DynTable Source dynamic table.
378 template <class ELFT>
379 static Error populateDynamic(DynamicEntries &Dyn,
380                              typename ELFT::DynRange DynTable) {
381   if (DynTable.empty())
382     return createError("No .dynamic section found");
383 
384   // Search .dynamic for relevant entries.
385   bool FoundDynStr = false;
386   bool FoundDynStrSz = false;
387   bool FoundDynSym = false;
388   for (auto &Entry : DynTable) {
389     switch (Entry.d_tag) {
390     case DT_SONAME:
391       Dyn.SONameOffset = Entry.d_un.d_val;
392       break;
393     case DT_STRTAB:
394       Dyn.StrTabAddr = Entry.d_un.d_ptr;
395       FoundDynStr = true;
396       break;
397     case DT_STRSZ:
398       Dyn.StrSize = Entry.d_un.d_val;
399       FoundDynStrSz = true;
400       break;
401     case DT_NEEDED:
402       Dyn.NeededLibNames.push_back(Entry.d_un.d_val);
403       break;
404     case DT_SYMTAB:
405       Dyn.DynSymAddr = Entry.d_un.d_ptr;
406       FoundDynSym = true;
407       break;
408     case DT_HASH:
409       Dyn.ElfHash = Entry.d_un.d_ptr;
410       break;
411     case DT_GNU_HASH:
412       Dyn.GnuHash = Entry.d_un.d_ptr;
413     }
414   }
415 
416   if (!FoundDynStr) {
417     return createError(
418         "Couldn't locate dynamic string table (no DT_STRTAB entry)");
419   }
420   if (!FoundDynStrSz) {
421     return createError(
422         "Couldn't determine dynamic string table size (no DT_STRSZ entry)");
423   }
424   if (!FoundDynSym) {
425     return createError(
426         "Couldn't locate dynamic symbol table (no DT_SYMTAB entry)");
427   }
428   if (Dyn.SONameOffset.hasValue() && *Dyn.SONameOffset >= Dyn.StrSize) {
429     return createStringError(object_error::parse_failed,
430                              "DT_SONAME string offset (0x%016" PRIx64
431                              ") outside of dynamic string table",
432                              *Dyn.SONameOffset);
433   }
434   for (uint64_t Offset : Dyn.NeededLibNames) {
435     if (Offset >= Dyn.StrSize) {
436       return createStringError(object_error::parse_failed,
437                                "DT_NEEDED string offset (0x%016" PRIx64
438                                ") outside of dynamic string table",
439                                Offset);
440     }
441   }
442 
443   return Error::success();
444 }
445 
446 /// This function creates an IFSSymbol and populates all members using
447 /// information from a binary ELFT::Sym.
448 ///
449 /// @param SymName The desired name of the IFSSymbol.
450 /// @param RawSym ELFT::Sym to extract symbol information from.
451 template <class ELFT>
452 static IFSSymbol createELFSym(StringRef SymName,
453                               const typename ELFT::Sym &RawSym) {
454   IFSSymbol TargetSym{std::string(SymName)};
455   uint8_t Binding = RawSym.getBinding();
456   if (Binding == STB_WEAK)
457     TargetSym.Weak = true;
458   else
459     TargetSym.Weak = false;
460 
461   TargetSym.Undefined = RawSym.isUndefined();
462   TargetSym.Type = convertELFSymbolTypeToIFS(RawSym.st_info);
463 
464   if (TargetSym.Type == IFSSymbolType::Func) {
465     TargetSym.Size = 0;
466   } else {
467     TargetSym.Size = RawSym.st_size;
468   }
469   return TargetSym;
470 }
471 
472 /// This function populates an IFSStub with symbols using information read
473 /// from an ELF binary.
474 ///
475 /// @param TargetStub IFSStub to add symbols to.
476 /// @param DynSym Range of dynamic symbols to add to TargetStub.
477 /// @param DynStr StringRef to the dynamic string table.
478 template <class ELFT>
479 static Error populateSymbols(IFSStub &TargetStub,
480                              const typename ELFT::SymRange DynSym,
481                              StringRef DynStr) {
482   // Skips the first symbol since it's the NULL symbol.
483   for (auto RawSym : DynSym.drop_front(1)) {
484     // If a symbol does not have global or weak binding, ignore it.
485     uint8_t Binding = RawSym.getBinding();
486     if (!(Binding == STB_GLOBAL || Binding == STB_WEAK))
487       continue;
488     // If a symbol doesn't have default or protected visibility, ignore it.
489     uint8_t Visibility = RawSym.getVisibility();
490     if (!(Visibility == STV_DEFAULT || Visibility == STV_PROTECTED))
491       continue;
492     // Create an IFSSymbol and populate it with information from the symbol
493     // table entry.
494     Expected<StringRef> SymName = terminatedSubstr(DynStr, RawSym.st_name);
495     if (!SymName)
496       return SymName.takeError();
497     IFSSymbol Sym = createELFSym<ELFT>(*SymName, RawSym);
498     TargetStub.Symbols.push_back(std::move(Sym));
499     // TODO: Populate symbol warning.
500   }
501   return Error::success();
502 }
503 
504 /// Returns a new IFSStub with all members populated from an ELFObjectFile.
505 /// @param ElfObj Source ELFObjectFile.
506 template <class ELFT>
507 static Expected<std::unique_ptr<IFSStub>>
508 buildStub(const ELFObjectFile<ELFT> &ElfObj) {
509   using Elf_Dyn_Range = typename ELFT::DynRange;
510   using Elf_Phdr_Range = typename ELFT::PhdrRange;
511   using Elf_Sym_Range = typename ELFT::SymRange;
512   using Elf_Sym = typename ELFT::Sym;
513   std::unique_ptr<IFSStub> DestStub = std::make_unique<IFSStub>();
514   const ELFFile<ELFT> &ElfFile = ElfObj.getELFFile();
515   // Fetch .dynamic table.
516   Expected<Elf_Dyn_Range> DynTable = ElfFile.dynamicEntries();
517   if (!DynTable) {
518     return DynTable.takeError();
519   }
520 
521   // Fetch program headers.
522   Expected<Elf_Phdr_Range> PHdrs = ElfFile.program_headers();
523   if (!PHdrs) {
524     return PHdrs.takeError();
525   }
526 
527   // Collect relevant .dynamic entries.
528   DynamicEntries DynEnt;
529   if (Error Err = populateDynamic<ELFT>(DynEnt, *DynTable))
530     return std::move(Err);
531 
532   // Get pointer to in-memory location of .dynstr section.
533   Expected<const uint8_t *> DynStrPtr = ElfFile.toMappedAddr(DynEnt.StrTabAddr);
534   if (!DynStrPtr)
535     return appendToError(DynStrPtr.takeError(),
536                          "when locating .dynstr section contents");
537 
538   StringRef DynStr(reinterpret_cast<const char *>(DynStrPtr.get()),
539                    DynEnt.StrSize);
540 
541   // Populate Arch from ELF header.
542   DestStub->Target.Arch = static_cast<IFSArch>(ElfFile.getHeader().e_machine);
543   DestStub->Target.BitWidth =
544       convertELFBitWidthToIFS(ElfFile.getHeader().e_ident[EI_CLASS]);
545   DestStub->Target.Endianness =
546       convertELFEndiannessToIFS(ElfFile.getHeader().e_ident[EI_DATA]);
547   DestStub->Target.ObjectFormat = "ELF";
548 
549   // Populate SoName from .dynamic entries and dynamic string table.
550   if (DynEnt.SONameOffset.hasValue()) {
551     Expected<StringRef> NameOrErr =
552         terminatedSubstr(DynStr, *DynEnt.SONameOffset);
553     if (!NameOrErr) {
554       return appendToError(NameOrErr.takeError(), "when reading DT_SONAME");
555     }
556     DestStub->SoName = std::string(*NameOrErr);
557   }
558 
559   // Populate NeededLibs from .dynamic entries and dynamic string table.
560   for (uint64_t NeededStrOffset : DynEnt.NeededLibNames) {
561     Expected<StringRef> LibNameOrErr =
562         terminatedSubstr(DynStr, NeededStrOffset);
563     if (!LibNameOrErr) {
564       return appendToError(LibNameOrErr.takeError(), "when reading DT_NEEDED");
565     }
566     DestStub->NeededLibs.push_back(std::string(*LibNameOrErr));
567   }
568 
569   // Populate Symbols from .dynsym table and dynamic string table.
570   Expected<uint64_t> SymCount = ElfFile.getDynSymtabSize();
571   if (!SymCount)
572     return SymCount.takeError();
573   if (*SymCount > 0) {
574     // Get pointer to in-memory location of .dynsym section.
575     Expected<const uint8_t *> DynSymPtr =
576         ElfFile.toMappedAddr(DynEnt.DynSymAddr);
577     if (!DynSymPtr)
578       return appendToError(DynSymPtr.takeError(),
579                            "when locating .dynsym section contents");
580     Elf_Sym_Range DynSyms = ArrayRef<Elf_Sym>(
581         reinterpret_cast<const Elf_Sym *>(*DynSymPtr), *SymCount);
582     Error SymReadError = populateSymbols<ELFT>(*DestStub, DynSyms, DynStr);
583     if (SymReadError)
584       return appendToError(std::move(SymReadError),
585                            "when reading dynamic symbols");
586   }
587 
588   return std::move(DestStub);
589 }
590 
591 /// This function opens a file for writing and then writes a binary ELF stub to
592 /// the file.
593 ///
594 /// @param FilePath File path for writing the ELF binary.
595 /// @param Stub Source InterFace Stub to generate a binary ELF stub from.
596 template <class ELFT>
597 static Error writeELFBinaryToFile(StringRef FilePath, const IFSStub &Stub,
598                                   bool WriteIfChanged) {
599   ELFStubBuilder<ELFT> Builder{Stub};
600   // Write Stub to memory first.
601   std::vector<uint8_t> Buf(Builder.getSize());
602   Builder.write(Buf.data());
603 
604   if (WriteIfChanged) {
605     if (ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrError =
606             MemoryBuffer::getFile(FilePath)) {
607       // Compare Stub output with existing Stub file.
608       // If Stub file unchanged, abort updating.
609       if ((*BufOrError)->getBufferSize() == Builder.getSize() &&
610           !memcmp((*BufOrError)->getBufferStart(), Buf.data(),
611                   Builder.getSize()))
612         return Error::success();
613     }
614   }
615 
616   Expected<std::unique_ptr<FileOutputBuffer>> BufOrError =
617       FileOutputBuffer::create(FilePath, Builder.getSize());
618   if (!BufOrError)
619     return createStringError(errc::invalid_argument,
620                              toString(BufOrError.takeError()) +
621                                  " when trying to open `" + FilePath +
622                                  "` for writing");
623 
624   // Write binary to file.
625   std::unique_ptr<FileOutputBuffer> FileBuf = std::move(*BufOrError);
626   memcpy(FileBuf->getBufferStart(), Buf.data(), Buf.size());
627 
628   return FileBuf->commit();
629 }
630 
631 Expected<std::unique_ptr<IFSStub>> readELFFile(MemoryBufferRef Buf) {
632   Expected<std::unique_ptr<Binary>> BinOrErr = createBinary(Buf);
633   if (!BinOrErr) {
634     return BinOrErr.takeError();
635   }
636 
637   Binary *Bin = BinOrErr->get();
638   if (auto Obj = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
639     return buildStub(*Obj);
640   } else if (auto Obj = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
641     return buildStub(*Obj);
642   } else if (auto Obj = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
643     return buildStub(*Obj);
644   } else if (auto Obj = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
645     return buildStub(*Obj);
646   }
647   return createStringError(errc::not_supported, "unsupported binary format");
648 }
649 
650 // This function wraps the ELFT writeELFBinaryToFile() so writeBinaryStub()
651 // can be called without having to use ELFType templates directly.
652 Error writeBinaryStub(StringRef FilePath, const IFSStub &Stub,
653                       bool WriteIfChanged) {
654   assert(Stub.Target.Arch);
655   assert(Stub.Target.BitWidth);
656   assert(Stub.Target.Endianness);
657   if (Stub.Target.BitWidth == IFSBitWidthType::IFS32) {
658     if (Stub.Target.Endianness == IFSEndiannessType::Little) {
659       return writeELFBinaryToFile<ELF32LE>(FilePath, Stub, WriteIfChanged);
660     } else {
661       return writeELFBinaryToFile<ELF32BE>(FilePath, Stub, WriteIfChanged);
662     }
663   } else {
664     if (Stub.Target.Endianness == IFSEndiannessType::Little) {
665       return writeELFBinaryToFile<ELF64LE>(FilePath, Stub, WriteIfChanged);
666     } else {
667       return writeELFBinaryToFile<ELF64BE>(FilePath, Stub, WriteIfChanged);
668     }
669   }
670   llvm_unreachable("invalid binary output target");
671 }
672 
673 } // end namespace ifs
674 } // end namespace llvm
675