main.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include "wasm_export.h"
  6. #include "bh_read_file.h"
  7. #include "bh_getopt.h"
  8. #include "assert.h"
  9. typedef void (*wasm_func_type_callback_t)(const wasm_import_t *import_type);
  10. const char *import_func_names[] = { "import_func1", "import_func2" };
  11. void
  12. import_func_type_callback(const wasm_import_t *import_type)
  13. {
  14. int ret = 0;
  15. for (uint32_t i = 0;
  16. i < sizeof(import_func_names) / sizeof(import_func_names[0]); i++) {
  17. if (strcmp(import_type->name, import_func_names[i]) == 0) {
  18. ret = 1;
  19. break;
  20. }
  21. }
  22. assert(ret == 1);
  23. return;
  24. }
  25. /* Iterate over all import functions in the module */
  26. void
  27. wasm_runtime_for_each_import_func(const wasm_module_t module,
  28. wasm_func_type_callback_t callback)
  29. {
  30. int32_t import_count = wasm_runtime_get_import_count(module);
  31. if (import_count <= 0)
  32. return;
  33. if (callback == NULL)
  34. return;
  35. for (int32_t i = 0; i < import_count; ++i) {
  36. wasm_import_t import_type;
  37. wasm_runtime_get_import_type(module, i, &import_type);
  38. if (import_type.kind != WASM_IMPORT_EXPORT_KIND_FUNC) {
  39. continue;
  40. }
  41. callback(&import_type);
  42. }
  43. }
  44. int
  45. main(int argc, char *argv_main[])
  46. {
  47. static char global_heap_buf[512 * 1024];
  48. wasm_module_t module = NULL;
  49. uint32 buf_size;
  50. char *buffer = NULL;
  51. const char *wasm_path = "wasm-apps/test.wasm";
  52. char error_buf[128];
  53. RuntimeInitArgs init_args;
  54. memset(&init_args, 0, sizeof(RuntimeInitArgs));
  55. init_args.mem_alloc_type = Alloc_With_Pool;
  56. init_args.mem_alloc_option.pool.heap_buf = global_heap_buf;
  57. init_args.mem_alloc_option.pool.heap_size = sizeof(global_heap_buf);
  58. if (!wasm_runtime_full_init(&init_args)) {
  59. printf("Init runtime environment failed.\n");
  60. return -1;
  61. }
  62. buffer = bh_read_file_to_buffer(wasm_path, &buf_size);
  63. if (!buffer) {
  64. printf("Open wasm app file [%s] failed.\n", wasm_path);
  65. goto fail;
  66. }
  67. module = wasm_runtime_load((uint8 *)buffer, buf_size, error_buf,
  68. sizeof(error_buf));
  69. if (!module) {
  70. printf("Load wasm app file [%s] failed.\n", wasm_path);
  71. goto fail;
  72. }
  73. wasm_runtime_for_each_import_func(module, import_func_type_callback);
  74. fail:
  75. if (module)
  76. wasm_runtime_unload(module);
  77. if (buffer)
  78. BH_FREE(buffer);
  79. wasm_runtime_destroy();
  80. return 0;
  81. }