From 0fdd49ea318f8cc52a4d910a5f9fa3d9fc2051d8 Mon Sep 17 00:00:00 2001 From: wenyongh Date: Tue, 10 Mar 2020 19:54:44 +0800 Subject: [PATCH] Re-org memory allocation interfaces, add --stack-size and --heap-size option (#193) --- README.md | 2 +- .../app-native-shared/attr_container.c | 4 + .../app-native-shared/bi-inc/attr_container.h | 4 +- .../app-native-shared/bi-inc/shared_utils.h | 2 + .../app-native-shared/restful_utils.c | 24 +- core/app-framework/base/app/bh_platform.c | 2 +- core/app-framework/base/app/bh_platform.h | 10 +- .../app-framework/base/native/timer_wrapper.c | 4 +- .../connection/native/linux/connection_mgr.c | 20 +- .../sensor/native/runtime_sensor.c | 24 +- .../wgl/native/wgl_native_utils.c | 6 +- .../wgl/native/wgl_obj_wrapper.c | 8 +- core/app-mgr/app-manager/app_manager.c | 1 - core/app-mgr/app-manager/app_manager.h | 3 + core/app-mgr/app-manager/app_manager_host.c | 9 +- core/app-mgr/app-manager/ble_msg.c | 8 +- core/app-mgr/app-manager/event.c | 9 +- core/app-mgr/app-manager/message.c | 3 +- core/app-mgr/app-manager/module_jeff.c | 80 +-- core/app-mgr/app-manager/module_utils.c | 5 +- core/app-mgr/app-manager/module_wasm_app.c | 46 +- .../platform/zephyr/app_mgr_zephyr.c | 5 +- core/app-mgr/app-manager/resource_reg.c | 8 +- core/app-mgr/app-manager/watchdog.c | 2 - core/iwasm/aot/aot_loader.c | 99 ++- core/iwasm/aot/aot_runtime.c | 26 +- core/iwasm/common/iwasm_common.cmake | 3 + core/iwasm/common/wasm_exec_env.c | 11 +- .../common/wasm_memory.c} | 175 ++--- core/iwasm/common/wasm_memory.h | 28 + core/iwasm/common/wasm_native.c | 4 +- core/iwasm/common/wasm_runtime_common.c | 91 ++- core/iwasm/common/wasm_runtime_common.h | 9 +- core/iwasm/compilation/aot.c | 53 +- core/iwasm/compilation/aot_compiler.c | 8 +- core/iwasm/compilation/aot_compiler.h | 15 +- core/iwasm/compilation/aot_emit_aot_file.c | 28 +- core/iwasm/compilation/aot_emit_control.c | 7 +- core/iwasm/compilation/aot_emit_function.c | 16 +- core/iwasm/compilation/aot_emit_numberic.c | 8 +- core/iwasm/compilation/aot_emit_parametric.c | 2 +- core/iwasm/compilation/aot_llvm.c | 35 +- core/iwasm/include/bh_memory.h | 99 --- core/iwasm/include/wasm_export.h | 75 ++- core/iwasm/interpreter/wasm_interp.c | 5 +- core/iwasm/interpreter/wasm_interp_fast.c | 1 - core/iwasm/interpreter/wasm_loader.c | 125 ++-- core/iwasm/interpreter/wasm_runtime.c | 50 +- .../libraries/libc-wasi/libc_wasi_wrapper.c | 12 +- .../sandboxed-system-primitives/src/posix.c | 95 ++- core/shared/include/bh_common.h | 15 +- core/shared/include/bh_memory.h | 111 ---- core/shared/include/bh_queue.h | 4 +- core/shared/include/bni.h | 225 ------- core/shared/include/jeff_export.h | 604 ------------------ core/shared/mem-alloc/ems/ems_gc_internal.h | 1 - core/shared/mem-alloc/mem_alloc.cmake | 3 +- core/shared/platform/CMakeLists.txt | 20 - core/shared/platform/Makefile | 4 - core/shared/platform/alios/bh_platform.c | 22 +- core/shared/platform/alios/bh_platform.h | 13 +- core/shared/platform/alios/bh_thread.c | 7 +- core/shared/platform/android/bh_platform.c | 22 +- core/shared/platform/android/bh_platform.h | 21 +- core/shared/platform/android/bh_thread.c | 9 +- core/shared/platform/darwin/bh_platform.c | 22 +- core/shared/platform/darwin/bh_platform.h | 20 +- core/shared/platform/darwin/bh_thread.c | 9 +- core/shared/platform/include/bh_config.h | 33 + core/shared/platform/linux-sgx/bh_platform.c | 18 + core/shared/platform/linux-sgx/bh_platform.h | 19 +- core/shared/platform/linux-sgx/bh_thread.c | 1 - core/shared/platform/linux/bh_platform.c | 22 +- core/shared/platform/linux/bh_platform.h | 14 +- core/shared/platform/linux/bh_thread.c | 9 +- core/shared/platform/vxworks/bh_platform.c | 22 +- core/shared/platform/vxworks/bh_platform.h | 16 +- core/shared/platform/vxworks/bh_thread.c | 9 +- core/shared/platform/zephyr/Makefile | 4 - core/shared/platform/zephyr/bh_platform.c | 22 +- core/shared/platform/zephyr/bh_platform.h | 15 +- core/shared/platform/zephyr/bh_thread.c | 27 +- core/shared/utils/bh_definition.c | 16 +- core/shared/utils/bh_hashmap.c | 13 +- core/shared/utils/bh_queue.c | 3 +- core/shared/utils/bh_vector.c | 7 +- core/shared/utils/runtime_timer.c | 16 +- doc/embed_wamr.md | 58 +- product-mini/platforms/alios-things/aos.mk | 5 +- .../platforms/alios-things/src/main.c | 35 +- product-mini/platforms/android/wasm-jni.cpp | 45 +- product-mini/platforms/darwin/main.c | 64 +- .../enclave-sample/Enclave/Enclave.cpp | 30 +- product-mini/platforms/linux/main.c | 35 +- product-mini/platforms/vxworks/main.c | 64 +- .../platforms/zephyr/simple/src/main.c | 28 +- samples/gui/lv_config/lv_conf.h | 6 +- .../src/platform/linux/iwasm_main.c | 21 +- .../src/platform/zephyr/iwasm_main.c | 21 +- .../src/platform/zephyr/main.c | 1 - .../zephyr-build/CMakeLists.txt | 4 +- .../src/platform/linux/iwasm_main.c | 33 +- .../src/platform/zephyr/iwasm_main.c | 34 +- .../src/platform/zephyr/main.c | 3 +- .../zephyr-build/CMakeLists.txt | 3 + samples/simple/src/iwasm_main.c | 51 +- test-tools/host-tool/CMakeLists.txt | 1 - test-tools/host-tool/src/host_tool_utils.c | 4 + wamr-compiler/main.c | 52 +- wamr-sdk/runtime/CMakeLists.txt | 4 + 110 files changed, 1264 insertions(+), 2125 deletions(-) rename core/{shared/mem-alloc/bh_memory.c => iwasm/common/wasm_memory.c} (64%) create mode 100644 core/iwasm/common/wasm_memory.h delete mode 100644 core/iwasm/include/bh_memory.h delete mode 100644 core/shared/include/bh_memory.h delete mode 100644 core/shared/include/bni.h delete mode 100644 core/shared/include/jeff_export.h delete mode 100755 core/shared/platform/CMakeLists.txt delete mode 100644 core/shared/platform/Makefile delete mode 100644 core/shared/platform/zephyr/Makefile diff --git a/README.md b/README.md index 5b7fbcbe0..faf50a57e 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ cd wamr-compiler mkdir build && cd build cmake .. make -ln -s ./wamrc /usr/bin/wamrc +ln -s {current path}/wamrc /usr/bin/wamrc ``` ### Build the mini product diff --git a/core/app-framework/app-native-shared/attr_container.c b/core/app-framework/app-native-shared/attr_container.c index 5145ac70b..478bef0e3 100644 --- a/core/app-framework/app-native-shared/attr_container.c +++ b/core/app-framework/app-native-shared/attr_container.c @@ -16,10 +16,14 @@ typedef union jvalue { double d; } jvalue; +#ifndef bh_memcpy_s +int b_memcpy_s(void * s1, unsigned int s1max, + const void * s2, unsigned int n); #define bh_memcpy_s(dest, dlen, src, slen) do { \ int _ret = slen == 0 ? 0 : b_memcpy_s (dest, dlen, src, slen); \ (void)_ret; \ } while (0) +#endif static inline int16_t get_int16(const char *buf) { diff --git a/core/app-framework/app-native-shared/bi-inc/attr_container.h b/core/app-framework/app-native-shared/bi-inc/attr_container.h index 52e0ebcc0..d8fc08e4b 100644 --- a/core/app-framework/app-native-shared/bi-inc/attr_container.h +++ b/core/app-framework/app-native-shared/bi-inc/attr_container.h @@ -406,11 +406,11 @@ void attr_container_dump(const attr_container_t *attr_cont); #ifndef attr_container_malloc -#define attr_container_malloc wa_malloc +#define attr_container_malloc WA_MALLOC #endif #ifndef attr_container_free -#define attr_container_free wa_free +#define attr_container_free WA_FREE #endif #ifndef attr_container_printf diff --git a/core/app-framework/app-native-shared/bi-inc/shared_utils.h b/core/app-framework/app-native-shared/bi-inc/shared_utils.h index 2ce84a1f0..3154b4b5c 100644 --- a/core/app-framework/app-native-shared/bi-inc/shared_utils.h +++ b/core/app-framework/app-native-shared/bi-inc/shared_utils.h @@ -145,6 +145,8 @@ unpack_response(char * packet, int size, response_t * response); void free_req_resp_packet(char * packet); +char * +wa_strdup(const char *str); #ifdef __cplusplus diff --git a/core/app-framework/app-native-shared/restful_utils.c b/core/app-framework/app-native-shared/restful_utils.c index 5edc47081..4907df017 100644 --- a/core/app-framework/app-native-shared/restful_utils.c +++ b/core/app-framework/app-native-shared/restful_utils.c @@ -43,7 +43,7 @@ char * pack_request(request_t *request, int * size) { int url_len = strlen(request->url) + 1; int len = REQUEST_PACKET_FIX_PART_LEN + url_len + request->payload_len; - char * packet = (char*) wa_malloc(len); + char * packet = (char*) WA_MALLOC(len); if (packet == NULL) return NULL; @@ -65,7 +65,7 @@ char * pack_request(request_t *request, int * size) void free_req_resp_packet(char * packet) { - wa_free(packet); + WA_FREE(packet); } request_t * unpack_request(char * packet, int size, request_t * request) @@ -108,7 +108,7 @@ request_t * unpack_request(char * packet, int size, request_t * request) char * pack_response(response_t *response, int * size) { int len = RESPONSE_PACKET_FIX_PART_LEN + response->payload_len; - char * packet = (char*) wa_malloc(len); + char * packet = (char*) WA_MALLOC(len); if (packet == NULL) return NULL; @@ -152,7 +152,7 @@ response_t * unpack_response(char * packet, int size, response_t * response) request_t *clone_request(request_t *request) { /* deep clone */ - request_t *req = (request_t *) wa_malloc(sizeof(request_t)); + request_t *req = (request_t *) WA_MALLOC(sizeof(request_t)); if (req == NULL) return NULL; @@ -169,7 +169,7 @@ request_t *clone_request(request_t *request) req->payload_len = request->payload_len; if (request->payload_len) { - req->payload = (char *) wa_malloc(request->payload_len); + req->payload = (char *) WA_MALLOC(request->payload_len); if (!req->payload) goto fail; memcpy(req->payload, request->payload, request->payload_len); @@ -188,24 +188,24 @@ fail: void request_cleaner(request_t *request) { if (request->url != NULL) - wa_free(request->url); + WA_FREE(request->url); if (request->payload != NULL && request->payload_len > 0) - wa_free(request->payload); + WA_FREE(request->payload); - wa_free(request); + WA_FREE(request); } void response_cleaner(response_t * response) { if (response->payload != NULL && response->payload_len > 0) - wa_free(response->payload); + WA_FREE(response->payload); - wa_free(response); + WA_FREE(response); } response_t * clone_response(response_t * response) { - response_t *clone = (response_t *) wa_malloc(sizeof(response_t)); + response_t *clone = (response_t *) WA_MALLOC(sizeof(response_t)); if (clone == NULL) return NULL; @@ -216,7 +216,7 @@ response_t * clone_response(response_t * response) clone->reciever = response->reciever; clone->payload_len = response->payload_len; if (clone->payload_len) { - clone->payload = (char *) wa_malloc(response->payload_len); + clone->payload = (char *) WA_MALLOC(response->payload_len); if (!clone->payload) goto fail; memcpy(clone->payload, response->payload, response->payload_len); diff --git a/core/app-framework/base/app/bh_platform.c b/core/app-framework/base/app/bh_platform.c index 37b828e0e..e539e8b0b 100644 --- a/core/app-framework/base/app/bh_platform.c +++ b/core/app-framework/base/app/bh_platform.c @@ -75,7 +75,7 @@ uint16 ntohs(uint16 value) char *wa_strdup(const char *s) { char *s1 = NULL; - if (s && (s1 = wa_malloc(strlen(s) + 1))) + if (s && (s1 = WA_MALLOC(strlen(s) + 1))) memcpy(s1, s, strlen(s) + 1); return s1; } diff --git a/core/app-framework/base/app/bh_platform.h b/core/app-framework/base/app/bh_platform.h index d44522c02..91b43bb25 100755 --- a/core/app-framework/base/app/bh_platform.h +++ b/core/app-framework/base/app/bh_platform.h @@ -25,14 +25,14 @@ typedef int int32; #define inline __inline #endif -// all wasm-app<->native shared source files should use wa_malloc/wa_free. +// all wasm-app<->native shared source files should use WA_MALLOC/WA_FREE. // they will be mapped to different implementations in each side -#ifndef wa_malloc -#define wa_malloc malloc +#ifndef WA_MALLOC +#define WA_MALLOC malloc #endif -#ifndef wa_free -#define wa_free free +#ifndef WA_FREE +#define WA_FREE free #endif char *wa_strdup(const char *s); diff --git a/core/app-framework/base/native/timer_wrapper.c b/core/app-framework/base/native/timer_wrapper.c index ba5db9e81..44887df9e 100644 --- a/core/app-framework/base/native/timer_wrapper.c +++ b/core/app-framework/base/native/timer_wrapper.c @@ -107,7 +107,7 @@ timer_ctx_t create_wasm_timer_ctx(unsigned int module_id, int prealloc_num) return NULL; timer_ctx_node_t * node = (timer_ctx_node_t*) - bh_malloc(sizeof(timer_ctx_node_t)); + wasm_runtime_malloc(sizeof(timer_ctx_node_t)); if (node == NULL) { destroy_timer_ctx(ctx); return NULL; @@ -131,7 +131,7 @@ void destroy_module_timer_ctx(unsigned int module_id) if (timer_ctx_get_owner(elem->timer_ctx) == module_id) { bh_list_remove(&g_timer_ctx_list, elem); destroy_timer_ctx(elem->timer_ctx); - bh_free(elem); + wasm_runtime_free(elem); break; } diff --git a/core/app-framework/connection/native/linux/connection_mgr.c b/core/app-framework/connection/native/linux/connection_mgr.c index cd8431a35..fe4ef6168 100644 --- a/core/app-framework/connection/native/linux/connection_mgr.c +++ b/core/app-framework/connection/native/linux/connection_mgr.c @@ -115,8 +115,8 @@ static void add_connection(sys_connection_t *conn) #define FREE_CONNECTION(conn) do { \ if (conn->arg) \ - bh_free(conn->arg); \ - bh_free(conn); \ + wasm_runtime_free(conn->arg); \ + wasm_runtime_free(conn); \ } while (0) static int get_app_conns_num(uint32 module_id) @@ -223,7 +223,7 @@ static uint32 _conn_open(wasm_module_inst_t module_inst, if (get_app_conns_num(module_id) >= MAX_CONNECTION_PER_APP) return -1; - conn = (sys_connection_t *)bh_malloc(sizeof(*conn)); + conn = (sys_connection_t *)wasm_runtime_malloc(sizeof(*conn)); if (conn == NULL) return -1; @@ -296,7 +296,7 @@ static uint32 _conn_open(wasm_module_inst_t module_inst, fail: find_connection(conn->handle, true); - bh_free(conn); + wasm_runtime_free(conn); return -1; } @@ -356,7 +356,7 @@ static bool _conn_config(uint32 handle, attr_container_t *cfg) port = attr_container_get_as_uint16(cfg, "port"); if (conn->arg == NULL) { - addr = (struct sockaddr_in *)bh_malloc(sizeof(*addr)); + addr = (struct sockaddr_in *)wasm_runtime_malloc(sizeof(*addr)); if (addr == NULL) return false; @@ -390,8 +390,8 @@ typedef struct connection_event { static void connection_event_cleaner(connection_event_t *conn_event) { if (conn_event->data != NULL) - bh_free(conn_event->data); - bh_free(conn_event); + wasm_runtime_free(conn_event->data); + wasm_runtime_free(conn_event); } static void post_msg_to_module(sys_connection_t *conn, @@ -406,14 +406,14 @@ static void post_msg_to_module(sys_connection_t *conn, if (module == NULL) return; - conn_data_event = (connection_event_t *)bh_malloc(sizeof(*conn_data_event)); + conn_data_event = (connection_event_t *)wasm_runtime_malloc(sizeof(*conn_data_event)); if (conn_data_event == NULL) return; if (len > 0) { - data_copy = (char *)bh_malloc(len); + data_copy = (char *)wasm_runtime_malloc(len); if (data_copy == NULL) { - bh_free(conn_data_event); + wasm_runtime_free(conn_data_event); return; } bh_memcpy_s(data_copy, len, data, len); diff --git a/core/app-framework/sensor/native/runtime_sensor.c b/core/app-framework/sensor/native/runtime_sensor.c index 63a03983d..ac7eed9dd 100644 --- a/core/app-framework/sensor/native/runtime_sensor.c +++ b/core/app-framework/sensor/native/runtime_sensor.c @@ -32,10 +32,10 @@ sensor_event_cleaner(sensor_event_data_t *sensor_event) if (sensor_event->data_fmt == FMT_ATTR_CONTAINER) attr_container_destroy(sensor_event->data); else - bh_free(sensor_event->data); + wasm_runtime_free(sensor_event->data); } - bh_free(sensor_event); + wasm_runtime_free(sensor_event); } static void @@ -56,7 +56,7 @@ wasm_sensor_callback(void *client, uint32 sensor_id, void *user_data) return; sensor_data_len = attr_container_get_serialize_length(sensor_data); - sensor_data_clone = (attr_container_t *)bh_malloc(sensor_data_len); + sensor_data_clone = (attr_container_t *)wasm_runtime_malloc(sensor_data_len); if (sensor_data_clone == NULL) return; @@ -64,9 +64,9 @@ wasm_sensor_callback(void *client, uint32 sensor_id, void *user_data) bh_memcpy_s(sensor_data_clone, sensor_data_len, sensor_data, sensor_data_len); - sensor_event = (sensor_event_data_t *)bh_malloc(sizeof(*sensor_event)); + sensor_event = (sensor_event_data_t *)wasm_runtime_malloc(sizeof(*sensor_event)); if (sensor_event == NULL) { - bh_free(sensor_data_clone); + wasm_runtime_free(sensor_data_clone); return; } @@ -158,7 +158,7 @@ wasm_sensor_open(wasm_exec_env_t exec_env, return -1; } - sensor_client_t * client = (sensor_client_t*) bh_malloc( + sensor_client_t * client = (sensor_client_t*) wasm_runtime_malloc( sizeof(sensor_client_t)); if (client == NULL) { vm_mutex_unlock(&s->lock); @@ -220,7 +220,7 @@ wasm_sensor_close(wasm_exec_env_t exec_env, uint32 sensor) vm_mutex_lock(&s->lock); if ((c = find_sensor_client(s, client_id, true)) != NULL) - bh_free(c); + wasm_runtime_free(c); vm_mutex_unlock(&s->lock); refresh_read_interval(s); @@ -272,7 +272,7 @@ sensor_obj_t add_sys_sensor(char * name, char * description, int instance, uint32 default_interval, void * read_func, void * config_func) { - sys_sensor_t * s = (sys_sensor_t *) bh_malloc(sizeof(sys_sensor_t)); + sys_sensor_t * s = (sys_sensor_t *) wasm_runtime_malloc(sizeof(sys_sensor_t)); if (s == NULL) return NULL; @@ -282,15 +282,15 @@ add_sys_sensor(char * name, char * description, int instance, s->default_interval = default_interval; if (!s->name) { - bh_free(s); + wasm_runtime_free(s); return NULL; } if (description) { s->description = bh_strdup(description); if (!s->description) { - bh_free(s->name); - bh_free(s); + wasm_runtime_free(s->name); + wasm_runtime_free(s); return NULL; } } @@ -414,7 +414,7 @@ void sensor_cleanup_callback(uint32 module_id) sensor_client_t *c; vm_mutex_lock(&s->lock); if ((c = find_sensor_client(s, module_id, true)) != NULL) { - bh_free(c); + wasm_runtime_free(c); } vm_mutex_unlock(&s->lock); s = s->next; diff --git a/core/app-framework/wgl/native/wgl_native_utils.c b/core/app-framework/wgl/native/wgl_native_utils.c index 353329802..005ab3fe7 100644 --- a/core/app-framework/wgl/native/wgl_native_utils.c +++ b/core/app-framework/wgl/native/wgl_native_utils.c @@ -124,7 +124,7 @@ void wgl_native_func_call(wasm_module_inst_t module_inst, argc1++; /* module_inst */ argc1 += func_def->arg_num; if (argc1 > 16) { - argv_copy = (intptr_t *)bh_malloc(func_def->arg_num * + argv_copy = (intptr_t *)wasm_runtime_malloc(func_def->arg_num * sizeof(intptr_t)); if (argv_copy == NULL) return; @@ -190,14 +190,14 @@ void wgl_native_func_call(wasm_module_inst_t module_inst, } if (argv_copy != argv_copy_buf) - bh_free(argv_copy); + wasm_runtime_free(argv_copy); /* success return */ return; fail: if (argv_copy != argv_copy_buf) - bh_free(argv_copy); + wasm_runtime_free(argv_copy); return; } diff --git a/core/app-framework/wgl/native/wgl_obj_wrapper.c b/core/app-framework/wgl/native/wgl_obj_wrapper.c index 9f2940ff9..31b648c0e 100644 --- a/core/app-framework/wgl/native/wgl_obj_wrapper.c +++ b/core/app-framework/wgl/native/wgl_obj_wrapper.c @@ -93,7 +93,7 @@ static void cleanup_object_list(uint32 module_id) found = true; lv_obj_del(elem->obj); bh_list_remove(&g_object_list, elem); - bh_free(elem); + wasm_runtime_free(elem); elem = next; } else { elem = (object_node_t *)bh_list_elem_next(elem); @@ -150,7 +150,7 @@ bool wgl_native_add_object(lv_obj_t *obj, uint32 module_id, uint32 *obj_id) { object_node_t *node; - node = (object_node_t *) bh_malloc(sizeof(object_node_t)); + node = (object_node_t *) wasm_runtime_malloc(sizeof(object_node_t)); if (node == NULL) return false; @@ -200,7 +200,7 @@ static void _obj_del_recursive(lv_obj_t *obj) while (elem) { if (obj == elem->obj) { bh_list_remove(&g_object_list, elem); - bh_free(elem); + wasm_runtime_free(elem); vm_mutex_unlock(&g_object_list_mutex); return; } @@ -237,7 +237,7 @@ static void post_widget_msg_to_module(object_node_t *object_node, lv_event_t eve if (module == NULL) return; - object_event = (object_event_t *)bh_malloc(sizeof(*object_event)); + object_event = (object_event_t *)wasm_runtime_malloc(sizeof(*object_event)); if (object_event == NULL) return; diff --git a/core/app-mgr/app-manager/app_manager.c b/core/app-mgr/app-manager/app_manager.c index 7c8c8577a..ca41d6ffd 100644 --- a/core/app-mgr/app-manager/app_manager.c +++ b/core/app-mgr/app-manager/app_manager.c @@ -6,7 +6,6 @@ #include "app_manager.h" #include "app_manager_host.h" #include "bh_queue.h" -#include "bh_memory.h" #include "bh_thread.h" #include "bi-inc/attr_container.h" #include "event.h" diff --git a/core/app-mgr/app-manager/app_manager.h b/core/app-mgr/app-manager/app_manager.h index 188c685d1..c41002f13 100644 --- a/core/app-mgr/app-manager/app_manager.h +++ b/core/app-mgr/app-manager/app_manager.h @@ -18,6 +18,9 @@ extern "C" { #endif +#define APP_MGR_MALLOC wasm_runtime_malloc +#define APP_MGR_FREE wasm_runtime_free + /* bh_printf is defined in each platform */ #define app_manager_printf bh_printf diff --git a/core/app-mgr/app-manager/app_manager_host.c b/core/app-mgr/app-manager/app_manager_host.c index efd86e486..db50cb1b4 100644 --- a/core/app-mgr/app-manager/app_manager_host.c +++ b/core/app-mgr/app-manager/app_manager_host.c @@ -9,7 +9,6 @@ #include "app_manager.h" #include "app_manager_export.h" #include "coap_ext.h" -#include "bh_memory.h" #include "bh_thread.h" /* host communication interface */ @@ -66,7 +65,7 @@ static int on_imrt_link_byte_arrive(unsigned char ch, recv_context_t *ctx) ctx->message.payload_size = 0; if (ctx->message.payload) { - bh_free(ctx->message.payload); + APP_MGR_FREE(ctx->message.payload); ctx->message.payload = NULL; } @@ -117,7 +116,7 @@ static int on_imrt_link_byte_arrive(unsigned char ch, recv_context_t *ctx) app_manager_printf("##On byte arrive: payload_size: %d\n", ctx->message.payload_size); if (ctx->message.payload) { - bh_free(ctx->message.payload); + APP_MGR_FREE(ctx->message.payload); ctx->message.payload = NULL; } @@ -137,7 +136,7 @@ static int on_imrt_link_byte_arrive(unsigned char ch, recv_context_t *ctx) if (ctx->message.message_type != INSTALL_WASM_APP) { ctx->message.payload = - (char *) bh_malloc(ctx->message.payload_size); + (char *) APP_MGR_MALLOC(ctx->message.payload_size); if (!ctx->message.payload) { ctx->phase = Phase_Non_Start; return 0; @@ -222,7 +221,7 @@ int aee_host_msg_callback(void *msg, uint16_t msg_len) printf("unexpected host msg type: %d\n", msg_type); } - bh_free(recv_ctx.message.payload); + APP_MGR_FREE(recv_ctx.message.payload); recv_ctx.message.payload = NULL; recv_ctx.message.payload_size = 0; } diff --git a/core/app-mgr/app-manager/ble_msg.c b/core/app-mgr/app-manager/ble_msg.c index 3794fa56b..179eb78ba 100644 --- a/core/app-mgr/app-manager/ble_msg.c +++ b/core/app-mgr/app-manager/ble_msg.c @@ -75,16 +75,16 @@ app_instance_free_ble_msg(char *msg) dev_info = (ble_device_info *) ble_msg->payload; if (dev_info->scan_response != NULL) - bh_free(dev_info->scan_response); + APP_MGR_FREE(dev_info->scan_response); if (dev_info->private_data != NULL) - bh_free(dev_info->private_data); + APP_MGR_FREE(dev_info->private_data); if (dev_info->adv_data != NULL) - bh_free(dev_info->adv_data); + APP_MGR_FREE(dev_info->adv_data); if (dev_info != NULL) - bh_free(dev_info); + APP_MGR_FREE(dev_info); } static void diff --git a/core/app-mgr/app-manager/event.c b/core/app-mgr/app-manager/event.c index 67def1c78..f2c49dfd0 100644 --- a/core/app-mgr/app-manager/event.c +++ b/core/app-mgr/app-manager/event.c @@ -8,7 +8,6 @@ #include "event.h" #include "app_manager.h" -#include "bh_memory.h" #include "coap_ext.h" typedef struct _subscribe { @@ -38,7 +37,7 @@ static bool find_subscriber(event_reg_t * reg, uint32 id, bool remove_found) else reg->subscribers = next; - bh_free(c); + APP_MGR_FREE(c); } return true; @@ -77,7 +76,7 @@ bool am_register_event(const char *url, uint32_t reg_client) if (current == NULL) { if (NULL - == (current = (event_reg_t *) bh_malloc( + == (current = (event_reg_t *) APP_MGR_MALLOC( offsetof(event_reg_t, url) + strlen(url) + 1))) { app_manager_printf("am_register_event: malloc fail\n"); return false; @@ -92,7 +91,7 @@ bool am_register_event(const char *url, uint32_t reg_client) if (find_subscriber(current, reg_client, false)) { return true; } else { - subscribe_t * s = (subscribe_t*) bh_malloc(sizeof(subscribe_t)); + subscribe_t * s = (subscribe_t*) APP_MGR_MALLOC(sizeof(subscribe_t)); if (s == NULL) return false; @@ -128,7 +127,7 @@ bool am_unregister_event(const char *url, uint32_t reg_client) pre->next = next; else g_events = next; - bh_free(current); + APP_MGR_FREE(current); current = next; continue; } diff --git a/core/app-mgr/app-manager/message.c b/core/app-mgr/app-manager/message.c index 13ee4c04f..2aed14757 100644 --- a/core/app-mgr/app-manager/message.c +++ b/core/app-mgr/app-manager/message.c @@ -7,7 +7,6 @@ #include "app_manager_host.h" #include "event.h" #include "bi-inc/attr_container.h" -#include "bh_memory.h" #include "coap_ext.h" #if 0 @@ -21,7 +20,7 @@ bool send_coap_packet_to_host(coap_packet_t * packet) return false; app_manager_host_send_msg(buf, size); - bh_free(buf); + APP_MGR_FREE(buf); return true; } diff --git a/core/app-mgr/app-manager/module_jeff.c b/core/app-mgr/app-manager/module_jeff.c index af2fbaef0..25ded4be0 100644 --- a/core/app-mgr/app-manager/module_jeff.c +++ b/core/app-mgr/app-manager/module_jeff.c @@ -125,7 +125,7 @@ get_class_qname(const JeffString *pname, const JeffString *cname) { unsigned int length = pname->length ? pname->length + 2 + cname->length : cname->length + 1; - char *buf = bh_malloc(length), *p; + char *buf = APP_MGR_MALLOC(length), *p; if (!buf) return NULL; @@ -166,7 +166,7 @@ send_exception_event_to_host(const char *applet_name, const char *exc_name) } url_len = strlen("/exception/") + strlen(applet_name); - url = bh_malloc(url_len + 1); + url = APP_MGR_MALLOC(url_len + 1); if (!url) { app_manager_printf("Send exception to host fail: allocate memory"); goto fail; @@ -182,7 +182,7 @@ send_exception_event_to_host(const char *applet_name, const char *exc_name) app_send_request_msg_to_host(&msg); - bh_free(url); + APP_MGR_FREE(url); fail: attr_container_destroy(payload); @@ -208,7 +208,7 @@ check_exception() /* Send exception event to host */ if (qname_buf) { send_exception_event_to_host(app_manager_get_module_name(Module_Jeff), qname_buf); - bh_free(qname_buf); + APP_MGR_FREE(qname_buf); } /* Uninstall the applet */ @@ -455,17 +455,17 @@ check_exception() fail: if (dev_info->scan_response != NULL) { - bh_free(dev_info->scan_response); + APP_MGR_FREE(dev_info->scan_response); } if (dev_info->private_data != NULL) { - bh_free(dev_info->private_data); + APP_MGR_FREE(dev_info->private_data); } if (dev_info->adv_data != NULL) { - bh_free(dev_info->adv_data); + APP_MGR_FREE(dev_info->adv_data); } if (dev_info != NULL) { - bh_free(dev_info); + APP_MGR_FREE(dev_info); } } @@ -479,16 +479,16 @@ check_exception() dev_info = (ble_device_info *) ble_msg->payload; if (dev_info->scan_response != NULL) - bh_free(dev_info->scan_response); + APP_MGR_FREE(dev_info->scan_response); if (dev_info->private_data != NULL) - bh_free(dev_info->private_data); + APP_MGR_FREE(dev_info->private_data); if (dev_info->adv_data != NULL) - bh_free(dev_info->adv_data); + APP_MGR_FREE(dev_info->adv_data); if (dev_info != NULL) - bh_free(dev_info); + APP_MGR_FREE(dev_info); } static void @@ -500,7 +500,7 @@ check_exception() case APPLET_REQUEST: { bh_request_msg_t *req_msg = (bh_request_msg_t *)msg->payload; - bh_free(req_msg); + APP_MGR_FREE(req_msg); break; } @@ -516,7 +516,7 @@ check_exception() attr_container_t *event = sensor_event->event; attr_container_destroy(event); - bh_free(sensor_event); + APP_MGR_FREE(sensor_event); } break; } @@ -525,7 +525,7 @@ check_exception() { if (msg->payload) { app_instance_free_ble_msg(msg->payload); - bh_free(msg->payload); + APP_MGR_FREE(msg->payload); } break; } @@ -541,7 +541,7 @@ check_exception() } } - bh_free(msg); + APP_MGR_FREE(msg); } static void @@ -609,7 +609,7 @@ check_exception() fail2: jeff_runtime_pop_local_object_ref(1); fail1: - bh_free(req_msg); + APP_MGR_FREE(req_msg); break; } @@ -633,7 +633,7 @@ check_exception() bool ret = attr_container_to_attr_obj(event, &sensor->event); attr_container_destroy(event); - bh_free(sensor_event); + APP_MGR_FREE(sensor_event); if (ret) { /* Call Sensor.callOnSensorEvent() method */ @@ -649,7 +649,7 @@ check_exception() { if (msg->payload) { app_instance_process_ble_msg(msg->payload); - bh_free(msg->payload); + APP_MGR_FREE(msg->payload); } break; } @@ -678,7 +678,7 @@ check_exception() } } - bh_free(msg); + APP_MGR_FREE(msg); } static JeffClassHeaderLinked* @@ -837,7 +837,7 @@ check_exception() /* TODO: convert bpk file to Jeff file */ main_file_len = bpk_file_len; - main_file = bh_malloc(main_file_len); + main_file = APP_MGR_MALLOC(main_file_len); if (!main_file) { SEND_ERR_RESPONSE(msg->mid, "Install Applet failed: allocate memory failed."); return false; @@ -866,7 +866,7 @@ check_exception() /* Create module data */ size = offsetof(module_data, module_name) + strlen(applet_name) + 1; size = align_uint(size, 4); - m_data = bh_malloc(size + sizeof(jeff_applet_data)); + m_data = APP_MGR_MALLOC(size + sizeof(jeff_applet_data)); if (!m_data) { SEND_ERR_RESPONSE(msg->mid, "Install Applet failed: allocate memory failed."); goto fail2; @@ -888,7 +888,7 @@ check_exception() /* Create applet permissions */ applet_perm = attr_container_get_as_string(attr_cont, "perm"); if (applet_perm != NULL) { - applet_data->perms = bh_malloc(strlen(applet_perm) + 1); + applet_data->perms = APP_MGR_MALLOC(strlen(applet_perm) + 1); if (!applet_data->perms) { SEND_ERR_RESPONSE(msg->mid, "Install Applet failed: allocate memory for applet permissions failed."); goto fail3; @@ -993,16 +993,16 @@ check_exception() bh_queue_destroy(m_data->queue, NULL); fail3_1: - bh_free(applet_data->perms); + APP_MGR_FREE(applet_data->perms); fail3: - bh_free(applet_data); + APP_MGR_FREE(applet_data); fail2: jeff_runtime_unload(main_file); fail1: - bh_free(main_file); + APP_MGR_FREE(main_file); return false; } @@ -1014,7 +1014,7 @@ check_exception() /* Unload Jeff main file and free it */ jeff_runtime_unload(applet_data->main_file); - bh_free(applet_data->main_file); + APP_MGR_FREE(applet_data->main_file); /* Destroy queue */ bh_queue_destroy(m_data->queue, app_instance_queue_free_callback); @@ -1027,8 +1027,8 @@ check_exception() /* Remove module data from module data list and free it */ app_manager_del_module_data(m_data); - bh_free(applet_data->perms); - bh_free(m_data); + APP_MGR_FREE(applet_data->perms); + APP_MGR_FREE(m_data); } /* Uninstall Java Applet */ @@ -1476,7 +1476,7 @@ check_exception() } /* Create queue message for tool agent */ - if (!(tool_agent_msg = bh_malloc(sizeof(bh_queue_msg_t)))) { + if (!(tool_agent_msg = APP_MGR_MALLOC(sizeof(bh_queue_msg_t)))) { SEND_ERR_RESPONSE(mid, "Send request to tool agent failed: allocate memory failed"); return false; } @@ -1487,9 +1487,9 @@ check_exception() req_msg_len = sizeof(bh_request_msg_t) + strlen(p) + 1 + attr_cont_len; /* Create request message */ - if (!(req_msg = bh_malloc(req_msg_len))) { + if (!(req_msg = APP_MGR_MALLOC(req_msg_len))) { SEND_ERR_RESPONSE(mid, "Send request to applet failed: allocate memory failed"); - bh_free(tool_agent_msg); + APP_MGR_FREE(tool_agent_msg); return false; } @@ -1511,8 +1511,8 @@ check_exception() tool_agent_msg->payload_size = req_msg_len; tool_agent_msg->payload = (char*)req_msg; if (!bh_queue_send_message(applet_data->tool_agent_queue, tool_agent_msg)) { - bh_free(req_msg); - bh_free(tool_agent_msg); + APP_MGR_FREE(req_msg); + APP_MGR_FREE(tool_agent_msg); SEND_ERR_RESPONSE (mid, "Send request to tool agent failed: send queue msg failed."); return false; @@ -1693,16 +1693,16 @@ check_exception() goto fail; } - bh_free(req_msg); - bh_free(msg); + APP_MGR_FREE(req_msg); + APP_MGR_FREE(msg); return; fail: bh_queue_exit_loop_run(queue); - bh_free(req_msg); + APP_MGR_FREE(req_msg); } - bh_free(msg); + APP_MGR_FREE(msg); } void @@ -1712,10 +1712,10 @@ check_exception() if (msg->message_type == JDWP_REQUEST) { bh_request_msg_t *req_msg = (bh_request_msg_t*)msg->payload; - bh_free(req_msg); + APP_MGR_FREE(req_msg); } - bh_free(msg); + APP_MGR_FREE(msg); } #endif /* BEIHAI_ENABLE_TOOL_AGENT != 0 */ diff --git a/core/app-mgr/app-manager/module_utils.c b/core/app-mgr/app-manager/module_utils.c index a4e52cb45..1f7219c8d 100644 --- a/core/app-mgr/app-manager/module_utils.c +++ b/core/app-mgr/app-manager/module_utils.c @@ -6,7 +6,6 @@ #include "app_manager.h" #include "app_manager_host.h" #include "bh_queue.h" -#include "bh_memory.h" #include "bh_thread.h" #include "bi-inc/attr_container.h" #include "event.h" @@ -32,7 +31,7 @@ void module_data_list_destroy() if (module_data_list) { while (module_data_list) { module_data *p = module_data_list->next; - bh_free(module_data_list); + APP_MGR_FREE(module_data_list); module_data_list = p; } } @@ -197,7 +196,7 @@ void release_module(module_data *m_data) destroy_module_timer_ctx(m_data->id); - bh_free(m_data); + APP_MGR_FREE(m_data); } int check_modules_timer_expiry() diff --git a/core/app-mgr/app-manager/module_wasm_app.c b/core/app-mgr/app-manager/module_wasm_app.c index ecc352ed0..1035a348c 100644 --- a/core/app-mgr/app-manager/module_wasm_app.c +++ b/core/app-mgr/app-manager/module_wasm_app.c @@ -10,7 +10,6 @@ #include "bh_queue.h" #include "bi-inc/attr_container.h" #include "bh_thread.h" -#include "bh_memory.h" #include "coap_ext.h" #include "event.h" #include "watchdog.h" @@ -551,12 +550,7 @@ cleanup_app_resource(module_data *m_data) static bool wasm_app_module_init(void) { - /* Initialize WASM VM*/ - if (!wasm_runtime_init()) { - app_manager_printf("WASM runtime environment initialization failed.\n"); - return false; - } - + /* wasm runtime is already initialized by main func */ return true; } @@ -776,7 +770,7 @@ wasm_app_module_install(request_t * msg) /* Create module data including the wasm_app_data as its internal_data*/ m_data_size = offsetof(module_data, module_name) + strlen(m_name) + 1; m_data_size = align_uint(m_data_size, 4); - m_data = bh_malloc(m_data_size + sizeof(wasm_data)); + m_data = APP_MGR_MALLOC(m_data_size + sizeof(wasm_data)); if (!m_data) { SEND_ERR_RESPONSE(msg->mid, "Install WASM app failed: allocate memory failed."); goto fail; @@ -1096,7 +1090,7 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, recv_ctx.message.request_url_len = ntohs(recv_ctx.message.request_url_len); recv_ctx.message.request_url = - bh_malloc(recv_ctx.message.request_url_len + 1); + APP_MGR_MALLOC(recv_ctx.message.request_url_len + 1); if (NULL == recv_ctx.message.request_url) { app_manager_printf("Allocate memory failed!\n"); goto fail; @@ -1177,7 +1171,7 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, uint8 section_type = ch; if (section_type <= SECTION_TYPE_DATA) { wasm_section_t *new_section; - if (!(new_section = (wasm_section_t *) bh_malloc(sizeof(wasm_section_t)))) { + if (!(new_section = (wasm_section_t *) APP_MGR_MALLOC(sizeof(wasm_section_t)))) { app_manager_printf("Allocate memory failed!\n"); goto fail; } @@ -1226,7 +1220,7 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, if ((byte & 0x80) == 0) { /* leb128 encoded section size parsed done */ - if (!(section->section_body = bh_malloc(section->section_body_size))) { + if (!(section->section_body = APP_MGR_MALLOC(section->section_body_size))) { app_manager_printf("Allocate memory failed!\n"); goto fail; } @@ -1248,7 +1242,7 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, if (recv_ctx.total_received_size == request_total_size) { /* whole wasm app received */ if (module_wasm_app_handle_install_msg(&recv_ctx.message)) { - bh_free(recv_ctx.message.request_url); + APP_MGR_FREE(recv_ctx.message.request_url); recv_ctx.message.request_url = NULL; memset(&recv_ctx, 0, sizeof(recv_ctx)); return true; @@ -1297,7 +1291,7 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, if (aot_file_cur_offset % 4) return true; - if (!(cur_section = (aot_section_t *) bh_malloc(sizeof(aot_section_t)))) { + if (!(cur_section = (aot_section_t *) APP_MGR_MALLOC(sizeof(aot_section_t)))) { app_manager_printf("Allocate memory failed!\n"); goto fail; } @@ -1377,7 +1371,7 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, } else { if (!(section->section_body = - bh_malloc(section->section_body_size))) { + APP_MGR_MALLOC(section->section_body_size))) { app_manager_printf("Allocate memory failed!\n"); goto fail; } @@ -1411,7 +1405,7 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, if (recv_ctx.total_received_size == request_total_size) { /* whole aot file received */ if (module_wasm_app_handle_install_msg(&recv_ctx.message)) { - bh_free(recv_ctx.message.request_url); + APP_MGR_FREE(recv_ctx.message.request_url); recv_ctx.message.request_url = NULL; memset(&recv_ctx, 0, sizeof(recv_ctx)); return true; @@ -1449,7 +1443,7 @@ fail: } if (recv_ctx.message.request_url != NULL) { - bh_free(recv_ctx.message.request_url); + APP_MGR_FREE(recv_ctx.message.request_url); recv_ctx.message.request_url = NULL; } @@ -1466,7 +1460,7 @@ module_wasm_app_handle_install_msg(install_wasm_app_msg_t *message) request_t *request = NULL; bh_message_t msg; - request = (request_t *) bh_malloc(sizeof(request_t)); + request = (request_t *) APP_MGR_MALLOC(sizeof(request_t)); if (request == NULL) return false; @@ -1477,7 +1471,7 @@ module_wasm_app_handle_install_msg(install_wasm_app_msg_t *message) request->sender = ID_HOST; request->mid = message->request_mid; request->payload_len = sizeof(message->app_file); - request->payload = bh_malloc(request->payload_len); + request->payload = APP_MGR_MALLOC(request->payload_len); if (request->url == NULL || request->payload == NULL) { request_cleaner(request); @@ -1512,8 +1506,8 @@ destroy_all_wasm_sections(wasm_section_list_t sections) while (cur) { wasm_section_t *next = cur->next; if (cur->section_body != NULL) - bh_free(cur->section_body); - bh_free(cur); + APP_MGR_FREE(cur->section_body); + APP_MGR_FREE(cur); cur = next; } } @@ -1537,8 +1531,8 @@ destroy_part_wasm_sections(wasm_section_list_t *p_sections, *p_sections = next; if (cur->section_body != NULL) - bh_free(cur->section_body); - bh_free(cur); + APP_MGR_FREE(cur->section_body); + APP_MGR_FREE(cur); break; } else { @@ -1561,9 +1555,9 @@ destroy_all_aot_sections(aot_section_list_t sections) if (cur->section_type == AOT_SECTION_TYPE_TEXT) bh_munmap(cur->section_body, cur->section_body_size); else - bh_free(cur->section_body); + APP_MGR_FREE(cur->section_body); } - bh_free(cur); + APP_MGR_FREE(cur); cur = next; } } @@ -1591,9 +1585,9 @@ destroy_part_aot_sections(aot_section_list_t *p_sections, if (cur->section_type == AOT_SECTION_TYPE_TEXT) bh_munmap(cur->section_body, cur->section_body_size); else - bh_free(cur->section_body); + APP_MGR_FREE(cur->section_body); } - bh_free(cur); + APP_MGR_FREE(cur); break; } else { diff --git a/core/app-mgr/app-manager/platform/zephyr/app_mgr_zephyr.c b/core/app-mgr/app-manager/platform/zephyr/app_mgr_zephyr.c index 67ae69b4f..59c471fe9 100644 --- a/core/app-mgr/app-manager/platform/zephyr/app_mgr_zephyr.c +++ b/core/app-mgr/app-manager/platform/zephyr/app_mgr_zephyr.c @@ -5,7 +5,6 @@ #include "app_manager.h" #include "bh_platform.h" -#include "bh_memory.h" #include #include #include @@ -21,7 +20,7 @@ void* app_manager_timer_create(void (*timer_callback)(void*), watchdog_timer *wd_timer) { - struct k_timer_watchdog *timer = bh_malloc(sizeof(struct k_timer_watchdog)); + struct k_timer_watchdog *timer = APP_MGR_MALLOC(sizeof(struct k_timer_watchdog)); if (timer) { k_timer_init(&timer->timer, (void (*)(struct k_timer*)) timer_callback, @@ -34,7 +33,7 @@ app_manager_timer_create(void (*timer_callback)(void*), void app_manager_timer_destroy(void *timer) { - bh_free(timer); + APP_MGR_FREE(timer); } void app_manager_timer_start(void *timer, int timeout) diff --git a/core/app-mgr/app-manager/resource_reg.c b/core/app-mgr/app-manager/resource_reg.c index 854357e09..c6655ff65 100644 --- a/core/app-mgr/app-manager/resource_reg.c +++ b/core/app-mgr/app-manager/resource_reg.c @@ -158,14 +158,14 @@ bool am_register_resource(const char *url, if (register_num >= RESOURCE_REGISTRATION_NUM_MAX) return false; - r = (app_res_register_t *) bh_malloc(sizeof(app_res_register_t)); + r = (app_res_register_t *) APP_MGR_MALLOC(sizeof(app_res_register_t)); if (r == NULL) return false; memset(r, 0, sizeof(*r)); r->url = bh_strdup(url); if (r->url == NULL) { - bh_free(r); + APP_MGR_FREE(r); return false; } @@ -191,8 +191,8 @@ void am_cleanup_registeration(uint32 register_id) else g_resources = next; - bh_free(r->url); - bh_free(r); + APP_MGR_FREE(r->url); + APP_MGR_FREE(r); } else /* if r is freed, should not change prev. Only set prev to r when r isn't freed. */ diff --git a/core/app-mgr/app-manager/watchdog.c b/core/app-mgr/app-manager/watchdog.c index e23939452..2f3179962 100644 --- a/core/app-mgr/app-manager/watchdog.c +++ b/core/app-mgr/app-manager/watchdog.c @@ -6,8 +6,6 @@ #include "watchdog.h" #include "bh_queue.h" #include "bh_thread.h" -#include "bh_memory.h" -#include "jeff_export.h" #define WATCHDOG_THREAD_PRIORITY 5 diff --git a/core/iwasm/aot/aot_loader.c b/core/iwasm/aot/aot_loader.c index 84018e88d..3b2baaaa9 100644 --- a/core/iwasm/aot/aot_loader.c +++ b/core/iwasm/aot/aot_loader.c @@ -5,7 +5,6 @@ #include "aot_runtime.h" #include "bh_common.h" -#include "bh_memory.h" #include "bh_log.h" #include "aot_reloc.h" #include "../common/wasm_runtime_common.h" @@ -155,7 +154,7 @@ const_str_set_insert(const uint8 *str, int32 len, AOTModule *module, char* error_buf, uint32 error_buf_size) { HashMap *set = module->const_str_set; - char *c_str = wasm_malloc((uint32)len + 1), *value; + char *c_str = wasm_runtime_malloc((uint32)len + 1), *value; if (!c_str) { set_error_buf(error_buf, error_buf_size, @@ -168,7 +167,7 @@ const_str_set_insert(const uint8 *str, int32 len, AOTModule *module, c_str[len] = '\0'; if ((value = bh_hash_map_find(set, c_str))) { - wasm_free(c_str); + wasm_runtime_free(c_str); return value; } @@ -176,7 +175,7 @@ const_str_set_insert(const uint8 *str, int32 len, AOTModule *module, set_error_buf(error_buf, error_buf_size, "AOT module load failed: " "insert string to hash map failed."); - wasm_free(c_str); + wasm_runtime_free(c_str); return NULL; } @@ -330,8 +329,8 @@ destroy_mem_init_data_list(AOTMemInitData **data_list, uint32 count, uint32 i; for (i = 0; i < count; i++) if (data_list[i]) - wasm_free(data_list[i]); - wasm_free(data_list); + wasm_runtime_free(data_list[i]); + wasm_runtime_free(data_list); } } @@ -349,7 +348,7 @@ load_mem_init_data_list(const uint8 **p_buf, const uint8 *buf_end, size = sizeof(AOTMemInitData *) * (uint64)module->mem_init_data_count; if (size >= UINT32_MAX || !(module->mem_init_data_list = - data_list = wasm_malloc((uint32)size))) { + data_list = wasm_runtime_malloc((uint32)size))) { set_error_buf(error_buf, error_buf_size, "AOT module load failed: " "allocate memory failed."); @@ -367,7 +366,7 @@ load_mem_init_data_list(const uint8 **p_buf, const uint8 *buf_end, read_uint32(buf, buf_end, byte_count); size = offsetof(AOTMemInitData, bytes) + (uint64)byte_count; if (size >= UINT32_MAX - || !(data_list[i] = wasm_malloc((uint32)size))) { + || !(data_list[i] = wasm_runtime_malloc((uint32)size))) { set_error_buf(error_buf, error_buf_size, "AOT module load failed: " "allocate memory failed."); @@ -419,8 +418,8 @@ destroy_table_init_data_list(AOTTableInitData **data_list, uint32 count, uint32 i; for (i = 0; i < count; i++) if (data_list[i]) - wasm_free(data_list[i]); - wasm_free(data_list); + wasm_runtime_free(data_list[i]); + wasm_runtime_free(data_list); } } @@ -438,7 +437,7 @@ load_table_init_data_list(const uint8 **p_buf, const uint8 *buf_end, size = sizeof(AOTTableInitData *) * (uint64)module->table_init_data_count; if (size >= UINT32_MAX || !(module->table_init_data_list = - data_list = wasm_malloc((uint32)size))) { + data_list = wasm_runtime_malloc((uint32)size))) { set_error_buf(error_buf, error_buf_size, "AOT module load failed: " "allocate memory failed."); @@ -459,7 +458,7 @@ load_table_init_data_list(const uint8 **p_buf, const uint8 *buf_end, size1 = sizeof(uint32) * (uint64)func_index_count; size = offsetof(AOTTableInitData, func_indexes) + size1; if (size >= UINT32_MAX - || !(data_list[i] = wasm_malloc((uint32)size))) { + || !(data_list[i] = wasm_runtime_malloc((uint32)size))) { set_error_buf(error_buf, error_buf_size, "AOT module load failed: " "allocate memory failed."); @@ -507,8 +506,8 @@ destroy_func_types(AOTFuncType **func_types, uint32 count, bool is_jit_mode) uint32 i; for (i = 0; i < count; i++) if (func_types[i]) - wasm_free(func_types[i]); - wasm_free(func_types); + wasm_runtime_free(func_types[i]); + wasm_runtime_free(func_types); } } @@ -525,7 +524,7 @@ load_func_types(const uint8 **p_buf, const uint8 *buf_end, /* Allocate memory */ size = sizeof(AOTFuncType *) * (uint64)module->func_type_count; if (size >= UINT32_MAX - || !(module->func_types = func_types = wasm_malloc((uint32)size))) { + || !(module->func_types = func_types = wasm_runtime_malloc((uint32)size))) { set_error_buf(error_buf, error_buf_size, "AOT module load failed: " "allocate memory failed."); @@ -545,7 +544,7 @@ load_func_types(const uint8 **p_buf, const uint8 *buf_end, size1 = (uint64)param_count + (uint64)result_count; size = offsetof(AOTFuncType, types) + size1; if (size >= UINT32_MAX - || !(func_types[i] = wasm_malloc((uint32)size))) { + || !(func_types[i] = wasm_runtime_malloc((uint32)size))) { set_error_buf(error_buf, error_buf_size, "AOT module load failed: " "allocate memory failed."); @@ -587,7 +586,7 @@ static void destroy_import_globals(AOTImportGlobal *import_globals, bool is_jit_mode) { if (!is_jit_mode) - wasm_free(import_globals); + wasm_runtime_free(import_globals); } static bool @@ -604,7 +603,7 @@ load_import_globals(const uint8 **p_buf, const uint8 *buf_end, size = sizeof(AOTImportGlobal) * (uint64)module->import_global_count; if (size >= UINT32_MAX || !(module->import_globals = - import_globals = wasm_malloc((uint32)size))) { + import_globals = wasm_runtime_malloc((uint32)size))) { set_error_buf(error_buf, error_buf_size, "AOT module load failed: " "allocate memory failed."); @@ -657,7 +656,7 @@ static void destroy_globals(AOTGlobal *globals, bool is_jit_mode) { if (!is_jit_mode) - wasm_free(globals); + wasm_runtime_free(globals); } static bool @@ -674,7 +673,7 @@ load_globals(const uint8 **p_buf, const uint8 *buf_end, /* Allocate memory */ size = sizeof(AOTGlobal) * (uint64)module->global_count; if (size >= UINT32_MAX - || !(module->globals = globals = wasm_malloc((uint32)size))) { + || !(module->globals = globals = wasm_runtime_malloc((uint32)size))) { set_error_buf(error_buf, error_buf_size, "AOT module load failed: " "allocate memory failed."); @@ -739,7 +738,7 @@ destroy_import_funcs(AOTImportFunc *import_funcs, bool is_jit_mode) { if (!is_jit_mode) - wasm_free(import_funcs); + wasm_runtime_free(import_funcs); } static bool @@ -757,7 +756,7 @@ load_import_funcs(const uint8 **p_buf, const uint8 *buf_end, size = sizeof(AOTImportFunc) * (uint64)module->import_func_count; if (size >= UINT32_MAX || !(module->import_funcs = - import_funcs = wasm_malloc((uint32)size))) { + import_funcs = wasm_runtime_malloc((uint32)size))) { set_error_buf(error_buf, error_buf_size, "AOT module load failed: " "allocate memory failed."); @@ -831,7 +830,7 @@ destroy_object_data_sections(AOTObjectDataSection *data_sections, for (i = 0; i < data_section_count; i++, data_section++) if (data_section->data) bh_munmap(data_section->data, data_section->size); - wasm_free(data_sections); + wasm_runtime_free(data_sections); } static bool @@ -848,7 +847,7 @@ load_object_data_sections(const uint8 **p_buf, const uint8 *buf_end, size = sizeof(AOTObjectDataSection) * (uint64)module->data_section_count; if (size >= UINT32_MAX || !(module->data_sections = - data_sections = wasm_malloc((uint32)size))) { + data_sections = wasm_runtime_malloc((uint32)size))) { set_error_buf(error_buf, error_buf_size, "AOT module load failed: " "allocate memory failed."); @@ -1002,7 +1001,7 @@ load_function_section(const uint8 *buf, const uint8 *buf_end, size = sizeof(void*) * (uint64)module->func_count; if (size >= UINT32_MAX - || !(module->func_ptrs = wasm_malloc((uint32)size))) { + || !(module->func_ptrs = wasm_runtime_malloc((uint32)size))) { set_error_buf(error_buf, error_buf_size, "AOT module load failed: allocate memory failed."); return false; @@ -1042,7 +1041,7 @@ load_function_section(const uint8 *buf, const uint8 *buf_end, size = sizeof(uint32) * (uint64)module->func_count; if (size >= UINT32_MAX - || !(module->func_type_indexes = wasm_malloc((uint32)size))) { + || !(module->func_type_indexes = wasm_runtime_malloc((uint32)size))) { set_error_buf(error_buf, error_buf_size, "AOT module load failed: allocate memory failed."); return false; @@ -1074,7 +1073,7 @@ static void destroy_export_funcs(AOTExportFunc *export_funcs, bool is_jit_mode) { if (!is_jit_mode) - wasm_free(export_funcs); + wasm_runtime_free(export_funcs); } static bool @@ -1091,7 +1090,7 @@ load_export_funcs(const uint8 **p_buf, const uint8 *buf_end, size = sizeof(AOTExportFunc) * (uint64)module->export_func_count; if (size >= UINT32_MAX || !(module->export_funcs = - export_funcs = wasm_malloc((uint32)size))) { + export_funcs = wasm_runtime_malloc((uint32)size))) { set_error_buf(error_buf, error_buf_size, "AOT module load failed: " "allocate memory failed."); @@ -1204,7 +1203,7 @@ do_text_relocation(AOTModule *module, if (symbol_len + 1 <= sizeof(symbol_buf)) symbol = symbol_buf; else { - if (!(symbol = wasm_malloc(symbol_len + 1))) { + if (!(symbol = wasm_runtime_malloc(symbol_len + 1))) { set_error_buf(error_buf, error_buf_size, "AOT module load failed: " "allocate memory failed."); @@ -1254,7 +1253,7 @@ do_text_relocation(AOTModule *module, } if (symbol != symbol_buf) - wasm_free(symbol); + wasm_runtime_free(symbol); if (!apply_relocation(module, aot_text, aot_text_size, @@ -1270,7 +1269,7 @@ do_text_relocation(AOTModule *module, check_symbol_fail: if (symbol != symbol_buf) - wasm_free(symbol); + wasm_runtime_free(symbol); return false; } @@ -1399,7 +1398,7 @@ load_relocation_section(const uint8 *buf, const uint8 *buf_end, /* Allocate memory for relocation groups */ size = sizeof(AOTRelocationGroup) * (uint64)group_count; - if (size >= UINT32_MAX || !(groups = wasm_malloc((uint32)size))) { + if (size >= UINT32_MAX || !(groups = wasm_runtime_malloc((uint32)size))) { set_error_buf(error_buf, error_buf_size, "AOT module load failed: " "allocate memory failed."); @@ -1442,7 +1441,7 @@ load_relocation_section(const uint8 *buf, const uint8 *buf_end, size = sizeof(AOTRelocation) * (uint64)group->relocation_count; if (size >= UINT32_MAX || !(group->relocations = relocation = - wasm_malloc((uint32)size))) { + wasm_runtime_malloc((uint32)size))) { set_error_buf(error_buf, error_buf_size, "AOT module load failed: " "allocate memory failed."); @@ -1522,8 +1521,8 @@ fail: if (groups) { for (i = 0, group = groups; i < group_count; i++, group++) if (group->relocations) - wasm_free(group->relocations); - wasm_free(groups); + wasm_runtime_free(group->relocations); + wasm_runtime_free(groups); } return ret; @@ -1603,16 +1602,16 @@ load_from_sections(AOTModule *module, AOTSection *sections, #if BEIHAI_ENABLE_MEMORY_PROFILING != 0 static void aot_free(void *ptr) { - wasm_free(ptr); + wasm_runtime_free(ptr); } #else -#define aot_free wasm_free +#define aot_free wasm_runtime_free #endif static AOTModule* create_module(char *error_buf, uint32 error_buf_size) { - AOTModule *module = wasm_malloc(sizeof(AOTModule)); + AOTModule *module = wasm_runtime_malloc(sizeof(AOTModule)); if (!module) { set_error_buf(error_buf, error_buf_size, @@ -1634,7 +1633,7 @@ create_module(char *error_buf, uint32 error_buf_size) set_error_buf(error_buf, error_buf_size, "AOT module load failed: " "create const string set failed."); - wasm_free(module); + wasm_runtime_free(module); return NULL; } @@ -1670,7 +1669,7 @@ destroy_sections(AOTSection *section_list, bool destroy_aot_text) && section->section_type == AOT_SECTION_TYPE_TEXT && section->section_body) bh_munmap((uint8*)section->section_body, section->section_body_size); - wasm_free(section); + wasm_runtime_free(section); section = next; } } @@ -1694,7 +1693,7 @@ create_sections(const uint8 *buf, uint32 size, read_uint32(p, p_end, section_size); CHECK_BUF(p, p_end, section_size); - if (!(section = wasm_malloc(sizeof(AOTSection)))) { + if (!(section = wasm_runtime_malloc(sizeof(AOTSection)))) { set_error_buf(error_buf, error_buf_size, "AOT module load failed: " "allocate memory failed."); @@ -1722,7 +1721,7 @@ create_sections(const uint8 *buf, uint32 size, if (total_size >= UINT32_MAX || !(aot_text = bh_mmap(NULL, (uint32)total_size, map_prot, map_flags))) { - wasm_free(section); + wasm_runtime_free(section); set_error_buf(error_buf, error_buf_size, "AOT module load failed: " "mmap memory failed."); @@ -1849,7 +1848,7 @@ aot_load_from_comp_data(AOTCompData *comp_data, AOTCompContext *comp_ctx, AOTModule *module; /* Allocate memory for module */ - if (!(module = wasm_malloc(sizeof(AOTModule)))) { + if (!(module = wasm_runtime_malloc(sizeof(AOTModule)))) { set_error_buf(error_buf, error_buf_size, "Allocate memory for AOT module failed."); return NULL; @@ -1891,7 +1890,7 @@ aot_load_from_comp_data(AOTCompData *comp_data, AOTCompContext *comp_ctx, /* Allocate memory for function pointers */ size = (uint64)module->func_count * sizeof(void *); if (size >= UINT32_MAX - || !(module->func_ptrs = wasm_malloc((uint32)size))) { + || !(module->func_ptrs = wasm_runtime_malloc((uint32)size))) { set_error_buf(error_buf, error_buf_size, "Create func ptrs fail."); goto fail1; } @@ -1913,7 +1912,7 @@ aot_load_from_comp_data(AOTCompData *comp_data, AOTCompContext *comp_ctx, /* Allocation memory for function type indexes */ size = (uint64)module->func_count * sizeof(uint32); if (size >= UINT32_MAX - || !(module->func_type_indexes = wasm_malloc((uint32)size))) { + || !(module->func_type_indexes = wasm_runtime_malloc((uint32)size))) { set_error_buf(error_buf, error_buf_size, "Create func type indexes fail."); goto fail2; } @@ -1965,9 +1964,9 @@ aot_load_from_comp_data(AOTCompData *comp_data, AOTCompContext *comp_ctx, return module; fail2: - wasm_free(module->func_ptrs); + wasm_runtime_free(module->func_ptrs); fail1: - wasm_free(module); + wasm_runtime_free(module); return NULL; } @@ -2067,10 +2066,10 @@ aot_unload(AOTModule *module) module->is_jit_mode); if (module->func_type_indexes) - wasm_free(module->func_type_indexes); + wasm_runtime_free(module->func_type_indexes); if (module->func_ptrs) - wasm_free(module->func_ptrs); + wasm_runtime_free(module->func_ptrs); if (module->const_str_set) bh_hash_map_destroy(module->const_str_set); @@ -2082,7 +2081,7 @@ aot_unload(AOTModule *module) destroy_object_data_sections(module->data_sections, module->data_section_count); - wasm_free(module); + wasm_runtime_free(module); } uint32 diff --git a/core/iwasm/aot/aot_runtime.c b/core/iwasm/aot/aot_runtime.c index 8c3ab5e16..2be359bf1 100644 --- a/core/iwasm/aot/aot_runtime.c +++ b/core/iwasm/aot/aot_runtime.c @@ -4,7 +4,6 @@ */ #include "aot_runtime.h" -#include "bh_memory.h" #include "bh_log.h" #include "mem_alloc.h" @@ -116,7 +115,7 @@ memory_instantiate(AOTModuleInstance *module_inst, AOTModule *module, /* Allocate memory */ if (total_size >= UINT32_MAX - || !(module_inst->memory_data.ptr = wasm_malloc((uint32)total_size))) { + || !(module_inst->memory_data.ptr = wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "AOT module instantiate failed: allocate memory failed."); return false; @@ -166,7 +165,7 @@ memory_instantiate(AOTModuleInstance *module_inst, AOTModule *module, if (length > 0 && (base_offset >= module_inst->memory_data_size || base_offset + length > module_inst->memory_data_size)) { - wasm_free(module_inst->memory_data.ptr); + wasm_runtime_free(module_inst->memory_data.ptr); module_inst->memory_data.ptr = NULL; set_error_buf(error_buf, error_buf_size, "AOT module instantiate failed: data segment out of range."); @@ -193,7 +192,7 @@ init_func_ptrs(AOTModuleInstance *module_inst, AOTModule *module, /* Allocate memory */ if (total_size >= UINT32_MAX - || !(module_inst->func_ptrs.ptr = wasm_malloc((uint32)total_size))) { + || !(module_inst->func_ptrs.ptr = wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "AOT module instantiate failed: allocate memory failed."); return false; @@ -222,7 +221,8 @@ init_func_type_indexes(AOTModuleInstance *module_inst, AOTModule *module, /* Allocate memory */ if (total_size >= UINT32_MAX - || !(module_inst->func_type_indexes.ptr = wasm_malloc((uint32)total_size))) { + || !(module_inst->func_type_indexes.ptr = + wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "AOT module instantiate failed: allocate memory failed."); return false; @@ -304,7 +304,7 @@ aot_instantiate(AOTModule *module, /* Allocate module instance, global data, table data and heap data */ if (total_size >= UINT32_MAX - || !(module_inst = wasm_malloc((uint32)total_size))) { + || !(module_inst = wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "AOT module instantiate failed: allocate memory failed."); return NULL; @@ -407,18 +407,18 @@ aot_deinstantiate(AOTModuleInstance *module_inst) #endif if (module_inst->memory_data.ptr) - wasm_free(module_inst->memory_data.ptr); + wasm_runtime_free(module_inst->memory_data.ptr); if (module_inst->heap_handle.ptr) mem_allocator_destroy(module_inst->heap_handle.ptr); if (module_inst->func_ptrs.ptr) - wasm_free(module_inst->func_ptrs.ptr); + wasm_runtime_free(module_inst->func_ptrs.ptr); if (module_inst->func_type_indexes.ptr) - wasm_free(module_inst->func_type_indexes.ptr); + wasm_runtime_free(module_inst->func_type_indexes.ptr); - wasm_free(module_inst); + wasm_runtime_free(module_inst); } AOTFunctionInstance* @@ -768,8 +768,8 @@ aot_enlarge_memory(AOTModuleInstance *module_inst, uint32 inc_page_count) return false; } - if (!(mem_data_new = wasm_realloc(mem_data_old, (uint32)total_size))) { - if (!(mem_data_new = wasm_malloc((uint32)total_size))) { + if (!(mem_data_new = wasm_runtime_realloc(mem_data_old, (uint32)total_size))) { + if (!(mem_data_new = wasm_runtime_malloc((uint32)total_size))) { aot_set_exception(module_inst, "fail to enlarge memory."); return false; } @@ -778,7 +778,7 @@ aot_enlarge_memory(AOTModuleInstance *module_inst, uint32 inc_page_count) mem_data_old, total_size_old); memset(mem_data_new + total_size_old, 0, (uint32)total_size - total_size_old); - wasm_free(mem_data_old); + wasm_runtime_free(mem_data_old); } module_inst->mem_cur_page_count = total_page_count; diff --git a/core/iwasm/common/iwasm_common.cmake b/core/iwasm/common/iwasm_common.cmake index 42ce00417..3e2acfd99 100644 --- a/core/iwasm/common/iwasm_common.cmake +++ b/core/iwasm/common/iwasm_common.cmake @@ -5,6 +5,9 @@ set (IWASM_COMMON_DIR ${CMAKE_CURRENT_LIST_DIR}) include_directories (${IWASM_COMMON_DIR}) +add_definitions(-DBH_MALLOC=wasm_runtime_malloc) +add_definitions(-DBH_FREE=wasm_runtime_free) + file (GLOB c_source_all ${IWASM_COMMON_DIR}/*.c) if (${WAMR_BUILD_TARGET} STREQUAL "X86_64" OR ${WAMR_BUILD_TARGET} STREQUAL "AMD_64") diff --git a/core/iwasm/common/wasm_exec_env.c b/core/iwasm/common/wasm_exec_env.c index 92ec42c96..895cdaea1 100644 --- a/core/iwasm/common/wasm_exec_env.c +++ b/core/iwasm/common/wasm_exec_env.c @@ -4,7 +4,6 @@ */ #include "wasm_exec_env.h" -#include "bh_memory.h" #include "wasm_runtime_common.h" WASMExecEnv * @@ -16,14 +15,14 @@ wasm_exec_env_create(struct WASMModuleInstanceCommon *module_inst, WASMExecEnv *exec_env; if (total_size >= UINT32_MAX - || !(exec_env = wasm_malloc((uint32)total_size))) + || !(exec_env = wasm_runtime_malloc((uint32)total_size))) return NULL; memset(exec_env, 0, (uint32)total_size); #if WASM_ENABLE_AOT != 0 - if (!(exec_env->argv_buf = wasm_malloc(sizeof(uint32) * 64))) { - wasm_free(exec_env); + if (!(exec_env->argv_buf = wasm_runtime_malloc(sizeof(uint32) * 64))) { + wasm_runtime_free(exec_env); return NULL; } #endif @@ -40,9 +39,9 @@ void wasm_exec_env_destroy(WASMExecEnv *exec_env) { #if WASM_ENABLE_AOT != 0 - wasm_free(exec_env->argv_buf); + wasm_runtime_free(exec_env->argv_buf); #endif - wasm_free(exec_env); + wasm_runtime_free(exec_env); } WASMModuleInstanceCommon * diff --git a/core/shared/mem-alloc/bh_memory.c b/core/iwasm/common/wasm_memory.c similarity index 64% rename from core/shared/mem-alloc/bh_memory.c rename to core/iwasm/common/wasm_memory.c index 4de2b295e..4f39df8de 100644 --- a/core/shared/mem-alloc/bh_memory.c +++ b/core/iwasm/common/wasm_memory.c @@ -3,28 +3,26 @@ * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ -#include "bh_config.h" +#include "wasm_runtime_common.h" #include "bh_platform.h" -#include "bh_memory.h" #include "mem_alloc.h" -#include +#include "bh_thread.h" #if BEIHAI_ENABLE_MEMORY_PROFILING != 0 -#include "bh_thread.h" /* Memory profile data of a function */ typedef struct memory_profile { - struct memory_profile *next; - const char *function_name; - const char *file_name; - int line_in_file; - int malloc_num; - int free_num; - int total_malloc; - int total_free; + struct memory_profile *next; + const char *function_name; + const char *file_name; + int line_in_file; + int malloc_num; + int free_num; + int total_malloc; + int total_free; } memory_profile_t; -/* Memory in use which grows when bh_malloc was called +/* Memory in use which grows when BH_MALLOC was called * and decreases when bh_free was called */ static unsigned int memory_in_use = 0; @@ -33,7 +31,7 @@ static memory_profile_t *memory_profiles_list = NULL; /* Lock of the memory profile list */ static korp_mutex profile_lock; -#endif +#endif /* end of BEIHAI_ENABLE_MEMORY_PROFILING */ #ifndef MALLOC_MEMORY_FROM_SYSTEM @@ -53,7 +51,8 @@ static void (*free_func)(void *ptr) = NULL; static unsigned int global_pool_size; -int bh_memory_init_with_pool(void *mem, unsigned int bytes) +static bool +wasm_memory_init_with_pool(void *mem, unsigned int bytes) { mem_allocator_t _allocator = mem_allocator_create(mem, bytes); @@ -64,15 +63,16 @@ int bh_memory_init_with_pool(void *mem, unsigned int bytes) vm_mutex_init(&profile_lock); #endif global_pool_size = bytes; - return 0; + return true; } bh_printf("Init memory with pool (%p, %u) failed.\n", mem, bytes); - return -1; + return false; } -int bh_memory_init_with_allocator_internal(void *_malloc_func, - void *_realloc_func, - void *_free_func) +static bool +wasm_memory_init_with_allocator(void *_malloc_func, + void *_realloc_func, + void *_free_func) { if (_malloc_func && _free_func && _malloc_func != _free_func) { memory_mode = MEMORY_MODE_ALLOCATOR; @@ -82,20 +82,32 @@ int bh_memory_init_with_allocator_internal(void *_malloc_func, #if BEIHAI_ENABLE_MEMORY_PROFILING != 0 vm_mutex_init(&profile_lock); #endif - return 0; + return true; } - bh_printf("Init memory with allocator (%p, %p) failed.\n", _malloc_func, - _free_func); - return -1; + bh_printf("Init memory with allocator (%p, %p, %p) failed.\n", + _malloc_func, _realloc_func, _free_func); + return false; } -int bh_memory_init_with_allocator(void *_malloc_func, void *_free_func) +bool +wasm_runtime_memory_init(mem_alloc_type_t mem_alloc_type, + const MemAllocOption *alloc_option) { - return bh_memory_init_with_allocator_internal(_malloc_func, - NULL, _free_func); + if (mem_alloc_type == Alloc_With_Pool) + return wasm_memory_init_with_pool(alloc_option->pool.heap_buf, + alloc_option->pool.heap_size); + else if (mem_alloc_type == Alloc_With_Allocator) + return wasm_memory_init_with_allocator(alloc_option->allocator.malloc_func, + alloc_option->allocator.realloc_func, + alloc_option->allocator.free_func); + else if (mem_alloc_type == Alloc_With_System_Allocator) + return wasm_memory_init_with_allocator(os_malloc, os_realloc, os_free); + else + return false; } -void bh_memory_destroy() +void +wasm_runtime_memory_destroy() { #if BEIHAI_ENABLE_MEMORY_PROFILING != 0 vm_mutex_destroy(&profile_lock); @@ -105,7 +117,8 @@ void bh_memory_destroy() memory_mode = MEMORY_MODE_UNKNOWN; } -unsigned bh_memory_pool_size() +unsigned +wasm_runtime_memory_pool_size() { if (memory_mode == MEMORY_MODE_POOL) return global_pool_size; @@ -113,10 +126,11 @@ unsigned bh_memory_pool_size() return 1 * BH_GB; } -void* bh_malloc_internal(unsigned int size) +void * +wasm_runtime_malloc(unsigned int size) { if (memory_mode == MEMORY_MODE_UNKNOWN) { - bh_printf("bh_malloc failed: memory hasn't been initialize.\n"); + bh_printf("wasm_runtime_malloc failed: memory hasn't been initialize.\n"); return NULL; } else if (memory_mode == MEMORY_MODE_POOL) { return mem_allocator_malloc(pool_allocator, size); @@ -125,10 +139,11 @@ void* bh_malloc_internal(unsigned int size) } } -void* bh_realloc_internal(void *ptr, unsigned int size) +void * +wasm_runtime_realloc(void *ptr, unsigned int size) { if (memory_mode == MEMORY_MODE_UNKNOWN) { - bh_printf("bh_realloc failed: memory hasn't been initialize.\n"); + bh_printf("wasm_runtime_realloc failed: memory hasn't been initialize.\n"); return NULL; } else if (memory_mode == MEMORY_MODE_POOL) { return mem_allocator_realloc(pool_allocator, ptr, size); @@ -140,10 +155,11 @@ void* bh_realloc_internal(void *ptr, unsigned int size) } } -void bh_free_internal(void *ptr) +void +wasm_runtime_free(void *ptr) { if (memory_mode == MEMORY_MODE_UNKNOWN) { - bh_printf("bh_free failed: memory hasn't been initialize.\n"); + bh_printf("wasm_runtime_free failed: memory hasn't been initialize.\n"); } else if (memory_mode == MEMORY_MODE_POOL) { mem_allocator_free(pool_allocator, ptr); } else { @@ -152,12 +168,11 @@ void bh_free_internal(void *ptr) } #if BEIHAI_ENABLE_MEMORY_PROFILING != 0 -void* bh_malloc_profile(const char *file, - int line, - const char *func, - unsigned int size) +void * +wasm_runtime_malloc_profile(const char *file, int line, + const char *func, unsigned int size) { - void *p = bh_malloc_internal(size + 8); + void *p = wasm_rutime_malloc(size + 8); if (p) { memory_profile_t *profile; @@ -177,7 +192,7 @@ void* bh_malloc_profile(const char *file, profile->total_malloc += size;/* TODO: overflow check */ profile->malloc_num++; } else { - profile = bh_malloc_internal(sizeof(memory_profile_t)); + profile = wasm_runtime_malloc(sizeof(memory_profile_t)); if (!profile) { vm_mutex_unlock(&profile_lock); bh_memcpy_s(p, size + 8, &size, sizeof(size)); @@ -207,12 +222,14 @@ void* bh_malloc_profile(const char *file, return NULL; } -void bh_free_profile(const char *file, int line, const char *func, void *ptr) +void +wasm_runtime_free_profile(const char *file, int line, + const char *func, void *ptr) { unsigned int size = *(unsigned int *)((char *)ptr - 8); memory_profile_t *profile; - bh_free_internal((char *)ptr - 8); + wasm_runtime_free((char *)ptr - 8); if (memory_in_use >= size) memory_in_use -= size; @@ -232,7 +249,7 @@ void bh_free_profile(const char *file, int line, const char *func, void *ptr) profile->total_free += size;/* TODO: overflow check */ profile->free_num++; } else { - profile = bh_malloc_internal(sizeof(memory_profile_t)); + profile = wasm_runtime_malloc(sizeof(memory_profile_t)); if (!profile) { vm_mutex_unlock(&profile_lock); return; @@ -265,70 +282,53 @@ void memory_usage_summarize() profile = memory_profiles_list; while (profile) { bh_printf("malloc:%d:malloc_num:%d:free:%d:free_num:%d:%s\n", - profile->total_malloc, - profile->malloc_num, - profile->total_free, - profile->free_num, - profile->function_name); + profile->total_malloc, + profile->malloc_num, + profile->total_free, + profile->free_num, + profile->function_name); profile = profile->next; } vm_mutex_unlock(&profile_lock); } -void memory_profile_print(const char *file, - int line, - const char *func, - int alloc) +void +memory_profile_print(const char *file, int line, + const char *func, int alloc) { bh_printf("location:%s@%d:used:%d:contribution:%d\n", - func, line, memory_in_use, alloc); + func, line, memory_in_use, alloc); } -#else - -void* bh_malloc(unsigned int size) -{ - return bh_malloc_internal(size); -} - -void* bh_realloc(void *ptr, unsigned int size) -{ - return bh_realloc_internal(ptr, size); -} - -void bh_free(void *ptr) -{ - bh_free_internal(ptr); -} -#endif +#endif /* end of BEIHAI_ENABLE_MEMORY_PROFILING */ #else /* else of MALLOC_MEMORY_FROM_SYSTEM */ -#if BEIHAI_ENABLE_MEMORY_PROFILING == 0 -void* bh_malloc(unsigned int size) +void * +wasm_runtime_malloc(unsigned int size) { return malloc(size); } -void* bh_realloc(void *ptr, unsigned int size) +void * +wasm_runtime_realloc(void *ptr, unsigned int size) { return realloc(ptr, size); } -void bh_free(void *ptr) +void +wasm_runtime_free(void *ptr) { if (ptr) free(ptr); } -#else /* else of BEIHAI_ENABLE_MEMORY_PROFILING */ - -void* bh_malloc_profile(const char *file, - int line, - const char *func, - unsigned int size) +#if BEIHAI_ENABLE_MEMORY_PROFILING != 0 +void * +wasm_runtime_malloc_profile(const char *file, int line, + const char *func, unsigned int size) { (void)file; (void)line; @@ -341,11 +341,9 @@ void* bh_malloc_profile(const char *file, return malloc(size); } -void* bh_realloc_profile(const char *file, - int line, - const char *func, - void *ptr, - unsigned int size) +void * +wasm_runtime_realloc_profile(const char *file, int line, + const char *func, void *ptr, unsigned int size) { (void)file; (void)line; @@ -358,7 +356,9 @@ void* bh_realloc_profile(const char *file, return realloc(ptr, size); } -void bh_free_profile(const char *file, int line, const char *func, void *ptr) +void +wasm_runtime_free_profile(const char *file, int line, + const char *func, void *ptr) { (void)file; (void)line; @@ -369,3 +369,4 @@ void bh_free_profile(const char *file, int line, const char *func, void *ptr) } #endif /* end of BEIHAI_ENABLE_MEMORY_PROFILING */ #endif /* end of MALLOC_MEMORY_FROM_SYSTEM*/ + diff --git a/core/iwasm/common/wasm_memory.h b/core/iwasm/common/wasm_memory.h new file mode 100644 index 000000000..08157acfb --- /dev/null +++ b/core/iwasm/common/wasm_memory.h @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef _WASM_MEMORY_H +#define _WASM_MEMORY_H + +#include "bh_common.h" +#include "../include/wasm_export.h" + +#ifdef __cplusplus +extern "C" { +#endif + +bool +wasm_runtime_memory_init(mem_alloc_type_t mem_alloc_type, + const MemAllocOption *alloc_option); + +void +wasm_runtime_memory_destroy(); + +#ifdef __cplusplus +} +#endif + +#endif /* end of _WASM_MEMORY_H */ + diff --git a/core/iwasm/common/wasm_native.c b/core/iwasm/common/wasm_native.c index 29b762da8..38d2f6bd6 100644 --- a/core/iwasm/common/wasm_native.c +++ b/core/iwasm/common/wasm_native.c @@ -184,7 +184,7 @@ wasm_native_register_natives(const char *module_name, { NativeSymbolsNode *node; - if (!(node = bh_malloc(sizeof(NativeSymbolsNode)))) + if (!(node = wasm_runtime_malloc(sizeof(NativeSymbolsNode)))) return false; node->module_name = module_name; @@ -256,7 +256,7 @@ wasm_native_destroy() node = g_native_symbols_list; while (node) { node_next = node->next; - bh_free(node); + wasm_runtime_free(node); node = node_next; } diff --git a/core/iwasm/common/wasm_runtime_common.c b/core/iwasm/common/wasm_runtime_common.c index b97eed826..f8d7eea07 100644 --- a/core/iwasm/common/wasm_runtime_common.c +++ b/core/iwasm/common/wasm_runtime_common.c @@ -9,6 +9,7 @@ #include "bh_assert.h" #include "bh_log.h" #include "wasm_runtime_common.h" +#include "wasm_memory.h" #if WASM_ENABLE_INTERP != 0 #include "../interpreter/wasm_runtime.h" #endif @@ -23,8 +24,8 @@ set_error_buf(char *error_buf, uint32 error_buf_size, const char *string) snprintf(error_buf, error_buf_size, "%s", string); } -bool -wasm_runtime_init() +static bool +wasm_runtime_env_init() { if (bh_platform_init() != 0) return false; @@ -35,8 +36,20 @@ wasm_runtime_init() if (vm_thread_sys_init() != 0) return false; - if (wasm_native_init() == false) { - wasm_runtime_destroy(); + if (wasm_native_init() == false) + return false; + + return true; +} + +bool +wasm_runtime_init() +{ + if (!wasm_runtime_memory_init(Alloc_With_System_Allocator, NULL)) + return false; + + if (!wasm_runtime_env_init()) { + wasm_runtime_memory_destroy(); return false; } @@ -48,56 +61,30 @@ wasm_runtime_destroy() { wasm_native_destroy(); vm_thread_sys_destroy(); + wasm_runtime_memory_destroy(); } -int bh_memory_init_with_allocator_internal(void *_malloc_func, - void *_realloc_func, - void *_free_func); - bool wasm_runtime_full_init(RuntimeInitArgs *init_args) { - if (init_args->mem_alloc_type == Alloc_With_Pool) { - void *heap_buf = init_args->mem_alloc.pool.heap_buf; - uint32 heap_size = init_args->mem_alloc.pool.heap_size; - if (bh_memory_init_with_pool(heap_buf, heap_size) != 0) - return false; - } - else if (init_args->mem_alloc_type == Alloc_With_Allocator) { - void *malloc_func = init_args->mem_alloc.allocator.malloc_func; - void *realloc_func = init_args->mem_alloc.allocator.realloc_func; - void *free_func = init_args->mem_alloc.allocator.free_func; - if (bh_memory_init_with_allocator_internal(malloc_func, - realloc_func, - free_func) != 0) - return false; - } - else + if (!wasm_runtime_memory_init(init_args->mem_alloc_type, + &init_args->mem_alloc_option)) return false; - if (!wasm_runtime_init()) - goto fail1; + if (!wasm_runtime_env_init()) { + wasm_runtime_memory_destroy(); + return false; + } if (init_args->n_native_symbols > 0 && !wasm_runtime_register_natives(init_args->native_module_name, init_args->native_symbols, - init_args->n_native_symbols)) - goto fail2; + init_args->n_native_symbols)) { + wasm_runtime_destroy(); + return false; + } return true; - -fail2: - wasm_runtime_destroy(); -fail1: - bh_memory_destroy(); - return false; -} - -void -wasm_runtime_full_destroy() -{ - wasm_runtime_destroy(); - bh_memory_destroy(); } PackageType @@ -723,7 +710,7 @@ wasm_runtime_init_wasi(WASMModuleInstanceCommon *module_inst, uint64 total_size; uint32 i; - if (!(wasi_ctx = wasm_malloc(sizeof(WASIContext)))) { + if (!(wasi_ctx = wasm_runtime_malloc(sizeof(WASIContext)))) { set_error_buf(error_buf, error_buf_size, "Init wasi environment failed: allocate memory failed."); return false; @@ -952,7 +939,7 @@ wasm_runtime_destroy_wasi(WASMModuleInstanceCommon *module_inst) fd_table_destroy(wasi_ctx->curfds); if (wasi_ctx->prestats) fd_prestats_destroy(wasi_ctx->prestats); - bh_free(wasi_ctx); + wasm_runtime_free(wasi_ctx); } } @@ -1272,7 +1259,7 @@ wasm_application_execute_func(WASMModuleInstanceCommon *module_inst, total_size = sizeof(uint32) * (uint64)(argc1 > 2 ? argc1 : 2); if (total_size >= UINT32_MAX - || (!(argv1 = wasm_malloc((uint32)total_size)))) { + || (!(argv1 = wasm_runtime_malloc((uint32)total_size)))) { wasm_runtime_set_exception(module_inst, "allocate memory failed."); goto fail; } @@ -1417,12 +1404,12 @@ wasm_application_execute_func(WASMModuleInstanceCommon *module_inst, } bh_printf("\n"); - wasm_free(argv1); + wasm_runtime_free(argv1); return true; fail: if (argv1) - wasm_free(argv1); + wasm_runtime_free(argv1); exception = wasm_runtime_get_exception(module_inst); bh_assert(exception); @@ -1551,7 +1538,7 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, if (argc1 > sizeof(argv_buf) / sizeof(uint32)) { size = sizeof(uint32) * (uint32)argc1; if (size >= UINT32_MAX - || !(argv1 = wasm_malloc((uint32)size))) { + || !(argv1 = wasm_runtime_malloc((uint32)size))) { wasm_runtime_set_exception(exec_env->module_inst, "allocate memory failed."); return false; @@ -1679,7 +1666,7 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, fail: if (argv1 != argv_buf) - wasm_free(argv1); + wasm_runtime_free(argv1); return ret; } #endif /* end of defined(BUILD_TARGET_ARM_VFP) || defined(BUILD_TARGET_THUMB_VFP) */ @@ -1726,7 +1713,7 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, if (argc1 > sizeof(argv_buf) / sizeof(uint32)) { size = sizeof(uint32) * (uint64)argc1; if (size >= UINT_MAX - || !(argv1 = wasm_malloc((uint32)size))) { + || !(argv1 = wasm_runtime_malloc((uint32)size))) { wasm_runtime_set_exception(exec_env->module_inst, "allocate memory failed."); return false; @@ -1819,7 +1806,7 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, fail: if (argv1 != argv_buf) - wasm_free(argv1); + wasm_runtime_free(argv1); return ret; } @@ -1874,7 +1861,7 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, if (argc1 > sizeof(argv_buf) / sizeof(uint64)) { size = sizeof(uint64) * (uint64)argc1; if (size >= UINT32_MAX - || !(argv1 = wasm_malloc((uint32)size))) { + || !(argv1 = wasm_runtime_malloc((uint32)size))) { wasm_runtime_set_exception(exec_env->module_inst, "allocate memory failed."); return false; @@ -1976,7 +1963,7 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, ret = true; fail: if (argv1 != argv_buf) - wasm_free(argv1); + wasm_runtime_free(argv1); return ret; } diff --git a/core/iwasm/common/wasm_runtime_common.h b/core/iwasm/common/wasm_runtime_common.h index 0e92652ad..39c803c19 100644 --- a/core/iwasm/common/wasm_runtime_common.h +++ b/core/iwasm/common/wasm_runtime_common.h @@ -22,9 +22,6 @@ extern "C" { #endif -#define wasm_malloc bh_malloc -#define wasm_realloc bh_realloc -#define wasm_free bh_free typedef struct WASMModuleCommon { /* Module type, for module loaded from WASM bytecode binary, @@ -63,17 +60,13 @@ typedef wasm_section_t WASMSection, AOTSection; bool wasm_runtime_init(); -/* See wasm_export.h for description */ -void -wasm_runtime_destroy(); - /* See wasm_export.h for description */ bool wasm_runtime_full_init(RuntimeInitArgs *init_args); /* See wasm_export.h for description */ void -wasm_runtime_full_destroy(); +wasm_runtime_destroy(); /* See wasm_export.h for description */ PackageType diff --git a/core/iwasm/compilation/aot.c b/core/iwasm/compilation/aot.c index 83b6bb981..8f8bfaa77 100644 --- a/core/iwasm/compilation/aot.c +++ b/core/iwasm/compilation/aot.c @@ -4,7 +4,6 @@ */ #include "aot.h" -#include "bh_memory.h" static char aot_error[128]; @@ -30,8 +29,8 @@ aot_destroy_mem_init_data_list(AOTMemInitData **data_list, uint32 count) uint32 i; for (i = 0; i < count; i++) if (data_list[i]) - wasm_free(data_list[i]); - wasm_free(data_list); + wasm_runtime_free(data_list[i]); + wasm_runtime_free(data_list); } static AOTMemInitData ** @@ -44,7 +43,7 @@ aot_create_mem_init_data_list(const WASMModule *module) /* Allocate memory */ size = sizeof(AOTMemInitData *) * (uint64)module->data_seg_count; if (size >= UINT32_MAX - || !(data_list = wasm_malloc((uint32)size))) { + || !(data_list = wasm_runtime_malloc((uint32)size))) { aot_set_last_error("allocate memory failed."); return NULL; } @@ -56,7 +55,7 @@ aot_create_mem_init_data_list(const WASMModule *module) size = offsetof(AOTMemInitData, bytes) + (uint64)module->data_segments[i]->data_length; if (size >= UINT32_MAX - || !(data_list[i] = wasm_malloc((uint32)size))) { + || !(data_list[i] = wasm_runtime_malloc((uint32)size))) { aot_set_last_error("allocate memory failed."); goto fail; } @@ -80,8 +79,8 @@ aot_destroy_table_init_data_list(AOTTableInitData **data_list, uint32 count) uint32 i; for (i = 0; i < count; i++) if (data_list[i]) - wasm_free(data_list[i]); - wasm_free(data_list); + wasm_runtime_free(data_list[i]); + wasm_runtime_free(data_list); } static AOTTableInitData ** @@ -94,7 +93,7 @@ aot_create_table_init_data_list(const WASMModule *module) /* Allocate memory */ size = sizeof(AOTTableInitData *) * (uint64)module->table_seg_count; if (size >= UINT32_MAX - || !(data_list = wasm_malloc((uint32)size))) { + || !(data_list = wasm_runtime_malloc((uint32)size))) { aot_set_last_error("allocate memory failed."); return NULL; } @@ -106,7 +105,7 @@ aot_create_table_init_data_list(const WASMModule *module) size = offsetof(AOTTableInitData, func_indexes) + sizeof(uint32) * (uint64)module->table_segments[i].function_count; if (size >= UINT32_MAX - || !(data_list[i] = wasm_malloc((uint32)size))) { + || !(data_list[i] = wasm_runtime_malloc((uint32)size))) { aot_set_last_error("allocate memory failed."); goto fail; } @@ -135,7 +134,7 @@ aot_create_import_globals(const WASMModule *module, /* Allocate memory */ size = sizeof(AOTImportGlobal) * (uint64)module->import_global_count; if (size >= UINT32_MAX - || !(import_globals = wasm_malloc((uint32)size))) { + || !(import_globals = wasm_runtime_malloc((uint32)size))) { aot_set_last_error("allocate memory failed."); return NULL; } @@ -172,7 +171,7 @@ aot_create_globals(const WASMModule *module, /* Allocate memory */ size = sizeof(AOTGlobal) * (uint64)module->global_count; if (size >= UINT32_MAX - || !(globals = wasm_malloc((uint32)size))) { + || !(globals = wasm_runtime_malloc((uint32)size))) { aot_set_last_error("allocate memory failed."); return NULL; } @@ -202,8 +201,8 @@ aot_destroy_func_types(AOTFuncType **func_types, uint32 count) uint32 i; for (i = 0; i < count; i++) if (func_types[i]) - wasm_free(func_types[i]); - wasm_free(func_types); + wasm_runtime_free(func_types[i]); + wasm_runtime_free(func_types); } static AOTFuncType ** @@ -216,7 +215,7 @@ aot_create_func_types(const WASMModule *module) /* Allocate memory */ size = sizeof(AOTFuncType*) * (uint64)module->type_count; if (size >= UINT32_MAX - || !(func_types = wasm_malloc((uint32)size))) { + || !(func_types = wasm_runtime_malloc((uint32)size))) { aot_set_last_error("allocate memory failed."); return NULL; } @@ -229,7 +228,7 @@ aot_create_func_types(const WASMModule *module) (uint64)module->types[i]->param_count + (uint64)module->types[i]->result_count; if (size >= UINT32_MAX - || !(func_types[i] = wasm_malloc((uint32)size))) { + || !(func_types[i] = wasm_runtime_malloc((uint32)size))) { aot_set_last_error("allocate memory failed."); goto fail; } @@ -253,7 +252,7 @@ aot_create_import_funcs(const WASMModule *module) /* Allocate memory */ size = sizeof(AOTImportFunc) * (uint64)module->import_function_count; if (size >= UINT32_MAX - || !(import_funcs = wasm_malloc((uint32)size))) { + || !(import_funcs = wasm_runtime_malloc((uint32)size))) { aot_set_last_error("allocate memory failed."); return NULL; } @@ -284,8 +283,8 @@ aot_destroy_funcs(AOTFunc **funcs, uint32 count) for (i = 0; i < count; i++) if (funcs[i]) - wasm_free(funcs[i]); - wasm_free(funcs); + wasm_runtime_free(funcs[i]); + wasm_runtime_free(funcs); } static AOTFunc ** @@ -298,7 +297,7 @@ aot_create_funcs(const WASMModule *module) /* Allocate memory */ size = sizeof(AOTFunc*) * (uint64)module->function_count; if (size >= UINT32_MAX - || !(funcs = wasm_malloc((uint32)size))) { + || !(funcs = wasm_runtime_malloc((uint32)size))) { aot_set_last_error("allocate memory failed."); return NULL; } @@ -309,7 +308,7 @@ aot_create_funcs(const WASMModule *module) for (i = 0; i < module->function_count; i++) { WASMFunction *func = module->functions[i]; size = sizeof (AOTFunc); - if (!(funcs[i] = wasm_malloc((uint32)size))) { + if (!(funcs[i] = wasm_runtime_malloc((uint32)size))) { aot_set_last_error("allocate memory failed."); goto fail; } @@ -348,7 +347,7 @@ aot_create_export_funcs(const WASMModule *module, /* Allocate memory */ size = sizeof(AOTExportFunc) * (uint64)export_func_count; if (size >= UINT32_MAX - || !(export_funcs = wasm_malloc((uint32)size))) { + || !(export_funcs = wasm_runtime_malloc((uint32)size))) { aot_set_last_error("allocate memory failed."); return NULL; } @@ -376,7 +375,7 @@ aot_create_comp_data(WASMModule *module) uint32 import_global_data_size = 0, global_data_size = 0, i; /* Allocate memory */ - if (!(comp_data = wasm_malloc(sizeof(AOTCompData)))) { + if (!(comp_data = wasm_runtime_malloc(sizeof(AOTCompData)))) { aot_set_last_error("create compile data failed.\n"); return NULL; } @@ -492,24 +491,24 @@ aot_destroy_comp_data(AOTCompData *comp_data) comp_data->table_init_data_count); if (comp_data->import_globals) - wasm_free(comp_data->import_globals); + wasm_runtime_free(comp_data->import_globals); if (comp_data->globals) - wasm_free(comp_data->globals); + wasm_runtime_free(comp_data->globals); if (comp_data->func_types) aot_destroy_func_types(comp_data->func_types, comp_data->func_type_count); if (comp_data->import_funcs) - wasm_free(comp_data->import_funcs); + wasm_runtime_free(comp_data->import_funcs); if (comp_data->funcs) aot_destroy_funcs(comp_data->funcs, comp_data->func_count); if (comp_data->export_funcs) - wasm_free(comp_data->export_funcs); + wasm_runtime_free(comp_data->export_funcs); - wasm_free(comp_data); + wasm_runtime_free(comp_data); } diff --git a/core/iwasm/compilation/aot_compiler.c b/core/iwasm/compilation/aot_compiler.c index 8d078344e..14e45f0ed 100644 --- a/core/iwasm/compilation/aot_compiler.c +++ b/core/iwasm/compilation/aot_compiler.c @@ -14,7 +14,6 @@ #include "aot_emit_control.h" #include "aot_emit_function.h" #include "aot_emit_parametric.h" -#include "bh_memory.h" #include "../aot/aot_runtime.h" #include "../interpreter/wasm_opcode.h" #include @@ -152,7 +151,8 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) case WASM_OP_BR_TABLE: read_leb_uint32(frame_ip, frame_ip_end, br_count); - if (!(br_depths = wasm_malloc((uint32)sizeof(uint32) * (br_count + 1)))) { + if (!(br_depths = + wasm_runtime_malloc((uint32)sizeof(uint32) * (br_count + 1)))) { aot_set_last_error("allocate memory failed."); goto fail; } @@ -161,11 +161,11 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) if (!aot_compile_op_br_table(comp_ctx, func_ctx, br_depths, br_count, &frame_ip)) { - wasm_free(br_depths); + wasm_runtime_free(br_depths); return false; } - wasm_free(br_depths); + wasm_runtime_free(br_depths); break; case WASM_OP_RETURN: diff --git a/core/iwasm/compilation/aot_compiler.h b/core/iwasm/compilation/aot_compiler.h index c9959e0ad..d13b43862 100644 --- a/core/iwasm/compilation/aot_compiler.h +++ b/core/iwasm/compilation/aot_compiler.h @@ -8,7 +8,6 @@ #include "aot.h" #include "aot_llvm.h" -#include "bh_memory.h" #ifdef __cplusplus extern "C" { @@ -103,7 +102,7 @@ typedef enum FloatArithmetic { && (aot_value->type != VALUE_TYPE_I32 \ && aot_value->type != VALUE_TYPE_I1))) { \ aot_set_last_error("invalid WASM stack data type."); \ - wasm_free(aot_value); \ + wasm_runtime_free(aot_value); \ goto fail; \ } \ if (aot_value->type == value_type) \ @@ -113,11 +112,11 @@ typedef enum FloatArithmetic { if (!(llvm_value = LLVMBuildZExt(comp_ctx->builder, \ aot_value->value, I32_TYPE, "i1toi32"))) { \ aot_set_last_error("invalid WASM stack data type.");\ - wasm_free(aot_value); \ + wasm_runtime_free(aot_value); \ goto fail; \ } \ } \ - wasm_free(aot_value); \ + wasm_runtime_free(aot_value); \ } while (0) #define POP_I32(v) POP(v, VALUE_TYPE_I32) @@ -133,7 +132,7 @@ typedef enum FloatArithmetic { if (aot_value->type != VALUE_TYPE_I1 \ && aot_value->type != VALUE_TYPE_I32) { \ aot_set_last_error("invalid WASM stack data type."); \ - wasm_free(aot_value); \ + wasm_runtime_free(aot_value); \ goto fail; \ } \ if (aot_value->type == VALUE_TYPE_I1) \ @@ -143,11 +142,11 @@ typedef enum FloatArithmetic { LLVMIntNE, aot_value->value, I32_ZERO, \ "i1_cond"))){ \ aot_set_last_error("llvm build trunc failed."); \ - wasm_free(aot_value); \ + wasm_runtime_free(aot_value); \ goto fail; \ } \ } \ - wasm_free(aot_value); \ + wasm_runtime_free(aot_value); \ } while (0) #define PUSH(llvm_value, value_type) do { \ @@ -156,7 +155,7 @@ typedef enum FloatArithmetic { aot_set_last_error("WASM block stack underflow."); \ goto fail; \ } \ - aot_value = wasm_malloc(sizeof(AOTValue)); \ + aot_value = wasm_runtime_malloc(sizeof(AOTValue)); \ memset(aot_value, 0, sizeof(AOTValue)); \ if (!aot_value) { \ aot_set_last_error("allocate memory failed."); \ diff --git a/core/iwasm/compilation/aot_emit_aot_file.c b/core/iwasm/compilation/aot_emit_aot_file.c index 29d706fd6..9f8c82d08 100644 --- a/core/iwasm/compilation/aot_emit_aot_file.c +++ b/core/iwasm/compilation/aot_emit_aot_file.c @@ -509,7 +509,7 @@ get_relocation_symbol_index(const char *symbol_name, } /* Not found in symbol_list, add it */ - sym = bh_malloc(sizeof(AOTSymbolNode)); + sym = wasm_runtime_malloc(sizeof(AOTSymbolNode)); if (!sym) { return (uint32)-1; } @@ -1492,7 +1492,7 @@ aot_resolve_object_data_sections(AOTObjectData *obj_data) if (sections_count > 0) { size = (uint32)sizeof(AOTObjectDataSection) * sections_count; - if (!(data_section = obj_data->data_sections = bh_malloc(size))) { + if (!(data_section = obj_data->data_sections = wasm_runtime_malloc(size))) { aot_set_last_error("allocate memory for data sections failed."); return false; } @@ -1531,7 +1531,7 @@ aot_resolve_functions(AOTCompContext *comp_ctx, AOTObjectData *obj_data) /* allocate memory for aot function */ obj_data->func_count = comp_ctx->comp_data->func_count; if (!(obj_data->funcs - = bh_malloc((uint32)sizeof(AOTObjectFunc) * obj_data->func_count))) { + = wasm_runtime_malloc((uint32)sizeof(AOTObjectFunc) * obj_data->func_count))) { aot_set_last_error("allocate memory for functions failed."); return false; } @@ -1602,7 +1602,7 @@ aot_resolve_object_relocation_group(AOTObjectData *obj_data, return false; } size = (uint32)sizeof(AOTRelocation) * group->relocation_count; - if (!(relocation = group->relocations = bh_malloc(size))) { + if (!(relocation = group->relocations = wasm_runtime_malloc(size))) { aot_set_last_error("allocate memory for relocations failed."); return false; } @@ -1754,7 +1754,7 @@ aot_resolve_object_relocation_groups(AOTObjectData *obj_data) return true; size = (uint32)sizeof(AOTRelocationGroup) * group_count; - if (!(relocation_group = obj_data->relocation_groups = bh_malloc(size))) { + if (!(relocation_group = obj_data->relocation_groups = wasm_runtime_malloc(size))) { aot_set_last_error("allocate memory for relocation groups failed."); return false; } @@ -1795,8 +1795,8 @@ destroy_relocation_groups(AOTRelocationGroup *relocation_groups, for (i = 0; i < relocation_group_count; i++, relocation_group++) if (relocation_group->relocations) - bh_free(relocation_group->relocations); - bh_free(relocation_groups); + wasm_runtime_free(relocation_group->relocations); + wasm_runtime_free(relocation_groups); } static void @@ -1807,7 +1807,7 @@ destroy_relocation_symbol_list(AOTSymbolList *symbol_list) elem = symbol_list->head; while (elem) { AOTSymbolNode *next = elem->next; - bh_free(elem); + wasm_runtime_free(elem); elem = next; } } @@ -1820,15 +1820,15 @@ aot_obj_data_destroy(AOTObjectData *obj_data) if (obj_data->mem_buf) LLVMDisposeMemoryBuffer(obj_data->mem_buf); if (obj_data->funcs) - bh_free(obj_data->funcs); + wasm_runtime_free(obj_data->funcs); if (obj_data->data_sections) - bh_free(obj_data->data_sections); + wasm_runtime_free(obj_data->data_sections); if (obj_data->relocation_groups) destroy_relocation_groups(obj_data->relocation_groups, obj_data->relocation_group_count); if (obj_data->symbol_list.len) destroy_relocation_symbol_list(&obj_data->symbol_list); - bh_free(obj_data); + wasm_runtime_free(obj_data); } static AOTObjectData * @@ -1837,7 +1837,7 @@ aot_obj_data_create(AOTCompContext *comp_ctx) char *err = NULL; AOTObjectData *obj_data; - if (!(obj_data = bh_malloc(sizeof(AOTObjectData)))) { + if (!(obj_data = wasm_runtime_malloc(sizeof(AOTObjectData)))) { aot_set_last_error("allocate memory failed."); return false; } @@ -1896,7 +1896,7 @@ aot_emit_aot_file(AOTCompContext *comp_ctx, AOTCompData *comp_data, aot_file_size = get_aot_file_size(comp_data, obj_data); - if (!(buf = aot_file_buf = bh_malloc(aot_file_size))) { + if (!(buf = aot_file_buf = wasm_runtime_malloc(aot_file_size))) { aot_set_last_error("allocate memory failed."); goto fail1; } @@ -1938,7 +1938,7 @@ fail3: fclose(file); fail2: - bh_free(aot_file_buf); + wasm_runtime_free(aot_file_buf); fail1: aot_obj_data_destroy(obj_data); diff --git a/core/iwasm/compilation/aot_emit_control.c b/core/iwasm/compilation/aot_emit_control.c index c98a08661..d2a321fa1 100644 --- a/core/iwasm/compilation/aot_emit_control.c +++ b/core/iwasm/compilation/aot_emit_control.c @@ -7,7 +7,6 @@ #include "aot_emit_exception.h" #include "../aot/aot_runtime.h" #include "../interpreter/wasm_loader.h" -#include "bh_memory.h" static char *block_name_prefix[] = { "block", "loop", "if" }; static char *block_name_suffix[] = { "begin", "else", "end" }; @@ -208,7 +207,7 @@ aot_compile_op_block(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, } /* Allocate memory */ - if (!(block = wasm_malloc(sizeof(AOTBlock)))) { + if (!(block = wasm_runtime_malloc(sizeof(AOTBlock)))) { aot_set_last_error("allocate memory failed."); return false; } @@ -309,7 +308,7 @@ aot_compile_op_block(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, goto fail; } /* skip the block */ - wasm_free(block); + wasm_runtime_free(block); *p_frame_ip = end_addr + 1; } } @@ -322,7 +321,7 @@ aot_compile_op_block(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, return true; fail: - wasm_free(block); + wasm_runtime_free(block); return false; } diff --git a/core/iwasm/compilation/aot_emit_function.c b/core/iwasm/compilation/aot_emit_function.c index 21c7324e0..0634435ba 100644 --- a/core/iwasm/compilation/aot_emit_function.c +++ b/core/iwasm/compilation/aot_emit_function.c @@ -247,7 +247,7 @@ aot_compile_op_call(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, param_count = (int32)func_type->param_count; total_size = sizeof(LLVMValueRef) * (uint64)(param_count + 1); if (total_size >= UINT32_MAX - || !(param_values = wasm_malloc((uint32)total_size))) { + || !(param_values = wasm_runtime_malloc((uint32)total_size))) { aot_set_last_error("Allocate memory failed."); return false; } @@ -268,7 +268,7 @@ aot_compile_op_call(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, /* Initialize parameter types of the LLVM function */ total_size = sizeof(LLVMTypeRef) * (uint64)(param_count + 1); if (total_size >= UINT32_MAX - || !(param_types = wasm_malloc((uint32)total_size))) { + || !(param_types = wasm_runtime_malloc((uint32)total_size))) { aot_set_last_error("Allocate memory failed."); goto fail; } @@ -321,9 +321,9 @@ aot_compile_op_call(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, ret = true; fail: if (param_types) - wasm_free(param_types); + wasm_runtime_free(param_types); if (param_values) - wasm_free(param_values); + wasm_runtime_free(param_values); return ret; } @@ -548,7 +548,7 @@ aot_compile_op_call_indirect(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, param_count = (int32)func_type->param_count; total_size = sizeof(LLVMTypeRef) * (uint64)(param_count + 1); if (total_size >= UINT32_MAX - || !(param_types = wasm_malloc((uint32)total_size))) { + || !(param_types = wasm_runtime_malloc((uint32)total_size))) { aot_set_last_error("Allocate memory failed."); goto fail; } @@ -571,7 +571,7 @@ aot_compile_op_call_indirect(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, /* Allocate memory for parameters */ total_size = sizeof(LLVMValueRef) * (uint64)(param_count + 1); if (total_size >= UINT32_MAX - || !(param_values = wasm_malloc((uint32)total_size))) { + || !(param_values = wasm_runtime_malloc((uint32)total_size))) { aot_set_last_error("Allocate memory failed."); goto fail; } @@ -601,9 +601,9 @@ aot_compile_op_call_indirect(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, fail: if (param_values) - wasm_free(param_values); + wasm_runtime_free(param_values); if (param_types) - wasm_free(param_types); + wasm_runtime_free(param_types); return ret; } diff --git a/core/iwasm/compilation/aot_emit_numberic.c b/core/iwasm/compilation/aot_emit_numberic.c index 93f4ada72..62ea6cc8c 100644 --- a/core/iwasm/compilation/aot_emit_numberic.c +++ b/core/iwasm/compilation/aot_emit_numberic.c @@ -186,7 +186,7 @@ call_llvm_intrinsic(AOTCompContext *comp_ctx, /* Create param values */ total_size = sizeof(LLVMValueRef) * (uint64)param_count; if (total_size >= UINT32_MAX - || !(param_values = wasm_malloc((uint32)total_size))) { + || !(param_values = wasm_runtime_malloc((uint32)total_size))) { aot_set_last_error("allocate memory for param values failed."); return false; } @@ -201,7 +201,7 @@ call_llvm_intrinsic(AOTCompContext *comp_ctx, param_types, param_count, param_values); - wasm_free(param_values); + wasm_runtime_free(param_values); return ret; } @@ -221,7 +221,7 @@ call_llvm_intrinsic_v(AOTCompContext *comp_ctx, /* Create param values */ total_size = sizeof(LLVMValueRef) * (uint64)param_count; if (total_size >= UINT32_MAX - || !(param_values = wasm_malloc((uint32)total_size))) { + || !(param_values = wasm_runtime_malloc((uint32)total_size))) { aot_set_last_error("allocate memory for param values failed."); return false; } @@ -234,7 +234,7 @@ call_llvm_intrinsic_v(AOTCompContext *comp_ctx, param_types, param_count, param_values); - wasm_free(param_values); + wasm_runtime_free(param_values); return ret; } diff --git a/core/iwasm/compilation/aot_emit_parametric.c b/core/iwasm/compilation/aot_emit_parametric.c index 0660f9562..dc81ad53e 100644 --- a/core/iwasm/compilation/aot_emit_parametric.c +++ b/core/iwasm/compilation/aot_emit_parametric.c @@ -43,7 +43,7 @@ pop_value_from_wasm_stack(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, *p_value = aot_value->value; } - wasm_free(aot_value); + wasm_runtime_free(aot_value); if ((is_32 && (type != VALUE_TYPE_I32 && type != VALUE_TYPE_F32)) diff --git a/core/iwasm/compilation/aot_llvm.c b/core/iwasm/compilation/aot_llvm.c index f12ff7c28..a7a7e799f 100644 --- a/core/iwasm/compilation/aot_llvm.c +++ b/core/iwasm/compilation/aot_llvm.c @@ -4,7 +4,6 @@ */ #include "aot_llvm.h" -#include "bh_memory.h" #include "aot_compiler.h" #include "../aot/aot_runtime.h" @@ -47,7 +46,7 @@ aot_add_llvm_func(AOTCompContext *comp_ctx, AOTFuncType *aot_func_type, /* Initialize parameter types of the LLVM function */ size = sizeof(LLVMTypeRef) * ((uint64)param_count); if (size >= UINT32_MAX - || !(param_types = wasm_malloc((uint32)size))) { + || !(param_types = wasm_runtime_malloc((uint32)size))) { aot_set_last_error("allocate memory failed."); return NULL; } @@ -88,7 +87,7 @@ aot_add_llvm_func(AOTCompContext *comp_ctx, AOTFuncType *aot_func_type, } fail: - wasm_free(param_types); + wasm_runtime_free(param_types); return func; } @@ -102,7 +101,7 @@ aot_create_func_block(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, AOTBlock *aot_block; /* Allocate memory */ - if (!(aot_block = wasm_malloc(sizeof(AOTBlock)))) { + if (!(aot_block = wasm_runtime_malloc(sizeof(AOTBlock)))) { aot_set_last_error("allocate memory failed."); return NULL; } @@ -129,7 +128,7 @@ aot_create_func_block(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, return aot_block; fail: - wasm_free(aot_block); + wasm_runtime_free(aot_block); return NULL; } @@ -137,7 +136,7 @@ static bool create_exception_blocks(AOTFuncContext *func_ctx) { if (!(func_ctx->exception_blocks = - wasm_malloc(sizeof(LLVMBasicBlockRef) * EXCE_NUM))) { + wasm_runtime_malloc(sizeof(LLVMBasicBlockRef) * EXCE_NUM))) { aot_set_last_error("allocate memory failed."); return false;; } @@ -451,7 +450,7 @@ aot_create_func_context(AOTCompData *comp_data, AOTCompContext *comp_ctx, size = offsetof(AOTFuncContext, locals) + sizeof(LLVMValueRef) * ((uint64)aot_func_type->param_count + func->local_count); if (size >= UINT32_MAX - || !(func_ctx = wasm_malloc((uint32)size))) { + || !(func_ctx = wasm_runtime_malloc((uint32)size))) { aot_set_last_error("allocate memory failed."); return NULL; } @@ -605,9 +604,9 @@ aot_create_func_context(AOTCompData *comp_data, AOTCompContext *comp_ctx, fail: if (func_ctx->exception_blocks) - wasm_free(func_ctx->exception_blocks); + wasm_runtime_free(func_ctx->exception_blocks); aot_block_stack_destroy(&func_ctx->block_stack); - wasm_free(func_ctx); + wasm_runtime_free(func_ctx); return NULL; } @@ -619,11 +618,11 @@ aot_destroy_func_contexts(AOTFuncContext **func_ctxes, uint32 count) for (i = 0; i < count; i++) if (func_ctxes[i]) { if (func_ctxes[i]->exception_blocks) - wasm_free(func_ctxes[i]->exception_blocks); + wasm_runtime_free(func_ctxes[i]->exception_blocks); aot_block_stack_destroy(&func_ctxes[i]->block_stack); - wasm_free(func_ctxes[i]); + wasm_runtime_free(func_ctxes[i]); } - wasm_free(func_ctxes); + wasm_runtime_free(func_ctxes); } /** @@ -639,7 +638,7 @@ aot_create_func_contexts(AOTCompData *comp_data, AOTCompContext *comp_ctx) /* Allocate memory */ size = sizeof(AOTFuncContext*) * (uint64)comp_data->func_count; if (size >= UINT32_MAX - || !(func_ctxes = wasm_malloc((uint32)size))) { + || !(func_ctxes = wasm_runtime_malloc((uint32)size))) { aot_set_last_error("allocate memory failed."); return NULL; } @@ -877,7 +876,7 @@ aot_create_comp_context(AOTCompData *comp_data, LLVMLinkInMCJIT(); /* Allocate memory */ - if (!(comp_ctx = wasm_malloc(sizeof(AOTCompContext)))) { + if (!(comp_ctx = wasm_runtime_malloc(sizeof(AOTCompContext)))) { aot_set_last_error("allocate memory failed."); return NULL; } @@ -1176,7 +1175,7 @@ aot_destroy_comp_context(AOTCompContext *comp_ctx) if (comp_ctx->func_ctxes) aot_destroy_func_contexts(comp_ctx->func_ctxes, comp_ctx->func_ctx_count); - wasm_free(comp_ctx); + wasm_runtime_free(comp_ctx); } void @@ -1216,7 +1215,7 @@ aot_value_stack_destroy(AOTValueStack *stack) while (value) { p = value->next; - wasm_free(value); + wasm_runtime_free(value); value = p; } } @@ -1259,7 +1258,7 @@ aot_block_stack_destroy(AOTBlockStack *stack) while (block) { p = block->next; aot_value_stack_destroy(&block->value_stack); - wasm_free(block); + wasm_runtime_free(block); block = p; } } @@ -1268,5 +1267,5 @@ void aot_block_destroy(AOTBlock *block) { aot_value_stack_destroy(&block->value_stack); - wasm_free(block); + wasm_runtime_free(block); } diff --git a/core/iwasm/include/bh_memory.h b/core/iwasm/include/bh_memory.h deleted file mode 100644 index 4b3aa86db..000000000 --- a/core/iwasm/include/bh_memory.h +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _BH_MEMORY_H -#define _BH_MEMORY_H - -#ifdef __cplusplus -extern "C" { -#endif - -#define BH_KB (1024) -#define BH_MB ((BH_KB)*1024) -#define BH_GB ((BH_MB)*1024) - -/** - * Initialize memory allocator with a pool, the bh_malloc/bh_free function - * will malloc/free memory from the pool - * - * @param mem the pool buffer - * @param bytes the size bytes of the buffer - * - * @return 0 if success, -1 otherwise - */ -int bh_memory_init_with_pool(void *mem, unsigned int bytes); - -/** - * Initialize memory allocator with memory allocator, the bh_malloc/bh_free - * function will malloc/free memory with the allocator passed - * - * @param malloc_func the malloc function - * @param free_func the free function - * - * @return 0 if success, -1 otherwise - */ -int bh_memory_init_with_allocator(void *malloc_func, void *free_func); - -/** - * Destroy memory - */ -void bh_memory_destroy(); - -/** - * Get the pool size of memory, if memory is initialized with allocator, - * return 1GB by default. - */ -unsigned bh_memory_pool_size(); - -#if BEIHAI_ENABLE_MEMORY_PROFILING == 0 - -/** - * This function allocates a memory chunk from system - * - * @param size bytes need allocate - * - * @return the pointer to memory allocated - */ -void* bh_malloc(unsigned int size); - -/** - * This function frees memory chunk - * - * @param ptr the pointer to memory need free - */ -void bh_free(void *ptr); - -#else - -void* bh_malloc_profile(const char *file, int line, const char *func, unsigned int size); -void bh_free_profile(const char *file, int line, const char *func, void *ptr); - -#define bh_malloc(size) bh_malloc_profile(__FILE__, __LINE__, __func__, size) -#define bh_free(ptr) bh_free_profile(__FILE__, __LINE__, __func__, ptr) - -/** - * Print current memory profiling data - * - * @param file file name of the caller - * @param line line of the file of the caller - * @param func function name of the caller - */ -void memory_profile_print(const char *file, int line, const char *func, int alloc); - -/** - * Summarize memory usage and print it out - * Can use awk to analyze the output like below: - * awk -F: '{print $2,$4,$6,$8,$9}' OFS="\t" ./out.txt | sort -n -r -k 1 - */ -void memory_usage_summarize(); - -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* #ifndef _BH_MEMORY_H */ - diff --git a/core/iwasm/include/wasm_export.h b/core/iwasm/include/wasm_export.h index c391a5aef..57b2ec077 100644 --- a/core/iwasm/include/wasm_export.h +++ b/core/iwasm/include/wasm_export.h @@ -9,7 +9,6 @@ #include #include #include "lib_export.h" -#include "bh_memory.h" #ifdef __cplusplus @@ -53,24 +52,33 @@ typedef enum { /* Memory allocator type */ typedef enum { + /* pool mode, allocate memory from user defined heap buffer */ Alloc_With_Pool = 0, - Alloc_With_Allocator + /* user allocator mode, allocate memory from user defined + malloc function */ + Alloc_With_Allocator, + /* system allocator mode, allocate memory from system allocator, + or, platform's os_malloc function */ + Alloc_With_System_Allocator, } mem_alloc_type_t; +/* Memory allocator option */ +typedef union MemAllocOption { + struct { + void *heap_buf; + uint32_t heap_size; + } pool; + struct { + void *malloc_func; + void *realloc_func; + void *free_func; + } allocator; +} MemAllocOption; + /* WASM runtime initialize arguments */ typedef struct RuntimeInitArgs { mem_alloc_type_t mem_alloc_type; - union { - struct { - void *heap_buf; - uint32_t heap_size; - } pool; - struct { - void *malloc_func; - void *realloc_func; - void *free_func; - } allocator; - } mem_alloc; + MemAllocOption mem_alloc_option; const char *native_module_name; NativeSymbol *native_symbols; @@ -78,19 +86,15 @@ typedef struct RuntimeInitArgs { } RuntimeInitArgs; /** - * Initialize the WASM runtime environment. + * Initialize the WASM runtime environment, and also initialize + * the memory allocator with system allocator, which calls os_malloc + * to allocate memory * * @return true if success, false otherwise */ bool wasm_runtime_init(); -/** - * Destroy the WASM runtime environment. - */ -void -wasm_runtime_destroy(); - /** * Initialize the WASM runtime environment, and also initialize * the memory allocator and register native symbols, which are specified @@ -104,11 +108,36 @@ bool wasm_runtime_full_init(RuntimeInitArgs *init_args); /** - * Destroy the wasm runtime environment, and also destroy - * the memory allocator and registered native symbols + * Destroy the WASM runtime environment. */ void -wasm_runtime_full_destroy(); +wasm_runtime_destroy(); + +/** + * Allocate memory from runtime memory environment. + * + * @param size bytes need to allocate + * + * @return the pointer to memory allocated + */ +void * +wasm_runtime_malloc(unsigned int size); + +/** + * Reallocate memory from runtime memory environment + * + * @param ptr the original memory + * @param size bytes need to reallocate + * + * @return the pointer to memory reallocated + */ +void * +wasm_runtime_realloc(void *ptr, unsigned int size); + +/* + * Free memory to runtime memory environment. + */ +void wasm_runtime_free(void *ptr); /** * Get the package type of a buffer. diff --git a/core/iwasm/interpreter/wasm_interp.c b/core/iwasm/interpreter/wasm_interp.c index 6141f1c2e..c18151ee6 100644 --- a/core/iwasm/interpreter/wasm_interp.c +++ b/core/iwasm/interpreter/wasm_interp.c @@ -4,7 +4,6 @@ */ #include "wasm_interp.h" -#include "bh_memory.h" #include "bh_log.h" #include "wasm_runtime.h" #include "wasm_opcode.h" @@ -948,7 +947,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, else { uint64 total_size = sizeof(uint32) * (uint64)count; if (total_size >= UINT32_MAX - || !(depths = wasm_malloc((uint32)total_size))) { + || !(depths = wasm_runtime_malloc((uint32)total_size))) { wasm_set_exception(module, "WASM interp failed: allocate memory failed."); goto got_exception; @@ -963,7 +962,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, depth = depths[didx]; } if (depths != depth_buf) { - wasm_free(depths); + wasm_runtime_free(depths); depths = NULL; } POP_CSP_N(depth); diff --git a/core/iwasm/interpreter/wasm_interp_fast.c b/core/iwasm/interpreter/wasm_interp_fast.c index f00358f32..f0b78d2a9 100644 --- a/core/iwasm/interpreter/wasm_interp_fast.c +++ b/core/iwasm/interpreter/wasm_interp_fast.c @@ -4,7 +4,6 @@ */ #include "wasm_interp.h" -#include "bh_memory.h" #include "bh_log.h" #include "wasm_runtime.h" #include "wasm_opcode.h" diff --git a/core/iwasm/interpreter/wasm_loader.c b/core/iwasm/interpreter/wasm_loader.c index 32b2fed8c..b718c47b3 100644 --- a/core/iwasm/interpreter/wasm_loader.c +++ b/core/iwasm/interpreter/wasm_loader.c @@ -5,7 +5,6 @@ #include "wasm_loader.h" #include "bh_common.h" -#include "bh_memory.h" #include "bh_log.h" #include "wasm.h" #include "wasm_opcode.h" @@ -295,7 +294,7 @@ const_str_list_insert(const uint8 *str, uint32 len, WASMModule *module, if (node) return node->str; - if (!(node = wasm_malloc(sizeof(StringNode) + len + 1))) { + if (!(node = wasm_runtime_malloc(sizeof(StringNode) + len + 1))) { set_error_buf(error_buf, error_buf_size, "WASM module load failed: " "allocate memory failed."); @@ -394,7 +393,7 @@ load_type_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, module->type_count = type_count; total_size = sizeof(WASMType*) * (uint64)type_count; if (total_size >= UINT32_MAX - || !(module->types = wasm_malloc((uint32)total_size))) { + || !(module->types = wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "Load type section failed: allocate memory failed."); return false; @@ -429,7 +428,8 @@ load_type_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, total_size = offsetof(WASMType, types) + sizeof(uint8) * (uint64)(param_count + result_count); if (total_size >= UINT32_MAX - || !(type = module->types[i] = wasm_malloc((uint32)total_size))) { + || !(type = module->types[i] = + wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "Load type section failed: allocate memory failed."); return false; @@ -482,13 +482,16 @@ load_table_import(const uint8 **p_buf, const uint8 *buf_end, return true; } +unsigned +wasm_runtime_memory_pool_size(); + static bool load_memory_import(const uint8 **p_buf, const uint8 *buf_end, WASMMemoryImport *memory, char *error_buf, uint32 error_buf_size) { const uint8 *p = *p_buf, *p_end = buf_end; - uint32 pool_size = bh_memory_pool_size(); + uint32 pool_size = wasm_runtime_memory_pool_size(); uint32 max_page_count = pool_size * APP_MEMORY_MAX_GLOBAL_HEAP_PERCENT / DEFAULT_NUM_BYTES_PER_PAGE; @@ -535,7 +538,7 @@ load_memory(const uint8 **p_buf, const uint8 *buf_end, WASMMemory *memory, char *error_buf, uint32 error_buf_size) { const uint8 *p = *p_buf, *p_end = buf_end; - uint32 pool_size = bh_memory_pool_size(); + uint32 pool_size = wasm_runtime_memory_pool_size(); uint32 max_page_count = pool_size * APP_MEMORY_MAX_GLOBAL_HEAP_PERCENT / DEFAULT_NUM_BYTES_PER_PAGE; @@ -575,7 +578,7 @@ load_import_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, module->import_count = import_count; total_size = sizeof(WASMImport) * (uint64)import_count; if (total_size >= UINT32_MAX - || !(module->imports = wasm_malloc((uint32)total_size))) { + || !(module->imports = wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "Load import section failed: allocate memory failed."); return false; @@ -817,7 +820,7 @@ init_function_local_offsets(WASMFunction *func, uint64 total_size = sizeof(uint16) * ((uint64)param_count + local_count); if (total_size >= UINT32_MAX - || !(func->local_offsets = wasm_malloc((uint32)total_size))) { + || !(func->local_offsets = wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "Load function section failed: allocate memory failed."); return false; @@ -868,7 +871,7 @@ load_function_section(const uint8 *buf, const uint8 *buf_end, module->function_count = func_count; total_size = sizeof(WASMFunction*) * (uint64)func_count; if (total_size >= UINT32_MAX - || !(module->functions = wasm_malloc((uint32)total_size))) { + || !(module->functions = wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "Load function section failed: allocate memory failed."); return false; @@ -921,7 +924,8 @@ load_function_section(const uint8 *buf, const uint8 *buf_end, total_size = sizeof(WASMFunction) + (uint64)local_count; if (total_size >= UINT32_MAX - || !(func = module->functions[i] = wasm_malloc((uint32)total_size))) { + || !(func = module->functions[i] = + wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "Load function section failed: " "allocate memory failed."); @@ -1006,7 +1010,7 @@ load_table_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, module->table_count = table_count; total_size = sizeof(WASMTable) * (uint64)table_count; if (total_size >= UINT32_MAX - || !(module->tables = wasm_malloc((uint32)total_size))) { + || !(module->tables = wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "Load table section failed: allocate memory failed."); return false; @@ -1052,7 +1056,7 @@ load_memory_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, module->memory_count = memory_count; total_size = sizeof(WASMMemory) * (uint64)memory_count; if (total_size >= UINT32_MAX - || !(module->memories = wasm_malloc((uint32)total_size))) { + || !(module->memories = wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "Load memory section failed: allocate memory failed."); return false; @@ -1093,7 +1097,7 @@ load_global_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, module->global_count = global_count; total_size = sizeof(WASMGlobal) * (uint64)global_count; if (total_size >= UINT32_MAX - || !(module->globals = wasm_malloc((uint32)total_size))) { + || !(module->globals = wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "Load global section failed: " "allocate memory failed."); @@ -1148,7 +1152,7 @@ load_export_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, module->export_count = export_count; total_size = sizeof(WASMExport) * (uint64)export_count; if (total_size >= UINT32_MAX - || !(module->exports = wasm_malloc((uint32)total_size))) { + || !(module->exports = wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "Load export section failed: " "allocate memory failed."); @@ -1242,7 +1246,7 @@ load_table_segment_section(const uint8 *buf, const uint8 *buf_end, WASMModule *m module->table_seg_count = table_segment_count; total_size = sizeof(WASMTableSeg) * (uint64)table_segment_count; if (total_size >= UINT32_MAX - || !(module->table_segments = wasm_malloc((uint32)total_size))) { + || !(module->table_segments = wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "Load table segment section failed: " "allocate memory failed."); @@ -1272,7 +1276,7 @@ load_table_segment_section(const uint8 *buf, const uint8 *buf_end, WASMModule *m total_size = sizeof(uint32) * (uint64)function_count; if (total_size >= UINT32_MAX || !(table_segment->func_indexes = (uint32 *) - wasm_malloc((uint32)total_size))) { + wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "Load table segment section failed: " "allocate memory failed."); @@ -1312,7 +1316,7 @@ load_data_segment_section(const uint8 *buf, const uint8 *buf_end, module->data_seg_count = data_seg_count; total_size = sizeof(WASMDataSeg*) * (uint64)data_seg_count; if (total_size >= UINT32_MAX - || !(module->data_segments = wasm_malloc((uint32)total_size))) { + || !(module->data_segments = wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "Load data segment section failed: " "allocate memory failed."); @@ -1330,7 +1334,7 @@ load_data_segment_section(const uint8 *buf, const uint8 *buf_end, read_leb_uint32(p, p_end, data_seg_len); if (!(dataseg = module->data_segments[i] = - wasm_malloc((uint32)sizeof(WASMDataSeg)))) { + wasm_runtime_malloc((uint32)sizeof(WASMDataSeg)))) { set_error_buf(error_buf, error_buf_size, "Load data segment section failed: " "allocate memory failed."); @@ -1564,7 +1568,7 @@ load_from_sections(WASMModule *module, WASMSection *sections, total_size = sizeof(BlockAddr) * (uint64)BLOCK_ADDR_CACHE_SIZE * BLOCK_ADDR_CONFLICT_SIZE; if (total_size >= UINT32_MAX - || !(block_addr_cache = wasm_malloc((uint32)total_size))) { + || !(block_addr_cache = wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "WASM module load failed: allocate memory failed"); return false; @@ -1576,7 +1580,7 @@ load_from_sections(WASMModule *module, WASMSection *sections, if (!wasm_loader_prepare_bytecode(module, func, block_addr_cache, error_buf, error_buf_size)) return false; } - wasm_free(block_addr_cache); + wasm_runtime_free(block_addr_cache); /* Resolve llvm auxiliary data/stack/heap info and reset memory info */ if (!module->possible_memory_grow) { @@ -1693,7 +1697,7 @@ load_from_sections(WASMModule *module, WASMSection *sections, #if BEIHAI_ENABLE_MEMORY_PROFILING != 0 static void wasm_loader_free(void *ptr) { - wasm_free(ptr); + wasm_runtime_free(ptr); } #else #define wasm_loader_free wasm_free @@ -1702,7 +1706,7 @@ static void wasm_loader_free(void *ptr) static WASMModule* create_module(char *error_buf, uint32 error_buf_size) { - WASMModule *module = wasm_malloc(sizeof(WASMModule)); + WASMModule *module = wasm_runtime_malloc(sizeof(WASMModule)); if (!module) { set_error_buf(error_buf, error_buf_size, @@ -1744,7 +1748,7 @@ destroy_sections(WASMSection *section_list) WASMSection *section = section_list, *next; while (section) { next = section->next; - wasm_free(section); + wasm_runtime_free(section); section = next; } } @@ -1783,7 +1787,7 @@ create_sections(const uint8 *buf, uint32 size, read_leb_uint32(p, p_end, section_size); CHECK_BUF1(p, p_end, section_size); - if (!(section = wasm_malloc(sizeof(WASMSection)))) { + if (!(section = wasm_runtime_malloc(sizeof(WASMSection)))) { set_error_buf(error_buf, error_buf_size, "WASM module load failed: " "allocate memory failed."); @@ -1877,7 +1881,7 @@ load(const uint8 *buf, uint32 size, WASMModule *module, WASMModule* wasm_loader_load(const uint8 *buf, uint32 size, char *error_buf, uint32 error_buf_size) { - WASMModule *module = wasm_malloc(sizeof(WASMModule)); + WASMModule *module = wasm_runtime_malloc(sizeof(WASMModule)); if (!module) { set_error_buf(error_buf, error_buf_size, @@ -1914,69 +1918,69 @@ wasm_loader_unload(WASMModule *module) if (module->types) { for (i = 0; i < module->type_count; i++) { if (module->types[i]) - wasm_free(module->types[i]); + wasm_runtime_free(module->types[i]); } - wasm_free(module->types); + wasm_runtime_free(module->types); } if (module->imports) - wasm_free(module->imports); + wasm_runtime_free(module->imports); if (module->functions) { for (i = 0; i < module->function_count; i++) { if (module->functions[i]) { if (module->functions[i]->local_offsets) - wasm_free(module->functions[i]->local_offsets); + wasm_runtime_free(module->functions[i]->local_offsets); #if WASM_ENABLE_FAST_INTERP != 0 if (module->functions[i]->code_compiled) - wasm_free(module->functions[i]->code_compiled); + wasm_runtime_free(module->functions[i]->code_compiled); if (module->functions[i]->consts) - wasm_free(module->functions[i]->consts); + wasm_runtime_free(module->functions[i]->consts); #endif - wasm_free(module->functions[i]); + wasm_runtime_free(module->functions[i]); } } - wasm_free(module->functions); + wasm_runtime_free(module->functions); } if (module->tables) - wasm_free(module->tables); + wasm_runtime_free(module->tables); if (module->memories) - wasm_free(module->memories); + wasm_runtime_free(module->memories); if (module->globals) - wasm_free(module->globals); + wasm_runtime_free(module->globals); if (module->exports) - wasm_free(module->exports); + wasm_runtime_free(module->exports); if (module->table_segments) { for (i = 0; i < module->table_seg_count; i++) { if (module->table_segments[i].func_indexes) - wasm_free(module->table_segments[i].func_indexes); + wasm_runtime_free(module->table_segments[i].func_indexes); } - wasm_free(module->table_segments); + wasm_runtime_free(module->table_segments); } if (module->data_segments) { for (i = 0; i < module->data_seg_count; i++) { if (module->data_segments[i]) - wasm_free(module->data_segments[i]); + wasm_runtime_free(module->data_segments[i]); } - wasm_free(module->data_segments); + wasm_runtime_free(module->data_segments); } if (module->const_str_list) { StringNode *node = module->const_str_list, *node_next; while (node) { node_next = node->next; - wasm_free(node); + wasm_runtime_free(node); node = node_next; } } - wasm_free(module); + wasm_runtime_free(module); } bool @@ -2388,10 +2392,10 @@ memory_realloc(void *mem_old, uint32 size_old, uint32 size_new, { uint8 *mem_new; bh_assert(size_new > size_old); - if ((mem_new = wasm_malloc(size_new))) { + if ((mem_new = wasm_runtime_malloc(size_new))) { bh_memcpy_s(mem_new, size_new, mem_old, size_old); memset(mem_new + size_old, 0, size_new - size_old); - wasm_free(mem_old); + wasm_runtime_free(mem_old); } else { set_error_buf(error_buf, error_buf_size, @@ -2454,7 +2458,7 @@ static void free_label_patch_list(BranchBlock *frame_csp) BranchBlockPatch *next; while (label_patch != NULL) { next = label_patch->next; - wasm_free(label_patch); + wasm_runtime_free(label_patch); label_patch = next; } frame_csp->patch_list = NULL; @@ -2524,20 +2528,20 @@ static void wasm_loader_ctx_destroy(WASMLoaderContext *ctx) { if (ctx) { if (ctx->frame_ref_bottom) - wasm_free(ctx->frame_ref_bottom); + wasm_runtime_free(ctx->frame_ref_bottom); if (ctx->frame_csp_bottom) { #if WASM_ENABLE_FAST_INTERP != 0 free_all_label_patch_lists(ctx->frame_csp_bottom, ctx->csp_num); #endif - wasm_free(ctx->frame_csp_bottom); + wasm_runtime_free(ctx->frame_csp_bottom); } #if WASM_ENABLE_FAST_INTERP != 0 if (ctx->frame_offset_bottom) - wasm_free(ctx->frame_offset_bottom); + wasm_runtime_free(ctx->frame_offset_bottom); if (ctx->const_buf) - wasm_free(ctx->const_buf); + wasm_runtime_free(ctx->const_buf); #endif - wasm_free(ctx); + wasm_runtime_free(ctx); } } @@ -2545,14 +2549,14 @@ static WASMLoaderContext* wasm_loader_ctx_init(WASMFunction *func) { WASMLoaderContext *loader_ctx = - wasm_malloc(sizeof(WASMLoaderContext)); + wasm_runtime_malloc(sizeof(WASMLoaderContext)); if (!loader_ctx) return false; memset(loader_ctx, 0, sizeof(WASMLoaderContext)); loader_ctx->frame_ref_size = 32; if (!(loader_ctx->frame_ref_bottom = loader_ctx->frame_ref = - wasm_malloc(loader_ctx->frame_ref_size))) + wasm_runtime_malloc(loader_ctx->frame_ref_size))) goto fail; memset(loader_ctx->frame_ref_bottom, 0, loader_ctx->frame_ref_size); loader_ctx->frame_ref_boundary = loader_ctx->frame_ref_bottom + @@ -2560,7 +2564,7 @@ wasm_loader_ctx_init(WASMFunction *func) loader_ctx->frame_csp_size = sizeof(BranchBlock) * 8; if (!(loader_ctx->frame_csp_bottom = loader_ctx->frame_csp = - wasm_malloc(loader_ctx->frame_csp_size))) + wasm_runtime_malloc(loader_ctx->frame_csp_size))) goto fail; memset(loader_ctx->frame_csp_bottom, 0, loader_ctx->frame_csp_size); loader_ctx->frame_csp_boundary = loader_ctx->frame_csp_bottom + 8; @@ -2568,7 +2572,7 @@ wasm_loader_ctx_init(WASMFunction *func) #if WASM_ENABLE_FAST_INTERP != 0 loader_ctx->frame_offset_size = sizeof(int16) * 32; if (!(loader_ctx->frame_offset_bottom = loader_ctx->frame_offset = - wasm_malloc(loader_ctx->frame_offset_size))) + wasm_runtime_malloc(loader_ctx->frame_offset_size))) goto fail; memset(loader_ctx->frame_offset_bottom, 0, loader_ctx->frame_offset_size); @@ -2576,7 +2580,7 @@ wasm_loader_ctx_init(WASMFunction *func) loader_ctx->num_const = 0; loader_ctx->const_buf_size = sizeof(Const) * 8; - if (!(loader_ctx->const_buf = wasm_malloc(loader_ctx->const_buf_size))) + if (!(loader_ctx->const_buf = wasm_runtime_malloc(loader_ctx->const_buf_size))) goto fail; memset(loader_ctx->const_buf, 0, loader_ctx->const_buf_size); @@ -2715,7 +2719,7 @@ wasm_loader_check_br(WASMLoaderContext *ctx, uint32 depth, static bool wasm_loader_ctx_reinit(WASMLoaderContext *ctx) { - if (!(ctx->p_code_compiled = wasm_malloc(ctx->code_compiled_size))) + if (!(ctx->p_code_compiled = wasm_runtime_malloc(ctx->code_compiled_size))) return false; memset(ctx->p_code_compiled, 0, ctx->code_compiled_size); ctx->p_code_compiled_end = ctx->p_code_compiled + @@ -2804,7 +2808,7 @@ add_label_patch_to_list(BranchBlock *frame_csp, uint8 patch_type, uint8 *p_code_compiled, char *error_buf, uint32 error_buf_size) { - BranchBlockPatch *patch = wasm_malloc(sizeof(BranchBlockPatch)); + BranchBlockPatch *patch = wasm_runtime_malloc(sizeof(BranchBlockPatch)); if (!patch) { set_error_buf(error_buf, error_buf_size, "WASM loader prepare bytecode failed: " @@ -2845,7 +2849,7 @@ apply_label_patch(WASMLoaderContext *ctx, uint8 depth, else { node_prev->next = node_next; } - wasm_free(node); + wasm_runtime_free(node); } else { node_prev = node; @@ -4589,7 +4593,8 @@ handle_next_reachable_block: goto re_scan; func->const_cell_num = loader_ctx->const_cell_num; - if (!(func->consts = func_const = wasm_malloc(func->const_cell_num * 4))) { + if (!(func->consts = func_const = + wasm_runtime_malloc(func->const_cell_num * 4))) { set_error_buf(error_buf, error_buf_size, "WASM loader prepare bytecode failed: " "allocate memory failed"); diff --git a/core/iwasm/interpreter/wasm_runtime.c b/core/iwasm/interpreter/wasm_runtime.c index ea3475170..cfd607f5b 100644 --- a/core/iwasm/interpreter/wasm_runtime.c +++ b/core/iwasm/interpreter/wasm_runtime.c @@ -51,10 +51,10 @@ memories_deinstantiate(WASMMemoryInstance **memories, uint32 count) if (memories[i]) { if (memories[i]->heap_handle) mem_allocator_destroy(memories[i]->heap_handle); - wasm_free(memories[i]->heap_data); - wasm_free(memories[i]); + wasm_runtime_free(memories[i]->heap_data); + wasm_runtime_free(memories[i]); } - wasm_free(memories); + wasm_runtime_free(memories); } } @@ -72,7 +72,7 @@ memory_instantiate(uint32 num_bytes_per_page, /* Allocate memory space, addr data and global data */ if (total_size >= UINT32_MAX - || !(memory = wasm_malloc((uint32)total_size))) { + || !(memory = wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "Instantiate memory failed: allocate memory failed."); return NULL; @@ -92,7 +92,7 @@ memory_instantiate(uint32 num_bytes_per_page, memory->end_addr = memory->global_data + global_data_size; /* Allocate heap space */ - if (!(memory->heap_data = wasm_malloc(heap_size))) { + if (!(memory->heap_data = wasm_runtime_malloc(heap_size))) { set_error_buf(error_buf, error_buf_size, "Instantiate memory failed: allocate memory failed."); goto fail1; @@ -114,10 +114,10 @@ memory_instantiate(uint32 num_bytes_per_page, return memory; fail2: - wasm_free(memory->heap_data); + wasm_runtime_free(memory->heap_data); fail1: - wasm_free(memory); + wasm_runtime_free(memory); return NULL; } @@ -141,7 +141,7 @@ memories_instantiate(const WASMModule *module, total_size = sizeof(WASMMemoryInstance*) * (uint64)memory_count; if (total_size >= UINT32_MAX - || !(memories = wasm_malloc((uint32)total_size))) { + || !(memories = wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "Instantiate memory failed: " "allocate memory failed."); @@ -210,8 +210,8 @@ tables_deinstantiate(WASMTableInstance **tables, uint32 count) if (tables) { for (i = 0; i < count; i++) if (tables[i]) - wasm_free(tables[i]); - wasm_free(tables); + wasm_runtime_free(tables[i]); + wasm_runtime_free(tables); } } @@ -229,7 +229,7 @@ tables_instantiate(const WASMModule *module, WASMTableInstance **tables, *table; if (total_size >= UINT32_MAX - || !(tables = wasm_malloc((uint32)total_size))) { + || !(tables = wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "Instantiate table failed: " "allocate memory failed."); @@ -244,7 +244,8 @@ tables_instantiate(const WASMModule *module, total_size = offsetof(WASMTableInstance, base_addr) + sizeof(uint32) * (uint64)import->u.table.init_size; if (total_size >= UINT32_MAX - || !(table = tables[table_index++] = wasm_malloc((uint32)total_size))) { + || !(table = tables[table_index++] = + wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "Instantiate table failed: " "allocate memory failed."); @@ -264,7 +265,8 @@ tables_instantiate(const WASMModule *module, total_size = offsetof(WASMTableInstance, base_addr) + sizeof(uint32) * (uint64)module->tables[i].init_size; if (total_size >= UINT32_MAX - || !(table = tables[table_index++] = wasm_malloc((uint32)total_size))) { + || !(table = tables[table_index++] = + wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "Instantiate table failed: " "allocate memory failed."); @@ -290,7 +292,7 @@ static void functions_deinstantiate(WASMFunctionInstance *functions, uint32 count) { if (functions) { - wasm_free(functions); + wasm_runtime_free(functions); } } @@ -308,7 +310,7 @@ functions_instantiate(const WASMModule *module, WASMFunctionInstance *functions, *function; if (total_size >= UINT32_MAX - || !(functions = wasm_malloc((uint32)total_size))) { + || !(functions = wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "Instantiate function failed: " "allocate memory failed."); @@ -373,7 +375,7 @@ static void globals_deinstantiate(WASMGlobalInstance *globals) { if (globals) - wasm_free(globals); + wasm_runtime_free(globals); } /** @@ -392,7 +394,7 @@ globals_instantiate(const WASMModule *module, WASMGlobalInstance *globals, *global; if (total_size >= UINT32_MAX - || !(globals = wasm_malloc((uint32)total_size))) { + || !(globals = wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "Instantiate global failed: " "allocate memory failed."); @@ -505,7 +507,7 @@ static void export_functions_deinstantiate(WASMExportFuncInstance *functions) { if (functions) - wasm_free(functions); + wasm_runtime_free(functions); } /** @@ -523,7 +525,7 @@ export_functions_instantiate(const WASMModule *module, uint64 total_size = sizeof(WASMExportFuncInstance) * (uint64)export_func_count; if (total_size >= UINT32_MAX - || !(export_func = export_funcs = wasm_malloc((uint32)total_size))) { + || !(export_func = export_funcs = wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "Instantiate export function failed: " "allocate memory failed."); @@ -623,7 +625,7 @@ wasm_instantiate(WASMModule *module, return NULL; /* Allocate the memory */ - if (!(module_inst = wasm_malloc((uint32)sizeof(WASMModuleInstance)))) { + if (!(module_inst = wasm_runtime_malloc((uint32)sizeof(WASMModuleInstance)))) { set_error_buf(error_buf, error_buf_size, "Instantiate module failed: allocate memory failed."); globals_deinstantiate(globals); @@ -850,7 +852,7 @@ wasm_deinstantiate(WASMModuleInstance *module_inst) globals_deinstantiate(module_inst->globals); export_functions_deinstantiate(module_inst->export_functions); - wasm_free(module_inst); + wasm_runtime_free(module_inst); } WASMFunctionInstance* @@ -1128,8 +1130,8 @@ wasm_enlarge_memory(WASMModuleInstance *module, uint32 inc_page_count) return false; } - if (!(new_memory = wasm_realloc(memory, (uint32)total_size))) { - if (!(new_memory = wasm_malloc((uint32)total_size))) { + if (!(new_memory = wasm_runtime_realloc(memory, (uint32)total_size))) { + if (!(new_memory = wasm_runtime_malloc((uint32)total_size))) { wasm_set_exception(module, "fail to enlarge memory."); return false; } @@ -1138,7 +1140,7 @@ wasm_enlarge_memory(WASMModuleInstance *module, uint32 inc_page_count) (uint8*)memory, total_size_old); memset((uint8*)new_memory + total_size_old, 0, (uint32)total_size - total_size_old); - wasm_free(memory); + wasm_runtime_free(memory); } new_memory->cur_page_count = total_page_count; diff --git a/core/iwasm/libraries/libc-wasi/libc_wasi_wrapper.c b/core/iwasm/libraries/libc-wasi/libc_wasi_wrapper.c index 724fe61c9..915788e97 100644 --- a/core/iwasm/libraries/libc-wasi/libc_wasi_wrapper.c +++ b/core/iwasm/libraries/libc-wasi/libc_wasi_wrapper.c @@ -78,12 +78,12 @@ wasi_args_get(wasm_exec_env_t exec_env, int32 *argv_offsets, char *argv_buf) total_size = sizeof(char*) * ((uint64)argc + 1); if (total_size >= UINT32_MAX - || !(argv = bh_malloc((uint32)total_size))) + || !(argv = wasm_runtime_malloc((uint32)total_size))) return (wasi_errno_t)-1; err = wasmtime_ssp_args_get(wasi_ctx->argv_environ, argv, argv_buf); if (err) { - bh_free(argv); + wasm_runtime_free(argv); return err; } @@ -91,7 +91,7 @@ wasi_args_get(wasm_exec_env_t exec_env, int32 *argv_offsets, char *argv_buf) argv_offsets[i] = addr_native_to_app(argv[i]); argv_offsets[argc] = 0; - bh_free(argv); + wasm_runtime_free(argv); return 0; } @@ -171,12 +171,12 @@ wasi_environ_get(wasm_exec_env_t exec_env, total_size = sizeof(char*) * (((uint64)environ_count + 1)); if (total_size >= UINT32_MAX - || !(environs = bh_malloc((uint32)total_size))) + || !(environs = wasm_runtime_malloc((uint32)total_size))) return (wasi_errno_t)-1; err = wasmtime_ssp_environ_get(wasi_ctx->argv_environ, environs, environ_buf); if (err) { - bh_free(environs); + wasm_runtime_free(environs); return err; } @@ -184,7 +184,7 @@ wasi_environ_get(wasm_exec_env_t exec_env, environ_offsets[i] = addr_native_to_app(environs[i]); environ_offsets[environ_count] = 0; - bh_free(environs); + wasm_runtime_free(environs); return 0; } 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 cf302f834..ca85b09e1 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 @@ -47,7 +47,6 @@ #include "str.h" #include "bh_common.h" -#include "bh_memory.h" #if 0 /* TODO: -std=gnu99 causes compile error, comment them first */ // struct iovec must have the same layout as __wasi_iovec_t. @@ -278,7 +277,7 @@ static bool fd_prestats_grow( size *= 2; // Grow the file descriptor table's allocation. - struct fd_prestat *prestats = bh_malloc((uint32)(sizeof(*prestats) * size)); + struct fd_prestat *prestats = wasm_runtime_malloc((uint32)(sizeof(*prestats) * size)); if (prestats == NULL) return false; @@ -288,7 +287,7 @@ static bool fd_prestats_grow( } if (pt->prestats) - bh_free(pt->prestats); + wasm_runtime_free(pt->prestats); // Mark all new file descriptors as unused. for (size_t i = pt->size; i < size; ++i) @@ -408,7 +407,7 @@ static bool fd_table_grow( size *= 2; // Grow the file descriptor table's allocation. - struct fd_entry *entries = bh_malloc((uint32)(sizeof(*entries) * size)); + struct fd_entry *entries = wasm_runtime_malloc((uint32)(sizeof(*entries) * size)); if (entries == NULL) return false; @@ -418,7 +417,7 @@ static bool fd_table_grow( } if (ft->entries) - bh_free(ft->entries); + wasm_runtime_free(ft->entries); // Mark all new file descriptors as unused. for (size_t i = ft->size; i < size; ++i) @@ -434,7 +433,7 @@ static __wasi_errno_t fd_object_new( __wasi_filetype_t type, struct fd_object **fo ) TRYLOCKS_SHARED(0, (*fo)->refcount) { - *fo = bh_malloc(sizeof(**fo)); + *fo = wasm_runtime_malloc(sizeof(**fo)); if (*fo == NULL) return __WASI_ENOMEM; refcount_init(&(*fo)->refcount, 1); @@ -585,7 +584,7 @@ static void fd_object_release( CLOSE_NON_STD_FD(fd_number(fo)); break; } - bh_free(fo); + wasm_runtime_free(fo); } } @@ -878,7 +877,7 @@ __wasi_errno_t wasmtime_ssp_fd_pread( size_t totalsize = 0; for (size_t i = 0; i < iovcnt; ++i) totalsize += iov[i].buf_len; - char *buf = bh_malloc(totalsize); + char *buf = wasm_runtime_malloc(totalsize); if (buf == NULL) { fd_object_release(fo); return __WASI_ENOMEM; @@ -888,7 +887,7 @@ __wasi_errno_t wasmtime_ssp_fd_pread( ssize_t len = pread(fd_number(fo), buf, totalsize, offset); fd_object_release(fo); if (len < 0) { - bh_free(buf); + wasm_runtime_free(buf); return convert_errno(errno); } @@ -903,7 +902,7 @@ __wasi_errno_t wasmtime_ssp_fd_pread( break; } } - bh_free(buf); + wasm_runtime_free(buf); *nread = len; return 0; } @@ -940,7 +939,7 @@ __wasi_errno_t wasmtime_ssp_fd_pwrite( size_t totalsize = 0; for (size_t i = 0; i < iovcnt; ++i) totalsize += iov[i].buf_len; - char *buf = bh_malloc(totalsize); + char *buf = wasm_runtime_malloc(totalsize); if (buf == NULL) { fd_object_release(fo); return __WASI_ENOMEM; @@ -954,7 +953,7 @@ __wasi_errno_t wasmtime_ssp_fd_pwrite( // Perform a single write operation. len = pwrite(fd_number(fo), buf, totalsize, offset); - bh_free(buf); + wasm_runtime_free(buf); } #endif fd_object_release(fo); @@ -1377,23 +1376,23 @@ static char *readlinkat_dup( size_t len_org = len; for (;;) { - char *newbuf = bh_malloc((uint32)len); + char *newbuf = wasm_runtime_malloc((uint32)len); if (newbuf == NULL) { if (buf) - bh_free(buf); + wasm_runtime_free(buf); return NULL; } if (buf != NULL) { bh_memcpy_s(newbuf, (uint32)len, buf, (uint32)len_org); - bh_free(buf); + wasm_runtime_free(buf); } buf = newbuf; ssize_t ret = readlinkat(fd, path, buf, len); if (ret < 0) { - bh_free(buf); + wasm_runtime_free(buf); return NULL; } if ((size_t)ret + 1 < len) { @@ -1444,7 +1443,7 @@ static __wasi_errno_t path_get( __wasi_errno_t error = fd_object_get(curfds, &fo, fd, rights_base, rights_inheriting); if (error != 0) { - bh_free(path); + wasm_runtime_free(path); return error; } @@ -1585,7 +1584,7 @@ static __wasi_errno_t path_get( // when called on paths like ".", "a/..", but also if the path // had trailing slashes and the caller is not interested in the // name of the pathname component. - bh_free(paths_start[0]); + wasm_runtime_free(paths_start[0]); pa->path = "."; pa->path_start = NULL; goto success; @@ -1593,7 +1592,7 @@ static __wasi_errno_t path_get( // Finished expanding symlink. Continue processing along the // original path. - bh_free(paths_start[curpath--]); + wasm_runtime_free(paths_start[curpath--]); } continue; @@ -1601,7 +1600,7 @@ static __wasi_errno_t path_get( // Prevent infinite loops by placing an upper limit on the number of // symlink expansions. if (++expansions == 128) { - bh_free(symlink); + wasm_runtime_free(symlink); error = __WASI_ELOOP; goto fail; } @@ -1609,10 +1608,10 @@ static __wasi_errno_t path_get( if (*paths[curpath] == '\0') { // The original path already finished processing. Replace it by // this symlink entirely. - bh_free(paths_start[curpath]); + wasm_runtime_free(paths_start[curpath]); } else if (curpath + 1 == sizeof(paths) / sizeof(paths[0])) { // Too many nested symlinks. Stop processing. - bh_free(symlink); + wasm_runtime_free(symlink); error = __WASI_ELOOP; goto fail; } else { @@ -1644,7 +1643,7 @@ fail: for (size_t i = 1; i <= curfd; ++i) close(fds[i]); for (size_t i = 0; i <= curpath; ++i) - bh_free(paths_start[i]); + wasm_runtime_free(paths_start[i]); fd_object_release(fo); return error; #endif @@ -1668,7 +1667,7 @@ static __wasi_errno_t path_get_nofollow( static void path_put( struct path_access *pa ) UNLOCKS(pa->fd_object->refcount) { - bh_free(pa->path_start); + wasm_runtime_free(pa->path_start); if (fd_number(pa->fd_object) != pa->fd) close(pa->fd); fd_object_release(pa->fd_object); @@ -1770,12 +1769,12 @@ __wasi_errno_t wasmtime_ssp_path_link( rwlock_rdlock(&prestats->lock); if (!validate_path(target, prestats)) { rwlock_unlock(&prestats->lock); - bh_free(target); + wasm_runtime_free(target); return __WASI_EBADF; } rwlock_unlock(&prestats->lock); ret = symlinkat(target, new_pa.fd, new_pa.path); - bh_free(target); + wasm_runtime_free(target); } } path_put(&old_pa); @@ -2312,21 +2311,21 @@ __wasi_errno_t wasmtime_ssp_path_symlink( __wasi_errno_t error = path_get_nofollow(curfds, &pa, fd, new_path, new_path_len, __WASI_RIGHT_PATH_SYMLINK, 0, true); if (error != 0) { - bh_free(target); + wasm_runtime_free(target); return error; } rwlock_rdlock(&prestats->lock); if (!validate_path(target, prestats)) { rwlock_unlock(&prestats->lock); - bh_free(target); + wasm_runtime_free(target); return __WASI_EBADF; } rwlock_unlock(&prestats->lock); int ret = symlinkat(target, pa.fd, pa.path); path_put(&pa); - bh_free(target); + wasm_runtime_free(target); if (ret < 0) return convert_errno(errno); return 0; @@ -2479,12 +2478,12 @@ __wasi_errno_t wasmtime_ssp_poll_oneoff( // __WASI_EVENTTYPE_FD_WRITE entries. There may be up to one // __WASI_EVENTTYPE_CLOCK entry to act as a timeout. These are also // the subscriptions generate by cloudlibc's poll() and select(). - struct fd_object **fos = bh_malloc((uint32)(nsubscriptions * sizeof(*fos))); + struct fd_object **fos = wasm_runtime_malloc((uint32)(nsubscriptions * sizeof(*fos))); if (fos == NULL) return __WASI_ENOMEM; - struct pollfd *pfds = bh_malloc((uint32)(nsubscriptions * sizeof(*pfds))); + struct pollfd *pfds = wasm_runtime_malloc((uint32)(nsubscriptions * sizeof(*pfds))); if (pfds == NULL) { - bh_free(fos); + wasm_runtime_free(fos); return __WASI_ENOMEM; } @@ -2623,8 +2622,8 @@ __wasi_errno_t wasmtime_ssp_poll_oneoff( for (size_t i = 0; i < nsubscriptions; ++i) if (fos[i] != NULL) fd_object_release(fos[i]); - bh_free(fos); - bh_free(pfds); + wasm_runtime_free(fos); + wasm_runtime_free(pfds); return error; } @@ -2866,12 +2865,12 @@ bool argv_environ_init(struct argv_environ_values *argv_environ, total_size = sizeof(char *) * (uint64)argv_offsets_len; if (total_size >= UINT32_MAX - || !(argv_environ->argv = bh_malloc((uint32)total_size))) + || !(argv_environ->argv = wasm_runtime_malloc((uint32)total_size))) return false; if (argv_buf_len >= UINT32_MAX - || !(argv_environ->argv_buf = bh_malloc((uint32)argv_buf_len))) + || !(argv_environ->argv_buf = wasm_runtime_malloc((uint32)argv_buf_len))) goto fail1; for (i = 0; i < argv_offsets_len; ++i) { @@ -2885,11 +2884,11 @@ bool argv_environ_init(struct argv_environ_values *argv_environ, total_size = sizeof(char *) * (uint64)environ_offsets_len; if (total_size >= UINT32_MAX - || !(argv_environ->environ = bh_malloc((uint32)total_size))) + || !(argv_environ->environ = wasm_runtime_malloc((uint32)total_size))) goto fail2; if (environ_buf_len >= UINT32_MAX - || !(argv_environ->environ_buf = bh_malloc((uint32)environ_buf_len))) + || !(argv_environ->environ_buf = wasm_runtime_malloc((uint32)environ_buf_len))) goto fail3; for (i = 0; i < environ_offsets_len; ++i) { @@ -2901,11 +2900,11 @@ bool argv_environ_init(struct argv_environ_values *argv_environ, return true; fail3: - bh_free(argv_environ->environ); + wasm_runtime_free(argv_environ->environ); fail2: - bh_free(argv_environ->argv_buf); + wasm_runtime_free(argv_environ->argv_buf); fail1: - bh_free(argv_environ->argv); + wasm_runtime_free(argv_environ->argv); memset(argv_environ, 0, sizeof(struct argv_environ_values)); return false; @@ -2914,13 +2913,13 @@ fail1: void argv_environ_destroy(struct argv_environ_values *argv_environ) { if (argv_environ->argv_buf) - bh_free(argv_environ->argv_buf); + wasm_runtime_free(argv_environ->argv_buf); if (argv_environ->argv) - bh_free(argv_environ->argv); + wasm_runtime_free(argv_environ->argv); if (argv_environ->environ_buf) - bh_free(argv_environ->environ_buf); + wasm_runtime_free(argv_environ->environ_buf); if (argv_environ->environ) - bh_free(argv_environ->environ); + wasm_runtime_free(argv_environ->environ); } void fd_table_destroy(struct fd_table *ft) @@ -2931,7 +2930,7 @@ void fd_table_destroy(struct fd_table *ft) fd_object_release(ft->entries[i].object); } } - bh_free(ft->entries); + wasm_runtime_free(ft->entries); } } @@ -2940,9 +2939,9 @@ void fd_prestats_destroy(struct fd_prestats *pt) if (pt->prestats) { for (uint32 i = 0; i < pt->size; i++) { if (pt->prestats[i].dir != NULL) { - bh_free((void*)pt->prestats[i].dir); + wasm_runtime_free((void*)pt->prestats[i].dir); } } - bh_free(pt->prestats); + wasm_runtime_free(pt->prestats); } } diff --git a/core/shared/include/bh_common.h b/core/shared/include/bh_common.h index 831ffe8a4..7e78e3e82 100644 --- a/core/shared/include/bh_common.h +++ b/core/shared/include/bh_common.h @@ -6,12 +6,7 @@ #ifndef _BH_COMMON_H #define _BH_COMMON_H -#include "bh_assert.h" #include "bh_platform.h" -#include "bh_list.h" - -typedef void (*bh_print_function_t)(const char* message); -void bh_set_print_function(bh_print_function_t pf); #define bh_memcpy_s(dest, dlen, src, slen) do { \ int _ret = slen == 0 ? 0 : b_memcpy_s (dest, dlen, src, slen); \ @@ -31,4 +26,14 @@ void bh_set_print_function(bh_print_function_t pf); bh_assert (_ret == 0); \ } while (0) +int b_memcpy_s(void * s1, unsigned int s1max, const void * s2, unsigned int n); +int b_strcat_s(char * s1, size_t s1max, const char * s2); +int b_strcpy_s(char * s1, size_t s1max, const char * s2); + +/* strdup with string allocated by BH_MALLOC */ +char *bh_strdup(const char *s); + +/* strdup with string allocated by WA_MALLOC */ +char *wa_strdup(const char *s); + #endif diff --git a/core/shared/include/bh_memory.h b/core/shared/include/bh_memory.h deleted file mode 100644 index 182e0db21..000000000 --- a/core/shared/include/bh_memory.h +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _BH_MEMORY_H -#define _BH_MEMORY_H - -#ifdef __cplusplus -extern "C" { -#endif - -#define BH_KB (1024) -#define BH_MB ((BH_KB)*1024) -#define BH_GB ((BH_MB)*1024) - -/** - * Initialize memory allocator with a pool, the bh_malloc/bh_free function - * will malloc/free memory from the pool - * - * @param mem the pool buffer - * @param bytes the size bytes of the buffer - * - * @return 0 if success, -1 otherwise - */ -int bh_memory_init_with_pool(void *mem, unsigned int bytes); - -/** - * Initialize memory allocator with memory allocator, the bh_malloc/bh_free - * function will malloc/free memory with the allocator passed - * - * @param malloc_func the malloc function - * @param free_func the free function - * - * @return 0 if success, -1 otherwise - */ -int bh_memory_init_with_allocator(void *malloc_func, void *free_func); - -/** - * Destroy memory - */ -void bh_memory_destroy(); - -/** - * Get the pool size of memory, if memory is initialized with allocator, - * return 1GB by default. - */ -unsigned bh_memory_pool_size(); - -#if BEIHAI_ENABLE_MEMORY_PROFILING == 0 - -/** - * This function allocates a memory chunk from system - * - * @param size bytes need allocate - * - * @return the pointer to memory allocated - */ -void* bh_malloc(unsigned int size); - -/** - * This function reallocates a memory chunk from system - * - * @param ptr the original memory - * @param size bytes need allocate - * - * @return the pointer to memory allocated - */ -void* bh_realloc(void *ptr, unsigned int size); - -/** - * This function frees memory chunk - * - * @param ptr the pointer to memory need free - */ -void bh_free(void *ptr); - -#else - -void* bh_malloc_profile(const char *file, int line, const char *func, unsigned int size); -void* bh_realloc_profile(const char *file, int line, const char *func, void *ptr, unsigned int size); -void bh_free_profile(const char *file, int line, const char *func, void *ptr); - -#define bh_malloc(size) bh_malloc_profile(__FILE__, __LINE__, __func__, size) -#define bh_realloc(ptr, size) bh_malloc_profile(__FILE__, __LINE__, __func__, ptr, size) -#define bh_free(ptr) bh_free_profile(__FILE__, __LINE__, __func__, ptr) - -/** - * Print current memory profiling data - * - * @param file file name of the caller - * @param line line of the file of the caller - * @param func function name of the caller - */ -void memory_profile_print(const char *file, int line, const char *func, int alloc); - -/** - * Summarize memory usage and print it out - * Can use awk to analyze the output like below: - * awk -F: '{print $2,$4,$6,$8,$9}' OFS="\t" ./out.txt | sort -n -r -k 1 - */ -void memory_usage_summarize(); - -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* #ifndef _BH_MEMORY_H */ - diff --git a/core/shared/include/bh_queue.h b/core/shared/include/bh_queue.h index 92e9b014e..41792012f 100644 --- a/core/shared/include/bh_queue.h +++ b/core/shared/include/bh_queue.h @@ -20,8 +20,8 @@ typedef struct bh_queue bh_queue; typedef void (*bh_queue_handle_msg_callback)(void *message, void *arg); -#define bh_queue_malloc bh_malloc -#define bh_queue_free bh_free +#define bh_queue_malloc BH_MALLOC +#define bh_queue_free BH_FREE #define bh_queue_mutex korp_mutex #define bh_queue_sem korp_sem diff --git a/core/shared/include/bni.h b/core/shared/include/bni.h deleted file mode 100644 index 437cf41d7..000000000 --- a/core/shared/include/bni.h +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ -/** - * @file bni.h - * @date Mon Jul 2 16:54:58 2012 - * - * @brief Beihai native interface. - */ - -#ifndef BNI_H -#define BNI_H - -#include "bh_types.h" - -/* Primitive types */ -typedef uint8 jboolean; -typedef int8 jbyte; -typedef uint16 jchar; -typedef int16 jshort; -typedef int32 jint; -typedef int64 jlong; -typedef float jfloat; -typedef double jdouble; -typedef jint jsize; - -/* Predefined Java class types. */ -struct _jobject; -typedef struct _jobject *jobject; -struct _jclass; -typedef struct _jclass *jclass; -struct _jstring; -typedef struct _jstring *jstring; - -/* Values of jboolean: */ -#define BNI_FALSE 0 -#define BNI_TRUE 1 - -/** - * Return the length of the array object. - * - * @param array Java array object - * - * @return the length of the Java array - */ -#define bni_array_length(array) ((jsize)((uint32)(array)->__length >> 2)) - -/** - * Return the address of the first element of array object. - * - * @param array Java array object - * - * @return the address of the first element of array object - */ -#define bni_array_elem(array) ((array)->__elem) - -/** - * Find the Java class with given class name. - * - * @param name Java class name - * - * @return class object of the Java class if found, NULL otherwise - * - * @throws OutOfMemoryError if VM runs out of memory. - */ -jclass -bni_find_class(const char *name); - -/** - * Throw an exception of given class with message. - * - * @param clazz class object of a subclass of java.lang.Throwable - * @param msg message for the exception or NULL if no message - * - * @return 0 if succeeds, nonzero otherwise - */ -jint -bni_throw_new(jclass clazz, const char *msg); - -/** - * Throw a NullPointerException. - * - * @throws NullPointerException - */ -void -bni_throw_npe(void); - -/** - * Throw an ArrayIndexOutOfBoundsException - * - * @param index the index used to access the array - * - * @throws ArrayIndexOutOfBoundsException - */ -void -bni_throw_aioobe(int index); - -/** - * Determine whether an exception is being thrown. - * - * @return exception object if exception is thrown, NULL otherwise - */ -jobject -bni_exception_occurred(void); - -/** - * Print the current exception to error-reporting channel. - */ -void -bni_exception_describe(void); - -/** - * Clear the currently thrown exception. - */ -void -bni_exception_clear(void); - -/** - * Return the Unicode character number of a string. - * - * @param str Java string object - * - * @return the Unicode character number of the string - */ -jsize -bni_string_length(jstring str); - -/** - * Return the length in bytes of the modified UTF-8 representation of - * a string. - * - * @param str Java string object - * @param start start offset in the string - * @param len number of Unicode characters - * - * @return the UTF-8 length of the string - * - * @throws StringIndexOutOfBoundsException on index overflow. - */ -jsize -bni_string_utf_length(jstring str, jsize start, jsize len); - -/** - * Copies len number of Unicode characters beginning at offset start - * to the given buffer buf. - * - * @param str Java string object - * @param start start offset in the string - * @param len number of Unicode characters to copy - * @param buf buffer for storing the result - */ -void -bni_string_region(jstring str, jsize start, jsize len, jchar *buf); - -/** - * Translates len number of Unicode characters beginning at offset - * start into modified UTF-8 encoding and place the result in the - * given buffer buf. - * - * @param str Java string object - * @param start start offset in the string - * @param len number of Unicode characters to copy - * @param buf buffer for storing the result - * - * @throws StringIndexOutOfBoundsException on index overflow. - */ -void -bni_string_utf_region(jstring str, jsize start, jsize len, char *buf); - -/** - * Translate Unicode characters into modified UTF-8 encoding and return - * the result. - * - * @param str Java string object - * - * @return the UTF-8 encoding string if succeeds, NULL otherwise - */ -char * -bni_string_get_utf_chars(jstring str); - -/** - * Get the given Java object's class index. - * - * @param obj Java object - * - * @return -1 if obj is an array, class index of the object otherwise - */ -jint -bni_object_class_index(jobject obj); - -/** - * Allocate memory from the current instance's private heap. - * - * @param size bytes to allocate - * - * @return pointer to the allocated memory - * - * @throws OutOfMemoryError if VM runs out of memory. - */ -void* -bni_malloc(unsigned size); - -/** - * Allocate memory from the current instance's private heap and clear - * to zero. - * - * @param size bytes to allocate - * - * @return pointer to the allocated memory - * - * @throws OutOfMemoryError if VM runs out of memory. - */ -void* -bni_calloc(unsigned size); - -/** - * Free the memory allocated from the current instance's private heap. - * - * @param ptr pointer to the memory in current instance's private heap - */ -void -bni_free(void *ptr); - -#endif diff --git a/core/shared/include/jeff_export.h b/core/shared/include/jeff_export.h deleted file mode 100644 index e9f4128dc..000000000 --- a/core/shared/include/jeff_export.h +++ /dev/null @@ -1,604 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ -/** - * @file jeff-export.h - * @date Wed Aug 3 18:17:30 2011 - * - * @brief Exported interface for operating or executing JEFF files. - * All interface names start with "jeff_", which is the namespace name - * of this module. - */ - -#ifndef JEFF_EXPORT_H -#define JEFF_EXPORT_H - -#include "bni.h" -#include "bh_types.h" - -/******************************************************************** - * Exported internal types - ********************************************************************/ - -/** - * JEFF file handle type - */ -struct JeffFileHeaderLinked; -typedef struct JeffFileHeaderLinked *jeff_file_t; - -/** - * JEFF class type - */ -struct JeffClassHeaderLinked; -typedef struct JeffClassHeaderLinked *jeff_class_t; - -/** - * VM instance handle type - */ -struct JeffInstanceLocalRoot; -typedef struct JeffInstanceLocalRoot *jeff_instance_t; - -/** - * Record of one native method's definition. - */ -struct JeffNativeMethodDef { - /* Mangled name of the native method. NULL for initialization - functions. */ - const char *mangled_name; - - /* Points to the native C function. */ - void (*func_ptr)(uint32 *); - - /* Return size type of the native function. */ - uint32 return_size_type; -}; - -/******************************************************************** - * Interface for operating global environment of the JEFF VM - ********************************************************************/ - -/** - * Load the core library from the given file buffer and initialize the - * runtime environment (global objects etc.) of the VM. The thread - * calls this function becomes the supervisor thread, which belongs to - * a unique supervisor instance. Currently, if this init failed, - * partially initialized states of the VM runtime environment won't be - * cleaned up, so the VM must be shutdown and restarted. method_defs - * points to an array of native method definition records. - * Initialization functions must be in the front of the array and - * following native method definitions must be sorted by their mangled - * names. - * - * @param file the JEFF file of the core library - * @param file_size the size of the JEFF file of the core library - * @param method_defs native method definition records - * @param method_defs_num number of native method records - * @param heap the heap for the current (supervisor) instance - * - * @return true if succeeds, otherwise the error cannot be recovered - */ -bool -jeff_runtime_init(jeff_file_t file, unsigned file_size, - struct JeffNativeMethodDef *method_defs, unsigned method_defs_num, - void *heap); - -/** - * Load a JEFF file into the VM from the given file buffer. It can be - * called from any VM thread. - * - * @param file the JEFF file to be loaded - * @param size the size of the JEFF file - * @param is_library whether the JEFF file is a library - * @param allow_to_load a function that returns true if classes in the - * given package is allowed to be loaded. The NULL function pointer - * allows all packages. - * @param allow_to_link a function that returns true if classes in the - * given package is allowed to be linked to. The NULL function - * pointer allows all packages. - * - * @return true if succeeds, otherwise detailed error information is - * passed to vmci_diagnostic_print. The caller can catch it by - * implementing that function. - */ -bool -jeff_runtime_load(jeff_file_t file, unsigned size, bool is_library, - bool (*allow_to_load)(const uint8 *pname, unsigned len), - bool (*allow_to_link)(const uint8 *pname, unsigned plen, - const uint8 *cname, unsigned clen)); - -/** - * Unload a JEFF file from the VM. All resources related to the JEFF - * file except the JEFF file itself are released. It can be called - * from any VM thread. - * - * @param file the JEFF file to be unloaded - * - * @return true if succeeds, otherwise detailed error information is - * passed to vmci_diagnostic_print. The caller can catch it by - * implementing that function. - */ -bool -jeff_runtime_unload(jeff_file_t file); - -/** - * Return the JEFF file with the given file uid. - * - * @param fuid the unique id of a loaded JEFF file - * - * @return the JEFF file is exists, otherwise NULL - */ -jeff_file_t -jeff_runtime_fuid_to_file(unsigned fuid); - -/** - * Return the file uid of the given JEFF file. - * - * @param file a loaded JEFF file - * - * @return the unique id of the given JEFF file - */ -unsigned -jeff_runtime_file_to_fuid(jeff_file_t file); - -/** - * Create a supervisor thread belonging to the supervisor instance. - * Threads that may interact with VM core must be either the main - * thread of supervisor instance (which calls jeff_runtime_init) or - * created by this function so that VM core required data structures - * can be set up correctly. - * - * @param start_routine the start routine of the new thread - * @param arg argument to the start routine - * - * @return true if succeeds, false otherwise - */ -bool -jeff_runtime_create_supervisor_thread(void* (*start_routine)(void *), - void *arg); - -/** - * Create a supervisor thread belonging to the supervisor instance. - * Threads that may interact with VM core must be either the main - * thread of supervisor instance (which calls jeff_runtime_init) or - * created by this function so that VM core required data structures - * can be set up correctly. - * - * @param start_routine the start routine of the new thread - * @param arg argument to the start routine - * @param prio thread priority - * - * @return true if succeeds, false otherwise - */ -bool -jeff_runtime_create_supervisor_thread_with_prio(void* (*start_routine)(void *), - void *arg, int prio); - -/******************************************************************** - * Interface for operating instance local environment - ********************************************************************/ - -/** - * Create a VM instance with the given JEFF file as its main file, - * (i.e. the file containing the main class of the VM instance). This - * function can be called from any VM thread, but it must be isolated - * from JEFF file's unloading operation so that the main file won't be - * unloaded before it's locked by the new instance. All instance - * local memory except stacks of threads are allocated from the given - * heap. If succeeds, it increases reference count of the main_file - * and returns the handle of the new VM instance. The new instance's - * main thread will run the start_routine with argument arg. If the - * cleanup_routine is not NULL, it will be called after start_routine - * returns and just before the main thread exits. It will also be - * called after the instance is destroied. It is guaranteed to be - * called exactly once no matter how the instance terminates. - * - * @param main_file the main JEFF file of the new instance - * @param heap the private heap of the new instance - * @param stack_depth the maximal nesting levels of Java methods of - * the new instance. It must be <= 16 * 1024. Otherwise the instance - * creation will fail. - * @param start_routine start routine of the main thread. Don't - * destroy the heap or inform other thread to do this at the end of - * this routine since after it returns, VM core will call destroy - * functions on objects allocated in this heap (e.g. locks and - * condition variables). Do the destroying or informing of destroying - * in the cleanup_routine. - * @param arg the instance argument that will be passed to the start - * routine. It can be get or set by jeff_runtime_get_instance_arg and - * jeff_runtime_set_instance arg from threads of the instance. The - * caller can use it to store instance local data. - * @param cleanup_routine the optional cleanup routine for the - * instance, which may be NULL. It may be executed in the end of the - * main thread of the created instance by this function if this - * instance exits normally, or it may be executed in a thread of other - * instance in case this instance is being killed by that instance. - * In both cases, this routine regards it is executed in a thread of - * this instance (the instance created by this function) because - * jeff_runtime_get_instance_arg will always return the argument of - * this instance. - * - * @return the VM instance handle if succeeds, NULL otherwise - */ -jeff_instance_t -jeff_runtime_create_instance(jeff_file_t main_file, void *heap, - unsigned stack_depth, void* (*start_routine)(void *), void *arg, - void (*cleanup_routine)(void)); - -/** - * Destroy the given VM instance and decrease the reference count of - * its main file and all explicitly used JEFF files. It can be called - * from any VM thread. If there are alive threads of the instance, - * they will be terminated mandatorily and then the cleanup routine is - * called if it's not NULL. - * - * @param handle the handle of the instance to be destroyed - */ -void -jeff_runtime_destroy_instance(jeff_instance_t handle); - -/** - * Retrieve the current instance's argument. - * - * @return the current instance's argument - */ -void* -jeff_runtime_get_instance_arg(void); - -/** - * Set the current instance's argument. - * - * @return the new argument for the current instance - */ -void -jeff_runtime_set_instance_arg(void *arg); - -/** - * Retrieve the current instance's heap. - * - * @return the current instance's heap - */ -void* -jeff_runtime_get_instance_heap(void); - -/** - * Suspend all threads of the given VM instance. This function can - * only be called from thread that is not of the given VM instance. - * - * @param handle the handle of the instance to be suspended - */ -void -jeff_runtime_suspend_instance(jeff_instance_t handle); - -/** - * Resume all threads of the given VM instance. This function can - * only be called from thread that is not of the given VM instance. - * - * @param handle the handle of the instance to be resumed - */ -void -jeff_runtime_resume_instance(jeff_instance_t handle); - -/** - * Interrupt all threads of the given VM instance. This function can - * only be called from thread that is not of the given VM instance. - * - * @param handle the handle of the instance to be interrupted - * @param by_force whether the interruption is by force - */ -void -jeff_runtime_interrupt_instance(jeff_instance_t handle, bool by_force); - -/** - * Wait for the given VM instance to terminate. - * - * @param ilr the VM instance to be waited for - * @param mills wait millseconds to return - */ -void -jeff_runtime_wait_for_instance(jeff_instance_t ilr, int mills); - -/******************************************************************** - * Interface for operating thread local environment - ********************************************************************/ - -/** - * Return true if there is an uncaught exception (thrown during - * running an application or applet command). - * - * @return true if there is an uncaught exception - */ -bool -jeff_runtime_check_uncaught_exception(void); - -/** - * Print qualified name of the uncaught exception (and stack trace if - * enabled) by calling vmci_diagnostic_print. - */ -void -jeff_runtime_print_uncaught_exception(void); - -/** - * Clear the uncaught exception. - */ -void -jeff_runtime_reset_uncaught_exception(void); - -/** - * Change current thread to a safe state (VMWAIT). After calling this - * and before calling jeff_runtime_exit_safe_state, all operations - * must be safe, i.e. no GC or system level resource operations are - * allowed because in a safe state, the VM instance is assumed to be - * able to perform GC, JDWP or termination at any time. Usually, this - * function is called just before the native code is going to wait for - * something and the exiting safe state function is called just after - * the waiting returns. - */ -void -jeff_runtime_enter_safe_state(void); - -/** - * Change current thread to an unsafe state (RUNNING) so that unsafe - * operations can also be done. - */ -void -jeff_runtime_exit_safe_state(void); - -/** - * Set thread local error code for the current thread. - * - * @param code the error code to be set - */ -void -jeff_runtime_set_error(unsigned code); - -/** - * Get the last error code of current thread. - * - * @return the last error code of current thread - */ -unsigned -jeff_runtime_get_error(void); - -/******************************************************************** - * Interface for GC support - ********************************************************************/ - -/** - * Traverse all objects of the given heap that are global or locate in - * threads' frames and return them by calling vmci_gc_rootset_elem. - * This function will suspend all threads except the current one of - * the VM instance owning the given heap before traversing. It - * traverses either all or none of the rootset objects, and returns - * true and false respectively. If it returns false, the GC process - * shouldn't proceed and is not necessary to unmark anything because - * no objects are marked. The function jeff_runtime_gc_finished must - * be called if and only if this function returns true so as to resume - * threads that are suspended during GC process. - * - * @param heap the heap for which rootset objects are looked up - * - * @return true if succeeds, false otherwise - */ -bool -jeff_runtime_traverse_gc_rootset(void *heap); - -/** - * Get the reference offset table of the given object. If the - * returned value R >= 0, *ret points to the reference offset table of - * the object and R is the number of offsets in the table. Otherwise, - * if the returned value R < 0, all reference fields of the object - * must be in a continuous region (usually the object is an array), - * then *ret is the offset to the first field in the region and R is - * the number of such fields in the region. - * - * @param obj pointer to the Java object - * @param ret points to a pointer for storing the reference offset - * table if return value >= 0, or for storing the offset to the first - * object reference in the Java object if return value < 0 - * - * @return number of offsets in the reference_offset table if >= 0, or - * number of object references in the object if < 0 - */ -int -jeff_object_get_reference_offsets(const jobject obj, uint16 **ret); - -/** - * Inform the containing VM instance that GC has finished and all - * suspended threads can be resumed. This function must be called if - * and only if jeff_runtime_traverse_gc_rootset returns true. - */ -void -jeff_runtime_gc_finished(void); - -/******************************************************************** - * Interface for tooling support - ********************************************************************/ - -/** - * This function is used to suspend the main thread of VM instance so - * that debugger can have chance to connect to the VM instance, set - * breakpoints and do any other debug settings. It must be called - * from the main thread of VM instance at the point just after VM - * instance initialization finishes and just before application code - * is to be executed. - */ -void -jeff_tool_suspend_self(void); - -/** - * Start up tool agent thread for the given VM instance. It can be - * called from any VM thread. - * - * @param handle the VM instance for which tool agent is started up - * @param queue queue of the tool agent - * @return true if succeeds, false otherwise - */ -bool -jeff_tool_start_agent(jeff_instance_t handle, void *queue); - -/******************************************************************** - * Interface for toolkit support - ********************************************************************/ - -/** - * Return the JEFF class pointer of the given class name. - * - * @param class_name the qualified class name - * - * @return the JEFF class pointer - */ -jeff_class_t -jeff_tool_get_jeff_class(const char *class_name); - -/** - * Get the mangled class name of the given class. - * - * @param clz the JEFF class - * @param buf buffer for returning the mangled name - * @param buf_size size of the buffer - * - * @return actual size of the mangled class name including the - * terminating null byte - */ -unsigned -jeff_tool_get_mangled_class_name(jeff_class_t clz, char *buf, - unsigned buf_size); - -/** - * Get class index of given class in its containing JEFF file. - * - * @param clz the JEFF class - * - * @return class index in the containing JEFF file - */ -int -jeff_tool_get_class_index(jeff_class_t clz); - -/** - * Callback handler prototype for traversing fields of class. - * - * @param arg argument passed to the handler from caller - * @param access_flag access flag of the method - * @param name the field name - * @param descriptor mangled field type descriptor - * @param offset the offset of the field in the class - * @param size size of the field - */ -typedef void -(*JeffToolFieldHandler)(void *arg, unsigned access_flag, const char *name, - const char *descriptor, unsigned offset, unsigned size); - -/** - * Traverse all fields of the given class, including those inherited - * from super classes. The fields are traversed in the same order as - * the field layout of the class. - * - * @param arg argument to be passed to the handler - * @param clz the JEFF class - * @param instance instance fields or static fielts - * @param handler the callback handler for each field - */ -void -jeff_tool_foreach_field(void *arg, jeff_class_t clz, bool instance, - JeffToolFieldHandler handler); - -/** - * Callback handler prototype for traversing methods of class. - * - * @param arg argument passed to the handler from caller - * @param access_flag access flag of the method - * @param name mangled name of the method - * @param descriptor mangled method arguments descriptor - * @param retune_type mangled descriptor of method's return type - */ -typedef void -(*JeffToolMethodHandler)(void *arg, unsigned access_flag, const char *name, - const char *descriptor, const char *return_type); - -/** - * Traverse all methods of the given class. - * - * @param arg argument to be passed to the handler - * @param clz the JEFF class - * @param handler the callback handler for each method - */ -void -jeff_tool_foreach_method(void *arg, jeff_class_t clz, - JeffToolMethodHandler handler); - -/** - * Callback handler prototype for traversing classes of main file. - * - * @param arg argument passed to the handler from caller - * @param clz pointer to one class in the main file - */ -typedef void -(*JeffToolClassHandler)(void *arg, jeff_class_t clz); - -/** - * Traverse all classes of the main file. - * - * @param arg argument to be passed to the handler - * @param handler the callback handler for each class - */ -void -jeff_tool_foreach_class(void *arg, JeffToolClassHandler handler); - -/******************************************************************** - * Interface for executing applications - ********************************************************************/ - -/** - * Initialize global environment for executing Java applications. - * - * @return true if succeeds, false otherwise - */ -bool -jeff_application_env_init(void); - -/** - * Find the unique class containing a public static "main - * ([Ljava.lang.String;)V" method from the main JEFF file of the - * current instance and execute that method. - * - * @param argc the number of arguments - * @param argv the arguments array - * - * @return true if the main method is called, false otherwise (e.g. an - * exception occurs when preparing the arguments Java string array) - */ -bool -jeff_application_execute(int argc, char *argv[]); - -/******************************************************************** - * Interface for executing applets - ********************************************************************/ - -/** - * Initialize global environment for executing applets. - * - * @return true if succeeds, false otherwise - */ -bool -jeff_applet_env_init(void); - -/** - * Start to run from com.intel.runtime.core.RuntimeContext.main with a - * default message queue size and a default service class object. If - * the main JEFF file of the current VM instance contains exactly one - * class that is derived from com.intel.util.IntelApplet, then use it - * as the default service class. - * - * @param queue_size the default main message queue size - * @param default_service_class qualified class name of the default - * service class (entry point class), which must be in the main JEFF - * file. If NULL, find the default main class with rules described - * above. - * - * @return true if succeeds, false otherwise - */ -bool -jeff_applet_start(int queue_size, const char *default_service_class); - -#endif diff --git a/core/shared/mem-alloc/ems/ems_gc_internal.h b/core/shared/mem-alloc/ems/ems_gc_internal.h index 94efb60cb..ac153fa10 100644 --- a/core/shared/mem-alloc/ems/ems_gc_internal.h +++ b/core/shared/mem-alloc/ems/ems_gc_internal.h @@ -12,7 +12,6 @@ extern "C" { #include "bh_platform.h" #include "bh_thread.h" -#include "bh_memory.h" #include "bh_assert.h" #include "ems_gc.h" diff --git a/core/shared/mem-alloc/mem_alloc.cmake b/core/shared/mem-alloc/mem_alloc.cmake index 2a224bf52..be57f3794 100644 --- a/core/shared/mem-alloc/mem_alloc.cmake +++ b/core/shared/mem-alloc/mem_alloc.cmake @@ -9,8 +9,7 @@ include_directories(${MEM_ALLOC_DIR}) file (GLOB_RECURSE source_all ${MEM_ALLOC_DIR}/ems/*.c ${MEM_ALLOC_DIR}/tlsf/*.c - ${MEM_ALLOC_DIR}/mem_alloc.c - ${MEM_ALLOC_DIR}/bh_memory.c) + ${MEM_ALLOC_DIR}/mem_alloc.c) set (MEM_ALLOC_SHARED_SOURCE ${source_all}) diff --git a/core/shared/platform/CMakeLists.txt b/core/shared/platform/CMakeLists.txt deleted file mode 100755 index 7abefa2b3..000000000 --- a/core/shared/platform/CMakeLists.txt +++ /dev/null @@ -1,20 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -include_directories (./include ../include ./${WAMR_BUILD_PLATFORM}) - -add_definitions (-D__POSIX__ -D_XOPEN_SOURCE=600 -D_POSIX_C_SOURCE=200809L -D_BSD_SOURCE) - -file (GLOB_RECURSE source_all ${WAMR_BUILD_PLATFORM}/*.c) -add_library (supportlib ${source_all}) - -target_link_libraries (supportlib -pthread -lrt) - -if ("${CMAKE_BUILD_TYPE}" STREQUAL "Debug") - add_library (supportlib_ut ${source_all}) - - set_target_properties (supportlib_ut PROPERTIES COMPILE_DEFINITIONS BH_TEST=1) - - target_link_libraries (supportlib_ut -pthread -lrt) -endif () - diff --git a/core/shared/platform/Makefile b/core/shared/platform/Makefile deleted file mode 100644 index cd10597a1..000000000 --- a/core/shared/platform/Makefile +++ /dev/null @@ -1,4 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -obj-y += zephyr/ diff --git a/core/shared/platform/alios/bh_platform.c b/core/shared/platform/alios/bh_platform.c index 91a2af0cb..f209bac1b 100644 --- a/core/shared/platform/alios/bh_platform.c +++ b/core/shared/platform/alios/bh_platform.c @@ -4,7 +4,6 @@ */ #include "bh_platform.h" -#include "bh_memory.h" #include "bh_common.h" #include #include @@ -15,16 +14,33 @@ bh_platform_init() return 0; } +void * +os_malloc(unsigned size) +{ + return NULL; +} + +void * +os_realloc(void *ptr, unsigned size) +{ + return NULL; +} + +void +os_free(void *ptr) +{ +} + void * bh_mmap(void *hint, unsigned int size, int prot, int flags) { - return bh_malloc(size); + return BH_MALLOC(size); } void bh_munmap(void *addr, uint32 size) { - return bh_free(addr); + return BH_FREE(addr); } int diff --git a/core/shared/platform/alios/bh_platform.h b/core/shared/platform/alios/bh_platform.h index 9b39c00e2..a3620112a 100644 --- a/core/shared/platform/alios/bh_platform.h +++ b/core/shared/platform/alios/bh_platform.h @@ -8,7 +8,6 @@ #include "bh_config.h" #include "bh_types.h" -#include "bh_memory.h" #include #include #include @@ -39,10 +38,6 @@ typedef uint64_t uint64; typedef int64_t int64; -#define wa_malloc bh_malloc -#define wa_free bh_free -#define wa_strdup bh_strdup - typedef aos_task_t korp_thread; typedef korp_thread *korp_tid; typedef aos_task_t *aos_tid_t; @@ -58,6 +53,10 @@ typedef struct korp_cond { typedef void* (*thread_start_routine_t)(void*); +void *os_malloc(unsigned size); +void *os_realloc(void *ptr, unsigned size); +void os_free(void *ptr); + /* Unit test framework is based on C++, where the declaration of snprintf is different. */ #ifndef __cplusplus @@ -85,10 +84,6 @@ int snprintf(char *buffer, size_t count, const char *format, ...); extern void bh_assert_internal(int v, const char *file_name, int line_number, const char *expr_string); #define bh_assert(expr) bh_assert_internal((int)(expr), __FILE__, __LINE__, # expr) -extern int b_memcpy_s(void * s1, unsigned int s1max, const void * s2, unsigned int n); -extern int b_strcat_s(char * s1, size_t s1max, const char * s2); -extern int b_strcpy_s(char * s1, size_t s1max, const char * s2); - /* math functions */ double sqrt(double x); double floor(double x); diff --git a/core/shared/platform/alios/bh_thread.c b/core/shared/platform/alios/bh_thread.c index a17751914..042e974a2 100644 --- a/core/shared/platform/alios/bh_thread.c +++ b/core/shared/platform/alios/bh_thread.c @@ -6,7 +6,6 @@ #include "bh_thread.h" #include "bh_assert.h" #include "bh_log.h" -#include "bh_memory.h" #include #include @@ -102,7 +101,7 @@ vm_thread_cleanup(void) wait_node_sem = &thread_data->wait_node.sem; /* Free thread data firstly */ - bh_free(thread_data); + BH_FREE(thread_data); aos_mutex_lock(wait_list_lock, AOS_WAIT_FOREVER); if (thread_wait_list) { @@ -152,7 +151,7 @@ _vm_thread_create_with_prio(korp_tid *p_tid, thread_start_routine_t start, return BHT_ERROR; /* Create and initialize thread data */ - if (!(thread_data = bh_malloc(sizeof(bh_thread_data)))) + if (!(thread_data = BH_MALLOC(sizeof(bh_thread_data)))) return BHT_ERROR; memset(thread_data, 0, sizeof(bh_thread_data)); @@ -184,7 +183,7 @@ fail3: fail2: aos_sem_free(&thread_data->wait_node.sem); fail1: - bh_free(thread_data); + BH_FREE(thread_data); return BHT_ERROR; } diff --git a/core/shared/platform/android/bh_platform.c b/core/shared/platform/android/bh_platform.c index 44e28ab07..1831e9502 100755 --- a/core/shared/platform/android/bh_platform.c +++ b/core/shared/platform/android/bh_platform.c @@ -18,6 +18,24 @@ bh_platform_init() return 0; } +void * +os_malloc(unsigned size) +{ + return malloc(size); +} + +void * +os_realloc(void *ptr, unsigned size) +{ + return realloc(ptr, size); +} + +void +os_free(void *ptr) +{ + free(ptr); +} + char* bh_read_file_to_buffer(const char *filename, uint32 *ret_size) { @@ -46,7 +64,7 @@ bh_read_file_to_buffer(const char *filename, uint32 *ret_size) file_size = (uint32)stat_buf.st_size; - if (!(buffer = bh_malloc(file_size))) { + if (!(buffer = BH_MALLOC(file_size))) { printf("Read file to buffer failed: alloc memory failed.\n"); close(file); return NULL; @@ -57,7 +75,7 @@ bh_read_file_to_buffer(const char *filename, uint32 *ret_size) if (read_size < file_size) { printf("Read file to buffer failed: read file content failed.\n"); - bh_free(buffer); + BH_FREE(buffer); return NULL; } diff --git a/core/shared/platform/android/bh_platform.h b/core/shared/platform/android/bh_platform.h index b449616e0..003850954 100644 --- a/core/shared/platform/android/bh_platform.h +++ b/core/shared/platform/android/bh_platform.h @@ -8,7 +8,6 @@ #include "bh_config.h" #include "bh_types.h" -#include "bh_memory.h" #include #include #include @@ -36,16 +35,10 @@ extern "C" { typedef uint64_t uint64; typedef int64_t int64; -extern void DEBUGME(void); - -#define DIE do{bh_debug("Die here\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); DEBUGME(void); while(1);}while(0) - #ifndef BH_PLATFORM_ANDROID #define BH_PLATFORM_ANDROID #endif -/* NEED qsort */ - #define _STACK_SIZE_ADJUSTMENT (32 * 1024) /* Stack size of applet threads's native part. */ @@ -67,13 +60,12 @@ typedef pthread_cond_t korp_cond; typedef pthread_t korp_thread; typedef void* (*thread_start_routine_t)(void*); -#define wa_malloc bh_malloc -#define wa_free bh_free -#define wa_strdup bh_strdup +void *os_malloc(unsigned size); +void *os_realloc(void *ptr, unsigned size); +void os_free(void *ptr); #define bh_printf(...) (__android_log_print(ANDROID_LOG_INFO, "wasm_runtime::", __VA_ARGS__)) - int snprintf(char *buffer, size_t count, const char *format, ...); double fmod(double x, double y); float fmodf(float x, float y); @@ -99,15 +91,8 @@ double sqrt(double x); #define bh_assert assert -int b_memcpy_s(void * s1, unsigned int s1max, const void * s2, - unsigned int n); -int b_strcat_s(char * s1, size_t s1max, const char * s2); -int b_strcpy_s(char * s1, size_t s1max, const char * s2); - char *bh_read_file_to_buffer(const char *filename, uint32 *ret_size); -char *bh_strdup(const char *s); - int bh_platform_init(); /* MMAP mode */ diff --git a/core/shared/platform/android/bh_thread.c b/core/shared/platform/android/bh_thread.c index cf41c4568..88c62a3ba 100755 --- a/core/shared/platform/android/bh_thread.c +++ b/core/shared/platform/android/bh_thread.c @@ -6,7 +6,6 @@ #include "bh_thread.h" #include "bh_assert.h" #include "bh_log.h" -#include "bh_memory.h" #include #include #include @@ -67,7 +66,7 @@ static void *vm_thread_wrapper(void *arg) targ->stack = (void *)((uintptr_t)(&arg) & (uintptr_t)~0xfff); _vm_tls_put(1, targ); targ->start(targ->arg); - bh_free(targ); + BH_FREE(targ); _vm_tls_put(1, NULL); return NULL; } @@ -94,7 +93,7 @@ int _vm_thread_create_with_prio(korp_tid *tid, thread_start_routine_t start, return BHT_ERROR; } - targ = (thread_wrapper_arg*) bh_malloc(sizeof(*targ)); + targ = (thread_wrapper_arg*) BH_MALLOC(sizeof(*targ)); if (!targ) { pthread_attr_destroy(&tattr); return BHT_ERROR; @@ -106,7 +105,7 @@ int _vm_thread_create_with_prio(korp_tid *tid, thread_start_routine_t start, if (pthread_create(tid, &tattr, vm_thread_wrapper, targ) != 0) { pthread_attr_destroy(&tattr); - bh_free(targ); + BH_FREE(targ); return BHT_ERROR; } @@ -128,7 +127,7 @@ korp_tid _vm_self_thread() void vm_thread_exit(void * code) { - bh_free(_vm_tls_get(1)); + BH_FREE(_vm_tls_get(1)); _vm_tls_put(1, NULL); pthread_exit(code); } diff --git a/core/shared/platform/darwin/bh_platform.c b/core/shared/platform/darwin/bh_platform.c index b6e251145..ddfacf3ea 100755 --- a/core/shared/platform/darwin/bh_platform.c +++ b/core/shared/platform/darwin/bh_platform.c @@ -18,6 +18,24 @@ bh_platform_init() return 0; } +void * +os_malloc(unsigned size) +{ + return malloc(size); +} + +void * +os_realloc(void *ptr, unsigned size) +{ + return realloc(ptr, size); +} + +void +os_free(void *ptr) +{ + free(ptr); +} + char* bh_read_file_to_buffer(const char *filename, uint32 *ret_size) { @@ -46,7 +64,7 @@ bh_read_file_to_buffer(const char *filename, uint32 *ret_size) file_size = (uint32)stat_buf.st_size; - if (!(buffer = bh_malloc(file_size))) { + if (!(buffer = BH_MALLOC(file_size))) { printf("Read file to buffer failed: alloc memory failed.\n"); close(file); return NULL; @@ -57,7 +75,7 @@ bh_read_file_to_buffer(const char *filename, uint32 *ret_size) if (read_size < file_size) { printf("Read file to buffer failed: read file content failed.\n"); - bh_free(buffer); + BH_FREE(buffer); return NULL; } diff --git a/core/shared/platform/darwin/bh_platform.h b/core/shared/platform/darwin/bh_platform.h index 7deaec68c..e07dd4e55 100644 --- a/core/shared/platform/darwin/bh_platform.h +++ b/core/shared/platform/darwin/bh_platform.h @@ -8,7 +8,6 @@ #include "bh_config.h" #include "bh_types.h" -#include "bh_memory.h" #include #include #include @@ -34,16 +33,10 @@ extern "C" { typedef uint64_t uint64; typedef int64_t int64; -extern void DEBUGME(void); - -#define DIE do{bh_debug("Die here\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); DEBUGME(void); while(1);}while(0) - #ifndef BH_PLATFORM_DARWIN #define BH_PLATFORM_DARWIN #endif -/* NEED qsort */ - #define _STACK_SIZE_ADJUSTMENT (32 * 1024) /* Stack size of applet threads's native part. */ @@ -65,9 +58,9 @@ typedef pthread_cond_t korp_cond; typedef pthread_t korp_thread; typedef void* (*thread_start_routine_t)(void*); -#define wa_malloc bh_malloc -#define wa_free bh_free -#define wa_strdup bh_strdup +void *os_malloc(unsigned size); +void *os_realloc(void *ptr, unsigned size); +void os_free(void *ptr); #define bh_printf printf @@ -96,15 +89,8 @@ double sqrt(double x); #define bh_assert assert -int b_memcpy_s(void * s1, unsigned int s1max, const void * s2, - unsigned int n); -int b_strcat_s(char * s1, size_t s1max, const char * s2); -int b_strcpy_s(char * s1, size_t s1max, const char * s2); - char *bh_read_file_to_buffer(const char *filename, uint32 *ret_size); -char *bh_strdup(const char *s); - int bh_platform_init(); /* MMAP mode */ diff --git a/core/shared/platform/darwin/bh_thread.c b/core/shared/platform/darwin/bh_thread.c index abf736806..c81e9786d 100644 --- a/core/shared/platform/darwin/bh_thread.c +++ b/core/shared/platform/darwin/bh_thread.c @@ -6,7 +6,6 @@ #include "bh_thread.h" #include "bh_assert.h" #include "bh_log.h" -#include "bh_memory.h" #include #include #include @@ -67,7 +66,7 @@ static void *vm_thread_wrapper(void *arg) targ->stack = (void *)((uintptr_t)(&arg) & (uintptr_t)~0xfff); _vm_tls_put(1, targ); targ->start(targ->arg); - bh_free(targ); + BH_FREE(targ); _vm_tls_put(1, NULL); return NULL; } @@ -93,7 +92,7 @@ int _vm_thread_create_with_prio(korp_tid *tid, thread_start_routine_t start, return BHT_ERROR; } - targ = (thread_wrapper_arg*) bh_malloc(sizeof(*targ)); + targ = (thread_wrapper_arg*) BH_MALLOC(sizeof(*targ)); if (!targ) { pthread_attr_destroy(&tattr); return BHT_ERROR; @@ -105,7 +104,7 @@ int _vm_thread_create_with_prio(korp_tid *tid, thread_start_routine_t start, if (pthread_create(tid, &tattr, vm_thread_wrapper, targ) != 0) { pthread_attr_destroy(&tattr); - bh_free(targ); + BH_FREE(targ); return BHT_ERROR; } @@ -127,7 +126,7 @@ korp_tid _vm_self_thread() void vm_thread_exit(void * code) { - bh_free(_vm_tls_get(1)); + BH_FREE(_vm_tls_get(1)); _vm_tls_put(1, NULL); pthread_exit(code); } diff --git a/core/shared/platform/include/bh_config.h b/core/shared/platform/include/bh_config.h index 0069194d1..ec4984133 100644 --- a/core/shared/platform/include/bh_config.h +++ b/core/shared/platform/include/bh_config.h @@ -16,5 +16,38 @@ #include "config.h" +#define BH_KB (1024) +#define BH_MB ((BH_KB)*1024) +#define BH_GB ((BH_MB)*1024) + +#ifndef BH_MALLOC +#define BH_MALLOC os_malloc +#endif + +#ifndef BH_FREE +#define BH_FREE os_free +#endif + +#ifndef WA_MALLOC +#include +#define WA_MALLOC malloc +#endif + +#ifndef WA_FREE +#include +#define WA_FREE free +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +void *wasm_runtime_malloc(unsigned int size); +void wasm_runtime_free(void *ptr); + +#ifdef __cplusplus +} +#endif + #endif /* end of BH_CONFIG */ diff --git a/core/shared/platform/linux-sgx/bh_platform.c b/core/shared/platform/linux-sgx/bh_platform.c index 9257b6a50..8b742c6d0 100644 --- a/core/shared/platform/linux-sgx/bh_platform.c +++ b/core/shared/platform/linux-sgx/bh_platform.c @@ -19,6 +19,24 @@ int bh_platform_init() return 0; } +void * +os_malloc(unsigned size) +{ + return malloc(size); +} + +void * +os_realloc(void *ptr, unsigned size) +{ + return realloc(ptr, size); +} + +void +os_free(void *ptr) +{ + free(ptr); +} + int putchar(int c) { return 0; diff --git a/core/shared/platform/linux-sgx/bh_platform.h b/core/shared/platform/linux-sgx/bh_platform.h index dc4723283..ab479e3da 100644 --- a/core/shared/platform/linux-sgx/bh_platform.h +++ b/core/shared/platform/linux-sgx/bh_platform.h @@ -8,7 +8,6 @@ #include "bh_config.h" #include "bh_types.h" -#include "bh_memory.h" #include #include #include @@ -27,14 +26,15 @@ extern "C" { #endif +typedef void (*bh_print_function_t)(const char* message); +void bh_set_print_function(bh_print_function_t pf); + extern int bh_printf_sgx(const char *message, ...); extern int bh_vprintf_sgx(const char * format, va_list arg); typedef uint64_t uint64; typedef int64_t int64; -#define DIE do{bh_debug("Die here\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); DEBUGME(void); while(1);}while(0) - #ifndef BH_PLATFORM_LINUX_SGX #define BH_PLATFORM_LINUX_SGX #endif @@ -62,9 +62,9 @@ typedef sgx_thread_t korp_tid; typedef sgx_thread_t korp_thread; typedef sgx_thread_cond_t korp_cond; -#define wa_malloc bh_malloc -#define wa_free bh_free -#define wa_strdup bh_strdup +void *os_malloc(unsigned size); +void *os_realloc(void *ptr, unsigned size); +void os_free(void *ptr); #define bh_printf bh_printf_sgx @@ -94,13 +94,6 @@ double sqrt(double x); #define bh_assert assert -int b_memcpy_s(void * s1, unsigned int s1max, const void * s2, - unsigned int n); -int b_strcat_s(char * s1, size_t s1max, const char * s2); -int b_strcpy_s(char * s1, size_t s1max, const char * s2); - -char *bh_strdup(const char *s); - int bh_platform_init(); /* MMAP mode */ diff --git a/core/shared/platform/linux-sgx/bh_thread.c b/core/shared/platform/linux-sgx/bh_thread.c index 28667be20..a2a76c3ca 100644 --- a/core/shared/platform/linux-sgx/bh_thread.c +++ b/core/shared/platform/linux-sgx/bh_thread.c @@ -5,7 +5,6 @@ #include "bh_thread.h" #include "bh_assert.h" -#include "bh_memory.h" #include #include #include diff --git a/core/shared/platform/linux/bh_platform.c b/core/shared/platform/linux/bh_platform.c index 44e28ab07..1831e9502 100755 --- a/core/shared/platform/linux/bh_platform.c +++ b/core/shared/platform/linux/bh_platform.c @@ -18,6 +18,24 @@ bh_platform_init() return 0; } +void * +os_malloc(unsigned size) +{ + return malloc(size); +} + +void * +os_realloc(void *ptr, unsigned size) +{ + return realloc(ptr, size); +} + +void +os_free(void *ptr) +{ + free(ptr); +} + char* bh_read_file_to_buffer(const char *filename, uint32 *ret_size) { @@ -46,7 +64,7 @@ bh_read_file_to_buffer(const char *filename, uint32 *ret_size) file_size = (uint32)stat_buf.st_size; - if (!(buffer = bh_malloc(file_size))) { + if (!(buffer = BH_MALLOC(file_size))) { printf("Read file to buffer failed: alloc memory failed.\n"); close(file); return NULL; @@ -57,7 +75,7 @@ bh_read_file_to_buffer(const char *filename, uint32 *ret_size) if (read_size < file_size) { printf("Read file to buffer failed: read file content failed.\n"); - bh_free(buffer); + BH_FREE(buffer); return NULL; } diff --git a/core/shared/platform/linux/bh_platform.h b/core/shared/platform/linux/bh_platform.h index dd7483668..e73b3d965 100644 --- a/core/shared/platform/linux/bh_platform.h +++ b/core/shared/platform/linux/bh_platform.h @@ -8,7 +8,6 @@ #include "bh_config.h" #include "bh_types.h" -#include "bh_memory.h" #include #include #include @@ -66,9 +65,9 @@ typedef pthread_cond_t korp_cond; typedef pthread_t korp_thread; typedef void* (*thread_start_routine_t)(void*); -#define wa_malloc bh_malloc -#define wa_free bh_free -#define wa_strdup bh_strdup +void *os_malloc(unsigned size); +void *os_realloc(void *ptr, unsigned size); +void os_free(void *ptr); #define bh_printf printf @@ -97,15 +96,8 @@ double sqrt(double x); #define bh_assert assert -int b_memcpy_s(void * s1, unsigned int s1max, const void * s2, - unsigned int n); -int b_strcat_s(char * s1, size_t s1max, const char * s2); -int b_strcpy_s(char * s1, size_t s1max, const char * s2); - char *bh_read_file_to_buffer(const char *filename, uint32 *ret_size); -char *bh_strdup(const char *s); - int bh_platform_init(); /* MMAP mode */ diff --git a/core/shared/platform/linux/bh_thread.c b/core/shared/platform/linux/bh_thread.c index 8160fb044..199809900 100755 --- a/core/shared/platform/linux/bh_thread.c +++ b/core/shared/platform/linux/bh_thread.c @@ -6,7 +6,6 @@ #include "bh_thread.h" #include "bh_assert.h" #include "bh_log.h" -#include "bh_memory.h" #include #include #include @@ -67,7 +66,7 @@ static void *vm_thread_wrapper(void *arg) targ->stack = (void *)((uintptr_t)(&arg) & (uintptr_t)~0xfff); _vm_tls_put(1, targ); targ->start(targ->arg); - bh_free(targ); + BH_FREE(targ); _vm_tls_put(1, NULL); return NULL; } @@ -93,7 +92,7 @@ int _vm_thread_create_with_prio(korp_tid *tid, thread_start_routine_t start, return BHT_ERROR; } - targ = (thread_wrapper_arg*) bh_malloc(sizeof(*targ)); + targ = (thread_wrapper_arg*) BH_MALLOC(sizeof(*targ)); if (!targ) { pthread_attr_destroy(&tattr); return BHT_ERROR; @@ -105,7 +104,7 @@ int _vm_thread_create_with_prio(korp_tid *tid, thread_start_routine_t start, if (pthread_create(tid, &tattr, vm_thread_wrapper, targ) != 0) { pthread_attr_destroy(&tattr); - bh_free(targ); + BH_FREE(targ); return BHT_ERROR; } @@ -127,7 +126,7 @@ korp_tid _vm_self_thread() void vm_thread_exit(void * code) { - bh_free(_vm_tls_get(1)); + BH_FREE(_vm_tls_get(1)); _vm_tls_put(1, NULL); pthread_exit(code); } diff --git a/core/shared/platform/vxworks/bh_platform.c b/core/shared/platform/vxworks/bh_platform.c index c2960485d..e0eca6a65 100644 --- a/core/shared/platform/vxworks/bh_platform.c +++ b/core/shared/platform/vxworks/bh_platform.c @@ -22,6 +22,24 @@ bh_platform_init() return 0; } +void * +os_malloc(unsigned size) +{ + return malloc(size); +} + +void * +os_realloc(void *ptr, unsigned size) +{ + return realloc(ptr, size); +} + +void +os_free(void *ptr) +{ + free(ptr); +} + char* bh_read_file_to_buffer(const char *filename, uint32 *ret_size) { @@ -50,7 +68,7 @@ bh_read_file_to_buffer(const char *filename, uint32 *ret_size) file_size = (uint32)stat_buf.st_size; - if (!(buffer = bh_malloc(file_size))) { + if (!(buffer = BH_MALLOC(file_size))) { printf("Read file to buffer failed: alloc memory failed.\n"); close(file); return NULL; @@ -61,7 +79,7 @@ bh_read_file_to_buffer(const char *filename, uint32 *ret_size) if (read_size < file_size) { printf("Read file to buffer failed: read file content failed.\n"); - bh_free(buffer); + BH_FREE(buffer); return NULL; } diff --git a/core/shared/platform/vxworks/bh_platform.h b/core/shared/platform/vxworks/bh_platform.h index 457933d84..70c030e74 100644 --- a/core/shared/platform/vxworks/bh_platform.h +++ b/core/shared/platform/vxworks/bh_platform.h @@ -8,7 +8,6 @@ #include "bh_config.h" #include "bh_types.h" -#include "bh_memory.h" #include #include #include @@ -42,8 +41,6 @@ extern void DEBUGME(void); #define BH_PLATFORM_VXWORKS #endif -/* NEED qsort */ - #define _STACK_SIZE_ADJUSTMENT (32 * 1024) /* Stack size of applet threads's native part. */ @@ -65,9 +62,9 @@ typedef pthread_cond_t korp_cond; typedef pthread_t korp_thread; typedef void* (*thread_start_routine_t)(void*); -#define wa_malloc bh_malloc -#define wa_free bh_free -#define wa_strdup bh_strdup +void *os_malloc(unsigned size); +void *os_realloc(void *ptr, unsigned size); +void os_free(void *ptr); #define bh_printf printf @@ -96,15 +93,8 @@ double sqrt(double x); #define bh_assert assert -int b_memcpy_s(void * s1, unsigned int s1max, const void * s2, - unsigned int n); -int b_strcat_s(char * s1, size_t s1max, const char * s2); -int b_strcpy_s(char * s1, size_t s1max, const char * s2); - char *bh_read_file_to_buffer(const char *filename, uint32 *ret_size); -char *bh_strdup(const char *s); - int bh_platform_init(); /* MMAP mode */ diff --git a/core/shared/platform/vxworks/bh_thread.c b/core/shared/platform/vxworks/bh_thread.c index 3b51596fd..4267154ec 100644 --- a/core/shared/platform/vxworks/bh_thread.c +++ b/core/shared/platform/vxworks/bh_thread.c @@ -6,7 +6,6 @@ #include "bh_thread.h" #include "bh_assert.h" #include "bh_log.h" -#include "bh_memory.h" #include #include #include @@ -67,7 +66,7 @@ static void *vm_thread_wrapper(void *arg) targ->stack = (void *)((uintptr_t)(&arg) & (uintptr_t)~0xfff); _vm_tls_put(1, targ); targ->start(targ->arg); - bh_free(targ); + BH_FREE(targ); _vm_tls_put(1, NULL); return NULL; } @@ -93,7 +92,7 @@ int _vm_thread_create_with_prio(korp_tid *tid, thread_start_routine_t start, return BHT_ERROR; } - targ = (thread_wrapper_arg*) bh_malloc(sizeof(*targ)); + targ = (thread_wrapper_arg*) BH_MALLOC(sizeof(*targ)); if (!targ) { pthread_attr_destroy(&tattr); return BHT_ERROR; @@ -105,7 +104,7 @@ int _vm_thread_create_with_prio(korp_tid *tid, thread_start_routine_t start, if (pthread_create(tid, &tattr, vm_thread_wrapper, targ) != 0) { pthread_attr_destroy(&tattr); - bh_free(targ); + BH_FREE(targ); return BHT_ERROR; } @@ -127,7 +126,7 @@ korp_tid _vm_self_thread() void vm_thread_exit(void * code) { - bh_free(_vm_tls_get(1)); + BH_FREE(_vm_tls_get(1)); _vm_tls_put(1, NULL); pthread_exit(code); } diff --git a/core/shared/platform/zephyr/Makefile b/core/shared/platform/zephyr/Makefile deleted file mode 100644 index c1520f363..000000000 --- a/core/shared/platform/zephyr/Makefile +++ /dev/null @@ -1,4 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -obj-y += bh_assert.o bh_definition.o bh_memory.o bh_platform_log.o bh_thread.o bh_time.o diff --git a/core/shared/platform/zephyr/bh_platform.c b/core/shared/platform/zephyr/bh_platform.c index a96483da7..ba528cd56 100755 --- a/core/shared/platform/zephyr/bh_platform.c +++ b/core/shared/platform/zephyr/bh_platform.c @@ -4,7 +4,6 @@ */ #include "bh_platform.h" -#include "bh_memory.h" #include "bh_common.h" #include #include @@ -58,16 +57,33 @@ bh_platform_init() return 0; } +void * +os_malloc(unsigned size) +{ + return NULL; +} + +void * +os_realloc(void *ptr, unsigned size) +{ + return NULL; +} + +void +os_free(void *ptr) +{ +} + void * bh_mmap(void *hint, unsigned int size, int prot, int flags) { - return bh_malloc(size); + return BH_MALLOC(size); } void bh_munmap(void *addr, uint32 size) { - return bh_free(addr); + return BH_FREE(addr); } int diff --git a/core/shared/platform/zephyr/bh_platform.h b/core/shared/platform/zephyr/bh_platform.h index 77db8a358..34cd386fa 100644 --- a/core/shared/platform/zephyr/bh_platform.h +++ b/core/shared/platform/zephyr/bh_platform.h @@ -8,7 +8,6 @@ #include "bh_config.h" #include "bh_types.h" -#include "bh_memory.h" #include #include #include @@ -55,10 +54,6 @@ typedef korp_thread *korp_tid; typedef struct k_mutex korp_mutex; typedef struct k_sem korp_sem; -#define wa_malloc bh_malloc -#define wa_free bh_free -#define wa_strdup bh_strdup - struct bh_thread_wait_node; typedef struct bh_thread_wait_node *bh_thread_wait_list; typedef struct korp_cond { @@ -68,8 +63,9 @@ typedef struct korp_cond { typedef void* (*thread_start_routine_t)(void*); -#define wa_malloc bh_malloc -#define wa_free bh_free +void *os_malloc(unsigned size); +void *os_realloc(void *ptr, unsigned size); +void os_free(void *ptr); #define bh_printf printf @@ -102,11 +98,6 @@ int snprintf(char *buffer, size_t count, const char *format, ...); } \ } while (0) -int b_memcpy_s(void * s1, unsigned int s1max, const void * s2, - unsigned int n); -int b_strcat_s(char * s1, size_t s1max, const char * s2); -int b_strcpy_s(char * s1, size_t s1max, const char * s2); - /* math functions */ double sqrt(double x); double floor(double x); diff --git a/core/shared/platform/zephyr/bh_thread.c b/core/shared/platform/zephyr/bh_thread.c index fd9e6e0c0..9493076e6 100755 --- a/core/shared/platform/zephyr/bh_thread.c +++ b/core/shared/platform/zephyr/bh_thread.c @@ -6,9 +6,6 @@ #include "bh_thread.h" #include "bh_assert.h" #include "bh_log.h" -#include "bh_memory.h" -#include -#include typedef struct bh_thread_wait_node { struct k_sem sem; @@ -140,11 +137,11 @@ static void thread_obj_list_reclaim() if (p->to_be_freed) { if (p_prev == NULL) { /* p is the head of list */ thread_obj_list = p->next; - bh_free(p); + BH_FREE(p); p = thread_obj_list; } else { /* p is not the head of list */ p_prev->next = p->next; - bh_free(p); + BH_FREE(p); p = p_prev->next; } } else { @@ -210,7 +207,7 @@ static void vm_thread_cleanup(void) /* Set flag to true for the next thread creating to free the thread object */ ((bh_thread_obj*) thread_data->tid)->to_be_freed = true; - bh_free(thread_data); + BH_FREE(thread_data); } static void vm_thread_wrapper(void *start, void *arg, void *thread_data) @@ -244,15 +241,15 @@ int _vm_thread_create_with_prio(korp_tid *p_tid, thread_start_routine_t start, thread_obj_list_reclaim(); /* Create and initialize thread object */ - if (!(tid = bh_malloc(sizeof(bh_thread_obj)))) + if (!(tid = BH_MALLOC(sizeof(bh_thread_obj)))) return BHT_ERROR; memset(tid, 0, sizeof(bh_thread_obj)); /* Create and initialize thread data */ thread_data_size = offsetof(bh_thread_data, stack) + stack_size; - if (!(thread_data = bh_malloc(thread_data_size))) { - bh_free(tid); + if (!(thread_data = BH_MALLOC(thread_data_size))) { + BH_FREE(tid); return BHT_ERROR; } @@ -265,8 +262,8 @@ int _vm_thread_create_with_prio(korp_tid *p_tid, thread_start_routine_t start, if (!((tid = k_thread_create(tid, (k_thread_stack_t *) thread_data->stack, stack_size, vm_thread_wrapper, start, arg, thread_data, prio, 0, K_NO_WAIT)))) { - bh_free(tid); - bh_free(thread_data); + BH_FREE(tid); + BH_FREE(thread_data); return BHT_ERROR; } @@ -305,7 +302,7 @@ int _vm_thread_join(korp_tid thread, void **value_ptr, int mills) bh_thread_wait_node *node; /* Create wait node and append it to wait list */ - if (!(node = bh_malloc(sizeof(bh_thread_wait_node)))) + if (!(node = BH_MALLOC(sizeof(bh_thread_wait_node)))) return BHT_ERROR; k_sem_init(&node->sem, 0, 1); @@ -334,7 +331,7 @@ int _vm_thread_join(korp_tid thread, void **value_ptr, int mills) k_sleep(100); /* Destroy resource */ - bh_free(node); + BH_FREE(node); return BHT_OK; } @@ -449,7 +446,7 @@ static int _vm_cond_wait_internal(korp_cond *cond, korp_mutex *mutex, bh_thread_wait_node *node; /* Create wait node and append it to wait list */ - if (!(node = bh_malloc(sizeof(bh_thread_wait_node)))) + if (!(node = BH_MALLOC(sizeof(bh_thread_wait_node)))) return BHT_ERROR; k_sem_init(&node->sem, 0, 1); @@ -483,7 +480,7 @@ static int _vm_cond_wait_internal(korp_cond *cond, korp_mutex *mutex, p = p->next; p->next = node->next; } - bh_free(node); + BH_FREE(node); k_mutex_unlock(&cond->wait_list_lock); return BHT_OK; diff --git a/core/shared/utils/bh_definition.c b/core/shared/utils/bh_definition.c index b417a764d..3d2a1e0df 100644 --- a/core/shared/utils/bh_definition.c +++ b/core/shared/utils/bh_definition.c @@ -67,7 +67,21 @@ bh_strdup(const char *s) if (s) { size = (uint32)(strlen(s) + 1); - if ((s1 = bh_malloc(size))) + if ((s1 = BH_MALLOC(size))) + bh_memcpy_s(s1, size, s, size); + } + return s1; +} + +char * +wa_strdup(const char *s) +{ + uint32 size; + char *s1 = NULL; + + if (s) { + size = (uint32)(strlen(s) + 1); + if ((s1 = WA_MALLOC(size))) bh_memcpy_s(s1, size, s, size); } return s1; diff --git a/core/shared/utils/bh_hashmap.c b/core/shared/utils/bh_hashmap.c index 33891a8a0..0bebdfc64 100644 --- a/core/shared/utils/bh_hashmap.c +++ b/core/shared/utils/bh_hashmap.c @@ -6,7 +6,6 @@ #include "bh_hashmap.h" #include "bh_log.h" #include "bh_thread.h" -#include "bh_memory.h" typedef struct HashMapElem { @@ -55,7 +54,7 @@ bh_hash_map_create(uint32 size, bool use_lock, (use_lock ? sizeof(korp_mutex) : 0); if (total_size >= UINT32_MAX - || !(map = bh_malloc((uint32)total_size))) { + || !(map = BH_MALLOC((uint32)total_size))) { LOG_ERROR("HashMap create failed: alloc memory failed.\n"); return NULL; } @@ -68,7 +67,7 @@ bh_hash_map_create(uint32 size, bool use_lock, + sizeof(HashMapElem) * size); if (vm_mutex_init(map->lock)) { LOG_ERROR("HashMap create failed: init map lock failed.\n"); - bh_free(map); + BH_FREE(map); return NULL; } } @@ -106,7 +105,7 @@ bh_hash_map_insert(HashMap *map, void *key, void *value) elem = elem->next; } - if (!(elem = bh_malloc(sizeof(HashMapElem)))) { + if (!(elem = BH_MALLOC(sizeof(HashMapElem)))) { LOG_ERROR("HashMap insert elem failed: alloc memory failed.\n"); goto fail; } @@ -233,7 +232,7 @@ bh_hash_map_remove(HashMap *map, void *key, else prev->next = elem->next; - bh_free(elem); + BH_FREE(elem); if (map->lock) { vm_mutex_unlock(map->lock); @@ -277,7 +276,7 @@ bh_hash_map_destroy(HashMap *map) if (map->value_destroy_func) { map->value_destroy_func(elem->value); } - bh_free(elem); + BH_FREE(elem); elem = next; } @@ -287,6 +286,6 @@ bh_hash_map_destroy(HashMap *map) vm_mutex_unlock(map->lock); vm_mutex_destroy(map->lock); } - bh_free(map); + BH_FREE(map); return true; } diff --git a/core/shared/utils/bh_queue.c b/core/shared/utils/bh_queue.c index cd6a58166..4f74cee7e 100644 --- a/core/shared/utils/bh_queue.c +++ b/core/shared/utils/bh_queue.c @@ -5,7 +5,6 @@ #include "bh_queue.h" #include "bh_thread.h" -#include "bh_memory.h" #include "bh_time.h" #include "bh_common.h" @@ -131,7 +130,7 @@ bool bh_post_msg(bh_queue *queue, unsigned short tag, void *body, if (msg == NULL) { queue->drops++; if (len != 0 && body) - bh_free(body); + BH_FREE(body); return false; } diff --git a/core/shared/utils/bh_vector.c b/core/shared/utils/bh_vector.c index bb7900f44..9b7c9db9e 100644 --- a/core/shared/utils/bh_vector.c +++ b/core/shared/utils/bh_vector.c @@ -5,7 +5,6 @@ #include "bh_log.h" #include "bh_vector.h" -#include "bh_memory.h" static uint8* @@ -18,7 +17,7 @@ alloc_vector_data(uint32 length, uint32 size_elem) return NULL; } - if ((data = bh_malloc((uint32)total_size))) { + if ((data = BH_MALLOC((uint32)total_size))) { memset(data, 0, (uint32)total_size); } @@ -41,7 +40,7 @@ extend_vector(Vector *vector, uint32 length) } memcpy(data, vector->data, vector->size_elem * vector->max_elements); - bh_free(vector->data); + BH_FREE(vector->data); vector->data = data; vector->max_elements = length; return true; @@ -200,7 +199,7 @@ bh_vector_destroy(Vector *vector) } if (vector->data) - bh_free(vector->data); + BH_FREE(vector->data); memset(vector, 0, sizeof(Vector)); return true; } diff --git a/core/shared/utils/runtime_timer.c b/core/shared/utils/runtime_timer.c index 09e3f1411..c2894e4eb 100644 --- a/core/shared/utils/runtime_timer.c +++ b/core/shared/utils/runtime_timer.c @@ -172,7 +172,7 @@ static void release_timer(timer_ctx_t ctx, app_timer_t * t) vm_mutex_unlock(&ctx->mutex); } else { PRINT("destroy timer :%d\n", t->id); - bh_free(t); + BH_FREE(t); } } @@ -182,7 +182,7 @@ void release_timer_list(app_timer_t ** p_list) while (t) { app_timer_t *next = t->next; PRINT("destroy timer list:%d\n", t->id); - bh_free(t); + BH_FREE(t); t = next; } @@ -199,7 +199,7 @@ timer_ctx_t create_timer_ctx(timer_callback_f timer_handler, check_timer_expiry_f expiery_checker, int prealloc_num, unsigned int owner) { - timer_ctx_t ctx = (timer_ctx_t) bh_malloc(sizeof(struct _timer_ctx)); + timer_ctx_t ctx = (timer_ctx_t) BH_MALLOC(sizeof(struct _timer_ctx)); if (ctx == NULL) return NULL; memset(ctx, 0, sizeof(struct _timer_ctx)); @@ -210,7 +210,7 @@ timer_ctx_t create_timer_ctx(timer_callback_f timer_handler, ctx->owner = owner; while (prealloc_num > 0) { - app_timer_t *timer = (app_timer_t*) bh_malloc(sizeof(app_timer_t)); + app_timer_t *timer = (app_timer_t*) BH_MALLOC(sizeof(app_timer_t)); if (timer == NULL) goto cleanup; @@ -231,7 +231,7 @@ timer_ctx_t create_timer_ctx(timer_callback_f timer_handler, if (ctx) { release_timer_list(&ctx->free_timers); - bh_free(ctx); + BH_FREE(ctx); } PRINT("timer ctx create failed\n"); return NULL; @@ -242,14 +242,14 @@ void destroy_timer_ctx(timer_ctx_t ctx) while (ctx->free_timers) { void * tmp = ctx->free_timers; ctx->free_timers = ctx->free_timers->next; - bh_free(tmp); + BH_FREE(tmp); } cleanup_app_timers(ctx); vm_cond_destroy(&ctx->cond); vm_mutex_destroy(&ctx->mutex); - bh_free(ctx); + BH_FREE(ctx); } unsigned int timer_ctx_get_owner(timer_ctx_t ctx) @@ -279,7 +279,7 @@ uint32 sys_create_timer(timer_ctx_t ctx, int interval, bool is_period, ctx->free_timers = timer->next; } } else { - timer = (app_timer_t*) bh_malloc(sizeof(app_timer_t)); + timer = (app_timer_t*) BH_MALLOC(sizeof(app_timer_t)); if (timer == NULL) return (uint32)-1; } diff --git a/doc/embed_wamr.md b/doc/embed_wamr.md index 79e5b7cc3..390dd7ebd 100644 --- a/doc/embed_wamr.md +++ b/doc/embed_wamr.md @@ -4,13 +4,11 @@ Embedding WAMR guideline **Note**: All the embedding APIs supported by the runtime are defined under folder [core/iwasm/include](../core/iwasm/include). The API details are available in the header files. -## The initialization procedure +## The runtime initialization ``` C - static char global_heap_buf[512 * 1024]; - char *buffer, error_buf[128]; wasm_module_t module; wasm_module_inst_t module_inst; @@ -18,14 +16,15 @@ Embedding WAMR guideline wasm_exec_env_t exec_env; uint32 size, stack_size = 8092, heap_size = 8092; - // all the WAMR heap and WASM applications are limited in this buffer - bh_memory_init_with_pool(global_heap_buf, sizeof(global_heap_buf)); - + // initialize the wasm runtime by default configurations wasm_runtime_init(); // read WASM file into a memory buffer buffer = read_wasm_binary_to_buffer(…, &size); + // Add it below if runtime needs to export native functions to WASM APP + // wasm_runtime_register_natives(...) + // parse the WASM file from buffer and create a WASM module module = wasm_runtime_load(buffer, size, error_buf, sizeof(error_buf)); @@ -37,9 +36,43 @@ Embedding WAMR guideline sizeof(error_buf)); ``` +The `wasm_runtime_init()` will use the default memory allocator from the [`core/shared/platform`](../core/shared/platform) for the runtime memory management. +The WAMR supports to restrict its all memory allocations in a raw buffer. It ensures the dynamics by the WASM applications won't harm the system availability, which is extremely important for embedded systems. This can be done by using `wasm_runtime_full_init()`. This function also allows you to configure the native APIs for exporting to WASM app. + +Refer to the following sample: + +```c +// the native functions that will be exported to WASM app +static NativeSymbol native_symbols[] = { + EXPORT_WASM_API_WITH_SIG(display_input_read, "(*)i"), + EXPORT_WASM_API_WITH_SIG(display_flush, "(iiii*)") +}; + +// all the runtime memory allocations are retricted in the global_heap_buf array +static char global_heap_buf[512 * 1024]; +RuntimeInitArgs init_args; +memset(&init_args, 0, sizeof(RuntimeInitArgs)); + +// configure the memory allocator for the runtime +init_args.mem_alloc_type = Alloc_With_Pool; +init_args.mem_alloc_option.pool.heap_buf = global_heap_buf; +init_args.mem_alloc_option.pool.heap_size = sizeof(global_heap_buf); + +// configure the native functions being exported to WASM app +init_args.native_module_name = "env"; +init_args.n_native_symbols = sizeof(native_symbols) / sizeof(NativeSymbol); +init_args.native_symbols = native_symbols; + +/* initialize runtime environment with user configurations*/ +if (!wasm_runtime_full_init(&init_args)) { + return -1; +} +``` + + ## Native calls WASM functions and passes parameters @@ -48,7 +81,8 @@ After a module is instantiated, the runtime native can lookup WASM functions by ```c unit32 argv[2]; - // lookup a WASM function by its name + // lookup a WASM function by its name. + // The function signature can NULL here func = wasm_runtime_lookup_function(module_inst, "fib", NULL); // creat a excution environment which can be used by executing WASM functions @@ -137,6 +171,10 @@ int32 wasm_runtime_module_dup_data(WASMModuleInstanceCommon *module_inst, const char *src, uint32 size); + +// free the memory allocated from module memory space +void +wasm_runtime_module_free(wasm_module_inst_t module_inst, int32_t ptr); ``` @@ -155,6 +193,10 @@ if(buffer_for_wasm != 0) argv[0] = buffer_for_wasm; // pass the buffer address for WASM space. argv[1] = 100; // the size of buffer wasm_runtime_call_wasm(exec_env, func, 2, argv); + + // it is runtime responsibility to release the memory, + // unless the WASM app will free the passed pointer in its code + wasm_runtime_module_free(module_inst, buffer); } ``` @@ -174,7 +216,7 @@ We can't pass structure data or class objects through the pointer since the memo wasm_runtime_deinstantiate(module_inst); wasm_runtime_unload(module); wasm_runtime_destroy(); - bh_memory_destroy(); + ``` diff --git a/product-mini/platforms/alios-things/aos.mk b/product-mini/platforms/alios-things/aos.mk index 83b611beb..6331f1fd8 100644 --- a/product-mini/platforms/alios-things/aos.mk +++ b/product-mini/platforms/alios-things/aos.mk @@ -5,6 +5,9 @@ NAME := iwasm IWASM_ROOT := wamr/core/iwasm SHARED_ROOT := wamr/core/shared +GLOBAL_DEFINES += BH_MALLOC=wasm_runtime_malloc +GLOBAL_DEFINES += BH_FREE=wasm_runtime_free + # Change it to THUMBV7M if you want to build for developerkit WAMR_BUILD_TARGET := X86_32 @@ -76,7 +79,6 @@ $(NAME)_SOURCES := ${SHARED_ROOT}/platform/alios/bh_assert.c \ ${SHARED_ROOT}/platform/alios/bh_platform_log.c \ ${SHARED_ROOT}/platform/alios/bh_thread.c \ ${SHARED_ROOT}/platform/alios/bh_time.c \ - ${SHARED_ROOT}/mem-alloc/bh_memory.c \ ${SHARED_ROOT}/mem-alloc/mem_alloc.c \ ${SHARED_ROOT}/mem-alloc/ems/ems_kfc.c \ ${SHARED_ROOT}/mem-alloc/ems/ems_alloc.c \ @@ -91,6 +93,7 @@ $(NAME)_SOURCES := ${SHARED_ROOT}/platform/alios/bh_assert.c \ ${IWASM_ROOT}/common/wasm_runtime_common.c \ ${IWASM_ROOT}/common/wasm_native.c \ ${IWASM_ROOT}/common/wasm_exec_env.c \ + ${IWASM_ROOT}/common/wasm_memory.c \ ${IWASM_ROOT}/common/arch/${INVOKE_NATIVE} \ src/main.c diff --git a/product-mini/platforms/alios-things/src/main.c b/product-mini/platforms/alios-things/src/main.c index 29bf5f9ba..6c5d322b7 100644 --- a/product-mini/platforms/alios-things/src/main.c +++ b/product-mini/platforms/alios-things/src/main.c @@ -9,7 +9,6 @@ #include "bh_log.h" #include "bh_platform_log.h" #include "wasm_export.h" -#include "bh_memory.h" #include "test_wasm.h" static int app_argc; @@ -48,6 +47,7 @@ void iwasm_main(void *arg1) uint32 wasm_file_size; wasm_module_t wasm_module = NULL; wasm_module_inst_t wasm_module_inst = NULL; + RuntimeInitArgs init_args; char error_buf[128]; #if WASM_ENABLE_LOG != 0 int log_verbose_level = 2; @@ -55,15 +55,17 @@ void iwasm_main(void *arg1) (void) arg1; - if (bh_memory_init_with_pool(global_heap_buf, sizeof(global_heap_buf)) - != 0) { - bh_printf("Init global heap failed.\n"); - return; - } + memset(&init_args, 0, sizeof(RuntimeInitArgs)); + + init_args.mem_alloc_type = Alloc_With_Pool; + init_args.mem_alloc_option.pool.heap_buf = global_heap_buf; + init_args.mem_alloc_option.pool.heap_size = sizeof(global_heap_buf); /* initialize runtime environment */ - if (!wasm_runtime_init()) - goto fail1; + if (!wasm_runtime_full_init(&init_args)) { + bh_printf("Init runtime environment failed.\n"); + return; + } #if WASM_ENABLE_LOG != 0 bh_log_set_verbose_level(log_verbose_level); @@ -77,14 +79,17 @@ void iwasm_main(void *arg1) if (!(wasm_module = wasm_runtime_load(wasm_file_buf, wasm_file_size, error_buf, sizeof(error_buf)))) { bh_printf("%s\n", error_buf); - goto fail2; + goto fail1; } /* instantiate the module */ - if (!(wasm_module_inst = wasm_runtime_instantiate(wasm_module, 8 * 1024, - 8 * 1024, error_buf, sizeof(error_buf)))) { + if (!(wasm_module_inst = wasm_runtime_instantiate(wasm_module, + 8 * 1024, + 8 * 1024, + error_buf, + sizeof(error_buf)))) { bh_printf("%s\n", error_buf); - goto fail3; + goto fail2; } app_instance_main(wasm_module_inst); @@ -92,15 +97,13 @@ void iwasm_main(void *arg1) /* destroy the module instance */ wasm_runtime_deinstantiate(wasm_module_inst); - fail3: +fail2: /* unload the module */ wasm_runtime_unload(wasm_module); - fail2: +fail1: /* destroy runtime environment */ wasm_runtime_destroy(); - - fail1: bh_memory_destroy(); } #define DEFAULT_THREAD_STACKSIZE (6 * 1024) diff --git a/product-mini/platforms/android/wasm-jni.cpp b/product-mini/platforms/android/wasm-jni.cpp index be57aba8a..648f7e54c 100644 --- a/product-mini/platforms/android/wasm-jni.cpp +++ b/product-mini/platforms/android/wasm-jni.cpp @@ -75,27 +75,25 @@ static unsigned char wasm_test_file[] = { 0x00, 0x61, 0x73, 0x6D, 0x01, 0x00, 0x extern "C" JNIEXPORT void JNICALL Java_com_intel_wasm_api_Runtime_run(JNIEnv *env, jclass thiz) { - char error_buf[128] = {0}; - - void *(*malloc_func)(size_t) = &malloc; - void (*free_func)(void *) = &free; - LOGI("bh_memory_init_with_allocator"); - if (bh_memory_init_with_allocator((void *) malloc_func, (void *) free_func)) { - LOGI("Init memory with memory allocator failed.\n"); - return; - } - wasm_module_t wasm_module = NULL; wasm_module_inst_t wasm_module_inst = NULL; - + RuntimeInitArgs init_args; uint wasm_file_size = 0; uint8_t *wasm_file_buf = NULL; + char error_buf[128] = {0}; + memset(&init_args, 0, sizeof(RuntimeInitArgs)); + + init_args.mem_alloc_type = Alloc_With_Allocator; + init_args.mem_alloc_option.allocator.malloc_func = (void*)malloc; + init_args.mem_alloc_option.allocator.realloc_func = (void*)realloc; + init_args.mem_alloc_option.allocator.free_func = (void*)free; + + LOGI("wasm_runtime_full_init"); /* initialize runtime environment */ - LOGI("wasm_runtime_init"); - if (!wasm_runtime_init()) { - LOGI("goto fail1\n"); - goto fail1; + if (!wasm_runtime_full_init(&init_args)) { + LOGI("Init runtime failed.\n"); + return; } // set log level to INFO @@ -112,8 +110,8 @@ Java_com_intel_wasm_api_Runtime_run(JNIEnv *env, jclass thiz) { if (!(wasm_module = wasm_runtime_load(wasm_file_buf, wasm_file_size, error_buf, sizeof(error_buf)))) { LOGI("in wasm_runtime_load %s\n", error_buf); - LOGI("goto fail3\n"); - goto fail3; + LOGI("goto fail1\n"); + goto fail1; } /* instantiate the module */ @@ -124,8 +122,8 @@ Java_com_intel_wasm_api_Runtime_run(JNIEnv *env, jclass thiz) { error_buf, sizeof(error_buf)))) { LOGI("%s\n", error_buf); - LOGI("goto fail4\n"); - goto fail4; + LOGI("goto fail2\n"); + goto fail2; } LOGI("run main() of the application"); @@ -135,23 +133,18 @@ Java_com_intel_wasm_api_Runtime_run(JNIEnv *env, jclass thiz) { LOGI("wasm_runtime_deinstantiate"); wasm_runtime_deinstantiate(wasm_module_inst); - fail4: +fail2: /* unload the module */ LOGI("wasm_runtime_unload"); wasm_runtime_unload(wasm_module); - fail3: +fail1: // in our case, we don't need a free, but it is not a typical one /* free the file buffer */ //bh_free((void *) wasm_file_buf); - fail2: /* destroy runtime environment */ LOGI("wasm_runtime_destroy"); wasm_runtime_destroy(); - - fail1: - LOGI("bh_memory_destroy"); - bh_memory_destroy(); return; } diff --git a/product-mini/platforms/darwin/main.c b/product-mini/platforms/darwin/main.c index 5f0ba1525..24c728862 100644 --- a/product-mini/platforms/darwin/main.c +++ b/product-mini/platforms/darwin/main.c @@ -11,7 +11,6 @@ #include "bh_platform.h" #include "bh_assert.h" #include "bh_log.h" -#include "bh_memory.h" #include "wasm_export.h" static int app_argc; @@ -24,9 +23,11 @@ static int print_help() bh_printf(" -f|--function name Specify function name to run in module\n" " rather than main\n"); #if WASM_ENABLE_LOG != 0 - bh_printf(" -v=X Set log verbose level (0 to 5, default is 2),\n" + bh_printf(" -v=n Set log verbose level (0 to 5, default is 2),\n" " larger level with more log\n"); #endif + bh_printf(" --stack-size=n Set maximum stack size in bytes, default is 16 KB\n"); + bh_printf(" --heap-size=n Set maximum heap size in bytes, default is 16 KB\n"); bh_printf(" --repl Start a very simple REPL (read-eval-print-loop) mode\n" " that runs commands in the form of `FUNC ARG...`\n"); #if WASM_ENABLE_LIBC_WASI != 0 @@ -153,8 +154,10 @@ int main(int argc, char *argv[]) const char *func_name = NULL; uint8 *wasm_file_buf = NULL; uint32 wasm_file_size; + uint32 stack_size = 16 * 1024, heap_size = 16 * 1024; wasm_module_t wasm_module = NULL; wasm_module_inst_t wasm_module_inst = NULL; + RuntimeInitArgs init_args; char error_buf[128] = { 0 }; #if WASM_ENABLE_LOG != 0 int log_verbose_level = 2; @@ -186,6 +189,16 @@ int main(int argc, char *argv[]) #endif else if (!strcmp(argv[0], "--repl")) is_repl_mode = true; + else if (!strncmp(argv[0], "--stack-size=", 13)) { + if (argv[0][13] == '\0') + return print_help(); + stack_size = atoi(argv[0] + 13); + } + else if (!strncmp(argv[0], "--heap-size=", 12)) { + if (argv[0][12] == '\0') + return print_help(); + heap_size = atoi(argv[0] + 12); + } #if WASM_ENABLE_LIBC_WASI != 0 else if (!strncmp(argv[0], "--dir=", 6)) { if (argv[0][6] == '\0') @@ -228,35 +241,37 @@ int main(int argc, char *argv[]) app_argc = argc; app_argv = argv; + memset(&init_args, 0, sizeof(RuntimeInitArgs)); + #if USE_GLOBAL_HEAP_BUF != 0 - if (bh_memory_init_with_pool(global_heap_buf, sizeof(global_heap_buf)) - != 0) { - bh_printf("Init memory with global heap buffer failed.\n"); - return -1; - } + init_args.mem_alloc_type = Alloc_With_Pool; + init_args.mem_alloc_option.pool.heap_buf = global_heap_buf; + init_args.mem_alloc_option.pool.heap_size = sizeof(global_heap_buf); #else - if (bh_memory_init_with_allocator(malloc, free)) { - bh_printf("Init memory with memory allocator failed.\n"); - return -1; - } + init_args.mem_alloc_type = Alloc_With_Allocator; + init_args.mem_alloc_option.allocator.malloc_func = malloc; + init_args.mem_alloc_option.allocator.realloc_func = realloc; + init_args.mem_alloc_option.allocator.free_func = free; #endif /* initialize runtime environment */ - if (!wasm_runtime_init()) - goto fail1; + if (!wasm_runtime_full_init(&init_args)) { + bh_printf("Init runtime environment failed.\n"); + return -1; + } bh_log_set_verbose_level(log_verbose_level); /* load WASM byte buffer from WASM bin file */ if (!(wasm_file_buf = (uint8*) bh_read_file_to_buffer(wasm_file, &wasm_file_size))) - goto fail2; + goto fail1; /* load WASM module */ if (!(wasm_module = wasm_runtime_load(wasm_file_buf, wasm_file_size, error_buf, sizeof(error_buf)))) { bh_printf("%s\n", error_buf); - goto fail3; + goto fail2; } #if WASM_ENABLE_LIBC_WASI != 0 @@ -269,12 +284,12 @@ int main(int argc, char *argv[]) /* instantiate the module */ if (!(wasm_module_inst = wasm_runtime_instantiate(wasm_module, - 64 * 1024, /* stack size */ - 64 * 1024, /* heap size */ + stack_size, + heap_size, error_buf, sizeof(error_buf)))) { bh_printf("%s\n", error_buf); - goto fail4; + goto fail3; } if (is_repl_mode) @@ -287,20 +302,17 @@ int main(int argc, char *argv[]) /* destroy the module instance */ wasm_runtime_deinstantiate(wasm_module_inst); -fail4: +fail3: /* unload the module */ wasm_runtime_unload(wasm_module); -fail3: - /* free the file buffer */ - bh_free(wasm_file_buf); - fail2: - /* destroy runtime environment */ - wasm_runtime_destroy(); + /* free the file buffer */ + wasm_runtime_free(wasm_file_buf); fail1: - bh_memory_destroy(); + /* destroy runtime environment */ + wasm_runtime_destroy(); return 0; } diff --git a/product-mini/platforms/linux-sgx/enclave-sample/Enclave/Enclave.cpp b/product-mini/platforms/linux-sgx/enclave-sample/Enclave/Enclave.cpp index 714360ae7..bfa0252e7 100644 --- a/product-mini/platforms/linux-sgx/enclave-sample/Enclave/Enclave.cpp +++ b/product-mini/platforms/linux-sgx/enclave-sample/Enclave/Enclave.cpp @@ -7,7 +7,6 @@ #include #include "Enclave_t.h" #include "test_wasm.h" -#include "bh_memory.h" #include "wasm_export.h" static char global_heap_buf[2* 1024 * 1024] = { 0 }; @@ -50,17 +49,21 @@ void ecall_iwasm_main() int wasm_file_size; wasm_module_t wasm_module = NULL; wasm_module_inst_t wasm_module_inst = NULL; + RuntimeInitArgs init_args; char error_buf[128]; - if (bh_memory_init_with_pool(global_heap_buf, - sizeof(global_heap_buf)) != 0) { - ocall_print("Init global heap failed.\n"); - return; - } + memset(&init_args, 0, sizeof(RuntimeInitArgs)); + + init_args.mem_alloc_type = Alloc_With_Pool; + init_args.mem_alloc_option.pool.heap_buf = global_heap_buf; + init_args.mem_alloc_option.pool.heap_size = sizeof(global_heap_buf); /* initialize runtime environment */ - if (!wasm_runtime_init()) - goto fail1; + if (!wasm_runtime_full_init(&init_args)) { + ocall_print("Init runtime environment failed."); + ocall_print("\n"); + return; + } /* load WASM byte buffer from byte buffer of include file */ wasm_file_buf = (uint8_t*) wasm_test_file; @@ -71,7 +74,7 @@ void ecall_iwasm_main() error_buf, sizeof(error_buf)))) { ocall_print(error_buf); ocall_print("\n"); - goto fail2; + goto fail1; } /* instantiate the module */ @@ -82,7 +85,7 @@ void ecall_iwasm_main() sizeof(error_buf)))) { ocall_print(error_buf); ocall_print("\n"); - goto fail3; + goto fail2; } /* execute the main function of wasm app */ @@ -91,15 +94,12 @@ void ecall_iwasm_main() /* destroy the module instance */ wasm_runtime_deinstantiate(wasm_module_inst); -fail3: +fail2: /* unload the module */ wasm_runtime_unload(wasm_module); -fail2: +fail1: /* destroy runtime environment */ wasm_runtime_destroy(); - -fail1: - bh_memory_destroy(); } diff --git a/product-mini/platforms/linux/main.c b/product-mini/platforms/linux/main.c index 0cc3ca08e..24c728862 100644 --- a/product-mini/platforms/linux/main.c +++ b/product-mini/platforms/linux/main.c @@ -11,7 +11,6 @@ #include "bh_platform.h" #include "bh_assert.h" #include "bh_log.h" -#include "bh_memory.h" #include "wasm_export.h" static int app_argc; @@ -24,9 +23,11 @@ static int print_help() bh_printf(" -f|--function name Specify function name to run in module\n" " rather than main\n"); #if WASM_ENABLE_LOG != 0 - bh_printf(" -v=X Set log verbose level (0 to 5, default is 2),\n" + bh_printf(" -v=n Set log verbose level (0 to 5, default is 2),\n" " larger level with more log\n"); #endif + bh_printf(" --stack-size=n Set maximum stack size in bytes, default is 16 KB\n"); + bh_printf(" --heap-size=n Set maximum heap size in bytes, default is 16 KB\n"); bh_printf(" --repl Start a very simple REPL (read-eval-print-loop) mode\n" " that runs commands in the form of `FUNC ARG...`\n"); #if WASM_ENABLE_LIBC_WASI != 0 @@ -153,6 +154,7 @@ int main(int argc, char *argv[]) const char *func_name = NULL; uint8 *wasm_file_buf = NULL; uint32 wasm_file_size; + uint32 stack_size = 16 * 1024, heap_size = 16 * 1024; wasm_module_t wasm_module = NULL; wasm_module_inst_t wasm_module_inst = NULL; RuntimeInitArgs init_args; @@ -187,6 +189,16 @@ int main(int argc, char *argv[]) #endif else if (!strcmp(argv[0], "--repl")) is_repl_mode = true; + else if (!strncmp(argv[0], "--stack-size=", 13)) { + if (argv[0][13] == '\0') + return print_help(); + stack_size = atoi(argv[0] + 13); + } + else if (!strncmp(argv[0], "--heap-size=", 12)) { + if (argv[0][12] == '\0') + return print_help(); + heap_size = atoi(argv[0] + 12); + } #if WASM_ENABLE_LIBC_WASI != 0 else if (!strncmp(argv[0], "--dir=", 6)) { if (argv[0][6] == '\0') @@ -233,15 +245,16 @@ int main(int argc, char *argv[]) #if USE_GLOBAL_HEAP_BUF != 0 init_args.mem_alloc_type = Alloc_With_Pool; - init_args.mem_alloc.pool.heap_buf = global_heap_buf; - init_args.mem_alloc.pool.heap_size = sizeof(global_heap_buf); + init_args.mem_alloc_option.pool.heap_buf = global_heap_buf; + init_args.mem_alloc_option.pool.heap_size = sizeof(global_heap_buf); #else init_args.mem_alloc_type = Alloc_With_Allocator; - init_args.mem_alloc.allocator.malloc_func = malloc; - init_args.mem_alloc.allocator.realloc_func = realloc; - init_args.mem_alloc.allocator.free_func = free; + init_args.mem_alloc_option.allocator.malloc_func = malloc; + init_args.mem_alloc_option.allocator.realloc_func = realloc; + init_args.mem_alloc_option.allocator.free_func = free; #endif + /* initialize runtime environment */ if (!wasm_runtime_full_init(&init_args)) { bh_printf("Init runtime environment failed.\n"); return -1; @@ -271,8 +284,8 @@ int main(int argc, char *argv[]) /* instantiate the module */ if (!(wasm_module_inst = wasm_runtime_instantiate(wasm_module, - 48 * 1024, /* stack size */ - 16 * 1024, /* heap size */ + stack_size, + heap_size, error_buf, sizeof(error_buf)))) { bh_printf("%s\n", error_buf); @@ -295,11 +308,11 @@ fail3: fail2: /* free the file buffer */ - bh_free(wasm_file_buf); + wasm_runtime_free(wasm_file_buf); fail1: /* destroy runtime environment */ - wasm_runtime_full_destroy(); + wasm_runtime_destroy(); return 0; } diff --git a/product-mini/platforms/vxworks/main.c b/product-mini/platforms/vxworks/main.c index 5f0ba1525..24c728862 100644 --- a/product-mini/platforms/vxworks/main.c +++ b/product-mini/platforms/vxworks/main.c @@ -11,7 +11,6 @@ #include "bh_platform.h" #include "bh_assert.h" #include "bh_log.h" -#include "bh_memory.h" #include "wasm_export.h" static int app_argc; @@ -24,9 +23,11 @@ static int print_help() bh_printf(" -f|--function name Specify function name to run in module\n" " rather than main\n"); #if WASM_ENABLE_LOG != 0 - bh_printf(" -v=X Set log verbose level (0 to 5, default is 2),\n" + bh_printf(" -v=n Set log verbose level (0 to 5, default is 2),\n" " larger level with more log\n"); #endif + bh_printf(" --stack-size=n Set maximum stack size in bytes, default is 16 KB\n"); + bh_printf(" --heap-size=n Set maximum heap size in bytes, default is 16 KB\n"); bh_printf(" --repl Start a very simple REPL (read-eval-print-loop) mode\n" " that runs commands in the form of `FUNC ARG...`\n"); #if WASM_ENABLE_LIBC_WASI != 0 @@ -153,8 +154,10 @@ int main(int argc, char *argv[]) const char *func_name = NULL; uint8 *wasm_file_buf = NULL; uint32 wasm_file_size; + uint32 stack_size = 16 * 1024, heap_size = 16 * 1024; wasm_module_t wasm_module = NULL; wasm_module_inst_t wasm_module_inst = NULL; + RuntimeInitArgs init_args; char error_buf[128] = { 0 }; #if WASM_ENABLE_LOG != 0 int log_verbose_level = 2; @@ -186,6 +189,16 @@ int main(int argc, char *argv[]) #endif else if (!strcmp(argv[0], "--repl")) is_repl_mode = true; + else if (!strncmp(argv[0], "--stack-size=", 13)) { + if (argv[0][13] == '\0') + return print_help(); + stack_size = atoi(argv[0] + 13); + } + else if (!strncmp(argv[0], "--heap-size=", 12)) { + if (argv[0][12] == '\0') + return print_help(); + heap_size = atoi(argv[0] + 12); + } #if WASM_ENABLE_LIBC_WASI != 0 else if (!strncmp(argv[0], "--dir=", 6)) { if (argv[0][6] == '\0') @@ -228,35 +241,37 @@ int main(int argc, char *argv[]) app_argc = argc; app_argv = argv; + memset(&init_args, 0, sizeof(RuntimeInitArgs)); + #if USE_GLOBAL_HEAP_BUF != 0 - if (bh_memory_init_with_pool(global_heap_buf, sizeof(global_heap_buf)) - != 0) { - bh_printf("Init memory with global heap buffer failed.\n"); - return -1; - } + init_args.mem_alloc_type = Alloc_With_Pool; + init_args.mem_alloc_option.pool.heap_buf = global_heap_buf; + init_args.mem_alloc_option.pool.heap_size = sizeof(global_heap_buf); #else - if (bh_memory_init_with_allocator(malloc, free)) { - bh_printf("Init memory with memory allocator failed.\n"); - return -1; - } + init_args.mem_alloc_type = Alloc_With_Allocator; + init_args.mem_alloc_option.allocator.malloc_func = malloc; + init_args.mem_alloc_option.allocator.realloc_func = realloc; + init_args.mem_alloc_option.allocator.free_func = free; #endif /* initialize runtime environment */ - if (!wasm_runtime_init()) - goto fail1; + if (!wasm_runtime_full_init(&init_args)) { + bh_printf("Init runtime environment failed.\n"); + return -1; + } bh_log_set_verbose_level(log_verbose_level); /* load WASM byte buffer from WASM bin file */ if (!(wasm_file_buf = (uint8*) bh_read_file_to_buffer(wasm_file, &wasm_file_size))) - goto fail2; + goto fail1; /* load WASM module */ if (!(wasm_module = wasm_runtime_load(wasm_file_buf, wasm_file_size, error_buf, sizeof(error_buf)))) { bh_printf("%s\n", error_buf); - goto fail3; + goto fail2; } #if WASM_ENABLE_LIBC_WASI != 0 @@ -269,12 +284,12 @@ int main(int argc, char *argv[]) /* instantiate the module */ if (!(wasm_module_inst = wasm_runtime_instantiate(wasm_module, - 64 * 1024, /* stack size */ - 64 * 1024, /* heap size */ + stack_size, + heap_size, error_buf, sizeof(error_buf)))) { bh_printf("%s\n", error_buf); - goto fail4; + goto fail3; } if (is_repl_mode) @@ -287,20 +302,17 @@ int main(int argc, char *argv[]) /* destroy the module instance */ wasm_runtime_deinstantiate(wasm_module_inst); -fail4: +fail3: /* unload the module */ wasm_runtime_unload(wasm_module); -fail3: - /* free the file buffer */ - bh_free(wasm_file_buf); - fail2: - /* destroy runtime environment */ - wasm_runtime_destroy(); + /* free the file buffer */ + wasm_runtime_free(wasm_file_buf); fail1: - bh_memory_destroy(); + /* destroy runtime environment */ + wasm_runtime_destroy(); return 0; } diff --git a/product-mini/platforms/zephyr/simple/src/main.c b/product-mini/platforms/zephyr/simple/src/main.c index add1c24b5..f7bbfaed9 100644 --- a/product-mini/platforms/zephyr/simple/src/main.c +++ b/product-mini/platforms/zephyr/simple/src/main.c @@ -8,7 +8,6 @@ #include "bh_platform.h" #include "bh_assert.h" #include "bh_log.h" -#include "bh_memory.h" #include "wasm_export.h" #include "test_wasm.h" @@ -63,6 +62,7 @@ void iwasm_main(void *arg1, void *arg2, void *arg3) uint32 wasm_file_size; wasm_module_t wasm_module = NULL; wasm_module_inst_t wasm_module_inst = NULL; + RuntimeInitArgs init_args; char error_buf[128]; #if WASM_ENABLE_LOG != 0 int log_verbose_level = 2; @@ -72,15 +72,17 @@ void iwasm_main(void *arg1, void *arg2, void *arg3) (void) arg2; (void) arg3; - if (bh_memory_init_with_pool(global_heap_buf, sizeof(global_heap_buf)) - != 0) { - bh_printf("Init global heap failed.\n"); - return; - } + memset(&init_args, 0, sizeof(RuntimeInitArgs)); + + init_args.mem_alloc_type = Alloc_With_Pool; + init_args.mem_alloc_option.pool.heap_buf = global_heap_buf; + init_args.mem_alloc_option.pool.heap_size = sizeof(global_heap_buf); /* initialize runtime environment */ - if (!wasm_runtime_init()) - goto fail1; + if (!wasm_runtime_full_init(&init_args)) { + bh_printf("Init runtime environment failed.\n"); + return -1; + } #if WASM_ENABLE_LOG != 0 bh_log_set_verbose_level(log_verbose_level); @@ -94,7 +96,7 @@ void iwasm_main(void *arg1, void *arg2, void *arg3) if (!(wasm_module = wasm_runtime_load(wasm_file_buf, wasm_file_size, error_buf, sizeof(error_buf)))) { bh_printf("%s\n", error_buf); - goto fail2; + goto fail1; } /* instantiate the module */ @@ -104,7 +106,7 @@ void iwasm_main(void *arg1, void *arg2, void *arg3) error_buf, sizeof(error_buf)))) { bh_printf("%s\n", error_buf); - goto fail3; + goto fail2; } /* invoke the main function */ @@ -113,16 +115,14 @@ void iwasm_main(void *arg1, void *arg2, void *arg3) /* destroy the module instance */ wasm_runtime_deinstantiate(wasm_module_inst); - fail3: +fail2: /* unload the module */ wasm_runtime_unload(wasm_module); - fail2: +fail1: /* destroy runtime environment */ wasm_runtime_destroy(); - fail1: bh_memory_destroy(); - end = k_uptime_get_32(); printf("elpase: %d\n", (end - start)); diff --git a/samples/gui/lv_config/lv_conf.h b/samples/gui/lv_config/lv_conf.h index e0caf37ab..5c46d7e83 100644 --- a/samples/gui/lv_config/lv_conf.h +++ b/samples/gui/lv_config/lv_conf.h @@ -84,9 +84,9 @@ typedef int16_t lv_coord_t; /* Automatically defrag. on free. Defrag. means joining the adjacent free cells. */ # define LV_MEM_AUTO_DEFRAG 1 #else /*LV_MEM_CUSTOM*/ -# define LV_MEM_CUSTOM_INCLUDE "bh_memory.h" /*Header for the dynamic memory function*/ -# define LV_MEM_CUSTOM_ALLOC bh_malloc /*Wrapper to malloc*/ -# define LV_MEM_CUSTOM_FREE bh_free /*Wrapper to free*/ +# define LV_MEM_CUSTOM_INCLUDE "bh_config.h" /*Header for the dynamic memory function*/ +# define LV_MEM_CUSTOM_ALLOC BH_MALLOC /*Wrapper to malloc*/ +# define LV_MEM_CUSTOM_FREE BH_FREE /*Wrapper to free*/ #endif /*LV_MEM_CUSTOM*/ /* Garbage Collector settings diff --git a/samples/gui/wasm-runtime-wgl/src/platform/linux/iwasm_main.c b/samples/gui/wasm-runtime-wgl/src/platform/linux/iwasm_main.c index b3b324d5d..38e121248 100644 --- a/samples/gui/wasm-runtime-wgl/src/platform/linux/iwasm_main.c +++ b/samples/gui/wasm-runtime-wgl/src/platform/linux/iwasm_main.c @@ -27,7 +27,6 @@ #include "bh_common.h" #include "bh_queue.h" #include "bh_thread.h" -#include "bh_memory.h" #include "runtime_sensor.h" #include "bi-inc/attr_container.h" #include "module_wasm_app.h" @@ -466,19 +465,22 @@ static void hal_init(void) // Driver function int iwasm_main(int argc, char *argv[]) { + RuntimeInitArgs init_args; korp_thread tid; if (!parse_args(argc, argv)) return -1; - if (bh_memory_init_with_pool(global_heap_buf, sizeof(global_heap_buf)) - != 0) { - printf("Init global heap failed.\n"); - return -1; - } + memset(&init_args, 0, sizeof(RuntimeInitArgs)); - if (vm_thread_sys_init() != 0) { - goto fail1; + init_args.mem_alloc_type = Alloc_With_Pool; + init_args.mem_alloc_option.pool.heap_buf = global_heap_buf; + init_args.mem_alloc_option.pool.heap_size = sizeof(global_heap_buf); + + /* initialize runtime environment */ + if (!wasm_runtime_full_init(&init_args)) { + bh_printf("Init runtime environment failed.\n"); + return -1; } if (!init_connection_framework()) { @@ -513,7 +515,6 @@ int iwasm_main(int argc, char *argv[]) exit_connection_framework(); fail1: - bh_memory_destroy(); - + wasm_runtime_destroy(); return -1; } diff --git a/samples/gui/wasm-runtime-wgl/src/platform/zephyr/iwasm_main.c b/samples/gui/wasm-runtime-wgl/src/platform/zephyr/iwasm_main.c index af8d4d7ba..41edfe0aa 100644 --- a/samples/gui/wasm-runtime-wgl/src/platform/zephyr/iwasm_main.c +++ b/samples/gui/wasm-runtime-wgl/src/platform/zephyr/iwasm_main.c @@ -10,7 +10,6 @@ #include "bh_common.h" #include "bh_queue.h" #include "bh_thread.h" -#include "bh_memory.h" #include "runtime_sensor.h" #include "bi-inc/attr_container.h" #include "module_wasm_app.h" @@ -146,16 +145,19 @@ static void hal_init(void) int iwasm_main() { + RuntimeInitArgs init_args; host_init(); - if (bh_memory_init_with_pool(global_heap_buf, sizeof(global_heap_buf)) - != 0) { - printf("Init global heap failed.\n"); - return -1; - } + memset(&init_args, 0, sizeof(RuntimeInitArgs)); - if (vm_thread_sys_init() != 0) { - goto fail1; + init_args.mem_alloc_type = Alloc_With_Pool; + init_args.mem_alloc_option.pool.heap_buf = global_heap_buf; + init_args.mem_alloc_option.pool.heap_size = sizeof(global_heap_buf); + + /* initialize runtime environment */ + if (!wasm_runtime_full_init(&init_args)) { + bh_printf("Init runtime environment failed.\n"); + return -1; } wgl_init(); @@ -167,7 +169,6 @@ int iwasm_main() // TODO: app_manager_startup(&interface); -fail1: - bh_memory_destroy(); + wasm_runtime_destroy(); return -1; } diff --git a/samples/gui/wasm-runtime-wgl/src/platform/zephyr/main.c b/samples/gui/wasm-runtime-wgl/src/platform/zephyr/main.c index 74e007e97..612259044 100644 --- a/samples/gui/wasm-runtime-wgl/src/platform/zephyr/main.c +++ b/samples/gui/wasm-runtime-wgl/src/platform/zephyr/main.c @@ -10,7 +10,6 @@ #include "bh_log.h" #include "bh_platform_log.h" #include "wasm_export.h" -#include "bh_memory.h" extern int iwasm_main(); diff --git a/samples/gui/wasm-runtime-wgl/zephyr-build/CMakeLists.txt b/samples/gui/wasm-runtime-wgl/zephyr-build/CMakeLists.txt index 2ff88b002..005358c72 100644 --- a/samples/gui/wasm-runtime-wgl/zephyr-build/CMakeLists.txt +++ b/samples/gui/wasm-runtime-wgl/zephyr-build/CMakeLists.txt @@ -10,6 +10,9 @@ set (WAMR_BUILD_PLATFORM "zephyr") enable_language (ASM) +add_definitions(-DWA_MALLOC=wasm_runtime_malloc) +add_definitions(-DWA_FREE=wasm_runtime_free) + # Build as THUMB by default # change to "ARM[sub]", "THUMB[sub]", "X86_32", "MIPS" or "XTENSA" # if we want to support arm_32, x86, mips or xtensa @@ -17,7 +20,6 @@ if (NOT DEFINED WAMR_BUILD_TARGET) set (WAMR_BUILD_TARGET "THUMBV7") endif () - if (NOT DEFINED WAMR_BUILD_INTERP) # Enable Interpreter by default set (WAMR_BUILD_INTERP 1) diff --git a/samples/littlevgl/vgl-wasm-runtime/src/platform/linux/iwasm_main.c b/samples/littlevgl/vgl-wasm-runtime/src/platform/linux/iwasm_main.c index 18ad0331a..83f72c5c4 100644 --- a/samples/littlevgl/vgl-wasm-runtime/src/platform/linux/iwasm_main.c +++ b/samples/littlevgl/vgl-wasm-runtime/src/platform/linux/iwasm_main.c @@ -27,7 +27,6 @@ #include "bh_common.h" #include "bh_queue.h" #include "bh_thread.h" -#include "bh_memory.h" #include "runtime_sensor.h" #include "bi-inc/attr_container.h" #include "module_wasm_app.h" @@ -448,8 +447,6 @@ static bool parse_args(int argc, char *argv[]) } static NativeSymbol native_symbols[] = { - #include "runtime_sensor.inl" - #include "connection.inl" EXPORT_WASM_API_WITH_SIG(display_input_read, "(*)i"), EXPORT_WASM_API_WITH_SIG(display_flush, "(iiii*)"), EXPORT_WASM_API_WITH_SIG(display_fill, "(iiii*)"), @@ -461,29 +458,29 @@ static NativeSymbol native_symbols[] = { // Driver function int iwasm_main(int argc, char *argv[]) { + RuntimeInitArgs init_args; korp_thread tid; uint32 n_native_symbols; if (!parse_args(argc, argv)) return -1; - if (bh_memory_init_with_pool(global_heap_buf, sizeof(global_heap_buf)) - != 0) { - printf("Init global heap failed.\n"); + memset(&init_args, 0, sizeof(RuntimeInitArgs)); + + init_args.mem_alloc_type = Alloc_With_Pool; + init_args.mem_alloc_option.pool.heap_buf = global_heap_buf; + init_args.mem_alloc_option.pool.heap_size = sizeof(global_heap_buf); + + init_args.native_module_name = "env"; + init_args.n_native_symbols = sizeof(native_symbols) / sizeof(NativeSymbol); + init_args.native_symbols = native_symbols; + + /* initialize runtime environment */ + if (!wasm_runtime_full_init(&init_args)) { + bh_printf("Init runtime environment failed.\n"); return -1; } - if (vm_thread_sys_init() != 0) { - goto fail1; - } - - /* Register native functions */ - n_native_symbols = sizeof(native_symbols) / sizeof(NativeSymbol); - if (!wasm_runtime_register_natives("env", - native_symbols, n_native_symbols)) { - goto fail1; - } - if (!init_connection_framework()) { vm_thread_sys_destroy(); goto fail1; @@ -514,7 +511,7 @@ int iwasm_main(int argc, char *argv[]) exit_connection_framework(); fail1: - bh_memory_destroy(); + wasm_runtime_destroy(); return -1; } diff --git a/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/iwasm_main.c b/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/iwasm_main.c index a9639dc20..cb140306a 100644 --- a/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/iwasm_main.c +++ b/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/iwasm_main.c @@ -10,7 +10,6 @@ #include "bh_common.h" #include "bh_queue.h" #include "bh_thread.h" -#include "bh_memory.h" #include "runtime_sensor.h" #include "bi-inc/attr_container.h" #include "module_wasm_app.h" @@ -80,8 +79,6 @@ timer_ctx_t timer_ctx; static char global_heap_buf[370 * 1024] = { 0 }; static NativeSymbol native_symbols[] = { - #include "runtime_sensor.inl" - #include "connection.inl" EXPORT_WASM_API_WITH_SIG(display_input_read, "(*)i"), EXPORT_WASM_API_WITH_SIG(display_flush, "(iiii*)"), EXPORT_WASM_API_WITH_SIG(display_fill, "(iiii*)"), @@ -92,28 +89,28 @@ static NativeSymbol native_symbols[] = { int iwasm_main() { + RuntimeInitArgs init_args; korp_thread tid, tm_tid; uint32 n_native_symbols; host_init(); - if (bh_memory_init_with_pool(global_heap_buf, sizeof(global_heap_buf)) - != 0) { - printf("Init global heap failed.\n"); + memset(&init_args, 0, sizeof(RuntimeInitArgs)); + + init_args.mem_alloc_type = Alloc_With_Pool; + init_args.mem_alloc_option.pool.heap_buf = global_heap_buf; + init_args.mem_alloc_option.pool.heap_size = sizeof(global_heap_buf); + + init_args.native_module_name = "env"; + init_args.n_native_symbols = sizeof(native_symbols) / sizeof(NativeSymbol); + init_args.native_symbols = native_symbols; + + /* initialize runtime environment */ + if (!wasm_runtime_full_init(&init_args)) { + bh_printf("Init runtime environment failed.\n"); return -1; } - if (vm_thread_sys_init() != 0) { - goto fail1; - } - - /* Register native functions */ - n_native_symbols = sizeof(native_symbols) / sizeof(NativeSymbol); - if (!wasm_runtime_register_natives("env", - native_symbols, n_native_symbols)) { - goto fail1; - } - display_init(); // timer manager @@ -122,7 +119,6 @@ int iwasm_main() // TODO: app_manager_startup(&interface); -fail1: - bh_memory_destroy(); + wasm_runtime_destroy(); return -1; } diff --git a/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/main.c b/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/main.c index 231073fa5..c12fbe632 100644 --- a/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/main.c +++ b/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/main.c @@ -10,9 +10,10 @@ #include "bh_log.h" #include "bh_platform_log.h" #include "wasm_export.h" -#include "bh_memory.h" + extern void display_init(void); extern int iwasm_main(); + void main(void) { display_init(); diff --git a/samples/littlevgl/vgl-wasm-runtime/zephyr-build/CMakeLists.txt b/samples/littlevgl/vgl-wasm-runtime/zephyr-build/CMakeLists.txt index 7458080d2..723ff8fa9 100644 --- a/samples/littlevgl/vgl-wasm-runtime/zephyr-build/CMakeLists.txt +++ b/samples/littlevgl/vgl-wasm-runtime/zephyr-build/CMakeLists.txt @@ -10,6 +10,9 @@ set (WAMR_BUILD_PLATFORM "zephyr") enable_language (ASM) +add_definitions(-DWA_MALLOC=wasm_runtime_malloc) +add_definitions(-DWA_FREE=wasm_runtime_free) + # Build as THUMB by default # change to "ARM[sub]", "THUMB[sub]", "X86_32", "MIPS_32" or "XTENSA_32" # if we want to support arm_32, x86, mips or xtensa diff --git a/samples/simple/src/iwasm_main.c b/samples/simple/src/iwasm_main.c index e9b389d21..98caa655f 100644 --- a/samples/simple/src/iwasm_main.c +++ b/samples/simple/src/iwasm_main.c @@ -27,7 +27,6 @@ #include "bh_common.h" #include "bh_queue.h" #include "bh_thread.h" -#include "bh_memory.h" #include "runtime_sensor.h" #include "bi-inc/attr_container.h" #include "module_wasm_app.h" @@ -462,54 +461,50 @@ static bool parse_args(int argc, char *argv[]) // Driver function int iwasm_main(int argc, char *argv[]) { + RuntimeInitArgs init_args; korp_thread tid; if (!parse_args(argc, argv)) return -1; -#if 1 - if (bh_memory_init_with_pool(global_heap_buf, sizeof(global_heap_buf)) + memset(&init_args, 0, sizeof(RuntimeInitArgs)); + +#if USE_GLOBAL_HEAP_BUF != 0 + init_args.mem_alloc_type = Alloc_With_Pool; + init_args.mem_alloc_option.pool.heap_buf = global_heap_buf; + init_args.mem_alloc_option.pool.heap_size = sizeof(global_heap_buf); #else - if (bh_memory_init_with_allocator(malloc, free) + init_args.mem_alloc_type = Alloc_With_Allocator; + init_args.mem_alloc_option.allocator.malloc_func = malloc; + init_args.mem_alloc_option.allocator.realloc_func = realloc; + init_args.mem_alloc_option.allocator.free_func = free; #endif - != 0) { - printf("Init global heap failed.\n"); + + /* initialize runtime environment */ + if (!wasm_runtime_full_init(&init_args)) { + bh_printf("Init runtime environment failed.\n"); return -1; } - if (vm_thread_sys_init() != 0) { - goto fail1; - } - - // - // timer manager - // + /* timer manager */ init_wasm_timer(); - - // - // connection framework - // + /* connection framework */ if (!init_connection_framework()) { - vm_thread_sys_destroy(); goto fail1; } - // - // sensor framework - // + /* sensor framework */ init_sensor_framework(); // add the sys sensor objects add_sys_sensor("sensor_test", - "This is a sensor for test", - 0, - 1000, - read_test_sensor, + "This is a sensor for test", + 0, + 1000, + read_test_sensor, config_test_sensor); start_sensor_framework(); - - #ifndef CONNECTION_UART if (server_mode) vm_thread_create(&tid, func_server_mode, NULL, @@ -527,7 +522,7 @@ int iwasm_main(int argc, char *argv[]) exit_connection_framework(); fail1: - bh_memory_destroy(); + wasm_runtime_destroy(); return -1; } diff --git a/test-tools/host-tool/CMakeLists.txt b/test-tools/host-tool/CMakeLists.txt index e5d3ce0f8..e45b4de50 100644 --- a/test-tools/host-tool/CMakeLists.txt +++ b/test-tools/host-tool/CMakeLists.txt @@ -50,7 +50,6 @@ SET(SOURCES ${HOST_TOOL_SRC} ${PLATFORM_SHARED_SOURCE} ${UTILS_SHARED_SOURCE} - ${MEM_ALLOC_DIR}/bh_memory.c ${NATIVE_INTERFACE_SOURCE} ${CJSON_SOURCE} ${LIB_HOST_AGENT_SOURCE} diff --git a/test-tools/host-tool/src/host_tool_utils.c b/test-tools/host-tool/src/host_tool_utils.c index 17084da99..1444715b0 100644 --- a/test-tools/host-tool/src/host_tool_utils.c +++ b/test-tools/host-tool/src/host_tool_utils.c @@ -23,10 +23,14 @@ typedef union jvalue { double d; } jvalue; +#ifndef bh_memcpy_s +int b_memcpy_s(void * s1, unsigned int s1max, + const void * s2, unsigned int n); #define bh_memcpy_s(dest, dlen, src, slen) do { \ int _ret = slen == 0 ? 0 : b_memcpy_s (dest, dlen, src, slen); \ (void)_ret; \ } while (0) +#endif static inline int16_t get_int16(const char *buf) { diff --git a/wamr-compiler/main.c b/wamr-compiler/main.c index 8143f38ba..39f82abda 100644 --- a/wamr-compiler/main.c +++ b/wamr-compiler/main.c @@ -5,7 +5,6 @@ #include #include "bh_platform.h" -#include "bh_memory.h" #include "bh_assert.h" #include "bh_log.h" #include "wasm_export.h" @@ -52,6 +51,7 @@ main(int argc, char *argv[]) wasm_module_t wasm_module = NULL; aot_comp_data_t comp_data = NULL; aot_comp_context_t comp_ctx = NULL; + RuntimeInitArgs init_args; AOTCompOption option = { 0 }; char error_buf[128]; int log_verbose_level = 2; @@ -134,43 +134,47 @@ main(int argc, char *argv[]) wasm_file_name = argv[0]; - if (bh_memory_init_with_allocator(malloc, free)) { - bh_printf("Init memory with memory allocator failed.\n"); - return -1; - } + memset(&init_args, 0, sizeof(RuntimeInitArgs)); + + init_args.mem_alloc_type = Alloc_With_Allocator; + init_args.mem_alloc_option.allocator.malloc_func = malloc; + init_args.mem_alloc_option.allocator.realloc_func = realloc; + init_args.mem_alloc_option.allocator.free_func = free; /* initialize runtime environment */ - if (!wasm_runtime_init()) - goto fail1; + if (!wasm_runtime_full_init(&init_args)) { + bh_printf("Init runtime environment failed.\n"); + return -1; + } bh_log_set_verbose_level(log_verbose_level); /* load WASM byte buffer from WASM bin file */ if (!(wasm_file = (uint8*) bh_read_file_to_buffer(wasm_file_name, &wasm_file_size))) - goto fail2; + goto fail1; /* load WASM module */ if (!(wasm_module = wasm_runtime_load(wasm_file, wasm_file_size, error_buf, sizeof(error_buf)))) { bh_printf("%s\n", error_buf); - goto fail3; + goto fail2; } if (!(comp_data = aot_create_comp_data(wasm_module))) { bh_printf("%s\n", aot_get_last_error()); - goto fail4; + goto fail3; } if (!(comp_ctx = aot_create_comp_context(comp_data, &option))) { bh_printf("%s\n", aot_get_last_error()); - goto fail5; + goto fail4; } if (!aot_compile_wasm(comp_ctx)) { bh_printf("%s\n", aot_get_last_error()); - goto fail6; + goto fail5; } switch (option.output_format) { @@ -178,19 +182,19 @@ main(int argc, char *argv[]) case AOT_LLVMIR_OPT_FILE: if (!aot_emit_llvm_file(comp_ctx, out_file_name)) { bh_printf("%s\n", aot_get_last_error()); - goto fail6; + goto fail5; } break; case AOT_OBJECT_FILE: if (!aot_emit_object_file(comp_ctx, out_file_name)) { bh_printf("%s\n", aot_get_last_error()); - goto fail6; + goto fail5; } break; case AOT_FORMAT_FILE: if (!aot_emit_aot_file(comp_ctx, comp_data, out_file_name)) { bh_printf("%s\n", aot_get_last_error()); - goto fail6; + goto fail5; } break; default: @@ -199,29 +203,25 @@ main(int argc, char *argv[]) bh_printf("Compile success, file %s was generated.\n", out_file_name); -fail6: +fail5: /* Destroy compiler context */ aot_destroy_comp_context(comp_ctx); -fail5: +fail4: /* Destroy compile data */ aot_destroy_comp_data(comp_data); -fail4: +fail3: /* Unload WASM module */ wasm_runtime_unload(wasm_module); -fail3: - /* free the file buffer */ - bh_free(wasm_file); - fail2: - /* Destroy runtime environment */ - wasm_runtime_destroy(); + /* free the file buffer */ + wasm_runtime_free(wasm_file); fail1: - bh_memory_destroy(); - + /* Destroy runtime environment */ + wasm_runtime_destroy(); return 0; } diff --git a/wamr-sdk/runtime/CMakeLists.txt b/wamr-sdk/runtime/CMakeLists.txt index 676daf56a..a6d47db83 100644 --- a/wamr-sdk/runtime/CMakeLists.txt +++ b/wamr-sdk/runtime/CMakeLists.txt @@ -7,6 +7,10 @@ project(runtime-sdk) SET (CMAKE_C_FLAGS "-O3") set (CMAKE_BUILD_TYPE Release) +add_definitions(-DBH_MALLOC=wasm_runtime_malloc) +add_definitions(-DBH_FREE=wasm_runtime_free) +add_definitions(-DWA_MALLOC=wasm_runtime_malloc) +add_definitions(-DWA_FREE=wasm_runtime_free) if (NOT DEFINED WAMR_BUILD_SDK_PROFILE) set (WAMR_BUILD_SDK_PROFILE "default")