wasm_dlfcn.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include "bh_platform.h"
  6. static bool sort_flag = false;
  7. typedef struct NativeSymbol {
  8. const char *symbol;
  9. void *func_ptr;
  10. } NativeSymbol;
  11. static bool
  12. sort_symbol_ptr(NativeSymbol *ptr, int len)
  13. {
  14. int i, j;
  15. NativeSymbol temp;
  16. for (i = 0; i < len - 1; ++i) {
  17. for (j = i + 1; j < len; ++j) {
  18. if (strcmp((ptr+i)->symbol, (ptr+j)->symbol) > 0) {
  19. temp = ptr[i];
  20. ptr[i] = ptr[j];
  21. ptr[j] = temp;
  22. }
  23. }
  24. }
  25. return true;
  26. }
  27. static void *
  28. lookup_symbol(NativeSymbol *ptr, int len, const char *symbol)
  29. {
  30. int low = 0, mid, ret;
  31. int high = len - 1;
  32. while (low <= high) {
  33. mid = (low + high) / 2;
  34. ret = strcmp(symbol, ptr[mid].symbol);
  35. if (ret == 0)
  36. return ptr[mid].func_ptr;
  37. else if (ret < 0)
  38. high = mid - 1;
  39. else
  40. low = mid + 1;
  41. }
  42. return NULL;
  43. }
  44. int
  45. get_base_lib_export_apis(NativeSymbol **p_base_lib_apis);
  46. int
  47. get_ext_lib_export_apis(NativeSymbol **p_ext_lib_apis);
  48. static NativeSymbol *base_native_symbol_defs;
  49. static NativeSymbol *ext_native_symbol_defs;
  50. static int base_native_symbol_len;
  51. static int ext_native_symbol_len;
  52. void *
  53. wasm_dlsym(void *handle, const char *symbol)
  54. {
  55. void *ret;
  56. if (!sort_flag) {
  57. base_native_symbol_len = get_base_lib_export_apis(&base_native_symbol_defs);
  58. ext_native_symbol_len = get_ext_lib_export_apis(&ext_native_symbol_defs);
  59. if (base_native_symbol_len > 0)
  60. sort_symbol_ptr(base_native_symbol_defs, base_native_symbol_len);
  61. if (ext_native_symbol_len > 0)
  62. sort_symbol_ptr(ext_native_symbol_defs, ext_native_symbol_len);
  63. sort_flag = true;
  64. }
  65. if (!symbol)
  66. return NULL;
  67. if ((ret = lookup_symbol(base_native_symbol_defs, base_native_symbol_len,
  68. symbol))
  69. || (ret = lookup_symbol(ext_native_symbol_defs, ext_native_symbol_len,
  70. symbol)))
  71. return ret;
  72. return NULL;
  73. }