diff --git a/.github/workflows/coding_guidelines.yml b/.github/workflows/coding_guidelines.yml index 259e84fe5..17d60ac43 100644 --- a/.github/workflows/coding_guidelines.yml +++ b/.github/workflows/coding_guidelines.yml @@ -16,7 +16,7 @@ concurrency: jobs: compliance_job: - runs-on: ubuntu-latest + runs-on: ubuntu-20.04 steps: - name: checkout uses: actions/checkout@v3 diff --git a/.github/workflows/compilation_on_android_ubuntu.yml b/.github/workflows/compilation_on_android_ubuntu.yml index 927ef4d75..6b653b501 100644 --- a/.github/workflows/compilation_on_android_ubuntu.yml +++ b/.github/workflows/compilation_on_android_ubuntu.yml @@ -65,6 +65,7 @@ env: THREADS_TEST_OPTIONS: "-s spec -b -p -P" X86_32_TARGET_TEST_OPTIONS: "-m x86_32 -P" WASI_TEST_OPTIONS: "-s wasi_certification -w" + WAMR_COMPILER_TEST_OPTIONS: "-s wamr_compiler -b -P" jobs: build_llvm_libraries_on_ubuntu_2204: @@ -150,9 +151,7 @@ jobs: exclude: # uncompatiable feature and platform # uncompatiable mode and feature - # MULTI_MODULE only on INTERP mode - - make_options_run_mode: $AOT_BUILD_OPTIONS - make_options_feature: "-DWAMR_BUILD_MULTI_MODULE=1" + # MULTI_MODULE only on INTERP mode and AOT mode - make_options_run_mode: $FAST_JIT_BUILD_OPTIONS make_options_feature: "-DWAMR_BUILD_MULTI_MODULE=1" - make_options_run_mode: $LLVM_LAZY_JIT_BUILD_OPTIONS @@ -328,7 +327,12 @@ jobs: working-directory: samples/wasm-c-api build_samples_others: - needs: [build_iwasm] + needs: + [ + build_iwasm, + build_llvm_libraries_on_ubuntu_2204, + build_wamrc, + ] runs-on: ${{ matrix.os }} strategy: matrix: @@ -341,6 +345,9 @@ jobs: [ "https://github.com/WebAssembly/wabt/releases/download/1.0.31/wabt-1.0.31-ubuntu.tar.gz", ] + include: + - os: ubuntu-22.04 + llvm_cache_key: ${{ needs.build_llvm_libraries_on_ubuntu_2204.outputs.cache_key }} steps: - name: checkout uses: actions/checkout@v3 @@ -358,7 +365,23 @@ jobs: sudo wget ${{ matrix.wabt_release }} sudo tar -xzf wabt-1.0.31-*.tar.gz sudo mv wabt-1.0.31 wabt - + - name: Get LLVM libraries + id: retrieve_llvm_libs + uses: actions/cache@v3 + with: + path: | + ./core/deps/llvm/build/bin + ./core/deps/llvm/build/include + ./core/deps/llvm/build/lib + ./core/deps/llvm/build/libexec + ./core/deps/llvm/build/share + key: ${{ matrix.llvm_cache_key }} + - name: Build wamrc + run: | + mkdir build && cd build + cmake .. + cmake --build . --config Release --parallel 4 + working-directory: wamr-compiler - name: Build Sample [basic] run: | cd samples/basic @@ -385,9 +408,10 @@ jobs: run: | cd samples/multi-module mkdir build && cd build - cmake .. + cmake .. -DWAMR_BUILD_AOT=1 cmake --build . --config Release --parallel 4 - ./multi_module + ./multi_module mC.wasm + ./multi_module mC.aot - name: Build Sample [spawn-thread] run: | @@ -457,6 +481,10 @@ jobs: - os: ubuntu-22.04 llvm_cache_key: ${{ needs.build_llvm_libraries_on_ubuntu_2204.outputs.cache_key }} ubuntu_version: "22.04" + - os: ubuntu-22.04 + llvm_cache_key: ${{ needs.build_llvm_libraries_on_ubuntu_2204.outputs.cache_key }} + running_mode: aot + test_option: $WAMR_COMPILER_TEST_OPTIONS exclude: # uncompatiable modes and features # classic-interp and fast-interp don't support simd @@ -464,9 +492,7 @@ jobs: test_option: $SIMD_TEST_OPTIONS - running_mode: "fast-interp" test_option: $SIMD_TEST_OPTIONS - # aot and jit don't support multi module - - running_mode: "aot" - test_option: $MULTI_MODULES_TEST_OPTIONS + # llvm jit doesn't support multi module - running_mode: "jit" test_option: $MULTI_MODULES_TEST_OPTIONS # fast-jit doesn't support multi module, simd diff --git a/.github/workflows/compilation_on_macos.yml b/.github/workflows/compilation_on_macos.yml index aaa97d038..aac16898b 100644 --- a/.github/workflows/compilation_on_macos.yml +++ b/.github/workflows/compilation_on_macos.yml @@ -133,13 +133,11 @@ jobs: exclude: # uncompatiable feature and platform # uncompatiable mode and feature - # MULTI_MODULE only on INTERP mode + # MULTI_MODULE only on INTERP mode and AOT mode - make_options_run_mode: $LLVM_LAZY_JIT_BUILD_OPTIONS make_options_feature: "-DWAMR_BUILD_MULTI_MODULE=1" - make_options_run_mode: $LLVM_EAGER_JIT_BUILD_OPTIONS make_options_feature: "-DWAMR_BUILD_MULTI_MODULE=1" - - make_options_run_mode: $AOT_BUILD_OPTIONS - make_options_feature: "-DWAMR_BUILD_MULTI_MODULE=1" # SIMD only on JIT/AOT mode - make_options_run_mode: $CLASSIC_INTERP_BUILD_OPTIONS make_options_feature: "-DWAMR_BUILD_SIMD=1" @@ -245,7 +243,7 @@ jobs: working-directory: samples/wasm-c-api build_samples_others: - needs: [build_iwasm] + needs: [build_iwasm, build_wamrc] runs-on: ${{ matrix.os }} strategy: matrix: @@ -304,7 +302,7 @@ jobs: mkdir build && cd build cmake .. cmake --build . --config Release --parallel 4 - ./multi_module + ./multi_module mC.wasm - name: Build Sample [spawn-thread] run: | diff --git a/.github/workflows/compilation_on_sgx.yml b/.github/workflows/compilation_on_sgx.yml index dd6317067..0d19d83ad 100644 --- a/.github/workflows/compilation_on_sgx.yml +++ b/.github/workflows/compilation_on_sgx.yml @@ -101,9 +101,6 @@ jobs: platform: [linux-sgx] exclude: # uncompatiable mode and feature - # MULTI_MODULE only on INTERP mode - - make_options_run_mode: $AOT_BUILD_OPTIONS - make_options_feature: "-DWAMR_BUILD_MULTI_MODULE=1" # MINI_LOADER only on INTERP mode - make_options_run_mode: $AOT_BUILD_OPTIONS make_options_feature: "-DWAMR_BUILD_MINI_LOADER=1" diff --git a/.github/workflows/nightly_run.yml b/.github/workflows/nightly_run.yml index adedd1ef7..bef639792 100644 --- a/.github/workflows/nightly_run.yml +++ b/.github/workflows/nightly_run.yml @@ -8,9 +8,11 @@ on: types: - opened - synchronize - #running nightly pipeline if you're changing it + # running nightly pipeline if you're changing it + # stress tests are run only in nightly at the moment, so running them in they are changed paths: - ".github/workflows/nightly_run.yml" + - "core/iwasm/libraries/lib-wasi-threads/stress-test/**" # midnight UTC schedule: @@ -125,9 +127,7 @@ jobs: exclude: # uncompatiable feature and platform # uncompatiable mode and feature - # MULTI_MODULE only on INTERP mode - - make_options_run_mode: $AOT_BUILD_OPTIONS - make_options_feature: "-DWAMR_BUILD_MULTI_MODULE=1" + # MULTI_MODULE only on INTERP mode and AOT mode - make_options_run_mode: $FAST_JIT_BUILD_OPTIONS make_options_feature: "-DWAMR_BUILD_MULTI_MODULE=1" - make_options_run_mode: $LLVM_LAZY_JIT_BUILD_OPTIONS @@ -250,7 +250,7 @@ jobs: exclude: # uncompatiable feature and platform # uncompatiable mode and feature - # MULTI_MODULE only on INTERP mode + # MULTI_MODULE only on INTERP mode and AOT mode - make_options_run_mode: $FAST_JIT_BUILD_OPTIONS make_options_feature: "-DWAMR_BUILD_MULTI_MODULE=1" # SIMD only on JIT/AOT mode @@ -380,7 +380,12 @@ jobs: working-directory: samples/wasm-c-api build_samples_others: - needs: [build_iwasm] + needs: + [ + build_iwasm, + build_llvm_libraries_on_ubuntu_2004, + build_wamrc, + ] runs-on: ${{ matrix.os }} strategy: matrix: @@ -393,6 +398,9 @@ jobs: [ "https://github.com/WebAssembly/wabt/releases/download/1.0.31/wabt-1.0.31-ubuntu.tar.gz", ] + include: + - os: ubuntu-20.04 + llvm_cache_key: ${{ needs.build_llvm_libraries_on_ubuntu_2004.outputs.cache_key }} steps: - name: checkout uses: actions/checkout@v3 @@ -409,6 +417,26 @@ jobs: sudo wget ${{ matrix.wabt_release }} sudo tar -xzf wabt-1.0.31-*.tar.gz sudo mv wabt-1.0.31 wabt + + - name: Get LLVM libraries + id: retrieve_llvm_libs + uses: actions/cache@v3 + with: + path: | + ./core/deps/llvm/build/bin + ./core/deps/llvm/build/include + ./core/deps/llvm/build/lib + ./core/deps/llvm/build/libexec + ./core/deps/llvm/build/share + key: ${{ matrix.llvm_cache_key }} + + - name: Build wamrc + run: | + mkdir build && cd build + cmake -D WAMR_BUILD_SANITIZER="${{matrix.sanitizer}}" .. + cmake --build . --config Release --parallel 4 + working-directory: wamr-compiler + - name: Build Sample [basic] run: | cd samples/basic @@ -432,9 +460,10 @@ jobs: run: | cd samples/multi-module mkdir build && cd build - cmake .. + cmake .. -DWAMR_BUILD_AOT=1 cmake --build . --config Release --parallel 4 - ./multi_module + ./multi_module mC.wasm + ./multi_module mC.aot - name: Build Sample [spawn-thread] run: | cd samples/spawn-thread @@ -522,9 +551,7 @@ jobs: test_option: $SIMD_TEST_OPTIONS - running_mode: "fast-interp" test_option: $SIMD_TEST_OPTIONS - # aot and jit don't support multi module - - running_mode: "aot" - test_option: $MULTI_MODULES_TEST_OPTIONS + # llvm jit doesn't support multi module - running_mode: "jit" test_option: $MULTI_MODULES_TEST_OPTIONS # fast-jit doesn't support multi module, simd @@ -629,4 +656,4 @@ jobs: timeout-minutes: 40 if: env.TEST_ON_X86_32 == 'true' run: ./test_wamr.sh ${{ env.X86_32_TARGET_TEST_OPTIONS }} ${{ matrix.test_option }} -t ${{ matrix.running_mode }} - working-directory: ./tests/wamr-test-suites \ No newline at end of file + working-directory: ./tests/wamr-test-suites diff --git a/build-scripts/config_common.cmake b/build-scripts/config_common.cmake index 0e27e0c09..210f2d788 100644 --- a/build-scripts/config_common.cmake +++ b/build-scripts/config_common.cmake @@ -273,6 +273,13 @@ else () add_definitions (-DWASM_DISABLE_STACK_HW_BOUND_CHECK=0) endif () endif () +if (WAMR_DISABLE_WAKEUP_BLOCKING_OP EQUAL 1) + add_definitions (-DWASM_DISABLE_WAKEUP_BLOCKING_OP=1) + message (" Wakeup of blocking operations disabled") +else () + add_definitions (-DWASM_DISABLE_WAKEUP_BLOCKING_OP=0) + message (" Wakeup of blocking operations enabled") +endif () if (WAMR_BUILD_SIMD EQUAL 1) if (NOT WAMR_BUILD_TARGET MATCHES "RISCV64.*") add_definitions (-DWASM_ENABLE_SIMD=1) diff --git a/core/iwasm/aot/aot_loader.c b/core/iwasm/aot/aot_loader.c index 0ce2cf9da..6575c8aca 100644 --- a/core/iwasm/aot/aot_loader.c +++ b/core/iwasm/aot/aot_loader.c @@ -558,6 +558,56 @@ str2uint32(const char *buf, uint32 *p_res); static bool str2uint64(const char *buf, uint64 *p_res); +#if WASM_ENABLE_MULTI_MODULE != 0 +static void * +aot_loader_resolve_function(const char *module_name, const char *function_name, + const AOTFuncType *expected_function_type, + char *error_buf, uint32 error_buf_size) +{ + WASMModuleCommon *module_reg; + void *function = NULL; + AOTExport *export = NULL; + AOTModule *module = NULL; + AOTFuncType *target_function_type = NULL; + + module_reg = wasm_runtime_find_module_registered(module_name); + if (!module_reg || module_reg->module_type != Wasm_Module_AoT) { + LOG_DEBUG("can not find a module named %s for function %s", module_name, + function_name); + set_error_buf(error_buf, error_buf_size, "unknown import"); + return NULL; + } + + module = (AOTModule *)module_reg; + export = loader_find_export(module_reg, module_name, function_name, + EXPORT_KIND_FUNC, error_buf, error_buf_size); + if (!export) { + return NULL; + } + + /* resolve function type and function */ + if (export->index < module->import_func_count) { + target_function_type = module->import_funcs[export->index].func_type; + function = module->import_funcs[export->index].func_ptr_linked; + } + else { + target_function_type = + module->func_types[module->func_type_indexes + [export->index - module->import_func_count]]; + function = + (module->func_ptrs[export->index - module->import_func_count]); + } + /* check function type */ + if (!wasm_type_equal(expected_function_type, target_function_type)) { + LOG_DEBUG("%s.%s failed the type check", module_name, function_name); + set_error_buf(error_buf, error_buf_size, "incompatible import type"); + return NULL; + } + return function; +} + +#endif /* end of WASM_ENABLE_MULTI_MODULE */ + static bool load_native_symbol_section(const uint8 *buf, const uint8 *buf_end, AOTModule *module, bool is_load_from_file_buf, @@ -1357,11 +1407,16 @@ load_import_funcs(const uint8 **p_buf, const uint8 *buf_end, AOTModule *module, bool is_load_from_file_buf, char *error_buf, uint32 error_buf_size) { - const char *module_name, *field_name; + char *module_name, *field_name; const uint8 *buf = *p_buf; AOTImportFunc *import_funcs; uint64 size; uint32 i; +#if WASM_ENABLE_MULTI_MODULE != 0 + AOTModule *sub_module = NULL; + AOTFunc *linked_func = NULL; + WASMType *declare_func_type = NULL; +#endif /* Allocate memory */ size = sizeof(AOTImportFunc) * (uint64)module->import_func_count; @@ -1377,17 +1432,46 @@ load_import_funcs(const uint8 **p_buf, const uint8 *buf_end, AOTModule *module, set_error_buf(error_buf, error_buf_size, "unknown type"); return false; } + +#if WASM_ENABLE_MULTI_MODULE != 0 + declare_func_type = module->func_types[import_funcs[i].func_type_index]; + read_string(buf, buf_end, module_name); + read_string(buf, buf_end, field_name); + + import_funcs[i].module_name = module_name; + import_funcs[i].func_name = field_name; + linked_func = wasm_native_resolve_symbol( + module_name, field_name, declare_func_type, + &import_funcs[i].signature, &import_funcs[i].attachment, + &import_funcs[i].call_conv_raw); + if (!linked_func) { + if (!wasm_runtime_is_built_in_module(module_name)) { + sub_module = (AOTModule *)wasm_runtime_load_depended_module( + (WASMModuleCommon *)module, module_name, error_buf, + error_buf_size); + if (!sub_module) { + return false; + } + } + linked_func = aot_loader_resolve_function( + module_name, field_name, declare_func_type, error_buf, + error_buf_size); + } + import_funcs[i].func_ptr_linked = linked_func; + import_funcs[i].func_type = declare_func_type; + +#else import_funcs[i].func_type = module->func_types[import_funcs[i].func_type_index]; read_string(buf, buf_end, import_funcs[i].module_name); read_string(buf, buf_end, import_funcs[i].func_name); - module_name = import_funcs[i].module_name; field_name = import_funcs[i].func_name; import_funcs[i].func_ptr_linked = wasm_native_resolve_symbol( module_name, field_name, import_funcs[i].func_type, &import_funcs[i].signature, &import_funcs[i].attachment, &import_funcs[i].call_conv_raw); +#endif #if WASM_ENABLE_LIBC_WASI != 0 if (!strcmp(import_funcs[i].module_name, "wasi_unstable") @@ -2871,6 +2955,7 @@ create_module(char *error_buf, uint32 error_buf_size) { AOTModule *module = loader_malloc(sizeof(AOTModule), error_buf, error_buf_size); + bh_list_status ret; if (!module) { return NULL; @@ -2878,6 +2963,13 @@ create_module(char *error_buf, uint32 error_buf_size) module->module_type = Wasm_Module_AoT; +#if WASM_ENABLE_MULTI_MODULE != 0 + module->import_module_list = &module->import_module_list_head; + ret = bh_list_init(module->import_module_list); + bh_assert(ret == BH_LIST_SUCCESS); +#endif + (void)ret; + return module; } @@ -3143,10 +3235,13 @@ aot_load_from_aot_file(const uint8 *buf, uint32 size, char *error_buf, if (!module) return NULL; + os_thread_jit_write_protect_np(false); /* Make memory writable */ if (!load(buf, size, module, error_buf, error_buf_size)) { aot_unload(module); return NULL; } + os_thread_jit_write_protect_np(true); /* Make memory executable */ + os_icache_flush(module->code, module->code_size); LOG_VERBOSE("Load module success.\n"); return module; @@ -3201,6 +3296,19 @@ aot_unload(AOTModule *module) if (module->const_str_set) bh_hash_map_destroy(module->const_str_set); +#if WASM_ENABLE_MULTI_MODULE != 0 + /* just release the sub module list */ + if (module->import_module_list) { + WASMRegisteredModule *node = + bh_list_first_elem(module->import_module_list); + while (node) { + WASMRegisteredModule *next = bh_list_elem_next(node); + bh_list_remove(module->import_module_list, node); + wasm_runtime_free(node); + node = next; + } + } +#endif if (module->code && !module->is_indirect_mode) { /* The layout is: literal size + literal + code (with plt table) */ diff --git a/core/iwasm/aot/aot_runtime.c b/core/iwasm/aot/aot_runtime.c index 55cf2d985..0799d625f 100644 --- a/core/iwasm/aot/aot_runtime.c +++ b/core/iwasm/aot/aot_runtime.c @@ -1091,6 +1091,9 @@ aot_instantiate(AOTModule *module, AOTModuleInstance *parent, uint8 *p; uint32 i, extra_info_offset; const bool is_sub_inst = parent != NULL; +#if WASM_ENABLE_MULTI_MODULE != 0 + bool ret = false; +#endif /* Check heap size */ heap_size = align_uint(heap_size, 8); @@ -1134,6 +1137,18 @@ aot_instantiate(AOTModule *module, AOTModuleInstance *parent, module_inst->e = (WASMModuleInstanceExtra *)((uint8 *)module_inst + extra_info_offset); +#if WASM_ENABLE_MULTI_MODULE != 0 + ((AOTModuleInstanceExtra *)module_inst->e)->sub_module_inst_list = + &((AOTModuleInstanceExtra *)module_inst->e)->sub_module_inst_list_head; + ret = wasm_runtime_sub_module_instantiate( + (WASMModuleCommon *)module, (WASMModuleInstanceCommon *)module_inst, + stack_size, heap_size, error_buf, error_buf_size); + if (!ret) { + LOG_DEBUG("build a sub module list failed"); + goto fail; + } +#endif + /* Initialize global info */ p = (uint8 *)module_inst + module_inst_struct_size + module_inst_mem_inst_size; @@ -1256,6 +1271,11 @@ aot_deinstantiate(AOTModuleInstance *module_inst, bool is_sub_inst) } #endif +#if WASM_ENABLE_MULTI_MODULE != 0 + wasm_runtime_sub_module_deinstantiate( + (WASMModuleInstanceCommon *)module_inst); +#endif + if (module_inst->tables) wasm_runtime_free(module_inst->tables); @@ -1411,10 +1431,43 @@ aot_call_function(WASMExecEnv *exec_env, AOTFunctionInstance *function, unsigned argc, uint32 argv[]) { AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst; - AOTFuncType *func_type = function->u.func.func_type; + AOTFuncType *func_type = function->is_import_func + ? function->u.func_import->func_type + : function->u.func.func_type; uint32 result_count = func_type->result_count; uint32 ext_ret_count = result_count > 1 ? result_count - 1 : 0; bool ret; + void *func_ptr = function->is_import_func + ? function->u.func_import->func_ptr_linked + : function->u.func.func_ptr; +#if WASM_ENABLE_MULTI_MODULE != 0 + bh_list *sub_module_list_node = NULL; + const char *sub_inst_name = NULL; + const char *func_name = function->u.func_import->module_name; + if (function->is_import_func) { + sub_module_list_node = + ((AOTModuleInstanceExtra *)module_inst->e)->sub_module_inst_list; + sub_module_list_node = bh_list_first_elem(sub_module_list_node); + while (sub_module_list_node) { + sub_inst_name = + ((AOTSubModInstNode *)sub_module_list_node)->module_name; + if (strcmp(sub_inst_name, func_name) == 0) { + exec_env = wasm_runtime_get_exec_env_singleton( + (WASMModuleInstanceCommon *)((AOTSubModInstNode *) + sub_module_list_node) + ->module_inst); + module_inst = (AOTModuleInstance *)exec_env->module_inst; + break; + } + sub_module_list_node = bh_list_elem_next(sub_module_list_node); + } + if (exec_env == NULL) { + wasm_runtime_set_exception((WASMModuleInstanceCommon *)module_inst, + "create singleton exec_env failed"); + return false; + } + } +#endif if (argc < func_type->param_cell_num) { char buf[108]; @@ -1436,8 +1489,7 @@ aot_call_function(WASMExecEnv *exec_env, AOTFunctionInstance *function, #endif /* func pointer was looked up previously */ - bh_assert(function->u.func.func_ptr != NULL); - + bh_assert(func_ptr != NULL); /* set thread handle and stack boundary */ wasm_exec_env_set_thread_info(exec_env); @@ -1546,8 +1598,8 @@ aot_call_function(WASMExecEnv *exec_env, AOTFunctionInstance *function, } #endif - ret = invoke_native_internal(exec_env, function->u.func.func_ptr, - func_type, NULL, NULL, argv, argc, argv); + ret = invoke_native_internal(exec_env, func_ptr, func_type, NULL, NULL, + argv, argc, argv); #if WASM_ENABLE_DUMP_CALL_STACK != 0 if (aot_copy_exception(module_inst, NULL)) { @@ -1939,7 +1991,10 @@ aot_invoke_native(WASMExecEnv *exec_env, uint32 func_idx, uint32 argc, void *attachment; char buf[96]; bool ret = false; - +#if WASM_ENABLE_MULTI_MODULE != 0 + bh_list *sub_module_list_node = NULL; + const char *sub_inst_name = NULL; +#endif bh_assert(func_idx < aot_module->import_func_count); import_func = aot_module->import_funcs + func_idx; @@ -1963,6 +2018,28 @@ aot_invoke_native(WASMExecEnv *exec_env, uint32 func_idx, uint32 argc, } else if (!import_func->call_conv_raw) { signature = import_func->signature; +#if WASM_ENABLE_MULTI_MODULE != 0 + sub_module_list_node = + ((AOTModuleInstanceExtra *)module_inst->e)->sub_module_inst_list; + sub_module_list_node = bh_list_first_elem(sub_module_list_node); + while (sub_module_list_node) { + sub_inst_name = + ((AOTSubModInstNode *)sub_module_list_node)->module_name; + if (strcmp(sub_inst_name, import_func->module_name) == 0) { + exec_env = wasm_runtime_get_exec_env_singleton( + (WASMModuleInstanceCommon *)((AOTSubModInstNode *) + sub_module_list_node) + ->module_inst); + break; + } + sub_module_list_node = bh_list_elem_next(sub_module_list_node); + } + if (exec_env == NULL) { + wasm_runtime_set_exception((WASMModuleInstanceCommon *)module_inst, + "create singleton exec_env failed"); + goto fail; + } +#endif ret = wasm_runtime_invoke_native(exec_env, func_ptr, func_type, signature, attachment, argv, argc, argv); @@ -2730,6 +2807,7 @@ aot_create_call_stack(struct WASMExecEnv *exec_env) total_len += \ wasm_runtime_dump_line_buf_impl(line_buf, print, &buf, &len); \ if ((!print) && buf && (len == 0)) { \ + exception_unlock(module_inst); \ return total_len; \ } \ } while (0) @@ -2752,6 +2830,7 @@ aot_dump_call_stack(WASMExecEnv *exec_env, bool print, char *buf, uint32 len) return 0; } + exception_lock(module_inst); snprintf(line_buf, sizeof(line_buf), "\n"); PRINT_OR_DUMP(); @@ -2760,6 +2839,7 @@ aot_dump_call_stack(WASMExecEnv *exec_env, bool print, char *buf, uint32 len) uint32 line_length, i; if (!bh_vector_get(module_inst->frames, n, &frame)) { + exception_unlock(module_inst); return 0; } @@ -2790,6 +2870,7 @@ aot_dump_call_stack(WASMExecEnv *exec_env, bool print, char *buf, uint32 len) } snprintf(line_buf, sizeof(line_buf), "\n"); PRINT_OR_DUMP(); + exception_unlock(module_inst); return total_len + 1; } diff --git a/core/iwasm/aot/aot_runtime.h b/core/iwasm/aot/aot_runtime.h index 4358e3079..35c78bfa0 100644 --- a/core/iwasm/aot/aot_runtime.h +++ b/core/iwasm/aot/aot_runtime.h @@ -90,6 +90,10 @@ typedef struct AOTFunctionInstance { typedef struct AOTModuleInstanceExtra { DefPointer(const uint32 *, stack_sizes); WASMModuleInstanceExtraCommon common; +#if WASM_ENABLE_MULTI_MODULE != 0 + bh_list sub_module_inst_list_head; + bh_list *sub_module_inst_list; +#endif } AOTModuleInstanceExtra; #if defined(BUILD_TARGET_X86_64) || defined(BUILD_TARGET_AMD_64) @@ -229,6 +233,12 @@ typedef struct AOTModule { WASIArguments wasi_args; bool import_wasi_api; #endif + +#if WASM_ENABLE_MULTI_MODULE != 0 + /* TODO: add mutex for mutli-thread? */ + bh_list import_module_list_head; + bh_list *import_module_list; +#endif #if WASM_ENABLE_DEBUG_AOT != 0 void *elf_hdr; uint32 elf_size; @@ -247,6 +257,10 @@ typedef struct AOTModule { #define AOTTableInstance WASMTableInstance #define AOTModuleInstance WASMModuleInstance +#if WASM_ENABLE_MULTI_MODULE != 0 +#define AOTSubModInstNode WASMSubModInstNode +#endif + /* Target info, read from ELF header of object file */ typedef struct AOTTargetInfo { /* Binary type, elf32l/elf32b/elf64l/elf64b */ diff --git a/core/iwasm/aot/arch/aot_reloc_aarch64.c b/core/iwasm/aot/arch/aot_reloc_aarch64.c index 4c46eaa00..b4bb6024a 100644 --- a/core/iwasm/aot/arch/aot_reloc_aarch64.c +++ b/core/iwasm/aot/arch/aot_reloc_aarch64.c @@ -53,7 +53,12 @@ get_target_symbol_map(uint32 *sym_num) return target_sym_map; } +#if (defined(__APPLE__) || defined(__MACH__)) && defined(__arm64__) +#define BUILD_TARGET_AARCH64_DEFAULT "arm64" +#else #define BUILD_TARGET_AARCH64_DEFAULT "aarch64v8" +#endif + void get_current_target(char *target_buf, uint32 target_buf_size) { diff --git a/core/iwasm/common/wasm_application.c b/core/iwasm/common/wasm_application.c index 795d65c8c..02999584f 100644 --- a/core/iwasm/common/wasm_application.c +++ b/core/iwasm/common/wasm_application.c @@ -231,7 +231,7 @@ wasm_application_execute_main(WASMModuleInstanceCommon *module_inst, int32 argc, char *argv[]) { bool ret; -#if (WASM_ENABLE_MEMORY_PROFILING != 0) || (WASM_ENABLE_DUMP_CALL_STACK != 0) +#if (WASM_ENABLE_MEMORY_PROFILING != 0) WASMExecEnv *exec_env; #endif @@ -251,14 +251,6 @@ wasm_application_execute_main(WASMModuleInstanceCommon *module_inst, int32 argc, if (ret) ret = wasm_runtime_get_exception(module_inst) == NULL; -#if WASM_ENABLE_DUMP_CALL_STACK != 0 - if (!ret) { - exec_env = wasm_runtime_get_exec_env_singleton(module_inst); - if (exec_env) - wasm_runtime_dump_call_stack(exec_env); - } -#endif - return ret; } diff --git a/core/iwasm/common/wasm_blocking_op.c b/core/iwasm/common/wasm_blocking_op.c new file mode 100644 index 000000000..25777c8d7 --- /dev/null +++ b/core/iwasm/common/wasm_blocking_op.c @@ -0,0 +1,92 @@ +/* + * Copyright (C) 2023 Midokura Japan KK. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include "wasm_runtime_common.h" + +#include "bh_platform.h" +#include "bh_common.h" +#include "bh_assert.h" + +#if WASM_ENABLE_THREAD_MGR != 0 && defined(OS_ENABLE_WAKEUP_BLOCKING_OP) + +#define LOCK(env) WASM_SUSPEND_FLAGS_LOCK((env)->wait_lock) +#define UNLOCK(env) WASM_SUSPEND_FLAGS_UNLOCK((env)->wait_lock) + +#define ISSET(env, bit) \ + ((WASM_SUSPEND_FLAGS_GET((env)->suspend_flags) & WASM_SUSPEND_FLAG_##bit) \ + != 0) +#define SET(env, bit) \ + WASM_SUSPEND_FLAGS_FETCH_OR((env)->suspend_flags, WASM_SUSPEND_FLAG_##bit) +#define CLR(env, bit) \ + WASM_SUSPEND_FLAGS_FETCH_AND((env)->suspend_flags, ~WASM_SUSPEND_FLAG_##bit) + +bool +wasm_runtime_begin_blocking_op(wasm_exec_env_t env) +{ + LOCK(env); + bh_assert(!ISSET(env, BLOCKING)); + SET(env, BLOCKING); + if (ISSET(env, TERMINATE)) { + CLR(env, BLOCKING); + UNLOCK(env); + return false; + } + UNLOCK(env); + os_begin_blocking_op(); + return true; +} + +void +wasm_runtime_end_blocking_op(wasm_exec_env_t env) +{ + int saved_errno = errno; + LOCK(env); + bh_assert(ISSET(env, BLOCKING)); + CLR(env, BLOCKING); + UNLOCK(env); + os_end_blocking_op(); + errno = saved_errno; +} + +void +wasm_runtime_interrupt_blocking_op(wasm_exec_env_t env) +{ + /* + * ISSET(BLOCKING) here means that the target thread + * is in somewhere between wasm_begin_blocking_op and + * wasm_end_blocking_op. + * keep waking it up until it reaches wasm_end_blocking_op, + * which clears the BLOCKING bit. + * + * this dumb loop is necessary because posix doesn't provide + * a way to unmask signal and block atomically. + */ + + LOCK(env); + SET(env, TERMINATE); + while (ISSET(env, BLOCKING)) { + UNLOCK(env); + os_wakeup_blocking_op(env->handle); + + /* relax a bit */ + os_usleep(50 * 1000); + LOCK(env); + } + UNLOCK(env); +} + +#else /* WASM_ENABLE_THREAD_MGR && OS_ENABLE_WAKEUP_BLOCKING_OP */ + +bool +wasm_runtime_begin_blocking_op(wasm_exec_env_t env) +{ + return true; +} + +void +wasm_runtime_end_blocking_op(wasm_exec_env_t env) +{} + +#endif /* WASM_ENABLE_THREAD_MGR && OS_ENABLE_WAKEUP_BLOCKING_OP */ diff --git a/core/iwasm/common/wasm_memory.c b/core/iwasm/common/wasm_memory.c index a083a214e..05635ef51 100644 --- a/core/iwasm/common/wasm_memory.c +++ b/core/iwasm/common/wasm_memory.c @@ -26,6 +26,7 @@ static Memory_Mode memory_mode = MEMORY_MODE_UNKNOWN; static mem_allocator_t pool_allocator = NULL; static enlarge_memory_error_callback_t enlarge_memory_error_cb; +static void *enlarge_memory_error_user_data; #if WASM_MEM_ALLOC_WITH_USER_DATA != 0 static void *allocator_user_data = NULL; @@ -716,7 +717,8 @@ return_func: enlarge_memory_error_cb(inc_page_count, total_size_old, 0, failure_reason, - (WASMModuleInstanceCommon *)module, exec_env); + (WASMModuleInstanceCommon *)module, exec_env, + enlarge_memory_error_user_data); } return ret; @@ -822,7 +824,8 @@ return_func: enlarge_memory_error_cb(inc_page_count, total_size_old, 0, failure_reason, - (WASMModuleInstanceCommon *)module, exec_env); + (WASMModuleInstanceCommon *)module, exec_env, + enlarge_memory_error_user_data); } return ret; @@ -831,9 +834,10 @@ return_func: void wasm_runtime_set_enlarge_mem_error_callback( - const enlarge_memory_error_callback_t callback) + const enlarge_memory_error_callback_t callback, void *user_data) { enlarge_memory_error_cb = callback; + enlarge_memory_error_user_data = user_data; } bool diff --git a/core/iwasm/common/wasm_memory.h b/core/iwasm/common/wasm_memory.h index cf7d7ffcd..daca2b71e 100644 --- a/core/iwasm/common/wasm_memory.h +++ b/core/iwasm/common/wasm_memory.h @@ -26,7 +26,7 @@ wasm_runtime_memory_pool_size(); void wasm_runtime_set_enlarge_mem_error_callback( - const enlarge_memory_error_callback_t callback); + const enlarge_memory_error_callback_t callback, void *user_data); #ifdef __cplusplus } diff --git a/core/iwasm/common/wasm_runtime_common.c b/core/iwasm/common/wasm_runtime_common.c index 7cac9e643..8faa5e444 100644 --- a/core/iwasm/common/wasm_runtime_common.c +++ b/core/iwasm/common/wasm_runtime_common.c @@ -125,6 +125,34 @@ runtime_malloc(uint64 size, WASMModuleInstanceCommon *module_inst, return mem; } +#if WASM_ENABLE_MULTI_MODULE != 0 +/* TODO: Let loader_malloc be a general API both for AOT and WASM. */ + +#define loader_malloc(size, error_buf, error_buf_size) \ + runtime_malloc(size, NULL, error_buf, error_buf_size) + +static void +set_error_buf_v(const WASMModuleCommon *module, char *error_buf, + uint32 error_buf_size, const char *format, ...) +{ + va_list args; + char buf[128]; + if (error_buf != NULL) { + va_start(args, format); + vsnprintf(buf, sizeof(buf), format, args); + va_end(args); + if (module->module_type == Wasm_Module_AoT) { + snprintf(error_buf, error_buf_size, "AOT module load failed: %s", + buf); + } + else if (module->module_type == Wasm_Module_Bytecode) { + snprintf(error_buf, error_buf_size, "WASM module load failed: %s", + buf); + } + } +} +#endif + #if WASM_ENABLE_FAST_JIT != 0 static JitCompOptions jit_options = { 0 }; #endif @@ -457,8 +485,21 @@ wasm_runtime_env_init() } #endif +#if WASM_ENABLE_THREAD_MGR != 0 && defined(OS_ENABLE_WAKEUP_BLOCKING_OP) + if (os_blocking_op_init() != BHT_OK) { + goto fail11; + } + os_end_blocking_op(); +#endif + return true; +#if WASM_ENABLE_THREAD_MGR != 0 && defined(OS_ENABLE_WAKEUP_BLOCKING_OP) +fail11: +#if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 + aot_compiler_destroy(); +#endif +#endif #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 fail10: #if WASM_ENABLE_FAST_JIT != 0 @@ -1185,27 +1226,34 @@ wasm_runtime_load(uint8 *buf, uint32 size, char *error_buf, if (get_package_type(buf, size) == Wasm_Module_Bytecode) { #if WASM_ENABLE_INTERP != 0 module_common = - (WASMModuleCommon *)wasm_load(buf, size, error_buf, error_buf_size); - return register_module_with_null_name(module_common, error_buf, - error_buf_size); + (WASMModuleCommon *)wasm_load(buf, size, +#if WASM_ENABLE_MULTI_MODULE != 0 + true, +#endif + error_buf, error_buf_size); #endif } else if (get_package_type(buf, size) == Wasm_Module_AoT) { #if WASM_ENABLE_AOT != 0 module_common = (WASMModuleCommon *)aot_load_from_aot_file( buf, size, error_buf, error_buf_size); - return register_module_with_null_name(module_common, error_buf, - error_buf_size); #endif } - - if (size < 4) - set_error_buf(error_buf, error_buf_size, - "WASM module load failed: unexpected end"); - else - set_error_buf(error_buf, error_buf_size, - "WASM module load failed: magic header not detected"); - return NULL; + else { + if (size < 4) + set_error_buf(error_buf, error_buf_size, + "WASM module load failed: unexpected end"); + else + set_error_buf(error_buf, error_buf_size, + "WASM module load failed: magic header not detected"); + return NULL; + } + if (!module_common) { + LOG_DEBUG("WASM module load failed"); + return NULL; + } + return register_module_with_null_name(module_common, error_buf, + error_buf_size); } WASMModuleCommon * @@ -1218,6 +1266,10 @@ wasm_runtime_load_from_sections(WASMSection *section_list, bool is_aot, #if WASM_ENABLE_INTERP != 0 module_common = (WASMModuleCommon *)wasm_load_from_sections( section_list, error_buf, error_buf_size); + if (!module_common) { + LOG_DEBUG("WASM module load failed from sections"); + return NULL; + } return register_module_with_null_name(module_common, error_buf, error_buf_size); #endif @@ -1226,6 +1278,10 @@ wasm_runtime_load_from_sections(WASMSection *section_list, bool is_aot, #if WASM_ENABLE_AOT != 0 module_common = (WASMModuleCommon *)aot_load_from_sections( section_list, error_buf, error_buf_size); + if (!module_common) { + LOG_DEBUG("WASM module load failed from sections"); + return NULL; + } return register_module_with_null_name(module_common, error_buf, error_buf_size); #endif @@ -1392,6 +1448,10 @@ wasm_runtime_init_thread_env(void) } #endif +#if WASM_ENABLE_THREAD_MGR != 0 && defined(OS_ENABLE_WAKEUP_BLOCKING_OP) + os_end_blocking_op(); +#endif + return true; } @@ -2342,8 +2402,8 @@ wasm_runtime_get_exec_env_singleton(WASMModuleInstanceCommon *module_inst_comm) return module_inst->exec_env_singleton; } -void -wasm_set_exception(WASMModuleInstance *module_inst, const char *exception) +static void +wasm_set_exception_local(WASMModuleInstance *module_inst, const char *exception) { exception_lock(module_inst); if (exception) { @@ -2354,13 +2414,22 @@ wasm_set_exception(WASMModuleInstance *module_inst, const char *exception) module_inst->cur_exception[0] = '\0'; } exception_unlock(module_inst); +} +void +wasm_set_exception(WASMModuleInstance *module_inst, const char *exception) +{ #if WASM_ENABLE_THREAD_MGR != 0 WASMExecEnv *exec_env = wasm_clusters_search_exec_env((WASMModuleInstanceCommon *)module_inst); if (exec_env) { - wasm_cluster_spread_exception(exec_env, exception); + wasm_cluster_set_exception(exec_env, exception); } + else { + wasm_set_exception_local(module_inst, exception); + } +#else + wasm_set_exception_local(module_inst, exception); #endif } @@ -2468,6 +2537,18 @@ wasm_runtime_clear_exception(WASMModuleInstanceCommon *module_inst_comm) wasm_runtime_set_exception(module_inst_comm, NULL); } +#if WASM_ENABLE_THREAD_MGR != 0 +void +wasm_runtime_terminate(WASMModuleInstanceCommon *module_inst_comm) +{ + WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm; + + bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode + || module_inst_comm->module_type == Wasm_Module_AoT); + wasm_set_exception(module_inst, "terminated by user"); +} +#endif + void wasm_runtime_set_custom_data_internal( WASMModuleInstanceCommon *module_inst_comm, void *custom_data) @@ -5625,6 +5706,314 @@ wasm_runtime_is_import_global_linked(const char *module_name, #endif } +#if WASM_ENABLE_LIBC_WASI != 0 || WASM_ENABLE_MULTI_MODULE != 0 +WASMExport * +loader_find_export(const WASMModuleCommon *module, const char *module_name, + const char *field_name, uint8 export_kind, char *error_buf, + uint32 error_buf_size) +{ + WASMExport *exports = NULL, *result = NULL, *export; + uint32 export_count = 0, i; +#if WASM_ENABLE_AOT != 0 + if (module->module_type == Wasm_Module_AoT) { + AOTModule *aot_module = (AOTModule *)module; + exports = (WASMExport *)aot_module->exports; + export_count = aot_module->export_count; + } +#endif +#if WASM_ENABLE_INTERP != 0 + if (module->module_type == Wasm_Module_Bytecode) { + WASMModule *wasm_module = (WASMModule *)module; + exports = wasm_module->exports; + export_count = wasm_module->export_count; + } +#endif + for (i = 0, export = exports; i < export_count; ++i, ++export) { + if (export->kind == export_kind && !strcmp(field_name, export->name)) { + result = export; + goto exit; + } + } + if (i == export_count) { + LOG_DEBUG("can not find an export %d named %s in the module %s", + export_kind, field_name, module_name); + set_error_buf(error_buf, error_buf_size, + "unknown import or incompatible import type"); + } +exit: + return result; +} +#endif + +#if WASM_ENABLE_MULTI_MODULE != 0 +WASMModuleCommon * +wasm_runtime_search_sub_module(const WASMModuleCommon *parent_module, + const char *sub_module_name) +{ + WASMRegisteredModule *node = NULL; +#if WASM_ENABLE_AOT != 0 + if (parent_module->module_type == Wasm_Module_AoT) { + node = bh_list_first_elem( + ((AOTModule *)parent_module)->import_module_list); + } +#endif +#if WASM_ENABLE_INTERP != 0 + if (parent_module->module_type == Wasm_Module_Bytecode) { + node = bh_list_first_elem( + ((WASMModule *)parent_module)->import_module_list); + } +#endif + while (node && strcmp(sub_module_name, node->module_name)) { + node = bh_list_elem_next(node); + } + return node ? node->module : NULL; +} + +bool +wasm_runtime_register_sub_module(const WASMModuleCommon *parent_module, + const char *sub_module_name, + WASMModuleCommon *sub_module) +{ + /* register sub_module into its parent sub module list */ + WASMRegisteredModule *node = NULL; + bh_list_status ret; + + if (wasm_runtime_search_sub_module(parent_module, sub_module_name)) { + LOG_DEBUG("%s has been registered in its parent", sub_module_name); + return true; + } + + node = loader_malloc(sizeof(WASMRegisteredModule), NULL, 0); + if (!node) { + return false; + } + + node->module_name = sub_module_name; + node->module = sub_module; +#if WASM_ENABLE_AOT != 0 + if (parent_module->module_type == Wasm_Module_AoT) { + ret = bh_list_insert(((AOTModule *)parent_module)->import_module_list, + node); + } +#endif +#if WASM_ENABLE_INTERP != 0 + if (parent_module->module_type == Wasm_Module_Bytecode) { + ret = bh_list_insert(((WASMModule *)parent_module)->import_module_list, + node); + } +#endif + bh_assert(BH_LIST_SUCCESS == ret); + (void)ret; + return true; +} + +WASMModuleCommon * +wasm_runtime_load_depended_module(const WASMModuleCommon *parent_module, + const char *sub_module_name, char *error_buf, + uint32 error_buf_size) +{ + WASMModuleCommon *sub_module = NULL; + bool ret = false; + uint8 *buffer = NULL; + uint32 buffer_size = 0; + + /* check the registered module list of the parent */ + sub_module = wasm_runtime_search_sub_module(parent_module, sub_module_name); + if (sub_module) { + LOG_DEBUG("%s has been loaded before", sub_module_name); + return sub_module; + } + + /* check the global registered module list */ + sub_module = wasm_runtime_find_module_registered(sub_module_name); + if (sub_module) { + LOG_DEBUG("%s has been loaded", sub_module_name); + goto wasm_runtime_register_sub_module; + } + LOG_VERBOSE("loading %s", sub_module_name); + if (!reader) { + set_error_buf_v(parent_module, error_buf, error_buf_size, + "no sub module reader to load %s", sub_module_name); + return NULL; + } + /* start to maintain a loading module list */ + ret = wasm_runtime_is_loading_module(sub_module_name); + if (ret) { + set_error_buf_v(parent_module, error_buf, error_buf_size, + "found circular dependency on %s", sub_module_name); + return NULL; + } + ret = wasm_runtime_add_loading_module(sub_module_name, error_buf, + error_buf_size); + if (!ret) { + LOG_DEBUG("can not add %s into loading module list\n", sub_module_name); + return NULL; + } + + ret = reader(parent_module->module_type, sub_module_name, &buffer, + &buffer_size); + if (!ret) { + LOG_DEBUG("read the file of %s failed", sub_module_name); + set_error_buf_v(parent_module, error_buf, error_buf_size, + "unknown import", sub_module_name); + goto delete_loading_module; + } + if (get_package_type(buffer, buffer_size) != parent_module->module_type) { + LOG_DEBUG("moudle %s type error", sub_module_name); + goto delete_loading_module; + } + if (get_package_type(buffer, buffer_size) == Wasm_Module_Bytecode) { +#if WASM_ENABLE_INTERP != 0 + sub_module = (WASMModuleCommon *)wasm_load(buffer, buffer_size, false, + error_buf, error_buf_size); +#endif + } + else if (get_package_type(buffer, buffer_size) == Wasm_Module_AoT) { +#if WASM_ENABLE_AOT != 0 + sub_module = (WASMModuleCommon *)aot_load_from_aot_file( + buffer, buffer_size, error_buf, error_buf_size); +#endif + } + if (!sub_module) { + LOG_DEBUG("error: can not load the sub_module %s", sub_module_name); + /* others will be destroyed in runtime_destroy() */ + goto destroy_file_buffer; + } + wasm_runtime_delete_loading_module(sub_module_name); + /* register on a global list */ + ret = wasm_runtime_register_module_internal( + sub_module_name, (WASMModuleCommon *)sub_module, buffer, buffer_size, + error_buf, error_buf_size); + if (!ret) { + LOG_DEBUG("error: can not register module %s globally\n", + sub_module_name); + /* others will be unloaded in runtime_destroy() */ + goto unload_module; + } + + /* register into its parent list */ +wasm_runtime_register_sub_module: + ret = wasm_runtime_register_sub_module(parent_module, sub_module_name, + sub_module); + if (!ret) { + set_error_buf_v(parent_module, error_buf, error_buf_size, + "failed to register sub module %s", sub_module_name); + /* since it is in the global module list, no need to + * unload the module. the runtime_destroy() will do it + */ + return NULL; + } + + return sub_module; + +unload_module: + wasm_runtime_unload(sub_module); + +destroy_file_buffer: + if (destroyer) { + destroyer(buffer, buffer_size); + } + else { + LOG_WARNING("need to release the reading buffer of %s manually", + sub_module_name); + } + +delete_loading_module: + wasm_runtime_delete_loading_module(sub_module_name); + return NULL; +} + +bool +wasm_runtime_sub_module_instantiate(WASMModuleCommon *module, + WASMModuleInstanceCommon *module_inst, + uint32 stack_size, uint32 heap_size, + char *error_buf, uint32 error_buf_size) +{ + bh_list *sub_module_inst_list = NULL; + WASMRegisteredModule *sub_module_list_node = NULL; + +#if WASM_ENABLE_AOT != 0 + if (module->module_type == Wasm_Module_AoT) { + sub_module_inst_list = + ((AOTModuleInstanceExtra *)((AOTModuleInstance *)module_inst)->e) + ->sub_module_inst_list; + sub_module_list_node = + bh_list_first_elem(((AOTModule *)module)->import_module_list); + } +#endif +#if WASM_ENABLE_INTERP != 0 + if (module->module_type == Wasm_Module_Bytecode) { + sub_module_inst_list = + ((WASMModuleInstanceExtra *)((WASMModuleInstance *)module_inst)->e) + ->sub_module_inst_list; + sub_module_list_node = + bh_list_first_elem(((WASMModule *)module)->import_module_list); + } +#endif + while (sub_module_list_node) { + WASMSubModInstNode *sub_module_inst_list_node = NULL; + WASMModuleCommon *sub_module = sub_module_list_node->module; + WASMModuleInstanceCommon *sub_module_inst = NULL; + sub_module_inst = wasm_runtime_instantiate_internal( + sub_module, NULL, NULL, stack_size, heap_size, error_buf, + error_buf_size); + if (!sub_module_inst) { + LOG_DEBUG("instantiate %s failed", + sub_module_list_node->module_name); + return false; + } + sub_module_inst_list_node = loader_malloc(sizeof(WASMSubModInstNode), + error_buf, error_buf_size); + if (!sub_module_inst_list_node) { + LOG_DEBUG("Malloc WASMSubModInstNode failed, SZ:%d", + sizeof(WASMSubModInstNode)); + if (sub_module_inst) + wasm_runtime_deinstantiate_internal(sub_module_inst, false); + return false; + } + sub_module_inst_list_node->module_inst = + (WASMModuleInstance *)sub_module_inst; + sub_module_inst_list_node->module_name = + sub_module_list_node->module_name; + bh_list_status ret = + bh_list_insert(sub_module_inst_list, sub_module_inst_list_node); + bh_assert(BH_LIST_SUCCESS == ret); + (void)ret; + sub_module_list_node = bh_list_elem_next(sub_module_list_node); + } + + return true; +} + +void +wasm_runtime_sub_module_deinstantiate(WASMModuleInstanceCommon *module_inst) +{ + bh_list *list = NULL; +#if WASM_ENABLE_AOT != 0 + if (module_inst->module_type == Wasm_Module_AoT) { + list = ((AOTModuleInstanceExtra *)((AOTModuleInstance *)module_inst)->e) + ->sub_module_inst_list; + } +#endif +#if WASM_ENABLE_INTERP != 0 + if (module_inst->module_type == Wasm_Module_Bytecode) { + list = + ((WASMModuleInstanceExtra *)((WASMModuleInstance *)module_inst)->e) + ->sub_module_inst_list; + } +#endif + + WASMSubModInstNode *node = bh_list_first_elem(list); + while (node) { + WASMSubModInstNode *next_node = bh_list_elem_next(node); + bh_list_remove(list, node); + wasm_runtime_deinstantiate_internal( + (WASMModuleInstanceCommon *)node->module_inst, false); + wasm_runtime_free(node); + node = next_node; + } +} +#endif /* end of WASM_ENABLE_MULTI_MODULE */ #if WASM_ENABLE_MODULE_INST_CONTEXT != 0 void * wasm_runtime_create_context_key(void (*dtor)(WASMModuleInstanceCommon *inst, diff --git a/core/iwasm/common/wasm_runtime_common.h b/core/iwasm/common/wasm_runtime_common.h index b9b0d0bf6..a834d67f2 100644 --- a/core/iwasm/common/wasm_runtime_common.h +++ b/core/iwasm/common/wasm_runtime_common.h @@ -675,6 +675,10 @@ wasm_runtime_get_exception(WASMModuleInstanceCommon *module); WASM_RUNTIME_API_EXTERN void wasm_runtime_clear_exception(WASMModuleInstanceCommon *module_inst); +/* See wasm_export.h for description */ +WASM_RUNTIME_API_EXTERN void +wasm_runtime_terminate(WASMModuleInstanceCommon *module); + /* Internal API */ void wasm_runtime_set_custom_data_internal(WASMModuleInstanceCommon *module_inst, @@ -784,6 +788,9 @@ wasm_runtime_register_module_internal(const char *module_name, void wasm_runtime_unregister_module(const WASMModuleCommon *module); +WASMModuleCommon * +wasm_runtime_find_module_registered(const char *module_name); + bool wasm_runtime_add_loading_module(const char *module_name, char *error_buf, uint32 error_buf_size); @@ -796,6 +803,35 @@ wasm_runtime_is_loading_module(const char *module_name); void wasm_runtime_destroy_loading_module_list(); + +WASMModuleCommon * +wasm_runtime_search_sub_module(const WASMModuleCommon *parent_module, + const char *sub_module_name); + +bool +wasm_runtime_register_sub_module(const WASMModuleCommon *parent_module, + const char *sub_module_name, + WASMModuleCommon *sub_module); + +WASMModuleCommon * +wasm_runtime_load_depended_module(const WASMModuleCommon *parent_module, + const char *sub_module_name, char *error_buf, + uint32 error_buf_size); + +bool +wasm_runtime_sub_module_instantiate(WASMModuleCommon *module, + WASMModuleInstanceCommon *module_inst, + uint32 stack_size, uint32 heap_size, + char *error_buf, uint32 error_buf_size); +void +wasm_runtime_sub_module_deinstantiate(WASMModuleInstanceCommon *module_inst); +#endif + +#if WASM_ENABLE_LIBC_WASI != 0 || WASM_ENABLE_MULTI_MODULE != 0 +WASMExport * +loader_find_export(const WASMModuleCommon *module, const char *module_name, + const char *field_name, uint8 export_kind, char *error_buf, + uint32 error_buf_size); #endif /* WASM_ENALBE_MULTI_MODULE */ bool @@ -1036,6 +1072,15 @@ WASM_RUNTIME_API_EXTERN bool wasm_runtime_is_import_global_linked(const char *module_name, const char *global_name); +WASM_RUNTIME_API_EXTERN bool +wasm_runtime_begin_blocking_op(WASMExecEnv *exec_env); + +WASM_RUNTIME_API_EXTERN void +wasm_runtime_end_blocking_op(WASMExecEnv *exec_env); + +void +wasm_runtime_interrupt_blocking_op(WASMExecEnv *exec_env); + #ifdef __cplusplus } #endif diff --git a/core/iwasm/common/wasm_suspend_flags.h b/core/iwasm/common/wasm_suspend_flags.h index b7ecbb0b2..b182b2b5f 100644 --- a/core/iwasm/common/wasm_suspend_flags.h +++ b/core/iwasm/common/wasm_suspend_flags.h @@ -20,6 +20,8 @@ extern "C" { #define WASM_SUSPEND_FLAG_BREAKPOINT 0x4 /* Return from pthread_exit */ #define WASM_SUSPEND_FLAG_EXIT 0x8 +/* The thread might be blocking */ +#define WASM_SUSPEND_FLAG_BLOCKING 0x10 typedef union WASMSuspendFlags { bh_atomic_32_t flags; diff --git a/core/iwasm/compilation/aot_compiler.h b/core/iwasm/compilation/aot_compiler.h index 40d79cf86..b6347c89d 100644 --- a/core/iwasm/compilation/aot_compiler.h +++ b/core/iwasm/compilation/aot_compiler.h @@ -363,6 +363,19 @@ check_type_compatible(uint8 src_type, uint8 dst_type) } \ } while (0) +/* if val is a constant integer and its value is not undef or poison */ +static inline bool +LLVMIsEfficientConstInt(LLVMValueRef val) +{ + return LLVMIsConstant(val) + && LLVMGetValueKind(val) == LLVMConstantIntValueKind + && !LLVMIsUndef(val) +#if LLVM_VERSION_NUMBER >= 12 + && !LLVMIsPoison(addr) +#endif + ; +} + bool aot_compile_wasm(AOTCompContext *comp_ctx); diff --git a/core/iwasm/compilation/aot_emit_aot_file.c b/core/iwasm/compilation/aot_emit_aot_file.c index 622187755..103b2750e 100644 --- a/core/iwasm/compilation/aot_emit_aot_file.c +++ b/core/iwasm/compilation/aot_emit_aot_file.c @@ -2703,6 +2703,7 @@ aot_resolve_stack_sizes(AOTCompContext *comp_ctx, AOTObjectData *obj_data) || (obj_data->target_info.bin_type == AOT_COFF32_BIN_TYPE && !strncmp(name, "_", 1) && !strcmp(name + 1, aot_stack_sizes_alias_name)))) { +#if 0 /* cf. https://github.com/llvm/llvm-project/issues/67765 */ uint64 sz = LLVMGetSymbolSize(sym_itr); if (sz != sizeof(uint32) * obj_data->func_count /* sz of COFF64/COFF32 is 0, ignore the check */ @@ -2711,6 +2712,7 @@ aot_resolve_stack_sizes(AOTCompContext *comp_ctx, AOTObjectData *obj_data) aot_set_last_error("stack_sizes had unexpected size."); goto fail; } +#endif uint64 addr = LLVMGetSymbolAddress(sym_itr); if (!(sec_itr = LLVMObjectFileCopySectionIterator(obj_data->binary))) { diff --git a/core/iwasm/compilation/aot_emit_control.c b/core/iwasm/compilation/aot_emit_control.c index 2cf51cf67..446ca5ea6 100644 --- a/core/iwasm/compilation/aot_emit_control.c +++ b/core/iwasm/compilation/aot_emit_control.c @@ -4,6 +4,7 @@ */ #include "aot_emit_control.h" +#include "aot_compiler.h" #include "aot_emit_exception.h" #include "../aot/aot_runtime.h" #include "../interpreter/wasm_loader.h" @@ -234,13 +235,15 @@ handle_next_reachable_block(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, else { /* Store extra return values to function parameters */ if (i != 0) { + LLVMValueRef res; uint32 param_index = func_type->param_count + i; - if (!LLVMBuildStore( - comp_ctx->builder, block->result_phis[i], - LLVMGetParam(func_ctx->func, param_index))) { + if (!(res = LLVMBuildStore( + comp_ctx->builder, block->result_phis[i], + LLVMGetParam(func_ctx->func, param_index)))) { aot_set_last_error("llvm build store failed."); goto fail; } + LLVMSetAlignment(res, 1); } } } @@ -278,7 +281,7 @@ push_aot_block_to_stack_and_pass_params(AOTCompContext *comp_ctx, AOTBlock *block) { uint32 i, param_index; - LLVMValueRef value; + LLVMValueRef value, br_inst; uint64 size; char name[32]; LLVMBasicBlockRef block_curr = CURR_BLOCK(); @@ -326,7 +329,14 @@ push_aot_block_to_stack_and_pass_params(AOTCompContext *comp_ctx, } } } - SET_BUILDER_POS(block_curr); + + /* At this point, the branch instruction was already built to jump to + * the new BB, to avoid generating zext instruction from the popped + * operand that would come after branch instruction, we should position + * the builder before the last branch instruction */ + br_inst = LLVMGetLastInstruction(block_curr); + bh_assert(LLVMGetInstructionOpcode(br_inst) == LLVMBr); + LLVMPositionBuilderBefore(comp_ctx->builder, br_inst); /* Pop param values from current block's * value stack and add to param phis. @@ -467,7 +477,7 @@ aot_compile_op_block(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, p_frame_ip); } - if (!LLVMIsConstant(value)) { + if (!LLVMIsEfficientConstInt(value)) { /* Compare value is not constant, create condition br IR */ /* Create entry block */ format_block_name(name, sizeof(name), block->block_index, @@ -833,7 +843,7 @@ aot_compile_op_br_if(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, return aot_handle_next_reachable_block(comp_ctx, func_ctx, p_frame_ip); } - if (!LLVMIsConstant(value_cmp)) { + if (!LLVMIsEfficientConstInt(value_cmp)) { /* Compare value is not constant, create condition br IR */ if (!(block_dst = get_target_block(func_ctx, br_depth))) { return false; @@ -970,7 +980,7 @@ aot_compile_op_br_table(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, return aot_handle_next_reachable_block(comp_ctx, func_ctx, p_frame_ip); } - if (!LLVMIsConstant(value_cmp)) { + if (!LLVMIsEfficientConstInt(value_cmp)) { /* Compare value is not constant, create switch IR */ for (i = 0; i <= br_count; i++) { target_block = get_target_block(func_ctx, br_depths[i]); @@ -1102,14 +1112,17 @@ aot_compile_op_return(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, if (block_func->result_count) { /* Store extra result values to function parameters */ for (i = 0; i < block_func->result_count - 1; i++) { + LLVMValueRef res; result_index = block_func->result_count - 1 - i; POP(value, block_func->result_types[result_index]); param_index = func_type->param_count + result_index; - if (!LLVMBuildStore(comp_ctx->builder, value, - LLVMGetParam(func_ctx->func, param_index))) { + if (!(res = LLVMBuildStore( + comp_ctx->builder, value, + LLVMGetParam(func_ctx->func, param_index)))) { aot_set_last_error("llvm build store failed."); goto fail; } + LLVMSetAlignment(res, 1); } /* Return the first result value */ POP(value, block_func->result_types[0]); diff --git a/core/iwasm/compilation/aot_emit_memory.c b/core/iwasm/compilation/aot_emit_memory.c index c11989ebf..7484d4b5b 100644 --- a/core/iwasm/compilation/aot_emit_memory.c +++ b/core/iwasm/compilation/aot_emit_memory.c @@ -4,6 +4,7 @@ */ #include "aot_emit_memory.h" +#include "aot_compiler.h" #include "aot_emit_exception.h" #include "../aot/aot_runtime.h" #include "aot_intrinsic.h" @@ -145,11 +146,7 @@ aot_check_memory_overflow(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, * have been thrown when converting float to integer before */ /* return addres directly if constant offset and inside memory space */ - if (LLVMIsConstant(addr) && !LLVMIsUndef(addr) -#if LLVM_VERSION_NUMBER >= 12 - && !LLVMIsPoison(addr) -#endif - ) { + if (LLVMIsEfficientConstInt(addr)) { uint64 mem_offset = (uint64)LLVMConstIntGetZExtValue(addr) + (uint64)offset; uint32 num_bytes_per_page = @@ -911,11 +908,7 @@ check_bulk_memory_overflow(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, * have been thrown when converting float to integer before */ /* return addres directly if constant offset and inside memory space */ - if (!LLVMIsUndef(offset) && !LLVMIsUndef(bytes) -#if LLVM_VERSION_NUMBER >= 12 - && !LLVMIsPoison(offset) && !LLVMIsPoison(bytes) -#endif - && LLVMIsConstant(offset) && LLVMIsConstant(bytes)) { + if (LLVMIsEfficientConstInt(offset) && LLVMIsEfficientConstInt(bytes)) { uint64 mem_offset = (uint64)LLVMConstIntGetZExtValue(offset); uint64 mem_len = (uint64)LLVMConstIntGetZExtValue(bytes); uint32 num_bytes_per_page = diff --git a/core/iwasm/compilation/aot_emit_numberic.c b/core/iwasm/compilation/aot_emit_numberic.c index 4c63e8a40..bda64f831 100644 --- a/core/iwasm/compilation/aot_emit_numberic.c +++ b/core/iwasm/compilation/aot_emit_numberic.c @@ -54,13 +54,13 @@ } while (0) #if LLVM_VERSION_NUMBER >= 12 -#define IS_CONST_ZERO(val) \ - (!LLVMIsUndef(val) && !LLVMIsPoison(val) && LLVMIsConstant(val) \ - && ((is_i32 && (int32)LLVMConstIntGetZExtValue(val) == 0) \ +#define IS_CONST_ZERO(val) \ + (LLVMIsEfficientConstInt(val) \ + && ((is_i32 && (int32)LLVMConstIntGetZExtValue(val) == 0) \ || (!is_i32 && (int64)LLVMConstIntGetSExtValue(val) == 0))) #else #define IS_CONST_ZERO(val) \ - (!LLVMIsUndef(val) && LLVMIsConstant(val) \ + (LLVMIsEfficientConstInt(val) \ && ((is_i32 && (int32)LLVMConstIntGetZExtValue(val) == 0) \ || (!is_i32 && (int64)LLVMConstIntGetSExtValue(val) == 0))) #endif @@ -171,6 +171,15 @@ right = shift_count_mask; \ } while (0) +static bool +is_shift_count_mask_needed(AOTCompContext *comp_ctx, LLVMValueRef left, + LLVMValueRef right) +{ + return (strcmp(comp_ctx->target_arch, "x86_64") != 0 + && strcmp(comp_ctx->target_arch, "i386") != 0) + || (LLVMIsEfficientConstInt(left) && LLVMIsEfficientConstInt(right)); +} + /* Call llvm constrained floating-point intrinsic */ static LLVMValueRef call_llvm_float_experimental_constrained_intrinsic(AOTCompContext *comp_ctx, @@ -473,7 +482,7 @@ compile_int_div(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, return aot_handle_next_reachable_block(comp_ctx, func_ctx, p_frame_ip); } - if (LLVMIsConstant(right)) { + if (LLVMIsEfficientConstInt(right)) { int64 right_val = (int64)LLVMConstIntGetSExtValue(right); switch (right_val) { case 0: @@ -728,8 +737,7 @@ compile_int_shl(AOTCompContext *comp_ctx, LLVMValueRef left, LLVMValueRef right, { LLVMValueRef res; - if (strcmp(comp_ctx->target_arch, "x86_64") != 0 - && strcmp(comp_ctx->target_arch, "i386") != 0) + if (is_shift_count_mask_needed(comp_ctx, left, right)) SHIFT_COUNT_MASK; /* Build shl */ @@ -744,8 +752,7 @@ compile_int_shr_s(AOTCompContext *comp_ctx, LLVMValueRef left, { LLVMValueRef res; - if (strcmp(comp_ctx->target_arch, "x86_64") != 0 - && strcmp(comp_ctx->target_arch, "i386") != 0) + if (is_shift_count_mask_needed(comp_ctx, left, right)) SHIFT_COUNT_MASK; /* Build shl */ @@ -760,8 +767,7 @@ compile_int_shr_u(AOTCompContext *comp_ctx, LLVMValueRef left, { LLVMValueRef res; - if (strcmp(comp_ctx->target_arch, "x86_64") != 0 - && strcmp(comp_ctx->target_arch, "i386") != 0) + if (is_shift_count_mask_needed(comp_ctx, left, right)) SHIFT_COUNT_MASK; /* Build shl */ diff --git a/core/iwasm/compilation/aot_llvm.c b/core/iwasm/compilation/aot_llvm.c index f4bc8500e..6dc3a0f7d 100644 --- a/core/iwasm/compilation/aot_llvm.c +++ b/core/iwasm/compilation/aot_llvm.c @@ -526,12 +526,18 @@ aot_add_precheck_function(AOTCompContext *comp_ctx, LLVMModuleRef module, } wasm_runtime_free(params); params = NULL; + +#if LLVM_VERSION_MAJOR < 17 if (aot_target_precheck_can_use_musttail(comp_ctx)) { LLVMSetTailCallKind(retval, LLVMTailCallKindMustTail); } else { LLVMSetTailCallKind(retval, LLVMTailCallKindTail); } +#else + LLVMSetTailCall(retval, true); +#endif + if (ret_type == VOID_TYPE) { if (!LLVMBuildRetVoid(b)) { goto fail; @@ -2172,8 +2178,10 @@ bool aot_compiler_init(void) { /* Initialize LLVM environment */ - +#if LLVM_VERSION_MAJOR < 17 LLVMInitializeCore(LLVMGetGlobalPassRegistry()); +#endif + #if WASM_ENABLE_WAMR_COMPILER != 0 /* Init environment of all targets for AOT compiler */ LLVMInitializeAllTargetInfos(); diff --git a/core/iwasm/compilation/aot_llvm.h b/core/iwasm/compilation/aot_llvm.h index 03994b6c0..b46ac3bd0 100644 --- a/core/iwasm/compilation/aot_llvm.h +++ b/core/iwasm/compilation/aot_llvm.h @@ -15,15 +15,18 @@ #include "llvm-c/ExecutionEngine.h" #include "llvm-c/Analysis.h" #include "llvm-c/BitWriter.h" +#if LLVM_VERSION_MAJOR < 17 #include "llvm-c/Transforms/Utils.h" #include "llvm-c/Transforms/Scalar.h" #include "llvm-c/Transforms/Vectorize.h" #include "llvm-c/Transforms/PassManagerBuilder.h" +#include "llvm-c/Initialization.h" +#endif #include "llvm-c/Orc.h" #include "llvm-c/Error.h" #include "llvm-c/Support.h" -#include "llvm-c/Initialization.h" + #include "llvm-c/TargetMachine.h" #include "llvm-c/LLJIT.h" #if WASM_ENABLE_DEBUG_AOT != 0 diff --git a/core/iwasm/compilation/aot_llvm_extra.cpp b/core/iwasm/compilation/aot_llvm_extra.cpp index 898fabd8c..ab6c621a0 100644 --- a/core/iwasm/compilation/aot_llvm_extra.cpp +++ b/core/iwasm/compilation/aot_llvm_extra.cpp @@ -5,11 +5,13 @@ #include #include +#if LLVM_VERSION_MAJOR < 17 #include #include +#include +#endif #include #include -#include #include #include #include @@ -18,7 +20,9 @@ #include #include #include +#if LLVM_VERSION_MAJOR < 17 #include +#endif #include #include #include @@ -30,6 +34,9 @@ #include #include #include +#if LLVM_VERSION_MAJOR >= 17 +#include +#endif #include #include #include @@ -55,6 +62,13 @@ using namespace llvm; using namespace llvm::orc; +#if LLVM_VERSION_MAJOR >= 17 +namespace llvm { +template +using Optional = std::optional; +} +#endif + LLVM_C_EXTERN_C_BEGIN bool @@ -110,7 +124,14 @@ ExpandMemoryOpPass::run(Function &F, FunctionAnalysisManager &AM) Memcpy->eraseFromParent(); } else if (MemMoveInst *Memmove = dyn_cast(MemCall)) { +#if LLVM_VERSION_MAJOR >= 17 + Function *ParentFunc = Memmove->getParent()->getParent(); + const TargetTransformInfo &TTI = + AM.getResult(*ParentFunc); + expandMemMoveAsLoop(Memmove, TTI); +#else expandMemMoveAsLoop(Memmove); +#endif Memmove->eraseFromParent(); } else if (MemSetInst *Memset = dyn_cast(MemCall)) { @@ -181,6 +202,9 @@ aot_apply_llvm_new_pass_manager(AOTCompContext *comp_ctx, LLVMModuleRef module) #else Optional PGO = llvm::None; #endif + +// TODO +#if LLVM_VERSION_MAJOR < 17 if (comp_ctx->enable_llvm_pgo) { /* Disable static counter allocation for value profiler, it will be allocated by runtime */ @@ -191,6 +215,7 @@ aot_apply_llvm_new_pass_manager(AOTCompContext *comp_ctx, LLVMModuleRef module) else if (comp_ctx->use_prof_file) { PGO = PGOOptions(comp_ctx->use_prof_file, "", "", PGOOptions::IRUse); } +#endif #ifdef DEBUG_PASS PassInstrumentationCallbacks PIC; diff --git a/core/iwasm/compilation/aot_llvm_extra2.cpp b/core/iwasm/compilation/aot_llvm_extra2.cpp index 42e53ddfa..8364e5ebf 100644 --- a/core/iwasm/compilation/aot_llvm_extra2.cpp +++ b/core/iwasm/compilation/aot_llvm_extra2.cpp @@ -4,8 +4,10 @@ */ #include +#if LLVM_VERSION_MAJOR < 17 #include #include +#endif #include #if LLVM_VERSION_MAJOR >= 14 #include @@ -18,6 +20,13 @@ #include "aot_llvm_extra2.h" +#if LLVM_VERSION_MAJOR >= 17 +namespace llvm { +template +using Optional = std::optional; +} +#endif + static llvm::Optional convert(LLVMRelocMode reloc_mode) { diff --git a/core/iwasm/compilation/aot_orc_extra.cpp b/core/iwasm/compilation/aot_orc_extra.cpp index 9cfe331e5..51d61bf3c 100644 --- a/core/iwasm/compilation/aot_orc_extra.cpp +++ b/core/iwasm/compilation/aot_orc_extra.cpp @@ -8,8 +8,10 @@ #include "llvm-c/OrcEE.h" #include "llvm-c/TargetMachine.h" +#if LLVM_VERSION_MAJOR < 17 #include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" +#endif #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h" #include "llvm/ExecutionEngine/Orc/LLJIT.h" #include "llvm/ExecutionEngine/Orc/ObjectTransformLayer.h" @@ -21,6 +23,13 @@ #include "aot_orc_extra.h" #include "aot.h" +#if LLVM_VERSION_MAJOR >= 17 +namespace llvm { +template +using Optional = std::optional; +} +#endif + using namespace llvm; using namespace llvm::orc; using GlobalValueSet = std::set; diff --git a/core/iwasm/compilation/simd/simd_floating_point.c b/core/iwasm/compilation/simd/simd_floating_point.c index d850fe8f7..7fcc1ab65 100644 --- a/core/iwasm/compilation/simd/simd_floating_point.c +++ b/core/iwasm/compilation/simd/simd_floating_point.c @@ -217,10 +217,9 @@ aot_compile_simd_f64x2_nearest(AOTCompContext *comp_ctx, static bool simd_float_cmp(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, - FloatArithmetic arith_op, LLVMTypeRef vector_type) + FloatArithmetic op, LLVMTypeRef vector_type) { - LLVMValueRef lhs, rhs, result; - LLVMRealPredicate op = FLOAT_MIN == arith_op ? LLVMRealULT : LLVMRealUGT; + LLVMValueRef lhs, rhs, cmp, selected; if (!(rhs = simd_pop_v128_and_bitcast(comp_ctx, func_ctx, vector_type, "rhs")) @@ -229,80 +228,240 @@ simd_float_cmp(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, return false; } - if (!(result = LLVMBuildFCmp(comp_ctx->builder, op, lhs, rhs, "cmp"))) { + if (!(cmp = LLVMBuildFCmp(comp_ctx->builder, + op == FLOAT_MIN ? LLVMRealOLT : LLVMRealOGT, rhs, + lhs, "cmp"))) { HANDLE_FAILURE("LLVMBuildFCmp"); return false; } - if (!(result = - LLVMBuildSelect(comp_ctx->builder, result, lhs, rhs, "select"))) { + if (!(selected = + LLVMBuildSelect(comp_ctx->builder, cmp, rhs, lhs, "selected"))) { HANDLE_FAILURE("LLVMBuildSelect"); return false; } - return simd_bitcast_and_push_v128(comp_ctx, func_ctx, result, "result"); + return simd_bitcast_and_push_v128(comp_ctx, func_ctx, selected, "result"); +} + +static bool +simd_float_min(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + LLVMTypeRef vector_type) +{ + LLVMValueRef lhs, rhs, lhs_nan, rhs_nan, olt_ret, ogt_ret, or_ret, ret1, + ret2, ret3, ret4; + + if (!(rhs = + simd_pop_v128_and_bitcast(comp_ctx, func_ctx, vector_type, "rhs")) + || !(lhs = simd_pop_v128_and_bitcast(comp_ctx, func_ctx, vector_type, + "lhs"))) { + return false; + } + + if (!(lhs_nan = LLVMBuildFCmp(comp_ctx->builder, LLVMRealUNO, lhs, lhs, + "lhs_nan"))) { + HANDLE_FAILURE("LLVMBuildFCmp + LLVMRealUNO"); + return false; + } + + if (!(rhs_nan = LLVMBuildFCmp(comp_ctx->builder, LLVMRealUNO, rhs, rhs, + "rhs_nan"))) { + HANDLE_FAILURE("LLVMBuildFCmp + LLVMRealUNO"); + return false; + } + + if (!(olt_ret = LLVMBuildFCmp(comp_ctx->builder, LLVMRealOLT, lhs, rhs, + "olt_ret"))) { + HANDLE_FAILURE("LLVMBuildFCmp + LLVMRealOLT"); + return false; + } + + if (!(ogt_ret = LLVMBuildFCmp(comp_ctx->builder, LLVMRealOGT, lhs, rhs, + "ogt_ret"))) { + HANDLE_FAILURE("LLVMBuildFCmp + LLVMRealOGT"); + return false; + } + + /* lhs or rhs */ + { + LLVMValueRef integer_l, integer_r, integer_or; + + if (!(integer_l = LLVMBuildBitCast(comp_ctx->builder, lhs, + V128_i64x2_TYPE, "lhs_to_int"))) { + HANDLE_FAILURE("LLVMBuildBitCas"); + return false; + } + + if (!(integer_r = LLVMBuildBitCast(comp_ctx->builder, rhs, + V128_i64x2_TYPE, "rhs_to_int"))) { + HANDLE_FAILURE("LLVMBuildBitCas"); + return false; + } + + if (!(integer_or = + LLVMBuildOr(comp_ctx->builder, integer_l, integer_r, "or"))) { + HANDLE_FAILURE("LLVMBuildOr"); + return false; + } + + if (!(or_ret = LLVMBuildBitCast(comp_ctx->builder, integer_or, + vector_type, "holder"))) { + HANDLE_FAILURE("LLVMBuildBitCast"); + return false; + } + } + + if (!(ret1 = LLVMBuildSelect(comp_ctx->builder, olt_ret, lhs, or_ret, + "sel_olt"))) { + HANDLE_FAILURE("LLVMBuildSelect"); + return false; + } + + if (!(ret2 = LLVMBuildSelect(comp_ctx->builder, ogt_ret, rhs, ret1, + "sel_ogt"))) { + HANDLE_FAILURE("LLVMBuildSelect"); + return false; + } + + if (!(ret3 = LLVMBuildSelect(comp_ctx->builder, lhs_nan, lhs, ret2, + "sel_lhs_nan"))) { + HANDLE_FAILURE("LLVMBuildSelect"); + return false; + } + + if (!(ret4 = LLVMBuildSelect(comp_ctx->builder, rhs_nan, rhs, ret3, + "sel_rhs_nan"))) { + HANDLE_FAILURE("LLVMBuildSelect"); + return false; + } + + return simd_bitcast_and_push_v128(comp_ctx, func_ctx, ret4, "result"); +} + +static bool +simd_float_max(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + LLVMTypeRef vector_type) +{ + LLVMValueRef lhs, rhs, lhs_nan, rhs_nan, olt_ret, ogt_ret, and_ret, ret1, + ret2, ret3, ret4; + + if (!(rhs = + simd_pop_v128_and_bitcast(comp_ctx, func_ctx, vector_type, "rhs")) + || !(lhs = simd_pop_v128_and_bitcast(comp_ctx, func_ctx, vector_type, + "lhs"))) { + return false; + } + + if (!(lhs_nan = LLVMBuildFCmp(comp_ctx->builder, LLVMRealUNO, lhs, lhs, + "lhs_nan"))) { + HANDLE_FAILURE("LLVMBuildFCmp + LLVMRealUNO"); + return false; + } + + if (!(rhs_nan = LLVMBuildFCmp(comp_ctx->builder, LLVMRealUNO, rhs, rhs, + "rhs_nan"))) { + HANDLE_FAILURE("LLVMBuildFCmp + LLVMRealUNO"); + return false; + } + + if (!(olt_ret = LLVMBuildFCmp(comp_ctx->builder, LLVMRealOLT, lhs, rhs, + "olt_ret"))) { + HANDLE_FAILURE("LLVMBuildFCmp + LLVMRealOLT"); + return false; + } + + if (!(ogt_ret = LLVMBuildFCmp(comp_ctx->builder, LLVMRealOGT, lhs, rhs, + "ogt_ret"))) { + HANDLE_FAILURE("LLVMBuildFCmp + LLVMRealOGT"); + return false; + } + + /* lhs and rhs */ + { + LLVMValueRef integer_l, integer_r, integer_and; + + if (!(integer_l = LLVMBuildBitCast(comp_ctx->builder, lhs, + V128_i64x2_TYPE, "lhs_to_int"))) { + HANDLE_FAILURE("LLVMBuildBitCas"); + return false; + } + + if (!(integer_r = LLVMBuildBitCast(comp_ctx->builder, rhs, + V128_i64x2_TYPE, "rhs_to_int"))) { + HANDLE_FAILURE("LLVMBuildBitCas"); + return false; + } + + if (!(integer_and = LLVMBuildAnd(comp_ctx->builder, integer_l, + integer_r, "and"))) { + HANDLE_FAILURE("LLVMBuildOr"); + return false; + } + + if (!(and_ret = LLVMBuildBitCast(comp_ctx->builder, integer_and, + vector_type, "holder"))) { + HANDLE_FAILURE("LLVMBuildBitCast"); + return false; + } + } + + if (!(ret1 = LLVMBuildSelect(comp_ctx->builder, ogt_ret, lhs, and_ret, + "sel_ogt"))) { + HANDLE_FAILURE("LLVMBuildSelect"); + return false; + } + + if (!(ret2 = LLVMBuildSelect(comp_ctx->builder, olt_ret, rhs, ret1, + "sel_olt"))) { + HANDLE_FAILURE("LLVMBuildSelect"); + return false; + } + + if (!(ret3 = LLVMBuildSelect(comp_ctx->builder, lhs_nan, lhs, ret2, + "sel_lhs_nan"))) { + HANDLE_FAILURE("LLVMBuildSelect"); + return false; + } + + if (!(ret4 = LLVMBuildSelect(comp_ctx->builder, rhs_nan, rhs, ret3, + "sel_rhs_nan"))) { + HANDLE_FAILURE("LLVMBuildSelect"); + return false; + } + + return simd_bitcast_and_push_v128(comp_ctx, func_ctx, ret4, "result"); } -/*TODO: sugggest non-IA platforms check with "llvm.minimum.*" and - * "llvm.maximum.*" firstly */ bool aot_compile_simd_f32x4_min_max(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, bool run_min) { - return simd_float_cmp(comp_ctx, func_ctx, run_min ? FLOAT_MIN : FLOAT_MAX, - V128_f32x4_TYPE); + return run_min ? simd_float_min(comp_ctx, func_ctx, V128_f32x4_TYPE) + : simd_float_max(comp_ctx, func_ctx, V128_f32x4_TYPE); } bool aot_compile_simd_f64x2_min_max(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, bool run_min) { - return simd_float_cmp(comp_ctx, func_ctx, run_min ? FLOAT_MIN : FLOAT_MAX, - V128_f64x2_TYPE); -} - -static bool -simd_float_pmin_max(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, - LLVMTypeRef vector_type, const char *intrinsic) -{ - LLVMValueRef lhs, rhs, result; - LLVMTypeRef param_types[2]; - - param_types[0] = vector_type; - param_types[1] = vector_type; - - if (!(rhs = - simd_pop_v128_and_bitcast(comp_ctx, func_ctx, vector_type, "rhs")) - || !(lhs = simd_pop_v128_and_bitcast(comp_ctx, func_ctx, vector_type, - "lhs"))) { - return false; - } - - if (!(result = - aot_call_llvm_intrinsic(comp_ctx, func_ctx, intrinsic, - vector_type, param_types, 2, lhs, rhs))) { - return false; - } - - return simd_bitcast_and_push_v128(comp_ctx, func_ctx, result, "result"); + return run_min ? simd_float_min(comp_ctx, func_ctx, V128_f64x2_TYPE) + : simd_float_max(comp_ctx, func_ctx, V128_f64x2_TYPE); } bool aot_compile_simd_f32x4_pmin_pmax(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, bool run_min) { - return simd_float_pmin_max(comp_ctx, func_ctx, V128_f32x4_TYPE, - run_min ? "llvm.minnum.v4f32" - : "llvm.maxnum.v4f32"); + return simd_float_cmp(comp_ctx, func_ctx, run_min ? FLOAT_MIN : FLOAT_MAX, + V128_f32x4_TYPE); } bool aot_compile_simd_f64x2_pmin_pmax(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, bool run_min) { - return simd_float_pmin_max(comp_ctx, func_ctx, V128_f64x2_TYPE, - run_min ? "llvm.minnum.v2f64" - : "llvm.maxnum.v2f64"); + return simd_float_cmp(comp_ctx, func_ctx, run_min ? FLOAT_MIN : FLOAT_MAX, + V128_f64x2_TYPE); } bool diff --git a/core/iwasm/fast-jit/fe/jit_emit_numberic.c b/core/iwasm/fast-jit/fe/jit_emit_numberic.c index 03491e691..6a1e93ede 100644 --- a/core/iwasm/fast-jit/fe/jit_emit_numberic.c +++ b/core/iwasm/fast-jit/fe/jit_emit_numberic.c @@ -298,7 +298,15 @@ fail: /* macros for integer binary operations (ibinop) */ +#if defined(__GNUC__) +#define NO_SANITIZER_INTEGER \ + __attribute__((no_sanitize("signed-integer-overflow"))) +#else +#define NO_SANITIZER_INTEGER +#endif + #define __DEF_BI_INT_CONST_OPS(bits, opname, op) \ + NO_SANITIZER_INTEGER \ static int##bits do_i##bits##_const_##opname(int##bits lhs, int##bits rhs) \ { \ return lhs op rhs; \ diff --git a/core/iwasm/include/wasm_export.h b/core/iwasm/include/wasm_export.h index 589d8af00..2a30ddc93 100644 --- a/core/iwasm/include/wasm_export.h +++ b/core/iwasm/include/wasm_export.h @@ -311,7 +311,7 @@ wasm_runtime_is_xip_file(const uint8_t *buf, uint32_t size); /** * Callback to load a module file into a buffer in multi-module feature */ -typedef bool (*module_reader)(const char *module_name, +typedef bool (*module_reader)(package_type_t module_type,const char *module_name, uint8_t **p_buffer, uint32_t *p_size); /** @@ -894,6 +894,27 @@ wasm_runtime_set_exception(wasm_module_inst_t module_inst, WASM_RUNTIME_API_EXTERN void wasm_runtime_clear_exception(wasm_module_inst_t module_inst); +/** + * Terminate the WASM module instance. + * + * This function causes the module instance fail as if it raised a trap. + * + * This is intended to be used in situations like: + * + * - A thread is executing the WASM module instance + * (eg. it's in the middle of `wasm_application_execute_main`) + * + * - Another thread has a copy of `wasm_module_inst_t` of + * the module instance and wants to terminate it asynchronously. + * + * This function is provided only when WAMR is built with threading enabled. + * (`WASM_ENABLE_THREAD_MGR=1`) + * + * @param module_inst the WASM module instance + */ +WASM_RUNTIME_API_EXTERN void +wasm_runtime_terminate(wasm_module_inst_t module_inst); + /** * Set custom data to WASM module instance. * Note: @@ -1447,14 +1468,15 @@ typedef enum { typedef void (*enlarge_memory_error_callback_t)( uint32_t inc_page_count, uint64_t current_memory_size, uint32_t memory_index, enlarge_memory_error_reason_t failure_reason, - wasm_module_inst_t instance, wasm_exec_env_t exec_env); + wasm_module_inst_t instance, wasm_exec_env_t exec_env, + void* user_data); /** * Setup callback invoked when memory.grow fails */ WASM_RUNTIME_API_EXTERN void wasm_runtime_set_enlarge_mem_error_callback( - const enlarge_memory_error_callback_t callback); + const enlarge_memory_error_callback_t callback, void *user_data); /* * module instance context APIs @@ -1524,6 +1546,50 @@ wasm_runtime_set_context_spread(wasm_module_inst_t inst, void *key, WASM_RUNTIME_API_EXTERN void * wasm_runtime_get_context(wasm_module_inst_t inst, void *key); +/* + * wasm_runtime_begin_blocking_op/wasm_runtime_end_blocking_op + * + * These APIs are intended to be used by the implementations of + * host functions. It wraps an operation which possibly blocks for long + * to prepare for async termination. + * + * eg. + * + * if (!wasm_runtime_begin_blocking_op(exec_env)) { + * return EINTR; + * } + * ret = possibly_blocking_op(); + * wasm_runtime_end_blocking_op(exec_env); + * return ret; + * + * If threading support (WASM_ENABLE_THREAD_MGR) is not enabled, + * these functions are no-op. + * + * If the underlying platform support (OS_ENABLE_WAKEUP_BLOCKING_OP) is + * not available, these functions are no-op. In that case, the runtime + * might not terminate a blocking thread in a timely manner. + * + * If the underlying platform support is available, it's used to wake up + * the thread for async termination. The expectation here is that a + * `os_wakeup_blocking_op` call makes the blocking operation + * (`possibly_blocking_op` in the above example) return in a timely manner. + * + * The actual wake up mechanism used by `os_wakeup_blocking_op` is + * platform-dependent. It might impose some platform-dependent restrictions + * on the implementation of the blocking opearation. + * + * For example, on POSIX-like platforms, a signal (by default SIGUSR1) is + * used. The signal delivery configurations (eg. signal handler, signal mask, + * etc) for the signal are set up by the runtime. You can change the signal + * to use for this purpose by calling os_set_signal_number_for_blocking_op + * before the runtime initialization. + */ +WASM_RUNTIME_API_EXTERN bool +wasm_runtime_begin_blocking_op(wasm_exec_env_t exec_env); + +WASM_RUNTIME_API_EXTERN void +wasm_runtime_end_blocking_op(wasm_exec_env_t exec_env); + /* clang-format on */ #ifdef __cplusplus diff --git a/core/iwasm/interpreter/wasm_interp_classic.c b/core/iwasm/interpreter/wasm_interp_classic.c index 2a48c1bde..50860d3a3 100644 --- a/core/iwasm/interpreter/wasm_interp_classic.c +++ b/core/iwasm/interpreter/wasm_interp_classic.c @@ -1418,6 +1418,8 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, while (node_cache) { node_next = bh_list_elem_next(node_cache); if (node_cache->br_table_op_addr == frame_ip - 1) { + if (lidx > node_cache->br_count) + lidx = node_cache->br_count; depth = node_cache->br_depths[lidx]; goto label_pop_csp_n; } @@ -4209,7 +4211,6 @@ wasm_interp_call_wasm(WASMModuleInstance *module_inst, WASMExecEnv *exec_env, unsigned frame_size = wasm_interp_interp_frame_size(all_cell_num); unsigned i; bool copy_argv_from_frame = true; - char exception[EXCEPTION_BUF_LEN]; if (argc < function->param_cell_num) { char buf[128]; @@ -4342,8 +4343,6 @@ wasm_interp_call_wasm(WASMModuleInstance *module_inst, WASMExecEnv *exec_env, wasm_interp_dump_call_stack(exec_env, true, NULL, 0); } #endif - wasm_copy_exception(module_inst, exception); - LOG_DEBUG("meet an exception %s", exception); } wasm_exec_env_set_cur_frame(exec_env, prev_frame); diff --git a/core/iwasm/interpreter/wasm_interp_fast.c b/core/iwasm/interpreter/wasm_interp_fast.c index 229a2151d..e565c2c89 100644 --- a/core/iwasm/interpreter/wasm_interp_fast.c +++ b/core/iwasm/interpreter/wasm_interp_fast.c @@ -3945,7 +3945,6 @@ wasm_interp_call_wasm(WASMModuleInstance *module_inst, WASMExecEnv *exec_env, /* This frame won't be used by JITed code, so only allocate interp frame here. */ unsigned frame_size = wasm_interp_interp_frame_size(all_cell_num); - char exception[EXCEPTION_BUF_LEN]; if (argc < function->param_cell_num) { char buf[128]; @@ -4030,8 +4029,6 @@ wasm_interp_call_wasm(WASMModuleInstance *module_inst, WASMExecEnv *exec_env, wasm_interp_dump_call_stack(exec_env, true, NULL, 0); } #endif - wasm_copy_exception(module_inst, exception); - LOG_DEBUG("meet an exception %s", exception); } wasm_exec_env_set_cur_frame(exec_env, prev_frame); diff --git a/core/iwasm/interpreter/wasm_loader.c b/core/iwasm/interpreter/wasm_loader.c index c775ee6c0..cf8b7719c 100644 --- a/core/iwasm/interpreter/wasm_loader.c +++ b/core/iwasm/interpreter/wasm_loader.c @@ -694,34 +694,10 @@ wasm_loader_find_export(const WASMModule *module, const char *module_name, const char *field_name, uint8 export_kind, char *error_buf, uint32 error_buf_size) { - WASMExport *export; - uint32 i; - - for (i = 0, export = module->exports; i < module->export_count; - ++i, ++export) { - /** - * need to consider a scenario that different kinds of exports - * may have the same name, like - * (table (export "m1" "exported") 10 funcref) - * (memory (export "m1" "exported") 10) - **/ - if (export->kind == export_kind && !strcmp(field_name, export->name)) { - break; - } - } - - if (i == module->export_count) { - LOG_DEBUG("can not find an export %d named %s in the module %s", - export_kind, field_name, module_name); - set_error_buf(error_buf, error_buf_size, - "unknown import or incompatible import type"); - return NULL; - } - - (void)module_name; - - /* since there is a validation in load_export_section(), it is for sure - * export->index is valid*/ + WASMExport *export = + loader_find_export((WASMModuleCommon *)module, module_name, field_name, + export_kind, error_buf, error_buf_size); + ; return export; } #endif @@ -912,152 +888,6 @@ wasm_loader_resolve_global(const char *module_name, const char *global_name, return global; } -static WASMModule * -search_sub_module(const WASMModule *parent_module, const char *sub_module_name) -{ - WASMRegisteredModule *node = - bh_list_first_elem(parent_module->import_module_list); - while (node && strcmp(sub_module_name, node->module_name)) { - node = bh_list_elem_next(node); - } - return node ? (WASMModule *)node->module : NULL; -} - -static bool -register_sub_module(const WASMModule *parent_module, - const char *sub_module_name, WASMModule *sub_module) -{ - /* register sub_module into its parent sub module list */ - WASMRegisteredModule *node = NULL; - bh_list_status ret; - - if (search_sub_module(parent_module, sub_module_name)) { - LOG_DEBUG("%s has been registered in its parent", sub_module_name); - return true; - } - - node = loader_malloc(sizeof(WASMRegisteredModule), NULL, 0); - if (!node) { - return false; - } - - node->module_name = sub_module_name; - node->module = (WASMModuleCommon *)sub_module; - ret = bh_list_insert(parent_module->import_module_list, node); - bh_assert(BH_LIST_SUCCESS == ret); - (void)ret; - return true; -} - -static WASMModule * -load_depended_module(const WASMModule *parent_module, - const char *sub_module_name, char *error_buf, - uint32 error_buf_size) -{ - WASMModule *sub_module = NULL; - bool ret = false; - uint8 *buffer = NULL; - uint32 buffer_size = 0; - const module_reader reader = wasm_runtime_get_module_reader(); - const module_destroyer destroyer = wasm_runtime_get_module_destroyer(); - - /* check the registered module list of the parent */ - sub_module = search_sub_module(parent_module, sub_module_name); - if (sub_module) { - LOG_DEBUG("%s has been loaded before", sub_module_name); - return sub_module; - } - - /* check the global registered module list */ - sub_module = - (WASMModule *)wasm_runtime_find_module_registered(sub_module_name); - if (sub_module) { - LOG_DEBUG("%s has been loaded", sub_module_name); - goto register_sub_module; - } - - LOG_VERBOSE("loading %s", sub_module_name); - - if (!reader) { - set_error_buf_v(error_buf, error_buf_size, - "no sub module reader to load %s", sub_module_name); - return NULL; - } - - /* start to maintain a loading module list */ - ret = wasm_runtime_is_loading_module(sub_module_name); - if (ret) { - set_error_buf_v(error_buf, error_buf_size, - "found circular dependency on %s", sub_module_name); - return NULL; - } - - ret = wasm_runtime_add_loading_module(sub_module_name, error_buf, - error_buf_size); - if (!ret) { - LOG_DEBUG("can not add %s into loading module list\n", sub_module_name); - return NULL; - } - - ret = reader(sub_module_name, &buffer, &buffer_size); - if (!ret) { - LOG_DEBUG("read the file of %s failed", sub_module_name); - set_error_buf_v(error_buf, error_buf_size, "unknown import", - sub_module_name); - goto delete_loading_module; - } - - sub_module = - wasm_loader_load(buffer, buffer_size, false, error_buf, error_buf_size); - if (!sub_module) { - LOG_DEBUG("error: can not load the sub_module %s", sub_module_name); - /* others will be destroyed in runtime_destroy() */ - goto destroy_file_buffer; - } - - wasm_runtime_delete_loading_module(sub_module_name); - - /* register on a global list */ - ret = wasm_runtime_register_module_internal( - sub_module_name, (WASMModuleCommon *)sub_module, buffer, buffer_size, - error_buf, error_buf_size); - if (!ret) { - LOG_DEBUG("error: can not register module %s globally\n", - sub_module_name); - /* others will be unloaded in runtime_destroy() */ - goto unload_module; - } - - /* register into its parent list */ -register_sub_module: - ret = register_sub_module(parent_module, sub_module_name, sub_module); - if (!ret) { - set_error_buf_v(error_buf, error_buf_size, - "failed to register sub module %s", sub_module_name); - /* since it is in the global module list, no need to - * unload the module. the runtime_destroy() will do it - */ - return NULL; - } - - return sub_module; - -unload_module: - wasm_loader_unload(sub_module); - -destroy_file_buffer: - if (destroyer) { - destroyer(buffer, buffer_size); - } - else { - LOG_WARNING("need to release the reading buffer of %s manually", - sub_module_name); - } - -delete_loading_module: - wasm_runtime_delete_loading_module(sub_module_name); - return NULL; -} #endif /* end of WASM_ENABLE_MULTI_MODULE */ static bool @@ -1104,8 +934,9 @@ load_function_import(const uint8 **p_buf, const uint8 *buf_end, #if WASM_ENABLE_MULTI_MODULE != 0 else { if (!wasm_runtime_is_built_in_module(sub_module_name)) { - sub_module = load_depended_module(parent_module, sub_module_name, - error_buf, error_buf_size); + sub_module = (WASMModule *)wasm_runtime_load_depended_module( + (WASMModuleCommon *)parent_module, sub_module_name, error_buf, + error_buf_size); if (!sub_module) { return false; } @@ -1193,8 +1024,9 @@ load_table_import(const uint8 **p_buf, const uint8 *buf_end, #if WASM_ENABLE_MULTI_MODULE != 0 if (!wasm_runtime_is_built_in_module(sub_module_name)) { - sub_module = load_depended_module(parent_module, sub_module_name, - error_buf, error_buf_size); + sub_module = (WASMModule *)wasm_runtime_load_depended_module( + (WASMModuleCommon *)parent_module, sub_module_name, error_buf, + error_buf_size); if (!sub_module) { return false; } @@ -1327,8 +1159,9 @@ load_memory_import(const uint8 **p_buf, const uint8 *buf_end, #if WASM_ENABLE_MULTI_MODULE != 0 if (!wasm_runtime_is_built_in_module(sub_module_name)) { - sub_module = load_depended_module(parent_module, sub_module_name, - error_buf, error_buf_size); + sub_module = (WASMModule *)wasm_runtime_load_depended_module( + (WASMModuleCommon *)parent_module, sub_module_name, error_buf, + error_buf_size); if (!sub_module) { return false; } @@ -1427,8 +1260,9 @@ load_global_import(const uint8 **p_buf, const uint8 *buf_end, #if WASM_ENABLE_MULTI_MODULE != 0 if (!global->is_linked && !wasm_runtime_is_built_in_module(sub_module_name)) { - sub_module = load_depended_module(parent_module, sub_module_name, - error_buf, error_buf_size); + sub_module = (WASMModule *)wasm_runtime_load_depended_module( + (WASMModuleCommon *)parent_module, sub_module_name, error_buf, + error_buf_size); if (!sub_module) { return false; } @@ -5476,6 +5310,7 @@ wasm_loader_pop_frame_ref(WASMLoaderContext *ctx, uint8 type, char *error_buf, return true; } +#if WASM_ENABLE_FAST_INTERP == 0 static bool wasm_loader_push_pop_frame_ref(WASMLoaderContext *ctx, uint8 pop_cnt, uint8 type_push, uint8 type_pop, char *error_buf, @@ -5490,6 +5325,7 @@ wasm_loader_push_pop_frame_ref(WASMLoaderContext *ctx, uint8 pop_cnt, return false; return true; } +#endif static bool wasm_loader_push_frame_csp(WASMLoaderContext *ctx, uint8 label_type, @@ -6166,27 +6002,6 @@ wasm_loader_pop_frame_offset(WASMLoaderContext *ctx, uint8 type, return true; } -static bool -wasm_loader_push_pop_frame_offset(WASMLoaderContext *ctx, uint8 pop_cnt, - uint8 type_push, uint8 type_pop, - bool disable_emit, int16 operand_offset, - char *error_buf, uint32 error_buf_size) -{ - uint8 i; - - for (i = 0; i < pop_cnt; i++) { - if (!wasm_loader_pop_frame_offset(ctx, type_pop, error_buf, - error_buf_size)) - return false; - } - if (!wasm_loader_push_frame_offset(ctx, type_push, disable_emit, - operand_offset, error_buf, - error_buf_size)) - return false; - - return true; -} - static bool wasm_loader_push_frame_ref_offset(WASMLoaderContext *ctx, uint8 type, bool disable_emit, int16 operand_offset, @@ -6220,12 +6035,24 @@ wasm_loader_push_pop_frame_ref_offset(WASMLoaderContext *ctx, uint8 pop_cnt, bool disable_emit, int16 operand_offset, char *error_buf, uint32 error_buf_size) { - if (!wasm_loader_push_pop_frame_offset(ctx, pop_cnt, type_push, type_pop, - disable_emit, operand_offset, - error_buf, error_buf_size)) + uint8 i; + + for (i = 0; i < pop_cnt; i++) { + if (!wasm_loader_pop_frame_offset(ctx, type_pop, error_buf, + error_buf_size)) + return false; + + if (!wasm_loader_pop_frame_ref(ctx, type_pop, error_buf, + error_buf_size)) + return false; + } + + if (!wasm_loader_push_frame_offset(ctx, type_push, disable_emit, + operand_offset, error_buf, + error_buf_size)) return false; - if (!wasm_loader_push_pop_frame_ref(ctx, pop_cnt, type_push, type_pop, - error_buf, error_buf_size)) + + if (!wasm_loader_push_frame_ref(ctx, type_push, error_buf, error_buf_size)) return false; return true; diff --git a/core/iwasm/interpreter/wasm_mini_loader.c b/core/iwasm/interpreter/wasm_mini_loader.c index 9f568e132..d16bc1a24 100644 --- a/core/iwasm/interpreter/wasm_mini_loader.c +++ b/core/iwasm/interpreter/wasm_mini_loader.c @@ -3937,6 +3937,7 @@ wasm_loader_pop_frame_ref(WASMLoaderContext *ctx, uint8 type, char *error_buf, return true; } +#if WASM_ENABLE_FAST_INTERP == 0 static bool wasm_loader_push_pop_frame_ref(WASMLoaderContext *ctx, uint8 pop_cnt, uint8 type_push, uint8 type_pop, char *error_buf, @@ -3951,6 +3952,7 @@ wasm_loader_push_pop_frame_ref(WASMLoaderContext *ctx, uint8 pop_cnt, return false; return true; } +#endif static bool wasm_loader_push_frame_csp(WASMLoaderContext *ctx, uint8 label_type, @@ -4608,25 +4610,6 @@ wasm_loader_pop_frame_offset(WASMLoaderContext *ctx, uint8 type, return true; } -static bool -wasm_loader_push_pop_frame_offset(WASMLoaderContext *ctx, uint8 pop_cnt, - uint8 type_push, uint8 type_pop, - bool disable_emit, int16 operand_offset, - char *error_buf, uint32 error_buf_size) -{ - for (int i = 0; i < pop_cnt; i++) { - if (!wasm_loader_pop_frame_offset(ctx, type_pop, error_buf, - error_buf_size)) - return false; - } - if (!wasm_loader_push_frame_offset(ctx, type_push, disable_emit, - operand_offset, error_buf, - error_buf_size)) - return false; - - return true; -} - static bool wasm_loader_push_frame_ref_offset(WASMLoaderContext *ctx, uint8 type, bool disable_emit, int16 operand_offset, @@ -4660,12 +4643,24 @@ wasm_loader_push_pop_frame_ref_offset(WASMLoaderContext *ctx, uint8 pop_cnt, bool disable_emit, int16 operand_offset, char *error_buf, uint32 error_buf_size) { - if (!wasm_loader_push_pop_frame_offset(ctx, pop_cnt, type_push, type_pop, - disable_emit, operand_offset, - error_buf, error_buf_size)) + uint8 i; + + for (i = 0; i < pop_cnt; i++) { + if (!wasm_loader_pop_frame_offset(ctx, type_pop, error_buf, + error_buf_size)) + return false; + + if (!wasm_loader_pop_frame_ref(ctx, type_pop, error_buf, + error_buf_size)) + return false; + } + + if (!wasm_loader_push_frame_offset(ctx, type_push, disable_emit, + operand_offset, error_buf, + error_buf_size)) return false; - if (!wasm_loader_push_pop_frame_ref(ctx, pop_cnt, type_push, type_pop, - error_buf, error_buf_size)) + + if (!wasm_loader_push_frame_ref(ctx, type_push, error_buf, error_buf_size)) return false; return true; diff --git a/core/iwasm/interpreter/wasm_runtime.c b/core/iwasm/interpreter/wasm_runtime.c index 301038a4d..8fb19d52e 100644 --- a/core/iwasm/interpreter/wasm_runtime.c +++ b/core/iwasm/interpreter/wasm_runtime.c @@ -51,11 +51,15 @@ set_error_buf_v(char *error_buf, uint32 error_buf_size, const char *format, ...) } WASMModule * -wasm_load(uint8 *buf, uint32 size, char *error_buf, uint32 error_buf_size) +wasm_load(uint8 *buf, uint32 size, +#if WASM_ENABLE_MULTI_MODULE != 0 + bool main_module, +#endif + char *error_buf, uint32 error_buf_size) { return wasm_loader_load(buf, size, #if WASM_ENABLE_MULTI_MODULE != 0 - true, + main_module, #endif error_buf, error_buf_size); } @@ -1265,78 +1269,6 @@ execute_free_function(WASMModuleInstance *module_inst, WASMExecEnv *exec_env, return ret; } -#if WASM_ENABLE_MULTI_MODULE != 0 -static bool -sub_module_instantiate(WASMModule *module, WASMModuleInstance *module_inst, - uint32 stack_size, uint32 heap_size, char *error_buf, - uint32 error_buf_size) -{ - bh_list *sub_module_inst_list = module_inst->e->sub_module_inst_list; - WASMRegisteredModule *sub_module_list_node = - bh_list_first_elem(module->import_module_list); - - while (sub_module_list_node) { - WASMSubModInstNode *sub_module_inst_list_node = NULL; - WASMModule *sub_module = (WASMModule *)sub_module_list_node->module; - WASMModuleInstance *sub_module_inst = NULL; - - sub_module_inst = - wasm_instantiate(sub_module, NULL, NULL, stack_size, heap_size, - error_buf, error_buf_size); - if (!sub_module_inst) { - LOG_DEBUG("instantiate %s failed", - sub_module_list_node->module_name); - goto failed; - } - - sub_module_inst_list_node = runtime_malloc(sizeof(WASMSubModInstNode), - error_buf, error_buf_size); - if (!sub_module_inst_list_node) { - LOG_DEBUG("Malloc WASMSubModInstNode failed, SZ:%d", - sizeof(WASMSubModInstNode)); - goto failed; - } - - sub_module_inst_list_node->module_inst = sub_module_inst; - sub_module_inst_list_node->module_name = - sub_module_list_node->module_name; - bh_list_status ret = - bh_list_insert(sub_module_inst_list, sub_module_inst_list_node); - bh_assert(BH_LIST_SUCCESS == ret); - (void)ret; - - sub_module_list_node = bh_list_elem_next(sub_module_list_node); - - continue; - failed: - if (sub_module_inst_list_node) { - bh_list_remove(sub_module_inst_list, sub_module_inst_list_node); - wasm_runtime_free(sub_module_inst_list_node); - } - - if (sub_module_inst) - wasm_deinstantiate(sub_module_inst, false); - return false; - } - - return true; -} - -static void -sub_module_deinstantiate(WASMModuleInstance *module_inst) -{ - bh_list *list = module_inst->e->sub_module_inst_list; - WASMSubModInstNode *node = bh_list_first_elem(list); - while (node) { - WASMSubModInstNode *next_node = bh_list_elem_next(node); - bh_list_remove(list, node); - wasm_deinstantiate(node->module_inst, false); - wasm_runtime_free(node); - node = next_node; - } -} -#endif - static bool check_linked_symbol(WASMModuleInstance *module_inst, char *error_buf, uint32 error_buf_size) @@ -1713,8 +1645,9 @@ wasm_instantiate(WASMModule *module, WASMModuleInstance *parent, #if WASM_ENABLE_MULTI_MODULE != 0 module_inst->e->sub_module_inst_list = &module_inst->e->sub_module_inst_list_head; - ret = sub_module_instantiate(module, module_inst, stack_size, heap_size, - error_buf, error_buf_size); + ret = wasm_runtime_sub_module_instantiate( + (WASMModuleCommon *)module, (WASMModuleInstanceCommon *)module_inst, + stack_size, heap_size, error_buf, error_buf_size); if (!ret) { LOG_DEBUG("build a sub module list failed"); goto fail; @@ -2197,7 +2130,8 @@ wasm_deinstantiate(WASMModuleInstance *module_inst, bool is_sub_inst) #endif #if WASM_ENABLE_MULTI_MODULE != 0 - sub_module_deinstantiate(module_inst); + wasm_runtime_sub_module_deinstantiate( + (WASMModuleInstanceCommon *)module_inst); #endif if (module_inst->memory_count > 0) @@ -2981,6 +2915,7 @@ wasm_interp_create_call_stack(struct WASMExecEnv *exec_env) total_len += \ wasm_runtime_dump_line_buf_impl(line_buf, print, &buf, &len); \ if ((!print) && buf && (len == 0)) { \ + exception_unlock(module_inst); \ return total_len; \ } \ } while (0) @@ -3005,6 +2940,7 @@ wasm_interp_dump_call_stack(struct WASMExecEnv *exec_env, bool print, char *buf, return 0; } + exception_lock(module_inst); snprintf(line_buf, sizeof(line_buf), "\n"); PRINT_OR_DUMP(); @@ -3013,6 +2949,7 @@ wasm_interp_dump_call_stack(struct WASMExecEnv *exec_env, bool print, char *buf, uint32 line_length, i; if (!bh_vector_get(module_inst->frames, n, &frame)) { + exception_unlock(module_inst); return 0; } @@ -3043,6 +2980,7 @@ wasm_interp_dump_call_stack(struct WASMExecEnv *exec_env, bool print, char *buf, } snprintf(line_buf, sizeof(line_buf), "\n"); PRINT_OR_DUMP(); + exception_unlock(module_inst); return total_len + 1; } diff --git a/core/iwasm/interpreter/wasm_runtime.h b/core/iwasm/interpreter/wasm_runtime.h index 605cefc6c..d6661fa0f 100644 --- a/core/iwasm/interpreter/wasm_runtime.h +++ b/core/iwasm/interpreter/wasm_runtime.h @@ -396,7 +396,11 @@ wasm_get_func_code_end(WASMFunctionInstance *func) } WASMModule * -wasm_load(uint8 *buf, uint32 size, char *error_buf, uint32 error_buf_size); +wasm_load(uint8 *buf, uint32 size, +#if WASM_ENABLE_MULTI_MODULE != 0 + bool main_module, +#endif + char *error_buf, uint32 error_buf_size); WASMModule * wasm_load_from_sections(WASMSection *section_list, char *error_buf, diff --git a/core/iwasm/libraries/lib-wasi-threads/stress-test/build.sh b/core/iwasm/libraries/lib-wasi-threads/stress-test/build.sh index 341f3ef12..1ea95cb97 100755 --- a/core/iwasm/libraries/lib-wasi-threads/stress-test/build.sh +++ b/core/iwasm/libraries/lib-wasi-threads/stress-test/build.sh @@ -60,6 +60,7 @@ for test_c in *.c; do -Wl,--export=wasi_thread_start \ -Wl,--export=malloc \ -Wl,--export=free \ + -Wl,--export=test \ $sysroot_command \ $test_c -o $test_wasm done diff --git a/core/iwasm/libraries/lib-wasi-threads/stress-test/errorcheck_mutex_stress_test.c b/core/iwasm/libraries/lib-wasi-threads/stress-test/errorcheck_mutex_stress_test.c index 3b594657f..946e8bd63 100644 --- a/core/iwasm/libraries/lib-wasi-threads/stress-test/errorcheck_mutex_stress_test.c +++ b/core/iwasm/libraries/lib-wasi-threads/stress-test/errorcheck_mutex_stress_test.c @@ -7,8 +7,8 @@ #include #include "mutex_common.h" -int -main() +void +test() { pthread_mutex_t mutex; @@ -25,3 +25,10 @@ main() fprintf(stderr, "Errorcheck mutex test is completed\n"); pthread_mutex_destroy(&mutex); } + +int +main() +{ + test(); + return 0; +} diff --git a/core/iwasm/libraries/lib-wasi-threads/stress-test/normal_mutex_stress_test.c b/core/iwasm/libraries/lib-wasi-threads/stress-test/normal_mutex_stress_test.c index 6c75f8814..c7ffae279 100644 --- a/core/iwasm/libraries/lib-wasi-threads/stress-test/normal_mutex_stress_test.c +++ b/core/iwasm/libraries/lib-wasi-threads/stress-test/normal_mutex_stress_test.c @@ -7,8 +7,8 @@ #include #include "mutex_common.h" -int -main() +void +test() { pthread_mutex_t mutex; pthread_mutex_init(&mutex, NULL); @@ -18,3 +18,10 @@ main() fprintf(stderr, "Normal mutex test is completed\n"); pthread_mutex_destroy(&mutex); } + +int +main() +{ + test(); + return 0; +} diff --git a/core/iwasm/libraries/lib-wasi-threads/stress-test/recursive_mutex_stress_test.c b/core/iwasm/libraries/lib-wasi-threads/stress-test/recursive_mutex_stress_test.c index 8c3e325e8..5874372cb 100644 --- a/core/iwasm/libraries/lib-wasi-threads/stress-test/recursive_mutex_stress_test.c +++ b/core/iwasm/libraries/lib-wasi-threads/stress-test/recursive_mutex_stress_test.c @@ -31,8 +31,8 @@ same_thread_multiple_rec_mutex_lock(void *mutex) return NULL; } -int -main() +void +test() { pthread_mutex_t mutex; @@ -63,3 +63,10 @@ main() fprintf(stderr, "Recursive mutex test is completed\n"); pthread_mutex_destroy(&mutex); } + +int +main() +{ + test(); + return 0; +} diff --git a/core/iwasm/libraries/lib-wasi-threads/stress-test/spawn_stress_test.c b/core/iwasm/libraries/lib-wasi-threads/stress-test/spawn_stress_test.c index a35337f35..8cb61a2a6 100644 --- a/core/iwasm/libraries/lib-wasi-threads/stress-test/spawn_stress_test.c +++ b/core/iwasm/libraries/lib-wasi-threads/stress-test/spawn_stress_test.c @@ -16,13 +16,6 @@ #include #include -enum CONSTANTS { - NUM_ITER = 100000, - NUM_RETRY = 8, - MAX_NUM_THREADS = 12, - RETRY_SLEEP_TIME_US = 2000, -}; - unsigned prime_numbers_count = 0; bool @@ -49,10 +42,10 @@ check_if_prime(void *value) } unsigned int -validate() +validate(int iter_num) { unsigned int counter = 0; - for (unsigned int i = 2; i <= NUM_ITER; ++i) { + for (unsigned int i = 2; i <= iter_num; ++i) { counter += is_prime(i); } @@ -60,11 +53,12 @@ validate() } void -spawn_thread(pthread_t *thread, unsigned int *arg) +spawn_thread(pthread_t *thread, int retry_time_us, int retry_num, + unsigned int *arg) { int status_code = -1; - int timeout_us = RETRY_SLEEP_TIME_US; - for (int tries = 0; status_code != 0 && tries < NUM_RETRY; ++tries) { + int timeout_us = retry_time_us; + for (int tries = 0; status_code != 0 && tries < retry_num; ++tries) { status_code = pthread_create(thread, NULL, &check_if_prime, arg); assert(status_code == 0 || status_code == EAGAIN); if (status_code == EAGAIN) { @@ -76,42 +70,56 @@ spawn_thread(pthread_t *thread, unsigned int *arg) assert(status_code == 0 && "Thread creation should succeed"); } -int -main(int argc, char **argv) +void +test(int iter_num, int retry_num, int max_threads_num, int retry_time_us) { - pthread_t threads[MAX_NUM_THREADS]; - unsigned int args[MAX_NUM_THREADS]; + pthread_t threads[max_threads_num]; + unsigned int args[max_threads_num]; double percentage = 0.1; - for (unsigned int factorised_number = 2; factorised_number < NUM_ITER; + for (unsigned int factorised_number = 2; factorised_number < iter_num; ++factorised_number) { - if (factorised_number > NUM_ITER * percentage) { + if (factorised_number > iter_num * percentage) { fprintf(stderr, "Stress test is %d%% finished\n", (unsigned int)(percentage * 100)); percentage += 0.1; } - unsigned int thread_num = factorised_number % MAX_NUM_THREADS; + unsigned int thread_num = factorised_number % max_threads_num; if (threads[thread_num] != 0) { assert(pthread_join(threads[thread_num], NULL) == 0); } args[thread_num] = factorised_number; - usleep(RETRY_SLEEP_TIME_US); - spawn_thread(&threads[thread_num], &args[thread_num]); + usleep(retry_time_us); + spawn_thread(&threads[thread_num], retry_time_us, retry_num, + &args[thread_num]); assert(threads[thread_num] != 0); } - for (int i = 0; i < MAX_NUM_THREADS; ++i) { + for (int i = 0; i < max_threads_num; ++i) { assert(threads[i] == 0 || pthread_join(threads[i], NULL) == 0); } // Check the test results assert( - prime_numbers_count == validate() + prime_numbers_count == validate(iter_num) && "Answer mismatch between tested code and reference implementation"); fprintf(stderr, "Stress test finished successfully\n"); +} + +enum DEFAULT_PARAMETERS { + ITER_NUM = 20000, + RETRY_NUM = 8, + MAX_THREADS_NUM = 12, + RETRY_SLEEP_TIME_US = 2000, +}; + +int +main(int argc, char **argv) +{ + test(ITER_NUM, RETRY_NUM, MAX_THREADS_NUM, RETRY_SLEEP_TIME_US); return 0; } diff --git a/core/iwasm/libraries/lib-wasi-threads/stress-test/stress_test_threads_creation.c b/core/iwasm/libraries/lib-wasi-threads/stress-test/stress_test_threads_creation.c index f991fa7ab..c4c2d2857 100644 --- a/core/iwasm/libraries/lib-wasi-threads/stress-test/stress_test_threads_creation.c +++ b/core/iwasm/libraries/lib-wasi-threads/stress-test/stress_test_threads_creation.c @@ -9,14 +9,6 @@ #include #include -enum CONSTANTS { - NUM_ITER = 200000, - NUM_RETRY = 8, - MAX_NUM_THREADS = 12, - RETRY_SLEEP_TIME_US = 4000, - SECOND = 1000 * 1000 * 1000 -}; - int threads_executed = 0; unsigned int threads_creation_tried = 0; unsigned int threads_in_use = 0; @@ -31,11 +23,11 @@ thread_func(void *arg) } void -spawn_thread(pthread_t *thread) +spawn_thread(pthread_t *thread, int retry_time, int iter_num) { int status_code = -1; - int timeout_us = RETRY_SLEEP_TIME_US; - for (int tries = 0; status_code != 0 && tries < NUM_RETRY; ++tries) { + int timeout_us = retry_time; + for (int tries = 0; status_code != 0 && tries < iter_num; ++tries) { status_code = pthread_create(thread, NULL, &thread_func, NULL); __atomic_fetch_add(&threads_creation_tried, 1, __ATOMIC_RELAXED); @@ -49,32 +41,33 @@ spawn_thread(pthread_t *thread) assert(status_code == 0 && "Thread creation should succeed"); } -int -main(int argc, char **argv) +void +test(int iter_num, int max_threads_num, int retry_num, int retry_time_us) { double percentage = 0.1; + int second_us = 1000 * 1000 * 1000; // 1 second in us - for (int iter = 0; iter < NUM_ITER; ++iter) { - if (iter > NUM_ITER * percentage) { + for (int iter = 0; iter < iter_num; ++iter) { + if (iter > iter_num * percentage) { fprintf(stderr, "Spawning stress test is %d%% finished\n", (unsigned int)(percentage * 100)); percentage += 0.1; } while (__atomic_load_n(&threads_in_use, __ATOMIC_SEQ_CST) - == MAX_NUM_THREADS) { + == max_threads_num) { usleep(100); } __atomic_fetch_add(&threads_in_use, 1, __ATOMIC_SEQ_CST); pthread_t tmp; - spawn_thread(&tmp); + spawn_thread(&tmp, retry_time_us, iter_num); pthread_detach(tmp); } while ((__atomic_load_n(&threads_in_use, __ATOMIC_SEQ_CST) != 0)) { // Casting to int* to supress compiler warning __builtin_wasm_memory_atomic_wait32((int *)(&threads_in_use), 0, - SECOND); + second_us); } assert(__atomic_load_n(&threads_in_use, __ATOMIC_SEQ_CST) == 0); @@ -91,5 +84,18 @@ main(int argc, char **argv) "with retry ratio %f\n", threads_creation_tried, (1. * threads_creation_tried) / threads_executed); +} + +enum DEFAULT_PARAMETERS { + ITER_NUM = 50000, + RETRY_NUM = 8, + MAX_NUM_THREADS = 12, + RETRY_SLEEP_TIME_US = 4000, +}; + +int +main(int argc, char **argv) +{ + test(ITER_NUM, MAX_NUM_THREADS, RETRY_NUM, RETRY_SLEEP_TIME_US); return 0; } diff --git a/core/iwasm/libraries/libc-wasi/libc_wasi_wrapper.c b/core/iwasm/libraries/libc-wasi/libc_wasi_wrapper.c index 70ac4dc54..292bd8379 100644 --- a/core/iwasm/libraries/libc-wasi/libc_wasi_wrapper.c +++ b/core/iwasm/libraries/libc-wasi/libc_wasi_wrapper.c @@ -335,7 +335,7 @@ wasi_fd_close(wasm_exec_env_t exec_env, wasi_fd_t fd) if (!wasi_ctx) return (wasi_errno_t)-1; - return wasmtime_ssp_fd_close(curfds, prestats, fd); + return wasmtime_ssp_fd_close(exec_env, curfds, prestats, fd); } static wasi_errno_t @@ -348,7 +348,7 @@ wasi_fd_datasync(wasm_exec_env_t exec_env, wasi_fd_t fd) if (!wasi_ctx) return (wasi_errno_t)-1; - return wasmtime_ssp_fd_datasync(curfds, fd); + return wasmtime_ssp_fd_datasync(exec_env, curfds, fd); } static wasi_errno_t @@ -389,8 +389,8 @@ wasi_fd_pread(wasm_exec_env_t exec_env, wasi_fd_t fd, iovec_app_t *iovec_app, iovec->buf_len = iovec_app->buf_len; } - err = wasmtime_ssp_fd_pread(curfds, fd, iovec_begin, iovs_len, offset, - &nread); + err = wasmtime_ssp_fd_pread(exec_env, curfds, fd, iovec_begin, iovs_len, + offset, &nread); if (err) goto fail; @@ -443,8 +443,8 @@ wasi_fd_pwrite(wasm_exec_env_t exec_env, wasi_fd_t fd, ciovec->buf_len = iovec_app->buf_len; } - err = wasmtime_ssp_fd_pwrite(curfds, fd, ciovec_begin, iovs_len, offset, - &nwritten); + err = wasmtime_ssp_fd_pwrite(exec_env, curfds, fd, ciovec_begin, iovs_len, + offset, &nwritten); if (err) goto fail; @@ -496,7 +496,8 @@ wasi_fd_read(wasm_exec_env_t exec_env, wasi_fd_t fd, iovec->buf_len = iovec_app->buf_len; } - err = wasmtime_ssp_fd_read(curfds, fd, iovec_begin, iovs_len, &nread); + err = wasmtime_ssp_fd_read(exec_env, curfds, fd, iovec_begin, iovs_len, + &nread); if (err) goto fail; @@ -521,7 +522,7 @@ wasi_fd_renumber(wasm_exec_env_t exec_env, wasi_fd_t from, wasi_fd_t to) if (!wasi_ctx) return (wasi_errno_t)-1; - return wasmtime_ssp_fd_renumber(curfds, prestats, from, to); + return wasmtime_ssp_fd_renumber(exec_env, curfds, prestats, from, to); } static wasi_errno_t @@ -538,7 +539,8 @@ wasi_fd_seek(wasm_exec_env_t exec_env, wasi_fd_t fd, wasi_filedelta_t offset, if (!validate_native_addr(newoffset, sizeof(wasi_filesize_t))) return (wasi_errno_t)-1; - return wasmtime_ssp_fd_seek(curfds, fd, offset, whence, newoffset); + return wasmtime_ssp_fd_seek(exec_env, curfds, fd, offset, whence, + newoffset); } static wasi_errno_t @@ -554,7 +556,7 @@ wasi_fd_tell(wasm_exec_env_t exec_env, wasi_fd_t fd, wasi_filesize_t *newoffset) if (!validate_native_addr(newoffset, sizeof(wasi_filesize_t))) return (wasi_errno_t)-1; - return wasmtime_ssp_fd_tell(curfds, fd, newoffset); + return wasmtime_ssp_fd_tell(exec_env, curfds, fd, newoffset); } static wasi_errno_t @@ -573,7 +575,7 @@ wasi_fd_fdstat_get(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!validate_native_addr(fdstat_app, sizeof(wasi_fdstat_t))) return (wasi_errno_t)-1; - err = wasmtime_ssp_fd_fdstat_get(curfds, fd, &fdstat); + err = wasmtime_ssp_fd_fdstat_get(exec_env, curfds, fd, &fdstat); if (err) return err; @@ -592,7 +594,7 @@ wasi_fd_fdstat_set_flags(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return (wasi_errno_t)-1; - return wasmtime_ssp_fd_fdstat_set_flags(curfds, fd, flags); + return wasmtime_ssp_fd_fdstat_set_flags(exec_env, curfds, fd, flags); } static wasi_errno_t @@ -607,8 +609,8 @@ wasi_fd_fdstat_set_rights(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return (wasi_errno_t)-1; - return wasmtime_ssp_fd_fdstat_set_rights(curfds, fd, fs_rights_base, - fs_rights_inheriting); + return wasmtime_ssp_fd_fdstat_set_rights( + exec_env, curfds, fd, fs_rights_base, fs_rights_inheriting); } static wasi_errno_t @@ -621,7 +623,7 @@ wasi_fd_sync(wasm_exec_env_t exec_env, wasi_fd_t fd) if (!wasi_ctx) return (wasi_errno_t)-1; - return wasmtime_ssp_fd_sync(curfds, fd); + return wasmtime_ssp_fd_sync(exec_env, curfds, fd); } static wasi_errno_t @@ -663,7 +665,8 @@ wasi_fd_write(wasm_exec_env_t exec_env, wasi_fd_t fd, ciovec->buf_len = iovec_app->buf_len; } - err = wasmtime_ssp_fd_write(curfds, fd, ciovec_begin, iovs_len, &nwritten); + err = wasmtime_ssp_fd_write(exec_env, curfds, fd, ciovec_begin, iovs_len, + &nwritten); if (err) goto fail; @@ -688,7 +691,7 @@ wasi_fd_advise(wasm_exec_env_t exec_env, wasi_fd_t fd, wasi_filesize_t offset, if (!wasi_ctx) return (wasi_errno_t)-1; - return wasmtime_ssp_fd_advise(curfds, fd, offset, len, advice); + return wasmtime_ssp_fd_advise(exec_env, curfds, fd, offset, len, advice); } static wasi_errno_t @@ -702,7 +705,7 @@ wasi_fd_allocate(wasm_exec_env_t exec_env, wasi_fd_t fd, wasi_filesize_t offset, if (!wasi_ctx) return (wasi_errno_t)-1; - return wasmtime_ssp_fd_allocate(curfds, fd, offset, len); + return wasmtime_ssp_fd_allocate(exec_env, curfds, fd, offset, len); } static wasi_errno_t @@ -716,7 +719,8 @@ wasi_path_create_directory(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return (wasi_errno_t)-1; - return wasmtime_ssp_path_create_directory(curfds, fd, path, path_len); + return wasmtime_ssp_path_create_directory(exec_env, curfds, fd, path, + path_len); } static wasi_errno_t @@ -733,8 +737,9 @@ wasi_path_link(wasm_exec_env_t exec_env, wasi_fd_t old_fd, if (!wasi_ctx) return (wasi_errno_t)-1; - return wasmtime_ssp_path_link(curfds, prestats, old_fd, old_flags, old_path, - old_path_len, new_fd, new_path, new_path_len); + return wasmtime_ssp_path_link(exec_env, curfds, prestats, old_fd, old_flags, + old_path, old_path_len, new_fd, new_path, + new_path_len); } static wasi_errno_t @@ -756,9 +761,9 @@ wasi_path_open(wasm_exec_env_t exec_env, wasi_fd_t dirfd, if (!validate_native_addr(fd_app, sizeof(wasi_fd_t))) return (wasi_errno_t)-1; - err = wasmtime_ssp_path_open(curfds, dirfd, dirflags, path, path_len, - oflags, fs_rights_base, fs_rights_inheriting, - fs_flags, &fd); + err = wasmtime_ssp_path_open(exec_env, curfds, dirfd, dirflags, path, + path_len, oflags, fs_rights_base, + fs_rights_inheriting, fs_flags, &fd); *fd_app = fd; return err; @@ -780,7 +785,8 @@ wasi_fd_readdir(wasm_exec_env_t exec_env, wasi_fd_t fd, void *buf, if (!validate_native_addr(bufused_app, sizeof(uint32))) return (wasi_errno_t)-1; - err = wasmtime_ssp_fd_readdir(curfds, fd, buf, buf_len, cookie, &bufused); + err = wasmtime_ssp_fd_readdir(exec_env, curfds, fd, buf, buf_len, cookie, + &bufused); if (err) return err; @@ -805,8 +811,8 @@ wasi_path_readlink(wasm_exec_env_t exec_env, wasi_fd_t fd, const char *path, if (!validate_native_addr(bufused_app, sizeof(uint32))) return (wasi_errno_t)-1; - err = wasmtime_ssp_path_readlink(curfds, fd, path, path_len, buf, buf_len, - &bufused); + err = wasmtime_ssp_path_readlink(exec_env, curfds, fd, path, path_len, buf, + buf_len, &bufused); if (err) return err; @@ -826,8 +832,9 @@ wasi_path_rename(wasm_exec_env_t exec_env, wasi_fd_t old_fd, if (!wasi_ctx) return (wasi_errno_t)-1; - return wasmtime_ssp_path_rename(curfds, old_fd, old_path, old_path_len, - new_fd, new_path, new_path_len); + return wasmtime_ssp_path_rename(exec_env, curfds, old_fd, old_path, + old_path_len, new_fd, new_path, + new_path_len); } static wasi_errno_t @@ -844,7 +851,7 @@ wasi_fd_filestat_get(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!validate_native_addr(filestat, sizeof(wasi_filestat_t))) return (wasi_errno_t)-1; - return wasmtime_ssp_fd_filestat_get(curfds, fd, filestat); + return wasmtime_ssp_fd_filestat_get(exec_env, curfds, fd, filestat); } static wasi_errno_t @@ -859,8 +866,8 @@ wasi_fd_filestat_set_times(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return (wasi_errno_t)-1; - return wasmtime_ssp_fd_filestat_set_times(curfds, fd, st_atim, st_mtim, - fstflags); + return wasmtime_ssp_fd_filestat_set_times(exec_env, curfds, fd, st_atim, + st_mtim, fstflags); } static wasi_errno_t @@ -874,7 +881,7 @@ wasi_fd_filestat_set_size(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return (wasi_errno_t)-1; - return wasmtime_ssp_fd_filestat_set_size(curfds, fd, st_size); + return wasmtime_ssp_fd_filestat_set_size(exec_env, curfds, fd, st_size); } static wasi_errno_t @@ -892,8 +899,8 @@ wasi_path_filestat_get(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!validate_native_addr(filestat, sizeof(wasi_filestat_t))) return (wasi_errno_t)-1; - return wasmtime_ssp_path_filestat_get(curfds, fd, flags, path, path_len, - filestat); + return wasmtime_ssp_path_filestat_get(exec_env, curfds, fd, flags, path, + path_len, filestat); } static wasi_errno_t @@ -909,8 +916,9 @@ wasi_path_filestat_set_times(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return (wasi_errno_t)-1; - return wasmtime_ssp_path_filestat_set_times( - curfds, fd, flags, path, path_len, st_atim, st_mtim, fstflags); + return wasmtime_ssp_path_filestat_set_times(exec_env, curfds, fd, flags, + path, path_len, st_atim, + st_mtim, fstflags); } static wasi_errno_t @@ -926,8 +934,8 @@ wasi_path_symlink(wasm_exec_env_t exec_env, const char *old_path, if (!wasi_ctx) return (wasi_errno_t)-1; - return wasmtime_ssp_path_symlink(curfds, prestats, old_path, old_path_len, - fd, new_path, new_path_len); + return wasmtime_ssp_path_symlink(exec_env, curfds, prestats, old_path, + old_path_len, fd, new_path, new_path_len); } static wasi_errno_t @@ -941,7 +949,7 @@ wasi_path_unlink_file(wasm_exec_env_t exec_env, wasi_fd_t fd, const char *path, if (!wasi_ctx) return (wasi_errno_t)-1; - return wasmtime_ssp_path_unlink_file(curfds, fd, path, path_len); + return wasmtime_ssp_path_unlink_file(exec_env, curfds, fd, path, path_len); } static wasi_errno_t @@ -955,7 +963,8 @@ wasi_path_remove_directory(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return (wasi_errno_t)-1; - return wasmtime_ssp_path_remove_directory(curfds, fd, path, path_len); + return wasmtime_ssp_path_remove_directory(exec_env, curfds, fd, path, + path_len); } #if WASM_ENABLE_THREAD_MGR != 0 @@ -1026,8 +1035,8 @@ execute_interruptible_poll_oneoff( /* update timeout for clock subscription events */ update_clock_subscription_data( in_copy, nsubscriptions, min_uint64(time_quant, timeout - elapsed)); - err = wasmtime_ssp_poll_oneoff(curfds, in_copy, out, nsubscriptions, - nevents); + err = wasmtime_ssp_poll_oneoff(exec_env, curfds, in_copy, out, + nsubscriptions, nevents); elapsed += time_quant; if (err) { @@ -1079,7 +1088,8 @@ wasi_poll_oneoff(wasm_exec_env_t exec_env, const wasi_subscription_t *in, return (wasi_errno_t)-1; #if WASM_ENABLE_THREAD_MGR == 0 - err = wasmtime_ssp_poll_oneoff(curfds, in, out, nsubscriptions, &nevents); + err = wasmtime_ssp_poll_oneoff(exec_env, curfds, in, out, nsubscriptions, + &nevents); #else err = execute_interruptible_poll_oneoff(curfds, in, out, nsubscriptions, &nevents, exec_env); @@ -1133,7 +1143,7 @@ wasi_sock_accept(wasm_exec_env_t exec_env, wasi_fd_t fd, wasi_fdflags_t flags, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasi_ssp_sock_accept(curfds, fd, flags, fd_new); + return wasi_ssp_sock_accept(exec_env, curfds, fd, flags, fd_new); } static wasi_errno_t @@ -1152,7 +1162,7 @@ wasi_sock_addr_local(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasi_ssp_sock_addr_local(curfds, fd, addr); + return wasi_ssp_sock_addr_local(exec_env, curfds, fd, addr); } static wasi_errno_t @@ -1171,7 +1181,7 @@ wasi_sock_addr_remote(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasi_ssp_sock_addr_remote(curfds, fd, addr); + return wasi_ssp_sock_addr_remote(exec_env, curfds, fd, addr); } static wasi_errno_t @@ -1192,8 +1202,8 @@ wasi_sock_addr_resolve(wasm_exec_env_t exec_env, const char *host, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); ns_lookup_list = wasi_ctx_get_ns_lookup_list(wasi_ctx); - return wasi_ssp_sock_addr_resolve(curfds, ns_lookup_list, host, service, - hints, addr_info, addr_info_size, + return wasi_ssp_sock_addr_resolve(exec_env, curfds, ns_lookup_list, host, + service, hints, addr_info, addr_info_size, max_info_size); } @@ -1211,7 +1221,7 @@ wasi_sock_bind(wasm_exec_env_t exec_env, wasi_fd_t fd, wasi_addr_t *addr) curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); addr_pool = wasi_ctx_get_addr_pool(module_inst, wasi_ctx); - return wasi_ssp_sock_bind(curfds, addr_pool, fd, addr); + return wasi_ssp_sock_bind(exec_env, curfds, addr_pool, fd, addr); } static wasi_errno_t @@ -1234,7 +1244,7 @@ wasi_sock_connect(wasm_exec_env_t exec_env, wasi_fd_t fd, wasi_addr_t *addr) curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); addr_pool = wasi_ctx_get_addr_pool(module_inst, wasi_ctx); - return wasi_ssp_sock_connect(curfds, addr_pool, fd, addr); + return wasi_ssp_sock_connect(exec_env, curfds, addr_pool, fd, addr); } static wasi_errno_t @@ -1253,7 +1263,7 @@ wasi_sock_get_broadcast(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_get_broadcast(curfds, fd, is_enabled); + return wasmtime_ssp_sock_get_broadcast(exec_env, curfds, fd, is_enabled); } static wasi_errno_t @@ -1272,7 +1282,7 @@ wasi_sock_get_keep_alive(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_get_keep_alive(curfds, fd, is_enabled); + return wasmtime_ssp_sock_get_keep_alive(exec_env, curfds, fd, is_enabled); } static wasi_errno_t @@ -1292,7 +1302,8 @@ wasi_sock_get_linger(wasm_exec_env_t exec_env, wasi_fd_t fd, bool *is_enabled, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_get_linger(curfds, fd, is_enabled, linger_s); + return wasmtime_ssp_sock_get_linger(exec_env, curfds, fd, is_enabled, + linger_s); } static wasi_errno_t @@ -1311,7 +1322,7 @@ wasi_sock_get_recv_buf_size(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_get_recv_buf_size(curfds, fd, size); + return wasmtime_ssp_sock_get_recv_buf_size(exec_env, curfds, fd, size); } static wasi_errno_t @@ -1330,7 +1341,7 @@ wasi_sock_get_recv_timeout(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_get_recv_timeout(curfds, fd, timeout_us); + return wasmtime_ssp_sock_get_recv_timeout(exec_env, curfds, fd, timeout_us); } static wasi_errno_t @@ -1349,7 +1360,7 @@ wasi_sock_get_reuse_addr(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_get_reuse_addr(curfds, fd, is_enabled); + return wasmtime_ssp_sock_get_reuse_addr(exec_env, curfds, fd, is_enabled); } static wasi_errno_t @@ -1368,7 +1379,7 @@ wasi_sock_get_reuse_port(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_get_reuse_port(curfds, fd, is_enabled); + return wasmtime_ssp_sock_get_reuse_port(exec_env, curfds, fd, is_enabled); } static wasi_errno_t @@ -1387,7 +1398,7 @@ wasi_sock_get_send_buf_size(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_get_send_buf_size(curfds, fd, size); + return wasmtime_ssp_sock_get_send_buf_size(exec_env, curfds, fd, size); } static wasi_errno_t @@ -1406,7 +1417,7 @@ wasi_sock_get_send_timeout(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_get_send_timeout(curfds, fd, timeout_us); + return wasmtime_ssp_sock_get_send_timeout(exec_env, curfds, fd, timeout_us); } static wasi_errno_t @@ -1425,7 +1436,8 @@ wasi_sock_get_tcp_fastopen_connect(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_get_tcp_fastopen_connect(curfds, fd, is_enabled); + return wasmtime_ssp_sock_get_tcp_fastopen_connect(exec_env, curfds, fd, + is_enabled); } static wasi_errno_t @@ -1444,7 +1456,7 @@ wasi_sock_get_tcp_no_delay(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_get_tcp_no_delay(curfds, fd, is_enabled); + return wasmtime_ssp_sock_get_tcp_no_delay(exec_env, curfds, fd, is_enabled); } static wasi_errno_t @@ -1463,7 +1475,8 @@ wasi_sock_get_tcp_quick_ack(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_get_tcp_quick_ack(curfds, fd, is_enabled); + return wasmtime_ssp_sock_get_tcp_quick_ack(exec_env, curfds, fd, + is_enabled); } static wasi_errno_t @@ -1482,7 +1495,7 @@ wasi_sock_get_tcp_keep_idle(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_get_tcp_keep_idle(curfds, fd, time_s); + return wasmtime_ssp_sock_get_tcp_keep_idle(exec_env, curfds, fd, time_s); } static wasi_errno_t @@ -1501,7 +1514,7 @@ wasi_sock_get_tcp_keep_intvl(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_get_tcp_keep_intvl(curfds, fd, time_s); + return wasmtime_ssp_sock_get_tcp_keep_intvl(exec_env, curfds, fd, time_s); } static wasi_errno_t @@ -1520,7 +1533,7 @@ wasi_sock_get_ip_multicast_loop(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_get_ip_multicast_loop(curfds, fd, ipv6, + return wasmtime_ssp_sock_get_ip_multicast_loop(exec_env, curfds, fd, ipv6, is_enabled); } @@ -1539,7 +1552,7 @@ wasi_sock_get_ip_ttl(wasm_exec_env_t exec_env, wasi_fd_t fd, uint8_t *ttl_s) curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_get_ip_ttl(curfds, fd, ttl_s); + return wasmtime_ssp_sock_get_ip_ttl(exec_env, curfds, fd, ttl_s); } static wasi_errno_t @@ -1558,7 +1571,7 @@ wasi_sock_get_ip_multicast_ttl(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_get_ip_multicast_ttl(curfds, fd, ttl_s); + return wasmtime_ssp_sock_get_ip_multicast_ttl(exec_env, curfds, fd, ttl_s); } static wasi_errno_t @@ -1577,7 +1590,7 @@ wasi_sock_get_ipv6_only(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_get_ipv6_only(curfds, fd, is_enabled); + return wasmtime_ssp_sock_get_ipv6_only(exec_env, curfds, fd, is_enabled); } static wasi_errno_t @@ -1592,7 +1605,7 @@ wasi_sock_listen(wasm_exec_env_t exec_env, wasi_fd_t fd, uint32 backlog) curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasi_ssp_sock_listen(curfds, fd, backlog); + return wasi_ssp_sock_listen(exec_env, curfds, fd, backlog); } static wasi_errno_t @@ -1609,7 +1622,7 @@ wasi_sock_open(wasm_exec_env_t exec_env, wasi_fd_t poolfd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasi_ssp_sock_open(curfds, poolfd, af, socktype, sockfd); + return wasi_ssp_sock_open(exec_env, curfds, poolfd, af, socktype, sockfd); } static wasi_errno_t @@ -1624,7 +1637,7 @@ wasi_sock_set_broadcast(wasm_exec_env_t exec_env, wasi_fd_t fd, bool is_enabled) curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_set_broadcast(curfds, fd, is_enabled); + return wasmtime_ssp_sock_set_broadcast(exec_env, curfds, fd, is_enabled); } static wasi_errno_t @@ -1640,7 +1653,7 @@ wasi_sock_set_keep_alive(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_set_keep_alive(curfds, fd, is_enabled); + return wasmtime_ssp_sock_set_keep_alive(exec_env, curfds, fd, is_enabled); } static wasi_errno_t @@ -1656,7 +1669,8 @@ wasi_sock_set_linger(wasm_exec_env_t exec_env, wasi_fd_t fd, bool is_enabled, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_set_linger(curfds, fd, is_enabled, linger_s); + return wasmtime_ssp_sock_set_linger(exec_env, curfds, fd, is_enabled, + linger_s); } static wasi_errno_t @@ -1671,7 +1685,7 @@ wasi_sock_set_recv_buf_size(wasm_exec_env_t exec_env, wasi_fd_t fd, size_t size) curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_set_recv_buf_size(curfds, fd, size); + return wasmtime_ssp_sock_set_recv_buf_size(exec_env, curfds, fd, size); } static wasi_errno_t @@ -1687,7 +1701,7 @@ wasi_sock_set_recv_timeout(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_set_recv_timeout(curfds, fd, timeout_us); + return wasmtime_ssp_sock_set_recv_timeout(exec_env, curfds, fd, timeout_us); } static wasi_errno_t @@ -1703,7 +1717,7 @@ wasi_sock_set_reuse_addr(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_set_reuse_addr(curfds, fd, is_enabled); + return wasmtime_ssp_sock_set_reuse_addr(exec_env, curfds, fd, is_enabled); } static wasi_errno_t @@ -1719,7 +1733,7 @@ wasi_sock_set_reuse_port(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_set_reuse_port(curfds, fd, is_enabled); + return wasmtime_ssp_sock_set_reuse_port(exec_env, curfds, fd, is_enabled); } static wasi_errno_t @@ -1734,7 +1748,7 @@ wasi_sock_set_send_buf_size(wasm_exec_env_t exec_env, wasi_fd_t fd, size_t size) curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_set_send_buf_size(curfds, fd, size); + return wasmtime_ssp_sock_set_send_buf_size(exec_env, curfds, fd, size); } static wasi_errno_t @@ -1750,7 +1764,7 @@ wasi_sock_set_send_timeout(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_set_send_timeout(curfds, fd, timeout_us); + return wasmtime_ssp_sock_set_send_timeout(exec_env, curfds, fd, timeout_us); } static wasi_errno_t @@ -1766,7 +1780,8 @@ wasi_sock_set_tcp_fastopen_connect(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_set_tcp_fastopen_connect(curfds, fd, is_enabled); + return wasmtime_ssp_sock_set_tcp_fastopen_connect(exec_env, curfds, fd, + is_enabled); } static wasi_errno_t @@ -1782,7 +1797,7 @@ wasi_sock_set_tcp_no_delay(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_set_tcp_no_delay(curfds, fd, is_enabled); + return wasmtime_ssp_sock_set_tcp_no_delay(exec_env, curfds, fd, is_enabled); } static wasi_errno_t @@ -1798,7 +1813,8 @@ wasi_sock_set_tcp_quick_ack(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_set_tcp_quick_ack(curfds, fd, is_enabled); + return wasmtime_ssp_sock_set_tcp_quick_ack(exec_env, curfds, fd, + is_enabled); } static wasi_errno_t @@ -1814,7 +1830,7 @@ wasi_sock_set_tcp_keep_idle(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_set_tcp_keep_idle(curfds, fd, time_s); + return wasmtime_ssp_sock_set_tcp_keep_idle(exec_env, curfds, fd, time_s); } static wasi_errno_t @@ -1830,7 +1846,7 @@ wasi_sock_set_tcp_keep_intvl(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_set_tcp_keep_intvl(curfds, fd, time_s); + return wasmtime_ssp_sock_set_tcp_keep_intvl(exec_env, curfds, fd, time_s); } static wasi_errno_t @@ -1846,7 +1862,7 @@ wasi_sock_set_ip_multicast_loop(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_set_ip_multicast_loop(curfds, fd, ipv6, + return wasmtime_ssp_sock_set_ip_multicast_loop(exec_env, curfds, fd, ipv6, is_enabled); } @@ -1867,8 +1883,8 @@ wasi_sock_set_ip_add_membership(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_set_ip_add_membership(curfds, fd, imr_multiaddr, - imr_interface); + return wasmtime_ssp_sock_set_ip_add_membership( + exec_env, curfds, fd, imr_multiaddr, imr_interface); } static wasi_errno_t @@ -1888,8 +1904,8 @@ wasi_sock_set_ip_drop_membership(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_set_ip_drop_membership(curfds, fd, imr_multiaddr, - imr_interface); + return wasmtime_ssp_sock_set_ip_drop_membership( + exec_env, curfds, fd, imr_multiaddr, imr_interface); } static wasi_errno_t @@ -1904,7 +1920,7 @@ wasi_sock_set_ip_ttl(wasm_exec_env_t exec_env, wasi_fd_t fd, uint8_t ttl_s) curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_set_ip_ttl(curfds, fd, ttl_s); + return wasmtime_ssp_sock_set_ip_ttl(exec_env, curfds, fd, ttl_s); } static wasi_errno_t @@ -1920,7 +1936,7 @@ wasi_sock_set_ip_multicast_ttl(wasm_exec_env_t exec_env, wasi_fd_t fd, curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_set_ip_multicast_ttl(curfds, fd, ttl_s); + return wasmtime_ssp_sock_set_ip_multicast_ttl(exec_env, curfds, fd, ttl_s); } static wasi_errno_t @@ -1935,7 +1951,7 @@ wasi_sock_set_ipv6_only(wasm_exec_env_t exec_env, wasi_fd_t fd, bool is_enabled) curfds = wasi_ctx_get_curfds(module_inst, wasi_ctx); - return wasmtime_ssp_sock_set_ipv6_only(curfds, fd, is_enabled); + return wasmtime_ssp_sock_set_ipv6_only(exec_env, curfds, fd, is_enabled); } static wasi_errno_t @@ -2053,8 +2069,9 @@ wasi_sock_recv_from(wasm_exec_env_t exec_env, wasi_fd_t sock, memset(buf_begin, 0, total_size); *ro_data_len = 0; - err = wasmtime_ssp_sock_recv_from(curfds, sock, buf_begin, total_size, - ri_flags, src_addr, &recv_bytes); + err = wasmtime_ssp_sock_recv_from(exec_env, curfds, sock, buf_begin, + total_size, ri_flags, src_addr, + &recv_bytes); if (err != __WASI_ESUCCESS) { goto fail; } @@ -2153,7 +2170,8 @@ wasi_sock_send(wasm_exec_env_t exec_env, wasi_fd_t sock, return err; *so_data_len = 0; - err = wasmtime_ssp_sock_send(curfds, sock, buf, buf_size, &send_bytes); + err = wasmtime_ssp_sock_send(exec_env, curfds, sock, buf, buf_size, + &send_bytes); *so_data_len = (uint32)send_bytes; wasm_runtime_free(buf); @@ -2193,8 +2211,8 @@ wasi_sock_send_to(wasm_exec_env_t exec_env, wasi_fd_t sock, return err; *so_data_len = 0; - err = wasmtime_ssp_sock_send_to(curfds, addr_pool, sock, buf, buf_size, - si_flags, dest_addr, &send_bytes); + err = wasmtime_ssp_sock_send_to(exec_env, curfds, addr_pool, sock, buf, + buf_size, si_flags, dest_addr, &send_bytes); *so_data_len = (uint32)send_bytes; wasm_runtime_free(buf); @@ -2212,7 +2230,7 @@ wasi_sock_shutdown(wasm_exec_env_t exec_env, wasi_fd_t sock, wasi_sdflags_t how) if (!wasi_ctx) return __WASI_EINVAL; - return wasmtime_ssp_sock_shutdown(curfds, sock); + return wasmtime_ssp_sock_shutdown(exec_env, curfds, sock); } static wasi_errno_t diff --git a/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/include/wasmtime_ssp.h b/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/include/wasmtime_ssp.h index a53153552..efe7c8e3a 100644 --- a/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/include/wasmtime_ssp.h +++ b/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/include/wasmtime_ssp.h @@ -22,6 +22,8 @@ #include #include +#include "wasm_export.h" + /* clang-format off */ #ifdef __cplusplus @@ -646,17 +648,20 @@ __wasi_errno_t wasmtime_ssp_fd_prestat_dir_name( ) WASMTIME_SSP_SYSCALL_NAME(fd_prestat_dir_name) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_fd_close( + wasm_exec_env_t exec_env, struct fd_table *curfds, struct fd_prestats *prestats, __wasi_fd_t fd ) WASMTIME_SSP_SYSCALL_NAME(fd_close) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_fd_datasync( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd ) WASMTIME_SSP_SYSCALL_NAME(fd_datasync) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_fd_pread( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, const __wasi_iovec_t *iovs, @@ -666,6 +671,7 @@ __wasi_errno_t wasmtime_ssp_fd_pread( ) WASMTIME_SSP_SYSCALL_NAME(fd_pread) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_fd_pwrite( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, const __wasi_ciovec_t *iovs, @@ -675,6 +681,7 @@ __wasi_errno_t wasmtime_ssp_fd_pwrite( ) WASMTIME_SSP_SYSCALL_NAME(fd_pwrite) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_fd_read( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, const __wasi_iovec_t *iovs, @@ -683,6 +690,7 @@ __wasi_errno_t wasmtime_ssp_fd_read( ) WASMTIME_SSP_SYSCALL_NAME(fd_read) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_fd_renumber( + wasm_exec_env_t exec_env, struct fd_table *curfds, struct fd_prestats *prestats, __wasi_fd_t from, @@ -690,6 +698,7 @@ __wasi_errno_t wasmtime_ssp_fd_renumber( ) WASMTIME_SSP_SYSCALL_NAME(fd_renumber) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_fd_seek( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, __wasi_filedelta_t offset, @@ -698,24 +707,28 @@ __wasi_errno_t wasmtime_ssp_fd_seek( ) WASMTIME_SSP_SYSCALL_NAME(fd_seek) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_fd_tell( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, __wasi_filesize_t *newoffset ) WASMTIME_SSP_SYSCALL_NAME(fd_tell) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_fd_fdstat_get( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, __wasi_fdstat_t *buf ) WASMTIME_SSP_SYSCALL_NAME(fd_fdstat_get) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_fd_fdstat_set_flags( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, __wasi_fdflags_t flags ) WASMTIME_SSP_SYSCALL_NAME(fd_fdstat_set_flags) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_fd_fdstat_set_rights( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, __wasi_rights_t fs_rights_base, @@ -723,11 +736,13 @@ __wasi_errno_t wasmtime_ssp_fd_fdstat_set_rights( ) WASMTIME_SSP_SYSCALL_NAME(fd_fdstat_set_rights) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_fd_sync( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd ) WASMTIME_SSP_SYSCALL_NAME(fd_sync) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_fd_write( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, const __wasi_ciovec_t *iovs, @@ -736,6 +751,7 @@ __wasi_errno_t wasmtime_ssp_fd_write( ) WASMTIME_SSP_SYSCALL_NAME(fd_write) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_fd_advise( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, __wasi_filesize_t offset, @@ -744,6 +760,7 @@ __wasi_errno_t wasmtime_ssp_fd_advise( ) WASMTIME_SSP_SYSCALL_NAME(fd_advise) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_fd_allocate( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, __wasi_filesize_t offset, @@ -751,6 +768,7 @@ __wasi_errno_t wasmtime_ssp_fd_allocate( ) WASMTIME_SSP_SYSCALL_NAME(fd_allocate) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_path_create_directory( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, const char *path, @@ -758,6 +776,7 @@ __wasi_errno_t wasmtime_ssp_path_create_directory( ) WASMTIME_SSP_SYSCALL_NAME(path_create_directory) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_path_link( + wasm_exec_env_t exec_env, struct fd_table *curfds, struct fd_prestats *prestats, __wasi_fd_t old_fd, @@ -770,6 +789,7 @@ __wasi_errno_t wasmtime_ssp_path_link( ) WASMTIME_SSP_SYSCALL_NAME(path_link) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_path_open( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t dirfd, __wasi_lookupflags_t dirflags, @@ -783,6 +803,7 @@ __wasi_errno_t wasmtime_ssp_path_open( ) WASMTIME_SSP_SYSCALL_NAME(path_open) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_fd_readdir( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, void *buf, @@ -792,6 +813,7 @@ __wasi_errno_t wasmtime_ssp_fd_readdir( ) WASMTIME_SSP_SYSCALL_NAME(fd_readdir) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_path_readlink( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, const char *path, @@ -802,6 +824,7 @@ __wasi_errno_t wasmtime_ssp_path_readlink( ) WASMTIME_SSP_SYSCALL_NAME(path_readlink) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_path_rename( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t old_fd, const char *old_path, @@ -812,12 +835,14 @@ __wasi_errno_t wasmtime_ssp_path_rename( ) WASMTIME_SSP_SYSCALL_NAME(path_rename) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_fd_filestat_get( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, __wasi_filestat_t *buf ) WASMTIME_SSP_SYSCALL_NAME(fd_filestat_get) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_fd_filestat_set_times( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, __wasi_timestamp_t st_atim, @@ -826,12 +851,14 @@ __wasi_errno_t wasmtime_ssp_fd_filestat_set_times( ) WASMTIME_SSP_SYSCALL_NAME(fd_filestat_set_times) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_fd_filestat_set_size( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, __wasi_filesize_t st_size ) WASMTIME_SSP_SYSCALL_NAME(fd_filestat_set_size) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_path_filestat_get( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, __wasi_lookupflags_t flags, @@ -841,6 +868,7 @@ __wasi_errno_t wasmtime_ssp_path_filestat_get( ) WASMTIME_SSP_SYSCALL_NAME(path_filestat_get) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_path_filestat_set_times( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, __wasi_lookupflags_t flags, @@ -852,6 +880,7 @@ __wasi_errno_t wasmtime_ssp_path_filestat_set_times( ) WASMTIME_SSP_SYSCALL_NAME(path_filestat_set_times) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_path_symlink( + wasm_exec_env_t exec_env, struct fd_table *curfds, struct fd_prestats *prestats, const char *old_path, @@ -862,6 +891,7 @@ __wasi_errno_t wasmtime_ssp_path_symlink( ) WASMTIME_SSP_SYSCALL_NAME(path_symlink) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_path_unlink_file( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, const char *path, @@ -869,6 +899,7 @@ __wasi_errno_t wasmtime_ssp_path_unlink_file( ) WASMTIME_SSP_SYSCALL_NAME(path_unlink_file) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_path_remove_directory( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, const char *path, @@ -876,6 +907,7 @@ __wasi_errno_t wasmtime_ssp_path_remove_directory( ) WASMTIME_SSP_SYSCALL_NAME(path_remove_directory) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_poll_oneoff( + wasm_exec_env_t exec_env, struct fd_table *curfds, const __wasi_subscription_t *in, __wasi_event_t *out, @@ -890,24 +922,28 @@ __wasi_errno_t wasmtime_ssp_random_get( __wasi_errno_t wasi_ssp_sock_accept( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, __wasi_fdflags_t flags, __wasi_fd_t *fd_new ) __attribute__((__warn_unused_result__)); __wasi_errno_t wasi_ssp_sock_addr_local( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, __wasi_addr_t *addr ) __attribute__((__warn_unused_result__)); __wasi_errno_t wasi_ssp_sock_addr_remote( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, __wasi_addr_t *addr ) __attribute__((__warn_unused_result__)); __wasi_errno_t wasi_ssp_sock_open( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t poolfd, __wasi_address_family_t af, __wasi_sock_type_t socktype, __wasi_fd_t *sockfd @@ -915,12 +951,14 @@ wasi_ssp_sock_open( __wasi_errno_t wasi_ssp_sock_bind( + wasm_exec_env_t exec_env, struct fd_table *curfds, struct addr_pool *addr_pool, __wasi_fd_t fd, __wasi_addr_t *addr ) __attribute__((__warn_unused_result__)); __wasi_errno_t wasi_ssp_sock_addr_resolve( + wasm_exec_env_t exec_env, struct fd_table *curfds, char **ns_lookup_list, const char *host, const char* service, __wasi_addr_info_hints_t *hints, __wasi_addr_info_t *addr_info, @@ -929,65 +967,76 @@ wasi_ssp_sock_addr_resolve( __wasi_errno_t wasi_ssp_sock_connect( + wasm_exec_env_t exec_env, struct fd_table *curfds, struct addr_pool *addr_pool, __wasi_fd_t fd, __wasi_addr_t *addr ) __attribute__((__warn_unused_result__)); __wasi_errno_t wasi_ssp_sock_get_recv_buf_size( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, __wasi_size_t *size ) __attribute__((__warn_unused_result__)); __wasi_errno_t wasi_ssp_sock_get_reuse_addr( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, uint8_t *reuse ) __attribute__((__warn_unused_result__)); __wasi_errno_t wasi_ssp_sock_get_reuse_port( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, uint8_t *reuse ) __attribute__((__warn_unused_result__)); __wasi_errno_t wasi_ssp_sock_get_send_buf_size( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, __wasi_size_t *size ) __attribute__((__warn_unused_result__)); __wasi_errno_t wasi_ssp_sock_set_recv_buf_size( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, __wasi_size_t size ) __attribute__((__warn_unused_result__)); __wasi_errno_t wasi_ssp_sock_set_reuse_addr( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, uint8_t reuse ) __attribute__((__warn_unused_result__)); __wasi_errno_t wasi_ssp_sock_set_reuse_port( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, uint8_t reuse ) __attribute__((__warn_unused_result__)); __wasi_errno_t wasi_ssp_sock_set_send_buf_size( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, __wasi_size_t size ) __attribute__((__warn_unused_result__)); __wasi_errno_t wasi_ssp_sock_listen( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t fd, __wasi_size_t backlog ) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_recv( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, void *buf, @@ -996,6 +1045,7 @@ __wasi_errno_t wasmtime_ssp_sock_recv( ) WASMTIME_SSP_SYSCALL_NAME(sock_recv) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_recv_from( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, void *buf, @@ -1006,6 +1056,7 @@ __wasi_errno_t wasmtime_ssp_sock_recv_from( ) WASMTIME_SSP_SYSCALL_NAME(sock_recv_from) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_send( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, const void *buf, @@ -1014,6 +1065,7 @@ __wasi_errno_t wasmtime_ssp_sock_send( ) WASMTIME_SSP_SYSCALL_NAME(sock_send) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_send_to( + wasm_exec_env_t exec_env, struct fd_table *curfds, struct addr_pool *addr_pool, __wasi_fd_t sock, const void *buf, @@ -1024,53 +1076,62 @@ __wasi_errno_t wasmtime_ssp_sock_send_to( ) WASMTIME_SSP_SYSCALL_NAME(sock_send_to) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_shutdown( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock ) WASMTIME_SSP_SYSCALL_NAME(sock_shutdown) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_set_recv_timeout( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, uint64_t timeout_us ) WASMTIME_SSP_SYSCALL_NAME(sock_set_recv_timeout) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_get_recv_timeout( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, uint64_t *timeout_us ) WASMTIME_SSP_SYSCALL_NAME(sock_get_recv_timeout) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_set_send_timeout( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, uint64_t timeout_us ) WASMTIME_SSP_SYSCALL_NAME(sock_set_send_timeout) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_get_send_timeout( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, uint64_t *timeout_us ) WASMTIME_SSP_SYSCALL_NAME(sock_get_send_timeout) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_set_send_buf_size( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, size_t bufsiz ) WASMTIME_SSP_SYSCALL_NAME(sock_set_send_buf_size) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_get_send_buf_size( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, size_t *bufsiz ) WASMTIME_SSP_SYSCALL_NAME(sock_get_send_buf_size) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_set_recv_buf_size( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, size_t bufsiz ) WASMTIME_SSP_SYSCALL_NAME(sock_set_recv_buf_size) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_get_recv_buf_size( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, size_t *bufsiz @@ -1078,42 +1139,49 @@ __wasi_errno_t wasmtime_ssp_sock_get_recv_buf_size( __wasi_errno_t wasmtime_ssp_sock_set_keep_alive( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, bool is_enabled ) WASMTIME_SSP_SYSCALL_NAME(sock_set_keep_alive) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_get_keep_alive( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, bool *is_enabled ) WASMTIME_SSP_SYSCALL_NAME(sock_get_keep_alive) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_set_reuse_addr( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, bool is_enabled ) WASMTIME_SSP_SYSCALL_NAME(sock_set_reuse_addr) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_get_reuse_addr( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, bool *is_enabled ) WASMTIME_SSP_SYSCALL_NAME(sock_get_reuse_addr) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_set_reuse_port( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, bool is_enabled ) WASMTIME_SSP_SYSCALL_NAME(sock_set_reuse_port) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_get_reuse_port( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, bool *is_enabled ) WASMTIME_SSP_SYSCALL_NAME(sock_get_reuse_port) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_set_linger( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, bool is_enabled, @@ -1121,83 +1189,97 @@ __wasi_errno_t wasmtime_ssp_sock_set_linger( ) WASMTIME_SSP_SYSCALL_NAME(sock_set_linger) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_get_linger( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, bool *is_enabled, int *linger_s ) WASMTIME_SSP_SYSCALL_NAME(sock_get_linger) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_set_broadcast( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, bool is_enabled ) WASMTIME_SSP_SYSCALL_NAME(sock_set_broadcast) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_get_broadcast( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, bool *is_enabled ) WASMTIME_SSP_SYSCALL_NAME(sock_get_broadcast) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_set_tcp_no_delay( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, bool is_enabled ) WASMTIME_SSP_SYSCALL_NAME(sock_set_tcp_no_delay) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_get_tcp_no_delay( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, bool *is_enabled ) WASMTIME_SSP_SYSCALL_NAME(sock_get_tcp_no_delay) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_set_tcp_quick_ack( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, bool is_enabled ) WASMTIME_SSP_SYSCALL_NAME(sock_set_tcp_quick_ack) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_get_tcp_quick_ack( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, bool *is_enabled ) WASMTIME_SSP_SYSCALL_NAME(sock_get_tcp_quick_ack) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_set_tcp_keep_idle( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, uint32_t time_s ) WASMTIME_SSP_SYSCALL_NAME(sock_set_tcp_keep_idle) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_get_tcp_keep_idle( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, uint32_t *time_s ) WASMTIME_SSP_SYSCALL_NAME(sock_get_tcp_keep_idle) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_set_tcp_keep_intvl( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, uint32_t time_s ) WASMTIME_SSP_SYSCALL_NAME(sock_set_tcp_keep_intvl) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_get_tcp_keep_intvl( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, uint32_t *time_s ) WASMTIME_SSP_SYSCALL_NAME(sock_get_tcp_keep_intvl) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_set_tcp_fastopen_connect( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, bool is_enabled ) WASMTIME_SSP_SYSCALL_NAME(sock_set_tcp_fastopen_connect) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_get_tcp_fastopen_connect( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, bool *is_enabled ) WASMTIME_SSP_SYSCALL_NAME(sock_get_tcp_fastopen_connect) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_set_ip_multicast_loop( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, bool ipv6, @@ -1205,6 +1287,7 @@ __wasi_errno_t wasmtime_ssp_sock_set_ip_multicast_loop( ) WASMTIME_SSP_SYSCALL_NAME(sock_set_ip_multicast_loop) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_get_ip_multicast_loop( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, bool ipv6, @@ -1212,6 +1295,7 @@ __wasi_errno_t wasmtime_ssp_sock_get_ip_multicast_loop( ) WASMTIME_SSP_SYSCALL_NAME(sock_get_ip_multicast_loop) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_set_ip_add_membership( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, __wasi_addr_ip_t *imr_multiaddr, @@ -1219,6 +1303,7 @@ __wasi_errno_t wasmtime_ssp_sock_set_ip_add_membership( ) WASMTIME_SSP_SYSCALL_NAME(sock_set_ip_add_membership) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_set_ip_drop_membership( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, __wasi_addr_ip_t *imr_multiaddr, @@ -1226,36 +1311,42 @@ __wasi_errno_t wasmtime_ssp_sock_set_ip_drop_membership( ) WASMTIME_SSP_SYSCALL_NAME(sock_set_ip_drop_membership) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_set_ip_ttl( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, uint8_t ttl_s ) WASMTIME_SSP_SYSCALL_NAME(sock_set_ip_ttl) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_get_ip_ttl( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, uint8_t *ttl_s ) WASMTIME_SSP_SYSCALL_NAME(sock_get_ip_ttl) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_set_ip_multicast_ttl( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, uint8_t ttl_s ) WASMTIME_SSP_SYSCALL_NAME(sock_set_ip_multicast_ttl) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_get_ip_multicast_ttl( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, uint8_t *ttl_s ) WASMTIME_SSP_SYSCALL_NAME(sock_get_ip_multicast_ttl) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_set_ipv6_only( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, bool is_enabled ) WASMTIME_SSP_SYSCALL_NAME(sock_set_ipv6_only) __attribute__((__warn_unused_result__)); __wasi_errno_t wasmtime_ssp_sock_get_ipv6_only( + wasm_exec_env_t exec_env, struct fd_table *curfds, __wasi_fd_t sock, bool *is_enabled diff --git a/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/src/blocking_op.c b/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/src/blocking_op.c new file mode 100644 index 000000000..9d01f2bfe --- /dev/null +++ b/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/src/blocking_op.c @@ -0,0 +1,201 @@ +/* + * Copyright (C) 2023 Midokura Japan KK. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include + +#include "ssp_config.h" +#include "blocking_op.h" + +int +blocking_op_close(wasm_exec_env_t exec_env, int fd) +{ + if (!wasm_runtime_begin_blocking_op(exec_env)) { + errno = EINTR; + return -1; + } + int ret = close(fd); + wasm_runtime_end_blocking_op(exec_env); + return ret; +} + +ssize_t +blocking_op_readv(wasm_exec_env_t exec_env, int fd, const struct iovec *iov, + int iovcnt) +{ + if (!wasm_runtime_begin_blocking_op(exec_env)) { + errno = EINTR; + return -1; + } + ssize_t ret = readv(fd, iov, iovcnt); + wasm_runtime_end_blocking_op(exec_env); + return ret; +} + +#if CONFIG_HAS_PREADV +ssize_t +blocking_op_preadv(wasm_exec_env_t exec_env, int fd, const struct iovec *iov, + int iovcnt, off_t offset) +{ + if (!wasm_runtime_begin_blocking_op(exec_env)) { + errno = EINTR; + return -1; + } + ssize_t ret = preadv(fd, iov, iovcnt, offset); + wasm_runtime_end_blocking_op(exec_env); + return ret; +} +#else /* CONFIG_HAS_PREADV */ +ssize_t +blocking_op_pread(wasm_exec_env_t exec_env, int fd, void *p, size_t nb, + off_t offset) +{ + if (!wasm_runtime_begin_blocking_op(exec_env)) { + errno = EINTR; + return -1; + } + ssize_t ret = pread(fd, p, nb, offset); + wasm_runtime_end_blocking_op(exec_env); + return ret; +} +#endif /* CONFIG_HAS_PREADV */ + +ssize_t +blocking_op_writev(wasm_exec_env_t exec_env, int fd, const struct iovec *iov, + int iovcnt) +{ + if (!wasm_runtime_begin_blocking_op(exec_env)) { + errno = EINTR; + return -1; + } + ssize_t ret = writev(fd, iov, iovcnt); + wasm_runtime_end_blocking_op(exec_env); + return ret; +} + +#if CONFIG_HAS_PWRITEV +ssize_t +blocking_op_pwritev(wasm_exec_env_t exec_env, int fd, const struct iovec *iov, + int iovcnt, off_t offset) +{ + if (!wasm_runtime_begin_blocking_op(exec_env)) { + errno = EINTR; + return -1; + } + ssize_t ret = pwritev(fd, iov, iovcnt, offset); + wasm_runtime_end_blocking_op(exec_env); + return ret; +} +#else /* CONFIG_HAS_PWRITEV */ +ssize_t +blocking_op_pwrite(wasm_exec_env_t exec_env, int fd, const void *p, size_t nb, + off_t offset) +{ + if (!wasm_runtime_begin_blocking_op(exec_env)) { + errno = EINTR; + return -1; + } + ssize_t ret = pwrite(fd, p, nb, offset); + wasm_runtime_end_blocking_op(exec_env); + return ret; +} +#endif /* CONFIG_HAS_PWRITEV */ + +int +blocking_op_socket_accept(wasm_exec_env_t exec_env, bh_socket_t server_sock, + bh_socket_t *sockp, void *addr, + unsigned int *addrlenp) +{ + if (!wasm_runtime_begin_blocking_op(exec_env)) { + errno = EINTR; + return -1; + } + int ret = os_socket_accept(server_sock, sockp, addr, addrlenp); + wasm_runtime_end_blocking_op(exec_env); + return ret; +} + +int +blocking_op_socket_connect(wasm_exec_env_t exec_env, bh_socket_t sock, + const char *addr, int port) +{ + if (!wasm_runtime_begin_blocking_op(exec_env)) { + errno = EINTR; + return -1; + } + int ret = os_socket_connect(sock, addr, port); + wasm_runtime_end_blocking_op(exec_env); + return ret; +} + +int +blocking_op_socket_recv_from(wasm_exec_env_t exec_env, bh_socket_t sock, + void *buf, unsigned int len, int flags, + bh_sockaddr_t *src_addr) +{ + if (!wasm_runtime_begin_blocking_op(exec_env)) { + errno = EINTR; + return -1; + } + int ret = os_socket_recv_from(sock, buf, len, flags, src_addr); + wasm_runtime_end_blocking_op(exec_env); + return ret; +} + +int +blocking_op_socket_send_to(wasm_exec_env_t exec_env, bh_socket_t sock, + const void *buf, unsigned int len, int flags, + const bh_sockaddr_t *dest_addr) +{ + if (!wasm_runtime_begin_blocking_op(exec_env)) { + errno = EINTR; + return -1; + } + int ret = os_socket_send_to(sock, buf, len, flags, dest_addr); + wasm_runtime_end_blocking_op(exec_env); + return ret; +} + +int +blocking_op_socket_addr_resolve(wasm_exec_env_t exec_env, const char *host, + const char *service, uint8_t *hint_is_tcp, + uint8_t *hint_is_ipv4, + bh_addr_info_t *addr_info, + size_t addr_info_size, size_t *max_info_size) +{ + /* + * Note: Unlike others, os_socket_addr_resolve() is not a simple system + * call. It's likely backed by a complex libc function, getaddrinfo(). + * Depending on the implementation of getaddrinfo() and underlying + * DNS resolver, it might or might not be possible to make it return + * with os_wakeup_blocking_op(). + * + * Unfortunately, many of ISC/bind based resolvers just keep going on + * interrupted system calls. It includes macOS and glibc. + * + * On the other hand, NuttX as of writing this returns EAI_AGAIN + * on EINTR. + */ + if (!wasm_runtime_begin_blocking_op(exec_env)) { + errno = EINTR; + return -1; + } + int ret = os_socket_addr_resolve(host, service, hint_is_tcp, hint_is_ipv4, + addr_info, addr_info_size, max_info_size); + wasm_runtime_end_blocking_op(exec_env); + return ret; +} + +int +blocking_op_openat(wasm_exec_env_t exec_env, int fd, const char *path, + int oflags, mode_t mode) +{ + if (!wasm_runtime_begin_blocking_op(exec_env)) { + errno = EINTR; + return -1; + } + int ret = openat(fd, path, oflags, mode); + wasm_runtime_end_blocking_op(exec_env); + return ret; +} diff --git a/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/src/blocking_op.h b/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/src/blocking_op.h new file mode 100644 index 000000000..44a16d338 --- /dev/null +++ b/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/src/blocking_op.h @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2023 Midokura Japan KK. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include "bh_platform.h" +#include "wasm_export.h" + +int +blocking_op_close(wasm_exec_env_t exec_env, int fd); +ssize_t +blocking_op_readv(wasm_exec_env_t exec_env, int fd, const struct iovec *iov, + int iovcnt); +ssize_t +blocking_op_preadv(wasm_exec_env_t exec_env, int fd, const struct iovec *iov, + int iovcnt, off_t offset); +ssize_t +blocking_op_pread(wasm_exec_env_t exec_env, int fd, void *p, size_t nb, + off_t offset); +ssize_t +blocking_op_writev(wasm_exec_env_t exec_env, int fd, const struct iovec *iov, + int iovcnt); +ssize_t +blocking_op_pwritev(wasm_exec_env_t exec_env, int fd, const struct iovec *iov, + int iovcnt, off_t offset); +ssize_t +blocking_op_pwrite(wasm_exec_env_t exec_env, int fd, const void *p, size_t nb, + off_t offset); +int +blocking_op_socket_accept(wasm_exec_env_t exec_env, bh_socket_t server_sock, + bh_socket_t *sockp, void *addr, + unsigned int *addrlenp); +int +blocking_op_socket_connect(wasm_exec_env_t exec_env, bh_socket_t sock, + const char *addr, int port); +int +blocking_op_socket_recv_from(wasm_exec_env_t exec_env, bh_socket_t sock, + void *buf, unsigned int len, int flags, + bh_sockaddr_t *src_addr); +int +blocking_op_socket_send_to(wasm_exec_env_t exec_env, bh_socket_t sock, + const void *buf, unsigned int len, int flags, + const bh_sockaddr_t *dest_addr); +int +blocking_op_socket_addr_resolve(wasm_exec_env_t exec_env, const char *host, + const char *service, uint8_t *hint_is_tcp, + uint8_t *hint_is_ipv4, + bh_addr_info_t *addr_info, + size_t addr_info_size, size_t *max_info_size); +int +blocking_op_openat(wasm_exec_env_t exec_env, int fd, const char *path, + int oflags, mode_t mode); diff --git a/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/src/posix.c b/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/src/posix.c index a9831d770..0ba91a7e9 100644 --- a/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/src/posix.c +++ b/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/src/posix.c @@ -13,6 +13,7 @@ #include "ssp_config.h" #include "bh_platform.h" +#include "blocking_op.h" #include "wasmtime_ssp.h" #include "locking.h" #include "posix.h" @@ -59,98 +60,99 @@ static_assert(sizeof(struct iovec) == sizeof(__wasi_ciovec_t), static __wasi_errno_t convert_errno(int error) { - static const __wasi_errno_t errors[] = { -#define X(v) [v] = __WASI_##v - X(E2BIG), - X(EACCES), - X(EADDRINUSE), - X(EADDRNOTAVAIL), - X(EAFNOSUPPORT), - X(EAGAIN), - X(EALREADY), - X(EBADF), - X(EBADMSG), - X(EBUSY), - X(ECANCELED), - X(ECHILD), - X(ECONNABORTED), - X(ECONNREFUSED), - X(ECONNRESET), - X(EDEADLK), - X(EDESTADDRREQ), - X(EDOM), - X(EDQUOT), - X(EEXIST), - X(EFAULT), - X(EFBIG), - X(EHOSTUNREACH), - X(EIDRM), - X(EILSEQ), - X(EINPROGRESS), - X(EINTR), - X(EINVAL), - X(EIO), - X(EISCONN), - X(EISDIR), - X(ELOOP), - X(EMFILE), - X(EMLINK), - X(EMSGSIZE), - X(EMULTIHOP), - X(ENAMETOOLONG), - X(ENETDOWN), - X(ENETRESET), - X(ENETUNREACH), - X(ENFILE), - X(ENOBUFS), - X(ENODEV), - X(ENOENT), - X(ENOEXEC), - X(ENOLCK), - X(ENOLINK), - X(ENOMEM), - X(ENOMSG), - X(ENOPROTOOPT), - X(ENOSPC), - X(ENOSYS), + __wasi_errno_t code = __WASI_ENOSYS; +#define X(v) \ + case v: \ + code = __WASI_##v; \ + break; + switch (error) { + X(E2BIG) + X(EACCES) + X(EADDRINUSE) + X(EADDRNOTAVAIL) + X(EAFNOSUPPORT) + X(EAGAIN) + X(EALREADY) + X(EBADF) + X(EBADMSG) + X(EBUSY) + X(ECANCELED) + X(ECHILD) + X(ECONNABORTED) + X(ECONNREFUSED) + X(ECONNRESET) + X(EDEADLK) + X(EDESTADDRREQ) + X(EDOM) + X(EDQUOT) + X(EEXIST) + X(EFAULT) + X(EFBIG) + X(EHOSTUNREACH) + X(EIDRM) + X(EILSEQ) + X(EINPROGRESS) + X(EINTR) + X(EINVAL) + X(EIO) + X(EISCONN) + X(EISDIR) + X(ELOOP) + X(EMFILE) + X(EMLINK) + X(EMSGSIZE) + X(EMULTIHOP) + X(ENAMETOOLONG) + X(ENETDOWN) + X(ENETRESET) + X(ENETUNREACH) + X(ENFILE) + X(ENOBUFS) + X(ENODEV) + X(ENOENT) + X(ENOEXEC) + X(ENOLCK) + X(ENOLINK) + X(ENOMEM) + X(ENOMSG) + X(ENOPROTOOPT) + X(ENOSPC) + X(ENOSYS) #ifdef ENOTCAPABLE - X(ENOTCAPABLE), + X(ENOTCAPABLE) #endif - X(ENOTCONN), - X(ENOTDIR), - X(ENOTEMPTY), - X(ENOTRECOVERABLE), - X(ENOTSOCK), - X(ENOTSUP), - X(ENOTTY), - X(ENXIO), - X(EOVERFLOW), - X(EOWNERDEAD), - X(EPERM), - X(EPIPE), - X(EPROTO), - X(EPROTONOSUPPORT), - X(EPROTOTYPE), - X(ERANGE), - X(EROFS), - X(ESPIPE), - X(ESRCH), - X(ESTALE), - X(ETIMEDOUT), - X(ETXTBSY), - X(EXDEV), + X(ENOTCONN) + X(ENOTDIR) + X(ENOTEMPTY) + X(ENOTRECOVERABLE) + X(ENOTSOCK) + X(ENOTSUP) + X(ENOTTY) + X(ENXIO) + X(EOVERFLOW) + X(EOWNERDEAD) + X(EPERM) + X(EPIPE) + X(EPROTO) + X(EPROTONOSUPPORT) + X(EPROTOTYPE) + X(ERANGE) + X(EROFS) + X(ESPIPE) + X(ESRCH) + X(ESTALE) + X(ETIMEDOUT) + X(ETXTBSY) + X(EXDEV) + default: + if (error == EOPNOTSUPP) + code = __WASI_ENOTSUP; + else if (code == EWOULDBLOCK) + code = __WASI_EAGAIN; + break; + } #undef X -#if EOPNOTSUPP != ENOTSUP - [EOPNOTSUPP] = __WASI_ENOTSUP, -#endif -#if EWOULDBLOCK != EAGAIN - [EWOULDBLOCK] = __WASI_EAGAIN, -#endif - }; - if (error < 0 || (size_t)error >= sizeof(errors) / sizeof(errors[0]) - || errors[error] == 0) - return __WASI_ENOSYS; - return errors[error]; + return code; } static bool @@ -338,7 +340,7 @@ fd_prestats_init(struct fd_prestats *pt) // Grows the preopened resource table to a required lower bound and a // minimum number of free preopened resource table entries. -static bool +static __wasi_errno_t fd_prestats_grow(struct fd_prestats *pt, size_t min, size_t incr) REQUIRES_EXCLUSIVE(pt->lock) { @@ -352,7 +354,7 @@ fd_prestats_grow(struct fd_prestats *pt, size_t min, size_t incr) struct fd_prestat *prestats = wasm_runtime_malloc((uint32)(sizeof(*prestats) * size)); if (prestats == NULL) - return false; + return __WASI_ENOMEM; if (pt->prestats && pt->size > 0) { bh_memcpy_s(prestats, (uint32)(sizeof(*prestats) * size), @@ -368,27 +370,39 @@ fd_prestats_grow(struct fd_prestats *pt, size_t min, size_t incr) pt->prestats = prestats; pt->size = size; } - return true; + return __WASI_ESUCCESS; +} + +static __wasi_errno_t +fd_prestats_insert_locked(struct fd_prestats *pt, const char *dir, + __wasi_fd_t fd) +{ + // Grow the preopened resource table if needed. + __wasi_errno_t error = fd_prestats_grow(pt, fd, 1); + + if (error != __WASI_ESUCCESS) { + return error; + } + + pt->prestats[fd].dir = bh_strdup(dir); + + if (pt->prestats[fd].dir == NULL) + return __WASI_ENOMEM; + + return __WASI_ESUCCESS; } // Inserts a preopened resource record into the preopened resource table. bool fd_prestats_insert(struct fd_prestats *pt, const char *dir, __wasi_fd_t fd) { - // Grow the preopened resource table if needed. rwlock_wrlock(&pt->lock); - if (!fd_prestats_grow(pt, fd, 1)) { - rwlock_unlock(&pt->lock); - return false; - } - pt->prestats[fd].dir = bh_strdup(dir); + __wasi_errno_t error = fd_prestats_insert_locked(pt, dir, fd); + rwlock_unlock(&pt->lock); - if (pt->prestats[fd].dir == NULL) - return false; - - return true; + return error == __WASI_ESUCCESS; } // Looks up a preopened resource table entry by number. @@ -407,6 +421,24 @@ fd_prestats_get_entry(struct fd_prestats *pt, __wasi_fd_t fd, return 0; } +// Remove a preopened resource record from the preopened resource table by +// number +static __wasi_errno_t +fd_prestats_remove_entry(struct fd_prestats *pt, __wasi_fd_t fd) +{ + // Test for file descriptor existence. + if (fd >= pt->size) + return __WASI_EBADF; + struct fd_prestat *prestat = &pt->prestats[fd]; + + if (prestat->dir != NULL) { + wasm_runtime_free((void *)prestat->dir); + prestat->dir = NULL; + } + + return __WASI_ESUCCESS; +} + struct fd_object { struct refcount refcount; __wasi_filetype_t type; @@ -630,16 +662,25 @@ fd_number(const struct fd_object *fo) return number; } -#define CLOSE_NON_STD_FD(fd) \ - do { \ - if (fd > 2) \ - close(fd); \ +// The env == NULL case is for +// fd_table_destroy, path_get, path_put, fd_table_insert_existing +#define CLOSE_NON_STD_FD(env, fd) \ + do { \ + if (fd > 2) { \ + if (env == NULL) { \ + close(fd); \ + } \ + else { \ + blocking_op_close(env, fd); \ + } \ + } \ } while (0) // Lowers the reference count on a file descriptor object. When the // reference count reaches zero, its resources are cleaned up. static void -fd_object_release(struct fd_object *fo) UNLOCKS(fo->refcount) +fd_object_release(wasm_exec_env_t env, struct fd_object *fo) + UNLOCKS(fo->refcount) { if (refcount_release(&fo->refcount)) { int saved_errno = errno; @@ -649,14 +690,14 @@ fd_object_release(struct fd_object *fo) UNLOCKS(fo->refcount) // closedir() on it also closes the underlying file descriptor. mutex_destroy(&fo->directory.lock); if (fo->directory.handle == NULL) { - CLOSE_NON_STD_FD(fd_number(fo)); + CLOSE_NON_STD_FD(env, fd_number(fo)); } else { closedir(fo->directory.handle); } break; default: - CLOSE_NON_STD_FD(fd_number(fo)); + CLOSE_NON_STD_FD(env, fd_number(fo)); break; } wasm_runtime_free(fo); @@ -669,8 +710,8 @@ fd_object_release(struct fd_object *fo) UNLOCKS(fo->refcount) bool fd_table_insert_existing(struct fd_table *ft, __wasi_fd_t in, int out) { - __wasi_filetype_t type; - __wasi_rights_t rights_base, rights_inheriting; + __wasi_filetype_t type = __WASI_FILETYPE_UNKNOWN; + __wasi_rights_t rights_base = 0, rights_inheriting = 0; struct fd_object *fo; __wasi_errno_t error; @@ -695,7 +736,7 @@ fd_table_insert_existing(struct fd_table *ft, __wasi_fd_t in, int out) fo->number = out; if (type == __WASI_FILETYPE_DIRECTORY) { if (!mutex_init(&fo->directory.lock)) { - fd_object_release(fo); + fd_object_release(NULL, fo); return false; } fo->directory.handle = NULL; @@ -705,7 +746,7 @@ fd_table_insert_existing(struct fd_table *ft, __wasi_fd_t in, int out) rwlock_wrlock(&ft->lock); if (!fd_table_grow(ft, in, 1)) { rwlock_unlock(&ft->lock); - fd_object_release(fo); + fd_object_release(NULL, fo); return false; } @@ -729,16 +770,16 @@ fd_table_unused(struct fd_table *ft) REQUIRES_SHARED(ft->lock) // Inserts a file descriptor object into an unused slot of the file // descriptor table. static __wasi_errno_t -fd_table_insert(struct fd_table *ft, struct fd_object *fo, - __wasi_rights_t rights_base, __wasi_rights_t rights_inheriting, - __wasi_fd_t *out) REQUIRES_UNLOCKED(ft->lock) - UNLOCKS(fo->refcount) +fd_table_insert(wasm_exec_env_t exec_env, struct fd_table *ft, + struct fd_object *fo, __wasi_rights_t rights_base, + __wasi_rights_t rights_inheriting, __wasi_fd_t *out) + REQUIRES_UNLOCKED(ft->lock) UNLOCKS(fo->refcount) { // Grow the file descriptor table if needed. rwlock_wrlock(&ft->lock); if (!fd_table_grow(ft, 0, 1)) { rwlock_unlock(&ft->lock); - fd_object_release(fo); + fd_object_release(exec_env, fo); return convert_errno(errno); } @@ -750,8 +791,8 @@ fd_table_insert(struct fd_table *ft, struct fd_object *fo, // Inserts a numerical file descriptor into the file descriptor table. static __wasi_errno_t -fd_table_insert_fd(struct fd_table *ft, int in, __wasi_filetype_t type, - __wasi_rights_t rights_base, +fd_table_insert_fd(wasm_exec_env_t exec_env, struct fd_table *ft, int in, + __wasi_filetype_t type, __wasi_rights_t rights_base, __wasi_rights_t rights_inheriting, __wasi_fd_t *out) REQUIRES_UNLOCKED(ft->lock) { @@ -766,12 +807,13 @@ fd_table_insert_fd(struct fd_table *ft, int in, __wasi_filetype_t type, fo->number = in; if (type == __WASI_FILETYPE_DIRECTORY) { if (!mutex_init(&fo->directory.lock)) { - fd_object_release(fo); + fd_object_release(exec_env, fo); return (__wasi_errno_t)-1; } fo->directory.handle = NULL; } - return fd_table_insert(ft, fo, rights_base, rights_inheriting, out); + return fd_table_insert(exec_env, ft, fo, rights_base, rights_inheriting, + out); } __wasi_errno_t @@ -808,12 +850,14 @@ wasmtime_ssp_fd_prestat_dir_name(struct fd_prestats *prestats, __wasi_fd_t fd, rwlock_unlock(&prestats->lock); return error; } - if (path_len != strlen(prestat->dir)) { + + const size_t prestat_dir_len = strlen(prestat->dir); + if (path_len < prestat_dir_len) { rwlock_unlock(&prestats->lock); - return EINVAL; + return __WASI_EINVAL; } - bh_memcpy_s(path, (uint32)path_len, prestat->dir, (uint32)path_len); + bh_memcpy_s(path, (uint32)path_len, prestat->dir, (uint32)prestat_dir_len); rwlock_unlock(&prestats->lock); @@ -821,28 +865,18 @@ wasmtime_ssp_fd_prestat_dir_name(struct fd_prestats *prestats, __wasi_fd_t fd, } __wasi_errno_t -wasmtime_ssp_fd_close(struct fd_table *curfds, struct fd_prestats *prestats, - __wasi_fd_t fd) +wasmtime_ssp_fd_close(wasm_exec_env_t exec_env, struct fd_table *curfds, + struct fd_prestats *prestats, __wasi_fd_t fd) { - // Don't allow closing a pre-opened resource. - // TODO: Eventually, we do want to permit this, once libpreopen in - // userspace is capable of removing entries from its tables as well. - { - rwlock_rdlock(&prestats->lock); - struct fd_prestat *prestat; - __wasi_errno_t error = fd_prestats_get_entry(prestats, fd, &prestat); - rwlock_unlock(&prestats->lock); - if (error == 0) { - return __WASI_ENOTSUP; - } - } - // Validate the file descriptor. struct fd_table *ft = curfds; rwlock_wrlock(&ft->lock); + rwlock_wrlock(&prestats->lock); + struct fd_entry *fe; __wasi_errno_t error = fd_table_get_entry(ft, fd, 0, 0, &fe); if (error != 0) { + rwlock_unlock(&prestats->lock); rwlock_unlock(&ft->lock); return error; } @@ -850,9 +884,20 @@ wasmtime_ssp_fd_close(struct fd_table *curfds, struct fd_prestats *prestats, // Remove it from the file descriptor table. struct fd_object *fo; fd_table_detach(ft, fd, &fo); + + // Remove it from the preopened resource table if it exists + error = fd_prestats_remove_entry(prestats, fd); + + rwlock_unlock(&prestats->lock); rwlock_unlock(&ft->lock); - fd_object_release(fo); - return 0; + fd_object_release(exec_env, fo); + + // Ignore the error if there is no preopen associated with this fd + if (error == __WASI_EBADF) { + return __WASI_ESUCCESS; + } + + return error; } // Look up a file descriptor object in a locked file descriptor table @@ -894,7 +939,8 @@ fd_object_get(struct fd_table *curfds, struct fd_object **fo, __wasi_fd_t fd, } __wasi_errno_t -wasmtime_ssp_fd_datasync(struct fd_table *curfds, __wasi_fd_t fd) +wasmtime_ssp_fd_datasync(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t fd) { struct fd_object *fo; __wasi_errno_t error = @@ -907,15 +953,15 @@ wasmtime_ssp_fd_datasync(struct fd_table *curfds, __wasi_fd_t fd) #else int ret = fsync(fd_number(fo)); #endif - fd_object_release(fo); + fd_object_release(exec_env, fo); if (ret < 0) return convert_errno(errno); return 0; } __wasi_errno_t -wasmtime_ssp_fd_pread(struct fd_table *curfds, __wasi_fd_t fd, - const __wasi_iovec_t *iov, size_t iovcnt, +wasmtime_ssp_fd_pread(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t fd, const __wasi_iovec_t *iov, size_t iovcnt, __wasi_filesize_t offset, size_t *nread) { if (iovcnt == 0) @@ -928,17 +974,19 @@ wasmtime_ssp_fd_pread(struct fd_table *curfds, __wasi_fd_t fd, return error; #if CONFIG_HAS_PREADV - ssize_t len = preadv(fd_number(fo), (const struct iovec *)iov, (int)iovcnt, - (off_t)offset); - fd_object_release(fo); + ssize_t len = + blocking_op_preadv(exec_env, fd_number(fo), (const struct iovec *)iov, + (int)iovcnt, (off_t)offset); + fd_object_release(exec_env, fo); if (len < 0) return convert_errno(errno); *nread = (size_t)len; return 0; #else if (iovcnt == 1) { - ssize_t len = pread(fd_number(fo), iov->buf, iov->buf_len, offset); - fd_object_release(fo); + ssize_t len = blocking_op_pread(exec_env, fd_number(fo), iov->buf, + iov->buf_len, offset); + fd_object_release(exec_env, fo); if (len < 0) return convert_errno(errno); *nread = len; @@ -951,13 +999,14 @@ wasmtime_ssp_fd_pread(struct fd_table *curfds, __wasi_fd_t fd, totalsize += iov[i].buf_len; char *buf = wasm_runtime_malloc(totalsize); if (buf == NULL) { - fd_object_release(fo); + fd_object_release(exec_env, fo); return __WASI_ENOMEM; } // Perform a single read operation. - ssize_t len = pread(fd_number(fo), buf, totalsize, offset); - fd_object_release(fo); + ssize_t len = + blocking_op_pread(exec_env, fd_number(fo), buf, totalsize, offset); + fd_object_release(exec_env, fo); if (len < 0) { wasm_runtime_free(buf); return convert_errno(errno); @@ -985,9 +1034,10 @@ wasmtime_ssp_fd_pread(struct fd_table *curfds, __wasi_fd_t fd, } __wasi_errno_t -wasmtime_ssp_fd_pwrite(struct fd_table *curfds, __wasi_fd_t fd, - const __wasi_ciovec_t *iov, size_t iovcnt, - __wasi_filesize_t offset, size_t *nwritten) +wasmtime_ssp_fd_pwrite(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t fd, const __wasi_ciovec_t *iov, + size_t iovcnt, __wasi_filesize_t offset, + size_t *nwritten) { if (iovcnt == 0) return __WASI_EINVAL; @@ -1000,11 +1050,13 @@ wasmtime_ssp_fd_pwrite(struct fd_table *curfds, __wasi_fd_t fd, ssize_t len; #if CONFIG_HAS_PWRITEV - len = pwritev(fd_number(fo), (const struct iovec *)iov, (int)iovcnt, - (off_t)offset); + len = + blocking_op_pwritev(exec_env, fd_number(fo), (const struct iovec *)iov, + (int)iovcnt, (off_t)offset); #else if (iovcnt == 1) { - len = pwrite(fd_number(fo), iov->buf, iov->buf_len, offset); + len = blocking_op_pwrite(exec_env, fd_number(fo), iov->buf, + iov->buf_len, offset); } else { // Allocate a single buffer to fit all data. @@ -1013,7 +1065,7 @@ wasmtime_ssp_fd_pwrite(struct fd_table *curfds, __wasi_fd_t fd, totalsize += iov[i].buf_len; char *buf = wasm_runtime_malloc(totalsize); if (buf == NULL) { - fd_object_release(fo); + fd_object_release(exec_env, fo); return __WASI_ENOMEM; } size_t bufoff = 0; @@ -1024,11 +1076,12 @@ wasmtime_ssp_fd_pwrite(struct fd_table *curfds, __wasi_fd_t fd, } // Perform a single write operation. - len = pwrite(fd_number(fo), buf, totalsize, offset); + len = + blocking_op_pwrite(exec_env, fd_number(fo), buf, totalsize, offset); wasm_runtime_free(buf); } #endif - fd_object_release(fo); + fd_object_release(exec_env, fo); if (len < 0) return convert_errno(errno); *nwritten = (size_t)len; @@ -1036,8 +1089,9 @@ wasmtime_ssp_fd_pwrite(struct fd_table *curfds, __wasi_fd_t fd, } __wasi_errno_t -wasmtime_ssp_fd_read(struct fd_table *curfds, __wasi_fd_t fd, - const __wasi_iovec_t *iov, size_t iovcnt, size_t *nread) +wasmtime_ssp_fd_read(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t fd, const __wasi_iovec_t *iov, size_t iovcnt, + size_t *nread) { struct fd_object *fo; __wasi_errno_t error = @@ -1045,8 +1099,9 @@ wasmtime_ssp_fd_read(struct fd_table *curfds, __wasi_fd_t fd, if (error != 0) return error; - ssize_t len = readv(fd_number(fo), (const struct iovec *)iov, (int)iovcnt); - fd_object_release(fo); + ssize_t len = blocking_op_readv(exec_env, fd_number(fo), + (const struct iovec *)iov, (int)iovcnt); + fd_object_release(exec_env, fo); if (len < 0) return convert_errno(errno); *nread = (size_t)len; @@ -1054,36 +1109,25 @@ wasmtime_ssp_fd_read(struct fd_table *curfds, __wasi_fd_t fd, } __wasi_errno_t -wasmtime_ssp_fd_renumber(struct fd_table *curfds, struct fd_prestats *prestats, - __wasi_fd_t from, __wasi_fd_t to) +wasmtime_ssp_fd_renumber(wasm_exec_env_t exec_env, struct fd_table *curfds, + struct fd_prestats *prestats, __wasi_fd_t from, + __wasi_fd_t to) { - // Don't allow renumbering over a pre-opened resource. - // TODO: Eventually, we do want to permit this, once libpreopen in - // userspace is capable of removing entries from its tables as well. - { - rwlock_rdlock(&prestats->lock); - struct fd_prestat *prestat; - __wasi_errno_t error = fd_prestats_get_entry(prestats, to, &prestat); - if (error != 0) { - error = fd_prestats_get_entry(prestats, from, &prestat); - } - rwlock_unlock(&prestats->lock); - if (error == 0) { - return __WASI_ENOTSUP; - } - } - struct fd_table *ft = curfds; rwlock_wrlock(&ft->lock); + rwlock_wrlock(&prestats->lock); + struct fd_entry *fe_from; __wasi_errno_t error = fd_table_get_entry(ft, from, 0, 0, &fe_from); if (error != 0) { + rwlock_unlock(&prestats->lock); rwlock_unlock(&ft->lock); return error; } struct fd_entry *fe_to; error = fd_table_get_entry(ft, to, 0, 0, &fe_to); if (error != 0) { + rwlock_unlock(&prestats->lock); rwlock_unlock(&ft->lock); return error; } @@ -1093,21 +1137,66 @@ wasmtime_ssp_fd_renumber(struct fd_table *curfds, struct fd_prestats *prestats, refcount_acquire(&fe_from->object->refcount); fd_table_attach(ft, to, fe_from->object, fe_from->rights_base, fe_from->rights_inheriting); - fd_object_release(fo); + fd_object_release(exec_env, fo); // Remove the old fd from the file descriptor table. fd_table_detach(ft, from, &fo); - fd_object_release(fo); + fd_object_release(exec_env, fo); --ft->used; + // Handle renumbering of any preopened resources + struct fd_prestat *prestat_from; + __wasi_errno_t prestat_from_error = + fd_prestats_get_entry(prestats, from, &prestat_from); + + struct fd_prestat *prestat_to; + __wasi_errno_t prestat_to_error = + fd_prestats_get_entry(prestats, to, &prestat_to); + + // Renumbering over two preopened resources. + if (prestat_from_error == __WASI_ESUCCESS + && prestat_to_error == __WASI_ESUCCESS) { + (void)fd_prestats_remove_entry(prestats, to); + + error = fd_prestats_insert_locked(prestats, prestat_from->dir, to); + + if (error == __WASI_ESUCCESS) { + (void)fd_prestats_remove_entry(prestats, from); + } + else { + (void)fd_prestats_remove_entry(prestats, to); + } + } + // Renumbering from a non-preopened fd to a preopened fd. In this case, we + // can't a keep the destination fd entry in the preopened table so remove + // it entirely. + else if (prestat_from_error != __WASI_ESUCCESS + && prestat_to_error == __WASI_ESUCCESS) { + (void)fd_prestats_remove_entry(prestats, to); + } + // Renumbering from a preopened fd to a non-preopened fd + else if (prestat_from_error == __WASI_ESUCCESS + && prestat_to_error != __WASI_ESUCCESS) { + error = fd_prestats_insert_locked(prestats, prestat_from->dir, to); + + if (error == __WASI_ESUCCESS) { + (void)fd_prestats_remove_entry(prestats, from); + } + else { + (void)fd_prestats_remove_entry(prestats, to); + } + } + + rwlock_unlock(&prestats->lock); rwlock_unlock(&ft->lock); - return 0; + + return error; } __wasi_errno_t -wasmtime_ssp_fd_seek(struct fd_table *curfds, __wasi_fd_t fd, - __wasi_filedelta_t offset, __wasi_whence_t whence, - __wasi_filesize_t *newoffset) +wasmtime_ssp_fd_seek(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t fd, __wasi_filedelta_t offset, + __wasi_whence_t whence, __wasi_filesize_t *newoffset) { int nwhence; switch (whence) { @@ -1135,7 +1224,7 @@ wasmtime_ssp_fd_seek(struct fd_table *curfds, __wasi_fd_t fd, return error; off_t ret = lseek(fd_number(fo), offset, nwhence); - fd_object_release(fo); + fd_object_release(exec_env, fo); if (ret < 0) return convert_errno(errno); *newoffset = (__wasi_filesize_t)ret; @@ -1143,8 +1232,8 @@ wasmtime_ssp_fd_seek(struct fd_table *curfds, __wasi_fd_t fd, } __wasi_errno_t -wasmtime_ssp_fd_tell(struct fd_table *curfds, __wasi_fd_t fd, - __wasi_filesize_t *newoffset) +wasmtime_ssp_fd_tell(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t fd, __wasi_filesize_t *newoffset) { struct fd_object *fo; __wasi_errno_t error = @@ -1153,7 +1242,7 @@ wasmtime_ssp_fd_tell(struct fd_table *curfds, __wasi_fd_t fd, return error; off_t ret = lseek(fd_number(fo), 0, SEEK_CUR); - fd_object_release(fo); + fd_object_release(exec_env, fo); if (ret < 0) return convert_errno(errno); *newoffset = (__wasi_filesize_t)ret; @@ -1161,8 +1250,8 @@ wasmtime_ssp_fd_tell(struct fd_table *curfds, __wasi_fd_t fd, } __wasi_errno_t -wasmtime_ssp_fd_fdstat_get(struct fd_table *curfds, __wasi_fd_t fd, - __wasi_fdstat_t *buf) +wasmtime_ssp_fd_fdstat_get(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t fd, __wasi_fdstat_t *buf) { struct fd_table *ft = curfds; rwlock_rdlock(&ft->lock); @@ -1194,44 +1283,51 @@ wasmtime_ssp_fd_fdstat_get(struct fd_table *curfds, __wasi_fd_t fd, if ((ret & O_APPEND) != 0) buf->fs_flags |= __WASI_FDFLAG_APPEND; -#ifdef O_DSYNC +#ifdef CONFIG_HAS_O_DSYNC if ((ret & O_DSYNC) != 0) buf->fs_flags |= __WASI_FDFLAG_DSYNC; #endif if ((ret & O_NONBLOCK) != 0) buf->fs_flags |= __WASI_FDFLAG_NONBLOCK; -#ifdef O_RSYNC +#ifdef CONFIG_HAS_O_RSYNC if ((ret & O_RSYNC) != 0) buf->fs_flags |= __WASI_FDFLAG_RSYNC; #endif +#ifdef CONFIG_HAS_O_SYNC if ((ret & O_SYNC) != 0) buf->fs_flags |= __WASI_FDFLAG_SYNC; +#endif return 0; } __wasi_errno_t -wasmtime_ssp_fd_fdstat_set_flags(struct fd_table *curfds, __wasi_fd_t fd, +wasmtime_ssp_fd_fdstat_set_flags(wasm_exec_env_t exec_env, + struct fd_table *curfds, __wasi_fd_t fd, __wasi_fdflags_t fs_flags) { int noflags = 0; if ((fs_flags & __WASI_FDFLAG_APPEND) != 0) noflags |= O_APPEND; if ((fs_flags & __WASI_FDFLAG_DSYNC) != 0) -#ifdef O_DSYNC +#ifdef CONFIG_HAS_O_DSYNC noflags |= O_DSYNC; #else - noflags |= O_SYNC; + return __WASI_ENOTSUP; #endif if ((fs_flags & __WASI_FDFLAG_NONBLOCK) != 0) noflags |= O_NONBLOCK; if ((fs_flags & __WASI_FDFLAG_RSYNC) != 0) -#ifdef O_RSYNC +#ifdef CONFIG_HAS_O_RSYNC noflags |= O_RSYNC; #else - noflags |= O_SYNC; + return __WASI_ENOTSUP; #endif if ((fs_flags & __WASI_FDFLAG_SYNC) != 0) +#ifdef CONFIG_HAS_O_SYNC noflags |= O_SYNC; +#else + return __WASI_ENOTSUP; +#endif struct fd_object *fo; __wasi_errno_t error = @@ -1240,14 +1336,15 @@ wasmtime_ssp_fd_fdstat_set_flags(struct fd_table *curfds, __wasi_fd_t fd, return error; int ret = fcntl(fd_number(fo), F_SETFL, noflags); - fd_object_release(fo); + fd_object_release(exec_env, fo); if (ret < 0) return convert_errno(errno); return 0; } __wasi_errno_t -wasmtime_ssp_fd_fdstat_set_rights(struct fd_table *curfds, __wasi_fd_t fd, +wasmtime_ssp_fd_fdstat_set_rights(wasm_exec_env_t exec_env, + struct fd_table *curfds, __wasi_fd_t fd, __wasi_rights_t fs_rights_base, __wasi_rights_t fs_rights_inheriting) { @@ -1269,7 +1366,8 @@ wasmtime_ssp_fd_fdstat_set_rights(struct fd_table *curfds, __wasi_fd_t fd, } __wasi_errno_t -wasmtime_ssp_fd_sync(struct fd_table *curfds, __wasi_fd_t fd) +wasmtime_ssp_fd_sync(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t fd) { struct fd_object *fo; __wasi_errno_t error = @@ -1278,15 +1376,15 @@ wasmtime_ssp_fd_sync(struct fd_table *curfds, __wasi_fd_t fd) return error; int ret = fsync(fd_number(fo)); - fd_object_release(fo); + fd_object_release(exec_env, fo); if (ret < 0) return convert_errno(errno); return 0; } __wasi_errno_t -wasmtime_ssp_fd_write(struct fd_table *curfds, __wasi_fd_t fd, - const __wasi_ciovec_t *iov, size_t iovcnt, +wasmtime_ssp_fd_write(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t fd, const __wasi_ciovec_t *iov, size_t iovcnt, size_t *nwritten) { struct fd_object *fo; @@ -1318,7 +1416,7 @@ wasmtime_ssp_fd_write(struct fd_table *curfds, __wasi_fd_t fd, len = writev(fd_number(fo), (const struct iovec *)iov, (int)iovcnt); } #endif /* end of BH_VPRINTF */ - fd_object_release(fo); + fd_object_release(exec_env, fo); if (len < 0) return convert_errno(errno); *nwritten = (size_t)len; @@ -1326,9 +1424,9 @@ wasmtime_ssp_fd_write(struct fd_table *curfds, __wasi_fd_t fd, } __wasi_errno_t -wasmtime_ssp_fd_advise(struct fd_table *curfds, __wasi_fd_t fd, - __wasi_filesize_t offset, __wasi_filesize_t len, - __wasi_advice_t advice) +wasmtime_ssp_fd_advise(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t fd, __wasi_filesize_t offset, + __wasi_filesize_t len, __wasi_advice_t advice) { #ifdef POSIX_FADV_NORMAL int nadvice; @@ -1362,7 +1460,7 @@ wasmtime_ssp_fd_advise(struct fd_table *curfds, __wasi_fd_t fd, return error; int ret = posix_fadvise(fd_number(fo), (off_t)offset, (off_t)len, nadvice); - fd_object_release(fo); + fd_object_release(exec_env, fo); if (ret != 0) return convert_errno(ret); return 0; @@ -1392,8 +1490,9 @@ wasmtime_ssp_fd_advise(struct fd_table *curfds, __wasi_fd_t fd, } __wasi_errno_t -wasmtime_ssp_fd_allocate(struct fd_table *curfds, __wasi_fd_t fd, - __wasi_filesize_t offset, __wasi_filesize_t len) +wasmtime_ssp_fd_allocate(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t fd, __wasi_filesize_t offset, + __wasi_filesize_t len) { struct fd_object *fo; __wasi_errno_t error = @@ -1414,7 +1513,7 @@ wasmtime_ssp_fd_allocate(struct fd_table *curfds, __wasi_fd_t fd, ret = ftruncate(fd_number(fo), newsize); #endif - fd_object_release(fo); + fd_object_release(exec_env, fo); if (ret != 0) return convert_errno(ret); return 0; @@ -1569,6 +1668,9 @@ path_get(struct fd_table *curfds, struct path_access *pa, __wasi_fd_t fd, // components. In other words, a pathname component that must be a // directory. First attempt to obtain a directory file descriptor // for it. + // + // Note: we don't bother to use blocking_op_openat here + // because openat with O_DIRECTORY should not block. int newdir = #ifdef O_SEARCH openat(fds[curfd], file, O_SEARCH | O_DIRECTORY | O_NOFOLLOW); @@ -1702,7 +1804,7 @@ fail: close(fds[i]); for (size_t i = 0; i <= curpath; ++i) wasm_runtime_free(paths_start[i]); - fd_object_release(fo); + fd_object_release(NULL, fo); return error; #endif } @@ -1726,11 +1828,12 @@ path_put(struct path_access *pa) UNLOCKS(pa->fd_object->refcount) wasm_runtime_free(pa->path_start); if (fd_number(pa->fd_object) != pa->fd) close(pa->fd); - fd_object_release(pa->fd_object); + fd_object_release(NULL, pa->fd_object); } __wasi_errno_t -wasmtime_ssp_path_create_directory(struct fd_table *curfds, __wasi_fd_t fd, +wasmtime_ssp_path_create_directory(wasm_exec_env_t exec_env, + struct fd_table *curfds, __wasi_fd_t fd, const char *path, size_t pathlen) { struct path_access pa; @@ -1775,11 +1878,11 @@ validate_path(const char *path, struct fd_prestats *pt) } __wasi_errno_t -wasmtime_ssp_path_link(struct fd_table *curfds, struct fd_prestats *prestats, - __wasi_fd_t old_fd, __wasi_lookupflags_t old_flags, - const char *old_path, size_t old_path_len, - __wasi_fd_t new_fd, const char *new_path, - size_t new_path_len) +wasmtime_ssp_path_link(wasm_exec_env_t exec_env, struct fd_table *curfds, + struct fd_prestats *prestats, __wasi_fd_t old_fd, + __wasi_lookupflags_t old_flags, const char *old_path, + size_t old_path_len, __wasi_fd_t new_fd, + const char *new_path, size_t new_path_len) { struct path_access old_pa; __wasi_errno_t error = @@ -1832,9 +1935,9 @@ wasmtime_ssp_path_link(struct fd_table *curfds, struct fd_prestats *prestats, } __wasi_errno_t -wasmtime_ssp_path_open(struct fd_table *curfds, __wasi_fd_t dirfd, - __wasi_lookupflags_t dirflags, const char *path, - size_t pathlen, __wasi_oflags_t oflags, +wasmtime_ssp_path_open(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t dirfd, __wasi_lookupflags_t dirflags, + const char *path, size_t pathlen, __wasi_oflags_t oflags, __wasi_rights_t fs_rights_base, __wasi_rights_t fs_rights_inheriting, __wasi_fdflags_t fs_flags, __wasi_fd_t *fd) @@ -1875,26 +1978,30 @@ wasmtime_ssp_path_open(struct fd_table *curfds, __wasi_fd_t dirfd, if ((fs_flags & __WASI_FDFLAG_APPEND) != 0) noflags |= O_APPEND; if ((fs_flags & __WASI_FDFLAG_DSYNC) != 0) { -#ifdef O_DSYNC +#ifdef CONFIG_HAS_O_DSYNC noflags |= O_DSYNC; -#else - noflags |= O_SYNC; -#endif needed_inheriting |= __WASI_RIGHT_FD_DATASYNC; +#else + return __WASI_ENOTSUP; +#endif } if ((fs_flags & __WASI_FDFLAG_NONBLOCK) != 0) noflags |= O_NONBLOCK; if ((fs_flags & __WASI_FDFLAG_RSYNC) != 0) { -#ifdef O_RSYNC +#ifdef CONFIG_HAS_O_RSYNC noflags |= O_RSYNC; -#else - noflags |= O_SYNC; -#endif needed_inheriting |= __WASI_RIGHT_FD_SYNC; +#else + return __WASI_ENOTSUP; +#endif } if ((fs_flags & __WASI_FDFLAG_SYNC) != 0) { +#ifdef CONFIG_HAS_O_SYNC noflags |= O_SYNC; needed_inheriting |= __WASI_RIGHT_FD_SYNC; +#else + return __WASI_ENOTSUP; +#endif } if (write && (noflags & (O_APPEND | O_TRUNC)) == 0) needed_inheriting |= __WASI_RIGHT_FD_SEEK; @@ -1908,7 +2015,7 @@ wasmtime_ssp_path_open(struct fd_table *curfds, __wasi_fd_t dirfd, if (!pa.follow) noflags |= O_NOFOLLOW; - int nfd = openat(pa.fd, pa.path, noflags, 0666); + int nfd = blocking_op_openat(exec_env, pa.fd, pa.path, noflags, 0666); if (nfd < 0) { int openat_errno = errno; // Linux returns ENXIO instead of EOPNOTSUPP when opening a socket. @@ -1951,21 +2058,8 @@ wasmtime_ssp_path_open(struct fd_table *curfds, __wasi_fd_t dirfd, return error; } - { - struct stat sb; - - if (fstat(nfd, &sb) < 0) { - close(nfd); - return convert_errno(errno); - } - - if (S_ISDIR(sb.st_mode)) - rights_base |= (__wasi_rights_t)RIGHTS_DIRECTORY_BASE; - else if (S_ISREG(sb.st_mode)) - rights_base |= (__wasi_rights_t)RIGHTS_REGULAR_FILE_BASE; - } - - return fd_table_insert_fd(curfds, nfd, type, rights_base & max_base, + return fd_table_insert_fd(exec_env, curfds, nfd, type, + rights_base & max_base, rights_inheriting & max_inheriting, fd); } @@ -1984,9 +2078,9 @@ fd_readdir_put(void *buf, size_t bufsize, size_t *bufused, const void *elem, } __wasi_errno_t -wasmtime_ssp_fd_readdir(struct fd_table *curfds, __wasi_fd_t fd, void *buf, - size_t nbyte, __wasi_dircookie_t cookie, - size_t *bufused) +wasmtime_ssp_fd_readdir(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t fd, void *buf, size_t nbyte, + __wasi_dircookie_t cookie, size_t *bufused) { struct fd_object *fo; __wasi_errno_t error = @@ -2002,7 +2096,7 @@ wasmtime_ssp_fd_readdir(struct fd_table *curfds, __wasi_fd_t fd, void *buf, dp = fdopendir(fd_number(fo)); if (dp == NULL) { mutex_unlock(&fo->directory.lock); - fd_object_release(fo); + fd_object_release(exec_env, fo); return convert_errno(errno); } fo->directory.handle = dp; @@ -2026,7 +2120,7 @@ wasmtime_ssp_fd_readdir(struct fd_table *curfds, __wasi_fd_t fd, void *buf, struct dirent *de = readdir(dp); if (de == NULL) { mutex_unlock(&fo->directory.lock); - fd_object_release(fo); + fd_object_release(exec_env, fo); return errno == 0 || *bufused > 0 ? 0 : convert_errno(errno); } fo->directory.offset = (__wasi_dircookie_t)telldir(dp); @@ -2075,14 +2169,14 @@ wasmtime_ssp_fd_readdir(struct fd_table *curfds, __wasi_fd_t fd, void *buf, fd_readdir_put(buf, nbyte, bufused, de->d_name, namlen); } mutex_unlock(&fo->directory.lock); - fd_object_release(fo); + fd_object_release(exec_env, fo); return 0; } __wasi_errno_t -wasmtime_ssp_path_readlink(struct fd_table *curfds, __wasi_fd_t fd, - const char *path, size_t pathlen, char *buf, - size_t bufsize, size_t *bufused) +wasmtime_ssp_path_readlink(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t fd, const char *path, size_t pathlen, + char *buf, size_t bufsize, size_t *bufused) { struct path_access pa; __wasi_errno_t error = path_get_nofollow( @@ -2103,10 +2197,10 @@ wasmtime_ssp_path_readlink(struct fd_table *curfds, __wasi_fd_t fd, } __wasi_errno_t -wasmtime_ssp_path_rename(struct fd_table *curfds, __wasi_fd_t old_fd, - const char *old_path, size_t old_path_len, - __wasi_fd_t new_fd, const char *new_path, - size_t new_path_len) +wasmtime_ssp_path_rename(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t old_fd, const char *old_path, + size_t old_path_len, __wasi_fd_t new_fd, + const char *new_path, size_t new_path_len) { struct path_access old_pa; __wasi_errno_t error = @@ -2148,8 +2242,8 @@ convert_stat(const struct stat *in, __wasi_filestat_t *out) } __wasi_errno_t -wasmtime_ssp_fd_filestat_get(struct fd_table *curfds, __wasi_fd_t fd, - __wasi_filestat_t *buf) +wasmtime_ssp_fd_filestat_get(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t fd, __wasi_filestat_t *buf) { struct fd_object *fo; __wasi_errno_t error = @@ -2168,7 +2262,7 @@ wasmtime_ssp_fd_filestat_get(struct fd_table *curfds, __wasi_fd_t fd, } } buf->st_filetype = fo->type; - fd_object_release(fo); + fd_object_release(exec_env, fo); if (ret < 0) return convert_errno(errno); return 0; @@ -2218,7 +2312,8 @@ convert_utimens_arguments(__wasi_timestamp_t st_atim, } __wasi_errno_t -wasmtime_ssp_fd_filestat_set_size(struct fd_table *curfds, __wasi_fd_t fd, +wasmtime_ssp_fd_filestat_set_size(wasm_exec_env_t exec_env, + struct fd_table *curfds, __wasi_fd_t fd, __wasi_filesize_t st_size) { struct fd_object *fo; @@ -2228,14 +2323,15 @@ wasmtime_ssp_fd_filestat_set_size(struct fd_table *curfds, __wasi_fd_t fd, return error; int ret = ftruncate(fd_number(fo), (off_t)st_size); - fd_object_release(fo); + fd_object_release(exec_env, fo); if (ret < 0) return convert_errno(errno); return 0; } __wasi_errno_t -wasmtime_ssp_fd_filestat_set_times(struct fd_table *curfds, __wasi_fd_t fd, +wasmtime_ssp_fd_filestat_set_times(wasm_exec_env_t exec_env, + struct fd_table *curfds, __wasi_fd_t fd, __wasi_timestamp_t st_atim, __wasi_timestamp_t st_mtim, __wasi_fstflags_t fstflags) @@ -2256,14 +2352,15 @@ wasmtime_ssp_fd_filestat_set_times(struct fd_table *curfds, __wasi_fd_t fd, convert_utimens_arguments(st_atim, st_mtim, fstflags, ts); int ret = futimens(fd_number(fo), ts); - fd_object_release(fo); + fd_object_release(exec_env, fo); if (ret < 0) return convert_errno(errno); return 0; } __wasi_errno_t -wasmtime_ssp_path_filestat_get(struct fd_table *curfds, __wasi_fd_t fd, +wasmtime_ssp_path_filestat_get(wasm_exec_env_t exec_env, + struct fd_table *curfds, __wasi_fd_t fd, __wasi_lookupflags_t flags, const char *path, size_t pathlen, __wasi_filestat_t *buf) { @@ -2300,7 +2397,8 @@ wasmtime_ssp_path_filestat_get(struct fd_table *curfds, __wasi_fd_t fd, } __wasi_errno_t -wasmtime_ssp_path_filestat_set_times(struct fd_table *curfds, __wasi_fd_t fd, +wasmtime_ssp_path_filestat_set_times(wasm_exec_env_t exec_env, + struct fd_table *curfds, __wasi_fd_t fd, __wasi_lookupflags_t flags, const char *path, size_t pathlen, __wasi_timestamp_t st_atim, @@ -2338,10 +2436,10 @@ wasmtime_ssp_path_filestat_set_times(struct fd_table *curfds, __wasi_fd_t fd, } __wasi_errno_t -wasmtime_ssp_path_symlink(struct fd_table *curfds, struct fd_prestats *prestats, - const char *old_path, size_t old_path_len, - __wasi_fd_t fd, const char *new_path, - size_t new_path_len) +wasmtime_ssp_path_symlink(wasm_exec_env_t exec_env, struct fd_table *curfds, + struct fd_prestats *prestats, const char *old_path, + size_t old_path_len, __wasi_fd_t fd, + const char *new_path, size_t new_path_len) { char *target = str_nullterminate(old_path, old_path_len); if (target == NULL) @@ -2373,8 +2471,8 @@ wasmtime_ssp_path_symlink(struct fd_table *curfds, struct fd_prestats *prestats, } __wasi_errno_t -wasmtime_ssp_path_unlink_file(struct fd_table *curfds, __wasi_fd_t fd, - const char *path, size_t pathlen) +wasmtime_ssp_path_unlink_file(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t fd, const char *path, size_t pathlen) { struct path_access pa; __wasi_errno_t error = path_get_nofollow( @@ -2407,7 +2505,8 @@ wasmtime_ssp_path_unlink_file(struct fd_table *curfds, __wasi_fd_t fd, } __wasi_errno_t -wasmtime_ssp_path_remove_directory(struct fd_table *curfds, __wasi_fd_t fd, +wasmtime_ssp_path_remove_directory(wasm_exec_env_t exec_env, + struct fd_table *curfds, __wasi_fd_t fd, const char *path, size_t pathlen) { struct path_access pa; @@ -2433,7 +2532,7 @@ wasmtime_ssp_path_remove_directory(struct fd_table *curfds, __wasi_fd_t fd, } __wasi_errno_t -wasmtime_ssp_poll_oneoff(struct fd_table *curfds, +wasmtime_ssp_poll_oneoff(wasm_exec_env_t exec_env, struct fd_table *curfds, const __wasi_subscription_t *in, __wasi_event_t *out, size_t nsubscriptions, size_t *nevents) NO_LOCK_ANALYSIS @@ -2681,7 +2780,7 @@ wasmtime_ssp_poll_oneoff(struct fd_table *curfds, for (size_t i = 0; i < nsubscriptions; ++i) if (fos[i] != NULL) - fd_object_release(fos[i]); + fd_object_release(exec_env, fos[i]); wasm_runtime_free(fos); wasm_runtime_free(pfds); return error; @@ -2695,8 +2794,9 @@ wasmtime_ssp_random_get(void *buf, size_t nbyte) } __wasi_errno_t -wasi_ssp_sock_accept(struct fd_table *curfds, __wasi_fd_t fd, - __wasi_fdflags_t flags, __wasi_fd_t *fd_new) +wasi_ssp_sock_accept(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t fd, __wasi_fdflags_t flags, + __wasi_fd_t *fd_new) { __wasi_filetype_t wasi_type; __wasi_rights_t max_base, max_inheriting; @@ -2709,8 +2809,9 @@ wasi_ssp_sock_accept(struct fd_table *curfds, __wasi_fd_t fd, goto fail; } - ret = os_socket_accept(fd_number(fo), &new_sock, NULL, NULL); - fd_object_release(fo); + ret = blocking_op_socket_accept(exec_env, fd_number(fo), &new_sock, NULL, + NULL); + fd_object_release(exec_env, fo); if (BHT_OK != ret) { error = convert_errno(errno); goto fail; @@ -2722,7 +2823,7 @@ wasi_ssp_sock_accept(struct fd_table *curfds, __wasi_fd_t fd, goto fail; } - error = fd_table_insert_fd(curfds, new_sock, wasi_type, max_base, + error = fd_table_insert_fd(exec_env, curfds, new_sock, wasi_type, max_base, max_inheriting, fd_new); if (error != __WASI_ESUCCESS) { /* released in fd_table_insert_fd() */ @@ -2740,8 +2841,8 @@ fail: } __wasi_errno_t -wasi_ssp_sock_addr_local(struct fd_table *curfds, __wasi_fd_t fd, - __wasi_addr_t *addr) +wasi_ssp_sock_addr_local(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t fd, __wasi_addr_t *addr) { struct fd_object *fo; bh_sockaddr_t bh_addr; @@ -2753,7 +2854,7 @@ wasi_ssp_sock_addr_local(struct fd_table *curfds, __wasi_fd_t fd, return error; ret = os_socket_addr_local(fd_number(fo), &bh_addr); - fd_object_release(fo); + fd_object_release(exec_env, fo); if (ret != BHT_OK) { return convert_errno(errno); } @@ -2764,8 +2865,8 @@ wasi_ssp_sock_addr_local(struct fd_table *curfds, __wasi_fd_t fd, } __wasi_errno_t -wasi_ssp_sock_addr_remote(struct fd_table *curfds, __wasi_fd_t fd, - __wasi_addr_t *addr) +wasi_ssp_sock_addr_remote(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t fd, __wasi_addr_t *addr) { struct fd_object *fo; bh_sockaddr_t bh_addr; @@ -2777,7 +2878,7 @@ wasi_ssp_sock_addr_remote(struct fd_table *curfds, __wasi_fd_t fd, return error; ret = os_socket_addr_remote(fd_number(fo), &bh_addr); - fd_object_release(fo); + fd_object_release(exec_env, fo); if (ret != BHT_OK) { return convert_errno(errno); } @@ -2817,8 +2918,9 @@ wasi_addr_to_string(const __wasi_addr_t *addr, char *buf, size_t buflen) } __wasi_errno_t -wasi_ssp_sock_bind(struct fd_table *curfds, struct addr_pool *addr_pool, - __wasi_fd_t fd, __wasi_addr_t *addr) +wasi_ssp_sock_bind(wasm_exec_env_t exec_env, struct fd_table *curfds, + struct addr_pool *addr_pool, __wasi_fd_t fd, + __wasi_addr_t *addr) { char buf[48] = { 0 }; struct fd_object *fo; @@ -2839,7 +2941,7 @@ wasi_ssp_sock_bind(struct fd_table *curfds, struct addr_pool *addr_pool, return error; ret = os_socket_bind(fd_number(fo), buf, &port); - fd_object_release(fo); + fd_object_release(exec_env, fo); if (BHT_OK != ret) { return convert_errno(errno); } @@ -2848,9 +2950,9 @@ wasi_ssp_sock_bind(struct fd_table *curfds, struct addr_pool *addr_pool, } __wasi_errno_t -wasi_ssp_sock_addr_resolve(struct fd_table *curfds, char **ns_lookup_list, - const char *host, const char *service, - __wasi_addr_info_hints_t *hints, +wasi_ssp_sock_addr_resolve(wasm_exec_env_t exec_env, struct fd_table *curfds, + char **ns_lookup_list, const char *host, + const char *service, __wasi_addr_info_hints_t *hints, __wasi_addr_info_t *addr_info, __wasi_size_t addr_info_size, __wasi_size_t *max_info_size) @@ -2871,8 +2973,8 @@ wasi_ssp_sock_addr_resolve(struct fd_table *curfds, char **ns_lookup_list, return __WASI_EACCES; } - int ret = os_socket_addr_resolve( - host, service, + int ret = blocking_op_socket_addr_resolve( + exec_env, host, service, hints->hints_enabled && hints->type != SOCKET_ANY ? &hints_is_tcp : NULL, hints->hints_enabled && hints->family != INET_UNSPEC ? &hints_is_ipv4 @@ -2900,8 +3002,9 @@ wasi_ssp_sock_addr_resolve(struct fd_table *curfds, char **ns_lookup_list, } __wasi_errno_t -wasi_ssp_sock_connect(struct fd_table *curfds, struct addr_pool *addr_pool, - __wasi_fd_t fd, __wasi_addr_t *addr) +wasi_ssp_sock_connect(wasm_exec_env_t exec_env, struct fd_table *curfds, + struct addr_pool *addr_pool, __wasi_fd_t fd, + __wasi_addr_t *addr) { char buf[48] = { 0 }; struct fd_object *fo; @@ -2920,10 +3023,10 @@ wasi_ssp_sock_connect(struct fd_table *curfds, struct addr_pool *addr_pool, if (error != __WASI_ESUCCESS) return error; - ret = os_socket_connect(fd_number(fo), buf, - addr->kind == IPv4 ? addr->addr.ip4.port - : addr->addr.ip6.port); - fd_object_release(fo); + ret = blocking_op_socket_connect(exec_env, fd_number(fo), buf, + addr->kind == IPv4 ? addr->addr.ip4.port + : addr->addr.ip6.port); + fd_object_release(exec_env, fo); if (BHT_OK != ret) { return convert_errno(errno); } @@ -2932,7 +3035,8 @@ wasi_ssp_sock_connect(struct fd_table *curfds, struct addr_pool *addr_pool, } __wasi_errno_t -wasi_ssp_sock_get_recv_buf_size(struct fd_table *curfds, __wasi_fd_t fd, +wasi_ssp_sock_get_recv_buf_size(wasm_exec_env_t exec_env, + struct fd_table *curfds, __wasi_fd_t fd, __wasi_size_t *size) { struct fd_object *fo; @@ -2945,7 +3049,7 @@ wasi_ssp_sock_get_recv_buf_size(struct fd_table *curfds, __wasi_fd_t fd, socklen_t optlen = sizeof(optval); ret = getsockopt(fd_number(fo), SOL_SOCKET, SO_RCVBUF, &optval, &optlen); - fd_object_release(fo); + fd_object_release(exec_env, fo); if (BHT_OK != ret) { return convert_errno(errno); } @@ -2956,8 +3060,8 @@ wasi_ssp_sock_get_recv_buf_size(struct fd_table *curfds, __wasi_fd_t fd, } __wasi_errno_t -wasi_ssp_sock_get_reuse_addr(struct fd_table *curfds, __wasi_fd_t fd, - uint8_t *reuse) +wasi_ssp_sock_get_reuse_addr(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t fd, uint8_t *reuse) { struct fd_object *fo; @@ -2970,7 +3074,7 @@ wasi_ssp_sock_get_reuse_addr(struct fd_table *curfds, __wasi_fd_t fd, socklen_t optlen = sizeof(optval); ret = getsockopt(fd_number(fo), SOL_SOCKET, SO_REUSEADDR, &optval, &optlen); - fd_object_release(fo); + fd_object_release(exec_env, fo); if (BHT_OK != ret) { return convert_errno(errno); } @@ -2981,8 +3085,8 @@ wasi_ssp_sock_get_reuse_addr(struct fd_table *curfds, __wasi_fd_t fd, } __wasi_errno_t -wasi_ssp_sock_get_reuse_port(struct fd_table *curfds, __wasi_fd_t fd, - uint8_t *reuse) +wasi_ssp_sock_get_reuse_port(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t fd, uint8_t *reuse) { struct fd_object *fo; int ret; @@ -3001,7 +3105,7 @@ wasi_ssp_sock_get_reuse_port(struct fd_table *curfds, __wasi_fd_t fd, optval = 0; #endif /* defined(SO_REUSEPORT) */ - fd_object_release(fo); + fd_object_release(exec_env, fo); if (BHT_OK != ret) { return convert_errno(errno); } @@ -3012,7 +3116,8 @@ wasi_ssp_sock_get_reuse_port(struct fd_table *curfds, __wasi_fd_t fd, } __wasi_errno_t -wasi_ssp_sock_get_send_buf_size(struct fd_table *curfds, __wasi_fd_t fd, +wasi_ssp_sock_get_send_buf_size(wasm_exec_env_t exec_env, + struct fd_table *curfds, __wasi_fd_t fd, __wasi_size_t *size) { struct fd_object *fo; @@ -3025,7 +3130,7 @@ wasi_ssp_sock_get_send_buf_size(struct fd_table *curfds, __wasi_fd_t fd, socklen_t optlen = sizeof(optval); ret = getsockopt(fd_number(fo), SOL_SOCKET, SO_SNDBUF, &optval, &optlen); - fd_object_release(fo); + fd_object_release(exec_env, fo); if (BHT_OK != ret) { return convert_errno(errno); } @@ -3036,8 +3141,8 @@ wasi_ssp_sock_get_send_buf_size(struct fd_table *curfds, __wasi_fd_t fd, } __wasi_errno_t -wasi_ssp_sock_listen(struct fd_table *curfds, __wasi_fd_t fd, - __wasi_size_t backlog) +wasi_ssp_sock_listen(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t fd, __wasi_size_t backlog) { struct fd_object *fo; int ret; @@ -3047,7 +3152,7 @@ wasi_ssp_sock_listen(struct fd_table *curfds, __wasi_fd_t fd, return error; ret = os_socket_listen(fd_number(fo), backlog); - fd_object_release(fo); + fd_object_release(exec_env, fo); if (BHT_OK != ret) { return convert_errno(errno); } @@ -3056,9 +3161,9 @@ wasi_ssp_sock_listen(struct fd_table *curfds, __wasi_fd_t fd, } __wasi_errno_t -wasi_ssp_sock_open(struct fd_table *curfds, __wasi_fd_t poolfd, - __wasi_address_family_t af, __wasi_sock_type_t socktype, - __wasi_fd_t *sockfd) +wasi_ssp_sock_open(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t poolfd, __wasi_address_family_t af, + __wasi_sock_type_t socktype, __wasi_fd_t *sockfd) { bh_socket_t sock; bool is_tcp = SOCKET_DGRAM == socktype ? false : true; @@ -3090,7 +3195,7 @@ wasi_ssp_sock_open(struct fd_table *curfds, __wasi_fd_t poolfd, } // TODO: base rights and inheriting rights ? - error = fd_table_insert_fd(curfds, sock, wasi_type, max_base, + error = fd_table_insert_fd(exec_env, curfds, sock, wasi_type, max_base, max_inheriting, sockfd); if (error != __WASI_ESUCCESS) { return error; @@ -3100,7 +3205,8 @@ wasi_ssp_sock_open(struct fd_table *curfds, __wasi_fd_t poolfd, } __wasi_errno_t -wasi_ssp_sock_set_recv_buf_size(struct fd_table *curfds, __wasi_fd_t fd, +wasi_ssp_sock_set_recv_buf_size(wasm_exec_env_t exec_env, + struct fd_table *curfds, __wasi_fd_t fd, __wasi_size_t size) { struct fd_object *fo; @@ -3113,7 +3219,7 @@ wasi_ssp_sock_set_recv_buf_size(struct fd_table *curfds, __wasi_fd_t fd, ret = setsockopt(fd_number(fo), SOL_SOCKET, SO_RCVBUF, &optval, sizeof(optval)); - fd_object_release(fo); + fd_object_release(exec_env, fo); if (BHT_OK != ret) { return convert_errno(errno); } @@ -3122,8 +3228,8 @@ wasi_ssp_sock_set_recv_buf_size(struct fd_table *curfds, __wasi_fd_t fd, } __wasi_errno_t -wasi_ssp_sock_set_reuse_addr(struct fd_table *curfds, __wasi_fd_t fd, - uint8_t reuse) +wasi_ssp_sock_set_reuse_addr(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t fd, uint8_t reuse) { struct fd_object *fo; int ret; @@ -3135,7 +3241,7 @@ wasi_ssp_sock_set_reuse_addr(struct fd_table *curfds, __wasi_fd_t fd, ret = setsockopt(fd_number(fo), SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); - fd_object_release(fo); + fd_object_release(exec_env, fo); if (BHT_OK != ret) { return convert_errno(errno); } @@ -3144,8 +3250,8 @@ wasi_ssp_sock_set_reuse_addr(struct fd_table *curfds, __wasi_fd_t fd, } __wasi_errno_t -wasi_ssp_sock_set_reuse_port(struct fd_table *curfds, __wasi_fd_t fd, - uint8_t reuse) +wasi_ssp_sock_set_reuse_port(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t fd, uint8_t reuse) { struct fd_object *fo; int ret; @@ -3163,7 +3269,7 @@ wasi_ssp_sock_set_reuse_port(struct fd_table *curfds, __wasi_fd_t fd, ret = BHT_ERROR; #endif /* defined(SO_REUSEPORT) */ - fd_object_release(fo); + fd_object_release(exec_env, fo); if (BHT_OK != ret) { return convert_errno(errno); } @@ -3172,7 +3278,8 @@ wasi_ssp_sock_set_reuse_port(struct fd_table *curfds, __wasi_fd_t fd, } __wasi_errno_t -wasi_ssp_sock_set_send_buf_size(struct fd_table *curfds, __wasi_fd_t fd, +wasi_ssp_sock_set_send_buf_size(wasm_exec_env_t exec_env, + struct fd_table *curfds, __wasi_fd_t fd, __wasi_size_t size) { struct fd_object *fo; @@ -3186,7 +3293,7 @@ wasi_ssp_sock_set_send_buf_size(struct fd_table *curfds, __wasi_fd_t fd, ret = setsockopt(fd_number(fo), SOL_SOCKET, SO_SNDBUF, &optval, sizeof(optval)); - fd_object_release(fo); + fd_object_release(exec_env, fo); if (BHT_OK != ret) { return convert_errno(errno); } @@ -3195,18 +3302,19 @@ wasi_ssp_sock_set_send_buf_size(struct fd_table *curfds, __wasi_fd_t fd, } __wasi_errno_t -wasmtime_ssp_sock_recv(struct fd_table *curfds, __wasi_fd_t sock, void *buf, - size_t buf_len, size_t *recv_len) +wasmtime_ssp_sock_recv(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t sock, void *buf, size_t buf_len, + size_t *recv_len) { __wasi_addr_t src_addr; - return wasmtime_ssp_sock_recv_from(curfds, sock, buf, buf_len, 0, &src_addr, - recv_len); + return wasmtime_ssp_sock_recv_from(exec_env, curfds, sock, buf, buf_len, 0, + &src_addr, recv_len); } __wasi_errno_t -wasmtime_ssp_sock_recv_from(struct fd_table *curfds, __wasi_fd_t sock, - void *buf, size_t buf_len, +wasmtime_ssp_sock_recv_from(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t sock, void *buf, size_t buf_len, __wasi_riflags_t ri_flags, __wasi_addr_t *src_addr, size_t *recv_len) { @@ -3220,8 +3328,9 @@ wasmtime_ssp_sock_recv_from(struct fd_table *curfds, __wasi_fd_t sock, return error; } - ret = os_socket_recv_from(fd_number(fo), buf, buf_len, 0, &sockaddr); - fd_object_release(fo); + ret = blocking_op_socket_recv_from(exec_env, fd_number(fo), buf, buf_len, 0, + &sockaddr); + fd_object_release(exec_env, fo); if (-1 == ret) { return convert_errno(errno); } @@ -3233,8 +3342,9 @@ wasmtime_ssp_sock_recv_from(struct fd_table *curfds, __wasi_fd_t sock, } __wasi_errno_t -wasmtime_ssp_sock_send(struct fd_table *curfds, __wasi_fd_t sock, - const void *buf, size_t buf_len, size_t *sent_len) +wasmtime_ssp_sock_send(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t sock, const void *buf, size_t buf_len, + size_t *sent_len) { struct fd_object *fo; __wasi_errno_t error; @@ -3246,7 +3356,7 @@ wasmtime_ssp_sock_send(struct fd_table *curfds, __wasi_fd_t sock, } ret = os_socket_send(fd_number(fo), buf, buf_len); - fd_object_release(fo); + fd_object_release(exec_env, fo); if (-1 == ret) { return convert_errno(errno); } @@ -3256,8 +3366,9 @@ wasmtime_ssp_sock_send(struct fd_table *curfds, __wasi_fd_t sock, } __wasi_errno_t -wasmtime_ssp_sock_send_to(struct fd_table *curfds, struct addr_pool *addr_pool, - __wasi_fd_t sock, const void *buf, size_t buf_len, +wasmtime_ssp_sock_send_to(wasm_exec_env_t exec_env, struct fd_table *curfds, + struct addr_pool *addr_pool, __wasi_fd_t sock, + const void *buf, size_t buf_len, __wasi_siflags_t si_flags, const __wasi_addr_t *dest_addr, size_t *sent_len) { @@ -3282,8 +3393,9 @@ wasmtime_ssp_sock_send_to(struct fd_table *curfds, struct addr_pool *addr_pool, wasi_addr_to_bh_sockaddr(dest_addr, &sockaddr); - ret = os_socket_send_to(fd_number(fo), buf, buf_len, 0, &sockaddr); - fd_object_release(fo); + ret = blocking_op_socket_send_to(exec_env, fd_number(fo), buf, buf_len, 0, + &sockaddr); + fd_object_release(exec_env, fo); if (-1 == ret) { return convert_errno(errno); } @@ -3293,7 +3405,8 @@ wasmtime_ssp_sock_send_to(struct fd_table *curfds, struct addr_pool *addr_pool, } __wasi_errno_t -wasmtime_ssp_sock_shutdown(struct fd_table *curfds, __wasi_fd_t sock) +wasmtime_ssp_sock_shutdown(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t sock) { struct fd_object *fo; __wasi_errno_t error; @@ -3304,7 +3417,7 @@ wasmtime_ssp_sock_shutdown(struct fd_table *curfds, __wasi_fd_t sock) return error; ret = os_socket_shutdown(fd_number(fo)); - fd_object_release(fo); + fd_object_release(exec_env, fo); if (BHT_OK != ret) return convert_errno(errno); @@ -3396,7 +3509,7 @@ fd_table_destroy(struct fd_table *ft) if (ft->entries) { for (uint32 i = 0; i < ft->size; i++) { if (ft->entries[i].object != NULL) { - fd_object_release(ft->entries[i].object); + fd_object_release(NULL, ft->entries[i].object); } } rwlock_destroy(&ft->lock); @@ -3591,6 +3704,7 @@ addr_pool_destroy(struct addr_pool *addr_pool) // implementation #define WASMTIME_SSP_PASSTHROUGH_SOCKET_OPTION(FUNC_NAME, OPTION_TYPE) \ __wasi_errno_t wasmtime_ssp_sock_##FUNC_NAME( \ + wasm_exec_env_t exec_env, \ WASMTIME_SSP_PASSTHROUGH_FD_TABLE __wasi_fd_t sock, \ OPTION_TYPE option) \ { \ @@ -3601,7 +3715,7 @@ addr_pool_destroy(struct addr_pool *addr_pool) if (error != 0) \ return error; \ ret = os_socket_##FUNC_NAME(fd_number(fo), option); \ - fd_object_release(fo); \ + fd_object_release(exec_env, fo); \ if (BHT_OK != ret) \ return convert_errno(errno); \ return __WASI_ESUCCESS; \ @@ -3644,8 +3758,8 @@ WASMTIME_SSP_PASSTHROUGH_SOCKET_OPTION(get_ipv6_only, bool *) #undef WASMTIME_SSP_PASSTHROUGH_SOCKET_OPTION __wasi_errno_t -wasmtime_ssp_sock_set_linger(struct fd_table *curfds, __wasi_fd_t sock, - bool is_enabled, int linger_s) +wasmtime_ssp_sock_set_linger(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t sock, bool is_enabled, int linger_s) { struct fd_object *fo; __wasi_errno_t error; @@ -3655,15 +3769,15 @@ wasmtime_ssp_sock_set_linger(struct fd_table *curfds, __wasi_fd_t sock, return error; ret = os_socket_set_linger(fd_number(fo), is_enabled, linger_s); - fd_object_release(fo); + fd_object_release(exec_env, fo); if (BHT_OK != ret) return convert_errno(errno); return __WASI_ESUCCESS; } __wasi_errno_t -wasmtime_ssp_sock_get_linger(struct fd_table *curfds, __wasi_fd_t sock, - bool *is_enabled, int *linger_s) +wasmtime_ssp_sock_get_linger(wasm_exec_env_t exec_env, struct fd_table *curfds, + __wasi_fd_t sock, bool *is_enabled, int *linger_s) { struct fd_object *fo; __wasi_errno_t error; @@ -3673,7 +3787,7 @@ wasmtime_ssp_sock_get_linger(struct fd_table *curfds, __wasi_fd_t sock, return error; ret = os_socket_get_linger(fd_number(fo), is_enabled, linger_s); - fd_object_release(fo); + fd_object_release(exec_env, fo); if (BHT_OK != ret) return convert_errno(errno); @@ -3681,7 +3795,8 @@ wasmtime_ssp_sock_get_linger(struct fd_table *curfds, __wasi_fd_t sock, } __wasi_errno_t -wasmtime_ssp_sock_set_ip_add_membership(struct fd_table *curfds, +wasmtime_ssp_sock_set_ip_add_membership(wasm_exec_env_t exec_env, + struct fd_table *curfds, __wasi_fd_t sock, __wasi_addr_ip_t *imr_multiaddr, uint32_t imr_interface) @@ -3699,14 +3814,15 @@ wasmtime_ssp_sock_set_ip_add_membership(struct fd_table *curfds, is_ipv6 = imr_multiaddr->kind == IPv6; ret = os_socket_set_ip_add_membership(fd_number(fo), &addr_info, imr_interface, is_ipv6); - fd_object_release(fo); + fd_object_release(exec_env, fo); if (BHT_OK != ret) return convert_errno(errno); return __WASI_ESUCCESS; } __wasi_errno_t -wasmtime_ssp_sock_set_ip_drop_membership(struct fd_table *curfds, +wasmtime_ssp_sock_set_ip_drop_membership(wasm_exec_env_t exec_env, + struct fd_table *curfds, __wasi_fd_t sock, __wasi_addr_ip_t *imr_multiaddr, uint32_t imr_interface) @@ -3724,14 +3840,15 @@ wasmtime_ssp_sock_set_ip_drop_membership(struct fd_table *curfds, is_ipv6 = imr_multiaddr->kind == IPv6; ret = os_socket_set_ip_drop_membership(fd_number(fo), &addr_info, imr_interface, is_ipv6); - fd_object_release(fo); + fd_object_release(exec_env, fo); if (BHT_OK != ret) return convert_errno(errno); return __WASI_ESUCCESS; } __wasi_errno_t -wasmtime_ssp_sock_set_ip_multicast_loop(struct fd_table *curfds, +wasmtime_ssp_sock_set_ip_multicast_loop(wasm_exec_env_t exec_env, + struct fd_table *curfds, __wasi_fd_t sock, bool ipv6, bool is_enabled) { @@ -3743,14 +3860,15 @@ wasmtime_ssp_sock_set_ip_multicast_loop(struct fd_table *curfds, return error; ret = os_socket_set_ip_multicast_loop(fd_number(fo), ipv6, is_enabled); - fd_object_release(fo); + fd_object_release(exec_env, fo); if (BHT_OK != ret) return convert_errno(errno); return __WASI_ESUCCESS; } __wasi_errno_t -wasmtime_ssp_sock_get_ip_multicast_loop(struct fd_table *curfds, +wasmtime_ssp_sock_get_ip_multicast_loop(wasm_exec_env_t exec_env, + struct fd_table *curfds, __wasi_fd_t sock, bool ipv6, bool *is_enabled) { @@ -3762,7 +3880,7 @@ wasmtime_ssp_sock_get_ip_multicast_loop(struct fd_table *curfds, return error; ret = os_socket_get_ip_multicast_loop(fd_number(fo), ipv6, is_enabled); - fd_object_release(fo); + fd_object_release(exec_env, fo); if (BHT_OK != ret) return convert_errno(errno); diff --git a/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/src/ssp_config.h b/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/src/ssp_config.h index f5e130a9e..a69d6ca38 100644 --- a/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/src/ssp_config.h +++ b/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/src/ssp_config.h @@ -14,8 +14,8 @@ #ifndef SSP_CONFIG_H #define SSP_CONFIG_H +#include "bh_platform.h" #include "gnuc.h" -#include #if defined(__FreeBSD__) || defined(__APPLE__) \ || (defined(ANDROID) && __ANDROID_API__ < 28) @@ -65,7 +65,7 @@ #endif #endif -#if !defined(__APPLE__) && !defined(ESP_PLATFORM) +#if !defined(__APPLE__) && !defined(ESP_PLATFORM) && !defined(__COSMOPOLITAN__) #define CONFIG_HAS_POSIX_FALLOCATE 1 #else #define CONFIG_HAS_POSIX_FALLOCATE 0 @@ -83,7 +83,8 @@ #define CONFIG_HAS_PTHREAD_COND_TIMEDWAIT_RELATIVE_NP 0 #endif -#if !defined(__APPLE__) && !defined(BH_PLATFORM_LINUX_SGX) +#if !defined(__APPLE__) && !defined(BH_PLATFORM_LINUX_SGX) \ + && !defined(__COSMOPOLITAN__) #define CONFIG_HAS_PTHREAD_CONDATTR_SETCLOCK 1 #else #define CONFIG_HAS_PTHREAD_CONDATTR_SETCLOCK 0 @@ -101,6 +102,20 @@ #define st_mtim st_mtimespec #endif +#if defined(O_DSYNC) +#define CONFIG_HAS_O_DSYNC +#endif + +// POSIX requires O_RSYNC to be defined, but Linux explicitly doesn't support +// it. +#if defined(O_RSYNC) && !defined(__linux__) +#define CONFIG_HAS_O_RSYNC +#endif + +#if defined(O_SYNC) +#define CONFIG_HAS_O_SYNC +#endif + #if !defined(BH_PLATFORM_LINUX_SGX) /* Clang's __GNUC_PREREQ macro has a different meaning than GCC one, so we have to handle this case specially */ diff --git a/core/iwasm/libraries/thread-mgr/thread_manager.c b/core/iwasm/libraries/thread-mgr/thread_manager.c index 95f0d4267..49545de72 100644 --- a/core/iwasm/libraries/thread-mgr/thread_manager.c +++ b/core/iwasm/libraries/thread-mgr/thread_manager.c @@ -1059,6 +1059,19 @@ set_thread_cancel_flags(WASMExecEnv *exec_env) WASM_SUSPEND_FLAG_TERMINATE); os_mutex_unlock(&exec_env->wait_lock); + +#ifdef OS_ENABLE_WAKEUP_BLOCKING_OP + wasm_runtime_interrupt_blocking_op(exec_env); +#endif +} + +static void +clear_thread_cancel_flags(WASMExecEnv *exec_env) +{ + os_mutex_lock(&exec_env->wait_lock); + WASM_SUSPEND_FLAGS_FETCH_AND(exec_env->suspend_flags, + ~WASM_SUSPEND_FLAG_TERMINATE); + os_mutex_unlock(&exec_env->wait_lock); } int32 @@ -1266,18 +1279,21 @@ set_exception_visitor(void *node, void *user_data) if (data->exception != NULL) { set_thread_cancel_flags(exec_env); } + else { + clear_thread_cancel_flags(exec_env); + } } } void -wasm_cluster_spread_exception(WASMExecEnv *exec_env, const char *exception) +wasm_cluster_set_exception(WASMExecEnv *exec_env, const char *exception) { const bool has_exception = exception != NULL; WASMCluster *cluster = wasm_exec_env_get_cluster(exec_env); bh_assert(cluster); struct spread_exception_data data; - data.skip = exec_env; + data.skip = NULL; data.exception = exception; os_mutex_lock(&cluster->lock); diff --git a/core/iwasm/libraries/thread-mgr/thread_manager.h b/core/iwasm/libraries/thread-mgr/thread_manager.h index 0280119fc..19186f597 100644 --- a/core/iwasm/libraries/thread-mgr/thread_manager.h +++ b/core/iwasm/libraries/thread-mgr/thread_manager.h @@ -139,7 +139,7 @@ WASMExecEnv * wasm_clusters_search_exec_env(WASMModuleInstanceCommon *module_inst); void -wasm_cluster_spread_exception(WASMExecEnv *exec_env, const char *exception); +wasm_cluster_set_exception(WASMExecEnv *exec_env, const char *exception); WASMExecEnv * wasm_cluster_spawn_exec_env(WASMExecEnv *exec_env); diff --git a/core/iwasm/libraries/wasi-nn/src/wasi_nn.c b/core/iwasm/libraries/wasi-nn/src/wasi_nn.c index ba27055ea..c234e450a 100644 --- a/core/iwasm/libraries/wasi-nn/src/wasi_nn.c +++ b/core/iwasm/libraries/wasi-nn/src/wasi_nn.c @@ -163,6 +163,7 @@ void wasi_nn_destroy(wasm_module_inst_t instance) { WASINNContext *wasi_nn_ctx = wasm_runtime_get_wasi_nn_ctx(instance); + bh_hash_map_remove(hashmap, (void *)instance, NULL, NULL); wasi_nn_ctx_destroy(wasi_nn_ctx); } diff --git a/core/shared/platform/alios/alios_platform.c b/core/shared/platform/alios/alios_platform.c index c9f5f17e6..60393ae52 100644 --- a/core/shared/platform/alios/alios_platform.c +++ b/core/shared/platform/alios/alios_platform.c @@ -69,3 +69,7 @@ os_mprotect(void *addr, size_t size, int prot) void os_dcache_flush() {} + +void +os_icache_flush(void *start, size_t len) +{} diff --git a/core/shared/platform/alios/alios_thread.c b/core/shared/platform/alios/alios_thread.c index 0efd2f394..9fe927db0 100644 --- a/core/shared/platform/alios/alios_thread.c +++ b/core/shared/platform/alios/alios_thread.c @@ -359,3 +359,7 @@ os_thread_get_stack_boundary() /* TODO: get alios stack boundary */ return NULL; } + +void +os_thread_jit_write_protect_np(bool enabled) +{} \ No newline at end of file diff --git a/core/shared/platform/android/platform_internal.h b/core/shared/platform/android/platform_internal.h index d718a2d7d..c28a7b9be 100644 --- a/core/shared/platform/android/platform_internal.h +++ b/core/shared/platform/android/platform_internal.h @@ -139,16 +139,12 @@ seekdir(DIR *__dir, long __location); #endif -#if __ANDROID_API__ < 24 - ssize_t preadv(int __fd, const struct iovec *__iov, int __count, off_t __offset); ssize_t pwritev(int __fd, const struct iovec *__iov, int __count, off_t __offset); -#endif - #ifdef __cplusplus } #endif diff --git a/core/shared/platform/common/posix/posix_blocking_op.c b/core/shared/platform/common/posix/posix_blocking_op.c new file mode 100644 index 000000000..560828a06 --- /dev/null +++ b/core/shared/platform/common/posix/posix_blocking_op.c @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2023 Midokura Japan KK. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include "platform_api_extension.h" + +#ifdef OS_ENABLE_WAKEUP_BLOCKING_OP + +static bool g_blocking_op_inited = false; +static int g_blocking_op_signo = SIGUSR1; +static sigset_t g_blocking_op_sigmask; + +static void +blocking_op_sighandler(int signo) +{ + /* nothing */ +} + +void +os_set_signal_number_for_blocking_op(int signo) +{ + g_blocking_op_signo = signo; +} + +int +os_blocking_op_init() +{ + if (g_blocking_op_inited) { + return BHT_OK; + } + + sigemptyset(&g_blocking_op_sigmask); + sigaddset(&g_blocking_op_sigmask, g_blocking_op_signo); + + struct sigaction sa; + sigemptyset(&sa.sa_mask); + sa.sa_flags = 0; + sa.sa_handler = blocking_op_sighandler; + if (sigaction(g_blocking_op_signo, &sa, NULL)) { + return BHT_ERROR; + } + g_blocking_op_inited = true; + return BHT_OK; +} + +void +os_begin_blocking_op() +{ + pthread_sigmask(SIG_UNBLOCK, &g_blocking_op_sigmask, NULL); +} + +void +os_end_blocking_op() +{ + pthread_sigmask(SIG_BLOCK, &g_blocking_op_sigmask, NULL); +} + +int +os_wakeup_blocking_op(korp_tid tid) +{ + int ret = pthread_kill(tid, g_blocking_op_signo); + if (ret != 0) { + return BHT_ERROR; + } + return BHT_OK; +} + +#endif /* OS_ENABLE_WAKEUP_BLOCKING_OP */ diff --git a/core/shared/platform/common/posix/posix_memmap.c b/core/shared/platform/common/posix/posix_memmap.c index 2dfbee453..5d33dcc81 100644 --- a/core/shared/platform/common/posix/posix_memmap.c +++ b/core/shared/platform/common/posix/posix_memmap.c @@ -5,6 +5,10 @@ #include "platform_api_vmcore.h" +#if (defined(__APPLE__) || defined(__MACH__)) && defined(__arm64__) +#include +#endif + #ifndef BH_ENABLE_TRACE_MMAP #define BH_ENABLE_TRACE_MMAP 0 #endif @@ -36,7 +40,11 @@ void * os_mmap(void *hint, size_t size, int prot, int flags) { int map_prot = PROT_NONE; +#if (defined(__APPLE__) || defined(__MACH__)) && defined(__arm64__) + int map_flags = MAP_ANONYMOUS | MAP_PRIVATE | MAP_JIT; +#else int map_flags = MAP_ANONYMOUS | MAP_PRIVATE; +#endif uint64 request_size, page_size; uint8 *addr = MAP_FAILED; uint32 i; @@ -251,3 +259,11 @@ os_mprotect(void *addr, size_t size, int prot) void os_dcache_flush(void) {} + +void +os_icache_flush(void *start, size_t len) +{ +#if (defined(__APPLE__) || defined(__MACH__)) && defined(__arm64__) + sys_icache_invalidate(start, len); +#endif +} \ No newline at end of file diff --git a/core/shared/platform/common/posix/posix_socket.c b/core/shared/platform/common/posix/posix_socket.c index 9f5538b5c..11c56e723 100644 --- a/core/shared/platform/common/posix/posix_socket.c +++ b/core/shared/platform/common/posix/posix_socket.c @@ -799,7 +799,7 @@ os_socket_set_ip_add_membership(bh_socket_t socket, { assert(imr_multiaddr); if (is_ipv6) { -#ifdef IPPROTO_IPV6 +#if defined(IPPROTO_IPV6) && !defined(BH_PLATFORM_COSMOPOLITAN) struct ipv6_mreq mreq; for (int i = 0; i < 8; i++) { ((uint16_t *)mreq.ipv6mr_multiaddr.s6_addr)[i] = @@ -837,7 +837,7 @@ os_socket_set_ip_drop_membership(bh_socket_t socket, { assert(imr_multiaddr); if (is_ipv6) { -#ifdef IPPROTO_IPV6 +#if defined(IPPROTO_IPV6) && !defined(BH_PLATFORM_COSMOPOLITAN) struct ipv6_mreq mreq; for (int i = 0; i < 8; i++) { ((uint16_t *)mreq.ipv6mr_multiaddr.s6_addr)[i] = diff --git a/core/shared/platform/common/posix/posix_thread.c b/core/shared/platform/common/posix/posix_thread.c index 4fb566d6e..498f5f5a2 100644 --- a/core/shared/platform/common/posix/posix_thread.c +++ b/core/shared/platform/common/posix/posix_thread.c @@ -39,6 +39,9 @@ os_thread_wrapper(void *arg) #ifdef OS_ENABLE_HW_BOUND_CHECK if (os_thread_signal_init(handler) != 0) return NULL; +#endif +#ifdef OS_ENABLE_WAKEUP_BLOCKING_OP + os_end_blocking_op(); #endif start_func(thread_arg); #ifdef OS_ENABLE_HW_BOUND_CHECK @@ -415,6 +418,14 @@ os_thread_get_stack_boundary() return addr; } +void +os_thread_jit_write_protect_np(bool enabled) +{ +#if (defined(__APPLE__) || defined(__MACH__)) && defined(__arm64__) + pthread_jit_write_protect_np(enabled); +#endif +} + #ifdef OS_ENABLE_HW_BOUND_CHECK #define SIG_ALT_STACK_SIZE (32 * 1024) @@ -509,8 +520,8 @@ mask_signals(int how) pthread_sigmask(how, &set, NULL); } -static os_thread_local_attribute struct sigaction prev_sig_act_SIGSEGV; -static os_thread_local_attribute struct sigaction prev_sig_act_SIGBUS; +static struct sigaction prev_sig_act_SIGSEGV; +static struct sigaction prev_sig_act_SIGBUS; /* ASAN is not designed to work with custom stack unwind or other low-level \ things. > Ignore a function that does some low-level magic. (e.g. walking \ @@ -541,9 +552,12 @@ signal_callback(int sig_num, siginfo_t *sig_info, void *sig_ucontext) prev_sig_act->sa_sigaction(sig_num, sig_info, sig_ucontext); } else if (prev_sig_act - && ((void *)prev_sig_act->sa_sigaction == SIG_DFL - || (void *)prev_sig_act->sa_sigaction == SIG_IGN)) { - sigaction(sig_num, prev_sig_act, NULL); + && prev_sig_act->sa_handler + /* Filter out SIG_DFL and SIG_IGN here, they will + run into the else branch below */ + && (void *)prev_sig_act->sa_handler != SIG_DFL + && (void *)prev_sig_act->sa_handler != SIG_IGN) { + prev_sig_act->sa_handler(sig_num); } /* Output signal info and then crash if signal is unhandled */ else { diff --git a/core/shared/platform/cosmopolitan/platform_init.c b/core/shared/platform/cosmopolitan/platform_init.c new file mode 100644 index 000000000..2aae13fa1 --- /dev/null +++ b/core/shared/platform/cosmopolitan/platform_init.c @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include "platform_api_vmcore.h" + +int +bh_platform_init() +{ + return 0; +} + +void +bh_platform_destroy() +{} + +int +os_printf(const char *format, ...) +{ + int ret = 0; + va_list ap; + + va_start(ap, format); +#ifndef BH_VPRINTF + ret += vprintf(format, ap); +#else + ret += BH_VPRINTF(format, ap); +#endif + va_end(ap); + + return ret; +} + +int +os_vprintf(const char *format, va_list ap) +{ +#ifndef BH_VPRINTF + return vprintf(format, ap); +#else + return BH_VPRINTF(format, ap); +#endif +} diff --git a/core/shared/platform/cosmopolitan/platform_internal.h b/core/shared/platform/cosmopolitan/platform_internal.h new file mode 100644 index 000000000..ed2545436 --- /dev/null +++ b/core/shared/platform/cosmopolitan/platform_internal.h @@ -0,0 +1,122 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * Copyright (C) 2023 Dylibso. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef _PLATFORM_INTERNAL_H +#define _PLATFORM_INTERNAL_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef BH_PLATFORM_COSMOPOLITAN +#define BH_PLATFORM_COSMOPOLITAN +#endif + +/* Stack size of applet threads's native part. */ +#define BH_APPLET_PRESERVED_STACK_SIZE (32 * 1024) + +/* Default thread priority */ +#define BH_THREAD_DEFAULT_PRIORITY 0 + +typedef pthread_t korp_tid; +typedef pthread_mutex_t korp_mutex; +typedef pthread_cond_t korp_cond; +typedef pthread_t korp_thread; +typedef sem_t korp_sem; + +#define OS_THREAD_MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER + +#define os_thread_local_attribute __thread + +#define bh_socket_t int + +#if WASM_DISABLE_WRITE_GS_BASE == 0 +#if defined(BUILD_TARGET_X86_64) || defined(BUILD_TARGET_AMD_64) +#define os_writegsbase(base_addr) \ + do { \ + uint64 __gs_value = (uint64)(uintptr_t)base_addr; \ + asm volatile("wrgsbase %0" ::"r"(__gs_value) : "memory"); \ + } while (0) +#if 0 +/* _writegsbase_u64 also works, but need to add -mfsgsbase flag for gcc */ +#include +#define os_writegsbase(base_addr) \ + _writegsbase_u64(((uint64)(uintptr_t)base_addr)) +#endif +#endif +#endif + +#if WASM_DISABLE_HW_BOUND_CHECK == 0 +#if defined(BUILD_TARGET_X86_64) || defined(BUILD_TARGET_AMD_64) \ + || defined(BUILD_TARGET_AARCH64) || defined(BUILD_TARGET_RISCV64_LP64D) \ + || defined(BUILD_TARGET_RISCV64_LP64) + +#include + +#define OS_ENABLE_HW_BOUND_CHECK + +typedef jmp_buf korp_jmpbuf; + +#define os_setjmp setjmp +#define os_longjmp longjmp +#define os_alloca alloca + +#define os_getpagesize getpagesize + +typedef void (*os_signal_handler)(void *sig_addr); + +int +os_thread_signal_init(os_signal_handler handler); + +void +os_thread_signal_destroy(); + +bool +os_thread_signal_inited(); + +void +os_signal_unmask(); + +void +os_sigreturn(); +#endif /* end of BUILD_TARGET_X86_64/AMD_64/AARCH64/RISCV64 */ +#endif /* end of WASM_DISABLE_HW_BOUND_CHECK */ + +#ifdef __cplusplus +} +#endif + +#endif /* end of _PLATFORM_INTERNAL_H */ diff --git a/core/shared/platform/cosmopolitan/shared_platform.cmake b/core/shared/platform/cosmopolitan/shared_platform.cmake new file mode 100644 index 000000000..929ecb9e4 --- /dev/null +++ b/core/shared/platform/cosmopolitan/shared_platform.cmake @@ -0,0 +1,19 @@ +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# Copyright (C) 2023 Dylibso. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +set (PLATFORM_SHARED_DIR ${CMAKE_CURRENT_LIST_DIR}) + +add_definitions(-DBH_PLATFORM_COSMOPOLITAN) + +include_directories(${PLATFORM_SHARED_DIR}) +include_directories(${PLATFORM_SHARED_DIR}/../include) + +include (${CMAKE_CURRENT_LIST_DIR}/../common/posix/platform_api_posix.cmake) + +file (GLOB_RECURSE source_all ${PLATFORM_SHARED_DIR}/*.c) + +set (PLATFORM_SHARED_SOURCE ${source_all} ${PLATFORM_COMMON_POSIX_SOURCE}) + +file (GLOB header ${PLATFORM_SHARED_DIR}/../include/*.h) +LIST (APPEND RUNTIME_LIB_HEADER_LIST ${header}) diff --git a/core/shared/platform/darwin/platform_internal.h b/core/shared/platform/darwin/platform_internal.h index 3fd1c258e..d72d48b53 100644 --- a/core/shared/platform/darwin/platform_internal.h +++ b/core/shared/platform/darwin/platform_internal.h @@ -102,6 +102,12 @@ os_sigreturn(); #endif /* end of BUILD_TARGET_X86_64/AMD_64/AARCH64/RISCV64 */ #endif /* end of WASM_DISABLE_HW_BOUND_CHECK */ +#if WASM_DISABLE_WAKEUP_BLOCKING_OP == 0 +#define OS_ENABLE_WAKEUP_BLOCKING_OP +#endif +void +os_set_signal_number_for_blocking_op(int signo); + #ifdef __cplusplus } #endif diff --git a/core/shared/platform/esp-idf/espidf_memmap.c b/core/shared/platform/esp-idf/espidf_memmap.c index 0a1fd4fe4..ce94a9549 100644 --- a/core/shared/platform/esp-idf/espidf_memmap.c +++ b/core/shared/platform/esp-idf/espidf_memmap.c @@ -100,6 +100,10 @@ void #endif } +void +os_icache_flush(void *start, size_t len) +{} + #if (WASM_MEM_DUAL_BUS_MIRROR != 0) void * os_get_dbus_mirror(void *ibus) diff --git a/core/shared/platform/esp-idf/espidf_platform.c b/core/shared/platform/esp-idf/espidf_platform.c index 35b893d81..bbc18f69b 100644 --- a/core/shared/platform/esp-idf/espidf_platform.c +++ b/core/shared/platform/esp-idf/espidf_platform.c @@ -53,6 +53,10 @@ os_thread_get_stack_boundary(void) #endif } +void +os_thread_jit_write_protect_np(bool enabled) +{} + int os_usleep(uint32 usec) { diff --git a/core/shared/platform/freebsd/platform_internal.h b/core/shared/platform/freebsd/platform_internal.h index 7b4789c99..50cabd344 100644 --- a/core/shared/platform/freebsd/platform_internal.h +++ b/core/shared/platform/freebsd/platform_internal.h @@ -101,6 +101,12 @@ os_sigreturn(); #endif /* end of BUILD_TARGET_X86_64/AMD_64/AARCH64/RISCV64 */ #endif /* end of WASM_DISABLE_HW_BOUND_CHECK */ +#if WASM_DISABLE_WAKEUP_BLOCKING_OP == 0 +#define OS_ENABLE_WAKEUP_BLOCKING_OP +#endif +void +os_set_signal_number_for_blocking_op(int signo); + #ifdef __cplusplus } #endif diff --git a/core/shared/platform/include/platform_api_extension.h b/core/shared/platform/include/platform_api_extension.h index 5b7b556e0..06bd9ee89 100644 --- a/core/shared/platform/include/platform_api_extension.h +++ b/core/shared/platform/include/platform_api_extension.h @@ -323,6 +323,34 @@ os_sem_getvalue(korp_sem *sem, int *sval); int os_sem_unlink(const char *name); +/** + * Initialize process-global state for os_wakeup_blocking_op. + */ +int +os_blocking_op_init(); + +/** + * Start accepting os_wakeup_blocking_op requests for the calling thread. + */ +void +os_begin_blocking_op(); + +/** + * Stop accepting os_wakeup_blocking_op requests for the calling thread. + */ +void +os_end_blocking_op(); + +/** + * Wake up the specified thread. + * + * For example, on posix-like platforms, this can be implemented by + * sending a signal (w/o SA_RESTART) which interrupts a blocking + * system call. + */ +int +os_wakeup_blocking_op(korp_tid tid); + /**************************************************** * Section 2 * * Socket support * diff --git a/core/shared/platform/include/platform_api_vmcore.h b/core/shared/platform/include/platform_api_vmcore.h index 15fc1d387..c803c12e4 100644 --- a/core/shared/platform/include/platform_api_vmcore.h +++ b/core/shared/platform/include/platform_api_vmcore.h @@ -81,6 +81,13 @@ os_self_thread(void); uint8 * os_thread_get_stack_boundary(void); +/** + * Set whether the MAP_JIT region write protection is enabled for this thread. + * Pass true to make the region executable, false to make it writable. + */ +void +os_thread_jit_write_protect_np(bool enabled); + /** ************** mutext APIs *********** * vmcore: Not required until pthread is supported by runtime @@ -143,6 +150,12 @@ os_get_dbus_mirror(void *ibus); void os_dcache_flush(void); +/** + * Flush instruction cache. + */ +void +os_icache_flush(void *start, size_t len); + #ifdef __cplusplus } #endif diff --git a/core/shared/platform/linux-sgx/sgx_platform.c b/core/shared/platform/linux-sgx/sgx_platform.c index b40eaf79c..1a90af4c6 100644 --- a/core/shared/platform/linux-sgx/sgx_platform.c +++ b/core/shared/platform/linux-sgx/sgx_platform.c @@ -195,3 +195,7 @@ os_mprotect(void *addr, size_t size, int prot) void os_dcache_flush(void) {} + +void +os_icache_flush(void *start, size_t len) +{} \ No newline at end of file diff --git a/core/shared/platform/linux-sgx/sgx_thread.c b/core/shared/platform/linux-sgx/sgx_thread.c index 1cb2f5d09..d9412927b 100644 --- a/core/shared/platform/linux-sgx/sgx_thread.c +++ b/core/shared/platform/linux-sgx/sgx_thread.c @@ -210,3 +210,7 @@ os_thread_get_stack_boundary() /* TODO: get sgx stack boundary */ return NULL; } + +void +os_thread_jit_write_protect_np(bool enabled) +{} \ No newline at end of file diff --git a/core/shared/platform/linux/platform_internal.h b/core/shared/platform/linux/platform_internal.h index 8439f8723..337cdd9cc 100644 --- a/core/shared/platform/linux/platform_internal.h +++ b/core/shared/platform/linux/platform_internal.h @@ -115,6 +115,12 @@ os_sigreturn(); #endif /* end of BUILD_TARGET_X86_64/AMD_64/AARCH64/RISCV64 */ #endif /* end of WASM_DISABLE_HW_BOUND_CHECK */ +#if WASM_DISABLE_WAKEUP_BLOCKING_OP == 0 +#define OS_ENABLE_WAKEUP_BLOCKING_OP +#endif +void +os_set_signal_number_for_blocking_op(int signo); + #ifdef __cplusplus } #endif diff --git a/core/shared/platform/nuttx/nuttx_platform.c b/core/shared/platform/nuttx/nuttx_platform.c index 0bd1f6808..92c17ed48 100644 --- a/core/shared/platform/nuttx/nuttx_platform.c +++ b/core/shared/platform/nuttx/nuttx_platform.c @@ -144,6 +144,10 @@ os_dcache_flush() bus_sync(); } +void +os_icache_flush(void *start, size_t len) +{} + #if (WASM_MEM_DUAL_BUS_MIRROR != 0) void * os_get_dbus_mirror(void *ibus) diff --git a/core/shared/platform/nuttx/platform_internal.h b/core/shared/platform/nuttx/platform_internal.h index b5bbdacd0..97ab5f697 100644 --- a/core/shared/platform/nuttx/platform_internal.h +++ b/core/shared/platform/nuttx/platform_internal.h @@ -123,6 +123,12 @@ utimensat(int fd, const char *path, const struct timespec ts[2], int flag); DIR * fdopendir(int fd); +#if WASM_DISABLE_WAKEUP_BLOCKING_OP == 0 +#define OS_ENABLE_WAKEUP_BLOCKING_OP +#endif +void +os_set_signal_number_for_blocking_op(int signo); + #ifdef __cplusplus } #endif diff --git a/core/shared/platform/riot/riot_platform.c b/core/shared/platform/riot/riot_platform.c index a0c38e8c9..6fd6617b4 100644 --- a/core/shared/platform/riot/riot_platform.c +++ b/core/shared/platform/riot/riot_platform.c @@ -79,3 +79,7 @@ os_dcache_flush(void) irq_unlock(key); #endif } + +void +os_icache_flush(void *start, size_t len) +{} \ No newline at end of file diff --git a/core/shared/platform/riot/riot_thread.c b/core/shared/platform/riot/riot_thread.c index 0ebcf30e0..a9062bfec 100644 --- a/core/shared/platform/riot/riot_thread.c +++ b/core/shared/platform/riot/riot_thread.c @@ -430,3 +430,7 @@ os_thread_get_stack_boundary() return NULL; #endif } + +void +os_thread_jit_write_protect_np(bool enabled) +{} \ No newline at end of file diff --git a/core/shared/platform/rt-thread/rtt_platform.c b/core/shared/platform/rt-thread/rtt_platform.c index 4685e1ea3..6dc719f01 100644 --- a/core/shared/platform/rt-thread/rtt_platform.c +++ b/core/shared/platform/rt-thread/rtt_platform.c @@ -140,6 +140,10 @@ os_thread_get_stack_boundary(void) return tid->stack_addr; } +void +os_thread_jit_write_protect_np(bool enabled) +{} + int os_mutex_init(korp_mutex *mutex) { @@ -207,3 +211,7 @@ os_mprotect(void *addr, size_t size, int prot) void os_dcache_flush(void) {} + +void +os_icache_flush(void *start, size_t len) +{} \ No newline at end of file diff --git a/core/shared/platform/windows/platform_init.c b/core/shared/platform/windows/platform_init.c index db5885387..96bcf9ab1 100644 --- a/core/shared/platform/windows/platform_init.c +++ b/core/shared/platform/windows/platform_init.c @@ -73,3 +73,7 @@ os_getpagesize() void os_dcache_flush(void) {} + +void +os_icache_flush(void *start, size_t len) +{} \ No newline at end of file diff --git a/core/shared/platform/windows/win_thread.c b/core/shared/platform/windows/win_thread.c index 09cf0c63f..abc36f2fc 100644 --- a/core/shared/platform/windows/win_thread.c +++ b/core/shared/platform/windows/win_thread.c @@ -712,6 +712,10 @@ os_thread_get_stack_boundary() return thread_stack_boundary; } +void +os_thread_jit_write_protect_np(bool enabled) +{} + #ifdef OS_ENABLE_HW_BOUND_CHECK static os_thread_local_attribute bool thread_signal_inited = false; diff --git a/core/shared/platform/zephyr/zephyr_platform.c b/core/shared/platform/zephyr/zephyr_platform.c index b4f2e5ec7..715be8b94 100644 --- a/core/shared/platform/zephyr/zephyr_platform.c +++ b/core/shared/platform/zephyr/zephyr_platform.c @@ -214,6 +214,10 @@ os_dcache_flush() #endif } +void +os_icache_flush(void *start, size_t len) +{} + void set_exec_mem_alloc_func(exec_mem_alloc_func_t alloc_func, exec_mem_free_func_t free_func) diff --git a/core/shared/platform/zephyr/zephyr_thread.c b/core/shared/platform/zephyr/zephyr_thread.c index 1ee2c5cef..105d53993 100644 --- a/core/shared/platform/zephyr/zephyr_thread.c +++ b/core/shared/platform/zephyr/zephyr_thread.c @@ -574,3 +574,7 @@ os_thread_get_stack_boundary() return NULL; #endif } + +void +os_thread_jit_write_protect_np(bool enabled) +{} \ No newline at end of file diff --git a/doc/build_wamr.md b/doc/build_wamr.md index 81b4f6211..9938eadcb 100644 --- a/doc/build_wamr.md +++ b/doc/build_wamr.md @@ -109,6 +109,10 @@ cmake -DWAMR_BUILD_PLATFORM=linux -DWAMR_BUILD_TARGET=ARM - **WAMR_DISABLE_STACK_HW_BOUND_CHECK**=1/0, default to enable if not set and supported by platform, same as `WAMR_DISABLE_HW_BOUND_CHECK`. > Note: When boundary check with hardware trap is disabled, or `WAMR_DISABLE_HW_BOUND_CHECK` is set to 1, the native stack boundary check with hardware trap will be disabled too, no matter what value is set to `WAMR_DISABLE_STACK_HW_BOUND_CHECK`. And when boundary check with hardware trap is enabled, the status of this feature is set according to the value of `WAMR_DISABLE_STACK_HW_BOUND_CHECK`. +#### **Disable async wakeup of blocking operation** +- **WAMR_DISABLE_WAKEUP_BLOCKING_OP**=1/0, default to enable if supported by the platform +> Note: The feature helps async termination of blocking threads. If you disable it, the runtime can wait for termination of blocking threads possibly forever. + #### **Enable tail call feature** - **WAMR_BUILD_TAIL_CALL**=1/0, default to disable if not set diff --git a/doc/export_native_api.md b/doc/export_native_api.md index b87d92552..e293e5c0d 100644 --- a/doc/export_native_api.md +++ b/doc/export_native_api.md @@ -261,4 +261,32 @@ wasm_response_send(wasm_exec_env_t exec_env, char *buffer, int size) ``` +## Native API implementation notes +### Async thread termination + +When threading support is enabled, a thread can be requested to terminate +itself either explicitly by the `wasm_runtime_terminate` API or implicitly +by cluster-wide activities like WASI `proc_exit`. +If a call to your native function can take long or even forever, +you should make it to respond to termination requests in a timely manner. +There are a few implementation approaches for that: + +* Design your API so that it always returns in a timely manner. + This is the most simple approach when possible. + +* Make your native function check the cluster state by calling + `wasm_cluster_is_thread_terminated` from time to time. + If `wasm_cluster_is_thread_terminated` returns true, make your + native function return. + Note: as of writing this, `wasm_cluster_is_thread_terminated` is not + exported as a runtime API. + +* If your native function is a simple wrapper of blocking system call, + you can probably use the `wasm_runtime_begin_blocking_op` and + `wasm_runtime_end_blocking_op` runtime API. + See the comment in `wamr_export.h` for details. + +* If your native function is very complex, it might be simpler to put the + guts of it into a separate worker process so that it can be cleaned up + by simply killing it. diff --git a/doc/memory_tune.md b/doc/memory_tune.md index e14a1a164..05a1a633f 100644 --- a/doc/memory_tune.md +++ b/doc/memory_tune.md @@ -16,7 +16,7 @@ Note: - **linear memory**: a contiguous, mutable array of raw bytes. It is created with an initial size but might be grown dynamically. For most compilers, e.g. wasi-sdk, emsdk, rustc or asc, normally it includes three parts, data area, auxiliary stack area and heap area. For wasi-sdk, the initial/max size can be specified with `-Wl,--initial-memory=n1,--max-memory=n2`, for emsdk, the initial/max size can be specified with `-s INITIAL_MEMORY=n1 -s MAXIMUM_MEMORY=n2 -s ALLOW_MEMORY_GROWTH=1` or `-s TOTAL_MEMORY=n`, and for asc, they can be specified with `--initialMemory` and `--maximumMemory` flags. - If the memory access boundary check with hardware trap feature is enabled, e.g. in Linux/MacOS/Windows x86-64 by default, the linear memory is allocated by `os_mmap` from virtual address space instead of global heap. - **aux stack**: the auxiliary stack resides in linear memory to store some temporary data when calling wasm functions, for example, calling a wasm function with complex struct arguments. For wasi-sdk, the size can be specified with `-z stack-size=n`, for emsdk, the size can be specified with `-s TOTAL_STACK=n`. -- **app heap and libc heap**: the heap to allocate memory for wasm app, note that app heap is created only when the malloc/free functions (or __new/__release functions for AssemblyScript) are not exported and runtime can not detect the libc heap. To export the malloc/free functions, for wasi-sdk and emsdk, developer can use `-Wl,--export=malloc -Wl,--export=free` options, for asc, developer can use `--exportRuntime` option. For app heap, the size is specified by `wasm_runtime_instantiate`. It is recommended to export the malloc/free functions and disable app heap in single thread mode, and for multi-threading, as the libc heap isn't thread-safe, it is recommended to remove the dlmalloc.o from libc.a for wasi-sdk and use `-s MALLOC="none"` for emsdk, refer to [WAMR pthread library](./pthread_library.md) for more details. And developer can use `wasm_runtime_module_malloc/wasm_runtime_module_free` to allocate/free memory from/to app heap (or libc heap if malloc/free functions are exported). +- **app heap and libc heap**: the heap to allocate memory for wasm app, note that app heap is created only when the malloc/free functions (or __new/__release functions for AssemblyScript) are not exported and runtime can not detect the libc heap. To export the malloc/free functions, for wasi-sdk and emsdk, developer can use `-Wl,--export=malloc -Wl,--export=free` options, for asc, developer can use `--exportRuntime` option. For app heap, the size is specified by `wasm_runtime_instantiate`. It is recommended to export the malloc/free functions and disable app heap. However, if you are using [the old pthread implementation](./pthread_impls.md), you might need some workaround to avoid the libc heap as mentioned in [WAMR pthread library](./pthread_library.md). And developer can use `wasm_runtime_module_malloc/wasm_runtime_module_free` to allocate/free memory from/to app heap (or libc heap if malloc/free functions are exported). - **__data_end global and __heap_base global**: two globals exported by wasm application to indicate the end of data area and the base address of libc heap. For WAMR, it is recommended to export them as when there are no possible memory grow operations, runtime will truncate the linear memory into the size indicated by `__heap_base`, so as to reduce the footprint, or at least one page (64KB) is required by linear memory. ## Tune the memory usage diff --git a/product-mini/README.md b/product-mini/README.md index 92f8183e0..22acfeaf4 100644 --- a/product-mini/README.md +++ b/product-mini/README.md @@ -443,3 +443,23 @@ make aos make ``` download the binary to developerkit board, check the output from serial port + +## Cosmopolitan Libc +Currently, only x86_64 architecture with interpreter modes is supported. + +Clone the Cosmopolitan Libc. Setup `cosmocc` as described in [Getting Started](https://github.com/jart/cosmopolitan/#getting-started) being sure to get it into `PATH`. + +Build iwasm +``` Bash +export CC=cosmocc +export CXX=cosmoc++ +rm -rf build +mkdir build +cmake -DWAMR_BUILD_INTERP=1 -DWAMR_BUILD_FAST_INTERP=1 -B build +cmake --build build -j +``` + +Run like +``` Bash +./build/iwasm.com +``` diff --git a/product-mini/platforms/cosmopolitan/CMakeLists.txt b/product-mini/platforms/cosmopolitan/CMakeLists.txt new file mode 100644 index 000000000..8533ea68c --- /dev/null +++ b/product-mini/platforms/cosmopolitan/CMakeLists.txt @@ -0,0 +1,175 @@ +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# Copyright (C) 2023 Dylibso. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required (VERSION 3.14) + +include(CheckPIESupported) + +project (iwasm) + +set (CMAKE_VERBOSE_MAKEFILE OFF) + +set (WAMR_BUILD_PLATFORM "cosmopolitan") + +set(CMAKE_EXECUTABLE_SUFFIX ".com") + +# Reset default linker flags +set (CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "") +set (CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS "") + +set (CMAKE_C_STANDARD 99) +set (CMAKE_CXX_STANDARD 17) + +# Set WAMR_BUILD_TARGET, currently values supported: +# "X86_64", "AMD_64", "X86_32", "AARCH64[sub]", "ARM[sub]", "THUMB[sub]", +# "MIPS", "XTENSA", "RISCV64[sub]", "RISCV32[sub]" +if (NOT DEFINED WAMR_BUILD_TARGET) + if (CMAKE_SYSTEM_PROCESSOR MATCHES "^(arm64|aarch64)") + set (WAMR_BUILD_TARGET "AARCH64") + elseif (CMAKE_SYSTEM_PROCESSOR STREQUAL "riscv64") + set (WAMR_BUILD_TARGET "RISCV64") + elseif (CMAKE_SIZEOF_VOID_P EQUAL 8) + # Build as X86_64 by default in 64-bit platform + set (WAMR_BUILD_TARGET "X86_64") + elseif (CMAKE_SIZEOF_VOID_P EQUAL 4) + # Build as X86_32 by default in 32-bit platform + set (WAMR_BUILD_TARGET "X86_32") + else () + message(SEND_ERROR "Unsupported build target platform!") + endif () +endif () + +if (NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE Release) +endif () + +if (NOT DEFINED WAMR_BUILD_INTERP) + # Enable Interpreter by default + set (WAMR_BUILD_INTERP 1) +endif () + +if (NOT DEFINED WAMR_BUILD_AOT) + # Enable AOT by default. + set (WAMR_BUILD_AOT 1) +endif () + +if (NOT DEFINED WAMR_BUILD_JIT) + # Disable JIT by default. + set (WAMR_BUILD_JIT 0) +endif () + +if (NOT DEFINED WAMR_BUILD_FAST_JIT) + # Disable Fast JIT by default + set (WAMR_BUILD_FAST_JIT 0) +endif () + +if (NOT DEFINED WAMR_BUILD_LIBC_BUILTIN) + # Enable libc builtin support by default + set (WAMR_BUILD_LIBC_BUILTIN 1) +endif () + +if (NOT DEFINED WAMR_BUILD_LIBC_WASI) + # Enable libc wasi support by default + set (WAMR_BUILD_LIBC_WASI 1) +endif () + +if (NOT DEFINED WAMR_BUILD_FAST_INTERP) + # Enable fast interpreter + set (WAMR_BUILD_FAST_INTERP 1) +endif () + +if (NOT DEFINED WAMR_BUILD_MULTI_MODULE) + # Disable multiple modules by default + set (WAMR_BUILD_MULTI_MODULE 0) +endif () + +if (NOT DEFINED WAMR_BUILD_LIB_PTHREAD) + # Disable pthread library by default + set (WAMR_BUILD_LIB_PTHREAD 0) +endif () + +if (NOT DEFINED WAMR_BUILD_LIB_WASI_THREADS) + # Disable wasi threads library by default + set (WAMR_BUILD_LIB_WASI_THREADS 0) +endif() + + +if (NOT DEFINED WAMR_BUILD_MINI_LOADER) + # Disable wasm mini loader by default + set (WAMR_BUILD_MINI_LOADER 0) +endif () + +if (NOT DEFINED WAMR_BUILD_SIMD) + # Enable SIMD by default + set (WAMR_BUILD_SIMD 1) +endif () + +if (NOT DEFINED WAMR_BUILD_REF_TYPES) + # Disable reference types by default + set (WAMR_BUILD_REF_TYPES 0) +endif () + +if (NOT DEFINED WAMR_BUILD_DEBUG_INTERP) + # Disable Debug feature by default + set (WAMR_BUILD_DEBUG_INTERP 0) +endif () + +if (WAMR_BUILD_DEBUG_INTERP EQUAL 1) + set (WAMR_BUILD_FAST_INTERP 0) + set (WAMR_BUILD_MINI_LOADER 0) + set (WAMR_BUILD_SIMD 0) +endif () + +set (WAMR_DISABLE_STACK_HW_BOUND_CHECK 1) +set (WAMR_BUILD_AOT 0) +set (WAMR_DISABLE_WRITE_GS_BASE 1) + +set (WAMR_ROOT_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../..) + +include (${WAMR_ROOT_DIR}/build-scripts/runtime_lib.cmake) + +check_pie_supported() +add_library(vmlib ${WAMR_RUNTIME_LIB_SOURCE}) +set_target_properties (vmlib PROPERTIES POSITION_INDEPENDENT_CODE ON) + +set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--gc-sections") + +set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wextra -Wformat -Wformat-security -Wshadow") +# set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wconversion -Wsign-conversion") + +set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wformat -Wformat-security -Wno-unused") + +if (WAMR_BUILD_TARGET MATCHES "X86_.*" OR WAMR_BUILD_TARGET STREQUAL "AMD_64") + if (NOT (CMAKE_C_COMPILER MATCHES ".*clang.*" OR CMAKE_C_COMPILER_ID MATCHES ".*Clang")) + set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -mindirect-branch-register") + set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mindirect-branch-register") + # UNDEFINED BEHAVIOR, refer to https://en.cppreference.com/w/cpp/language/ub + endif () +endif () + +# The following flags are to enhance security, but it may impact performance, +# we disable them by default. +#if (WAMR_BUILD_TARGET MATCHES "X86_.*" OR WAMR_BUILD_TARGET STREQUAL "AMD_64") +# set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -ftrapv -D_FORTIFY_SOURCE=2") +#endif () +#set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fstack-protector-strong --param ssp-buffer-size=4") +#set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wl,-z,noexecstack,-z,relro,-z,now") + +include (${SHARED_DIR}/utils/uncommon/shared_uncommon.cmake) + +add_executable (iwasm main.c ${UNCOMMON_SHARED_SOURCE}) + +set_target_properties (iwasm PROPERTIES POSITION_INDEPENDENT_CODE ON) + +install (TARGETS iwasm DESTINATION bin) + +target_link_libraries (iwasm vmlib ${LLVM_AVAILABLE_LIBS} ${UV_A_LIBS} ${WASI_NN_LIBS} -lm -ldl -lpthread) + +add_library (libiwasm STATIC ${WAMR_RUNTIME_LIB_SOURCE}) + +install (TARGETS libiwasm DESTINATION lib) + +set_target_properties (libiwasm PROPERTIES OUTPUT_NAME iwasm) + +target_link_libraries (libiwasm ${LLVM_AVAILABLE_LIBS} ${UV_A_LIBS} ${WASI_NN_LIBS} -lm -ldl -lpthread) diff --git a/product-mini/platforms/cosmopolitan/build_cosmocc.sh b/product-mini/platforms/cosmopolitan/build_cosmocc.sh new file mode 100755 index 000000000..b2ce15d33 --- /dev/null +++ b/product-mini/platforms/cosmopolitan/build_cosmocc.sh @@ -0,0 +1,10 @@ +#!/bin/sh + +# Copyright (C) 2023 Dylibso. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +export CC=cosmocc +export CXX=cosmoc++ +rm -rf build +mkdir build +cmake -DWAMR_BUILD_INTERP=1 -DWAMR_BUILD_FAST_INTERP=1 -B build +cmake --build build -j diff --git a/product-mini/platforms/cosmopolitan/main.c b/product-mini/platforms/cosmopolitan/main.c new file mode 100644 index 000000000..8f0e84a97 --- /dev/null +++ b/product-mini/platforms/cosmopolitan/main.c @@ -0,0 +1,6 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include "../posix/main.c" diff --git a/product-mini/platforms/nuttx/wamr.mk b/product-mini/platforms/nuttx/wamr.mk index e5af62cc8..04a6db91f 100644 --- a/product-mini/platforms/nuttx/wamr.mk +++ b/product-mini/platforms/nuttx/wamr.mk @@ -246,6 +246,7 @@ ifeq ($(CONFIG_INTERPRETERS_WAMR_LIBC_WASI),y) CFLAGS += -DWASM_ENABLE_LIBC_WASI=1 CFLAGS += -I$(IWASM_ROOT)/libraries/libc-wasi/sandboxed-system-primitives/src CFLAGS += -I$(IWASM_ROOT)/libraries/libc-wasi/sandboxed-system-primitives/include +CSRCS += blocking_op.c CSRCS += posix_socket.c CSRCS += libc_wasi_wrapper.c VPATH += $(IWASM_ROOT)/libraries/libc-wasi @@ -309,6 +310,9 @@ CFLAGS += -DWASM_DISABLE_HW_BOUND_CHECK=0 CFLAGS += -DWASM_DISABLE_STACK_HW_BOUND_CHECK=0 endif +# REVISIT: is this worth to have a Kconfig? +CFLAGS += -DWASM_DISABLE_WAKEUP_BLOCKING_OP=0 + ifeq ($(CONFIG_INTERPRETERS_WAMR_CUSTOM_NAME_SECTIONS),y) CFLAGS += -DWASM_ENABLE_CUSTOM_NAME_SECTION=1 else @@ -354,8 +358,10 @@ CFLAGS += -I$(IWASM_ROOT)/interpreter endif CSRCS += nuttx_platform.c \ + posix_blocking_op.c \ posix_thread.c \ posix_time.c \ + posix_sleep.c \ mem_alloc.c \ ems_kfc.c \ ems_alloc.c \ @@ -370,6 +376,7 @@ CSRCS += nuttx_platform.c \ bh_read_file.c \ runtime_timer.c \ wasm_application.c \ + wasm_blocking_op.c \ wasm_runtime_common.c \ wasm_native.c \ wasm_exec_env.c \ diff --git a/product-mini/platforms/posix/main.c b/product-mini/platforms/posix/main.c index 6d4ada662..b27bd8c2e 100644 --- a/product-mini/platforms/posix/main.c +++ b/product-mini/platforms/posix/main.c @@ -97,6 +97,11 @@ print_help() #if WASM_ENABLE_LIB_PTHREAD != 0 || WASM_ENABLE_LIB_WASI_THREADS != 0 printf(" --max-threads=n Set maximum thread number per cluster, default is 4\n"); #endif +#if WASM_ENABLE_THREAD_MGR != 0 + printf(" --timeout=ms Set the maximum execution time in ms.\n"); + printf(" If it expires, the runtime aborts the execution\n"); + printf(" with a trap.\n"); +#endif #if WASM_ENABLE_DEBUG_INTERP != 0 printf(" -g=ip:port Set the debug sever address, default is debug disabled\n"); printf(" if port is 0, then a random port will be used\n"); @@ -115,8 +120,7 @@ app_instance_main(wasm_module_inst_t module_inst) const char *exception; wasm_application_execute_main(module_inst, app_argc, app_argv); - if ((exception = wasm_runtime_get_exception(module_inst))) - printf("%s\n", exception); + exception = wasm_runtime_get_exception(module_inst); return exception; } @@ -415,19 +419,28 @@ handle_module_path(const char *module_path) static char *module_search_path = "."; static bool -module_reader_callback(const char *module_name, uint8 **p_buffer, - uint32 *p_size) +module_reader_callback(package_type_t module_type, const char *module_name, + uint8 **p_buffer, uint32 *p_size) { - const char *format = "%s/%s.wasm"; + char *file_format = NULL; +#if WASM_ENABLE_INTERP != 0 + if (module_type == Wasm_Module_Bytecode) + file_format = ".wasm"; +#endif +#if WASM_ENABLE_AOT != 0 + if (module_type == Wasm_Module_AoT) + file_format = ".aot"; +#endif + bh_assert(file_format); + const char *format = "%s/%s%s"; int sz = strlen(module_search_path) + strlen("/") + strlen(module_name) - + strlen(".wasm") + 1; + + strlen(file_format) + 1; char *wasm_file_name = BH_MALLOC(sz); if (!wasm_file_name) { return false; } - - snprintf(wasm_file_name, sz, format, module_search_path, module_name); - + snprintf(wasm_file_name, sz, format, module_search_path, module_name, + file_format); *p_buffer = (uint8_t *)bh_read_file_to_buffer(wasm_file_name, p_size); wasm_runtime_free(wasm_file_name); @@ -488,6 +501,40 @@ dump_pgo_prof_data(wasm_module_inst_t module_inst, const char *path) } #endif +#if WASM_ENABLE_THREAD_MGR != 0 +struct timeout_arg { + uint32 timeout_ms; + wasm_module_inst_t inst; +#if defined(BH_HAS_STD_ATOMIC) + _Atomic +#endif + bool cancel; +}; + +void * +timeout_thread(void *vp) +{ + const struct timeout_arg *arg = vp; + uint32 left = arg->timeout_ms; + while (!arg->cancel) { + uint32 ms; + if (left >= 100) { + ms = 100; + } + else { + ms = left; + } + os_usleep((uint64)ms * 1000); + left -= ms; + if (left == 0) { + wasm_runtime_terminate(arg->inst); + break; + } + } + return NULL; +} +#endif + int main(int argc, char *argv[]) { @@ -546,6 +593,9 @@ main(int argc, char *argv[]) #if WASM_ENABLE_STATIC_PGO != 0 const char *gen_prof_file = NULL; #endif +#if WASM_ENABLE_THREAD_MGR != 0 + int timeout_ms = -1; +#endif /* Process options. */ for (argc--, argv++; argc > 0 && argv[0][0] == '-'; argc--, argv++) { @@ -742,6 +792,13 @@ main(int argc, char *argv[]) wasm_runtime_set_max_thread_num(atoi(argv[0] + 14)); } #endif +#if WASM_ENABLE_THREAD_MGR != 0 + else if (!strncmp(argv[0], "--timeout=", 10)) { + if (argv[0][10] == '\0') + return print_help(); + timeout_ms = atoi(argv[0] + 10); + } +#endif #if WASM_ENABLE_DEBUG_INTERP != 0 else if (!strncmp(argv[0], "-g=", 3)) { char *port_str = strchr(argv[0] + 3, ':'); @@ -902,18 +959,37 @@ main(int argc, char *argv[]) } #endif +#if WASM_ENABLE_THREAD_MGR != 0 + struct timeout_arg timeout_arg; + korp_tid timeout_tid; + if (timeout_ms >= 0) { + timeout_arg.timeout_ms = timeout_ms; + timeout_arg.inst = wasm_module_inst; + timeout_arg.cancel = false; + ret = os_thread_create(&timeout_tid, timeout_thread, &timeout_arg, + APP_THREAD_STACK_SIZE_DEFAULT); + if (ret != 0) { + printf("Failed to start timeout\n"); + goto fail5; + } + } +#endif + ret = 0; + const char *exception = NULL; if (is_repl_mode) { app_instance_repl(wasm_module_inst); } else if (func_name) { - if (app_instance_func(wasm_module_inst, func_name)) { + exception = app_instance_func(wasm_module_inst, func_name); + if (exception) { /* got an exception */ ret = 1; } } else { - if (app_instance_main(wasm_module_inst)) { + exception = app_instance_main(wasm_module_inst); + if (exception) { /* got an exception */ ret = 1; } @@ -926,12 +1002,25 @@ main(int argc, char *argv[]) } #endif + if (exception) + printf("%s\n", exception); + #if WASM_ENABLE_STATIC_PGO != 0 && WASM_ENABLE_AOT != 0 if (get_package_type(wasm_file_buf, wasm_file_size) == Wasm_Module_AoT && gen_prof_file) dump_pgo_prof_data(wasm_module_inst, gen_prof_file); #endif +#if WASM_ENABLE_THREAD_MGR != 0 + if (timeout_ms >= 0) { + timeout_arg.cancel = true; + os_thread_join(timeout_tid, NULL); + } +#endif + +#if WASM_ENABLE_THREAD_MGR != 0 +fail5: +#endif #if WASM_ENABLE_DEBUG_INTERP != 0 fail4: #endif diff --git a/product-mini/platforms/rt-thread/iwasm.c b/product-mini/platforms/rt-thread/iwasm.c index 8ae4da761..9a21301d8 100644 --- a/product-mini/platforms/rt-thread/iwasm.c +++ b/product-mini/platforms/rt-thread/iwasm.c @@ -10,7 +10,6 @@ #include #include #include -#include #ifdef WAMR_ENABLE_RTT_EXPORT @@ -183,8 +182,6 @@ rt_uint8_t * my_read_file_to_buffer(char *filename, rt_uint32_t *size) { struct stat f_stat; - dfs_file_stat(filename, &f_stat); - struct dfs_fd fd; rt_uint8_t *buff = rt_malloc(f_stat.st_size); *size = 0; @@ -193,16 +190,16 @@ my_read_file_to_buffer(char *filename, rt_uint32_t *size) return RT_NULL; } - int ret = dfs_file_open(&fd, filename, O_RDONLY); - if (ret) { + int fd = open(filename, O_RDONLY); + if (fd < 0) { rt_free(buff); - rt_set_errno(ret); + rt_set_errno(fd); return RT_NULL; } - *size = dfs_file_read(&fd, buff, f_stat.st_size); + *size = read(fd, buff, f_stat.st_size); - dfs_file_close(&fd); + close(fd); if (*size != f_stat.st_size) { rt_free(buff); diff --git a/product-mini/platforms/windows/main.c b/product-mini/platforms/windows/main.c index 8b1b1f371..f6347919b 100644 --- a/product-mini/platforms/windows/main.c +++ b/product-mini/platforms/windows/main.c @@ -77,8 +77,7 @@ app_instance_main(wasm_module_inst_t module_inst) const char *exception; wasm_application_execute_main(module_inst, app_argc, app_argv); - if ((exception = wasm_runtime_get_exception(module_inst))) - printf("%s\n", exception); + exception = wasm_runtime_get_exception(module_inst); return exception; } @@ -204,20 +203,29 @@ handle_module_path(const char *module_path) static char *module_search_path = "."; static bool -module_reader_callback(const char *module_name, uint8 **p_buffer, - uint32 *p_size) +module_reader_callback(package_type_t module_type, const char *module_name, + uint8 **p_buffer, uint32 *p_size) { - const char *format = "%s/%s.wasm"; - uint32 sz = (uint32)(strlen(module_search_path) + strlen("/") - + strlen(module_name) + strlen(".wasm") + 1); + char *file_format = NULL; +#if WASM_ENABLE_INTERP != 0 + if (module_type == Wasm_Module_Bytecode) + file_format = ".wasm"; +#endif +#if WASM_ENABLE_AOT != 0 + if (module_type == Wasm_Module_AoT) + file_format = ".aot"; +#endif + bh_assert(file_format); + const char *format = "%s/%s%s"; + int sz = strlen(module_search_path) + strlen("/") + strlen(module_name) + + strlen(file_format) + 1; char *wasm_file_name = BH_MALLOC(sz); if (!wasm_file_name) { return false; } - - snprintf(wasm_file_name, sz, format, module_search_path, module_name); - - *p_buffer = (uint8 *)bh_read_file_to_buffer(wasm_file_name, p_size); + snprintf(wasm_file_name, sz, format, module_search_path, module_name, + file_format); + *p_buffer = (uint8_t *)bh_read_file_to_buffer(wasm_file_name, p_size); wasm_runtime_free(wasm_file_name); return *p_buffer != NULL; @@ -536,17 +544,20 @@ main(int argc, char *argv[]) #endif ret = 0; + const char *exception = NULL; if (is_repl_mode) { app_instance_repl(wasm_module_inst); } else if (func_name) { - if (app_instance_func(wasm_module_inst, func_name)) { + exception = app_instance_func(wasm_module_inst, func_name); + if (exception) { /* got an exception */ ret = 1; } } else { - if (app_instance_main(wasm_module_inst)) { + exception = app_instance_main(wasm_module_inst); + if (exception) { /* got an exception */ ret = 1; } @@ -559,6 +570,9 @@ main(int argc, char *argv[]) } #endif + if (exception) + printf("%s\n", exception); + #if WASM_ENABLE_DEBUG_INTERP != 0 fail4: #endif diff --git a/samples/inst-context-threads/README.md b/samples/inst-context-threads/README.md index 43b13c66b..d64cbff52 100644 --- a/samples/inst-context-threads/README.md +++ b/samples/inst-context-threads/README.md @@ -1,4 +1,5 @@ -The "inst-context" sample project -================================= +The "inst-context-threads" sample project +========================================= -This sample demonstrates module instance context API. +This sample demonstrates some interactions between +module instance context API and wasi-threads. diff --git a/samples/multi-module/CMakeLists.txt b/samples/multi-module/CMakeLists.txt index 2769b9779..ee6c98df4 100644 --- a/samples/multi-module/CMakeLists.txt +++ b/samples/multi-module/CMakeLists.txt @@ -43,8 +43,12 @@ if (NOT CMAKE_BUILD_TYPE) endif () set(WAMR_BUILD_INTERP 1) -set(WAMR_BUILD_AOT 0) -set(WAMR_BUILD_JIT 0) +if (NOT DEFINED WAMR_BUILD_AOT) + set(WAMR_BUILD_AOT 0) +endif () +if (NOT DEFINED WAMR_BUILD_JIT) + set(WAMR_BUILD_JIT 0) +endif () set(WAMR_BUILD_LIBC_BUILTIN 1) set(WAMR_BUILD_LIBC_WASI 1) set(WAMR_BUILD_MULTI_MODULE 1) @@ -144,6 +148,43 @@ ExternalProject_Add(WASM_MODULE ./mE.wasm ${CMAKE_BINARY_DIR} ) +################ WASM MODULES TO AOT +if (WAMR_BUILD_AOT EQUAL 1) + set(WAMR_COMPILER_DIR ${CMAKE_CURRENT_LIST_DIR}/../../wamr-compiler/build) + message(CHECK_START "Detecting WAMR_COMPILER at ${WAMR_COMPILER_DIR}") + find_file(WAMR_COMPILER + wamrc + PATHS "${CMAKE_CURRENT_LIST_DIR}/../../wamr-compiler/build" + NO_DEFAULT_PATH + NO_CMAKE_FIND_ROOT_PATH + ) + if(WAMR_COMPILER) + message(CHECK_PASS "found") + else() + message(CHECK_FAIL "not found") + endif() + if((NOT EXISTS ${WAMR_COMPILER}) ) + message(FATAL_ERROR "Please build wamrc under the path=${WAMR_ROOT_DIR}/wamr-compiler/ ") + else() + message(STATUS "WAMR_COMPILER is ${WAMR_COMPILER}") + endif() + + add_custom_target( + wasm_to_aot + ALL + DEPENDS + WASM_MODULE ${WAMR_COMPILER} + COMMAND + ${WAMR_COMPILER} -o mA.aot ./mA.wasm + COMMAND + ${WAMR_COMPILER} -o mB.aot ./mB.wasm + COMMAND + ${WAMR_COMPILER} -o mC.aot ./mC.wasm + WORKING_DIRECTORY + ${CMAKE_BINARY_DIR} + ) +endif() + ################ NATIVE include_directories(${CMAKE_CURRENT_LIST_DIR}/src) include (${SHARED_DIR}/utils/uncommon/shared_uncommon.cmake) diff --git a/samples/multi-module/README.md b/samples/multi-module/README.md new file mode 100644 index 000000000..1ec92620c --- /dev/null +++ b/samples/multi-module/README.md @@ -0,0 +1,20 @@ +# WAMR MULTI-MODUEL SAMPLE +**WAMR supports *multi-module* in both *interpreter* mode and *aot* mode.** + +Multi-modules will determine the running mode based on the type of the main module. + + +``` shell +$ mkdir build +$ cd build +$ cmake .. +$ make +$ # It will build multi-module runtime and +$ # wasm file under the ./build . +$ # If you have built wamrc, +$ # aot file will also genrate. +$ ./multi-module mC.wasm +$ ... +$ ./multi-module mC.aot +$ ... + diff --git a/samples/multi-module/src/main.c b/samples/multi-module/src/main.c index ca95ded5f..361856136 100644 --- a/samples/multi-module/src/main.c +++ b/samples/multi-module/src/main.c @@ -1,59 +1,63 @@ #include #include #include - #include "bh_read_file.h" #include "platform_common.h" #include "wasm_export.h" -static char * -build_module_path(const char *module_name) +#if WASM_ENABLE_MULTI_MODULE != 0 +static char *module_search_path = "."; +static bool +module_reader_callback(package_type_t module_type, const char *module_name, + uint8 **p_buffer, uint32 *p_size) { - const char *module_search_path = "."; - const char *format = "%s/%s.wasm"; + char *file_format; +#if WASM_ENABLE_INTERP != 0 + if (module_type == Wasm_Module_Bytecode) + file_format = ".wasm"; +#endif +#if WASM_ENABLE_AOT != 0 + if (module_type == Wasm_Module_AoT) + file_format = ".aot"; + +#endif + const char *format = "%s/%s%s"; int sz = strlen(module_search_path) + strlen("/") + strlen(module_name) - + strlen(".wasm") + 1; + + strlen(file_format) + 1; char *wasm_file_name = BH_MALLOC(sz); if (!wasm_file_name) { - return NULL; - } - - snprintf(wasm_file_name, sz, format, module_search_path, module_name); - return wasm_file_name; -} - -static bool -module_reader_cb(const char *module_name, uint8 **p_buffer, uint32 *p_size) -{ - char *wasm_file_path = build_module_path(module_name); - if (!wasm_file_path) { return false; } + snprintf(wasm_file_name, sz, format, module_search_path, module_name, + file_format); + *p_buffer = (uint8_t *)bh_read_file_to_buffer(wasm_file_name, p_size); - printf("- bh_read_file_to_buffer %s\n", wasm_file_path); - *p_buffer = (uint8_t *)bh_read_file_to_buffer(wasm_file_path, p_size); - BH_FREE(wasm_file_path); + wasm_runtime_free(wasm_file_name); return *p_buffer != NULL; } static void -module_destroyer_cb(uint8 *buffer, uint32 size) +moudle_destroyer(uint8 *buffer, uint32 size) { - printf("- release the read file buffer\n"); if (!buffer) { return; } - BH_FREE(buffer); + wasm_runtime_free(buffer); buffer = NULL; } +#endif /* WASM_ENABLE_MULTI_MODULE */ /* 10M */ static char sandbox_memory_space[10 * 1024 * 1024] = { 0 }; int -main() +main(int argc, char *argv[]) { bool ret = false; + if (argc != 2) { + return -1; + } + char *wasm_file = argv[1]; /* 16K */ const uint32 stack_size = 16 * 1024; const uint32 heap_size = 16 * 1024; @@ -84,16 +88,16 @@ main() #if WASM_ENABLE_MULTI_MODULE != 0 printf("- wasm_runtime_set_module_reader\n"); /* set module reader and destroyer */ - wasm_runtime_set_module_reader(module_reader_cb, module_destroyer_cb); + wasm_runtime_set_module_reader(module_reader_callback, moudle_destroyer); #endif /* load WASM byte buffer from WASM bin file */ - if (!module_reader_cb("mC", &file_buf, &file_buf_size)) { + if (!(file_buf = + (uint8 *)bh_read_file_to_buffer(wasm_file, &file_buf_size))) goto RELEASE_RUNTIME; - } - /* load mC and let WAMR load mA and mB */ printf("- wasm_runtime_load\n"); + if (!(module = wasm_runtime_load(file_buf, file_buf_size, error_buf, sizeof(error_buf)))) { printf("%s\n", error_buf); @@ -158,7 +162,7 @@ UNLOAD_MODULE: printf("- wasm_runtime_unload\n"); wasm_runtime_unload(module); RELEASE_BINARY: - module_destroyer_cb(file_buf, file_buf_size); + moudle_destroyer(file_buf, file_buf_size); RELEASE_RUNTIME: printf("- wasm_runtime_destroy\n"); wasm_runtime_destroy(); diff --git a/tests/benchmarks/jetstream/tsf.patch b/tests/benchmarks/jetstream/tsf.patch index e52c3cdc5..98355b08c 100644 --- a/tests/benchmarks/jetstream/tsf.patch +++ b/tests/benchmarks/jetstream/tsf.patch @@ -1,6 +1,18 @@ +diff -urN tsf-src-org/gpc_code_gen_util.c tsf-src/gpc_code_gen_util.c +--- tsf-src-org/gpc_code_gen_util.c 2023-09-21 11:12:40.211166472 +0800 ++++ tsf-src/gpc_code_gen_util.c 2023-09-21 11:09:13.643170967 +0800 +@@ -34,6 +34,8 @@ + #include + #include + ++int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result); ++ + /* code generation debugging */ + + /* NOTE: It is now the case that the count may be incremented multiple times, diff -urN tsf-src-org/tsf_internal.h tsf-src/tsf_internal.h ---- tsf-src-org/tsf_internal.h 2023-03-31 10:49:45.000000000 +0800 -+++ tsf-src/tsf_internal.h 2023-05-11 08:18:35.000000000 +0800 +--- tsf-src-org/tsf_internal.h 2023-09-21 11:11:50.843167546 +0800 ++++ tsf-src/tsf_internal.h 2023-09-21 11:06:53.031174027 +0800 @@ -429,6 +429,7 @@ #endif tsf_fsdb_connection_t *connection; @@ -10,15 +22,15 @@ diff -urN tsf-src-org/tsf_internal.h tsf-src/tsf_internal.h } u; tsf_limits_t *limits; diff -urN tsf-src-org/tsf_ir_speed.c tsf-src/tsf_ir_speed.c ---- tsf-src-org/tsf_ir_speed.c 2023-03-31 10:49:45.000000000 +0800 -+++ tsf-src/tsf_ir_speed.c 2023-05-11 08:18:35.000000000 +0800 +--- tsf-src-org/tsf_ir_speed.c 2023-09-21 11:12:15.699167005 +0800 ++++ tsf-src/tsf_ir_speed.c 2023-09-21 11:06:53.031174027 +0800 @@ -63,6 +63,9 @@ Program_t *program; unsigned elementIndex; - + + if (!(programIndex % 100)) + printf("##programIndex: %u\n", programIndex); + CS(program = tsf_region_create(sizeof(Program_t))); - + program->globals.len = numDecls + numDefns; diff --git a/tests/wamr-compiler/.gitignore b/tests/wamr-compiler/.gitignore new file mode 100644 index 000000000..5425c41bd --- /dev/null +++ b/tests/wamr-compiler/.gitignore @@ -0,0 +1,2 @@ +*.aot +*.wasm \ No newline at end of file diff --git a/tests/wamr-compiler/README.md b/tests/wamr-compiler/README.md new file mode 100644 index 000000000..d48ea9827 --- /dev/null +++ b/tests/wamr-compiler/README.md @@ -0,0 +1,3 @@ +# WAMR test benchmarks + +This folder contains tests for WAMR AOT compiler and its generated code. diff --git a/tests/wamr-compiler/test_shift_negative_constants.wat b/tests/wamr-compiler/test_shift_negative_constants.wat new file mode 100644 index 000000000..030cc8983 --- /dev/null +++ b/tests/wamr-compiler/test_shift_negative_constants.wat @@ -0,0 +1,43 @@ +;; Copyright (C) 2023 Amazon Inc. All rights reserved. +;; SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +;; +;; Those tests verify if passing constant negative value +;; as a right parameter of the shift operator (along +;; with a constant value of the left operator) causes +;; any problems. See: https://github.com/bytecodealliance/wasm-micro-runtime/pull/2619 +(module + (memory (export "memory") 1 1) + (func $assert_eq (param i32 i32) + (i32.ne (local.get 0) (local.get 1)) + if + unreachable + end + ) + + (func $i32_shr_u + (call $assert_eq + (i32.shr_u (i32.const -1) (i32.const -5)) + (i32.const 31) + ) + ) + + (func $i32_shr_s + (call $assert_eq + (i32.shr_u (i32.const 32) (i32.const -30)) + (i32.const 8) + ) + ) + + (func $i32_shl + (call $assert_eq + (i32.shl (i32.const -1) (i32.const -30)) + (i32.const -4) + ) + ) + + (func (export "_start") + call $i32_shr_u + call $i32_shr_s + call $i32_shl + ) +) diff --git a/tests/wamr-test-suites/spec-test-script/all.py b/tests/wamr-test-suites/spec-test-script/all.py index bd5b89ce4..12ac005bb 100644 --- a/tests/wamr-test-suites/spec-test-script/all.py +++ b/tests/wamr-test-suites/spec-test-script/all.py @@ -37,6 +37,7 @@ WAST2WASM_CMD = "./wabt/out/gcc/Release/wat2wasm" SPEC_INTERPRETER_CMD = "spec/interpreter/wasm" WAMRC_CMD = "../../../wamr-compiler/build/wamrc" + class TargetAction(argparse.Action): TARGET_MAP = { "ARMV7_VFP": "armv7", @@ -49,6 +50,7 @@ class TargetAction(argparse.Action): "THUMBV7_VFP": "thumbv7", "X86_32": "i386", "X86_64": "x86_64", + "AARCH64": "arm64" } def __call__(self, parser, namespace, values, option_string=None): @@ -65,7 +67,7 @@ def ignore_the_case( simd_flag=False, gc_flag=False, xip_flag=False, - qemu_flag=False + qemu_flag=False, ): if case_name in ["comments", "inline-module", "names"]: return True @@ -79,7 +81,7 @@ def ignore_the_case( if gc_flag: if case_name in ["type-canon", "type-equivalence", "type-rec"]: - return True; + return True if sgx_flag: if case_name in ["conversions", "f32_bitwise", "f64_bitwise"]: @@ -94,9 +96,20 @@ def ignore_the_case( return True if qemu_flag: - if case_name in ["f32_bitwise", "f64_bitwise", "loop", "f64", "f64_cmp", - "conversions", "f32", "f32_cmp", "float_exprs", - "float_misc", "select", "memory_grow"]: + if case_name in [ + "f32_bitwise", + "f64_bitwise", + "loop", + "f64", + "f64_cmp", + "conversions", + "f32", + "f32_cmp", + "float_exprs", + "float_misc", + "select", + "memory_grow", + ]: return True return False @@ -131,26 +144,9 @@ def test_case( verbose_flag=True, gc_flag=False, qemu_flag=False, - qemu_firmware='', - log='', + qemu_firmware="", + log="", ): - case_path = pathlib.Path(case_path).resolve() - case_name = case_path.stem - - if ignore_the_case( - case_name, - target, - aot_flag, - sgx_flag, - multi_module_flag, - multi_thread_flag, - simd_flag, - gc_flag, - xip_flag, - qemu_flag - ): - return True - CMD = ["python3", "runtest.py"] CMD.append("--wast2wasm") CMD.append(WAST2WASM_CMD if not gc_flag else SPEC_INTERPRETER_CMD) @@ -196,11 +192,15 @@ def test_case( if gc_flag: CMD.append("--gc") - if log != '': + if log != "": CMD.append("--log-dir") CMD.append(log) - CMD.append(case_path) + case_path = pathlib.Path(case_path).resolve() + case_name = case_path.stem + + CMD.append(str(case_path)) + # print(f"============> use {' '.join(CMD)}") print(f"============> run {case_name} ", end="") with subprocess.Popen( CMD, @@ -259,8 +259,8 @@ def test_suite( gc_flag=False, parl_flag=False, qemu_flag=False, - qemu_firmware='', - log='', + qemu_firmware="", + log="", ): suite_path = pathlib.Path(SPEC_TEST_DIR).resolve() if not suite_path.exists(): @@ -276,6 +276,26 @@ def test_suite( gc_case_list = sorted(suite_path.glob("gc/*.wast")) case_list.extend(gc_case_list) + # ignore based on command line options + filtered_case_list = [] + for case_path in case_list: + case_name = case_path.stem + if not ignore_the_case( + case_name, + target, + aot_flag, + sgx_flag, + multi_module_flag, + multi_thread_flag, + simd_flag, + gc_flag, + xip_flag, + qemu_flag, + ): + filtered_case_list.append(case_path) + print(f"---> {len(case_list)} --filter--> {len(filtered_case_list)}") + case_list = filtered_case_list + case_count = len(case_list) failed_case = 0 successful_case = 0 @@ -435,7 +455,7 @@ def main(): ) parser.add_argument( "--log", - default='', + default="", dest="log", help="Log directory", ) @@ -462,7 +482,6 @@ def main(): ) options = parser.parse_args() - print(options) if not preflight_check(options.aot_flag): return False @@ -512,7 +531,7 @@ def main(): options.gc_flag, options.qemu_flag, options.qemu_firmware, - options.log + options.log, ) else: ret = True diff --git a/tests/wamr-test-suites/spec-test-script/muti_module_aot_ignore_cases.patch b/tests/wamr-test-suites/spec-test-script/muti_module_aot_ignore_cases.patch new file mode 100644 index 000000000..4494e0856 --- /dev/null +++ b/tests/wamr-test-suites/spec-test-script/muti_module_aot_ignore_cases.patch @@ -0,0 +1,174 @@ +diff --git a/test/core/linking.wast b/test/core/linking.wast +index d0bfb5f..6617945 100644 +--- a/test/core/linking.wast ++++ b/test/core/linking.wast +@@ -35,7 +35,7 @@ + + + ;; Globals +- ++(; + (module $Mg + (global $glob (export "glob") i32 (i32.const 42)) + (func (export "get") (result i32) (global.get $glob)) +@@ -63,7 +63,7 @@ + (export "Mg.get_mut" (func $get_mut)) + (export "Mg.set_mut" (func $set_mut)) + ) +- ++;) + (; + (assert_return (get $Mg "glob") (i32.const 42)) + (assert_return (get $Ng "Mg.glob") (i32.const 42)) +@@ -84,7 +84,7 @@ + (assert_return (invoke $Ng "Mg.get_mut") (i32.const 241)) + ;) + +- ++(; + (assert_unlinkable + (module (import "Mg" "mut_glob" (global i32))) + "incompatible import type" +@@ -166,7 +166,7 @@ + (call_indirect (type 1) (local.get 0)) + ) + ) +- ++;) + (; + (assert_return (invoke $Mt "call" (i32.const 2)) (i32.const 4)) + (assert_return (invoke $Nt "Mt.call" (i32.const 2)) (i32.const 4)) +@@ -191,7 +191,7 @@ + (assert_return (invoke $Nt "call" (i32.const 3)) (i32.const -4)) + (assert_trap (invoke $Nt "call" (i32.const 4)) "indirect call type mismatch") + ;) +- ++(; + (module $Ot + (type (func (result i32))) + +@@ -204,7 +204,7 @@ + (call_indirect (type 0) (local.get 0)) + ) + ) +- ++;) + (; + (assert_return (invoke $Mt "call" (i32.const 3)) (i32.const 4)) + (assert_return (invoke $Nt "Mt.call" (i32.const 3)) (i32.const 4)) +@@ -231,7 +231,7 @@ + + (assert_trap (invoke $Ot "call" (i32.const 20)) "undefined element") + ;) +- ++(; + (module + (table (import "Mt" "tab") 0 funcref) + (elem (i32.const 9) $f) +@@ -266,7 +266,7 @@ + "unknown import" + ) + (assert_trap (invoke $Mt "call" (i32.const 7)) "uninitialized element") +- ++;) + ;; Unlike in the v1 spec, active element segments stored before an + ;; out-of-bounds access persist after the instantiation failure. + (; +@@ -297,7 +297,7 @@ + (assert_return (invoke $Mt "call" (i32.const 7)) (i32.const 0)) + ;) + +- ++(; + (module $Mtable_ex + (table $t1 (export "t-func") 1 funcref) + (table $t2 (export "t-extern") 1 externref) +@@ -308,7 +308,7 @@ + (table (import "Mtable_ex" "t-func") 1 funcref) + (table (import "Mtable_ex" "t-extern") 1 externref) + ) +- ++;) + (; + (assert_unlinkable + (module (table (import "Mtable_ex" "t-func") 1 externref)) +@@ -322,7 +322,7 @@ + + + ;; Memories +- ++(; + (module $Mm + (memory (export "mem") 1 5) + (data (i32.const 10) "\00\01\02\03\04\05\06\07\08\09") +@@ -357,14 +357,14 @@ + (i32.load8_u (local.get 0)) + ) + ) +- ++;) + (; + (assert_return (invoke $Mm "load" (i32.const 12)) (i32.const 0xa7)) + (assert_return (invoke $Nm "Mm.load" (i32.const 12)) (i32.const 0xa7)) + (assert_return (invoke $Nm "load" (i32.const 12)) (i32.const 0xf2)) + (assert_return (invoke $Om "load" (i32.const 12)) (i32.const 0xa7)) + ;) +- ++(; + (module + (memory (import "Mm" "mem") 0) + (data (i32.const 0xffff) "a") +@@ -385,7 +385,7 @@ + (memory.grow (local.get 0)) + ) + ) +- ++;) + (; + (assert_return (invoke $Pm "grow" (i32.const 0)) (i32.const 1)) + (assert_return (invoke $Pm "grow" (i32.const 2)) (i32.const 1)) +@@ -396,7 +396,7 @@ + (assert_return (invoke $Pm "grow" (i32.const 1)) (i32.const -1)) + (assert_return (invoke $Pm "grow" (i32.const 0)) (i32.const 5)) + ;) +- ++(; + (assert_unlinkable + (module + (func $host (import "spectest" "print")) +@@ -419,11 +419,12 @@ + ) + "out of bounds memory access" + ) ++;) + (; + (assert_return (invoke $Mm "load" (i32.const 0)) (i32.const 97)) + (assert_return (invoke $Mm "load" (i32.const 327670)) (i32.const 0)) + ;) +- ++(; + (assert_trap + (module + (memory (import "Mm" "mem") 1) +@@ -434,10 +435,11 @@ + ) + "out of bounds table access" + ) ++;) + (; + (assert_return (invoke $Mm "load" (i32.const 0)) (i32.const 97)) + ;) +- ++(; + ;; Store is modified if the start function traps. + (module $Ms + (type $t (func (result i32))) +@@ -451,7 +453,7 @@ + ) + ) + (register "Ms" $Ms) +- ++;) + (; + (assert_trap + (module diff --git a/tests/wamr-test-suites/spec-test-script/runtest.py b/tests/wamr-test-suites/spec-test-script/runtest.py index a1e505bd0..566a165f3 100755 --- a/tests/wamr-test-suites/spec-test-script/runtest.py +++ b/tests/wamr-test-suites/spec-test-script/runtest.py @@ -400,7 +400,7 @@ def cast_v128_to_i64x2(numbers, type, lane_type): assert(packed) unpacked = struct.unpack("Q Q", packed) - return unpacked, "[{} {}]:{}:v128".format(unpacked[0], unpacked[1], lane_type) + return unpacked, f"[{unpacked[0]:#x} {unpacked[1]:#x}]:{lane_type}:v128" def parse_simple_const_w_type(number, type): @@ -412,13 +412,7 @@ def parse_simple_const_w_type(number, type): else "-0x{:x}:{}".format(0 - number, type) elif type in ["f32", "f64"]: if "nan:" in number: - # TODO: how to handle this correctly - if "nan:canonical" in number: - return float.fromhex("0x200000"), "nan:{}".format(type) - elif "nan:arithmetic" in number: - return float.fromhex("-0x200000"), "nan:{}".format(type) - else: - return float('nan'), "nan:{}".format(type) + return float('nan'), "nan:{}".format(type) else: number = float.fromhex(number) if '0x' in number else float(number) return number, "{:.7g}:{}".format(number, type) @@ -542,9 +536,6 @@ def vector_value_comparison(out, expected): if out_type != expected_type: return False - if out_val == expected_val: - return True - out_val = out_val.split(" ") expected_val = expected_val.split(" ") @@ -568,12 +559,14 @@ def vector_value_comparison(out, expected): out_is_nan = [math.isnan(o) for o in out_unpacked] expected_is_nan = [math.isnan(e) for e in expected_unpacked] - if out_is_nan and expected_is_nan: - return True; + if any(out_is_nan): + nan_comparision = [o == e for o, e in zip(out_is_nan, expected_is_nan)] + if all(nan_comparision): + print(f"Pass NaN comparision") + return True - # print("compare {} and {}".format(out_unpacked, expected_unpacked)) + # print(f"compare {out_unpacked} and {expected_unpacked}") result = [o == e for o, e in zip(out_unpacked, expected_unpacked)] - if not all(result): result = [ "{:.7g}".format(o) == "{:.7g}".format(e) @@ -778,7 +771,7 @@ def test_assert_return(r, opts, form): numbers, _ = cast_v128_to_i64x2(splitted[2:], 'v128', splitted[1]) assert(len(numbers) == 2), "has to reform arguments into i64x2" - args.append("{}\{}".format(numbers[0], numbers[1])) + args.append(f"{numbers[0]:#x}\{numbers[1]:#x}") elif "ref.null" == splitted[0]: args.append("null") elif "ref.extern" == splitted[0]: @@ -1129,7 +1122,7 @@ def test_assert_with_exception(form, wast_tempfile, wasm_tempfile, aot_tempfile, if __name__ == "__main__": opts = parser.parse_args(sys.argv[1:]) - print('Input param :',opts) + # print('Input param :',opts) if opts.aot: test_aot = True # default x86_64 @@ -1152,7 +1145,7 @@ if __name__ == "__main__": ret_code = 0 try: - log("################################################") + log("\n################################################") log("### Testing %s" % opts.test_file.name) log("################################################") forms = read_forms(opts.test_file.read()) @@ -1299,6 +1292,16 @@ if __name__ == "__main__": # add new_module copied from the old into temp_file_repo[] temp_file_repo.append(new_module) + + if test_aot: + new_module_aot = os.path.join(tempfile.gettempdir(), name_new + ".aot") + r = compile_wasm_to_aot(new_module, new_module_aot, True, opts, r) + try: + assert_prompt(r, ['Compile success'], opts.start_timeout, True) + except: + raise Exception("compile wasm to aot failed") + # add aot module into temp_file_repo[] + temp_file_repo.append(new_module_aot) else: # there is no name defined in register cmd raise Exception("can not find module name from the register") @@ -1341,3 +1344,4 @@ if __name__ == "__main__": log("Leaving tempfiles: %s" % ([wast_tempfile, wasm_tempfile])) sys.exit(ret_code) + \ No newline at end of file diff --git a/tests/wamr-test-suites/test_wamr.sh b/tests/wamr-test-suites/test_wamr.sh index 1448e3e1e..81844f0e7 100755 --- a/tests/wamr-test-suites/test_wamr.sh +++ b/tests/wamr-test-suites/test_wamr.sh @@ -14,8 +14,8 @@ function help() { echo "test_wamr.sh [options]" echo "-c clean previous test results, not start test" - echo "-s {suite_name} test only one suite (spec|wasi_certification)" - echo "-m set compile target of iwasm(x86_64|x86_32|armv7_vfp|thumbv7_vfp|riscv64_lp64d|riscv64_lp64)" + echo "-s {suite_name} test only one suite (spec|wasi_certification|wamr_compiler)" + echo "-m set compile target of iwasm(x86_64|x86_32|armv7_vfp|thumbv7_vfp|riscv64_lp64d|riscv64_lp64|aarch64)" echo "-t set compile type of iwasm(classic-interp|fast-interp|jit|aot|fast-jit|multi-tier-jit)" echo "-M enable multi module feature" echo "-p enable multi thread feature" @@ -31,6 +31,7 @@ function help() echo "-Q enable qemu" echo "-F set the firmware path used by qemu" echo "-C enable code coverage collect" + echo "-j set the platform to test" } OPT_PARSED="" @@ -55,9 +56,10 @@ PLATFORM=$(uname -s | tr A-Z a-z) PARALLELISM=0 ENABLE_QEMU=0 QEMU_FIRMWARE="" -WASI_TESTSUITE_COMMIT="aca78d919355ae00af141e6741a439039615b257" +# prod/testsuite-all branch +WASI_TESTSUITE_COMMIT="ee807fc551978490bf1c277059aabfa1e589a6c2" -while getopts ":s:cabgvt:m:MCpSXxwPGQF:" opt +while getopts ":s:cabgvt:m:MCpSXxwPGQF:j:" opt do OPT_PARSED="TRUE" case $opt in @@ -159,6 +161,10 @@ do echo "QEMU firmware" ${OPTARG} QEMU_FIRMWARE=${OPTARG} ;; + j) + echo "test platform " ${OPTARG} + PLATFORM=${OPTARG} + ;; ?) help exit 1;; @@ -303,6 +309,53 @@ function sightglass_test() echo "Finish sightglass benchmark tests" } +function setup_wabt() +{ + if [ ${WABT_BINARY_RELEASE} == "YES" ]; then + echo "download a binary release and install" + local WAT2WASM=${WORK_DIR}/wabt/out/gcc/Release/wat2wasm + if [ ! -f ${WAT2WASM} ]; then + case ${PLATFORM} in + cosmopolitan) + ;& + linux) + WABT_PLATFORM=ubuntu + ;; + darwin) + WABT_PLATFORM=macos + ;; + *) + echo "wabt platform for ${PLATFORM} in unknown" + exit 1 + ;; + esac + if [ ! -f /tmp/wabt-1.0.31-${WABT_PLATFORM}.tar.gz ]; then + wget \ + https://github.com/WebAssembly/wabt/releases/download/1.0.31/wabt-1.0.31-${WABT_PLATFORM}.tar.gz \ + -P /tmp + fi + + cd /tmp \ + && tar zxf wabt-1.0.31-${WABT_PLATFORM}.tar.gz \ + && mkdir -p ${WORK_DIR}/wabt/out/gcc/Release/ \ + && install wabt-1.0.31/bin/wa* ${WORK_DIR}/wabt/out/gcc/Release/ \ + && cd - + fi + else + echo "download source code and compile and install" + if [ ! -d "wabt" ];then + echo "wabt not exist, clone it from github" + git clone --recursive https://github.com/WebAssembly/wabt + fi + echo "upate wabt" + cd wabt + git pull + git reset --hard origin/main + cd .. + make -C wabt gcc-release -j 4 + fi +} + # TODO: with iwasm only function spec_test() { @@ -332,6 +385,9 @@ function spec_test() if [[ ${ENABLE_SIMD} == 1 ]]; then git apply ../../spec-test-script/simd_ignore_cases.patch fi + if [[ ${ENABLE_MULTI_MODULE} == 1 && $1 == 'aot' ]]; then + git apply ../../spec-test-script/muti_module_aot_ignore_cases.patch + fi # udpate thread cases if [ ${ENABLE_MULTI_THREAD} == 1 ]; then @@ -374,47 +430,7 @@ function spec_test() popd echo $(pwd) - if [ ${WABT_BINARY_RELEASE} == "YES" ]; then - echo "download a binary release and install" - local WAT2WASM=${WORK_DIR}/wabt/out/gcc/Release/wat2wasm - if [ ! -f ${WAT2WASM} ]; then - case ${PLATFORM} in - linux) - WABT_PLATFORM=ubuntu - ;; - darwin) - WABT_PLATFORM=macos - ;; - *) - echo "wabt platform for ${PLATFORM} in unknown" - exit 1 - ;; - esac - if [ ! -f /tmp/wabt-1.0.31-${WABT_PLATFORM}.tar.gz ]; then - wget \ - https://github.com/WebAssembly/wabt/releases/download/1.0.31/wabt-1.0.31-${WABT_PLATFORM}.tar.gz \ - -P /tmp - fi - - cd /tmp \ - && tar zxf wabt-1.0.31-${WABT_PLATFORM}.tar.gz \ - && mkdir -p ${WORK_DIR}/wabt/out/gcc/Release/ \ - && install wabt-1.0.31/bin/wa* ${WORK_DIR}/wabt/out/gcc/Release/ \ - && cd - - fi - else - echo "download source code and compile and install" - if [ ! -d "wabt" ];then - echo "wabt not exist, clone it from github" - git clone --recursive https://github.com/WebAssembly/wabt - fi - echo "upate wabt" - cd wabt - git pull - git reset --hard origin/main - cd .. - make -C wabt gcc-release -j 4 - fi + setup_wabt ln -sf ${WORK_DIR}/../spec-test-script/all.py . ln -sf ${WORK_DIR}/../spec-test-script/runtest.py . @@ -423,7 +439,7 @@ function spec_test() # multi-module only enable in interp mode if [[ 1 == ${ENABLE_MULTI_MODULE} ]]; then - if [[ $1 == 'classic-interp' || $1 == 'fast-interp' ]]; then + if [[ $1 == 'classic-interp' || $1 == 'fast-interp' || $1 == 'aot' ]]; then ARGS_FOR_SPEC_TEST+="-M " fi fi @@ -502,13 +518,35 @@ function wasi_test() echo "Finish wasi tests" } +function wamr_compiler_test() +{ + if [[ $1 != "aot" ]]; then + echo "WAMR compiler tests only support AOT mode" + exit 1 + fi + + echo "Now start WAMR compiler tests" + setup_wabt + cd ${WORK_DIR}/../wamr-compiler-test-script + ./run_wamr_compiler_tests.sh ${WORK_DIR}/wabt/out/gcc/Release/wat2wasm $WAMRC_CMD $IWASM_CMD \ + | tee -a ${REPORT_DIR}/wamr_compiler_test_report.txt + + ret=${PIPESTATUS[0]} + + if [[ ${ret} -ne 0 ]];then + echo -e "\nWAMR compiler tests FAILED" | tee -a ${REPORT_DIR}/wamr_compiler_test_report.txt + exit 1 + fi + echo -e "\nFinish WAMR compiler tests" | tee -a ${REPORT_DIR}/wamr_compiler_test_report.txt +} + function wasi_certification_test() { echo "Now start wasi certification tests" cd ${WORK_DIR} if [ ! -d "wasi-testsuite" ]; then - echo "wasi not exist, clone it from github" + echo "wasi-testsuite not exist, clone it from github" git clone -b prod/testsuite-all \ --single-branch https://github.com/WebAssembly/wasi-testsuite.git fi @@ -652,6 +690,20 @@ function build_iwasm_with_cfg() echo -e "build iwasm failed" exit 1 fi + + if [[ ${PLATFORM} == "cosmopolitan" ]]; then + # convert from APE to ELF so it can be ran easier + # HACK: link to linux so tests work when platform is detected by uname + cp iwasm.com iwasm \ + && ./iwasm --assimilate \ + && rm -rf ../../linux/build \ + && mkdir ../../linux/build \ + && ln -s ../../cosmopolitan/build/iwasm ../../linux/build/iwasm + if [ "$?" != 0 ];then + echo -e "build iwasm failed (cosmopolitan)" + exit 1 + fi + fi } function build_wamrc() @@ -896,4 +948,4 @@ fi echo -e "Test finish. Reports are under ${REPORT_DIR}" DEBUG set +xv pipefail echo "TEST SUCCESSFUL" -exit 0 +exit 0 \ No newline at end of file diff --git a/tests/wamr-test-suites/wamr-compiler-test-script/run_wamr_compiler_tests.sh b/tests/wamr-test-suites/wamr-compiler-test-script/run_wamr_compiler_tests.sh new file mode 100755 index 000000000..19c8030d0 --- /dev/null +++ b/tests/wamr-test-suites/wamr-compiler-test-script/run_wamr_compiler_tests.sh @@ -0,0 +1,22 @@ +#!/bin/bash + +# Copyright (C) 2023 Amazon Inc. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +set -e + +WAT2WASM_CMD=$1 +WAMRC_CMD=$2 +IWASM_CMD=$3 + +for wat_file in ../../wamr-compiler/*.wat; do + wasm_file="${wat_file%.wat}.wasm" + aot_file="${wat_file%.wat}.aot" + + echo "Compiling $wat_file to $wasm_file" + $WAT2WASM_CMD "$wat_file" -o "$wasm_file" + echo "Compiling $wasm_file to $aot_file" + $WAMRC_CMD -o $aot_file $wasm_file + echo "Testing $aot_file" + $IWASM_CMD "$aot_file" +done diff --git a/tests/wamr-test-suites/wasi-test-script/pipe.py b/tests/wamr-test-suites/wasi-test-script/pipe.py new file mode 100644 index 000000000..e37408717 --- /dev/null +++ b/tests/wamr-test-suites/wasi-test-script/pipe.py @@ -0,0 +1,19 @@ +#! /usr/bin/env python3 + +# Copyright (C) 2023 YAMAMOTO Takashi +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +# This is a copy of https://github.com/yamt/toywasm/blob/master/test/pipe.py + +# keep stdout open until the peer closes it + +import sys +import select + +p = select.poll() +p.register(sys.stdout, select.POLLHUP) +# http://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=57369 +while True: + l = p.poll(1) + if l: + break diff --git a/tests/wamr-test-suites/wasi-test-script/run_wasi_tests.sh b/tests/wamr-test-suites/wasi-test-script/run_wasi_tests.sh index 37607859b..b8e3ddfec 100755 --- a/tests/wamr-test-suites/wasi-test-script/run_wasi_tests.sh +++ b/tests/wamr-test-suites/wasi-test-script/run_wasi_tests.sh @@ -5,6 +5,8 @@ # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # +THIS_DIR=$(cd $(dirname $0) && pwd -P) + readonly MODE=$1 readonly TARGET=$2 @@ -18,6 +20,7 @@ readonly IWASM_CMD="${WORK_DIR}/../../../../product-mini/platforms/${PLATFORM}/b readonly IWASM_CMD_STRESS="${IWASM_CMD} --max-threads=12" readonly WAMRC_CMD="${WORK_DIR}/../../../../wamr-compiler/build/wamrc" readonly C_TESTS="tests/c/testsuite/" +readonly RUST_TESTS="tests/rust/testsuite/" readonly ASSEMBLYSCRIPT_TESTS="tests/assemblyscript/testsuite/" readonly THREAD_PROPOSAL_TESTS="tests/proposals/wasi-threads/" readonly THREAD_INTERNAL_TESTS="${WAMR_DIR}/core/iwasm/libraries/lib-wasi-threads/test/" @@ -49,8 +52,8 @@ run_aot_tests () { expected=$(jq .exit_code ${test_json}) fi - ${iwasm} $test_aot - ret=${PIPESTATUS[0]} + python3 ${THIS_DIR}/pipe.py | ${iwasm} $test_aot + ret=${PIPESTATUS[1]} echo "expected=$expected, actual=$ret" if [[ $expected != "" ]] && [[ $expected != $ret ]];then @@ -63,16 +66,18 @@ if [[ $MODE != "aot" ]];then python3 -m venv wasi-env && source wasi-env/bin/activate python3 -m pip install -r test-runner/requirements.txt - TEST_RUNTIME_EXE="${IWASM_CMD}" python3 test-runner/wasi_test_runner.py \ + export TEST_RUNTIME_EXE="${IWASM_CMD}" + python3 ${THIS_DIR}/pipe.py | python3 test-runner/wasi_test_runner.py \ -r adapters/wasm-micro-runtime.py \ -t \ ${C_TESTS} \ + ${RUST_TESTS} \ ${ASSEMBLYSCRIPT_TESTS} \ ${THREAD_PROPOSAL_TESTS} \ ${THREAD_INTERNAL_TESTS} \ ${LIB_SOCKET_TESTS} \ - ret=${PIPESTATUS[0]} + ret=${PIPESTATUS[1]} TEST_RUNTIME_EXE="${IWASM_CMD_STRESS}" python3 test-runner/wasi_test_runner.py \ -r adapters/wasm-micro-runtime.py \ @@ -100,4 +105,4 @@ else done fi -exit ${exit_code} \ No newline at end of file +exit ${exit_code}