LLVM  13.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"
14 #include "llvm/Object/ELFTypes.h"
15 #include "llvm/Support/Errc.h"
16 #include "llvm/Support/Error.h"
20 #include "llvm/Support/Process.h"
21 
24 
25 using namespace llvm;
26 using namespace llvm::object;
27 using namespace llvm::ELF;
28 
29 namespace llvm {
30 namespace elfabi {
31 
32 // Simple struct to hold relevant .dynamic entries.
34  uint64_t StrTabAddr = 0;
35  uint64_t StrSize = 0;
37  std::vector<uint64_t> NeededLibNames;
38  // Symbol table:
39  uint64_t DynSymAddr = 0;
40  // Hash tables:
43 };
44 
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.
49 ///
50 /// @param ElfHeader Target ELFT::Ehdr to populate.
51 /// @param Machine Target architecture (e_machine from ELF specifications).
52 template <class ELFT>
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;
65 
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);
73 }
74 
75 namespace {
76 template <class ELFT> struct OutputSection {
77  using Elf_Shdr = typename ELFT::Shdr;
78  std::string Name;
79  Elf_Shdr Shdr;
80  uint64_t Addr;
81  uint64_t Offset;
82  uint64_t Size;
83  uint64_t Align;
85  bool NoBits = true;
86 };
87 
88 template <class T, class ELFT>
89 struct ContentSection : public OutputSection<ELFT> {
91  ContentSection() { this->NoBits = false; }
92 };
93 
94 // This class just wraps StringTableBuilder for the purpose of adding a
95 // default constructor.
96 class ELFStringTableBuilder : public StringTableBuilder {
97 public:
98  ELFStringTableBuilder() : StringTableBuilder(StringTableBuilder::ELF) {}
99 };
100 
101 template <class ELFT> class ELFSymbolTableBuilder {
102 public:
103  using Elf_Sym = typename ELFT::Sym;
104 
105  ELFSymbolTableBuilder() { Symbols.push_back({}); }
106 
107  void add(size_t StNameOffset, uint64_t StSize, uint8_t StBind, uint8_t StType,
108  uint8_t StOther, uint16_t StShndx) {
109  Elf_Sym S{};
110  S.st_name = StNameOffset;
111  S.st_size = StSize;
112  S.st_info = (StBind << 4) | (StType & 0xf);
113  S.st_other = StOther;
114  S.st_shndx = StShndx;
115  Symbols.push_back(S);
116  }
117 
118  size_t getSize() const { return Symbols.size() * sizeof(Elf_Sym); }
119 
120  void write(uint8_t *Buf) const {
121  memcpy(Buf, Symbols.data(), sizeof(Elf_Sym) * Symbols.size());
122  }
123 
124 private:
126 };
127 
128 template <class ELFT> class ELFDynamicTableBuilder {
129 public:
130  using Elf_Dyn = typename ELFT::Dyn;
131 
132  size_t addAddr(uint64_t Tag, uint64_t Addr) {
133  Elf_Dyn Entry;
134  Entry.d_tag = Tag;
135  Entry.d_un.d_ptr = Addr;
136  Entries.push_back(Entry);
137  return Entries.size() - 1;
138  }
139 
140  void modifyAddr(size_t Index, uint64_t Addr) {
141  Entries[Index].d_un.d_ptr = Addr;
142  }
143 
144  size_t addValue(uint64_t Tag, uint64_t Value) {
145  Elf_Dyn Entry;
146  Entry.d_tag = Tag;
147  Entry.d_un.d_val = Value;
148  Entries.push_back(Entry);
149  return Entries.size() - 1;
150  }
151 
152  void modifyValue(size_t Index, uint64_t Value) {
153  Entries[Index].d_un.d_val = Value;
154  }
155 
156  size_t getSize() const {
157  // Add DT_NULL entry at the end.
158  return (Entries.size() + 1) * sizeof(Elf_Dyn);
159  }
160 
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));
165  }
166 
167 private:
169 };
170 
171 template <class ELFT> class ELFStubBuilder {
172 public:
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;
179 
180  ELFStubBuilder(const ELFStubBuilder &) = delete;
181  ELFStubBuilder(ELFStubBuilder &&) = default;
182 
183  explicit ELFStubBuilder(const ELFStub &Stub) {
184  DynSym.Name = ".dynsym";
185  DynSym.Align = sizeof(Elf_Addr);
186  DynStr.Name = ".dynstr";
187  DynStr.Align = 1;
188  DynTab.Name = ".dynamic";
189  DynTab.Align = sizeof(Elf_Addr);
190  ShStrTab.Name = ".shstrtab";
191  ShStrTab.Align = 1;
192 
193  // Populate string tables.
194  for (const ELFSymbol &Sym : Stub.Symbols)
195  DynStr.Content.add(Sym.Name);
196  for (const std::string &Lib : Stub.NeededLibs)
197  DynStr.Content.add(Lib);
198  if (Stub.SoName)
199  DynStr.Content.add(Stub.SoName.getValue());
200 
201  std::vector<OutputSection<ELFT> *> Sections = {&DynSym, &DynStr, &DynTab,
202  &ShStrTab};
203  const OutputSection<ELFT> *LastSection = Sections.back();
204  // Now set the Index and put sections names into ".shstrtab".
205  uint64_t Index = 1;
206  for (OutputSection<ELFT> *Sec : Sections) {
207  Sec->Index = Index++;
208  ShStrTab.Content.add(Sec->Name);
209  }
210  ShStrTab.Content.finalize();
211  ShStrTab.Size = ShStrTab.Content.getSize();
212  DynStr.Content.finalize();
213  DynStr.Size = DynStr.Content.getSize();
214 
215  // Populate dynamic symbol table.
216  for (const ELFSymbol &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  (uint8_t)Sym.Type, 0, Shndx);
224  }
225  DynSym.Size = DynSym.Content.getSize();
226 
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));
232  if (Stub.SoName)
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;
242  }
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);
251 
252  // Finish initializing the ELF header.
253  initELFHeader<ELFT>(ElfHeader, Stub.Arch);
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.
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.
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().c_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 sanity checks.
375 ///
376 /// @param Dyn Target DynamicEntries struct to populate.
377 /// @param DynTable Source dynamic table.
378 template <class ELFT>
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) {
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) {
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 extracts symbol type from a symbol's st_info member and
447 /// maps it to an ELFSymbolType enum.
448 /// Currently, STT_NOTYPE, STT_OBJECT, STT_FUNC, and STT_TLS are supported.
449 /// Other symbol types are mapped to ELFSymbolType::Unknown.
450 ///
451 /// @param Info Binary symbol st_info to extract symbol type from.
453  Info = Info & 0xf;
454  switch (Info) {
455  case ELF::STT_NOTYPE:
456  return ELFSymbolType::NoType;
457  case ELF::STT_OBJECT:
458  return ELFSymbolType::Object;
459  case ELF::STT_FUNC:
460  return ELFSymbolType::Func;
461  case ELF::STT_TLS:
462  return ELFSymbolType::TLS;
463  default:
464  return ELFSymbolType::Unknown;
465  }
466 }
467 
468 /// This function creates an ELFSymbol and populates all members using
469 /// information from a binary ELFT::Sym.
470 ///
471 /// @param SymName The desired name of the ELFSymbol.
472 /// @param RawSym ELFT::Sym to extract symbol information from.
473 template <class ELFT>
475  const typename ELFT::Sym &RawSym) {
476  ELFSymbol TargetSym{std::string(SymName)};
477  uint8_t Binding = RawSym.getBinding();
478  if (Binding == STB_WEAK)
479  TargetSym.Weak = true;
480  else
481  TargetSym.Weak = false;
482 
483  TargetSym.Undefined = RawSym.isUndefined();
484  TargetSym.Type = convertInfoToType(RawSym.st_info);
485 
486  if (TargetSym.Type == ELFSymbolType::Func) {
487  TargetSym.Size = 0;
488  } else {
489  TargetSym.Size = RawSym.st_size;
490  }
491  return TargetSym;
492 }
493 
494 /// This function populates an ELFStub with symbols using information read
495 /// from an ELF binary.
496 ///
497 /// @param TargetStub ELFStub to add symbols to.
498 /// @param DynSym Range of dynamic symbols to add to TargetStub.
499 /// @param DynStr StringRef to the dynamic string table.
500 template <class ELFT>
501 static Error populateSymbols(ELFStub &TargetStub,
502  const typename ELFT::SymRange DynSym,
503  StringRef DynStr) {
504  // Skips the first symbol since it's the NULL symbol.
505  for (auto RawSym : DynSym.drop_front(1)) {
506  // If a symbol does not have global or weak binding, ignore it.
507  uint8_t Binding = RawSym.getBinding();
508  if (!(Binding == STB_GLOBAL || Binding == STB_WEAK))
509  continue;
510  // If a symbol doesn't have default or protected visibility, ignore it.
511  uint8_t Visibility = RawSym.getVisibility();
512  if (!(Visibility == STV_DEFAULT || Visibility == STV_PROTECTED))
513  continue;
514  // Create an ELFSymbol and populate it with information from the symbol
515  // table entry.
516  Expected<StringRef> SymName = terminatedSubstr(DynStr, RawSym.st_name);
517  if (!SymName)
518  return SymName.takeError();
519  ELFSymbol Sym = createELFSym<ELFT>(*SymName, RawSym);
520  TargetStub.Symbols.insert(std::move(Sym));
521  // TODO: Populate symbol warning.
522  }
523  return Error::success();
524 }
525 
526 /// Returns a new ELFStub with all members populated from an ELFObjectFile.
527 /// @param ElfObj Source ELFObjectFile.
528 template <class ELFT>
531  using Elf_Dyn_Range = typename ELFT::DynRange;
532  using Elf_Phdr_Range = typename ELFT::PhdrRange;
533  using Elf_Sym_Range = typename ELFT::SymRange;
534  using Elf_Sym = typename ELFT::Sym;
535  std::unique_ptr<ELFStub> DestStub = std::make_unique<ELFStub>();
536  const ELFFile<ELFT> &ElfFile = ElfObj.getELFFile();
537  // Fetch .dynamic table.
538  Expected<Elf_Dyn_Range> DynTable = ElfFile.dynamicEntries();
539  if (!DynTable) {
540  return DynTable.takeError();
541  }
542 
543  // Fetch program headers.
544  Expected<Elf_Phdr_Range> PHdrs = ElfFile.program_headers();
545  if (!PHdrs) {
546  return PHdrs.takeError();
547  }
548 
549  // Collect relevant .dynamic entries.
550  DynamicEntries DynEnt;
551  if (Error Err = populateDynamic<ELFT>(DynEnt, *DynTable))
552  return std::move(Err);
553 
554  // Get pointer to in-memory location of .dynstr section.
555  Expected<const uint8_t *> DynStrPtr = ElfFile.toMappedAddr(DynEnt.StrTabAddr);
556  if (!DynStrPtr)
557  return appendToError(DynStrPtr.takeError(),
558  "when locating .dynstr section contents");
559 
560  StringRef DynStr(reinterpret_cast<const char *>(DynStrPtr.get()),
561  DynEnt.StrSize);
562 
563  // Populate Arch from ELF header.
564  DestStub->Arch = ElfFile.getHeader().e_machine;
565 
566  // Populate SoName from .dynamic entries and dynamic string table.
567  if (DynEnt.SONameOffset.hasValue()) {
568  Expected<StringRef> NameOrErr =
569  terminatedSubstr(DynStr, *DynEnt.SONameOffset);
570  if (!NameOrErr) {
571  return appendToError(NameOrErr.takeError(), "when reading DT_SONAME");
572  }
573  DestStub->SoName = std::string(*NameOrErr);
574  }
575 
576  // Populate NeededLibs from .dynamic entries and dynamic string table.
577  for (uint64_t NeededStrOffset : DynEnt.NeededLibNames) {
578  Expected<StringRef> LibNameOrErr =
579  terminatedSubstr(DynStr, NeededStrOffset);
580  if (!LibNameOrErr) {
581  return appendToError(LibNameOrErr.takeError(), "when reading DT_NEEDED");
582  }
583  DestStub->NeededLibs.push_back(std::string(*LibNameOrErr));
584  }
585 
586  // Populate Symbols from .dynsym table and dynamic string table.
587  Expected<uint64_t> SymCount = ElfFile.getDynSymtabSize();
588  if (!SymCount)
589  return SymCount.takeError();
590  if (*SymCount > 0) {
591  // Get pointer to in-memory location of .dynsym section.
592  Expected<const uint8_t *> DynSymPtr =
593  ElfFile.toMappedAddr(DynEnt.DynSymAddr);
594  if (!DynSymPtr)
595  return appendToError(DynSymPtr.takeError(),
596  "when locating .dynsym section contents");
597  Elf_Sym_Range DynSyms = ArrayRef<Elf_Sym>(
598  reinterpret_cast<const Elf_Sym *>(*DynSymPtr), *SymCount);
599  Error SymReadError = populateSymbols<ELFT>(*DestStub, DynSyms, DynStr);
600  if (SymReadError)
601  return appendToError(std::move(SymReadError),
602  "when reading dynamic symbols");
603  }
604 
605  return std::move(DestStub);
606 }
607 
608 /// This function opens a file for writing and then writes a binary ELF stub to
609 /// the file.
610 ///
611 /// @param FilePath File path for writing the ELF binary.
612 /// @param Stub Source ELFStub to generate a binary ELF stub from.
613 template <class ELFT>
614 static Error writeELFBinaryToFile(StringRef FilePath, const ELFStub &Stub,
615  bool WriteIfChanged) {
616  ELFStubBuilder<ELFT> Builder{Stub};
617  // Write Stub to memory first.
618  std::vector<uint8_t> Buf(Builder.getSize());
619  Builder.write(Buf.data());
620 
621  if (WriteIfChanged) {
622  if (ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrError =
623  MemoryBuffer::getFile(FilePath)) {
624  // Compare Stub output with existing Stub file.
625  // If Stub file unchanged, abort updating.
626  if ((*BufOrError)->getBufferSize() == Builder.getSize() &&
627  !memcmp((*BufOrError)->getBufferStart(), Buf.data(),
628  Builder.getSize()))
629  return Error::success();
630  }
631  }
632 
634  FileOutputBuffer::create(FilePath, Builder.getSize());
635  if (!BufOrError)
637  toString(BufOrError.takeError()) +
638  " when trying to open `" + FilePath +
639  "` for writing");
640 
641  // Write binary to file.
642  std::unique_ptr<FileOutputBuffer> FileBuf = std::move(*BufOrError);
643  memcpy(FileBuf->getBufferStart(), Buf.data(), Buf.size());
644 
645  return FileBuf->commit();
646 }
647 
650  if (!BinOrErr) {
651  return BinOrErr.takeError();
652  }
653 
654  Binary *Bin = BinOrErr->get();
655  if (auto Obj = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
656  return buildStub(*Obj);
657  } else if (auto Obj = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
658  return buildStub(*Obj);
659  } else if (auto Obj = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
660  return buildStub(*Obj);
661  } else if (auto Obj = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
662  return buildStub(*Obj);
663  }
664  return createStringError(errc::not_supported, "unsupported binary format");
665 }
666 
667 // This function wraps the ELFT writeELFBinaryToFile() so writeBinaryStub()
668 // can be called without having to use ELFType templates directly.
669 Error writeBinaryStub(StringRef FilePath, const ELFStub &Stub,
670  ELFTarget OutputFormat, bool WriteIfChanged) {
671  if (OutputFormat == ELFTarget::ELF32LE)
672  return writeELFBinaryToFile<ELF32LE>(FilePath, Stub, WriteIfChanged);
673  if (OutputFormat == ELFTarget::ELF32BE)
674  return writeELFBinaryToFile<ELF32BE>(FilePath, Stub, WriteIfChanged);
675  if (OutputFormat == ELFTarget::ELF64LE)
676  return writeELFBinaryToFile<ELF64LE>(FilePath, Stub, WriteIfChanged);
677  if (OutputFormat == ELFTarget::ELF64BE)
678  return writeELFBinaryToFile<ELF64BE>(FilePath, Stub, WriteIfChanged);
679  llvm_unreachable("invalid binary output target");
680 }
681 
682 } // end namespace elfabi
683 } // end namespace llvm
llvm::elfabi::writeBinaryStub
Error writeBinaryStub(StringRef FilePath, const ELFStub &Stub, ELFTarget OutputFormat, bool WriteIfChanged=false)
Attempt to write a binary ELF stub.
Definition: ELFObjHandler.cpp:669
MemoryBuffer.h
llvm::ELF::ET_DYN
@ ET_DYN
Definition: ELF.h:117
llvm::alignTo
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:158
llvm::errc::invalid_argument
@ invalid_argument
llvm::elfabi::ELFSymbolType
ELFSymbolType
Definition: ELFStub.h:27
llvm::elfabi::ELFSymbol
Definition: ELFStub.h:37
MathExtras.h
llvm
This class represents lattice values for constants.
Definition: AllocatorList.h:23
llvm::ELF::EI_MAG0
@ EI_MAG0
Definition: ELF.h:47
llvm::ELF::ELFCLASS64
@ ELFCLASS64
Definition: ELF.h:326
llvm::ELF::EI_MAG3
@ EI_MAG3
Definition: ELF.h:50
llvm::elfabi::terminatedSubstr
static Expected< StringRef > terminatedSubstr(StringRef Str, size_t Offset)
This function behaves similarly to StringRef::substr(), but attempts to terminate the returned String...
Definition: ELFObjHandler.cpp:345
WriteIfChanged
static cl::opt< bool > WriteIfChanged("write-if-changed", cl::desc("Only write output if it changed"))
llvm::raw_string_ostream
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:614
llvm::toString
std::string toString(Error E)
Write all error messages (if any) in E to a string.
Definition: Error.h:991
llvm::StringRef::npos
static constexpr size_t npos
Definition: StringRef.h:59
llvm::StringRef::find
LLVM_NODISCARD size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:318
llvm::elfabi::appendToError
Error appendToError(Error Err, StringRef After)
This function takes an error, and appends a string of text to the end of that error.
Definition: ELFObjHandler.cpp:363
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1168
llvm::elfabi::DynamicEntries::StrTabAddr
uint64_t StrTabAddr
Definition: ELFObjHandler.cpp:34
llvm::Error::success
static ErrorSuccess success()
Create a success value.
Definition: Error.h:332
llvm::elfabi::DynamicEntries::GnuHash
Optional< uint64_t > GnuHash
Definition: ELFObjHandler.cpp:42
llvm::object::createError
static Error createError(const Twine &Err)
Definition: ELF.h:84
llvm::ELF::EI_DATA
@ EI_DATA
Definition: ELF.h:52
Content
T Content
Definition: ELFObjHandler.cpp:90
memcmp
Merge contiguous icmps into a memcmp
Definition: MergeICmps.cpp:928
Error.h
llvm::ELF::SHF_ALLOC
@ SHF_ALLOC
Definition: ELF.h:927
Errc.h
llvm::ELF::SHT_STRTAB
@ SHT_STRTAB
Definition: ELF.h:851
llvm::dyn_cast
LLVM_NODISCARD std::enable_if_t< !is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type > dyn_cast(const Y &Val)
Definition: Casting.h:334
llvm::object::ELFFile::getDynSymtabSize
Expected< uint64_t > getDynSymtabSize() const
This function determines the number of dynamic symbols.
Definition: ELF.h:692
llvm::elfabi::DynamicEntries
Definition: ELFObjHandler.cpp:33
llvm::Optional< uint64_t >
T
#define T
Definition: Mips16ISelLowering.cpp:341
Offset
uint64_t Offset
Definition: ELFObjHandler.cpp:81
FileOutputBuffer.h
llvm::Expected
Tagged union holding either a T or a Error.
Definition: APFloat.h:42
llvm::dwarf::Tag
Tag
Definition: Dwarf.h:104
llvm::consumeError
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1006
llvm::Data
@ Data
Definition: SIMachineScheduler.h:56
llvm::ELF
Definition: ELF.h:26
llvm::MemoryBufferRef
Definition: MemoryBufferRef.h:22
llvm::ELF::STT_TLS
@ STT_TLS
Definition: ELF.h:1095
llvm::object::ELF32BE
ELFType< support::big, false > ELF32BE
Definition: ELFTypes.h:95
ELFObjHandler.h
llvm::ELF::SHN_UNDEF
@ SHN_UNDEF
Definition: ELF.h:834
llvm::Optional::hasValue
constexpr bool hasValue() const
Definition: Optional.h:286
llvm::StringRef::substr
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:612
llvm::elfabi::createELFSym
static ELFSymbol createELFSym(StringRef SymName, const typename ELFT::Sym &RawSym)
This function creates an ELFSymbol and populates all members using information from a binary ELFT::Sy...
Definition: ELFObjHandler.cpp:474
llvm::elfabi::DynamicEntries::DynSymAddr
uint64_t DynSymAddr
Definition: ELFObjHandler.cpp:39
StringTableBuilder.h
Process.h
llvm::object
Definition: ObjectFileTransformer.h:18
llvm::ELF::STV_PROTECTED
@ STV_PROTECTED
Definition: ELF.h:1110
llvm::ELF::EI_CLASS
@ EI_CLASS
Definition: ELF.h:51
llvm::elfabi::ELFSymbol::Weak
bool Weak
Definition: ELFStub.h:43
llvm::support::little
@ little
Definition: Endian.h:27
llvm::object::ELFObjectFile::getELFFile
const ELFFile< ELFT > & getELFFile() const
Definition: ELFObjectFile.h:436
llvm::elfabi::initELFHeader
static void initELFHeader(typename ELFT::Ehdr &ElfHeader, uint16_t Machine)
This initializes an ELF file header with information specific to a binary dynamic shared object.
Definition: ELFObjHandler.cpp:53
llvm::ELF::STT_NOTYPE
@ STT_NOTYPE
Definition: ELF.h:1089
llvm::elfabi::ELFStub
Definition: ELFStub.h:50
llvm::object::object_error::parse_failed
@ parse_failed
llvm::ELF::EI_MAG2
@ EI_MAG2
Definition: ELF.h:49
llvm::ELF::EI_OSABI
@ EI_OSABI
Definition: ELF.h:54
llvm::ELF::EI_MAG1
@ EI_MAG1
Definition: ELF.h:48
Info
Analysis containing CSE Info
Definition: CSEInfo.cpp:26
llvm::ELF::EV_CURRENT
@ EV_CURRENT
Definition: ELF.h:126
llvm::ELF::STV_DEFAULT
@ STV_DEFAULT
Definition: ELF.h:1107
Align
uint64_t Align
Definition: ELFObjHandler.cpp:83
llvm::object::ELF32LE
ELFType< support::little, false > ELF32LE
Definition: ELFTypes.h:94
llvm::ELF::EI_VERSION
@ EI_VERSION
Definition: ELF.h:53
llvm::object::ELF64BE
ELFType< support::big, true > ELF64BE
Definition: ELFTypes.h:97
llvm::elfabi::readELFFile
Expected< std::unique_ptr< ELFStub > > readELFFile(MemoryBufferRef Buf)
Attempt to read a binary ELF file from a MemoryBuffer.
Definition: ELFObjHandler.cpp:648
Index
uint32_t Index
Definition: ELFObjHandler.cpp:84
llvm::pdb::Unknown
@ Unknown
Definition: PDBTypes.h:395
Addr
uint64_t Addr
Definition: ELFObjHandler.cpp:80
llvm::object::ELF64LE
ELFType< support::little, true > ELF64LE
Definition: ELFTypes.h:96
llvm::ARM_AM::add
@ add
Definition: ARMAddressingModes.h:39
llvm::elfabi::writeELFBinaryToFile
static Error writeELFBinaryToFile(StringRef FilePath, const ELFStub &Stub, bool WriteIfChanged)
This function opens a file for writing and then writes a binary ELF stub to the file.
Definition: ELFObjHandler.cpp:614
move
compiles ldr LCPI1_0 ldr ldr mov lsr tst moveq r1 ldr LCPI1_1 and r0 bx lr It would be better to do something like to fold the shift into the conditional move
Definition: README.txt:546
llvm::object::ELFFile::toMappedAddr
Expected< const uint8_t * > toMappedAddr(uint64_t VAddr, WarningHandler WarnHandler=&defaultWarningHandler) const
Definition: ELF.cpp:558
llvm::ELF::STB_GLOBAL
@ STB_GLOBAL
Definition: ELF.h:1078
llvm::object::ELFFile::dynamicEntries
Expected< Elf_Dyn_Range > dynamicEntries() const
Definition: ELF.cpp:507
memcpy
<%struct.s * > cast struct s *S to sbyte *< sbyte * > sbyte uint cast struct s *agg result to sbyte *< sbyte * > sbyte uint cast struct s *memtmp to sbyte *< sbyte * > sbyte uint ret void llc ends up issuing two memcpy or custom lower memcpy(of small size) to be ldmia/stmia. I think option 2 is better but the current register allocator cannot allocate a chunk of registers at a time. A feasible temporary solution is to use specific physical registers at the lowering time for small(<
ELFTypes.h
NoBits
bool NoBits
Definition: ELFObjHandler.cpp:85
Builder
assume Assume Builder
Definition: AssumeBundleBuilder.cpp:643
llvm::ELF::ELFCLASS32
@ ELFCLASS32
Definition: ELF.h:325
llvm::ArrayRef
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: APInt.h:32
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:57
llvm::object::Binary
Definition: Binary.h:32
llvm::errc::not_supported
@ not_supported
llvm_unreachable
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:136
llvm::elfabi::DynamicEntries::ElfHash
Optional< uint64_t > ElfHash
Definition: ELFObjHandler.cpp:41
llvm::Expected::get
reference get()
Returns a reference to the stored T value.
Definition: Error.h:537
uint32_t
S
add sub stmia L5 ldr r0 bl L_printf $stub Instead of a and a wouldn t it be better to do three moves *Return an aggregate type is even return S
Definition: README.txt:210
llvm::ELF::STB_WEAK
@ STB_WEAK
Definition: ELF.h:1079
llvm::elfabi::populateDynamic
static Error populateDynamic(DynamicEntries &Dyn, typename ELFT::DynRange DynTable)
This function populates a DynamicEntries struct using an ELFT::DynRange.
Definition: ELFObjHandler.cpp:379
Size
uint64_t Size
Definition: ELFObjHandler.cpp:82
ELFObjectFile.h
llvm::object::ELFFile::getHeader
const Elf_Ehdr & getHeader() const
Definition: ELF.h:192
llvm::createStringError
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1202
uint16_t
llvm::elfabi::ELFStub::Symbols
std::set< ELFSymbol > Symbols
Definition: ELFStub.h:57
llvm::Error
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
llvm::ELF::SHT_DYNSYM
@ SHT_DYNSYM
Definition: ELF.h:859
llvm::TargetStackID::Value
Value
Definition: TargetFrameLowering.h:27
llvm::StringTableBuilder
Utility for building string tables with deduplicated suffixes.
Definition: StringTableBuilder.h:23
llvm::ELF::ELFDATA2MSB
@ ELFDATA2MSB
Definition: ELF.h:333
llvm::ELF::ElfMagic
static const char ElfMagic[]
Definition: ELF.h:43
llvm::Expected::takeError
Error takeError()
Take ownership of the stored error.
Definition: Error.h:557
llvm::elfabi::buildStub
static Expected< std::unique_ptr< ELFStub > > buildStub(const ELFObjectFile< ELFT > &ElfObj)
Returns a new ELFStub with all members populated from an ELFObjectFile.
Definition: ELFObjHandler.cpp:530
Binary.h
llvm::ELF::STT_OBJECT
@ STT_OBJECT
Definition: ELF.h:1090
llvm::FileOutputBuffer::create
static Expected< std::unique_ptr< FileOutputBuffer > > create(StringRef FilePath, size_t Size, unsigned Flags=0, unsigned UserID=0, unsigned GroupID=0)
Factory method to create an OutputBuffer object which manages a read/write buffer of the specified si...
Definition: FileOutputBuffer.cpp:174
llvm::elfabi::DynamicEntries::StrSize
uint64_t StrSize
Definition: ELFObjHandler.cpp:35
Machine
COFF::MachineTypes Machine
Definition: COFFYAML.cpp:365
llvm::ErrorOr
Represents either an error or a value T.
Definition: ErrorOr.h:56
llvm::object::createBinary
Expected< std::unique_ptr< Binary > > createBinary(MemoryBufferRef Source, LLVMContext *Context=nullptr, bool InitContent=true)
Create a Binary from Source, autodetecting the file type.
Definition: Binary.cpp:46
Name
std::string Name
Definition: ELFObjHandler.cpp:78
llvm::elfabi::ELFTarget
ELFTarget
Definition: ELFObjHandler.h:27
llvm::elfabi::populateSymbols
static Error populateSymbols(ELFStub &TargetStub, const typename ELFT::SymRange DynSym, StringRef DynStr)
This function populates an ELFStub with symbols using information read from an ELF binary.
Definition: ELFObjHandler.cpp:501
llvm::MemoryBuffer::getFile
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
Definition: MemoryBuffer.cpp:245
llvm::elfabi::convertInfoToType
static ELFSymbolType convertInfoToType(uint8_t Info)
This function extracts symbol type from a symbol's st_info member and maps it to an ELFSymbolType enu...
Definition: ELFObjHandler.cpp:452
llvm::ELF::STT_FUNC
@ STT_FUNC
Definition: ELF.h:1091
llvm::elfabi::DynamicEntries::SONameOffset
Optional< uint64_t > SONameOffset
Definition: ELFObjHandler.cpp:36
ELFStub.h
llvm::object::ELFObjectFile
Definition: ELFObjectFile.h:228
llvm::raw_string_ostream::str
std::string & str()
Flushes the stream contents to the target string and returns the string's reference.
Definition: raw_ostream.h:632
llvm::ELF::SHT_DYNAMIC
@ SHT_DYNAMIC
Definition: ELF.h:854
llvm::Value
LLVM Value Representation.
Definition: Value.h:75
llvm::ELF::ELFOSABI_NONE
@ ELFOSABI_NONE
Definition: ELF.h:338
llvm::object::ELFFile
Definition: ELF.h:98
llvm::ELF::ELFDATA2LSB
@ ELFDATA2LSB
Definition: ELF.h:332
llvm::object::ELFFile::program_headers
Expected< Elf_Phdr_Range > program_headers() const
Iterate over program header table.
Definition: ELF.h:284
Shdr
Elf_Shdr Shdr
Definition: ELFObjHandler.cpp:79
write
static void write(bool isBE, void *P, T V)
Definition: RuntimeDyldELF.cpp:37
llvm::elfabi::DynamicEntries::NeededLibNames
std::vector< uint64_t > NeededLibNames
Definition: ELFObjHandler.cpp:37