api_hashtable.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #pragma once
  2. #include <flipper_application/elf/elf_api_interface.h>
  3. #include <stdint.h>
  4. #ifdef __cplusplus
  5. extern "C" {
  6. #endif
  7. /**
  8. * @brief Symbol table entry
  9. */
  10. struct sym_entry {
  11. uint32_t hash;
  12. uint32_t address;
  13. };
  14. /**
  15. * @brief Resolver for API entries using a pre-sorted table with hashes
  16. * @param interface pointer to HashtableApiInterface
  17. * @param name function name
  18. * @param address output for function address
  19. * @return true if the table contains a function
  20. */
  21. bool elf_resolve_from_hashtable(
  22. const ElfApiInterface* interface,
  23. const char* name,
  24. Elf32_Addr* address);
  25. #ifdef __cplusplus
  26. }
  27. #include <array>
  28. #include <algorithm>
  29. /**
  30. * @brief HashtableApiInterface is an implementation of ElfApiInterface
  31. * that uses a hash table to resolve function addresses.
  32. * table_cbegin and table_cend must point to a sorted array of sym_entry
  33. */
  34. struct HashtableApiInterface : public ElfApiInterface {
  35. const sym_entry *table_cbegin, *table_cend;
  36. };
  37. #define API_METHOD(x, ret_type, args_type) \
  38. sym_entry { \
  39. .hash = elf_gnu_hash(#x), .address = (uint32_t)(static_cast<ret_type(*) args_type>(x)) \
  40. }
  41. #define API_VARIABLE(x, var_type) \
  42. sym_entry { .hash = elf_gnu_hash(#x), .address = (uint32_t)(&(x)), }
  43. constexpr bool operator<(const sym_entry& k1, const sym_entry& k2) {
  44. return k1.hash < k2.hash;
  45. }
  46. /**
  47. * @brief Calculate hash for a string using the ELF GNU hash algorithm
  48. * @param s string to calculate hash for
  49. * @return hash value
  50. */
  51. constexpr uint32_t elf_gnu_hash(const char* s) {
  52. uint32_t h = 0x1505;
  53. for(unsigned char c = *s; c != '\0'; c = *++s) {
  54. h = (h << 5) + h + c;
  55. }
  56. return h;
  57. }
  58. /* Compile-time check for hash collisions in API table.
  59. * Usage: static_assert(!has_hash_collisions(api_methods), "Hash collision detected");
  60. */
  61. template <std::size_t N>
  62. constexpr bool has_hash_collisions(const std::array<sym_entry, N>& api_methods) {
  63. for(std::size_t i = 0; i < (N - 1); ++i) {
  64. if(api_methods[i].hash == api_methods[i + 1].hash) {
  65. return true;
  66. }
  67. }
  68. return false;
  69. }
  70. #endif