From d4f2649d8f192536e34123d8adb8dfd24dc92b51 Mon Sep 17 00:00:00 2001 From: Wenyong Huang Date: Wed, 13 Oct 2021 23:46:37 +0800 Subject: [PATCH 1/8] Apply clang-format for core/shared and product-mini files --- core/shared/coap/er-coap/coap-constants.h | 196 +- core/shared/mem-alloc/ems/ems_alloc.c | 122 +- core/shared/mem-alloc/ems/ems_gc.h | 34 +- core/shared/mem-alloc/ems/ems_gc_internal.h | 86 +- core/shared/mem-alloc/ems/ems_hmu.c | 18 +- core/shared/mem-alloc/ems/ems_kfc.c | 94 +- core/shared/mem-alloc/mem_alloc.c | 52 +- core/shared/mem-alloc/mem_alloc.h | 5 +- core/shared/platform/alios/alios_platform.c | 6 +- core/shared/platform/alios/alios_thread.c | 41 +- core/shared/platform/alios/alios_time.c | 1 - .../shared/platform/alios/platform_internal.h | 9 +- core/shared/platform/android/platform_init.c | 41 +- .../platform/android/platform_internal.h | 54 +- .../common/freertos/freertos_malloc.c | 5 +- .../common/freertos/freertos_thread.c | 70 +- .../platform/common/freertos/freertos_time.c | 1 - core/shared/platform/common/math/math.c | 1707 +++++++++-------- .../platform/common/posix/posix_malloc.c | 3 - .../platform/common/posix/posix_memmap.c | 18 +- .../platform/common/posix/posix_thread.c | 94 +- .../shared/platform/common/posix/posix_time.c | 3 +- core/shared/platform/darwin/platform_init.c | 4 +- .../platform/darwin/platform_internal.h | 22 +- .../shared/platform/esp-idf/espidf_platform.c | 12 +- core/shared/platform/esp-idf/espidf_thread.c | 4 +- .../platform/esp-idf/platform_internal.h | 8 +- .../platform/include/platform_api_extension.h | 44 +- .../platform/include/platform_api_vmcore.h | 56 +- .../shared/platform/include/platform_common.h | 18 +- .../platform/linux-sgx/platform_internal.h | 11 +- core/shared/platform/linux-sgx/sgx_file.c | 343 ++-- core/shared/platform/linux-sgx/sgx_file.h | 260 +-- core/shared/platform/linux-sgx/sgx_platform.c | 56 +- core/shared/platform/linux-sgx/sgx_pthread.c | 40 +- core/shared/platform/linux-sgx/sgx_pthread.h | 18 +- .../platform/linux-sgx/sgx_rsrv_mem_mngr.h | 71 +- core/shared/platform/linux-sgx/sgx_signal.c | 7 +- core/shared/platform/linux-sgx/sgx_signal.h | 74 +- core/shared/platform/linux-sgx/sgx_socket.c | 60 +- core/shared/platform/linux-sgx/sgx_socket.h | 60 +- core/shared/platform/linux-sgx/sgx_thread.c | 60 +- core/shared/platform/linux-sgx/sgx_time.c | 71 +- core/shared/platform/linux-sgx/sgx_time.h | 29 +- .../platform/linux-sgx/untrusted/file.c | 145 +- .../platform/linux-sgx/untrusted/pthread.c | 18 +- .../platform/linux-sgx/untrusted/signal.c | 3 +- .../platform/linux-sgx/untrusted/socket.c | 32 +- .../platform/linux-sgx/untrusted/time.c | 31 +- core/shared/platform/linux/platform_init.c | 4 +- .../shared/platform/linux/platform_internal.h | 22 +- .../shared/platform/nuttx/platform_internal.h | 2 +- core/shared/platform/riot/platform_internal.h | 15 +- core/shared/platform/riot/riot_thread.c | 78 +- core/shared/platform/riot/riot_time.c | 1 - .../platform/rt-thread/platform_internal.h | 3 +- core/shared/platform/rt-thread/rtt_platform.c | 123 +- core/shared/platform/vxworks/platform_init.c | 4 +- .../platform/vxworks/platform_internal.h | 19 +- core/shared/platform/windows/platform_init.c | 4 +- .../platform/windows/platform_internal.h | 22 +- core/shared/platform/windows/win_malloc.c | 3 - core/shared/platform/windows/win_memmap.c | 12 +- core/shared/platform/windows/win_thread.c | 37 +- core/shared/platform/windows/win_time.c | 1 - .../platform/zephyr/platform_internal.h | 15 +- core/shared/platform/zephyr/zephyr_platform.c | 14 +- core/shared/platform/zephyr/zephyr_thread.c | 115 +- core/shared/platform/zephyr/zephyr_time.c | 1 - core/shared/utils/bh_assert.c | 10 +- core/shared/utils/bh_assert.h | 10 +- core/shared/utils/bh_common.c | 94 +- core/shared/utils/bh_common.h | 70 +- core/shared/utils/bh_hashmap.c | 33 +- core/shared/utils/bh_hashmap.h | 18 +- core/shared/utils/bh_list.c | 37 +- core/shared/utils/bh_list.h | 33 +- core/shared/utils/bh_log.c | 5 +- core/shared/utils/bh_log.h | 15 +- core/shared/utils/bh_platform.h | 3 - core/shared/utils/bh_queue.c | 68 +- core/shared/utils/bh_queue.h | 32 +- core/shared/utils/bh_vector.c | 22 +- core/shared/utils/bh_vector.h | 1 - core/shared/utils/runtime_timer.c | 41 +- core/shared/utils/runtime_timer.h | 42 +- core/shared/utils/uncommon/bh_getopt.c | 23 +- core/shared/utils/uncommon/bh_getopt.h | 3 +- core/shared/utils/uncommon/bh_read_file.c | 18 +- core/shared/utils/uncommon/bh_read_file.h | 1 - .../app-samples/hello-world-cmake/main.c | 6 +- .../app-samples/hello-world-cmake/print.c | 3 +- product-mini/app-samples/hello-world/main.c | 3 +- .../platforms/alios-things/src/main.c | 30 +- product-mini/platforms/android/wasm-jni.cpp | 29 +- product-mini/platforms/esp-idf/iwasm_main.c | 15 +- .../linux-sgx/enclave-sample/App/App.cpp | 221 +-- .../linux-sgx/enclave-sample/App/pal_api.h | 56 +- .../enclave-sample/Enclave/Enclave.cpp | 75 +- .../enclave-sample/Enclave/Enclave_test.cpp | 48 +- product-mini/platforms/posix/main.c | 28 +- product-mini/platforms/riot/iwasmt.c | 67 +- product-mini/platforms/rt-thread/iwasm.c | 292 +-- product-mini/platforms/windows/main.c | 74 +- .../platforms/zephyr/simple/src/main.c | 69 +- .../zephyr/simple/src/test_wasm_riscv64.h | 68 +- .../zephyr/simple/src/wasm-app-riscv64/main.c | 3 +- 107 files changed, 3458 insertions(+), 2920 deletions(-) diff --git a/core/shared/coap/er-coap/coap-constants.h b/core/shared/coap/er-coap/coap-constants.h index d2898f89dc..1de2ed9d8a 100644 --- a/core/shared/coap/er-coap/coap-constants.h +++ b/core/shared/coap/er-coap/coap-constants.h @@ -44,6 +44,7 @@ #ifndef COAP_CONSTANTS_H_ #define COAP_CONSTANTS_H_ +/* clang-format off */ #define COAP_DEFAULT_PORT 5683 #define COAP_DEFAULT_SECURE_PORT 5684 @@ -65,128 +66,129 @@ #define COAP_HEADER_OPTION_DELTA_MASK 0xF0 #define COAP_HEADER_OPTION_SHORT_LENGTH_MASK 0x0F +/* clang-format on */ /* CoAP message types */ typedef enum { - COAP_TYPE_CON, /* confirmables */ - COAP_TYPE_NON, /* non-confirmables */ - COAP_TYPE_ACK, /* acknowledgements */ - COAP_TYPE_RST /* reset */ + COAP_TYPE_CON, /* confirmables */ + COAP_TYPE_NON, /* non-confirmables */ + COAP_TYPE_ACK, /* acknowledgements */ + COAP_TYPE_RST /* reset */ } coap_message_type_t; +/* clang-format off */ /* CoAP request method codes */ typedef enum { - COAP_GET = 1, - COAP_POST, - COAP_PUT, - COAP_DELETE + COAP_GET = 1, + COAP_POST, COAP_PUT, + COAP_DELETE } coap_method_t; +/* clang-format on */ /* CoAP response codes */ typedef enum { - COAP_NO_ERROR = 0, - - CREATED_2_01 = 65, /* CREATED */ - DELETED_2_02 = 66, /* DELETED */ - VALID_2_03 = 67, /* NOT_MODIFIED */ - CHANGED_2_04 = 68, /* CHANGED */ - CONTENT_2_05 = 69, /* OK */ - CONTINUE_2_31 = 95, /* CONTINUE */ - - BAD_REQUEST_4_00 = 128, /* BAD_REQUEST */ - UNAUTHORIZED_4_01 = 129, /* UNAUTHORIZED */ - BAD_OPTION_4_02 = 130, /* BAD_OPTION */ - FORBIDDEN_4_03 = 131, /* FORBIDDEN */ - NOT_FOUND_4_04 = 132, /* NOT_FOUND */ - METHOD_NOT_ALLOWED_4_05 = 133, /* METHOD_NOT_ALLOWED */ - NOT_ACCEPTABLE_4_06 = 134, /* NOT_ACCEPTABLE */ - PRECONDITION_FAILED_4_12 = 140, /* BAD_REQUEST */ - REQUEST_ENTITY_TOO_LARGE_4_13 = 141, /* REQUEST_ENTITY_TOO_LARGE */ - UNSUPPORTED_MEDIA_TYPE_4_15 = 143, /* UNSUPPORTED_MEDIA_TYPE */ - - INTERNAL_SERVER_ERROR_5_00 = 160, /* INTERNAL_SERVER_ERROR */ - NOT_IMPLEMENTED_5_01 = 161, /* NOT_IMPLEMENTED */ - BAD_GATEWAY_5_02 = 162, /* BAD_GATEWAY */ - SERVICE_UNAVAILABLE_5_03 = 163, /* SERVICE_UNAVAILABLE */ - GATEWAY_TIMEOUT_5_04 = 164, /* GATEWAY_TIMEOUT */ - PROXYING_NOT_SUPPORTED_5_05 = 165, /* PROXYING_NOT_SUPPORTED */ - - /* Erbium errors */ - MEMORY_ALLOCATION_ERROR = 192, - PACKET_SERIALIZATION_ERROR, - - /* Erbium hooks */ - MANUAL_RESPONSE, - PING_RESPONSE + COAP_NO_ERROR = 0, + + CREATED_2_01 = 65, /* CREATED */ + DELETED_2_02 = 66, /* DELETED */ + VALID_2_03 = 67, /* NOT_MODIFIED */ + CHANGED_2_04 = 68, /* CHANGED */ + CONTENT_2_05 = 69, /* OK */ + CONTINUE_2_31 = 95, /* CONTINUE */ + + BAD_REQUEST_4_00 = 128, /* BAD_REQUEST */ + UNAUTHORIZED_4_01 = 129, /* UNAUTHORIZED */ + BAD_OPTION_4_02 = 130, /* BAD_OPTION */ + FORBIDDEN_4_03 = 131, /* FORBIDDEN */ + NOT_FOUND_4_04 = 132, /* NOT_FOUND */ + METHOD_NOT_ALLOWED_4_05 = 133, /* METHOD_NOT_ALLOWED */ + NOT_ACCEPTABLE_4_06 = 134, /* NOT_ACCEPTABLE */ + PRECONDITION_FAILED_4_12 = 140, /* BAD_REQUEST */ + REQUEST_ENTITY_TOO_LARGE_4_13 = 141, /* REQUEST_ENTITY_TOO_LARGE */ + UNSUPPORTED_MEDIA_TYPE_4_15 = 143, /* UNSUPPORTED_MEDIA_TYPE */ + + INTERNAL_SERVER_ERROR_5_00 = 160, /* INTERNAL_SERVER_ERROR */ + NOT_IMPLEMENTED_5_01 = 161, /* NOT_IMPLEMENTED */ + BAD_GATEWAY_5_02 = 162, /* BAD_GATEWAY */ + SERVICE_UNAVAILABLE_5_03 = 163, /* SERVICE_UNAVAILABLE */ + GATEWAY_TIMEOUT_5_04 = 164, /* GATEWAY_TIMEOUT */ + PROXYING_NOT_SUPPORTED_5_05 = 165, /* PROXYING_NOT_SUPPORTED */ + + /* Erbium errors */ + MEMORY_ALLOCATION_ERROR = 192, + PACKET_SERIALIZATION_ERROR, + + /* Erbium hooks */ + MANUAL_RESPONSE, + PING_RESPONSE } coap_status_t; /* CoAP header option numbers */ typedef enum { - COAP_OPTION_IF_MATCH = 1, /* 0-8 B */ - COAP_OPTION_URI_HOST = 3, /* 1-255 B */ - COAP_OPTION_ETAG = 4, /* 1-8 B */ - COAP_OPTION_IF_NONE_MATCH = 5, /* 0 B */ - COAP_OPTION_OBSERVE = 6, /* 0-3 B */ - COAP_OPTION_URI_PORT = 7, /* 0-2 B */ - COAP_OPTION_LOCATION_PATH = 8, /* 0-255 B */ - COAP_OPTION_URI_PATH = 11, /* 0-255 B */ - COAP_OPTION_CONTENT_FORMAT = 12, /* 0-2 B */ - COAP_OPTION_MAX_AGE = 14, /* 0-4 B */ - COAP_OPTION_URI_QUERY = 15, /* 0-255 B */ - COAP_OPTION_ACCEPT = 17, /* 0-2 B */ - COAP_OPTION_LOCATION_QUERY = 20, /* 0-255 B */ - COAP_OPTION_BLOCK2 = 23, /* 1-3 B */ - COAP_OPTION_BLOCK1 = 27, /* 1-3 B */ - COAP_OPTION_SIZE2 = 28, /* 0-4 B */ - COAP_OPTION_PROXY_URI = 35, /* 1-1034 B */ - COAP_OPTION_PROXY_SCHEME = 39, /* 1-255 B */ - COAP_OPTION_SIZE1 = 60, /* 0-4 B */ + COAP_OPTION_IF_MATCH = 1, /* 0-8 B */ + COAP_OPTION_URI_HOST = 3, /* 1-255 B */ + COAP_OPTION_ETAG = 4, /* 1-8 B */ + COAP_OPTION_IF_NONE_MATCH = 5, /* 0 B */ + COAP_OPTION_OBSERVE = 6, /* 0-3 B */ + COAP_OPTION_URI_PORT = 7, /* 0-2 B */ + COAP_OPTION_LOCATION_PATH = 8, /* 0-255 B */ + COAP_OPTION_URI_PATH = 11, /* 0-255 B */ + COAP_OPTION_CONTENT_FORMAT = 12, /* 0-2 B */ + COAP_OPTION_MAX_AGE = 14, /* 0-4 B */ + COAP_OPTION_URI_QUERY = 15, /* 0-255 B */ + COAP_OPTION_ACCEPT = 17, /* 0-2 B */ + COAP_OPTION_LOCATION_QUERY = 20, /* 0-255 B */ + COAP_OPTION_BLOCK2 = 23, /* 1-3 B */ + COAP_OPTION_BLOCK1 = 27, /* 1-3 B */ + COAP_OPTION_SIZE2 = 28, /* 0-4 B */ + COAP_OPTION_PROXY_URI = 35, /* 1-1034 B */ + COAP_OPTION_PROXY_SCHEME = 39, /* 1-255 B */ + COAP_OPTION_SIZE1 = 60, /* 0-4 B */ } coap_option_t; /* CoAP Content-Formats */ typedef enum { - TEXT_PLAIN = 0, - TEXT_XML = 1, - TEXT_CSV = 2, - TEXT_HTML = 3, - IMAGE_GIF = 21, - IMAGE_JPEG = 22, - IMAGE_PNG = 23, - IMAGE_TIFF = 24, - AUDIO_RAW = 25, - VIDEO_RAW = 26, - APPLICATION_LINK_FORMAT = 40, - APPLICATION_XML = 41, - APPLICATION_OCTET_STREAM = 42, - APPLICATION_RDF_XML = 43, - APPLICATION_SOAP_XML = 44, - APPLICATION_ATOM_XML = 45, - APPLICATION_XMPP_XML = 46, - APPLICATION_EXI = 47, - APPLICATION_FASTINFOSET = 48, - APPLICATION_SOAP_FASTINFOSET = 49, - APPLICATION_JSON = 50, - APPLICATION_X_OBIX_BINARY = 51 + TEXT_PLAIN = 0, + TEXT_XML = 1, + TEXT_CSV = 2, + TEXT_HTML = 3, + IMAGE_GIF = 21, + IMAGE_JPEG = 22, + IMAGE_PNG = 23, + IMAGE_TIFF = 24, + AUDIO_RAW = 25, + VIDEO_RAW = 26, + APPLICATION_LINK_FORMAT = 40, + APPLICATION_XML = 41, + APPLICATION_OCTET_STREAM = 42, + APPLICATION_RDF_XML = 43, + APPLICATION_SOAP_XML = 44, + APPLICATION_ATOM_XML = 45, + APPLICATION_XMPP_XML = 46, + APPLICATION_EXI = 47, + APPLICATION_FASTINFOSET = 48, + APPLICATION_SOAP_FASTINFOSET = 49, + APPLICATION_JSON = 50, + APPLICATION_X_OBIX_BINARY = 51 } coap_content_format_t; /** * Resource flags for allowed methods and special functionalities. */ typedef enum { - NO_FLAGS = 0, - - /* methods to handle */ - METHOD_GET = (1 << 0), - METHOD_POST = (1 << 1), - METHOD_PUT = (1 << 2), - METHOD_DELETE = (1 << 3), - - /* special flags */ - HAS_SUB_RESOURCES = (1 << 4), - IS_SEPARATE = (1 << 5), - IS_OBSERVABLE = (1 << 6), - IS_PERIODIC = (1 << 7) + NO_FLAGS = 0, + + /* methods to handle */ + METHOD_GET = (1 << 0), + METHOD_POST = (1 << 1), + METHOD_PUT = (1 << 2), + METHOD_DELETE = (1 << 3), + + /* special flags */ + HAS_SUB_RESOURCES = (1 << 4), + IS_SEPARATE = (1 << 5), + IS_OBSERVABLE = (1 << 6), + IS_PERIODIC = (1 << 7) } coap_resource_flags_t; #endif /* COAP_CONSTANTS_H_ */ -/** @} */ diff --git a/core/shared/mem-alloc/ems/ems_alloc.c b/core/shared/mem-alloc/ems/ems_alloc.c index 92094d7d47..1d432a763f 100644 --- a/core/shared/mem-alloc/ems/ems_alloc.c +++ b/core/shared/mem-alloc/ems/ems_alloc.c @@ -5,15 +5,11 @@ #include "ems_gc_internal.h" - static inline bool -hmu_is_in_heap(void *hmu, - gc_uint8 *heap_base_addr, - gc_uint8 *heap_end_addr) +hmu_is_in_heap(void *hmu, gc_uint8 *heap_base_addr, gc_uint8 *heap_end_addr) { gc_uint8 *addr = (gc_uint8 *)hmu; - return (addr >= heap_base_addr && addr < heap_end_addr) - ? true : false; + return (addr >= heap_base_addr && addr < heap_end_addr) ? true : false; } /** @@ -38,8 +34,7 @@ remove_tree_node(gc_heap_t *heap, hmu_tree_node_t *p) parent = p->parent; if (!parent || p == root /* p can not be the ROOT node */ || !hmu_is_in_heap(p, base_addr, end_addr) - || (parent != root - && !hmu_is_in_heap(parent, base_addr, end_addr))) { + || (parent != root && !hmu_is_in_heap(parent, base_addr, end_addr))) { goto fail; } @@ -139,8 +134,8 @@ unlink_hmu(gc_heap_t *heap, hmu_t *hmu) gc_size_t size; bh_assert(gci_is_heap_valid(heap)); - bh_assert(hmu && (gc_uint8*) hmu >= heap->base_addr - && (gc_uint8*) hmu < heap->base_addr + heap->current_size); + bh_assert(hmu && (gc_uint8 *)hmu >= heap->base_addr + && (gc_uint8 *)hmu < heap->base_addr + heap->current_size); if (hmu_get_ut(hmu) != HMU_FC) { heap->is_heap_corrupted = true; @@ -162,7 +157,7 @@ unlink_hmu(gc_heap_t *heap, hmu_t *hmu) return false; } node_next = get_hmu_normal_node_next(node); - if ((hmu_t*)node == hmu) { + if ((hmu_t *)node == hmu) { if (!node_prev) /* list head */ heap->kfc_normal_list[node_idx].next = node_next; else @@ -191,15 +186,15 @@ hmu_set_free_size(hmu_t *hmu) bh_assert(hmu && hmu_get_ut(hmu) == HMU_FC); size = hmu_get_size(hmu); - *((uint32*)((char*) hmu + size) - 1) = size; + *((uint32 *)((char *)hmu + size) - 1) = size; } /** * Add free chunk back to KFC * * @param heap should not be NULL and it should be a valid heap - * @param hmu should not be NULL and it should be a HMU of length @size inside @heap - * hmu should be 8-bytes aligned + * @param hmu should not be NULL and it should be a HMU of length @size inside + * @heap hmu should be 8-bytes aligned * @param size should be positive and multiple of 8 * hmu with size @size will be added into KFC as a new FC. */ @@ -212,11 +207,12 @@ gci_add_fc(gc_heap_t *heap, hmu_t *hmu, gc_size_t size) uint32 node_idx; bh_assert(gci_is_heap_valid(heap)); - bh_assert(hmu && (gc_uint8*)hmu >= heap->base_addr - && (gc_uint8*)hmu < heap->base_addr + heap->current_size); + bh_assert(hmu && (gc_uint8 *)hmu >= heap->base_addr + && (gc_uint8 *)hmu < heap->base_addr + heap->current_size); bh_assert(((gc_uint32)(uintptr_t)hmu_to_obj(hmu) & 7) == 0); bh_assert(size > 0 - && ((gc_uint8*)hmu) + size <= heap->base_addr + heap->current_size); + && ((gc_uint8 *)hmu) + size + <= heap->base_addr + heap->current_size); bh_assert(!(size & 7)); base_addr = heap->base_addr; @@ -227,7 +223,7 @@ gci_add_fc(gc_heap_t *heap, hmu_t *hmu, gc_size_t size) hmu_set_free_size(hmu); if (HMU_IS_FC_NORMAL(size)) { - np = (hmu_normal_node_t*)hmu; + np = (hmu_normal_node_t *)hmu; if (!hmu_is_in_heap(np, base_addr, end_addr)) { heap->is_heap_corrupted = true; return false; @@ -240,7 +236,7 @@ gci_add_fc(gc_heap_t *heap, hmu_t *hmu, gc_size_t size) } /* big block*/ - node = (hmu_tree_node_t*)hmu; + node = (hmu_tree_node_t *)hmu; node->size = size; node->left = node->right = node->parent = NULL; @@ -308,7 +304,7 @@ alloc_hmu(gc_heap_t *heap, gc_size_t size) /* find a non-empty slot in normal_node_list with good size*/ init_node_idx = (size >> 3); for (node_idx = init_node_idx; node_idx < HMU_NORMAL_NODE_CNT; - node_idx++) { + node_idx++) { normal_head = heap->kfc_normal_list + node_idx; if (normal_head->next) break; @@ -333,7 +329,7 @@ alloc_hmu(gc_heap_t *heap, gc_size_t size) if ((gc_size_t)node_idx != (uint32)init_node_idx /* with bigger size*/ && ((gc_size_t)node_idx << 3) >= size + GC_SMALLEST_SIZE) { - rest = (hmu_t*) (((char *) p) + size); + rest = (hmu_t *)(((char *)p) + size); if (!gci_add_fc(heap, rest, (node_idx << 3) - size)) { return NULL; } @@ -341,7 +337,7 @@ alloc_hmu(gc_heap_t *heap, gc_size_t size) } else { size = node_idx << 3; - next = (hmu_t*) ((char*) p + size); + next = (hmu_t *)((char *)p + size); if (hmu_is_in_heap(next, base_addr, end_addr)) hmu_mark_pinuse(next); } @@ -349,11 +345,11 @@ alloc_hmu(gc_heap_t *heap, gc_size_t size) heap->total_free_size -= size; if ((heap->current_size - heap->total_free_size) > heap->highmark_size) - heap->highmark_size = heap->current_size - - heap->total_free_size; + heap->highmark_size = + heap->current_size - heap->total_free_size; - hmu_set_size((hmu_t* )p, size); - return (hmu_t*)p; + hmu_set_size((hmu_t *)p, size); + return (hmu_t *)p; } } @@ -389,14 +385,14 @@ alloc_hmu(gc_heap_t *heap, gc_size_t size) return NULL; if (last_tp->size >= size + GC_SMALLEST_SIZE) { - rest = (hmu_t*)((char*)last_tp + size); + rest = (hmu_t *)((char *)last_tp + size); if (!gci_add_fc(heap, rest, last_tp->size - size)) return NULL; hmu_mark_pinuse(rest); } else { size = last_tp->size; - next = (hmu_t*)((char*)last_tp + size); + next = (hmu_t *)((char *)last_tp + size); if (hmu_is_in_heap(next, base_addr, end_addr)) hmu_mark_pinuse(next); } @@ -405,8 +401,8 @@ alloc_hmu(gc_heap_t *heap, gc_size_t size) if ((heap->current_size - heap->total_free_size) > heap->highmark_size) heap->highmark_size = heap->current_size - heap->total_free_size; - hmu_set_size((hmu_t*)last_tp, size); - return (hmu_t*)last_tp; + hmu_set_size((hmu_t *)last_tp, size); + return (hmu_t *)last_tp; } return NULL; @@ -444,13 +440,12 @@ gc_object_t gc_alloc_vo(void *vheap, gc_size_t size) #else gc_object_t -gc_alloc_vo_internal(void *vheap, gc_size_t size, - const char *file, int line) +gc_alloc_vo_internal(void *vheap, gc_size_t size, const char *file, int line) #endif { - gc_heap_t* heap = (gc_heap_t*) vheap; + gc_heap_t *heap = (gc_heap_t *)vheap; hmu_t *hmu = NULL; - gc_object_t ret = (gc_object_t) NULL; + gc_object_t ret = (gc_object_t)NULL; gc_size_t tot_size = 0, tot_size_unaligned; /* hmu header + prefix + obj + suffix */ @@ -489,7 +484,7 @@ gc_alloc_vo_internal(void *vheap, gc_size_t size, ret = hmu_to_obj(hmu); if (tot_size > tot_size_unaligned) /* clear buffer appended by GC_ALIGN_8() */ - memset((uint8*)ret + size, 0, tot_size - tot_size_unaligned); + memset((uint8 *)ret + size, 0, tot_size - tot_size_unaligned); finish: os_mutex_unlock(&heap->lock); @@ -501,13 +496,13 @@ gc_object_t gc_realloc_vo(void *vheap, void *ptr, gc_size_t size) #else gc_object_t -gc_realloc_vo_internal(void *vheap, void *ptr, gc_size_t size, - const char *file, int line) +gc_realloc_vo_internal(void *vheap, void *ptr, gc_size_t size, const char *file, + int line) #endif { - gc_heap_t* heap = (gc_heap_t*) vheap; + gc_heap_t *heap = (gc_heap_t *)vheap; hmu_t *hmu = NULL, *hmu_old = NULL, *hmu_next; - gc_object_t ret = (gc_object_t) NULL, obj_old = (gc_object_t)ptr; + gc_object_t ret = (gc_object_t)NULL, obj_old = (gc_object_t)ptr; gc_size_t tot_size, tot_size_unaligned, tot_size_old = 0, tot_size_next; gc_size_t obj_size, obj_size_old; gc_uint8 *base_addr, *end_addr; @@ -540,24 +535,24 @@ gc_realloc_vo_internal(void *vheap, void *ptr, gc_size_t size, os_mutex_lock(&heap->lock); if (hmu_old) { - hmu_next = (hmu_t*)((char *)hmu_old + tot_size_old); + hmu_next = (hmu_t *)((char *)hmu_old + tot_size_old); if (hmu_is_in_heap(hmu_next, base_addr, end_addr)) { ut = hmu_get_ut(hmu_next); tot_size_next = hmu_get_size(hmu_next); - if (ut == HMU_FC - && tot_size <= tot_size_old + tot_size_next) { + if (ut == HMU_FC && tot_size <= tot_size_old + tot_size_next) { /* current node and next node meets requirement */ if (!unlink_hmu(heap, hmu_next)) { os_mutex_unlock(&heap->lock); return NULL; } hmu_set_size(hmu_old, tot_size); - memset((char*)hmu_old + tot_size_old, 0, tot_size - tot_size_old); + memset((char *)hmu_old + tot_size_old, 0, + tot_size - tot_size_old); #if BH_ENABLE_GC_VERIFY != 0 hmu_init_prefix_and_suffix(hmu_old, tot_size, file, line); #endif if (tot_size < tot_size_old + tot_size_next) { - hmu_next = (hmu_t*)((char*)hmu_old + tot_size); + hmu_next = (hmu_t *)((char *)hmu_old + tot_size); tot_size_next = tot_size_old + tot_size_next - tot_size; if (!gci_add_fc(heap, hmu_next, tot_size_next)) { os_mutex_unlock(&heap->lock); @@ -570,7 +565,6 @@ gc_realloc_vo_internal(void *vheap, void *ptr, gc_size_t size, } } - hmu = alloc_hmu_ex(heap, tot_size); if (!hmu) goto finish; @@ -596,8 +590,8 @@ gc_realloc_vo_internal(void *vheap, void *ptr, gc_size_t size, obj_size = tot_size - HMU_SIZE - OBJ_PREFIX_SIZE - OBJ_SUFFIX_SIZE; memset(ret, 0, obj_size); if (obj_old) { - obj_size_old = tot_size_old - HMU_SIZE - - OBJ_PREFIX_SIZE - OBJ_SUFFIX_SIZE; + obj_size_old = + tot_size_old - HMU_SIZE - OBJ_PREFIX_SIZE - OBJ_SUFFIX_SIZE; bh_memcpy_s(ret, obj_size, obj_old, obj_size_old); } } @@ -619,7 +613,7 @@ gci_is_heap_valid(gc_heap_t *heap) { if (!heap) return GC_FALSE; - if (heap->heap_id != (gc_handle_t) heap) + if (heap->heap_id != (gc_handle_t)heap) return GC_FALSE; return GC_TRUE; @@ -630,11 +624,10 @@ int gc_free_vo(void *vheap, gc_object_t obj) #else int -gc_free_vo_internal(void *vheap, gc_object_t obj, - const char *file, int line) +gc_free_vo_internal(void *vheap, gc_object_t obj, const char *file, int line) #endif { - gc_heap_t* heap = (gc_heap_t*) vheap; + gc_heap_t *heap = (gc_heap_t *)vheap; gc_uint8 *base_addr, *end_addr; hmu_t *hmu = NULL; hmu_t *prev = NULL; @@ -678,7 +671,7 @@ gc_free_vo_internal(void *vheap, gc_object_t obj, heap->total_free_size += size; if (!hmu_get_pinuse(hmu)) { - prev = (hmu_t*) ((char*) hmu - *((int*) hmu - 1)); + prev = (hmu_t *)((char *)hmu - *((int *)hmu - 1)); if (hmu_is_in_heap(prev, base_addr, end_addr) && hmu_get_ut(prev) == HMU_FC) { @@ -691,7 +684,7 @@ gc_free_vo_internal(void *vheap, gc_object_t obj, } } - next = (hmu_t*) ((char*) hmu + size); + next = (hmu_t *)((char *)hmu + size); if (hmu_is_in_heap(next, base_addr, end_addr)) { if (hmu_get_ut(next) == HMU_FC) { size += hmu_get_size(next); @@ -699,7 +692,7 @@ gc_free_vo_internal(void *vheap, gc_object_t obj, ret = GC_ERROR; goto out; } - next = (hmu_t*)((char*) hmu + size); + next = (hmu_t *)((char *)hmu + size); } } @@ -711,8 +704,8 @@ gc_free_vo_internal(void *vheap, gc_object_t obj, if (hmu_is_in_heap(next, base_addr, end_addr)) { hmu_unmark_pinuse(next); } - - } else { + } + else { ret = GC_ERROR; goto out; } @@ -750,14 +743,14 @@ gci_dump(gc_heap_t *heap) int i = 0, p, mark; char inuse = 'U'; - cur = (hmu_t*)heap->base_addr; - end = (hmu_t*)((char*)heap->base_addr + heap->current_size); + cur = (hmu_t *)heap->base_addr; + end = (hmu_t *)((char *)heap->base_addr + heap->current_size); - while(cur < end) { + while (cur < end) { ut = hmu_get_ut(cur); size = hmu_get_size(cur); p = hmu_get_pinuse(cur); - mark = hmu_is_jo_marked (cur); + mark = hmu_is_jo_marked(cur); if (ut == HMU_VO) inuse = 'V'; @@ -772,9 +765,9 @@ gci_dump(gc_heap_t *heap) return; } - os_printf("#%d %08x %x %x %d %c %d\n", - i, (int32)((char*) cur - (char*) heap->base_addr), - ut, p, mark, inuse, (int32)hmu_obj_size(size)); + os_printf("#%d %08x %x %x %d %c %d\n", i, + (int32)((char *)cur - (char *)heap->base_addr), ut, p, mark, + inuse, (int32)hmu_obj_size(size)); #if BH_ENABLE_GC_VERIFY != 0 if (inuse == 'V') { gc_object_prefix_t *prefix = (gc_object_prefix_t *)(cur + 1); @@ -782,10 +775,9 @@ gci_dump(gc_heap_t *heap) } #endif - cur = (hmu_t*)((char *)cur + size); + cur = (hmu_t *)((char *)cur + size); i++; } bh_assert(cur == end); } - diff --git a/core/shared/mem-alloc/ems/ems_gc.h b/core/shared/mem-alloc/ems/ems_gc.h index a9db04c7df..9a74d0046c 100644 --- a/core/shared/mem-alloc/ems/ems_gc.h +++ b/core/shared/mem-alloc/ems/ems_gc.h @@ -8,8 +8,6 @@ * @date Wed Aug 3 10:46:38 2011 * * @brief This file defines GC modules types and interfaces. - * - * */ #ifndef _EMS_GC_H @@ -33,15 +31,15 @@ extern "C" { #define GC_MAX_HEAP_SIZE (256 * BH_KB) -typedef void * gc_handle_t; -typedef void * gc_object_t; -typedef int64 gc_int64; +typedef void *gc_handle_t; +typedef void *gc_object_t; +typedef int64 gc_int64; typedef uint32 gc_uint32; -typedef int32 gc_int32; +typedef int32 gc_int32; typedef uint16 gc_uint16; -typedef int16 gc_int16; -typedef uint8 gc_uint8; -typedef int8 gc_int8; +typedef int16 gc_int16; +typedef uint8 gc_uint8; +typedef int8 gc_int8; typedef uint32 gc_size_t; typedef enum { @@ -105,8 +103,7 @@ gc_get_heap_struct_size(void); * @return GC_SUCCESS if success, GC_ERROR otherwise */ int -gc_migrate(gc_handle_t handle, - char *pool_buf_new, gc_size_t pool_buf_size); +gc_migrate(gc_handle_t handle, char *pool_buf_new, gc_size_t pool_buf_size); /** * Check whether the heap is corrupted @@ -126,7 +123,7 @@ gc_is_heap_corrupted(gc_handle_t handle); * @param mmt [in] type of heap, MMT_SHARED or MMT_INSTANCE */ void * -gc_heap_stats(void *heap, uint32* stats, int size); +gc_heap_stats(void *heap, uint32 *stats, int size); #if BH_ENABLE_GC_VERIFY == 0 @@ -142,17 +139,16 @@ gc_free_vo(void *heap, gc_object_t obj); #else /* else of BH_ENABLE_GC_VERIFY */ gc_object_t -gc_alloc_vo_internal(void *heap, gc_size_t size, - const char *file, int line); +gc_alloc_vo_internal(void *heap, gc_size_t size, const char *file, int line); gc_object_t -gc_realloc_vo_internal(void *heap, void *ptr, gc_size_t size, - const char *file, int line); +gc_realloc_vo_internal(void *heap, void *ptr, gc_size_t size, const char *file, + int line); int -gc_free_vo_internal(void *heap, gc_object_t obj, - const char *file, int line); +gc_free_vo_internal(void *heap, gc_object_t obj, const char *file, int line); +/* clang-format off */ #define gc_alloc_vo(heap, size) \ gc_alloc_vo_internal(heap, size, __FILE__, __LINE__) @@ -161,6 +157,7 @@ gc_free_vo_internal(void *heap, gc_object_t obj, #define gc_free_vo(heap, obj) \ gc_free_vo_internal(heap, obj, __FILE__, __LINE__) +/* clang-format on */ #endif /* end of BH_ENABLE_GC_VERIFY */ @@ -169,4 +166,3 @@ gc_free_vo_internal(void *heap, gc_object_t obj, #endif #endif - diff --git a/core/shared/mem-alloc/ems/ems_gc_internal.h b/core/shared/mem-alloc/ems/ems_gc_internal.h index b099211c1e..39b1ff8f14 100644 --- a/core/shared/mem-alloc/ems/ems_gc_internal.h +++ b/core/shared/mem-alloc/ems/ems_gc_internal.h @@ -60,8 +60,8 @@ hmu_init_prefix_and_suffix(hmu_t *hmu, gc_size_t tot_size, void hmu_verify(void *vheap, hmu_t *hmu); -#define SKIP_OBJ_PREFIX(p) ((void*)((gc_uint8*)(p) + OBJ_PREFIX_SIZE)) -#define SKIP_OBJ_SUFFIX(p) ((void*)((gc_uint8*)(p) + OBJ_SUFFIX_SIZE)) +#define SKIP_OBJ_PREFIX(p) ((void *)((gc_uint8 *)(p) + OBJ_PREFIX_SIZE)) +#define SKIP_OBJ_SUFFIX(p) ((void *)((gc_uint8 *)(p) + OBJ_SUFFIX_SIZE)) #define OBJ_EXTRA_SIZE (HMU_SIZE + OBJ_PREFIX_SIZE + OBJ_SUFFIX_SIZE) @@ -70,8 +70,8 @@ hmu_verify(void *vheap, hmu_t *hmu); #define OBJ_PREFIX_SIZE 0 #define OBJ_SUFFIX_SIZE 0 -#define SKIP_OBJ_PREFIX(p) ((void*)((gc_uint8*)(p) + OBJ_PREFIX_SIZE)) -#define SKIP_OBJ_SUFFIX(p) ((void*)((gc_uint8*)(p) + OBJ_SUFFIX_SIZE)) +#define SKIP_OBJ_PREFIX(p) ((void *)((gc_uint8 *)(p) + OBJ_PREFIX_SIZE)) +#define SKIP_OBJ_SUFFIX(p) ((void *)((gc_uint8 *)(p) + OBJ_SUFFIX_SIZE)) #define OBJ_EXTRA_SIZE (HMU_SIZE + OBJ_PREFIX_SIZE + OBJ_SUFFIX_SIZE) @@ -81,8 +81,11 @@ hmu_verify(void *vheap, hmu_t *hmu); #define GC_ALIGN_8(s) (((uint32)(s) + 7) & (uint32)~7) -#define GC_SMALLEST_SIZE GC_ALIGN_8(HMU_SIZE + OBJ_PREFIX_SIZE + OBJ_SUFFIX_SIZE + 8) -#define GC_GET_REAL_SIZE(x) GC_ALIGN_8(HMU_SIZE + OBJ_PREFIX_SIZE + OBJ_SUFFIX_SIZE + (((x) > 8) ? (x): 8)) +#define GC_SMALLEST_SIZE \ + GC_ALIGN_8(HMU_SIZE + OBJ_PREFIX_SIZE + OBJ_SUFFIX_SIZE + 8) +#define GC_GET_REAL_SIZE(x) \ + GC_ALIGN_8(HMU_SIZE + OBJ_PREFIX_SIZE + OBJ_SUFFIX_SIZE \ + + (((x) > 8) ? (x) : 8)) /** * hmu bit operation @@ -92,12 +95,17 @@ hmu_verify(void *vheap, hmu_t *hmu); #define GETBIT(v, offset) ((v) & ((uint32)1 << (offset)) ? 1 : 0) #define CLRBIT(v, offset) (v) &= (~((uint32)1 << (offset))) -#define SETBITS(v, offset, size, value) do { \ - (v) &= ~((((uint32)1 << size) - 1) << offset); \ - (v) |= ((uint32)value << offset); \ - } while(0) -#define CLRBITS(v, offset, size) (v) &= ~((((uint32)1 << size) - 1) << offset) -#define GETBITS(v, offset, size) (((v) & (((((uint32)1 << size) - 1) << offset))) >> offset) +/* clang-format off */ +#define SETBITS(v, offset, size, value) \ + do { \ + (v) &= ~((((uint32)1 << size) - 1) << offset); \ + (v) |= ((uint32)value << offset); \ + } while (0) +#define CLRBITS(v, offset, size) \ + (v) &= ~((((uint32)1 << size) - 1) << offset) +#define GETBITS(v, offset, size) \ + (((v) & (((((uint32)1 << size) - 1) << offset))) >> offset) +/* clang-format on */ /** * gc object layout definition @@ -105,30 +113,35 @@ hmu_verify(void *vheap, hmu_t *hmu); #define HMU_SIZE (sizeof(hmu_t)) -#define hmu_to_obj(hmu) (gc_object_t)(SKIP_OBJ_PREFIX((hmu_t*) (hmu) + 1)) -#define obj_to_hmu(obj) ((hmu_t *)((gc_uint8*)(obj) - OBJ_PREFIX_SIZE) - 1) +#define hmu_to_obj(hmu) (gc_object_t)(SKIP_OBJ_PREFIX((hmu_t *)(hmu) + 1)) +#define obj_to_hmu(obj) ((hmu_t *)((gc_uint8 *)(obj)-OBJ_PREFIX_SIZE) - 1) -#define HMU_UT_SIZE 2 -#define HMU_UT_OFFSET 30 +#define HMU_UT_SIZE 2 +#define HMU_UT_OFFSET 30 -#define hmu_get_ut(hmu) GETBITS ((hmu)->header, HMU_UT_OFFSET, HMU_UT_SIZE) -#define hmu_set_ut(hmu, type) SETBITS ((hmu)->header, HMU_UT_OFFSET, HMU_UT_SIZE, type) -#define hmu_is_ut_valid(tp) (tp >= HMU_TYPE_MIN && tp <= HMU_TYPE_MAX) +/* clang-format off */ +#define hmu_get_ut(hmu) \ + GETBITS((hmu)->header, HMU_UT_OFFSET, HMU_UT_SIZE) +#define hmu_set_ut(hmu, type) \ + SETBITS((hmu)->header, HMU_UT_OFFSET, HMU_UT_SIZE, type) +#define hmu_is_ut_valid(tp) \ + (tp >= HMU_TYPE_MIN && tp <= HMU_TYPE_MAX) +/* clang-format on */ /* P in use bit means the previous chunk is in use */ #define HMU_P_OFFSET 29 -#define hmu_mark_pinuse(hmu) SETBIT ((hmu)->header, HMU_P_OFFSET) -#define hmu_unmark_pinuse(hmu) CLRBIT ((hmu)->header, HMU_P_OFFSET) -#define hmu_get_pinuse(hmu) GETBIT ((hmu)->header, HMU_P_OFFSET) +#define hmu_mark_pinuse(hmu) SETBIT((hmu)->header, HMU_P_OFFSET) +#define hmu_unmark_pinuse(hmu) CLRBIT((hmu)->header, HMU_P_OFFSET) +#define hmu_get_pinuse(hmu) GETBIT((hmu)->header, HMU_P_OFFSET) -#define HMU_JO_VT_SIZE 27 +#define HMU_JO_VT_SIZE 27 #define HMU_JO_VT_OFFSET 0 #define HMU_JO_MB_OFFSET 28 -#define hmu_mark_jo(hmu) SETBIT ((hmu)->header, HMU_JO_MB_OFFSET) -#define hmu_unmark_jo(hmu) CLRBIT ((hmu)->header, HMU_JO_MB_OFFSET) -#define hmu_is_jo_marked(hmu) GETBIT ((hmu)->header, HMU_JO_MB_OFFSET) +#define hmu_mark_jo(hmu) SETBIT((hmu)->header, HMU_JO_MB_OFFSET) +#define hmu_unmark_jo(hmu) CLRBIT((hmu)->header, HMU_JO_MB_OFFSET) +#define hmu_is_jo_marked(hmu) GETBIT((hmu)->header, HMU_JO_MB_OFFSET) /** * The hmu size is divisible by 8, its lowest 3 bits are 0, so we only @@ -141,11 +154,13 @@ hmu_verify(void *vheap, hmu_t *hmu); #define HMU_VO_FB_OFFSET 28 -#define hmu_is_vo_freed(hmu) GETBIT ((hmu)->header, HMU_VO_FB_OFFSET) -#define hmu_unfree_vo(hmu) CLRBIT ((hmu)->header, HMU_VO_FB_OFFSET) +#define hmu_is_vo_freed(hmu) GETBIT((hmu)->header, HMU_VO_FB_OFFSET) +#define hmu_unfree_vo(hmu) CLRBIT((hmu)->header, HMU_VO_FB_OFFSET) -#define hmu_get_size(hmu) (GETBITS ((hmu)->header, HMU_SIZE_OFFSET, HMU_SIZE_SIZE) << 3) -#define hmu_set_size(hmu, size) SETBITS ((hmu)->header, HMU_SIZE_OFFSET, HMU_SIZE_SIZE, ((size) >> 3)) +#define hmu_get_size(hmu) \ + (GETBITS((hmu)->header, HMU_SIZE_OFFSET, HMU_SIZE_SIZE) << 3) +#define hmu_set_size(hmu, size) \ + SETBITS((hmu)->header, HMU_SIZE_OFFSET, HMU_SIZE_SIZE, ((size) >> 3)) /** * HMU free chunk management @@ -173,17 +188,16 @@ static inline hmu_normal_node_t * get_hmu_normal_node_next(hmu_normal_node_t *node) { return node->next_offset - ? (hmu_normal_node_t *)((uint8*)node + node->next_offset) - : NULL; + ? (hmu_normal_node_t *)((uint8 *)node + node->next_offset) + : NULL; } static inline void set_hmu_normal_node_next(hmu_normal_node_t *node, hmu_normal_node_t *next) { if (next) { - bh_assert((uint8*)next - (uint8*)node < INT32_MAX); - node->next_offset = (gc_int32)(intptr_t) - ((uint8*)next - (uint8*)node); + bh_assert((uint8 *)next - (uint8 *)node < INT32_MAX); + node->next_offset = (gc_int32)(intptr_t)((uint8 *)next - (uint8 *)node); } else { node->next_offset = 0; @@ -247,4 +261,4 @@ gci_dump(gc_heap_t *heap); } #endif -#endif +#endif /* end of _EMS_GC_INTERNAL_H */ diff --git a/core/shared/mem-alloc/ems/ems_hmu.c b/core/shared/mem-alloc/ems/ems_hmu.c index d7cf34189d..41745e161e 100644 --- a/core/shared/mem-alloc/ems/ems_hmu.c +++ b/core/shared/mem-alloc/ems/ems_hmu.c @@ -11,8 +11,8 @@ * Set default value to prefix and suffix * @param hmu should not be NULL and should have been correctly initilized * (except prefix and suffix part) - * @param tot_size is offered here because hmu_get_size can not be used till now. - * tot_size should not be smaller than OBJ_EXTRA_SIZE. + * @param tot_size is offered here because hmu_get_size can not be used + * till now. tot_size should not be smaller than OBJ_EXTRA_SIZE. * For VO, tot_size should be equal to object total size. */ void @@ -30,16 +30,17 @@ hmu_init_prefix_and_suffix(hmu_t *hmu, gc_size_t tot_size, bh_assert(hmu_get_ut(hmu) != HMU_VO || hmu_get_size(hmu) >= tot_size); prefix = (gc_object_prefix_t *)(hmu + 1); - suffix = (gc_object_suffix_t *)((gc_uint8*)hmu + tot_size - OBJ_SUFFIX_SIZE); + suffix = + (gc_object_suffix_t *)((gc_uint8 *)hmu + tot_size - OBJ_SUFFIX_SIZE); prefix->file_name = file_name; prefix->line_no = line_no; prefix->size = tot_size; - for(i = 0;i < GC_OBJECT_PREFIX_PADDING_CNT;i++) { + for (i = 0; i < GC_OBJECT_PREFIX_PADDING_CNT; i++) { prefix->padding[i] = GC_OBJECT_PADDING_VALUE; } - for(i = 0;i < GC_OBJECT_SUFFIX_PADDING_CNT;i++) { + for (i = 0; i < GC_OBJECT_SUFFIX_PADDING_CNT; i++) { suffix->padding[i] = GC_OBJECT_PADDING_VALUE; } } @@ -61,17 +62,17 @@ hmu_verify(void *vheap, hmu_t *hmu) prefix = (gc_object_prefix_t *)(hmu + 1); size = prefix->size; - suffix = (gc_object_suffix_t *)((gc_uint8*)hmu + size - OBJ_SUFFIX_SIZE); + suffix = (gc_object_suffix_t *)((gc_uint8 *)hmu + size - OBJ_SUFFIX_SIZE); if (ut == HMU_VO || ut == HMU_JO) { /* check padding*/ - for (i = 0;i < GC_OBJECT_PREFIX_PADDING_CNT;i++) { + for (i = 0; i < GC_OBJECT_PREFIX_PADDING_CNT; i++) { if (prefix->padding[i] != GC_OBJECT_PADDING_VALUE) { is_padding_ok = 0; break; } } - for (i = 0;i < GC_OBJECT_SUFFIX_PADDING_CNT;i++) { + for (i = 0; i < GC_OBJECT_SUFFIX_PADDING_CNT; i++) { if (suffix->padding[i] != GC_OBJECT_PADDING_VALUE) { is_padding_ok = 0; break; @@ -88,4 +89,3 @@ hmu_verify(void *vheap, hmu_t *hmu) } #endif /* end of BH_ENABLE_GC_VERIFY */ - diff --git a/core/shared/mem-alloc/ems/ems_kfc.c b/core/shared/mem-alloc/ems/ems_kfc.c index c4f7195b82..e363399304 100644 --- a/core/shared/mem-alloc/ems/ems_kfc.c +++ b/core/shared/mem-alloc/ems/ems_kfc.c @@ -22,7 +22,7 @@ gc_init_internal(gc_heap_t *heap, char *base_addr, gc_size_t heap_max_size) /* init all data structures*/ heap->current_size = heap_max_size; - heap->base_addr = (gc_uint8*)base_addr; + heap->base_addr = (gc_uint8 *)base_addr; heap->heap_id = (gc_handle_t)heap; heap->total_free_size = heap->current_size; @@ -34,7 +34,7 @@ gc_init_internal(gc_heap_t *heap, char *base_addr, gc_size_t heap_max_size) hmu_set_ut(&root->hmu_header, HMU_FC); hmu_set_size(&root->hmu_header, sizeof *root); - q = (hmu_tree_node_t *) heap->base_addr; + q = (hmu_tree_node_t *)heap->base_addr; memset(q, 0, sizeof *q); hmu_set_ut(&q->hmu_header, HMU_FC); hmu_set_size(&q->hmu_header, heap->current_size); @@ -53,18 +53,19 @@ gc_handle_t gc_init_with_pool(char *buf, gc_size_t buf_size) { char *buf_end = buf + buf_size; - char *buf_aligned = (char*)(((uintptr_t) buf + 7) & (uintptr_t)~7); + char *buf_aligned = (char *)(((uintptr_t)buf + 7) & (uintptr_t)~7); char *base_addr = buf_aligned + sizeof(gc_heap_t); - gc_heap_t *heap = (gc_heap_t*)buf_aligned; + gc_heap_t *heap = (gc_heap_t *)buf_aligned; gc_size_t heap_max_size; if (buf_size < APP_HEAP_SIZE_MIN) { - os_printf("[GC_ERROR]heap init buf size (%u) < %u\n", - buf_size, APP_HEAP_SIZE_MIN); + os_printf("[GC_ERROR]heap init buf size (%u) < %u\n", buf_size, + APP_HEAP_SIZE_MIN); return NULL; } - base_addr = (char*) (((uintptr_t) base_addr + 7) & (uintptr_t)~7) + GC_HEAD_PADDING; + base_addr = + (char *)(((uintptr_t)base_addr + 7) & (uintptr_t)~7) + GC_HEAD_PADDING; heap_max_size = (uint32)(buf_end - base_addr) & (uint32)~7; #if WASM_ENABLE_MEMORY_TRACING != 0 @@ -81,7 +82,7 @@ gc_handle_t gc_init_with_struct_and_pool(char *struct_buf, gc_size_t struct_buf_size, char *pool_buf, gc_size_t pool_buf_size) { - gc_heap_t *heap = (gc_heap_t*)struct_buf; + gc_heap_t *heap = (gc_heap_t *)struct_buf; char *base_addr = pool_buf + GC_HEAD_PADDING; char *pool_buf_end = pool_buf + pool_buf_size; gc_size_t heap_max_size; @@ -103,8 +104,8 @@ gc_init_with_struct_and_pool(char *struct_buf, gc_size_t struct_buf_size, } if (pool_buf_size < APP_HEAP_SIZE_MIN) { - os_printf("[GC_ERROR]heap init buf size (%u) < %u\n", - pool_buf_size, APP_HEAP_SIZE_MIN); + os_printf("[GC_ERROR]heap init buf size (%u) < %u\n", pool_buf_size, + APP_HEAP_SIZE_MIN); return NULL; } @@ -115,8 +116,7 @@ gc_init_with_struct_and_pool(char *struct_buf, gc_size_t struct_buf_size, struct_buf_size + pool_buf_size); os_printf(" heap struct size: %u\n", sizeof(gc_heap_t)); os_printf(" actual heap size: %u\n", heap_max_size); - os_printf(" padding bytes: %u\n", - pool_buf_size - heap_max_size); + os_printf(" padding bytes: %u\n", pool_buf_size - heap_max_size); #endif return gc_init_internal(heap, base_addr, heap_max_size); } @@ -124,16 +124,17 @@ gc_init_with_struct_and_pool(char *struct_buf, gc_size_t struct_buf_size, int gc_destroy_with_pool(gc_handle_t handle) { - gc_heap_t *heap = (gc_heap_t *) handle; + gc_heap_t *heap = (gc_heap_t *)handle; #if BH_ENABLE_GC_VERIFY != 0 - hmu_t *cur = (hmu_t*)heap->base_addr; - hmu_t *end = (hmu_t*)((char*)heap->base_addr + heap->current_size); + hmu_t *cur = (hmu_t *)heap->base_addr; + hmu_t *end = (hmu_t *)((char *)heap->base_addr + heap->current_size); if (!heap->is_heap_corrupted - && (hmu_t*)((char *)cur + hmu_get_size(cur)) != end) { + && (hmu_t *)((char *)cur + hmu_get_size(cur)) != end) { os_printf("Memory leak detected:\n"); gci_dump(heap); #if WASM_ENABLE_SPEC_TEST != 0 - while (1); + while (1) { + } #endif } #endif @@ -157,13 +158,12 @@ adjust_ptr(uint8 **p_ptr, intptr_t offset) } int -gc_migrate(gc_handle_t handle, - char *pool_buf_new, gc_size_t pool_buf_size) +gc_migrate(gc_handle_t handle, char *pool_buf_new, gc_size_t pool_buf_size) { gc_heap_t *heap = (gc_heap_t *)handle; char *base_addr_new = pool_buf_new + GC_HEAD_PADDING; char *pool_buf_end = pool_buf_new + pool_buf_size; - intptr_t offset = (uint8*)base_addr_new - (uint8*)heap->base_addr; + intptr_t offset = (uint8 *)base_addr_new - (uint8 *)heap->base_addr; hmu_t *cur = NULL, *end = NULL; hmu_tree_node_t *tree_node; gc_size_t heap_max_size, size; @@ -175,8 +175,7 @@ gc_migrate(gc_handle_t handle, heap_max_size = (uint32)(pool_buf_end - base_addr_new) & (uint32)~7; - if (pool_buf_end < base_addr_new - || heap_max_size < heap->current_size) { + if (pool_buf_end < base_addr_new || heap_max_size < heap->current_size) { os_printf("[GC_ERROR]heap migrate invlaid pool buf size\n"); return GC_ERROR; } @@ -184,13 +183,13 @@ gc_migrate(gc_handle_t handle, if (offset == 0) return 0; - heap->base_addr = (uint8*)base_addr_new; - adjust_ptr((uint8**)&heap->kfc_tree_root.left, offset); - adjust_ptr((uint8**)&heap->kfc_tree_root.right, offset); - adjust_ptr((uint8**)&heap->kfc_tree_root.parent, offset); + heap->base_addr = (uint8 *)base_addr_new; + adjust_ptr((uint8 **)&heap->kfc_tree_root.left, offset); + adjust_ptr((uint8 **)&heap->kfc_tree_root.right, offset); + adjust_ptr((uint8 **)&heap->kfc_tree_root.parent, offset); - cur = (hmu_t*)heap->base_addr; - end = (hmu_t*)((char*)heap->base_addr + heap->current_size); + cur = (hmu_t *)heap->base_addr; + end = (hmu_t *)((char *)heap->base_addr + heap->current_size); while (cur < end) { size = hmu_get_size(cur); @@ -198,14 +197,14 @@ gc_migrate(gc_handle_t handle, if (hmu_get_ut(cur) == HMU_FC && !HMU_IS_FC_NORMAL(size)) { tree_node = (hmu_tree_node_t *)cur; - adjust_ptr((uint8**)&tree_node->left, offset); - adjust_ptr((uint8**)&tree_node->right, offset); + adjust_ptr((uint8 **)&tree_node->left, offset); + adjust_ptr((uint8 **)&tree_node->right, offset); if (tree_node->parent != &heap->kfc_tree_root) /* The root node belongs to heap structure, it is fixed part and isn't changed. */ - adjust_ptr((uint8**)&tree_node->parent, offset); + adjust_ptr((uint8 **)&tree_node->parent, offset); } - cur = (hmu_t*)((char *)cur + size); + cur = (hmu_t *)((char *)cur + size); } bh_assert(cur == end); @@ -229,35 +228,34 @@ gci_verify_heap(gc_heap_t *heap) bh_assert(heap && gci_is_heap_valid(heap)); cur = (hmu_t *)heap->base_addr; end = (hmu_t *)(heap->base_addr + heap->current_size); - while(cur < end) { + while (cur < end) { hmu_verify(heap, cur); - cur = (hmu_t *)((gc_uint8*)cur + hmu_get_size(cur)); + cur = (hmu_t *)((gc_uint8 *)cur + hmu_get_size(cur)); } bh_assert(cur == end); } #endif void * -gc_heap_stats(void *heap_arg, uint32* stats, int size) +gc_heap_stats(void *heap_arg, uint32 *stats, int size) { int i; - gc_heap_t *heap = (gc_heap_t *) heap_arg; + gc_heap_t *heap = (gc_heap_t *)heap_arg; for (i = 0; i < size; i++) { switch (i) { - case GC_STAT_TOTAL: - stats[i] = heap->current_size; - break; - case GC_STAT_FREE: - stats[i] = heap->total_free_size; - break; - case GC_STAT_HIGHMARK: - stats[i] = heap->highmark_size; - break; - default: - break; + case GC_STAT_TOTAL: + stats[i] = heap->current_size; + break; + case GC_STAT_FREE: + stats[i] = heap->total_free_size; + break; + case GC_STAT_HIGHMARK: + stats[i] = heap->highmark_size; + break; + default: + break; } } return heap; } - diff --git a/core/shared/mem-alloc/mem_alloc.c b/core/shared/mem-alloc/mem_alloc.c index b460e6d190..166529651a 100644 --- a/core/shared/mem-alloc/mem_alloc.c +++ b/core/shared/mem-alloc/mem_alloc.c @@ -9,9 +9,10 @@ #include "ems/ems_gc.h" -mem_allocator_t mem_allocator_create(void *mem, uint32_t size) +mem_allocator_t +mem_allocator_create(void *mem, uint32_t size) { - return gc_init_with_pool((char *) mem, size); + return gc_init_with_pool((char *)mem, size); } mem_allocator_t @@ -20,15 +21,14 @@ mem_allocator_create_with_struct_and_pool(void *struct_buf, void *pool_buf, uint32_t pool_buf_size) { - return gc_init_with_struct_and_pool((char *)struct_buf, - struct_buf_size, - pool_buf, - pool_buf_size); + return gc_init_with_struct_and_pool((char *)struct_buf, struct_buf_size, + pool_buf, pool_buf_size); } -void mem_allocator_destroy(mem_allocator_t allocator) +void +mem_allocator_destroy(mem_allocator_t allocator) { - gc_destroy_with_pool((gc_handle_t) allocator); + gc_destroy_with_pool((gc_handle_t)allocator); } uint32 @@ -40,33 +40,33 @@ mem_allocator_get_heap_struct_size() void * mem_allocator_malloc(mem_allocator_t allocator, uint32_t size) { - return gc_alloc_vo((gc_handle_t) allocator, size); + return gc_alloc_vo((gc_handle_t)allocator, size); } void * mem_allocator_realloc(mem_allocator_t allocator, void *ptr, uint32_t size) { - return gc_realloc_vo((gc_handle_t) allocator, ptr, size); + return gc_realloc_vo((gc_handle_t)allocator, ptr, size); } -void mem_allocator_free(mem_allocator_t allocator, void *ptr) +void +mem_allocator_free(mem_allocator_t allocator, void *ptr) { if (ptr) - gc_free_vo((gc_handle_t) allocator, ptr); + gc_free_vo((gc_handle_t)allocator, ptr); } int -mem_allocator_migrate(mem_allocator_t allocator, - char *pool_buf_new, uint32 pool_buf_size) +mem_allocator_migrate(mem_allocator_t allocator, char *pool_buf_new, + uint32 pool_buf_size) { - return gc_migrate((gc_handle_t) allocator, - pool_buf_new, pool_buf_size); + return gc_migrate((gc_handle_t)allocator, pool_buf_new, pool_buf_size); } bool mem_allocator_is_heap_corrupted(mem_allocator_t allocator) { - return gc_is_heap_corrupted((gc_handle_t) allocator); + return gc_is_heap_corrupted((gc_handle_t)allocator); } #else /* else of DEFAULT_MEM_ALLOCATOR */ @@ -76,23 +76,23 @@ mem_allocator_is_heap_corrupted(mem_allocator_t allocator) typedef struct mem_allocator_tlsf { tlsf_t tlsf; korp_mutex lock; -}mem_allocator_tlsf; +} mem_allocator_tlsf; mem_allocator_t mem_allocator_create(void *mem, uint32_t size) { mem_allocator_tlsf *allocator_tlsf; tlsf_t tlsf; - char *mem_aligned = (char*)(((uintptr_t)mem + 3) & ~3); + char *mem_aligned = (char *)(((uintptr_t)mem + 3) & ~3); if (size < 1024) { printf("Create mem allocator failed: pool size must be " - "at least 1024 bytes.\n"); + "at least 1024 bytes.\n"); return NULL; } - size -= mem_aligned - (char*)mem; - mem = (void*)mem_aligned; + size -= mem_aligned - (char *)mem; + mem = (void *)mem_aligned; tlsf = tlsf_create_with_pool(mem, size); if (!tlsf) { @@ -174,12 +174,10 @@ mem_allocator_free(mem_allocator_t allocator, void *ptr) } int -mem_allocator_migrate(mem_allocator_t allocator, - mem_allocator_t allocator_old) +mem_allocator_migrate(mem_allocator_t allocator, mem_allocator_t allocator_old) { - return tlsf_migrate((mem_allocator_tlsf *) allocator, - (mem_allocator_tlsf *) allocator_old); + return tlsf_migrate((mem_allocator_tlsf *)allocator, + (mem_allocator_tlsf *)allocator_old); } #endif /* end of DEFAULT_MEM_ALLOCATOR */ - diff --git a/core/shared/mem-alloc/mem_alloc.h b/core/shared/mem-alloc/mem_alloc.h index 8224889e98..d5dc66f110 100644 --- a/core/shared/mem-alloc/mem_alloc.h +++ b/core/shared/mem-alloc/mem_alloc.h @@ -39,8 +39,8 @@ void mem_allocator_free(mem_allocator_t allocator, void *ptr); int -mem_allocator_migrate(mem_allocator_t allocator, - char *pool_buf_new, uint32 pool_buf_size); +mem_allocator_migrate(mem_allocator_t allocator, char *pool_buf_new, + uint32 pool_buf_size); bool mem_allocator_is_heap_corrupted(mem_allocator_t allocator); @@ -50,4 +50,3 @@ mem_allocator_is_heap_corrupted(mem_allocator_t allocator); #endif #endif /* #ifndef __MEM_ALLOC_H */ - diff --git a/core/shared/platform/alios/alios_platform.c b/core/shared/platform/alios/alios_platform.c index 8150548209..6418587373 100644 --- a/core/shared/platform/alios/alios_platform.c +++ b/core/shared/platform/alios/alios_platform.c @@ -38,8 +38,7 @@ os_realloc(void *ptr, unsigned size) void os_free(void *ptr) -{ -} +{} void * os_mmap(void *hint, size_t size, int prot, int flags) @@ -63,5 +62,4 @@ os_mprotect(void *addr, size_t size, int prot) void os_dcache_flush() -{ -} +{} diff --git a/core/shared/platform/alios/alios_thread.c b/core/shared/platform/alios/alios_thread.c index f6165bd99d..0efd2f3944 100644 --- a/core/shared/platform/alios/alios_thread.c +++ b/core/shared/platform/alios/alios_thread.c @@ -6,14 +6,16 @@ #include "platform_api_vmcore.h" #include "platform_api_extension.h" +/* clang-format off */ #define bh_assert(v) do { \ - if (!(v)) { \ - printf("\nASSERTION FAILED: %s, at %s, line %d\n", \ - #v, __FILE__, __LINE__); \ - aos_reboot(); \ - while (1); \ - } \ - } while (0) + if (!(v)) { \ + printf("\nASSERTION FAILED: %s, at %s, line %d\n", \ + #v, __FILE__, __LINE__); \ + aos_reboot(); \ + while (1); \ + } \ +} while (0) +/* clang-format on */ struct os_thread_data; typedef struct os_thread_wait_node { @@ -138,8 +140,8 @@ os_thread_wrapper(void *arg) } int -os_thread_create(korp_tid *p_tid, thread_start_routine_t start, - void *arg, unsigned int stack_size) +os_thread_create(korp_tid *p_tid, thread_start_routine_t start, void *arg, + unsigned int stack_size) { return os_thread_create_with_prio(p_tid, start, arg, stack_size, BH_THREAD_DEFAULT_PRIORITY); @@ -170,13 +172,12 @@ os_thread_create_with_prio(korp_tid *p_tid, thread_start_routine_t start, if (aos_mutex_new(&thread_data->wait_list_lock)) goto fail2; - snprintf(thread_name, sizeof(thread_name), "%s%d", - "wasm-thread-", ++thread_name_index); + snprintf(thread_name, sizeof(thread_name), "%s%d", "wasm-thread-", + ++thread_name_index); /* Create the thread */ - if (aos_task_new_ext((aos_task_t*)thread_data, thread_name, - os_thread_wrapper, thread_data, - stack_size, prio)) + if (aos_task_new_ext((aos_task_t *)thread_data, thread_name, + os_thread_wrapper, thread_data, stack_size, prio)) goto fail3; aos_msleep(10); @@ -199,7 +200,7 @@ os_self_thread() } int -os_thread_join (korp_tid thread, void **value_ptr) +os_thread_join(korp_tid thread, void **value_ptr) { (void)value_ptr; os_thread_data *thread_data, *curr_thread_data; @@ -209,7 +210,7 @@ os_thread_join (korp_tid thread, void **value_ptr) curr_thread_data->wait_node.next = NULL; /* Get thread data */ - thread_data = (os_thread_data*)thread; + thread_data = (os_thread_data *)thread; aos_mutex_lock(&thread_data->wait_list_lock, AOS_WAIT_FOREVER); if (!thread_data->thread_wait_list) @@ -272,8 +273,8 @@ os_cond_destroy(korp_cond *cond) } static int -os_cond_wait_internal(korp_cond *cond, korp_mutex *mutex, - bool timed, uint32 mills) +os_cond_wait_internal(korp_cond *cond, korp_mutex *mutex, bool timed, + uint32 mills) { os_thread_wait_node *node = &thread_data_current()->wait_node; @@ -352,9 +353,9 @@ os_cond_signal(korp_cond *cond) return BHT_OK; } -uint8 *os_thread_get_stack_boundary() +uint8 * +os_thread_get_stack_boundary() { /* TODO: get alios stack boundary */ return NULL; } - diff --git a/core/shared/platform/alios/alios_time.c b/core/shared/platform/alios/alios_time.c index f793049798..549252738c 100644 --- a/core/shared/platform/alios/alios_time.c +++ b/core/shared/platform/alios/alios_time.c @@ -10,4 +10,3 @@ os_time_get_boot_microsecond() { return (uint64)aos_now_ms() * 1000; } - diff --git a/core/shared/platform/alios/platform_internal.h b/core/shared/platform/alios/platform_internal.h index 7201fb0fd1..07b8f75e2a 100644 --- a/core/shared/platform/alios/platform_internal.h +++ b/core/shared/platform/alios/platform_internal.h @@ -34,13 +34,14 @@ typedef aos_mutex_t korp_mutex; struct os_thread_wait_node; typedef struct os_thread_wait_node *os_thread_wait_list; typedef struct korp_cond { - aos_mutex_t wait_list_lock; - os_thread_wait_list thread_wait_list; + aos_mutex_t wait_list_lock; + os_thread_wait_list thread_wait_list; } korp_cond; -#define os_printf printf +#define os_printf printf #define os_vprintf vprintf +/* clang-format off */ /* math functions which are not provided by os*/ double sqrt(double x); double floor(double x); @@ -58,6 +59,6 @@ float rintf(float x); float truncf(float x); int signbit(double x); int isnan(double x); +/* clang-format on */ #endif /* end of _BH_PLATFORM_H */ - diff --git a/core/shared/platform/android/platform_init.c b/core/shared/platform/android/platform_init.c index 5353308c13..d7ffab33da 100644 --- a/core/shared/platform/android/platform_init.c +++ b/core/shared/platform/android/platform_init.c @@ -19,10 +19,10 @@ bh_platform_init() void bh_platform_destroy() -{ -} +{} -int os_printf(const char *fmt, ...) +int +os_printf(const char *fmt, ...) { int ret; va_list ap; @@ -34,14 +34,16 @@ int os_printf(const char *fmt, ...) return ret; } -int os_vprintf(const char *fmt, va_list ap) +int +os_vprintf(const char *fmt, va_list ap) { return __android_log_vprint(ANDROID_LOG_INFO, "wasm_runtime::", fmt, ap); } #if __ANDROID_API__ < 19 -int futimens(int __dir_fd, const struct timespec __times[2]) +int +futimens(int __dir_fd, const struct timespec __times[2]) { API_NOT_SUPPORT_ERROR(futimens, 19); return -1; @@ -51,32 +53,37 @@ int futimens(int __dir_fd, const struct timespec __times[2]) #if __ANDROID_API__ < 21 -int posix_fallocate(int __fd, off_t __offset, off_t __length) +int +posix_fallocate(int __fd, off_t __offset, off_t __length) { API_NOT_SUPPORT_ERROR(posix_fallocate, 21); return -1; } -int posix_fadvise(int fd, off_t offset, off_t len, int advice) +int +posix_fadvise(int fd, off_t offset, off_t len, int advice) { API_NOT_SUPPORT_ERROR(posix_fadvise, 21); return -1; } -int linkat(int __old_dir_fd, const char *__old_path, - int __new_dir_fd, const char *__new_path, int __flags) +int +linkat(int __old_dir_fd, const char *__old_path, int __new_dir_fd, + const char *__new_path, int __flags) { API_NOT_SUPPORT_ERROR(linkat, 21); return -1; } -int symlinkat(const char *__old_path, int __new_dir_fd, const char *__new_path) +int +symlinkat(const char *__old_path, int __new_dir_fd, const char *__new_path) { API_NOT_SUPPORT_ERROR(symlinkat, 21); return -1; } -ssize_t readlinkat(int __dir_fd, const char *__path, char *__buf, size_t __buf_size) +ssize_t +readlinkat(int __dir_fd, const char *__path, char *__buf, size_t __buf_size) { API_NOT_SUPPORT_ERROR(readlinkat, 21); return -1; @@ -86,13 +93,15 @@ ssize_t readlinkat(int __dir_fd, const char *__path, char *__buf, size_t __buf_s #if __ANDROID_API__ < 23 -long telldir(DIR *__dir) +long +telldir(DIR *__dir) { API_NOT_SUPPORT_ERROR(telldir, 23); return -1; } -void seekdir(DIR *__dir, long __location) +void +seekdir(DIR *__dir, long __location) { API_NOT_SUPPORT_ERROR(seekdir, 23); } @@ -101,13 +110,15 @@ void seekdir(DIR *__dir, long __location) #if __ANDROID_API__ < 24 -ssize_t preadv(int __fd, const struct iovec *__iov, int __count, off_t __offset) +ssize_t +preadv(int __fd, const struct iovec *__iov, int __count, off_t __offset) { API_NOT_SUPPORT_ERROR(preadv, 24); return -1; } -ssize_t pwritev(int __fd, const struct iovec *__iov, int __count, off_t __offset) +ssize_t +pwritev(int __fd, const struct iovec *__iov, int __count, off_t __offset) { API_NOT_SUPPORT_ERROR(pwritev, 24); return -1; diff --git a/core/shared/platform/android/platform_internal.h b/core/shared/platform/android/platform_internal.h index 703e6bf5bb..49f6b7f0b5 100644 --- a/core/shared/platform/android/platform_internal.h +++ b/core/shared/platform/android/platform_internal.h @@ -59,10 +59,8 @@ typedef pthread_t korp_thread; #define os_thread_local_attribute __thread #if WASM_DISABLE_HW_BOUND_CHECK == 0 -#if defined(BUILD_TARGET_X86_64) \ - || defined(BUILD_TARGET_AMD_64) \ - || defined(BUILD_TARGET_AARCH64) \ - || defined(BUILD_TARGET_RISCV64_LP64D) \ +#if defined(BUILD_TARGET_X86_64) || defined(BUILD_TARGET_AMD_64) \ + || defined(BUILD_TARGET_AARCH64) || defined(BUILD_TARGET_RISCV64_LP64D) \ || defined(BUILD_TARGET_RISCV64_LP64) #include @@ -79,15 +77,20 @@ typedef jmp_buf korp_jmpbuf; typedef void (*os_signal_handler)(void *sig_addr); -int os_thread_signal_init(os_signal_handler handler); +int +os_thread_signal_init(os_signal_handler handler); -void os_thread_signal_destroy(); +void +os_thread_signal_destroy(); -bool os_thread_signal_inited(); +bool +os_thread_signal_inited(); -void os_signal_unmask(); +void +os_signal_unmask(); -void os_sigreturn(); +void +os_sigreturn(); #endif /* end of BUILD_TARGET_X86_64/AMD_64/AARCH64/RISCV64 */ #endif /* end of WASM_DISABLE_HW_BOUND_CHECK */ @@ -95,38 +98,48 @@ typedef long int __syscall_slong_t; #if __ANDROID_API__ < 19 -int futimens(int __dir_fd, const struct timespec __times[2]); +int +futimens(int __dir_fd, const struct timespec __times[2]); #endif #if __ANDROID_API__ < 21 -int posix_fallocate(int __fd, off_t __offset, off_t __length); +int +posix_fallocate(int __fd, off_t __offset, off_t __length); -int posix_fadvise(int fd, off_t offset, off_t len, int advice); +int +posix_fadvise(int fd, off_t offset, off_t len, int advice); -int linkat(int __old_dir_fd, const char *__old_path, - int __new_dir_fd, const char *__new_path, int __flags); +int +linkat(int __old_dir_fd, const char *__old_path, int __new_dir_fd, + const char *__new_path, int __flags); -int symlinkat(const char *__old_path, int __new_dir_fd, const char *__new_path); +int +symlinkat(const char *__old_path, int __new_dir_fd, const char *__new_path); -ssize_t readlinkat(int __dir_fd, const char *__path, char *__buf, size_t __buf_size); +ssize_t +readlinkat(int __dir_fd, const char *__path, char *__buf, size_t __buf_size); #endif #if __ANDROID_API__ < 23 -long telldir(DIR *__dir); +long +telldir(DIR *__dir); -void seekdir(DIR *__dir, long __location); +void +seekdir(DIR *__dir, long __location); #endif #if __ANDROID_API__ < 24 -ssize_t preadv(int __fd, const struct iovec *__iov, int __count, off_t __offset); +ssize_t +preadv(int __fd, const struct iovec *__iov, int __count, off_t __offset); -ssize_t pwritev(int __fd, const struct iovec *__iov, int __count, off_t __offset); +ssize_t +pwritev(int __fd, const struct iovec *__iov, int __count, off_t __offset); #endif @@ -135,4 +148,3 @@ ssize_t pwritev(int __fd, const struct iovec *__iov, int __count, off_t __offset #endif #endif /* end of _PLATFORM_INTERNAL_H */ - diff --git a/core/shared/platform/common/freertos/freertos_malloc.c b/core/shared/platform/common/freertos/freertos_malloc.c index 70002163c7..19cf4d5f1d 100644 --- a/core/shared/platform/common/freertos/freertos_malloc.c +++ b/core/shared/platform/common/freertos/freertos_malloc.c @@ -5,7 +5,6 @@ #include "platform_api_vmcore.h" - void * os_malloc(unsigned size) { @@ -20,6 +19,4 @@ os_realloc(void *ptr, unsigned size) void os_free(void *ptr) -{ -} - +{} diff --git a/core/shared/platform/common/freertos/freertos_thread.c b/core/shared/platform/common/freertos/freertos_thread.c index 9b9dbea05c..9f68bc8f92 100644 --- a/core/shared/platform/common/freertos/freertos_thread.c +++ b/core/shared/platform/common/freertos/freertos_thread.c @@ -6,6 +6,7 @@ #include "platform_api_vmcore.h" #include "platform_api_extension.h" +/* clang-format off */ #define bh_assert(v) do { \ if (!(v)) { \ int _count = 1; \ @@ -15,7 +16,8 @@ os_printf("%d\n", _count / (_count - 1)); \ while (1); \ } \ - } while (0) +} while (0) +/* clang-format on */ struct os_thread_data; typedef struct os_thread_wait_node { @@ -56,7 +58,8 @@ static os_thread_data supervisor_thread_data; /* Thread name index */ static int thread_name_index; -static void thread_data_list_add(os_thread_data *thread_data) +static void +thread_data_list_add(os_thread_data *thread_data) { xSemaphoreTake(thread_data_lock, portMAX_DELAY); if (!thread_data_list) @@ -79,7 +82,8 @@ static void thread_data_list_add(os_thread_data *thread_data) xSemaphoreGive(thread_data_lock); } -static void thread_data_list_remove(os_thread_data *thread_data) +static void +thread_data_list_remove(os_thread_data *thread_data) { xSemaphoreTake(thread_data_lock, portMAX_DELAY); if (thread_data_list) { @@ -204,15 +208,17 @@ os_thread_wrapper(void *arg) vTaskDelete(NULL); } -int os_thread_create(korp_tid *p_tid, thread_start_routine_t start, void *arg, - unsigned int stack_size) +int +os_thread_create(korp_tid *p_tid, thread_start_routine_t start, void *arg, + unsigned int stack_size) { return os_thread_create_with_prio(p_tid, start, arg, stack_size, BH_THREAD_DEFAULT_PRIORITY); } -int os_thread_create_with_prio(korp_tid *p_tid, thread_start_routine_t start, - void *arg, unsigned int stack_size, int prio) +int +os_thread_create_with_prio(korp_tid *p_tid, thread_start_routine_t start, + void *arg, unsigned int stack_size, int prio) { os_thread_data *thread_data; char thread_name[32]; @@ -235,13 +241,13 @@ int os_thread_create_with_prio(korp_tid *p_tid, thread_start_routine_t start, if (!(thread_data->wait_list_lock = xSemaphoreCreateMutex())) goto fail2; - snprintf(thread_name, sizeof(thread_name), "%s%d", - "wasm-thread-", ++thread_name_index); + snprintf(thread_name, sizeof(thread_name), "%s%d", "wasm-thread-", + ++thread_name_index); /* Create the thread */ - if (pdPASS != xTaskCreate(os_thread_wrapper, thread_name, - stack_size / 4, thread_data, - prio, &thread_data->handle)) + if (pdPASS + != xTaskCreate(os_thread_wrapper, thread_name, stack_size / 4, + thread_data, prio, &thread_data->handle)) goto fail3; thread_data_list_add(thread_data); @@ -257,12 +263,14 @@ int os_thread_create_with_prio(korp_tid *p_tid, thread_start_routine_t start, return BHT_ERROR; } -korp_tid os_self_thread() +korp_tid +os_self_thread() { return xTaskGetCurrentTaskHandle(); } -int os_thread_join(korp_tid thread, void **value_ptr) +int +os_thread_join(korp_tid thread, void **value_ptr) { os_thread_data *thread_data, *curr_thread_data; TaskHandle_t handle = thread; @@ -293,7 +301,8 @@ int os_thread_join(korp_tid thread, void **value_ptr) return BHT_OK; } -int os_mutex_init(korp_mutex *mutex) +int +os_mutex_init(korp_mutex *mutex) { SemaphoreHandle_t semaphore; @@ -304,7 +313,8 @@ int os_mutex_init(korp_mutex *mutex) return BHT_OK; } -int os_recursive_mutex_init(korp_mutex *mutex) +int +os_recursive_mutex_init(korp_mutex *mutex) { SemaphoreHandle_t semaphore; @@ -315,13 +325,15 @@ int os_recursive_mutex_init(korp_mutex *mutex) return BHT_OK; } -int os_mutex_destroy(korp_mutex *mutex) +int +os_mutex_destroy(korp_mutex *mutex) { vSemaphoreDelete(mutex->sem); return BHT_OK; } -int os_mutex_lock(korp_mutex *mutex) +int +os_mutex_lock(korp_mutex *mutex) { int ret = -1; @@ -332,7 +344,8 @@ int os_mutex_lock(korp_mutex *mutex) return ret == pdPASS ? BHT_OK : BHT_ERROR; } -int os_mutex_unlock(korp_mutex *mutex) +int +os_mutex_unlock(korp_mutex *mutex) { int ret = -1; @@ -343,7 +356,8 @@ int os_mutex_unlock(korp_mutex *mutex) return ret == pdPASS ? BHT_OK : BHT_ERROR; } -int os_cond_init(korp_cond *cond) +int +os_cond_init(korp_cond *cond) { if (!(cond->wait_list_lock = xSemaphoreCreateMutex())) return BHT_ERROR; @@ -352,15 +366,15 @@ int os_cond_init(korp_cond *cond) return BHT_OK; } -int os_cond_destroy(korp_cond *cond) +int +os_cond_destroy(korp_cond *cond) { vSemaphoreDelete(cond->wait_list_lock); return BHT_OK; } static int -os_cond_wait_internal(korp_cond *cond, korp_mutex *mutex, - bool timed, int mills) +os_cond_wait_internal(korp_cond *cond, korp_mutex *mutex, bool timed, int mills) { os_thread_wait_node *node = &thread_data_current()->wait_node; @@ -399,12 +413,14 @@ os_cond_wait_internal(korp_cond *cond, korp_mutex *mutex, return BHT_OK; } -int os_cond_wait(korp_cond *cond, korp_mutex *mutex) +int +os_cond_wait(korp_cond *cond, korp_mutex *mutex) { return os_cond_wait_internal(cond, mutex, false, 0); } -int os_cond_reltimedwait(korp_cond *cond, korp_mutex *mutex, uint64 useconds) +int +os_cond_reltimedwait(korp_cond *cond, korp_mutex *mutex, uint64 useconds) { if (useconds == BHT_WAIT_FOREVER) { return os_cond_wait_internal(cond, mutex, false, 0); @@ -425,7 +441,8 @@ int os_cond_reltimedwait(korp_cond *cond, korp_mutex *mutex, uint64 useconds) } } -int os_cond_signal(korp_cond *cond) +int +os_cond_signal(korp_cond *cond) { /* Signal the head wait node of wait list */ xSemaphoreTake(cond->wait_list_lock, portMAX_DELAY); @@ -435,4 +452,3 @@ int os_cond_signal(korp_cond *cond) return BHT_OK; } - diff --git a/core/shared/platform/common/freertos/freertos_time.c b/core/shared/platform/common/freertos/freertos_time.c index 72b1b58422..4497d8c6ce 100644 --- a/core/shared/platform/common/freertos/freertos_time.c +++ b/core/shared/platform/common/freertos/freertos_time.c @@ -11,4 +11,3 @@ os_time_get_boot_microsecond() TickType_t ticks = xTaskGetTickCount(); return (uint64)1000 * 1000 / configTICK_RATE_HZ * ticks; } - diff --git a/core/shared/platform/common/math/math.c b/core/shared/platform/common/math/math.c index 6b4f25f2b7..e3b1a7a48c 100644 --- a/core/shared/platform/common/math/math.c +++ b/core/shared/platform/common/math/math.c @@ -52,69 +52,63 @@ pdouble2pint(double *pdouble) return u.pint; } -typedef union -{ +typedef union { double value; - struct - { + struct { u_int32_t lsw; u_int32_t msw; } parts; - struct - { + struct { u_int64_t w; } xparts; } ieee_double_shape_type_little; -typedef union -{ +typedef union { double value; - struct - { + struct { u_int32_t msw; u_int32_t lsw; } parts; - struct - { + struct { u_int64_t w; } xparts; } ieee_double_shape_type_big; typedef union { - double d; + double d; struct { - unsigned int manl :32; - unsigned int manh :20; - unsigned int exp :11; - unsigned int sign :1; + unsigned int manl : 32; + unsigned int manh : 20; + unsigned int exp : 11; + unsigned int sign : 1; } bits; } IEEEd2bits_L; typedef union { - double d; + double d; struct { - unsigned int sign :1; - unsigned int exp :11; - unsigned int manh :20; - unsigned int manl :32; + unsigned int sign : 1; + unsigned int exp : 11; + unsigned int manh : 20; + unsigned int manl : 32; } bits; } IEEEd2bits_B; typedef union { - float f; + float f; struct { - unsigned int man :23; - unsigned int exp :8; - unsigned int sign :1; + unsigned int man : 23; + unsigned int exp : 8; + unsigned int sign : 1; } bits; } IEEEf2bits_L; typedef union { - float f; + float f; struct { - unsigned int sign :1; - unsigned int exp :8; - unsigned int man :23; + unsigned int sign : 1; + unsigned int exp : 8; + unsigned int man : 23; } bits; } IEEEf2bits_B; @@ -125,191 +119,192 @@ static union { #define is_little_endian() (__ue.b == 1) -#define __HIL(x) *(1+pdouble2pint(&x)) +#define __HIL(x) *(1 + pdouble2pint(&x)) #define __LOL(x) *(pdouble2pint(&x)) #define __HIB(x) *(pdouble2pint(&x)) -#define __LOB(x) *(1+pdouble2pint(&x)) +#define __LOB(x) *(1 + pdouble2pint(&x)) /* Get two 32 bit ints from a double. */ -#define EXTRACT_WORDS_L(ix0,ix1,d) \ - do { \ - ieee_double_shape_type_little ew_u; \ - ew_u.value = (d); \ - (ix0) = ew_u.parts.msw; \ - (ix1) = ew_u.parts.lsw; \ - } while (0) +#define EXTRACT_WORDS_L(ix0, ix1, d) \ + do { \ + ieee_double_shape_type_little ew_u; \ + ew_u.value = (d); \ + (ix0) = ew_u.parts.msw; \ + (ix1) = ew_u.parts.lsw; \ + } while (0) /* Set a double from two 32 bit ints. */ -#define INSERT_WORDS_L(d,ix0,ix1) \ - do { \ - ieee_double_shape_type_little iw_u; \ - iw_u.parts.msw = (ix0); \ - iw_u.parts.lsw = (ix1); \ - (d) = iw_u.value; \ - } while (0) +#define INSERT_WORDS_L(d, ix0, ix1) \ + do { \ + ieee_double_shape_type_little iw_u; \ + iw_u.parts.msw = (ix0); \ + iw_u.parts.lsw = (ix1); \ + (d) = iw_u.value; \ + } while (0) /* Get two 32 bit ints from a double. */ -#define EXTRACT_WORDS_B(ix0,ix1,d) \ - do { \ - ieee_double_shape_type_big ew_u; \ - ew_u.value = (d); \ - (ix0) = ew_u.parts.msw; \ - (ix1) = ew_u.parts.lsw; \ - } while (0) +#define EXTRACT_WORDS_B(ix0, ix1, d) \ + do { \ + ieee_double_shape_type_big ew_u; \ + ew_u.value = (d); \ + (ix0) = ew_u.parts.msw; \ + (ix1) = ew_u.parts.lsw; \ + } while (0) /* Set a double from two 32 bit ints. */ -#define INSERT_WORDS_B(d,ix0,ix1) \ - do { \ - ieee_double_shape_type_big iw_u; \ - iw_u.parts.msw = (ix0); \ - iw_u.parts.lsw = (ix1); \ - (d) = iw_u.value; \ - } while (0) +#define INSERT_WORDS_B(d, ix0, ix1) \ + do { \ + ieee_double_shape_type_big iw_u; \ + iw_u.parts.msw = (ix0); \ + iw_u.parts.lsw = (ix1); \ + (d) = iw_u.value; \ + } while (0) /* Get the more significant 32 bit int from a double. */ -#define GET_HIGH_WORD_L(i,d) \ - do { \ - ieee_double_shape_type_little gh_u; \ - gh_u.value = (d); \ - (i) = gh_u.parts.msw; \ - } while (0) +#define GET_HIGH_WORD_L(i, d) \ + do { \ + ieee_double_shape_type_little gh_u; \ + gh_u.value = (d); \ + (i) = gh_u.parts.msw; \ + } while (0) /* Get the more significant 32 bit int from a double. */ -#define GET_HIGH_WORD_B(i,d) \ - do { \ - ieee_double_shape_type_big gh_u; \ - gh_u.value = (d); \ - (i) = gh_u.parts.msw; \ - } while (0) +#define GET_HIGH_WORD_B(i, d) \ + do { \ + ieee_double_shape_type_big gh_u; \ + gh_u.value = (d); \ + (i) = gh_u.parts.msw; \ + } while (0) /* Set the more significant 32 bits of a double from an int. */ -#define SET_HIGH_WORD_L(d,v) \ - do { \ - ieee_double_shape_type_little sh_u; \ - sh_u.value = (d); \ - sh_u.parts.msw = (v); \ - (d) = sh_u.value; \ - } while (0) +#define SET_HIGH_WORD_L(d, v) \ + do { \ + ieee_double_shape_type_little sh_u; \ + sh_u.value = (d); \ + sh_u.parts.msw = (v); \ + (d) = sh_u.value; \ + } while (0) /* Set the more significant 32 bits of a double from an int. */ -#define SET_HIGH_WORD_B(d,v) \ - do { \ - ieee_double_shape_type_big sh_u; \ - sh_u.value = (d); \ - sh_u.parts.msw = (v); \ - (d) = sh_u.value; \ - } while (0) +#define SET_HIGH_WORD_B(d, v) \ + do { \ + ieee_double_shape_type_big sh_u; \ + sh_u.value = (d); \ + sh_u.parts.msw = (v); \ + (d) = sh_u.value; \ + } while (0) /* Set the less significant 32 bits of a double from an int. */ -#define SET_LOW_WORD_L(d,v) \ - do { \ - ieee_double_shape_type_little sh_u; \ - sh_u.value = (d); \ - sh_u.parts.lsw = (v); \ - (d) = sh_u.value; \ - } while (0) +#define SET_LOW_WORD_L(d, v) \ + do { \ + ieee_double_shape_type_little sh_u; \ + sh_u.value = (d); \ + sh_u.parts.lsw = (v); \ + (d) = sh_u.value; \ + } while (0) /* Set the more significant 32 bits of a double from an int. */ -#define SET_LOW_WORD_B(d,v) \ - do { \ - ieee_double_shape_type_big sh_u; \ - sh_u.value = (d); \ - sh_u.parts.lsw = (v); \ - (d) = sh_u.value; \ - } while (0) +#define SET_LOW_WORD_B(d, v) \ + do { \ + ieee_double_shape_type_big sh_u; \ + sh_u.value = (d); \ + sh_u.parts.lsw = (v); \ + (d) = sh_u.value; \ + } while (0) /* Get the less significant 32 bit int from a double. */ -#define GET_LOW_WORD_L(i,d) \ - do { \ - ieee_double_shape_type_little gl_u; \ - gl_u.value = (d); \ - (i) = gl_u.parts.lsw; \ - } while (0) +#define GET_LOW_WORD_L(i, d) \ + do { \ + ieee_double_shape_type_little gl_u; \ + gl_u.value = (d); \ + (i) = gl_u.parts.lsw; \ + } while (0) /* Get the less significant 32 bit int from a double. */ -#define GET_LOW_WORD_B(i,d) \ - do { \ - ieee_double_shape_type_big gl_u; \ - gl_u.value = (d); \ - (i) = gl_u.parts.lsw; \ - } while (0) +#define GET_LOW_WORD_B(i, d) \ + do { \ + ieee_double_shape_type_big gl_u; \ + gl_u.value = (d); \ + (i) = gl_u.parts.lsw; \ + } while (0) /* * A union which permits us to convert between a float and a 32 bit * int. */ -typedef union -{ +typedef union { float value; /* FIXME: Assumes 32 bit int. */ unsigned int word; } ieee_float_shape_type; /* Get a 32 bit int from a float. */ -#define GET_FLOAT_WORD(i,d) \ - do { \ - ieee_float_shape_type gf_u; \ - gf_u.value = (d); \ - (i) = gf_u.word; \ +#define GET_FLOAT_WORD(i, d) \ + do { \ + ieee_float_shape_type gf_u; \ + gf_u.value = (d); \ + (i) = gf_u.word; \ } while (0) /* Set a float from a 32 bit int. */ -#define SET_FLOAT_WORD(d,i) \ - do { \ - ieee_float_shape_type sf_u; \ - sf_u.word = (i); \ - (d) = sf_u.value; \ +#define SET_FLOAT_WORD(d, i) \ + do { \ + ieee_float_shape_type sf_u; \ + sf_u.word = (i); \ + (d) = sf_u.value; \ } while (0) /* Macro wrappers. */ -#define EXTRACT_WORDS(ix0,ix1,d) do { \ - if (is_little_endian()) \ - EXTRACT_WORDS_L(ix0,ix1,d); \ - else \ - EXTRACT_WORDS_B(ix0,ix1,d); \ -} while (0) - -#define INSERT_WORDS(d,ix0,ix1) do { \ - if (is_little_endian()) \ - INSERT_WORDS_L(d,ix0,ix1); \ - else \ - INSERT_WORDS_B(d,ix0,ix1); \ -} while (0) - -#define GET_HIGH_WORD(i,d) \ - do { \ - if (is_little_endian()) \ - GET_HIGH_WORD_L(i,d); \ - else \ - GET_HIGH_WORD_B(i,d); \ +#define EXTRACT_WORDS(ix0, ix1, d) \ + do { \ + if (is_little_endian()) \ + EXTRACT_WORDS_L(ix0, ix1, d); \ + else \ + EXTRACT_WORDS_B(ix0, ix1, d); \ + } while (0) + +#define INSERT_WORDS(d, ix0, ix1) \ + do { \ + if (is_little_endian()) \ + INSERT_WORDS_L(d, ix0, ix1); \ + else \ + INSERT_WORDS_B(d, ix0, ix1); \ + } while (0) + +#define GET_HIGH_WORD(i, d) \ + do { \ + if (is_little_endian()) \ + GET_HIGH_WORD_L(i, d); \ + else \ + GET_HIGH_WORD_B(i, d); \ } while (0) -#define SET_HIGH_WORD(d,v) \ - do { \ - if (is_little_endian()) \ - SET_HIGH_WORD_L(d,v); \ - else \ - SET_HIGH_WORD_B(d,v); \ +#define SET_HIGH_WORD(d, v) \ + do { \ + if (is_little_endian()) \ + SET_HIGH_WORD_L(d, v); \ + else \ + SET_HIGH_WORD_B(d, v); \ } while (0) -#define GET_LOW_WORD(d,v) \ - do { \ - if (is_little_endian()) \ - GET_LOW_WORD_L(d,v); \ - else \ - GET_LOW_WORD_B(d,v); \ +#define GET_LOW_WORD(d, v) \ + do { \ + if (is_little_endian()) \ + GET_LOW_WORD_L(d, v); \ + else \ + GET_LOW_WORD_B(d, v); \ } while (0) -#define SET_LOW_WORD(d,v) \ - do { \ - if (is_little_endian()) \ - SET_LOW_WORD_L(d,v); \ - else \ - SET_LOW_WORD_B(d,v); \ +#define SET_LOW_WORD(d, v) \ + do { \ + if (is_little_endian()) \ + SET_LOW_WORD_L(d, v); \ + else \ + SET_LOW_WORD_B(d, v); \ } while (0) #define __HI(x) (is_little_endian() ? __HIL(x) : __HIB(x)) @@ -320,18 +315,19 @@ typedef union * Attempt to get strict C99 semantics for assignment with non-C99 compilers. */ #if FLT_EVAL_METHOD == 0 || __GNUC__ == 0 -#define STRICT_ASSIGN(type, lval, rval) ((lval) = (rval)) +#define STRICT_ASSIGN(type, lval, rval) ((lval) = (rval)) #else -#define STRICT_ASSIGN(type, lval, rval) do { \ - volatile type __lval; \ - \ - if (sizeof(type) >= sizeof(long double)) \ - (lval) = (rval); \ - else { \ - __lval = (rval); \ - (lval) = __lval; \ - } \ -} while (0) +#define STRICT_ASSIGN(type, lval, rval) \ + do { \ + volatile type __lval; \ + \ + if (sizeof(type) >= sizeof(long double)) \ + (lval) = (rval); \ + else { \ + __lval = (rval); \ + (lval) = __lval; \ + } \ + } while (0) #endif #ifdef __FDLIBM_STDC__ @@ -345,78 +341,78 @@ static const double #else static double #endif -tiny = 1.0e-300; + tiny = 1.0e-300; #ifdef __STDC__ static const double #else static double #endif -one= 1.00000000000000000000e+00; /* 0x3FF00000, 0x00000000 */ + one = 1.00000000000000000000e+00; /* 0x3FF00000, 0x00000000 */ #ifdef __STDC__ static const double #else static double #endif -TWO52[2]={ - 4.50359962737049600000e+15, /* 0x43300000, 0x00000000 */ + TWO52[2] = { + 4.50359962737049600000e+15, /* 0x43300000, 0x00000000 */ -4.50359962737049600000e+15, /* 0xC3300000, 0x00000000 */ -}; + }; #ifdef __STDC__ static const double #else static double #endif -atanhi[] = { - 4.63647609000806093515e-01, /* atan(0.5)hi 0x3FDDAC67, 0x0561BB4F */ - 7.85398163397448278999e-01, /* atan(1.0)hi 0x3FE921FB, 0x54442D18 */ - 9.82793723247329054082e-01, /* atan(1.5)hi 0x3FEF730B, 0xD281F69B */ - 1.57079632679489655800e+00, /* atan(inf)hi 0x3FF921FB, 0x54442D18 */ -}; + atanhi[] = { + 4.63647609000806093515e-01, /* atan(0.5)hi 0x3FDDAC67, 0x0561BB4F */ + 7.85398163397448278999e-01, /* atan(1.0)hi 0x3FE921FB, 0x54442D18 */ + 9.82793723247329054082e-01, /* atan(1.5)hi 0x3FEF730B, 0xD281F69B */ + 1.57079632679489655800e+00, /* atan(inf)hi 0x3FF921FB, 0x54442D18 */ + }; #ifdef __STDC__ static const double #else static double #endif -atanlo[] = { - 2.26987774529616870924e-17, /* atan(0.5)lo 0x3C7A2B7F, 0x222F65E2 */ - 3.06161699786838301793e-17, /* atan(1.0)lo 0x3C81A626, 0x33145C07 */ - 1.39033110312309984516e-17, /* atan(1.5)lo 0x3C700788, 0x7AF0CBBD */ - 6.12323399573676603587e-17, /* atan(inf)lo 0x3C91A626, 0x33145C07 */ -}; + atanlo[] = { + 2.26987774529616870924e-17, /* atan(0.5)lo 0x3C7A2B7F, 0x222F65E2 */ + 3.06161699786838301793e-17, /* atan(1.0)lo 0x3C81A626, 0x33145C07 */ + 1.39033110312309984516e-17, /* atan(1.5)lo 0x3C700788, 0x7AF0CBBD */ + 6.12323399573676603587e-17, /* atan(inf)lo 0x3C91A626, 0x33145C07 */ + }; #ifdef __STDC__ static const double #else static double #endif -aT[] = { - 3.33333333333329318027e-01, /* 0x3FD55555, 0x5555550D */ - -1.99999999998764832476e-01, /* 0xBFC99999, 0x9998EBC4 */ - 1.42857142725034663711e-01, /* 0x3FC24924, 0x920083FF */ - -1.11111104054623557880e-01, /* 0xBFBC71C6, 0xFE231671 */ - 9.09088713343650656196e-02, /* 0x3FB745CD, 0xC54C206E */ - -7.69187620504482999495e-02, /* 0xBFB3B0F2, 0xAF749A6D */ - 6.66107313738753120669e-02, /* 0x3FB10D66, 0xA0D03D51 */ - -5.83357013379057348645e-02, /* 0xBFADDE2D, 0x52DEFD9A */ - 4.97687799461593236017e-02, /* 0x3FA97B4B, 0x24760DEB */ - -3.65315727442169155270e-02, /* 0xBFA2B444, 0x2C6A6C2F */ - 1.62858201153657823623e-02, /* 0x3F90AD3A, 0xE322DA11 */ -}; + aT[] = { + 3.33333333333329318027e-01, /* 0x3FD55555, 0x5555550D */ + -1.99999999998764832476e-01, /* 0xBFC99999, 0x9998EBC4 */ + 1.42857142725034663711e-01, /* 0x3FC24924, 0x920083FF */ + -1.11111104054623557880e-01, /* 0xBFBC71C6, 0xFE231671 */ + 9.09088713343650656196e-02, /* 0x3FB745CD, 0xC54C206E */ + -7.69187620504482999495e-02, /* 0xBFB3B0F2, 0xAF749A6D */ + 6.66107313738753120669e-02, /* 0x3FB10D66, 0xA0D03D51 */ + -5.83357013379057348645e-02, /* 0xBFADDE2D, 0x52DEFD9A */ + 4.97687799461593236017e-02, /* 0x3FA97B4B, 0x24760DEB */ + -3.65315727442169155270e-02, /* 0xBFA2B444, 0x2C6A6C2F */ + 1.62858201153657823623e-02, /* 0x3F90AD3A, 0xE322DA11 */ + }; #ifdef __STDC__ static const double #else static double #endif -zero = 0.0, -pi_o_4 = 7.8539816339744827900E-01, /* 0x3FE921FB, 0x54442D18 */ -pi_o_2 = 1.5707963267948965580E+00, /* 0x3FF921FB, 0x54442D18 */ -pi = 3.1415926535897931160E+00, /* 0x400921FB, 0x54442D18 */ -pi_lo = 1.2246467991473531772E-16; /* 0x3CA1A626, 0x33145C07 */ + zero = 0.0, + pi_o_4 = 7.8539816339744827900E-01, /* 0x3FE921FB, 0x54442D18 */ + pi_o_2 = 1.5707963267948965580E+00, /* 0x3FF921FB, 0x54442D18 */ + pi = 3.1415926535897931160E+00, /* 0x400921FB, 0x54442D18 */ + pi_lo = 1.2246467991473531772E-16; /* 0x3CA1A626, 0x33145C07 */ #ifdef __STDC__ static const double @@ -453,346 +449,441 @@ ivln2 = 1.44269504088896338700e+00, /* 0x3FF71547, 0x652B82FE =1/ln2 */ ivln2_h = 1.44269502162933349609e+00, /* 0x3FF71547, 0x60000000 =24b 1/ln2*/ ivln2_l = 1.92596299112661746887e-08; /* 0x3E54AE0B, 0xF85DDF44 =1/ln2 tail*/ -static double freebsd_sqrt(double x); -static double freebsd_floor(double x); -static double freebsd_ceil(double x); -static double freebsd_fabs(double x); -static double freebsd_rint(double x); -static int freebsd_isnan(double x); -static double freebsd_atan(double x); -static double freebsd_atan2(double y, double x); - +static double +freebsd_sqrt(double x); +static double +freebsd_floor(double x); +static double +freebsd_ceil(double x); +static double +freebsd_fabs(double x); +static double +freebsd_rint(double x); +static int +freebsd_isnan(double x); +static double +freebsd_atan(double x); +static double +freebsd_atan2(double y, double x); -static double freebsd_atan(double x) +static double +freebsd_atan(double x) { - double w,s1,s2,z; - int32_t ix,hx,id; - - GET_HIGH_WORD(hx,x); - ix = hx&0x7fffffff; - if(ix>=0x44100000) { /* if |x| >= 2^66 */ - u_int32_t low; - GET_LOW_WORD(low,x); - if(ix>0x7ff00000|| - (ix==0x7ff00000&&(low!=0))) - return x+x; /* NaN */ - if(hx>0) return atanhi[3]+*(volatile double *)&atanlo[3]; - else return -atanhi[3]-*(volatile double *)&atanlo[3]; - } if (ix < 0x3fdc0000) { /* |x| < 0.4375 */ - if (ix < 0x3e400000) { /* |x| < 2^-27 */ - if(huge+x>one) return x; /* raise inexact */ - } - id = -1; - } else { - x = freebsd_fabs(x); - if (ix < 0x3ff30000) { /* |x| < 1.1875 */ - if (ix < 0x3fe60000) { /* 7/16 <=|x|<11/16 */ - id = 0; x = (2.0*x-one)/(2.0+x); - } else { /* 11/16<=|x|< 19/16 */ - id = 1; x = (x-one)/(x+one); - } - } else { - if (ix < 0x40038000) { /* |x| < 2.4375 */ - id = 2; x = (x-1.5)/(one+1.5*x); - } else { /* 2.4375 <= |x| < 2^66 */ - id = 3; x = -1.0/x; - } - }} + double w, s1, s2, z; + int32_t ix, hx, id; + + GET_HIGH_WORD(hx, x); + ix = hx & 0x7fffffff; + if (ix >= 0x44100000) { /* if |x| >= 2^66 */ + u_int32_t low; + GET_LOW_WORD(low, x); + if (ix > 0x7ff00000 || (ix == 0x7ff00000 && (low != 0))) + return x + x; /* NaN */ + if (hx > 0) + return atanhi[3] + *(volatile double *)&atanlo[3]; + else + return -atanhi[3] - *(volatile double *)&atanlo[3]; + } + if (ix < 0x3fdc0000) { /* |x| < 0.4375 */ + if (ix < 0x3e400000) { /* |x| < 2^-27 */ + if (huge + x > one) + return x; /* raise inexact */ + } + id = -1; + } + else { + x = freebsd_fabs(x); + if (ix < 0x3ff30000) { /* |x| < 1.1875 */ + if (ix < 0x3fe60000) { /* 7/16 <=|x|<11/16 */ + id = 0; + x = (2.0 * x - one) / (2.0 + x); + } + else { /* 11/16<=|x|< 19/16 */ + id = 1; + x = (x - one) / (x + one); + } + } + else { + if (ix < 0x40038000) { /* |x| < 2.4375 */ + id = 2; + x = (x - 1.5) / (one + 1.5 * x); + } + else { /* 2.4375 <= |x| < 2^66 */ + id = 3; + x = -1.0 / x; + } + } + } /* end of argument reduction */ - z = x*x; - w = z*z; + z = x * x; + w = z * z; /* break sum from i=0 to 10 aT[i]z**(i+1) into odd and even poly */ - s1 = z*(aT[0]+w*(aT[2]+w*(aT[4]+w*(aT[6]+w*(aT[8]+w*aT[10]))))); - s2 = w*(aT[1]+w*(aT[3]+w*(aT[5]+w*(aT[7]+w*aT[9])))); - if (id<0) return x - x*(s1+s2); - else { - z = atanhi[id] - ((x*(s1+s2) - atanlo[id]) - x); - return (hx<0)? -z:z; - } + s1 = z + * (aT[0] + + w + * (aT[2] + + w * (aT[4] + w * (aT[6] + w * (aT[8] + w * aT[10]))))); + s2 = w * (aT[1] + w * (aT[3] + w * (aT[5] + w * (aT[7] + w * aT[9])))); + if (id < 0) + return x - x * (s1 + s2); + else { + z = atanhi[id] - ((x * (s1 + s2) - atanlo[id]) - x); + return (hx < 0) ? -z : z; + } } - -static double freebsd_atan2(double y, double x) +static double +freebsd_atan2(double y, double x) { double z; - int32_t k,m,hx,hy,ix,iy; - u_int32_t lx,ly; - - EXTRACT_WORDS(hx,lx,x); - ix = hx&0x7fffffff; - EXTRACT_WORDS(hy,ly,y); - iy = hy&0x7fffffff; - if(((ix|((lx|-lx)>>31))>0x7ff00000)|| - ((iy|((ly|-ly)>>31))>0x7ff00000)) /* x or y is NaN */ - return x+y; - if(hx==0x3ff00000&&lx==0) return freebsd_atan(y); /* x=1.0 */ - m = ((hy>>31)&1)|((hx>>30)&2); /* 2*sign(x)+sign(y) */ + int32_t k, m, hx, hy, ix, iy; + u_int32_t lx, ly; + + EXTRACT_WORDS(hx, lx, x); + ix = hx & 0x7fffffff; + EXTRACT_WORDS(hy, ly, y); + iy = hy & 0x7fffffff; + if (((ix | ((lx | -lx) >> 31)) > 0x7ff00000) + || ((iy | ((ly | -ly) >> 31)) > 0x7ff00000)) /* x or y is NaN */ + return x + y; + if (hx == 0x3ff00000 && lx == 0) + return freebsd_atan(y); /* x=1.0 */ + m = ((hy >> 31) & 1) | ((hx >> 30) & 2); /* 2*sign(x)+sign(y) */ /* when y = 0 */ - if((iy|ly)==0) { - switch(m) { - case 0: - case 1: return y; /* atan(+-0,+anything)=+-0 */ - case 2: return pi+tiny;/* atan(+0,-anything) = pi */ - case 3: - default: return -pi-tiny;/* atan(-0,-anything) =-pi */ - } - } + if ((iy | ly) == 0) { + switch (m) { + case 0: + case 1: + return y; /* atan(+-0,+anything)=+-0 */ + case 2: + return pi + tiny; /* atan(+0,-anything) = pi */ + case 3: + default: + return -pi - tiny; /* atan(-0,-anything) =-pi */ + } + } /* when x = 0 */ - if((ix|lx)==0) return (hy<0)? -pi_o_2-tiny: pi_o_2+tiny; + if ((ix | lx) == 0) + return (hy < 0) ? -pi_o_2 - tiny : pi_o_2 + tiny; /* when x is INF */ - if(ix==0x7ff00000) { - if(iy==0x7ff00000) { - switch(m) { - case 0: return pi_o_4+tiny;/* atan(+INF,+INF) */ - case 1: return -pi_o_4-tiny;/* atan(-INF,+INF) */ - case 2: return 3.0*pi_o_4+tiny;/*atan(+INF,-INF)*/ - case 3: - default: return -3.0*pi_o_4-tiny;/*atan(-INF,-INF)*/ - } - } else { - switch(m) { - case 0: return zero ; /* atan(+...,+INF) */ - case 1: return -zero ; /* atan(-...,+INF) */ - case 2: return pi+tiny ; /* atan(+...,-INF) */ - case 3: - default: return -pi-tiny ; /* atan(-...,-INF) */ - } - } - } + if (ix == 0x7ff00000) { + if (iy == 0x7ff00000) { + switch (m) { + case 0: + return pi_o_4 + tiny; /* atan(+INF,+INF) */ + case 1: + return -pi_o_4 - tiny; /* atan(-INF,+INF) */ + case 2: + return 3.0 * pi_o_4 + tiny; /*atan(+INF,-INF)*/ + case 3: + default: + return -3.0 * pi_o_4 - tiny; /*atan(-INF,-INF)*/ + } + } + else { + switch (m) { + case 0: + return zero; /* atan(+...,+INF) */ + case 1: + return -zero; /* atan(-...,+INF) */ + case 2: + return pi + tiny; /* atan(+...,-INF) */ + case 3: + default: + return -pi - tiny; /* atan(-...,-INF) */ + } + } + } /* when y is INF */ - if(iy==0x7ff00000) return (hy<0)? -pi_o_2-tiny: pi_o_2+tiny; + if (iy == 0x7ff00000) + return (hy < 0) ? -pi_o_2 - tiny : pi_o_2 + tiny; /* compute y/x */ - k = (iy-ix)>>20; - if(k > 60) { /* |y/x| > 2**60 */ - z=pi_o_2+0.5*pi_lo; - m&=1; - } - else if(hx<0&&k<-60) z=0.0; /* 0 > |y|/x > -2**-60 */ - else z=freebsd_atan(fabs(y/x)); /* safe to do y/x */ - switch (m) { - case 0: return z ; /* atan(+,+) */ - case 1: return -z ; /* atan(-,+) */ - case 2: return pi-(z-pi_lo);/* atan(+,-) */ - default: /* case 3 */ - return (z-pi_lo)-pi;/* atan(-,-) */ - } + k = (iy - ix) >> 20; + if (k > 60) { /* |y/x| > 2**60 */ + z = pi_o_2 + 0.5 * pi_lo; + m &= 1; + } + else if (hx < 0 && k < -60) + z = 0.0; /* 0 > |y|/x > -2**-60 */ + else + z = freebsd_atan(fabs(y / x)); /* safe to do y/x */ + switch (m) { + case 0: + return z; /* atan(+,+) */ + case 1: + return -z; /* atan(-,+) */ + case 2: + return pi - (z - pi_lo); /* atan(+,-) */ + default: /* case 3 */ + return (z - pi_lo) - pi; /* atan(-,-) */ + } } -static double freebsd_sqrt(double x) /* wrapper sqrt */ +static double +freebsd_sqrt(double x) /* wrapper sqrt */ { double z; int32_t sign = (int)0x80000000; - int32_t ix0,s0,q,m,t,i; - u_int32_t r,t1,s1,ix1,q1; + int32_t ix0, s0, q, m, t, i; + u_int32_t r, t1, s1, ix1, q1; - EXTRACT_WORDS(ix0,ix1,x); + EXTRACT_WORDS(ix0, ix1, x); /* take care of Inf and NaN */ - if((ix0&0x7ff00000)==0x7ff00000) { - return x*x+x; /* sqrt(NaN)=NaN, sqrt(+inf)=+inf - sqrt(-inf)=sNaN */ + if ((ix0 & 0x7ff00000) == 0x7ff00000) { + return x * x + x; /* sqrt(NaN)=NaN, sqrt(+inf)=+inf + sqrt(-inf)=sNaN */ } /* take care of zero */ - if(ix0<=0) { - if(((ix0&(~sign))|ix1)==0) return x;/* sqrt(+-0) = +-0 */ - else if(ix0<0) - return (x-x)/(x-x); /* sqrt(-ve) = sNaN */ + if (ix0 <= 0) { + if (((ix0 & (~sign)) | ix1) == 0) + return x; /* sqrt(+-0) = +-0 */ + else if (ix0 < 0) + return (x - x) / (x - x); /* sqrt(-ve) = sNaN */ } /* normalize x */ - m = (ix0>>20); - if(m==0) { /* subnormal x */ - while(ix0==0) { + m = (ix0 >> 20); + if (m == 0) { /* subnormal x */ + while (ix0 == 0) { m -= 21; - ix0 |= (ix1>>11); ix1 <<= 21; + ix0 |= (ix1 >> 11); + ix1 <<= 21; } - for(i=0;(ix0&0x00100000)==0;i++) ix0<<=1; - m -= i-1; - ix0 |= (ix1>>(32-i)); + for (i = 0; (ix0 & 0x00100000) == 0; i++) + ix0 <<= 1; + m -= i - 1; + ix0 |= (ix1 >> (32 - i)); ix1 <<= i; } - m -= 1023; /* unbias exponent */ - ix0 = (ix0&0x000fffff)|0x00100000; - if(m&1){ /* odd m, double x to make it even */ - ix0 += ix0 + ((ix1&sign)>>31); + m -= 1023; /* unbias exponent */ + ix0 = (ix0 & 0x000fffff) | 0x00100000; + if (m & 1) { /* odd m, double x to make it even */ + ix0 += ix0 + ((ix1 & sign) >> 31); ix1 += ix1; } - m >>= 1; /* m = [m/2] */ + m >>= 1; /* m = [m/2] */ /* generate sqrt(x) bit by bit */ - ix0 += ix0 + ((ix1&sign)>>31); + ix0 += ix0 + ((ix1 & sign) >> 31); ix1 += ix1; - q = q1 = s0 = s1 = 0; /* [q,q1] = sqrt(x) */ - r = 0x00200000; /* r = moving bit from right to left */ + q = q1 = s0 = s1 = 0; /* [q,q1] = sqrt(x) */ + r = 0x00200000; /* r = moving bit from right to left */ - while(r!=0) { - t = s0+r; - if(t<=ix0) { - s0 = t+r; + while (r != 0) { + t = s0 + r; + if (t <= ix0) { + s0 = t + r; ix0 -= t; - q += r; + q += r; } - ix0 += ix0 + ((ix1&sign)>>31); + ix0 += ix0 + ((ix1 & sign) >> 31); ix1 += ix1; - r>>=1; + r >>= 1; } r = sign; - while(r!=0) { - t1 = s1+r; - t = s0; - if((t>31); + ix0 += ix0 + ((ix1 & sign) >> 31); ix1 += ix1; - r>>=1; + r >>= 1; } /* use floating add to find out rounding direction */ - if((ix0|ix1)!=0) { - z = one-tiny; /* trigger inexact flag */ - if (z>=one) { - z = one+tiny; - if (q1==(u_int32_t)0xffffffff) { q1=0; q += 1;} - else if (z>one) { - if (q1==(u_int32_t)0xfffffffe) q+=1; - q1+=2; - } else - q1 += (q1&1); + if ((ix0 | ix1) != 0) { + z = one - tiny; /* trigger inexact flag */ + if (z >= one) { + z = one + tiny; + if (q1 == (u_int32_t)0xffffffff) { + q1 = 0; + q += 1; + } + else if (z > one) { + if (q1 == (u_int32_t)0xfffffffe) + q += 1; + q1 += 2; + } + else + q1 += (q1 & 1); } } - ix0 = (q>>1)+0x3fe00000; - ix1 = q1>>1; - if ((q&1)==1) ix1 |= sign; - ix0 += (m <<20); + ix0 = (q >> 1) + 0x3fe00000; + ix1 = q1 >> 1; + if ((q & 1) == 1) + ix1 |= sign; + ix0 += (m << 20); - INSERT_WORDS(z,ix0,ix1); + INSERT_WORDS(z, ix0, ix1); return z; } -static double freebsd_floor(double x) +static double +freebsd_floor(double x) { - int32_t i0,i1,j0; - u_int32_t i,j; - - EXTRACT_WORDS(i0,i1,x); - - j0 = ((i0>>20)&0x7ff)-0x3ff; - if(j0<20) { - if(j0<0) { /* raise inexact if x != 0 */ - if(huge+x>0.0) {/* return 0*sign(x) if |x|<1 */ - if(i0>=0) {i0=i1=0;} - else if(((i0&0x7fffffff)|i1)!=0) - { i0=0xbff00000;i1=0;} + int32_t i0, i1, j0; + u_int32_t i, j; + + EXTRACT_WORDS(i0, i1, x); + + j0 = ((i0 >> 20) & 0x7ff) - 0x3ff; + if (j0 < 20) { + if (j0 < 0) { /* raise inexact if x != 0 */ + if (huge + x > 0.0) { /* return 0*sign(x) if |x|<1 */ + if (i0 >= 0) { + i0 = i1 = 0; + } + else if (((i0 & 0x7fffffff) | i1) != 0) { + i0 = 0xbff00000; + i1 = 0; + } } - } else { - i = (0x000fffff)>>j0; - if(((i0&i)|i1)==0) return x; /* x is integral */ - if(huge+x>0.0) { /* raise inexact flag */ - if(i0<0) i0 += (0x00100000)>>j0; - i0 &= (~i); i1=0; + } + else { + i = (0x000fffff) >> j0; + if (((i0 & i) | i1) == 0) + return x; /* x is integral */ + if (huge + x > 0.0) { /* raise inexact flag */ + if (i0 < 0) + i0 += (0x00100000) >> j0; + i0 &= (~i); + i1 = 0; } } - } else if (j0>51) { - if(j0==0x400) return x+x; /* inf or NaN */ - else return x; /* x is integral */ - } else { - i = ((u_int32_t)(0xffffffff))>>(j0-20); - if((i1&i)==0) return x; /* x is integral */ - if(huge+x>0.0) { /* raise inexact flag */ - if(i0<0) { - if(j0==20) i0+=1; + } + else if (j0 > 51) { + if (j0 == 0x400) + return x + x; /* inf or NaN */ + else + return x; /* x is integral */ + } + else { + i = ((u_int32_t)(0xffffffff)) >> (j0 - 20); + if ((i1 & i) == 0) + return x; /* x is integral */ + if (huge + x > 0.0) { /* raise inexact flag */ + if (i0 < 0) { + if (j0 == 20) + i0 += 1; else { - j = i1+(1<<(52-j0)); - if(j>20)&0x7ff)-0x3ff; - if(j0<20) { - if(j0<0) { /* raise inexact if x != 0 */ - if(huge+x>0.0) {/* return 0*sign(x) if |x|<1 */ - if(i0<0) {i0=0x80000000;i1=0;} - else if((i0|i1)!=0) { i0=0x3ff00000;i1=0;} + int32_t i0, i1, j0; + u_int32_t i, j; + EXTRACT_WORDS(i0, i1, x); + j0 = ((i0 >> 20) & 0x7ff) - 0x3ff; + if (j0 < 20) { + if (j0 < 0) { /* raise inexact if x != 0 */ + if (huge + x > 0.0) { /* return 0*sign(x) if |x|<1 */ + if (i0 < 0) { + i0 = 0x80000000; + i1 = 0; + } + else if ((i0 | i1) != 0) { + i0 = 0x3ff00000; + i1 = 0; + } } - } else { - i = (0x000fffff)>>j0; - if(((i0&i)|i1)==0) return x; /* x is integral */ - if(huge+x>0.0) { /* raise inexact flag */ - if(i0>0) i0 += (0x00100000)>>j0; - i0 &= (~i); i1=0; + } + else { + i = (0x000fffff) >> j0; + if (((i0 & i) | i1) == 0) + return x; /* x is integral */ + if (huge + x > 0.0) { /* raise inexact flag */ + if (i0 > 0) + i0 += (0x00100000) >> j0; + i0 &= (~i); + i1 = 0; } } - } else if (j0>51) { - if(j0==0x400) return x+x; /* inf or NaN */ - else return x; /* x is integral */ - } else { - i = ((u_int32_t)(0xffffffff))>>(j0-20); - if((i1&i)==0) return x; /* x is integral */ - if(huge+x>0.0) { /* raise inexact flag */ - if(i0>0) { - if(j0==20) i0+=1; + } + else if (j0 > 51) { + if (j0 == 0x400) + return x + x; /* inf or NaN */ + else + return x; /* x is integral */ + } + else { + i = ((u_int32_t)(0xffffffff)) >> (j0 - 20); + if ((i1 & i) == 0) + return x; /* x is integral */ + if (huge + x > 0.0) { /* raise inexact flag */ + if (i0 > 0) { + if (j0 == 20) + i0 += 1; else { - j = i1 + (1<<(52-j0)); - if(j>31)&1; - j0 = ((i0>>20)&0x7ff)-0x3ff; - if(j0<20) { - if(j0<0) { - if(((i0&0x7fffffff)|i1)==0) return x; - i1 |= (i0&0x0fffff); + int32_t i0, j0, sx; + u_int32_t i, i1; + double w, t; + EXTRACT_WORDS(i0, i1, x); + sx = (i0 >> 31) & 1; + j0 = ((i0 >> 20) & 0x7ff) - 0x3ff; + if (j0 < 20) { + if (j0 < 0) { + if (((i0 & 0x7fffffff) | i1) == 0) + return x; + i1 |= (i0 & 0x0fffff); i0 &= 0xfffe0000; - i0 |= ((i1|-i1)>>12)&0x80000; - SET_HIGH_WORD(x,i0); - STRICT_ASSIGN(double,w,TWO52[sx]+x); - t = w-TWO52[sx]; - GET_HIGH_WORD(i0,t); - SET_HIGH_WORD(t,(i0&0x7fffffff)|(sx<<31)); + i0 |= ((i1 | -i1) >> 12) & 0x80000; + SET_HIGH_WORD(x, i0); + STRICT_ASSIGN(double, w, TWO52[sx] + x); + t = w - TWO52[sx]; + GET_HIGH_WORD(i0, t); + SET_HIGH_WORD(t, (i0 & 0x7fffffff) | (sx << 31)); return t; - } else { - i = (0x000fffff)>>j0; - if(((i0&i)|i1)==0) return x; /* x is integral */ - i>>=1; - if(((i0&i)|i1)!=0) { + } + else { + i = (0x000fffff) >> j0; + if (((i0 & i) | i1) == 0) + return x; /* x is integral */ + i >>= 1; + if (((i0 & i) | i1) != 0) { /* * Some bit is set after the 0.5 bit. To avoid the * possibility of errors from double rounding in @@ -801,26 +892,36 @@ static double freebsd_rint(double x) * adjustment is trickiest for j0==18 and j0==19 * since then it spans the word boundary. */ - if(j0==19) i1 = 0x40000000; else - if(j0==18) i1 = 0x80000000; else - i0 = (i0&(~i))|((0x20000)>>j0); + if (j0 == 19) + i1 = 0x40000000; + else if (j0 == 18) + i1 = 0x80000000; + else + i0 = (i0 & (~i)) | ((0x20000) >> j0); } } - } else if (j0>51) { - if(j0==0x400) return x+x; /* inf or NaN */ - else return x; /* x is integral */ - } else { - i = ((u_int32_t)(0xffffffff))>>(j0-20); - if((i1&i)==0) return x; /* x is integral */ - i>>=1; - if((i1&i)!=0) i1 = (i1&(~i))|((0x40000000)>>(j0-20)); } - INSERT_WORDS(x,i0,i1); - STRICT_ASSIGN(double,w,TWO52[sx]+x); - return w-TWO52[sx]; + else if (j0 > 51) { + if (j0 == 0x400) + return x + x; /* inf or NaN */ + else + return x; /* x is integral */ + } + else { + i = ((u_int32_t)(0xffffffff)) >> (j0 - 20); + if ((i1 & i) == 0) + return x; /* x is integral */ + i >>= 1; + if ((i1 & i) != 0) + i1 = (i1 & (~i)) | ((0x40000000) >> (j0 - 20)); + } + INSERT_WORDS(x, i0, i1); + STRICT_ASSIGN(double, w, TWO52[sx] + x); + return w - TWO52[sx]; } -static int freebsd_isnan(double d) +static int +freebsd_isnan(double d) { if (is_little_endian()) { IEEEd2bits_L u; @@ -834,128 +935,155 @@ static int freebsd_isnan(double d) } } -static double freebsd_fabs(double x) +static double +freebsd_fabs(double x) { u_int32_t high; - GET_HIGH_WORD(high,x); - SET_HIGH_WORD(x,high&0x7fffffff); + GET_HIGH_WORD(high, x); + SET_HIGH_WORD(x, high & 0x7fffffff); return x; } static const float huge_f = 1.0e30F; -static const float -TWO23[2]={ - 8.3886080000e+06, /* 0x4b000000 */ +static const float TWO23[2] = { + 8.3886080000e+06, /* 0x4b000000 */ -8.3886080000e+06, /* 0xcb000000 */ }; static float freebsd_truncf(float x) { - int32_t i0,j0; + int32_t i0, j0; u_int32_t i; - GET_FLOAT_WORD(i0,x); - j0 = ((i0>>23)&0xff)-0x7f; - if(j0<23) { - if(j0<0) { /* raise inexact if x != 0 */ - if(huge_f+x>0.0F) /* |x|<1, so return 0*sign(x) */ + GET_FLOAT_WORD(i0, x); + j0 = ((i0 >> 23) & 0xff) - 0x7f; + if (j0 < 23) { + if (j0 < 0) { /* raise inexact if x != 0 */ + if (huge_f + x > 0.0F) /* |x|<1, so return 0*sign(x) */ i0 &= 0x80000000; - } else { - i = (0x007fffff)>>j0; - if((i0&i)==0) return x; /* x is integral */ - if(huge_f+x>0.0F) /* raise inexact flag */ + } + else { + i = (0x007fffff) >> j0; + if ((i0 & i) == 0) + return x; /* x is integral */ + if (huge_f + x > 0.0F) /* raise inexact flag */ i0 &= (~i); } - } else { - if(j0==0x80) return x+x; /* inf or NaN */ - else return x; /* x is integral */ } - SET_FLOAT_WORD(x,i0); + else { + if (j0 == 0x80) + return x + x; /* inf or NaN */ + else + return x; /* x is integral */ + } + SET_FLOAT_WORD(x, i0); return x; } static float freebsd_rintf(float x) { - int32_t i0,j0,sx; - float w,t; - GET_FLOAT_WORD(i0,x); - sx = (i0>>31)&1; - j0 = ((i0>>23)&0xff)-0x7f; - if(j0<23) { - if(j0<0) { - if((i0&0x7fffffff)==0) return x; - STRICT_ASSIGN(float,w,TWO23[sx]+x); - t = w-TWO23[sx]; - GET_FLOAT_WORD(i0,t); - SET_FLOAT_WORD(t,(i0&0x7fffffff)|(sx<<31)); + int32_t i0, j0, sx; + float w, t; + GET_FLOAT_WORD(i0, x); + sx = (i0 >> 31) & 1; + j0 = ((i0 >> 23) & 0xff) - 0x7f; + if (j0 < 23) { + if (j0 < 0) { + if ((i0 & 0x7fffffff) == 0) + return x; + STRICT_ASSIGN(float, w, TWO23[sx] + x); + t = w - TWO23[sx]; + GET_FLOAT_WORD(i0, t); + SET_FLOAT_WORD(t, (i0 & 0x7fffffff) | (sx << 31)); return t; } - STRICT_ASSIGN(float,w,TWO23[sx]+x); - return w-TWO23[sx]; + STRICT_ASSIGN(float, w, TWO23[sx] + x); + return w - TWO23[sx]; } - if(j0==0x80) return x+x; /* inf or NaN */ - else return x; /* x is integral */ + if (j0 == 0x80) + return x + x; /* inf or NaN */ + else + return x; /* x is integral */ } static float freebsd_ceilf(float x) { - int32_t i0,j0; + int32_t i0, j0; u_int32_t i; - GET_FLOAT_WORD(i0,x); - j0 = ((i0>>23)&0xff)-0x7f; - if(j0<23) { - if(j0<0) { /* raise inexact if x != 0 */ - if(huge_f+x>(float)0.0) {/* return 0*sign(x) if |x|<1 */ - if(i0<0) {i0=0x80000000;} - else if(i0!=0) { i0=0x3f800000;} + GET_FLOAT_WORD(i0, x); + j0 = ((i0 >> 23) & 0xff) - 0x7f; + if (j0 < 23) { + if (j0 < 0) { /* raise inexact if x != 0 */ + if (huge_f + x > (float)0.0) { /* return 0*sign(x) if |x|<1 */ + if (i0 < 0) { + i0 = 0x80000000; + } + else if (i0 != 0) { + i0 = 0x3f800000; + } } - } else { - i = (0x007fffff)>>j0; - if((i0&i)==0) return x; /* x is integral */ - if(huge_f+x>(float)0.0) { /* raise inexact flag */ - if(i0>0) i0 += (0x00800000)>>j0; + } + else { + i = (0x007fffff) >> j0; + if ((i0 & i) == 0) + return x; /* x is integral */ + if (huge_f + x > (float)0.0) { /* raise inexact flag */ + if (i0 > 0) + i0 += (0x00800000) >> j0; i0 &= (~i); } } - } else { - if(j0==0x80) return x+x; /* inf or NaN */ - else return x; /* x is integral */ } - SET_FLOAT_WORD(x,i0); + else { + if (j0 == 0x80) + return x + x; /* inf or NaN */ + else + return x; /* x is integral */ + } + SET_FLOAT_WORD(x, i0); return x; } static float freebsd_floorf(float x) { - int32_t i0,j0; + int32_t i0, j0; u_int32_t i; - GET_FLOAT_WORD(i0,x); - j0 = ((i0>>23)&0xff)-0x7f; - if(j0<23) { - if(j0<0) { /* raise inexact if x != 0 */ - if(huge_f+x>(float)0.0) {/* return 0*sign(x) if |x|<1 */ - if(i0>=0) {i0=0;} - else if((i0&0x7fffffff)!=0) - { i0=0xbf800000;} + GET_FLOAT_WORD(i0, x); + j0 = ((i0 >> 23) & 0xff) - 0x7f; + if (j0 < 23) { + if (j0 < 0) { /* raise inexact if x != 0 */ + if (huge_f + x > (float)0.0) { /* return 0*sign(x) if |x|<1 */ + if (i0 >= 0) { + i0 = 0; + } + else if ((i0 & 0x7fffffff) != 0) { + i0 = 0xbf800000; + } } - } else { - i = (0x007fffff)>>j0; - if((i0&i)==0) return x; /* x is integral */ - if(huge_f+x>(float)0.0) { /* raise inexact flag */ - if(i0<0) i0 += (0x00800000)>>j0; + } + else { + i = (0x007fffff) >> j0; + if ((i0 & i) == 0) + return x; /* x is integral */ + if (huge_f + x > (float)0.0) { /* raise inexact flag */ + if (i0 < 0) + i0 += (0x00800000) >> j0; i0 &= (~i); } } - } else { - if(j0==0x80) return x+x; /* inf or NaN */ - else return x; /* x is integral */ } - SET_FLOAT_WORD(x,i0); + else { + if (j0 == 0x80) + return x + x; /* inf or NaN */ + else + return x; /* x is integral */ + } + SET_FLOAT_WORD(x, i0); return x; } @@ -1040,314 +1168,371 @@ freebsd_fmaxf(float x, float y) static double freebsd_copysign(double x, double y) { - u_int32_t hx,hy; - GET_HIGH_WORD(hx,x); - GET_HIGH_WORD(hy,y); - SET_HIGH_WORD(x,(hx&0x7fffffff)|(hy&0x80000000)); - return x; + u_int32_t hx, hy; + GET_HIGH_WORD(hx, x); + GET_HIGH_WORD(hy, y); + SET_HIGH_WORD(x, (hx & 0x7fffffff) | (hy & 0x80000000)); + return x; } static double freebsd_scalbn(double x, int n) { - int32_t k,hx,lx; - EXTRACT_WORDS(hx,lx,x); - k = (hx&0x7ff00000)>>20; /* extract exponent */ - if (k==0) { /* 0 or subnormal x */ - if ((lx|(hx&0x7fffffff))==0) return x; /* +-0 */ + int32_t k, hx, lx; + EXTRACT_WORDS(hx, lx, x); + k = (hx & 0x7ff00000) >> 20; /* extract exponent */ + if (k == 0) { /* 0 or subnormal x */ + if ((lx | (hx & 0x7fffffff)) == 0) + return x; /* +-0 */ x *= two54; - GET_HIGH_WORD(hx,x); - k = ((hx&0x7ff00000)>>20) - 54; - if (n< -50000) return tiny*x; /*underflow*/ + GET_HIGH_WORD(hx, x); + k = ((hx & 0x7ff00000) >> 20) - 54; + if (n < -50000) + return tiny * x; /*underflow*/ + } + if (k == 0x7ff) + return x + x; /* NaN or Inf */ + k = k + n; + if (k > 0x7fe) + return huge * freebsd_copysign(huge, x); /* overflow */ + if (k > 0) /* normal result */ + { + SET_HIGH_WORD(x, (hx & 0x800fffff) | (k << 20)); + return x; } - if (k==0x7ff) return x+x; /* NaN or Inf */ - k = k+n; - if (k > 0x7fe) return huge*freebsd_copysign(huge,x); /* overflow */ - if (k > 0) /* normal result */ - {SET_HIGH_WORD(x,(hx&0x800fffff)|(k<<20)); return x;} if (k <= -54) { - if (n > 50000) /* in case integer overflow in n+k */ - return huge*freebsd_copysign(huge,x); /*overflow*/ - else return tiny*freebsd_copysign(tiny,x); /*underflow*/ + if (n > 50000) /* in case integer overflow in n+k */ + return huge * freebsd_copysign(huge, x); /*overflow*/ + else + return tiny * freebsd_copysign(tiny, x); /*underflow*/ } - k += 54; /* subnormal result */ - SET_HIGH_WORD(x,(hx&0x800fffff)|(k<<20)); - return x*twom54; + k += 54; /* subnormal result */ + SET_HIGH_WORD(x, (hx & 0x800fffff) | (k << 20)); + return x * twom54; } static double freebsd_pow(double x, double y) { - double z,ax,z_h,z_l,p_h,p_l; - double y1,t1,t2,r,s,t,u,v,w; - int32_t i,j,k,yisint,n; - int32_t hx,hy,ix,iy; - u_int32_t lx,ly; + double z, ax, z_h, z_l, p_h, p_l; + double y1, t1, t2, r, s, t, u, v, w; + int32_t i, j, k, yisint, n; + int32_t hx, hy, ix, iy; + u_int32_t lx, ly; - EXTRACT_WORDS(hx,lx,x); - EXTRACT_WORDS(hy,ly,y); - ix = hx&0x7fffffff; iy = hy&0x7fffffff; + EXTRACT_WORDS(hx, lx, x); + EXTRACT_WORDS(hy, ly, y); + ix = hx & 0x7fffffff; + iy = hy & 0x7fffffff; /* y==zero: x**0 = 1 */ - if((iy|ly)==0) return one; + if ((iy | ly) == 0) + return one; /* x==1: 1**y = 1, even if y is NaN */ - if (hx==0x3ff00000 && lx == 0) return one; + if (hx == 0x3ff00000 && lx == 0) + return one; /* y!=zero: result is NaN if either arg is NaN */ - if(ix > 0x7ff00000 || ((ix==0x7ff00000)&&(lx!=0)) || - iy > 0x7ff00000 || ((iy==0x7ff00000)&&(ly!=0))) - return (x+0.0)+(y+0.0); + if (ix > 0x7ff00000 || ((ix == 0x7ff00000) && (lx != 0)) || iy > 0x7ff00000 + || ((iy == 0x7ff00000) && (ly != 0))) + return (x + 0.0) + (y + 0.0); /* determine if y is an odd int when x < 0 * yisint = 0 ... y is not an integer * yisint = 1 ... y is an odd int * yisint = 2 ... y is an even int */ - yisint = 0; - if(hx<0) { - if(iy>=0x43400000) yisint = 2; /* even integer y */ - else if(iy>=0x3ff00000) { - k = (iy>>20)-0x3ff; /* exponent */ - if(k>20) { - j = ly>>(52-k); - if((j<<(52-k))==ly) yisint = 2-(j&1); - } else if(ly==0) { - j = iy>>(20-k); - if((j<<(20-k))==iy) yisint = 2-(j&1); - } - } - } + yisint = 0; + if (hx < 0) { + if (iy >= 0x43400000) + yisint = 2; /* even integer y */ + else if (iy >= 0x3ff00000) { + k = (iy >> 20) - 0x3ff; /* exponent */ + if (k > 20) { + j = ly >> (52 - k); + if ((j << (52 - k)) == ly) + yisint = 2 - (j & 1); + } + else if (ly == 0) { + j = iy >> (20 - k); + if ((j << (20 - k)) == iy) + yisint = 2 - (j & 1); + } + } + } /* special value of y */ - if(ly==0) { - if (iy==0x7ff00000) { /* y is +-inf */ - if(((ix-0x3ff00000)|lx)==0) - return one; /* (-1)**+-inf is NaN */ - else if (ix >= 0x3ff00000)/* (|x|>1)**+-inf = inf,0 */ - return (hy>=0)? y: zero; - else /* (|x|<1)**-,+inf = inf,0 */ - return (hy<0)?-y: zero; - } - if(iy==0x3ff00000) { /* y is +-1 */ - if(hy<0) return one/x; else return x; - } - if(hy==0x40000000) return x*x; /* y is 2 */ - if(hy==0x40080000) return x*x*x; /* y is 3 */ - if(hy==0x40100000) { /* y is 4 */ - u = x*x; - return u*u; - } - if(hy==0x3fe00000) { /* y is 0.5 */ - if(hx>=0) /* x >= +0 */ - return sqrt(x); - } - } + if (ly == 0) { + if (iy == 0x7ff00000) { /* y is +-inf */ + if (((ix - 0x3ff00000) | lx) == 0) + return one; /* (-1)**+-inf is NaN */ + else if (ix >= 0x3ff00000) /* (|x|>1)**+-inf = inf,0 */ + return (hy >= 0) ? y : zero; + else /* (|x|<1)**-,+inf = inf,0 */ + return (hy < 0) ? -y : zero; + } + if (iy == 0x3ff00000) { /* y is +-1 */ + if (hy < 0) + return one / x; + else + return x; + } + if (hy == 0x40000000) + return x * x; /* y is 2 */ + if (hy == 0x40080000) + return x * x * x; /* y is 3 */ + if (hy == 0x40100000) { /* y is 4 */ + u = x * x; + return u * u; + } + if (hy == 0x3fe00000) { /* y is 0.5 */ + if (hx >= 0) /* x >= +0 */ + return sqrt(x); + } + } - ax = fabs(x); + ax = fabs(x); /* special value of x */ - if(lx==0) { - if(ix==0x7ff00000||ix==0||ix==0x3ff00000){ - z = ax; /*x is +-0,+-inf,+-1*/ - if(hy<0) z = one/z; /* z = (1/|x|) */ - if(hx<0) { - if(((ix-0x3ff00000)|yisint)==0) { - z = (z-z)/(z-z); /* (-1)**non-int is NaN */ - } else if(yisint==1) - z = -z; /* (x<0)**odd = -(|x|**odd) */ - } - return z; - } - } + if (lx == 0) { + if (ix == 0x7ff00000 || ix == 0 || ix == 0x3ff00000) { + z = ax; /*x is +-0,+-inf,+-1*/ + if (hy < 0) + z = one / z; /* z = (1/|x|) */ + if (hx < 0) { + if (((ix - 0x3ff00000) | yisint) == 0) { + z = (z - z) / (z - z); /* (-1)**non-int is NaN */ + } + else if (yisint == 1) + z = -z; /* (x<0)**odd = -(|x|**odd) */ + } + return z; + } + } /* CYGNUS LOCAL + fdlibm-5.3 fix: This used to be - n = (hx>>31)+1; + n = (hx>>31)+1; but ANSI C says a right shift of a signed negative quantity is implementation defined. */ - n = ((u_int32_t)hx>>31)-1; + n = ((u_int32_t)hx >> 31) - 1; /* (x<0)**(non-int) is NaN */ - if((n|yisint)==0) return (x-x)/(x-x); + if ((n | yisint) == 0) + return (x - x) / (x - x); - s = one; /* s (sign of result -ve**odd) = -1 else = 1 */ - if((n|(yisint-1))==0) s = -one;/* (-ve)**(odd int) */ + s = one; /* s (sign of result -ve**odd) = -1 else = 1 */ + if ((n | (yisint - 1)) == 0) + s = -one; /* (-ve)**(odd int) */ /* |y| is huge */ - if(iy>0x41e00000) { /* if |y| > 2**31 */ - if(iy>0x43f00000){ /* if |y| > 2**64, must o/uflow */ - if(ix<=0x3fefffff) return (hy<0)? huge*huge:tiny*tiny; - if(ix>=0x3ff00000) return (hy>0)? huge*huge:tiny*tiny; - } - /* over/underflow if x is not close to one */ - if(ix<0x3fefffff) return (hy<0)? s*huge*huge:s*tiny*tiny; - if(ix>0x3ff00000) return (hy>0)? s*huge*huge:s*tiny*tiny; - /* now |1-x| is tiny <= 2**-20, suffice to compute - log(x) by x-x^2/2+x^3/3-x^4/4 */ - t = ax-one; /* t has 20 trailing zeros */ - w = (t*t)*(0.5-t*(0.3333333333333333333333-t*0.25)); - u = ivln2_h*t; /* ivln2_h has 21 sig. bits */ - v = t*ivln2_l-w*ivln2; - t1 = u+v; - SET_LOW_WORD(t1,0); - t2 = v-(t1-u); - } else { - double ss,s2,s_h,s_l,t_h,t_l; - n = 0; - /* take care subnormal number */ - if(ix<0x00100000) - {ax *= two53; n -= 53; GET_HIGH_WORD(ix,ax); } - n += ((ix)>>20)-0x3ff; - j = ix&0x000fffff; - /* determine interval */ - ix = j|0x3ff00000; /* normalize ix */ - if(j<=0x3988E) k=0; /* |x|>1)|0x20000000)+0x00080000+(k<<18)); - t_l = ax - (t_h-bp[k]); - s_l = v*((u-s_h*t_h)-s_h*t_l); - /* compute log(ax) */ - s2 = ss*ss; - r = s2*s2*(L1+s2*(L2+s2*(L3+s2*(L4+s2*(L5+s2*L6))))); - r += s_l*(s_h+ss); - s2 = s_h*s_h; - t_h = 3.0+s2+r; - SET_LOW_WORD(t_h,0); - t_l = r-((t_h-3.0)-s2); - /* u+v = ss*(1+...) */ - u = s_h*t_h; - v = s_l*t_h+t_l*ss; - /* 2/(3log2)*(ss+...) */ - p_h = u+v; - SET_LOW_WORD(p_h,0); - p_l = v-(p_h-u); - z_h = cp_h*p_h; /* cp_h+cp_l = 2/(3*log2) */ - z_l = cp_l*p_h+p_l*cp+dp_l[k]; - /* log2(ax) = (ss+..)*2/(3*log2) = n + dp_h + z_h + z_l */ - t = (double)n; - t1 = (((z_h+z_l)+dp_h[k])+t); - SET_LOW_WORD(t1,0); - t2 = z_l-(((t1-t)-dp_h[k])-z_h); - } + if (iy > 0x41e00000) { /* if |y| > 2**31 */ + if (iy > 0x43f00000) { /* if |y| > 2**64, must o/uflow */ + if (ix <= 0x3fefffff) + return (hy < 0) ? huge * huge : tiny * tiny; + if (ix >= 0x3ff00000) + return (hy > 0) ? huge * huge : tiny * tiny; + } + /* over/underflow if x is not close to one */ + if (ix < 0x3fefffff) + return (hy < 0) ? s * huge * huge : s * tiny * tiny; + if (ix > 0x3ff00000) + return (hy > 0) ? s * huge * huge : s * tiny * tiny; + /* now |1-x| is tiny <= 2**-20, suffice to compute + log(x) by x-x^2/2+x^3/3-x^4/4 */ + t = ax - one; /* t has 20 trailing zeros */ + w = (t * t) * (0.5 - t * (0.3333333333333333333333 - t * 0.25)); + u = ivln2_h * t; /* ivln2_h has 21 sig. bits */ + v = t * ivln2_l - w * ivln2; + t1 = u + v; + SET_LOW_WORD(t1, 0); + t2 = v - (t1 - u); + } + else { + double ss, s2, s_h, s_l, t_h, t_l; + n = 0; + /* take care subnormal number */ + if (ix < 0x00100000) { + ax *= two53; + n -= 53; + GET_HIGH_WORD(ix, ax); + } + n += ((ix) >> 20) - 0x3ff; + j = ix & 0x000fffff; + /* determine interval */ + ix = j | 0x3ff00000; /* normalize ix */ + if (j <= 0x3988E) + k = 0; /* |x|> 1) | 0x20000000) + 0x00080000 + (k << 18)); + t_l = ax - (t_h - bp[k]); + s_l = v * ((u - s_h * t_h) - s_h * t_l); + /* compute log(ax) */ + s2 = ss * ss; + r = s2 * s2 + * (L1 + s2 * (L2 + s2 * (L3 + s2 * (L4 + s2 * (L5 + s2 * L6))))); + r += s_l * (s_h + ss); + s2 = s_h * s_h; + t_h = 3.0 + s2 + r; + SET_LOW_WORD(t_h, 0); + t_l = r - ((t_h - 3.0) - s2); + /* u+v = ss*(1+...) */ + u = s_h * t_h; + v = s_l * t_h + t_l * ss; + /* 2/(3log2)*(ss+...) */ + p_h = u + v; + SET_LOW_WORD(p_h, 0); + p_l = v - (p_h - u); + z_h = cp_h * p_h; /* cp_h+cp_l = 2/(3*log2) */ + z_l = cp_l * p_h + p_l * cp + dp_l[k]; + /* log2(ax) = (ss+..)*2/(3*log2) = n + dp_h + z_h + z_l */ + t = (double)n; + t1 = (((z_h + z_l) + dp_h[k]) + t); + SET_LOW_WORD(t1, 0); + t2 = z_l - (((t1 - t) - dp_h[k]) - z_h); + } /* split up y into y1+y2 and compute (y1+y2)*(t1+t2) */ - y1 = y; - SET_LOW_WORD(y1,0); - p_l = (y-y1)*t1+y*t2; - p_h = y1*t1; - z = p_l+p_h; - EXTRACT_WORDS(j,i,z); - if (j>=0x40900000) { /* z >= 1024 */ - if(((j-0x40900000)|i)!=0) /* if z > 1024 */ - return s*huge*huge; /* overflow */ - else { - if(p_l+ovt>z-p_h) return s*huge*huge; /* overflow */ - } - } else if((j&0x7fffffff)>=0x4090cc00 ) { /* z <= -1075 */ - if(((j-0xc090cc00)|i)!=0) /* z < -1075 */ - return s*tiny*tiny; /* underflow */ - else { - if(p_l<=z-p_h) return s*tiny*tiny; /* underflow */ - } - } + y1 = y; + SET_LOW_WORD(y1, 0); + p_l = (y - y1) * t1 + y * t2; + p_h = y1 * t1; + z = p_l + p_h; + EXTRACT_WORDS(j, i, z); + if (j >= 0x40900000) { /* z >= 1024 */ + if (((j - 0x40900000) | i) != 0) /* if z > 1024 */ + return s * huge * huge; /* overflow */ + else { + if (p_l + ovt > z - p_h) + return s * huge * huge; /* overflow */ + } + } + else if ((j & 0x7fffffff) >= 0x4090cc00) { /* z <= -1075 */ + if (((j - 0xc090cc00) | i) != 0) /* z < -1075 */ + return s * tiny * tiny; /* underflow */ + else { + if (p_l <= z - p_h) + return s * tiny * tiny; /* underflow */ + } + } /* * compute 2**(p_h+p_l) */ - i = j&0x7fffffff; - k = (i>>20)-0x3ff; - n = 0; - if(i>0x3fe00000) { /* if |z| > 0.5, set n = [z+0.5] */ - n = j+(0x00100000>>(k+1)); - k = ((n&0x7fffffff)>>20)-0x3ff; /* new k for n */ - t = zero; - SET_HIGH_WORD(t,n&~(0x000fffff>>k)); - n = ((n&0x000fffff)|0x00100000)>>(20-k); - if(j<0) n = -n; - p_h -= t; - } - t = p_l+p_h; - SET_LOW_WORD(t,0); - u = t*lg2_h; - v = (p_l-(t-p_h))*lg2+t*lg2_l; - z = u+v; - w = v-(z-u); - t = z*z; - t1 = z - t*(P1+t*(P2+t*(P3+t*(P4+t*P5)))); - r = (z*t1)/(t1-two)-(w+z*w); - z = one-(r-z); - GET_HIGH_WORD(j,z); - j += (n<<20); - if((j>>20)<=0) z = freebsd_scalbn(z,n); /* subnormal output */ - else SET_HIGH_WORD(z,j); - return s*z; + i = j & 0x7fffffff; + k = (i >> 20) - 0x3ff; + n = 0; + if (i > 0x3fe00000) { /* if |z| > 0.5, set n = [z+0.5] */ + n = j + (0x00100000 >> (k + 1)); + k = ((n & 0x7fffffff) >> 20) - 0x3ff; /* new k for n */ + t = zero; + SET_HIGH_WORD(t, n & ~(0x000fffff >> k)); + n = ((n & 0x000fffff) | 0x00100000) >> (20 - k); + if (j < 0) + n = -n; + p_h -= t; + } + t = p_l + p_h; + SET_LOW_WORD(t, 0); + u = t * lg2_h; + v = (p_l - (t - p_h)) * lg2 + t * lg2_l; + z = u + v; + w = v - (z - u); + t = z * z; + t1 = z - t * (P1 + t * (P2 + t * (P3 + t * (P4 + t * P5)))); + r = (z * t1) / (t1 - two) - (w + z * w); + z = one - (r - z); + GET_HIGH_WORD(j, z); + j += (n << 20); + if ((j >> 20) <= 0) + z = freebsd_scalbn(z, n); /* subnormal output */ + else + SET_HIGH_WORD(z, j); + return s * z; } -double atan(double x) +double +atan(double x) { return freebsd_atan(x); } -double atan2(double y, double x) +double +atan2(double y, double x) { return freebsd_atan2(y, x); } -double sqrt(double x) +double +sqrt(double x) { return freebsd_sqrt(x); } -double floor(double x) +double +floor(double x) { return freebsd_floor(x); } -double ceil(double x) +double +ceil(double x) { return freebsd_ceil(x); } -double fmin(double x, double y) +double +fmin(double x, double y) { return x < y ? x : y; } -double fmax(double x, double y) +double +fmax(double x, double y) { return x > y ? x : y; } -double rint(double x) +double +rint(double x) { return freebsd_rint(x); } -double fabs(double x) +double +fabs(double x) { return freebsd_fabs(x); } -int isnan(double x) +int +isnan(double x) { return freebsd_isnan(x); } -double trunc(double x) +double +trunc(double x) { return (x > 0) ? freebsd_floor(x) : freebsd_ceil(x); } -int signbit(double x) +int +signbit(double x) { return ((__HI(x) & 0x80000000) >> 31); } diff --git a/core/shared/platform/common/posix/posix_malloc.c b/core/shared/platform/common/posix/posix_malloc.c index e83fc7d7bd..660d1baae6 100644 --- a/core/shared/platform/common/posix/posix_malloc.c +++ b/core/shared/platform/common/posix/posix_malloc.c @@ -22,6 +22,3 @@ os_free(void *ptr) { free(ptr); } - - - diff --git a/core/shared/platform/common/posix/posix_memmap.c b/core/shared/platform/common/posix/posix_memmap.c index 15a4de8b65..72b51824e8 100644 --- a/core/shared/platform/common/posix/posix_memmap.c +++ b/core/shared/platform/common/posix/posix_memmap.c @@ -50,21 +50,19 @@ os_mmap(void *hint, size_t size, int prot, int flags) * (mmap's first argument) to meet the requirement. */ if (!hint && !(flags & MMAP_MAP_FIXED) && (flags & MMAP_MAP_32BIT)) { - uint8 *stack_addr = (uint8*)&map_prot; - uint8 *text_addr = (uint8*)os_mmap; + uint8 *stack_addr = (uint8 *)&map_prot; + uint8 *text_addr = (uint8 *)os_mmap; /* hint address begins with 1MB */ static uint8 *hint_addr = (uint8 *)(uintptr_t)BH_MB; - if ((hint_addr - text_addr >= 0 - && hint_addr - text_addr < 100 * BH_MB) + if ((hint_addr - text_addr >= 0 && hint_addr - text_addr < 100 * BH_MB) || (text_addr - hint_addr >= 0 && text_addr - hint_addr < 100 * BH_MB)) { /* hint address is possibly in text section, skip it */ hint_addr += 100 * BH_MB; } - if ((hint_addr - stack_addr >= 0 - && hint_addr - stack_addr < 8 * BH_MB) + if ((hint_addr - stack_addr >= 0 && hint_addr - stack_addr < 8 * BH_MB) || (stack_addr - hint_addr >= 0 && stack_addr - hint_addr < 8 * BH_MB)) { /* hint address is possibly in native stack area, skip it */ @@ -72,8 +70,7 @@ os_mmap(void *hint, size_t size, int prot, int flags) } /* try 10 times, step with 1MB each time */ - for (i = 0; - i < 10 && hint_addr < (uint8 *)(uintptr_t)(2ULL * BH_GB); + for (i = 0; i < 10 && hint_addr < (uint8 *)(uintptr_t)(2ULL * BH_GB); i++) { addr = mmap(hint_addr, request_size, map_prot, map_flags, -1, 0); if (addr != MAP_FAILED) { @@ -114,7 +111,7 @@ os_munmap(void *addr, size_t size) if (addr) { if (munmap(addr, request_size)) { - os_printf("os_munmap error addr:%p, size:0x%"PRIx64", errno:%d\n", + os_printf("os_munmap error addr:%p, size:0x%" PRIx64 ", errno:%d\n", addr, request_size, errno); } } @@ -144,5 +141,4 @@ os_mprotect(void *addr, size_t size, int prot) void os_dcache_flush(void) -{ -} +{} diff --git a/core/shared/platform/common/posix/posix_thread.c b/core/shared/platform/common/posix/posix_thread.c index 3da44a6904..1e7e4f3750 100644 --- a/core/shared/platform/common/posix/posix_thread.c +++ b/core/shared/platform/common/posix/posix_thread.c @@ -22,7 +22,8 @@ typedef struct { static os_thread_local_attribute os_signal_handler signal_handler; #endif -static void *os_thread_wrapper(void *arg) +static void * +os_thread_wrapper(void *arg) { thread_wrapper_arg *targ = arg; thread_start_routine_t start_func = targ->start; @@ -44,8 +45,9 @@ static void *os_thread_wrapper(void *arg) return NULL; } -int os_thread_create_with_prio(korp_tid *tid, thread_start_routine_t start, - void *arg, unsigned int stack_size, int prio) +int +os_thread_create_with_prio(korp_tid *tid, thread_start_routine_t start, + void *arg, unsigned int stack_size, int prio) { pthread_attr_t tattr; thread_wrapper_arg *targ; @@ -63,7 +65,7 @@ int os_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; @@ -85,24 +87,28 @@ int os_thread_create_with_prio(korp_tid *tid, thread_start_routine_t start, return BHT_OK; } -int os_thread_create(korp_tid *tid, thread_start_routine_t start, void *arg, - unsigned int stack_size) +int +os_thread_create(korp_tid *tid, thread_start_routine_t start, void *arg, + unsigned int stack_size) { return os_thread_create_with_prio(tid, start, arg, stack_size, BH_THREAD_DEFAULT_PRIORITY); } -korp_tid os_self_thread() +korp_tid +os_self_thread() { - return (korp_tid) pthread_self(); + return (korp_tid)pthread_self(); } -int os_mutex_init(korp_mutex *mutex) +int +os_mutex_init(korp_mutex *mutex) { return pthread_mutex_init(mutex, NULL) == 0 ? BHT_OK : BHT_ERROR; } -int os_recursive_mutex_init(korp_mutex *mutex) +int +os_recursive_mutex_init(korp_mutex *mutex) { int ret; @@ -120,7 +126,8 @@ int os_recursive_mutex_init(korp_mutex *mutex) return ret == 0 ? BHT_OK : BHT_ERROR; } -int os_mutex_destroy(korp_mutex *mutex) +int +os_mutex_destroy(korp_mutex *mutex) { int ret; @@ -130,7 +137,8 @@ int os_mutex_destroy(korp_mutex *mutex) return ret == 0 ? BHT_OK : BHT_ERROR; } -int os_mutex_lock(korp_mutex *mutex) +int +os_mutex_lock(korp_mutex *mutex) { int ret; @@ -140,7 +148,8 @@ int os_mutex_lock(korp_mutex *mutex) return ret == 0 ? BHT_OK : BHT_ERROR; } -int os_mutex_unlock(korp_mutex *mutex) +int +os_mutex_unlock(korp_mutex *mutex) { int ret; @@ -150,7 +159,8 @@ int os_mutex_unlock(korp_mutex *mutex) return ret == 0 ? BHT_OK : BHT_ERROR; } -int os_cond_init(korp_cond *cond) +int +os_cond_init(korp_cond *cond) { assert(cond); @@ -160,7 +170,8 @@ int os_cond_init(korp_cond *cond) return BHT_OK; } -int os_cond_destroy(korp_cond *cond) +int +os_cond_destroy(korp_cond *cond) { assert(cond); @@ -170,7 +181,8 @@ int os_cond_destroy(korp_cond *cond) return BHT_OK; } -int os_cond_wait(korp_cond *cond, korp_mutex *mutex) +int +os_cond_wait(korp_cond *cond, korp_mutex *mutex) { assert(cond); assert(mutex); @@ -181,7 +193,8 @@ int os_cond_wait(korp_cond *cond, korp_mutex *mutex) return BHT_OK; } -static void msec_nsec_to_abstime(struct timespec *ts, uint64 usec) +static void +msec_nsec_to_abstime(struct timespec *ts, uint64 usec) { struct timeval tv; time_t tv_sec_new; @@ -201,8 +214,7 @@ static void msec_nsec_to_abstime(struct timespec *ts, uint64 usec) } tv_nsec_new = (long int)(tv.tv_usec * 1000 + (usec % 1000000) * 1000); - if (tv.tv_usec * 1000 >= tv.tv_usec - && tv_nsec_new >= tv.tv_usec * 1000) { + if (tv.tv_usec * 1000 >= tv.tv_usec && tv_nsec_new >= tv.tv_usec * 1000) { ts->tv_nsec = tv_nsec_new; } else { @@ -218,7 +230,8 @@ static void msec_nsec_to_abstime(struct timespec *ts, uint64 usec) } } -int os_cond_reltimedwait(korp_cond *cond, korp_mutex *mutex, uint64 useconds) +int +os_cond_reltimedwait(korp_cond *cond, korp_mutex *mutex, uint64 useconds) { int ret; struct timespec abstime; @@ -236,7 +249,8 @@ int os_cond_reltimedwait(korp_cond *cond, korp_mutex *mutex, uint64 useconds) return ret; } -int os_cond_signal(korp_cond *cond) +int +os_cond_signal(korp_cond *cond) { assert(cond); @@ -246,17 +260,20 @@ int os_cond_signal(korp_cond *cond) return BHT_OK; } -int os_thread_join(korp_tid thread, void **value_ptr) +int +os_thread_join(korp_tid thread, void **value_ptr) { return pthread_join(thread, value_ptr); } -int os_thread_detach(korp_tid thread) +int +os_thread_detach(korp_tid thread) { return pthread_detach(thread); } -void os_thread_exit(void *retval) +void +os_thread_exit(void *retval) { #ifdef OS_ENABLE_HW_BOUND_CHECK os_thread_signal_destroy(); @@ -268,7 +285,8 @@ void os_thread_exit(void *retval) static os_thread_local_attribute uint8 *thread_stack_boundary = NULL; #endif -uint8 *os_thread_get_stack_boundary() +uint8 * +os_thread_get_stack_boundary() { pthread_t self; #ifdef __linux__ @@ -286,15 +304,15 @@ uint8 *os_thread_get_stack_boundary() page_size = getpagesize(); self = pthread_self(); - max_stack_size = (size_t)(APP_THREAD_STACK_SIZE_MAX + page_size - 1) - & ~(page_size - 1); + max_stack_size = + (size_t)(APP_THREAD_STACK_SIZE_MAX + page_size - 1) & ~(page_size - 1); if (max_stack_size < APP_THREAD_STACK_SIZE_DEFAULT) max_stack_size = APP_THREAD_STACK_SIZE_DEFAULT; #ifdef __linux__ if (pthread_getattr_np(self, &attr) == 0) { - pthread_attr_getstack(&attr, (void**)&addr, &stack_size); + pthread_attr_getstack(&attr, (void **)&addr, &stack_size); pthread_attr_getguardsize(&attr, &guard_size); pthread_attr_destroy(&attr); if (stack_size > max_stack_size) @@ -306,7 +324,7 @@ uint8 *os_thread_get_stack_boundary() } (void)stack_size; #elif defined(__APPLE__) || defined(__NuttX__) - if ((addr = (uint8*)pthread_get_stackaddr_np(self))) { + if ((addr = (uint8 *)pthread_get_stackaddr_np(self))) { stack_size = pthread_get_stacksize_np(self); if (stack_size > max_stack_size) addr -= max_stack_size; @@ -349,8 +367,7 @@ touch_pages(uint8 *stack_min_addr, uint32 page_size) { uint8 sum = 0; while (1) { - volatile uint8 *touch_addr = - (volatile uint8*)os_alloca(page_size / 2); + volatile uint8 *touch_addr = (volatile uint8 *)os_alloca(page_size / 2); if (touch_addr < stack_min_addr + page_size) { sum += *(stack_min_addr + page_size - 1); break; @@ -378,7 +395,8 @@ init_stack_guard_pages() (void)touch_pages(stack_min_addr, page_size); /* First time to call aot function, protect guard pages */ if (os_mprotect(stack_min_addr, page_size * guard_page_count, - MMAP_PROT_NONE) != 0) { + MMAP_PROT_NONE) + != 0) { return false; } return true; @@ -413,8 +431,7 @@ signal_callback(int sig_num, siginfo_t *sig_info, void *sig_ucontext) mask_signals(SIG_BLOCK); - if (signal_handler - && (sig_num == SIGSEGV || sig_num == SIGBUS)) { + if (signal_handler && (sig_num == SIGSEGV || sig_num == SIGBUS)) { signal_handler(sig_addr); } @@ -427,8 +444,7 @@ signal_callback(int sig_num, siginfo_t *sig_info, void *sig_ucontext) os_printf("unhandled SIGBUS, si_addr: %p\n", sig_addr); break; default: - os_printf("unhandle signal %d, si_addr: %p\n", - sig_num, sig_addr); + os_printf("unhandle signal %d, si_addr: %p\n", sig_num, sig_addr); break; } @@ -452,8 +468,7 @@ os_thread_signal_init(os_signal_handler handler) } /* Initialize memory for signal alternate stack of current thread */ - if (!(map_addr = os_mmap(NULL, map_size, - MMAP_PROT_READ | MMAP_PROT_WRITE, + if (!(map_addr = os_mmap(NULL, map_size, MMAP_PROT_READ | MMAP_PROT_WRITE, MMAP_MAP_NONE))) { os_printf("Failed to mmap memory for alternate stack\n"); goto fail1; @@ -533,7 +548,7 @@ void os_sigreturn() { #if defined(__APPLE__) - #define UC_RESET_ALT_STACK 0x80000000 +#define UC_RESET_ALT_STACK 0x80000000 extern int __sigreturn(void *, int); /* It's necessary to call __sigreturn to restore the sigaltstack state @@ -542,4 +557,3 @@ os_sigreturn() #endif } #endif /* end of OS_ENABLE_HW_BOUND_CHECK */ - diff --git a/core/shared/platform/common/posix/posix_time.c b/core/shared/platform/common/posix/posix_time.c index 744dd4cb13..bcf5ca3ce5 100644 --- a/core/shared/platform/common/posix/posix_time.c +++ b/core/shared/platform/common/posix/posix_time.c @@ -13,6 +13,5 @@ os_time_get_boot_microsecond() return 0; } - return ((uint64) ts.tv_sec) * 1000 * 1000 + ((uint64)ts.tv_nsec) / 1000; + return ((uint64)ts.tv_sec) * 1000 * 1000 + ((uint64)ts.tv_nsec) / 1000; } - diff --git a/core/shared/platform/darwin/platform_init.c b/core/shared/platform/darwin/platform_init.c index 17aeb8baab..2aae13fa14 100644 --- a/core/shared/platform/darwin/platform_init.c +++ b/core/shared/platform/darwin/platform_init.c @@ -13,8 +13,7 @@ bh_platform_init() void bh_platform_destroy() -{ -} +{} int os_printf(const char *format, ...) @@ -42,4 +41,3 @@ os_vprintf(const char *format, va_list ap) return BH_VPRINTF(format, ap); #endif } - diff --git a/core/shared/platform/darwin/platform_internal.h b/core/shared/platform/darwin/platform_internal.h index 3fa85a3078..77fdf0fdf7 100644 --- a/core/shared/platform/darwin/platform_internal.h +++ b/core/shared/platform/darwin/platform_internal.h @@ -60,10 +60,8 @@ typedef pthread_t korp_thread; #define os_thread_local_attribute __thread #if WASM_DISABLE_HW_BOUND_CHECK == 0 -#if defined(BUILD_TARGET_X86_64) \ - || defined(BUILD_TARGET_AMD_64) \ - || defined(BUILD_TARGET_AARCH64) \ - || defined(BUILD_TARGET_RISCV64_LP64D) \ +#if defined(BUILD_TARGET_X86_64) || defined(BUILD_TARGET_AMD_64) \ + || defined(BUILD_TARGET_AARCH64) || defined(BUILD_TARGET_RISCV64_LP64D) \ || defined(BUILD_TARGET_RISCV64_LP64) #include @@ -80,15 +78,20 @@ typedef jmp_buf korp_jmpbuf; typedef void (*os_signal_handler)(void *sig_addr); -int os_thread_signal_init(os_signal_handler handler); +int +os_thread_signal_init(os_signal_handler handler); -void os_thread_signal_destroy(); +void +os_thread_signal_destroy(); -bool os_thread_signal_inited(); +bool +os_thread_signal_inited(); -void os_signal_unmask(); +void +os_signal_unmask(); -void os_sigreturn(); +void +os_sigreturn(); #endif /* end of BUILD_TARGET_X86_64/AMD_64/AARCH64/RISCV64 */ #endif /* end of WASM_DISABLE_HW_BOUND_CHECK */ @@ -97,4 +100,3 @@ void os_sigreturn(); #endif #endif /* end of _PLATFORM_INTERNAL_H */ - diff --git a/core/shared/platform/esp-idf/espidf_platform.c b/core/shared/platform/esp-idf/espidf_platform.c index 7660ada431..1fd99b91fa 100644 --- a/core/shared/platform/esp-idf/espidf_platform.c +++ b/core/shared/platform/esp-idf/espidf_platform.c @@ -6,7 +6,6 @@ #include "platform_api_vmcore.h" #include "platform_api_extension.h" - int errno = 0; int @@ -27,7 +26,8 @@ bh_platform_destroy() os_thread_sys_destroy(); } -int os_printf(const char *format, ...) +int +os_printf(const char *format, ...) { int ret = 0; va_list ap; @@ -66,8 +66,7 @@ os_mprotect(void *addr, size_t size, int prot) void os_dcache_flush() -{ -} +{} int atoi(const char *nptr) @@ -112,11 +111,10 @@ memmove(void *dest, const void *src, size_t n) *d++ = *s++; } else { - const char *lasts = s + (n-1); - char *lastd = d + (n-1); + const char *lasts = s + (n - 1); + char *lastd = d + (n - 1); while (n--) *lastd-- = *lasts--; } return dest; } - diff --git a/core/shared/platform/esp-idf/espidf_thread.c b/core/shared/platform/esp-idf/espidf_thread.c index d5228dc2bb..f4bcbc711b 100644 --- a/core/shared/platform/esp-idf/espidf_thread.c +++ b/core/shared/platform/esp-idf/espidf_thread.c @@ -6,9 +6,9 @@ #include "platform_api_vmcore.h" #include "platform_api_extension.h" -uint8 *os_thread_get_stack_boundary() +uint8 * +os_thread_get_stack_boundary() { /* TODO: implement os_thread_get_stack_boundary */ return NULL; } - diff --git a/core/shared/platform/esp-idf/platform_internal.h b/core/shared/platform/esp-idf/platform_internal.h index 5703fa7891..09f269fc9a 100644 --- a/core/shared/platform/esp-idf/platform_internal.h +++ b/core/shared/platform/esp-idf/platform_internal.h @@ -45,9 +45,12 @@ typedef struct korp_cond { os_thread_wait_list thread_wait_list; } korp_cond; -int os_printf(const char *format, ...); -int os_vprintf(const char *format, va_list ap); +int +os_printf(const char *format, ...); +int +os_vprintf(const char *format, va_list ap); +/* clang-format off */ /* math functions which are not provided by os */ double sqrt(double x); double floor(double x); @@ -93,5 +96,6 @@ uint32_t htonl(uint32_t hostlong); uint16_t htons(uint16_t hostshort); uint32_t ntohl(uint32_t netlong); uint16_t ntohs(uint16_t netshort); +/* clang-format on */ #endif diff --git a/core/shared/platform/include/platform_api_extension.h b/core/shared/platform/include/platform_api_extension.h index 7b92824cc1..11eee8b162 100644 --- a/core/shared/platform/include/platform_api_extension.h +++ b/core/shared/platform/include/platform_api_extension.h @@ -30,7 +30,6 @@ extern "C" { * 2. To build the app-mgr and app-framework, you must implement it */ - /** * Ceates a thread * @@ -41,8 +40,9 @@ extern "C" { * * @return 0 if success. */ -int os_thread_create(korp_tid *p_tid, thread_start_routine_t start, void *arg, - unsigned int stack_size); +int +os_thread_create(korp_tid *p_tid, thread_start_routine_t start, void *arg, + unsigned int stack_size); /** * Creates a thread with priority @@ -55,8 +55,9 @@ int os_thread_create(korp_tid *p_tid, thread_start_routine_t start, void *arg, * * @return 0 if success. */ -int os_thread_create_with_prio(korp_tid *p_tid, thread_start_routine_t start, - void *arg, unsigned int stack_size, int prio); +int +os_thread_create_with_prio(korp_tid *p_tid, thread_start_routine_t start, + void *arg, unsigned int stack_size, int prio); /** * Waits for the thread specified by thread to terminate @@ -66,7 +67,8 @@ int os_thread_create_with_prio(korp_tid *p_tid, thread_start_routine_t start, * * @return return 0 if success */ -int os_thread_join(korp_tid thread, void **retval); +int +os_thread_join(korp_tid thread, void **retval); /** * Detach the thread specified by thread @@ -82,7 +84,8 @@ int os_thread_detach(korp_tid); * * @param retval the return value of the current thread */ -void os_thread_exit(void *retval); +void +os_thread_exit(void *retval); /** * Initialize current thread environment if current thread @@ -90,12 +93,14 @@ void os_thread_exit(void *retval); * * @return 0 if success, -1 otherwise */ -int os_thread_env_init(); +int +os_thread_env_init(); /** * Destroy current thread environment */ -void os_thread_env_destroy(); +void +os_thread_env_destroy(); /** * Suspend execution of the calling thread for (at least) @@ -103,7 +108,8 @@ void os_thread_env_destroy(); * * @return 0 if success, -1 otherwise */ -int os_usleep(uint32 usec); +int +os_usleep(uint32 usec); /** * Creates a recursive mutex @@ -112,7 +118,8 @@ int os_usleep(uint32 usec); * * @return 0 if success */ -int os_recursive_mutex_init(korp_mutex *mutex); +int +os_recursive_mutex_init(korp_mutex *mutex); /** * This function creates a condition variable @@ -121,7 +128,8 @@ int os_recursive_mutex_init(korp_mutex *mutex); * * @return 0 if success */ -int os_cond_init(korp_cond *cond); +int +os_cond_init(korp_cond *cond); /** * This function destroys condition variable @@ -130,7 +138,8 @@ int os_cond_init(korp_cond *cond); * * @return 0 if success */ -int os_cond_destroy(korp_cond *cond); +int +os_cond_destroy(korp_cond *cond); /** * Wait a condition variable. @@ -140,7 +149,8 @@ int os_cond_destroy(korp_cond *cond); * * @return 0 if success */ -int os_cond_wait(korp_cond *cond, korp_mutex *mutex); +int +os_cond_wait(korp_cond *cond, korp_mutex *mutex); /** * Wait a condition varible or return if time specified passes. @@ -151,7 +161,8 @@ int os_cond_wait(korp_cond *cond, korp_mutex *mutex); * * @return 0 if success */ -int os_cond_reltimedwait(korp_cond *cond, korp_mutex *mutex, uint64 useconds); +int +os_cond_reltimedwait(korp_cond *cond, korp_mutex *mutex, uint64 useconds); /** * Signals the condition variable @@ -160,7 +171,8 @@ int os_cond_reltimedwait(korp_cond *cond, korp_mutex *mutex, uint64 useconds); * * @return 0 if success */ -int os_cond_signal(korp_cond *cond); +int +os_cond_signal(korp_cond *cond); #ifdef __cplusplus } diff --git a/core/shared/platform/include/platform_api_vmcore.h b/core/shared/platform/include/platform_api_vmcore.h index 0f162fc039..c2f03c9e50 100644 --- a/core/shared/platform/include/platform_api_vmcore.h +++ b/core/shared/platform/include/platform_api_vmcore.h @@ -25,23 +25,28 @@ extern "C" { * * @return 0 if success */ -int bh_platform_init(void); +int +bh_platform_init(void); /** * Destroy the platform internal resources if needed, * this function is called by wasm_runtime_destroy() */ -void bh_platform_destroy(void); +void +bh_platform_destroy(void); /** ******** memory allocator APIs ********** */ -void *os_malloc(unsigned size); +void * +os_malloc(unsigned size); -void *os_realloc(void *ptr, unsigned size); +void * +os_realloc(void *ptr, unsigned size); -void os_free(void *ptr); +void +os_free(void *ptr); /** * Note: the above APIs can simply return NULL if wasm runtime @@ -49,28 +54,32 @@ void os_free(void *ptr); * Refer to wasm_runtime_full_init(). */ +int +os_printf(const char *format, ...); -int os_printf(const char *format, ...); - -int os_vprintf(const char *format, va_list ap); +int +os_vprintf(const char *format, va_list ap); /** * Get microseconds after boot. */ -uint64 os_time_get_boot_microsecond(void); +uint64 +os_time_get_boot_microsecond(void); /** * Get current thread id. * Implementation optional: Used by runtime for logging only. */ -korp_tid os_self_thread(void); +korp_tid +os_self_thread(void); /** * Get current thread's stack boundary address, used for runtime * to check the native stack overflow. Return NULL if it is not * easy to implement, but may have potential issue. */ -uint8 *os_thread_get_stack_boundary(void); +uint8 * +os_thread_get_stack_boundary(void); /** ************** mutext APIs *********** @@ -78,14 +87,17 @@ uint8 *os_thread_get_stack_boundary(void); * app-mgr: Must be implemented */ -int os_mutex_init(korp_mutex *mutex); - -int os_mutex_destroy(korp_mutex *mutex); +int +os_mutex_init(korp_mutex *mutex); -int os_mutex_lock(korp_mutex *mutex); +int +os_mutex_destroy(korp_mutex *mutex); -int os_mutex_unlock(korp_mutex *mutex); +int +os_mutex_lock(korp_mutex *mutex); +int +os_mutex_unlock(korp_mutex *mutex); /************************************************** * Section 2 * @@ -110,9 +122,12 @@ enum { MMAP_MAP_FIXED = 2 }; -void *os_mmap(void *hint, size_t size, int prot, int flags); -void os_munmap(void *addr, size_t size); -int os_mprotect(void *addr, size_t size, int prot); +void * +os_mmap(void *hint, size_t size, int prot, int flags); +void +os_munmap(void *addr, size_t size); +int +os_mprotect(void *addr, size_t size, int prot); /** * Flush cpu data cache, in some CPUs, after applying relocation to the @@ -120,7 +135,8 @@ int os_mprotect(void *addr, size_t size, int prot); * which may cause unexpected behaviour when executing the AOT code. * Implement this function if required, or just leave it empty. */ -void os_dcache_flush(void); +void +os_dcache_flush(void); #ifdef __cplusplus } diff --git a/core/shared/platform/include/platform_common.h b/core/shared/platform/include/platform_common.h index 92418f8120..57629654fd 100644 --- a/core/shared/platform/include/platform_common.h +++ b/core/shared/platform/include/platform_common.h @@ -42,24 +42,27 @@ extern "C" { __declspec(dllexport) void *BH_MALLOC(unsigned int size); __declspec(dllexport) void BH_FREE(void *ptr); #else -__declspec(dllimport) void* BH_MALLOC(unsigned int size); -__declspec(dllimport) void BH_FREE(void* ptr); +__declspec(dllimport) void *BH_MALLOC(unsigned int size); +__declspec(dllimport) void BH_FREE(void *ptr); #endif #else -void *BH_MALLOC(unsigned int size); -void BH_FREE(void *ptr); +void * +BH_MALLOC(unsigned int size); +void +BH_FREE(void *ptr); #endif #if defined(BH_VPRINTF) #if defined(MSVC) __declspec(dllimport) int BH_VPRINTF(const char *format, va_list ap); #else -int BH_VPRINTF(const char *format, va_list ap); +int +BH_VPRINTF(const char *format, va_list ap); #endif #endif #ifndef NULL -#define NULL (void*)0 +#define NULL (void *)0 #endif #ifndef __cplusplus @@ -99,8 +102,7 @@ typedef double float64; typedef uint64_t uint64; typedef int64_t int64; -typedef void* (*thread_start_routine_t)(void*); - +typedef void *(*thread_start_routine_t)(void *); #ifdef __cplusplus } diff --git a/core/shared/platform/linux-sgx/platform_internal.h b/core/shared/platform/linux-sgx/platform_internal.h index 65b40872e9..4ce7ee3563 100644 --- a/core/shared/platform/linux-sgx/platform_internal.h +++ b/core/shared/platform/linux-sgx/platform_internal.h @@ -40,7 +40,7 @@ extern "C" { #define _STACK_SIZE_ADJUSTMENT (32 * 1024) /* Stack size of applet threads's native part. */ -#define BH_APPLET_PRESERVED_STACK_SIZE (8 * 1024 + _STACK_SIZE_ADJUSTMENT) +#define BH_APPLET_PRESERVED_STACK_SIZE (8 * 1024 + _STACK_SIZE_ADJUSTMENT) /* Default thread priority */ #define BH_THREAD_DEFAULT_PRIORITY 0 @@ -50,14 +50,15 @@ typedef pthread_t korp_tid; typedef pthread_mutex_t korp_mutex; typedef pthread_cond_t korp_cond; -typedef void (*os_print_function_t)(const char* message); -void os_set_print_function(os_print_function_t pf); +typedef void (*os_print_function_t)(const char *message); +void +os_set_print_function(os_print_function_t pf); -char *strcpy(char *dest, const char *src); +char * +strcpy(char *dest, const char *src); #ifdef __cplusplus } #endif #endif /* end of _PLATFORM_INTERNAL_H */ - diff --git a/core/shared/platform/linux-sgx/sgx_file.c b/core/shared/platform/linux-sgx/sgx_file.c index 4e21b8b42f..240c4a780c 100644 --- a/core/shared/platform/linux-sgx/sgx_file.c +++ b/core/shared/platform/linux-sgx/sgx_file.c @@ -13,97 +13,129 @@ #define TRACE_OCALL_FAIL() os_printf("ocall %s failed!\n", __FUNCTION__) /** fd **/ -int ocall_open(int *p_fd, const char *pathname, int flags, - bool has_mode, unsigned mode); +int +ocall_open(int *p_fd, const char *pathname, int flags, bool has_mode, + unsigned mode); -int ocall_openat(int *p_fd, int dirfd, const char *pathname, int flags, - bool has_mode, unsigned mode); +int +ocall_openat(int *p_fd, int dirfd, const char *pathname, int flags, + bool has_mode, unsigned mode); -int ocall_read(ssize_t *p_ret, int fd, void *buf, size_t read_size); +int +ocall_read(ssize_t *p_ret, int fd, void *buf, size_t read_size); -int ocall_close(int *p_ret, int fd); +int +ocall_close(int *p_ret, int fd); -int ocall_lseek(off_t *p_ret, int fd, off_t offset, int whence); +int +ocall_lseek(off_t *p_ret, int fd, off_t offset, int whence); -int ocall_ftruncate(int *p_ret, int fd, off_t length); +int +ocall_ftruncate(int *p_ret, int fd, off_t length); -int ocall_fsync(int *p_ret, int fd); +int +ocall_fsync(int *p_ret, int fd); -int ocall_fdatasync(int *p_ret, int fd); +int +ocall_fdatasync(int *p_ret, int fd); -int ocall_isatty(int *p_ret, int fd); +int +ocall_isatty(int *p_ret, int fd); /** fd end **/ /** DIR **/ -int ocall_fdopendir(int fd, void **p_dirp); +int +ocall_fdopendir(int fd, void **p_dirp); -int ocall_readdir(void **p_dirent, void *dirp); +int +ocall_readdir(void **p_dirent, void *dirp); -int ocall_rewinddir(void *dirp); +int +ocall_rewinddir(void *dirp); -int ocall_seekdir(void *dirp, long loc); +int +ocall_seekdir(void *dirp, long loc); -int ocall_telldir(long *p_dir, void *dirp); +int +ocall_telldir(long *p_dir, void *dirp); -int ocall_closedir(int *p_ret, void *dirp); +int +ocall_closedir(int *p_ret, void *dirp); /** DIR end **/ /** stat **/ -int ocall_stat(int *p_ret, const char *pathname, - void *buf, unsigned int buf_len); -int ocall_fstat(int *p_ret, int fd, void *buf, unsigned int buf_len); -int ocall_fstatat(int *p_ret, int dirfd, const char *pathname, - void *buf, unsigned int buf_len, int flags); +int +ocall_stat(int *p_ret, const char *pathname, void *buf, unsigned int buf_len); +int +ocall_fstat(int *p_ret, int fd, void *buf, unsigned int buf_len); +int +ocall_fstatat(int *p_ret, int dirfd, const char *pathname, void *buf, + unsigned int buf_len, int flags); /** stat end **/ /** link **/ -int ocall_mkdirat(int *p_ret, int dirfd, const char * pathname, - unsigned mode); -int ocall_link(int *p_ret, const char *oldpath, const char *newpath); -int ocall_linkat(int *p_ret, int olddirfd, const char *oldpath, - int newdirfd, const char *newpath, int flags); -int ocall_unlinkat(int *p_ret, int dirfd, const char *pathname, - int flags); -int ocall_readlinkat(ssize_t *p_ret, int dirfd, const char *pathname, - char *buf, size_t bufsiz); -int ocall_renameat(int *p_ret, int olddirfd,const char *oldpath, - int newdirfd,const char *newpath); -int ocall_symlinkat(int *p_ret, const char *target, int newdirfd, - const char *linkpath); +int +ocall_mkdirat(int *p_ret, int dirfd, const char *pathname, unsigned mode); +int +ocall_link(int *p_ret, const char *oldpath, const char *newpath); +int +ocall_linkat(int *p_ret, int olddirfd, const char *oldpath, int newdirfd, + const char *newpath, int flags); +int +ocall_unlinkat(int *p_ret, int dirfd, const char *pathname, int flags); +int +ocall_readlinkat(ssize_t *p_ret, int dirfd, const char *pathname, char *buf, + size_t bufsiz); +int +ocall_renameat(int *p_ret, int olddirfd, const char *oldpath, int newdirfd, + const char *newpath); +int +ocall_symlinkat(int *p_ret, const char *target, int newdirfd, + const char *linkpath); /** link end **/ /** control **/ -int ocall_ioctl(int *p_ret, int fd, unsigned long request, void *arg, - unsigned int arg_len); -int ocall_fcntl(int *p_ret, int fd, int cmd); -int ocall_fcntl_long(int *p_ret, int fd, int cmd, long arg); +int +ocall_ioctl(int *p_ret, int fd, unsigned long request, void *arg, + unsigned int arg_len); +int +ocall_fcntl(int *p_ret, int fd, int cmd); +int +ocall_fcntl_long(int *p_ret, int fd, int cmd, long arg); /** control end **/ /** **/ -int ocall_realpath(int *p_ret, const char *path, char *buf, - unsigned int buf_len); -int ocall_posix_fallocate(int *p_ret, int fd, off_t offset, off_t len); -int ocall_poll(int *p_ret, void *fds, unsigned nfds, int timeout, - unsigned int fds_len); -int ocall_getopt(int *p_ret, int argc, char *argv_buf, - unsigned int argv_buf_len, const char *optstring); -int ocall_getrandom(ssize_t *p_ret, void *buf, size_t buflen, - unsigned int flags); -int ocall_getentropy(int *p_ret, void *buffer, size_t length); -int ocall_sched_yield(int *p_ret); +int +ocall_realpath(int *p_ret, const char *path, char *buf, unsigned int buf_len); +int +ocall_posix_fallocate(int *p_ret, int fd, off_t offset, off_t len); +int +ocall_poll(int *p_ret, void *fds, unsigned nfds, int timeout, + unsigned int fds_len); +int +ocall_getopt(int *p_ret, int argc, char *argv_buf, unsigned int argv_buf_len, + const char *optstring); +int +ocall_getrandom(ssize_t *p_ret, void *buf, size_t buflen, unsigned int flags); +int +ocall_getentropy(int *p_ret, void *buffer, size_t length); +int +ocall_sched_yield(int *p_ret); /** struct iovec **/ -ssize_t ocall_readv(ssize_t *p_ret, int fd, char *iov_buf, - unsigned int buf_size, int iovcnt, - bool has_offset, off_t offset); -ssize_t ocall_writev(ssize_t *p_ret, int fd, char *iov_buf, - unsigned int buf_size, int iovcnt, - bool has_offset, off_t offset); +ssize_t +ocall_readv(ssize_t *p_ret, int fd, char *iov_buf, unsigned int buf_size, + int iovcnt, bool has_offset, off_t offset); +ssize_t +ocall_writev(ssize_t *p_ret, int fd, char *iov_buf, unsigned int buf_size, + int iovcnt, bool has_offset, off_t offset); /** iovec end **/ -int ocall_get_errno(int *p_ret); +int +ocall_get_errno(int *p_ret); -int open(const char *pathname, int flags, ...) +int +open(const char *pathname, int flags, ...) { int fd; bool has_mode = false; @@ -130,7 +162,8 @@ int open(const char *pathname, int flags, ...) return fd; } -int openat(int dirfd, const char *pathname, int flags, ...) +int +openat(int dirfd, const char *pathname, int flags, ...) { int fd; bool has_mode = false; @@ -144,8 +177,8 @@ int openat(int dirfd, const char *pathname, int flags, ...) has_mode = true; } - if (SGX_SUCCESS != ocall_openat(&fd, dirfd, pathname, flags, - has_mode, mode)) { + if (SGX_SUCCESS + != ocall_openat(&fd, dirfd, pathname, flags, has_mode, mode)) { TRACE_OCALL_FAIL(); return -1; } @@ -158,7 +191,8 @@ int openat(int dirfd, const char *pathname, int flags, ...) return fd; } -int close(int fd) +int +close(int fd) { int ret; @@ -171,7 +205,8 @@ int close(int fd) return ret; } -ssize_t read(int fd, void *buf, size_t size) +ssize_t +read(int fd, void *buf, size_t size) { ssize_t ret; int size_read_max = 2048, size_read, total_size_read = 0, count, i; @@ -184,9 +219,7 @@ ssize_t read(int fd, void *buf, size_t size) count = (size + size_read_max - 1) / size_read_max; for (i = 0; i < count; i++) { - size_read = (i < count - 1) - ? size_read_max - : size - size_read_max * i; + size_read = (i < count - 1) ? size_read_max : size - size_read_max * i; if (ocall_read(&ret, fd, p, size_read) != SGX_SUCCESS) { TRACE_OCALL_FAIL(); @@ -208,7 +241,8 @@ ssize_t read(int fd, void *buf, size_t size) return total_size_read; } -DIR *fdopendir(int fd) +DIR * +fdopendir(int fd) { DIR *result = NULL; @@ -232,7 +266,8 @@ DIR *fdopendir(int fd) return result; } -struct dirent *readdir(DIR *dirp) +struct dirent * +readdir(DIR *dirp) { struct dirent *result; @@ -249,21 +284,24 @@ struct dirent *readdir(DIR *dirp) return result; } -void rewinddir(DIR *dirp) +void +rewinddir(DIR *dirp) { if (ocall_rewinddir((void *)*dirp) != SGX_SUCCESS) { TRACE_OCALL_FAIL(); } } -void seekdir(DIR *dirp, long loc) +void +seekdir(DIR *dirp, long loc) { if (ocall_seekdir((void *)*dirp, loc) != SGX_SUCCESS) { TRACE_OCALL_FAIL(); } } -long telldir(DIR *dirp) +long +telldir(DIR *dirp) { long ret; @@ -276,7 +314,8 @@ long telldir(DIR *dirp) return ret; } -int closedir(DIR *dirp) +int +closedir(DIR *dirp) { int ret; @@ -291,8 +330,8 @@ int closedir(DIR *dirp) } static ssize_t -readv_internal(int fd, const struct iovec *iov, int iovcnt, - bool has_offset, off_t offset) +readv_internal(int fd, const struct iovec *iov, int iovcnt, bool has_offset, + off_t offset) { ssize_t ret, size_left; struct iovec *iov1; @@ -317,7 +356,7 @@ readv_internal(int fd, const struct iovec *iov, int iovcnt, memset(iov1, 0, (uint32)total_size); - p = (char*)(uintptr_t)(sizeof(struct iovec) * iovcnt); + p = (char *)(uintptr_t)(sizeof(struct iovec) * iovcnt); for (i = 0; i < iovcnt; i++) { iov1[i].iov_len = iov[i].iov_len; @@ -325,8 +364,9 @@ readv_internal(int fd, const struct iovec *iov, int iovcnt, p += iov[i].iov_len; } - if (ocall_readv(&ret, fd, (char *)iov1, (uint32)total_size, - iovcnt, has_offset, offset) != SGX_SUCCESS) { + if (ocall_readv(&ret, fd, (char *)iov1, (uint32)total_size, iovcnt, + has_offset, offset) + != SGX_SUCCESS) { TRACE_OCALL_FAIL(); BH_FREE(iov1); return -1; @@ -343,8 +383,7 @@ readv_internal(int fd, const struct iovec *iov, int iovcnt, size_left -= iov[i].iov_len; } else { - memcpy(iov[i].iov_base, (uintptr_t)p + (char *)iov1, - size_left); + memcpy(iov[i].iov_base, (uintptr_t)p + (char *)iov1, size_left); break; } } @@ -356,8 +395,8 @@ readv_internal(int fd, const struct iovec *iov, int iovcnt, } static ssize_t -writev_internal(int fd, const struct iovec *iov, int iovcnt, - bool has_offset, off_t offset) +writev_internal(int fd, const struct iovec *iov, int iovcnt, bool has_offset, + off_t offset) { ssize_t ret; struct iovec *iov1; @@ -387,13 +426,13 @@ writev_internal(int fd, const struct iovec *iov, int iovcnt, for (i = 0; i < iovcnt; i++) { iov1[i].iov_len = iov[i].iov_len; iov1[i].iov_base = p; - memcpy((uintptr_t)p + (char *)iov1, iov[i].iov_base, - iov[i].iov_len); + memcpy((uintptr_t)p + (char *)iov1, iov[i].iov_base, iov[i].iov_len); p += iov[i].iov_len; } - if (ocall_writev(&ret, fd, (char *)iov1, (uint32)total_size, - iovcnt, has_offset, offset) != SGX_SUCCESS) { + if (ocall_writev(&ret, fd, (char *)iov1, (uint32)total_size, iovcnt, + has_offset, offset) + != SGX_SUCCESS) { TRACE_OCALL_FAIL(); BH_FREE(iov1); return -1; @@ -405,29 +444,32 @@ writev_internal(int fd, const struct iovec *iov, int iovcnt, return ret; } -ssize_t readv(int fd, const struct iovec *iov, int iovcnt) +ssize_t +readv(int fd, const struct iovec *iov, int iovcnt) { return readv_internal(fd, iov, iovcnt, false, 0); } -ssize_t writev(int fd, const struct iovec *iov, int iovcnt) +ssize_t +writev(int fd, const struct iovec *iov, int iovcnt) { return writev_internal(fd, iov, iovcnt, false, 0); } -ssize_t preadv(int fd, const struct iovec *iov, int iovcnt, - off_t offset) +ssize_t +preadv(int fd, const struct iovec *iov, int iovcnt, off_t offset) { return readv_internal(fd, iov, iovcnt, true, offset); } -ssize_t pwritev(int fd, const struct iovec *iov, int iovcnt, - off_t offset) +ssize_t +pwritev(int fd, const struct iovec *iov, int iovcnt, off_t offset) { return writev_internal(fd, iov, iovcnt, true, offset); } -off_t lseek(int fd, off_t offset, int whence) +off_t +lseek(int fd, off_t offset, int whence) { off_t ret; if (ocall_lseek(&ret, fd, (long)offset, whence) != SGX_SUCCESS) { @@ -439,7 +481,8 @@ off_t lseek(int fd, off_t offset, int whence) return ret; } -int ftruncate(int fd, off_t length) +int +ftruncate(int fd, off_t length) { int ret; @@ -452,16 +495,16 @@ int ftruncate(int fd, off_t length) return ret; } -int stat(const char *pathname, struct stat *statbuf) +int +stat(const char *pathname, struct stat *statbuf) { int ret; if (statbuf == NULL) return -1; - if (ocall_stat(&ret, pathname, - (void *)statbuf, - sizeof(struct stat)) != SGX_SUCCESS) { + if (ocall_stat(&ret, pathname, (void *)statbuf, sizeof(struct stat)) + != SGX_SUCCESS) { TRACE_OCALL_FAIL(); return -1; } @@ -471,15 +514,16 @@ int stat(const char *pathname, struct stat *statbuf) return ret; } -int fstat(int fd, struct stat *statbuf) +int +fstat(int fd, struct stat *statbuf) { int ret; if (statbuf == NULL) return -1; - if (ocall_fstat(&ret, fd, (void *)statbuf, - sizeof(struct stat)) != SGX_SUCCESS) { + if (ocall_fstat(&ret, fd, (void *)statbuf, sizeof(struct stat)) + != SGX_SUCCESS) { TRACE_OCALL_FAIL(); return -1; } @@ -489,8 +533,8 @@ int fstat(int fd, struct stat *statbuf) return ret; } -int fstatat(int dirfd, const char *pathname, struct stat *statbuf, - int flags) +int +fstatat(int dirfd, const char *pathname, struct stat *statbuf, int flags) { int ret; @@ -498,7 +542,8 @@ int fstatat(int dirfd, const char *pathname, struct stat *statbuf, return -1; if (ocall_fstatat(&ret, dirfd, pathname, (void *)statbuf, - sizeof(struct stat), flags) != SGX_SUCCESS) { + sizeof(struct stat), flags) + != SGX_SUCCESS) { TRACE_OCALL_FAIL(); return -1; } @@ -508,7 +553,8 @@ int fstatat(int dirfd, const char *pathname, struct stat *statbuf, return ret; } -int fsync(int fd) +int +fsync(int fd) { int ret; @@ -521,7 +567,8 @@ int fsync(int fd) return ret; } -int fdatasync(int fd) +int +fdatasync(int fd) { int ret; @@ -534,7 +581,8 @@ int fdatasync(int fd) return ret; } -int mkdirat(int dirfd, const char *pathname, mode_t mode) +int +mkdirat(int dirfd, const char *pathname, mode_t mode) { int ret; @@ -548,7 +596,8 @@ int mkdirat(int dirfd, const char *pathname, mode_t mode) return ret; } -int link(const char *oldpath, const char *newpath) +int +link(const char *oldpath, const char *newpath) { int ret; @@ -562,13 +611,14 @@ int link(const char *oldpath, const char *newpath) return ret; } -int linkat(int olddirfd, const char *oldpath, - int newdirfd, const char *newpath, int flags) +int +linkat(int olddirfd, const char *oldpath, int newdirfd, const char *newpath, + int flags) { int ret; - if (ocall_linkat(&ret, olddirfd, oldpath, newdirfd, newpath, - flags) != SGX_SUCCESS) { + if (ocall_linkat(&ret, olddirfd, oldpath, newdirfd, newpath, flags) + != SGX_SUCCESS) { TRACE_OCALL_FAIL(); return -1; } @@ -578,7 +628,8 @@ int linkat(int olddirfd, const char *oldpath, return ret; } -int unlinkat(int dirfd, const char *pathname, int flags) +int +unlinkat(int dirfd, const char *pathname, int flags) { int ret; @@ -592,16 +643,15 @@ int unlinkat(int dirfd, const char *pathname, int flags) return ret; } -ssize_t readlinkat(int dirfd, const char *pathname, - char *buf, size_t bufsiz) +ssize_t +readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz) { ssize_t ret; if (buf == NULL) return -1; - if (ocall_readlinkat(&ret, dirfd, pathname, buf, - bufsiz) != SGX_SUCCESS) { + if (ocall_readlinkat(&ret, dirfd, pathname, buf, bufsiz) != SGX_SUCCESS) { TRACE_OCALL_FAIL(); return -1; } @@ -611,12 +661,12 @@ ssize_t readlinkat(int dirfd, const char *pathname, return ret; } -int symlinkat(const char *target, int newdirfd, const char *linkpath) +int +symlinkat(const char *target, int newdirfd, const char *linkpath) { int ret; - if (ocall_symlinkat(&ret, target, - newdirfd, linkpath) != SGX_SUCCESS) { + if (ocall_symlinkat(&ret, target, newdirfd, linkpath) != SGX_SUCCESS) { TRACE_OCALL_FAIL(); return -1; } @@ -626,13 +676,13 @@ int symlinkat(const char *target, int newdirfd, const char *linkpath) return ret; } -int renameat(int olddirfd, const char *oldpath, - int newdirfd, const char *newpath) +int +renameat(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) { int ret; - if (ocall_renameat(&ret, olddirfd, oldpath, - newdirfd, newpath) != SGX_SUCCESS) { + if (ocall_renameat(&ret, olddirfd, oldpath, newdirfd, newpath) + != SGX_SUCCESS) { TRACE_OCALL_FAIL(); return -1; } @@ -642,7 +692,8 @@ int renameat(int olddirfd, const char *oldpath, return ret; } -int ioctl(int fd, unsigned long request, ...) +int +ioctl(int fd, unsigned long request, ...) { int ret; va_list args; @@ -651,8 +702,8 @@ int ioctl(int fd, unsigned long request, ...) case FIONREAD: va_start(args, request); int *arg = (int *)va_arg(args, int *); - if (ocall_ioctl(&ret, fd, request, arg, - sizeof(*arg)) != SGX_SUCCESS) { + if (ocall_ioctl(&ret, fd, request, arg, sizeof(*arg)) + != SGX_SUCCESS) { TRACE_OCALL_FAIL(); va_end(args); return -1; @@ -670,7 +721,8 @@ int ioctl(int fd, unsigned long request, ...) return ret; } -int fcntl(int fd, int cmd, ... /* arg */ ) +int +fcntl(int fd, int cmd, ... /* arg */) { int ret; va_list args; @@ -707,7 +759,8 @@ int fcntl(int fd, int cmd, ... /* arg */ ) return ret; } -int isatty(int fd) +int +isatty(int fd) { int ret; @@ -720,7 +773,8 @@ int isatty(int fd) return ret; } -char *realpath(const char *path, char *resolved_path) +char * +realpath(const char *path, char *resolved_path) { int ret; char buf[PATH_MAX] = { 0 }; @@ -746,7 +800,8 @@ char *realpath(const char *path, char *resolved_path) return resolved_path; } -int posix_fallocate(int fd, off_t offset, off_t len) +int +posix_fallocate(int fd, off_t offset, off_t len) { int ret; @@ -758,15 +813,16 @@ int posix_fallocate(int fd, off_t offset, off_t len) return ret; } -int poll(struct pollfd *fds, nfds_t nfds, int timeout) +int +poll(struct pollfd *fds, nfds_t nfds, int timeout) { int ret; if (fds == NULL) return -1; - if (ocall_poll(&ret, fds, nfds, timeout, - sizeof(*fds) * nfds) != SGX_SUCCESS) { + if (ocall_poll(&ret, fds, nfds, timeout, sizeof(*fds) * nfds) + != SGX_SUCCESS) { TRACE_OCALL_FAIL(); return -1; } @@ -776,8 +832,8 @@ int poll(struct pollfd *fds, nfds_t nfds, int timeout) return ret; } -int getopt(int argc, char * const argv[], - const char *optstring) +int +getopt(int argc, char *const argv[], const char *optstring) { int ret; char **argv1; @@ -805,8 +861,8 @@ int getopt(int argc, char * const argv[], p += ((uintptr_t)strlen(argv[i]) + 1); } - if (ocall_getopt(&ret, argc, (char *)argv1, total_size, - optstring) != SGX_SUCCESS) { + if (ocall_getopt(&ret, argc, (char *)argv1, total_size, optstring) + != SGX_SUCCESS) { TRACE_OCALL_FAIL(); BH_FREE(argv1); return -1; @@ -818,7 +874,8 @@ int getopt(int argc, char * const argv[], return ret; } -int sched_yield(void) +int +sched_yield(void) { int ret; @@ -831,7 +888,8 @@ int sched_yield(void) return ret; } -ssize_t getrandom(void *buf, size_t buflen, unsigned int flags) +ssize_t +getrandom(void *buf, size_t buflen, unsigned int flags) { ssize_t ret; @@ -844,7 +902,8 @@ ssize_t getrandom(void *buf, size_t buflen, unsigned int flags) return ret; } -int getentropy(void *buffer, size_t length) +int +getentropy(void *buffer, size_t length) { int ret; @@ -857,7 +916,8 @@ int getentropy(void *buffer, size_t length) return ret; } -int get_errno(void) +int +get_errno(void) { int ret; @@ -869,4 +929,3 @@ int get_errno(void) } #endif - diff --git a/core/shared/platform/linux-sgx/sgx_file.h b/core/shared/platform/linux-sgx/sgx_file.h index 178e6e7f44..83be395bf1 100644 --- a/core/shared/platform/linux-sgx/sgx_file.h +++ b/core/shared/platform/linux-sgx/sgx_file.h @@ -12,45 +12,45 @@ extern "C" { #endif -#define F_DUPFD 0 -#define F_GETFD 1 -#define F_SETFD 2 -#define F_GETFL 3 -#define F_SETFL 4 +#define F_DUPFD 0 +#define F_GETFD 1 +#define F_SETFD 2 +#define F_GETFL 3 +#define F_SETFL 4 #define FD_CLOEXEC 1 -#define O_PATH 010000000 -#define O_SEARCH O_PATH -#define O_EXEC O_PATH - -#define O_ACCMODE (03|O_SEARCH) -#define O_RDONLY 00 -#define O_WRONLY 01 -#define O_RDWR 02 - -#define O_CREAT 0100 -#define O_EXCL 0200 -#define O_NOCTTY 0400 -#define O_TRUNC 01000 -#define O_APPEND 02000 -#define O_NONBLOCK 04000 -#define O_DSYNC 010000 -#define O_SYNC 04010000 -#define O_RSYNC 04010000 +#define O_PATH 010000000 +#define O_SEARCH O_PATH +#define O_EXEC O_PATH + +#define O_ACCMODE (03 | O_SEARCH) +#define O_RDONLY 00 +#define O_WRONLY 01 +#define O_RDWR 02 + +#define O_CREAT 0100 +#define O_EXCL 0200 +#define O_NOCTTY 0400 +#define O_TRUNC 01000 +#define O_APPEND 02000 +#define O_NONBLOCK 04000 +#define O_DSYNC 010000 +#define O_SYNC 04010000 +#define O_RSYNC 04010000 #define O_DIRECTORY 0200000 -#define O_NOFOLLOW 0400000 -#define O_CLOEXEC 02000000 - -#define O_ASYNC 020000 -#define O_DIRECT 040000 -#define O_LARGEFILE 0 -#define O_NOATIME 01000000 -#define O_PATH 010000000 +#define O_NOFOLLOW 0400000 +#define O_CLOEXEC 02000000 + +#define O_ASYNC 020000 +#define O_DIRECT 040000 +#define O_LARGEFILE 0 +#define O_NOATIME 01000000 +#define O_PATH 010000000 #define O_TMPFILE 020200000 #define O_NDELAY O_NONBLOCK -#define S_IFMT 0170000 +#define S_IFMT 0170000 #define S_IFDIR 0040000 #define S_IFCHR 0020000 #define S_IFBLK 0060000 @@ -63,13 +63,13 @@ extern "C" { #define SEEK_CUR 1 #define SEEK_END 2 -#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR) -#define S_ISCHR(mode) (((mode) & S_IFMT) == S_IFCHR) -#define S_ISBLK(mode) (((mode) & S_IFMT) == S_IFBLK) -#define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG) -#define S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFIFO) -#define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK) -#define S_ISSOCK(mode) (((mode) & S_IFMT) == S_IFSOCK) +#define S_ISDIR(mode) (((mode)&S_IFMT) == S_IFDIR) +#define S_ISCHR(mode) (((mode)&S_IFMT) == S_IFCHR) +#define S_ISBLK(mode) (((mode)&S_IFMT) == S_IFBLK) +#define S_ISREG(mode) (((mode)&S_IFMT) == S_IFREG) +#define S_ISFIFO(mode) (((mode)&S_IFMT) == S_IFIFO) +#define S_ISLNK(mode) (((mode)&S_IFMT) == S_IFLNK) +#define S_ISSOCK(mode) (((mode)&S_IFMT) == S_IFSOCK) #define DT_UNKNOWN 0 #define DT_FIFO 1 @@ -85,24 +85,24 @@ extern "C" { #define AT_REMOVEDIR 0x200 #define AT_SYMLINK_FOLLOW 0x400 -#define POLLIN 0x001 -#define POLLPRI 0x002 -#define POLLOUT 0x004 -#define POLLERR 0x008 -#define POLLHUP 0x010 -#define POLLNVAL 0x020 +#define POLLIN 0x001 +#define POLLPRI 0x002 +#define POLLOUT 0x004 +#define POLLERR 0x008 +#define POLLHUP 0x010 +#define POLLNVAL 0x020 #define POLLRDNORM 0x040 #define POLLRDBAND 0x080 #define POLLWRNORM 0x100 #define POLLWRBAND 0x200 -#define FIONREAD 0x541B +#define FIONREAD 0x541B -#define PATH_MAX 4096 +#define PATH_MAX 4096 /* Special value used to indicate openat should use the current working directory. */ -#define AT_FDCWD -100 +#define AT_FDCWD -100 typedef long __syscall_slong_t; @@ -138,7 +138,7 @@ struct stat { mode_t st_mode; uid_t st_uid; gid_t st_gid; - unsigned int __pad0; + unsigned int __pad0; dev_t st_rdev; off_t st_size; blksize_t st_blksize; @@ -156,76 +156,108 @@ struct iovec { }; struct pollfd { - int fd; - short events; - short revents; + int fd; + short events; + short revents; }; -int open(const char *pathname, int flags, ...); -int openat(int dirfd, const char *pathname, int flags, ...); -int close(int fd); - -DIR *fdopendir(int fd); -int closedir(DIR *dirp); -void rewinddir(DIR *dirp); -void seekdir(DIR *dirp, long loc); -struct dirent *readdir(DIR *dirp); -long telldir(DIR *dirp); - -ssize_t read(int fd, void *buf, size_t count); -ssize_t readv(int fd, const struct iovec *iov, int iovcnt); -ssize_t writev(int fd, const struct iovec *iov, int iovcnt); -ssize_t preadv(int fd, const struct iovec *iov, int iovcnt, - off_t offset); -ssize_t pwritev(int fd, const struct iovec *iov, int iovcnt, - off_t offset); - -off_t lseek(int fd, off_t offset, int whence); -int ftruncate(int fd, off_t length); - -int stat(const char *pathname, struct stat *statbuf); -int fstat(int fd, struct stat *statbuf); -int fstatat(int dirfd, const char *pathname, struct stat *statbuf, - int flags); - -int fsync(int fd); -int fdatasync(int fd); - -int mkdirat(int dirfd, const char *pathname, mode_t mode); -int link(const char *oldpath, const char *newpath); -int linkat(int olddirfd, const char *oldpath, - int newdirfd, const char *newpath, int flags); -int unlinkat(int dirfd, const char *pathname, int flags); -ssize_t readlinkat(int dirfd, const char *pathname, - char *buf, size_t bufsiz); -int symlinkat(const char *target, int newdirfd, const char *linkpath); -int renameat(int olddirfd, const char *oldpath, - int newdirfd, const char *newpath); - -int ioctl(int fd, unsigned long request, ...); -int fcntl(int fd, int cmd, ... /* arg */ ); - -int isatty(int fd); - -char *realpath(const char *path, char *resolved_path); - -int posix_fallocate(int fd, off_t offset, off_t len); - -int poll(struct pollfd *fds, nfds_t nfds, int timeout); - -int getopt(int argc, char * const argv[], - const char *optstring); - -int sched_yield(void); - -ssize_t getrandom(void *buf, size_t buflen, unsigned int flags); -int getentropy(void *buffer, size_t length); - -int get_errno(void); +int +open(const char *pathname, int flags, ...); +int +openat(int dirfd, const char *pathname, int flags, ...); +int +close(int fd); + +DIR * +fdopendir(int fd); +int +closedir(DIR *dirp); +void +rewinddir(DIR *dirp); +void +seekdir(DIR *dirp, long loc); +struct dirent * +readdir(DIR *dirp); +long +telldir(DIR *dirp); + +ssize_t +read(int fd, void *buf, size_t count); +ssize_t +readv(int fd, const struct iovec *iov, int iovcnt); +ssize_t +writev(int fd, const struct iovec *iov, int iovcnt); +ssize_t +preadv(int fd, const struct iovec *iov, int iovcnt, off_t offset); +ssize_t +pwritev(int fd, const struct iovec *iov, int iovcnt, off_t offset); + +off_t +lseek(int fd, off_t offset, int whence); +int +ftruncate(int fd, off_t length); + +int +stat(const char *pathname, struct stat *statbuf); +int +fstat(int fd, struct stat *statbuf); +int +fstatat(int dirfd, const char *pathname, struct stat *statbuf, int flags); + +int +fsync(int fd); +int +fdatasync(int fd); + +int +mkdirat(int dirfd, const char *pathname, mode_t mode); +int +link(const char *oldpath, const char *newpath); +int +linkat(int olddirfd, const char *oldpath, int newdirfd, const char *newpath, + int flags); +int +unlinkat(int dirfd, const char *pathname, int flags); +ssize_t +readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz); +int +symlinkat(const char *target, int newdirfd, const char *linkpath); +int +renameat(int olddirfd, const char *oldpath, int newdirfd, const char *newpath); + +int +ioctl(int fd, unsigned long request, ...); +int +fcntl(int fd, int cmd, ... /* arg */); + +int +isatty(int fd); + +char * +realpath(const char *path, char *resolved_path); + +int +posix_fallocate(int fd, off_t offset, off_t len); + +int +poll(struct pollfd *fds, nfds_t nfds, int timeout); + +int +getopt(int argc, char *const argv[], const char *optstring); + +int +sched_yield(void); + +ssize_t +getrandom(void *buf, size_t buflen, unsigned int flags); +int +getentropy(void *buffer, size_t length); + +int +get_errno(void); #ifdef __cplusplus } #endif #endif /* end of _SGX_FILE_H */ - diff --git a/core/shared/platform/linux-sgx/sgx_platform.c b/core/shared/platform/linux-sgx/sgx_platform.c index abfb991192..a383698fcb 100644 --- a/core/shared/platform/linux-sgx/sgx_platform.c +++ b/core/shared/platform/linux-sgx/sgx_platform.c @@ -7,19 +7,19 @@ #include "platform_api_extension.h" #include "sgx_rsrv_mem_mngr.h" -#define FIXED_BUFFER_SIZE (1<<9) +#define FIXED_BUFFER_SIZE (1 << 9) static os_print_function_t print_function = NULL; -int bh_platform_init() +int +bh_platform_init() { return 0; } void bh_platform_destroy() -{ -} +{} void * os_malloc(unsigned size) @@ -39,22 +39,26 @@ os_free(void *ptr) free(ptr); } -int putchar(int c) +int +putchar(int c) { return 0; } -int puts(const char *s) +int +puts(const char *s) { return 0; } -void os_set_print_function(os_print_function_t pf) +void +os_set_print_function(os_print_function_t pf) { print_function = pf; } -int os_printf(const char *message, ...) +int +os_printf(const char *message, ...) { if (print_function != NULL) { char msg[FIXED_BUFFER_SIZE] = { '\0' }; @@ -68,7 +72,8 @@ int os_printf(const char *message, ...) return 0; } -int os_vprintf(const char * format, va_list arg) +int +os_vprintf(const char *format, va_list arg) { if (print_function != NULL) { char msg[FIXED_BUFFER_SIZE] = { '\0' }; @@ -79,20 +84,23 @@ int os_vprintf(const char * format, va_list arg) return 0; } -char *strcpy(char *dest, const char *src) +char * +strcpy(char *dest, const char *src) { const unsigned char *s = src; unsigned char *d = dest; - while ((*d++ = *s++)); + while ((*d++ = *s++)) + ; return dest; } -void* os_mmap(void *hint, size_t size, int prot, int flags) +void * +os_mmap(void *hint, size_t size, int prot, int flags) { int mprot = 0; uint64 aligned_size, page_size; - void* ret = NULL; + void *ret = NULL; sgx_status_t st = 0; page_size = getpagesize(); @@ -103,8 +111,8 @@ void* os_mmap(void *hint, size_t size, int prot, int flags) ret = sgx_alloc_rsrv_mem(aligned_size); if (ret == NULL) { - os_printf("os_mmap(size=%u, aligned size=%lu, prot=0x%x) failed.", - size, aligned_size, prot); + os_printf("os_mmap(size=%u, aligned size=%lu, prot=0x%x) failed.", size, + aligned_size, prot); return NULL; } @@ -117,8 +125,8 @@ void* os_mmap(void *hint, size_t size, int prot, int flags) st = sgx_tprotect_rsrv_mem(ret, aligned_size, mprot); if (st != SGX_SUCCESS) { - os_printf("os_mmap(size=%u, prot=0x%x) failed to set protect.", - size, prot); + os_printf("os_mmap(size=%u, prot=0x%x) failed to set protect.", size, + prot); sgx_free_rsrv_mem(ret, aligned_size); return NULL; } @@ -126,7 +134,8 @@ void* os_mmap(void *hint, size_t size, int prot, int flags) return ret; } -void os_munmap(void *addr, size_t size) +void +os_munmap(void *addr, size_t size) { uint64 aligned_size, page_size; @@ -135,7 +144,8 @@ void os_munmap(void *addr, size_t size) sgx_free_rsrv_mem(addr, aligned_size); } -int os_mprotect(void *addr, size_t size, int prot) +int +os_mprotect(void *addr, size_t size, int prot) { int mprot = 0; sgx_status_t st = 0; @@ -152,14 +162,12 @@ int os_mprotect(void *addr, size_t size, int prot) mprot |= SGX_PROT_EXEC; st = sgx_tprotect_rsrv_mem(addr, aligned_size, mprot); if (st != SGX_SUCCESS) - os_printf("os_mprotect(addr=0x%"PRIx64", size=%u, prot=0x%x) failed.", + os_printf("os_mprotect(addr=0x%" PRIx64 ", size=%u, prot=0x%x) failed.", (uintptr_t)addr, size, prot); - return (st == SGX_SUCCESS? 0:-1); + return (st == SGX_SUCCESS ? 0 : -1); } void os_dcache_flush(void) -{ -} - +{} diff --git a/core/shared/platform/linux-sgx/sgx_pthread.c b/core/shared/platform/linux-sgx/sgx_pthread.c index cf000565ac..7801e3534f 100644 --- a/core/shared/platform/linux-sgx/sgx_pthread.c +++ b/core/shared/platform/linux-sgx/sgx_pthread.c @@ -15,22 +15,27 @@ #ifndef SGX_THREAD_LOCK_INITIALIZER /* defined since sgxsdk-2.11 */ /* sgxsdk doesn't support pthread_rwlock related APIs until version 2.11, we implement them by ourselves. */ -int ocall_pthread_rwlock_init(int *p_ret, void **rwlock, void *attr); +int +ocall_pthread_rwlock_init(int *p_ret, void **rwlock, void *attr); -int ocall_pthread_rwlock_destroy(int *p_ret, void **rwlock); +int +ocall_pthread_rwlock_destroy(int *p_ret, void **rwlock); -int ocall_pthread_rwlock_rdlock(int *p_ret, void **rwlock); +int +ocall_pthread_rwlock_rdlock(int *p_ret, void **rwlock); -int ocall_pthread_rwlock_wrlock(int *p_ret, void **rwlock); +int +ocall_pthread_rwlock_wrlock(int *p_ret, void **rwlock); -int ocall_pthread_rwlock_unlock(int *p_ret, void **rwlock); +int +ocall_pthread_rwlock_unlock(int *p_ret, void **rwlock); -int pthread_rwlock_init(pthread_rwlock_t *rwlock, void *attr) +int +pthread_rwlock_init(pthread_rwlock_t *rwlock, void *attr) { int ret = -1; - if (ocall_pthread_rwlock_init(&ret, (void **)rwlock, NULL) - != SGX_SUCCESS) { + if (ocall_pthread_rwlock_init(&ret, (void **)rwlock, NULL) != SGX_SUCCESS) { TRACE_OCALL_FAIL(); return -1; } @@ -38,7 +43,8 @@ int pthread_rwlock_init(pthread_rwlock_t *rwlock, void *attr) return ret; } -int pthread_rwlock_destroy(pthread_rwlock_t *rwlock) +int +pthread_rwlock_destroy(pthread_rwlock_t *rwlock) { int ret = -1; @@ -48,31 +54,34 @@ int pthread_rwlock_destroy(pthread_rwlock_t *rwlock) return ret; } -int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock) +int +pthread_rwlock_rdlock(pthread_rwlock_t *rwlock) { int ret = -1; - if (ocall_pthread_rwlock_rdlock(&ret, (void*)*rwlock) != SGX_SUCCESS) { + if (ocall_pthread_rwlock_rdlock(&ret, (void *)*rwlock) != SGX_SUCCESS) { TRACE_OCALL_FAIL(); } return ret; } -int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock) +int +pthread_rwlock_wrlock(pthread_rwlock_t *rwlock) { int ret = -1; - if (ocall_pthread_rwlock_wrlock(&ret, (void*)*rwlock) != SGX_SUCCESS) { + if (ocall_pthread_rwlock_wrlock(&ret, (void *)*rwlock) != SGX_SUCCESS) { TRACE_OCALL_FAIL(); } return ret; } -int pthread_rwlock_unlock(pthread_rwlock_t *rwlock) +int +pthread_rwlock_unlock(pthread_rwlock_t *rwlock) { int ret = -1; - if (ocall_pthread_rwlock_unlock(&ret, (void*)*rwlock) != SGX_SUCCESS) { + if (ocall_pthread_rwlock_unlock(&ret, (void *)*rwlock) != SGX_SUCCESS) { TRACE_OCALL_FAIL(); } return ret; @@ -80,4 +89,3 @@ int pthread_rwlock_unlock(pthread_rwlock_t *rwlock) #endif /* end of SGX_THREAD_LOCK_INITIALIZER */ #endif - diff --git a/core/shared/platform/linux-sgx/sgx_pthread.h b/core/shared/platform/linux-sgx/sgx_pthread.h index 513bd3ab01..01a3ae0443 100644 --- a/core/shared/platform/linux-sgx/sgx_pthread.h +++ b/core/shared/platform/linux-sgx/sgx_pthread.h @@ -15,12 +15,17 @@ extern "C" { version 2.11, we implement them by ourselves. */ typedef uintptr_t pthread_rwlock_t; -int pthread_rwlock_init(pthread_rwlock_t *rwlock, void *attr); -int pthread_rwlock_destroy(pthread_rwlock_t *rwlock); - -int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock); -int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock); -int pthread_rwlock_unlock(pthread_rwlock_t *rwlock); +int +pthread_rwlock_init(pthread_rwlock_t *rwlock, void *attr); +int +pthread_rwlock_destroy(pthread_rwlock_t *rwlock); + +int +pthread_rwlock_wrlock(pthread_rwlock_t *rwlock); +int +pthread_rwlock_rdlock(pthread_rwlock_t *rwlock); +int +pthread_rwlock_unlock(pthread_rwlock_t *rwlock); #endif /* end of SGX_THREAD_LOCK_INITIALIZER */ #ifdef __cplusplus @@ -28,4 +33,3 @@ int pthread_rwlock_unlock(pthread_rwlock_t *rwlock); #endif #endif /* end of _SGX_PTHREAD_H */ - diff --git a/core/shared/platform/linux-sgx/sgx_rsrv_mem_mngr.h b/core/shared/platform/linux-sgx/sgx_rsrv_mem_mngr.h index b32a68ba51..5555d4d9f9 100644 --- a/core/shared/platform/linux-sgx/sgx_rsrv_mem_mngr.h +++ b/core/shared/platform/linux-sgx/sgx_rsrv_mem_mngr.h @@ -30,7 +30,8 @@ */ /* - * This file is copied from https://github.com/intel/linux-sgx/blob/4589daddd58bec7367a6a9de3fe301e6de17671a/common/inc/internal/sgx_rsrv_mem_mngr.h + * This file is copied from + * https://github.com/intel/linux-sgx/blob/4589daddd58bec7367a6a9de3fe301e6de17671a/common/inc/internal/sgx_rsrv_mem_mngr.h * The reason we copied here is that the official SGX SDK release has * not included this header file yet. */ @@ -43,48 +44,52 @@ #include "stdint.h" #include "sgx_error.h" -#define SGX_PROT_READ 0x1 /* page can be read */ -#define SGX_PROT_WRITE 0x2 /* page can be written */ -#define SGX_PROT_EXEC 0x4 /* page can be executed */ -#define SGX_PROT_NONE 0x0 /* page can not be accessed */ +#define SGX_PROT_READ 0x1 /* page can be read */ +#define SGX_PROT_WRITE 0x2 /* page can be written */ +#define SGX_PROT_EXEC 0x4 /* page can be executed */ +#define SGX_PROT_NONE 0x0 /* page can not be accessed */ #ifdef __cplusplus extern "C" { #endif - /* Allocate a range of EPC memory from the reserved memory area with RW permission - * - * Parameters: - * Inputs: length [in]: Size of region to be allocated in bytes. Page aligned - * Return: Starting address of the new allocated memory area on success; otherwise NULL - */ - void * sgx_alloc_rsrv_mem(size_t length); - - - /* Free a range of EPC memory from the reserved memory area - * - * Parameters: - * Inputs: addr[in]: Starting address of region to be freed. Page aligned. - * length[in]: The length of the memory to be freed in bytes. Page aligned - * Return: 0 on success; otherwise -1 - */ - int sgx_free_rsrv_mem(void * addr, size_t length); - +/* Allocate a range of EPC memory from the reserved memory area with RW + * permission + * + * Parameters: + * Inputs: length [in]: Size of region to be allocated in bytes. Page aligned. + * Return: Starting address of the new allocated memory area on success; + * otherwise NULL + */ +void * +sgx_alloc_rsrv_mem(size_t length); - /* Modify the access permissions of the pages in the reserved memory area. - * - * Parameters: - * Inputs: addr[in]: Starting address of region which needs to change access permission. Page aligned. - * length[in]: The length of the memory to be manipulated in bytes. Page aligned. - * prot[in]: The target memory protection. - * Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h - */ - sgx_status_t sgx_tprotect_rsrv_mem(void *addr, size_t len, int prot); +/* Free a range of EPC memory from the reserved memory area + * + * Parameters: + * Inputs: addr[in]: Starting address of region to be freed. Page aligned. + * length[in]: The length of the memory to be freed in bytes. + * Page aligned. + * Return: 0 on success; otherwise -1 + */ +int +sgx_free_rsrv_mem(void *addr, size_t length); +/* Modify the access permissions of the pages in the reserved memory area. + * + * Parameters: + * Inputs: addr[in]: Starting address of region which needs to change access + * permission. Page aligned. + * length[in]: The length of the memory to be manipulated in bytes. + * Page aligned. + * prot[in]: The target memory protection. + * Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h + */ +sgx_status_t +sgx_tprotect_rsrv_mem(void *addr, size_t len, int prot); #ifdef __cplusplus } #endif #endif - diff --git a/core/shared/platform/linux-sgx/sgx_signal.c b/core/shared/platform/linux-sgx/sgx_signal.c index 698272ca5a..b52c18821c 100644 --- a/core/shared/platform/linux-sgx/sgx_signal.c +++ b/core/shared/platform/linux-sgx/sgx_signal.c @@ -9,9 +9,11 @@ #define TRACE_OCALL_FAIL() os_printf("ocall %s failed!\n", __FUNCTION__) -int ocall_raise(int *p_ret, int sig); +int +ocall_raise(int *p_ret, int sig); -int raise(int sig) +int +raise(int sig) { int ret; @@ -27,4 +29,3 @@ int raise(int sig) } #endif - diff --git a/core/shared/platform/linux-sgx/sgx_signal.h b/core/shared/platform/linux-sgx/sgx_signal.h index b83a9235d0..494342be3d 100644 --- a/core/shared/platform/linux-sgx/sgx_signal.h +++ b/core/shared/platform/linux-sgx/sgx_signal.h @@ -11,47 +11,47 @@ extern "C" { #endif /* Signals. */ -#define SIGHUP 1 /* Hangup (POSIX). */ -#define SIGINT 2 /* Interrupt (ANSI). */ -#define SIGQUIT 3 /* Quit (POSIX). */ -#define SIGILL 4 /* Illegal instruction (ANSI). */ -#define SIGTRAP 5 /* Trace trap (POSIX). */ -#define SIGABRT 6 /* Abort (ANSI). */ -#define SIGIOT 6 /* IOT trap (4.2 BSD). */ -#define SIGBUS 7 /* BUS error (4.2 BSD). */ -#define SIGFPE 8 /* Floating-point exception (ANSI). */ -#define SIGKILL 9 /* Kill, unblockable (POSIX). */ -#define SIGUSR1 10 /* User-defined signal 1 (POSIX). */ -#define SIGSEGV 11 /* Segmentation violation (ANSI). */ -#define SIGUSR2 12 /* User-defined signal 2 (POSIX). */ -#define SIGPIPE 13 /* Broken pipe (POSIX). */ -#define SIGALRM 14 /* Alarm clock (POSIX). */ -#define SIGTERM 15 /* Termination (ANSI). */ -#define SIGSTKFLT 16 /* Stack fault. */ -#define SIGCLD SIGCHLD /* Same as SIGCHLD (System V). */ -#define SIGCHLD 17 /* Child status has changed (POSIX). */ -#define SIGCONT 18 /* Continue (POSIX). */ -#define SIGSTOP 19 /* Stop, unblockable (POSIX). */ -#define SIGTSTP 20 /* Keyboard stop (POSIX). */ -#define SIGTTIN 21 /* Background read from tty (POSIX). */ -#define SIGTTOU 22 /* Background write to tty (POSIX). */ -#define SIGURG 23 /* Urgent condition on socket (4.2 BSD). */ -#define SIGXCPU 24 /* CPU limit exceeded (4.2 BSD). */ -#define SIGXFSZ 25 /* File size limit exceeded (4.2 BSD). */ -#define SIGVTALRM 26 /* Virtual alarm clock (4.2 BSD). */ -#define SIGPROF 27 /* Profiling alarm clock (4.2 BSD). */ -#define SIGWINCH 28 /* Window size change (4.3 BSD, Sun). */ -#define SIGPOLL SIGIO /* Pollable event occurred (System V). */ -#define SIGIO 29 /* I/O now possible (4.2 BSD). */ -#define SIGPWR 30 /* Power failure restart (System V). */ -#define SIGSYS 31 /* Bad system call. */ -#define SIGUNUSED 31 +#define SIGHUP 1 /* Hangup (POSIX). */ +#define SIGINT 2 /* Interrupt (ANSI). */ +#define SIGQUIT 3 /* Quit (POSIX). */ +#define SIGILL 4 /* Illegal instruction (ANSI). */ +#define SIGTRAP 5 /* Trace trap (POSIX). */ +#define SIGABRT 6 /* Abort (ANSI). */ +#define SIGIOT 6 /* IOT trap (4.2 BSD). */ +#define SIGBUS 7 /* BUS error (4.2 BSD). */ +#define SIGFPE 8 /* Floating-point exception (ANSI). */ +#define SIGKILL 9 /* Kill, unblockable (POSIX). */ +#define SIGUSR1 10 /* User-defined signal 1 (POSIX). */ +#define SIGSEGV 11 /* Segmentation violation (ANSI). */ +#define SIGUSR2 12 /* User-defined signal 2 (POSIX). */ +#define SIGPIPE 13 /* Broken pipe (POSIX). */ +#define SIGALRM 14 /* Alarm clock (POSIX). */ +#define SIGTERM 15 /* Termination (ANSI). */ +#define SIGSTKFLT 16 /* Stack fault. */ +#define SIGCLD SIGCHLD /* Same as SIGCHLD (System V). */ +#define SIGCHLD 17 /* Child status has changed (POSIX). */ +#define SIGCONT 18 /* Continue (POSIX). */ +#define SIGSTOP 19 /* Stop, unblockable (POSIX). */ +#define SIGTSTP 20 /* Keyboard stop (POSIX). */ +#define SIGTTIN 21 /* Background read from tty (POSIX). */ +#define SIGTTOU 22 /* Background write to tty (POSIX). */ +#define SIGURG 23 /* Urgent condition on socket (4.2 BSD). */ +#define SIGXCPU 24 /* CPU limit exceeded (4.2 BSD). */ +#define SIGXFSZ 25 /* File size limit exceeded (4.2 BSD). */ +#define SIGVTALRM 26 /* Virtual alarm clock (4.2 BSD). */ +#define SIGPROF 27 /* Profiling alarm clock (4.2 BSD). */ +#define SIGWINCH 28 /* Window size change (4.3 BSD, Sun). */ +#define SIGPOLL SIGIO /* Pollable event occurred (System V). */ +#define SIGIO 29 /* I/O now possible (4.2 BSD). */ +#define SIGPWR 30 /* Power failure restart (System V). */ +#define SIGSYS 31 /* Bad system call. */ +#define SIGUNUSED 31 -int raise(int sig); +int +raise(int sig); #ifdef __cplusplus } #endif #endif /* end of _SGX_SIGNAL_H */ - diff --git a/core/shared/platform/linux-sgx/sgx_socket.c b/core/shared/platform/linux-sgx/sgx_socket.c index e4ed97d2d7..e9a824fda6 100644 --- a/core/shared/platform/linux-sgx/sgx_socket.c +++ b/core/shared/platform/linux-sgx/sgx_socket.c @@ -9,18 +9,23 @@ #define TRACE_OCALL_FAIL() os_printf("ocall %s failed!\n", __FUNCTION__) -int ocall_socket(int *p_ret, int domain, int type, int protocol); -int ocall_getsockopt(int *p_ret, int sockfd, int level, int optname, - void *val_buf, unsigned int val_buf_size, - void *len_buf); - -int ocall_sendmsg(ssize_t *p_ret, int sockfd, void *msg_buf, - unsigned int msg_buf_size, int flags); -int ocall_recvmsg(ssize_t *p_ret, int sockfd, void *msg_buf, - unsigned int msg_buf_size, int flags); -int ocall_shutdown(int *p_ret, int sockfd, int how); - -int socket(int domain, int type, int protocol) +int +ocall_socket(int *p_ret, int domain, int type, int protocol); +int +ocall_getsockopt(int *p_ret, int sockfd, int level, int optname, void *val_buf, + unsigned int val_buf_size, void *len_buf); + +int +ocall_sendmsg(ssize_t *p_ret, int sockfd, void *msg_buf, + unsigned int msg_buf_size, int flags); +int +ocall_recvmsg(ssize_t *p_ret, int sockfd, void *msg_buf, + unsigned int msg_buf_size, int flags); +int +ocall_shutdown(int *p_ret, int sockfd, int how); + +int +socket(int domain, int type, int protocol) { int ret; @@ -35,14 +40,15 @@ int socket(int domain, int type, int protocol) return ret; } -int getsockopt(int sockfd, int level, int optname, - void *optval, socklen_t *optlen) +int +getsockopt(int sockfd, int level, int optname, void *optval, socklen_t *optlen) { int ret; unsigned int val_buf_size = *optlen; - if (ocall_getsockopt(&ret, sockfd, level, optname, optval, - val_buf_size, (void *)optlen) != SGX_SUCCESS) { + if (ocall_getsockopt(&ret, sockfd, level, optname, optval, val_buf_size, + (void *)optlen) + != SGX_SUCCESS) { TRACE_OCALL_FAIL(); return -1; } @@ -53,7 +59,8 @@ int getsockopt(int sockfd, int level, int optname, return ret; } -ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags) +ssize_t +sendmsg(int sockfd, const struct msghdr *msg, int flags) { ssize_t ret; int i; @@ -77,7 +84,7 @@ ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags) if (msg1 == NULL) return -1; - p = (char*)(uintptr_t)sizeof(struct msghdr); + p = (char *)(uintptr_t)sizeof(struct msghdr); if (msg->msg_name != NULL) { msg1->msg_name = p; @@ -106,8 +113,8 @@ ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags) } } - if (ocall_sendmsg(&ret, sockfd, (void *)msg1, (uint32)total_size, - flags) != SGX_SUCCESS) { + if (ocall_sendmsg(&ret, sockfd, (void *)msg1, (uint32)total_size, flags) + != SGX_SUCCESS) { TRACE_OCALL_FAIL(); return -1; } @@ -118,7 +125,8 @@ ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags) return ret; } -ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags) +ssize_t +recvmsg(int sockfd, struct msghdr *msg, int flags) { ssize_t ret; int i; @@ -144,7 +152,7 @@ ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags) memset(msg1, 0, total_size); - p = (char*)(uintptr_t)sizeof(struct msghdr); + p = (char *)(uintptr_t)sizeof(struct msghdr); if (msg->msg_name != NULL) { msg1->msg_name = p; @@ -167,8 +175,8 @@ ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags) } } - if (ocall_recvmsg(&ret, sockfd, (void *)msg1, (uint32)total_size, - flags) != SGX_SUCCESS) { + if (ocall_recvmsg(&ret, sockfd, (void *)msg1, (uint32)total_size, flags) + != SGX_SUCCESS) { TRACE_OCALL_FAIL(); return -1; } @@ -203,7 +211,8 @@ ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags) return ret; } -int shutdown(int sockfd, int how) +int +shutdown(int sockfd, int how) { int ret; @@ -219,4 +228,3 @@ int shutdown(int sockfd, int how) } #endif - diff --git a/core/shared/platform/linux-sgx/sgx_socket.h b/core/shared/platform/linux-sgx/sgx_socket.h index c070354507..6e5b0438d2 100644 --- a/core/shared/platform/linux-sgx/sgx_socket.h +++ b/core/shared/platform/linux-sgx/sgx_socket.h @@ -12,32 +12,32 @@ extern "C" { #endif -#define SOL_SOCKET 1 +#define SOL_SOCKET 1 -#define SOCK_STREAM 1 -#define SOCK_DGRAM 2 +#define SOCK_STREAM 1 +#define SOCK_DGRAM 2 -#define SO_TYPE 3 +#define SO_TYPE 3 -#define MSG_OOB 0x0001 -#define MSG_PEEK 0x0002 +#define MSG_OOB 0x0001 +#define MSG_PEEK 0x0002 #define MSG_DONTROUTE 0x0004 -#define MSG_CTRUNC 0x0008 -#define MSG_PROXY 0x0010 -#define MSG_TRUNC 0x0020 -#define MSG_DONTWAIT 0x0040 -#define MSG_EOR 0x0080 -#define MSG_WAITALL 0x0100 -#define MSG_FIN 0x0200 -#define MSG_SYN 0x0400 -#define MSG_CONFIRM 0x0800 -#define MSG_RST 0x1000 -#define MSG_ERRQUEUE 0x2000 -#define MSG_NOSIGNAL 0x4000 -#define MSG_MORE 0x8000 +#define MSG_CTRUNC 0x0008 +#define MSG_PROXY 0x0010 +#define MSG_TRUNC 0x0020 +#define MSG_DONTWAIT 0x0040 +#define MSG_EOR 0x0080 +#define MSG_WAITALL 0x0100 +#define MSG_FIN 0x0200 +#define MSG_SYN 0x0400 +#define MSG_CONFIRM 0x0800 +#define MSG_RST 0x1000 +#define MSG_ERRQUEUE 0x2000 +#define MSG_NOSIGNAL 0x4000 +#define MSG_MORE 0x8000 #define MSG_WAITFORONE 0x10000 -#define MSG_BATCH 0x40000 -#define MSG_FASTOPEN 0x20000000 +#define MSG_BATCH 0x40000 +#define MSG_FASTOPEN 0x20000000 #define MSG_CMSG_CLOEXEC 0x40000000 #define SHUT_RD 0 @@ -54,21 +54,23 @@ struct msghdr { int msg_flags; }; +int +socket(int domain, int type, int protocol); -int socket(int domain, int type, int protocol); +int +getsockopt(int sockfd, int level, int optname, void *optval, socklen_t *optlen); -int getsockopt(int sockfd, int level, int optname, - void *optval, socklen_t *optlen); +ssize_t +sendmsg(int sockfd, const struct msghdr *msg, int flags); -ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags); +ssize_t +recvmsg(int sockfd, struct msghdr *msg, int flags); -ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags); - -int shutdown(int sockfd, int how); +int +shutdown(int sockfd, int how); #ifdef __cplusplus } #endif #endif /* end of _SGX_SOCKET_H */ - diff --git a/core/shared/platform/linux-sgx/sgx_thread.c b/core/shared/platform/linux-sgx/sgx_thread.c index d1503b47cc..34405a1030 100644 --- a/core/shared/platform/linux-sgx/sgx_thread.c +++ b/core/shared/platform/linux-sgx/sgx_thread.c @@ -12,9 +12,10 @@ typedef struct { void *arg; } thread_wrapper_arg; -static void *os_thread_wrapper(void *arg) +static void * +os_thread_wrapper(void *arg) { - thread_wrapper_arg * targ = arg; + thread_wrapper_arg *targ = arg; thread_start_routine_t start_func = targ->start; void *thread_arg = targ->arg; os_printf("THREAD CREATED %p\n", &targ); @@ -23,15 +24,16 @@ static void *os_thread_wrapper(void *arg) return NULL; } -int os_thread_create_with_prio(korp_tid *tid, thread_start_routine_t start, - void *arg, unsigned int stack_size, int prio) +int +os_thread_create_with_prio(korp_tid *tid, thread_start_routine_t start, + void *arg, unsigned int stack_size, int prio) { thread_wrapper_arg *targ; assert(tid); assert(start); - targ = (thread_wrapper_arg *) BH_MALLOC(sizeof(*targ)); + targ = (thread_wrapper_arg *)BH_MALLOC(sizeof(*targ)); if (!targ) { return BHT_ERROR; } @@ -47,15 +49,17 @@ int os_thread_create_with_prio(korp_tid *tid, thread_start_routine_t start, return BHT_OK; } -int os_thread_create(korp_tid *tid, thread_start_routine_t start, void *arg, - unsigned int stack_size) +int +os_thread_create(korp_tid *tid, thread_start_routine_t start, void *arg, + unsigned int stack_size) { return os_thread_create_with_prio(tid, start, arg, stack_size, BH_THREAD_DEFAULT_PRIORITY); } #endif -korp_tid os_self_thread() +korp_tid +os_self_thread() { #ifndef SGX_DISABLE_PTHREAD return pthread_self(); @@ -64,7 +68,8 @@ korp_tid os_self_thread() #endif } -int os_mutex_init(korp_mutex *mutex) +int +os_mutex_init(korp_mutex *mutex) { #ifndef SGX_DISABLE_PTHREAD pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; @@ -73,7 +78,8 @@ int os_mutex_init(korp_mutex *mutex) return BHT_OK; } -int os_mutex_destroy(korp_mutex *mutex) +int +os_mutex_destroy(korp_mutex *mutex) { #ifndef SGX_DISABLE_PTHREAD pthread_mutex_destroy(mutex); @@ -81,7 +87,8 @@ int os_mutex_destroy(korp_mutex *mutex) return BHT_OK; } -int os_mutex_lock(korp_mutex *mutex) +int +os_mutex_lock(korp_mutex *mutex) { #ifndef SGX_DISABLE_PTHREAD return pthread_mutex_lock(mutex); @@ -90,7 +97,8 @@ int os_mutex_lock(korp_mutex *mutex) #endif } -int os_mutex_unlock(korp_mutex *mutex) +int +os_mutex_unlock(korp_mutex *mutex) { #ifndef SGX_DISABLE_PTHREAD return pthread_mutex_unlock(mutex); @@ -99,7 +107,8 @@ int os_mutex_unlock(korp_mutex *mutex) #endif } -int os_cond_init(korp_cond *cond) +int +os_cond_init(korp_cond *cond) { #ifndef SGX_DISABLE_PTHREAD pthread_cond_t c = PTHREAD_COND_INITIALIZER; @@ -108,7 +117,8 @@ int os_cond_init(korp_cond *cond) return BHT_OK; } -int os_cond_destroy(korp_cond *cond) +int +os_cond_destroy(korp_cond *cond) { #ifndef SGX_DISABLE_PTHREAD pthread_cond_destroy(cond); @@ -116,7 +126,8 @@ int os_cond_destroy(korp_cond *cond) return BHT_OK; } -int os_cond_wait(korp_cond *cond, korp_mutex *mutex) +int +os_cond_wait(korp_cond *cond, korp_mutex *mutex) { #ifndef SGX_DISABLE_PTHREAD assert(cond); @@ -129,14 +140,16 @@ int os_cond_wait(korp_cond *cond, korp_mutex *mutex) return BHT_OK; } -int os_cond_reltimedwait(korp_cond *cond, korp_mutex *mutex, uint64 useconds) +int +os_cond_reltimedwait(korp_cond *cond, korp_mutex *mutex, uint64 useconds) { os_printf("warning: SGX pthread_cond_timedwait isn't supported, " "calling pthread_cond_wait instead!\n"); return BHT_ERROR; } -int os_cond_signal(korp_cond *cond) +int +os_cond_signal(korp_cond *cond) { #ifndef SGX_DISABLE_PTHREAD assert(cond); @@ -148,7 +161,8 @@ int os_cond_signal(korp_cond *cond) return BHT_OK; } -int os_thread_join(korp_tid thread, void **value_ptr) +int +os_thread_join(korp_tid thread, void **value_ptr) { #ifndef SGX_DISABLE_PTHREAD return pthread_join(thread, value_ptr); @@ -157,13 +171,15 @@ int os_thread_join(korp_tid thread, void **value_ptr) #endif } -int os_thread_detach(korp_tid thread) +int +os_thread_detach(korp_tid thread) { /* SGX pthread_detach isn't provided, return directly. */ return 0; } -void os_thread_exit(void *retval) +void +os_thread_exit(void *retval) { #ifndef SGX_DISABLE_PTHREAD pthread_exit(retval); @@ -172,9 +188,9 @@ void os_thread_exit(void *retval) #endif } -uint8 *os_thread_get_stack_boundary() +uint8 * +os_thread_get_stack_boundary() { /* TODO: get sgx stack boundary */ return NULL; } - diff --git a/core/shared/platform/linux-sgx/sgx_time.c b/core/shared/platform/linux-sgx/sgx_time.c index 34fe125702..c945bbcc79 100644 --- a/core/shared/platform/linux-sgx/sgx_time.c +++ b/core/shared/platform/linux-sgx/sgx_time.c @@ -8,18 +8,22 @@ #define TRACE_FUNC() os_printf("undefined %s\n", __FUNCTION__) #define TRACE_OCALL_FAIL() os_printf("ocall %s failed!\n", __FUNCTION__) -int ocall_clock_gettime(int *p_ret, unsigned clock_id, - void *tp_buf, unsigned int tp_buf_size); -int ocall_clock_getres(int *p_ret, int clock_id, - void *res_buf, unsigned int res_buf_size); -int ocall_utimensat(int *p_ret, int dirfd, const char *pathname, - const void *times_buf, unsigned int times_buf_size, - int flags); -int ocall_futimens(int *p_ret, int fd, - const void *times_buf, unsigned int times_buf_size); -int ocall_clock_nanosleep(int *p_ret, unsigned clock_id, int flags, - const void *req_buf, unsigned int req_buf_size, - const void *rem_buf, unsigned int rem_buf_size); +int +ocall_clock_gettime(int *p_ret, unsigned clock_id, void *tp_buf, + unsigned int tp_buf_size); +int +ocall_clock_getres(int *p_ret, int clock_id, void *res_buf, + unsigned int res_buf_size); +int +ocall_utimensat(int *p_ret, int dirfd, const char *pathname, + const void *times_buf, unsigned int times_buf_size, int flags); +int +ocall_futimens(int *p_ret, int fd, const void *times_buf, + unsigned int times_buf_size); +int +ocall_clock_nanosleep(int *p_ret, unsigned clock_id, int flags, + const void *req_buf, unsigned int req_buf_size, + const void *rem_buf, unsigned int rem_buf_size); uint64 os_time_get_boot_microsecond() @@ -30,12 +34,13 @@ os_time_get_boot_microsecond() #ifndef SGX_DISABLE_WASI -int clock_getres(int clock_id, struct timespec *res) +int +clock_getres(int clock_id, struct timespec *res) { int ret; - if (ocall_clock_getres(&ret, clock_id, (void *)res, - sizeof(struct timespec)) != SGX_SUCCESS) { + if (ocall_clock_getres(&ret, clock_id, (void *)res, sizeof(struct timespec)) + != SGX_SUCCESS) { TRACE_OCALL_FAIL(); return -1; } @@ -46,12 +51,13 @@ int clock_getres(int clock_id, struct timespec *res) return ret; } -int clock_gettime(clockid_t clock_id, struct timespec *tp) +int +clock_gettime(clockid_t clock_id, struct timespec *tp) { int ret; - if(ocall_clock_gettime(&ret, clock_id, (void *)tp, - sizeof(struct timespec)) != SGX_SUCCESS) { + if (ocall_clock_gettime(&ret, clock_id, (void *)tp, sizeof(struct timespec)) + != SGX_SUCCESS) { TRACE_OCALL_FAIL(); return -1; } @@ -62,14 +68,15 @@ int clock_gettime(clockid_t clock_id, struct timespec *tp) return ret; } -int utimensat(int dirfd, const char *pathname, - const struct timespec times[2], int flags) +int +utimensat(int dirfd, const char *pathname, const struct timespec times[2], + int flags) { int ret; if (ocall_utimensat(&ret, dirfd, pathname, (void *)times, - sizeof(struct timespec) * 2, - flags) != SGX_SUCCESS) { + sizeof(struct timespec) * 2, flags) + != SGX_SUCCESS) { TRACE_OCALL_FAIL(); return -1; } @@ -80,12 +87,13 @@ int utimensat(int dirfd, const char *pathname, return ret; } -int futimens(int fd, const struct timespec times[2]) +int +futimens(int fd, const struct timespec times[2]) { int ret; - if (ocall_futimens(&ret, fd, (void *)times, - sizeof(struct timespec) * 2) != SGX_SUCCESS) { + if (ocall_futimens(&ret, fd, (void *)times, sizeof(struct timespec) * 2) + != SGX_SUCCESS) { TRACE_OCALL_FAIL(); return -1; } @@ -96,16 +104,16 @@ int futimens(int fd, const struct timespec times[2]) return ret; } -int clock_nanosleep(clockid_t clock_id, int flags, - const struct timespec *request, - struct timespec *remain) +int +clock_nanosleep(clockid_t clock_id, int flags, const struct timespec *request, + struct timespec *remain) { int ret; if (ocall_clock_nanosleep(&ret, clock_id, flags, (void *)request, - sizeof(struct timespec), - (void *)remain, - sizeof(struct timespec)) != SGX_SUCCESS) { + sizeof(struct timespec), (void *)remain, + sizeof(struct timespec)) + != SGX_SUCCESS) { TRACE_OCALL_FAIL(); return -1; } @@ -117,4 +125,3 @@ int clock_nanosleep(clockid_t clock_id, int flags, } #endif - diff --git a/core/shared/platform/linux-sgx/sgx_time.h b/core/shared/platform/linux-sgx/sgx_time.h index 2aa83b8c58..8267f1fa50 100644 --- a/core/shared/platform/linux-sgx/sgx_time.h +++ b/core/shared/platform/linux-sgx/sgx_time.h @@ -10,12 +10,12 @@ extern "C" { #endif -#define CLOCK_REALTIME 0 -#define CLOCK_MONOTONIC 1 +#define CLOCK_REALTIME 0 +#define CLOCK_MONOTONIC 1 #define CLOCK_PROCESS_CPUTIME_ID 2 -#define CLOCK_THREAD_CPUTIME_ID 3 +#define CLOCK_THREAD_CPUTIME_ID 3 -#define UTIME_NOW 0x3fffffff +#define UTIME_NOW 0x3fffffff #define UTIME_OMIT 0x3ffffffe #define TIMER_ABSTIME 1 @@ -28,20 +28,23 @@ struct timespec { long tv_nsec; }; -int clock_getres(int clock_id, struct timespec *res); +int +clock_getres(int clock_id, struct timespec *res); -int clock_gettime(clockid_t clock_id, struct timespec *tp); +int +clock_gettime(clockid_t clock_id, struct timespec *tp); -int utimensat(int dirfd, const char *pathname, - const struct timespec times[2], int flags); -int futimens(int fd, const struct timespec times[2]); -int clock_nanosleep(clockid_t clock_id, int flags, - const struct timespec *request, - struct timespec *remain); +int +utimensat(int dirfd, const char *pathname, const struct timespec times[2], + int flags); +int +futimens(int fd, const struct timespec times[2]); +int +clock_nanosleep(clockid_t clock_id, int flags, const struct timespec *request, + struct timespec *remain); #ifdef __cplusplus } #endif #endif /* end of _SGX_TIME_H */ - diff --git a/core/shared/platform/linux-sgx/untrusted/file.c b/core/shared/platform/linux-sgx/untrusted/file.c index 6852f222f2..4da4be2d3f 100644 --- a/core/shared/platform/linux-sgx/untrusted/file.c +++ b/core/shared/platform/linux-sgx/untrusted/file.c @@ -19,8 +19,8 @@ #include #include -int ocall_open(const char *pathname, int flags, - bool has_mode, unsigned mode) +int +ocall_open(const char *pathname, int flags, bool has_mode, unsigned mode) { if (has_mode) { return open(pathname, flags, (mode_t)mode); @@ -30,9 +30,9 @@ int ocall_open(const char *pathname, int flags, } } -int ocall_openat(int dirfd, - const char *pathname, int flags, - bool has_mode, unsigned mode) +int +ocall_openat(int dirfd, const char *pathname, int flags, bool has_mode, + unsigned mode) { if (has_mode) { return openat(dirfd, pathname, flags, (mode_t)mode); @@ -42,12 +42,14 @@ int ocall_openat(int dirfd, } } -int ocall_close(int fd) +int +ocall_close(int fd) { return close(fd); } -ssize_t ocall_read(int fd, void *buf, size_t read_size) +ssize_t +ocall_read(int fd, void *buf, size_t read_size) { if (buf != NULL) { return read(fd, buf, read_size); @@ -57,45 +59,53 @@ ssize_t ocall_read(int fd, void *buf, size_t read_size) } } -off_t ocall_lseek(int fd, off_t offset, int whence) +off_t +ocall_lseek(int fd, off_t offset, int whence) { return lseek(fd, offset, whence); } -int ocall_ftruncate(int fd, off_t length) +int +ocall_ftruncate(int fd, off_t length) { return ftruncate(fd, length); } -int ocall_fsync(int fd) +int +ocall_fsync(int fd) { return fsync(fd); } -int ocall_fdatasync(int fd) +int +ocall_fdatasync(int fd) { return fdatasync(fd); } -int ocall_isatty(int fd) +int +ocall_isatty(int fd) { return isatty(fd); } -void ocall_fdopendir(int fd, void **dirp) +void +ocall_fdopendir(int fd, void **dirp) { if (dirp) { *(DIR **)dirp = fdopendir(fd); } } -void *ocall_readdir(void *dirp) +void * +ocall_readdir(void *dirp) { DIR *p_dirp = (DIR *)dirp; return readdir(p_dirp); } -void ocall_rewinddir(void *dirp) +void +ocall_rewinddir(void *dirp) { DIR *p_dirp = (DIR *)dirp; if (p_dirp) { @@ -103,7 +113,8 @@ void ocall_rewinddir(void *dirp) } } -void ocall_seekdir(void *dirp, long loc) +void +ocall_seekdir(void *dirp, long loc) { DIR *p_dirp = (DIR *)dirp; @@ -112,7 +123,8 @@ void ocall_seekdir(void *dirp, long loc) } } -long ocall_telldir(void *dirp) +long +ocall_telldir(void *dirp) { DIR *p_dirp = (DIR *)dirp; if (p_dirp) { @@ -121,7 +133,8 @@ long ocall_telldir(void *dirp) return -1; } -int ocall_closedir(void* dirp) +int +ocall_closedir(void *dirp) { DIR *p_dirp = (DIR *)dirp; if (p_dirp) { @@ -130,82 +143,91 @@ int ocall_closedir(void* dirp) return -1; } -int ocall_stat(const char *pathname, - void *buf, unsigned int buf_len) +int +ocall_stat(const char *pathname, void *buf, unsigned int buf_len) { return stat(pathname, (struct stat *)buf); } -int ocall_fstat(int fd, void *buf, unsigned int buf_len) +int +ocall_fstat(int fd, void *buf, unsigned int buf_len) { return fstat(fd, (struct stat *)buf); } -int ocall_fstatat(int dirfd, const char *pathname, void *buf, - unsigned int buf_len, int flags) +int +ocall_fstatat(int dirfd, const char *pathname, void *buf, unsigned int buf_len, + int flags) { return fstatat(dirfd, pathname, (struct stat *)buf, flags); } -int ocall_mkdirat(int dirfd, const char *pathname, unsigned mode) +int +ocall_mkdirat(int dirfd, const char *pathname, unsigned mode) { return mkdirat(dirfd, pathname, (mode_t)mode); } -int ocall_link(const char *oldpath, const char *newpath) +int +ocall_link(const char *oldpath, const char *newpath) { return link(oldpath, newpath); } -int ocall_linkat(int olddirfd, const char *oldpath, - int newdirfd, const char *newpath, int flags) +int +ocall_linkat(int olddirfd, const char *oldpath, int newdirfd, + const char *newpath, int flags) { return linkat(olddirfd, oldpath, newdirfd, newpath, flags); } -int ocall_unlinkat(int dirfd, const char *pathname, int flags) +int +ocall_unlinkat(int dirfd, const char *pathname, int flags) { return unlinkat(dirfd, pathname, flags); } -ssize_t ocall_readlinkat(int dirfd, const char *pathname, - char *buf, size_t bufsiz) +ssize_t +ocall_readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz) { return readlinkat(dirfd, pathname, buf, bufsiz); } -int ocall_renameat(int olddirfd, const char *oldpath, - int newdirfd, const char *newpath) +int +ocall_renameat(int olddirfd, const char *oldpath, int newdirfd, + const char *newpath) { return renameat(olddirfd, oldpath, newdirfd, newpath); } -int ocall_symlinkat(const char *target, int newdirfd, - const char *linkpath) +int +ocall_symlinkat(const char *target, int newdirfd, const char *linkpath) { return symlinkat(target, newdirfd, linkpath); } -int ocall_ioctl(int fd, unsigned long request, - void *arg, unsigned int arg_len) +int +ocall_ioctl(int fd, unsigned long request, void *arg, unsigned int arg_len) { /* support just int *arg temporally */ return ioctl(fd, request, (int *)arg); } -int ocall_fcntl(int fd, int cmd) +int +ocall_fcntl(int fd, int cmd) { - return fcntl(fd, cmd); + return fcntl(fd, cmd); } -int ocall_fcntl_long(int fd, int cmd, long arg) +int +ocall_fcntl_long(int fd, int cmd, long arg) { - return fcntl(fd, cmd, arg); + return fcntl(fd, cmd, arg); } -ssize_t ocall_readv(int fd, char *iov_buf, - unsigned int buf_size, int iovcnt, - bool has_offset, off_t offset) +ssize_t +ocall_readv(int fd, char *iov_buf, unsigned int buf_size, int iovcnt, + bool has_offset, off_t offset) { struct iovec *iov = (struct iovec *)iov_buf; ssize_t ret; @@ -223,9 +245,9 @@ ssize_t ocall_readv(int fd, char *iov_buf, return ret; } -ssize_t ocall_writev(int fd, char *iov_buf, - unsigned int buf_size, int iovcnt, - bool has_offset, off_t offset) +ssize_t +ocall_writev(int fd, char *iov_buf, unsigned int buf_size, int iovcnt, + bool has_offset, off_t offset) { struct iovec *iov = (struct iovec *)iov_buf; int i; @@ -243,9 +265,10 @@ ssize_t ocall_writev(int fd, char *iov_buf, return ret; } -int ocall_realpath(const char *path, char *buf, unsigned int buf_len) +int +ocall_realpath(const char *path, char *buf, unsigned int buf_len) { - char* val = NULL; + char *val = NULL; val = realpath(path, buf); if (val != NULL) { return 0; @@ -253,47 +276,53 @@ int ocall_realpath(const char *path, char *buf, unsigned int buf_len) return -1; } -int ocall_posix_fallocate(int fd, off_t offset, off_t len) +int +ocall_posix_fallocate(int fd, off_t offset, off_t len) { return posix_fallocate(fd, offset, len); } -int ocall_poll(void *fds, unsigned nfds, int timeout, - unsigned int fds_len) +int +ocall_poll(void *fds, unsigned nfds, int timeout, unsigned int fds_len) { return poll((struct pollfd *)fds, (nfds_t)nfds, timeout); } -int ocall_getopt(int argc, char *argv_buf, unsigned int argv_buf_len, - const char *optstring) +int +ocall_getopt(int argc, char *argv_buf, unsigned int argv_buf_len, + const char *optstring) { int ret; int i; char **argv = (char **)argv_buf; - for (i=0; i < argc; i++) { + for (i = 0; i < argc; i++) { argv[i] = argv_buf + (uintptr_t)argv[i]; } return getopt(argc, argv, optstring); } -ssize_t ocall_getrandom(void *buf, size_t buflen, unsigned int flags) +ssize_t +ocall_getrandom(void *buf, size_t buflen, unsigned int flags) { return getrandom(buf, buflen, flags); } -int ocall_getentropy(void *buffer, size_t length) +int +ocall_getentropy(void *buffer, size_t length) { return getentropy(buffer, length); } -int ocall_sched_yield() +int +ocall_sched_yield() { return sched_yield(); } -int ocall_get_errno() +int +ocall_get_errno() { return errno; } diff --git a/core/shared/platform/linux-sgx/untrusted/pthread.c b/core/shared/platform/linux-sgx/untrusted/pthread.c index f3026874db..890ef754c5 100644 --- a/core/shared/platform/linux-sgx/untrusted/pthread.c +++ b/core/shared/platform/linux-sgx/untrusted/pthread.c @@ -6,7 +6,8 @@ #include #include -int ocall_pthread_rwlock_init(void **rwlock, void *attr) +int +ocall_pthread_rwlock_init(void **rwlock, void *attr) { int ret = 0; @@ -15,7 +16,7 @@ int ocall_pthread_rwlock_init(void **rwlock, void *attr) return -1; ret = pthread_rwlock_init((pthread_rwlock_t *)*rwlock, NULL); - if (ret != 0) { + if (ret != 0) { free(*rwlock); *rwlock = NULL; } @@ -23,7 +24,8 @@ int ocall_pthread_rwlock_init(void **rwlock, void *attr) return ret; } -int ocall_pthread_rwlock_destroy(void *rwlock) +int +ocall_pthread_rwlock_destroy(void *rwlock) { pthread_rwlock_t *lock = (pthread_rwlock_t *)rwlock; int ret; @@ -33,18 +35,20 @@ int ocall_pthread_rwlock_destroy(void *rwlock) return ret; } -int ocall_pthread_rwlock_rdlock(void *rwlock) +int +ocall_pthread_rwlock_rdlock(void *rwlock) { return pthread_rwlock_rdlock((pthread_rwlock_t *)rwlock); } -int ocall_pthread_rwlock_wrlock(void *rwlock) +int +ocall_pthread_rwlock_wrlock(void *rwlock) { return pthread_rwlock_wrlock((pthread_rwlock_t *)rwlock); } -int ocall_pthread_rwlock_unlock(void *rwlock) +int +ocall_pthread_rwlock_unlock(void *rwlock) { return pthread_rwlock_unlock((pthread_rwlock_t *)rwlock); } - diff --git a/core/shared/platform/linux-sgx/untrusted/signal.c b/core/shared/platform/linux-sgx/untrusted/signal.c index 115fbfa564..b2eecfb7ad 100644 --- a/core/shared/platform/linux-sgx/untrusted/signal.c +++ b/core/shared/platform/linux-sgx/untrusted/signal.c @@ -4,7 +4,8 @@ */ #include -int ocall_raise(int sig) +int +ocall_raise(int sig) { return raise(sig); } \ No newline at end of file diff --git a/core/shared/platform/linux-sgx/untrusted/socket.c b/core/shared/platform/linux-sgx/untrusted/socket.c index 34b5d460e1..08d884bb57 100644 --- a/core/shared/platform/linux-sgx/untrusted/socket.c +++ b/core/shared/platform/linux-sgx/untrusted/socket.c @@ -7,20 +7,21 @@ #include #include -int ocall_socket(int domain, int type, int protocol) +int +ocall_socket(int domain, int type, int protocol) { return socket(domain, type, protocol); } -int ocall_getsockopt(int sockfd, int level, int optname, void *val_buf, - unsigned int val_buf_size, void *len_buf) +int +ocall_getsockopt(int sockfd, int level, int optname, void *val_buf, + unsigned int val_buf_size, void *len_buf) { - return getsockopt(sockfd, level, optname, val_buf, - (socklen_t *)len_buf); + return getsockopt(sockfd, level, optname, val_buf, (socklen_t *)len_buf); } -ssize_t ocall_sendmsg(int sockfd, void *msg_buf, - unsigned int msg_buf_size, int flags) +ssize_t +ocall_sendmsg(int sockfd, void *msg_buf, unsigned int msg_buf_size, int flags) { struct msghdr *msg = (struct msghdr *)msg_buf; int i; @@ -35,16 +36,16 @@ ssize_t ocall_sendmsg(int sockfd, void *msg_buf, if (msg->msg_iov != NULL) { msg->msg_iov = msg_buf + (unsigned)(uintptr_t)msg->msg_iov; for (i = 0; i < msg->msg_iovlen; i++) { - msg->msg_iov[i].iov_base = msg_buf + (unsigned)(uintptr_t) - msg->msg_iov[i].iov_base; + msg->msg_iov[i].iov_base = + msg_buf + (unsigned)(uintptr_t)msg->msg_iov[i].iov_base; } } return sendmsg(sockfd, msg, flags); } -ssize_t ocall_recvmsg(int sockfd, void *msg_buf, unsigned int msg_buf_size, - int flags) +ssize_t +ocall_recvmsg(int sockfd, void *msg_buf, unsigned int msg_buf_size, int flags) { struct msghdr *msg = (struct msghdr *)msg_buf; int i; @@ -58,16 +59,17 @@ ssize_t ocall_recvmsg(int sockfd, void *msg_buf, unsigned int msg_buf_size, if (msg->msg_iov != NULL) { msg->msg_iov = msg_buf + (unsigned)(uintptr_t)msg->msg_iov; - for (i = 0; i msg_iovlen; i++) { - msg->msg_iov[i].iov_base = msg_buf + (unsigned)(uintptr_t) - msg->msg_iov[i].iov_base; + for (i = 0; i < msg->msg_iovlen; i++) { + msg->msg_iov[i].iov_base = + msg_buf + (unsigned)(uintptr_t)msg->msg_iov[i].iov_base; } } return recvmsg(sockfd, msg, flags); } -int ocall_shutdown(int sockfd, int how) +int +ocall_shutdown(int sockfd, int how) { return shutdown(sockfd, how); } \ No newline at end of file diff --git a/core/shared/platform/linux-sgx/untrusted/time.c b/core/shared/platform/linux-sgx/untrusted/time.c index 1d15e8dfd3..5fa387b0cd 100644 --- a/core/shared/platform/linux-sgx/untrusted/time.c +++ b/core/shared/platform/linux-sgx/untrusted/time.c @@ -7,41 +7,38 @@ #include #include - /** time clock **/ -int ocall_clock_gettime(unsigned clock_id, void *tp_buf, - unsigned int tp_buf_size) +int +ocall_clock_gettime(unsigned clock_id, void *tp_buf, unsigned int tp_buf_size) { - return clock_gettime((clockid_t)clock_id, - (struct timespec *)tp_buf); + return clock_gettime((clockid_t)clock_id, (struct timespec *)tp_buf); } -int ocall_clock_getres(int clock_id, void *res_buf, - unsigned int res_buf_size) +int +ocall_clock_getres(int clock_id, void *res_buf, unsigned int res_buf_size) { return clock_getres(clock_id, (struct timespec *)res_buf); } -int ocall_utimensat(int dirfd, const char *pathname, - const void *times_buf, - unsigned int times_buf_size, int flags) +int +ocall_utimensat(int dirfd, const char *pathname, const void *times_buf, + unsigned int times_buf_size, int flags) { return utimensat(dirfd, pathname, (struct timespec *)times_buf, flags); - } -int ocall_futimens(int fd, const void *times_buf, - unsigned int times_buf_size) +int +ocall_futimens(int fd, const void *times_buf, unsigned int times_buf_size) { return futimens(fd, (struct timespec *)times_buf); } -int ocall_clock_nanosleep(unsigned clock_id, int flags, - const void *req_buf, unsigned int req_buf_size, - const void *rem_buf, unsigned int rem_buf_size) +int +ocall_clock_nanosleep(unsigned clock_id, int flags, const void *req_buf, + unsigned int req_buf_size, const void *rem_buf, + unsigned int rem_buf_size) { return clock_nanosleep((clockid_t)clock_id, flags, (struct timespec *)req_buf, (struct timespec *)rem_buf); - } diff --git a/core/shared/platform/linux/platform_init.c b/core/shared/platform/linux/platform_init.c index 17aeb8baab..2aae13fa14 100644 --- a/core/shared/platform/linux/platform_init.c +++ b/core/shared/platform/linux/platform_init.c @@ -13,8 +13,7 @@ bh_platform_init() void bh_platform_destroy() -{ -} +{} int os_printf(const char *format, ...) @@ -42,4 +41,3 @@ os_vprintf(const char *format, va_list ap) return BH_VPRINTF(format, ap); #endif } - diff --git a/core/shared/platform/linux/platform_internal.h b/core/shared/platform/linux/platform_internal.h index 3e5c7e3f06..58b6a6ad24 100644 --- a/core/shared/platform/linux/platform_internal.h +++ b/core/shared/platform/linux/platform_internal.h @@ -59,10 +59,8 @@ typedef pthread_t korp_thread; #define os_thread_local_attribute __thread #if WASM_DISABLE_HW_BOUND_CHECK == 0 -#if defined(BUILD_TARGET_X86_64) \ - || defined(BUILD_TARGET_AMD_64) \ - || defined(BUILD_TARGET_AARCH64) \ - || defined(BUILD_TARGET_RISCV64_LP64D) \ +#if defined(BUILD_TARGET_X86_64) || defined(BUILD_TARGET_AMD_64) \ + || defined(BUILD_TARGET_AARCH64) || defined(BUILD_TARGET_RISCV64_LP64D) \ || defined(BUILD_TARGET_RISCV64_LP64) #include @@ -79,15 +77,20 @@ typedef jmp_buf korp_jmpbuf; typedef void (*os_signal_handler)(void *sig_addr); -int os_thread_signal_init(os_signal_handler handler); +int +os_thread_signal_init(os_signal_handler handler); -void os_thread_signal_destroy(); +void +os_thread_signal_destroy(); -bool os_thread_signal_inited(); +bool +os_thread_signal_inited(); -void os_signal_unmask(); +void +os_signal_unmask(); -void os_sigreturn(); +void +os_sigreturn(); #endif /* end of BUILD_TARGET_X86_64/AMD_64/AARCH64/RISCV64 */ #endif /* end of WASM_DISABLE_HW_BOUND_CHECK */ @@ -96,4 +99,3 @@ void os_sigreturn(); #endif #endif /* end of _PLATFORM_INTERNAL_H */ - diff --git a/core/shared/platform/nuttx/platform_internal.h b/core/shared/platform/nuttx/platform_internal.h index 14e44ad4eb..a4a2b69712 100644 --- a/core/shared/platform/nuttx/platform_internal.h +++ b/core/shared/platform/nuttx/platform_internal.h @@ -38,7 +38,7 @@ typedef pthread_t korp_thread; /* Default thread priority */ #define BH_THREAD_DEFAULT_PRIORITY 100 -#define os_printf printf +#define os_printf printf #define os_vprintf vprintf /* On NuttX, time_t is uint32_t */ diff --git a/core/shared/platform/riot/platform_internal.h b/core/shared/platform/riot/platform_internal.h index 91d08cfe7f..0de7dfdd57 100644 --- a/core/shared/platform/riot/platform_internal.h +++ b/core/shared/platform/riot/platform_internal.h @@ -7,12 +7,12 @@ #ifndef _PLATFORM_INTERNAL_H #define _PLATFORM_INTERNAL_H -//Riot includes core +/* Riot includes core */ #include #include #include -//Riot includes sys +/* Riot includes sys */ #include #include @@ -39,19 +39,20 @@ typedef thread_t korp_thread; typedef kernel_pid_t korp_tid; typedef mutex_t korp_mutex; -// typedef sema_t korp_sem; +/* typedef sema_t korp_sem; */ struct os_thread_wait_node; typedef struct os_thread_wait_node *os_thread_wait_list; typedef struct korp_cond { - mutex_t wait_list_lock; - os_thread_wait_list thread_wait_list; + mutex_t wait_list_lock; + os_thread_wait_list thread_wait_list; } korp_cond; -#define os_printf printf +#define os_printf printf #define os_vprintf vprintf #if WA_MATH +/* clang-format off */ /* math functions which are not provided by os*/ double sqrt(double x); double floor(double x); @@ -69,7 +70,7 @@ float rintf(float x); float truncf(float x); int signbit(double x); int isnan(double x); +/* clang-format on */ #endif #endif /* end of _BH_PLATFORM_H */ - diff --git a/core/shared/platform/riot/riot_thread.c b/core/shared/platform/riot/riot_thread.c index e324a9d054..e103a0965a 100644 --- a/core/shared/platform/riot/riot_thread.c +++ b/core/shared/platform/riot/riot_thread.c @@ -9,19 +9,21 @@ #include +/* clang-format off */ #define bh_assert(v) do { \ if (!(v)) { \ printf("\nASSERTION FAILED: %s, at %s, line %d\n", \ #v, __FILE__, __LINE__); \ - core_panic(0,0/*expr_string*/); \ + core_panic(0, 0/*expr_string*/); \ while (1); \ } \ - } while (0) +} while (0) +/* clang-format on */ struct os_thread_data; typedef struct os_thread_wait_node { sema_t sem; - void * ret; + void *ret; os_thread_wait_list next; } os_thread_wait_node; @@ -63,7 +65,8 @@ static mutex_t thread_data_lock; /* Thread data list */ static os_thread_data *thread_data_list = NULL; -static void thread_data_list_add(os_thread_data *thread_data) +static void +thread_data_list_add(os_thread_data *thread_data) { mutex_lock(&thread_data_lock); if (!thread_data_list) @@ -86,7 +89,8 @@ static void thread_data_list_add(os_thread_data *thread_data) mutex_unlock(&thread_data_lock); } -static void thread_data_list_remove(os_thread_data *thread_data) +static void +thread_data_list_remove(os_thread_data *thread_data) { mutex_lock(&thread_data_lock); if (thread_data_list) { @@ -153,7 +157,7 @@ thread_data_current() static void os_thread_cleanup(void) { - //TODO Check this (Join sema trigger, cleanup of thread_data) + // TODO Check this (Join sema trigger, cleanup of thread_data) os_thread_data *thread_data = thread_data_current(); bh_assert(thread_data != NULL); mutex_lock(&thread_data->wait_list_lock); @@ -177,7 +181,7 @@ static void * os_thread_wrapper(void *thread_data) { /* Set thread custom data */ - os_thread_data * t = (os_thread_data*) thread_data; + os_thread_data *t = (os_thread_data *)thread_data; t->tid = thread_getpid(); thread_data_list_add(t); @@ -187,13 +191,13 @@ os_thread_wrapper(void *thread_data) os_thread_cleanup(); // internal structures and joiners BH_FREE(thread_data); - sched_task_exit();// stop thread //clean - return NULL; //never reached + sched_task_exit(); // stop thread //clean + return NULL; // never reached } int -os_thread_create(korp_tid *p_tid, thread_start_routine_t start, - void *arg, unsigned int stack_size) +os_thread_create(korp_tid *p_tid, thread_start_routine_t start, void *arg, + unsigned int stack_size) { return os_thread_create_with_prio(p_tid, start, arg, stack_size, BH_THREAD_DEFAULT_PRIORITY); @@ -223,8 +227,8 @@ os_thread_create_with_prio(korp_tid *p_tid, thread_start_routine_t start, thread_data->arg = arg; /* Create the thread &*/ - if (!((tid = thread_create( thread_data->stack, - stack_size,prio,0, os_thread_wrapper, thread_data,"WASM")))) { + if (!((tid = thread_create(thread_data->stack, stack_size, prio, 0, + os_thread_wrapper, thread_data, "WASM")))) { BH_FREE(thread_data); return BHT_ERROR; } @@ -240,15 +244,14 @@ os_thread_create_with_prio(korp_tid *p_tid, thread_start_routine_t start, korp_tid os_self_thread() { - return (korp_tid) thread_getpid(); + return (korp_tid)thread_getpid(); } int -os_thread_join (korp_tid thread, void **value_ptr) +os_thread_join(korp_tid thread, void **value_ptr) { // will test if thread is still working, // wait if it is -// (void) value_ptr; os_thread_data *thread_data; os_thread_wait_node node; @@ -257,8 +260,8 @@ os_thread_join (korp_tid thread, void **value_ptr) /* Get thread data */ thread_data = thread_data_list_lookup(thread); - if(thread_data == NULL){ - //thread not found + if (thread_data == NULL) { + // thread not found sema_destroy(&node.sem); return BHT_ERROR; } @@ -277,22 +280,21 @@ os_thread_join (korp_tid thread, void **value_ptr) mutex_unlock(&thread_data->wait_list_lock); sema_wait(&node.sem); - //get the return value pointer conted may not be availible after return - if(value_ptr) (* value_ptr) = node.ret; + // get the return value pointer conted may not be availible after return + if (value_ptr) + (*value_ptr) = node.ret; /* Wait some time for the thread to be actually terminated */ -// TODO: k_sleep(100); + // TODO: k_sleep(100); - //TODO: bump target prio to make it finish and free its resources + // TODO: bump target prio to make it finish and free its resources thread_yield(); - //node has done its job + // node has done its job sema_destroy(&node.sem); return BHT_OK; } - - // int vm_mutex_trylock(korp_mutex *mutex) // { // return mutex_trylock(mutex); @@ -308,7 +310,7 @@ os_mutex_init(korp_mutex *mutex) int os_mutex_destroy(korp_mutex *mutex) { - (void) mutex; + (void)mutex; return BHT_OK; } @@ -316,15 +318,14 @@ int os_mutex_lock(korp_mutex *mutex) { mutex_lock(mutex); - return 0; //Riot mutexes do not return until success + return 0; // Riot mutexes do not return until success } int os_mutex_unlock(korp_mutex *mutex) { mutex_unlock(mutex); - return 0; //Riot mutexes do not return until success - + return 0; // Riot mutexes do not return until success } int @@ -338,13 +339,13 @@ os_cond_init(korp_cond *cond) int os_cond_destroy(korp_cond *cond) { - (void) cond; + (void)cond; return BHT_OK; } static int -os_cond_wait_internal(korp_cond *cond, korp_mutex *mutex, - bool timed, uint64 useconds) +os_cond_wait_internal(korp_cond *cond, korp_mutex *mutex, bool timed, + uint64 useconds) { os_thread_wait_node *node; @@ -369,10 +370,10 @@ os_cond_wait_internal(korp_cond *cond, korp_mutex *mutex, /* Unlock mutex, wait sem and lock mutex again */ mutex_unlock(mutex); - if(timed) + if (timed) sema_wait(&node->sem); else - sema_wait_timed(&node->sem,useconds); + sema_wait_timed(&node->sem, useconds); mutex_lock(mutex); /* Remove wait node from wait list */ @@ -401,8 +402,8 @@ os_cond_wait(korp_cond *cond, korp_mutex *mutex) int os_cond_reltimedwait(korp_cond *cond, korp_mutex *mutex, uint64 useconds) { - return os_cond_wait_internal(cond, mutex, - (useconds != BHT_WAIT_FOREVER), useconds); + return os_cond_wait_internal(cond, mutex, (useconds != BHT_WAIT_FOREVER), + useconds); } int @@ -417,11 +418,12 @@ os_cond_signal(korp_cond *cond) return BHT_OK; } -uint8 *os_thread_get_stack_boundary() +uint8 * +os_thread_get_stack_boundary() { #if defined(DEVELHELP) || defined(SCHED_TEST_STACK) \ || defined(MODULE_MPU_STACK_GUARD) - return (uint8*)thread_get_active()->stack_start; + return (uint8 *)thread_get_active()->stack_start; #else return NULL; #endif diff --git a/core/shared/platform/riot/riot_time.c b/core/shared/platform/riot/riot_time.c index 8b480f69c7..24bc18416a 100644 --- a/core/shared/platform/riot/riot_time.c +++ b/core/shared/platform/riot/riot_time.c @@ -12,4 +12,3 @@ os_time_get_boot_microsecond() { return xtimer_now_usec64(); } - diff --git a/core/shared/platform/rt-thread/platform_internal.h b/core/shared/platform/rt-thread/platform_internal.h index 9fe1c9c616..4fc29e946a 100644 --- a/core/shared/platform/rt-thread/platform_internal.h +++ b/core/shared/platform/rt-thread/platform_internal.h @@ -44,5 +44,4 @@ typedef rt_int16_t int16_t; typedef rt_uint64_t uint64_t; typedef rt_int64_t int64_t; - -#endif //RTTHREAD_PLATFORM_INTERNAL_H +#endif /* RTTHREAD_PLATFORM_INTERNAL_H */ diff --git a/core/shared/platform/rt-thread/rtt_platform.c b/core/shared/platform/rt-thread/rtt_platform.c index 493d766ca2..13eb439863 100644 --- a/core/shared/platform/rt-thread/rtt_platform.c +++ b/core/shared/platform/rt-thread/rtt_platform.c @@ -8,67 +8,65 @@ #include typedef struct os_malloc_list { - void* real; - void* used; + void *real; + void *used; rt_list_t node; -}os_malloc_list_t; +} os_malloc_list_t; -int bh_platform_init(void) +int +bh_platform_init(void) { return 0; } -void bh_platform_destroy(void) -{ -} +void +bh_platform_destroy(void) +{} -void *os_malloc(unsigned size) +void * +os_malloc(unsigned size) { void *buf_origin; void *buf_fixed; rt_ubase_t *addr_field; buf_origin = rt_malloc(size + 8 + sizeof(rt_ubase_t)); - buf_fixed = buf_origin + sizeof(void*); - if ((rt_ubase_t)buf_fixed & 0x7) - { - buf_fixed = (void*)((rt_ubase_t)(buf_fixed+8)&(~7)); + buf_fixed = buf_origin + sizeof(void *); + if ((rt_ubase_t)buf_fixed & 0x7) { + buf_fixed = (void *)((rt_ubase_t)(buf_fixed + 8) & (~7)); } addr_field = buf_fixed - sizeof(rt_ubase_t); - *addr_field = (rt_ubase_t )buf_origin; + *addr_field = (rt_ubase_t)buf_origin; return buf_fixed; - } -void *os_realloc(void *ptr, unsigned size) +void * +os_realloc(void *ptr, unsigned size) { - void* mem_origin; - void* mem_new; + void *mem_origin; + void *mem_new; void *mem_new_fixed; rt_ubase_t *addr_field; - if (!ptr) - { + if (!ptr) { return RT_NULL; } addr_field = ptr - sizeof(rt_ubase_t); - mem_origin = (void*)(*addr_field); + mem_origin = (void *)(*addr_field); mem_new = rt_realloc(mem_origin, size + 8 + sizeof(rt_ubase_t)); - if (mem_origin != mem_new) - { + if (mem_origin != mem_new) { mem_new_fixed = mem_new + sizeof(rt_ubase_t); - if ((rt_ubase_t)mem_new_fixed & 0x7) - { - mem_new_fixed = (void*)((rt_ubase_t)(mem_new_fixed+8)&(~7)); + if ((rt_ubase_t)mem_new_fixed & 0x7) { + mem_new_fixed = (void *)((rt_ubase_t)(mem_new_fixed + 8) & (~7)); } addr_field = mem_new_fixed - sizeof(rt_ubase_t); - *addr_field = (rt_ubase_t )mem_new; + *addr_field = (rt_ubase_t)mem_new; return mem_new_fixed; } @@ -76,115 +74,130 @@ void *os_realloc(void *ptr, unsigned size) return ptr; } -void os_free(void *ptr) +void +os_free(void *ptr) { - void* mem_origin; + void *mem_origin; rt_ubase_t *addr_field; - if (ptr) - { + if (ptr) { addr_field = ptr - sizeof(rt_ubase_t); - mem_origin = (void*)(*addr_field); + mem_origin = (void *)(*addr_field); rt_free(mem_origin); } - } - static char wamr_vprint_buf[RT_CONSOLEBUF_SIZE * 2]; -int os_printf(const char *format, ...) + +int +os_printf(const char *format, ...) { va_list ap; va_start(ap, format); - rt_size_t len = vsnprintf(wamr_vprint_buf, sizeof(wamr_vprint_buf)-1, format, ap); + rt_size_t len = + vsnprintf(wamr_vprint_buf, sizeof(wamr_vprint_buf) - 1, format, ap); wamr_vprint_buf[len] = 0x00; rt_kputs(wamr_vprint_buf); va_end(ap); return 0; } -int os_vprintf(const char *format, va_list ap) +int +os_vprintf(const char *format, va_list ap) { - rt_size_t len = vsnprintf(wamr_vprint_buf, sizeof(wamr_vprint_buf)-1, format, ap); + rt_size_t len = + vsnprintf(wamr_vprint_buf, sizeof(wamr_vprint_buf) - 1, format, ap); wamr_vprint_buf[len] = 0; rt_kputs(wamr_vprint_buf); return 0; } -uint64 os_time_get_boot_microsecond(void) +uint64 +os_time_get_boot_microsecond(void) { - uint64 ret = rt_tick_get()*1000; + uint64 ret = rt_tick_get() * 1000; ret /= RT_TICK_PER_SECOND; return ret; } -korp_tid os_self_thread(void) +korp_tid +os_self_thread(void) { return rt_thread_self(); } -uint8 *os_thread_get_stack_boundary(void) +uint8 * +os_thread_get_stack_boundary(void) { rt_thread_t tid = rt_thread_self(); return tid->stack_addr; } -int os_mutex_init(korp_mutex *mutex) +int +os_mutex_init(korp_mutex *mutex) { return rt_mutex_init(mutex, "wamr0", RT_IPC_FLAG_FIFO); } -int os_mutex_destroy(korp_mutex *mutex) +int +os_mutex_destroy(korp_mutex *mutex) { return rt_mutex_detach(mutex); } -int os_mutex_lock(korp_mutex *mutex) +int +os_mutex_lock(korp_mutex *mutex) { return rt_mutex_take(mutex, RT_WAITING_FOREVER); } -int os_mutex_unlock(korp_mutex *mutex) +int +os_mutex_unlock(korp_mutex *mutex) { return rt_mutex_release(mutex); } - /* * functions below was not implement */ -int os_cond_init(korp_cond *cond) +int +os_cond_init(korp_cond *cond) { return 0; } -int os_cond_destroy(korp_cond *cond) +int +os_cond_destroy(korp_cond *cond) { return 0; } -int os_cond_wait(korp_cond *cond, korp_mutex *mutex) +int +os_cond_wait(korp_cond *cond, korp_mutex *mutex) { return 0; } -void *os_mmap(void *hint, size_t size, int prot, int flags) +void * +os_mmap(void *hint, size_t size, int prot, int flags) { return rt_malloc(size); } -void os_munmap(void *addr, size_t size) +void +os_munmap(void *addr, size_t size) { rt_free(addr); } -int os_mprotect(void *addr, size_t size, int prot) +int +os_mprotect(void *addr, size_t size, int prot) { return 0; } -void os_dcache_flush(void) -{ -} +void +os_dcache_flush(void) +{} diff --git a/core/shared/platform/vxworks/platform_init.c b/core/shared/platform/vxworks/platform_init.c index 17aeb8baab..2aae13fa14 100644 --- a/core/shared/platform/vxworks/platform_init.c +++ b/core/shared/platform/vxworks/platform_init.c @@ -13,8 +13,7 @@ bh_platform_init() void bh_platform_destroy() -{ -} +{} int os_printf(const char *format, ...) @@ -42,4 +41,3 @@ os_vprintf(const char *format, va_list ap) return BH_VPRINTF(format, ap); #endif } - diff --git a/core/shared/platform/vxworks/platform_internal.h b/core/shared/platform/vxworks/platform_internal.h index 56870b56e2..9fa30722c6 100644 --- a/core/shared/platform/vxworks/platform_internal.h +++ b/core/shared/platform/vxworks/platform_internal.h @@ -58,8 +58,7 @@ typedef pthread_t korp_thread; #define os_thread_local_attribute __thread #if WASM_DISABLE_HW_BOUND_CHECK == 0 -#if defined(BUILD_TARGET_X86_64) \ - || defined(BUILD_TARGET_AMD_64) \ +#if defined(BUILD_TARGET_X86_64) || defined(BUILD_TARGET_AMD_64) \ || defined(BUILD_TARGET_AARCH64) #include @@ -76,15 +75,20 @@ typedef jmp_buf korp_jmpbuf; typedef void (*os_signal_handler)(void *sig_addr); -int os_thread_signal_init(os_signal_handler handler); +int +os_thread_signal_init(os_signal_handler handler); -void os_thread_signal_destroy(); +void +os_thread_signal_destroy(); -bool os_thread_signal_inited(); +bool +os_thread_signal_inited(); -void os_signal_unmask(); +void +os_signal_unmask(); -void os_sigreturn(); +void +os_sigreturn(); #endif /* end of BUILD_TARGET_X86_64/AMD_64/AARCH64 */ #endif /* end of WASM_DISABLE_HW_BOUND_CHECK */ @@ -93,4 +97,3 @@ void os_sigreturn(); #endif #endif /* end of _PLATFORM_INTERNAL_H */ - diff --git a/core/shared/platform/windows/platform_init.c b/core/shared/platform/windows/platform_init.c index bdb75f858c..7505e5325e 100644 --- a/core/shared/platform/windows/platform_init.c +++ b/core/shared/platform/windows/platform_init.c @@ -60,6 +60,4 @@ os_getpagesize() void os_dcache_flush(void) -{ -} - +{} diff --git a/core/shared/platform/windows/platform_internal.h b/core/shared/platform/windows/platform_internal.h index 0b6d39638d..5983052715 100644 --- a/core/shared/platform/windows/platform_internal.h +++ b/core/shared/platform/windows/platform_internal.h @@ -53,15 +53,17 @@ typedef struct korp_cond { os_thread_wait_list thread_wait_list; } korp_cond; -unsigned os_getpagesize(); -void *os_mem_commit(void *ptr, size_t size, int flags); -void os_mem_decommit(void *ptr, size_t size); +unsigned +os_getpagesize(); +void * +os_mem_commit(void *ptr, size_t size, int flags); +void +os_mem_decommit(void *ptr, size_t size); #define os_thread_local_attribute __declspec(thread) #if WASM_DISABLE_HW_BOUND_CHECK == 0 -#if defined(BUILD_TARGET_X86_64) \ - || defined(BUILD_TARGET_AMD_64) +#if defined(BUILD_TARGET_X86_64) || defined(BUILD_TARGET_AMD_64) #include @@ -72,11 +74,14 @@ typedef jmp_buf korp_jmpbuf; #define os_setjmp setjmp #define os_longjmp longjmp -int os_thread_signal_init(); +int +os_thread_signal_init(); -void os_thread_signal_destroy(); +void +os_thread_signal_destroy(); -bool os_thread_signal_inited(); +bool +os_thread_signal_inited(); #define os_signal_unmask() (void)0 #define os_sigreturn() (void)0 @@ -89,4 +94,3 @@ bool os_thread_signal_inited(); #endif #endif /* end of _PLATFORM_INTERNAL_H */ - diff --git a/core/shared/platform/windows/win_malloc.c b/core/shared/platform/windows/win_malloc.c index e83fc7d7bd..660d1baae6 100644 --- a/core/shared/platform/windows/win_malloc.c +++ b/core/shared/platform/windows/win_malloc.c @@ -22,6 +22,3 @@ os_free(void *ptr) { free(ptr); } - - - diff --git a/core/shared/platform/windows/win_memmap.c b/core/shared/platform/windows/win_memmap.c index 4d45897df3..7afe73962b 100644 --- a/core/shared/platform/windows/win_memmap.c +++ b/core/shared/platform/windows/win_memmap.c @@ -79,8 +79,7 @@ os_munmap(void *addr, size_t size) } } #if TRACE_MEMMAP != 0 - printf("Unmap memory, addr: %p, request_size: %zu\n", - addr, request_size); + printf("Unmap memory, addr: %p, request_size: %zu\n", addr, request_size); #endif } @@ -95,8 +94,8 @@ os_mem_commit(void *addr, size_t size, int flags) return NULL; #if TRACE_MEMMAP != 0 - printf("Commit memory, addr: %p, request_size: %zu, protect: 0x%x\n", - addr, request_size, protect); + printf("Commit memory, addr: %p, request_size: %zu, protect: 0x%x\n", addr, + request_size, protect); #endif return VirtualAlloc((LPVOID)addr, request_size, MEM_COMMIT, protect); } @@ -111,8 +110,8 @@ os_mem_decommit(void *addr, size_t size) return; #if TRACE_MEMMAP != 0 - printf("Decommit memory, addr: %p, request_size: %zu\n", - addr, request_size); + printf("Decommit memory, addr: %p, request_size: %zu\n", addr, + request_size); #endif VirtualFree((LPVOID)addr, request_size, MEM_DECOMMIT); } @@ -134,4 +133,3 @@ os_mprotect(void *addr, size_t size, int prot) #endif return VirtualProtect((LPVOID)addr, request_size, protect, NULL); } - diff --git a/core/shared/platform/windows/win_thread.c b/core/shared/platform/windows/win_thread.c index 95792f72c1..3a123d6fab 100644 --- a/core/shared/platform/windows/win_thread.c +++ b/core/shared/platform/windows/win_thread.c @@ -47,11 +47,16 @@ static os_thread_data supervisor_thread_data; /* Thread data key */ static DWORD thread_data_key; -int os_sem_init(korp_sem* sem); -int os_sem_destroy(korp_sem* sem); -int os_sem_wait(korp_sem* sem); -int os_sem_reltimed_wait(korp_sem* sem, uint64 useconds); -int os_sem_signal(korp_sem* sem); +int +os_sem_init(korp_sem *sem); +int +os_sem_destroy(korp_sem *sem); +int +os_sem_wait(korp_sem *sem); +int +os_sem_reltimed_wait(korp_sem *sem, uint64 useconds); +int +os_sem_signal(korp_sem *sem); int os_thread_sys_init() @@ -141,8 +146,7 @@ os_thread_cleanup(void *retval) BH_FREE(thread_data); } -static unsigned __stdcall -os_thread_wrapper(void *arg) +static unsigned __stdcall os_thread_wrapper(void *arg) { os_thread_data *thread_data = arg; os_thread_data *parent = thread_data->parent; @@ -202,9 +206,8 @@ os_thread_create_with_prio(korp_tid *p_tid, thread_start_routine_t start, goto fail3; os_mutex_lock(&parent->wait_lock); - if (!_beginthreadex(NULL, stack_size, - os_thread_wrapper, thread_data, - 0, NULL)) { + if (!_beginthreadex(NULL, stack_size, os_thread_wrapper, thread_data, 0, + NULL)) { os_mutex_unlock(&parent->wait_lock); goto fail4; } @@ -371,7 +374,7 @@ os_sem_wait(korp_sem *sem) if (ret == WAIT_OBJECT_0) return BHT_OK; - else if(ret == WAIT_TIMEOUT) + else if (ret == WAIT_TIMEOUT) return (int)WAIT_TIMEOUT; else /* WAIT_FAILED or others */ return BHT_ERROR; @@ -404,7 +407,7 @@ os_sem_reltimed_wait(korp_sem *sem, uint64 useconds) if (ret == WAIT_OBJECT_0) return BHT_OK; - else if(ret == WAIT_TIMEOUT) + else if (ret == WAIT_TIMEOUT) return (int)WAIT_TIMEOUT; else /* WAIT_FAILED or others */ return BHT_ERROR; @@ -414,8 +417,7 @@ int os_sem_signal(korp_sem *sem) { bh_assert(sem); - return ReleaseSemaphore(*sem, 1, NULL) != FALSE - ? BHT_OK: BHT_ERROR; + return ReleaseSemaphore(*sem, 1, NULL) != FALSE ? BHT_OK : BHT_ERROR; } int @@ -478,8 +480,8 @@ os_cond_destroy(korp_cond *cond) } static int -os_cond_wait_internal(korp_cond *cond, korp_mutex *mutex, - bool timed, uint64 useconds) +os_cond_wait_internal(korp_cond *cond, korp_mutex *mutex, bool timed, + uint64 useconds) { os_thread_wait_node *node = &thread_data_current()->wait_node; @@ -567,7 +569,7 @@ os_thread_get_stack_boundary() GetCurrentThreadStackLimits(&low_limit, &high_limit); /* 4 pages are set unaccessible by system, we reserved one more page at least for safety */ - thread_stack_boundary = (uint8*)(uintptr_t)low_limit + page_size * 5; + thread_stack_boundary = (uint8 *)(uintptr_t)low_limit + page_size * 5; return thread_stack_boundary; } @@ -601,4 +603,3 @@ os_thread_signal_inited() return thread_signal_inited; } #endif - diff --git a/core/shared/platform/windows/win_time.c b/core/shared/platform/windows/win_time.c index a48e4191d7..ea324f2051 100644 --- a/core/shared/platform/windows/win_time.c +++ b/core/shared/platform/windows/win_time.c @@ -13,4 +13,3 @@ os_time_get_boot_microsecond() return ((uint64)ts.tv_sec) * 1000 * 1000 + ((uint64)ts.tv_nsec) / 1000; } - diff --git a/core/shared/platform/zephyr/platform_internal.h b/core/shared/platform/zephyr/platform_internal.h index 9de485f8f1..d09c3a9209 100644 --- a/core/shared/platform/zephyr/platform_internal.h +++ b/core/shared/platform/zephyr/platform_internal.h @@ -37,7 +37,6 @@ #include #endif - #ifndef BH_PLATFORM_ZEPHYR #define BH_PLATFORM_ZEPHYR #endif @@ -62,6 +61,7 @@ typedef struct korp_cond { #define Z_TIMEOUT_MS(ms) ms #endif +/* clang-format off */ void abort(void); size_t strspn(const char *s, const char *accept); size_t strcspn(const char *s, const char *reject); @@ -91,6 +91,7 @@ double scalbn(double x, int n); unsigned long long int strtoull(const char *nptr, char **endptr, int base); double strtod(const char *nptr, char **endptr); float strtof(const char *nptr, char **endptr); +/* clang-format on */ /** * @brief Allocate executable memroy @@ -99,7 +100,7 @@ float strtof(const char *nptr, char **endptr); * * @return the address of the allocated memory if not NULL */ -typedef void* (*exec_mem_alloc_func_t)(unsigned int size); +typedef void *(*exec_mem_alloc_func_t)(unsigned int size); /** * @brief Release executable memroy @@ -108,8 +109,12 @@ typedef void* (*exec_mem_alloc_func_t)(unsigned int size); */ typedef void (*exec_mem_free_func_t)(void *addr); -/* Below function are called by external project to set related function pointers that - * will be used to malloc/free executable memory. Otherwise default mechanise will be used. */ -void set_exec_mem_alloc_func(exec_mem_alloc_func_t alloc_func, exec_mem_free_func_t free_func); +/* Below function are called by external project to set related function + * pointers that will be used to malloc/free executable memory. Otherwise + * default mechanise will be used. + */ +void +set_exec_mem_alloc_func(exec_mem_alloc_func_t alloc_func, + exec_mem_free_func_t free_func); #endif diff --git a/core/shared/platform/zephyr/zephyr_platform.c b/core/shared/platform/zephyr/zephyr_platform.c index 4ecc828d3b..55ad84f420 100644 --- a/core/shared/platform/zephyr/zephyr_platform.c +++ b/core/shared/platform/zephyr/zephyr_platform.c @@ -29,9 +29,8 @@ disable_mpu_rasr_xn(void) MPU->RASR |= ~MPU_RASR_XN_Msk; } } - } -#endif /* end of CONFIG_ARM_MPU */ +#endif /* end of CONFIG_ARM_MPU */ #endif static int @@ -84,8 +83,7 @@ os_realloc(void *ptr, unsigned size) void os_free(void *ptr) -{ -} +{} #if 0 struct out_context { @@ -203,17 +201,17 @@ os_dcache_flush() SCB_CleanDCache(); irq_unlock(key); #elif defined(CONFIG_SOC_CVF_EM7D) && defined(CONFIG_ARC_MPU) \ - && defined (CONFIG_CACHE_FLUSHING) + && defined(CONFIG_CACHE_FLUSHING) __asm__ __volatile__("sync"); z_arc_v2_aux_reg_write(_ARC_V2_DC_FLSH, BIT(0)); __asm__ __volatile__("sync"); #endif } -void set_exec_mem_alloc_func(exec_mem_alloc_func_t alloc_func, - exec_mem_free_func_t free_func) +void +set_exec_mem_alloc_func(exec_mem_alloc_func_t alloc_func, + exec_mem_free_func_t free_func) { exec_mem_alloc_func = alloc_func; exec_mem_free_func = free_func; } - diff --git a/core/shared/platform/zephyr/zephyr_thread.c b/core/shared/platform/zephyr/zephyr_thread.c index 55cadb47c9..1ee2c5cefc 100644 --- a/core/shared/platform/zephyr/zephyr_thread.c +++ b/core/shared/platform/zephyr/zephyr_thread.c @@ -6,13 +6,15 @@ #include "platform_api_vmcore.h" #include "platform_api_extension.h" +/* clang-format off */ #define bh_assert(v) do { \ if (!(v)) { \ printf("\nASSERTION FAILED: %s, at %s, line %d\n", \ #v, __FILE__, __LINE__); \ abort(); \ } \ - } while (0) +} while (0) +/* clang-format on */ #if defined(CONFIG_ARM_MPU) || defined(CONFIG_ARC_MPU) \ || KERNEL_VERSION_NUMBER > 0x020300 /* version 2.3.0 */ @@ -28,13 +30,13 @@ #endif #if BH_ENABLE_ZEPHYR_MPU_STACK != 0 -static K_THREAD_STACK_ARRAY_DEFINE(mpu_stacks, - BH_ZEPHYR_MPU_STACK_COUNT, +static K_THREAD_STACK_ARRAY_DEFINE(mpu_stacks, BH_ZEPHYR_MPU_STACK_COUNT, BH_ZEPHYR_MPU_STACK_SIZE); static bool mpu_stack_allocated[BH_ZEPHYR_MPU_STACK_COUNT]; static struct k_mutex mpu_stack_lock; -static char *mpu_stack_alloc() +static char * +mpu_stack_alloc() { int i; @@ -43,14 +45,15 @@ static char *mpu_stack_alloc() if (!mpu_stack_allocated[i]) { mpu_stack_allocated[i] = true; k_mutex_unlock(&mpu_stack_lock); - return (char*)mpu_stacks[i]; + return (char *)mpu_stacks[i]; } } k_mutex_unlock(&mpu_stack_lock); return NULL; } -static void mpu_stack_free(char *stack) +static void +mpu_stack_free(char *stack) { int i; @@ -114,7 +117,8 @@ static struct k_mutex thread_obj_lock; /* Thread object list */ static os_thread_obj *thread_obj_list = NULL; -static void thread_data_list_add(os_thread_data *thread_data) +static void +thread_data_list_add(os_thread_data *thread_data) { k_mutex_lock(&thread_data_lock, K_FOREVER); if (!thread_data_list) @@ -137,7 +141,8 @@ static void thread_data_list_add(os_thread_data *thread_data) k_mutex_unlock(&thread_data_lock); } -static void thread_data_list_remove(os_thread_data *thread_data) +static void +thread_data_list_remove(os_thread_data *thread_data) { k_mutex_lock(&thread_data_lock, K_FOREVER); if (thread_data_list) { @@ -174,7 +179,8 @@ thread_data_list_lookup(k_tid_t tid) return NULL; } -static void thread_obj_list_add(os_thread_obj *thread_obj) +static void +thread_obj_list_add(os_thread_obj *thread_obj) { k_mutex_lock(&thread_obj_lock, K_FOREVER); if (!thread_obj_list) @@ -187,7 +193,8 @@ static void thread_obj_list_add(os_thread_obj *thread_obj) k_mutex_unlock(&thread_obj_lock); } -static void thread_obj_list_reclaim() +static void +thread_obj_list_reclaim() { os_thread_obj *p, *p_prev; k_mutex_lock(&thread_obj_lock, K_FOREVER); @@ -199,12 +206,14 @@ static void thread_obj_list_reclaim() thread_obj_list = p->next; BH_FREE(p); p = thread_obj_list; - } else { /* p is not the head of list */ + } + else { /* p is not the head of list */ p_prev->next = p->next; BH_FREE(p); p = p_prev->next; } - } else { + } + else { p_prev = p; p = p->next; } @@ -212,7 +221,8 @@ static void thread_obj_list_reclaim() k_mutex_unlock(&thread_obj_lock); } -int os_thread_sys_init() +int +os_thread_sys_init() { if (is_thread_sys_inited) return BHT_OK; @@ -233,7 +243,8 @@ int os_thread_sys_init() return BHT_OK; } -void os_thread_sys_destroy(void) +void +os_thread_sys_destroy(void) { if (is_thread_sys_inited) { is_thread_sys_inited = false; @@ -247,7 +258,8 @@ thread_data_current() return thread_data_list_lookup(tid); } -static void os_thread_cleanup(void) +static void +os_thread_cleanup(void) { os_thread_data *thread_data = thread_data_current(); @@ -269,32 +281,35 @@ static void os_thread_cleanup(void) thread_data_list_remove(thread_data); /* Set flag to true for the next thread creating to free the thread object */ - ((os_thread_obj*) thread_data->tid)->to_be_freed = true; + ((os_thread_obj *)thread_data->tid)->to_be_freed = true; #if BH_ENABLE_ZEPHYR_MPU_STACK != 0 mpu_stack_free(thread_data->stack); #endif BH_FREE(thread_data); } -static void os_thread_wrapper(void *start, void *arg, void *thread_data) +static void +os_thread_wrapper(void *start, void *arg, void *thread_data) { /* Set thread custom data */ - ((os_thread_data*) thread_data)->tid = k_current_get(); + ((os_thread_data *)thread_data)->tid = k_current_get(); thread_data_list_add(thread_data); - ((thread_start_routine_t) start)(arg); + ((thread_start_routine_t)start)(arg); os_thread_cleanup(); } -int os_thread_create(korp_tid *p_tid, thread_start_routine_t start, void *arg, - unsigned int stack_size) +int +os_thread_create(korp_tid *p_tid, thread_start_routine_t start, void *arg, + unsigned int stack_size) { return os_thread_create_with_prio(p_tid, start, arg, stack_size, BH_THREAD_DEFAULT_PRIORITY); } -int os_thread_create_with_prio(korp_tid *p_tid, thread_start_routine_t start, - void *arg, unsigned int stack_size, int prio) +int +os_thread_create_with_prio(korp_tid *p_tid, thread_start_routine_t start, + void *arg, unsigned int stack_size, int prio) { korp_tid tid; os_thread_data *thread_data; @@ -347,7 +362,7 @@ int os_thread_create_with_prio(korp_tid *p_tid, thread_start_routine_t start, /* Set thread custom data */ thread_data_list_add(thread_data); - thread_obj_list_add((os_thread_obj*)tid); + thread_obj_list_add((os_thread_obj *)tid); *p_tid = tid; return BHT_OK; @@ -362,14 +377,16 @@ int os_thread_create_with_prio(korp_tid *p_tid, thread_start_routine_t start, return BHT_ERROR; } -korp_tid os_self_thread() +korp_tid +os_self_thread() { return (korp_tid)k_current_get(); } -int os_thread_join(korp_tid thread, void **value_ptr) +int +os_thread_join(korp_tid thread, void **value_ptr) { - (void) value_ptr; + (void)value_ptr; os_thread_data *thread_data; os_thread_wait_node *node; @@ -407,30 +424,35 @@ int os_thread_join(korp_tid thread, void **value_ptr) return BHT_OK; } -int os_mutex_init(korp_mutex *mutex) +int +os_mutex_init(korp_mutex *mutex) { k_mutex_init(mutex); return BHT_OK; } -int os_recursive_mutex_init(korp_mutex *mutex) +int +os_recursive_mutex_init(korp_mutex *mutex) { k_mutex_init(mutex); return BHT_OK; } -int os_mutex_destroy(korp_mutex *mutex) +int +os_mutex_destroy(korp_mutex *mutex) { - (void) mutex; + (void)mutex; return BHT_OK; } -int os_mutex_lock(korp_mutex *mutex) +int +os_mutex_lock(korp_mutex *mutex) { return k_mutex_lock(mutex, K_FOREVER); } -int os_mutex_unlock(korp_mutex *mutex) +int +os_mutex_unlock(korp_mutex *mutex) { #if KERNEL_VERSION_NUMBER >= 0x020200 /* version 2.2.0 */ return k_mutex_unlock(mutex); @@ -440,21 +462,23 @@ int os_mutex_unlock(korp_mutex *mutex) #endif } -int os_cond_init(korp_cond *cond) +int +os_cond_init(korp_cond *cond) { k_mutex_init(&cond->wait_list_lock); cond->thread_wait_list = NULL; return BHT_OK; } -int os_cond_destroy(korp_cond *cond) +int +os_cond_destroy(korp_cond *cond) { - (void) cond; + (void)cond; return BHT_OK; } -static int os_cond_wait_internal(korp_cond *cond, korp_mutex *mutex, - bool timed, int mills) +static int +os_cond_wait_internal(korp_cond *cond, korp_mutex *mutex, bool timed, int mills) { os_thread_wait_node *node; @@ -499,12 +523,14 @@ static int os_cond_wait_internal(korp_cond *cond, korp_mutex *mutex, return BHT_OK; } -int os_cond_wait(korp_cond *cond, korp_mutex *mutex) +int +os_cond_wait(korp_cond *cond, korp_mutex *mutex) { return os_cond_wait_internal(cond, mutex, false, 0); } -int os_cond_reltimedwait(korp_cond *cond, korp_mutex *mutex, uint64 useconds) +int +os_cond_reltimedwait(korp_cond *cond, korp_mutex *mutex, uint64 useconds) { if (useconds == BHT_WAIT_FOREVER) { @@ -526,7 +552,8 @@ int os_cond_reltimedwait(korp_cond *cond, korp_mutex *mutex, uint64 useconds) } } -int os_cond_signal(korp_cond *cond) +int +os_cond_signal(korp_cond *cond) { /* Signal the head wait node of wait list */ k_mutex_lock(&cond->wait_list_lock, K_FOREVER); @@ -537,13 +564,13 @@ int os_cond_signal(korp_cond *cond) return BHT_OK; } -uint8 *os_thread_get_stack_boundary() +uint8 * +os_thread_get_stack_boundary() { #if defined(CONFIG_THREAD_STACK_INFO) korp_tid thread = k_current_get(); - return (uint8*)thread->stack_info.start; + return (uint8 *)thread->stack_info.start; #else return NULL; #endif } - diff --git a/core/shared/platform/zephyr/zephyr_time.c b/core/shared/platform/zephyr/zephyr_time.c index 6a9db0806d..99eb3b3546 100644 --- a/core/shared/platform/zephyr/zephyr_time.c +++ b/core/shared/platform/zephyr/zephyr_time.c @@ -10,4 +10,3 @@ os_time_get_boot_microsecond() { return k_uptime_get() * 1000; } - diff --git a/core/shared/utils/bh_assert.c b/core/shared/utils/bh_assert.c index cf93b170bc..f341df4df5 100644 --- a/core/shared/utils/bh_assert.c +++ b/core/shared/utils/bh_assert.c @@ -5,8 +5,9 @@ #include "bh_assert.h" -void bh_assert_internal(int v, const char *file_name, int line_number, - const char *expr_string) +void +bh_assert_internal(int v, const char *file_name, int line_number, + const char *expr_string) { if (v) return; @@ -17,9 +18,8 @@ void bh_assert_internal(int v, const char *file_name, int line_number, if (!expr_string) expr_string = "NULL EXPR_STRING"; - os_printf("\nASSERTION FAILED: %s, at file %s, line %d\n", - expr_string, file_name, line_number); + os_printf("\nASSERTION FAILED: %s, at file %s, line %d\n", expr_string, + file_name, line_number); abort(); } - diff --git a/core/shared/utils/bh_assert.h b/core/shared/utils/bh_assert.h index 3a83d62b15..ba89d12c0f 100644 --- a/core/shared/utils/bh_assert.h +++ b/core/shared/utils/bh_assert.h @@ -13,10 +13,11 @@ extern "C" { #endif #if BH_DEBUG != 0 -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)(uintptr_t)(expr), \ - __FILE__, __LINE__, #expr) +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)(uintptr_t)(expr), __FILE__, __LINE__, #expr) #else #define bh_assert(expr) (void)0 #endif /* end of BH_DEBUG */ @@ -26,4 +27,3 @@ void bh_assert_internal(int v, const char *file_name, int line_number, #endif #endif /* end of _BH_ASSERT_H */ - diff --git a/core/shared/utils/bh_common.c b/core/shared/utils/bh_common.c index 44bdbed1b0..690d573def 100644 --- a/core/shared/utils/bh_common.c +++ b/core/shared/utils/bh_common.c @@ -12,70 +12,67 @@ #define RSIZE_MAX 0x7FFFFFFF int -b_memcpy_s(void * s1, unsigned int s1max, - const void * s2, unsigned int n) +b_memcpy_s(void *s1, unsigned int s1max, const void *s2, unsigned int n) { - char *dest = (char*)s1; - char *src = (char*)s2; - if (n == 0) { - return 0; - } + char *dest = (char *)s1; + char *src = (char *)s2; + if (n == 0) { + return 0; + } - if (s1 == NULL || s1max > RSIZE_MAX) { - return -1; - } - if (s2 == NULL || n > s1max) { - memset(dest, 0, s1max); - return -1; - } - memcpy(dest, src, n); - return 0; + if (s1 == NULL || s1max > RSIZE_MAX) { + return -1; + } + if (s2 == NULL || n > s1max) { + memset(dest, 0, s1max); + return -1; + } + memcpy(dest, src, n); + return 0; } -int b_memmove_s(void * s1, unsigned int s1max, - const void * s2, unsigned int n) +int +b_memmove_s(void *s1, unsigned int s1max, const void *s2, unsigned int n) { - char *dest = (char*)s1; - char *src = (char*)s2; - if (n == 0) { - return 0; - } + char *dest = (char *)s1; + char *src = (char *)s2; + if (n == 0) { + return 0; + } - if (s1 == NULL || s1max > RSIZE_MAX) { - return -1; - } - if (s2 == NULL || n > s1max) { - memset(dest, 0, s1max); - return -1; - } - memmove(dest, src, n); - return 0; + if (s1 == NULL || s1max > RSIZE_MAX) { + return -1; + } + if (s2 == NULL || n > s1max) { + memset(dest, 0, s1max); + return -1; + } + memmove(dest, src, n); + return 0; } int -b_strcat_s(char * s1, unsigned int s1max, const char * s2) +b_strcat_s(char *s1, unsigned int s1max, const char *s2) { - if (NULL == s1 || NULL == s2 - || s1max < (strlen(s1) + strlen(s2) + 1) - || s1max > RSIZE_MAX) { - return -1; - } + if (NULL == s1 || NULL == s2 || s1max < (strlen(s1) + strlen(s2) + 1) + || s1max > RSIZE_MAX) { + return -1; + } - memcpy(s1 + strlen(s1), s2, strlen(s2) + 1); - return 0; + memcpy(s1 + strlen(s1), s2, strlen(s2) + 1); + return 0; } int -b_strcpy_s(char * s1, unsigned int s1max, const char * s2) +b_strcpy_s(char *s1, unsigned int s1max, const char *s2) { - if (NULL == s1 || NULL == s2 - || s1max < (strlen(s2) + 1) - || s1max > RSIZE_MAX) { - return -1; - } + if (NULL == s1 || NULL == s2 || s1max < (strlen(s2) + 1) + || s1max > RSIZE_MAX) { + return -1; + } - memcpy(s1, s2, strlen(s2) + 1); - return 0; + memcpy(s1, s2, strlen(s2) + 1); + return 0; } char * @@ -105,4 +102,3 @@ wa_strdup(const char *s) } return s1; } - diff --git a/core/shared/utils/bh_common.h b/core/shared/utils/bh_common.h index cd3bcdacf7..eaeec51082 100644 --- a/core/shared/utils/bh_common.h +++ b/core/shared/utils/bh_common.h @@ -12,40 +12,50 @@ extern "C" { #endif -#define bh_memcpy_s(dest, dlen, src, slen) do { \ - int _ret = slen == 0 ? 0 : b_memcpy_s (dest, dlen, src, slen); \ - (void)_ret; \ - bh_assert (_ret == 0); \ - } while (0) - -#define bh_memmove_s(dest, dlen, src, slen) do { \ - int _ret = slen == 0 ? 0 : b_memmove_s (dest, dlen, src, slen); \ - (void)_ret; \ - bh_assert (_ret == 0); \ - } while (0) - -#define bh_strcat_s(dest, dlen, src) do { \ - int _ret = b_strcat_s (dest, dlen, src); \ - (void)_ret; \ - bh_assert (_ret == 0); \ - } while (0) - -#define bh_strcpy_s(dest, dlen, src) do { \ - int _ret = b_strcpy_s (dest, dlen, src); \ - (void)_ret; \ - bh_assert (_ret == 0); \ - } while (0) - -int b_memcpy_s(void * s1, unsigned int s1max, const void * s2, unsigned int n); -int b_memmove_s(void * s1, unsigned int s1max, const void * s2, unsigned int n); -int b_strcat_s(char * s1, unsigned int s1max, const char * s2); -int b_strcpy_s(char * s1, unsigned int s1max, const char * s2); +#define bh_memcpy_s(dest, dlen, src, slen) \ + do { \ + int _ret = slen == 0 ? 0 : b_memcpy_s(dest, dlen, src, slen); \ + (void)_ret; \ + bh_assert(_ret == 0); \ + } while (0) + +#define bh_memmove_s(dest, dlen, src, slen) \ + do { \ + int _ret = slen == 0 ? 0 : b_memmove_s(dest, dlen, src, slen); \ + (void)_ret; \ + bh_assert(_ret == 0); \ + } while (0) + +#define bh_strcat_s(dest, dlen, src) \ + do { \ + int _ret = b_strcat_s(dest, dlen, src); \ + (void)_ret; \ + bh_assert(_ret == 0); \ + } while (0) + +#define bh_strcpy_s(dest, dlen, src) \ + do { \ + int _ret = b_strcpy_s(dest, dlen, src); \ + (void)_ret; \ + bh_assert(_ret == 0); \ + } while (0) + +int +b_memcpy_s(void *s1, unsigned int s1max, const void *s2, unsigned int n); +int +b_memmove_s(void *s1, unsigned int s1max, const void *s2, unsigned int n); +int +b_strcat_s(char *s1, unsigned int s1max, const char *s2); +int +b_strcpy_s(char *s1, unsigned int s1max, const char *s2); /* strdup with string allocated by BH_MALLOC */ -char *bh_strdup(const char *s); +char * +bh_strdup(const char *s); /* strdup with string allocated by WA_MALLOC */ -char *wa_strdup(const char *s); +char * +wa_strdup(const char *s); #ifdef __cplusplus } diff --git a/core/shared/utils/bh_hashmap.c b/core/shared/utils/bh_hashmap.c index 7ed0360197..70119c7709 100644 --- a/core/shared/utils/bh_hashmap.c +++ b/core/shared/utils/bh_hashmap.c @@ -25,11 +25,9 @@ struct HashMap { HashMapElem *elements[1]; }; -HashMap* -bh_hash_map_create(uint32 size, bool use_lock, - HashFunc hash_func, - KeyEqualFunc key_equal_func, - KeyDestroyFunc key_destroy_func, +HashMap * +bh_hash_map_create(uint32 size, bool use_lock, HashFunc hash_func, + KeyEqualFunc key_equal_func, KeyDestroyFunc key_destroy_func, ValueDestroyFunc value_destroy_func) { HashMap *map; @@ -42,16 +40,15 @@ bh_hash_map_create(uint32 size, bool use_lock, if (!hash_func || !key_equal_func) { LOG_ERROR("HashMap create failed: hash function or key equal function " - " is NULL.\n"); + " is NULL.\n"); return NULL; } - total_size = offsetof(HashMap, elements) + - sizeof(HashMapElem *) * (uint64)size + - (use_lock ? sizeof(korp_mutex) : 0); + total_size = offsetof(HashMap, elements) + + sizeof(HashMapElem *) * (uint64)size + + (use_lock ? sizeof(korp_mutex) : 0); - if (total_size >= UINT32_MAX - || !(map = BH_MALLOC((uint32)total_size))) { + if (total_size >= UINT32_MAX || !(map = BH_MALLOC((uint32)total_size))) { LOG_ERROR("HashMap create failed: alloc memory failed.\n"); return NULL; } @@ -59,9 +56,8 @@ bh_hash_map_create(uint32 size, bool use_lock, memset(map, 0, (uint32)total_size); if (use_lock) { - map->lock = (korp_mutex*) - ((uint8*)map + offsetof(HashMap, elements) - + sizeof(HashMapElem *) * size); + map->lock = (korp_mutex *)((uint8 *)map + offsetof(HashMap, elements) + + sizeof(HashMapElem *) * size); if (os_mutex_init(map->lock)) { LOG_ERROR("HashMap create failed: init map lock failed.\n"); BH_FREE(map); @@ -124,7 +120,7 @@ bh_hash_map_insert(HashMap *map, void *key, void *value) return false; } -void* +void * bh_hash_map_find(HashMap *map, void *key) { uint32 index; @@ -161,8 +157,7 @@ bh_hash_map_find(HashMap *map, void *key) } bool -bh_hash_map_update(HashMap *map, void *key, void *value, - void **p_old_value) +bh_hash_map_update(HashMap *map, void *key, void *value, void **p_old_value) { uint32 index; HashMapElem *elem; @@ -199,8 +194,8 @@ bh_hash_map_update(HashMap *map, void *key, void *value, } bool -bh_hash_map_remove(HashMap *map, void *key, - void **p_old_key, void **p_old_value) +bh_hash_map_remove(HashMap *map, void *key, void **p_old_key, + void **p_old_value) { uint32 index; HashMapElem *elem, *prev; diff --git a/core/shared/utils/bh_hashmap.h b/core/shared/utils/bh_hashmap.h index de4eefcfce..ca61ae4178 100644 --- a/core/shared/utils/bh_hashmap.h +++ b/core/shared/utils/bh_hashmap.h @@ -51,11 +51,9 @@ typedef void (*TraverseCallbackFunc)(void *key, void *value, void *user_data); * * @return the hash map created, NULL if failed */ -HashMap* -bh_hash_map_create(uint32 size, bool use_lock, - HashFunc hash_func, - KeyEqualFunc key_equal_func, - KeyDestroyFunc key_destroy_func, +HashMap * +bh_hash_map_create(uint32 size, bool use_lock, HashFunc hash_func, + KeyEqualFunc key_equal_func, KeyDestroyFunc key_destroy_func, ValueDestroyFunc value_destroy_func); /** @@ -79,7 +77,7 @@ bh_hash_map_insert(HashMap *map, void *key, void *value); * * @return the value of the found element if success, NULL otherwise */ -void* +void * bh_hash_map_find(HashMap *map, void *key); /** @@ -95,8 +93,7 @@ bh_hash_map_find(HashMap *map, void *key); * it will be copied to p_old_value for user to process. */ bool -bh_hash_map_update(HashMap *map, void *key, void *value, - void **p_old_value); +bh_hash_map_update(HashMap *map, void *key, void *value, void **p_old_value); /** * Remove an element from the hash map @@ -112,8 +109,8 @@ bh_hash_map_update(HashMap *map, void *key, void *value, * p_old_key and p_old_value for user to process. */ bool -bh_hash_map_remove(HashMap *map, void *key, - void **p_old_key, void **p_old_value); +bh_hash_map_remove(HashMap *map, void *key, void **p_old_key, + void **p_old_value); /** * Destroy the hashmap @@ -166,4 +163,3 @@ bh_hash_map_traverse(HashMap *map, TraverseCallbackFunc callback, #endif #endif /* endof WASM_HASHMAP_H */ - diff --git a/core/shared/utils/bh_list.c b/core/shared/utils/bh_list.c index 79f46adced..7102d42a14 100644 --- a/core/shared/utils/bh_list.c +++ b/core/shared/utils/bh_list.c @@ -14,10 +14,12 @@ * @return true if the pointer has been in the list; * false otherwise. */ -static bool bh_list_is_elem_exist(bh_list *list, void *elem); +static bool +bh_list_is_elem_exist(bh_list *list, void *elem); #endif -bh_list_status bh_list_init(bh_list *list) +bh_list_status +bh_list_init(bh_list *list) { if (!list) return BH_LIST_ERROR; @@ -27,23 +29,25 @@ bh_list_status bh_list_init(bh_list *list) return BH_LIST_SUCCESS; } -bh_list_status bh_list_insert(bh_list *list, void *elem) +bh_list_status +bh_list_insert(bh_list *list, void *elem) { bh_list_link *p = NULL; if (!list || !elem) return BH_LIST_ERROR; #if BH_DEBUG != 0 - bh_assert (!bh_list_is_elem_exist(list, elem)); + bh_assert(!bh_list_is_elem_exist(list, elem)); #endif - p = (bh_list_link *) elem; + p = (bh_list_link *)elem; p->next = (list->head).next; (list->head).next = p; list->len++; return BH_LIST_SUCCESS; } -bh_list_status bh_list_remove(bh_list *list, void *elem) +bh_list_status +bh_list_remove(bh_list *list, void *elem) { bh_list_link *cur = NULL; bh_list_link *prev = NULL; @@ -71,32 +75,37 @@ bh_list_status bh_list_remove(bh_list *list, void *elem) return BH_LIST_ERROR; } -uint32 bh_list_length(bh_list *list) +uint32 +bh_list_length(bh_list *list) { return (list ? list->len : 0); } -void* bh_list_first_elem(bh_list *list) +void * +bh_list_first_elem(bh_list *list) { return (list ? (list->head).next : NULL); } -void* bh_list_elem_next(void *node) +void * +bh_list_elem_next(void *node) { - return (node ? ((bh_list_link *) node)->next : NULL); + return (node ? ((bh_list_link *)node)->next : NULL); } #if BH_DEBUG != 0 -static bool bh_list_is_elem_exist(bh_list *list, void *elem) +static bool +bh_list_is_elem_exist(bh_list *list, void *elem) { bh_list_link *p = NULL; - if (!list || !elem) return false; + if (!list || !elem) + return false; p = (list->head).next; - while (p && p != elem) p = p->next; + while (p && p != elem) + p = p->next; return (p != NULL); } #endif - diff --git a/core/shared/utils/bh_list.h b/core/shared/utils/bh_list.h index f47b93743e..eaf15f2f3d 100644 --- a/core/shared/utils/bh_list.h +++ b/core/shared/utils/bh_list.h @@ -46,29 +46,34 @@ typedef enum bh_list_status { * @return BH_LIST_ERROR if OK; * BH_LIST_ERROR if list pointer is NULL. */ -bh_list_status bh_list_init(bh_list *list); +bh_list_status +bh_list_init(bh_list *list); /** - * Insert an elem pointer into list. The list node memory is maintained by list while - * elem memory is the responsibility of list user. + * Insert an elem pointer into list. The list node memory is maintained by list + * while elem memory is the responsibility of list user. * * @param list pointer to list. * @param elem pointer to elem that will be inserted into list. * @return BH_LIST_ERROR if OK; - * BH_LIST_ERROR if input is invalid or no memory available. + * BH_LIST_ERROR if input is invalid or no memory + * available. */ -extern bh_list_status bh_list_insert(bh_list *list, void *elem); +extern bh_list_status +bh_list_insert(bh_list *list, void *elem); /** - * Remove an elem pointer from list. The list node memory is maintained by list while - * elem memory is the responsibility of list user. + * Remove an elem pointer from list. The list node memory is maintained by list + * while elem memory is the responsibility of list user. * * @param list pointer to list. * @param elem pointer to elem that will be inserted into list. * @return BH_LIST_ERROR if OK; - * BH_LIST_ERROR if element does not exist in given list. + * BH_LIST_ERROR if element does not exist in given + * list. */ -bh_list_status bh_list_remove(bh_list *list, void *elem); +bh_list_status +bh_list_remove(bh_list *list, void *elem); /** * Get the list length. @@ -76,7 +81,8 @@ bh_list_status bh_list_remove(bh_list *list, void *elem); * @param list pointer to list. * @return the length of the list. */ -uint32 bh_list_length(bh_list *list); +uint32 +bh_list_length(bh_list *list); /** * Get the first elem in the list. @@ -84,7 +90,8 @@ uint32 bh_list_length(bh_list *list); * @param list pointer to list. * @return pointer to the first node. */ -void* bh_list_first_elem(bh_list *list); +void * +bh_list_first_elem(bh_list *list); /** * Get the next elem of given list input elem. @@ -92,11 +99,11 @@ void* bh_list_first_elem(bh_list *list); * @param node pointer to list node. * @return pointer to next list node. */ -void* bh_list_elem_next(void *node); +void * +bh_list_elem_next(void *node); #ifdef __cplusplus } #endif #endif /* #ifndef _BH_LIST_H */ - diff --git a/core/shared/utils/bh_log.c b/core/shared/utils/bh_log.c index a3b392e879..04d3e98ae6 100644 --- a/core/shared/utils/bh_log.c +++ b/core/shared/utils/bh_log.c @@ -71,9 +71,8 @@ bh_print_time(const char *prompt) total_time_ms += curr_time_ms - last_time_ms; - os_printf("%-48s time of last stage: %u ms, total time: %u ms\n", - prompt, curr_time_ms - last_time_ms, total_time_ms); + os_printf("%-48s time of last stage: %u ms, total time: %u ms\n", prompt, + curr_time_ms - last_time_ms, total_time_ms); last_time_ms = curr_time_ms; } - diff --git a/core/shared/utils/bh_log.h b/core/shared/utils/bh_log.h index dd24dc0431..1578028b7b 100644 --- a/core/shared/utils/bh_log.h +++ b/core/shared/utils/bh_log.h @@ -52,19 +52,22 @@ bh_log(LogLevel log_level, const char *file, int line, const char *fmt, ...); #endif #if BH_DEBUG != 0 -#define LOG_FATAL(...) bh_log(BH_LOG_LEVEL_FATAL, __FILE__, __LINE__, __VA_ARGS__) +#define LOG_FATAL(...) \ + bh_log(BH_LOG_LEVEL_FATAL, __FILE__, __LINE__, __VA_ARGS__) #else -#define LOG_FATAL(...) bh_log(BH_LOG_LEVEL_FATAL, __FUNCTION__, __LINE__, __VA_ARGS__) +#define LOG_FATAL(...) \ + bh_log(BH_LOG_LEVEL_FATAL, __FUNCTION__, __LINE__, __VA_ARGS__) #endif -#define LOG_ERROR(...) bh_log(BH_LOG_LEVEL_ERROR, NULL, 0, __VA_ARGS__) +#define LOG_ERROR(...) bh_log(BH_LOG_LEVEL_ERROR, NULL, 0, __VA_ARGS__) #define LOG_WARNING(...) bh_log(BH_LOG_LEVEL_WARNING, NULL, 0, __VA_ARGS__) #define LOG_VERBOSE(...) bh_log(BH_LOG_LEVEL_VERBOSE, NULL, 0, __VA_ARGS__) #if BH_DEBUG != 0 -#define LOG_DEBUG(...) bh_log(BH_LOG_LEVEL_DEBUG, __FILE__, __LINE__, __VA_ARGS__) +#define LOG_DEBUG(...) \ + bh_log(BH_LOG_LEVEL_DEBUG, __FILE__, __LINE__, __VA_ARGS__) #else -#define LOG_DEBUG(...) (void)0 +#define LOG_DEBUG(...) (void)0 #endif void @@ -74,4 +77,4 @@ bh_print_time(const char *prompt); } #endif -#endif /* _BH_LOG_H */ +#endif /* _BH_LOG_H */ diff --git a/core/shared/utils/bh_platform.h b/core/shared/utils/bh_platform.h index 94b156f477..86aef839dd 100644 --- a/core/shared/utils/bh_platform.h +++ b/core/shared/utils/bh_platform.h @@ -18,8 +18,6 @@ #include "bh_vector.h" #include "runtime_timer.h" - - /** * WA_MALLOC/WA_FREE need to be redefined for both * runtime native and WASM app respectively. @@ -38,4 +36,3 @@ #endif #endif /* #ifndef _BH_PLATFORM_H */ - diff --git a/core/shared/utils/bh_queue.c b/core/shared/utils/bh_queue.c index 602c2cdfbe..7c860d11a4 100644 --- a/core/shared/utils/bh_queue.c +++ b/core/shared/utils/bh_queue.c @@ -6,11 +6,11 @@ #include "bh_queue.h" typedef struct bh_queue_node { - struct bh_queue_node * next; - struct bh_queue_node * prev; + struct bh_queue_node *next; + struct bh_queue_node *prev; unsigned short tag; unsigned int len; - void * body; + void *body; bh_msg_cleaner msg_cleaner; } bh_queue_node; @@ -20,23 +20,26 @@ struct bh_queue { unsigned int cnt; unsigned int max; unsigned int drops; - bh_queue_node * head; - bh_queue_node * tail; + bh_queue_node *head; + bh_queue_node *tail; bool exit_loop_run; }; -char * bh_message_payload(bh_message_t message) +char * +bh_message_payload(bh_message_t message) { return message->body; } -uint32 bh_message_payload_len(bh_message_t message) +uint32 +bh_message_payload_len(bh_message_t message) { return message->len; } -int bh_message_type(bh_message_t message) +int +bh_message_type(bh_message_t message) { return message->tag; } @@ -68,7 +71,8 @@ bh_queue_create() return queue; } -void bh_queue_destroy(bh_queue *queue) +void +bh_queue_destroy(bh_queue *queue) { bh_queue_node *node; @@ -89,7 +93,8 @@ void bh_queue_destroy(bh_queue *queue) bh_queue_free(queue); } -bool bh_post_msg2(bh_queue *queue, bh_queue_node *msg) +bool +bh_post_msg2(bh_queue *queue, bh_queue_node *msg) { if (queue->cnt >= queue->max) { queue->drops++; @@ -107,7 +112,8 @@ bool bh_post_msg2(bh_queue *queue, bh_queue_node *msg) queue->cnt = 1; bh_queue_cond_signal(&queue->queue_wait_cond); - } else { + } + else { msg->next = NULL; msg->prev = queue->tail; queue->tail->next = msg; @@ -120,8 +126,8 @@ bool bh_post_msg2(bh_queue *queue, bh_queue_node *msg) return true; } -bool bh_post_msg(bh_queue *queue, unsigned short tag, void *body, - unsigned int len) +bool +bh_post_msg(bh_queue *queue, unsigned short tag, void *body, unsigned int len) { bh_queue_node *msg = bh_new_msg(tag, body, len, NULL); if (msg == NULL) { @@ -139,23 +145,24 @@ bool bh_post_msg(bh_queue *queue, unsigned short tag, void *body, return true; } -bh_queue_node * bh_new_msg(unsigned short tag, void *body, unsigned int len, - void * handler) +bh_queue_node * +bh_new_msg(unsigned short tag, void *body, unsigned int len, void *handler) { - bh_queue_node *msg = (bh_queue_node*) - bh_queue_malloc(sizeof(bh_queue_node)); + bh_queue_node *msg = + (bh_queue_node *)bh_queue_malloc(sizeof(bh_queue_node)); if (msg == NULL) return NULL; memset(msg, 0, sizeof(bh_queue_node)); msg->len = len; msg->body = body; msg->tag = tag; - msg->msg_cleaner = (bh_msg_cleaner) handler; + msg->msg_cleaner = (bh_msg_cleaner)handler; return msg; } -void bh_free_msg(bh_queue_node *msg) +void +bh_free_msg(bh_queue_node *msg) { if (msg->msg_cleaner) { msg->msg_cleaner(msg->body); @@ -171,7 +178,8 @@ void bh_free_msg(bh_queue_node *msg) bh_queue_free(msg); } -bh_message_t bh_get_msg(bh_queue *queue, uint64 timeout_us) +bh_message_t +bh_get_msg(bh_queue *queue, uint64 timeout_us) { bh_queue_node *msg = NULL; bh_queue_mutex_lock(&queue->queue_lock); @@ -192,13 +200,15 @@ bh_message_t bh_get_msg(bh_queue *queue, uint64 timeout_us) if (queue->cnt == 0) { bh_assert(queue->head == NULL); bh_assert(queue->tail == NULL); - } else if (queue->cnt == 1) { + } + else if (queue->cnt == 1) { bh_assert(queue->head == queue->tail); msg = queue->head; queue->head = queue->tail = NULL; queue->cnt = 0; - } else { + } + else { msg = queue->head; queue->head = queue->head->next; queue->head->prev = NULL; @@ -210,7 +220,8 @@ bh_message_t bh_get_msg(bh_queue *queue, uint64 timeout_us) return msg; } -unsigned bh_queue_get_message_count(bh_queue *queue) +unsigned +bh_queue_get_message_count(bh_queue *queue) { if (!queue) return 0; @@ -218,15 +229,15 @@ unsigned bh_queue_get_message_count(bh_queue *queue) return queue->cnt; } -void bh_queue_enter_loop_run(bh_queue *queue, - bh_queue_handle_msg_callback handle_cb, - void *arg) +void +bh_queue_enter_loop_run(bh_queue *queue, bh_queue_handle_msg_callback handle_cb, + void *arg) { if (!queue) return; while (!queue->exit_loop_run) { - bh_queue_node * message = bh_get_msg(queue, BHT_WAIT_FOREVER); + bh_queue_node *message = bh_get_msg(queue, BHT_WAIT_FOREVER); if (message) { handle_cb(message, arg); @@ -235,7 +246,8 @@ void bh_queue_enter_loop_run(bh_queue *queue, } } -void bh_queue_exit_loop_run(bh_queue *queue) +void +bh_queue_exit_loop_run(bh_queue *queue) { if (queue) { queue->exit_loop_run = true; diff --git a/core/shared/utils/bh_queue.h b/core/shared/utils/bh_queue.h index 09d1a7421b..394fed9e73 100644 --- a/core/shared/utils/bh_queue.h +++ b/core/shared/utils/bh_queue.h @@ -13,7 +13,7 @@ extern "C" { #include "bh_platform.h" struct bh_queue_node; -typedef struct bh_queue_node * bh_message_t; +typedef struct bh_queue_node *bh_message_t; struct bh_queue; typedef struct bh_queue bh_queue; @@ -45,25 +45,30 @@ bh_queue_create(); void bh_queue_destroy(bh_queue *queue); -char * bh_message_payload(bh_message_t message); -uint32 bh_message_payload_len(bh_message_t message); -int bh_message_type(bh_message_t message); +char * +bh_message_payload(bh_message_t message); +uint32 +bh_message_payload_len(bh_message_t message); +int +bh_message_type(bh_message_t message); -bh_message_t bh_new_msg(unsigned short tag, void *body, unsigned int len, - void * handler); -void bh_free_msg(bh_message_t msg); -bool bh_post_msg(bh_queue *queue, unsigned short tag, void *body, - unsigned int len); -bool bh_post_msg2(bh_queue *queue, bh_message_t msg); +bh_message_t +bh_new_msg(unsigned short tag, void *body, unsigned int len, void *handler); +void +bh_free_msg(bh_message_t msg); +bool +bh_post_msg(bh_queue *queue, unsigned short tag, void *body, unsigned int len); +bool +bh_post_msg2(bh_queue *queue, bh_message_t msg); -bh_message_t bh_get_msg(bh_queue *queue, uint64 timeout_us); +bh_message_t +bh_get_msg(bh_queue *queue, uint64 timeout_us); unsigned bh_queue_get_message_count(bh_queue *queue); void -bh_queue_enter_loop_run(bh_queue *queue, - bh_queue_handle_msg_callback handle_cb, +bh_queue_enter_loop_run(bh_queue *queue, bh_queue_handle_msg_callback handle_cb, void *arg); void bh_queue_exit_loop_run(bh_queue *queue); @@ -73,4 +78,3 @@ bh_queue_exit_loop_run(bh_queue *queue); #endif #endif /* #ifndef _BH_QUEUE_H */ - diff --git a/core/shared/utils/bh_vector.c b/core/shared/utils/bh_vector.c index 33ea7265e6..426c024256 100644 --- a/core/shared/utils/bh_vector.c +++ b/core/shared/utils/bh_vector.c @@ -5,14 +5,13 @@ #include "bh_vector.h" -static uint8* +static uint8 * alloc_vector_data(size_t length, size_t size_elem) { uint64 total_size = ((uint64)size_elem) * length; uint8 *data; - if (length > UINT32_MAX - || size_elem > UINT32_MAX + if (length > UINT32_MAX || size_elem > UINT32_MAX || total_size > UINT32_MAX) { return NULL; } @@ -82,12 +81,13 @@ bh_vector_set(Vector *vector, uint32 index, const void *elem_buf) return false; } - memcpy(vector->data + vector->size_elem * index, - elem_buf, vector->size_elem); + memcpy(vector->data + vector->size_elem * index, elem_buf, + vector->size_elem); return true; } -bool bh_vector_get(const Vector *vector, uint32 index, void *elem_buf) +bool +bh_vector_get(const Vector *vector, uint32 index, void *elem_buf) { if (!vector || !elem_buf) { LOG_ERROR("Get vector elem failed: vector or elem buf is NULL.\n"); @@ -104,7 +104,8 @@ bool bh_vector_get(const Vector *vector, uint32 index, void *elem_buf) return true; } -bool bh_vector_insert(Vector *vector, uint32 index, const void *elem_buf) +bool +bh_vector_insert(Vector *vector, uint32 index, const void *elem_buf) { size_t i; uint8 *p; @@ -135,7 +136,8 @@ bool bh_vector_insert(Vector *vector, uint32 index, const void *elem_buf) return true; } -bool bh_vector_append(Vector *vector, const void *elem_buf) +bool +bh_vector_append(Vector *vector, const void *elem_buf) { if (!vector || !elem_buf) { LOG_ERROR("Append vector elem failed: vector or elem buf is NULL.\n"); @@ -147,8 +149,8 @@ bool bh_vector_append(Vector *vector, const void *elem_buf) return false; } - memcpy(vector->data + vector->size_elem * vector->num_elems, - elem_buf, vector->size_elem); + memcpy(vector->data + vector->size_elem * vector->num_elems, elem_buf, + vector->size_elem); vector->num_elems++; return true; } diff --git a/core/shared/utils/bh_vector.h b/core/shared/utils/bh_vector.h index 59f432f783..072b1cb0d7 100644 --- a/core/shared/utils/bh_vector.h +++ b/core/shared/utils/bh_vector.h @@ -122,4 +122,3 @@ bh_vector_destroy(Vector *vector); #endif #endif /* endof _WASM_VECTOR_H */ - diff --git a/core/shared/utils/runtime_timer.c b/core/shared/utils/runtime_timer.c index 205b92ab98..8fccf4c2f3 100644 --- a/core/shared/utils/runtime_timer.c +++ b/core/shared/utils/runtime_timer.c @@ -12,7 +12,7 @@ #endif typedef struct _app_timer { - struct _app_timer * next; + struct _app_timer *next; uint32 id; uint32 interval; uint64 expiry; @@ -81,13 +81,13 @@ remove_timer_from(timer_ctx_t ctx, uint32 timer_id, bool active_list) if (t->id == timer_id) { if (prev == NULL) { *head = t->next; - PRINT("removed timer [%d] at head from list %d\n", - t->id, active_list); + PRINT("removed timer [%d] at head from list %d\n", t->id, + active_list); } else { prev->next = t->next; - PRINT("removed timer [%d] after [%d] from list %d\n", - t->id, prev->id, active_list); + PRINT("removed timer [%d] after [%d] from list %d\n", t->id, + prev->id, active_list); } os_mutex_unlock(&ctx->mutex); @@ -143,8 +143,8 @@ reschedule_timer(timer_ctx_t ctx, app_timer_t *timer) else { timer->next = t; prev->next = timer; - PRINT("rescheduled timer [%d] after [%d]\n", - timer->id, prev->id); + PRINT("rescheduled timer [%d] after [%d]\n", timer->id, + prev->id); } goto out; @@ -158,8 +158,8 @@ reschedule_timer(timer_ctx_t ctx, app_timer_t *timer) if (prev) { /* insert to the list end */ prev->next = timer; - PRINT("rescheduled timer [%d] at end, after [%d]\n", - timer->id, prev->id); + PRINT("rescheduled timer [%d] at end, after [%d]\n", timer->id, + prev->id); } else { /* insert at the begin */ @@ -213,8 +213,8 @@ release_timer_list(app_timer_t **p_list) timer_ctx_t create_timer_ctx(timer_callback_f timer_handler, - check_timer_expiry_f expiery_checker, - int prealloc_num, unsigned int owner) + 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)); @@ -229,7 +229,7 @@ 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; @@ -283,7 +283,7 @@ timer_ctx_get_owner(timer_ctx_t ctx) } void -add_idle_timer(timer_ctx_t ctx, app_timer_t * timer) +add_idle_timer(timer_ctx_t ctx, app_timer_t *timer) { os_mutex_lock(&ctx->mutex); timer->next = ctx->idle_timers; @@ -292,8 +292,7 @@ add_idle_timer(timer_ctx_t ctx, app_timer_t * timer) } uint32 -sys_create_timer(timer_ctx_t ctx, int interval, bool is_period, - bool auto_start) +sys_create_timer(timer_ctx_t ctx, int interval, bool is_period, bool auto_start) { app_timer_t *timer; @@ -307,7 +306,7 @@ sys_create_timer(timer_ctx_t ctx, int interval, bool is_period, } } 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; } @@ -333,7 +332,7 @@ bool sys_timer_cancel(timer_ctx_t ctx, uint32 timer_id) { bool from_active; - app_timer_t * t = remove_timer(ctx, timer_id, &from_active); + app_timer_t *t = remove_timer(ctx, timer_id, &from_active); if (t == NULL) return false; @@ -348,7 +347,7 @@ bool sys_timer_destroy(timer_ctx_t ctx, uint32 timer_id) { bool from_active; - app_timer_t * t = remove_timer(ctx, timer_id, &from_active); + app_timer_t *t = remove_timer(ctx, timer_id, &from_active); if (t == NULL) return false; @@ -362,7 +361,7 @@ sys_timer_destroy(timer_ctx_t ctx, uint32 timer_id) bool sys_timer_restart(timer_ctx_t ctx, uint32 timer_id, int interval) { - app_timer_t * t = remove_timer(ctx, timer_id, NULL); + app_timer_t *t = remove_timer(ctx, timer_id, NULL); if (t == NULL) return false; @@ -376,7 +375,8 @@ sys_timer_restart(timer_ctx_t ctx, uint32 timer_id, int interval) } /* - * API called by the timer manager from another thread or the kernel timer handler + * API called by the timer manager from another thread or the kernel timer + * handler */ /** @@ -467,4 +467,3 @@ cleanup_app_timers(timer_ctx_t ctx) os_mutex_unlock(&ctx->mutex); } - diff --git a/core/shared/utils/runtime_timer.h b/core/shared/utils/runtime_timer.h index db81d77b82..00db298342 100644 --- a/core/shared/utils/runtime_timer.h +++ b/core/shared/utils/runtime_timer.h @@ -12,28 +12,38 @@ extern "C" { #endif -uint64 bh_get_tick_ms(); -uint32 bh_get_elpased_ms(uint32 *last_system_clock); +uint64 +bh_get_tick_ms(); +uint32 +bh_get_elpased_ms(uint32 *last_system_clock); struct _timer_ctx; -typedef struct _timer_ctx * timer_ctx_t; +typedef struct _timer_ctx *timer_ctx_t; typedef void (*timer_callback_f)(unsigned int id, unsigned int owner); typedef void (*check_timer_expiry_f)(timer_ctx_t ctx); -timer_ctx_t create_timer_ctx(timer_callback_f timer_handler, - check_timer_expiry_f, int prealloc_num, - unsigned int owner); +timer_ctx_t +create_timer_ctx(timer_callback_f timer_handler, check_timer_expiry_f, + int prealloc_num, unsigned int owner); void destroy_timer_ctx(timer_ctx_t); -unsigned int timer_ctx_get_owner(timer_ctx_t ctx); - -uint32 sys_create_timer(timer_ctx_t ctx, int interval, bool is_period, - bool auto_start); -bool sys_timer_destroy(timer_ctx_t ctx, uint32 timer_id); -bool sys_timer_cancel(timer_ctx_t ctx, uint32 timer_id); -bool sys_timer_restart(timer_ctx_t ctx, uint32 timer_id, int interval); -void cleanup_app_timers(timer_ctx_t ctx); -uint32 check_app_timers(timer_ctx_t ctx); -uint32 get_expiry_ms(timer_ctx_t ctx); +unsigned int +timer_ctx_get_owner(timer_ctx_t ctx); + +uint32 +sys_create_timer(timer_ctx_t ctx, int interval, bool is_period, + bool auto_start); +bool +sys_timer_destroy(timer_ctx_t ctx, uint32 timer_id); +bool +sys_timer_cancel(timer_ctx_t ctx, uint32 timer_id); +bool +sys_timer_restart(timer_ctx_t ctx, uint32 timer_id, int interval); +void +cleanup_app_timers(timer_ctx_t ctx); +uint32 +check_app_timers(timer_ctx_t ctx); +uint32 +get_expiry_ms(timer_ctx_t ctx); #ifdef __cplusplus } diff --git a/core/shared/utils/uncommon/bh_getopt.c b/core/shared/utils/uncommon/bh_getopt.c index 67815e19df..19e23a7b5c 100644 --- a/core/shared/utils/uncommon/bh_getopt.c +++ b/core/shared/utils/uncommon/bh_getopt.c @@ -9,19 +9,22 @@ #include #include -char* optarg = NULL; +char *optarg = NULL; int optind = 1; -int getopt(int argc, char *const argv[], const char *optstring) +int +getopt(int argc, char *const argv[], const char *optstring) { static int sp = 1; int opt; char *p; if (sp == 1) { - if ((optind >= argc) || (argv[optind][0] != '-') || (argv[optind][1] == 0)){ + if ((optind >= argc) || (argv[optind][0] != '-') + || (argv[optind][1] == 0)) { return -1; - } else if (!strcmp(argv[optind], "--")) { + } + else if (!strcmp(argv[optind], "--")) { optind++; return -1; } @@ -31,24 +34,26 @@ int getopt(int argc, char *const argv[], const char *optstring) p = strchr(optstring, opt); if (opt == ':' || p == NULL) { printf("illegal option : '-%c'\n", opt); - if ( argv[optind][++sp] == '\0') { - optind ++; + if (argv[optind][++sp] == '\0') { + optind++; sp = 1; } return ('?'); } - if (p[1] == ':') { + if (p[1] == ':') { if (argv[optind][sp + 1] != '\0') optarg = &argv[optind++][sp + 1]; else if (++optind >= argc) { printf("option '-%c' requires an argument :\n", opt); sp = 1; return ('?'); - } else { + } + else { optarg = argv[optind++]; } sp = 1; - } else { + } + else { if (argv[optind][++sp] == '\0') { sp = 1; optind++; diff --git a/core/shared/utils/uncommon/bh_getopt.h b/core/shared/utils/uncommon/bh_getopt.h index e6243bfda2..efd3ab4036 100644 --- a/core/shared/utils/uncommon/bh_getopt.h +++ b/core/shared/utils/uncommon/bh_getopt.h @@ -17,7 +17,8 @@ extern "C" { extern char *optarg; extern int optind; -int getopt(int argc, char *const argv[], const char *optstring); +int +getopt(int argc, char *const argv[], const char *optstring); #ifdef __cplusplus } diff --git a/core/shared/utils/uncommon/bh_read_file.c b/core/shared/utils/uncommon/bh_read_file.c index 5513fe52e1..e17f1de316 100644 --- a/core/shared/utils/uncommon/bh_read_file.c +++ b/core/shared/utils/uncommon/bh_read_file.c @@ -9,7 +9,7 @@ #endif #if defined(_WIN32) || defined(_WIN32_) -char* +char * bh_read_file_to_buffer(const char *filename, uint32 *ret_size) { char *buffer; @@ -22,15 +22,13 @@ bh_read_file_to_buffer(const char *filename, uint32 *ret_size) return NULL; } - if (_sopen_s(&file, filename, _O_RDONLY| _O_BINARY, _SH_DENYNO, 0)) { - printf("Read file to buffer failed: open file %s failed.\n", - filename); + if (_sopen_s(&file, filename, _O_RDONLY | _O_BINARY, _SH_DENYNO, 0)) { + printf("Read file to buffer failed: open file %s failed.\n", filename); return NULL; } if (fstat(file, &stat_buf) != 0) { - printf("Read file to buffer failed: fstat file %s failed.\n", - filename); + printf("Read file to buffer failed: fstat file %s failed.\n", filename); _close(file); return NULL; } @@ -61,7 +59,7 @@ bh_read_file_to_buffer(const char *filename, uint32 *ret_size) return buffer; } #else /* else of defined(_WIN32) || defined(_WIN32_) */ -char* +char * bh_read_file_to_buffer(const char *filename, uint32 *ret_size) { char *buffer; @@ -75,14 +73,12 @@ bh_read_file_to_buffer(const char *filename, uint32 *ret_size) } if ((file = open(filename, O_RDONLY, 0)) == -1) { - printf("Read file to buffer failed: open file %s failed.\n", - filename); + printf("Read file to buffer failed: open file %s failed.\n", filename); return NULL; } if (fstat(file, &stat_buf) != 0) { - printf("Read file to buffer failed: fstat file %s failed.\n", - filename); + printf("Read file to buffer failed: fstat file %s failed.\n", filename); close(file); return NULL; } diff --git a/core/shared/utils/uncommon/bh_read_file.h b/core/shared/utils/uncommon/bh_read_file.h index 7c947d6214..bbebf847ff 100644 --- a/core/shared/utils/uncommon/bh_read_file.h +++ b/core/shared/utils/uncommon/bh_read_file.h @@ -20,4 +20,3 @@ bh_read_file_to_buffer(const char *filename, uint32 *ret_size); #endif #endif /* end of _BH_FILE_H */ - diff --git a/product-mini/app-samples/hello-world-cmake/main.c b/product-mini/app-samples/hello-world-cmake/main.c index 1c356c4799..b6dfd2802b 100644 --- a/product-mini/app-samples/hello-world-cmake/main.c +++ b/product-mini/app-samples/hello-world-cmake/main.c @@ -5,9 +5,11 @@ #include "stdio.h" -void print_line(char* str); +void +print_line(char *str); -int main() +int +main() { print_line("Hello World!"); print_line("Wasm Micro Runtime"); diff --git a/product-mini/app-samples/hello-world-cmake/print.c b/product-mini/app-samples/hello-world-cmake/print.c index 8eee6b6b39..d98a82667b 100644 --- a/product-mini/app-samples/hello-world-cmake/print.c +++ b/product-mini/app-samples/hello-world-cmake/print.c @@ -6,7 +6,8 @@ #include "stdio.h" #include "string.h" -void print_line(char* str) +void +print_line(char *str) { printf("%s\n", str); } \ No newline at end of file diff --git a/product-mini/app-samples/hello-world/main.c b/product-mini/app-samples/hello-world/main.c index d392fb1f86..4778a4d9b6 100644 --- a/product-mini/app-samples/hello-world/main.c +++ b/product-mini/app-samples/hello-world/main.c @@ -6,7 +6,8 @@ #include #include -int main(int argc, char **argv) +int +main(int argc, char **argv) { char *buf; diff --git a/product-mini/platforms/alios-things/src/main.c b/product-mini/platforms/alios-things/src/main.c index 1c148432c3..6393e2e4a2 100644 --- a/product-mini/platforms/alios-things/src/main.c +++ b/product-mini/platforms/alios-things/src/main.c @@ -24,10 +24,10 @@ static char **app_argv; * @return true if the main function is called, false otherwise. */ bool -wasm_application_execute_main(wasm_module_inst_t module_inst, - int32_t argc, char *argv[]); +wasm_application_execute_main(wasm_module_inst_t module_inst, int32_t argc, + char *argv[]); -static void* +static void * app_instance_main(wasm_module_inst_t module_inst) { const char *exception; @@ -40,7 +40,8 @@ app_instance_main(wasm_module_inst_t module_inst) static char global_heap_buf[256 * 1024] = { 0 }; -void iwasm_main(void *arg1) +void +iwasm_main(void *arg1) { uint8 *wasm_file_buf = NULL; uint32 wasm_file_size; @@ -52,7 +53,7 @@ void iwasm_main(void *arg1) int log_verbose_level = 2; #endif - (void) arg1; + (void)arg1; memset(&init_args, 0, sizeof(RuntimeInitArgs)); @@ -71,22 +72,19 @@ void iwasm_main(void *arg1) #endif /* load WASM byte buffer from byte buffer of include file */ - wasm_file_buf = (uint8*) wasm_test_file; + wasm_file_buf = (uint8 *)wasm_test_file; wasm_file_size = sizeof(wasm_test_file); /* load WASM module */ if (!(wasm_module = wasm_runtime_load(wasm_file_buf, wasm_file_size, - error_buf, sizeof(error_buf)))) { + error_buf, sizeof(error_buf)))) { printf("%s\n", error_buf); 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)))) { printf("%s\n", error_buf); goto fail2; } @@ -108,10 +106,10 @@ void iwasm_main(void *arg1) #define DEFAULT_THREAD_STACKSIZE (6 * 1024) #define DEFAULT_THREAD_PRIORITY 50 -bool iwasm_init(void) +bool +iwasm_init(void) { - int ret = aos_task_new("wasm-main", iwasm_main, NULL, - DEFAULT_THREAD_STACKSIZE); + int ret = + aos_task_new("wasm-main", iwasm_main, NULL, DEFAULT_THREAD_STACKSIZE); return ret == 0 ? true : false; } - diff --git a/product-mini/platforms/android/wasm-jni.cpp b/product-mini/platforms/android/wasm-jni.cpp index 2941754228..48ce6186f9 100644 --- a/product-mini/platforms/android/wasm-jni.cpp +++ b/product-mini/platforms/android/wasm-jni.cpp @@ -7,10 +7,11 @@ #include #define LOGI(...) \ - ((void)__android_log_print(ANDROID_LOG_INFO, "wasm_jni::", __VA_ARGS__)) + ((void)__android_log_print(ANDROID_LOG_INFO, "wasm_jni::", __VA_ARGS__)) static void * -app_instance_main(wasm_module_inst_t module_inst) { +app_instance_main(wasm_module_inst_t module_inst) +{ const char *exception; wasm_application_execute_main(module_inst, 0, NULL); @@ -58,20 +59,21 @@ static unsigned char wasm_test_file[] = { }; extern "C" JNIEXPORT void JNICALL -Java_com_intel_wasm_api_Runtime_run(JNIEnv *env, jclass thiz) { +Java_com_intel_wasm_api_Runtime_run(JNIEnv *env, jclass thiz) +{ 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}; + 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; + 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 */ @@ -82,7 +84,7 @@ Java_com_intel_wasm_api_Runtime_run(JNIEnv *env, jclass thiz) { /* load WASM byte buffer from a preinstall WASM bin file */ LOGI("use an internal test file, gona to output Hello World in logcat\n"); - wasm_file_buf = (uint8_t*) wasm_test_file; + wasm_file_buf = (uint8_t *)wasm_test_file; wasm_file_size = sizeof(wasm_test_file); /* load WASM module */ @@ -96,11 +98,10 @@ Java_com_intel_wasm_api_Runtime_run(JNIEnv *env, jclass thiz) { /* instantiate the module */ LOGI("wasm_runtime_instantiate"); - if (!(wasm_module_inst = wasm_runtime_instantiate(wasm_module, - 64 * 1024, /* stack size */ - 64 * 1024, /* heap size */ - error_buf, - sizeof(error_buf)))) { + if (!(wasm_module_inst = + wasm_runtime_instantiate(wasm_module, 64 * 1024, /* stack size */ + 64 * 1024, /* heap size */ + error_buf, sizeof(error_buf)))) { LOGI("%s\n", error_buf); LOGI("goto fail2\n"); goto fail2; @@ -121,7 +122,7 @@ Java_com_intel_wasm_api_Runtime_run(JNIEnv *env, jclass thiz) { 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); + // bh_free((void *) wasm_file_buf); /* destroy runtime environment */ LOGI("wasm_runtime_destroy"); diff --git a/product-mini/platforms/esp-idf/iwasm_main.c b/product-mini/platforms/esp-idf/iwasm_main.c index fd0d0a9a79..4f0d922e6f 100644 --- a/product-mini/platforms/esp-idf/iwasm_main.c +++ b/product-mini/platforms/esp-idf/iwasm_main.c @@ -14,7 +14,7 @@ static int app_argc; static char **app_argv; -static void* +static void * app_instance_main(wasm_module_inst_t module_inst) { const char *exception; @@ -27,7 +27,8 @@ app_instance_main(wasm_module_inst_t module_inst) static char global_heap_buf[CONFIG_GLOBAL_HEAP_BUF_SIZE] = { 0 }; -void iwasm_main(void) +void +iwasm_main(void) { uint8 *wasm_file_buf = NULL; uint32 wasm_file_size; @@ -60,7 +61,7 @@ void iwasm_main(void) #endif /* load WASM byte buffer from byte buffer of include file */ - wasm_file_buf = (uint8*)wasm_test_file; + wasm_file_buf = (uint8 *)wasm_test_file; wasm_file_size = sizeof(wasm_test_file); /* load WASM module */ @@ -73,11 +74,9 @@ void iwasm_main(void) os_printf("### wasm runtime load module success.\n"); /* instantiate the module */ - if (!(wasm_module_inst = wasm_runtime_instantiate(wasm_module, - CONFIG_APP_STACK_SIZE, - CONFIG_APP_HEAP_SIZE, - error_buf, - sizeof(error_buf)))) { + if (!(wasm_module_inst = wasm_runtime_instantiate( + wasm_module, CONFIG_APP_STACK_SIZE, CONFIG_APP_HEAP_SIZE, + error_buf, sizeof(error_buf)))) { os_printf("%s\n", error_buf); goto fail2; } diff --git a/product-mini/platforms/linux-sgx/enclave-sample/App/App.cpp b/product-mini/platforms/linux-sgx/enclave-sample/App/App.cpp index 14b8c415be..bd6b0e367e 100644 --- a/product-mini/platforms/linux-sgx/enclave-sample/App/App.cpp +++ b/product-mini/platforms/linux-sgx/enclave-sample/App/App.cpp @@ -26,7 +26,7 @@ #define FALSE 0 #endif -#define TOKEN_FILENAME "enclave.token" +#define TOKEN_FILENAME "enclave.token" #define ENCLAVE_FILENAME "enclave.signed.so" #define MAX_PATH 1024 @@ -41,7 +41,7 @@ pal_get_enclave_id(void) } void -ocall_print(const char* str) +ocall_print(const char *str) { printf("%s", str); } @@ -50,8 +50,7 @@ static char * get_exe_path(char *path_buf, unsigned path_buf_size) { ssize_t i; - ssize_t size = readlink("/proc/self/exe", - path_buf, path_buf_size - 1); + ssize_t size = readlink("/proc/self/exe", path_buf, path_buf_size - 1); if (size < 0 || (size >= path_buf_size - 1)) { return NULL; @@ -99,8 +98,9 @@ enclave_init(sgx_enclave_id_t *p_eid) home_dir = getpwuid(getuid())->pw_dir; size_t home_dir_len = home_dir ? strlen(home_dir) : 0; - if (home_dir != NULL && - home_dir_len <= MAX_PATH - 1 - sizeof(TOKEN_FILENAME) - strlen("/")) { + if (home_dir != NULL + && home_dir_len + <= MAX_PATH - 1 - sizeof(TOKEN_FILENAME) - strlen("/")) { /* compose the token path */ strncpy(token_path, home_dir, MAX_PATH); strncat(token_path, "/", strlen("/")); @@ -123,18 +123,19 @@ enclave_init(sgx_enclave_id_t *p_eid) if (read_num != 0 && read_num != sizeof(sgx_launch_token_t)) { /* if token is invalid, clear the buffer */ memset(&token, 0x0, sizeof(sgx_launch_token_t)); - printf("Warning: Invalid launch token read from \"%s\".\n", token_path); + printf("Warning: Invalid launch token read from \"%s\".\n", + token_path); } } /* Step 2: call sgx_create_enclave to initialize an enclave instance */ /* Debug Support: set 2nd parameter to 1 */ - ret = sgx_create_enclave(ENCLAVE_FILENAME, SGX_DEBUG_FLAG, - &token, &updated, p_eid, NULL); + ret = sgx_create_enclave(ENCLAVE_FILENAME, SGX_DEBUG_FLAG, &token, &updated, + p_eid, NULL); if (ret != SGX_SUCCESS) /* Try to load enclave.sign.so from the path of exe file */ - ret = sgx_create_enclave(enclave_path, SGX_DEBUG_FLAG, - &token, &updated, p_eid, NULL); + ret = sgx_create_enclave(enclave_path, SGX_DEBUG_FLAG, &token, &updated, + p_eid, NULL); if (ret != SGX_SUCCESS) { printf("Failed to create enclave from %s, error code: %d\n", ENCLAVE_FILENAME, ret); @@ -145,8 +146,10 @@ enclave_init(sgx_enclave_id_t *p_eid) /* Step 3: save the launch token if it is updated */ if (updated == FALSE || fp == NULL) { - /* if the token is not updated, or file handler is invalid, do not perform saving */ - if (fp != NULL) fclose(fp); + /* if the token is not updated, or file handler is invalid, + do not perform saving */ + if (fp != NULL) + fclose(fp); return 0; } @@ -176,8 +179,7 @@ read_file_to_buffer(const char *filename, uint32_t *ret_size) } if (!(file = fopen(filename, "r"))) { - printf("Read file to buffer failed: open file %s failed.\n", - filename); + printf("Read file to buffer failed: open file %s failed.\n", filename); return NULL; } @@ -185,7 +187,7 @@ read_file_to_buffer(const char *filename, uint32_t *ret_size) file_size = ftell(file); fseek(file, 0, SEEK_SET); - if (!(buffer = (unsigned char*)malloc(file_size))) { + if (!(buffer = (unsigned char *)malloc(file_size))) { printf("Read file to buffer failed: alloc memory failed.\n"); fclose(file); return NULL; @@ -205,6 +207,7 @@ read_file_to_buffer(const char *filename, uint32_t *ret_size) return buffer; } +/* clang-format off */ static int print_help() { @@ -227,6 +230,7 @@ print_help() printf(" --max-threads=n Set maximum thread number per cluster, default is 4\n"); return 1; } +/* clang-format on */ /** * Split a space separated strings into an array of strings @@ -287,8 +291,8 @@ typedef enum EcallCmd { } EcallCmd; static void -app_instance_func(void *wasm_module_inst, const char *func_name, - int app_argc, char **app_argv); +app_instance_func(void *wasm_module_inst, const char *func_name, int app_argc, + char **app_argv); static void * app_instance_repl(void *module_inst, int app_argc, char **app_argv) @@ -315,8 +319,8 @@ app_instance_repl(void *module_inst, int app_argc, char **app_argv) break; } if (app_argc != 0) { - app_instance_func(module_inst, app_argv[0], - app_argc - 1, app_argv + 1); + app_instance_func(module_inst, app_argv[0], app_argc - 1, + app_argv + 1); } free(app_argv); } @@ -349,9 +353,9 @@ set_log_verbose_level(int log_verbose_level) /* Set log verbose level */ if (log_verbose_level != 2) { ecall_args[0] = log_verbose_level; - if (SGX_SUCCESS != ecall_handle_command(g_eid, CMD_SET_LOG_LEVEL, - (uint8_t *)ecall_args, - sizeof(uint64_t))) { + if (SGX_SUCCESS + != ecall_handle_command(g_eid, CMD_SET_LOG_LEVEL, + (uint8_t *)ecall_args, sizeof(uint64_t))) { printf("Call ecall_handle_command() failed.\n"); return false; } @@ -366,9 +370,9 @@ init_runtime(bool alloc_with_pool, uint32_t max_thread_num) ecall_args[0] = alloc_with_pool; ecall_args[1] = max_thread_num; - if (SGX_SUCCESS != ecall_handle_command(g_eid, CMD_INIT_RUNTIME, - (uint8_t *)ecall_args, - sizeof(uint64_t) * 2)) { + if (SGX_SUCCESS + != ecall_handle_command(g_eid, CMD_INIT_RUNTIME, (uint8_t *)ecall_args, + sizeof(uint64_t) * 2)) { printf("Call ecall_handle_command() failed.\n"); return false; } @@ -382,15 +386,15 @@ init_runtime(bool alloc_with_pool, uint32_t max_thread_num) static void destroy_runtime() { - if (SGX_SUCCESS != ecall_handle_command(g_eid, CMD_DESTROY_RUNTIME, - NULL, 0)) { + if (SGX_SUCCESS + != ecall_handle_command(g_eid, CMD_DESTROY_RUNTIME, NULL, 0)) { printf("Call ecall_handle_command() failed.\n"); } } static void * -load_module(uint8_t *wasm_file_buf, uint32_t wasm_file_size, - char *error_buf, uint32_t error_buf_size) +load_module(uint8_t *wasm_file_buf, uint32_t wasm_file_size, char *error_buf, + uint32_t error_buf_size) { uint64_t ecall_args[4]; @@ -398,9 +402,9 @@ load_module(uint8_t *wasm_file_buf, uint32_t wasm_file_size, ecall_args[1] = wasm_file_size; ecall_args[2] = (uint64_t)(uintptr_t)error_buf; ecall_args[3] = error_buf_size; - if (SGX_SUCCESS != ecall_handle_command(g_eid, CMD_LOAD_MODULE, - (uint8_t *)ecall_args, - sizeof(uint64_t) * 4)) { + if (SGX_SUCCESS + != ecall_handle_command(g_eid, CMD_LOAD_MODULE, (uint8_t *)ecall_args, + sizeof(uint64_t) * 4)) { printf("Call ecall_handle_command() failed.\n"); return NULL; } @@ -414,16 +418,15 @@ unload_module(void *wasm_module) uint64_t ecall_args[1]; ecall_args[0] = (uint64_t)(uintptr_t)wasm_module; - if (SGX_SUCCESS != ecall_handle_command(g_eid, CMD_UNLOAD_MODULE, - (uint8_t *)ecall_args, - sizeof(uint64_t))) { + if (SGX_SUCCESS + != ecall_handle_command(g_eid, CMD_UNLOAD_MODULE, (uint8_t *)ecall_args, + sizeof(uint64_t))) { printf("Call ecall_handle_command() failed.\n"); } } static void * -instantiate_module(void *wasm_module, - uint32_t stack_size, uint32_t heap_size, +instantiate_module(void *wasm_module, uint32_t stack_size, uint32_t heap_size, char *error_buf, uint32_t error_buf_size) { uint64_t ecall_args[5]; @@ -433,9 +436,9 @@ instantiate_module(void *wasm_module, ecall_args[2] = heap_size; ecall_args[3] = (uint64_t)(uintptr_t)error_buf; ecall_args[4] = error_buf_size; - if (SGX_SUCCESS != ecall_handle_command(g_eid, CMD_INSTANTIATE_MODULE, - (uint8_t *)ecall_args, - sizeof(uint64_t) * 5)) { + if (SGX_SUCCESS + != ecall_handle_command(g_eid, CMD_INSTANTIATE_MODULE, + (uint8_t *)ecall_args, sizeof(uint64_t) * 5)) { printf("Call ecall_handle_command() failed.\n"); return NULL; } @@ -449,25 +452,24 @@ deinstantiate_module(void *wasm_module_inst) uint64_t ecall_args[1]; ecall_args[0] = (uint64_t)(uintptr_t)wasm_module_inst; - if (SGX_SUCCESS != ecall_handle_command(g_eid, CMD_DEINSTANTIATE_MODULE, - (uint8_t *)ecall_args, - sizeof(uint64_t))) { + if (SGX_SUCCESS + != ecall_handle_command(g_eid, CMD_DEINSTANTIATE_MODULE, + (uint8_t *)ecall_args, sizeof(uint64_t))) { printf("Call ecall_handle_command() failed.\n"); } } static bool -get_exception(void *wasm_module_inst, - char *exception, uint32_t exception_size) +get_exception(void *wasm_module_inst, char *exception, uint32_t exception_size) { uint64_t ecall_args[3]; ecall_args[0] = (uint64_t)(uintptr_t)wasm_module_inst; ecall_args[1] = (uint64_t)(uintptr_t)exception; ecall_args[2] = exception_size; - if (SGX_SUCCESS != ecall_handle_command(g_eid, CMD_GET_EXCEPTION, - (uint8_t *)ecall_args, - sizeof(uint64_t) * 3)) { + if (SGX_SUCCESS + != ecall_handle_command(g_eid, CMD_GET_EXCEPTION, (uint8_t *)ecall_args, + sizeof(uint64_t) * 3)) { printf("Call ecall_handle_command() failed.\n"); } @@ -475,16 +477,15 @@ get_exception(void *wasm_module_inst, } static void -app_instance_main(void *wasm_module_inst, - int app_argc, char **app_argv) +app_instance_main(void *wasm_module_inst, int app_argc, char **app_argv) { char exception[128]; uint64_t ecall_args_buf[16], *ecall_args = ecall_args_buf; int i, size; if (app_argc + 2 > sizeof(ecall_args_buf) / sizeof(uint64_t)) { - if (!(ecall_args = (uint64_t *) - malloc(sizeof(uint64_t) * (app_argc + 2)))) { + if (!(ecall_args = + (uint64_t *)malloc(sizeof(uint64_t) * (app_argc + 2)))) { printf("Allocate memory failed.\n"); return; } @@ -497,9 +498,9 @@ app_instance_main(void *wasm_module_inst, } size = (uint32_t)sizeof(uint64_t) * (app_argc + 2); - if (SGX_SUCCESS != ecall_handle_command(g_eid, CMD_EXEC_APP_MAIN, - (uint8_t *)ecall_args, - size)) { + if (SGX_SUCCESS + != ecall_handle_command(g_eid, CMD_EXEC_APP_MAIN, (uint8_t *)ecall_args, + size)) { printf("Call ecall_handle_command() failed.\n"); } @@ -513,15 +514,15 @@ app_instance_main(void *wasm_module_inst, } static void -app_instance_func(void *wasm_module_inst, const char *func_name, - int app_argc, char **app_argv) +app_instance_func(void *wasm_module_inst, const char *func_name, int app_argc, + char **app_argv) { uint64_t ecall_args_buf[16], *ecall_args = ecall_args_buf; int i, size; if (app_argc + 3 > sizeof(ecall_args_buf) / sizeof(uint64_t)) { - if (!(ecall_args = (uint64_t *) - malloc(sizeof(uint64_t) * (app_argc + 3)))) { + if (!(ecall_args = + (uint64_t *)malloc(sizeof(uint64_t) * (app_argc + 3)))) { printf("Allocate memory failed.\n"); return; } @@ -535,9 +536,9 @@ app_instance_func(void *wasm_module_inst, const char *func_name, } size = (uint32_t)sizeof(uint64_t) * (app_argc + 3); - if (SGX_SUCCESS != ecall_handle_command(g_eid, CMD_EXEC_APP_FUNC, - (uint8_t *)ecall_args, - size)) { + if (SGX_SUCCESS + != ecall_handle_command(g_eid, CMD_EXEC_APP_FUNC, (uint8_t *)ecall_args, + size)) { printf("Call ecall_handle_command() failed.\n"); } @@ -547,11 +548,9 @@ app_instance_func(void *wasm_module_inst, const char *func_name, } static bool -set_wasi_args(void *wasm_module, - const char **dir_list, uint32_t dir_list_size, - const char **env_list, uint32_t env_list_size, - int stdinfd, int stdoutfd, int stderrfd, - char **argv, uint32_t argc) +set_wasi_args(void *wasm_module, const char **dir_list, uint32_t dir_list_size, + const char **env_list, uint32_t env_list_size, int stdinfd, + int stdoutfd, int stderrfd, char **argv, uint32_t argc) { uint64_t ecall_args[10]; @@ -565,9 +564,9 @@ set_wasi_args(void *wasm_module, ecall_args[7] = stderrfd; ecall_args[8] = (uint64_t)(uintptr_t)argv; ecall_args[9] = argc; - if (SGX_SUCCESS != ecall_handle_command(g_eid, CMD_SET_WASI_ARGS, - (uint8_t *)ecall_args, - sizeof(uint64_t) * 10)) { + if (SGX_SUCCESS + != ecall_handle_command(g_eid, CMD_SET_WASI_ARGS, (uint8_t *)ecall_args, + sizeof(uint64_t) * 10)) { printf("Call ecall_handle_command() failed.\n"); } @@ -693,29 +692,28 @@ main(int argc, char *argv[]) /* Load WASM byte buffer from WASM bin file */ if (!(wasm_file_buf = - (uint8_t *)read_file_to_buffer(wasm_file, &wasm_file_size))) { + (uint8_t *)read_file_to_buffer(wasm_file, &wasm_file_size))) { goto fail1; } /* Load module */ - if (!(wasm_module = load_module(wasm_file_buf, wasm_file_size, - error_buf, sizeof(error_buf)))) { + if (!(wasm_module = load_module(wasm_file_buf, wasm_file_size, error_buf, + sizeof(error_buf)))) { printf("%s\n", error_buf); goto fail2; } /* Set wasi arguments */ - if (!set_wasi_args(wasm_module, dir_list, dir_list_size, - env_list, env_list_size, 0, 1, 2, argv, argc)) { + if (!set_wasi_args(wasm_module, dir_list, dir_list_size, env_list, + env_list_size, 0, 1, 2, argv, argc)) { printf("%s\n", "set wasi arguments failed.\n"); goto fail3; } /* Instantiate module */ - if (!(wasm_module_inst = instantiate_module(wasm_module, - stack_size, heap_size, - error_buf, - sizeof(error_buf)))) { + if (!(wasm_module_inst = + instantiate_module(wasm_module, stack_size, heap_size, error_buf, + sizeof(error_buf)))) { printf("%s\n", error_buf); goto fail3; } @@ -723,8 +721,7 @@ main(int argc, char *argv[]) if (is_repl_mode) app_instance_repl(wasm_module_inst, argc, argv); else if (func_name) - app_instance_func(wasm_module_inst, func_name, - argc - 1, argv + 1); + app_instance_func(wasm_module_inst, func_name, argc - 1, argv + 1); else app_instance_main(wasm_module_inst, argc, argv); @@ -782,19 +779,19 @@ wamr_pal_create_process(struct wamr_pal_create_process_args *args) int stderrfd = -1; int argc = 2; - char *argv[argc] = { (char*)"./iwasm", (char *)args->argv[0] }; + char *argv[argc] = { (char *)"./iwasm", (char *)args->argv[0] }; uint8_t *wasm_files_buf = NULL; void *wasm_modules = NULL; int len = 0, i; char *temp = (char *)args->argv[0]; - while(temp) { + while (temp) { len++; - temp=(char *)args->argv[len]; + temp = (char *)args->argv[len]; } - if (len > sizeof(wasm_files)/sizeof(char *)) { + if (len > sizeof(wasm_files) / sizeof(char *)) { printf("Number of input files is out of range\n"); return -1; } @@ -829,8 +826,8 @@ wamr_pal_create_process(struct wamr_pal_create_process_args *args) char error_buf[128] = { 0 }; /* Load WASM byte buffer from WASM bin file */ - if (!(wasm_file_buf = (uint8_t *)read_file_to_buffer - (wasm_files[i], &wasm_file_size))) { + if (!(wasm_file_buf = (uint8_t *)read_file_to_buffer( + wasm_files[i], &wasm_file_size))) { printf("Failed to read file to buffer\n"); destroy_runtime(); return -1; @@ -846,10 +843,9 @@ wamr_pal_create_process(struct wamr_pal_create_process_args *args) } /* Set wasi arguments */ - if (!set_wasi_args(wasm_module, dir_list, dir_list_size, - env_list, env_list_size, - stdinfd, stdoutfd, stderrfd, - argv, argc)) { + if (!set_wasi_args(wasm_module, dir_list, dir_list_size, env_list, + env_list_size, stdinfd, stdoutfd, stderrfd, argv, + argc)) { printf("%s\n", "set wasi arguments failed.\n"); unload_module(wasm_module); free(wasm_file_buf); @@ -858,10 +854,9 @@ wamr_pal_create_process(struct wamr_pal_create_process_args *args) } /* Instantiate module */ - if (!(wasm_module_inst[i] = instantiate_module(wasm_module, - stack_size, heap_size, - error_buf, - sizeof(error_buf)))) { + if (!(wasm_module_inst[i] = + instantiate_module(wasm_module, stack_size, heap_size, + error_buf, sizeof(error_buf)))) { printf("%s\n", error_buf); unload_module(wasm_module); free(wasm_file_buf); @@ -884,37 +879,43 @@ wamr_pal_create_process(struct wamr_pal_create_process_args *args) int wamr_pal_destroy(void) { - //sgx_destroy_enclave(g_eid); + // sgx_destroy_enclave(g_eid); return 0; } int wamr_pal_exec(struct wamr_pal_exec_args *args) { - //app_instance_main(wasm_module_inst[i], argc, argv); + // app_instance_main(wasm_module_inst[i], argc, argv); return 0; } int wamr_pal_kill(int pid, int sig) { - //deinstantiate_module(wasm_module_inst[i]); - //unload_module(wasm_module); - //free(wasm_file_buf); + // deinstantiate_module(wasm_module_inst[i]); + // unload_module(wasm_module); + // free(wasm_file_buf); return 0; } -int pal_get_version(void) __attribute__((weak, alias ("wamr_pal_get_version"))); +int +pal_get_version(void) __attribute__((weak, alias("wamr_pal_get_version"))); -int pal_init(const struct wamr_pal_attr *attr)\ -__attribute__ ((weak, alias ("wamr_pal_init"))); +int +pal_init(const struct wamr_pal_attr *attr) + __attribute__((weak, alias("wamr_pal_init"))); -int pal_create_process(struct wamr_pal_create_process_args *args)\ -__attribute__ ((weak, alias ("wamr_pal_create_process"))); +int +pal_create_process(struct wamr_pal_create_process_args *args) + __attribute__((weak, alias("wamr_pal_create_process"))); -int pal_exec(struct wamr_pal_exec_args *args)\ -__attribute__ ((weak, alias ("wamr_pal_exec"))); +int +pal_exec(struct wamr_pal_exec_args *args) + __attribute__((weak, alias("wamr_pal_exec"))); -int pal_kill(int pid, int sig) __attribute__ ((weak, alias ("wamr_pal_kill"))); +int +pal_kill(int pid, int sig) __attribute__((weak, alias("wamr_pal_kill"))); -int pal_destroy(void) __attribute__ ((weak, alias ("wamr_pal_destroy"))); +int +pal_destroy(void) __attribute__((weak, alias("wamr_pal_destroy"))); diff --git a/product-mini/platforms/linux-sgx/enclave-sample/App/pal_api.h b/product-mini/platforms/linux-sgx/enclave-sample/App/pal_api.h index 55668f3045..6f6ae73275 100644 --- a/product-mini/platforms/linux-sgx/enclave-sample/App/pal_api.h +++ b/product-mini/platforms/linux-sgx/enclave-sample/App/pal_api.h @@ -20,7 +20,8 @@ extern "C" { * * @retval If > 0, then success; otherwise, it is an invalid version. */ -int wamr_pal_get_version(void); +int +wamr_pal_get_version(void); /* * WAMR PAL attributes @@ -29,19 +30,21 @@ typedef struct wamr_pal_attr { // WAMR instance directory. // // The default value is "."; that is, the current working directory - const char *instance_dir; + const char *instance_dir; // Log level. // // Specifies the log verbose level (0 to 5, default is 2) // large level with more log // - const char *log_level; + const char *log_level; } wamr_pal_attr_t; +/* clang-format off */ #define WAMR_PAL_ATTR_INITVAL { \ .instance_dir = ".", \ .log_level = 2 \ } +/* clang-format on */ /* * The struct which consists of file descriptors of standard I/O @@ -66,21 +69,23 @@ struct wamr_pal_create_process_args { // Argments array pass to new process. // - // The arguments to the command. By convention, the argv[0] should be the program name. - // And the last element of the array must be NULL to indicate the length of array. + // The arguments to the command. By convention, the argv[0] should be the + // program name. And the last element of the array must be NULL to indicate + // the length of array. // // Mandatory field. Must not be NULL. const char **argv; // Untrusted environment variable array pass to new process. // - // The untrusted env vars to the command. And the last element of the array must be - // NULL to indicate the length of array. + // The untrusted env vars to the command. And the last element of the array + // must be NULL to indicate the length of array. // // Optional field. const char **env; - // File descriptors of the redirected standard I/O (i.e., stdin, stdout, stderr) + // File descriptors of the redirected standard I/O (i.e., stdin, stdout, + // stderr) // // If set to NULL, will use the original standard I/O file descriptors. // @@ -115,32 +120,41 @@ struct wamr_pal_exec_args { int *exit_value; }; -int wamr_pal_init(const struct wamr_pal_attr *args); +int +wamr_pal_init(const struct wamr_pal_attr *args); -int wamr_pal_create_process(struct wamr_pal_create_process_args *args); +int +wamr_pal_create_process(struct wamr_pal_create_process_args *args); -int wamr_pal_destroy(void); +int +wamr_pal_destroy(void); -int wamr_pal_exec(struct wamr_pal_exec_args *args); +int +wamr_pal_exec(struct wamr_pal_exec_args *args); -int wamr_pal_kill(int pid, int sig); +int +wamr_pal_kill(int pid, int sig); -int pal_get_version(void); +int +pal_get_version(void); -int pal_init(const struct wamr_pal_attr *attr); +int +pal_init(const struct wamr_pal_attr *attr); -int pal_create_process(struct wamr_pal_create_process_args *args); +int +pal_create_process(struct wamr_pal_create_process_args *args); -int pal_exec(struct wamr_pal_exec_args *args); +int +pal_exec(struct wamr_pal_exec_args *args); -int pal_kill(int pid, int sig); - -int pal_destroy(void); +int +pal_kill(int pid, int sig); +int +pal_destroy(void); #ifdef __cplusplus } #endif #endif /* __WAMR_PAL_API_H__ */ - 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 15ce6c290d..b9fafe4529 100644 --- a/product-mini/platforms/linux-sgx/enclave-sample/Enclave/Enclave.cpp +++ b/product-mini/platforms/linux-sgx/enclave-sample/Enclave/Enclave.cpp @@ -13,14 +13,15 @@ #include "bh_platform.h" extern "C" { - typedef void (*os_print_function_t)(const char* message); - extern void os_set_print_function(os_print_function_t pf); +typedef void (*os_print_function_t)(const char *message); +extern void +os_set_print_function(os_print_function_t pf); - void - enclave_print(const char *message) - { - ocall_print(message); - } +void +enclave_print(const char *message) +{ + ocall_print(message); +} } typedef enum EcallCmd { @@ -130,8 +131,8 @@ handle_cmd_load_module(uint64 *args, uint32 argc) bh_assert(argc == 4); if (total_size >= UINT32_MAX - || !(enclave_module = (EnclaveModule *) - wasm_runtime_malloc((uint32)total_size))) { + || !(enclave_module = + (EnclaveModule *)wasm_runtime_malloc((uint32)total_size))) { set_error_buf(error_buf, error_buf_size, "WASM module load failed: " "allocate memory failed."); @@ -140,14 +141,13 @@ handle_cmd_load_module(uint64 *args, uint32 argc) } memset(enclave_module, 0, (uint32)total_size); - enclave_module->wasm_file = (uint8 *)enclave_module - + sizeof(EnclaveModule); - bh_memcpy_s(enclave_module->wasm_file, wasm_file_size, - wasm_file, wasm_file_size); + enclave_module->wasm_file = (uint8 *)enclave_module + sizeof(EnclaveModule); + bh_memcpy_s(enclave_module->wasm_file, wasm_file_size, wasm_file, + wasm_file_size); if (!(enclave_module->module = - wasm_runtime_load(enclave_module->wasm_file, wasm_file_size, - error_buf, error_buf_size))) { + wasm_runtime_load(enclave_module->wasm_file, wasm_file_size, + error_buf, error_buf_size))) { wasm_runtime_free(enclave_module); *(void **)args_org = NULL; return; @@ -189,9 +189,8 @@ handle_cmd_instantiate_module(uint64 *args, uint32 argc) bh_assert(argc == 5); if (!(module_inst = - wasm_runtime_instantiate(enclave_module->module, - stack_size, heap_size, - error_buf, error_buf_size))) { + wasm_runtime_instantiate(enclave_module->module, stack_size, + heap_size, error_buf, error_buf_size))) { *(void **)args_org = NULL; return; } @@ -225,8 +224,7 @@ handle_cmd_get_exception(uint64 *args, uint32 argc) bh_assert(argc == 3); if ((exception1 = wasm_runtime_get_exception(module_inst))) { - snprintf(exception, exception_size, - "%s", exception1); + snprintf(exception, exception_size, "%s", exception1); args_org[0] = true; } else { @@ -339,15 +337,14 @@ handle_cmd_set_wasi_args(uint64 *args, int32 argc) } if (total_size >= UINT32_MAX - || !(enclave_module->wasi_arg_buf = p = (char *) - wasm_runtime_malloc((uint32)total_size))) { + || !(enclave_module->wasi_arg_buf = p = + (char *)wasm_runtime_malloc((uint32)total_size))) { *args_org = false; return; } - p1 = p + sizeof(char *) * dir_list_size - + sizeof(char *) * env_list_size - + sizeof(char *) * wasi_argc; + p1 = p + sizeof(char *) * dir_list_size + sizeof(char *) * env_list_size + + sizeof(char *) * wasi_argc; if (dir_list_size > 0) { enclave_module->wasi_dir_list = (char **)p; @@ -385,17 +382,12 @@ handle_cmd_set_wasi_args(uint64 *args, int32 argc) p += sizeof(char *) * wasi_argc; } - wasm_runtime_set_wasi_args_ex(enclave_module->module, - (const char **)enclave_module->wasi_dir_list, - dir_list_size, - NULL, 0, - (const char **)enclave_module->wasi_env_list, - env_list_size, - enclave_module->wasi_argv, - enclave_module->wasi_argc, - (stdinfd != -1) ? stdinfd : 0, - (stdoutfd != -1) ? stdoutfd : 1, - (stderrfd != -1) ? stderrfd : 2); + wasm_runtime_set_wasi_args_ex( + enclave_module->module, (const char **)enclave_module->wasi_dir_list, + dir_list_size, NULL, 0, (const char **)enclave_module->wasi_env_list, + env_list_size, enclave_module->wasi_argv, enclave_module->wasi_argc, + (stdinfd != -1) ? stdinfd : 0, (stdoutfd != -1) ? stdoutfd : 1, + (stderrfd != -1) ? stderrfd : 2); *args_org = true; } @@ -408,8 +400,7 @@ handle_cmd_set_wasi_args(uint64 *args, int32 argc) #endif /* end of SGX_DISABLE_WASI */ void -ecall_handle_command(unsigned cmd, - unsigned char *cmd_buf, +ecall_handle_command(unsigned cmd, unsigned char *cmd_buf, unsigned cmd_buf_size) { uint64 *args = (uint64 *)cmd_buf; @@ -494,11 +485,9 @@ ecall_iwasm_main(uint8_t *wasm_file_buf, uint32_t wasm_file_size) } /* instantiate the module */ - if (!(wasm_module_inst = wasm_runtime_instantiate(wasm_module, - 16 * 1024, - 16 * 1024, - error_buf, - sizeof(error_buf)))) { + if (!(wasm_module_inst = + wasm_runtime_instantiate(wasm_module, 16 * 1024, 16 * 1024, + error_buf, sizeof(error_buf)))) { ocall_print(error_buf); ocall_print("\n"); goto fail2; diff --git a/product-mini/platforms/linux-sgx/enclave-sample/Enclave/Enclave_test.cpp b/product-mini/platforms/linux-sgx/enclave-sample/Enclave/Enclave_test.cpp index 12632a0297..2ae6454d61 100644 --- a/product-mini/platforms/linux-sgx/enclave-sample/Enclave/Enclave_test.cpp +++ b/product-mini/platforms/linux-sgx/enclave-sample/Enclave/Enclave_test.cpp @@ -8,7 +8,8 @@ #include "wasm_export.h" #include "bh_platform.h" -void ecall_iwasm_test() +void +ecall_iwasm_test() { ocall_print(" Prepare to invoke sgx_open ... ==>\n\n"); @@ -76,7 +77,7 @@ void ecall_iwasm_test() 02 : - O_RDWR */ /** 1. open **/ fd = open(file, O_RDWR); - if (fd !=-1) { + if (fd != -1) { ocall_print("\tOperation open test_open.txt success.\n"); } @@ -107,7 +108,7 @@ void ecall_iwasm_test() ocall_print("\tOperation fdatasync success.\n"); } - /** isatty **/ + /** isatty **/ ret = isatty(fd); if (ret == 0) { ocall_print("\tOperation fisatty success.\n"); @@ -140,7 +141,7 @@ void ecall_iwasm_test() p_dirent = readdir(dirp); if (p_dirent != NULL) { ocall_print("\tOperation readdir success.\t"); - ocall_print(p_dirent -> d_name); + ocall_print(p_dirent->d_name); ocall_print("\n"); } @@ -158,7 +159,7 @@ void ecall_iwasm_test() /** closedir **/ ret = closedir(dirp); - if (ret == 0 ) { + if (ret == 0) { ocall_print("\tOperation closedir success. \n"); } /* 2. close */ @@ -192,7 +193,7 @@ void ecall_iwasm_test() ret = renameat(AT_FDCWD, rlt_dir_path, AT_FDCWD, rlt_dir_path_new); if (ret == 0) { ocall_print("\tOperation renameat ./tmp to " - "./tmp_new success. \n"); + "./tmp_new success. \n"); } renameat(AT_FDCWD, rlt_dir_path_new, AT_FDCWD, rlt_dir_path); @@ -220,7 +221,7 @@ void ecall_iwasm_test() ret = symlinkat(file, AT_FDCWD, file_sf_ln); if (ret == 0) { ocall_print("\tOperation symlinkat from test.txt " - "to text_sf_ln.txt success. \n"); + "to text_sf_ln.txt success. \n"); } /** readlinkat **/ total_size = readlinkat(AT_FDCWD, file_sf_ln, buf, sizeof(buf)); @@ -336,22 +337,23 @@ void ecall_iwasm_test() close(fd); /** getopt **/ - while((ret = getopt(argc, argv, "f:abc")) != -1){ //get option from the getopt() method - switch(ret){ - //For option i, r, l, print that these are options - case 'a': - case 'b': - case 'c': - ocall_print("\tGiven Option operation success. \n"); - break; - case 'f': //here f is used for some file name - ocall_print("\tGiven File operation success.\n"); - break; - case '?': //used for some unknown options - ocall_print("\tunknown option trigger success.\n"); - break; - } - } + while ((ret = getopt(argc, argv, "f:abc")) + != -1) { // get option from the getopt() method + switch (ret) { + // For option i, r, l, print that these are options + case 'a': + case 'b': + case 'c': + ocall_print("\tGiven Option operation success. \n"); + break; + case 'f': // here f is used for some file name + ocall_print("\tGiven File operation success.\n"); + break; + case '?': // used for some unknown options + ocall_print("\tunknown option trigger success.\n"); + break; + } + } /** sched_yield **/ ret = sched_yield(); diff --git a/product-mini/platforms/posix/main.c b/product-mini/platforms/posix/main.c index de24175160..ecdd7973bd 100644 --- a/product-mini/platforms/posix/main.c +++ b/product-mini/platforms/posix/main.c @@ -18,6 +18,7 @@ static char **app_argv; #define MODULE_PATH ("--module-path=") +/* clang-format off */ static int print_help() { @@ -55,6 +56,7 @@ print_help() #endif return 1; } +/* clang-format on */ static void * app_instance_main(wasm_module_inst_t module_inst) @@ -194,8 +196,8 @@ module_reader_callback(const char *module_name, uint8 **p_buffer, uint32 *p_size) { const char *format = "%s/%s.wasm"; - int sz = strlen(module_search_path) + strlen("/") + strlen(module_name) + - strlen(".wasm") + 1; + int sz = strlen(module_search_path) + strlen("/") + strlen(module_name) + + strlen(".wasm") + 1; char *wasm_file_name = BH_MALLOC(sz); if (!wasm_file_name) { return false; @@ -245,12 +247,12 @@ main(int argc, char *argv[]) uint32 env_list_size = 0; #endif #if WASM_ENABLE_DEBUG_INTERP != 0 - char * ip_addr = NULL; - //int platform_port = 0; + char *ip_addr = NULL; + /* int platform_port = 0; */ int instance_port = 0; #endif - /* Process options. */ + /* Process options. */ for (argc--, argv++; argc > 0 && argv[0][0] == '-'; argc--, argv++) { if (!strcmp(argv[0], "-f") || !strcmp(argv[0], "--function")) { argc--, argv++; @@ -332,7 +334,7 @@ main(int argc, char *argv[]) #endif #if WASM_ENABLE_DEBUG_INTERP != 0 else if (!strncmp(argv[0], "-g=", 3)) { - char * port_str = strchr(argv[0] + 3, ':'); + char *port_str = strchr(argv[0] + 3, ':'); char *port_end; if (port_str == NULL) return print_help(); @@ -386,7 +388,7 @@ main(int argc, char *argv[]) /* load WASM byte buffer from WASM bin file */ if (!(wasm_file_buf = - (uint8 *)bh_read_file_to_buffer(wasm_file, &wasm_file_size))) + (uint8 *)bh_read_file_to_buffer(wasm_file, &wasm_file_size))) goto fail1; if (is_xip_mode) { @@ -394,15 +396,15 @@ main(int argc, char *argv[]) int map_prot = MMAP_PROT_READ | MMAP_PROT_WRITE | MMAP_PROT_EXEC; int map_flags = MMAP_MAP_NONE; - if (!(wasm_file_mapped = os_mmap(NULL, (uint32)wasm_file_size, - map_prot, map_flags))) { + if (!(wasm_file_mapped = + os_mmap(NULL, (uint32)wasm_file_size, map_prot, map_flags))) { printf("mmap memory failed\n"); wasm_runtime_free(wasm_file_buf); goto fail1; } - bh_memcpy_s(wasm_file_mapped, wasm_file_size, - wasm_file_buf, wasm_file_size); + bh_memcpy_s(wasm_file_mapped, wasm_file_size, wasm_file_buf, + wasm_file_size); wasm_runtime_free(wasm_file_buf); wasm_file_buf = wasm_file_mapped; } @@ -425,8 +427,8 @@ main(int argc, char *argv[]) /* instantiate the module */ if (!(wasm_module_inst = - wasm_runtime_instantiate(wasm_module, stack_size, heap_size, - error_buf, sizeof(error_buf)))) { + wasm_runtime_instantiate(wasm_module, stack_size, heap_size, + error_buf, sizeof(error_buf)))) { printf("%s\n", error_buf); goto fail3; } diff --git a/product-mini/platforms/riot/iwasmt.c b/product-mini/platforms/riot/iwasmt.c index 7f6b75fbc1..955a15941d 100644 --- a/product-mini/platforms/riot/iwasmt.c +++ b/product-mini/platforms/riot/iwasmt.c @@ -4,19 +4,17 @@ * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ -// #include #include #include #include -// #include "platform_api_extension.h" #include "wasm_export.h" #include -/*provide some test program*/ +/* provide some test program */ #include "test_wasm.h" #define DEFAULT_THREAD_STACKSIZE (6 * 1024) @@ -25,31 +23,31 @@ static int app_argc; static char **app_argv; -static void* +static void * app_instance_main(wasm_module_inst_t module_inst) { const char *exception; wasm_application_execute_main(module_inst, app_argc, app_argv); - if ((exception = wasm_runtime_get_exception(module_inst))){ + if ((exception = wasm_runtime_get_exception(module_inst))) { puts(exception); } return NULL; } - void * iwasm_t(void *arg1) { - wasm_module_t wasm_module = (wasm_module_t) arg1; + wasm_module_t wasm_module = (wasm_module_t)arg1; wasm_module_inst_t wasm_module_inst = NULL; char error_buf[128]; - + /* 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)))) { puts(error_buf); - }else{ + } + else { app_instance_main(wasm_module_inst); /* destroy the module instance */ wasm_runtime_deinstantiate(wasm_module_inst); @@ -57,10 +55,14 @@ iwasm_t(void *arg1) return NULL; } +/* choose allocator */ +#define FUNC_ALLOC +/* #define POOL_ALLOC */ + void * iwasm_main(void *arg1) { - (void) arg1; /*unused*/ + (void)arg1; /* unused */ uint8_t *wasm_file_buf = NULL; unsigned wasm_file_buf_size = 0; wasm_module_t wasm_module = NULL; @@ -68,13 +70,9 @@ iwasm_main(void *arg1) RuntimeInitArgs init_args; -//chose allocator -#define FUNC_ALLOC -//#define POOL_ALLOC - memset(&init_args, 0, sizeof(RuntimeInitArgs)); #ifdef POOL_ALLOC - static char global_heap_buf[256 * 1024] = { 0 };//(256 kB) + static char global_heap_buf[256 * 1024] = { 0 }; /* 256 kB */ init_args.mem_alloc_type = Alloc_With_Pool; init_args.mem_alloc_option.pool.heap_buf = global_heap_buf; @@ -94,17 +92,16 @@ iwasm_main(void *arg1) return NULL; } - /* load WASM byte buffer from byte buffer of include file */ - wasm_file_buf = (uint8_t *) wasm_test_file; + wasm_file_buf = (uint8_t *)wasm_test_file; wasm_file_buf_size = sizeof(wasm_test_file); /* load WASM module */ if (!(wasm_module = wasm_runtime_load(wasm_file_buf, wasm_file_buf_size, error_buf, sizeof(error_buf)))) { puts(error_buf); - - }else{ + } + else { iwasm_t(wasm_module); wasm_runtime_unload(wasm_module); } @@ -116,14 +113,15 @@ iwasm_main(void *arg1) bool iwasm_init(void) { - struct{ - char * stack; - int stacksize; - uint8_t priority; - int flags; + /* clang-format off */ + struct { + char *stack; + int stacksize; + uint8_t priority; + int flags; thread_task_func_t task_func; - void * arg; - const char * name; + void *arg; + const char *name; } b = { .stacksize = DEFAULT_THREAD_STACKSIZE, .priority = 8, @@ -132,17 +130,20 @@ iwasm_init(void) .arg = NULL, .name = "simple_wamr" }; + /* clang-format on */ - b.stack=malloc(b.stacksize); - kernel_pid_t tpid = thread_create (b.stack, b.stacksize, b.priority, b.flags, b.task_func, b.arg, b.name); + b.stack = malloc(b.stacksize); + kernel_pid_t tpid = thread_create(b.stack, b.stacksize, b.priority, b.flags, + b.task_func, b.arg, b.name); - return tpid != 0 ? true : false;; + return tpid != 0 ? true : false; + ; } -#define telltruth(X) ((X) ? "true" : "false") +#define telltruth(X) ((X) ? "true" : "false") int main(void) { - printf("iwasm_initilised: %s\n",telltruth(iwasm_init())); + printf("iwasm_initilised: %s\n", telltruth(iwasm_init())); } diff --git a/product-mini/platforms/rt-thread/iwasm.c b/product-mini/platforms/rt-thread/iwasm.c index c7ab46a8a9..8ae4da7617 100644 --- a/product-mini/platforms/rt-thread/iwasm.c +++ b/product-mini/platforms/rt-thread/iwasm.c @@ -15,17 +15,21 @@ #ifdef WAMR_ENABLE_RTT_EXPORT #ifdef WAMR_RTT_EXPORT_VPRINTF -static int wasm_vprintf(wasm_exec_env_t env, const char* fmt, va_list va) +static int +wasm_vprintf(wasm_exec_env_t env, const char *fmt, va_list va) { return vprintf(fmt, va); } -static int wasm_vsprintf(wasm_exec_env_t env, char* buf, const char* fmt, va_list va) +static int +wasm_vsprintf(wasm_exec_env_t env, char *buf, const char *fmt, va_list va) { return vsprintf(buf, fmt, va); } -static int wasm_vsnprintf(wasm_exec_env_t env, char *buf, int n, const char *fmt, va_list va) +static int +wasm_vsnprintf(wasm_exec_env_t env, char *buf, int n, const char *fmt, + va_list va) { return vsnprintf(buf, n, fmt, va); } @@ -33,118 +37,127 @@ static int wasm_vsnprintf(wasm_exec_env_t env, char *buf, int n, const char *fmt #endif /* WAMR_RTT_EXPORT_VPRINTF */ #ifdef WAMR_RTT_EXPORT_DEVICE_OPS -static rt_device_t wasm_rt_device_find(wasm_exec_env_t env, const char *name) +static rt_device_t +wasm_rt_device_find(wasm_exec_env_t env, const char *name) { return rt_device_find(name); } -static rt_err_t wasm_rt_device_open(wasm_exec_env_t env, rt_device_t dev, rt_uint16_t o_flag) +static rt_err_t +wasm_rt_device_open(wasm_exec_env_t env, rt_device_t dev, rt_uint16_t o_flag) { - return rt_device_open(dev , o_flag); + return rt_device_open(dev, o_flag); } -static rt_size_t wasm_rt_device_write(wasm_exec_env_t env, rt_device_t dev, rt_off_t offset, const void*buf, rt_size_t size) +static rt_size_t +wasm_rt_device_write(wasm_exec_env_t env, rt_device_t dev, rt_off_t offset, + const void *buf, rt_size_t size) { return rt_device_write(dev, offset, buf, size); } -static rt_size_t wasm_rt_device_read(wasm_exec_env_t env, rt_device_t dev, rt_off_t offset, void *buf, rt_size_t size) +static rt_size_t +wasm_rt_device_read(wasm_exec_env_t env, rt_device_t dev, rt_off_t offset, + void *buf, rt_size_t size) { return rt_device_read(dev, offset, buf, size); } -static rt_err_t wasm_rt_device_close(wasm_exec_env_t env, rt_device_t dev) +static rt_err_t +wasm_rt_device_close(wasm_exec_env_t env, rt_device_t dev) { return rt_device_close(dev); } -static rt_err_t wasm_rt_device_control(wasm_exec_env_t env, rt_device_t dev, int cmd, void *arg) +static rt_err_t +wasm_rt_device_control(wasm_exec_env_t env, rt_device_t dev, int cmd, void *arg) { return rt_device_control(dev, cmd, arg); } #endif /* WAMR_RTT_EXPORT_DEVICE_OPS */ +/* clang-format off */ static NativeSymbol native_export_symbols[] = { - #ifdef WAMR_RTT_EXPORT_VPRINTF - { - "vprintf", - wasm_vprintf, - "($*)i" - }, - { - "vsprintf", - wasm_vsprintf, - "($$*)i" - }, - { - "vsnprintf", - wasm_vsnprintf, - "($i$*)i" - }, + { + "vprintf", + wasm_vprintf, + "($*)i" + }, + { + "vsprintf", + wasm_vsprintf, + "($$*)i" + }, + { + "vsnprintf", + wasm_vsnprintf, + "($i$*)i" + }, #endif /* WAMR_RTT_EXPORT_VPRINTF */ #ifdef WAMR_RTT_EXPORT_DEVICE_OPS - { - "rt_device_find", - wasm_rt_device_find, - "($)i" - }, - { - "rt_device_open", - wasm_rt_device_open, - "(ii)i" - }, - { - "rt_device_write", - wasm_rt_device_write, - "(ii*~)i" - }, - { - "rt_device_read", - wasm_rt_device_read, - "(ii*~)i" - }, - { - "rt_device_close", - wasm_rt_device_close, - "(i)i" - }, - { - "rt_device_control", - wasm_rt_device_control, - "(ii*)i" - }, + { + "rt_device_find", + wasm_rt_device_find, + "($)i" + }, + { + "rt_device_open", + wasm_rt_device_open, + "(ii)i" + }, + { + "rt_device_write", + wasm_rt_device_write, + "(ii*~)i" + }, + { + "rt_device_read", + wasm_rt_device_read, + "(ii*~)i" + }, + { + "rt_device_close", + wasm_rt_device_close, + "(i)i" + }, + { + "rt_device_control", + wasm_rt_device_control, + "(ii*)i" + }, #ifdef WAMR_RTT_EXPORT_DEVICE_OPS_CPP - { - "_Z15rt_device_closeP9rt_device", - wasm_rt_device_close, - "(i)i" - }, - { - "_Z14rt_device_readP9rt_devicejPvj", - wasm_rt_device_read, - "(ii*~)i" - }, - { - "_Z15rt_device_writeP9rt_devicejPKvj", - wasm_rt_device_write, - "(ii*~)i" - }, - { - "_Z14rt_device_openP9rt_devicet", - wasm_rt_device_open, - "(ii)i" - }, - { - "_Z14rt_device_findPKc", - wasm_rt_device_find, - "($)i" - }, + { + "_Z15rt_device_closeP9rt_device", + wasm_rt_device_close, + "(i)i" + }, + { + "_Z14rt_device_readP9rt_devicejPvj", + wasm_rt_device_read, + "(ii*~)i" + }, + { + "_Z15rt_device_writeP9rt_devicejPKvj", + wasm_rt_device_write, + "(ii*~)i" + }, + { + "_Z14rt_device_openP9rt_devicet", + wasm_rt_device_open, + "(ii)i" + }, + { + "_Z14rt_device_findPKc", + wasm_rt_device_find, + "($)i" + }, #endif /* WAMR_RTT_EXPORT_DEVICE_OPS_CPP */ #endif /* WAMR_RTT_EXPORT_DEVICE_OPS */ }; +/* clang-format on */ #endif /* WAMR_ENABLE_RTT_EXPORT */ @@ -166,23 +179,22 @@ app_instance_main(wasm_module_inst_t module_inst, int app_argc, char **app_argv) return NULL; } -rt_uint8_t *my_read_file_to_buffer(char* filename, rt_uint32_t *size) +rt_uint8_t * +my_read_file_to_buffer(char *filename, rt_uint32_t *size) { struct stat f_stat; dfs_file_stat(filename, &f_stat); struct dfs_fd fd; - rt_uint8_t* buff = rt_malloc(f_stat.st_size); + rt_uint8_t *buff = rt_malloc(f_stat.st_size); *size = 0; - if (!buff) - { + if (!buff) { rt_set_errno(-ENOMEM); return RT_NULL; } int ret = dfs_file_open(&fd, filename, O_RDONLY); - if (ret) - { + if (ret) { rt_free(buff); rt_set_errno(ret); return RT_NULL; @@ -192,8 +204,7 @@ rt_uint8_t *my_read_file_to_buffer(char* filename, rt_uint32_t *size) dfs_file_close(&fd); - if (*size != f_stat.st_size) - { + if (*size != f_stat.st_size) { rt_free(buff); rt_set_errno(-EBADF); return RT_NULL; @@ -202,20 +213,23 @@ rt_uint8_t *my_read_file_to_buffer(char* filename, rt_uint32_t *size) return buff; } -void iwasm_help(void) +void +iwasm_help(void) { #ifdef WAMR_ENABLE_IWASM_PARAMS - rt_kputs("wrong input: iwasm [-t] [-m] [-s] <*.wasm> \n iwasm [-h]\n"); + rt_kputs("wrong input: iwasm [-t] [-m] [-s] <*.wasm> \n" + " iwasm [-h]\n"); rt_kputs("\t -h: show this tips.\n"); rt_kputs("\t -t: show time taking to run this app.\n"); rt_kputs("\t -m: show memory taking to run this app\n"); rt_kputs("\t wasm file name and exec params must behind of all vm-param\n"); #else rt_kputs("wrong input: iwasm <*.wasm> \n"); -#endif /* WAMR_ENABLE_PARAMS */ +#endif /* WAMR_ENABLE_PARAMS */ } -int iwasm(int argc, char **argv) +int +iwasm(int argc, char **argv) { rt_uint8_t *wasm_file_buf = NULL; rt_uint32_t wasm_file_size; @@ -224,52 +238,43 @@ int iwasm(int argc, char **argv) wasm_module_inst_t wasm_module_inst = NULL; RuntimeInitArgs init_args; static char error_buf[128] = { 0 }; - // avoid stack overflow + /* avoid stack overflow */ #ifdef WAMR_ENABLE_IWASM_PARAMS int i_arg_begin; bool show_mem = false; bool show_stack = false; bool show_time_exec = false; - for(i_arg_begin=1; i_arg_begin < argc; i_arg_begin++) - { - if (argv[i_arg_begin][0] != '-') - { + for (i_arg_begin = 1; i_arg_begin < argc; i_arg_begin++) { + if (argv[i_arg_begin][0] != '-') { break; } - if (argv[i_arg_begin][1] == 'm') - { + if (argv[i_arg_begin][1] == 'm') { show_mem = true; } - else if (argv[i_arg_begin][1] == 's') - { + else if (argv[i_arg_begin][1] == 's') { show_stack = true; } - else if (argv[i_arg_begin][1] == 't') - { + else if (argv[i_arg_begin][1] == 't') { show_time_exec = true; } - else if (argv[i_arg_begin][1] == 'h') - { + else if (argv[i_arg_begin][1] == 'h') { iwasm_help(); return 0; } - else if (argv[i_arg_begin][1] == 0x00) - { + else if (argv[i_arg_begin][1] == 0x00) { continue; } - else - { + else { rt_kprintf("[iwasm] unknown param: %s\n", argv[i_arg_begin]); } } -#else /* WAMR_ENABLE_PARAMS */ +#else /* WAMR_ENABLE_PARAMS */ #define i_arg_begin 1 -#endif /* WAMR_ENABLE_PARAMS */ +#endif /* WAMR_ENABLE_PARAMS */ - if (argc - i_arg_begin < 1) - { + if (argc - i_arg_begin < 1) { iwasm_help(); return -1; } @@ -281,56 +286,53 @@ int iwasm(int argc, char **argv) init_args.mem_alloc_option.allocator.free_func = os_free; #ifdef WAMR_ENABLE_RTT_EXPORT init_args.native_symbols = native_export_symbols; - init_args.n_native_symbols = sizeof(native_export_symbols) / sizeof(NativeSymbol); + init_args.n_native_symbols = + sizeof(native_export_symbols) / sizeof(NativeSymbol); init_args.native_module_name = "env"; #endif /* WAMR_ENABLE_RTT_EXPORT */ #ifdef WAMR_ENABLE_IWASM_PARAMS #if defined(RT_USING_HEAP) && defined(RT_USING_MEMHEAP_AS_HEAP) extern long list_memheap(void); - if (show_mem) - { + if (show_mem) { list_memheap(); } #else rt_uint32_t total, max, used; - if (show_mem) - { + if (show_mem) { rt_memory_info(&total, &used, &max); } #endif rt_thread_t tid; - if (show_stack) - { + if (show_stack) { tid = rt_thread_self(); - printf("thread stack addr: %p, size: %u, sp: %p\n", tid->stack_addr, tid->stack_size, tid->sp); + printf("thread stack addr: %p, size: %u, sp: %p\n", tid->stack_addr, + tid->stack_size, tid->sp); } -#endif /* WAMR_ENABLE_PARAMS */ +#endif /* WAMR_ENABLE_PARAMS */ - if (wasm_runtime_full_init(&init_args) == false) - { + if (wasm_runtime_full_init(&init_args) == false) { rt_kprintf("Init WASM runtime environment failed.\n"); return -1; } - wasm_file_buf = my_read_file_to_buffer (argv[i_arg_begin], &wasm_file_size); - if (!wasm_file_buf) - { + wasm_file_buf = my_read_file_to_buffer(argv[i_arg_begin], &wasm_file_size); + if (!wasm_file_buf) { rt_err_t err = rt_get_errno(); rt_kprintf("WASM load file to RAM failed: %d\n", err); goto fail1; } rt_memset(error_buf, 0x00, sizeof(error_buf)); - wasm_module = wasm_runtime_load(wasm_file_buf, wasm_file_size, error_buf, sizeof(error_buf)); - if (!wasm_module) - { + wasm_module = wasm_runtime_load(wasm_file_buf, wasm_file_size, error_buf, + sizeof(error_buf)); + if (!wasm_module) { rt_kprintf("%s\n", error_buf); goto fail2; } rt_memset(error_buf, 0x00, sizeof(error_buf)); - wasm_module_inst = wasm_runtime_instantiate(wasm_module, stack_size, heap_size, error_buf, sizeof(error_buf)); - if (!wasm_module_inst) - { + wasm_module_inst = wasm_runtime_instantiate( + wasm_module, stack_size, heap_size, error_buf, sizeof(error_buf)); + if (!wasm_module_inst) { rt_kprintf("%s\n", error_buf); goto fail3; } @@ -340,35 +342,33 @@ int iwasm(int argc, char **argv) if (show_time_exec) { ticks_exec = rt_tick_get(); } -#endif /* WAMR_ENABLE_PARAMS */ +#endif /* WAMR_ENABLE_PARAMS */ app_instance_main(wasm_module_inst, argc - i_arg_begin, &argv[i_arg_begin]); #ifdef WAMR_ENABLE_IWASM_PARAMS - if (show_time_exec) - { + if (show_time_exec) { ticks_exec = rt_tick_get() - ticks_exec; - printf("[iwasm] execute ticks took: %u [ticks/s = %u]\n", ticks_exec, RT_TICK_PER_SECOND); + printf("[iwasm] execute ticks took: %u [ticks/s = %u]\n", ticks_exec, + RT_TICK_PER_SECOND); } #if defined(RT_USING_HEAP) && defined(RT_USING_MEMHEAP_AS_HEAP) - if (show_mem) - { + if (show_mem) { list_memheap(); } #else rt_uint32_t total_after, max_after, used_after; - if (show_mem) - { + if (show_mem) { rt_memory_info(&total_after, &used_after, &max_after); rt_kprintf("[iwasm] memory took: %u\n", used_after - used); } #endif - if (show_stack) - { - printf("[iwasm] thread stack addr: %p, size: %u, sp: %p\n", tid->stack_addr, tid->stack_size, tid->sp); + if (show_stack) { + printf("[iwasm] thread stack addr: %p, size: %u, sp: %p\n", + tid->stack_addr, tid->stack_size, tid->sp); } -#endif /* WAMR_ENABLE_PARAMS */ +#endif /* WAMR_ENABLE_PARAMS */ /* destroy the module instance */ wasm_runtime_deinstantiate(wasm_module_inst); diff --git a/product-mini/platforms/windows/main.c b/product-mini/platforms/windows/main.c index 3a224d9cd0..04828041fc 100644 --- a/product-mini/platforms/windows/main.c +++ b/product-mini/platforms/windows/main.c @@ -15,6 +15,7 @@ static char **app_argv; #define MODULE_PATH ("--module-path=") +/* clang-format off */ static int print_help() { @@ -47,6 +48,7 @@ print_help() #endif return 1; } +/* clang-format on */ static void * app_instance_main(wasm_module_inst_t module_inst) @@ -113,37 +115,37 @@ split_string(char *str, int *count) static void * app_instance_repl(wasm_module_inst_t module_inst) { - char buffer[4096]; - char *cmd; - size_t n; - - while ((printf("webassembly> "), - cmd = fgets(buffer, sizeof(buffer), stdin)) != NULL) { - bh_assert(cmd); - n = strlen(cmd); - if (cmd[n - 1] == '\n') { - if (n == 1) - continue; - else - cmd[n - 1] = '\0'; - } - if (!strcmp(cmd, "__exit__")) { - printf("exit repl mode\n"); - break; - } - app_argv = split_string(cmd, &app_argc); - if (app_argv == NULL) { - LOG_ERROR("Wasm prepare param failed: split string failed.\n"); - break; - } - if (app_argc != 0) { - wasm_application_execute_func(module_inst, app_argv[0], - app_argc - 1, app_argv + 1); - } - free(app_argv); - } - - return NULL; + char buffer[4096]; + char *cmd; + size_t n; + + while ((printf("webassembly> "), cmd = fgets(buffer, sizeof(buffer), stdin)) + != NULL) { + bh_assert(cmd); + n = strlen(cmd); + if (cmd[n - 1] == '\n') { + if (n == 1) + continue; + else + cmd[n - 1] = '\0'; + } + if (!strcmp(cmd, "__exit__")) { + printf("exit repl mode\n"); + break; + } + app_argv = split_string(cmd, &app_argc); + if (app_argv == NULL) { + LOG_ERROR("Wasm prepare param failed: split string failed.\n"); + break; + } + if (app_argc != 0) { + wasm_application_execute_func(module_inst, app_argv[0], + app_argc - 1, app_argv + 1); + } + free(app_argv); + } + + return NULL; } #if WASM_ENABLE_LIBC_WASI != 0 @@ -175,7 +177,7 @@ static char global_heap_buf[10 * 1024 * 1024] = { 0 }; static char * handle_module_path(const char *module_path) { - // next character after = + /* next character after '=' */ return (strchr(module_path, '=')) + 1; } @@ -235,7 +237,7 @@ main(int argc, char *argv[]) uint32 env_list_size = 0; #endif - /* Process options. */ + /* Process options. */ for (argc--, argv++; argc > 0 && argv[0][0] == '-'; argc--, argv++) { if (!strcmp(argv[0], "-f") || !strcmp(argv[0], "--function")) { argc--, argv++; @@ -348,7 +350,7 @@ main(int argc, char *argv[]) /* load WASM byte buffer from WASM bin file */ if (!(wasm_file_buf = - (uint8 *)bh_read_file_to_buffer(wasm_file, &wasm_file_size))) + (uint8 *)bh_read_file_to_buffer(wasm_file, &wasm_file_size))) goto fail1; #if WASM_ENABLE_MULTI_MODULE != 0 @@ -369,8 +371,8 @@ main(int argc, char *argv[]) /* instantiate the module */ if (!(wasm_module_inst = - wasm_runtime_instantiate(wasm_module, stack_size, heap_size, - error_buf, sizeof(error_buf)))) { + wasm_runtime_instantiate(wasm_module, stack_size, heap_size, + error_buf, sizeof(error_buf)))) { printf("%s\n", error_buf); goto fail3; } diff --git a/product-mini/platforms/zephyr/simple/src/main.c b/product-mini/platforms/zephyr/simple/src/main.c index f5b83e6dfd..27ce7cb950 100644 --- a/product-mini/platforms/zephyr/simple/src/main.c +++ b/product-mini/platforms/zephyr/simple/src/main.c @@ -57,10 +57,10 @@ static char **app_argv; * @return true if the main function is called, false otherwise. */ bool -wasm_application_execute_main(wasm_module_inst_t module_inst, - int argc, char *argv[]); +wasm_application_execute_main(wasm_module_inst_t module_inst, int argc, + char *argv[]); -static void* +static void * app_instance_main(wasm_module_inst_t module_inst) { const char *exception; @@ -69,15 +69,15 @@ app_instance_main(wasm_module_inst_t module_inst) unsigned argv[2] = { 0 }; if (wasm_runtime_lookup_function(module_inst, "main", NULL) - || wasm_runtime_lookup_function(module_inst, - "__main_argc_argv", NULL)) { + || wasm_runtime_lookup_function(module_inst, "__main_argc_argv", + NULL)) { LOG_VERBOSE("Calling main funciton\n"); wasm_application_execute_main(module_inst, app_argc, app_argv); } - else if ((func = wasm_runtime_lookup_function(module_inst, - "app_main", NULL))) { - exec_env = wasm_runtime_create_exec_env(module_inst, - CONFIG_APP_HEAP_SIZE); + else if ((func = wasm_runtime_lookup_function(module_inst, "app_main", + NULL))) { + exec_env = + wasm_runtime_create_exec_env(module_inst, CONFIG_APP_HEAP_SIZE); if (!exec_env) { os_printf("Create exec env failed\n"); return NULL; @@ -110,15 +110,17 @@ static char global_heap_buf[CONFIG_GLOBAL_HEAP_BUF_SIZE] = { 0 }; /* esp32_technical_reference_manual: " -The capacity of Internal SRAM 1 is 128 KB. Either CPU can read and write this memory at addresses -0x3FFE_0000 ~ 0x3FFF_FFFF of the data bus, and also at addresses 0x400A_0000 ~ 0x400B_FFFF of the -instruction bus. +The capacity of Internal SRAM 1 is 128 KB. Either CPU can read and write this +memory at addresses 0x3FFE_0000 ~ 0x3FFF_FFFF of the data bus, and also at +addresses 0x400A_0000 ~ 0x400B_FFFF of the instruction bus. " -The custom linker script defines dram0_1_seg and map it to 0x400A_0000 ~ 0x400B_FFFF for instruction bus access. -Here we define the buffer that will be placed to dram0_1_seg. +The custom linker script defines dram0_1_seg and map it to 0x400A_0000 ~ +0x400B_FFFF for instruction bus access. Here we define the buffer that will be +placed to dram0_1_seg. */ -static char esp32_executable_memory_buf[100 * 1024] __attribute__((section (".aot_code_buf"))) = { 0 }; +static char esp32_executable_memory_buf[100 * 1024] + __attribute__((section(".aot_code_buf"))) = { 0 }; /* the poll allocator for executable memory */ static mem_allocator_t esp32_exec_mem_pool_allocator; @@ -127,8 +129,8 @@ static int esp32_exec_mem_init() { if (!(esp32_exec_mem_pool_allocator = - mem_allocator_create(esp32_executable_memory_buf, - sizeof(esp32_executable_memory_buf)))) + mem_allocator_create(esp32_executable_memory_buf, + sizeof(esp32_executable_memory_buf)))) return -1; return 0; @@ -153,7 +155,8 @@ esp32_exec_mem_free(void *addr) } #endif /* end of #ifdef CONFIG_BOARD_ESP32 */ -void iwasm_main(void *arg1, void *arg2, void *arg3) +void +iwasm_main(void *arg1, void *arg2, void *arg3) { int start, end; start = k_uptime_get_32(); @@ -167,9 +170,9 @@ void iwasm_main(void *arg1, void *arg2, void *arg3) int log_verbose_level = 2; #endif - (void) arg1; - (void) arg2; - (void) arg3; + (void)arg1; + (void)arg2; + (void)arg3; memset(&init_args, 0, sizeof(RuntimeInitArgs)); @@ -198,7 +201,7 @@ void iwasm_main(void *arg1, void *arg2, void *arg3) #endif /* load WASM byte buffer from byte buffer of include file */ - wasm_file_buf = (uint8*) wasm_test_file; + wasm_file_buf = (uint8 *)wasm_test_file; wasm_file_size = sizeof(wasm_test_file); /* load WASM module */ @@ -213,11 +216,9 @@ void iwasm_main(void *arg1, void *arg2, void *arg3) } /* instantiate the module */ - if (!(wasm_module_inst = wasm_runtime_instantiate(wasm_module, - CONFIG_APP_STACK_SIZE, - CONFIG_APP_HEAP_SIZE, - error_buf, - sizeof(error_buf)))) { + if (!(wasm_module_inst = wasm_runtime_instantiate( + wasm_module, CONFIG_APP_STACK_SIZE, CONFIG_APP_HEAP_SIZE, + error_buf, sizeof(error_buf)))) { printf("%s\n", error_buf); goto fail2; } @@ -253,16 +254,16 @@ void iwasm_main(void *arg1, void *arg2, void *arg3) K_THREAD_STACK_DEFINE(iwasm_main_thread_stack, MAIN_THREAD_STACK_SIZE); static struct k_thread iwasm_main_thread; -bool iwasm_init(void) +bool +iwasm_init(void) { - k_tid_t tid = k_thread_create(&iwasm_main_thread, iwasm_main_thread_stack, - MAIN_THREAD_STACK_SIZE, - iwasm_main, NULL, NULL, NULL, - MAIN_THREAD_PRIORITY, 0, K_NO_WAIT); + k_tid_t tid = k_thread_create( + &iwasm_main_thread, iwasm_main_thread_stack, MAIN_THREAD_STACK_SIZE, + iwasm_main, NULL, NULL, NULL, MAIN_THREAD_PRIORITY, 0, K_NO_WAIT); return tid ? true : false; } -void main(void) +void +main(void) { iwasm_init(); } - diff --git a/product-mini/platforms/zephyr/simple/src/test_wasm_riscv64.h b/product-mini/platforms/zephyr/simple/src/test_wasm_riscv64.h index 526317afa8..1b45211d7a 100644 --- a/product-mini/platforms/zephyr/simple/src/test_wasm_riscv64.h +++ b/product-mini/platforms/zephyr/simple/src/test_wasm_riscv64.h @@ -4,38 +4,38 @@ */ unsigned char __aligned(4) wasm_test_file[] = { - 0x00, 0x61, 0x73, 0x6D, 0x01, 0x00, 0x00, 0x00, 0x01, 0x10, 0x03, 0x60, - 0x01, 0x7F, 0x01, 0x7F, 0x60, 0x02, 0x7F, 0x7F, 0x01, 0x7F, 0x60, 0x01, - 0x7F, 0x00, 0x02, 0x31, 0x04, 0x03, 0x65, 0x6E, 0x76, 0x04, 0x70, 0x75, - 0x74, 0x73, 0x00, 0x00, 0x03, 0x65, 0x6E, 0x76, 0x06, 0x6D, 0x61, 0x6C, - 0x6C, 0x6F, 0x63, 0x00, 0x00, 0x03, 0x65, 0x6E, 0x76, 0x06, 0x70, 0x72, - 0x69, 0x6E, 0x74, 0x66, 0x00, 0x01, 0x03, 0x65, 0x6E, 0x76, 0x04, 0x66, - 0x72, 0x65, 0x65, 0x00, 0x02, 0x03, 0x02, 0x01, 0x01, 0x04, 0x05, 0x01, - 0x70, 0x01, 0x01, 0x01, 0x05, 0x03, 0x01, 0x00, 0x01, 0x06, 0x12, 0x03, - 0x7F, 0x01, 0x41, 0xC0, 0x01, 0x0B, 0x7F, 0x00, 0x41, 0x3A, 0x0B, 0x7F, - 0x00, 0x41, 0xC0, 0x01, 0x0B, 0x07, 0x2C, 0x04, 0x06, 0x6D, 0x65, 0x6D, - 0x6F, 0x72, 0x79, 0x02, 0x00, 0x04, 0x6D, 0x61, 0x69, 0x6E, 0x00, 0x04, - 0x0A, 0x5F, 0x5F, 0x64, 0x61, 0x74, 0x61, 0x5F, 0x65, 0x6E, 0x64, 0x03, - 0x01, 0x0B, 0x5F, 0x5F, 0x68, 0x65, 0x61, 0x70, 0x5F, 0x62, 0x61, 0x73, - 0x65, 0x03, 0x02, 0x0A, 0xB1, 0x01, 0x01, 0xAE, 0x01, 0x01, 0x03, 0x7F, - 0x23, 0x80, 0x80, 0x80, 0x80, 0x00, 0x41, 0x20, 0x6B, 0x22, 0x02, 0x24, - 0x80, 0x80, 0x80, 0x80, 0x00, 0x41, 0x9B, 0x80, 0x80, 0x80, 0x00, 0x10, - 0x80, 0x80, 0x80, 0x80, 0x00, 0x1A, 0x02, 0x40, 0x02, 0x40, 0x41, 0x10, - 0x10, 0x81, 0x80, 0x80, 0x80, 0x00, 0x22, 0x03, 0x0D, 0x00, 0x41, 0xA8, - 0x80, 0x80, 0x80, 0x00, 0x10, 0x80, 0x80, 0x80, 0x80, 0x00, 0x1A, 0x41, - 0x7F, 0x21, 0x04, 0x0C, 0x01, 0x0B, 0x20, 0x02, 0x20, 0x03, 0x36, 0x02, - 0x10, 0x41, 0x80, 0x80, 0x80, 0x80, 0x00, 0x20, 0x02, 0x41, 0x10, 0x6A, - 0x10, 0x82, 0x80, 0x80, 0x80, 0x00, 0x1A, 0x41, 0x00, 0x21, 0x04, 0x20, - 0x03, 0x41, 0x04, 0x6A, 0x41, 0x00, 0x2F, 0x00, 0x91, 0x80, 0x80, 0x80, - 0x00, 0x3B, 0x00, 0x00, 0x20, 0x03, 0x41, 0x00, 0x28, 0x00, 0x8D, 0x80, - 0x80, 0x80, 0x00, 0x36, 0x00, 0x00, 0x20, 0x02, 0x20, 0x03, 0x36, 0x02, - 0x00, 0x41, 0x93, 0x80, 0x80, 0x80, 0x00, 0x20, 0x02, 0x10, 0x82, 0x80, - 0x80, 0x80, 0x00, 0x1A, 0x20, 0x03, 0x10, 0x83, 0x80, 0x80, 0x80, 0x00, - 0x0B, 0x20, 0x02, 0x41, 0x20, 0x6A, 0x24, 0x80, 0x80, 0x80, 0x80, 0x00, - 0x20, 0x04, 0x0B, 0x0B, 0x40, 0x01, 0x00, 0x41, 0x00, 0x0B, 0x3A, 0x62, - 0x75, 0x66, 0x20, 0x70, 0x74, 0x72, 0x3A, 0x20, 0x25, 0x70, 0x0A, 0x00, - 0x31, 0x32, 0x33, 0x34, 0x0A, 0x00, 0x62, 0x75, 0x66, 0x3A, 0x20, 0x25, - 0x73, 0x00, 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x77, 0x6F, 0x72, 0x6C, - 0x64, 0x21, 0x00, 0x6D, 0x61, 0x6C, 0x6C, 0x6F, 0x63, 0x20, 0x62, 0x75, - 0x66, 0x20, 0x66, 0x61, 0x69, 0x6C, 0x65, 0x64, 0x00 + 0x00, 0x61, 0x73, 0x6D, 0x01, 0x00, 0x00, 0x00, 0x01, 0x10, 0x03, 0x60, + 0x01, 0x7F, 0x01, 0x7F, 0x60, 0x02, 0x7F, 0x7F, 0x01, 0x7F, 0x60, 0x01, + 0x7F, 0x00, 0x02, 0x31, 0x04, 0x03, 0x65, 0x6E, 0x76, 0x04, 0x70, 0x75, + 0x74, 0x73, 0x00, 0x00, 0x03, 0x65, 0x6E, 0x76, 0x06, 0x6D, 0x61, 0x6C, + 0x6C, 0x6F, 0x63, 0x00, 0x00, 0x03, 0x65, 0x6E, 0x76, 0x06, 0x70, 0x72, + 0x69, 0x6E, 0x74, 0x66, 0x00, 0x01, 0x03, 0x65, 0x6E, 0x76, 0x04, 0x66, + 0x72, 0x65, 0x65, 0x00, 0x02, 0x03, 0x02, 0x01, 0x01, 0x04, 0x05, 0x01, + 0x70, 0x01, 0x01, 0x01, 0x05, 0x03, 0x01, 0x00, 0x01, 0x06, 0x12, 0x03, + 0x7F, 0x01, 0x41, 0xC0, 0x01, 0x0B, 0x7F, 0x00, 0x41, 0x3A, 0x0B, 0x7F, + 0x00, 0x41, 0xC0, 0x01, 0x0B, 0x07, 0x2C, 0x04, 0x06, 0x6D, 0x65, 0x6D, + 0x6F, 0x72, 0x79, 0x02, 0x00, 0x04, 0x6D, 0x61, 0x69, 0x6E, 0x00, 0x04, + 0x0A, 0x5F, 0x5F, 0x64, 0x61, 0x74, 0x61, 0x5F, 0x65, 0x6E, 0x64, 0x03, + 0x01, 0x0B, 0x5F, 0x5F, 0x68, 0x65, 0x61, 0x70, 0x5F, 0x62, 0x61, 0x73, + 0x65, 0x03, 0x02, 0x0A, 0xB1, 0x01, 0x01, 0xAE, 0x01, 0x01, 0x03, 0x7F, + 0x23, 0x80, 0x80, 0x80, 0x80, 0x00, 0x41, 0x20, 0x6B, 0x22, 0x02, 0x24, + 0x80, 0x80, 0x80, 0x80, 0x00, 0x41, 0x9B, 0x80, 0x80, 0x80, 0x00, 0x10, + 0x80, 0x80, 0x80, 0x80, 0x00, 0x1A, 0x02, 0x40, 0x02, 0x40, 0x41, 0x10, + 0x10, 0x81, 0x80, 0x80, 0x80, 0x00, 0x22, 0x03, 0x0D, 0x00, 0x41, 0xA8, + 0x80, 0x80, 0x80, 0x00, 0x10, 0x80, 0x80, 0x80, 0x80, 0x00, 0x1A, 0x41, + 0x7F, 0x21, 0x04, 0x0C, 0x01, 0x0B, 0x20, 0x02, 0x20, 0x03, 0x36, 0x02, + 0x10, 0x41, 0x80, 0x80, 0x80, 0x80, 0x00, 0x20, 0x02, 0x41, 0x10, 0x6A, + 0x10, 0x82, 0x80, 0x80, 0x80, 0x00, 0x1A, 0x41, 0x00, 0x21, 0x04, 0x20, + 0x03, 0x41, 0x04, 0x6A, 0x41, 0x00, 0x2F, 0x00, 0x91, 0x80, 0x80, 0x80, + 0x00, 0x3B, 0x00, 0x00, 0x20, 0x03, 0x41, 0x00, 0x28, 0x00, 0x8D, 0x80, + 0x80, 0x80, 0x00, 0x36, 0x00, 0x00, 0x20, 0x02, 0x20, 0x03, 0x36, 0x02, + 0x00, 0x41, 0x93, 0x80, 0x80, 0x80, 0x00, 0x20, 0x02, 0x10, 0x82, 0x80, + 0x80, 0x80, 0x00, 0x1A, 0x20, 0x03, 0x10, 0x83, 0x80, 0x80, 0x80, 0x00, + 0x0B, 0x20, 0x02, 0x41, 0x20, 0x6A, 0x24, 0x80, 0x80, 0x80, 0x80, 0x00, + 0x20, 0x04, 0x0B, 0x0B, 0x40, 0x01, 0x00, 0x41, 0x00, 0x0B, 0x3A, 0x62, + 0x75, 0x66, 0x20, 0x70, 0x74, 0x72, 0x3A, 0x20, 0x25, 0x70, 0x0A, 0x00, + 0x31, 0x32, 0x33, 0x34, 0x0A, 0x00, 0x62, 0x75, 0x66, 0x3A, 0x20, 0x25, + 0x73, 0x00, 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x77, 0x6F, 0x72, 0x6C, + 0x64, 0x21, 0x00, 0x6D, 0x61, 0x6C, 0x6C, 0x6F, 0x63, 0x20, 0x62, 0x75, + 0x66, 0x20, 0x66, 0x61, 0x69, 0x6C, 0x65, 0x64, 0x00 }; diff --git a/product-mini/platforms/zephyr/simple/src/wasm-app-riscv64/main.c b/product-mini/platforms/zephyr/simple/src/wasm-app-riscv64/main.c index 7606345259..026cb8fd11 100644 --- a/product-mini/platforms/zephyr/simple/src/wasm-app-riscv64/main.c +++ b/product-mini/platforms/zephyr/simple/src/wasm-app-riscv64/main.c @@ -6,7 +6,8 @@ #include #include -int main(int argc, char **argv) +int +main(int argc, char **argv) { char *buf; From f0cd7ea5185ee48cf29b37c4747f6de65fb1731c Mon Sep 17 00:00:00 2001 From: Wenyong Huang Date: Sat, 16 Oct 2021 01:37:44 +0800 Subject: [PATCH 2/8] Fix app heap corrupted unchecked issue --- core/iwasm/aot/aot_runtime.c | 19 +++++++++++++------ core/iwasm/common/wasm_runtime_common.c | 11 +++++++++++ core/iwasm/common/wasm_runtime_common.h | 3 +++ core/iwasm/interpreter/wasm_runtime.c | 19 +++++++++++++------ .../include/wasmtime_ssp.h | 12 ++++++++++-- core/shared/mem-alloc/ems/ems_alloc.c | 13 ++++++++----- core/shared/mem-alloc/ems/ems_kfc.c | 19 +++++++++++++++++-- 7 files changed, 75 insertions(+), 21 deletions(-) diff --git a/core/iwasm/aot/aot_runtime.c b/core/iwasm/aot/aot_runtime.c index 28db2878e6..33e2730dd7 100644 --- a/core/iwasm/aot/aot_runtime.c +++ b/core/iwasm/aot/aot_runtime.c @@ -1770,10 +1770,7 @@ aot_module_malloc(AOTModuleInstance *module_inst, uint32 size, if (!addr) { if (memory_inst->heap_handle.ptr && mem_allocator_is_heap_corrupted(memory_inst->heap_handle.ptr)) { - LOG_ERROR("Error: app heap is corrupted, if the wasm file " - "is compiled by wasi-sdk-12.0 or larger version, " - "please add -Wl,--export=malloc -Wl,--export=free " - " to export malloc and free functions."); + show_app_heap_corrupted_prompt(); aot_set_exception(module_inst, "app heap corrupted"); } else { @@ -2014,6 +2011,7 @@ aot_enlarge_memory(AOTModuleInstance *module_inst, uint32 inc_page_count) uint32 total_page_count, total_size_old, heap_size; uint64 total_size; uint8 *memory_data_old, *heap_data_old, *memory_data, *heap_data; + bool ret = true; if (!memory_inst) return false; @@ -2051,6 +2049,13 @@ aot_enlarge_memory(AOTModuleInstance *module_inst, uint32 inc_page_count) } #endif + if (heap_size > 0) { + if (mem_allocator_is_heap_corrupted(memory_inst->heap_handle.ptr)) { + show_app_heap_corrupted_prompt(); + return false; + } + } + if (!(memory_data = wasm_runtime_realloc(memory_data_old, (uint32)total_size))) { if (!(memory_data = wasm_runtime_malloc((uint32)total_size))) { @@ -2076,7 +2081,9 @@ aot_enlarge_memory(AOTModuleInstance *module_inst, uint32 inc_page_count) (char *)heap_data_old + (memory_data - memory_data_old), heap_size)) { - return false; + /* Don't return here as memory->memory_data is obsolete and + must be updated to be correctly used later. */ + ret = false; } } @@ -2098,7 +2105,7 @@ aot_enlarge_memory(AOTModuleInstance *module_inst, uint32 inc_page_count) memory_inst->mem_bound_check_8bytes.u32[0] = (uint32)total_size - 8; memory_inst->mem_bound_check_16bytes.u32[0] = (uint32)total_size - 16; } - return true; + return ret; } #else /* else of OS_ENABLE_HW_BOUND_CHECK */ bool diff --git a/core/iwasm/common/wasm_runtime_common.c b/core/iwasm/common/wasm_runtime_common.c index 286c2200c0..f3d9705907 100644 --- a/core/iwasm/common/wasm_runtime_common.c +++ b/core/iwasm/common/wasm_runtime_common.c @@ -4211,3 +4211,14 @@ wasm_runtime_invoke_c_api_native(WASMModuleInstanceCommon *module_inst, wasm_runtime_free(results); return ret; } + +void +show_app_heap_corrupted_prompt() +{ + LOG_ERROR("Error: app heap is corrupted, if the wasm file " + "is compiled by wasi-sdk-12.0 or higher version, " + "please add -Wl,--export=malloc -Wl,--export=free " + "to export malloc and free functions. If it is " + "compiled by asc, please add --exportRuntime to " + "export the runtime helpers."); +} diff --git a/core/iwasm/common/wasm_runtime_common.h b/core/iwasm/common/wasm_runtime_common.h index b115a8a121..45ab0caa34 100644 --- a/core/iwasm/common/wasm_runtime_common.h +++ b/core/iwasm/common/wasm_runtime_common.h @@ -839,6 +839,9 @@ wasm_runtime_invoke_c_api_native(WASMModuleInstanceCommon *module_inst, uint32 argc, uint32 *argv, bool with_env, void *wasm_c_api_env); +void +show_app_heap_corrupted_prompt(); + #ifdef __cplusplus } #endif diff --git a/core/iwasm/interpreter/wasm_runtime.c b/core/iwasm/interpreter/wasm_runtime.c index 372d572fbb..2e8dffd1f3 100644 --- a/core/iwasm/interpreter/wasm_runtime.c +++ b/core/iwasm/interpreter/wasm_runtime.c @@ -1826,10 +1826,7 @@ wasm_module_malloc(WASMModuleInstance *module_inst, uint32 size, if (!addr) { if (memory->heap_handle && mem_allocator_is_heap_corrupted(memory->heap_handle)) { - LOG_ERROR("Error: app heap is corrupted, if the wasm file " - "is compiled by wasi-sdk-12.0 or larger version, " - "please add -Wl,--export=malloc -Wl,--export=free " - " to export malloc and free functions."); + show_app_heap_corrupted_prompt(); wasm_set_exception(module_inst, "app heap corrupted"); } else { @@ -2057,6 +2054,7 @@ wasm_enlarge_memory(WASMModuleInstance *module, uint32 inc_page_count) uint8 *new_memory_data, *memory_data, *heap_data_old; uint32 heap_size, total_size_old, total_page_count; uint64 total_size; + bool ret = true; if (!memory) return false; @@ -2090,6 +2088,13 @@ wasm_enlarge_memory(WASMModuleInstance *module, uint32 inc_page_count) } #endif + if (heap_size > 0) { + if (mem_allocator_is_heap_corrupted(memory->heap_handle)) { + show_app_heap_corrupted_prompt(); + return false; + } + } + if (!(new_memory_data = wasm_runtime_realloc(memory_data, (uint32)total_size))) { if (!(new_memory_data = wasm_runtime_malloc((uint32)total_size))) { @@ -2111,7 +2116,9 @@ wasm_enlarge_memory(WASMModuleInstance *module, uint32 inc_page_count) + (new_memory_data - memory_data), heap_size) != 0) { - return false; + /* Don't return here as memory->memory_data is obsolete and + must be updated to be correctly used later. */ + ret = false; } } @@ -2122,7 +2129,7 @@ wasm_enlarge_memory(WASMModuleInstance *module, uint32 inc_page_count) memory->memory_data_end = memory->memory_data + memory->num_bytes_per_page * total_page_count; - return true; + return ret; } #if WASM_ENABLE_REF_TYPES != 0 diff --git a/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/include/wasmtime_ssp.h b/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/include/wasmtime_ssp.h index ace6616376..297d0c50c0 100644 --- a/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/include/wasmtime_ssp.h +++ b/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/include/wasmtime_ssp.h @@ -9,6 +9,12 @@ * around to avoid storing them in TLS. */ +/** + * The defitions of type, macro and structure in this file should be + * consistent with those in wasi-libc: + * https://github.com/WebAssembly/wasi-libc/blob/main/libc-bottom-half/headers/public/wasi/api.h + */ + #ifndef WASMTIME_SSP_H #define WASMTIME_SSP_H @@ -201,8 +207,10 @@ typedef uint16_t __wasi_riflags_t; typedef uint64_t __wasi_rights_t; -// Observe that WASI defines rights in the plural form -// TODO - re-factor to use RIGHTS instead of RIGHT +/** + * Observe that WASI defines rights in the plural form + * TODO: refactor to use RIGHTS instead of RIGHT + */ #define __WASI_RIGHT_FD_DATASYNC ((__wasi_rights_t)(1 << 0)) #define __WASI_RIGHT_FD_READ ((__wasi_rights_t)(1 << 1)) #define __WASI_RIGHT_FD_SEEK ((__wasi_rights_t)(1 << 2)) diff --git a/core/shared/mem-alloc/ems/ems_alloc.c b/core/shared/mem-alloc/ems/ems_alloc.c index 1d432a763f..a342bb5e40 100644 --- a/core/shared/mem-alloc/ems/ems_alloc.c +++ b/core/shared/mem-alloc/ems/ems_alloc.c @@ -235,12 +235,12 @@ gci_add_fc(gc_heap_t *heap, hmu_t *hmu, gc_size_t size) return true; } - /* big block*/ + /* big block */ node = (hmu_tree_node_t *)hmu; node->size = size; node->left = node->right = node->parent = NULL; - /* find proper node to link this new node to*/ + /* find proper node to link this new node to */ root = &heap->kfc_tree_root; tp = root; bh_assert(tp->size < size); @@ -253,7 +253,7 @@ gci_add_fc(gc_heap_t *heap, hmu_t *hmu, gc_size_t size) } tp = tp->right; } - else { /* tp->size >= size*/ + else { /* tp->size >= size */ if (!tp->left) { tp->left = node; node->parent = tp; @@ -759,7 +759,7 @@ gci_dump(gc_heap_t *heap) else if (ut == HMU_FC) inuse = 'F'; - if (size == 0) { + if (size == 0 || size > (uint8 *)end - (uint8 *)cur) { os_printf("[GC_ERROR]Heap is corrupted, heap dump failed.\n"); heap->is_heap_corrupted = true; return; @@ -779,5 +779,8 @@ gci_dump(gc_heap_t *heap) i++; } - bh_assert(cur == end); + if (cur != end) { + os_printf("[GC_ERROR]Heap is corrupted, heap dump failed.\n"); + heap->is_heap_corrupted = true; + } } diff --git a/core/shared/mem-alloc/ems/ems_kfc.c b/core/shared/mem-alloc/ems/ems_kfc.c index e363399304..ee3ecde08e 100644 --- a/core/shared/mem-alloc/ems/ems_kfc.c +++ b/core/shared/mem-alloc/ems/ems_kfc.c @@ -183,6 +183,11 @@ gc_migrate(gc_handle_t handle, char *pool_buf_new, gc_size_t pool_buf_size) if (offset == 0) return 0; + if (heap->is_heap_corrupted) { + os_printf("[GC_ERROR]Heap is corrupted, heap migrate failed.\n"); + return GC_ERROR; + } + heap->base_addr = (uint8 *)base_addr_new; adjust_ptr((uint8 **)&heap->kfc_tree_root.left, offset); adjust_ptr((uint8 **)&heap->kfc_tree_root.right, offset); @@ -193,7 +198,12 @@ gc_migrate(gc_handle_t handle, char *pool_buf_new, gc_size_t pool_buf_size) while (cur < end) { size = hmu_get_size(cur); - bh_assert(size > 0); + + if (size <= 0 || size > (uint8 *)end - (uint8 *)cur) { + os_printf("[GC_ERROR]Heap is corrupted, heap migrate failed.\n"); + heap->is_heap_corrupted = true; + return GC_ERROR; + } if (hmu_get_ut(cur) == HMU_FC && !HMU_IS_FC_NORMAL(size)) { tree_node = (hmu_tree_node_t *)cur; @@ -207,7 +217,12 @@ gc_migrate(gc_handle_t handle, char *pool_buf_new, gc_size_t pool_buf_size) cur = (hmu_t *)((char *)cur + size); } - bh_assert(cur == end); + if (cur != end) { + os_printf("[GC_ERROR]Heap is corrupted, heap migrate failed.\n"); + heap->is_heap_corrupted = true; + return GC_ERROR; + } + return 0; } From a4c88837c5ba974248689929c741e41db8c5b2e1 Mon Sep 17 00:00:00 2001 From: Wenyong Huang Date: Sat, 16 Oct 2021 02:14:26 +0800 Subject: [PATCH 3/8] Change API to wasm_runtime_show_app_heap_corrupted_prompt() --- core/iwasm/aot/aot_runtime.c | 4 ++-- core/iwasm/common/wasm_runtime_common.c | 2 +- core/iwasm/common/wasm_runtime_common.h | 2 +- core/iwasm/interpreter/wasm_runtime.c | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/core/iwasm/aot/aot_runtime.c b/core/iwasm/aot/aot_runtime.c index 33e2730dd7..81120db9c6 100644 --- a/core/iwasm/aot/aot_runtime.c +++ b/core/iwasm/aot/aot_runtime.c @@ -1770,7 +1770,7 @@ aot_module_malloc(AOTModuleInstance *module_inst, uint32 size, if (!addr) { if (memory_inst->heap_handle.ptr && mem_allocator_is_heap_corrupted(memory_inst->heap_handle.ptr)) { - show_app_heap_corrupted_prompt(); + wasm_runtime_show_app_heap_corrupted_prompt(); aot_set_exception(module_inst, "app heap corrupted"); } else { @@ -2051,7 +2051,7 @@ aot_enlarge_memory(AOTModuleInstance *module_inst, uint32 inc_page_count) if (heap_size > 0) { if (mem_allocator_is_heap_corrupted(memory_inst->heap_handle.ptr)) { - show_app_heap_corrupted_prompt(); + wasm_runtime_show_app_heap_corrupted_prompt(); return false; } } diff --git a/core/iwasm/common/wasm_runtime_common.c b/core/iwasm/common/wasm_runtime_common.c index f3d9705907..6402a51b74 100644 --- a/core/iwasm/common/wasm_runtime_common.c +++ b/core/iwasm/common/wasm_runtime_common.c @@ -4213,7 +4213,7 @@ wasm_runtime_invoke_c_api_native(WASMModuleInstanceCommon *module_inst, } void -show_app_heap_corrupted_prompt() +wasm_runtime_show_app_heap_corrupted_prompt() { LOG_ERROR("Error: app heap is corrupted, if the wasm file " "is compiled by wasi-sdk-12.0 or higher version, " diff --git a/core/iwasm/common/wasm_runtime_common.h b/core/iwasm/common/wasm_runtime_common.h index 45ab0caa34..483bf9443b 100644 --- a/core/iwasm/common/wasm_runtime_common.h +++ b/core/iwasm/common/wasm_runtime_common.h @@ -840,7 +840,7 @@ wasm_runtime_invoke_c_api_native(WASMModuleInstanceCommon *module_inst, void *wasm_c_api_env); void -show_app_heap_corrupted_prompt(); +wasm_runtime_show_app_heap_corrupted_prompt(); #ifdef __cplusplus } diff --git a/core/iwasm/interpreter/wasm_runtime.c b/core/iwasm/interpreter/wasm_runtime.c index 2e8dffd1f3..7574a3f8d9 100644 --- a/core/iwasm/interpreter/wasm_runtime.c +++ b/core/iwasm/interpreter/wasm_runtime.c @@ -1826,7 +1826,7 @@ wasm_module_malloc(WASMModuleInstance *module_inst, uint32 size, if (!addr) { if (memory->heap_handle && mem_allocator_is_heap_corrupted(memory->heap_handle)) { - show_app_heap_corrupted_prompt(); + wasm_runtime_show_app_heap_corrupted_prompt(); wasm_set_exception(module_inst, "app heap corrupted"); } else { @@ -2090,7 +2090,7 @@ wasm_enlarge_memory(WASMModuleInstance *module, uint32 inc_page_count) if (heap_size > 0) { if (mem_allocator_is_heap_corrupted(memory->heap_handle)) { - show_app_heap_corrupted_prompt(); + wasm_runtime_show_app_heap_corrupted_prompt(); return false; } } From 5a39a9df7f879ad3f7e572e837fdeffd16eb18ae Mon Sep 17 00:00:00 2001 From: Wenyong Huang Date: Thu, 21 Oct 2021 20:59:14 +0800 Subject: [PATCH 4/8] Apply clang-format for more files --- .github/workflows/codeing_guildelines.yml | 2 +- .../app-native-shared/attr_container.c | 540 ++-- .../app-native-shared/bi-inc/attr_container.h | 39 +- .../app-native-shared/bi-inc/shared_utils.h | 43 +- .../bi-inc/wgl_shared_utils.h | 2 - .../app-native-shared/native_interface.h | 2 - .../app-native-shared/restful_utils.c | 71 +- core/app-framework/app_ext_lib_export.c | 15 +- core/app-framework/base/app/bh_platform.c | 28 +- core/app-framework/base/app/bh_platform.h | 37 +- core/app-framework/base/app/req_resp_api.h | 1 - core/app-framework/base/app/request.c | 96 +- core/app-framework/base/app/timer.c | 33 +- core/app-framework/base/app/timer_api.h | 1 - core/app-framework/base/app/wa-inc/request.h | 67 +- .../base/app/wa-inc/timer_wasm_app.h | 13 +- core/app-framework/base/app/wasm_app.h | 1 - .../base/native/base_lib_export.c | 11 +- .../base/native/req_resp_native_api.h | 1 - .../base/native/request_response.c | 16 +- core/app-framework/base/native/runtime_lib.h | 16 +- .../base/native/timer_native_api.h | 9 +- .../app-framework/base/native/timer_wrapper.c | 43 +- .../app-framework/connection/app/connection.c | 39 +- .../connection/app/connection_api.h | 1 - .../connection/app/wa-inc/connection.h | 23 +- .../connection/native/connection_lib.h | 8 +- .../connection/native/connection_native_api.h | 19 +- .../connection/native/connection_wrapper.c | 16 +- .../connection/native/linux/conn_tcp.c | 11 +- .../connection/native/linux/conn_tcp.h | 10 +- .../connection/native/linux/conn_uart.c | 12 +- .../connection/native/linux/conn_uart.h | 10 +- .../connection/native/linux/conn_udp.c | 17 +- .../connection/native/linux/conn_udp.h | 10 +- .../connection/native/linux/connection_mgr.c | 192 +- .../native/zephyr/connection_lib_impl.c | 10 +- core/app-framework/sensor/app/sensor.c | 35 +- core/app-framework/sensor/app/sensor_api.h | 3 +- core/app-framework/sensor/app/wa-inc/sensor.h | 20 +- .../sensor/native/runtime_sensor.c | 110 +- .../sensor/native/runtime_sensor.h | 53 +- .../sensor/native/sensor_mgr_ref.c | 70 +- .../sensor/native/sensor_native_api.h | 11 +- core/app-framework/wgl/app/gui_api.h | 2 - core/app-framework/wgl/app/src/wgl_btn.c | 68 +- core/app-framework/wgl/app/src/wgl_cb.c | 40 +- core/app-framework/wgl/app/src/wgl_label.c | 159 +- core/app-framework/wgl/app/src/wgl_list.c | 54 +- core/app-framework/wgl/app/src/wgl_obj.c | 40 +- .../wgl/app/wa-inc/lvgl/lv_obj.h | 470 +-- core/app-framework/wgl/app/wa-inc/lvgl/lvgl.h | 4 - core/app-framework/wgl/app/wa-inc/lvgl/test.c | 8 +- .../app-framework/wgl/native/gui_native_api.h | 22 +- core/app-framework/wgl/native/wgl.h | 6 +- .../wgl/native/wgl_btn_wrapper.c | 40 +- .../app-framework/wgl/native/wgl_cb_wrapper.c | 25 +- .../wgl/native/wgl_label_wrapper.c | 23 +- .../wgl/native/wgl_list_wrapper.c | 20 +- .../wgl/native/wgl_native_utils.c | 29 +- .../wgl/native/wgl_native_utils.h | 43 +- .../wgl/native/wgl_obj_wrapper.c | 107 +- core/app-mgr/app-manager/app_manager.c | 102 +- core/app-mgr/app-manager/app_manager.h | 26 +- core/app-mgr/app-manager/app_manager_host.c | 46 +- core/app-mgr/app-manager/app_manager_host.h | 3 +- core/app-mgr/app-manager/ble_msg.c | 2 +- core/app-mgr/app-manager/event.c | 68 +- core/app-mgr/app-manager/event.h | 2 +- core/app-mgr/app-manager/message.c | 18 +- core/app-mgr/app-manager/module_jeff.c | 2552 +++++++++-------- core/app-mgr/app-manager/module_utils.c | 57 +- core/app-mgr/app-manager/module_wasm_app.c | 623 ++-- core/app-mgr/app-manager/module_wasm_app.h | 14 +- core/app-mgr/app-manager/module_wasm_lib.c | 45 +- .../platform/linux/app_mgr_linux.c | 21 +- .../platform/zephyr/app_mgr_zephyr.c | 24 +- core/app-mgr/app-manager/resource_reg.c | 55 +- core/app-mgr/app-manager/watchdog.c | 46 +- core/app-mgr/app-manager/watchdog.h | 3 +- .../app-mgr-shared/app_manager_export.h | 45 +- core/iwasm/aot/arch/aot_reloc_x86_32.c | 6 +- doc/build_wamr.md | 2 +- test-tools/binarydump-tool/binarydump.c | 60 +- .../README.md | 0 .../__init__.py | 0 .../framework/__init__.py | 0 .../framework/case_base.py | 0 .../framework/engine.py | 0 .../framework/framework.py | 0 .../framework/suite.py | 0 .../framework/test_api.py | 0 .../framework/test_utils.py | 0 .../harness/__init__.py | 0 .../harness/harness_api.py | 0 .../host-clients/src/host_app_sample.c | 84 +- .../host-clients/src/makefile | 0 .../set_dev_env.sh | 0 .../start.py | 0 .../suites/01-life-cycle/__init__.py | 0 .../cases/01-install/__init__.py | 0 .../01-life-cycle/cases/01-install/case.py | 0 .../cases/02-request/__init__.py | 0 .../01-life-cycle/cases/02-request/case.py | 0 .../01-life-cycle/cases/03-event/__init__.py | 0 .../01-life-cycle/cases/03-event/case.py | 0 .../cases/04-request-internal/__init__.py | 0 .../cases/04-request-internal/case.py | 0 .../cases/05-event-internal/__init__.py | 0 .../cases/05-event-internal/case.py | 0 .../01-life-cycle/cases/06-timer/__init__.py | 0 .../01-life-cycle/cases/06-timer/case.py | 0 .../01-life-cycle/cases/07-sensor/__init__.py | 0 .../01-life-cycle/cases/07-sensor/case.py | 0 .../cases/08-on-destroy/__init__.py | 0 .../01-life-cycle/cases/08-on-destroy/case.py | 0 .../suites/01-life-cycle/cases/__init__.py | 0 .../suites/01-life-cycle/suite_setup.py | 0 .../01-life-cycle/test-app/01_install.c | 19 + .../01-life-cycle/test-app/02_request.c | 32 +- .../suites/01-life-cycle/test-app/03_event.c | 26 +- .../test-app/04_request_internal_req.c | 32 +- .../test-app/04_request_internal_resp.c | 27 +- .../test-app/05_event_internal_provider.c | 26 +- .../test-app/05_event_internal_subscriber.c | 26 +- .../suites/01-life-cycle/test-app/06_timer.c | 34 +- .../suites/01-life-cycle/test-app/07_sensor.c | 27 +- .../01-life-cycle/test-app/08_on_destroy.c | 70 + .../suites/01-life-cycle/test-app/build.sh | 0 .../01-life-cycle/tools/product/start.sh | 0 .../01-life-cycle/tools/product/stop.sh | 0 .../suites/__init__.py | 0 .../suites/readme.txt | 0 .../01-life-cycle/test-app/01_install.c | 16 - .../01-life-cycle/test-app/08_on_destroy.c | 67 - test-tools/host-tool/external/cJSON/cJSON.c | 1428 ++++----- test-tools/host-tool/external/cJSON/cJSON.h | 291 +- test-tools/host-tool/src/host_tool_utils.c | 210 +- test-tools/host-tool/src/host_tool_utils.h | 18 +- test-tools/host-tool/src/main.c | 169 +- test-tools/host-tool/src/transport.c | 38 +- test-tools/host-tool/src/transport.h | 24 +- wamr-compiler/main.c | 531 ++-- 143 files changed, 5346 insertions(+), 4596 deletions(-) mode change 100755 => 100644 core/app-framework/base/app/bh_platform.h rename test-tools/{component_test => component-test}/README.md (100%) rename test-tools/{component_test => component-test}/__init__.py (100%) rename test-tools/{component_test => component-test}/framework/__init__.py (100%) rename test-tools/{component_test => component-test}/framework/case_base.py (100%) rename test-tools/{component_test => component-test}/framework/engine.py (100%) rename test-tools/{component_test => component-test}/framework/framework.py (100%) rename test-tools/{component_test => component-test}/framework/suite.py (100%) rename test-tools/{component_test => component-test}/framework/test_api.py (100%) rename test-tools/{component_test => component-test}/framework/test_utils.py (100%) rename test-tools/{component_test => component-test}/harness/__init__.py (100%) rename test-tools/{component_test => component-test}/harness/harness_api.py (100%) rename test-tools/{component_test => component-test}/host-clients/src/host_app_sample.c (81%) rename test-tools/{component_test => component-test}/host-clients/src/makefile (100%) rename test-tools/{component_test => component-test}/set_dev_env.sh (100%) rename test-tools/{component_test => component-test}/start.py (100%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/__init__.py (100%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/cases/01-install/__init__.py (100%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/cases/01-install/case.py (100%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/cases/02-request/__init__.py (100%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/cases/02-request/case.py (100%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/cases/03-event/__init__.py (100%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/cases/03-event/case.py (100%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/cases/04-request-internal/__init__.py (100%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/cases/04-request-internal/case.py (100%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/cases/05-event-internal/__init__.py (100%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/cases/05-event-internal/case.py (100%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/cases/06-timer/__init__.py (100%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/cases/06-timer/case.py (100%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/cases/07-sensor/__init__.py (100%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/cases/07-sensor/case.py (100%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/cases/08-on-destroy/__init__.py (100%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/cases/08-on-destroy/case.py (100%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/cases/__init__.py (100%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/suite_setup.py (100%) create mode 100644 test-tools/component-test/suites/01-life-cycle/test-app/01_install.c rename test-tools/{component_test => component-test}/suites/01-life-cycle/test-app/02_request.c (66%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/test-app/03_event.c (67%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/test-app/04_request_internal_req.c (67%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/test-app/04_request_internal_resp.c (67%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/test-app/05_event_internal_provider.c (67%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/test-app/05_event_internal_subscriber.c (64%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/test-app/06_timer.c (68%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/test-app/07_sensor.c (71%) create mode 100644 test-tools/component-test/suites/01-life-cycle/test-app/08_on_destroy.c rename test-tools/{component_test => component-test}/suites/01-life-cycle/test-app/build.sh (100%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/tools/product/start.sh (100%) rename test-tools/{component_test => component-test}/suites/01-life-cycle/tools/product/stop.sh (100%) rename test-tools/{component_test => component-test}/suites/__init__.py (100%) rename test-tools/{component_test => component-test}/suites/readme.txt (100%) delete mode 100644 test-tools/component_test/suites/01-life-cycle/test-app/01_install.c delete mode 100644 test-tools/component_test/suites/01-life-cycle/test-app/08_on_destroy.c diff --git a/.github/workflows/codeing_guildelines.yml b/.github/workflows/codeing_guildelines.yml index 9c0f71c5d9..de1364f280 100644 --- a/.github/workflows/codeing_guildelines.yml +++ b/.github/workflows/codeing_guildelines.yml @@ -33,7 +33,7 @@ jobs: uses: actions/checkout@v2 with: fetch-depth: 0 - + # github.event.pull_request.base.label = ${{github.repository}}/${{github.base_ref}} - name: Run Coding Guidelines Checks run: /usr/bin/env python3 ./ci/coding_guidelines_check.py --commits ${{ github.event.pull_request.base.sha }}..HEAD diff --git a/core/app-framework/app-native-shared/attr_container.c b/core/app-framework/app-native-shared/attr_container.c index b27dacdf7b..e8c1201960 100644 --- a/core/app-framework/app-native-shared/attr_container.c +++ b/core/app-framework/app-native-shared/attr_container.c @@ -16,79 +16,89 @@ typedef union jvalue { double d; } jvalue; - - -static inline int16_t get_int16(const char *buf) +static inline int16_t +get_int16(const char *buf) { int16_t ret; bh_memcpy_s(&ret, sizeof(int16_t), buf, sizeof(int16_t)); return ret; } -static inline uint16_t get_uint16(const char *buf) +static inline uint16_t +get_uint16(const char *buf) { return get_int16(buf); } -static inline int32_t get_int32(const char *buf) +static inline int32_t +get_int32(const char *buf) { int32_t ret; bh_memcpy_s(&ret, sizeof(int32_t), buf, sizeof(int32_t)); return ret; } -static inline uint32_t get_uint32(const char *buf) +static inline uint32_t +get_uint32(const char *buf) { return get_int32(buf); } -static inline int64_t get_int64(const char *buf) +static inline int64_t +get_int64(const char *buf) { int64_t ret; bh_memcpy_s(&ret, sizeof(int64_t), buf, sizeof(int64_t)); return ret; } -static inline uint64_t get_uint64(const char *buf) +static inline uint64_t +get_uint64(const char *buf) { return get_int64(buf); } -static inline void set_int16(char *buf, int16_t v) +static inline void +set_int16(char *buf, int16_t v) { bh_memcpy_s(buf, sizeof(int16_t), &v, sizeof(int16_t)); } -static inline void set_uint16(char *buf, uint16_t v) +static inline void +set_uint16(char *buf, uint16_t v) { bh_memcpy_s(buf, sizeof(uint16_t), &v, sizeof(uint16_t)); } -static inline void set_int32(char *buf, int32_t v) +static inline void +set_int32(char *buf, int32_t v) { bh_memcpy_s(buf, sizeof(int32_t), &v, sizeof(int32_t)); } -static inline void set_uint32(char *buf, uint32_t v) +static inline void +set_uint32(char *buf, uint32_t v) { bh_memcpy_s(buf, sizeof(uint32_t), &v, sizeof(uint32_t)); } -static inline void set_int64(char *buf, int64_t v) +static inline void +set_int64(char *buf, int64_t v) { bh_memcpy_s(buf, sizeof(int64_t), &v, sizeof(int64_t)); } -static inline void set_uint64(char *buf, uint64_t v) +static inline void +set_uint64(char *buf, uint64_t v) { bh_memcpy_s(buf, sizeof(uint64_t), &v, sizeof(uint64_t)); } -char* +char * attr_container_get_attr_begin(const attr_container_t *attr_cont, - uint32_t *p_total_length, uint16_t *p_attr_num) + uint32_t *p_total_length, uint16_t *p_attr_num) { - char *p = (char*) attr_cont->buf; + char *p = (char *)attr_cont->buf; uint16_t str_len, attr_num; uint32_t total_length; @@ -125,10 +135,10 @@ attr_container_get_attr_begin(const attr_container_t *attr_cont, return p; } -static char* +static char * attr_container_get_attr_next(const char *curr_attr) { - char *p = (char*) curr_attr; + char *p = (char *)curr_attr; uint8_t type; /* key length and key */ @@ -154,7 +164,7 @@ attr_container_get_attr_next(const char *curr_attr) return NULL; } -static const char* +static const char * attr_container_find_attr(const attr_container_t *attr_cont, const char *key) { uint32_t total_length; @@ -164,7 +174,8 @@ attr_container_find_attr(const attr_container_t *attr_cont, const char *key) if (!key) return NULL; - if (!(p = attr_container_get_attr_begin(attr_cont, &total_length, &attr_num))) + if (!(p = attr_container_get_attr_begin(attr_cont, &total_length, + &attr_num))) return NULL; for (i = 0; i < attr_num; i++) { @@ -173,9 +184,9 @@ attr_container_find_attr(const attr_container_t *attr_cont, const char *key) return NULL; if (str_len == strlen(key) + 1 - && memcmp(p + sizeof(uint16_t), key, str_len) == 0) { - if ((uint32_t)(p + sizeof(uint16_t) + str_len - - attr_cont->buf) >= total_length) + && memcmp(p + sizeof(uint16_t), key, str_len) == 0) { + if ((uint32_t)(p + sizeof(uint16_t) + str_len - attr_cont->buf) + >= total_length) return NULL; return p; } @@ -187,14 +198,15 @@ attr_container_find_attr(const attr_container_t *attr_cont, const char *key) return NULL; } -char* +char * attr_container_get_attr_end(const attr_container_t *attr_cont) { uint32_t total_length; uint16_t attr_num, i; char *p; - if (!(p = attr_container_get_attr_begin(attr_cont, &total_length, &attr_num))) + if (!(p = attr_container_get_attr_begin(attr_cont, &total_length, + &attr_num))) return NULL; for (i = 0; i < attr_num; i++) @@ -204,14 +216,15 @@ attr_container_get_attr_end(const attr_container_t *attr_cont) return p; } -static char* +static char * attr_container_get_msg_end(attr_container_t *attr_cont) { char *p = attr_cont->buf; return p + get_uint32(p); } -uint16_t attr_container_get_attr_num(const attr_container_t *attr_cont) +uint16_t +attr_container_get_attr_num(const attr_container_t *attr_cont) { uint16_t str_len; /* skip total length */ @@ -225,7 +238,8 @@ uint16_t attr_container_get_attr_num(const attr_container_t *attr_cont) return get_uint16(p); } -static void attr_container_inc_attr_num(attr_container_t *attr_cont) +static void +attr_container_inc_attr_num(attr_container_t *attr_cont) { uint16_t str_len, attr_num; /* skip total length */ @@ -249,12 +263,12 @@ attr_container_create(const char *tag) tag_length = tag ? strlen(tag) + 1 : 1; length = offsetof(attr_container_t, buf) + - /* total length + tag length + tag + reserved 100 bytes */ - sizeof(uint32_t) + sizeof(uint16_t) + tag_length + 100; + /* total length + tag length + tag + reserved 100 bytes */ + sizeof(uint32_t) + sizeof(uint16_t) + tag_length + 100; if (!(attr_cont = attr_container_malloc(length))) { attr_container_printf( - "Create attr_container failed: allocate memory failed.\r\n"); + "Create attr_container failed: allocate memory failed.\r\n"); return NULL; } @@ -274,34 +288,37 @@ attr_container_create(const char *tag) return attr_cont; } -void attr_container_destroy(const attr_container_t *attr_cont) +void +attr_container_destroy(const attr_container_t *attr_cont) { if (attr_cont) - attr_container_free((char*) attr_cont); + attr_container_free((char *)attr_cont); } -static bool check_set_attr(attr_container_t **p_attr_cont, const char *key) +static bool +check_set_attr(attr_container_t **p_attr_cont, const char *key) { uint32_t flags; if (!p_attr_cont || !*p_attr_cont || !key || strlen(key) == 0) { attr_container_printf( - "Set attribute failed: invalid input arguments.\r\n"); + "Set attribute failed: invalid input arguments.\r\n"); return false; } - flags = get_uint32((char*) *p_attr_cont); + flags = get_uint32((char *)*p_attr_cont); if (flags & ATTR_CONT_READONLY_SHIFT) { attr_container_printf( - "Set attribute failed: attribute container is readonly.\r\n"); + "Set attribute failed: attribute container is readonly.\r\n"); return false; } return true; } -bool attr_container_set_attr(attr_container_t **p_attr_cont, const char *key, - int type, const void *value, int value_length) +bool +attr_container_set_attr(attr_container_t **p_attr_cont, const char *key, + int type, const void *value, int value_length) { attr_container_t *attr_cont, *attr_cont1; uint16_t str_len; @@ -351,13 +368,14 @@ bool attr_container_set_attr(attr_container_t **p_attr_cont, const char *key, set_uint16(p, value_length); p += sizeof(uint16_t); bh_memcpy_s(p, value_length, value, value_length); - } else if (type == ATTR_TYPE_BYTEARRAY) { + } + else if (type == ATTR_TYPE_BYTEARRAY) { set_uint32(p, value_length); p += sizeof(uint32_t); bh_memcpy_s(p, value_length, value, value_length); } - if ((p = (char*) attr_container_find_attr(attr_cont, key))) { + if ((p = (char *)attr_container_find_attr(attr_cont, key))) { /* key found */ p1 = attr_container_get_attr_next(p); @@ -375,22 +393,21 @@ bool attr_container_set_attr(attr_container_t **p_attr_cont, const char *key, } total_length += attr_len + 100; - if (!(attr_cont1 = attr_container_malloc( - offsetof(attr_container_t, buf) + total_length))) { + if (!(attr_cont1 = attr_container_malloc(offsetof(attr_container_t, buf) + + total_length))) { attr_container_printf( - "Set attr failed: allocate memory failed.\r\n"); + "Set attr failed: allocate memory failed.\r\n"); attr_container_free(attr_buf); return false; } - bh_memcpy_s(attr_cont1, p - (char* )attr_cont, attr_cont, - p - (char* )attr_cont); - bh_memcpy_s((char* )attr_cont1 + (unsigned )(p - (char* )attr_cont), - attr_end - p1, p1, attr_end - p1); - bh_memcpy_s( - (char* )attr_cont1 + (unsigned )(p - (char* )attr_cont) - + (unsigned )(attr_end - p1), attr_len, attr_buf, - attr_len); + bh_memcpy_s(attr_cont1, p - (char *)attr_cont, attr_cont, + p - (char *)attr_cont); + bh_memcpy_s((char *)attr_cont1 + (unsigned)(p - (char *)attr_cont), + attr_end - p1, p1, attr_end - p1); + bh_memcpy_s((char *)attr_cont1 + (unsigned)(p - (char *)attr_cont) + + (unsigned)(attr_end - p1), + attr_len, attr_buf, attr_len); p = attr_cont1->buf; set_uint32(p, total_length); *p_attr_cont = attr_cont1; @@ -398,7 +415,8 @@ bool attr_container_set_attr(attr_container_t **p_attr_cont, const char *key, attr_container_free(attr_cont); attr_container_free(attr_buf); return true; - } else { + } + else { /* key not found */ if ((uint32_t)(msg_end - attr_end) >= attr_len) { bh_memcpy_s(attr_end, msg_end - attr_end, attr_buf, attr_len); @@ -408,19 +426,19 @@ bool attr_container_set_attr(attr_container_t **p_attr_cont, const char *key, } total_length += attr_len + 100; - if (!(attr_cont1 = attr_container_malloc( - offsetof(attr_container_t, buf) + total_length))) { + if (!(attr_cont1 = attr_container_malloc(offsetof(attr_container_t, buf) + + total_length))) { attr_container_printf( - "Set attr failed: allocate memory failed.\r\n"); + "Set attr failed: allocate memory failed.\r\n"); attr_container_free(attr_buf); return false; } - bh_memcpy_s(attr_cont1, attr_end - (char* )attr_cont, attr_cont, - attr_end - (char* )attr_cont); - bh_memcpy_s( - (char* )attr_cont1 + (unsigned )(attr_end - (char* )attr_cont), - attr_len, attr_buf, attr_len); + bh_memcpy_s(attr_cont1, attr_end - (char *)attr_cont, attr_cont, + attr_end - (char *)attr_cont); + bh_memcpy_s((char *)attr_cont1 + + (unsigned)(attr_end - (char *)attr_cont), + attr_len, attr_buf, attr_len); attr_container_inc_attr_num(attr_cont1); p = attr_cont1->buf; set_uint32(p, total_length); @@ -434,88 +452,101 @@ bool attr_container_set_attr(attr_container_t **p_attr_cont, const char *key, return false; } -bool attr_container_set_short(attr_container_t **p_attr_cont, const char *key, - short value) +bool +attr_container_set_short(attr_container_t **p_attr_cont, const char *key, + short value) { - return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_SHORT, &value, 2); + return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_SHORT, &value, + 2); } -bool attr_container_set_int(attr_container_t **p_attr_cont, const char *key, - int value) +bool +attr_container_set_int(attr_container_t **p_attr_cont, const char *key, + int value) { return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_INT, &value, 4); } -bool attr_container_set_int64(attr_container_t **p_attr_cont, const char *key, - int64_t value) +bool +attr_container_set_int64(attr_container_t **p_attr_cont, const char *key, + int64_t value) { - return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_INT64, &value, 8); + return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_INT64, &value, + 8); } -bool attr_container_set_byte(attr_container_t **p_attr_cont, const char *key, - int8_t value) +bool +attr_container_set_byte(attr_container_t **p_attr_cont, const char *key, + int8_t value) { return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_BYTE, &value, 1); } -bool attr_container_set_uint16(attr_container_t **p_attr_cont, const char *key, - uint16_t value) +bool +attr_container_set_uint16(attr_container_t **p_attr_cont, const char *key, + uint16_t value) { return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_UINT16, &value, - 2); + 2); } -bool attr_container_set_float(attr_container_t **p_attr_cont, const char *key, - float value) +bool +attr_container_set_float(attr_container_t **p_attr_cont, const char *key, + float value) { - return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_FLOAT, &value, 4); + return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_FLOAT, &value, + 4); } -bool attr_container_set_double(attr_container_t **p_attr_cont, const char *key, - double value) +bool +attr_container_set_double(attr_container_t **p_attr_cont, const char *key, + double value) { return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_DOUBLE, &value, - 8); + 8); } -bool attr_container_set_bool(attr_container_t **p_attr_cont, const char *key, - bool value) +bool +attr_container_set_bool(attr_container_t **p_attr_cont, const char *key, + bool value) { int8_t value1 = value ? 1 : 0; return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_BOOLEAN, &value1, - 1); + 1); } -bool attr_container_set_string(attr_container_t **p_attr_cont, const char *key, - const char *value) +bool +attr_container_set_string(attr_container_t **p_attr_cont, const char *key, + const char *value) { if (!value) { attr_container_printf("Set attr failed: invald input arguments.\r\n"); return false; } return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_STRING, value, - strlen(value) + 1);; + strlen(value) + 1); } -bool attr_container_set_bytearray(attr_container_t **p_attr_cont, - const char *key, const int8_t *value, unsigned length) +bool +attr_container_set_bytearray(attr_container_t **p_attr_cont, const char *key, + const int8_t *value, unsigned length) { if (!value) { attr_container_printf("Set attr failed: invald input arguments.\r\n"); return false; } return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_BYTEARRAY, value, - length);; + length); } -static const char* +static const char * attr_container_get_attr(const attr_container_t *attr_cont, const char *key) { const char *attr_addr; if (!attr_cont || !key) { attr_container_printf( - "Get attribute failed: invalid input arguments.\r\n"); + "Get attribute failed: invalid input arguments.\r\n"); return NULL; } @@ -528,101 +559,103 @@ attr_container_get_attr(const attr_container_t *attr_cont, const char *key) return attr_addr + 2 + strlen(key) + 1; } -#define TEMPLATE_ATTR_BUF_TO_VALUE(attr, key, var_name) do {\ - jvalue val; \ - const char *addr = attr_container_get_attr(attr, key); \ - uint8_t type; \ - if (!addr) \ - return 0; \ - val.j = 0; \ - type = *(uint8_t*)addr++; \ - switch (type) { \ - case ATTR_TYPE_SHORT: \ - case ATTR_TYPE_INT: \ - case ATTR_TYPE_INT64: \ - case ATTR_TYPE_BYTE: \ - case ATTR_TYPE_UINT16: \ - case ATTR_TYPE_FLOAT: \ - case ATTR_TYPE_DOUBLE: \ - case ATTR_TYPE_BOOLEAN: \ - bh_memcpy_s(&val, sizeof(val.var_name), addr, 1 << (type & 3)); \ - break; \ - case ATTR_TYPE_STRING: \ - { \ - unsigned len= get_uint16(addr); \ - addr += 2; \ - if (len > sizeof(val.var_name)) \ - len = sizeof(val.var_name); \ - bh_memcpy_s(&val.var_name, sizeof(val.var_name), addr, len); \ - break; \ - } \ - case ATTR_TYPE_BYTEARRAY: \ - { \ - unsigned len= get_uint32(addr); \ - addr += 4; \ - if (len > sizeof(val.var_name)) \ - len = sizeof(val.var_name); \ - bh_memcpy_s(&val.var_name, sizeof(val.var_name), addr, len); \ - break; \ - } \ - default: \ - bh_assert(0); \ - break; \ - } \ - return val.var_name; \ - } while (0) - -short attr_container_get_as_short(const attr_container_t *attr_cont, - const char *key) +#define TEMPLATE_ATTR_BUF_TO_VALUE(attr, key, var_name) \ + do { \ + jvalue val; \ + const char *addr = attr_container_get_attr(attr, key); \ + uint8_t type; \ + if (!addr) \ + return 0; \ + val.j = 0; \ + type = *(uint8_t *)addr++; \ + switch (type) { \ + case ATTR_TYPE_SHORT: \ + case ATTR_TYPE_INT: \ + case ATTR_TYPE_INT64: \ + case ATTR_TYPE_BYTE: \ + case ATTR_TYPE_UINT16: \ + case ATTR_TYPE_FLOAT: \ + case ATTR_TYPE_DOUBLE: \ + case ATTR_TYPE_BOOLEAN: \ + bh_memcpy_s(&val, sizeof(val.var_name), addr, \ + 1 << (type & 3)); \ + break; \ + case ATTR_TYPE_STRING: \ + { \ + unsigned len = get_uint16(addr); \ + addr += 2; \ + if (len > sizeof(val.var_name)) \ + len = sizeof(val.var_name); \ + bh_memcpy_s(&val.var_name, sizeof(val.var_name), addr, len); \ + break; \ + } \ + case ATTR_TYPE_BYTEARRAY: \ + { \ + unsigned len = get_uint32(addr); \ + addr += 4; \ + if (len > sizeof(val.var_name)) \ + len = sizeof(val.var_name); \ + bh_memcpy_s(&val.var_name, sizeof(val.var_name), addr, len); \ + break; \ + } \ + default: \ + bh_assert(0); \ + break; \ + } \ + return val.var_name; \ + } while (0) + +short +attr_container_get_as_short(const attr_container_t *attr_cont, const char *key) { TEMPLATE_ATTR_BUF_TO_VALUE(attr_cont, key, s); } -int attr_container_get_as_int(const attr_container_t *attr_cont, - const char *key) +int +attr_container_get_as_int(const attr_container_t *attr_cont, const char *key) { TEMPLATE_ATTR_BUF_TO_VALUE(attr_cont, key, i); } -int64_t attr_container_get_as_int64(const attr_container_t *attr_cont, - const char *key) +int64_t +attr_container_get_as_int64(const attr_container_t *attr_cont, const char *key) { TEMPLATE_ATTR_BUF_TO_VALUE(attr_cont, key, j); } -int8_t attr_container_get_as_byte(const attr_container_t *attr_cont, - const char *key) +int8_t +attr_container_get_as_byte(const attr_container_t *attr_cont, const char *key) { TEMPLATE_ATTR_BUF_TO_VALUE(attr_cont, key, b); } -uint16_t attr_container_get_as_uint16(const attr_container_t *attr_cont, - const char *key) +uint16_t +attr_container_get_as_uint16(const attr_container_t *attr_cont, const char *key) { TEMPLATE_ATTR_BUF_TO_VALUE(attr_cont, key, s); } -float attr_container_get_as_float(const attr_container_t *attr_cont, - const char *key) +float +attr_container_get_as_float(const attr_container_t *attr_cont, const char *key) { TEMPLATE_ATTR_BUF_TO_VALUE(attr_cont, key, f); } -double attr_container_get_as_double(const attr_container_t *attr_cont, - const char *key) +double +attr_container_get_as_double(const attr_container_t *attr_cont, const char *key) { TEMPLATE_ATTR_BUF_TO_VALUE(attr_cont, key, d); } -bool attr_container_get_as_bool(const attr_container_t *attr_cont, - const char *key) +bool +attr_container_get_as_bool(const attr_container_t *attr_cont, const char *key) { TEMPLATE_ATTR_BUF_TO_VALUE(attr_cont, key, z); } -const int8_t* +const int8_t * attr_container_get_as_bytearray(const attr_container_t *attr_cont, - const char *key, unsigned *array_length) + const char *key, unsigned *array_length) { const char *addr = attr_container_get_attr(attr_cont, key); uint8_t type; @@ -636,68 +669,68 @@ attr_container_get_as_bytearray(const attr_container_t *attr_cont, return NULL; } - type = *(uint8_t*) addr++; + type = *(uint8_t *)addr++; switch (type) { - case ATTR_TYPE_SHORT: - case ATTR_TYPE_INT: - case ATTR_TYPE_INT64: - case ATTR_TYPE_BYTE: - case ATTR_TYPE_UINT16: - case ATTR_TYPE_FLOAT: - case ATTR_TYPE_DOUBLE: - case ATTR_TYPE_BOOLEAN: - length = 1 << (type & 3); - break; - case ATTR_TYPE_STRING: - length = get_uint16(addr); - addr += 2; - break; - case ATTR_TYPE_BYTEARRAY: - length = get_uint32(addr); - addr += 4; - break; - default: - return NULL; + case ATTR_TYPE_SHORT: + case ATTR_TYPE_INT: + case ATTR_TYPE_INT64: + case ATTR_TYPE_BYTE: + case ATTR_TYPE_UINT16: + case ATTR_TYPE_FLOAT: + case ATTR_TYPE_DOUBLE: + case ATTR_TYPE_BOOLEAN: + length = 1 << (type & 3); + break; + case ATTR_TYPE_STRING: + length = get_uint16(addr); + addr += 2; + break; + case ATTR_TYPE_BYTEARRAY: + length = get_uint32(addr); + addr += 4; + break; + default: + return NULL; } *array_length = length; - return (const int8_t*) addr; + return (const int8_t *)addr; } -char* +char * attr_container_get_as_string(const attr_container_t *attr_cont, const char *key) { unsigned array_length; - return (char*) attr_container_get_as_bytearray(attr_cont, key, - &array_length); + return (char *)attr_container_get_as_bytearray(attr_cont, key, + &array_length); } -const char* +const char * attr_container_get_tag(const attr_container_t *attr_cont) { - return attr_cont ? - attr_cont->buf + sizeof(uint32_t) + sizeof(uint16_t) : NULL; + return attr_cont ? attr_cont->buf + sizeof(uint32_t) + sizeof(uint16_t) + : NULL; } -bool attr_container_contain_key(const attr_container_t *attr_cont, - const char *key) +bool +attr_container_contain_key(const attr_container_t *attr_cont, const char *key) { if (!attr_cont || !key || !strlen(key)) { attr_container_printf( - "Check contain key failed: invalid input arguments.\r\n"); + "Check contain key failed: invalid input arguments.\r\n"); return false; } return attr_container_find_attr(attr_cont, key) ? true : false; } -unsigned int attr_container_get_serialize_length( - const attr_container_t *attr_cont) +unsigned int +attr_container_get_serialize_length(const attr_container_t *attr_cont) { const char *p; if (!attr_cont) { - attr_container_printf( - "Get container serialize length failed: invalid input arguments.\r\n"); + attr_container_printf("Get container serialize length failed: invalid " + "input arguments.\r\n"); return 0; } @@ -705,7 +738,8 @@ unsigned int attr_container_get_serialize_length( return sizeof(uint16_t) + get_uint32(p); } -bool attr_container_serialize(char *buf, const attr_container_t *attr_cont) +bool +attr_container_serialize(char *buf, const attr_container_t *attr_cont) { const char *p; uint16_t flags; @@ -713,7 +747,7 @@ bool attr_container_serialize(char *buf, const attr_container_t *attr_cont) if (!buf || !attr_cont) { attr_container_printf( - "Container serialize failed: invalid input arguments.\r\n"); + "Container serialize failed: invalid input arguments.\r\n"); return false; } @@ -721,27 +755,29 @@ bool attr_container_serialize(char *buf, const attr_container_t *attr_cont) length = sizeof(uint16_t) + get_uint32(p); bh_memcpy_s(buf, length, attr_cont, length); /* Set readonly */ - flags = get_uint16((const char*) attr_cont); + flags = get_uint16((const char *)attr_cont); set_uint16(buf, flags | (1 << ATTR_CONT_READONLY_SHIFT)); return true; } -bool attr_container_is_constant(const attr_container_t* attr_cont) +bool +attr_container_is_constant(const attr_container_t *attr_cont) { uint16_t flags; if (!attr_cont) { attr_container_printf( - "Container check const: invalid input arguments.\r\n"); + "Container check const: invalid input arguments.\r\n"); return false; } - flags = get_uint16((const char*) attr_cont); + flags = get_uint16((const char *)attr_cont); return (flags & (1 << ATTR_CONT_READONLY_SHIFT)) ? true : false; } -void attr_container_dump(const attr_container_t *attr_cont) +void +attr_container_dump(const attr_container_t *attr_cont) { uint32_t total_length; uint16_t attr_num, i, type; @@ -771,64 +807,64 @@ void attr_container_dump(const attr_container_t *attr_cont) attr_container_printf(" key: %s", key); switch (type) { - case ATTR_TYPE_SHORT: - bh_memcpy_s(&value.s, sizeof(int16_t), p, sizeof(int16_t)); - attr_container_printf(", type: short, value: 0x%x\n", - value.s & 0xFFFF); - p += 2; - break; - case ATTR_TYPE_INT: - bh_memcpy_s(&value.i, sizeof(int32_t), p, sizeof(int32_t)); - attr_container_printf(", type: int, value: 0x%x\n", value.i); - p += 4; - break; - case ATTR_TYPE_INT64: - bh_memcpy_s(&value.j, sizeof(uint64_t), p, sizeof(uint64_t)); - attr_container_printf(", type: int64, value: 0x%llx\n", (long long unsigned int)(value.j)); - p += 8; - break; - case ATTR_TYPE_BYTE: - bh_memcpy_s(&value.b, 1, p, 1); - attr_container_printf(", type: byte, value: 0x%x\n", - value.b & 0xFF); - p++; - break; - case ATTR_TYPE_UINT16: - bh_memcpy_s(&value.c, sizeof(uint16_t), p, sizeof(uint16_t)); - attr_container_printf(", type: uint16, value: 0x%x\n", value.c); - p += 2; - break; - case ATTR_TYPE_FLOAT: - bh_memcpy_s(&value.f, sizeof(float), p, sizeof(float)); - attr_container_printf(", type: float, value: %f\n", value.f); - p += 4; - break; - case ATTR_TYPE_DOUBLE: - bh_memcpy_s(&value.d, sizeof(double), p, sizeof(double)); - attr_container_printf(", type: double, value: %f\n", value.d); - p += 8; - break; - case ATTR_TYPE_BOOLEAN: - bh_memcpy_s(&value.z, 1, p, 1); - attr_container_printf(", type: bool, value: 0x%x\n", value.z); - p++; - break; - case ATTR_TYPE_STRING: - attr_container_printf(", type: string, value: %s\n", - p + sizeof(uint16_t)); - p += sizeof(uint16_t) + get_uint16(p); - break; - case ATTR_TYPE_BYTEARRAY: - attr_container_printf(", type: byte array, length: %d\n", - get_uint32(p)); - p += sizeof(uint32_t) + get_uint32(p); - break; - default: - bh_assert(0); - break; + case ATTR_TYPE_SHORT: + bh_memcpy_s(&value.s, sizeof(int16_t), p, sizeof(int16_t)); + attr_container_printf(", type: short, value: 0x%x\n", + value.s & 0xFFFF); + p += 2; + break; + case ATTR_TYPE_INT: + bh_memcpy_s(&value.i, sizeof(int32_t), p, sizeof(int32_t)); + attr_container_printf(", type: int, value: 0x%x\n", value.i); + p += 4; + break; + case ATTR_TYPE_INT64: + bh_memcpy_s(&value.j, sizeof(uint64_t), p, sizeof(uint64_t)); + attr_container_printf(", type: int64, value: 0x%llx\n", + (long long unsigned int)(value.j)); + p += 8; + break; + case ATTR_TYPE_BYTE: + bh_memcpy_s(&value.b, 1, p, 1); + attr_container_printf(", type: byte, value: 0x%x\n", + value.b & 0xFF); + p++; + break; + case ATTR_TYPE_UINT16: + bh_memcpy_s(&value.c, sizeof(uint16_t), p, sizeof(uint16_t)); + attr_container_printf(", type: uint16, value: 0x%x\n", value.c); + p += 2; + break; + case ATTR_TYPE_FLOAT: + bh_memcpy_s(&value.f, sizeof(float), p, sizeof(float)); + attr_container_printf(", type: float, value: %f\n", value.f); + p += 4; + break; + case ATTR_TYPE_DOUBLE: + bh_memcpy_s(&value.d, sizeof(double), p, sizeof(double)); + attr_container_printf(", type: double, value: %f\n", value.d); + p += 8; + break; + case ATTR_TYPE_BOOLEAN: + bh_memcpy_s(&value.z, 1, p, 1); + attr_container_printf(", type: bool, value: 0x%x\n", value.z); + p++; + break; + case ATTR_TYPE_STRING: + attr_container_printf(", type: string, value: %s\n", + p + sizeof(uint16_t)); + p += sizeof(uint16_t) + get_uint16(p); + break; + case ATTR_TYPE_BYTEARRAY: + attr_container_printf(", type: byte array, length: %d\n", + get_uint32(p)); + p += sizeof(uint32_t) + get_uint32(p); + break; + default: + bh_assert(0); + break; } } attr_container_printf("\n"); } - 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 e70d0e4c41..3b7be80626 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 @@ -34,7 +34,7 @@ enum { ATTR_TYPE_END = ATTR_TYPE_BYTEARRAY }; -#define ATTR_CONT_READONLY_SHIFT 2 +#define ATTR_CONT_READONLY_SHIFT 2 typedef struct attr_container { /* container flag: @@ -87,7 +87,7 @@ attr_container_destroy(const attr_container_t *attr_cont); */ bool attr_container_set_short(attr_container_t **p_attr_cont, const char *key, - short value); + short value); /** * Set int attribute in attribute container @@ -101,7 +101,7 @@ attr_container_set_short(attr_container_t **p_attr_cont, const char *key, */ bool attr_container_set_int(attr_container_t **p_attr_cont, const char *key, - int value); + int value); /** * Set int64 attribute in attribute container @@ -115,7 +115,7 @@ attr_container_set_int(attr_container_t **p_attr_cont, const char *key, */ bool attr_container_set_int64(attr_container_t **p_attr_cont, const char *key, - int64_t value); + int64_t value); /** * Set byte attribute in attribute container @@ -129,7 +129,7 @@ attr_container_set_int64(attr_container_t **p_attr_cont, const char *key, */ bool attr_container_set_byte(attr_container_t **p_attr_cont, const char *key, - int8_t value); + int8_t value); /** * Set uint16 attribute in attribute container @@ -143,7 +143,7 @@ attr_container_set_byte(attr_container_t **p_attr_cont, const char *key, */ bool attr_container_set_uint16(attr_container_t **p_attr_cont, const char *key, - uint16_t value); + uint16_t value); /** * Set float attribute in attribute container @@ -157,7 +157,7 @@ attr_container_set_uint16(attr_container_t **p_attr_cont, const char *key, */ bool attr_container_set_float(attr_container_t **p_attr_cont, const char *key, - float value); + float value); /** * Set double attribute in attribute container @@ -171,7 +171,7 @@ attr_container_set_float(attr_container_t **p_attr_cont, const char *key, */ bool attr_container_set_double(attr_container_t **p_attr_cont, const char *key, - double value); + double value); /** * Set bool attribute in attribute container @@ -185,7 +185,7 @@ attr_container_set_double(attr_container_t **p_attr_cont, const char *key, */ bool attr_container_set_bool(attr_container_t **p_attr_cont, const char *key, - bool value); + bool value); /** * Set string attribute in attribute container @@ -199,7 +199,7 @@ attr_container_set_bool(attr_container_t **p_attr_cont, const char *key, */ bool attr_container_set_string(attr_container_t **p_attr_cont, const char *key, - const char *value); + const char *value); /** * Set bytearray attribute in attribute container @@ -214,7 +214,7 @@ attr_container_set_string(attr_container_t **p_attr_cont, const char *key, */ bool attr_container_set_bytearray(attr_container_t **p_attr_cont, const char *key, - const int8_t *value, unsigned length); + const int8_t *value, unsigned length); /** * Get tag of current attribute container @@ -223,7 +223,7 @@ attr_container_set_bytearray(attr_container_t **p_attr_cont, const char *key, * * @return tag of current attribute container */ -const char* +const char * attr_container_get_tag(const attr_container_t *attr_cont); /** @@ -306,7 +306,7 @@ attr_container_get_as_byte(const attr_container_t *attr_cont, const char *key); */ uint16_t attr_container_get_as_uint16(const attr_container_t *attr_cont, - const char *key); + const char *key); /** * Get attribute from attribute container and return it as float value, @@ -331,7 +331,7 @@ attr_container_get_as_float(const attr_container_t *attr_cont, const char *key); */ double attr_container_get_as_double(const attr_container_t *attr_cont, - const char *key); + const char *key); /** * Get attribute from attribute container and return it as bool value, @@ -354,9 +354,9 @@ attr_container_get_as_bool(const attr_container_t *attr_cont, const char *key); * * @return the string value of the attribute, NULL if key isn't found */ -char* +char * attr_container_get_as_string(const attr_container_t *attr_cont, - const char *key); + const char *key); /** * Get attribute from attribute container and return it as bytearray value, @@ -367,9 +367,9 @@ attr_container_get_as_string(const attr_container_t *attr_cont, * * @return the bytearray value of the attribute, NULL if key isn't found */ -const int8_t* +const int8_t * attr_container_get_as_bytearray(const attr_container_t *attr_cont, - const char *key, unsigned *array_length); + const char *key, unsigned *array_length); /** * Get the buffer size of attribute container @@ -400,7 +400,7 @@ attr_container_serialize(char *buf, const attr_container_t *attr_cont); * @return true if const, false otherwise */ bool -attr_container_is_constant(const attr_container_t* attr_cont); +attr_container_is_constant(const attr_container_t *attr_cont); void attr_container_dump(const attr_container_t *attr_cont); @@ -422,4 +422,3 @@ attr_container_dump(const attr_container_t *attr_cont); #endif #endif /* end of _ATTR_CONTAINER_H_ */ - 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 3154b4b5cc..8155ea1f7f 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 @@ -12,8 +12,8 @@ extern "C" { #endif -#define FMT_ATTR_CONTAINER 99 -#define FMT_APP_RAW_BINARY 98 +#define FMT_ATTR_CONTAINER 99 +#define FMT_APP_RAW_BINARY 98 /* the request structure */ typedef struct request { @@ -32,10 +32,10 @@ typedef struct request { // payload of the request, currently only support attr_container_t type void *payload; - //length in bytes of the payload + // length in bytes of the payload int payload_len; - //sender of the request + // sender of the request unsigned long sender; } request_t; @@ -53,21 +53,21 @@ typedef struct response { // payload of the response, void *payload; - //length in bytes of the payload + // length in bytes of the payload int payload_len; - //receiver of the response + // receiver of the response unsigned long reciever; } response_t; int -check_url_start(const char* url, int url_len, const char * leading_str); +check_url_start(const char *url, int url_len, const char *leading_str); bool -match_url(char * pattern, char * matched); +match_url(char *pattern, char *matched); char * -find_key_value(char * buffer, int buffer_len, char * key, char * value, +find_key_value(char *buffer, int buffer_len, char *key, char *value, int value_len, char delimiter); request_t * @@ -77,10 +77,10 @@ void request_cleaner(request_t *request); response_t * -clone_response(response_t * response); +clone_response(response_t *response); void -response_cleaner(response_t * response); +response_cleaner(response_t *response); /** * @brief Set fields of response. @@ -96,8 +96,8 @@ response_cleaner(response_t * response); * @warning the response pointer MUST NOT be NULL */ response_t * -set_response(response_t * response, int status, int fmt, - const char *payload, int payload_len); +set_response(response_t *response, int status, int fmt, const char *payload, + int payload_len); /** * @brief Make a response for a request. @@ -110,7 +110,7 @@ set_response(response_t * response, int status, int fmt, * @warning the request and response pointers MUST NOT be NULL */ response_t * -make_response_for_request(request_t * request, response_t * response); +make_response_for_request(request_t *request, response_t *response); /** * @brief Initialize a request. @@ -127,28 +127,27 @@ make_response_for_request(request_t * request, response_t * response); * @warning the request pointer MUST NOT be NULL */ request_t * -init_request(request_t * request, char *url, int action, int fmt, - void *payload, int payload_len); +init_request(request_t *request, char *url, int action, int fmt, void *payload, + int payload_len); char * -pack_request(request_t *request, int * size); +pack_request(request_t *request, int *size); request_t * -unpack_request(char * packet, int size, request_t * request); +unpack_request(char *packet, int size, request_t *request); char * -pack_response(response_t *response, int * size); +pack_response(response_t *response, int *size); response_t * -unpack_response(char * packet, int size, response_t * response); +unpack_response(char *packet, int size, response_t *response); void -free_req_resp_packet(char * packet); +free_req_resp_packet(char *packet); char * wa_strdup(const char *str); - #ifdef __cplusplus } #endif diff --git a/core/app-framework/app-native-shared/bi-inc/wgl_shared_utils.h b/core/app-framework/app-native-shared/bi-inc/wgl_shared_utils.h index 7a391a1938..86d864e410 100644 --- a/core/app-framework/app-native-shared/bi-inc/wgl_shared_utils.h +++ b/core/app-framework/app-native-shared/bi-inc/wgl_shared_utils.h @@ -8,14 +8,12 @@ #include "bh_platform.h" - #ifdef __cplusplus extern "C" { #endif #include - /* Object native function IDs */ enum { OBJ_FUNC_ID_DEL, diff --git a/core/app-framework/app-native-shared/native_interface.h b/core/app-framework/app-native-shared/native_interface.h index 76af444829..ce9f24780d 100644 --- a/core/app-framework/app-native-shared/native_interface.h +++ b/core/app-framework/app-native-shared/native_interface.h @@ -10,6 +10,4 @@ implemented by both [app] and [native] worlds */ #include "bh_platform.h" - #endif /* end of _NATIVE_INTERFACE_H */ - diff --git a/core/app-framework/app-native-shared/restful_utils.c b/core/app-framework/app-native-shared/restful_utils.c index 74bd59a52a..03e86a6991 100644 --- a/core/app-framework/app-native-shared/restful_utils.c +++ b/core/app-framework/app-native-shared/restful_utils.c @@ -20,22 +20,27 @@ * 4. attr-containers of our own * 5. customized serialization for request/response * - * Now we choose the #5 mainly because we need to quickly get the URL for dispatching - * and sometimes we want to change the URL in the original packet. the request format: - * fixed part: version: (1 byte), code (1 byte), fmt(2 byte), mid (4 bytes), sender_id(4 bytes), url_len(2 bytes), payload_len(4bytes) - * dynamic part: url (bytes in url_len), payload + * Now we choose the #5 mainly because we need to quickly get the URL for + * dispatching and sometimes we want to change the URL in the original packet. + * the request format: fixed part: version: (1 byte), code (1 byte), fmt(2 + * byte), mid (4 bytes), sender_id(4 bytes), url_len(2 bytes), + * payload_len(4bytes) dynamic part: url (bytes in url_len), payload * * response format: - * fixed part: (1 byte), code (1 byte), fmt(2 byte), mid (4 bytes), sender_id(4 bytes), payload_len(4bytes) - * dynamic part: payload + * fixed part: (1 byte), code (1 byte), fmt(2 byte), mid (4 bytes), sender_id(4 + * bytes), payload_len(4bytes) dynamic part: payload */ #define REQUES_PACKET_VER 1 #define REQUEST_PACKET_FIX_PART_LEN 18 #define REQUEST_PACKET_URL_OFFSET REQUEST_PACKET_FIX_PART_LEN -#define REQUEST_PACKET_URL_LEN *((uint16*)((char*) buffer + 12)) /* to ensure little endian */ -#define REQUEST_PACKET_PAYLOAD_LEN *((uint32*)((char*) buffer + 14)) /* to ensure little endian */ -#define REQUEST_PACKET_URL(buffer) ((char*) buffer + REQUEST_PACKET_URL_OFFSET) -#define REQUEST_PACKET_PAYLOAD(buffer) ((char*) buffer + REQUEST_PACKET_URL_OFFSET + REQUEST_PACKET_URL_LEN(buffer)) +#define REQUEST_PACKET_URL_LEN \ + *((uint16 *)((char *)buffer + 12)) /* to ensure little endian */ +#define REQUEST_PACKET_PAYLOAD_LEN \ + *((uint32 *)((char *)buffer + 14)) /* to ensure little endian */ +#define REQUEST_PACKET_URL(buffer) ((char *)buffer + REQUEST_PACKET_URL_OFFSET) +#define REQUEST_PACKET_PAYLOAD(buffer) \ + ((char *)buffer + REQUEST_PACKET_URL_OFFSET \ + + REQUEST_PACKET_URL_LEN(buffer)) #define RESPONSE_PACKET_FIX_PART_LEN 16 @@ -48,17 +53,17 @@ pack_request(request_t *request, int *size) uint32 u32; char *packet; - if ((packet = (char*) WA_MALLOC(len)) == NULL) + if ((packet = (char *)WA_MALLOC(len)) == NULL) return NULL; /* TODO: ensure little endian for words and dwords */ *packet = REQUES_PACKET_VER; - *((uint8*) (packet + 1)) = request->action; + *((uint8 *)(packet + 1)) = request->action; u16 = htons(request->fmt); memcpy(packet + 2, &u16, 2); - u32 = htonl(request->mid); + u32 = htonl(request->mid); memcpy(packet + 4, &u32, 4); u32 = htonl(request->sender); @@ -72,7 +77,7 @@ pack_request(request_t *request, int *size) strcpy(packet + REQUEST_PACKET_URL_OFFSET, request->url); memcpy(packet + REQUEST_PACKET_URL_OFFSET + url_len, request->payload, - request->payload_len); + request->payload_len); *size = len; return packet; @@ -111,7 +116,7 @@ unpack_request(char *packet, int size, request_t *request) return NULL; } - request->action = *((uint8*) (packet + 1)); + request->action = *((uint8 *)(packet + 1)); memcpy(&u16, packet + 2, 2); request->fmt = ntohs(u16); @@ -141,12 +146,12 @@ pack_response(response_t *response, int *size) uint32 u32; char *packet; - if ((packet = (char*) WA_MALLOC(len)) == NULL) + if ((packet = (char *)WA_MALLOC(len)) == NULL) return NULL; /* TODO: ensure little endian for words and dwords */ *packet = REQUES_PACKET_VER; - *((uint8*) (packet + 1)) = response->status; + *((uint8 *)(packet + 1)) = response->status; u16 = htons(response->fmt); memcpy(packet + 2, &u16, 2); @@ -161,7 +166,7 @@ pack_response(response_t *response, int *size) memcpy(packet + 12, &u32, 4); memcpy(packet + RESPONSE_PACKET_FIX_PART_LEN, response->payload, - response->payload_len); + response->payload_len); *size = len; return packet; @@ -184,7 +189,7 @@ unpack_response(char *packet, int size, response_t *response) if (size != (RESPONSE_PACKET_FIX_PART_LEN + payload_len)) return NULL; - response->status = *((uint8*) (packet + 1)); + response->status = *((uint8 *)(packet + 1)); memcpy(&u16, packet + 2, 2); response->fmt = ntohs(u16); @@ -208,7 +213,7 @@ 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; @@ -278,7 +283,7 @@ 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); @@ -296,8 +301,8 @@ clone_response(response_t *response) } response_t * -set_response(response_t *response, int status, int fmt, - const char *payload, int payload_len) +set_response(response_t *response, int status, int fmt, const char *payload, + int payload_len) { response->payload = (void *)payload; response->payload_len = payload_len; @@ -307,8 +312,7 @@ set_response(response_t *response, int status, int fmt, } response_t * -make_response_for_request(request_t *request, - response_t *response) +make_response_for_request(request_t *request, response_t *response) { response->mid = request->mid; response->reciever = request->sender; @@ -319,8 +323,8 @@ make_response_for_request(request_t *request, static unsigned int mid = 0; request_t * -init_request(request_t *request, char *url, int action, int fmt, - void *payload, int payload_len) +init_request(request_t *request, char *url, int action, int fmt, void *payload, + int payload_len) { request->url = url; request->action = action; @@ -334,10 +338,10 @@ init_request(request_t *request, char *url, int action, int fmt, /* check if the "url" is starting with "leading_str" - return: 0 - not match; >0 - the offset of matched url, include any "/" at the end - notes: - 1. it ensures the leading_str "/abc" can pass "/abc/cde" and "/abc/, but fail "/ab" and "/abcd". - leading_str "/abc/" can pass "/abc" + return: 0 - not match; >0 - the offset of matched url, include any "/" at the + end notes: + 1. it ensures the leading_str "/abc" can pass "/abc/cde" and "/abc/, but fail + "/ab" and "/abcd". leading_str "/abc/" can pass "/abc" 2. it omit the '/' at the first char 3. it ensure the leading_str "/abc" can pass "/abc?cde */ @@ -425,7 +429,6 @@ match_url(char *pattern, char *matched) return true; return false; - } else if (pattern[len - 1] == '*') { if (pattern[len - 2] == '/') { @@ -468,9 +471,9 @@ find_key_value(char *buffer, int buffer_len, char *key, char *value, if (0 == strncmp(p, key, key_len) && p[key_len] == '=') { p += (key_len + 1); remaining -= (key_len + 1); - char * v = value; + char *v = value; memset(value, 0, value_len); - value_len--; /* ensure last char is 0 */ + value_len--; /* ensure last char is 0 */ while (*p != delimiter && remaining > 0 && value_len > 0) { *v++ = *p++; remaining--; diff --git a/core/app-framework/app_ext_lib_export.c b/core/app-framework/app_ext_lib_export.c index 6e66fdfb6d..532491b431 100644 --- a/core/app-framework/app_ext_lib_export.c +++ b/core/app-framework/app_ext_lib_export.c @@ -1,33 +1,33 @@ #include "lib_export.h" #ifdef APP_FRAMEWORK_SENSOR - #include "sensor_native_api.h" +#include "sensor_native_api.h" #endif #ifdef APP_FRAMEWORK_CONNECTION - #include "connection_native_api.h" +#include "connection_native_api.h" #endif #ifdef APP_FRAMEWORK_WGL - #include "gui_native_api.h" +#include "gui_native_api.h" #endif /* More header file here */ static NativeSymbol extended_native_symbol_defs[] = { #ifdef APP_FRAMEWORK_SENSOR - #include "runtime_sensor.inl" +#include "runtime_sensor.inl" #endif #ifdef APP_FRAMEWORK_CONNECTION - #include "connection.inl" +#include "connection.inl" #endif #ifdef APP_FRAMEWORK_WGL - #include "wamr_gui.inl" +#include "wamr_gui.inl" #endif -/* More inl file here */ + /* More inl file here */ }; int @@ -36,4 +36,3 @@ get_ext_lib_export_apis(NativeSymbol **p_ext_lib_apis) *p_ext_lib_apis = extended_native_symbol_defs; return sizeof(extended_native_symbol_defs) / sizeof(NativeSymbol); } - diff --git a/core/app-framework/base/app/bh_platform.c b/core/app-framework/base/app/bh_platform.c index 0dbf04752e..1848d07927 100644 --- a/core/app-framework/base/app/bh_platform.c +++ b/core/app-framework/base/app/bh_platform.c @@ -13,14 +13,16 @@ * */ -static bool is_little_endian() +static bool +is_little_endian() { long i = 0x01020304; - unsigned char* c = (unsigned char*) &i; + unsigned char *c = (unsigned char *)&i; return (*c == 0x04) ? true : false; } -static void swap32(uint8* pData) +static void +swap32(uint8 *pData) { uint8 value = *pData; *pData = *(pData + 3); @@ -31,31 +33,35 @@ static void swap32(uint8* pData) *(pData + 2) = value; } -static void swap16(uint8* pData) +static void +swap16(uint8 *pData) { uint8 value = *pData; *(pData) = *(pData + 1); *(pData + 1) = value; } -uint32 htonl(uint32 value) +uint32 +htonl(uint32 value) { uint32 ret; if (is_little_endian()) { ret = value; - swap32((uint8*) &ret); + swap32((uint8 *)&ret); return ret; } return value; } -uint32 ntohl(uint32 value) +uint32 +ntohl(uint32 value) { return htonl(value); } -uint16 htons(uint16 value) +uint16 +htons(uint16 value) { uint16 ret; if (is_little_endian()) { @@ -67,12 +73,14 @@ uint16 htons(uint16 value) return value; } -uint16 ntohs(uint16 value) +uint16 +ntohs(uint16 value) { return htons(value); } -char *wa_strdup(const char *s) +char * +wa_strdup(const char *s) { char *s1 = NULL; if (s && (s1 = WA_MALLOC(strlen(s) + 1))) diff --git a/core/app-framework/base/app/bh_platform.h b/core/app-framework/base/app/bh_platform.h old mode 100755 new mode 100644 index 70760e9c16..8e10dcb646 --- a/core/app-framework/base/app/bh_platform.h +++ b/core/app-framework/base/app/bh_platform.h @@ -16,7 +16,7 @@ typedef unsigned int uint32; typedef int int32; #ifndef NULL -# define NULL ((void*) 0) +#define NULL ((void *)0) #endif #ifndef __cplusplus @@ -35,28 +35,31 @@ typedef int int32; #define WA_FREE free #endif - -uint32 htonl(uint32 value); -uint32 ntohl(uint32 value); -uint16 htons(uint16 value); -uint16 ntohs(uint16 value); - +uint32 +htonl(uint32 value); +uint32 +ntohl(uint32 value); +uint16 +htons(uint16 value); +uint16 +ntohs(uint16 value); // We are not worried for the WASM world since the sandbox will catch it. -#define bh_memcpy_s(dst, dst_len, src, src_len) memcpy(dst, src, src_len) +#define bh_memcpy_s(dst, dst_len, src, src_len) memcpy(dst, src, src_len) #ifdef NDEBUG #define bh_assert(v) (void)0 #else -#define bh_assert(v) do { \ - if (!(v)) { \ - int _count; \ - printf("ASSERTION FAILED: %s, at %s, line %d",\ - #v, __FILE__, __LINE__); \ - _count = printf("\n"); \ - printf("%d\n", _count / (_count - 1)); \ - } \ - } while (0) +#define bh_assert(v) \ + do { \ + if (!(v)) { \ + int _count; \ + printf("ASSERTION FAILED: %s, at %s, line %d", #v, __FILE__, \ + __LINE__); \ + _count = printf("\n"); \ + printf("%d\n", _count / (_count - 1)); \ + } \ + } while (0) #endif #endif /* DEPS_IWASM_APP_LIBS_BASE_BH_PLATFORM_H_ */ diff --git a/core/app-framework/base/app/req_resp_api.h b/core/app-framework/base/app/req_resp_api.h index cbddab5f7f..575c357321 100644 --- a/core/app-framework/base/app/req_resp_api.h +++ b/core/app-framework/base/app/req_resp_api.h @@ -29,4 +29,3 @@ wasm_sub_event(const char *url); #endif #endif /* end of _REQ_RESP_API_H_ */ - diff --git a/core/app-framework/base/app/request.c b/core/app-framework/base/app/request.c index 13fa22a8ff..3ba44fbc7e 100644 --- a/core/app-framework/base/app/request.c +++ b/core/app-framework/base/app/request.c @@ -13,13 +13,11 @@ #define TRANSACTION_TIMEOUT_MS 5000 -typedef enum { - Reg_Event, Reg_Request -} reg_type_t; +typedef enum { Reg_Event, Reg_Request } reg_type_t; typedef struct _res_register { struct _res_register *next; - const char * url; + const char *url; reg_type_t reg_type; void (*request_handler)(request_t *); } res_register_t; @@ -32,13 +30,14 @@ typedef struct transaction { void *user_data; } transaction_t; -static res_register_t * g_resources = NULL; +static res_register_t *g_resources = NULL; static transaction_t *g_transactions = NULL; static user_timer_t g_trans_timer = NULL; -static transaction_t *transaction_find(int mid) +static transaction_t * +transaction_find(int mid) { transaction_t *t = g_transactions; @@ -55,7 +54,8 @@ static transaction_t *transaction_find(int mid) * new transaction is added to the tail of the list, so the list * is sorted by expiry time naturally. */ -static void transaction_add(transaction_t *trans) +static void +transaction_add(transaction_t *trans) { transaction_t *t; @@ -73,7 +73,8 @@ static void transaction_add(transaction_t *trans) } } -static void transaction_remove(transaction_t *trans) +static void +transaction_remove(transaction_t *trans) { transaction_t *prev = NULL, *current = g_transactions; @@ -93,15 +94,17 @@ static void transaction_remove(transaction_t *trans) } } -static bool is_event_type(request_t * req) +static bool +is_event_type(request_t *req) { return req->action == COAP_EVENT; } -static bool register_url_handler(const char *url, - request_handler_f request_handler, reg_type_t reg_type) +static bool +register_url_handler(const char *url, request_handler_f request_handler, + reg_type_t reg_type) { - res_register_t * r = g_resources; + res_register_t *r = g_resources; while (r) { if (reg_type == r->reg_type && strcmp(r->url, url) == 0) { @@ -111,7 +114,7 @@ static bool register_url_handler(const char *url, r = r->next; } - r = (res_register_t *) malloc(sizeof(res_register_t)); + r = (res_register_t *)malloc(sizeof(res_register_t)); if (r == NULL) return false; @@ -137,13 +140,15 @@ static bool register_url_handler(const char *url, return true; } -bool api_register_resource_handler(const char *url, - request_handler_f request_handler) +bool +api_register_resource_handler(const char *url, + request_handler_f request_handler) { return register_url_handler(url, request_handler, Reg_Request); } -static void transaction_timeout_handler(user_timer_t timer) +static void +transaction_timeout_handler(user_timer_t timer) { transaction_t *cur, *expired = NULL; unsigned int elpased_ms, now = wasm_get_sys_tick_ms(); @@ -164,7 +169,8 @@ static void transaction_timeout_handler(user_timer_t timer) cur->next = expired; expired = cur; cur = g_transactions; - } else { + } + else { break; } } @@ -186,27 +192,30 @@ static void transaction_timeout_handler(user_timer_t timer) unsigned int elpased_ms, ms_to_expiry, now = wasm_get_sys_tick_ms(); if (now < g_transactions->time) { elpased_ms = now + (0xFFFFFFFF - g_transactions->time) + 1; - } else { + } + else { elpased_ms = now - g_transactions->time; } ms_to_expiry = TRANSACTION_TIMEOUT_MS - elpased_ms; api_timer_restart(g_trans_timer, ms_to_expiry); - } else { + } + else { api_timer_cancel(g_trans_timer); g_trans_timer = NULL; } } -void api_send_request(request_t * request, response_handler_f response_handler, - void * user_data) +void +api_send_request(request_t *request, response_handler_f response_handler, + void *user_data) { int size; char *buffer; transaction_t *trans; - if ((trans = (transaction_t *) malloc(sizeof(transaction_t))) == NULL) { + if ((trans = (transaction_t *)malloc(sizeof(transaction_t))) == NULL) { printf( - "send request: allocate memory for request transaction failed!\n"); + "send request: allocate memory for request transaction failed!\n"); return; } @@ -228,9 +237,8 @@ void api_send_request(request_t * request, response_handler_f response_handler, if (trans == g_transactions) { /* assert(g_trans_timer == NULL); */ if (g_trans_timer == NULL) { - g_trans_timer = api_timer_create(TRANSACTION_TIMEOUT_MS, - false, - true, transaction_timeout_handler); + g_trans_timer = api_timer_create(TRANSACTION_TIMEOUT_MS, false, + true, transaction_timeout_handler); } } @@ -241,11 +249,13 @@ void api_send_request(request_t * request, response_handler_f response_handler, /* * - * APIs for the native layers to callback for request/response arrived to this app + * APIs for the native layers to callback for request/response arrived to this + * app * */ -void on_response(char * buffer, int size) +void +on_response(char *buffer, int size) { response_t response[1]; transaction_t *trans; @@ -262,7 +272,8 @@ void on_response(char * buffer, int size) /* * When the 1st transaction get response: - * 1. If the 2nd trans exist, restart the timer according to its expiry time; + * 1. If the 2nd trans exist, restart the timer according to its expiry + * time; * 2. Otherwise, stop the timer since there is no more transactions; */ if (trans == g_transactions) { @@ -270,12 +281,14 @@ void on_response(char * buffer, int size) unsigned int elpased_ms, ms_to_expiry, now = wasm_get_sys_tick_ms(); if (now < trans->next->time) { elpased_ms = now + (0xFFFFFFFF - trans->next->time) + 1; - } else { + } + else { elpased_ms = now - trans->next->time; } ms_to_expiry = TRANSACTION_TIMEOUT_MS - elpased_ms; api_timer_restart(g_trans_timer, ms_to_expiry); - } else { + } + else { api_timer_cancel(g_trans_timer); g_trans_timer = NULL; } @@ -285,7 +298,8 @@ void on_response(char * buffer, int size) transaction_remove(trans); } -void on_request(char *buffer, int size) +void +on_request(char *buffer, int size) { request_t request[1]; bool is_event; @@ -300,9 +314,9 @@ void on_request(char *buffer, int size) while (r) { if ((is_event && r->reg_type == Reg_Event) - || (!is_event && r->reg_type == Reg_Request)) { + || (!is_event && r->reg_type == Reg_Request)) { if (check_url_start(request->url, strlen(request->url), r->url) - > 0) { + > 0) { r->request_handler(request); return; } @@ -314,10 +328,11 @@ void on_request(char *buffer, int size) printf("on_request: exit. no service handler\n"); } -void api_response_send(response_t *response) +void +api_response_send(response_t *response) { int size; - char * buffer = pack_response(response, &size); + char *buffer = pack_response(response, &size); if (buffer == NULL) return; @@ -327,12 +342,13 @@ void api_response_send(response_t *response) /// event api -bool api_publish_event(const char *url, int fmt, void *payload, int payload_len) +bool +api_publish_event(const char *url, int fmt, void *payload, int payload_len) { int size; request_t request[1]; init_request(request, (char *)url, COAP_EVENT, fmt, payload, payload_len); - char * buffer = pack_request(request, &size); + char *buffer = pack_request(request, &size); if (buffer == NULL) return false; wasm_post_request(buffer, size); @@ -342,8 +358,8 @@ bool api_publish_event(const char *url, int fmt, void *payload, int payload_len) return true; } -bool api_subscribe_event(const char * url, request_handler_f handler) +bool +api_subscribe_event(const char *url, request_handler_f handler) { return register_url_handler(url, handler, Reg_Event); } - diff --git a/core/app-framework/base/app/timer.c b/core/app-framework/base/app/timer.c index 41bd59f59b..692626ca36 100644 --- a/core/app-framework/base/app/timer.c +++ b/core/app-framework/base/app/timer.c @@ -16,22 +16,23 @@ #endif struct user_timer { - struct user_timer * next; + struct user_timer *next; int timer_id; void (*user_timer_callback)(user_timer_t); }; -struct user_timer * g_timers = NULL; +struct user_timer *g_timers = NULL; -user_timer_t api_timer_create(int interval, bool is_period, bool auto_start, - on_user_timer_update_f on_timer_update) +user_timer_t +api_timer_create(int interval, bool is_period, bool auto_start, + on_user_timer_update_f on_timer_update) { int timer_id = wasm_create_timer(interval, is_period, auto_start); - //TODO - struct user_timer * timer = (struct user_timer *) malloc( - sizeof(struct user_timer)); + // TODO + struct user_timer *timer = + (struct user_timer *)malloc(sizeof(struct user_timer)); if (timer == NULL) { // TODO: remove the timer_id printf("### api_timer_create malloc faild!!! \n"); @@ -52,7 +53,8 @@ user_timer_t api_timer_create(int interval, bool is_period, bool auto_start, return timer; } -void api_timer_cancel(user_timer_t timer) +void +api_timer_cancel(user_timer_t timer) { user_timer_t t = g_timers, prev = NULL; @@ -63,26 +65,30 @@ void api_timer_cancel(user_timer_t timer) if (prev == NULL) { g_timers = t->next; free(t); - } else { + } + else { prev->next = t->next; free(t); } return; - } else { + } + else { prev = t; t = t->next; } } } -void api_timer_restart(user_timer_t timer, int interval) +void +api_timer_restart(user_timer_t timer, int interval) { wasm_timer_restart(timer->timer_id, interval); } -void on_timer_callback(int timer_id) +void +on_timer_callback(int timer_id) { - struct user_timer * t = g_timers; + struct user_timer *t = g_timers; while (t) { if (t->timer_id == timer_id) { @@ -92,4 +98,3 @@ void on_timer_callback(int timer_id) t = t->next; } } - diff --git a/core/app-framework/base/app/timer_api.h b/core/app-framework/base/app/timer_api.h index 0881bab95c..1fc7555ef2 100644 --- a/core/app-framework/base/app/timer_api.h +++ b/core/app-framework/base/app/timer_api.h @@ -34,4 +34,3 @@ wasm_get_sys_tick_ms(void); #endif #endif /* end of _TIMER_API_H_ */ - diff --git a/core/app-framework/base/app/wa-inc/request.h b/core/app-framework/base/app/wa-inc/request.h index c209fae7cc..25830f0a47 100644 --- a/core/app-framework/base/app/wa-inc/request.h +++ b/core/app-framework/base/app/wa-inc/request.h @@ -12,7 +12,6 @@ extern "C" { #endif - /* CoAP request method codes */ typedef enum { COAP_GET = 1, @@ -26,39 +25,40 @@ typedef enum { typedef enum { NO_ERROR = 0, - CREATED_2_01 = 65, /* CREATED */ - DELETED_2_02 = 66, /* DELETED */ - VALID_2_03 = 67, /* NOT_MODIFIED */ - CHANGED_2_04 = 68, /* CHANGED */ - CONTENT_2_05 = 69, /* OK */ + CREATED_2_01 = 65, /* CREATED */ + DELETED_2_02 = 66, /* DELETED */ + VALID_2_03 = 67, /* NOT_MODIFIED */ + CHANGED_2_04 = 68, /* CHANGED */ + CONTENT_2_05 = 69, /* OK */ CONTINUE_2_31 = 95, /* CONTINUE */ - BAD_REQUEST_4_00 = 128, /* BAD_REQUEST */ - UNAUTHORIZED_4_01 = 129, /* UNAUTHORIZED */ - BAD_OPTION_4_02 = 130, /* BAD_OPTION */ - FORBIDDEN_4_03 = 131, /* FORBIDDEN */ - NOT_FOUND_4_04 = 132, /* NOT_FOUND */ - METHOD_NOT_ALLOWED_4_05 = 133, /* METHOD_NOT_ALLOWED */ - NOT_ACCEPTABLE_4_06 = 134, /* NOT_ACCEPTABLE */ - PRECONDITION_FAILED_4_12 = 140, /* BAD_REQUEST */ + BAD_REQUEST_4_00 = 128, /* BAD_REQUEST */ + UNAUTHORIZED_4_01 = 129, /* UNAUTHORIZED */ + BAD_OPTION_4_02 = 130, /* BAD_OPTION */ + FORBIDDEN_4_03 = 131, /* FORBIDDEN */ + NOT_FOUND_4_04 = 132, /* NOT_FOUND */ + METHOD_NOT_ALLOWED_4_05 = 133, /* METHOD_NOT_ALLOWED */ + NOT_ACCEPTABLE_4_06 = 134, /* NOT_ACCEPTABLE */ + PRECONDITION_FAILED_4_12 = 140, /* BAD_REQUEST */ REQUEST_ENTITY_TOO_LARGE_4_13 = 141, /* REQUEST_ENTITY_TOO_LARGE */ - UNSUPPORTED_MEDIA_TYPE_4_15 = 143, /* UNSUPPORTED_MEDIA_TYPE */ + UNSUPPORTED_MEDIA_TYPE_4_15 = 143, /* UNSUPPORTED_MEDIA_TYPE */ - INTERNAL_SERVER_ERROR_5_00 = 160, /* INTERNAL_SERVER_ERROR */ - NOT_IMPLEMENTED_5_01 = 161, /* NOT_IMPLEMENTED */ - BAD_GATEWAY_5_02 = 162, /* BAD_GATEWAY */ - SERVICE_UNAVAILABLE_5_03 = 163, /* SERVICE_UNAVAILABLE */ - GATEWAY_TIMEOUT_5_04 = 164, /* GATEWAY_TIMEOUT */ + INTERNAL_SERVER_ERROR_5_00 = 160, /* INTERNAL_SERVER_ERROR */ + NOT_IMPLEMENTED_5_01 = 161, /* NOT_IMPLEMENTED */ + BAD_GATEWAY_5_02 = 162, /* BAD_GATEWAY */ + SERVICE_UNAVAILABLE_5_03 = 163, /* SERVICE_UNAVAILABLE */ + GATEWAY_TIMEOUT_5_04 = 164, /* GATEWAY_TIMEOUT */ PROXYING_NOT_SUPPORTED_5_05 = 165, /* PROXYING_NOT_SUPPORTED */ /* Erbium errors */ - MEMORY_ALLOCATION_ERROR = 192, PACKET_SERIALIZATION_ERROR, + MEMORY_ALLOCATION_ERROR = 192, + PACKET_SERIALIZATION_ERROR, /* Erbium hooks */ - MANUAL_RESPONSE, PING_RESPONSE + MANUAL_RESPONSE, + PING_RESPONSE } coap_status_t; - /** * @typedef request_handler_f * @@ -87,7 +87,6 @@ typedef void (*request_handler_f)(request_t *request); */ typedef void (*response_handler_f)(response_t *response, void *user_data); - /* ***************** * Request APIs @@ -102,7 +101,8 @@ typedef void (*response_handler_f)(response_t *response, void *user_data); * * @return true if success, false otherwise */ -bool api_register_resource_handler(const char *url, request_handler_f handler); +bool +api_register_resource_handler(const char *url, request_handler_f handler); /** * @brief Send request asynchronously. @@ -111,8 +111,9 @@ bool api_register_resource_handler(const char *url, request_handler_f handler); * @param response_handler callback function to handle the response * @param user_data user data */ -void api_send_request(request_t * request, response_handler_f response_handler, - void * user_data); +void +api_send_request(request_t *request, response_handler_f response_handler, + void *user_data); /** * @brief Send response. @@ -130,8 +131,8 @@ void api_send_request(request_t * request, response_handler_f response_handler, * } * @endcode */ -void api_response_send(response_t *response); - +void +api_response_send(response_t *response); /* ***************** @@ -149,9 +150,8 @@ void api_response_send(response_t *response); * * @return true if success, false otherwise */ -bool api_publish_event(const char *url, int fmt, void *payload, - int payload_len); - +bool +api_publish_event(const char *url, int fmt, void *payload, int payload_len); /** * @brief Subscribe an event. @@ -161,7 +161,8 @@ bool api_publish_event(const char *url, int fmt, void *payload, * * @return true if success, false otherwise */ -bool api_subscribe_event(const char * url, request_handler_f handler); +bool +api_subscribe_event(const char *url, request_handler_f handler); #ifdef __cplusplus } diff --git a/core/app-framework/base/app/wa-inc/timer_wasm_app.h b/core/app-framework/base/app/wa-inc/timer_wasm_app.h index 17e59bc036..cf158a3658 100644 --- a/core/app-framework/base/app/wa-inc/timer_wasm_app.h +++ b/core/app-framework/base/app/wa-inc/timer_wasm_app.h @@ -14,7 +14,7 @@ extern "C" { /* board producer define user_timer */ struct user_timer; -typedef struct user_timer * user_timer_t; +typedef struct user_timer *user_timer_t; /** * @typedef on_user_timer_update_f @@ -43,15 +43,17 @@ typedef void (*on_user_timer_update_f)(user_timer_t timer); * * @return the timer created if success, NULL otherwise */ -user_timer_t api_timer_create(int interval, bool is_period, bool auto_start, - on_user_timer_update_f on_timer_update); +user_timer_t +api_timer_create(int interval, bool is_period, bool auto_start, + on_user_timer_update_f on_timer_update); /** * @brief Cancel timer. * * @param timer the timer to cancel */ -void api_timer_cancel(user_timer_t timer); +void +api_timer_cancel(user_timer_t timer); /** * @brief Restart timer. @@ -59,7 +61,8 @@ void api_timer_cancel(user_timer_t timer); * @param timer the timer to cancel * @param interval the timer interval */ -void api_timer_restart(user_timer_t timer, int interval); +void +api_timer_restart(user_timer_t timer, int interval); #ifdef __cplusplus } diff --git a/core/app-framework/base/app/wasm_app.h b/core/app-framework/base/app/wasm_app.h index a22e77ed45..e7be8a4c1b 100644 --- a/core/app-framework/base/app/wasm_app.h +++ b/core/app-framework/base/app/wasm_app.h @@ -13,7 +13,6 @@ extern "C" { #endif - #ifdef __cplusplus } #endif diff --git a/core/app-framework/base/native/base_lib_export.c b/core/app-framework/base/native/base_lib_export.c index 0b716fc5eb..19ac7185c2 100644 --- a/core/app-framework/base/native/base_lib_export.c +++ b/core/app-framework/base/native/base_lib_export.c @@ -10,16 +10,15 @@ #include "req_resp_native_api.h" #include "timer_native_api.h" - static NativeSymbol extended_native_symbol_defs[] = { - /* TODO: use macro EXPORT_WASM_API() or EXPORT_WASM_API2() to - add functions to register. */ - #include "base_lib.inl" +/* TODO: use macro EXPORT_WASM_API() or EXPORT_WASM_API2() to + add functions to register. */ +#include "base_lib.inl" }; -uint32 get_base_lib_export_apis(NativeSymbol **p_base_lib_apis) +uint32 +get_base_lib_export_apis(NativeSymbol **p_base_lib_apis) { *p_base_lib_apis = extended_native_symbol_defs; return sizeof(extended_native_symbol_defs) / sizeof(NativeSymbol); } - diff --git a/core/app-framework/base/native/req_resp_native_api.h b/core/app-framework/base/native/req_resp_native_api.h index 6fe0581b6e..3e5938772c 100644 --- a/core/app-framework/base/native/req_resp_native_api.h +++ b/core/app-framework/base/native/req_resp_native_api.h @@ -27,4 +27,3 @@ wasm_sub_event(wasm_exec_env_t exec_env, char *url); #endif #endif /* end of _REQ_RESP_API_H_ */ - diff --git a/core/app-framework/base/native/request_response.c b/core/app-framework/base/native/request_response.c index 4088c38857..674ba5e9dd 100644 --- a/core/app-framework/base/native/request_response.c +++ b/core/app-framework/base/native/request_response.c @@ -8,7 +8,8 @@ #include "wasm_export.h" #include "bh_assert.h" -extern void module_request_handler(request_t *request, void *user_data); +extern void +module_request_handler(request_t *request, void *user_data); bool wasm_response_send(wasm_exec_env_t exec_env, char *buffer, int size) @@ -33,8 +34,8 @@ wasm_register_resource(wasm_exec_env_t exec_env, char *url) wasm_module_inst_t module_inst = get_module_inst(exec_env); if (url != NULL) { - unsigned int mod_id = app_manager_get_module_id(Module_WASM_App, - module_inst); + unsigned int mod_id = + app_manager_get_module_id(Module_WASM_App, module_inst); bh_assert(mod_id != ID_NONE); am_register_resource(url, module_request_handler, mod_id); } @@ -54,8 +55,8 @@ wasm_post_request(wasm_exec_env_t exec_env, char *buffer, int size) // TODO: add permission check, ensure app can't do harm // set sender to help dispatch the response to the sender ap - unsigned int mod_id = app_manager_get_module_id(Module_WASM_App, - module_inst); + unsigned int mod_id = + app_manager_get_module_id(Module_WASM_App, module_inst); bh_assert(mod_id != ID_NONE); req->sender = mod_id; @@ -74,11 +75,10 @@ wasm_sub_event(wasm_exec_env_t exec_env, char *url) wasm_module_inst_t module_inst = get_module_inst(exec_env); if (url != NULL) { - unsigned int mod_id = app_manager_get_module_id(Module_WASM_App, - module_inst); + unsigned int mod_id = + app_manager_get_module_id(Module_WASM_App, module_inst); bh_assert(mod_id != ID_NONE); am_register_event(url, mod_id); } } - diff --git a/core/app-framework/base/native/runtime_lib.h b/core/app-framework/base/native/runtime_lib.h index 8fb9dbb341..ec4d84cb7d 100644 --- a/core/app-framework/base/native/runtime_lib.h +++ b/core/app-framework/base/native/runtime_lib.h @@ -6,13 +6,17 @@ #ifndef LIB_BASE_RUNTIME_LIB_H_ #define LIB_BASE_RUNTIME_LIB_H_ - #include "runtime_timer.h" -void init_wasm_timer(); -void exit_wasm_timer(); -timer_ctx_t get_wasm_timer_ctx(); -timer_ctx_t create_wasm_timer_ctx(unsigned int module_id, int prealloc_num); -void destroy_module_timer_ctx(unsigned int module_id); +void +init_wasm_timer(); +void +exit_wasm_timer(); +timer_ctx_t +get_wasm_timer_ctx(); +timer_ctx_t +create_wasm_timer_ctx(unsigned int module_id, int prealloc_num); +void +destroy_module_timer_ctx(unsigned int module_id); #endif /* LIB_BASE_RUNTIME_LIB_H_ */ diff --git a/core/app-framework/base/native/timer_native_api.h b/core/app-framework/base/native/timer_native_api.h index 4d1f58786d..138e7c60d3 100644 --- a/core/app-framework/base/native/timer_native_api.h +++ b/core/app-framework/base/native/timer_native_api.h @@ -9,7 +9,6 @@ #include "bh_platform.h" #include "wasm_export.h" - #ifdef __cplusplus extern "C" { #endif @@ -23,15 +22,14 @@ typedef unsigned int timer_id_t; typedef unsigned int timer_id_t; timer_id_t -wasm_create_timer(wasm_exec_env_t exec_env, - int interval, bool is_period, bool auto_start); +wasm_create_timer(wasm_exec_env_t exec_env, int interval, bool is_period, + bool auto_start); void wasm_timer_destroy(wasm_exec_env_t exec_env, timer_id_t timer_id); void wasm_timer_cancel(wasm_exec_env_t exec_env, timer_id_t timer_id); void -wasm_timer_restart(wasm_exec_env_t exec_env, - timer_id_t timer_id, int interval); +wasm_timer_restart(wasm_exec_env_t exec_env, timer_id_t timer_id, int interval); uint32 wasm_get_sys_tick_ms(wasm_exec_env_t exec_env); @@ -40,4 +38,3 @@ wasm_get_sys_tick_ms(wasm_exec_env_t exec_env); #endif #endif /* end of _TIMER_API_H_ */ - diff --git a/core/app-framework/base/native/timer_wrapper.c b/core/app-framework/base/native/timer_wrapper.c index 07aca8b41a..7ad350cf20 100644 --- a/core/app-framework/base/native/timer_wrapper.c +++ b/core/app-framework/base/native/timer_wrapper.c @@ -22,7 +22,7 @@ static korp_mutex g_timer_ctx_list_mutex; void wasm_timer_callback(timer_id_t id, unsigned int mod_id) { - module_data* module = module_data_list_lookup_id(mod_id); + module_data *module = module_data_list_lookup_id(mod_id); if (module == NULL) return; @@ -40,7 +40,8 @@ wasm_timer_callback(timer_id_t id, unsigned int mod_id) * the module from module id. It is for avoiding that situation. */ -void * thread_modulers_timer_check(void * arg) +void * +thread_modulers_timer_check(void *arg) { uint32 ms_to_expiry; uint64 us_to_wait; @@ -48,8 +49,8 @@ void * thread_modulers_timer_check(void * arg) while (timer_thread_run) { ms_to_expiry = (uint32)-1; os_mutex_lock(&g_timer_ctx_list_mutex); - timer_ctx_node_t* elem = (timer_ctx_node_t*) - bh_list_first_elem(&g_timer_ctx_list); + timer_ctx_node_t *elem = + (timer_ctx_node_t *)bh_list_first_elem(&g_timer_ctx_list); while (elem) { uint32 next = check_app_timers(elem->timer_ctx); if (next != (uint32)-1) { @@ -57,7 +58,7 @@ void * thread_modulers_timer_check(void * arg) ms_to_expiry = next; } - elem = (timer_ctx_node_t*) bh_list_elem_next(elem); + elem = (timer_ctx_node_t *)bh_list_elem_next(elem); } os_mutex_unlock(&g_timer_ctx_list_mutex); @@ -93,8 +94,8 @@ init_wasm_timer() would recursive lock the mutex */ os_recursive_mutex_init(&g_timer_ctx_list_mutex); - os_thread_create(&tm_tid, thread_modulers_timer_check, - NULL, BH_APPLET_PRESERVED_STACK_SIZE); + os_thread_create(&tm_tid, thread_modulers_timer_check, NULL, + BH_APPLET_PRESERVED_STACK_SIZE); } void @@ -106,15 +107,15 @@ exit_wasm_timer() timer_ctx_t create_wasm_timer_ctx(unsigned int module_id, int prealloc_num) { - timer_ctx_t ctx = create_timer_ctx(wasm_timer_callback, - wakeup_modules_timer_thread, - prealloc_num, module_id); + timer_ctx_t ctx = + create_timer_ctx(wasm_timer_callback, wakeup_modules_timer_thread, + prealloc_num, module_id); if (ctx == NULL) return NULL; - timer_ctx_node_t * node = (timer_ctx_node_t*) - wasm_runtime_malloc(sizeof(timer_ctx_node_t)); + timer_ctx_node_t *node = + (timer_ctx_node_t *)wasm_runtime_malloc(sizeof(timer_ctx_node_t)); if (node == NULL) { destroy_timer_ctx(ctx); return NULL; @@ -132,11 +133,10 @@ create_wasm_timer_ctx(unsigned int module_id, int prealloc_num) void destroy_module_timer_ctx(unsigned int module_id) { - timer_ctx_node_t* elem; + timer_ctx_node_t *elem; os_mutex_lock(&g_timer_ctx_list_mutex); - elem = (timer_ctx_node_t*) - bh_list_first_elem(&g_timer_ctx_list); + elem = (timer_ctx_node_t *)bh_list_first_elem(&g_timer_ctx_list); while (elem) { if (timer_ctx_get_owner(elem->timer_ctx) == module_id) { bh_list_remove(&g_timer_ctx_list, elem); @@ -145,7 +145,7 @@ destroy_module_timer_ctx(unsigned int module_id) break; } - elem = (timer_ctx_node_t*) bh_list_elem_next(elem); + elem = (timer_ctx_node_t *)bh_list_elem_next(elem); } os_mutex_unlock(&g_timer_ctx_list_mutex); } @@ -153,16 +153,15 @@ destroy_module_timer_ctx(unsigned int module_id) timer_ctx_t get_wasm_timer_ctx(wasm_module_inst_t module_inst) { - module_data * m = app_manager_get_module_data(Module_WASM_App, - module_inst); + module_data *m = app_manager_get_module_data(Module_WASM_App, module_inst); if (m == NULL) return NULL; return m->timer_ctx; } timer_id_t -wasm_create_timer(wasm_exec_env_t exec_env, - int interval, bool is_period, bool auto_start) +wasm_create_timer(wasm_exec_env_t exec_env, int interval, bool is_period, + bool auto_start) { wasm_module_inst_t module_inst = get_module_inst(exec_env); timer_ctx_t timer_ctx = get_wasm_timer_ctx(module_inst); @@ -189,8 +188,7 @@ wasm_timer_cancel(wasm_exec_env_t exec_env, timer_id_t timer_id) } void -wasm_timer_restart(wasm_exec_env_t exec_env, - timer_id_t timer_id, int interval) +wasm_timer_restart(wasm_exec_env_t exec_env, timer_id_t timer_id, int interval) { wasm_module_inst_t module_inst = get_module_inst(exec_env); timer_ctx_t timer_ctx = get_wasm_timer_ctx(module_inst); @@ -203,4 +201,3 @@ wasm_get_sys_tick_ms(wasm_exec_env_t exec_env) { return (uint32)bh_get_tick_ms(); } - diff --git a/core/app-framework/connection/app/connection.c b/core/app-framework/connection/app/connection.c index 775ee16f17..b5b2bfc543 100644 --- a/core/app-framework/connection/app/connection.c +++ b/core/app-framework/connection/app/connection.c @@ -24,10 +24,9 @@ typedef struct _connection { /* Raw connections list */ static connection_t *g_conns = NULL; -connection_t *api_open_connection(const char *name, - attr_container_t *args, - on_connection_event_f on_event, - void *user_data) +connection_t * +api_open_connection(const char *name, attr_container_t *args, + on_connection_event_f on_event, void *user_data) { connection_t *conn; char *args_buffer = (char *)args; @@ -51,14 +50,16 @@ connection_t *api_open_connection(const char *name, if (g_conns != NULL) { conn->next = g_conns; g_conns = conn; - } else { + } + else { g_conns = conn; } return conn; } -void api_close_connection(connection_t *c) +void +api_close_connection(connection_t *c) { connection_t *conn = g_conns, *prev = NULL; @@ -71,19 +72,22 @@ void api_close_connection(connection_t *c) g_conns = conn->next; free(conn); return; - } else { + } + else { prev = conn; conn = conn->next; } } } -int api_send_on_connection(connection_t *conn, const char *data, uint32 len) +int +api_send_on_connection(connection_t *conn, const char *data, uint32 len) { return wasm_send_on_connection(conn->handle, data, len); } -bool api_config_connection(connection_t *conn, attr_container_t *cfg) +bool +api_config_connection(connection_t *conn, attr_container_t *cfg) { char *cfg_buffer = (char *)cfg; uint32 cfg_len = attr_container_get_serialize_length(cfg); @@ -91,23 +95,19 @@ bool api_config_connection(connection_t *conn, attr_container_t *cfg) return wasm_config_connection(conn->handle, cfg_buffer, cfg_len); } -void on_connection_data(uint32 handle, char *buffer, uint32 len) +void +on_connection_data(uint32 handle, char *buffer, uint32 len) { connection_t *conn = g_conns; while (conn != NULL) { if (conn->handle == handle) { if (len == 0) { - conn->on_event(conn, - CONN_EVENT_TYPE_DISCONNECT, - NULL, - 0, + conn->on_event(conn, CONN_EVENT_TYPE_DISCONNECT, NULL, 0, conn->user_data); - } else { - conn->on_event(conn, - CONN_EVENT_TYPE_DATA, - buffer, - len, + } + else { + conn->on_event(conn, CONN_EVENT_TYPE_DATA, buffer, len, conn->user_data); } @@ -116,4 +116,3 @@ void on_connection_data(uint32 handle, char *buffer, uint32 len) conn = conn->next; } } - diff --git a/core/app-framework/connection/app/connection_api.h b/core/app-framework/connection/app/connection_api.h index 5697c8361b..22bd5a182c 100644 --- a/core/app-framework/connection/app/connection_api.h +++ b/core/app-framework/connection/app/connection_api.h @@ -28,5 +28,4 @@ wasm_config_connection(uint32 handle, const char *cfg_buf, uint32 cfg_buf_len); } #endif - #endif /* end of CONNECTION_API_H_ */ diff --git a/core/app-framework/connection/app/wa-inc/connection.h b/core/app-framework/connection/app/wa-inc/connection.h index 675befa59a..823eaec74b 100644 --- a/core/app-framework/connection/app/wa-inc/connection.h +++ b/core/app-framework/connection/app/wa-inc/connection.h @@ -33,10 +33,8 @@ typedef enum { * @param user_data user data */ typedef void (*on_connection_event_f)(connection_t *conn, - conn_event_type_t type, - const char *data, - uint32 len, - void *user_data); + conn_event_type_t type, const char *data, + uint32 len, void *user_data); /* ***************** @@ -54,17 +52,17 @@ typedef void (*on_connection_event_f)(connection_t *conn, * * @return the connection or NULL means fail */ -connection_t *api_open_connection(const char *name, - attr_container_t *args, - on_connection_event_f on_event, - void *user_data); +connection_t * +api_open_connection(const char *name, attr_container_t *args, + on_connection_event_f on_event, void *user_data); /* * @brief Close a connection. * * @param conn connection */ -void api_close_connection(connection_t *conn); +void +api_close_connection(connection_t *conn); /* * Send data to the connection in non-blocking manner which returns immediately @@ -75,7 +73,8 @@ void api_close_connection(connection_t *conn); * * @return actual length sent, or -1 if fail(maybe underlying buffer is full) */ -int api_send_on_connection(connection_t *conn, const char *data, uint32 len); +int +api_send_on_connection(connection_t *conn, const char *data, uint32 len); /* * @brief Configure connection. @@ -85,8 +84,8 @@ int api_send_on_connection(connection_t *conn, const char *data, uint32 len); * * @return true if success, false otherwise */ -bool api_config_connection(connection_t *conn, attr_container_t *cfg); - +bool +api_config_connection(connection_t *conn, attr_container_t *cfg); #ifdef __cplusplus } diff --git a/core/app-framework/connection/native/connection_lib.h b/core/app-framework/connection/native/connection_lib.h index 4a69f555ff..3e182cbb81 100644 --- a/core/app-framework/connection/native/connection_lib.h +++ b/core/app-framework/connection/native/connection_lib.h @@ -13,10 +13,9 @@ extern "C" { #endif -/* - ***************** - * This file defines connection library which should be implemented by different platforms - ***************** +/** + * This file defines connection library which should be implemented by + * different platforms */ /* @@ -73,5 +72,4 @@ extern connection_interface_t connection_impl; } #endif - #endif /* CONNECTION_LIB_H_ */ diff --git a/core/app-framework/connection/native/connection_native_api.h b/core/app-framework/connection/native/connection_native_api.h index 79e911d191..42a2508f12 100644 --- a/core/app-framework/connection/native/connection_native_api.h +++ b/core/app-framework/connection/native/connection_native_api.h @@ -13,29 +13,24 @@ extern "C" { #endif - /* * connection interfaces */ uint32 -wasm_open_connection(wasm_exec_env_t exec_env, - char *name, char *args_buf, uint32 len); +wasm_open_connection(wasm_exec_env_t exec_env, char *name, char *args_buf, + uint32 len); void -wasm_close_connection(wasm_exec_env_t exec_env, - uint32 handle); +wasm_close_connection(wasm_exec_env_t exec_env, uint32 handle); int -wasm_send_on_connection(wasm_exec_env_t exec_env, - uint32 handle, char *data, uint32 len); +wasm_send_on_connection(wasm_exec_env_t exec_env, uint32 handle, char *data, + uint32 len); bool -wasm_config_connection(wasm_exec_env_t exec_env, - uint32 handle, char *cfg_buf, uint32 len); - - +wasm_config_connection(wasm_exec_env_t exec_env, uint32 handle, char *cfg_buf, + uint32 len); #ifdef __cplusplus } #endif - #endif /* end of CONNECTION_API_H_ */ diff --git a/core/app-framework/connection/native/connection_wrapper.c b/core/app-framework/connection/native/connection_wrapper.c index 742a45b288..7c20b51d06 100644 --- a/core/app-framework/connection/native/connection_wrapper.c +++ b/core/app-framework/connection/native/connection_wrapper.c @@ -8,15 +8,15 @@ #include "native_interface.h" #include "connection_native_api.h" - /* Note: * - * This file is the consumer of connection lib which is implemented by different platforms + * This file is the consumer of connection lib which is implemented by different + * platforms */ uint32 -wasm_open_connection(wasm_exec_env_t exec_env, - char *name, char *args_buf, uint32 len) +wasm_open_connection(wasm_exec_env_t exec_env, char *name, char *args_buf, + uint32 len) { wasm_module_inst_t module_inst = get_module_inst(exec_env); attr_container_t *args; @@ -37,8 +37,8 @@ wasm_close_connection(wasm_exec_env_t exec_env, uint32 handle) } int -wasm_send_on_connection(wasm_exec_env_t exec_env, - uint32 handle, char *data, uint32 len) +wasm_send_on_connection(wasm_exec_env_t exec_env, uint32 handle, char *data, + uint32 len) { if (connection_impl._send != NULL) return connection_impl._send(handle, data, len); @@ -47,8 +47,8 @@ wasm_send_on_connection(wasm_exec_env_t exec_env, } bool -wasm_config_connection(wasm_exec_env_t exec_env, - uint32 handle, char *cfg_buf, uint32 len) +wasm_config_connection(wasm_exec_env_t exec_env, uint32 handle, char *cfg_buf, + uint32 len) { attr_container_t *cfg; diff --git a/core/app-framework/connection/native/linux/conn_tcp.c b/core/app-framework/connection/native/linux/conn_tcp.c index e676e53a07..054eb59fd2 100644 --- a/core/app-framework/connection/native/linux/conn_tcp.c +++ b/core/app-framework/connection/native/linux/conn_tcp.c @@ -11,7 +11,8 @@ #include #include -int tcp_open(char *address, uint16 port) +int +tcp_open(char *address, uint16 port) { int sock, ret; struct sockaddr_in servaddr; @@ -25,7 +26,7 @@ int tcp_open(char *address, uint16 port) if (sock == -1) return -1; - ret = connect(sock, (struct sockaddr*)&servaddr, sizeof(servaddr)); + ret = connect(sock, (struct sockaddr *)&servaddr, sizeof(servaddr)); if (ret == -1) { close(sock); return -1; @@ -40,12 +41,14 @@ int tcp_open(char *address, uint16 port) return sock; } -int tcp_send(int sock, const char *data, int size) +int +tcp_send(int sock, const char *data, int size) { return send(sock, data, size, 0); } -int tcp_recv(int sock, char *buffer, int buf_size) +int +tcp_recv(int sock, char *buffer, int buf_size) { return recv(sock, buffer, buf_size, 0); } diff --git a/core/app-framework/connection/native/linux/conn_tcp.h b/core/app-framework/connection/native/linux/conn_tcp.h index c1b560e321..c4d5cc86af 100644 --- a/core/app-framework/connection/native/linux/conn_tcp.h +++ b/core/app-framework/connection/native/linux/conn_tcp.h @@ -12,15 +12,17 @@ extern "C" { #endif -int tcp_open(char *address, uint16 port); +int +tcp_open(char *address, uint16 port); -int tcp_send(int sock, const char *data, int size); +int +tcp_send(int sock, const char *data, int size); -int tcp_recv(int sock, char *buffer, int buf_size); +int +tcp_recv(int sock, char *buffer, int buf_size); #ifdef __cplusplus } #endif - #endif diff --git a/core/app-framework/connection/native/linux/conn_uart.c b/core/app-framework/connection/native/linux/conn_uart.c index 1f5c4e767c..0bcdc93f7e 100644 --- a/core/app-framework/connection/native/linux/conn_uart.c +++ b/core/app-framework/connection/native/linux/conn_uart.c @@ -9,7 +9,8 @@ #include #include -static int parse_baudrate(int baud) +static int +parse_baudrate(int baud) { switch (baud) { case 9600: @@ -53,7 +54,8 @@ static int parse_baudrate(int baud) } } -int uart_open(char* device, int baudrate) +int +uart_open(char *device, int baudrate) { int uart_fd; struct termios uart_term; @@ -88,12 +90,14 @@ int uart_open(char* device, int baudrate) return uart_fd; } -int uart_send(int fd, const char *data, int size) +int +uart_send(int fd, const char *data, int size) { return write(fd, data, size); } -int uart_recv(int fd, char *buffer, int buf_size) +int +uart_recv(int fd, char *buffer, int buf_size) { return read(fd, buffer, buf_size); } diff --git a/core/app-framework/connection/native/linux/conn_uart.h b/core/app-framework/connection/native/linux/conn_uart.h index 9d40fb004d..443167026e 100644 --- a/core/app-framework/connection/native/linux/conn_uart.h +++ b/core/app-framework/connection/native/linux/conn_uart.h @@ -12,15 +12,17 @@ extern "C" { #endif -int uart_open(char* device, int baudrate); +int +uart_open(char *device, int baudrate); -int uart_send(int fd, const char *data, int size); +int +uart_send(int fd, const char *data, int size); -int uart_recv(int fd, char *buffer, int buf_size); +int +uart_recv(int fd, char *buffer, int buf_size); #ifdef __cplusplus } #endif - #endif diff --git a/core/app-framework/connection/native/linux/conn_udp.c b/core/app-framework/connection/native/linux/conn_udp.c index 9d370475ad..61652b14da 100644 --- a/core/app-framework/connection/native/linux/conn_udp.c +++ b/core/app-framework/connection/native/linux/conn_udp.c @@ -11,7 +11,8 @@ #include #include -int udp_open(uint16 port) +int +udp_open(uint16 port) { int sock, ret; struct sockaddr_in addr; @@ -25,7 +26,7 @@ int udp_open(uint16 port) addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(port); - ret = bind(sock, (struct sockaddr*)&addr, sizeof(addr)); + ret = bind(sock, (struct sockaddr *)&addr, sizeof(addr)); if (ret == -1) { close(sock); return -1; @@ -40,20 +41,18 @@ int udp_open(uint16 port) return sock; } -int udp_send(int sock, struct sockaddr *dest, const char *data, int size) +int +udp_send(int sock, struct sockaddr *dest, const char *data, int size) { return sendto(sock, data, size, MSG_CONFIRM, dest, sizeof(*dest)); } -int udp_recv(int sock, char *buffer, int buf_size) +int +udp_recv(int sock, char *buffer, int buf_size) { struct sockaddr_in remaddr; socklen_t addrlen = sizeof(remaddr); - return recvfrom(sock, - buffer, - buf_size, - 0, - (struct sockaddr *)&remaddr, + return recvfrom(sock, buffer, buf_size, 0, (struct sockaddr *)&remaddr, &addrlen); } diff --git a/core/app-framework/connection/native/linux/conn_udp.h b/core/app-framework/connection/native/linux/conn_udp.h index 37b9db79a7..377c26eb1b 100644 --- a/core/app-framework/connection/native/linux/conn_udp.h +++ b/core/app-framework/connection/native/linux/conn_udp.h @@ -12,15 +12,17 @@ extern "C" { #endif -int udp_open(uint16 port); +int +udp_open(uint16 port); -int udp_send(int sock, struct sockaddr *dest, const char *data, int size); +int +udp_send(int sock, struct sockaddr *dest, const char *data, int size); -int udp_recv(int sock, char *buffer, int buf_size); +int +udp_recv(int sock, char *buffer, int buf_size); #ifdef __cplusplus } #endif - #endif diff --git a/core/app-framework/connection/native/linux/connection_mgr.c b/core/app-framework/connection/native/linux/connection_mgr.c index df0fc8f073..0014462062 100644 --- a/core/app-framework/connection/native/linux/connection_mgr.c +++ b/core/app-framework/connection/native/linux/connection_mgr.c @@ -76,23 +76,30 @@ static struct epoll_event epoll_events[MAX_EVENTS]; /* Buffer to receive data */ static char io_buf[IO_BUF_SIZE]; -static uint32 _conn_open(wasm_module_inst_t module_inst, - const char *name, attr_container_t *args); -static void _conn_close(uint32 handle); -static int _conn_send(uint32 handle, const char *data, int len); -static bool _conn_config(uint32 handle, attr_container_t *cfg); - +static uint32 +_conn_open(wasm_module_inst_t module_inst, const char *name, + attr_container_t *args); +static void +_conn_close(uint32 handle); +static int +_conn_send(uint32 handle, const char *data, int len); +static bool +_conn_config(uint32 handle, attr_container_t *cfg); + +/* clang-format off */ /* * Platform implementation of connection library */ connection_interface_t connection_impl = { - ._open = _conn_open, - ._close = _conn_close, - ._send = _conn_send, - ._config = _conn_config + ._open = _conn_open, + ._close = _conn_close, + ._send = _conn_send, + ._config = _conn_config }; +/* clang-format on */ -static void add_connection(sys_connection_t *conn) +static void +add_connection(sys_connection_t *conn) { os_mutex_lock(&g_lock); @@ -104,20 +111,23 @@ static void add_connection(sys_connection_t *conn) if (g_connections) { conn->next = g_connections; g_connections = conn; - } else { + } + else { g_connections = conn; } os_mutex_unlock(&g_lock); } -#define FREE_CONNECTION(conn) do { \ - if (conn->arg) \ - wasm_runtime_free(conn->arg); \ - wasm_runtime_free(conn); \ -} while (0) +#define FREE_CONNECTION(conn) \ + do { \ + if (conn->arg) \ + wasm_runtime_free(conn->arg); \ + wasm_runtime_free(conn); \ + } while (0) -static int get_app_conns_num(uint32 module_id) +static int +get_app_conns_num(uint32 module_id) { sys_connection_t *conn; int num = 0; @@ -136,7 +146,8 @@ static int get_app_conns_num(uint32 module_id) return num; } -static sys_connection_t *find_connection(uint32 handle, bool remove_found) +static sys_connection_t * +find_connection(uint32 handle, bool remove_found) { sys_connection_t *conn, *prev = NULL; @@ -148,13 +159,15 @@ static sys_connection_t *find_connection(uint32 handle, bool remove_found) if (remove_found) { if (prev != NULL) { prev->next = conn->next; - } else { + } + else { g_connections = conn->next; } } os_mutex_unlock(&g_lock); return conn; - } else { + } + else { prev = conn; conn = conn->next; } @@ -165,7 +178,8 @@ static sys_connection_t *find_connection(uint32 handle, bool remove_found) return NULL; } -static void cleanup_connections(uint32 module_id) +static void +cleanup_connections(uint32 module_id) { sys_connection_t *conn, *prev = NULL; @@ -181,12 +195,14 @@ static void cleanup_connections(uint32 module_id) prev->next = conn->next; FREE_CONNECTION(conn); conn = prev->next; - } else { + } + else { g_connections = conn->next; FREE_CONNECTION(conn); conn = g_connections; } - } else { + } + else { prev = conn; conn = conn->next; } @@ -195,7 +211,8 @@ static void cleanup_connections(uint32 module_id) os_mutex_unlock(&g_lock); } -static conn_type_t get_conn_type(const char *name) +static conn_type_t +get_conn_type(const char *name) { if (strcmp(name, "TCP") == 0) return CONN_TYPE_TCP; @@ -208,14 +225,14 @@ static conn_type_t get_conn_type(const char *name) } /* --- connection lib function --- */ -static uint32 _conn_open(wasm_module_inst_t module_inst, - const char *name, attr_container_t *args) +static uint32 +_conn_open(wasm_module_inst_t module_inst, const char *name, + attr_container_t *args) { int fd; sys_connection_t *conn; struct epoll_event ev; - uint32 module_id = app_manager_get_module_id(Module_WASM_App, - module_inst); + uint32 module_id = app_manager_get_module_id(Module_WASM_App, module_inst); bh_assert(module_id != ID_NONE); if (get_app_conns_num(module_id) >= MAX_CONNECTION_PER_APP) @@ -237,8 +254,8 @@ static uint32 _conn_open(wasm_module_inst_t module_inst, uint16 port; /* Check and parse connection parameters */ - if (!attr_container_contain_key(args, "address") || - !attr_container_contain_key(args, "port")) + if (!attr_container_contain_key(args, "address") + || !attr_container_contain_key(args, "port")) goto fail; address = attr_container_get_as_string(args, "address"); @@ -247,8 +264,8 @@ static uint32 _conn_open(wasm_module_inst_t module_inst, /* Connect to TCP server */ if (!address || (fd = tcp_open(address, port)) == -1) goto fail; - - } else if (conn->type == CONN_TYPE_UDP) { + } + else if (conn->type == CONN_TYPE_UDP) { uint16 port; /* Check and parse connection parameters */ @@ -259,14 +276,14 @@ static uint32 _conn_open(wasm_module_inst_t module_inst, /* Bind port */ if ((fd = udp_open(port)) == -1) goto fail; - - } else if (conn->type == CONN_TYPE_UART) { + } + else if (conn->type == CONN_TYPE_UART) { char *device; int baud; /* Check and parse connection parameters */ - if (!attr_container_contain_key(args, "device") || - !attr_container_contain_key(args, "baudrate")) + if (!attr_container_contain_key(args, "device") + || !attr_container_contain_key(args, "baudrate")) goto fail; device = attr_container_get_as_string(args, "device"); baud = attr_container_get_as_int(args, "baudrate"); @@ -274,7 +291,8 @@ static uint32 _conn_open(wasm_module_inst_t module_inst, /* Open device */ if (!device || (fd = uart_open(device, baud)) == -1) goto fail; - } else { + } + else { goto fail; } @@ -299,7 +317,8 @@ static uint32 _conn_open(wasm_module_inst_t module_inst, } /* --- connection lib function --- */ -static void _conn_close(uint32 handle) +static void +_conn_close(uint32 handle) { sys_connection_t *conn = find_connection(handle, true); @@ -311,7 +330,8 @@ static void _conn_close(uint32 handle) } /* --- connection lib function --- */ -static int _conn_send(uint32 handle, const char *data, int len) +static int +_conn_send(uint32 handle, const char *data, int len) { sys_connection_t *conn = find_connection(handle, false); @@ -333,7 +353,8 @@ static int _conn_send(uint32 handle, const char *data, int len) } /* --- connection lib function --- */ -static bool _conn_config(uint32 handle, attr_container_t *cfg) +static bool +_conn_config(uint32 handle, attr_container_t *cfg) { sys_connection_t *conn = find_connection(handle, false); @@ -346,8 +367,8 @@ static bool _conn_config(uint32 handle, attr_container_t *cfg) struct sockaddr_in *addr; /* Parse remote address/port */ - if (!attr_container_contain_key(cfg, "address") || - !attr_container_contain_key(cfg, "port")) + if (!attr_container_contain_key(cfg, "address") + || !attr_container_contain_key(cfg, "port")) return false; if (!(address = attr_container_get_as_string(cfg, "address"))) return false; @@ -365,7 +386,8 @@ static bool _conn_config(uint32 handle, attr_container_t *cfg) /* Set remote address as connection arg */ conn->arg = addr; - } else { + } + else { addr = (struct sockaddr_in *)conn->arg; addr->sin_addr.s_addr = inet_addr(address); addr->sin_port = htons(port); @@ -385,16 +407,16 @@ typedef struct connection_event { uint32 len; } connection_event_t; -static void connection_event_cleaner(connection_event_t *conn_event) +static void +connection_event_cleaner(connection_event_t *conn_event) { if (conn_event->data != NULL) wasm_runtime_free(conn_event->data); wasm_runtime_free(conn_event); } -static void post_msg_to_module(sys_connection_t *conn, - char *data, - uint32 len) +static void +post_msg_to_module(sys_connection_t *conn, char *data, uint32 len) { module_data *module = module_data_list_lookup_id(conn->module_id); char *data_copy = NULL; @@ -404,7 +426,8 @@ static void post_msg_to_module(sys_connection_t *conn, if (module == NULL) return; - conn_data_event = (connection_event_t *)wasm_runtime_malloc(sizeof(*conn_data_event)); + conn_data_event = + (connection_event_t *)wasm_runtime_malloc(sizeof(*conn_data_event)); if (conn_data_event == NULL) return; @@ -422,10 +445,8 @@ static void post_msg_to_module(sys_connection_t *conn, conn_data_event->data = data_copy; conn_data_event->len = len; - msg = bh_new_msg(CONNECTION_EVENT_WASM, - conn_data_event, - sizeof(*conn_data_event), - connection_event_cleaner); + msg = bh_new_msg(CONNECTION_EVENT_WASM, conn_data_event, + sizeof(*conn_data_event), connection_event_cleaner); if (!msg) { connection_event_cleaner(conn_data_event); return; @@ -434,7 +455,8 @@ static void post_msg_to_module(sys_connection_t *conn, bh_post_msg2(module->queue, msg); } -static void* polling_thread_routine (void *arg) +static void * +polling_thread_routine(void *arg) { while (polling_thread_run) { int i, n; @@ -445,8 +467,8 @@ static void* polling_thread_routine (void *arg) continue; for (i = 0; i < n; i++) { - sys_connection_t *conn - = (sys_connection_t *)epoll_events[i].data.ptr; + sys_connection_t *conn = + (sys_connection_t *)epoll_events[i].data.ptr; if (conn->type == CONN_TYPE_TCP) { int count = tcp_recv(conn->fd, io_buf, IO_BUF_SIZE); @@ -454,15 +476,18 @@ static void* polling_thread_routine (void *arg) /* Connection is closed by peer */ post_msg_to_module(conn, NULL, 0); _conn_close(conn->handle); - } else { + } + else { /* Data is received */ post_msg_to_module(conn, io_buf, count); } - } else if (conn->type == CONN_TYPE_UDP) { + } + else if (conn->type == CONN_TYPE_UDP) { int count = udp_recv(conn->fd, io_buf, IO_BUF_SIZE); if (count > 0) post_msg_to_module(conn, io_buf, count); - } else if (conn->type == CONN_TYPE_UART) { + } + else if (conn->type == CONN_TYPE_UART) { int count = uart_recv(conn->fd, io_buf, IO_BUF_SIZE); if (count > 0) post_msg_to_module(conn, io_buf, count); @@ -473,25 +498,26 @@ static void* polling_thread_routine (void *arg) return NULL; } -void app_mgr_connection_event_callback(module_data *m_data, bh_message_t msg) +void +app_mgr_connection_event_callback(module_data *m_data, bh_message_t msg) { uint32 argv[3]; wasm_function_inst_t func_on_conn_data; bh_assert(CONNECTION_EVENT_WASM == bh_message_type(msg)); - wasm_data *wasm_app_data = (wasm_data*)m_data->internal_data; + wasm_data *wasm_app_data = (wasm_data *)m_data->internal_data; wasm_module_inst_t inst = wasm_app_data->wasm_module_inst; - connection_event_t *conn_event - = (connection_event_t *)bh_message_payload(msg); + connection_event_t *conn_event = + (connection_event_t *)bh_message_payload(msg); int32 data_offset; if (conn_event == NULL) return; - func_on_conn_data = wasm_runtime_lookup_function(inst, "_on_connection_data", - "(i32i32i32)"); + func_on_conn_data = wasm_runtime_lookup_function( + inst, "_on_connection_data", "(i32i32i32)"); if (!func_on_conn_data) - func_on_conn_data = wasm_runtime_lookup_function(inst, "on_connection_data", - "(i32i32i32)"); + func_on_conn_data = wasm_runtime_lookup_function( + inst, "on_connection_data", "(i32i32i32)"); if (!func_on_conn_data) { printf("Cannot find function on_connection_data\n"); return; @@ -506,34 +532,31 @@ void app_mgr_connection_event_callback(module_data *m_data, bh_message_t msg) 3, argv)) { const char *exception = wasm_runtime_get_exception(inst); bh_assert(exception); - printf(":Got exception running wasm code: %s\n", - exception); + printf(":Got exception running wasm code: %s\n", exception); wasm_runtime_clear_exception(inst); return; } - } else { - data_offset = wasm_runtime_module_dup_data(inst, - conn_event->data, + } + else { + data_offset = wasm_runtime_module_dup_data(inst, conn_event->data, conn_event->len); if (data_offset == 0) { const char *exception = wasm_runtime_get_exception(inst); if (exception) { - printf("Got exception running wasm code: %s\n", - exception); + printf("Got exception running wasm code: %s\n", exception); wasm_runtime_clear_exception(inst); } return; } argv[0] = conn_event->handle; - argv[1] = (uint32) data_offset; + argv[1] = (uint32)data_offset; argv[2] = conn_event->len; if (!wasm_runtime_call_wasm(wasm_app_data->exec_env, func_on_conn_data, 3, argv)) { const char *exception = wasm_runtime_get_exception(inst); bh_assert(exception); - printf(":Got exception running wasm code: %s\n", - exception); + printf(":Got exception running wasm code: %s\n", exception); wasm_runtime_clear_exception(inst); wasm_runtime_module_free(inst, data_offset); return; @@ -542,7 +565,8 @@ void app_mgr_connection_event_callback(module_data *m_data, bh_message_t msg) } } -bool init_connection_framework() +bool +init_connection_framework() { korp_tid tid; @@ -560,14 +584,13 @@ bool init_connection_framework() } if (!wasm_register_msg_callback(CONNECTION_EVENT_WASM, - app_mgr_connection_event_callback)) { + app_mgr_connection_event_callback)) { goto fail; } - if (os_thread_create(&tid, - polling_thread_routine, - NULL, - BH_APPLET_PRESERVED_STACK_SIZE) != 0) { + if (os_thread_create(&tid, polling_thread_routine, NULL, + BH_APPLET_PRESERVED_STACK_SIZE) + != 0) { goto fail; } @@ -579,7 +602,8 @@ bool init_connection_framework() return false; } -void exit_connection_framework() +void +exit_connection_framework() { polling_thread_run = false; } diff --git a/core/app-framework/connection/native/zephyr/connection_lib_impl.c b/core/app-framework/connection/native/zephyr/connection_lib_impl.c index 9c30edcaf6..a812a71a25 100644 --- a/core/app-framework/connection/native/zephyr/connection_lib_impl.c +++ b/core/app-framework/connection/native/zephyr/connection_lib_impl.c @@ -12,12 +12,14 @@ #include "connection_lib.h" +/* clang-format off */ /* * Platform implementation of connection library */ connection_interface_t connection_impl = { - ._open = NULL, - ._close = NULL, - ._send = NULL, - ._config = NULL + ._open = NULL, + ._close = NULL, + ._send = NULL, + ._config = NULL }; +/* clang-format on */ diff --git a/core/app-framework/sensor/app/sensor.c b/core/app-framework/sensor/app/sensor.c index 2af23fafbb..d898a1d3ac 100644 --- a/core/app-framework/sensor/app/sensor.c +++ b/core/app-framework/sensor/app/sensor.c @@ -8,7 +8,7 @@ #include "sensor_api.h" typedef struct _sensor { - struct _sensor * next; + struct _sensor *next; char *name; uint32 handle; void (*sensor_callback)(sensor_t, attr_container_t *, void *); @@ -17,16 +17,16 @@ typedef struct _sensor { static sensor_t g_sensors = NULL; -sensor_t sensor_open(const char* name, int index, - sensor_event_handler_f sensor_event_handler, - void *user_data) +sensor_t +sensor_open(const char *name, int index, + sensor_event_handler_f sensor_event_handler, void *user_data) { uint32 id = wasm_sensor_open(name, index); if (id == -1) return NULL; - //create local node for holding the user callback - sensor_t sensor = (sensor_t) malloc(sizeof(struct _sensor)); + // create local node for holding the user callback + sensor_t sensor = (sensor_t)malloc(sizeof(struct _sensor)); if (sensor == NULL) return NULL; @@ -43,7 +43,8 @@ sensor_t sensor_open(const char* name, int index, if (g_sensors == NULL) { g_sensors = sensor; - } else { + } + else { sensor->next = g_sensors; g_sensors = sensor; } @@ -51,7 +52,8 @@ sensor_t sensor_open(const char* name, int index, return sensor; } -bool sensor_config_with_attr_container(sensor_t sensor, attr_container_t *cfg) +bool +sensor_config_with_attr_container(sensor_t sensor, attr_container_t *cfg) { char *buffer = (char *)cfg; int len = attr_container_get_serialize_length(cfg); @@ -59,13 +61,15 @@ bool sensor_config_with_attr_container(sensor_t sensor, attr_container_t *cfg) return wasm_sensor_config_with_attr_container(sensor->handle, buffer, len); } -bool sensor_config(sensor_t sensor, int interval, int bit_cfg, int delay) +bool +sensor_config(sensor_t sensor, int interval, int bit_cfg, int delay) { bool ret = wasm_sensor_config(sensor->handle, interval, bit_cfg, delay); return ret; } -bool sensor_close(sensor_t sensor) +bool +sensor_close(sensor_t sensor) { wasm_sensor_close(sensor->handle); @@ -76,13 +80,15 @@ bool sensor_close(sensor_t sensor) if (s == sensor) { if (prev == NULL) { g_sensors = s->next; - } else { + } + else { prev->next = s->next; } free(s->name); free(s); return true; - } else { + } + else { prev = s; s = s->next; } @@ -97,9 +103,10 @@ bool sensor_close(sensor_t sensor) * */ -void on_sensor_event(uint32 sensor_id, char * buffer, int len) +void +on_sensor_event(uint32 sensor_id, char *buffer, int len) { - attr_container_t * sensor_data = (attr_container_t *) buffer; + attr_container_t *sensor_data = (attr_container_t *)buffer; // lookup the sensor and call the handlers sensor_t s = g_sensors; diff --git a/core/app-framework/sensor/app/sensor_api.h b/core/app-framework/sensor/app/sensor_api.h index 9f67677026..094f110852 100644 --- a/core/app-framework/sensor/app/sensor_api.h +++ b/core/app-framework/sensor/app/sensor_api.h @@ -13,7 +13,7 @@ extern "C" { #endif uint32 -wasm_sensor_open(const char* name, int instance); +wasm_sensor_open(const char *name, int instance); bool wasm_sensor_config(uint32 sensor, int interval, int bit_cfg, int delay); @@ -29,4 +29,3 @@ wasm_sensor_close(uint32 sensor); #endif #endif /* end of _SENSOR_API_H_ */ - diff --git a/core/app-framework/sensor/app/wa-inc/sensor.h b/core/app-framework/sensor/app/wa-inc/sensor.h index 8abc1addff..109f895d38 100644 --- a/core/app-framework/sensor/app/wa-inc/sensor.h +++ b/core/app-framework/sensor/app/wa-inc/sensor.h @@ -30,8 +30,8 @@ typedef struct _sensor *sensor_t; * @see sensor_open */ typedef void (*sensor_event_handler_f)(sensor_t sensor, - attr_container_t *sensor_event, - void *user_data); + attr_container_t *sensor_event, + void *user_data); /* ***************** @@ -49,10 +49,9 @@ typedef void (*sensor_event_handler_f)(sensor_t sensor, * * @return the sensor opened if success, NULL otherwise */ -sensor_t sensor_open(const char* name, - int index, - sensor_event_handler_f handler, - void *user_data); +sensor_t +sensor_open(const char *name, int index, sensor_event_handler_f handler, + void *user_data); /** * @brief Configure sensor with interval/bit_cfg/delay values. @@ -64,7 +63,8 @@ sensor_t sensor_open(const char* name, * * @return true if success, false otherwise */ -bool sensor_config(sensor_t sensor, int interval, int bit_cfg, int delay); +bool +sensor_config(sensor_t sensor, int interval, int bit_cfg, int delay); /** * @brief Configure sensor with attr_container_t object. @@ -74,7 +74,8 @@ bool sensor_config(sensor_t sensor, int interval, int bit_cfg, int delay); * * @return true if success, false otherwise */ -bool sensor_config_with_attr_container(sensor_t sensor, attr_container_t *cfg); +bool +sensor_config_with_attr_container(sensor_t sensor, attr_container_t *cfg); /** * @brief Close sensor. @@ -83,7 +84,8 @@ bool sensor_config_with_attr_container(sensor_t sensor, attr_container_t *cfg); * * @return true if success, false otherwise */ -bool sensor_close(sensor_t sensor); +bool +sensor_close(sensor_t sensor); #ifdef __cplusplus } diff --git a/core/app-framework/sensor/native/runtime_sensor.c b/core/app-framework/sensor/native/runtime_sensor.c index 89f7ea8bbd..2e2fed929d 100644 --- a/core/app-framework/sensor/native/runtime_sensor.c +++ b/core/app-framework/sensor/native/runtime_sensor.c @@ -8,12 +8,12 @@ #include "module_wasm_app.h" #include "bh_platform.h" -static sys_sensor_t * g_sys_sensors = NULL; +static sys_sensor_t *g_sys_sensors = NULL; static int g_sensor_id_max = 0; static sensor_client_t * -find_sensor_client(sys_sensor_t * sensor, - unsigned int client_id, bool remove_if_found); +find_sensor_client(sys_sensor_t *sensor, unsigned int client_id, + bool remove_if_found); void (*rechedule_sensor_callback)() = NULL; @@ -38,30 +38,32 @@ sensor_event_cleaner(sensor_event_data_t *sensor_event) static void wasm_sensor_callback(void *client, uint32 sensor_id, void *user_data) { - attr_container_t *sensor_data = (attr_container_t *) user_data; + attr_container_t *sensor_data = (attr_container_t *)user_data; attr_container_t *sensor_data_clone; int sensor_data_len; sensor_event_data_t *sensor_event; bh_message_t msg; - sensor_client_t *c = (sensor_client_t *) client; + sensor_client_t *c = (sensor_client_t *)client; module_data *module = module_data_list_lookup_id(c->client_id); if (module == NULL) return; if (sensor_data == NULL) - return; + return; sensor_data_len = attr_container_get_serialize_length(sensor_data); - sensor_data_clone = (attr_container_t *)wasm_runtime_malloc(sensor_data_len); + sensor_data_clone = + (attr_container_t *)wasm_runtime_malloc(sensor_data_len); if (sensor_data_clone == NULL) return; /* multiple sensor clients may use/free the sensor data, so make a copy */ - bh_memcpy_s(sensor_data_clone, sensor_data_len, - sensor_data, sensor_data_len); + bh_memcpy_s(sensor_data_clone, sensor_data_len, sensor_data, + sensor_data_len); - sensor_event = (sensor_event_data_t *)wasm_runtime_malloc(sizeof(*sensor_event)); + sensor_event = + (sensor_event_data_t *)wasm_runtime_malloc(sizeof(*sensor_event)); if (sensor_event == NULL) { wasm_runtime_free(sensor_data_clone); return; @@ -72,9 +74,7 @@ wasm_sensor_callback(void *client, uint32 sensor_id, void *user_data) sensor_event->data = sensor_data_clone; sensor_event->data_fmt = FMT_ATTR_CONTAINER; - msg = bh_new_msg(SENSOR_EVENT_WASM, - sensor_event, - sizeof(*sensor_event), + msg = bh_new_msg(SENSOR_EVENT_WASM, sensor_event, sizeof(*sensor_event), sensor_event_cleaner); if (!msg) { sensor_event_cleaner(sensor_event); @@ -85,19 +85,18 @@ wasm_sensor_callback(void *client, uint32 sensor_id, void *user_data) } bool -wasm_sensor_config(wasm_exec_env_t exec_env, - uint32 sensor, int interval, +wasm_sensor_config(wasm_exec_env_t exec_env, uint32 sensor, int interval, int bit_cfg, int delay) { wasm_module_inst_t module_inst = get_module_inst(exec_env); - attr_container_t * attr_cont; - sensor_client_t * c; + attr_container_t *attr_cont; + sensor_client_t *c; sensor_obj_t s = find_sys_sensor_id(sensor); if (s == NULL) return false; - unsigned int mod_id = app_manager_get_module_id(Module_WASM_App, - module_inst); + unsigned int mod_id = + app_manager_get_module_id(Module_WASM_App, module_inst); bh_assert(mod_id != ID_NONE); os_mutex_lock(&s->lock); @@ -131,8 +130,7 @@ wasm_sensor_config(wasm_exec_env_t exec_env, } uint32 -wasm_sensor_open(wasm_exec_env_t exec_env, - char *name, int instance) +wasm_sensor_open(wasm_exec_env_t exec_env, char *name, int instance) { wasm_module_inst_t module_inst = get_module_inst(exec_env); @@ -142,8 +140,8 @@ wasm_sensor_open(wasm_exec_env_t exec_env, if (s == NULL) return -1; - unsigned int mod_id = app_manager_get_module_id(Module_WASM_App, - module_inst); + unsigned int mod_id = + app_manager_get_module_id(Module_WASM_App, module_inst); bh_assert(mod_id != ID_NONE); os_mutex_lock(&s->lock); @@ -155,8 +153,8 @@ wasm_sensor_open(wasm_exec_env_t exec_env, return -1; } - sensor_client_t * client = (sensor_client_t*) wasm_runtime_malloc( - sizeof(sensor_client_t)); + sensor_client_t *client = + (sensor_client_t *)wasm_runtime_malloc(sizeof(sensor_client_t)); if (client == NULL) { os_mutex_unlock(&s->lock); return -1; @@ -182,8 +180,8 @@ wasm_sensor_open(wasm_exec_env_t exec_env, } bool -wasm_sensor_config_with_attr_container(wasm_exec_env_t exec_env, - uint32 sensor, char *buffer, int len) +wasm_sensor_config_with_attr_container(wasm_exec_env_t exec_env, uint32 sensor, + char *buffer, int len) { if (buffer != NULL) { attr_container_t *cfg = (attr_container_t *)buffer; @@ -204,8 +202,8 @@ bool wasm_sensor_close(wasm_exec_env_t exec_env, uint32 sensor) { wasm_module_inst_t module_inst = get_module_inst(exec_env); - unsigned int mod_id = app_manager_get_module_id(Module_WASM_App, - module_inst); + unsigned int mod_id = + app_manager_get_module_id(Module_WASM_App, module_inst); unsigned int client_id = mod_id; sensor_obj_t s = find_sys_sensor_id(sensor); sensor_client_t *c; @@ -232,19 +230,22 @@ wasm_sensor_close(wasm_exec_env_t exec_env, uint32 sensor) * sensor framework API - don't expose to the applications * */ -void set_sensor_reshceduler(void (*callback)()) +void +set_sensor_reshceduler(void (*callback)()) { rechedule_sensor_callback = callback; } // used for other threads to wakeup the sensor read thread -void reschedule_sensor_read() +void +reschedule_sensor_read() { if (rechedule_sensor_callback) rechedule_sensor_callback(); } -void refresh_read_interval(sensor_obj_t sensor) +void +refresh_read_interval(sensor_obj_t sensor) { sensor_client_t *c; uint32 interval = sensor->default_interval; @@ -266,10 +267,10 @@ void refresh_read_interval(sensor_obj_t sensor) } sensor_obj_t -add_sys_sensor(char * name, char * description, int instance, - uint32 default_interval, void * read_func, void * config_func) +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 *) wasm_runtime_malloc(sizeof(sys_sensor_t)); + sys_sensor_t *s = (sys_sensor_t *)wasm_runtime_malloc(sizeof(sys_sensor_t)); if (s == NULL) return NULL; @@ -302,7 +303,8 @@ add_sys_sensor(char * name, char * description, int instance, if (g_sys_sensors == NULL) { g_sys_sensors = s; - } else { + } + else { s->next = g_sys_sensors; g_sys_sensors = s; } @@ -312,9 +314,10 @@ add_sys_sensor(char * name, char * description, int instance, return s; } -sensor_obj_t find_sys_sensor(const char* name, int instance) +sensor_obj_t +find_sys_sensor(const char *name, int instance) { - sys_sensor_t * s = g_sys_sensors; + sys_sensor_t *s = g_sys_sensors; while (s) { if (strcmp(s->name, name) == 0 && s->sensor_instance == instance) return s; @@ -324,9 +327,10 @@ sensor_obj_t find_sys_sensor(const char* name, int instance) return NULL; } -sensor_obj_t find_sys_sensor_id(uint32 sensor_id) +sensor_obj_t +find_sys_sensor_id(uint32 sensor_id) { - sys_sensor_t * s = g_sys_sensors; + sys_sensor_t *s = g_sys_sensors; while (s) { if (s->sensor_id == sensor_id) return s; @@ -336,8 +340,9 @@ sensor_obj_t find_sys_sensor_id(uint32 sensor_id) return NULL; } -sensor_client_t *find_sensor_client(sys_sensor_t * sensor, - unsigned int client_id, bool remove_if_found) +sensor_client_t * +find_sensor_client(sys_sensor_t *sensor, unsigned int client_id, + bool remove_if_found) { sensor_client_t *prev = NULL, *c = sensor->clients; @@ -351,7 +356,8 @@ sensor_client_t *find_sensor_client(sys_sensor_t * sensor, sensor->clients = next; } return c; - } else { + } + else { c = c->next; } } @@ -360,12 +366,13 @@ sensor_client_t *find_sensor_client(sys_sensor_t * sensor, } // return the milliseconds to next check -int check_sensor_timers() +int +check_sensor_timers() { int ms_to_next_check = -1; uint32 now = (uint32)bh_get_tick_ms(); - sys_sensor_t * s = g_sys_sensors; + sys_sensor_t *s = g_sys_sensors; while (s) { uint32 last_read = s->last_read; uint32 elpased_ms = bh_get_elpased_ms(&last_read); @@ -376,9 +383,9 @@ int check_sensor_timers() } if (elpased_ms >= s->read_interval) { - attr_container_t * data = s->read(s); + attr_container_t *data = s->read(s); if (data) { - sensor_client_t * client = s->clients; + sensor_client_t *client = s->clients; while (client) { client->client_callback(client, s->sensor_id, data); client = client->next; @@ -390,11 +397,11 @@ int check_sensor_timers() if (ms_to_next_check == -1 || (ms_to_next_check < s->read_interval)) ms_to_next_check = s->read_interval; - } else { + } + else { int remaining = s->read_interval - elpased_ms; if (ms_to_next_check == -1 || (ms_to_next_check < remaining)) ms_to_next_check = remaining; - } s = s->next; @@ -403,9 +410,10 @@ int check_sensor_timers() return ms_to_next_check; } -void sensor_cleanup_callback(uint32 module_id) +void +sensor_cleanup_callback(uint32 module_id) { - sys_sensor_t * s = g_sys_sensors; + sys_sensor_t *s = g_sys_sensors; while (s) { sensor_client_t *c; diff --git a/core/app-framework/sensor/native/runtime_sensor.h b/core/app-framework/sensor/native/runtime_sensor.h index 8154d6d916..22f625df55 100644 --- a/core/app-framework/sensor/native/runtime_sensor.h +++ b/core/app-framework/sensor/native/runtime_sensor.h @@ -12,49 +12,58 @@ #include "sensor_native_api.h" struct _sys_sensor; -typedef struct _sys_sensor* sensor_obj_t; +typedef struct _sys_sensor *sensor_obj_t; typedef struct _sensor_client { - struct _sensor_client * next; + struct _sensor_client *next; unsigned int client_id; // the app id int interval; int bit_cfg; int delay; - void (*client_callback)(void * client, uint32, attr_container_t *); + void (*client_callback)(void *client, uint32, attr_container_t *); } sensor_client_t; typedef struct _sys_sensor { - struct _sys_sensor * next; - char * name; + struct _sys_sensor *next; + char *name; int sensor_instance; - char * description; + char *description; uint32 sensor_id; - sensor_client_t * clients; + sensor_client_t *clients; /* app, sensor mgr and app mgr may access the clients at the same time, - * so need a lock to protect the clients */ + so need a lock to protect the clients */ korp_mutex lock; uint32 last_read; uint32 read_interval; uint32 default_interval; - attr_container_t * (*read)(void *); /* TODO: may support other type return value, such as 'cbor' */ + /* TODO: may support other type return value, such as 'cbor' */ + attr_container_t *(*read)(void *); bool (*config)(void *, void *); } sys_sensor_t; -sensor_obj_t add_sys_sensor(char * name, char * description, int instance, - uint32 default_interval, void * read_func, void * config_func); -sensor_obj_t find_sys_sensor(const char* name, int instance); -sensor_obj_t find_sys_sensor_id(uint32 sensor_id); -void refresh_read_interval(sensor_obj_t sensor); -void sensor_cleanup_callback(uint32 module_id); -int check_sensor_timers(); -void reschedule_sensor_read(); - -void init_sensor_framework(); -void start_sensor_framework(); -void exit_sensor_framework(); - +sensor_obj_t +add_sys_sensor(char *name, char *description, int instance, + uint32 default_interval, void *read_func, void *config_func); +sensor_obj_t +find_sys_sensor(const char *name, int instance); +sensor_obj_t +find_sys_sensor_id(uint32 sensor_id); +void +refresh_read_interval(sensor_obj_t sensor); +void +sensor_cleanup_callback(uint32 module_id); +int +check_sensor_timers(); +void +reschedule_sensor_read(); +void +init_sensor_framework(); +void +start_sensor_framework(); +void +exit_sensor_framework(); #endif /* LIB_EXTENSION_RUNTIME_SENSOR_H_ */ diff --git a/core/app-framework/sensor/native/sensor_mgr_ref.c b/core/app-framework/sensor/native/sensor_mgr_ref.c index 80646bee66..cbbc6df535 100644 --- a/core/app-framework/sensor/native/sensor_mgr_ref.c +++ b/core/app-framework/sensor/native/sensor_mgr_ref.c @@ -19,60 +19,62 @@ static korp_cond cond; static korp_mutex mutex; static bool sensor_check_thread_run = true; -void app_mgr_sensor_event_callback(module_data *m_data, bh_message_t msg) +void +app_mgr_sensor_event_callback(module_data *m_data, bh_message_t msg) { uint32 argv[3]; wasm_function_inst_t func_onSensorEvent; bh_assert(SENSOR_EVENT_WASM == bh_message_type(msg)); - wasm_data *wasm_app_data = (wasm_data*)m_data->internal_data; + wasm_data *wasm_app_data = (wasm_data *)m_data->internal_data; wasm_module_inst_t inst = wasm_app_data->wasm_module_inst; - sensor_event_data_t *payload = (sensor_event_data_t*) - bh_message_payload(msg); + sensor_event_data_t *payload = + (sensor_event_data_t *)bh_message_payload(msg); if (payload == NULL) return; - func_onSensorEvent = wasm_runtime_lookup_function(inst, "_on_sensor_event", - "(i32i32i32)"); + func_onSensorEvent = + wasm_runtime_lookup_function(inst, "_on_sensor_event", "(i32i32i32)"); if (!func_onSensorEvent) - func_onSensorEvent = wasm_runtime_lookup_function(inst, "on_sensor_event", - "(i32i32i32)"); + func_onSensorEvent = wasm_runtime_lookup_function( + inst, "on_sensor_event", "(i32i32i32)"); if (!func_onSensorEvent) { printf("Cannot find function on_sensor_event\n"); - } else { + } + else { int32 sensor_data_offset; uint32 sensor_data_len; if (payload->data_fmt == FMT_ATTR_CONTAINER) { - sensor_data_len = attr_container_get_serialize_length(payload->data); - } else { + sensor_data_len = + attr_container_get_serialize_length(payload->data); + } + else { printf("Unsupported sensor data format: %d\n", payload->data_fmt); return; } - sensor_data_offset = wasm_runtime_module_dup_data(inst, payload->data, - sensor_data_len); + sensor_data_offset = + wasm_runtime_module_dup_data(inst, payload->data, sensor_data_len); if (sensor_data_offset == 0) { const char *exception = wasm_runtime_get_exception(inst); if (exception) { - printf("Got exception running wasm code: %s\n", - exception); + printf("Got exception running wasm code: %s\n", exception); wasm_runtime_clear_exception(inst); } return; } argv[0] = payload->sensor_id; - argv[1] = (uint32) sensor_data_offset; + argv[1] = (uint32)sensor_data_offset; argv[2] = sensor_data_len; if (!wasm_runtime_call_wasm(wasm_app_data->exec_env, func_onSensorEvent, 3, argv)) { const char *exception = wasm_runtime_get_exception(inst); bh_assert(exception); - printf(":Got exception running wasm code: %s\n", - exception); + printf(":Got exception running wasm code: %s\n", exception); wasm_runtime_clear_exception(inst); wasm_runtime_module_free(inst, sensor_data_offset); return; @@ -82,8 +84,8 @@ void app_mgr_sensor_event_callback(module_data *m_data, bh_message_t msg) } } - -static void thread_sensor_check(void * arg) +static void +thread_sensor_check(void *arg) { while (sensor_check_thread_run) { int ms_to_expiry = check_sensor_timers(); @@ -95,46 +97,44 @@ static void thread_sensor_check(void * arg) } } -static void cb_wakeup_thread() +static void +cb_wakeup_thread() { os_cond_signal(&cond); } -void set_sensor_reshceduler(void (*callback)()); +void +set_sensor_reshceduler(void (*callback)()); -void init_sensor_framework() +void +init_sensor_framework() { // init the mutext and conditions os_cond_init(&cond); os_mutex_init(&mutex); - set_sensor_reshceduler(cb_wakeup_thread); wasm_register_msg_callback(SENSOR_EVENT_WASM, app_mgr_sensor_event_callback); wasm_register_cleanup_callback(sensor_cleanup_callback); - - } -void start_sensor_framework() +void +start_sensor_framework() { korp_tid tid; - os_thread_create(&tid, - (void *)thread_sensor_check, - NULL, - BH_APPLET_PRESERVED_STACK_SIZE); + os_thread_create(&tid, (void *)thread_sensor_check, NULL, + BH_APPLET_PRESERVED_STACK_SIZE); } - -void exit_sensor_framework() +void +exit_sensor_framework() { sensor_check_thread_run = false; reschedule_sensor_read(); - //todo: wait the sensor thread termination + // todo: wait the sensor thread termination } - diff --git a/core/app-framework/sensor/native/sensor_native_api.h b/core/app-framework/sensor/native/sensor_native_api.h index ed323174eb..8fbaa3e86a 100644 --- a/core/app-framework/sensor/native/sensor_native_api.h +++ b/core/app-framework/sensor/native/sensor_native_api.h @@ -14,16 +14,14 @@ extern "C" { #endif bool -wasm_sensor_config(wasm_exec_env_t exec_env, - uint32 sensor, int interval, +wasm_sensor_config(wasm_exec_env_t exec_env, uint32 sensor, int interval, int bit_cfg, int delay); uint32 -wasm_sensor_open(wasm_exec_env_t exec_env, - char *name, int instance); +wasm_sensor_open(wasm_exec_env_t exec_env, char *name, int instance); bool -wasm_sensor_config_with_attr_container(wasm_exec_env_t exec_env, - uint32 sensor, char *buffer, int len); +wasm_sensor_config_with_attr_container(wasm_exec_env_t exec_env, uint32 sensor, + char *buffer, int len); bool wasm_sensor_close(wasm_exec_env_t exec_env, uint32 sensor); @@ -33,4 +31,3 @@ wasm_sensor_close(wasm_exec_env_t exec_env, uint32 sensor); #endif #endif /* end of _SENSOR_NATIVE_API_H_ */ - diff --git a/core/app-framework/wgl/app/gui_api.h b/core/app-framework/wgl/app/gui_api.h index a258474cfe..7547cdcdc2 100644 --- a/core/app-framework/wgl/app/gui_api.h +++ b/core/app-framework/wgl/app/gui_api.h @@ -28,10 +28,8 @@ wasm_cb_native_call(int32 func_id, uint32 *argv, uint32 argc); void wasm_list_native_call(int32 func_id, uint32 *argv, uint32 argc); - #ifdef __cplusplus } #endif - #endif /* end of _GUI_API_H_ */ diff --git a/core/app-framework/wgl/app/src/wgl_btn.c b/core/app-framework/wgl/app/src/wgl_btn.c index 89dbbca670..680124e5f1 100644 --- a/core/app-framework/wgl/app/src/wgl_btn.c +++ b/core/app-framework/wgl/app/src/wgl_btn.c @@ -7,12 +7,13 @@ #include "bh_platform.h" #include "gui_api.h" -#define ARGC sizeof(argv)/sizeof(uint32) +#define ARGC sizeof(argv) / sizeof(uint32) #define CALL_BTN_NATIVE_FUNC(id) wasm_btn_native_call(id, argv, ARGC) -lv_obj_t * lv_btn_create(lv_obj_t * par, const lv_obj_t * copy) +lv_obj_t * +lv_btn_create(lv_obj_t *par, const lv_obj_t *copy) { - uint32 argv[2] = {0}; + uint32 argv[2] = { 0 }; argv[0] = (uint32)par; argv[1] = (uint32)copy; @@ -20,100 +21,113 @@ lv_obj_t * lv_btn_create(lv_obj_t * par, const lv_obj_t * copy) return (lv_obj_t *)argv[0]; } -void lv_btn_set_toggle(lv_obj_t * btn, bool tgl) +void +lv_btn_set_toggle(lv_obj_t *btn, bool tgl) { - uint32 argv[2] = {0}; + uint32 argv[2] = { 0 }; argv[0] = (uint32)btn; argv[1] = tgl; CALL_BTN_NATIVE_FUNC(BTN_FUNC_ID_SET_TOGGLE); } -void lv_btn_set_state(lv_obj_t * btn, lv_btn_state_t state) +void +lv_btn_set_state(lv_obj_t *btn, lv_btn_state_t state) { - uint32 argv[2] = {0}; + uint32 argv[2] = { 0 }; argv[0] = (uint32)btn; argv[1] = state; CALL_BTN_NATIVE_FUNC(BTN_FUNC_ID_SET_STATE); } -void lv_btn_toggle(lv_obj_t * btn) +void +lv_btn_toggle(lv_obj_t *btn) { - uint32 argv[1] = {0}; + uint32 argv[1] = { 0 }; argv[0] = (uint32)btn; CALL_BTN_NATIVE_FUNC(BTN_FUNC_ID_TOGGLE); } -void lv_btn_set_ink_in_time(lv_obj_t * btn, uint16_t time) +void +lv_btn_set_ink_in_time(lv_obj_t *btn, uint16_t time) { - uint32 argv[2] = {0}; + uint32 argv[2] = { 0 }; argv[0] = (uint32)btn; argv[1] = time; CALL_BTN_NATIVE_FUNC(BTN_FUNC_ID_SET_INK_IN_TIME); } -void lv_btn_set_ink_wait_time(lv_obj_t * btn, uint16_t time) +void +lv_btn_set_ink_wait_time(lv_obj_t *btn, uint16_t time) { - uint32 argv[2] = {0}; + uint32 argv[2] = { 0 }; argv[0] = (uint32)btn; argv[1] = time; CALL_BTN_NATIVE_FUNC(BTN_FUNC_ID_SET_INK_WAIT_TIME); } -void lv_btn_set_ink_out_time(lv_obj_t * btn, uint16_t time) +void +lv_btn_set_ink_out_time(lv_obj_t *btn, uint16_t time) { - uint32 argv[2] = {0}; + uint32 argv[2] = { 0 }; argv[0] = (uint32)btn; argv[1] = time; CALL_BTN_NATIVE_FUNC(BTN_FUNC_ID_SET_INK_OUT_TIME); } -//void wgl_btn_set_style(wgl_obj_t btn, wgl_btn_style_t type, const wgl_style_t * style) +// void wgl_btn_set_style(wgl_obj_t btn, wgl_btn_style_t type, +// const wgl_style_t *style) //{ // //TODO: pack style // //wasm_btn_set_style(btn, type, style); //} // -lv_btn_state_t lv_btn_get_state(const lv_obj_t * btn) +lv_btn_state_t +lv_btn_get_state(const lv_obj_t *btn) { - uint32 argv[1] = {0}; + uint32 argv[1] = { 0 }; argv[0] = (uint32)btn; CALL_BTN_NATIVE_FUNC(BTN_FUNC_ID_GET_STATE); return (lv_btn_state_t)argv[0]; } -bool lv_btn_get_toggle(const lv_obj_t * btn) +bool +lv_btn_get_toggle(const lv_obj_t *btn) { - uint32 argv[1] = {0}; + uint32 argv[1] = { 0 }; argv[0] = (uint32)btn; CALL_BTN_NATIVE_FUNC(BTN_FUNC_ID_GET_TOGGLE); return (bool)argv[0]; } -uint16_t lv_btn_get_ink_in_time(const lv_obj_t * btn) +uint16_t +lv_btn_get_ink_in_time(const lv_obj_t *btn) { - uint32 argv[1] = {0}; + uint32 argv[1] = { 0 }; argv[0] = (uint32)btn; CALL_BTN_NATIVE_FUNC(BTN_FUNC_ID_GET_INK_IN_TIME); return (uint16_t)argv[0]; } -uint16_t lv_btn_get_ink_wait_time(const lv_obj_t * btn) +uint16_t +lv_btn_get_ink_wait_time(const lv_obj_t *btn) { - uint32 argv[1] = {0}; + uint32 argv[1] = { 0 }; argv[0] = (uint32)btn; CALL_BTN_NATIVE_FUNC(BTN_FUNC_ID_GET_INK_WAIT_TIME); return (uint16_t)argv[0]; } -uint16_t lv_btn_get_ink_out_time(const lv_obj_t * btn) +uint16_t +lv_btn_get_ink_out_time(const lv_obj_t *btn) { - uint32 argv[1] = {0}; + uint32 argv[1] = { 0 }; argv[0] = (uint32)btn; CALL_BTN_NATIVE_FUNC(BTN_FUNC_ID_GET_INK_OUT_TIME); return (uint16_t)argv[0]; } // -//const wgl_style_t * wgl_btn_get_style(const wgl_obj_t btn, wgl_btn_style_t type) +// const wgl_style_t * wgl_btn_get_style(const wgl_obj_t btn, +// wgl_btn_style_t type) //{ // //TODO: pack style // //wasm_btn_get_style(btn, type); diff --git a/core/app-framework/wgl/app/src/wgl_cb.c b/core/app-framework/wgl/app/src/wgl_cb.c index 83a541ab3d..bd172d3b0c 100644 --- a/core/app-framework/wgl/app/src/wgl_cb.c +++ b/core/app-framework/wgl/app/src/wgl_cb.c @@ -3,18 +3,18 @@ * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ - #include "wa-inc/lvgl/lvgl.h" #include "gui_api.h" #include -#define ARGC sizeof(argv)/sizeof(uint32) +#define ARGC sizeof(argv) / sizeof(uint32) #define CALL_CB_NATIVE_FUNC(id) wasm_cb_native_call(id, argv, ARGC) -lv_obj_t * lv_cb_create(lv_obj_t * par, const lv_obj_t * copy) +lv_obj_t * +lv_cb_create(lv_obj_t *par, const lv_obj_t *copy) { - uint32 argv[2] = {0}; + uint32 argv[2] = { 0 }; argv[0] = (uint32)par; argv[1] = (uint32)copy; @@ -22,41 +22,46 @@ lv_obj_t * lv_cb_create(lv_obj_t * par, const lv_obj_t * copy) return (lv_obj_t *)argv[0]; } -void lv_cb_set_text(lv_obj_t * cb, const char * txt) +void +lv_cb_set_text(lv_obj_t *cb, const char *txt) { - uint32 argv[3] = {0}; + uint32 argv[3] = { 0 }; argv[0] = (uint32)cb; argv[1] = (uint32)txt; argv[2] = strlen(txt) + 1; CALL_CB_NATIVE_FUNC(CB_FUNC_ID_SET_TEXT); } -void lv_cb_set_static_text(lv_obj_t * cb, const char * txt) +void +lv_cb_set_static_text(lv_obj_t *cb, const char *txt) { - uint32 argv[3] = {0}; + uint32 argv[3] = { 0 }; argv[0] = (uint32)cb; argv[1] = (uint32)txt; argv[2] = strlen(txt) + 1; CALL_CB_NATIVE_FUNC(CB_FUNC_ID_SET_STATIC_TEXT); } -//void wgl_cb_set_style(wgl_obj_t cb, wgl_cb_style_t type, const wgl_style_t * style) +// void wgl_cb_set_style(wgl_obj_t cb, wgl_cb_style_t type, +// const wgl_style_t *style) //{ // //TODO: //} // -static unsigned int wgl_cb_get_text_length(lv_obj_t * cb) +static unsigned int +wgl_cb_get_text_length(lv_obj_t *cb) { - uint32 argv[1] = {0}; + uint32 argv[1] = { 0 }; argv[0] = (uint32)cb; CALL_CB_NATIVE_FUNC(CB_FUNC_ID_GET_TEXT_LENGTH); return argv[0]; } -static char *wgl_cb_get_text(lv_obj_t * cb, char *buffer, int buffer_len) +static char * +wgl_cb_get_text(lv_obj_t *cb, char *buffer, int buffer_len) { - uint32 argv[3] = {0}; + uint32 argv[3] = { 0 }; argv[0] = (uint32)cb; argv[1] = (uint32)buffer; argv[2] = buffer_len; @@ -65,18 +70,17 @@ static char *wgl_cb_get_text(lv_obj_t * cb, char *buffer, int buffer_len) } // TODO: need to use a global data buffer for the returned text -const char * lv_cb_get_text(const lv_obj_t * cb) +const char * +lv_cb_get_text(const lv_obj_t *cb) { return NULL; } - -//const wgl_style_t * wgl_cb_get_style(const wgl_obj_t cb, wgl_cb_style_t type) +// const wgl_style_t * wgl_cb_get_style(const wgl_obj_t cb, +// wgl_cb_style_t type) //{ // //TODO // return NULL; //} // - - diff --git a/core/app-framework/wgl/app/src/wgl_label.c b/core/app-framework/wgl/app/src/wgl_label.c index cecd9910f4..81c6dcf5f5 100644 --- a/core/app-framework/wgl/app/src/wgl_label.c +++ b/core/app-framework/wgl/app/src/wgl_label.c @@ -3,19 +3,17 @@ * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ - - #include "wa-inc/lvgl/lvgl.h" #include "gui_api.h" #include - -#define ARGC sizeof(argv)/sizeof(uint32) +#define ARGC sizeof(argv) / sizeof(uint32) #define CALL_LABEL_NATIVE_FUNC(id) wasm_label_native_call(id, argv, ARGC) -lv_obj_t * lv_label_create(lv_obj_t * par, const lv_obj_t * copy) +lv_obj_t * +lv_label_create(lv_obj_t *par, const lv_obj_t *copy) { - uint32 argv[2] = {0}; + uint32 argv[2] = { 0 }; argv[0] = (uint32)par; argv[1] = (uint32)copy; @@ -23,109 +21,112 @@ lv_obj_t * lv_label_create(lv_obj_t * par, const lv_obj_t * copy) return (lv_obj_t *)argv[0]; } -void lv_label_set_text(lv_obj_t * label, const char * text) +void +lv_label_set_text(lv_obj_t *label, const char *text) { - uint32 argv[3] = {0}; + uint32 argv[3] = { 0 }; argv[0] = (uint32)label; argv[1] = (uint32)text; argv[2] = strlen(text) + 1; CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_SET_TEXT); } - -void lv_label_set_array_text(lv_obj_t * label, const char * array, uint16_t size) +void +lv_label_set_array_text(lv_obj_t *label, const char *array, uint16_t size) { - uint32 argv[3] = {0}; + uint32 argv[3] = { 0 }; argv[0] = (uint32)label; argv[1] = (uint32)array; argv[2] = size; CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_SET_ARRAY_TEXT); } - -void lv_label_set_static_text(lv_obj_t * label, const char * text) +void +lv_label_set_static_text(lv_obj_t *label, const char *text) { - uint32 argv[3] = {0}; + uint32 argv[3] = { 0 }; argv[0] = (uint32)label; argv[1] = (uint32)text; argv[2] = strlen(text) + 1; CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_SET_STATIC_TEXT); } - -void lv_label_set_long_mode(lv_obj_t * label, lv_label_long_mode_t long_mode) +void +lv_label_set_long_mode(lv_obj_t *label, lv_label_long_mode_t long_mode) { - uint32 argv[2] = {0}; + uint32 argv[2] = { 0 }; argv[0] = (uint32)label; argv[1] = long_mode; CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_SET_LONG_MODE); } - -void lv_label_set_align(lv_obj_t * label, lv_label_align_t align) +void +lv_label_set_align(lv_obj_t *label, lv_label_align_t align) { - uint32 argv[2] = {0}; + uint32 argv[2] = { 0 }; argv[0] = (uint32)label; argv[1] = align; CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_SET_ALIGN); } - -void lv_label_set_recolor(lv_obj_t * label, bool en) +void +lv_label_set_recolor(lv_obj_t *label, bool en) { - uint32 argv[2] = {0}; + uint32 argv[2] = { 0 }; argv[0] = (uint32)label; argv[1] = en; CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_SET_RECOLOR); } - -void lv_label_set_body_draw(lv_obj_t * label, bool en) +void +lv_label_set_body_draw(lv_obj_t *label, bool en) { - uint32 argv[2] = {0}; + uint32 argv[2] = { 0 }; argv[0] = (uint32)label; argv[1] = en; CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_SET_BODY_DRAW); } - -void lv_label_set_anim_speed(lv_obj_t * label, uint16_t anim_speed) +void +lv_label_set_anim_speed(lv_obj_t *label, uint16_t anim_speed) { - uint32 argv[2] = {0}; + uint32 argv[2] = { 0 }; argv[0] = (uint32)label; argv[1] = anim_speed; CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_SET_ANIM_SPEED); } - -void lv_label_set_text_sel_start(lv_obj_t * label, uint16_t index) +void +lv_label_set_text_sel_start(lv_obj_t *label, uint16_t index) { - uint32 argv[2] = {0}; + uint32 argv[2] = { 0 }; argv[0] = (uint32)label; argv[1] = index; CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_SET_TEXT_SEL_START); } - -void lv_label_set_text_sel_end(lv_obj_t * label, uint16_t index) +void +lv_label_set_text_sel_end(lv_obj_t *label, uint16_t index) { - uint32 argv[2] = {0}; + uint32 argv[2] = { 0 }; argv[0] = (uint32)label; argv[1] = index; CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_SET_TEXT_SEL_END); } -unsigned int wgl_label_get_text_length(lv_obj_t * label) +unsigned int +wgl_label_get_text_length(lv_obj_t *label) { - uint32 argv[1] = {0}; + uint32 argv[1] = { 0 }; argv[0] = (uint32)label; CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_GET_TEXT_LENGTH); return argv[0]; } -char * wgl_label_get_text(lv_obj_t * label, char *buffer, int buffer_len) +char * +wgl_label_get_text(lv_obj_t *label, char *buffer, int buffer_len) { - uint32 argv[3] = {0}; + uint32 argv[3] = { 0 }; argv[0] = (uint32)label; argv[1] = (uint32)buffer; argv[2] = buffer_len; @@ -133,63 +134,63 @@ char * wgl_label_get_text(lv_obj_t * label, char *buffer, int buffer_len) return (char *)argv[0]; } -// TODO: -char * lv_label_get_text(const lv_obj_t * label) +// TODO: +char * +lv_label_get_text(const lv_obj_t *label) { return NULL; - } - -lv_label_long_mode_t lv_label_get_long_mode(const lv_obj_t * label) +lv_label_long_mode_t +lv_label_get_long_mode(const lv_obj_t *label) { - uint32 argv[1] = {0}; + uint32 argv[1] = { 0 }; argv[0] = (uint32)label; CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_GET_LONG_MODE); return (lv_label_long_mode_t)argv[0]; } - -lv_label_align_t lv_label_get_align(const lv_obj_t * label) +lv_label_align_t +lv_label_get_align(const lv_obj_t *label) { - uint32 argv[1] = {0}; + uint32 argv[1] = { 0 }; argv[0] = (uint32)label; CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_GET_ALIGN); return (lv_label_align_t)argv[0]; } - -bool lv_label_get_recolor(const lv_obj_t * label) +bool +lv_label_get_recolor(const lv_obj_t *label) { - uint32 argv[1] = {0}; + uint32 argv[1] = { 0 }; argv[0] = (uint32)label; CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_GET_RECOLOR); return (bool)argv[0]; } - -bool lv_label_get_body_draw(const lv_obj_t * label) +bool +lv_label_get_body_draw(const lv_obj_t *label) { - uint32 argv[1] = {0}; + uint32 argv[1] = { 0 }; argv[0] = (uint32)label; CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_GET_BODY_DRAW); return (bool)argv[0]; } - -uint16_t lv_label_get_anim_speed(const lv_obj_t * label) +uint16_t +lv_label_get_anim_speed(const lv_obj_t *label) { - uint32 argv[1] = {0}; + uint32 argv[1] = { 0 }; argv[0] = (uint32)label; CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_GET_ANIM_SPEED); return (uint16_t)argv[0]; } - -void lv_label_get_letter_pos(const lv_obj_t * label, uint16_t index, lv_point_t * pos) +void +lv_label_get_letter_pos(const lv_obj_t *label, uint16_t index, lv_point_t *pos) { - uint32 argv[4] = {0}; + uint32 argv[4] = { 0 }; argv[0] = (uint32)label; argv[1] = index; CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_GET_LETTER_POS); @@ -197,10 +198,10 @@ void lv_label_get_letter_pos(const lv_obj_t * label, uint16_t index, lv_point_t pos->y = argv[3]; } - -uint16_t lv_label_get_letter_on(const lv_obj_t * label, lv_point_t * pos) +uint16_t +lv_label_get_letter_on(const lv_obj_t *label, lv_point_t *pos) { - uint32 argv[3] = {0}; + uint32 argv[3] = { 0 }; argv[0] = (uint32)label; argv[1] = pos->x; argv[2] = pos->y; @@ -208,10 +209,10 @@ uint16_t lv_label_get_letter_on(const lv_obj_t * label, lv_point_t * pos) return (uint16_t)argv[0]; } - -bool lv_label_is_char_under_pos(const lv_obj_t * label, lv_point_t * pos) +bool +lv_label_is_char_under_pos(const lv_obj_t *label, lv_point_t *pos) { - uint32 argv[3] = {0}; + uint32 argv[3] = { 0 }; argv[0] = (uint32)label; argv[1] = pos->x; argv[2] = pos->y; @@ -219,28 +220,28 @@ bool lv_label_is_char_under_pos(const lv_obj_t * label, lv_point_t * pos) return (bool)argv[0]; } - -uint16_t lv_label_get_text_sel_start(const lv_obj_t * label) +uint16_t +lv_label_get_text_sel_start(const lv_obj_t *label) { - uint32 argv[1] = {0}; + uint32 argv[1] = { 0 }; argv[0] = (uint32)label; CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_GET_TEXT_SEL_START); return (uint16_t)argv[0]; } - -uint16_t lv_label_get_text_sel_end(const lv_obj_t * label) +uint16_t +lv_label_get_text_sel_end(const lv_obj_t *label) { - uint32 argv[1] = {0}; + uint32 argv[1] = { 0 }; argv[0] = (uint32)label; CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_GET_TEXT_SEL_END); return (uint16_t)argv[0]; } - -void lv_label_ins_text(lv_obj_t * label, uint32_t pos, const char * txt) +void +lv_label_ins_text(lv_obj_t *label, uint32_t pos, const char *txt) { - uint32 argv[4] = {0}; + uint32 argv[4] = { 0 }; argv[0] = (uint32)label; argv[1] = pos; argv[2] = (uint32)txt; @@ -248,14 +249,12 @@ void lv_label_ins_text(lv_obj_t * label, uint32_t pos, const char * txt) CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_INS_TEXT); } - -void lv_label_cut_text(lv_obj_t * label, uint32_t pos, uint32_t cnt) +void +lv_label_cut_text(lv_obj_t *label, uint32_t pos, uint32_t cnt) { - uint32 argv[3] = {0}; + uint32 argv[3] = { 0 }; argv[0] = (uint32)label; argv[1] = pos; argv[2] = cnt; CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_CUT_TEXT); } - - diff --git a/core/app-framework/wgl/app/src/wgl_list.c b/core/app-framework/wgl/app/src/wgl_list.c index 1ac9b32ed8..1ca95a6e8a 100644 --- a/core/app-framework/wgl/app/src/wgl_list.c +++ b/core/app-framework/wgl/app/src/wgl_list.c @@ -3,19 +3,18 @@ * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ - #include "wa-inc/lvgl/lvgl.h" #include "gui_api.h" #include -#define ARGC sizeof(argv)/sizeof(uint32) +#define ARGC sizeof(argv) / sizeof(uint32) #define CALL_LIST_NATIVE_FUNC(id) wasm_list_native_call(id, argv, ARGC) - -lv_obj_t * lv_list_create(lv_obj_t * par, const lv_obj_t * copy) +lv_obj_t * +lv_list_create(lv_obj_t *par, const lv_obj_t *copy) { - uint32 argv[2] = {0}; + uint32 argv[2] = { 0 }; argv[0] = (uint32)par; argv[1] = (uint32)copy; @@ -25,15 +24,16 @@ lv_obj_t * lv_list_create(lv_obj_t * par, const lv_obj_t * copy) } // // -//void wgl_list_clean(wgl_obj_t obj) +// void wgl_list_clean(wgl_obj_t obj) //{ // wasm_list_clean(obj); //} // -lv_obj_t * lv_list_add_btn(lv_obj_t * list, const void * img_src, const char * txt) +lv_obj_t * +lv_list_add_btn(lv_obj_t *list, const void *img_src, const char *txt) { - uint32 argv[3] = {0}; + uint32 argv[3] = { 0 }; (void)img_src; /* doesn't support img src currently */ @@ -45,13 +45,13 @@ lv_obj_t * lv_list_add_btn(lv_obj_t * list, const void * img_src, const char * t } // // -//bool wgl_list_remove(const wgl_obj_t list, uint16_t index) +// bool wgl_list_remove(const wgl_obj_t list, uint16_t index) //{ // return wasm_list_remove(list, index); //} // // -//void wgl_list_set_single_mode(wgl_obj_t list, bool mode) +// void wgl_list_set_single_mode(wgl_obj_t list, bool mode) //{ // wasm_list_set_single_mode(list, mode); //} @@ -59,68 +59,69 @@ lv_obj_t * lv_list_add_btn(lv_obj_t * list, const void * img_src, const char * t //#if LV_USE_GROUP // // -//void wgl_list_set_btn_selected(wgl_obj_t list, wgl_obj_t btn) +// void wgl_list_set_btn_selected(wgl_obj_t list, wgl_obj_t btn) //{ // wasm_list_set_btn_selected(list, btn); //} //#endif // // -//void wgl_list_set_style(wgl_obj_t list, wgl_list_style_t type, const wgl_style_t * style) +// void wgl_list_set_style(wgl_obj_t list, wgl_list_style_t type, +// const wgl_style_t * style) //{ // //TODO //} // // -//bool wgl_list_get_single_mode(wgl_obj_t list) +// bool wgl_list_get_single_mode(wgl_obj_t list) //{ // return wasm_list_get_single_mode(list); //} // // -//const char * wgl_list_get_btn_text(const wgl_obj_t btn) +// const char * wgl_list_get_btn_text(const wgl_obj_t btn) //{ // return wasm_list_get_btn_text(btn); //} // -//wgl_obj_t wgl_list_get_btn_label(const wgl_obj_t btn) +// wgl_obj_t wgl_list_get_btn_label(const wgl_obj_t btn) //{ // return wasm_list_get_btn_label(btn); //} // // -//wgl_obj_t wgl_list_get_btn_img(const wgl_obj_t btn) +// wgl_obj_t wgl_list_get_btn_img(const wgl_obj_t btn) //{ // return wasm_list_get_btn_img(btn); //} // // -//wgl_obj_t wgl_list_get_prev_btn(const wgl_obj_t list, wgl_obj_t prev_btn) +// wgl_obj_t wgl_list_get_prev_btn(const wgl_obj_t list, wgl_obj_t prev_btn) //{ // return wasm_list_get_prev_btn(list, prev_btn); //} // // -//wgl_obj_t wgl_list_get_next_btn(const wgl_obj_t list, wgl_obj_t prev_btn) +// wgl_obj_t wgl_list_get_next_btn(const wgl_obj_t list, wgl_obj_t prev_btn) //{ // return wasm_list_get_next_btn(list, prev_btn); //} // // -//int32_t wgl_list_get_btn_index(const wgl_obj_t list, const wgl_obj_t btn) +// int32_t wgl_list_get_btn_index(const wgl_obj_t list, const wgl_obj_t btn) //{ // return wasm_list_get_btn_index(list, btn); //} // // -//uint16_t wgl_list_get_size(const wgl_obj_t list) +// uint16_t wgl_list_get_size(const wgl_obj_t list) //{ // return wasm_list_get_size(list); //} // //#if LV_USE_GROUP // -//wgl_obj_t wgl_list_get_btn_selected(const wgl_obj_t list) +// wgl_obj_t wgl_list_get_btn_selected(const wgl_obj_t list) //{ // return wasm_list_get_btn_selected(list); //} @@ -128,28 +129,27 @@ lv_obj_t * lv_list_add_btn(lv_obj_t * list, const void * img_src, const char * t // // // -//const wgl_style_t * wgl_list_get_style(const wgl_obj_t list, wgl_list_style_t type) +// const wgl_style_t * wgl_list_get_style(const wgl_obj_t list, +// wgl_list_style_t type) //{ // //TODO // return NULL; //} // // -//void wgl_list_up(const wgl_obj_t list) +// void wgl_list_up(const wgl_obj_t list) //{ // wasm_list_up(list); //} // -//void wgl_list_down(const wgl_obj_t list) +// void wgl_list_down(const wgl_obj_t list) //{ // wasm_list_down(list); //} // // -//void wgl_list_focus(const wgl_obj_t btn, wgl_anim_enable_t anim) +// void wgl_list_focus(const wgl_obj_t btn, wgl_anim_enable_t anim) //{ // wasm_list_focus(btn, anim); //} // - - diff --git a/core/app-framework/wgl/app/src/wgl_obj.c b/core/app-framework/wgl/app/src/wgl_obj.c index ee72beb624..e1fe152c55 100644 --- a/core/app-framework/wgl/app/src/wgl_obj.c +++ b/core/app-framework/wgl/app/src/wgl_obj.c @@ -3,19 +3,18 @@ * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ - #include "wa-inc/lvgl/lvgl.h" #include "gui_api.h" #include #include -#define ARGC sizeof(argv)/sizeof(uint32) +#define ARGC sizeof(argv) / sizeof(uint32) #define CALL_OBJ_NATIVE_FUNC(id) wasm_obj_native_call(id, argv, ARGC) typedef struct _obj_evt_cb { struct _obj_evt_cb *next; - lv_obj_t * obj; + lv_obj_t *obj; lv_event_cb_t event_cb; } obj_evt_cb_t; @@ -24,31 +23,36 @@ static obj_evt_cb_t *g_obj_evt_cb_list = NULL; /* For lvgl compatible */ char g_widget_text[100]; -lv_res_t lv_obj_del(lv_obj_t * obj) +lv_res_t +lv_obj_del(lv_obj_t *obj) { - uint32 argv[1] = {0}; + uint32 argv[1] = { 0 }; argv[0] = (uint32)obj; CALL_OBJ_NATIVE_FUNC(OBJ_FUNC_ID_DEL); return (lv_res_t)argv[0]; } -void lv_obj_del_async(struct _lv_obj_t *obj) +void +lv_obj_del_async(struct _lv_obj_t *obj) { - uint32 argv[1] = {0}; + uint32 argv[1] = { 0 }; argv[0] = (uint32)obj; CALL_OBJ_NATIVE_FUNC(OBJ_FUNC_ID_DEL_ASYNC); } -void lv_obj_clean(lv_obj_t * obj) +void +lv_obj_clean(lv_obj_t *obj) { - uint32 argv[1] = {0}; + uint32 argv[1] = { 0 }; argv[0] = (uint32)obj; CALL_OBJ_NATIVE_FUNC(OBJ_FUNC_ID_CLEAN); } -void lv_obj_align(lv_obj_t * obj, const lv_obj_t * base, lv_align_t align, lv_coord_t x_mod, lv_coord_t y_mod) +void +lv_obj_align(lv_obj_t *obj, const lv_obj_t *base, lv_align_t align, + lv_coord_t x_mod, lv_coord_t y_mod) { - uint32 argv[5] = {0}; + uint32 argv[5] = { 0 }; argv[0] = (uint32)obj; argv[1] = (uint32)base; argv[2] = align; @@ -57,7 +61,8 @@ void lv_obj_align(lv_obj_t * obj, const lv_obj_t * base, lv_align_t align, lv_co CALL_OBJ_NATIVE_FUNC(OBJ_FUNC_ID_ALIGN); } -lv_event_cb_t lv_obj_get_event_cb(const lv_obj_t * obj) +lv_event_cb_t +lv_obj_get_event_cb(const lv_obj_t *obj) { obj_evt_cb_t *obj_evt_cb = g_obj_evt_cb_list; while (obj_evt_cb != NULL) { @@ -70,10 +75,11 @@ lv_event_cb_t lv_obj_get_event_cb(const lv_obj_t * obj) return NULL; } -void lv_obj_set_event_cb(lv_obj_t * obj, lv_event_cb_t event_cb) +void +lv_obj_set_event_cb(lv_obj_t *obj, lv_event_cb_t event_cb) { obj_evt_cb_t *obj_evt_cb; - uint32 argv[1] = {0}; + uint32 argv[1] = { 0 }; obj_evt_cb = g_obj_evt_cb_list; while (obj_evt_cb) { @@ -94,7 +100,8 @@ void lv_obj_set_event_cb(lv_obj_t * obj, lv_event_cb_t event_cb) if (g_obj_evt_cb_list != NULL) { obj_evt_cb->next = g_obj_evt_cb_list; g_obj_evt_cb_list = obj_evt_cb; - } else { + } + else { g_obj_evt_cb_list = obj_evt_cb; } @@ -102,7 +109,8 @@ void lv_obj_set_event_cb(lv_obj_t * obj, lv_event_cb_t event_cb) CALL_OBJ_NATIVE_FUNC(OBJ_FUNC_ID_SET_EVT_CB); } -void on_widget_event(lv_obj_t * obj, lv_event_t event) +void +on_widget_event(lv_obj_t *obj, lv_event_t event) { obj_evt_cb_t *obj_evt_cb = g_obj_evt_cb_list; diff --git a/core/app-framework/wgl/app/wa-inc/lvgl/lv_obj.h b/core/app-framework/wgl/app/wa-inc/lvgl/lv_obj.h index c79838e22d..5497b0b62d 100644 --- a/core/app-framework/wgl/app/wa-inc/lvgl/lv_obj.h +++ b/core/app-framework/wgl/app/wa-inc/lvgl/lv_obj.h @@ -55,12 +55,12 @@ extern "C" { struct _lv_obj_t; - /** Design modes */ enum { - LV_DESIGN_DRAW_MAIN, /**< Draw the main portion of the object */ - LV_DESIGN_DRAW_POST, /**< Draw extras on the object */ - LV_DESIGN_COVER_CHK, /**< Check if the object fully covers the 'mask_p' area */ + LV_DESIGN_DRAW_MAIN, /* Draw the main portion of the object */ + LV_DESIGN_DRAW_POST, /* Draw extras on the object */ + LV_DESIGN_COVER_CHK, /* Check if the object fully covers the 'mask_p' + area */ }; typedef uint8_t lv_design_mode_t; @@ -68,71 +68,92 @@ typedef uint8_t lv_design_mode_t; * The design callback is used to draw the object on the screen. * It accepts the object, a mask area, and the mode in which to draw the object. */ -typedef bool (*lv_design_cb_t)(struct _lv_obj_t * obj, const lv_area_t * mask_p, lv_design_mode_t mode); +typedef bool (*lv_design_cb_t)(struct _lv_obj_t *obj, const lv_area_t *mask_p, + lv_design_mode_t mode); enum { - LV_EVENT_PRESSED, /**< The object has been pressed*/ - LV_EVENT_PRESSING, /**< The object is being pressed (called continuously while pressing)*/ - LV_EVENT_PRESS_LOST, /**< User is still pressing but slid cursor/finger off of the object */ - LV_EVENT_SHORT_CLICKED, /**< User pressed object for a short period of time, then released it. Not called if dragged. */ - LV_EVENT_LONG_PRESSED, /**< Object has been pressed for at least `LV_INDEV_LONG_PRESS_TIME`. Not called if dragged.*/ - LV_EVENT_LONG_PRESSED_REPEAT, /**< Called after `LV_INDEV_LONG_PRESS_TIME` in every - `LV_INDEV_LONG_PRESS_REP_TIME` ms. Not called if dragged.*/ - LV_EVENT_CLICKED, /**< Called on release if not dragged (regardless to long press)*/ - LV_EVENT_RELEASED, /**< Called in every cases when the object has been released*/ - LV_EVENT_DRAG_BEGIN, + LV_EVENT_PRESSED, /* The object has been pressed */ + LV_EVENT_PRESSING, /* The object is being pressed (called continuously + while pressing) */ + LV_EVENT_PRESS_LOST, /* User is still pressing but slid cursor/finger off + of the object */ + LV_EVENT_SHORT_CLICKED, /* User pressed object for a short period of time, + then released it. Not called if dragged. */ + LV_EVENT_LONG_PRESSED, /* Object has been pressed for at least + `LV_INDEV_LONG_PRESS_TIME`. Not called if + dragged. */ + LV_EVENT_LONG_PRESSED_REPEAT, /* Called after `LV_INDEV_LONG_PRESS_TIME` + in every `LV_INDEV_LONG_PRESS_REP_TIME` + ms. Not called if dragged.*/ + LV_EVENT_CLICKED, /* Called on release if not dragged (regardless to long + press) */ + LV_EVENT_RELEASED, /* Called in every cases when the object has been + released */ + LV_EVENT_DRAG_BEGIN, LV_EVENT_DRAG_END, LV_EVENT_DRAG_THROW_BEGIN, LV_EVENT_KEY, LV_EVENT_FOCUSED, LV_EVENT_DEFOCUSED, - LV_EVENT_VALUE_CHANGED, /**< The object's value has changed (i.e. slider moved) */ + LV_EVENT_VALUE_CHANGED, /* The object's value has changed (i.e. slider + moved) */ LV_EVENT_INSERT, LV_EVENT_REFRESH, - LV_EVENT_APPLY, /**< "Ok", "Apply" or similar specific button has clicked*/ - LV_EVENT_CANCEL, /**< "Close", "Cancel" or similar specific button has clicked*/ - LV_EVENT_DELETE, /**< Object is being deleted */ + LV_EVENT_APPLY, /* "Ok", "Apply" or similar specific button has clicked */ + LV_EVENT_CANCEL, /* "Close", "Cancel" or similar specific button has + clicked */ + LV_EVENT_DELETE, /* Object is being deleted */ }; -typedef uint8_t lv_event_t; /**< Type of event being sent to the object. */ + +typedef uint8_t lv_event_t; /* Type of event being sent to the object. */ /** * @brief Event callback. * Events are used to notify the user of some action being taken on the object. * For details, see ::lv_event_t. */ -typedef void (*lv_event_cb_t)(struct _lv_obj_t * obj, lv_event_t event); +typedef void (*lv_event_cb_t)(struct _lv_obj_t *obj, lv_event_t event); -/** Signals are for use by the object itself or to extend the object's functionality. - * Applications should use ::lv_obj_set_event_cb to be notified of events that occur - * on the object. */ +/** Signals are for use by the object itself or to extend the object's + * functionality. Applications should use ::lv_obj_set_event_cb to be notified + * of events that occur on the object. */ enum { /*General signals*/ - LV_SIGNAL_CLEANUP, /**< Object is being deleted */ - LV_SIGNAL_CHILD_CHG, /**< Child was removed/added */ - LV_SIGNAL_CORD_CHG, /**< Object coordinates/size have changed */ - LV_SIGNAL_PARENT_SIZE_CHG, /**< Parent's size has changed */ - LV_SIGNAL_STYLE_CHG, /**< Object's style has changed */ - LV_SIGNAL_REFR_EXT_DRAW_PAD, /**< Object's extra padding has changed */ - LV_SIGNAL_GET_TYPE, /**< LittlevGL needs to retrieve the object's type */ + LV_SIGNAL_CLEANUP, /* Object is being deleted */ + LV_SIGNAL_CHILD_CHG, /* Child was removed/added */ + LV_SIGNAL_CORD_CHG, /* Object coordinates/size have changed */ + LV_SIGNAL_PARENT_SIZE_CHG, /* Parent's size has changed */ + LV_SIGNAL_STYLE_CHG, /* Object's style has changed */ + LV_SIGNAL_REFR_EXT_DRAW_PAD, /* Object's extra padding has changed */ + LV_SIGNAL_GET_TYPE, /* LittlevGL needs to retrieve the object's type */ /*Input device related*/ - LV_SIGNAL_PRESSED, /**< The object has been pressed*/ - LV_SIGNAL_PRESSING, /**< The object is being pressed (called continuously while pressing)*/ - LV_SIGNAL_PRESS_LOST, /**< User is still pressing but slid cursor/finger off of the object */ - LV_SIGNAL_RELEASED, /**< User pressed object for a short period of time, then released it. Not called if dragged. */ - LV_SIGNAL_LONG_PRESS, /**< Object has been pressed for at least `LV_INDEV_LONG_PRESS_TIME`. Not called if dragged.*/ - LV_SIGNAL_LONG_PRESS_REP, /**< Called after `LV_INDEV_LONG_PRESS_TIME` in every `LV_INDEV_LONG_PRESS_REP_TIME` ms. Not called if dragged.*/ - LV_SIGNAL_DRAG_BEGIN, - LV_SIGNAL_DRAG_END, + LV_SIGNAL_PRESSED, /* The object has been pressed*/ + LV_SIGNAL_PRESSING, /* The object is being pressed (called continuously + while pressing)*/ + LV_SIGNAL_PRESS_LOST, /* User is still pressing but slid cursor/finger off + of the object */ + LV_SIGNAL_RELEASED, /* User pressed object for a short period of time, + then released it. Not called if dragged. */ + LV_SIGNAL_LONG_PRESS, /* Object has been pressed for at least + `LV_INDEV_LONG_PRESS_TIME`. Not called if + dragged.*/ + LV_SIGNAL_LONG_PRESS_REP, /* Called after `LV_INDEV_LONG_PRESS_TIME` in + every `LV_INDEV_LONG_PRESS_REP_TIME` ms. Not + called if dragged.*/ + LV_SIGNAL_DRAG_BEGIN, + LV_SIGNAL_DRAG_END, /*Group related*/ LV_SIGNAL_FOCUS, LV_SIGNAL_DEFOCUS, LV_SIGNAL_CONTROL, LV_SIGNAL_GET_EDITABLE, }; + typedef uint8_t lv_signal_t; -typedef lv_res_t (*lv_signal_cb_t)(struct _lv_obj_t * obj, lv_signal_t sign, void * param); +typedef lv_res_t (*lv_signal_cb_t)(struct _lv_obj_t *obj, lv_signal_t sign, + void *param); /** Object alignment. */ enum { @@ -161,22 +182,21 @@ enum { typedef uint8_t lv_align_t; #if LV_USE_OBJ_REALIGN -typedef struct -{ - const struct _lv_obj_t * base; +typedef struct { + const struct _lv_obj_t *base; lv_coord_t xofs; lv_coord_t yofs; lv_align_t align; uint8_t auto_realign : 1; - uint8_t origo_align : 1; /**< 1: the origo (center of the object) was aligned with - `lv_obj_align_origo`*/ + uint8_t origo_align : 1; /* 1: the origo (center of the object) was + aligned with `lv_obj_align_origo`*/ } lv_reailgn_t; #endif enum { - LV_DRAG_DIR_HOR = 0x1, /**< Object can be dragged horizontally. */ - LV_DRAG_DIR_VER = 0x2, /**< Object can be dragged vertically. */ - LV_DRAG_DIR_ALL = 0x3, /**< Object can be dragged in all directions. */ + LV_DRAG_DIR_HOR = 0x1, /* Object can be dragged horizontally. */ + LV_DRAG_DIR_VER = 0x2, /* Object can be dragged vertically. */ + LV_DRAG_DIR_ALL = 0x3, /* Object can be dragged in all directions. */ }; typedef uint8_t lv_drag_dir_t; @@ -184,7 +204,6 @@ typedef uint8_t lv_drag_dir_t; typedef void lv_obj_t; typedef void lv_obj_type_t; - /********************** * GLOBAL PROTOTYPES **********************/ @@ -192,7 +211,8 @@ typedef void lv_obj_type_t; /** * Init. the 'lv' library. */ -void lv_init(void); +void +lv_init(void); /*-------------------- * Create and delete @@ -201,38 +221,46 @@ void lv_init(void); /** * Create a basic object * @param parent pointer to a parent object. - * If NULL then a screen will be created - * @param copy pointer to a base object, if not NULL then the new object will be copied from it + * If NULL then a screen will be created + * @param copy pointer to a base object, if not NULL then + * the new object will be copied from it * @return pointer to the new object */ -lv_obj_t * lv_obj_create(lv_obj_t * parent, const lv_obj_t * copy); +lv_obj_t * +lv_obj_create(lv_obj_t *parent, const lv_obj_t *copy); /** * Delete 'obj' and all of its children * @param obj pointer to an object to delete * @return LV_RES_INV because the object is deleted */ -lv_res_t lv_obj_del(lv_obj_t * obj); +lv_res_t +lv_obj_del(lv_obj_t *obj); /** * Helper function for asynchronously deleting objects. - * Useful for cases where you can't delete an object directly in an `LV_EVENT_DELETE` handler (i.e. parent). + * Useful for cases where you can't delete an object directly in an + * `LV_EVENT_DELETE` handler (i.e. parent). * @param obj object to delete * @see lv_async_call */ -void lv_obj_del_async(struct _lv_obj_t *obj); +void +lv_obj_del_async(struct _lv_obj_t *obj); /** * Delete all children of an object * @param obj pointer to an object */ -void lv_obj_clean(lv_obj_t * obj); +void +lv_obj_clean(lv_obj_t *obj); /** - * Mark the object as invalid therefore its current position will be redrawn by 'lv_refr_task' + * Mark the object as invalid therefore its current position will be redrawn by + * 'lv_refr_task' * @param obj pointer to an object */ -void lv_obj_invalidate(const lv_obj_t * obj); +void +lv_obj_invalidate(const lv_obj_t *obj); /*===================== * Setter functions @@ -247,19 +275,22 @@ void lv_obj_invalidate(const lv_obj_t * obj); * @param obj pointer to an object. Can't be a screen. * @param parent pointer to the new parent object. (Can't be NULL) */ -void lv_obj_set_parent(lv_obj_t * obj, lv_obj_t * parent); +void +lv_obj_set_parent(lv_obj_t *obj, lv_obj_t *parent); /** * Move and object to the foreground * @param obj pointer to an object */ -void lv_obj_move_foreground(lv_obj_t * obj); +void +lv_obj_move_foreground(lv_obj_t *obj); /** * Move and object to the background * @param obj pointer to an object */ -void lv_obj_move_background(lv_obj_t * obj); +void +lv_obj_move_background(lv_obj_t *obj); /*-------------------- * Coordinate set @@ -271,21 +302,24 @@ void lv_obj_move_background(lv_obj_t * obj); * @param x new distance from the left side of the parent * @param y new distance from the top of the parent */ -void lv_obj_set_pos(lv_obj_t * obj, lv_coord_t x, lv_coord_t y); +void +lv_obj_set_pos(lv_obj_t *obj, lv_coord_t x, lv_coord_t y); /** * Set the x coordinate of a object * @param obj pointer to an object * @param x new distance from the left side from the parent */ -void lv_obj_set_x(lv_obj_t * obj, lv_coord_t x); +void +lv_obj_set_x(lv_obj_t *obj, lv_coord_t x); /** * Set the y coordinate of a object * @param obj pointer to an object * @param y new distance from the top of the parent */ -void lv_obj_set_y(lv_obj_t * obj, lv_coord_t y); +void +lv_obj_set_y(lv_obj_t *obj, lv_coord_t y); /** * Set the size of an object @@ -293,55 +327,66 @@ void lv_obj_set_y(lv_obj_t * obj, lv_coord_t y); * @param w new width * @param h new height */ -void lv_obj_set_size(lv_obj_t * obj, lv_coord_t w, lv_coord_t h); +void +lv_obj_set_size(lv_obj_t *obj, lv_coord_t w, lv_coord_t h); /** * Set the width of an object * @param obj pointer to an object * @param w new width */ -void lv_obj_set_width(lv_obj_t * obj, lv_coord_t w); +void +lv_obj_set_width(lv_obj_t *obj, lv_coord_t w); /** * Set the height of an object * @param obj pointer to an object * @param h new height */ -void lv_obj_set_height(lv_obj_t * obj, lv_coord_t h); +void +lv_obj_set_height(lv_obj_t *obj, lv_coord_t h); /** * Align an object to an other object. * @param obj pointer to an object to align - * @param base pointer to an object (if NULL the parent is used). 'obj' will be aligned to it. + * @param base pointer to an object (if NULL the parent is used). 'obj' will be + * aligned to it. * @param align type of alignment (see 'lv_align_t' enum) * @param x_mod x coordinate shift after alignment * @param y_mod y coordinate shift after alignment */ -void lv_obj_align(lv_obj_t * obj, const lv_obj_t * base, lv_align_t align, lv_coord_t x_mod, lv_coord_t y_mod); +void +lv_obj_align(lv_obj_t *obj, const lv_obj_t *base, lv_align_t align, + lv_coord_t x_mod, lv_coord_t y_mod); /** * Align an object to an other object. * @param obj pointer to an object to align - * @param base pointer to an object (if NULL the parent is used). 'obj' will be aligned to it. + * @param base pointer to an object (if NULL the parent is used). 'obj' will be + * aligned to it. * @param align type of alignment (see 'lv_align_t' enum) * @param x_mod x coordinate shift after alignment * @param y_mod y coordinate shift after alignment */ -void lv_obj_align_origo(lv_obj_t * obj, const lv_obj_t * base, lv_align_t align, lv_coord_t x_mod, lv_coord_t y_mod); +void +lv_obj_align_origo(lv_obj_t *obj, const lv_obj_t *base, lv_align_t align, + lv_coord_t x_mod, lv_coord_t y_mod); /** * Realign the object based on the last `lv_obj_align` parameters. * @param obj pointer to an object */ -void lv_obj_realign(lv_obj_t * obj); +void +lv_obj_realign(lv_obj_t *obj); /** - * Enable the automatic realign of the object when its size has changed based on the last - * `lv_obj_align` parameters. + * Enable the automatic realign of the object when its size has changed based on + * the last `lv_obj_align` parameters. * @param obj pointer to an object * @param en true: enable auto realign; false: disable auto realign */ -void lv_obj_set_auto_realign(lv_obj_t * obj, bool en); +void +lv_obj_set_auto_realign(lv_obj_t *obj, bool en); /** * Set the size of an extended clickable area @@ -351,7 +396,9 @@ void lv_obj_set_auto_realign(lv_obj_t * obj, bool en); * @param top extended clickable are on the top [px] * @param bottom extended clickable are on the bottom [px] */ -void lv_obj_set_ext_click_area(lv_obj_t * obj, lv_coord_t left, lv_coord_t right, lv_coord_t top, lv_coord_t bottom); +void +lv_obj_set_ext_click_area(lv_obj_t *obj, lv_coord_t left, lv_coord_t right, + lv_coord_t top, lv_coord_t bottom); /*--------------------- * Appearance set @@ -362,20 +409,23 @@ void lv_obj_set_ext_click_area(lv_obj_t * obj, lv_coord_t left, lv_coord_t right * @param obj pointer to an object * @param style_p pointer to the new style */ -void lv_obj_set_style(lv_obj_t * obj, const lv_style_t * style); +void +lv_obj_set_style(lv_obj_t *obj, const lv_style_t *style); /** * Notify an object about its style is modified * @param obj pointer to an object */ -void lv_obj_refresh_style(lv_obj_t * obj); +void +lv_obj_refresh_style(lv_obj_t *obj); /** * Notify all object if a style is modified - * @param style pointer to a style. Only the objects with this style will be notified - * (NULL to notify all objects) + * @param style pointer to a style. Only the objects with this style will be + * notified (NULL to notify all objects) */ -void lv_obj_report_style_mod(lv_style_t * style); +void +lv_obj_report_style_mod(lv_style_t *style); /*----------------- * Attribute set @@ -386,14 +436,16 @@ void lv_obj_report_style_mod(lv_style_t * style); * @param obj pointer to an object * @param en true: hide the object */ -void lv_obj_set_hidden(lv_obj_t * obj, bool en); +void +lv_obj_set_hidden(lv_obj_t *obj, bool en); /** * Enable or disable the clicking of an object * @param obj pointer to an object * @param en true: make the object clickable */ -void lv_obj_set_click(lv_obj_t * obj, bool en); +void +lv_obj_set_click(lv_obj_t *obj, bool en); /** * Enable to bring this object to the foreground if it @@ -401,28 +453,32 @@ void lv_obj_set_click(lv_obj_t * obj, bool en); * @param obj pointer to an object * @param en true: enable the auto top feature */ -void lv_obj_set_top(lv_obj_t * obj, bool en); +void +lv_obj_set_top(lv_obj_t *obj, bool en); /** * Enable the dragging of an object * @param obj pointer to an object * @param en true: make the object dragable */ -void lv_obj_set_drag(lv_obj_t * obj, bool en); +void +lv_obj_set_drag(lv_obj_t *obj, bool en); /** * Set the directions an object can be dragged in * @param obj pointer to an object * @param drag_dir bitwise OR of allowed drag directions */ -void lv_obj_set_drag_dir(lv_obj_t * obj, lv_drag_dir_t drag_dir); +void +lv_obj_set_drag_dir(lv_obj_t *obj, lv_drag_dir_t drag_dir); /** * Enable the throwing of an object after is is dragged * @param obj pointer to an object * @param en true: enable the drag throw */ -void lv_obj_set_drag_throw(lv_obj_t * obj, bool en); +void +lv_obj_set_drag_throw(lv_obj_t *obj, bool en); /** * Enable to use parent for drag related operations. @@ -430,45 +486,54 @@ void lv_obj_set_drag_throw(lv_obj_t * obj, bool en); * @param obj pointer to an object * @param en true: enable the 'drag parent' for the object */ -void lv_obj_set_drag_parent(lv_obj_t * obj, bool en); +void +lv_obj_set_drag_parent(lv_obj_t *obj, bool en); /** * Propagate the events to the parent too * @param obj pointer to an object * @param en true: enable the event propagation */ -void lv_obj_set_parent_event(lv_obj_t * obj, bool en); +void +lv_obj_set_parent_event(lv_obj_t *obj, bool en); /** - * Set the opa scale enable parameter (required to set opa_scale with `lv_obj_set_opa_scale()`) + * Set the opa scale enable parameter (required to set opa_scale with + * `lv_obj_set_opa_scale()`) * @param obj pointer to an object - * @param en true: opa scaling is enabled for this object and all children; false: no opa scaling + * @param en true: opa scaling is enabled for this object and all children; + * false: no opa scaling */ -void lv_obj_set_opa_scale_enable(lv_obj_t * obj, bool en); +void +lv_obj_set_opa_scale_enable(lv_obj_t *obj, bool en); /** * Set the opa scale of an object. - * The opacity of this object and all it's children will be scaled down with this factor. - * `lv_obj_set_opa_scale_enable(obj, true)` needs to be called to enable it. - * (not for all children just for the parent where to start the opa scaling) + * The opacity of this object and all it's children will be scaled down with + * this factor. `lv_obj_set_opa_scale_enable(obj, true)` needs to be called to + * enable it. (not for all children just for the parent where to start the opa + * scaling) * @param obj pointer to an object * @param opa_scale a factor to scale down opacity [0..255] */ -void lv_obj_set_opa_scale(lv_obj_t * obj, lv_opa_t opa_scale); +void +lv_obj_set_opa_scale(lv_obj_t *obj, lv_opa_t opa_scale); /** * Set a bit or bits in the protect filed * @param obj pointer to an object * @param prot 'OR'-ed values from `lv_protect_t` */ -void lv_obj_set_protect(lv_obj_t * obj, uint8_t prot); +void +lv_obj_set_protect(lv_obj_t *obj, uint8_t prot); /** * Clear a bit or bits in the protect filed * @param obj pointer to an object * @param prot 'OR'-ed values from `lv_protect_t` */ -void lv_obj_clear_protect(lv_obj_t * obj, uint8_t prot); +void +lv_obj_clear_protect(lv_obj_t *obj, uint8_t prot); /** * Set a an event handler function for an object. @@ -476,34 +541,44 @@ void lv_obj_clear_protect(lv_obj_t * obj, uint8_t prot); * @param obj pointer to an object * @param event_cb the new event function */ -void lv_obj_set_event_cb(lv_obj_t * obj, lv_event_cb_t event_cb); +void +lv_obj_set_event_cb(lv_obj_t *obj, lv_event_cb_t event_cb); /** * Send an event to the object * @param obj pointer to an object * @param event the type of the event from `lv_event_t`. - * @param data arbitrary data depending on the object type and the event. (Usually `NULL`) - * @return LV_RES_OK: `obj` was not deleted in the event; LV_RES_INV: `obj` was deleted in the event + * @param data arbitrary data depending on the object type and the event. + * (Usually `NULL`) + * @return LV_RES_OK: `obj` was not deleted in the event; LV_RES_INV: `obj` + * was deleted in the event */ -lv_res_t lv_event_send(lv_obj_t * obj, lv_event_t event, const void * data); +lv_res_t +lv_event_send(lv_obj_t *obj, lv_event_t event, const void *data); /** * Call an event function with an object, event, and data. - * @param event_xcb an event callback function. If `NULL` `LV_RES_OK` will return without any actions. - * (the 'x' in the argument name indicates that its not a fully generic function because it not follows - * the `func_name(object, callback, ...)` convention) - * @param obj pointer to an object to associate with the event (can be `NULL` to simply call the `event_cb`) + * @param event_xcb an event callback function. If `NULL` `LV_RES_OK` will + * return without any actions. (the 'x' in the argument name indicates + * that its not a fully generic function because it not follows the + * `func_name(object, callback, ...)` convention) + * @param obj pointer to an object to associate with the event (can be `NULL` + * to simply call the `event_cb`) * @param event an event * @param data pointer to a custom data - * @return LV_RES_OK: `obj` was not deleted in the event; LV_RES_INV: `obj` was deleted in the event + * @return LV_RES_OK: `obj` was not deleted in the event; LV_RES_INV: `obj` + * was deleted in the event */ -lv_res_t lv_event_send_func(lv_event_cb_t event_xcb, lv_obj_t * obj, lv_event_t event, const void * data); +lv_res_t +lv_event_send_func(lv_event_cb_t event_xcb, lv_obj_t *obj, lv_event_t event, + const void *data); /** * Get the `data` parameter of the current event * @return the `data` parameter */ -const void * lv_event_get_data(void); +const void * +lv_event_get_data(void); /** * Set the a signal function of an object. Used internally by the library. @@ -511,21 +586,24 @@ const void * lv_event_get_data(void); * @param obj pointer to an object * @param signal_cb the new signal function */ -void lv_obj_set_signal_cb(lv_obj_t * obj, lv_signal_cb_t signal_cb); +void +lv_obj_set_signal_cb(lv_obj_t *obj, lv_signal_cb_t signal_cb); /** * Send an event to the object * @param obj pointer to an object * @param event the type of the event from `lv_event_t`. */ -void lv_signal_send(lv_obj_t * obj, lv_signal_t signal, void * param); +void +lv_signal_send(lv_obj_t *obj, lv_signal_t signal, void *param); /** * Set a new design function for an object * @param obj pointer to an object * @param design_cb the new design function */ -void lv_obj_set_design_cb(lv_obj_t * obj, lv_design_cb_t design_cb); +void +lv_obj_set_design_cb(lv_obj_t *obj, lv_design_cb_t design_cb); /*---------------- * Other set @@ -537,13 +615,15 @@ void lv_obj_set_design_cb(lv_obj_t * obj, lv_design_cb_t design_cb); * @param ext_size the size of the new ext. data * @return pointer to the allocated ext */ -void * lv_obj_allocate_ext_attr(lv_obj_t * obj, uint16_t ext_size); +void * +lv_obj_allocate_ext_attr(lv_obj_t *obj, uint16_t ext_size); /** * Send a 'LV_SIGNAL_REFR_EXT_SIZE' signal to the object * @param obj pointer to an object */ -void lv_obj_refresh_ext_draw_pad(lv_obj_t * obj); +void +lv_obj_refresh_ext_draw_pad(lv_obj_t *obj); /*======================= * Getter functions @@ -554,14 +634,16 @@ void lv_obj_refresh_ext_draw_pad(lv_obj_t * obj); * @param obj pointer to an object * @return pointer to a screen */ -lv_obj_t * lv_obj_get_screen(const lv_obj_t * obj); +lv_obj_t * +lv_obj_get_screen(const lv_obj_t *obj); /** * Get the display of an object * @param scr pointer to an object * @return pointer the object's display */ -lv_disp_t * lv_obj_get_disp(const lv_obj_t * obj); +lv_disp_t * +lv_obj_get_disp(const lv_obj_t *obj); /*--------------------- * Parent/children get @@ -572,38 +654,45 @@ lv_disp_t * lv_obj_get_disp(const lv_obj_t * obj); * @param obj pointer to an object * @return pointer to the parent of 'obj' */ -lv_obj_t * lv_obj_get_parent(const lv_obj_t * obj); +lv_obj_t * +lv_obj_get_parent(const lv_obj_t *obj); /** - * Iterate through the children of an object (start from the "youngest, lastly created") + * Iterate through the children of an object (start from the "youngest, lastly + * created") * @param obj pointer to an object * @param child NULL at first call to get the next children - * and the previous return value later + * and the previous return value later * @return the child after 'act_child' or NULL if no more child */ -lv_obj_t * lv_obj_get_child(const lv_obj_t * obj, const lv_obj_t * child); +lv_obj_t * +lv_obj_get_child(const lv_obj_t *obj, const lv_obj_t *child); /** - * Iterate through the children of an object (start from the "oldest", firstly created) + * Iterate through the children of an object (start from the "oldest", firstly + * created) * @param obj pointer to an object * @param child NULL at first call to get the next children - * and the previous return value later + * and the previous return value later * @return the child after 'act_child' or NULL if no more child */ -lv_obj_t * lv_obj_get_child_back(const lv_obj_t * obj, const lv_obj_t * child); +lv_obj_t * +lv_obj_get_child_back(const lv_obj_t *obj, const lv_obj_t *child); /** * Count the children of an object (only children directly on 'obj') * @param obj pointer to an object * @return children number of 'obj' */ -uint16_t lv_obj_count_children(const lv_obj_t * obj); +uint16_t +lv_obj_count_children(const lv_obj_t *obj); /** Recursively count the children of an object * @param obj pointer to an object * @return children number of 'obj' */ -uint16_t lv_obj_count_children_recursive(const lv_obj_t * obj); +uint16_t +lv_obj_count_children_recursive(const lv_obj_t *obj); /*--------------------- * Coordinate get @@ -614,98 +703,113 @@ uint16_t lv_obj_count_children_recursive(const lv_obj_t * obj); * @param obj pointer to an object * @param cords_p pointer to an area to store the coordinates */ -void lv_obj_get_coords(const lv_obj_t * obj, lv_area_t * cords_p); +void +lv_obj_get_coords(const lv_obj_t *obj, lv_area_t *cords_p); /** - * Reduce area retried by `lv_obj_get_coords()` the get graphically usable area of an object. - * (Without the size of the border or other extra graphical elements) + * Reduce area retried by `lv_obj_get_coords()` the get graphically usable area + * of an object. (Without the size of the border or other extra graphical + * elements) * @param coords_p store the result area here */ -void lv_obj_get_inner_coords(const lv_obj_t * obj, lv_area_t * coords_p); +void +lv_obj_get_inner_coords(const lv_obj_t *obj, lv_area_t *coords_p); /** * Get the x coordinate of object * @param obj pointer to an object * @return distance of 'obj' from the left side of its parent */ -lv_coord_t lv_obj_get_x(const lv_obj_t * obj); +lv_coord_t +lv_obj_get_x(const lv_obj_t *obj); /** * Get the y coordinate of object * @param obj pointer to an object * @return distance of 'obj' from the top of its parent */ -lv_coord_t lv_obj_get_y(const lv_obj_t * obj); +lv_coord_t +lv_obj_get_y(const lv_obj_t *obj); /** * Get the width of an object * @param obj pointer to an object * @return the width */ -lv_coord_t lv_obj_get_width(const lv_obj_t * obj); +lv_coord_t +lv_obj_get_width(const lv_obj_t *obj); /** * Get the height of an object * @param obj pointer to an object * @return the height */ -lv_coord_t lv_obj_get_height(const lv_obj_t * obj); +lv_coord_t +lv_obj_get_height(const lv_obj_t *obj); /** * Get that width reduced by the left and right padding. * @param obj pointer to an object * @return the width which still fits into the container */ -lv_coord_t lv_obj_get_width_fit(lv_obj_t * obj); +lv_coord_t +lv_obj_get_width_fit(lv_obj_t *obj); /** * Get that height reduced by the top an bottom padding. * @param obj pointer to an object * @return the height which still fits into the container */ -lv_coord_t lv_obj_get_height_fit(lv_obj_t * obj); +lv_coord_t +lv_obj_get_height_fit(lv_obj_t *obj); /** * Get the automatic realign property of the object. * @param obj pointer to an object * @return true: auto realign is enabled; false: auto realign is disabled */ -bool lv_obj_get_auto_realign(lv_obj_t * obj); +bool +lv_obj_get_auto_realign(lv_obj_t *obj); /** * Get the left padding of extended clickable area * @param obj pointer to an object * @return the extended left padding */ -lv_coord_t lv_obj_get_ext_click_pad_left(const lv_obj_t * obj); +lv_coord_t +lv_obj_get_ext_click_pad_left(const lv_obj_t *obj); /** * Get the right padding of extended clickable area * @param obj pointer to an object * @return the extended right padding */ -lv_coord_t lv_obj_get_ext_click_pad_right(const lv_obj_t * obj); +lv_coord_t +lv_obj_get_ext_click_pad_right(const lv_obj_t *obj); /** * Get the top padding of extended clickable area * @param obj pointer to an object * @return the extended top padding */ -lv_coord_t lv_obj_get_ext_click_pad_top(const lv_obj_t * obj); +lv_coord_t +lv_obj_get_ext_click_pad_top(const lv_obj_t *obj); /** * Get the bottom padding of extended clickable area * @param obj pointer to an object * @return the extended bottom padding */ -lv_coord_t lv_obj_get_ext_click_pad_bottom(const lv_obj_t * obj); +lv_coord_t +lv_obj_get_ext_click_pad_bottom(const lv_obj_t *obj); /** * Get the extended size attribute of an object * @param obj pointer to an object * @return the extended size attribute */ -lv_coord_t lv_obj_get_ext_draw_pad(const lv_obj_t * obj); +lv_coord_t +lv_obj_get_ext_draw_pad(const lv_obj_t *obj); /*----------------- * Appearance get @@ -716,7 +820,8 @@ lv_coord_t lv_obj_get_ext_draw_pad(const lv_obj_t * obj); * @param obj pointer to an object * @return pointer to a style */ -const lv_style_t * lv_obj_get_style(const lv_obj_t * obj); +const lv_style_t * +lv_obj_get_style(const lv_obj_t *obj); /*----------------- * Attribute get @@ -727,77 +832,89 @@ const lv_style_t * lv_obj_get_style(const lv_obj_t * obj); * @param obj pointer to an object * @return true: the object is hidden */ -bool lv_obj_get_hidden(const lv_obj_t * obj); +bool +lv_obj_get_hidden(const lv_obj_t *obj); /** * Get the click enable attribute of an object * @param obj pointer to an object * @return true: the object is clickable */ -bool lv_obj_get_click(const lv_obj_t * obj); +bool +lv_obj_get_click(const lv_obj_t *obj); /** * Get the top enable attribute of an object * @param obj pointer to an object * @return true: the auto top feature is enabled */ -bool lv_obj_get_top(const lv_obj_t * obj); +bool +lv_obj_get_top(const lv_obj_t *obj); /** * Get the drag enable attribute of an object * @param obj pointer to an object * @return true: the object is dragable */ -bool lv_obj_get_drag(const lv_obj_t * obj); +bool +lv_obj_get_drag(const lv_obj_t *obj); /** * Get the directions an object can be dragged * @param obj pointer to an object * @return bitwise OR of allowed directions an object can be dragged in */ -lv_drag_dir_t lv_obj_get_drag_dir(const lv_obj_t * obj); +lv_drag_dir_t +lv_obj_get_drag_dir(const lv_obj_t *obj); /** * Get the drag throw enable attribute of an object * @param obj pointer to an object * @return true: drag throw is enabled */ -bool lv_obj_get_drag_throw(const lv_obj_t * obj); +bool +lv_obj_get_drag_throw(const lv_obj_t *obj); /** * Get the drag parent attribute of an object * @param obj pointer to an object * @return true: drag parent is enabled */ -bool lv_obj_get_drag_parent(const lv_obj_t * obj); +bool +lv_obj_get_drag_parent(const lv_obj_t *obj); /** * Get the drag parent attribute of an object * @param obj pointer to an object * @return true: drag parent is enabled */ -bool lv_obj_get_parent_event(const lv_obj_t * obj); +bool +lv_obj_get_parent_event(const lv_obj_t *obj); /** * Get the opa scale enable parameter * @param obj pointer to an object - * @return true: opa scaling is enabled for this object and all children; false: no opa scaling + * @return true: opa scaling is enabled for this object and all children; false: + * no opa scaling */ -lv_opa_t lv_obj_get_opa_scale_enable(const lv_obj_t * obj); +lv_opa_t +lv_obj_get_opa_scale_enable(const lv_obj_t *obj); /** * Get the opa scale parameter of an object * @param obj pointer to an object * @return opa scale [0..255] */ -lv_opa_t lv_obj_get_opa_scale(const lv_obj_t * obj); +lv_opa_t +lv_obj_get_opa_scale(const lv_obj_t *obj); /** * Get the protect field of an object * @param obj pointer to an object * @return protect field ('OR'ed values of `lv_protect_t`) */ -uint8_t lv_obj_get_protect(const lv_obj_t * obj); +uint8_t +lv_obj_get_protect(const lv_obj_t *obj); /** * Check at least one bit of a given protect bitfield is set @@ -805,28 +922,32 @@ uint8_t lv_obj_get_protect(const lv_obj_t * obj); * @param prot protect bits to test ('OR'ed values of `lv_protect_t`) * @return false: none of the given bits are set, true: at least one bit is set */ -bool lv_obj_is_protected(const lv_obj_t * obj, uint8_t prot); +bool +lv_obj_is_protected(const lv_obj_t *obj, uint8_t prot); /** * Get the signal function of an object * @param obj pointer to an object * @return the signal function */ -lv_signal_cb_t lv_obj_get_signal_cb(const lv_obj_t * obj); +lv_signal_cb_t +lv_obj_get_signal_cb(const lv_obj_t *obj); /** * Get the design function of an object * @param obj pointer to an object * @return the design function */ -lv_design_cb_t lv_obj_get_design_cb(const lv_obj_t * obj); +lv_design_cb_t +lv_obj_get_design_cb(const lv_obj_t *obj); /** * Get the event function of an object * @param obj pointer to an object * @return the event function */ -lv_event_cb_t lv_obj_get_event_cb(const lv_obj_t * obj); +lv_event_cb_t +lv_obj_get_event_cb(const lv_obj_t *obj); /*------------------ * Other get @@ -838,15 +959,18 @@ lv_event_cb_t lv_obj_get_event_cb(const lv_obj_t * obj); * @return the ext pointer but not the dynamic version * Use it as ext->data1, and NOT da(ext)->data1 */ -void * lv_obj_get_ext_attr(const lv_obj_t * obj); +void * +lv_obj_get_ext_attr(const lv_obj_t *obj); /** - * Get object's and its ancestors type. Put their name in `type_buf` starting with the current type. - * E.g. buf.type[0]="lv_btn", buf.type[1]="lv_cont", buf.type[2]="lv_obj" + * Get object's and its ancestors type. Put their name in `type_buf` starting + * with the current type. E.g. buf.type[0]="lv_btn", buf.type[1]="lv_cont", + * buf.type[2]="lv_obj" * @param obj pointer to an object which type should be get * @param buf pointer to an `lv_obj_type_t` buffer to store the types */ -void lv_obj_get_type(lv_obj_t * obj, lv_obj_type_t * buf); +void +lv_obj_get_type(lv_obj_t *obj, lv_obj_type_t *buf); #if LV_USE_USER_DATA /** @@ -854,21 +978,24 @@ void lv_obj_get_type(lv_obj_t * obj, lv_obj_type_t * buf); * @param obj pointer to an object * @return user data */ -lv_obj_user_data_t lv_obj_get_user_data(lv_obj_t * obj); +lv_obj_user_data_t +lv_obj_get_user_data(lv_obj_t *obj); /** * Get a pointer to the object's user data * @param obj pointer to an object * @return pointer to the user data */ -lv_obj_user_data_t * lv_obj_get_user_data_ptr(lv_obj_t * obj); +lv_obj_user_data_t * +lv_obj_get_user_data_ptr(lv_obj_t *obj); /** * Set the object's user data. The data will be copied. * @param obj pointer to an object * @param data user data */ -void lv_obj_set_user_data(lv_obj_t * obj, lv_obj_user_data_t data); +void +lv_obj_set_user_data(lv_obj_t *obj, lv_obj_user_data_t data); #endif @@ -878,14 +1005,17 @@ void lv_obj_set_user_data(lv_obj_t * obj, lv_obj_user_data_t data); * @param obj pointer to an object * @return the pointer to group of the object */ -void * lv_obj_get_group(const lv_obj_t * obj); +void * +lv_obj_get_group(const lv_obj_t *obj); /** * Tell whether the object is the focused object of a group or not. * @param obj pointer to an object - * @return true: the object is focused, false: the object is not focused or not in a group + * @return true: the object is focused, + * false: the object is not focused or not in a group */ -bool lv_obj_is_focused(const lv_obj_t * obj); +bool +lv_obj_is_focused(const lv_obj_t *obj); #endif @@ -907,7 +1037,7 @@ bool lv_obj_is_focused(const lv_obj_t * obj); * } * } */ -#define LV_EVENT_CB_DECLARE(name) void name(lv_obj_t * obj, lv_event_t e) +#define LV_EVENT_CB_DECLARE(name) void name(lv_obj_t *obj, lv_event_t e) #ifdef __cplusplus } /* extern "C" */ diff --git a/core/app-framework/wgl/app/wa-inc/lvgl/lvgl.h b/core/app-framework/wgl/app/wa-inc/lvgl/lvgl.h index c70dd49bec..7c4c7b2fe0 100644 --- a/core/app-framework/wgl/app/wa-inc/lvgl/lvgl.h +++ b/core/app-framework/wgl/app/wa-inc/lvgl/lvgl.h @@ -10,7 +10,6 @@ extern "C" { #endif - //#include "bi-inc/wgl_shared_utils.h" /* shared types between app and native */ /* #include "lvgl-compatible/lv_types.h" @@ -21,9 +20,6 @@ extern "C" { #include "lvgl-compatible/lv_list.h" */ - - - #include "src/lv_version.h" #include "src/lv_misc/lv_log.h" diff --git a/core/app-framework/wgl/app/wa-inc/lvgl/test.c b/core/app-framework/wgl/app/wa-inc/lvgl/test.c index ceafbd512f..2262aa551e 100644 --- a/core/app-framework/wgl/app/wa-inc/lvgl/test.c +++ b/core/app-framework/wgl/app/wa-inc/lvgl/test.c @@ -1,11 +1,9 @@ #include "lvgl.h" - -int main() +int +main() { - - return 0; - + return 0; } diff --git a/core/app-framework/wgl/native/gui_native_api.h b/core/app-framework/wgl/native/gui_native_api.h index f61d9b51ac..ee91b0eaaa 100644 --- a/core/app-framework/wgl/native/gui_native_api.h +++ b/core/app-framework/wgl/native/gui_native_api.h @@ -13,34 +13,32 @@ extern "C" { #endif - /** * gui interfaces */ void -wasm_obj_native_call(wasm_exec_env_t exec_env, - int32 func_id, uint32 *argv, uint32 argc); +wasm_obj_native_call(wasm_exec_env_t exec_env, int32 func_id, uint32 *argv, + uint32 argc); void -wasm_btn_native_call(wasm_exec_env_t exec_env, - int32 func_id, uint32 *argv, uint32 argc); +wasm_btn_native_call(wasm_exec_env_t exec_env, int32 func_id, uint32 *argv, + uint32 argc); void -wasm_label_native_call(wasm_exec_env_t exec_env, - int32 func_id, uint32 *argv, uint32 argc); +wasm_label_native_call(wasm_exec_env_t exec_env, int32 func_id, uint32 *argv, + uint32 argc); void -wasm_cb_native_call(wasm_exec_env_t exec_env, - int32 func_id, uint32 *argv, uint32 argc); +wasm_cb_native_call(wasm_exec_env_t exec_env, int32 func_id, uint32 *argv, + uint32 argc); void -wasm_list_native_call(wasm_exec_env_t exec_env, - int32 func_id, uint32 *argv, uint32 argc); +wasm_list_native_call(wasm_exec_env_t exec_env, int32 func_id, uint32 *argv, + uint32 argc); #ifdef __cplusplus } #endif - #endif /* end of _GUI_API_H_ */ diff --git a/core/app-framework/wgl/native/wgl.h b/core/app-framework/wgl/native/wgl.h index dc01191c29..ad58431159 100644 --- a/core/app-framework/wgl/native/wgl.h +++ b/core/app-framework/wgl/native/wgl.h @@ -10,8 +10,10 @@ extern "C" { #endif -void wgl_init(void); -void wgl_exit(void); +void +wgl_init(void); +void +wgl_exit(void); #ifdef __cplusplus } diff --git a/core/app-framework/wgl/native/wgl_btn_wrapper.c b/core/app-framework/wgl/native/wgl_btn_wrapper.c index dbe6224766..4c3a23239d 100644 --- a/core/app-framework/wgl/native/wgl_btn_wrapper.c +++ b/core/app-framework/wgl/native/wgl_btn_wrapper.c @@ -19,7 +19,8 @@ DEFINE_WGL_NATIVE_WRAPPER(lv_btn_create_wrapper) wgl_native_get_arg(uint32, copy_obj_id); wasm_module_inst_t module_inst = get_module_inst(exec_env); - res = wgl_native_wigdet_create(WIDGET_TYPE_BTN, par_obj_id, copy_obj_id, module_inst); + res = wgl_native_wigdet_create(WIDGET_TYPE_BTN, par_obj_id, copy_obj_id, + module_inst); wgl_native_set_return(res); } @@ -131,33 +132,30 @@ DEFINE_WGL_NATIVE_WRAPPER(lv_btn_toggle_wrapper) lv_btn_toggle(btn); } +/* clang-format off */ static WGLNativeFuncDef btn_native_func_defs[] = { - { BTN_FUNC_ID_CREATE, lv_btn_create_wrapper, 2, false }, - { BTN_FUNC_ID_SET_TOGGLE, lv_btn_set_toggle_wrapper, 2, true }, - { BTN_FUNC_ID_SET_STATE, lv_btn_set_state_wrapper, 2, true }, - { BTN_FUNC_ID_SET_INK_IN_TIME, lv_btn_set_ink_in_time_wrapper, 2, true }, - { BTN_FUNC_ID_SET_INK_OUT_TIME, lv_btn_set_ink_out_time_wrapper, 2, true }, - { BTN_FUNC_ID_SET_INK_WAIT_TIME, lv_btn_set_ink_wait_time_wrapper, 2, true }, - { BTN_FUNC_ID_GET_INK_IN_TIME, lv_btn_get_ink_in_time_wrapper, 1, true }, - { BTN_FUNC_ID_GET_INK_OUT_TIME, lv_btn_get_ink_out_time_wrapper, 1, true }, - { BTN_FUNC_ID_GET_INK_WAIT_TIME, lv_btn_get_ink_wait_time_wrapper, 1, true }, - { BTN_FUNC_ID_GET_STATE, lv_btn_get_state_wrapper, 1, true }, - { BTN_FUNC_ID_GET_TOGGLE, lv_btn_get_toggle_wrapper, 1, true }, - { BTN_FUNC_ID_TOGGLE, lv_btn_toggle_wrapper, 1, true }, - + { BTN_FUNC_ID_CREATE, lv_btn_create_wrapper, 2, false }, + { BTN_FUNC_ID_SET_TOGGLE, lv_btn_set_toggle_wrapper, 2, true }, + { BTN_FUNC_ID_SET_STATE, lv_btn_set_state_wrapper, 2, true }, + { BTN_FUNC_ID_SET_INK_IN_TIME, lv_btn_set_ink_in_time_wrapper, 2, true }, + { BTN_FUNC_ID_SET_INK_OUT_TIME, lv_btn_set_ink_out_time_wrapper, 2, true }, + { BTN_FUNC_ID_SET_INK_WAIT_TIME, lv_btn_set_ink_wait_time_wrapper, 2, true }, + { BTN_FUNC_ID_GET_INK_IN_TIME, lv_btn_get_ink_in_time_wrapper, 1, true }, + { BTN_FUNC_ID_GET_INK_OUT_TIME, lv_btn_get_ink_out_time_wrapper, 1, true }, + { BTN_FUNC_ID_GET_INK_WAIT_TIME, lv_btn_get_ink_wait_time_wrapper, 1, true }, + { BTN_FUNC_ID_GET_STATE, lv_btn_get_state_wrapper, 1, true }, + { BTN_FUNC_ID_GET_TOGGLE, lv_btn_get_toggle_wrapper, 1, true }, + { BTN_FUNC_ID_TOGGLE, lv_btn_toggle_wrapper, 1, true }, }; +/* clang-format on */ /*************** Native Interface to Wasm App ***********/ void -wasm_btn_native_call(wasm_exec_env_t exec_env, - int32 func_id, uint32 *argv, uint32 argc) +wasm_btn_native_call(wasm_exec_env_t exec_env, int32 func_id, uint32 *argv, + uint32 argc) { uint32 size = sizeof(btn_native_func_defs) / sizeof(WGLNativeFuncDef); - wgl_native_func_call(exec_env, - btn_native_func_defs, - size, - func_id, - argv, + wgl_native_func_call(exec_env, btn_native_func_defs, size, func_id, argv, argc); } diff --git a/core/app-framework/wgl/native/wgl_cb_wrapper.c b/core/app-framework/wgl/native/wgl_cb_wrapper.c index e306b1045a..51510b9974 100644 --- a/core/app-framework/wgl/native/wgl_cb_wrapper.c +++ b/core/app-framework/wgl/native/wgl_cb_wrapper.c @@ -20,7 +20,8 @@ DEFINE_WGL_NATIVE_WRAPPER(lv_cb_create_wrapper) wgl_native_get_arg(uint32, copy_obj_id); wasm_module_inst_t module_inst = get_module_inst(exec_env); - res = wgl_native_wigdet_create(WIDGET_TYPE_CB, par_obj_id, copy_obj_id, module_inst); + res = wgl_native_wigdet_create(WIDGET_TYPE_CB, par_obj_id, copy_obj_id, + module_inst); wgl_native_set_return(res); } @@ -63,7 +64,7 @@ DEFINE_WGL_NATIVE_WRAPPER(lv_cb_get_text_length_wrapper) (void)exec_env; text = lv_cb_get_text(cb); - wgl_native_set_return(text ? strlen(text): 0); + wgl_native_set_return(text ? strlen(text) : 0); } DEFINE_WGL_NATIVE_WRAPPER(lv_cb_get_text_wrapper) @@ -89,24 +90,20 @@ DEFINE_WGL_NATIVE_WRAPPER(lv_cb_get_text_wrapper) } static WGLNativeFuncDef cb_native_func_defs[] = { - { CB_FUNC_ID_CREATE, lv_cb_create_wrapper, 2, false }, - { CB_FUNC_ID_SET_TEXT, lv_cb_set_text_wrapper, 3, true }, - { CB_FUNC_ID_SET_STATIC_TEXT, lv_cb_set_static_text_wrapper, 3, true }, - { CB_FUNC_ID_GET_TEXT_LENGTH, lv_cb_get_text_length_wrapper, 1, true }, - { CB_FUNC_ID_GET_TEXT, lv_cb_get_text_wrapper, 3, true }, + { CB_FUNC_ID_CREATE, lv_cb_create_wrapper, 2, false }, + { CB_FUNC_ID_SET_TEXT, lv_cb_set_text_wrapper, 3, true }, + { CB_FUNC_ID_SET_STATIC_TEXT, lv_cb_set_static_text_wrapper, 3, true }, + { CB_FUNC_ID_GET_TEXT_LENGTH, lv_cb_get_text_length_wrapper, 1, true }, + { CB_FUNC_ID_GET_TEXT, lv_cb_get_text_wrapper, 3, true }, }; /*************** Native Interface to Wasm App ***********/ void -wasm_cb_native_call(wasm_exec_env_t exec_env, - int32 func_id, uint32 *argv, uint32 argc) +wasm_cb_native_call(wasm_exec_env_t exec_env, int32 func_id, uint32 *argv, + uint32 argc) { uint32 size = sizeof(cb_native_func_defs) / sizeof(WGLNativeFuncDef); - wgl_native_func_call(exec_env, - cb_native_func_defs, - size, - func_id, - argv, + wgl_native_func_call(exec_env, cb_native_func_defs, size, func_id, argv, argc); } diff --git a/core/app-framework/wgl/native/wgl_label_wrapper.c b/core/app-framework/wgl/native/wgl_label_wrapper.c index c1327e4dbc..dbdefec146 100644 --- a/core/app-framework/wgl/native/wgl_label_wrapper.c +++ b/core/app-framework/wgl/native/wgl_label_wrapper.c @@ -20,7 +20,8 @@ DEFINE_WGL_NATIVE_WRAPPER(lv_label_create_wrapper) wgl_native_get_arg(uint32, copy_obj_id); wasm_module_inst_t module_inst = get_module_inst(exec_env); - res = wgl_native_wigdet_create(WIDGET_TYPE_LABEL, par_obj_id, copy_obj_id, module_inst); + res = wgl_native_wigdet_create(WIDGET_TYPE_LABEL, par_obj_id, copy_obj_id, + module_inst); wgl_native_set_return(res); } @@ -73,24 +74,22 @@ DEFINE_WGL_NATIVE_WRAPPER(lv_label_get_text_wrapper) wgl_native_set_return(buffer_offset); } +/* clang-format off */ static WGLNativeFuncDef label_native_func_defs[] = { - { LABEL_FUNC_ID_CREATE, lv_label_create_wrapper, 2, false }, - { LABEL_FUNC_ID_SET_TEXT, lv_label_set_text_wrapper, 3, true }, - { LABEL_FUNC_ID_GET_TEXT_LENGTH, lv_label_get_text_length_wrapper, 1, true }, - { LABEL_FUNC_ID_GET_TEXT, lv_label_get_text_wrapper, 3, true }, + { LABEL_FUNC_ID_CREATE, lv_label_create_wrapper, 2, false }, + { LABEL_FUNC_ID_SET_TEXT, lv_label_set_text_wrapper, 3, true }, + { LABEL_FUNC_ID_GET_TEXT_LENGTH, lv_label_get_text_length_wrapper, 1, true }, + { LABEL_FUNC_ID_GET_TEXT, lv_label_get_text_wrapper, 3, true }, }; +/* clang-format on */ /*************** Native Interface to Wasm App ***********/ void -wasm_label_native_call(wasm_exec_env_t exec_env, - int32 func_id, uint32 *argv, uint32 argc) +wasm_label_native_call(wasm_exec_env_t exec_env, int32 func_id, uint32 *argv, + uint32 argc) { uint32 size = sizeof(label_native_func_defs) / sizeof(WGLNativeFuncDef); - wgl_native_func_call(exec_env, - label_native_func_defs, - size, - func_id, - argv, + wgl_native_func_call(exec_env, label_native_func_defs, size, func_id, argv, argc); } diff --git a/core/app-framework/wgl/native/wgl_list_wrapper.c b/core/app-framework/wgl/native/wgl_list_wrapper.c index 926573ec66..c77f449309 100644 --- a/core/app-framework/wgl/native/wgl_list_wrapper.c +++ b/core/app-framework/wgl/native/wgl_list_wrapper.c @@ -20,7 +20,8 @@ DEFINE_WGL_NATIVE_WRAPPER(lv_list_create_wrapper) wgl_native_get_arg(uint32, copy_obj_id); wasm_module_inst_t module_inst = get_module_inst(exec_env); - res = wgl_native_wigdet_create(WIDGET_TYPE_LIST, par_obj_id, copy_obj_id, module_inst); + res = wgl_native_wigdet_create(WIDGET_TYPE_LIST, par_obj_id, copy_obj_id, + module_inst); wgl_native_set_return(res); } @@ -49,7 +50,8 @@ DEFINE_WGL_NATIVE_WRAPPER(lv_list_add_btn_wrapper) bh_assert(mod_id != ID_NONE); if (!wgl_native_add_object(btn, mod_id, &btn_obj_id)) { - wasm_runtime_set_exception(module_inst, "add button to object list fail."); + wasm_runtime_set_exception(module_inst, + "add button to object list fail."); return; } @@ -57,21 +59,17 @@ DEFINE_WGL_NATIVE_WRAPPER(lv_list_add_btn_wrapper) } static WGLNativeFuncDef list_native_func_defs[] = { - { LIST_FUNC_ID_CREATE, lv_list_create_wrapper, 2, false }, - { LIST_FUNC_ID_ADD_BTN, lv_list_add_btn_wrapper, 3, true }, + { LIST_FUNC_ID_CREATE, lv_list_create_wrapper, 2, false }, + { LIST_FUNC_ID_ADD_BTN, lv_list_add_btn_wrapper, 3, true }, }; /*************** Native Interface to Wasm App ***********/ void -wasm_list_native_call(wasm_exec_env_t exec_env, - int32 func_id, uint32 *argv, uint32 argc) +wasm_list_native_call(wasm_exec_env_t exec_env, int32 func_id, uint32 *argv, + uint32 argc) { uint32 size = sizeof(list_native_func_defs) / sizeof(WGLNativeFuncDef); - wgl_native_func_call(exec_env, - list_native_func_defs, - size, - func_id, - argv, + wgl_native_func_call(exec_env, list_native_func_defs, size, func_id, argv, argc); } diff --git a/core/app-framework/wgl/native/wgl_native_utils.c b/core/app-framework/wgl/native/wgl_native_utils.c index 081a31a283..6683fff973 100644 --- a/core/app-framework/wgl/native/wgl_native_utils.c +++ b/core/app-framework/wgl/native/wgl_native_utils.c @@ -10,16 +10,15 @@ #define THROW_EXC(msg) wasm_runtime_set_exception(module_inst, msg); -uint32 wgl_native_wigdet_create(int8 widget_type, - uint32 par_obj_id, - uint32 copy_obj_id, - wasm_module_inst_t module_inst) +uint32 +wgl_native_wigdet_create(int8 widget_type, uint32 par_obj_id, + uint32 copy_obj_id, wasm_module_inst_t module_inst) { uint32 obj_id; lv_obj_t *wigdet = NULL, *par = NULL, *copy = NULL; uint32 mod_id; - //TODO: limit total widget number + // TODO: limit total widget number /* validate the parent object id if not equal to 0 */ if (par_obj_id != 0 && !wgl_native_validate_object(par_obj_id, &par)) { @@ -58,14 +57,11 @@ uint32 wgl_native_wigdet_create(int8 widget_type, return 0; } -void wgl_native_func_call(wasm_exec_env_t exec_env, - WGLNativeFuncDef *funcs, - uint32 size, - int32 func_id, - uint32 *argv, - uint32 argc) +void +wgl_native_func_call(wasm_exec_env_t exec_env, WGLNativeFuncDef *funcs, + uint32 size, int32 func_id, uint32 *argv, uint32 argc) { - typedef void (*WGLNativeFuncPtr)(wasm_exec_env_t, uint64*, uint32*); + typedef void (*WGLNativeFuncPtr)(wasm_exec_env_t, uint64 *, uint32 *); WGLNativeFuncPtr wglNativeFuncPtr; wasm_module_inst_t module_inst = get_module_inst(exec_env); WGLNativeFuncDef *func_def = funcs; @@ -74,12 +70,12 @@ void wgl_native_func_call(wasm_exec_env_t exec_env, /* Note: argv is validated in wasm_runtime_invoke_native() * with pointer length equals to 1. Here validate the argv * buffer again but with its total length in bytes */ - if (!wasm_runtime_validate_native_addr(module_inst, argv, argc * sizeof(uint32))) + if (!wasm_runtime_validate_native_addr(module_inst, argv, + argc * sizeof(uint32))) return; while (func_def < func_def_end) { - if (func_def->func_id == func_id - && (uint32)func_def->arg_num == argc) { + if (func_def->func_id == func_id && (uint32)func_def->arg_num == argc) { uint64 argv_copy_buf[16], size; uint64 *argv_copy = argv_copy_buf; int i; @@ -96,7 +92,7 @@ void wgl_native_func_call(wasm_exec_env_t exec_env, /* Init argv_copy */ for (i = 0; i < func_def->arg_num; i++) - *(uint32*)&argv_copy[i] = argv[i]; + *(uint32 *)&argv_copy[i] = argv[i]; /* Validate the first argument which is a lvgl object if needed */ if (func_def->check_obj) { @@ -128,4 +124,3 @@ void wgl_native_func_call(wasm_exec_env_t exec_env, THROW_EXC("the native widget function is not found!"); } - diff --git a/core/app-framework/wgl/native/wgl_native_utils.h b/core/app-framework/wgl/native/wgl_native_utils.h index 1150f01209..f550dcc719 100644 --- a/core/app-framework/wgl/native/wgl_native_utils.h +++ b/core/app-framework/wgl/native/wgl_native_utils.h @@ -15,21 +15,22 @@ extern "C" { #include "wasm_export.h" #include "bi-inc/wgl_shared_utils.h" -#define wgl_native_return_type(type) type *wgl_ret = (type*)(args_ret) -#define wgl_native_get_arg(type, name) type name = *((type*)(args++)) +#define wgl_native_return_type(type) type *wgl_ret = (type *)(args_ret) +#define wgl_native_get_arg(type, name) type name = *((type *)(args++)) #define wgl_native_set_return(val) *wgl_ret = (val) -#define DEFINE_WGL_NATIVE_WRAPPER(func_name) \ -static void func_name(wasm_exec_env_t exec_env, uint64 *args, uint32 *args_ret) +#define DEFINE_WGL_NATIVE_WRAPPER(func_name) \ + static void func_name(wasm_exec_env_t exec_env, uint64 *args, \ + uint32 *args_ret) enum { - WIDGET_TYPE_BTN, - WIDGET_TYPE_LABEL, - WIDGET_TYPE_CB, - WIDGET_TYPE_LIST, - WIDGET_TYPE_DDLIST, + WIDGET_TYPE_BTN, + WIDGET_TYPE_LABEL, + WIDGET_TYPE_CB, + WIDGET_TYPE_LIST, + WIDGET_TYPE_DDLIST, - _WIDGET_TYPE_NUM, + _WIDGET_TYPE_NUM, }; typedef struct WGLNativeFuncDef { @@ -46,21 +47,19 @@ typedef struct WGLNativeFuncDef { bool check_obj; } WGLNativeFuncDef; -bool wgl_native_validate_object(int32 obj_id, lv_obj_t **obj); +bool +wgl_native_validate_object(int32 obj_id, lv_obj_t **obj); -bool wgl_native_add_object(lv_obj_t *obj, uint32 module_id, uint32 *obj_id); +bool +wgl_native_add_object(lv_obj_t *obj, uint32 module_id, uint32 *obj_id); -uint32 wgl_native_wigdet_create(int8 widget_type, - uint32 par_obj_id, - uint32 copy_obj_id, - wasm_module_inst_t module_inst); +uint32 +wgl_native_wigdet_create(int8 widget_type, uint32 par_obj_id, + uint32 copy_obj_id, wasm_module_inst_t module_inst); -void wgl_native_func_call(wasm_exec_env_t exec_env, - WGLNativeFuncDef *funcs, - uint32 size, - int32 func_id, - uint32 *argv, - uint32 argc); +void +wgl_native_func_call(wasm_exec_env_t exec_env, WGLNativeFuncDef *funcs, + uint32 size, int32 func_id, uint32 *argv, uint32 argc); #ifdef __cplusplus } diff --git a/core/app-framework/wgl/native/wgl_obj_wrapper.c b/core/app-framework/wgl/native/wgl_obj_wrapper.c index 801c55d2c2..41f605b48e 100644 --- a/core/app-framework/wgl/native/wgl_obj_wrapper.c +++ b/core/app-framework/wgl/native/wgl_obj_wrapper.c @@ -10,7 +10,6 @@ #include "wgl_native_utils.h" #include "wgl.h" - typedef struct { bh_list_link l; @@ -42,24 +41,24 @@ static korp_mutex task_handler_lock; static korp_cond task_handler_cond; -static void app_mgr_object_event_callback(module_data *m_data, bh_message_t msg) +static void +app_mgr_object_event_callback(module_data *m_data, bh_message_t msg) { uint32 argv[2]; wasm_function_inst_t func_on_object_event; bh_assert(WIDGET_EVENT_WASM == bh_message_type(msg)); - wasm_data *wasm_app_data = (wasm_data*)m_data->internal_data; + wasm_data *wasm_app_data = (wasm_data *)m_data->internal_data; wasm_module_inst_t inst = wasm_app_data->wasm_module_inst; - object_event_t *object_event - = (object_event_t *)bh_message_payload(msg); + object_event_t *object_event = (object_event_t *)bh_message_payload(msg); if (object_event == NULL) return; - func_on_object_event = wasm_runtime_lookup_function(inst, "_on_widget_event", - "(i32i32)"); + func_on_object_event = + wasm_runtime_lookup_function(inst, "_on_widget_event", "(i32i32)"); if (!func_on_object_event) - func_on_object_event = wasm_runtime_lookup_function(inst, "on_widget_event", - "(i32i32)"); + func_on_object_event = + wasm_runtime_lookup_function(inst, "on_widget_event", "(i32i32)"); if (!func_on_object_event) { printf("Cannot find function on_widget_event\n"); return; @@ -71,14 +70,14 @@ static void app_mgr_object_event_callback(module_data *m_data, bh_message_t msg) 2, argv)) { const char *exception = wasm_runtime_get_exception(inst); bh_assert(exception); - printf(":Got exception running wasm code: %s\n", - exception); + printf(":Got exception running wasm code: %s\n", exception); wasm_runtime_clear_exception(inst); return; } } -static void cleanup_object_list(uint32 module_id) +static void +cleanup_object_list(uint32 module_id) { object_node_t *elem; @@ -89,8 +88,8 @@ static void cleanup_object_list(uint32 module_id) elem = (object_node_t *)bh_list_first_elem(&g_object_list); while (elem) { /* delete the leaf node belongs to the module firstly */ - if (module_id == elem->module_id && - lv_obj_count_children(elem->obj) == 0) { + if (module_id == elem->module_id + && lv_obj_count_children(elem->obj) == 0) { object_node_t *next = (object_node_t *)bh_list_elem_next(elem); found = true; @@ -98,7 +97,8 @@ static void cleanup_object_list(uint32 module_id) bh_list_remove(&g_object_list, elem); wasm_runtime_free(elem); elem = next; - } else { + } + else { elem = (object_node_t *)bh_list_elem_next(elem); } } @@ -110,7 +110,8 @@ static void cleanup_object_list(uint32 module_id) os_mutex_unlock(&g_object_list_mutex); } -static bool init_object_event_callback_framework() +static bool +init_object_event_callback_framework() { if (!wasm_register_cleanup_callback(cleanup_object_list)) { goto fail; @@ -127,7 +128,8 @@ static bool init_object_event_callback_framework() return false; } -bool wgl_native_validate_object(int32 obj_id, lv_obj_t **obj) +bool +wgl_native_validate_object(int32 obj_id, lv_obj_t **obj) { object_node_t *elem; @@ -141,7 +143,7 @@ bool wgl_native_validate_object(int32 obj_id, lv_obj_t **obj) os_mutex_unlock(&g_object_list_mutex); return true; } - elem = (object_node_t *) bh_list_elem_next(elem); + elem = (object_node_t *)bh_list_elem_next(elem); } os_mutex_unlock(&g_object_list_mutex); @@ -149,11 +151,12 @@ bool wgl_native_validate_object(int32 obj_id, lv_obj_t **obj) return false; } -bool wgl_native_add_object(lv_obj_t *obj, uint32 module_id, uint32 *obj_id) +bool +wgl_native_add_object(lv_obj_t *obj, uint32 module_id, uint32 *obj_id) { object_node_t *node; - node = (object_node_t *) wasm_runtime_malloc(sizeof(object_node_t)); + node = (object_node_t *)wasm_runtime_malloc(sizeof(object_node_t)); if (node == NULL) return false; @@ -178,11 +181,12 @@ bool wgl_native_add_object(lv_obj_t *obj, uint32 module_id, uint32 *obj_id) return true; } -static void _obj_del_recursive(lv_obj_t *obj) +static void +_obj_del_recursive(lv_obj_t *obj) { object_node_t *elem; - lv_obj_t * i; - lv_obj_t * i_next; + lv_obj_t *i; + lv_obj_t *i_next; i = lv_ll_get_head(&(obj->child_ll)); @@ -207,16 +211,17 @@ static void _obj_del_recursive(lv_obj_t *obj) os_mutex_unlock(&g_object_list_mutex); return; } - elem = (object_node_t *) bh_list_elem_next(elem); + elem = (object_node_t *)bh_list_elem_next(elem); } os_mutex_unlock(&g_object_list_mutex); } -static void _obj_clean_recursive(lv_obj_t *obj) +static void +_obj_clean_recursive(lv_obj_t *obj) { - lv_obj_t * i; - lv_obj_t * i_next; + lv_obj_t *i; + lv_obj_t *i_next; i = lv_ll_get_head(&(obj->child_ll)); @@ -232,7 +237,8 @@ static void _obj_clean_recursive(lv_obj_t *obj) } } -static void post_widget_msg_to_module(object_node_t *object_node, lv_event_t event) +static void +post_widget_msg_to_module(object_node_t *object_node, lv_event_t event) { module_data *module = module_data_list_lookup_id(object_node->module_id); object_event_t *object_event; @@ -248,13 +254,12 @@ static void post_widget_msg_to_module(object_node_t *object_node, lv_event_t eve object_event->obj_id = object_node->obj_id; object_event->event = event; - bh_post_msg(module->queue, - WIDGET_EVENT_WASM, - object_event, + bh_post_msg(module->queue, WIDGET_EVENT_WASM, object_event, sizeof(*object_event)); } -static void internal_lv_obj_event_cb(lv_obj_t *obj, lv_event_t event) +static void +internal_lv_obj_event_cb(lv_obj_t *obj, lv_event_t event) { object_node_t *elem; @@ -267,13 +272,14 @@ static void internal_lv_obj_event_cb(lv_obj_t *obj, lv_event_t event) os_mutex_unlock(&g_object_list_mutex); return; } - elem = (object_node_t *) bh_list_elem_next(elem); + elem = (object_node_t *)bh_list_elem_next(elem); } os_mutex_unlock(&g_object_list_mutex); } -static void* lv_task_handler_thread_routine (void *arg) +static void * +lv_task_handler_thread_routine(void *arg) { os_mutex_lock(&task_handler_lock); @@ -287,7 +293,8 @@ static void* lv_task_handler_thread_routine (void *arg) return NULL; } -void wgl_init(void) +void +wgl_init(void) { korp_tid tid; @@ -306,13 +313,12 @@ void wgl_init(void) init_object_event_callback_framework(); /* new a thread, call lv_task_handler periodically */ - os_thread_create(&tid, - lv_task_handler_thread_routine, - NULL, + os_thread_create(&tid, lv_task_handler_thread_routine, NULL, BH_APPLET_PRESERVED_STACK_SIZE); } -void wgl_exit(void) +void +wgl_exit(void) { lv_task_handler_thread_run = false; os_cond_destroy(&task_handler_cond); @@ -371,7 +377,8 @@ DEFINE_WGL_NATIVE_WRAPPER(lv_obj_align_wrapper) /* validate the base object id if not equal to 0 */ if (base_obj_id != 0 && !wgl_native_validate_object(base_obj_id, &base)) { - wasm_runtime_set_exception(module_inst, "align with invalid base object."); + wasm_runtime_set_exception(module_inst, + "align with invalid base object."); return; } @@ -388,24 +395,20 @@ DEFINE_WGL_NATIVE_WRAPPER(lv_obj_set_event_cb_wrapper) /* ------------------------------------------------------------------------- */ static WGLNativeFuncDef obj_native_func_defs[] = { - { OBJ_FUNC_ID_DEL, lv_obj_del_wrapper, 1, true }, - { OBJ_FUNC_ID_DEL_ASYNC, lv_obj_del_async_wrapper, 1, true }, - { OBJ_FUNC_ID_CLEAN, lv_obj_clean_wrapper, 1, true }, - { OBJ_FUNC_ID_ALIGN, lv_obj_align_wrapper, 5, true }, - { OBJ_FUNC_ID_SET_EVT_CB, lv_obj_set_event_cb_wrapper, 1, true }, + { OBJ_FUNC_ID_DEL, lv_obj_del_wrapper, 1, true }, + { OBJ_FUNC_ID_DEL_ASYNC, lv_obj_del_async_wrapper, 1, true }, + { OBJ_FUNC_ID_CLEAN, lv_obj_clean_wrapper, 1, true }, + { OBJ_FUNC_ID_ALIGN, lv_obj_align_wrapper, 5, true }, + { OBJ_FUNC_ID_SET_EVT_CB, lv_obj_set_event_cb_wrapper, 1, true }, }; /*************** Native Interface to Wasm App ***********/ void -wasm_obj_native_call(wasm_exec_env_t exec_env, - int32 func_id, uint32 *argv, uint32 argc) +wasm_obj_native_call(wasm_exec_env_t exec_env, int32 func_id, uint32 *argv, + uint32 argc) { uint32 size = sizeof(obj_native_func_defs) / sizeof(WGLNativeFuncDef); - wgl_native_func_call(exec_env, - obj_native_func_defs, - size, - func_id, - argv, + wgl_native_func_call(exec_env, obj_native_func_defs, size, func_id, argv, argc); } diff --git a/core/app-mgr/app-manager/app_manager.c b/core/app-mgr/app-manager/app_manager.c index daf5bca646..6cf88cd445 100644 --- a/core/app-mgr/app-manager/app_manager.c +++ b/core/app-mgr/app-manager/app_manager.c @@ -14,13 +14,14 @@ /* Queue of app manager */ static bh_queue *g_app_mgr_queue; -void* +void * get_app_manager_queue() { return g_app_mgr_queue; } -void app_manager_post_applets_update_event() +void +app_manager_post_applets_update_event() { module_data *m_data; attr_container_t *attr_cont; @@ -56,7 +57,8 @@ void app_manager_post_applets_update_event() char buf[32]; i++; snprintf(buf, sizeof(buf), "%s%d", "applet", i); - if (!(attr_container_set_string(&attr_cont, buf, m_data->module_name))) { + if (!(attr_container_set_string(&attr_cont, buf, + m_data->module_name))) { app_manager_printf("Post applets update event failed: " "set attr applet name key failed."); goto fail; @@ -73,7 +75,7 @@ void app_manager_post_applets_update_event() memset(&msg, 0, sizeof(msg)); msg.url = url; msg.action = COAP_EVENT; - msg.payload = (char*) attr_cont; + msg.payload = (char *)attr_cont; send_request_to_host(&msg); app_manager_printf("Post applets update event success!\n"); @@ -84,7 +86,8 @@ void app_manager_post_applets_update_event() attr_container_destroy(attr_cont); } -static int get_applets_count() +static int +get_applets_count() { module_data *m_data; int num = 0; @@ -103,7 +106,8 @@ static int get_applets_count() } /* Query fw apps info if name = NULL, otherwise query specify app */ -static bool app_manager_query_applets(request_t *msg, const char *name) +static bool +app_manager_query_applets(request_t *msg, const char *name) { module_data *m_data; attr_container_t *attr_cont; @@ -127,8 +131,8 @@ static bool app_manager_query_applets(request_t *msg, const char *name) } if (name == NULL && !(attr_container_set_int(&attr_cont, "num", num))) { - SEND_ERR_RESPONSE(msg->mid, - "Query Applets failed: set attr container key failed."); + SEND_ERR_RESPONSE( + msg->mid, "Query Applets failed: set attr container key failed."); goto fail; } @@ -140,10 +144,9 @@ static bool app_manager_query_applets(request_t *msg, const char *name) i++; snprintf(buf, sizeof(buf), "%s%d", "applet", i); if (!(attr_container_set_string(&attr_cont, buf, - m_data->module_name))) { - SEND_ERR_RESPONSE(msg->mid, - "Query Applets failed: " - "set attr container key failed."); + m_data->module_name))) { + SEND_ERR_RESPONSE(msg->mid, "Query Applets failed: " + "set attr container key failed."); goto fail; } snprintf(buf, sizeof(buf), "%s%d", "heap", i); @@ -157,13 +160,13 @@ static bool app_manager_query_applets(request_t *msg, const char *name) else if (!strcmp(name, m_data->module_name)) { found = true; if (!(attr_container_set_string(&attr_cont, "name", - m_data->module_name))) { - SEND_ERR_RESPONSE(msg->mid, - "Query Applet failed: " - "set attr container key failed."); + m_data->module_name))) { + SEND_ERR_RESPONSE(msg->mid, "Query Applet failed: " + "set attr container key failed."); goto fail; } - if (!(attr_container_set_int(&attr_cont, "heap", m_data->heap_size))) { + if (!(attr_container_set_int(&attr_cont, "heap", + m_data->heap_size))) { SEND_ERR_RESPONSE(msg->mid, "Query Applet failed: " "set attr container heap key failed."); @@ -176,15 +179,15 @@ static bool app_manager_query_applets(request_t *msg, const char *name) if (name != NULL && !found) { SEND_ERR_RESPONSE(msg->mid, - "Query Applet failed: the app is not found."); + "Query Applet failed: the app is not found."); goto fail; } len = attr_container_get_serialize_length(attr_cont); make_response_for_request(msg, response); - set_response(response, CONTENT_2_05, - FMT_ATTR_CONTAINER, (char*) attr_cont, len); + set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, (char *)attr_cont, + len); send_response_to_host(response); ret = true; @@ -197,7 +200,8 @@ static bool app_manager_query_applets(request_t *msg, const char *name) return ret; } -void applet_mgt_reqeust_handler(request_t *request, void *unused) +void +applet_mgt_reqeust_handler(request_t *request, void *unused) { bh_message_t msg; /* deep copy, but not use app self heap, but use global heap */ @@ -216,13 +220,14 @@ void applet_mgt_reqeust_handler(request_t *request, void *unused) } /* return -1 for error */ -static int get_module_type(char *kv_str) +static int +get_module_type(char *kv_str) { int module_type = -1; char type_str[16] = { 0 }; find_key_value(kv_str, strlen(kv_str), "type", type_str, - sizeof(type_str) - 1, '&'); + sizeof(type_str) - 1, '&'); if (strlen(type_str) == 0) module_type = Module_WASM_App; @@ -240,34 +245,37 @@ static int get_module_type(char *kv_str) /* Queue callback of App Manager */ -static void app_manager_queue_callback(void *message, void *arg) +static void +app_manager_queue_callback(void *message, void *arg) { - request_t *request = (request_t *) bh_message_payload((bh_message_t)message); + request_t *request = (request_t *)bh_message_payload((bh_message_t)message); int mid = request->mid, module_type, offset; (void)arg; - if ((offset = check_url_start(request->url, strlen(request->url), "/applet")) - > 0) { + if ((offset = + check_url_start(request->url, strlen(request->url), "/applet")) + > 0) { module_type = get_module_type(request->url + offset); if (module_type == -1) { SEND_ERR_RESPONSE(mid, - "Applet Management failed: invalid module type."); + "Applet Management failed: invalid module type."); goto fail; } /* Install Applet */ if (request->action == COAP_PUT) { if (get_applets_count() >= MAX_APP_INSTALLATIONS) { - SEND_ERR_RESPONSE(mid, - "Install Applet failed: exceed max app installations."); + SEND_ERR_RESPONSE( + mid, + "Install Applet failed: exceed max app installations."); goto fail; } if (!request->payload) { SEND_ERR_RESPONSE(mid, - "Install Applet failed: invalid payload."); + "Install Applet failed: invalid payload."); goto fail; } if (g_module_interfaces[module_type] @@ -280,14 +288,15 @@ static void app_manager_queue_callback(void *message, void *arg) else if (request->action == COAP_DELETE) { module_type = get_module_type(request->url + offset); if (module_type == -1) { - SEND_ERR_RESPONSE(mid, - "Uninstall Applet failed: invalid module type."); + SEND_ERR_RESPONSE( + mid, "Uninstall Applet failed: invalid module type."); goto fail; } if (g_module_interfaces[module_type] - && g_module_interfaces[module_type]->module_uninstall) { - if (!g_module_interfaces[module_type]->module_uninstall(request)) + && g_module_interfaces[module_type]->module_uninstall) { + if (!g_module_interfaces[module_type]->module_uninstall( + request)) goto fail; } } @@ -308,7 +317,8 @@ static void app_manager_queue_callback(void *message, void *arg) } /* Event Register/Unregister */ else if ((offset = check_url_start(request->url, strlen(request->url), - "/event/")) > 0) { + "/event/")) + > 0) { char url_buf[256] = { 0 }; strncpy(url_buf, request->url + offset, sizeof(url_buf) - 1); @@ -328,14 +338,14 @@ static void app_manager_queue_callback(void *message, void *arg) break; } } - } fail: return; } -static void module_interfaces_init() +static void +module_interfaces_init() { int i; for (i = 0; i < Module_Max; i++) { @@ -344,7 +354,8 @@ static void module_interfaces_init() } } -void app_manager_startup(host_interface *interface) +void +app_manager_startup(host_interface *interface) { module_interfaces_init(); @@ -390,21 +401,20 @@ void app_manager_startup(host_interface *interface) module_interface *g_module_interfaces[Module_Max] = { #if ENABLE_MODULE_JEFF != 0 - &jeff_module_interface, + &jeff_module_interface, #else - NULL, + NULL, #endif #if ENABLE_MODULE_WASM_APP != 0 - &wasm_app_module_interface, + &wasm_app_module_interface, #else - NULL, + NULL, #endif #if ENABLE_MODULE_WASM_LIB != 0 - &wasm_lib_module_interface + &wasm_lib_module_interface #else - NULL + NULL #endif }; - diff --git a/core/app-mgr/app-manager/app_manager.h b/core/app-mgr/app-manager/app_manager.h index fb2a42f71d..ce83bd170c 100644 --- a/core/app-mgr/app-manager/app_manager.h +++ b/core/app-mgr/app-manager/app_manager.h @@ -21,10 +21,11 @@ extern "C" { /* os_printf is defined in each platform */ #define app_manager_printf os_printf -#define SEND_ERR_RESPONSE(mid, err_msg) do { \ - app_manager_printf("%s\n", err_msg); \ - send_error_response_to_host(mid, INTERNAL_SERVER_ERROR_5_00, err_msg); \ -} while (0) +#define SEND_ERR_RESPONSE(mid, err_msg) \ + do { \ + app_manager_printf("%s\n", err_msg); \ + send_error_response_to_host(mid, INTERNAL_SERVER_ERROR_5_00, err_msg); \ + } while (0) extern module_interface *g_module_interfaces[Module_Max]; @@ -49,14 +50,15 @@ module_data_list_destroy(); bool app_manager_is_interrupting_module(uint32 module_type, void *module_inst); -void release_module(module_data *m_data); +void +release_module(module_data *m_data); void module_data_list_remove(module_data *m_data); -void* -app_manager_timer_create(void (*timer_callback)(void*), - watchdog_timer *wd_timer); +void * +app_manager_timer_create(void (*timer_callback)(void *), + watchdog_timer *wd_timer); void app_manager_timer_destroy(void *timer); @@ -67,18 +69,18 @@ app_manager_timer_start(void *timer, int timeout); void app_manager_timer_stop(void *timer); -watchdog_timer* +watchdog_timer * app_manager_get_wd_timer_from_timer_handle(void *timer); int app_manager_signature_verify(const uint8_t *file, unsigned int file_len, - const uint8_t *signature, unsigned int sig_size); + const uint8_t *signature, unsigned int sig_size); -void targeted_app_request_handler(request_t *request, void *unused); +void +targeted_app_request_handler(request_t *request, void *unused); #ifdef __cplusplus } /* end of extern "C" */ #endif #endif - diff --git a/core/app-mgr/app-manager/app_manager_host.c b/core/app-mgr/app-manager/app_manager_host.c index c7429da2a8..6b1c3ba457 100644 --- a/core/app-mgr/app-manager/app_manager_host.c +++ b/core/app-mgr/app-manager/app_manager_host.c @@ -13,10 +13,7 @@ static host_interface host_commu; /* IMRTLink Two leading bytes */ -static unsigned char leadings[] = { - (unsigned char)0x12, - (unsigned char)0x34 -}; +static unsigned char leadings[] = { (unsigned char)0x12, (unsigned char)0x34 }; /* IMRTLink Receiving Phase */ typedef enum recv_phase_t { @@ -43,14 +40,16 @@ static korp_mutex host_lock; static bool enable_log = false; -static bool is_little_endian() +static bool +is_little_endian() { long i = 0x01020304; - unsigned char* c = (unsigned char*) &i; + unsigned char *c = (unsigned char *)&i; return (*c == 0x04) ? true : false; } -static void exchange32(uint8* pData) +static void +exchange32(uint8 *pData) { uint8 value = *pData; *pData = *(pData + 3); @@ -65,7 +64,8 @@ static void exchange32(uint8* pData) * 1: complete message received * 0: incomplete message received */ -static int on_imrt_link_byte_arrive(unsigned char ch, recv_context_t *ctx) +static int +on_imrt_link_byte_arrive(unsigned char ch, recv_context_t *ctx) { if (ctx->phase == Phase_Non_Start) { ctx->message.payload_size = 0; @@ -88,7 +88,8 @@ static int on_imrt_link_byte_arrive(unsigned char ch, recv_context_t *ctx) if (enable_log) app_manager_printf("##On byte arrive: got leading 1\n"); ctx->phase = Phase_Type; - } else + } + else ctx->phase = Phase_Non_Start; return 0; @@ -111,7 +112,7 @@ static int on_imrt_link_byte_arrive(unsigned char ch, recv_context_t *ctx) return 0; } else if (ctx->phase == Phase_Size) { - unsigned char *p = (unsigned char *) &ctx->message.payload_size; + unsigned char *p = (unsigned char *)&ctx->message.payload_size; if (enable_log) app_manager_printf("##On byte arrive: got payload_size, byte %d\n", @@ -141,7 +142,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 *) APP_MGR_MALLOC(ctx->message.payload_size); + (char *)APP_MGR_MALLOC(ctx->message.payload_size); if (!ctx->message.payload) { ctx->phase = Phase_Non_Start; return 0; @@ -158,7 +159,7 @@ static int on_imrt_link_byte_arrive(unsigned char ch, recv_context_t *ctx) if (ctx->message.message_type == INSTALL_WASM_APP) { int received_size; module_on_install_request_byte_arrive_func module_on_install = - g_module_interfaces[Module_WASM_App]->module_on_install; + g_module_interfaces[Module_WASM_App]->module_on_install; ctx->size_in_phase++; @@ -216,7 +217,8 @@ static int on_imrt_link_byte_arrive(unsigned char ch, recv_context_t *ctx) return 0; } -int aee_host_msg_callback(void *msg, uint32_t msg_len) +int +aee_host_msg_callback(void *msg, uint32_t msg_len) { unsigned char *p = msg, *p_end = p + msg_len; @@ -234,7 +236,8 @@ int aee_host_msg_callback(void *msg, uint32_t msg_len) memset(&request, 0, sizeof(request)); if (!unpack_request(recv_ctx.message.payload, - recv_ctx.message.payload_size, &request)) + recv_ctx.message.payload_size, + &request)) continue; request.sender = ID_HOST; @@ -242,7 +245,8 @@ int aee_host_msg_callback(void *msg, uint32_t msg_len) am_dispatch_request(&request); } else { - app_manager_printf("unexpected host msg type: %d\n", msg_type); + app_manager_printf("unexpected host msg type: %d\n", + msg_type); } APP_MGR_FREE(recv_ctx.message.payload); @@ -257,7 +261,8 @@ int aee_host_msg_callback(void *msg, uint32_t msg_len) return 0; } -bool app_manager_host_init(host_interface *interface) +bool +app_manager_host_init(host_interface *interface) { os_mutex_init(&host_lock); memset(&recv_ctx, 0, sizeof(recv_ctx)); @@ -267,12 +272,13 @@ bool app_manager_host_init(host_interface *interface) host_commu.destroy = interface->destroy; if (host_commu.init != NULL) - return host_commu.init(); + return host_commu.init(); return true; } -int app_manager_host_send_msg(int msg_type, const char *buf, int size) +int +app_manager_host_send_msg(int msg_type, const char *buf, int size) { /* send an IMRT LINK message contains the buf as payload */ if (host_commu.send != NULL) { @@ -285,11 +291,11 @@ int app_manager_host_send_msg(int msg_type, const char *buf, int size) /* message type */ /* TODO: check if use network byte order!!! */ - *((uint16*)(header + 2)) = htons(msg_type); + *((uint16 *)(header + 2)) = htons(msg_type); /* payload length */ if (is_little_endian()) - exchange32((uint8*) &size_s); + exchange32((uint8 *)&size_s); bh_memcpy_s(header + 4, 4, &size_s, 4); n = host_commu.send(NULL, header, 8); diff --git a/core/app-mgr/app-manager/app_manager_host.h b/core/app-mgr/app-manager/app_manager_host.h index cc663725be..b19404f910 100644 --- a/core/app-mgr/app-manager/app_manager_host.h +++ b/core/app-mgr/app-manager/app_manager_host.h @@ -12,7 +12,7 @@ extern "C" { #endif -#define HOST_MODE_AON 1 +#define HOST_MODE_AON 1 #define HOST_MODE_UART 2 #define HOST_MODE_TEST 3 @@ -21,4 +21,3 @@ extern "C" { #endif #endif - diff --git a/core/app-mgr/app-manager/ble_msg.c b/core/app-mgr/app-manager/ble_msg.c index 179eb78ba4..1d19dddaf9 100644 --- a/core/app-mgr/app-manager/ble_msg.c +++ b/core/app-mgr/app-manager/ble_msg.c @@ -5,7 +5,7 @@ #if 0 -#define BLUETOOTH_INTERFACE_ADVERTISMENT_DATA_LENGTH 31 +#define BLUETOOTH_INTERFACE_ADVERTISMENT_DATA_LENGTH 31 /* ble_device_info */ typedef struct ble_device_info { diff --git a/core/app-mgr/app-manager/event.c b/core/app-mgr/app-manager/event.c index f2c49dfd03..a21065fab2 100644 --- a/core/app-mgr/app-manager/event.c +++ b/core/app-mgr/app-manager/event.c @@ -11,25 +11,26 @@ #include "coap_ext.h" typedef struct _subscribe { - struct _subscribe * next; + struct _subscribe *next; uint32 subscriber_id; } subscribe_t; typedef struct _event { struct _event *next; int subscriber_size; - subscribe_t * subscribers; + subscribe_t *subscribers; char url[1]; /* event url */ } event_reg_t; event_reg_t *g_events = NULL; -static bool find_subscriber(event_reg_t * reg, uint32 id, bool remove_found) +static bool +find_subscriber(event_reg_t *reg, uint32 id, bool remove_found) { - subscribe_t* c = reg->subscribers; - subscribe_t * prev = NULL; + subscribe_t *c = reg->subscribers; + subscribe_t *prev = NULL; while (c) { - subscribe_t * next = c->next; + subscribe_t *next = c->next; if (c->subscriber_id == id) { if (remove_found) { if (prev) @@ -41,7 +42,8 @@ static bool find_subscriber(event_reg_t * reg, uint32 id, bool remove_found) } return true; - } else { + } + else { prev = c; c = next; } @@ -50,7 +52,8 @@ static bool find_subscriber(event_reg_t * reg, uint32 id, bool remove_found) return false; } -static bool check_url(const char *url) +static bool +check_url(const char *url) { if (*url == 0) return false; @@ -58,7 +61,8 @@ static bool check_url(const char *url) return true; } -bool am_register_event(const char *url, uint32_t reg_client) +bool +am_register_event(const char *url, uint32_t reg_client) { event_reg_t *current = g_events; @@ -76,8 +80,8 @@ bool am_register_event(const char *url, uint32_t reg_client) if (current == NULL) { if (NULL - == (current = (event_reg_t *) APP_MGR_MALLOC( - offsetof(event_reg_t, url) + strlen(url) + 1))) { + == (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; } @@ -90,8 +94,9 @@ 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*) APP_MGR_MALLOC(sizeof(subscribe_t)); + } + else { + subscribe_t *s = (subscribe_t *)APP_MGR_MALLOC(sizeof(subscribe_t)); if (s == NULL) return false; @@ -100,29 +105,30 @@ bool am_register_event(const char *url, uint32_t reg_client) s->next = current->subscribers; current->subscribers = s; app_manager_printf("client: %d registered event (%s)\n", reg_client, - url); + url); } return true; } // @url: NULL means the client wants to unregister all its subscribed items -bool am_unregister_event(const char *url, uint32_t reg_client) +bool +am_unregister_event(const char *url, uint32_t reg_client) { event_reg_t *current = g_events, *pre = NULL; while (current != NULL) { if (url == NULL || strcmp(current->url, url) == 0) { - event_reg_t * next = current->next; + event_reg_t *next = current->next; if (find_subscriber(current, reg_client, true)) { app_manager_printf("client: %d deregistered event (%s)\n", - reg_client, current->url); + reg_client, current->url); } // remove the registration if no client subscribe it if (current->subscribers == NULL) { app_manager_printf("unregister for event deleted url:(%s)\n", - current->url); + current->url); if (pre) pre->next = next; else @@ -139,33 +145,38 @@ bool am_unregister_event(const char *url, uint32_t reg_client) return true; } -bool event_handle_event_request(uint8_t code, const char *event_url, - uint32_t reg_client) +bool +event_handle_event_request(uint8_t code, const char *event_url, + uint32_t reg_client) { if (code == COAP_PUT) { /* register */ return am_register_event(event_url, reg_client); - } else if (code == COAP_DELETE) { /* unregister */ + } + else if (code == COAP_DELETE) { /* unregister */ return am_unregister_event(event_url, reg_client); - } else { + } + else { /* invalid request */ return false; } } -void am_publish_event(request_t * event) +void +am_publish_event(request_t *event) { bh_assert(event->action == COAP_EVENT); event_reg_t *current = g_events; while (current) { if (0 == strcmp(event->url, current->url)) { - subscribe_t* c = current->subscribers; + subscribe_t *c = current->subscribers; while (c) { if (c->subscriber_id == ID_HOST) { send_request_to_host(event); - } else { - module_request_handler - (event, (void *)(uintptr_t)c->subscriber_id); + } + else { + module_request_handler(event, + (void *)(uintptr_t)c->subscriber_id); } c = c->next; } @@ -177,7 +188,8 @@ void am_publish_event(request_t * event) } } -bool event_is_registered(const char *event_url) +bool +event_is_registered(const char *event_url) { event_reg_t *current = g_events; diff --git a/core/app-mgr/app-manager/event.h b/core/app-mgr/app-manager/event.h index a9c3de3b2f..36ced521d4 100644 --- a/core/app-mgr/app-manager/event.h +++ b/core/app-mgr/app-manager/event.h @@ -22,7 +22,7 @@ extern "C" { */ bool event_handle_event_request(uint8_t code, const char *event_url, - uint32_t register); + uint32_t register); /** * Test whether the event is registered diff --git a/core/app-mgr/app-manager/message.c b/core/app-mgr/app-manager/message.c index e9c594ec2d..aac7a23647 100644 --- a/core/app-mgr/app-manager/message.c +++ b/core/app-mgr/app-manager/message.c @@ -26,7 +26,8 @@ bool send_coap_packet_to_host(coap_packet_t * packet) } #endif -bool send_request_to_host(request_t *msg) +bool +send_request_to_host(request_t *msg) { if (COAP_EVENT == msg->action && !event_is_registered(msg->url)) { app_manager_printf("Event is not registered\n"); @@ -34,7 +35,7 @@ bool send_request_to_host(request_t *msg) } int size; - char * packet = pack_request(msg, &size); + char *packet = pack_request(msg, &size); if (packet == NULL) return false; @@ -45,10 +46,11 @@ bool send_request_to_host(request_t *msg) return true; } -bool send_response_to_host(response_t *response) +bool +send_response_to_host(response_t *response) { int size; - char * packet = pack_response(response, &size); + char *packet = pack_response(response, &size); if (packet == NULL) return false; @@ -59,7 +61,8 @@ bool send_response_to_host(response_t *response) return true; } -bool send_error_response_to_host(int mid, int status, const char *msg) +bool +send_error_response_to_host(int mid, int status, const char *msg) { int payload_len = 0; attr_container_t *payload = NULL; @@ -73,8 +76,8 @@ bool send_error_response_to_host(int mid, int status, const char *msg) } } - set_response(response, status, FMT_ATTR_CONTAINER, - (const char *)payload, payload_len); + set_response(response, status, FMT_ATTR_CONTAINER, (const char *)payload, + payload_len); response->mid = mid; send_response_to_host(response); @@ -83,4 +86,3 @@ bool send_error_response_to_host(int mid, int status, const char *msg) attr_container_destroy(payload); return true; } - diff --git a/core/app-mgr/app-manager/module_jeff.c b/core/app-mgr/app-manager/module_jeff.c index 7e1a8be34e..7c7f9510d1 100644 --- a/core/app-mgr/app-manager/module_jeff.c +++ b/core/app-mgr/app-manager/module_jeff.c @@ -45,7 +45,7 @@ typedef struct jeff_applet_data { JeffFileHeaderLinked *main_file; /* Permissions of the Java Applet */ char *perms; -}jeff_applet_data; +} jeff_applet_data; /* Jeff class com.intel.aee.AEEApplet */ static JeffClassHeaderLinked *class_AEEApplet; @@ -113,9 +113,8 @@ app_manager_get_tool_agent_queue() static bool is_tool_agent_running(module_data *m_data) { - jeff_applet_data *applet_data = (jeff_applet_data*)m_data->internal_data; - return (applet_data->debug_mode - && applet_data->tool_agent_queue + jeff_applet_data *applet_data = (jeff_applet_data *)m_data->internal_data; + return (applet_data->debug_mode && applet_data->tool_agent_queue && applet_data->vm_instance->tool_agent); } #endif @@ -123,12 +122,12 @@ is_tool_agent_running(module_data *m_data) static char * get_class_qname(const JeffString *pname, const JeffString *cname) { - unsigned int length = pname->length ? pname->length + 2 + cname->length - : cname->length + 1; + unsigned int length = + pname->length ? pname->length + 2 + cname->length : cname->length + 1; char *buf = APP_MGR_MALLOC(length), *p; if (!buf) - return NULL; + return NULL; p = buf; if (pname->length) { @@ -159,8 +158,8 @@ send_exception_event_to_host(const char *applet_name, const char *exc_name) } if (!attr_container_set_string(&payload, "exception name", exc_name) - || !attr_container_set_string(&payload, "stack trace", "TODO") - || !attr_container_set_string(&payload, "applet name", applet_name)) { + || !attr_container_set_string(&payload, "stack trace", "TODO") + || !attr_container_set_string(&payload, "applet name", applet_name)) { app_manager_printf("Send exception to host fail: set attr"); goto fail; } @@ -184,7 +183,7 @@ send_exception_event_to_host(const char *applet_name, const char *exc_name) APP_MGR_FREE(url); - fail: +fail: attr_container_destroy(payload); } @@ -193,1541 +192,1692 @@ check_exception() { if (jeff_runtime_get_exception()) { jeff_printf("V1.Exception thrown when running applet '%s':\n", - app_manager_get_module_name(Module_Jeff)); + app_manager_get_module_name(Module_Jeff)); jeff_runtime_print_exception(); jeff_printf("\n"); jeff_printf(NULL); + } - if (!app_manager_is_interrupting_module(Module_Jeff)) { - attr_container_t *payload; - int payload_len; - JeffClassHeaderLinked *exc_class = jeff_object_class_pointer(jeff_runtime_get_exception()); - char *qname_buf = get_class_qname(jeff_get_class_pname(exc_class), - jeff_get_class_cname(exc_class)); - - /* Send exception event to host */ - if (qname_buf) { - send_exception_event_to_host(app_manager_get_module_name(Module_Jeff), qname_buf); - APP_MGR_FREE(qname_buf); - } - - /* Uninstall the applet */ - if ((payload = attr_container_create("uninstall myself"))) { - if (attr_container_set_string(&payload, "name", app_manager_get_module_name(Module_Jeff)) - /* Set special flag to prevent app manager making response since this is an internal message */ - && attr_container_set_bool(&payload, "do not reply me", true)) { - request_t request = {0}; - payload_len = attr_container_get_serialize_length(payload); + if (!app_manager_is_interrupting_module(Module_Jeff)) { + attr_container_t *payload; + int payload_len; + JeffClassHeaderLinked *exc_class = + jeff_object_class_pointer(jeff_runtime_get_exception()); + char *qname_buf = get_class_qname(jeff_get_class_pname(exc_class), + jeff_get_class_cname(exc_class)); + + /* Send exception event to host */ + if (qname_buf) { + send_exception_event_to_host( + app_manager_get_module_name(Module_Jeff), qname_buf); + APP_MGR_FREE(qname_buf); + } + + /* Uninstall the applet */ + if ((payload = attr_container_create("uninstall myself"))) { + if (attr_container_set_string( + &payload, "name", app_manager_get_module_name(Module_Jeff)) + /* Set special flag to prevent app manager making response + since this is an internal message */ + && attr_container_set_bool(&payload, "do not reply me", true)) { + request_t request = { 0 }; + payload_len = attr_container_get_serialize_length(payload); init_request(request, "/applet", COAP_DELETE, (char *)payload, payload_len)); app_mgr_lookup_resource(&request); // TODO: confirm this is right attr_container_destroy(payload); - } } - - jeff_runtime_set_exception(NULL); - return true; } - return false; + jeff_runtime_set_exception(NULL); + return true; } - static bool - app_manager_initialize_class(JeffClassHeaderLinked *c) - { - jeff_runtime_initialize_class(c); - return !check_exception(); - } + return false; +} - static bool - app_manager_initialize_object(JeffObjectRef obj) - { - jeff_runtime_initialize_object(obj); - return !check_exception(); - } +static bool +app_manager_initialize_class(JeffClassHeaderLinked *c) +{ + jeff_runtime_initialize_class(c); + return !check_exception(); +} + +static bool +app_manager_initialize_object(JeffObjectRef obj) +{ + jeff_runtime_initialize_object(obj); + return !check_exception(); +} - static bool - app_manager_call_java(JeffMethodLinked *method, - unsigned int argc, uint32 argv[], uint8 argt[]) - { - module_data *m_data = app_manager_get_module_data(Module_Jeff); - watchdog_timer *wd_timer = &m_data->wd_timer; - bool is_wd_started = false; +static bool +app_manager_call_java(JeffMethodLinked *method, unsigned int argc, + uint32 argv[], uint8 argt[]) +{ + module_data *m_data = app_manager_get_module_data(Module_Jeff); + watchdog_timer *wd_timer = &m_data->wd_timer; + bool is_wd_started = false; #if BEIHAI_ENABLE_TOOL_AGENT != 0 - /* Only start watchdog when debugger is not running */ - if (!is_tool_agent_running(m_data)) { + /* Only start watchdog when debugger is not running */ + if (!is_tool_agent_running(m_data)) { #endif - watchdog_timer_start(wd_timer); - is_wd_started = true; + watchdog_timer_start(wd_timer); + is_wd_started = true; #if BEIHAI_ENABLE_TOOL_AGENT != 0 - } + } #endif - jeff_runtime_call_java(method, argc, argv, argt); + jeff_runtime_call_java(method, argc, argv, argt); - if (is_wd_started) { - os_mutex_lock(&wd_timer->lock); - if (!wd_timer->is_interrupting) { - wd_timer->is_stopped = true; - watchdog_timer_stop(wd_timer); - } - os_mutex_unlock(&wd_timer->lock); + if (is_wd_started) { + os_mutex_lock(&wd_timer->lock); + if (!wd_timer->is_interrupting) { + wd_timer->is_stopped = true; + watchdog_timer_stop(wd_timer); } - - return !check_exception(); + os_mutex_unlock(&wd_timer->lock); } - static AEEBLEDevice - create_object_BLEDevice(ble_device_info *dev_info) - { - JeffLocalObjectRef ref; - AEEBLEDevice dev_struct; - - jeff_runtime_push_local_object_ref(&ref); - - ref.val = jeff_runtime_new_object(class_BLEDevice); + return !check_exception(); +} - if (!ref.val) { - jeff_runtime_pop_local_object_ref(1); - return NULL; - } +static AEEBLEDevice +create_object_BLEDevice(ble_device_info *dev_info) +{ + JeffLocalObjectRef ref; + AEEBLEDevice dev_struct; - dev_struct = (AEEBLEDevice) (ref.val); - dev_struct->rssi = dev_info->rssi; - dev_struct->mac = (jbyteArray) jeff_runtime_create_byte_array((int8 *)dev_info->mac, 6); + jeff_runtime_push_local_object_ref(&ref); - app_manager_printf("adv_data_len:%d,scan_response_len:%d\n", dev_info->adv_data_len, dev_info->scan_response_len); + ref.val = jeff_runtime_new_object(class_BLEDevice); - dev_struct->advData = (jbyteArray) jeff_runtime_create_byte_array((int8 *)dev_info->adv_data, dev_info->adv_data_len); - dev_struct->scanResponse = (jbyteArray) jeff_runtime_create_byte_array((int8 *)dev_info->scan_response, dev_info->scan_response_len); - dev_struct->addressType = dev_info->address_type; - jeff_runtime_initialize_object(ref.val); + if (!ref.val) { jeff_runtime_pop_local_object_ref(1); - if ((dev_struct->mac == NULL) || (dev_struct->advData == NULL) || (dev_struct->scanResponse == NULL)) { - return NULL; - } - return (AEEBLEDevice) ref.val; + return NULL; } - static void - app_instance_process_ble_msg(char *msg) - { - bh_queue_ble_sub_msg_t *ble_msg = (bh_queue_ble_sub_msg_t *)msg; - unsigned int argv[5]; - uint8 argt[5]; - - ble_device_info *dev_info; - - dev_info = (ble_device_info *) ble_msg->payload; - AEEBLEDevice ble_dev; + dev_struct = (AEEBLEDevice)(ref.val); + dev_struct->rssi = dev_info->rssi; + dev_struct->mac = + (jbyteArray)jeff_runtime_create_byte_array((int8 *)dev_info->mac, 6); + + app_manager_printf("adv_data_len:%d,scan_response_len:%d\n", + dev_info->adv_data_len, dev_info->scan_response_len); + + dev_struct->advData = (jbyteArray)jeff_runtime_create_byte_array( + (int8 *)dev_info->adv_data, dev_info->adv_data_len); + dev_struct->scanResponse = (jbyteArray)jeff_runtime_create_byte_array( + (int8 *)dev_info->scan_response, dev_info->scan_response_len); + dev_struct->addressType = dev_info->address_type; + jeff_runtime_initialize_object(ref.val); + jeff_runtime_pop_local_object_ref(1); + if ((dev_struct->mac == NULL) || (dev_struct->advData == NULL) + || (dev_struct->scanResponse == NULL)) { + return NULL; + } + return (AEEBLEDevice)ref.val; +} - argv[0] = (unsigned int) (jbyteArray) jeff_runtime_create_byte_array((int8 *)dev_info->mac, 6); - argt[0] = 1; - if (!app_manager_call_java(method_callOnBLEManagerGetBLEDevice, 1, argv, argt)) { - app_manager_printf("app_manager_call_java BLEManagerGetBLEDevice fail error\n"); +static void +app_instance_process_ble_msg(char *msg) +{ + bh_queue_ble_sub_msg_t *ble_msg = (bh_queue_ble_sub_msg_t *)msg; + unsigned int argv[5]; + uint8 argt[5]; + + ble_device_info *dev_info; + + dev_info = (ble_device_info *)ble_msg->payload; + AEEBLEDevice ble_dev; + + argv[0] = (unsigned int)(jbyteArray)jeff_runtime_create_byte_array( + (int8 *)dev_info->mac, 6); + argt[0] = 1; + if (!app_manager_call_java(method_callOnBLEManagerGetBLEDevice, 1, argv, + argt)) { + app_manager_printf( + "app_manager_call_java BLEManagerGetBLEDevice fail error\n"); + goto fail; + } + ble_dev = (AEEBLEDevice)argv[0]; + if (ble_dev == NULL) { + ble_dev = create_object_BLEDevice(dev_info); + if (ble_dev == NULL) { goto fail; } - ble_dev = (AEEBLEDevice) argv[0]; - if (ble_dev == NULL) { - ble_dev = create_object_BLEDevice(dev_info); - if (ble_dev == NULL) { + } + + switch (ble_msg->type) { + case BLE_SUB_EVENT_DISCOVERY: + { + argv[0] = (unsigned int)ble_dev; + argt[0] = 1; + ble_dev->rssi = dev_info->rssi; + if (!app_manager_call_java(method_callOnBLEStartDiscovery, 1, argv, + argt)) { + app_manager_printf( + "app_manager_call_java method_callOnBLEStartDiscovery " + "fail error\n"); goto fail; } + break; } - switch (ble_msg->type) { - case BLE_SUB_EVENT_DISCOVERY: - { - argv[0] = (unsigned int) ble_dev; + case BLE_SUB_EVENT_CONNECTED: + { + if (ble_dev) { + argv[0] = (unsigned int)ble_dev; + argv[1] = 0; argt[0] = 1; - ble_dev->rssi = dev_info->rssi; - if (!app_manager_call_java(method_callOnBLEStartDiscovery, 1, argv, argt)) { - app_manager_printf("app_manager_call_java method_callOnBLEStartDiscovery fail error\n"); + argt[1] = 1; + if (!app_manager_call_java(method_callOnBLEConnected, 2, argv, + argt)) { + app_manager_printf( + "app_manager_call_java method_callOnBLEConnected " + "fail error\n"); goto fail; } } break; + } - case BLE_SUB_EVENT_CONNECTED: - { - if (ble_dev) { - argv[0] = (unsigned int) ble_dev; - argv[1] = 0; - argt[0] = 1; - argt[1] = 1; - if (!app_manager_call_java(method_callOnBLEConnected, 2, argv, argt)) { - app_manager_printf("app_manager_call_java method_callOnBLEConnected fail error\n"); - goto fail; - } - } - } - break; - - case BLE_SUB_EVENT_DISCONNECTED: - { - app_manager_printf("app instance received disconnected\n"); + case BLE_SUB_EVENT_DISCONNECTED: + { + app_manager_printf("app instance received disconnected\n"); - if (ble_dev) { - argv[0] = (unsigned int) ble_dev; - argv[1] = 0; - argt[0] = 1; - argt[1] = 1; - ble_dev->rssi = dev_info->rssi; - if (!app_manager_call_java(method_callOnBLEDisconnected, 2, argv, argt)) { - app_manager_printf("app_manager_call_java method_callOnBLEDisconnected fail error\n"); - goto fail; - } + if (ble_dev) { + argv[0] = (unsigned int)ble_dev; + argv[1] = 0; + argt[0] = 1; + argt[1] = 1; + ble_dev->rssi = dev_info->rssi; + if (!app_manager_call_java(method_callOnBLEDisconnected, 2, + argv, argt)) { + app_manager_printf( + "app_manager_call_java " + "method_callOnBLEDisconnected fail error\n"); + goto fail; } } break; + } - case BLE_SUB_EVENT_NOTIFICATION: - { - if (ble_dev) { - argv[0] = (unsigned int) ble_dev; - argv[1] = (unsigned int) (jbyteArray) jeff_runtime_create_byte_array( - (int8 *)dev_info->private_data, dev_info->private_data_length); - argv[2] = dev_info->value_handle; - argv[3] = dev_info->ccc_handle; - argt[1] = 1; - argt[2] = 0; - argt[3] = 0; - ble_dev->rssi = dev_info->rssi; - if (!app_manager_call_java(method_callOnBLENotification, 4, argv, argt)) { - app_manager_printf("app_manager_call_java method_callOnBLENotification fail error\n"); - goto fail; - } + case BLE_SUB_EVENT_NOTIFICATION: + { + if (ble_dev) { + argv[0] = (unsigned int)ble_dev; + argv[1] = + (unsigned int)(jbyteArray)jeff_runtime_create_byte_array( + (int8 *)dev_info->private_data, + dev_info->private_data_length); + argv[2] = dev_info->value_handle; + argv[3] = dev_info->ccc_handle; + argt[1] = 1; + argt[2] = 0; + argt[3] = 0; + ble_dev->rssi = dev_info->rssi; + if (!app_manager_call_java(method_callOnBLENotification, 4, + argv, argt)) { + app_manager_printf( + "app_manager_call_java " + "method_callOnBLENotification fail error\n"); + goto fail; } } break; + } - case BLE_SUB_EVENT_INDICATION: - { - if (ble_dev) { - argv[0] = (unsigned int) ble_dev; - argv[1] = (unsigned int) (jbyteArray) jeff_runtime_create_byte_array( - (int8 *)dev_info->private_data, dev_info->private_data_length); - argv[2] = dev_info->value_handle; - argv[3] = dev_info->ccc_handle; - argt[0] = 1; - argt[1] = 1; - argt[2] = 0; - argt[3] = 0; - ble_dev->rssi = dev_info->rssi; - if (!app_manager_call_java(method_callOnBLEIndication, 4, argv, argt)) { - app_manager_printf("app_manager_call_java method_callOnBLEIndication fail error\n"); - goto fail; - } + case BLE_SUB_EVENT_INDICATION: + { + if (ble_dev) { + argv[0] = (unsigned int)ble_dev; + argv[1] = + (unsigned int)(jbyteArray)jeff_runtime_create_byte_array( + (int8 *)dev_info->private_data, + dev_info->private_data_length); + argv[2] = dev_info->value_handle; + argv[3] = dev_info->ccc_handle; + argt[0] = 1; + argt[1] = 1; + argt[2] = 0; + argt[3] = 0; + ble_dev->rssi = dev_info->rssi; + if (!app_manager_call_java(method_callOnBLEIndication, 4, argv, + argt)) { + app_manager_printf( + "app_manager_call_java method_callOnBLEIndication " + "fail error\n"); + goto fail; } } break; + } - case BLE_SUB_EVENT_PASSKEYENTRY: - { + case BLE_SUB_EVENT_PASSKEYENTRY: + { - if (ble_dev) { - argv[0] = (unsigned int) ble_dev; - argt[0] = 1; - argt[1] = 1; - ble_dev->rssi = dev_info->rssi; - if (!app_manager_call_java(method_callOnBLEPasskeyEntry, 1, argv, argt)) { - app_manager_printf("app_manager_call_java method_callOnBLEPasskeyEntry fail error\n"); - goto fail; - } + if (ble_dev) { + argv[0] = (unsigned int)ble_dev; + argt[0] = 1; + argt[1] = 1; + ble_dev->rssi = dev_info->rssi; + if (!app_manager_call_java(method_callOnBLEPasskeyEntry, 1, + argv, argt)) { + app_manager_printf( + "app_manager_call_java " + "method_callOnBLEPasskeyEntry fail error\n"); + goto fail; } } break; + } - case BLE_SUB_EVENT_SECURITY_LEVEL_CHANGE: - { - if (ble_dev) { - ble_dev->securityLevel = dev_info->security_level; - } + case BLE_SUB_EVENT_SECURITY_LEVEL_CHANGE: + { + if (ble_dev) { + ble_dev->securityLevel = dev_info->security_level; } break; - - default: - break; } - fail: - if (dev_info->scan_response != NULL) { - APP_MGR_FREE(dev_info->scan_response); - } - if (dev_info->private_data != NULL) { - APP_MGR_FREE(dev_info->private_data); - } + default: + break; + } - if (dev_info->adv_data != NULL) { - APP_MGR_FREE(dev_info->adv_data); - } - if (dev_info != NULL) { - APP_MGR_FREE(dev_info); - } +fail: + if (dev_info->scan_response != NULL) { + APP_MGR_FREE(dev_info->scan_response); + } + if (dev_info->private_data != NULL) { + APP_MGR_FREE(dev_info->private_data); + } + if (dev_info->adv_data != NULL) { + APP_MGR_FREE(dev_info->adv_data); + } + if (dev_info != NULL) { + APP_MGR_FREE(dev_info); } +} - static void - app_instance_free_ble_msg(char *msg) - { - bh_queue_ble_sub_msg_t *ble_msg = (bh_queue_ble_sub_msg_t *)msg; - ble_device_info *dev_info; +static void +app_instance_free_ble_msg(char *msg) +{ + bh_queue_ble_sub_msg_t *ble_msg = (bh_queue_ble_sub_msg_t *)msg; + ble_device_info *dev_info; - dev_info = (ble_device_info *) ble_msg->payload; + dev_info = (ble_device_info *)ble_msg->payload; - if (dev_info->scan_response != NULL) + if (dev_info->scan_response != NULL) APP_MGR_FREE(dev_info->scan_response); - if (dev_info->private_data != NULL) + if (dev_info->private_data != NULL) APP_MGR_FREE(dev_info->private_data); - if (dev_info->adv_data != NULL) + if (dev_info->adv_data != NULL) APP_MGR_FREE(dev_info->adv_data); - if (dev_info != NULL) + if (dev_info != NULL) APP_MGR_FREE(dev_info); - } - - static void - app_instance_queue_free_callback(void *queue_msg) - { - bh_queue_msg_t *msg = (bh_queue_msg_t *)queue_msg; +} - switch (msg->message_type) { - case APPLET_REQUEST: - { - bh_request_msg_t *req_msg = (bh_request_msg_t *)msg->payload; - APP_MGR_FREE(req_msg); - break; - } +static void +app_instance_queue_free_callback(void *queue_msg) +{ + bh_queue_msg_t *msg = (bh_queue_msg_t *)queue_msg; - case TIMER_EVENT: - { - break; - } + switch (msg->message_type) { + case APPLET_REQUEST: + { + bh_request_msg_t *req_msg = (bh_request_msg_t *)msg->payload; + APP_MGR_FREE(req_msg); + break; + } - case SENSOR_EVENT: - { - if (msg->payload) { - bh_sensor_event_t *sensor_event = (bh_sensor_event_t *)msg->payload; - attr_container_t *event = sensor_event->event; + case TIMER_EVENT: + { + break; + } - attr_container_destroy(event); - APP_MGR_FREE(sensor_event); - } - break; - } + case SENSOR_EVENT: + { + if (msg->payload) { + bh_sensor_event_t *sensor_event = + (bh_sensor_event_t *)msg->payload; + attr_container_t *event = sensor_event->event; - case BLE_EVENT: - { - if (msg->payload) { - app_instance_free_ble_msg(msg->payload); - APP_MGR_FREE(msg->payload); - } - break; + attr_container_destroy(event); + APP_MGR_FREE(sensor_event); } + break; + } - case GPIO_INTERRUPT_EVENT: - { - break; + case BLE_EVENT: + { + if (msg->payload) { + app_instance_free_ble_msg(msg->payload); + APP_MGR_FREE(msg->payload); } + break; + } - default: - { - break; - } + case GPIO_INTERRUPT_EVENT: + { + break; } - APP_MGR_FREE(msg); + default: + { + break; + } } - static void - app_instance_queue_callback(void *queue_msg) - { - bh_queue_msg_t *msg = (bh_queue_msg_t *)queue_msg; - unsigned int argv[5]; - uint8 argt[5]; + APP_MGR_FREE(msg); +} - if (app_manager_is_interrupting_module(Module_Jeff)) { - app_instance_queue_free_callback(queue_msg); - return; - } +static void +app_instance_queue_callback(void *queue_msg) +{ + bh_queue_msg_t *msg = (bh_queue_msg_t *)queue_msg; + unsigned int argv[5]; + uint8 argt[5]; - switch (msg->message_type) { - case APPLET_REQUEST: - { - JeffLocalObjectRef ref; - AEERequest req_obj; - bh_request_msg_t *req_msg = (bh_request_msg_t *)msg->payload; - attr_container_t *attr_cont = (attr_container_t *)req_msg->payload; - module_data *m_data = app_manager_get_module_data(Module_Jeff); - jeff_applet_data *applet_data = (jeff_applet_data*)m_data->internal_data; - - app_manager_printf("Applet %s got request, url %s, action %d\n", - m_data->module_name, req_msg->url, req_msg->action); - - /* Create Request object */ - req_obj = (AEERequest)jeff_object_new(m_data->heap, class_AEERequest); - if (!req_obj) { - app_manager_printf("Applet process request failed: create request obj failed.\n"); - goto fail1; - } + if (app_manager_is_interrupting_module(Module_Jeff)) { + app_instance_queue_free_callback(queue_msg); + return; + } - jeff_runtime_push_local_object_ref(&ref); - ref.val = (JeffObjectRef)req_obj; + switch (msg->message_type) { + case APPLET_REQUEST: + { + JeffLocalObjectRef ref; + AEERequest req_obj; + bh_request_msg_t *req_msg = (bh_request_msg_t *)msg->payload; + attr_container_t *attr_cont = (attr_container_t *)req_msg->payload; + module_data *m_data = app_manager_get_module_data(Module_Jeff); + jeff_applet_data *applet_data = + (jeff_applet_data *)m_data->internal_data; + + app_manager_printf("Applet %s got request, url %s, action %d\n", + m_data->module_name, req_msg->url, + req_msg->action); + + /* Create Request object */ + req_obj = + (AEERequest)jeff_object_new(m_data->heap, class_AEERequest); + if (!req_obj) { + app_manager_printf("Applet process request failed: create " + "request obj failed.\n"); + goto fail1; + } - req_obj->mid = req_msg->mid; - req_obj->action = req_msg->action; - req_obj->fmt = req_msg->fmt; + jeff_runtime_push_local_object_ref(&ref); + ref.val = (JeffObjectRef)req_obj; - /* Create Java url string */ - if (req_msg->url) { - req_obj->url = (jstring)jeff_runtime_create_java_string(req_msg->url); - if (!req_obj->url) { - app_manager_printf("Applet process request failed: create url string failed.\n"); - goto fail2; - } - } + req_obj->mid = req_msg->mid; + req_obj->action = req_msg->action; + req_obj->fmt = req_msg->fmt; - /* Create Java AttributeObject payload */ - if (attr_cont - && !attr_container_to_attr_obj(attr_cont, &req_obj->payload)) { - app_manager_printf("Applet process request failed: convert payload failed.\n"); + /* Create Java url string */ + if (req_msg->url) { + req_obj->url = + (jstring)jeff_runtime_create_java_string(req_msg->url); + if (!req_obj->url) { + app_manager_printf("Applet process request failed: " + "create url string failed.\n"); goto fail2; } - - /* Call AEEApplet.callOnRequest(Request request) method */ - argv[0] = (unsigned int)applet_data->applet_obj; - argv[1] = (unsigned int)req_obj; - argt[0] = argt[1] = 1; - app_manager_call_java(method_AEEApplet_callOnRequest, 2, argv, argt); - app_manager_printf("Applet process request success.\n"); - - fail2: - jeff_runtime_pop_local_object_ref(1); - fail1: - APP_MGR_FREE(req_msg); - break; } - case TIMER_EVENT: - { - if (msg->payload) { - /* Call Timer.callOnTimer() method */ - argv[0] = (unsigned int)msg->payload; - argt[0] = 1; - app_manager_call_java(method_callOnTimer, 1, argv, argt); - } - break; + /* Create Java AttributeObject payload */ + if (attr_cont + && !attr_container_to_attr_obj(attr_cont, &req_obj->payload)) { + app_manager_printf("Applet process request failed: convert " + "payload failed.\n"); + goto fail2; } - case SENSOR_EVENT: - { - if (msg->payload) { - bh_sensor_event_t *sensor_event = (bh_sensor_event_t *)msg->payload; - AEESensor sensor = sensor_event->sensor; - attr_container_t *event = sensor_event->event; - bool ret = attr_container_to_attr_obj(event, &sensor->event); - - attr_container_destroy(event); - APP_MGR_FREE(sensor_event); - - if (ret) { - /* Call Sensor.callOnSensorEvent() method */ - argv[0] = (unsigned int)sensor; - argt[0] = 1; - app_manager_call_java(method_callOnSensorEvent, 1, argv, argt); - } - } - break; - } + /* Call AEEApplet.callOnRequest(Request request) method */ + argv[0] = (unsigned int)applet_data->applet_obj; + argv[1] = (unsigned int)req_obj; + argt[0] = argt[1] = 1; + app_manager_call_java(method_AEEApplet_callOnRequest, 2, argv, + argt); + app_manager_printf("Applet process request success.\n"); - case BLE_EVENT: - { - if (msg->payload) { - app_instance_process_ble_msg(msg->payload); - APP_MGR_FREE(msg->payload); - } - break; + fail2: + jeff_runtime_pop_local_object_ref(1); + fail1: + APP_MGR_FREE(req_msg); + break; + } + + case TIMER_EVENT: + { + if (msg->payload) { + /* Call Timer.callOnTimer() method */ + argv[0] = (unsigned int)msg->payload; + argt[0] = 1; + app_manager_call_java(method_callOnTimer, 1, argv, argt); } + break; + } - case GPIO_INTERRUPT_EVENT: - { - AEEGPIOChannel gpio_ch = (AEEGPIOChannel)msg->payload; + case SENSOR_EVENT: + { + if (msg->payload) { + bh_sensor_event_t *sensor_event = + (bh_sensor_event_t *)msg->payload; + AEESensor sensor = sensor_event->sensor; + attr_container_t *event = sensor_event->event; + bool ret = attr_container_to_attr_obj(event, &sensor->event); - if ((gpio_ch == NULL) || (gpio_ch->callback == 0) || (gpio_ch->listener == NULL)) { - break; - } - argv[0] = (unsigned int) gpio_ch; - argt[0] = 1; - bool ret_value = app_manager_call_java(method_callOnGPIOInterrupt, 1, argv, argt); + attr_container_destroy(event); + APP_MGR_FREE(sensor_event); - if (!ret_value) { - app_manager_printf("app_manager_call_java method_method_callOnGPIOInterrupt return false\n"); + if (ret) { + /* Call Sensor.callOnSensorEvent() method */ + argv[0] = (unsigned int)sensor; + argt[0] = 1; + app_manager_call_java(method_callOnSensorEvent, 1, argv, + argt); } - break; } + break; + } + + case BLE_EVENT: + { + if (msg->payload) { + app_instance_process_ble_msg(msg->payload); + APP_MGR_FREE(msg->payload); + } + break; + } - default: - { - app_manager_printf("Invalid message type of applet queue message.\n"); + case GPIO_INTERRUPT_EVENT: + { + AEEGPIOChannel gpio_ch = (AEEGPIOChannel)msg->payload; + + if ((gpio_ch == NULL) || (gpio_ch->callback == 0) + || (gpio_ch->listener == NULL)) { break; } + argv[0] = (unsigned int)gpio_ch; + argt[0] = 1; + bool ret_value = app_manager_call_java(method_callOnGPIOInterrupt, + 1, argv, argt); + + if (!ret_value) { + app_manager_printf( + "app_manager_call_java " + "method_method_callOnGPIOInterrupt return false\n"); + } + break; } - APP_MGR_FREE(msg); + default: + { + app_manager_printf( + "Invalid message type of applet queue message.\n"); + break; + } } - static JeffClassHeaderLinked* - find_main_class(JeffFileHeaderLinked *main_file) - { - JeffClassHeaderLinked *c = NULL, *ci; - unsigned int i; + APP_MGR_FREE(msg); +} - for (i = 0; i < main_file->internal_class_count; i++) { - ci = main_file->class_header[i]; +static JeffClassHeaderLinked * +find_main_class(JeffFileHeaderLinked *main_file) +{ + JeffClassHeaderLinked *c = NULL, *ci; + unsigned int i; - if (jeff_is_super_class(class_AEEApplet, ci) - && (ci->access_flag & JEFF_ACC_PUBLIC)) { - if (c) { - jeff_printe_more_than_one_main_class(); - return NULL; - } + for (i = 0; i < main_file->internal_class_count; i++) { + ci = main_file->class_header[i]; - c = ci; + if (jeff_is_super_class(class_AEEApplet, ci) + && (ci->access_flag & JEFF_ACC_PUBLIC)) { + if (c) { + jeff_printe_more_than_one_main_class(); + return NULL; } + + c = ci; } + } - if (!c) + if (!c) jeff_printe_no_main_class(); - return c; - } + return c; +} - /* Java applet thread main routine */ - static void* - app_instance_main(void *arg) - { - module_data *m_data = (module_data *)arg; - jeff_applet_data *applet_data = (jeff_applet_data*)m_data->internal_data; - JeffClassHeaderLinked *object_class; - JeffMethodLinked *m; - unsigned int argv[1]; - uint8 argt[1]; +/* Java applet thread main routine */ +static void * +app_instance_main(void *arg) +{ + module_data *m_data = (module_data *)arg; + jeff_applet_data *applet_data = (jeff_applet_data *)m_data->internal_data; + JeffClassHeaderLinked *object_class; + JeffMethodLinked *m; + unsigned int argv[1]; + uint8 argt[1]; - app_manager_printf("Java Applet '%s' started\n", m_data->module_name); + app_manager_printf("Java Applet '%s' started\n", m_data->module_name); #if BEIHAI_ENABLE_TOOL_AGENT != 0 - if (applet_data->debug_mode) + if (applet_data->debug_mode) jeff_tool_suspend_self(); #endif - applet_data->vm_instance->applet_object = applet_data->applet_obj; - object_class = jeff_object_class_pointer(applet_data->applet_obj); - m = jeff_select_method_virtual(object_class, method_AEEApplet_onInit); - bh_assert(m != NULL); - /* Initialize applet class which call */ - if (!app_manager_initialize_class(object_class)) { - app_manager_printf("Call fail\n"); - goto fail; - } + applet_data->vm_instance->applet_object = applet_data->applet_obj; + object_class = jeff_object_class_pointer(applet_data->applet_obj); + m = jeff_select_method_virtual(object_class, method_AEEApplet_onInit); + bh_assert(m != NULL); + /* Initialize applet class which call */ + if (!app_manager_initialize_class(object_class)) { + app_manager_printf("Call fail\n"); + goto fail; + } - /* Initialize applet object which call */ - if (!app_manager_initialize_object(applet_data->applet_obj)) { - app_manager_printf("Call fail\n"); - goto fail; - } + /* Initialize applet object which call */ + if (!app_manager_initialize_object(applet_data->applet_obj)) { + app_manager_printf("Call fail\n"); + goto fail; + } - /* Call applet's onInit() method */ - argv[0] = (unsigned int)applet_data->applet_obj; - argt[0] = 1; - if (app_manager_call_java(m, 1, argv, argt)) - /* Enter queue loop run to receive and process applet queue message */ + /* Call applet's onInit() method */ + argv[0] = (unsigned int)applet_data->applet_obj; + argt[0] = 1; + if (app_manager_call_java(m, 1, argv, argt)) + /* Enter queue loop run to receive and process applet queue message + */ bh_queue_enter_loop_run(m_data->queue, app_instance_queue_callback); - fail: - applet_data->vm_instance->applet_object = applet_data->applet_obj; - object_class = jeff_object_class_pointer(applet_data->applet_obj); - m = jeff_select_method_virtual(object_class, method_AEEApplet_onDestroy); - bh_assert(m != NULL); - /* Call User Applet or AEEApplet onDestroy() method */ - app_manager_call_java(m, 1, argv, argt); - if (m != method_AEEApplet_onDestroy) { - /*If 'm' is user onDestroy, then Call AEEApplet.onDestroy() method*/ - app_manager_call_java(method_AEEApplet_onDestroy, 1, argv, argt); - } - app_manager_printf("Applet instance main thread exit.\n"); - return NULL; +fail: + applet_data->vm_instance->applet_object = applet_data->applet_obj; + object_class = jeff_object_class_pointer(applet_data->applet_obj); + m = jeff_select_method_virtual(object_class, method_AEEApplet_onDestroy); + bh_assert(m != NULL); + /* Call User Applet or AEEApplet onDestroy() method */ + app_manager_call_java(m, 1, argv, argt); + if (m != method_AEEApplet_onDestroy) { + /*If 'm' is user onDestroy, then Call AEEApplet.onDestroy() method*/ + app_manager_call_java(method_AEEApplet_onDestroy, 1, argv, argt); } + app_manager_printf("Applet instance main thread exit.\n"); + return NULL; +} - static bool - verify_signature(JeffFileHeader *file, unsigned size) - { - uint8 *sig; - unsigned sig_size; +static bool +verify_signature(JeffFileHeader *file, unsigned size) +{ + uint8 *sig; + unsigned sig_size; #if BEIHAI_ENABLE_NO_SIGNATURE != 0 - /* no signature */ - if (file->file_signature == 0) + /* no signature */ + if (file->file_signature == 0) return true; #endif - if (file->file_length != size + if (file->file_length != size #if BEIHAI_ENABLE_NO_SIGNATURE == 0 || file->file_signature == 0 #endif || file->file_signature >= file->file_length) return false; - sig = (uint8 *)file + file->file_signature; - sig_size = file->file_length - file->file_signature; + sig = (uint8 *)file + file->file_signature; + sig_size = file->file_length - file->file_signature; - if (0 == app_manager_signature_verify((uint8_t *)file, file->file_signature, - sig, sig_size)) + if (0 + == app_manager_signature_verify((uint8_t *)file, file->file_signature, + sig, sig_size)) return false; - return true; - } - - /* Install Java Applet */ - static bool - jeff_module_install(bh_request_msg_t *msg) - { - unsigned int size, bpk_file_len, main_file_len, heap_size, timeout; - uint8 *bpk_file; - JeffFileHeaderLinked *main_file; - JeffClassHeaderLinked *main_class; - module_data *m_data; - jeff_applet_data *applet_data; - char *applet_name, *applet_perm; - attr_container_t *attr_cont; - bool debug = false; - - /* Check url */ - if (!msg->url - || strcmp(msg->url, "/applet") != 0) { - SEND_ERR_RESPONSE(msg->mid, "Install Applet failed: invalid url."); - return false; - } + return true; +} - /* Check payload */ - attr_cont = (attr_container_t *)msg->payload; - if (!attr_cont - || !(bpk_file = (uint8 *) - attr_container_get_as_bytearray(attr_cont, "bpk", &bpk_file_len))) { - SEND_ERR_RESPONSE(msg->mid, "Install Applet failed: invalid bpk file."); - return false; - } +/* Install Java Applet */ +static bool +jeff_module_install(bh_request_msg_t *msg) +{ + unsigned int size, bpk_file_len, main_file_len, heap_size, timeout; + uint8 *bpk_file; + JeffFileHeaderLinked *main_file; + JeffClassHeaderLinked *main_class; + module_data *m_data; + jeff_applet_data *applet_data; + char *applet_name, *applet_perm; + attr_container_t *attr_cont; + bool debug = false; + + /* Check url */ + if (!msg->url || strcmp(msg->url, "/applet") != 0) { + SEND_ERR_RESPONSE(msg->mid, "Install Applet failed: invalid url."); + return false; + } - /* Check applet name */ - applet_name = attr_container_get_as_string(attr_cont, "name"); + /* Check payload */ + attr_cont = (attr_container_t *)msg->payload; + if (!attr_cont + || !(bpk_file = (uint8 *)attr_container_get_as_bytearray( + attr_cont, "bpk", &bpk_file_len))) { + SEND_ERR_RESPONSE(msg->mid, "Install Applet failed: invalid bpk file."); + return false; + } - if (!applet_name || strlen(applet_name) == 0) { - SEND_ERR_RESPONSE(msg->mid, "Install Applet failed: invalid applet name."); - return false; - } + /* Check applet name */ + applet_name = attr_container_get_as_string(attr_cont, "name"); - if (app_manager_lookup_module_data(applet_name)) { - SEND_ERR_RESPONSE(msg->mid, "Install Applet failed: applet already installed."); - return false; - } + if (!applet_name || strlen(applet_name) == 0) { + SEND_ERR_RESPONSE(msg->mid, + "Install Applet failed: invalid applet name."); + return false; + } - /* TODO: convert bpk file to Jeff file */ - main_file_len = bpk_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; - } - bh_memcpy_s(main_file, main_file_len, bpk_file, main_file_len); + if (app_manager_lookup_module_data(applet_name)) { + SEND_ERR_RESPONSE(msg->mid, + "Install Applet failed: applet already installed."); + return false; + } - /* Verify signature */ - if (!verify_signature((JeffFileHeader *)main_file, main_file_len)) { - SEND_ERR_RESPONSE(msg->mid, "Install Applet failed: verify Jeff file signature failed."); - goto fail1; - } + /* TODO: convert bpk file to Jeff file */ + main_file_len = bpk_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; + } + bh_memcpy_s(main_file, main_file_len, bpk_file, main_file_len); + + /* Verify signature */ + if (!verify_signature((JeffFileHeader *)main_file, main_file_len)) { + SEND_ERR_RESPONSE( + msg->mid, + "Install Applet failed: verify Jeff file signature failed."); + goto fail1; + } - /* Load Jeff main file */ - if (!jeff_runtime_load(main_file, main_file_len, false, NULL, NULL)) { - SEND_ERR_RESPONSE(msg->mid, "Install Applet failed: load Jeff file failed."); - goto fail1; - } + /* Load Jeff main file */ + if (!jeff_runtime_load(main_file, main_file_len, false, NULL, NULL)) { + SEND_ERR_RESPONSE(msg->mid, + "Install Applet failed: load Jeff file failed."); + goto fail1; + } - /* Find main class */ - main_class = find_main_class(main_file); - if (!main_class) { - SEND_ERR_RESPONSE(msg->mid, "Install Applet failed: find applet class failed."); - goto fail2; - } + /* Find main class */ + main_class = find_main_class(main_file); + if (!main_class) { + SEND_ERR_RESPONSE(msg->mid, + "Install Applet failed: find applet class failed."); + goto fail2; + } - /* Create module data */ - size = offsetof(module_data, module_name) + strlen(applet_name) + 1; - size = align_uint(size, 4); - 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; - } + /* Create module data */ + size = offsetof(module_data, module_name) + strlen(applet_name) + 1; + size = align_uint(size, 4); + 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; + } - memset(m_data, 0, size + sizeof(jeff_applet_data)); - m_data->module_type = Module_Jeff; - m_data->internal_data = (uint8*)m_data + size; - applet_data = (jeff_applet_data*)m_data->internal_data; - bh_strcpy_s(m_data->module_name, strlen(applet_name) + 1, applet_name); - applet_data->main_file = main_file; + memset(m_data, 0, size + sizeof(jeff_applet_data)); + m_data->module_type = Module_Jeff; + m_data->internal_data = (uint8 *)m_data + size; + applet_data = (jeff_applet_data *)m_data->internal_data; + bh_strcpy_s(m_data->module_name, strlen(applet_name) + 1, applet_name); + applet_data->main_file = main_file; - /* Set applet execution timeout */ - timeout = DEFAULT_APPLET_TIMEOUT; - if (attr_container_contain_key(attr_cont, "execution timeout")) + /* Set applet execution timeout */ + timeout = DEFAULT_APPLET_TIMEOUT; + if (attr_container_contain_key(attr_cont, "execution timeout")) timeout = attr_container_get_as_int(attr_cont, "execution timeout"); - m_data->timeout = timeout; - - /* Create applet permissions */ - applet_perm = attr_container_get_as_string(attr_cont, "perm"); - if (applet_perm != NULL) { - 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; - } + m_data->timeout = timeout; - bh_strcpy_s(applet_data->perms, strlen(applet_perm) + 1, applet_perm); + /* Create applet permissions */ + applet_perm = attr_container_get_as_string(attr_cont, "perm"); + if (applet_perm != NULL) { + 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; } - /* Create applet queue */ - m_data->queue = bh_queue_create(); - if (!m_data->queue) { - SEND_ERR_RESPONSE(msg->mid, "Install Applet failed: create applet queue failed."); - goto fail3_1; - } + bh_strcpy_s(applet_data->perms, strlen(applet_perm) + 1, applet_perm); + } + + /* Create applet queue */ + m_data->queue = bh_queue_create(); + if (!m_data->queue) { + SEND_ERR_RESPONSE(msg->mid, + "Install Applet failed: create applet queue failed."); + goto fail3_1; + } - /* Set heap size */ - heap_size = DEFAULT_APPLET_HEAP_SIZE; - if (attr_container_contain_key(attr_cont, "heap size")) { - heap_size = attr_container_get_as_int(attr_cont, "heap size"); - if (heap_size < MIN_APPLET_HEAP_SIZE) + /* Set heap size */ + heap_size = DEFAULT_APPLET_HEAP_SIZE; + if (attr_container_contain_key(attr_cont, "heap size")) { + heap_size = attr_container_get_as_int(attr_cont, "heap size"); + if (heap_size < MIN_APPLET_HEAP_SIZE) heap_size = MIN_APPLET_HEAP_SIZE; - else if (heap_size > MAX_APPLET_HEAP_SIZE) + else if (heap_size > MAX_APPLET_HEAP_SIZE) heap_size = MAX_APPLET_HEAP_SIZE; - } + } - m_data->heap_size = heap_size; + m_data->heap_size = heap_size; - /* Create applet heap */ - m_data->heap = gc_init_for_instance(heap_size); - if (!m_data->heap) { - SEND_ERR_RESPONSE(msg->mid, "Install Applet failed: create heap failed."); - goto fail4; - } + /* Create applet heap */ + m_data->heap = gc_init_for_instance(heap_size); + if (!m_data->heap) { + SEND_ERR_RESPONSE(msg->mid, + "Install Applet failed: create heap failed."); + goto fail4; + } - /* Create applet object */ - applet_data->applet_obj = jeff_object_new(m_data->heap, main_class); - if (!applet_data->applet_obj) { - SEND_ERR_RESPONSE(msg->mid, "Install Applet failed: create applet object failed."); - goto fail5; - } + /* Create applet object */ + applet_data->applet_obj = jeff_object_new(m_data->heap, main_class); + if (!applet_data->applet_obj) { + SEND_ERR_RESPONSE( + msg->mid, "Install Applet failed: create applet object failed."); + goto fail5; + } - /* Initialize watchdog timer */ - if (!watchdog_timer_init(m_data)) { - SEND_ERR_RESPONSE(msg->mid, "Install Applet failed: create applet watchdog timer failed."); - goto fail5; - } + /* Initialize watchdog timer */ + if (!watchdog_timer_init(m_data)) { + SEND_ERR_RESPONSE( + msg->mid, + "Install Applet failed: create applet watchdog timer failed."); + goto fail5; + } #if BEIHAI_ENABLE_TOOL_AGENT != 0 - /* Check whether applet is debuggable */ - if (attr_container_contain_key(attr_cont, "debug")) + /* Check whether applet is debuggable */ + if (attr_container_contain_key(attr_cont, "debug")) debug = attr_container_get_as_bool(attr_cont, "debug"); - applet_data->debug_mode = debug; + applet_data->debug_mode = debug; - /* Create tool agent queue */ - if (debug && !(applet_data->tool_agent_queue = bh_queue_create())) { - SEND_ERR_RESPONSE(msg->mid, "Install Applet failed: create tool agent queue failed."); - goto fail5_1; - } + /* Create tool agent queue */ + if (debug && !(applet_data->tool_agent_queue = bh_queue_create())) { + SEND_ERR_RESPONSE( + msg->mid, "Install Applet failed: create tool agent queue failed."); + goto fail5_1; + } #endif - /* Create applet instance */ - applet_data->vm_instance = - jeff_runtime_create_instance(main_file, m_data->heap, 16, - app_instance_main, m_data, - NULL); - if (!applet_data->vm_instance) { - SEND_ERR_RESPONSE(msg->mid, "Install Applet failed: create Java VM failed"); - goto fail6; - } + /* Create applet instance */ + applet_data->vm_instance = jeff_runtime_create_instance( + main_file, m_data->heap, 16, app_instance_main, m_data, NULL); + if (!applet_data->vm_instance) { + SEND_ERR_RESPONSE(msg->mid, + "Install Applet failed: create Java VM failed"); + goto fail6; + } - /* Add applet data to applet data list */ - applet_data->vm_instance->applet_object = applet_data->applet_obj; - app_manager_add_module_data(m_data); - app_manager_post_applets_update_event(); + /* Add applet data to applet data list */ + applet_data->vm_instance->applet_object = applet_data->applet_obj; + app_manager_add_module_data(m_data); + app_manager_post_applets_update_event(); #if BEIHAI_ENABLE_TOOL_AGENT != 0 - /* Start tool agent thread */ - if (debug && !jeff_tool_start_agent(applet_data->vm_instance, applet_data->tool_agent_queue)) { - SEND_ERR_RESPONSE(msg->mid, "Install Applet failed: start tool agent failed"); - goto fail6; - } + /* Start tool agent thread */ + if (debug + && !jeff_tool_start_agent(applet_data->vm_instance, + applet_data->tool_agent_queue)) { + SEND_ERR_RESPONSE(msg->mid, + "Install Applet failed: start tool agent failed"); + goto fail6; + } #endif - app_manager_printf("Install Applet success!\n"); - app_send_response_to_host(msg->mid, CREATED_2_01, NULL); /* CREATED */ - return true; + app_manager_printf("Install Applet success!\n"); + app_send_response_to_host(msg->mid, CREATED_2_01, NULL); /* CREATED */ + return true; - fail6: +fail6: #if BEIHAI_ENABLE_TOOL_AGENT != 0 - if (debug) + if (debug) bh_queue_destroy(applet_data->tool_agent_queue); #endif - fail5_1: - watchdog_timer_destroy(&m_data->wd_timer); +fail5_1: + watchdog_timer_destroy(&m_data->wd_timer); - fail5: - gc_destroy_for_instance(m_data->heap); +fail5: + gc_destroy_for_instance(m_data->heap); - fail4: - bh_queue_destroy(m_data->queue, NULL); +fail4: + bh_queue_destroy(m_data->queue, NULL); - fail3_1: - APP_MGR_FREE(applet_data->perms); +fail3_1: + APP_MGR_FREE(applet_data->perms); - fail3: - APP_MGR_FREE(applet_data); +fail3: + APP_MGR_FREE(applet_data); - fail2: - jeff_runtime_unload(main_file); +fail2: + jeff_runtime_unload(main_file); - fail1: - APP_MGR_FREE(main_file); +fail1: + APP_MGR_FREE(main_file); - return false; - } + return false; +} - static void - cleanup_applet_resource(module_data *m_data) - { - jeff_applet_data *applet_data = (jeff_applet_data*)m_data->internal_data; +static void +cleanup_applet_resource(module_data *m_data) +{ + jeff_applet_data *applet_data = (jeff_applet_data *)m_data->internal_data; - /* Unload Jeff main file and free it */ - jeff_runtime_unload(applet_data->main_file); - APP_MGR_FREE(applet_data->main_file); + /* Unload Jeff main file and free it */ + jeff_runtime_unload(applet_data->main_file); + APP_MGR_FREE(applet_data->main_file); - /* Destroy queue */ - bh_queue_destroy(m_data->queue, app_instance_queue_free_callback); + /* Destroy queue */ + bh_queue_destroy(m_data->queue, app_instance_queue_free_callback); - /* Destroy heap */ - gc_destroy_for_instance(m_data->heap); + /* Destroy heap */ + gc_destroy_for_instance(m_data->heap); - /* Destroy watchdog timer */ - watchdog_timer_destroy(&m_data->wd_timer); + /* Destroy watchdog timer */ + watchdog_timer_destroy(&m_data->wd_timer); - /* Remove module data from module data list and free it */ - app_manager_del_module_data(m_data); - APP_MGR_FREE(applet_data->perms); - APP_MGR_FREE(m_data); - } + /* Remove module data from module data list and free it */ + app_manager_del_module_data(m_data); + APP_MGR_FREE(applet_data->perms); + APP_MGR_FREE(m_data); +} - /* Uninstall Java Applet */ - static bool - jeff_module_uninstall(bh_request_msg_t *msg) - { - module_data *m_data; - jeff_applet_data *applet_data; - attr_container_t *attr_cont; - char *applet_name; - bool do_not_reply = false; +/* Uninstall Java Applet */ +static bool +jeff_module_uninstall(bh_request_msg_t *msg) +{ + module_data *m_data; + jeff_applet_data *applet_data; + attr_container_t *attr_cont; + char *applet_name; + bool do_not_reply = false; - /* Check payload and applet name*/ - attr_cont = (attr_container_t *)msg->payload; + /* Check payload and applet name*/ + attr_cont = (attr_container_t *)msg->payload; - /* Check whether need to reply this request */ - if (attr_container_contain_key(attr_cont, "do not reply me")) + /* Check whether need to reply this request */ + if (attr_container_contain_key(attr_cont, "do not reply me")) do_not_reply = attr_container_get_as_bool(attr_cont, "do not reply me"); - /* Check url */ - if (!msg->url - || strcmp(msg->url, "/applet") != 0) { - if (!do_not_reply) - SEND_ERR_RESPONSE(msg->mid, "Uninstall Applet failed: invalid url."); - else + /* Check url */ + if (!msg->url || strcmp(msg->url, "/applet") != 0) { + if (!do_not_reply) + SEND_ERR_RESPONSE(msg->mid, + "Uninstall Applet failed: invalid url."); + else app_manager_printf("Uninstall Applet failed: invalid url."); - return false; - } + return false; + } - if (!attr_cont + if (!attr_cont || !(applet_name = attr_container_get_as_string(attr_cont, "name")) || strlen(applet_name) == 0) { - if (!do_not_reply) - SEND_ERR_RESPONSE(msg->mid, "Uninstall Applet failed: invalid applet name."); - else + if (!do_not_reply) + SEND_ERR_RESPONSE(msg->mid, + "Uninstall Applet failed: invalid applet name."); + else app_manager_printf("Uninstall Applet failed: invalid applet name."); - return false; - } + return false; + } - m_data = app_manager_lookup_module_data(applet_name); - if (!m_data) { - if (!do_not_reply) - SEND_ERR_RESPONSE(msg->mid, "Uninstall Applet failed: no applet found."); - else + m_data = app_manager_lookup_module_data(applet_name); + if (!m_data) { + if (!do_not_reply) + SEND_ERR_RESPONSE(msg->mid, + "Uninstall Applet failed: no applet found."); + else app_manager_printf("Uninstall Applet failed: no applet found."); - return false; - } + return false; + } - if (m_data->module_type != Module_Jeff) { - if (!do_not_reply) - SEND_ERR_RESPONSE(msg->mid, "Uninstall Applet failed: invlaid module type."); - else + if (m_data->module_type != Module_Jeff) { + if (!do_not_reply) + SEND_ERR_RESPONSE(msg->mid, + "Uninstall Applet failed: invlaid module type."); + else app_manager_printf("Uninstall Applet failed: invalid module type."); - return false; - } + return false; + } - if (m_data->wd_timer.is_interrupting) { - if (!do_not_reply) - SEND_ERR_RESPONSE(msg->mid, "Uninstall Applet failed: applet is being interrupted by watchdog."); - else - app_manager_printf("Uninstall Applet failed: applet is being interrupted by watchdog."); - return false; - } + if (m_data->wd_timer.is_interrupting) { + if (!do_not_reply) + SEND_ERR_RESPONSE(msg->mid, + "Uninstall Applet failed: applet is being " + "interrupted by watchdog."); + else + app_manager_printf("Uninstall Applet failed: applet is being " + "interrupted by watchdog."); + return false; + } - /* Exit applet queue loop run */ - bh_queue_exit_loop_run(m_data->queue); + /* Exit applet queue loop run */ + bh_queue_exit_loop_run(m_data->queue); - applet_data = (jeff_applet_data*)m_data->internal_data; + applet_data = (jeff_applet_data *)m_data->internal_data; #if BEIHAI_ENABLE_TOOL_AGENT != 0 - /* Exit tool agent queue loop run */ - if (is_tool_agent_running(m_data)) { - bh_queue_exit_loop_run(applet_data->tool_agent_queue); - } + /* Exit tool agent queue loop run */ + if (is_tool_agent_running(m_data)) { + bh_queue_exit_loop_run(applet_data->tool_agent_queue); + } #endif - /* Wait the end of the applet instance and then destroy it */ - if (applet_data->vm_instance->main_file) + /* Wait the end of the applet instance and then destroy it */ + if (applet_data->vm_instance->main_file) jeff_runtime_wait_for_instance(applet_data->vm_instance, -1); - jeff_runtime_destroy_instance(applet_data->vm_instance); + jeff_runtime_destroy_instance(applet_data->vm_instance); - cleanup_applet_resource(m_data); - app_manager_post_applets_update_event(); + cleanup_applet_resource(m_data); + app_manager_post_applets_update_event(); - app_manager_printf("Uninstall Applet success!\n"); + app_manager_printf("Uninstall Applet success!\n"); - if (!do_not_reply) + if (!do_not_reply) app_send_response_to_host(msg->mid, DELETED_2_02, NULL); /* DELETED */ - return true; - } + return true; +} #define PERM_PREFIX "AEE.permission." - static bool - check_permission_format(const char *perm) - { - const char *prefix = PERM_PREFIX; - const char *p; +static bool +check_permission_format(const char *perm) +{ + const char *prefix = PERM_PREFIX; + const char *p; - if (perm == NULL || strncmp(perm, prefix, strlen(prefix)) != 0 + if (perm == NULL || strncmp(perm, prefix, strlen(prefix)) != 0 || *(p = perm + strlen(prefix)) == '\0') return false; - do { - if (!(*p == '.' || ('A' <= *p && *p <= 'Z') || ('a' <= *p && *p <= 'z'))) + do { + if (!(*p == '.' || ('A' <= *p && *p <= 'Z') + || ('a' <= *p && *p <= 'z'))) return false; - }while (*++p != '\0'); + } while (*++p != '\0'); - return true; - } + return true; +} - static bool - match(const char *haystack, const char *needle, char delim) - { - const char *p = needle; +static bool +match(const char *haystack, const char *needle, char delim) +{ + const char *p = needle; - if (haystack == NULL || *haystack == '\0' - || needle == NULL || *needle == '\0') + if (haystack == NULL || *haystack == '\0' || needle == NULL + || *needle == '\0') return false; + while (true) { while (true) { - while (true) { - if ((*haystack == '\0' || *haystack == delim) && *p == '\0') { - return true; - } else if (*p == *haystack) { - ++p; - ++haystack; - } else { - break; - } + if ((*haystack == '\0' || *haystack == delim) && *p == '\0') { + return true; } - while (*haystack != '\0' && *haystack != delim) { + else if (*p == *haystack) { + ++p; ++haystack; } - if (*haystack == '\0') { - return false; - } else { - ++haystack; - p = needle; + else { + break; } } + while (*haystack != '\0' && *haystack != delim) { + ++haystack; + } + if (*haystack == '\0') { + return false; + } + else { + ++haystack; + p = needle; + } } +} - bool - bh_applet_check_permission(const char *perm) - { - return check_permission_format(perm) - && match(app_manager_get_jeff_applet_data()->perms, - perm + strlen(PERM_PREFIX), ' '); - } - - static bool - jeff_module_init() - { - JeffDescriptorFull d[] = { {JEFF_TYPE_VOID, 0, NULL}}; - JeffDescriptorFull d1[] = { - { JEFF_TYPE_OBJECT | JEFF_TYPE_REF, 0, NULL}, - { JEFF_TYPE_VOID, 0, NULL} - }; +bool +bh_applet_check_permission(const char *perm) +{ + return check_permission_format(perm) + && match(app_manager_get_jeff_applet_data()->perms, + perm + strlen(PERM_PREFIX), ' '); +} - /* Resolve class com.intel.aee.AEEApplet */ - class_AEEApplet = jeff_runtime_resolve_class_full_name("com.intel.aee.AEEApplet"); - if (!class_AEEApplet) { - app_manager_printf("App Manager start failed: resolve class AEEApplet failed.\n"); - return false; - } +static bool +jeff_module_init() +{ + JeffDescriptorFull d[] = { { JEFF_TYPE_VOID, 0, NULL } }; + JeffDescriptorFull d1[] = { { JEFF_TYPE_OBJECT | JEFF_TYPE_REF, 0, NULL }, + { JEFF_TYPE_VOID, 0, NULL } }; + + /* Resolve class com.intel.aee.AEEApplet */ + class_AEEApplet = + jeff_runtime_resolve_class_full_name("com.intel.aee.AEEApplet"); + if (!class_AEEApplet) { + app_manager_printf( + "App Manager start failed: resolve class AEEApplet failed.\n"); + return false; + } - /* Resolve class com.intel.aee.Request */ - class_AEERequest = jeff_runtime_resolve_class_full_name("com.intel.aee.Request"); - if (!class_AEERequest) { - app_manager_printf("App Manager start failed: resolve class Request failed.\n"); - return false; - } + /* Resolve class com.intel.aee.Request */ + class_AEERequest = + jeff_runtime_resolve_class_full_name("com.intel.aee.Request"); + if (!class_AEERequest) { + app_manager_printf( + "App Manager start failed: resolve class Request failed.\n"); + return false; + } - /* Resolve class com.intel.aee.Timer */ - class_Timer = jeff_runtime_resolve_class_full_name("com.intel.aee.Timer"); - if (!class_Timer) { - app_manager_printf("App Manager start failed: resolve class Timer failed.\n"); - return false; - } + /* Resolve class com.intel.aee.Timer */ + class_Timer = jeff_runtime_resolve_class_full_name("com.intel.aee.Timer"); + if (!class_Timer) { + app_manager_printf( + "App Manager start failed: resolve class Timer failed.\n"); + return false; + } - /* Resolve class com.intel.aee.Sensor */ - class_Sensor = jeff_runtime_resolve_class_full_name("com.intel.aee.Sensor"); - if (!class_Sensor) { - app_manager_printf("App Manager start failed: resolve class Sensor failed.\n"); - return false; - } + /* Resolve class com.intel.aee.Sensor */ + class_Sensor = jeff_runtime_resolve_class_full_name("com.intel.aee.Sensor"); + if (!class_Sensor) { + app_manager_printf( + "App Manager start failed: resolve class Sensor failed.\n"); + return false; + } - /* Resolve class com.intel.aee.ble.BLEManager */ - class_BLEManager = jeff_runtime_resolve_class_full_name( - "com.intel.aee.ble.BLEManager"); - if (!class_BLEManager) { - app_manager_printf( + /* Resolve class com.intel.aee.ble.BLEManager */ + class_BLEManager = + jeff_runtime_resolve_class_full_name("com.intel.aee.ble.BLEManager"); + if (!class_BLEManager) { + app_manager_printf( "App Manager start failed: resolve class BLEManager failed.\n"); - return false; - } + return false; + } - /* Resolve class com.intel.aee.ble.BLEDevice */ - class_BLEDevice = jeff_runtime_resolve_class_full_name( - "com.intel.aee.ble.BLEDevice"); - if (!class_BLEDevice) { - app_manager_printf( + /* Resolve class com.intel.aee.ble.BLEDevice */ + class_BLEDevice = + jeff_runtime_resolve_class_full_name("com.intel.aee.ble.BLEDevice"); + if (!class_BLEDevice) { + app_manager_printf( "App Manager start failed: resolve class BLEDevice failed.\n"); - return false; - } - /* Resolve class com.intel.aee.ble.BLEDevice */ - class_BLEGattService = jeff_runtime_resolve_class_full_name( + return false; + } + /* Resolve class com.intel.aee.ble.BLEDevice */ + class_BLEGattService = jeff_runtime_resolve_class_full_name( "com.intel.aee.ble.BLEGattService"); - if (!class_BLEGattService) { - app_manager_printf( - "App Manager start failed: resolve class BLEGattService failed.\n"); - return false; - } + if (!class_BLEGattService) { + app_manager_printf("App Manager start failed: resolve class " + "BLEGattService failed.\n"); + return false; + } - /* Resolve class com.intel.aee.ble.BLEDevice */ - class_BLEGattCharacteristic = jeff_runtime_resolve_class_full_name( + /* Resolve class com.intel.aee.ble.BLEDevice */ + class_BLEGattCharacteristic = jeff_runtime_resolve_class_full_name( "com.intel.aee.ble.BLEGattCharacteristic"); - if (!class_BLEGattCharacteristic) { - app_manager_printf( - "App Manager start failed: resolve class BLEGattCharacteristic failed.\n"); - return false; - } + if (!class_BLEGattCharacteristic) { + app_manager_printf("App Manager start failed: resolve class " + "BLEGattCharacteristic failed.\n"); + return false; + } - /* Resolve class com.intel.aee.ble.BLEDevice */ - class_BLEGattDescriptor = jeff_runtime_resolve_class_full_name( + /* Resolve class com.intel.aee.ble.BLEDevice */ + class_BLEGattDescriptor = jeff_runtime_resolve_class_full_name( "com.intel.aee.ble.BLEGattDescriptor"); - if (!class_BLEGattDescriptor) { - app_manager_printf( - "App Manager start failed: resolve class BLEGattDescriptor failed.\n"); - return false; - } - /* Resolve class com.intel.aee.gpio.GPIOChannel */ - class_GPIOChannel = jeff_runtime_resolve_class_full_name( - "com.intel.aee.gpio.GPIOChannel"); - if (!class_GPIOChannel) { - app_manager_printf( - "App Manager start failed: resolve class GPIOChannel failed.\n"); - return false; - } - - /* Resolve method com.intel.aee.AEEApplet.onInit() */ - method_AEEApplet_onInit = jeff_lookup_method(class_AEEApplet, "onInit", 0, d); - if (!method_AEEApplet_onInit) { - app_manager_printf("App Manager start failed: resolve method Applet.onInit() failed.\n"); - return false; - } + if (!class_BLEGattDescriptor) { + app_manager_printf("App Manager start failed: resolve class " + "BLEGattDescriptor failed.\n"); + return false; + } + /* Resolve class com.intel.aee.gpio.GPIOChannel */ + class_GPIOChannel = + jeff_runtime_resolve_class_full_name("com.intel.aee.gpio.GPIOChannel"); + if (!class_GPIOChannel) { + app_manager_printf("App Manager start failed: resolve class " + "GPIOChannel failed.\n"); + return false; + } - /* Resolve method com.intel.aee.AEEApplet.onDestroy() */ - method_AEEApplet_onDestroy = jeff_lookup_method(class_AEEApplet, "onDestroy", 0, d); - if (!method_AEEApplet_onDestroy) { - app_manager_printf("App Manager start failed: resolve method AEEApplet.onDestroy() failed.\n"); - return false; - } + /* Resolve method com.intel.aee.AEEApplet.onInit() */ + method_AEEApplet_onInit = + jeff_lookup_method(class_AEEApplet, "onInit", 0, d); + if (!method_AEEApplet_onInit) { + app_manager_printf("App Manager start failed: resolve method " + "Applet.onInit() failed.\n"); + return false; + } - /* Resolve method com.intel.aee.AEEApplet.callOnRequest(Request) */ - d1[0].class_header = class_AEERequest; - method_AEEApplet_callOnRequest = jeff_lookup_method(class_AEEApplet, "callOnRequest", 1, d1); - if (!method_AEEApplet_callOnRequest) { - app_manager_printf("App Manager start failed: resolve method AEEApplet.callOnRequest() failed.\n"); - return false; - } + /* Resolve method com.intel.aee.AEEApplet.onDestroy() */ + method_AEEApplet_onDestroy = + jeff_lookup_method(class_AEEApplet, "onDestroy", 0, d); + if (!method_AEEApplet_onDestroy) { + app_manager_printf("App Manager start failed: resolve method " + "AEEApplet.onDestroy() failed.\n"); + return false; + } - /* Resolve method com.intel.aee.Timer.callOnTimer() */ - method_callOnTimer = jeff_lookup_method(class_Timer, "callOnTimer", 0, d); - if (!method_callOnTimer) { - app_manager_printf("App Manager start failed: resolve method Timer.callOnTimer() failed.\n"); - return false; - } + /* Resolve method com.intel.aee.AEEApplet.callOnRequest(Request) */ + d1[0].class_header = class_AEERequest; + method_AEEApplet_callOnRequest = + jeff_lookup_method(class_AEEApplet, "callOnRequest", 1, d1); + if (!method_AEEApplet_callOnRequest) { + app_manager_printf("App Manager start failed: resolve method " + "AEEApplet.callOnRequest() failed.\n"); + return false; + } - /* Resolve method com.intel.aee.Sensor.callOnSensorEvent() */ - method_callOnSensorEvent = jeff_lookup_method(class_Sensor, "callOnSensorEvent", 0, d); - if (!method_callOnSensorEvent) { - app_manager_printf("App Manager start failed: resolve method Sensor.callOnSensorEvent() failed.\n"); - return false; - } + /* Resolve method com.intel.aee.Timer.callOnTimer() */ + method_callOnTimer = jeff_lookup_method(class_Timer, "callOnTimer", 0, d); + if (!method_callOnTimer) { + app_manager_printf("App Manager start failed: resolve method " + "Timer.callOnTimer() failed.\n"); + return false; + } - /* Resovle method com.intel.aee.ble.BLEManager.callOnBLEStartDiscovery(BLEDevice) */ - d1[0].class_header = class_BLEDevice; - method_callOnBLEStartDiscovery = jeff_lookup_method(class_BLEManager, "callOnBLEStartDiscovery", 1, d1); - if (!method_callOnBLEStartDiscovery) { - app_manager_printf("App Manager start failed: resolve method BLEManager.callOnBLEStartDiscovery() failed.\n"); - return false; - } + /* Resolve method com.intel.aee.Sensor.callOnSensorEvent() */ + method_callOnSensorEvent = + jeff_lookup_method(class_Sensor, "callOnSensorEvent", 0, d); + if (!method_callOnSensorEvent) { + app_manager_printf("App Manager start failed: resolve method " + "Sensor.callOnSensorEvent() failed.\n"); + return false; + } - /* Resovle method com.intel.aee.ble.BLEManager.callOnBLEConnected(BLEDevice) */ - JeffDescriptorFull d2_1[] = { {JEFF_TYPE_OBJECT | JEFF_TYPE_REF, 0, class_BLEDevice}, - { JEFF_TYPE_INT, 0, NULL}, - { JEFF_TYPE_VOID, 0, NULL}}; - method_callOnBLEConnected = jeff_lookup_method(class_BLEManager, "callOnBLEConnected", 2, d2_1); - if (!method_callOnBLEConnected) { - app_manager_printf("App Manager start failed: resolve method BLEManager.callOnBLEConnected() failed.\n"); - return false; - } + /* Resovle method + * com.intel.aee.ble.BLEManager.callOnBLEStartDiscovery(BLEDevice) */ + d1[0].class_header = class_BLEDevice; + method_callOnBLEStartDiscovery = + jeff_lookup_method(class_BLEManager, "callOnBLEStartDiscovery", 1, d1); + if (!method_callOnBLEStartDiscovery) { + app_manager_printf("App Manager start failed: resolve method " + "BLEManager.callOnBLEStartDiscovery() failed.\n"); + return false; + } - /* Resovle method com.intel.aee.ble.BLEManager.method_callOnBLENotification(BLEDevice,byte[]) */ - JeffDescriptorFull d2_2[] = { {JEFF_TYPE_OBJECT | JEFF_TYPE_REF, 0, class_BLEDevice}, - { JEFF_TYPE_BYTE | JEFF_TYPE_REF | JEFF_TYPE_MONO, 1, NULL}, - { JEFF_TYPE_INT, 0, NULL}, - { JEFF_TYPE_INT, 0, NULL}, - { JEFF_TYPE_VOID, 0, NULL}}; - method_callOnBLENotification = jeff_lookup_method(class_BLEManager, "callOnBLENotification", 4, d2_2); - if (!method_callOnBLENotification) { - app_manager_printf("App Manager start failed: resolve method BLEManager.callOnBLENotification() failed.\n"); - return false; - } + /* Resovle method + * com.intel.aee.ble.BLEManager.callOnBLEConnected(BLEDevice) */ + JeffDescriptorFull d2_1[] = { { JEFF_TYPE_OBJECT | JEFF_TYPE_REF, 0, + class_BLEDevice }, + { JEFF_TYPE_INT, 0, NULL }, + { JEFF_TYPE_VOID, 0, NULL } }; + method_callOnBLEConnected = + jeff_lookup_method(class_BLEManager, "callOnBLEConnected", 2, d2_1); + if (!method_callOnBLEConnected) { + app_manager_printf("App Manager start failed: resolve method " + "BLEManager.callOnBLEConnected() failed.\n"); + return false; + } - /* Resovle method com.intel.aee.ble.BLEManager.callOnBLEConnected(BLEDevice,byte[]) */ - method_callOnBLEIndication = jeff_lookup_method(class_BLEManager, "callOnBLEIndication", 4, d2_2); - if (!method_callOnBLEIndication) { - app_manager_printf("App Manager start failed: resolve method BLEManager.callOnBLEIndication() failed.\n"); - return false; - } + /* Resovle method + * com.intel.aee.ble.BLEManager.method_callOnBLENotification(BLEDevice,byte[]) + */ + JeffDescriptorFull d2_2[] = { + { JEFF_TYPE_OBJECT | JEFF_TYPE_REF, 0, class_BLEDevice }, + { JEFF_TYPE_BYTE | JEFF_TYPE_REF | JEFF_TYPE_MONO, 1, NULL }, + { JEFF_TYPE_INT, 0, NULL }, + { JEFF_TYPE_INT, 0, NULL }, + { JEFF_TYPE_VOID, 0, NULL } + }; + method_callOnBLENotification = + jeff_lookup_method(class_BLEManager, "callOnBLENotification", 4, d2_2); + if (!method_callOnBLENotification) { + app_manager_printf("App Manager start failed: resolve method " + "BLEManager.callOnBLENotification() failed.\n"); + return false; + } - /* Resovle method com.intel.aee.ble.BLEManager.callOnBLEConnected(BLEDevice) */ - d1[0].class_header = class_BLEDevice; - method_callOnBLEDisconnected = jeff_lookup_method(class_BLEManager, "callOnBLEDisconnected", 1, d1); - if (!method_callOnBLEDisconnected) { - app_manager_printf("App Manager start failed: resolve method BLEManager.callOnBLEDisconnected() failed.\n"); - return false; - } + /* Resovle method + * com.intel.aee.ble.BLEManager.callOnBLEConnected(BLEDevice,byte[]) */ + method_callOnBLEIndication = + jeff_lookup_method(class_BLEManager, "callOnBLEIndication", 4, d2_2); + if (!method_callOnBLEIndication) { + app_manager_printf("App Manager start failed: resolve method " + "BLEManager.callOnBLEIndication() failed.\n"); + return false; + } - /* Resovle method com.intel.aee.ble.BLEManager.callOnBLEConnected(BLEDevice) */ - method_callOnBLEPasskeyEntry = jeff_lookup_method(class_BLEManager, "callOnBLEPasskeyEntry", 1, d1); - if (!method_callOnBLEPasskeyEntry) { - app_manager_printf("App Manager start failed: resolve method BLEManager.callOnBLEPasskeyEntry() failed.\n"); - return false; - } - /* Resovle method void com.intel.aee.gpio.GPIOChannel.callOnGPIOInterrupt() */ - method_callOnGPIOInterrupt = jeff_lookup_method(class_GPIOChannel, "callOnGPIOInterrupt", 0, d); - if (!method_callOnGPIOInterrupt) { - app_manager_printf("App Manager start failed: resolve method GPIOChannel.callOnGPIOInterrupt() failed.\n"); - return false; - } + /* Resovle method + * com.intel.aee.ble.BLEManager.callOnBLEConnected(BLEDevice) */ + d1[0].class_header = class_BLEDevice; + method_callOnBLEDisconnected = + jeff_lookup_method(class_BLEManager, "callOnBLEDisconnected", 1, d1); + if (!method_callOnBLEDisconnected) { + app_manager_printf("App Manager start failed: resolve method " + "BLEManager.callOnBLEDisconnected() failed.\n"); + return false; + } - JeffDescriptorFull d2[] = { {JEFF_TYPE_BYTE | JEFF_TYPE_REF | JEFF_TYPE_MONO, 1, NULL}, - { JEFF_TYPE_OBJECT | JEFF_TYPE_REF, 0, class_BLEDevice}}; - /* Resovle method com.intel.aee.ble.BLEManager.getBLEDevice(byte []) */ - method_callOnBLEManagerGetBLEDevice = jeff_lookup_method(class_BLEManager, - "getBLEDevice", 1, d2); - if (!method_callOnBLEManagerGetBLEDevice) { - app_manager_printf( - "App Manager start failed: resolve method BLEManager.getBLEDevice() failed.\n"); - return false; - } + /* Resovle method + * com.intel.aee.ble.BLEManager.callOnBLEConnected(BLEDevice) */ + method_callOnBLEPasskeyEntry = + jeff_lookup_method(class_BLEManager, "callOnBLEPasskeyEntry", 1, d1); + if (!method_callOnBLEPasskeyEntry) { + app_manager_printf("App Manager start failed: resolve method " + "BLEManager.callOnBLEPasskeyEntry() failed.\n"); + return false; + } + /* Resovle method void + * com.intel.aee.gpio.GPIOChannel.callOnGPIOInterrupt() */ + method_callOnGPIOInterrupt = + jeff_lookup_method(class_GPIOChannel, "callOnGPIOInterrupt", 0, d); + if (!method_callOnGPIOInterrupt) { + app_manager_printf("App Manager start failed: resolve method " + "GPIOChannel.callOnGPIOInterrupt() failed.\n"); + return false; + } - return true; + JeffDescriptorFull d2[] = { + { JEFF_TYPE_BYTE | JEFF_TYPE_REF | JEFF_TYPE_MONO, 1, NULL }, + { JEFF_TYPE_OBJECT | JEFF_TYPE_REF, 0, class_BLEDevice } + }; + /* Resovle method com.intel.aee.ble.BLEManager.getBLEDevice(byte []) */ + method_callOnBLEManagerGetBLEDevice = + jeff_lookup_method(class_BLEManager, "getBLEDevice", 1, d2); + if (!method_callOnBLEManagerGetBLEDevice) { + app_manager_printf("App Manager start failed: resolve method " + "BLEManager.getBLEDevice() failed.\n"); + return false; } - static void - jeff_module_watchdog_kill(module_data *m_data) - { - jeff_applet_data *applet_data = (jeff_applet_data*)m_data->internal_data; + return true; +} - app_manager_printf("Watchdog interrupt the applet %s\n", m_data->module_name); +static void +jeff_module_watchdog_kill(module_data *m_data) +{ + jeff_applet_data *applet_data = (jeff_applet_data *)m_data->internal_data; - jeff_runtime_interrupt_instance(applet_data->vm_instance, true); + app_manager_printf("Watchdog interrupt the applet %s\n", + m_data->module_name); - /* Exit applet queue loop run */ - bh_queue_exit_loop_run(m_data->queue); + jeff_runtime_interrupt_instance(applet_data->vm_instance, true); - /* Wait the end of the applet instance. If timeout, it means applet - * is busy executing native code, then try to cancle the main thread. */ - if (applet_data->vm_instance->main_file) - jeff_runtime_wait_for_instance(applet_data->vm_instance, 3000); + /* Exit applet queue loop run */ + bh_queue_exit_loop_run(m_data->queue); - if (applet_data->vm_instance->main_file) { - app_manager_printf("Watchdog cancel applet main thread.\n"); - os_thread_cancel(applet_data->vm_instance->main_tlr.handle); - /* k_thread_abort(applet_data->vm_instance->main_tlr.handle); */ - } + /* Wait the end of the applet instance. If timeout, it means applet + * is busy executing native code, then try to cancle the main thread. */ + if (applet_data->vm_instance->main_file) + jeff_runtime_wait_for_instance(applet_data->vm_instance, 3000); - send_exception_event_to_host(m_data->module_name, "java.lang.InterruptedException"); - cleanup_applet_resource(m_data); - app_manager_printf("Watchdog interrupt Jeff applet done.\n"); + if (applet_data->vm_instance->main_file) { + app_manager_printf("Watchdog cancel applet main thread.\n"); + os_thread_cancel(applet_data->vm_instance->main_tlr.handle); + /* k_thread_abort(applet_data->vm_instance->main_tlr.handle); */ } - static bool - jeff_module_handle_host_url(void *queue_msg) - { + send_exception_event_to_host(m_data->module_name, + "java.lang.InterruptedException"); + cleanup_applet_resource(m_data); + app_manager_printf("Watchdog interrupt Jeff applet done.\n"); +} + +static bool +jeff_module_handle_host_url(void *queue_msg) +{ #if BEIHAI_ENABLE_TOOL_AGENT != 0 - bh_queue_msg_t *msg = (bh_queue_msg_t *)queue_msg; - - if (msg->message_type == COAP_PARSED) { - coap_packet_t *packet = (coap_packet_t *)msg->payload; - attr_container_t *attr_cont = (attr_container_t *)packet->payload; - const char *url = NULL; - int url_len = 0, mid; - - bh_memcpy_s(&mid, sizeof(uint32), packet->token, sizeof(uint32)); - url_len = coap_get_header_uri_path(packet, &url); - - /* Send request to tool agent */ - if (url_len >= 12 && memcmp(url, "/tool_agent/", 12) == 0) { - module_data *m_data; - jeff_applet_data *applet_data; - unsigned attr_cont_len = 0, req_msg_len; - bh_queue_msg_t *tool_agent_msg; - bh_request_msg_t *req_msg; - char url_buf[256] = {0}, *p = url_buf; - char applet_name[128] = {0}; - - /* Resolve applet name */ - bh_memcpy_s(url_buf, sizeof(url_buf), url + 12, url_len - 12); - while (*p != '/' && *p != '\0') + bh_queue_msg_t *msg = (bh_queue_msg_t *)queue_msg; + + if (msg->message_type == COAP_PARSED) { + coap_packet_t *packet = (coap_packet_t *)msg->payload; + attr_container_t *attr_cont = (attr_container_t *)packet->payload; + const char *url = NULL; + int url_len = 0, mid; + + bh_memcpy_s(&mid, sizeof(uint32), packet->token, sizeof(uint32)); + url_len = coap_get_header_uri_path(packet, &url); + + /* Send request to tool agent */ + if (url_len >= 12 && memcmp(url, "/tool_agent/", 12) == 0) { + module_data *m_data; + jeff_applet_data *applet_data; + unsigned attr_cont_len = 0, req_msg_len; + bh_queue_msg_t *tool_agent_msg; + bh_request_msg_t *req_msg; + char url_buf[256] = { 0 }, *p = url_buf; + char applet_name[128] = { 0 }; + + /* Resolve applet name */ + bh_memcpy_s(url_buf, sizeof(url_buf), url + 12, url_len - 12); + while (*p != '/' && *p != '\0') p++; - bh_memcpy_s(applet_name, sizeof(applet_name), url_buf, p - url_buf); - app_manager_printf("Send request to tool agent of applet: %s\n", applet_name); + bh_memcpy_s(applet_name, sizeof(applet_name), url_buf, p - url_buf); + app_manager_printf("Send request to tool agent of applet: %s\n", + applet_name); + + /* Check applet name */ + if (!(m_data = app_manager_lookup_module_data(applet_name))) { + SEND_ERR_RESPONSE(mid, "Send request to tool agent failed: " + "invalid applet name"); + return false; + } - /* Check applet name */ - if (!(m_data = app_manager_lookup_module_data(applet_name))) { - SEND_ERR_RESPONSE(mid, "Send request to tool agent failed: invalid applet name"); + applet_data = (jeff_applet_data *)m_data->internal_data; + /* Attach debug: start the tool agent firstly */ + if (packet->code == COAP_PUT) { + if (is_tool_agent_running(m_data)) { + SEND_ERR_RESPONSE(mid, "Attach debug failed: tool " + "agent is already exist."); return false; } - applet_data = (jeff_applet_data*)m_data->internal_data; - /* Attach debug: start the tool agent firstly */ - if (packet->code == COAP_PUT) { - if (is_tool_agent_running(m_data)) { - SEND_ERR_RESPONSE(mid, "Attach debug failed: tool agent is already exist."); - return false; - } - - applet_data->debug_mode = true; - - /* Create tool agent queue */ - if (!(applet_data->tool_agent_queue = bh_queue_create())) { - SEND_ERR_RESPONSE(mid, "Attach debug failed: create tool agent queue failed."); - return false; - } - - /* Start tool agent thread */ - if (!jeff_tool_start_agent(applet_data->vm_instance, applet_data->tool_agent_queue)) { - bh_queue_destroy(applet_data->tool_agent_queue, NULL); - SEND_ERR_RESPONSE(mid, "Attach debug failed: start tool agent failed"); - return false; - } - - app_manager_printf("Attach debug: start tool agent of applet %s success.\n", applet_name); - app_send_response_to_host(mid, CREATED_2_01, NULL); /* OK */ - } else { - /* Check tool agent running */ - if (!is_tool_agent_running(m_data)) { - SEND_ERR_RESPONSE(mid, "Send request to tool agent failed: tool agent is not running"); - return false; - } - - /* Create queue message for tool agent */ - 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; - } - - if (attr_cont) - attr_cont_len = attr_container_get_serialize_length(attr_cont); - - req_msg_len = sizeof(bh_request_msg_t) + strlen(p) + 1 + attr_cont_len; - - /* Create request message */ - if (!(req_msg = APP_MGR_MALLOC(req_msg_len))) { - SEND_ERR_RESPONSE(mid, "Send request to applet failed: allocate memory failed"); - APP_MGR_FREE(tool_agent_msg); - return false; - } - - /* Set request message */ - memset(req_msg, 0, req_msg_len); - req_msg->mid = mid; - req_msg->url = (char*)req_msg + sizeof(bh_request_msg_t); - bh_strcpy_s(req_msg->url, strlen(p)+1, p); /* Actual url sent to tool agent */ - req_msg->action = packet->code; - req_msg->fmt = 0; - if (attr_cont) { - req_msg->payload = (char*)req_msg + sizeof(bh_request_msg_t) + - strlen(p) + 1; - attr_container_serialize(req_msg->payload, attr_cont); - } - - /* Set queue message and send to tool agent's queue */ - tool_agent_msg->message_type = JDWP_REQUEST; - 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)) { - 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; - } - - /* app_manager_printf("Send request to tool agent of applet %s success.\n", applet_name); */ + applet_data->debug_mode = true; + + /* Create tool agent queue */ + if (!(applet_data->tool_agent_queue = bh_queue_create())) { + SEND_ERR_RESPONSE(mid, "Attach debug failed: create " + "tool agent queue failed."); + return false; } - return true; + /* Start tool agent thread */ + if (!jeff_tool_start_agent(applet_data->vm_instance, + applet_data->tool_agent_queue)) { + bh_queue_destroy(applet_data->tool_agent_queue, NULL); + SEND_ERR_RESPONSE( + mid, "Attach debug failed: start tool agent failed"); + return false; + } + + app_manager_printf("Attach debug: start tool agent of " + "applet %s success.\n", + applet_name); + app_send_response_to_host(mid, CREATED_2_01, NULL); /* OK */ + } + else { + /* Check tool agent running */ + if (!is_tool_agent_running(m_data)) { + SEND_ERR_RESPONSE(mid, "Send request to tool agent failed: " + "tool agent is not running"); + return false; + } + + /* Create queue message for tool agent */ + 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; + } + + if (attr_cont) + attr_cont_len = + attr_container_get_serialize_length(attr_cont); + + req_msg_len = + sizeof(bh_request_msg_t) + strlen(p) + 1 + attr_cont_len; + + /* Create request message */ + if (!(req_msg = APP_MGR_MALLOC(req_msg_len))) { + SEND_ERR_RESPONSE(mid, "Send request to applet failed: " + "allocate memory failed"); + APP_MGR_FREE(tool_agent_msg); + return false; + } + + /* Set request message */ + memset(req_msg, 0, req_msg_len); + req_msg->mid = mid; + req_msg->url = (char *)req_msg + sizeof(bh_request_msg_t); + bh_strcpy_s(req_msg->url, strlen(p) + 1, + p); /* Actual url sent to tool agent */ + req_msg->action = packet->code; + req_msg->fmt = 0; + if (attr_cont) { + req_msg->payload = (char *)req_msg + + sizeof(bh_request_msg_t) + strlen(p) + + 1; + attr_container_serialize(req_msg->payload, attr_cont); + } + + /* Set queue message and send to tool agent's queue */ + tool_agent_msg->message_type = JDWP_REQUEST; + 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)) { + 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; + } + + /* app_manager_printf("Send request to tool agent of applet + * %s success.\n", applet_name); */ } + + return true; } -#endif /* BEIHAI_ENABLE_TOOL_AGENT != 0 */ - return false; } +#endif /* BEIHAI_ENABLE_TOOL_AGENT != 0 */ + return false; +} - static module_data* - jeff_module_get_module_data(void) - { - JeffThreadLocalRoot *self = jeff_runtime_get_tlr(); - return (module_data *)self->il_root->start_routine_arg; - } +static module_data * +jeff_module_get_module_data(void) +{ + JeffThreadLocalRoot *self = jeff_runtime_get_tlr(); + return (module_data *)self->il_root->start_routine_arg; +} #if BEIHAI_ENABLE_TOOL_AGENT != 0 -#define JDWP_HANDSHAKE_MAGIC "JDWP-Handshake" -#define JDWP_HANDSHAKE_LEN (sizeof (JDWP_HANDSHAKE_MAGIC) - 1) +#define JDWP_HANDSHAKE_MAGIC "JDWP-Handshake" +#define JDWP_HANDSHAKE_LEN (sizeof(JDWP_HANDSHAKE_MAGIC) - 1) -#define JDWP_PAYLOAD_KEY "jdwp" +#define JDWP_PAYLOAD_KEY "jdwp" - static bool debug = true; +static bool debug = true; - static bool - send_msg_to_host (int mid, const char *url, int code, const uint8 *msg, unsigned size) - { - bool ret; - int payload_len = 0; - attr_container_t *payload = NULL; +static bool +send_msg_to_host(int mid, const char *url, int code, const uint8 *msg, + unsigned size) +{ + bool ret; + int payload_len = 0; + attr_container_t *payload = NULL; - if (msg) { - if ((payload = attr_container_create(""))) { - attr_container_set_bytearray(&payload, JDWP_PAYLOAD_KEY, (const int8_t *)msg, size); - payload_len = attr_container_get_serialize_length(payload); - } + if (msg) { + if ((payload = attr_container_create(""))) { + attr_container_set_bytearray(&payload, JDWP_PAYLOAD_KEY, + (const int8_t *)msg, size); + payload_len = attr_container_get_serialize_length(payload); } - ret = app_send_msg_to_host(mid, url, code, (char*)payload, payload_len); + } + ret = app_send_msg_to_host(mid, url, code, (char *)payload, payload_len); - if (payload) + if (payload) attr_container_destroy(payload); - return ret; - } + return ret; +} - static bool - send_response(int mid, int code, const uint8 *msg, unsigned size) - { - return send_msg_to_host(mid, NULL, code, msg, size); - } +static bool +send_response(int mid, int code, const uint8 *msg, unsigned size) +{ + return send_msg_to_host(mid, NULL, code, msg, size); +} - static bool - send_packet_response(int mid, int code, JeffBuffer *packet) - { - int size; +static bool +send_packet_response(int mid, int code, JeffBuffer *packet) +{ + int size; - if ((size = jeff_buffer_size(packet)) == 0) + if ((size = jeff_buffer_size(packet)) == 0) /* No data need to be written, succeed. */ return true; - return send_msg_to_host(mid, NULL, code, jeff_buffer_at(packet, 0), size); - } + return send_msg_to_host(mid, NULL, code, jeff_buffer_at(packet, 0), size); +} - void - jeff_tool_event_publish(uint8 *evtbuf, unsigned size) - { - char *prefix = "/jdwp/", *url = NULL; - int url_len; +void +jeff_tool_event_publish(uint8 *evtbuf, unsigned size) +{ + char *prefix = "/jdwp/", *url = NULL; + int url_len; - url_len = strlen(prefix) + strlen(app_manager_get_module_name(Module_Jeff)); - if (NULL == (url = jeff_runtime_malloc(url_len + 1))) + url_len = strlen(prefix) + strlen(app_manager_get_module_name(Module_Jeff)); + if (NULL == (url = jeff_runtime_malloc(url_len + 1))) return; - bh_strcpy_s(url,url_len + 1, prefix); - bh_strcat_s(url,url_len + 1, app_manager_get_module_name(Module_Jeff)); + bh_strcpy_s(url, url_len + 1, prefix); + bh_strcat_s(url, url_len + 1, app_manager_get_module_name(Module_Jeff)); - /* Event is sent as request so we set code as COAP_PUT */ - if (event_is_registered(url)) + /* Event is sent as request so we set code as COAP_PUT */ + if (event_is_registered(url)) send_msg_to_host(0, url, COAP_PUT, evtbuf, size); - jeff_runtime_free(url); - } - -#define SEND_ERROR_RESPONSE(err_msg) do { \ - app_manager_printf("%s\n", err_msg); \ - send_response(req_msg->mid, INTERNAL_SERVER_ERROR_5_00,\ - (uint8 *)err_msg, strlen(err_msg) + 1); \ - } while (0) - - /* Queue callback of tool agent */ - void - tool_agent_queue_callback(void *arg) - { - bh_queue_msg_t *msg = (bh_queue_msg_t*)arg; - - if (msg->message_type == JDWP_REQUEST) { - bh_request_msg_t *req_msg = (bh_request_msg_t*)msg->payload; - attr_container_t *attr_cont = (attr_container_t*)req_msg->payload; - JeffThreadLocalRoot *self = jeff_runtime_get_tlr(); - JeffInstanceLocalRoot *cur_instance = self->il_root; - JeffToolAgent *agent = cur_instance->tool_agent; - bh_queue *queue = (bh_queue *)self->start_routine_arg; - - if (debug) - app_manager_printf("Tool Agent of applet %s got request, url %s, action %d\n", - app_manager_get_module_name(Module_Jeff), req_msg->url, req_msg->action); - - /* Handshake or Process Request */ - if (req_msg->action == COAP_GET) { - uint8 *buf; - unsigned buf_len; - - if (!attr_cont - || !(buf = (uint8*) - attr_container_get_as_bytearray(attr_cont, JDWP_PAYLOAD_KEY, &buf_len))) { - SEND_ERROR_RESPONSE("Tool Agent fail: invalid JDWP payload."); + jeff_runtime_free(url); +} + +#define SEND_ERROR_RESPONSE(err_msg) \ + do { \ + app_manager_printf("%s\n", err_msg); \ + send_response(req_msg->mid, INTERNAL_SERVER_ERROR_5_00, \ + (uint8 *)err_msg, strlen(err_msg) + 1); \ + } while (0) + +/* Queue callback of tool agent */ +void +tool_agent_queue_callback(void *arg) +{ + bh_queue_msg_t *msg = (bh_queue_msg_t *)arg; + + if (msg->message_type == JDWP_REQUEST) { + bh_request_msg_t *req_msg = (bh_request_msg_t *)msg->payload; + attr_container_t *attr_cont = (attr_container_t *)req_msg->payload; + JeffThreadLocalRoot *self = jeff_runtime_get_tlr(); + JeffInstanceLocalRoot *cur_instance = self->il_root; + JeffToolAgent *agent = cur_instance->tool_agent; + bh_queue *queue = (bh_queue *)self->start_routine_arg; + + if (debug) + app_manager_printf( + "Tool Agent of applet %s got request, url %s, action %d\n", + app_manager_get_module_name(Module_Jeff), req_msg->url, + req_msg->action); + + /* Handshake or Process Request */ + if (req_msg->action == COAP_GET) { + uint8 *buf; + unsigned buf_len; + + if (!attr_cont + || !(buf = (uint8 *)attr_container_get_as_bytearray( + attr_cont, JDWP_PAYLOAD_KEY, &buf_len))) { + SEND_ERROR_RESPONSE("Tool Agent fail: invalid JDWP payload."); + goto fail; + } + + if (!agent->connected) { + if (buf_len != JDWP_HANDSHAKE_LEN + || memcmp(buf, JDWP_HANDSHAKE_MAGIC, JDWP_HANDSHAKE_LEN)) { + SEND_ERROR_RESPONSE("Tool Agent fail: handshake fail."); goto fail; } - if (!agent->connected) { - if (buf_len != JDWP_HANDSHAKE_LEN - || memcmp (buf, JDWP_HANDSHAKE_MAGIC, JDWP_HANDSHAKE_LEN)) { - SEND_ERROR_RESPONSE("Tool Agent fail: handshake fail."); - goto fail; - } - - /* Handshake success and response */ - agent->connected = true; - send_response(req_msg->mid, CONTENT_2_05, buf, buf_len); - } else { - /* TODO: tool-agent thread should reuse the request/reply buffer to avoid allocating memory repeatedly */ - JeffBuffer request, reply; - - /* Initialize the package buffers. */ - jeff_buffer_init(&request); - jeff_buffer_init(&reply); - - if (!jeff_buffer_resize(&request, buf_len)) { - SEND_ERROR_RESPONSE("Tool Agent fail: resize buffer fail."); - jeff_buffer_destroy(&request); - jeff_buffer_destroy(&reply); - goto fail; - } - - /* Copy data from request to jeff buffer */ - bh_memcpy_s(jeff_buffer_at(&request, 0), jeff_buffer_size(&request), buf, buf_len); - - /* Handle JDWP request */ - if (!jeff_tool_handle_packet(agent, &request, &reply)) { - SEND_ERROR_RESPONSE("Tool agent fail: handle request fail."); - jeff_buffer_destroy(&request); - jeff_buffer_destroy(&reply); - goto fail; - } - - /* Response JDWP reply */ - send_packet_response(req_msg->mid, CONTENT_2_05, &reply); - - /* Destroy the package buffers. */ + /* Handshake success and response */ + agent->connected = true; + send_response(req_msg->mid, CONTENT_2_05, buf, buf_len); + } + else { + /* TODO: tool-agent thread should reuse the request/reply + * buffer to avoid allocating memory repeatedly */ + JeffBuffer request, reply; + + /* Initialize the package buffers. */ + jeff_buffer_init(&request); + jeff_buffer_init(&reply); + + if (!jeff_buffer_resize(&request, buf_len)) { + SEND_ERROR_RESPONSE("Tool Agent fail: resize buffer fail."); jeff_buffer_destroy(&request); jeff_buffer_destroy(&reply); + goto fail; } - } - /* Debugger disconnect */ - else if (req_msg->action == COAP_DELETE) { - send_response(req_msg->mid, DELETED_2_02, NULL, 0); - bh_queue_exit_loop_run(queue); - } - else { - SEND_ERROR_RESPONSE("Tool agent fail: invalid request."); - goto fail; - } - APP_MGR_FREE(req_msg); - APP_MGR_FREE(msg); - return; + /* Copy data from request to jeff buffer */ + bh_memcpy_s(jeff_buffer_at(&request, 0), + jeff_buffer_size(&request), buf, buf_len); + + /* Handle JDWP request */ + if (!jeff_tool_handle_packet(agent, &request, &reply)) { + SEND_ERROR_RESPONSE( + "Tool agent fail: handle request fail."); + jeff_buffer_destroy(&request); + jeff_buffer_destroy(&reply); + goto fail; + } + + /* Response JDWP reply */ + send_packet_response(req_msg->mid, CONTENT_2_05, &reply); - fail: + /* Destroy the package buffers. */ + jeff_buffer_destroy(&request); + jeff_buffer_destroy(&reply); + } + } + /* Debugger disconnect */ + else if (req_msg->action == COAP_DELETE) { + send_response(req_msg->mid, DELETED_2_02, NULL, 0); bh_queue_exit_loop_run(queue); - APP_MGR_FREE(req_msg); + } + else { + SEND_ERROR_RESPONSE("Tool agent fail: invalid request."); + goto fail; } + APP_MGR_FREE(req_msg); APP_MGR_FREE(msg); + return; + + fail: + bh_queue_exit_loop_run(queue); + APP_MGR_FREE(req_msg); } - void - tool_agent_queue_free_callback(void *message) - { - bh_queue_msg_t *msg = (bh_queue_msg_t*)message; + APP_MGR_FREE(msg); +} - if (msg->message_type == JDWP_REQUEST) { - bh_request_msg_t *req_msg = (bh_request_msg_t*)msg->payload; - APP_MGR_FREE(req_msg); - } +void +tool_agent_queue_free_callback(void *message) +{ + bh_queue_msg_t *msg = (bh_queue_msg_t *)message; - APP_MGR_FREE(msg); + if (msg->message_type == JDWP_REQUEST) { + bh_request_msg_t *req_msg = (bh_request_msg_t *)msg->payload; + APP_MGR_FREE(req_msg); } -#endif /* BEIHAI_ENABLE_TOOL_AGENT != 0 */ + APP_MGR_FREE(msg); +} - module_interface jeff_module_interface = { - jeff_module_init, - jeff_module_install, - jeff_module_uninstall, - jeff_module_watchdog_kill, - jeff_module_handle_host_url, - jeff_module_get_module_data, - NULL - }; +#endif /* BEIHAI_ENABLE_TOOL_AGENT != 0 */ + +/* clang-format off */ +module_interface jeff_module_interface = { + jeff_module_init, + jeff_module_install, + jeff_module_uninstall, + jeff_module_watchdog_kill, + jeff_module_handle_host_url, + jeff_module_get_module_data, + NULL +}; +/* clang-format on */ #endif diff --git a/core/app-mgr/app-manager/module_utils.c b/core/app-mgr/app-manager/module_utils.c index 561ef24fea..b4b25e4a91 100644 --- a/core/app-mgr/app-manager/module_utils.c +++ b/core/app-mgr/app-manager/module_utils.c @@ -17,13 +17,15 @@ korp_mutex module_data_list_lock; /* Module data list */ module_data *module_data_list; -bool module_data_list_init() +bool +module_data_list_init() { module_data_list = NULL; return !os_mutex_init(&module_data_list_lock) ? true : false; } -void module_data_list_destroy() +void +module_data_list_destroy() { os_mutex_lock(&module_data_list_lock); @@ -38,7 +40,8 @@ void module_data_list_destroy() os_mutex_destroy(&module_data_list_lock); } -static void module_data_list_add(module_data *m_data) +static void +module_data_list_add(module_data *m_data) { static uint32 module_id_max = 1; os_mutex_lock(&module_data_list_lock); @@ -49,7 +52,8 @@ static void module_data_list_add(module_data *m_data) m_data->id = module_id_max++; if (!module_data_list) { module_data_list = m_data; - } else { + } + else { /* Set as head */ m_data->next = module_data_list; module_data_list = m_data; @@ -57,7 +61,8 @@ static void module_data_list_add(module_data *m_data) os_mutex_unlock(&module_data_list_lock); } -void module_data_list_remove(module_data *m_data) +void +module_data_list_remove(module_data *m_data) { os_mutex_lock(&module_data_list_lock); if (module_data_list) { @@ -76,7 +81,7 @@ void module_data_list_remove(module_data *m_data) os_mutex_unlock(&module_data_list_lock); } -module_data* +module_data * module_data_list_lookup(const char *module_name) { os_mutex_lock(&module_data_list_lock); @@ -96,7 +101,7 @@ module_data_list_lookup(const char *module_name) return NULL; } -module_data* +module_data * module_data_list_lookup_id(unsigned int module_id) { os_mutex_lock(&module_data_list_lock); @@ -119,72 +124,78 @@ module_data_list_lookup_id(unsigned int module_id) module_data * app_manager_get_module_data(uint32 module_type, void *module_inst) { - if (module_type < Module_Max - && g_module_interfaces[module_type] + if (module_type < Module_Max && g_module_interfaces[module_type] && g_module_interfaces[module_type]->module_get_module_data) - return g_module_interfaces[module_type]->module_get_module_data(module_inst); + return g_module_interfaces[module_type]->module_get_module_data( + module_inst); return NULL; } -void* +void * app_manager_get_module_queue(uint32 module_type, void *module_inst) { module_data *m_data = app_manager_get_module_data(module_type, module_inst); return m_data ? m_data->queue : NULL; } -const char* +const char * app_manager_get_module_name(uint32 module_type, void *module_inst) { module_data *m_data = app_manager_get_module_data(module_type, module_inst); return m_data ? m_data->module_name : NULL; } -unsigned int app_manager_get_module_id(uint32 module_type, void *module_inst) +unsigned int +app_manager_get_module_id(uint32 module_type, void *module_inst) { module_data *m_data = app_manager_get_module_data(module_type, module_inst); return m_data ? m_data->id : ID_NONE; } -void* +void * app_manager_get_module_heap(uint32 module_type, void *module_inst) { module_data *m_data = app_manager_get_module_data(module_type, module_inst); return m_data ? m_data->heap : NULL; } -module_data* +module_data * app_manager_lookup_module_data(const char *name) { return module_data_list_lookup(name); } -void app_manager_add_module_data(module_data *m_data) +void +app_manager_add_module_data(module_data *m_data) { module_data_list_add(m_data); } -void app_manager_del_module_data(module_data *m_data) +void +app_manager_del_module_data(module_data *m_data) { module_data_list_remove(m_data); release_module(m_data); } -bool app_manager_is_interrupting_module(uint32 module_type, void *module_inst) +bool +app_manager_is_interrupting_module(uint32 module_type, void *module_inst) { module_data *m_data = app_manager_get_module_data(module_type, module_inst); return m_data ? m_data->wd_timer.is_interrupting : false; } -extern void destroy_module_timer_ctx(unsigned int module_id); +extern void +destroy_module_timer_ctx(unsigned int module_id); -void release_module(module_data *m_data) +void +release_module(module_data *m_data) { watchdog_timer_destroy(&m_data->wd_timer); #ifdef HEAP_ENABLED /* TODO */ - if(m_data->heap) + if (m_data->heap) gc_destroy_for_instance(m_data->heap); #endif @@ -198,7 +209,8 @@ void release_module(module_data *m_data) APP_MGR_FREE(m_data); } -uint32 check_modules_timer_expiry() +uint32 +check_modules_timer_expiry() { os_mutex_lock(&module_data_list_lock); module_data *p = module_data_list; @@ -216,4 +228,3 @@ uint32 check_modules_timer_expiry() os_mutex_unlock(&module_data_list_lock); return ms_to_expiry; } - diff --git a/core/app-mgr/app-manager/module_wasm_app.c b/core/app-mgr/app-manager/module_wasm_app.c index f7752bd5bf..dd86524db1 100644 --- a/core/app-mgr/app-manager/module_wasm_app.c +++ b/core/app-mgr/app-manager/module_wasm_app.c @@ -20,25 +20,27 @@ #include "aot_export.h" #endif +/* clang-format off */ #if WASM_ENABLE_INTERP != 0 || WASM_ENABLE_JIT != 0 /* Wasm bytecode file 4 version bytes */ static uint8 wasm_bytecode_version[4] = { - (uint8) 0x01, - (uint8) 0x00, - (uint8) 0x00, - (uint8) 0x00 + (uint8)0x01, + (uint8)0x00, + (uint8)0x00, + (uint8)0x00 }; #endif #if WASM_ENABLE_AOT != 0 /* Wasm aot file 4 version bytes */ static uint8 wasm_aot_version[4] = { - (uint8) 0x02, - (uint8) 0x00, - (uint8) 0x00, - (uint8) 0x00 + (uint8)0x02, + (uint8)0x00, + (uint8)0x00, + (uint8)0x00 }; #endif +/* clang-format on */ static union { int a; @@ -133,8 +135,7 @@ destroy_all_wasm_sections(wasm_section_list_t sections); static void destroy_part_wasm_sections(wasm_section_list_t *p_sections, - uint8 *section_types, - int section_cnt); + uint8 *section_types, int section_cnt); #endif #if WASM_ENABLE_AOT != 0 @@ -142,8 +143,7 @@ static void destroy_all_aot_sections(aot_section_list_t sections); static void -destroy_part_aot_sections(aot_section_list_t *p_sections, - uint8 *section_types, +destroy_part_aot_sections(aot_section_list_t *p_sections, uint8 *section_types, int section_cnt); #endif @@ -152,8 +152,9 @@ int g_msg_type[Max_Msg_Callback] = { 0 }; message_type_handler_t g_msg_callbacks[Max_Msg_Callback] = { 0 }; #define Max_Cleanup_Callback 10 -static resource_cleanup_handler_t -g_cleanup_callbacks[Max_Cleanup_Callback] = { 0 }; +static resource_cleanup_handler_t g_cleanup_callbacks[Max_Cleanup_Callback] = { + 0 +}; module_interface wasm_app_module_interface = { wasm_app_module_init, @@ -198,7 +199,6 @@ app_manager_lookup_function(const wasm_module_inst_t module_inst, return func; } - static void app_instance_queue_callback(void *queue_msg, void *arg) { @@ -207,174 +207,180 @@ app_instance_queue_callback(void *queue_msg, void *arg) wasm_module_inst_t inst = (wasm_module_inst_t)arg; module_data *m_data = app_manager_get_module_data(Module_WASM_App, inst); - wasm_data *wasm_app_data = (wasm_data*)m_data->internal_data; + wasm_data *wasm_app_data = (wasm_data *)m_data->internal_data; int message_type = bh_message_type(queue_msg); bh_assert(m_data); if (message_type < BASE_EVENT_MAX) { switch (message_type) { - case RESTFUL_REQUEST: { - request_t *request = (request_t *)bh_message_payload(queue_msg); - int size; - char *buffer; - int32 buffer_offset; - - app_manager_printf("App %s got request, url %s, action %d\n", - m_data->module_name, - request->url, - request->action); - - func_onRequest = app_manager_lookup_function(inst, - "_on_request", - "(i32i32)"); - if (!func_onRequest) { - app_manager_printf("Cannot find function onRequest\n"); - break; - } - - buffer = pack_request(request, &size); - if (buffer == NULL) - break; - - buffer_offset = wasm_runtime_module_dup_data(inst, buffer, size); - if (buffer_offset == 0) { - const char *exception = wasm_runtime_get_exception(inst); - if (exception) { - app_manager_printf("Got exception running wasm code: %s\n", - exception); - wasm_runtime_clear_exception(inst); - } - free_req_resp_packet(buffer); - break; - } - - free_req_resp_packet(buffer); - - argv[0] = (uint32) buffer_offset; - argv[1] = (uint32) size; - - if (!wasm_runtime_call_wasm(wasm_app_data->exec_env, func_onRequest, - 2, argv)) { - const char *exception = wasm_runtime_get_exception(inst); - bh_assert(exception); - app_manager_printf("Got exception running wasm code: %s\n", - exception); - wasm_runtime_clear_exception(inst); - wasm_runtime_module_free(inst, buffer_offset); - break; - } - - wasm_runtime_module_free(inst, buffer_offset); - app_manager_printf("Wasm app process request success.\n"); - break; - } - case RESTFUL_RESPONSE: { - wasm_function_inst_t func_onResponse; - response_t *response = (response_t *) bh_message_payload(queue_msg); - int size; - char *buffer; - int32 buffer_offset; - - app_manager_printf("App %s got response_t,status %d\n", - m_data->module_name, response->status); - - func_onResponse = - app_manager_lookup_function(inst, "_on_response", "(i32i32)"); - if (!func_onResponse) { - app_manager_printf("Cannot find function on_response\n"); - break; - } - - buffer = pack_response(response, &size); - if (buffer == NULL) - break; - - buffer_offset = wasm_runtime_module_dup_data(inst, buffer, size); - if (buffer_offset == 0) { - const char *exception = wasm_runtime_get_exception(inst); - if (exception) { - app_manager_printf("Got exception running wasm code: %s\n", - exception); - wasm_runtime_clear_exception(inst); - } - free_req_resp_packet(buffer); - break; - } - - free_req_resp_packet(buffer); - - argv[0] = (uint32) buffer_offset; - argv[1] = (uint32) size; - - if (!wasm_runtime_call_wasm(wasm_app_data->exec_env, func_onResponse, - 2, argv)) { - const char *exception = wasm_runtime_get_exception(inst); - bh_assert(exception); - app_manager_printf("Got exception running wasm code: %s\n", - exception); - wasm_runtime_clear_exception(inst); - wasm_runtime_module_free(inst, buffer_offset); - break; - } - - wasm_runtime_module_free(inst, buffer_offset); - app_manager_printf("Wasm app process response success.\n"); - break; + case RESTFUL_REQUEST: + { + request_t *request = (request_t *)bh_message_payload(queue_msg); + int size; + char *buffer; + int32 buffer_offset; + + app_manager_printf("App %s got request, url %s, action %d\n", + m_data->module_name, request->url, + request->action); + + func_onRequest = app_manager_lookup_function( + inst, "_on_request", "(i32i32)"); + if (!func_onRequest) { + app_manager_printf("Cannot find function onRequest\n"); + break; + } + + buffer = pack_request(request, &size); + if (buffer == NULL) + break; + + buffer_offset = + wasm_runtime_module_dup_data(inst, buffer, size); + if (buffer_offset == 0) { + const char *exception = wasm_runtime_get_exception(inst); + if (exception) { + app_manager_printf( + "Got exception running wasm code: %s\n", exception); + wasm_runtime_clear_exception(inst); + } + free_req_resp_packet(buffer); + break; + } + + free_req_resp_packet(buffer); + + argv[0] = (uint32)buffer_offset; + argv[1] = (uint32)size; + + if (!wasm_runtime_call_wasm(wasm_app_data->exec_env, + func_onRequest, 2, argv)) { + const char *exception = wasm_runtime_get_exception(inst); + bh_assert(exception); + app_manager_printf("Got exception running wasm code: %s\n", + exception); + wasm_runtime_clear_exception(inst); + wasm_runtime_module_free(inst, buffer_offset); + break; + } + + wasm_runtime_module_free(inst, buffer_offset); + app_manager_printf("Wasm app process request success.\n"); + break; } - default: { - for (int i = 0; i < Max_Msg_Callback; i++) { - if (g_msg_type[i] == message_type) { - g_msg_callbacks[i](m_data, queue_msg); - return; - } - } - app_manager_printf("Invalid message type of WASM app queue message.\n"); - break; + case RESTFUL_RESPONSE: + { + wasm_function_inst_t func_onResponse; + response_t *response = + (response_t *)bh_message_payload(queue_msg); + int size; + char *buffer; + int32 buffer_offset; + + app_manager_printf("App %s got response_t,status %d\n", + m_data->module_name, response->status); + + func_onResponse = app_manager_lookup_function( + inst, "_on_response", "(i32i32)"); + if (!func_onResponse) { + app_manager_printf("Cannot find function on_response\n"); + break; + } + + buffer = pack_response(response, &size); + if (buffer == NULL) + break; + + buffer_offset = + wasm_runtime_module_dup_data(inst, buffer, size); + if (buffer_offset == 0) { + const char *exception = wasm_runtime_get_exception(inst); + if (exception) { + app_manager_printf( + "Got exception running wasm code: %s\n", exception); + wasm_runtime_clear_exception(inst); + } + free_req_resp_packet(buffer); + break; + } + + free_req_resp_packet(buffer); + + argv[0] = (uint32)buffer_offset; + argv[1] = (uint32)size; + if (!wasm_runtime_call_wasm(wasm_app_data->exec_env, + func_onResponse, 2, argv)) { + const char *exception = wasm_runtime_get_exception(inst); + bh_assert(exception); + app_manager_printf("Got exception running wasm code: %s\n", + exception); + wasm_runtime_clear_exception(inst); + wasm_runtime_module_free(inst, buffer_offset); + break; + } + + wasm_runtime_module_free(inst, buffer_offset); + app_manager_printf("Wasm app process response success.\n"); + break; + } + default: + { + for (int i = 0; i < Max_Msg_Callback; i++) { + if (g_msg_type[i] == message_type) { + g_msg_callbacks[i](m_data, queue_msg); + return; + } + } + app_manager_printf( + "Invalid message type of WASM app queue message.\n"); + break; } } } else { switch (message_type) { - case TIMER_EVENT_WASM: { - unsigned int timer_id; - if (bh_message_payload(queue_msg)) { - /* Call Timer.callOnTimer() method */ - func_onTimer = - app_manager_lookup_function(inst, - "_on_timer_callback", - "(i32)"); - - if (!func_onTimer) { - app_manager_printf("Cannot find function _on_timer_callback\n"); - break; - } - timer_id = - (unsigned int)(uintptr_t)bh_message_payload(queue_msg); - argv[0] = timer_id; - if (!wasm_runtime_call_wasm(wasm_app_data->exec_env, func_onTimer, - 1, argv)) { - const char *exception = wasm_runtime_get_exception(inst); - bh_assert(exception); - app_manager_printf("Got exception running wasm code: %s\n", - exception); - wasm_runtime_clear_exception(inst); - } - } - break; + case TIMER_EVENT_WASM: + { + unsigned int timer_id; + if (bh_message_payload(queue_msg)) { + /* Call Timer.callOnTimer() method */ + func_onTimer = app_manager_lookup_function( + inst, "_on_timer_callback", "(i32)"); + + if (!func_onTimer) { + app_manager_printf( + "Cannot find function _on_timer_callback\n"); + break; + } + timer_id = + (unsigned int)(uintptr_t)bh_message_payload(queue_msg); + argv[0] = timer_id; + if (!wasm_runtime_call_wasm(wasm_app_data->exec_env, + func_onTimer, 1, argv)) { + const char *exception = + wasm_runtime_get_exception(inst); + bh_assert(exception); + app_manager_printf( + "Got exception running wasm code: %s\n", exception); + wasm_runtime_clear_exception(inst); + } + } + break; } - default: { - for (int i = 0; i < Max_Msg_Callback; i++) { - if (g_msg_type[i] == message_type) { - g_msg_callbacks[i](m_data, queue_msg); - return; - } - } - app_manager_printf("Invalid message type of WASM app queue message.\n"); - break; + default: + { + for (int i = 0; i < Max_Msg_Callback; i++) { + if (g_msg_type[i] == message_type) { + g_msg_callbacks[i](m_data, queue_msg); + return; + } + } + app_manager_printf( + "Invalid message type of WASM app queue message.\n"); + break; } - } } } @@ -421,14 +427,14 @@ wasm_app_prepare_wasi_dir(wasm_module_t module, const char *module_name, #endif /* WASM app thread main routine */ -static void* +static void * wasm_app_routine(void *arg) { wasm_function_inst_t func_onInit; wasm_function_inst_t func_onDestroy; - module_data *m_data = (module_data *) arg; - wasm_data *wasm_app_data = (wasm_data*) m_data->internal_data; + module_data *m_data = (module_data *)arg; + wasm_data *wasm_app_data = (wasm_data *)m_data->internal_data; wasm_module_inst_t inst = wasm_app_data->wasm_module_inst; /* Set m_data to the VM managed instance's custom data */ @@ -443,12 +449,13 @@ wasm_app_routine(void *arg) which initializes the wasi envrionment. The "_start" function will call "main" function */ if ((func_start = wasm_runtime_lookup_wasi_start_function(inst))) { - if (!wasm_runtime_call_wasm(wasm_app_data->exec_env, func_start, - 0, NULL)) { + if (!wasm_runtime_call_wasm(wasm_app_data->exec_env, func_start, 0, + NULL)) { const char *exception = wasm_runtime_get_exception(inst); bh_assert(exception); - app_manager_printf("Got exception running wasi start function: %s\n", - exception); + app_manager_printf( + "Got exception running wasi start function: %s\n", + exception); wasm_runtime_clear_exception(inst); goto fail1; } @@ -465,12 +472,11 @@ wasm_app_routine(void *arg) goto fail1; } - if (!wasm_runtime_call_wasm(wasm_app_data->exec_env, func_onInit, - 0, NULL)) { + if (!wasm_runtime_call_wasm(wasm_app_data->exec_env, func_onInit, 0, + NULL)) { const char *exception = wasm_runtime_get_exception(inst); bh_assert(exception); - app_manager_printf("Got exception running WASM code: %s\n", - exception); + app_manager_printf("Got exception running WASM code: %s\n", exception); wasm_runtime_clear_exception(inst); /* call on_destroy() in case some resources are opened in on_init() * and then exception thrown */ @@ -486,7 +492,8 @@ wasm_app_routine(void *arg) /* Call WASM app onDestroy() method if there is */ func_onDestroy = app_manager_lookup_function(inst, "_on_destroy", "()"); if (func_onDestroy) - wasm_runtime_call_wasm(wasm_app_data->exec_env, func_onDestroy, 0, NULL); + wasm_runtime_call_wasm(wasm_app_data->exec_env, func_onDestroy, 0, + NULL); fail1: @@ -497,7 +504,7 @@ static void cleanup_app_resource(module_data *m_data) { int i; - wasm_data *wasm_app_data = (wasm_data*) m_data->internal_data; + wasm_data *wasm_app_data = (wasm_data *)m_data->internal_data; bool is_bytecode = wasm_app_data->is_bytecode; am_cleanup_registeration(m_data->id); @@ -517,7 +524,8 @@ cleanup_app_resource(module_data *m_data) * or text section of aot file) from app file's section list. */ if (is_bytecode) { #if WASM_ENABLE_INTERP != 0 || WASM_ENABLE_JIT != 0 - destroy_all_wasm_sections((wasm_section_list_t)(wasm_app_data->sections)); + destroy_all_wasm_sections( + (wasm_section_list_t)(wasm_app_data->sections)); #else bh_assert(0); #endif @@ -572,7 +580,7 @@ wasm_app_module_init(void) #define MAX_INT_STR_LEN 11 static bool -wasm_app_module_install(request_t * msg) +wasm_app_module_install(request_t *msg) { unsigned int m_data_size, heap_size, stack_size; unsigned int timeout, timers, err_size; @@ -598,7 +606,8 @@ wasm_app_module_install(request_t * msg) /* Check payload */ if (!msg->payload || msg->payload_len == 0) { - SEND_ERR_RESPONSE(msg->mid, "Install WASM app failed: invalid wasm file."); + SEND_ERR_RESPONSE(msg->mid, + "Install WASM app failed: invalid wasm file."); return false; } @@ -610,7 +619,8 @@ wasm_app_module_install(request_t * msg) properties_offset = check_url_start(msg->url, strlen(msg->url), "/applet"); bh_assert(properties_offset > 0); if (properties_offset <= 0) { - SEND_ERR_RESPONSE(msg->mid, "Install WASM app failed: invalid app name."); + SEND_ERR_RESPONSE(msg->mid, + "Install WASM app failed: invalid app name."); goto fail; } @@ -619,12 +629,14 @@ wasm_app_module_install(request_t * msg) sizeof(m_name) - 1, '&'); if (strlen(m_name) == 0) { - SEND_ERR_RESPONSE(msg->mid, "Install WASM app failed: invalid app name."); + SEND_ERR_RESPONSE(msg->mid, + "Install WASM app failed: invalid app name."); goto fail; } if (app_manager_lookup_module_data(m_name)) { - SEND_ERR_RESPONSE(msg->mid, "Install WASM app failed: app already installed."); + SEND_ERR_RESPONSE(msg->mid, + "Install WASM app failed: app already installed."); goto fail; } @@ -646,6 +658,7 @@ wasm_app_module_install(request_t * msg) case Wasm_Module_AoT: { wasm_aot_file_t *aot_file; + /* clang-format off */ /* Sections to be released after loading */ uint8 sections1[] = { AOT_SECTION_TYPE_TARGET_INFO, @@ -656,6 +669,7 @@ wasm_app_module_install(request_t * msg) AOT_SECTION_TYPE_SIGANATURE, AOT_SECTION_TYPE_CUSTOM, }; + /* clang-format on */ aot_file = &wasm_app_file->u.aot; @@ -669,26 +683,24 @@ wasm_app_module_install(request_t * msg) goto fail; } /* Destroy useless sections from list after load */ - destroy_part_aot_sections(&aot_file->sections, - sections1, + destroy_part_aot_sections(&aot_file->sections, sections1, sizeof(sections1) / sizeof(uint8)); #if WASM_ENABLE_LIBC_WASI != 0 - if (!wasm_app_prepare_wasi_dir(module, m_name, - wasi_dir_buf, sizeof(wasi_dir_buf))) { - SEND_ERR_RESPONSE(msg->mid, - "Install WASM app failed: prepare wasi env failed."); + if (!wasm_app_prepare_wasi_dir(module, m_name, wasi_dir_buf, + sizeof(wasi_dir_buf))) { + SEND_ERR_RESPONSE( + msg->mid, + "Install WASM app failed: prepare wasi env failed."); goto fail; } - wasm_runtime_set_wasi_args(module, - wasi_dir_list, 1, - NULL, 0, - NULL, 0, - NULL, 0); + wasm_runtime_set_wasi_args(module, wasi_dir_list, 1, NULL, 0, NULL, + 0, NULL, 0); #endif /* Instantiate the AOT module */ - inst = wasm_runtime_instantiate(module, 0, heap_size, err, err_size); + inst = + wasm_runtime_instantiate(module, 0, heap_size, err, err_size); if (!inst) { snprintf(err_resp, sizeof(err_resp), "Install WASM app failed: %s", err); @@ -726,8 +738,8 @@ wasm_app_module_install(request_t * msg) bytecode_file = &wasm_app_file->u.bytecode; /* Load wasm module from sections */ - module = wasm_runtime_load_from_sections(bytecode_file->sections, false, - err, err_size); + module = wasm_runtime_load_from_sections(bytecode_file->sections, + false, err, err_size); if (!module) { snprintf(err_resp, sizeof(err_resp), "Install WASM app failed: %s", err); @@ -736,26 +748,24 @@ wasm_app_module_install(request_t * msg) } /* Destroy useless sections from list after load */ - destroy_part_wasm_sections(&bytecode_file->sections, - sections1, + destroy_part_wasm_sections(&bytecode_file->sections, sections1, sizeof(sections1) / sizeof(uint8)); #if WASM_ENABLE_LIBC_WASI != 0 - if (!wasm_app_prepare_wasi_dir(module, m_name, - wasi_dir_buf, sizeof(wasi_dir_buf))) { - SEND_ERR_RESPONSE(msg->mid, - "Install WASM app failed: prepare wasi env failed."); + if (!wasm_app_prepare_wasi_dir(module, m_name, wasi_dir_buf, + sizeof(wasi_dir_buf))) { + SEND_ERR_RESPONSE( + msg->mid, + "Install WASM app failed: prepare wasi env failed."); goto fail; } - wasm_runtime_set_wasi_args(module, - wasi_dir_list, 1, - NULL, 0, - NULL, 0, - NULL, 0); + wasm_runtime_set_wasi_args(module, wasi_dir_list, 1, NULL, 0, NULL, + 0, NULL, 0); #endif /* Instantiate the wasm module */ - inst = wasm_runtime_instantiate(module, 0, heap_size, err, err_size); + inst = + wasm_runtime_instantiate(module, 0, heap_size, err, err_size); if (!inst) { snprintf(err_resp, sizeof(err_resp), "Install WASM app failed: %s", err); @@ -764,15 +774,15 @@ wasm_app_module_install(request_t * msg) } /* Destroy useless sections from list after instantiate */ - destroy_part_wasm_sections(&bytecode_file->sections, - sections2, + destroy_part_wasm_sections(&bytecode_file->sections, sections2, sizeof(sections2) / sizeof(uint8)); break; } #endif /* endof WASM_ENALBE_INTERP != 0 || WASM_ENABLE_JIT != 0 */ default: - SEND_ERR_RESPONSE(msg->mid, - "Install WASM app failed: invalid wasm package type."); + SEND_ERR_RESPONSE( + msg->mid, + "Install WASM app failed: invalid wasm package type."); goto fail; } @@ -781,14 +791,15 @@ wasm_app_module_install(request_t * msg) m_data_size = align_uint(m_data_size, 4); 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."); + SEND_ERR_RESPONSE(msg->mid, + "Install WASM app failed: allocate memory failed."); goto fail; } memset(m_data, 0, m_data_size + sizeof(wasm_data)); m_data->module_type = Module_WASM_App; - m_data->internal_data = (uint8*) m_data + m_data_size; - wasm_app_data = (wasm_data*) m_data->internal_data; + m_data->internal_data = (uint8 *)m_data + m_data_size; + wasm_app_data = (wasm_data *)m_data->internal_data; wasm_app_data->wasm_module_inst = inst; wasm_app_data->wasm_module = module; wasm_app_data->m_data = m_data; @@ -802,8 +813,9 @@ wasm_app_module_install(request_t * msg) } if (!(wasm_app_data->exec_env = exec_env = - wasm_runtime_create_exec_env(inst, DEFAULT_WASM_STACK_SIZE))) { - SEND_ERR_RESPONSE(msg->mid, "Install WASM app failed: create exec env failed."); + wasm_runtime_create_exec_env(inst, DEFAULT_WASM_STACK_SIZE))) { + SEND_ERR_RESPONSE(msg->mid, + "Install WASM app failed: create exec env failed."); goto fail; } @@ -821,7 +833,8 @@ wasm_app_module_install(request_t * msg) /* Set module data - create queue */ m_data->queue = bh_queue_create(); if (!m_data->queue) { - SEND_ERR_RESPONSE(msg->mid, "Install WASM app failed: create app queue failed."); + SEND_ERR_RESPONSE(msg->mid, + "Install WASM app failed: create app queue failed."); goto fail; } @@ -850,8 +863,9 @@ wasm_app_module_install(request_t * msg) /* Initialize watchdog timer */ if (!watchdog_timer_init(m_data)) { - SEND_ERR_RESPONSE(msg->mid, - "Install WASM app failed: create app watchdog timer failed."); + SEND_ERR_RESPONSE( + msg->mid, + "Install WASM app failed: create app watchdog timer failed."); goto fail; } @@ -861,7 +875,8 @@ wasm_app_module_install(request_t * msg) #endif /* Create WASM app thread. */ if (os_thread_create(&wasm_app_data->thread_id, wasm_app_routine, - (void*) m_data, stack_size) != 0) { + (void *)m_data, stack_size) + != 0) { module_data_list_remove(m_data); SEND_ERR_RESPONSE(msg->mid, "Install WASM app failed: create app thread failed."); @@ -933,7 +948,8 @@ wasm_app_module_uninstall(request_t *msg) sizeof(m_name) - 1, '&'); if (strlen(m_name) == 0) { - SEND_ERR_RESPONSE(msg->mid, "Uninstall WASM app failed: invalid app name."); + SEND_ERR_RESPONSE(msg->mid, + "Uninstall WASM app failed: invalid app name."); return false; } @@ -944,13 +960,15 @@ wasm_app_module_uninstall(request_t *msg) } if (m_data->module_type != Module_WASM_App) { - SEND_ERR_RESPONSE(msg->mid, "Uninstall WASM app failed: invalid module type."); + SEND_ERR_RESPONSE(msg->mid, + "Uninstall WASM app failed: invalid module type."); return false; } if (m_data->wd_timer.is_interrupting) { - SEND_ERR_RESPONSE(msg->mid, - "Uninstall WASM app failed: app is being interrupted by watchdog."); + SEND_ERR_RESPONSE( + msg->mid, + "Uninstall WASM app failed: app is being interrupted by watchdog."); return false; } @@ -958,7 +976,7 @@ wasm_app_module_uninstall(request_t *msg) bh_queue_exit_loop_run(m_data->queue); /* Wait for wasm app thread to exit */ - wasm_app_data = (wasm_data*) m_data->internal_data; + wasm_app_data = (wasm_data *)m_data->internal_data; os_thread_join(wasm_app_data->thread_id, NULL); cleanup_app_resource(m_data); @@ -984,7 +1002,7 @@ wasm_app_module_handle_host_url(void *queue_msg) return false; } -static module_data* +static module_data * wasm_app_module_get_module_data(void *inst) { wasm_module_inst_t module_inst = (wasm_module_inst_t)inst; @@ -1001,7 +1019,7 @@ wasm_app_module_watchdog_kill(module_data *m_data) bool wasm_register_msg_callback(int message_type, - message_type_handler_t message_handler) + message_type_handler_t message_handler) { int i; int freeslot = -1; @@ -1019,7 +1037,8 @@ wasm_register_msg_callback(int message_type, else if (freeslot != -1) { g_msg_callbacks[freeslot] = message_handler; g_msg_type[freeslot] = message_type; - } else + } + else return false; return true; @@ -1040,18 +1059,19 @@ wasm_register_cleanup_callback(resource_cleanup_handler_t handler) return false; } -#define RECV_INTEGER(value, next_phase) do { \ - uint8 *p = (uint8 *)&value; \ - p[recv_ctx.size_in_phase++] = ch; \ - if (recv_ctx.size_in_phase == sizeof(value)) { \ - if (sizeof(value) == 4) \ - value = ntohl(value); \ - else if (sizeof(value) == 2) \ - value = ntohs(value); \ - recv_ctx.phase = next_phase; \ - recv_ctx.size_in_phase = 0; \ - } \ - } while(0) +#define RECV_INTEGER(value, next_phase) \ + do { \ + uint8 *p = (uint8 *)&value; \ + p[recv_ctx.size_in_phase++] = ch; \ + if (recv_ctx.size_in_phase == sizeof(value)) { \ + if (sizeof(value) == 4) \ + value = ntohl(value); \ + else if (sizeof(value) == 2) \ + value = ntohs(value); \ + recv_ctx.phase = next_phase; \ + recv_ctx.size_in_phase = 0; \ + } \ + } while (0) /* return: * 1: whole wasm app arrived @@ -1059,8 +1079,7 @@ wasm_register_cleanup_callback(resource_cleanup_handler_t handler) * -1: fail to process the byte arrived, e.g. allocate memory fail */ static bool -wasm_app_module_on_install_request_byte_arrive(uint8 ch, - int request_total_size, +wasm_app_module_on_install_request_byte_arrive(uint8 ch, int request_total_size, int *received_size) { uint8 *p; @@ -1101,11 +1120,11 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, return true; } else if (recv_ctx.phase == Phase_Req_Url_Len) { - p = (uint8*)&recv_ctx.message.request_url_len; + p = (uint8 *)&recv_ctx.message.request_url_len; p[recv_ctx.size_in_phase++] = ch; - if (recv_ctx.size_in_phase == - sizeof(recv_ctx.message.request_url_len)) { + if (recv_ctx.size_in_phase + == sizeof(recv_ctx.message.request_url_len)) { recv_ctx.message.request_url_len = ntohs(recv_ctx.message.request_url_len); recv_ctx.message.request_url = @@ -1138,19 +1157,18 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, } else if (recv_ctx.phase == Phase_App_Magic) { /* start to receive wasm app magic: bytecode or aot */ - p = (uint8*)&recv_ctx.message.app_file_magic; + p = (uint8 *)&recv_ctx.message.app_file_magic; p[recv_ctx.size_in_phase++] = ch; - if (recv_ctx.size_in_phase == - sizeof(recv_ctx.message.app_file_magic)) { + if (recv_ctx.size_in_phase == sizeof(recv_ctx.message.app_file_magic)) { magic = recv_ctx.message.app_file_magic; package_type = get_package_type((uint8 *)&magic, sizeof(magic) + 1); switch (package_type) { #if WASM_ENABLE_INTERP != 0 || WASM_ENABLE_JIT != 0 case Wasm_Module_Bytecode: recv_ctx.message.app_file.u.bytecode.magic = - recv_ctx.message.app_file_magic; + recv_ctx.message.app_file_magic; recv_ctx.phase = Phase_Wasm_Version; recv_ctx.size_in_phase = 0; break; @@ -1158,7 +1176,7 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, #if WASM_ENABLE_AOT != 0 case Wasm_Module_AoT: recv_ctx.message.app_file.u.aot.magic = - recv_ctx.message.app_file_magic; + recv_ctx.message.app_file_magic; recv_ctx.phase = Phase_AOT_Version; recv_ctx.size_in_phase = 0; break; @@ -1174,7 +1192,7 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, } #if WASM_ENABLE_INTERP != 0 || WASM_ENABLE_JIT != 0 else if (recv_ctx.phase == Phase_Wasm_Version) { - p = (uint8*)&recv_ctx.message.app_file.u.bytecode.version; + p = (uint8 *)&recv_ctx.message.app_file.u.bytecode.version; if (ch == wasm_bytecode_version[recv_ctx.size_in_phase]) p[recv_ctx.size_in_phase++] = ch; @@ -1185,8 +1203,8 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, goto fail; } - if (recv_ctx.size_in_phase == - sizeof(recv_ctx.message.app_file.u.bytecode.version)) { + if (recv_ctx.size_in_phase + == sizeof(recv_ctx.message.app_file.u.bytecode.version)) { recv_ctx.phase = Phase_Wasm_Section_Type; recv_ctx.size_in_phase = 0; } @@ -1201,8 +1219,8 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, #endif if (section_type <= section_type_max) { wasm_section_t *new_section; - if (!(new_section = (wasm_section_t *) - APP_MGR_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"); SEND_ERR_RESPONSE(recv_ctx.message.request_mid, "Install WASM app failed: " @@ -1219,7 +1237,8 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, recv_ctx.message.app_file.u.bytecode.section_end = new_section; } else { - recv_ctx.message.app_file.u.bytecode.section_end->next = new_section; + recv_ctx.message.app_file.u.bytecode.section_end->next = + new_section; recv_ctx.message.app_file.u.bytecode.section_end = new_section; } @@ -1241,7 +1260,8 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, } else if (recv_ctx.phase == Phase_Wasm_Section_Size) { /* the last section is the current receiving one */ - wasm_section_t *section = recv_ctx.message.app_file.u.bytecode.section_end; + wasm_section_t *section = + recv_ctx.message.app_file.u.bytecode.section_end; uint32 byte; bh_assert(section); @@ -1252,8 +1272,8 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, ((byte & 0x7f) << recv_ctx.size_in_phase * 7); recv_ctx.size_in_phase++; /* check leab128 overflow for uint32 value */ - if (recv_ctx.size_in_phase > - (sizeof(section->section_body_size) * 8 + 7 - 1) / 7) { + if (recv_ctx.size_in_phase + > (sizeof(section->section_body_size) * 8 + 7 - 1) / 7) { app_manager_printf("LEB overflow when parsing section size\n"); SEND_ERR_RESPONSE(recv_ctx.message.request_mid, "Install WASM app failed: " @@ -1263,10 +1283,12 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, if ((byte & 0x80) == 0) { /* leb128 encoded section size parsed done */ - if (!(section->section_body = APP_MGR_MALLOC(section->section_body_size))) { + if (!(section->section_body = + APP_MGR_MALLOC(section->section_body_size))) { app_manager_printf("Allocate memory failed!\n"); - SEND_ERR_RESPONSE(recv_ctx.message.request_mid, - "Install WASM app failed: allocate memory failed"); + SEND_ERR_RESPONSE( + recv_ctx.message.request_mid, + "Install WASM app failed: allocate memory failed"); goto fail; } recv_ctx.phase = Phase_Wasm_Section_Content; @@ -1277,7 +1299,8 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, } else if (recv_ctx.phase == Phase_Wasm_Section_Content) { /* the last section is the current receiving one */ - wasm_section_t *section = recv_ctx.message.app_file.u.bytecode.section_end; + wasm_section_t *section = + recv_ctx.message.app_file.u.bytecode.section_end; bh_assert(section); @@ -1317,7 +1340,7 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, #endif /* end of WASM_ENABLE_INTERP != 0 || WASM_ENABLE_JIT != 0 */ #if WASM_ENABLE_AOT != 0 else if (recv_ctx.phase == Phase_AOT_Version) { - p = (uint8*)&recv_ctx.message.app_file.u.aot.version; + p = (uint8 *)&recv_ctx.message.app_file.u.aot.version; if (ch == wasm_aot_version[recv_ctx.size_in_phase]) p[recv_ctx.size_in_phase++] = ch; @@ -1328,8 +1351,8 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, goto fail; } - if (recv_ctx.size_in_phase == - sizeof(recv_ctx.message.app_file.u.aot.version)) { + if (recv_ctx.size_in_phase + == sizeof(recv_ctx.message.app_file.u.aot.version)) { recv_ctx.phase = Phase_AOT_Section_ID; recv_ctx.size_in_phase = 0; } @@ -1337,17 +1360,17 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, } else if (recv_ctx.phase == Phase_AOT_Section_ID) { aot_section_t *cur_section; - uint32 aot_file_cur_offset = recv_ctx.total_received_size - 1 - - 18 /* Request fixed part */ - - recv_ctx.message.request_url_len; + uint32 aot_file_cur_offset = + recv_ctx.total_received_size - 1 + - 18 /* Request fixed part */ - recv_ctx.message.request_url_len; if (recv_ctx.size_in_phase == 0) { /* Skip paddings */ if (aot_file_cur_offset % 4) return true; - if (!(cur_section = (aot_section_t *) - APP_MGR_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"); SEND_ERR_RESPONSE(recv_ctx.message.request_mid, "Install WASM app failed: " @@ -1365,7 +1388,8 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, recv_ctx.message.app_file.u.aot.section_end->next = cur_section; recv_ctx.message.app_file.u.aot.section_end = cur_section; } - } else { + } + else { cur_section = recv_ctx.message.app_file.u.aot.section_end; bh_assert(cur_section); } @@ -1401,7 +1425,7 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, aot_section_t *section = recv_ctx.message.app_file.u.aot.section_end; bh_assert(section); - p = (uint8*)§ion->section_body_size; + p = (uint8 *)§ion->section_body_size; p[recv_ctx.size_in_phase++] = ch; if (recv_ctx.size_in_phase == sizeof(section->section_body_size)) { /* Notes: integers are always little endian encoded in AOT file */ @@ -1413,9 +1437,10 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, int map_prot = MMAP_PROT_READ | MMAP_PROT_WRITE | MMAP_PROT_EXEC; #if defined(BUILD_TARGET_X86_64) || defined(BUILD_TARGET_AMD_64) \ - || defined(BUILD_TARGET_RISCV64_LP64D) || defined(BUILD_TARGET_RISCV64_LP64) - /* aot code and data in x86_64 must be in range 0 to 2G due to - relocation for R_X86_64_32/32S/PC32 */ + || defined(BUILD_TARGET_RISCV64_LP64D) \ + || defined(BUILD_TARGET_RISCV64_LP64) + /* aot code and data in x86_64 must be in range 0 to 2G due + to relocation for R_X86_64_32/32S/PC32 */ int map_flags = MMAP_MAP_32BIT; #else int map_flags = MMAP_MAP_NONE; @@ -1425,9 +1450,10 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, total_size = (total_size + 3) & ~((uint64)3); if (total_size >= UINT32_MAX || !(section->section_body = - os_mmap(NULL, (uint32)total_size, - map_prot, map_flags))) { - app_manager_printf("Allocate executable memory failed!\n"); + os_mmap(NULL, (uint32)total_size, map_prot, + map_flags))) { + app_manager_printf( + "Allocate executable memory failed!\n"); SEND_ERR_RESPONSE(recv_ctx.message.request_mid, "Install WASM app failed: " "allocate memory failed"); @@ -1441,7 +1467,7 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, } else { if (!(section->section_body = - APP_MGR_MALLOC(section->section_body_size))) { + APP_MGR_MALLOC(section->section_body_size))) { app_manager_printf("Allocate memory failed!\n"); SEND_ERR_RESPONSE(recv_ctx.message.request_mid, "Install WASM app failed: " @@ -1466,12 +1492,12 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, if (recv_ctx.size_in_phase == section->section_body_size) { if (section->section_type == AOT_SECTION_TYPE_TEXT) { - uint32 total_size = section->section_body_size - + aot_get_plt_table_size(); + uint32 total_size = + section->section_body_size + aot_get_plt_table_size(); total_size = (total_size + 3) & ~3; if (total_size > section->section_body_size) { - memset(section->section_body + section->section_body_size, - 0, total_size - section->section_body_size); + memset(section->section_body + section->section_body_size, + 0, total_size - section->section_body_size); section->section_body_size = total_size; } } @@ -1514,7 +1540,8 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, switch (package_type) { #if WASM_ENABLE_INTERP != 0 || WASM_ENABLE_JIT != 0 case Wasm_Module_Bytecode: - destroy_all_wasm_sections(recv_ctx.message.app_file.u.bytecode.sections); + destroy_all_wasm_sections( + recv_ctx.message.app_file.u.bytecode.sections); break; #endif #if WASM_ENABLE_AOT != 0 @@ -1541,7 +1568,7 @@ module_wasm_app_handle_install_msg(install_wasm_app_msg_t *message) request_t *request = NULL; bh_message_t msg; - request = (request_t *) APP_MGR_MALLOC(sizeof(request_t)); + request = (request_t *)APP_MGR_MALLOC(sizeof(request_t)); if (request == NULL) return false; @@ -1561,8 +1588,8 @@ module_wasm_app_handle_install_msg(install_wasm_app_msg_t *message) /* Request payload is set to wasm_app_file_t struct, * but not whole app buffer */ - bh_memcpy_s(request->payload, request->payload_len, - &message->app_file, request->payload_len); + bh_memcpy_s(request->payload, request->payload_len, &message->app_file, + request->payload_len); /* Since it's a wasm app install request, so directly post to app-mgr's * queue. The benefit is that section list can be freed when the msg @@ -1595,8 +1622,7 @@ destroy_all_wasm_sections(wasm_section_list_t sections) static void destroy_part_wasm_sections(wasm_section_list_t *p_sections, - uint8 *section_types, - int section_cnt) + uint8 *section_types, int section_cnt) { int i; for (i = 0; i < section_cnt; i++) { @@ -1643,10 +1669,8 @@ destroy_all_aot_sections(aot_section_list_t sections) } } - static void -destroy_part_aot_sections(aot_section_list_t *p_sections, - uint8 *section_types, +destroy_part_aot_sections(aot_section_list_t *p_sections, uint8 *section_types, int section_cnt) { int i; @@ -1701,4 +1725,3 @@ wasm_get_wasi_root_dir() return wasi_root_dir; } #endif - diff --git a/core/app-mgr/app-manager/module_wasm_app.h b/core/app-mgr/app-manager/module_wasm_app.h index 8965a975fd..8a7ae4e542 100644 --- a/core/app-mgr/app-manager/module_wasm_app.h +++ b/core/app-mgr/app-manager/module_wasm_app.h @@ -56,7 +56,7 @@ typedef struct wasm_data { /* thread list mapped with this WASM module */ korp_tid thread_id; /* for easily access the containing module data */ - module_data* m_data; + module_data *m_data; /* is bytecode or aot */ bool is_bytecode; /* sections of wasm bytecode or aot file */ @@ -109,16 +109,18 @@ typedef struct wasm_app_file_t { extern module_interface wasm_app_module_interface; typedef void (*message_type_handler_t)(module_data *m_data, bh_message_t msg); -extern bool wasm_register_msg_callback(int msg_type, - message_type_handler_t message_handler); +extern bool +wasm_register_msg_callback(int msg_type, + message_type_handler_t message_handler); typedef void (*resource_cleanup_handler_t)(uint32 module_id); -extern bool wasm_register_cleanup_callback(resource_cleanup_handler_t handler); +extern bool +wasm_register_cleanup_callback(resource_cleanup_handler_t handler); /** * Set WASI root dir for modules. On each wasm app installation, a sub dir named - * with the app's name will be created autamically. That wasm app can only access - * this sub dir. + * with the app's name will be created autamically. That wasm app can only + * access this sub dir. * * @param root_dir the root dir to set * @return true for success, false otherwise diff --git a/core/app-mgr/app-manager/module_wasm_lib.c b/core/app-mgr/app-manager/module_wasm_lib.c index bdf3215c82..0b5c07ea70 100644 --- a/core/app-mgr/app-manager/module_wasm_lib.c +++ b/core/app-mgr/app-manager/module_wasm_lib.c @@ -3,47 +3,56 @@ * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ - #include "module_wasm_lib.h" -static bool wasm_lib_module_init(void) +static bool +wasm_lib_module_init(void) { return false; } -static bool wasm_lib_module_install(request_t *msg) +static bool +wasm_lib_module_install(request_t *msg) { - (void) msg; + (void)msg; return false; } -static bool wasm_lib_module_uninstall(request_t *msg) +static bool +wasm_lib_module_uninstall(request_t *msg) { - (void) msg; + (void)msg; return false; } -static void wasm_lib_module_watchdog_kill(module_data *m_data) +static void +wasm_lib_module_watchdog_kill(module_data *m_data) { - (void) m_data; + (void)m_data; } -static bool wasm_lib_module_handle_host_url(void *queue_msg) +static bool +wasm_lib_module_handle_host_url(void *queue_msg) { - (void) queue_msg; + (void)queue_msg; return false; } -static module_data* +static module_data * wasm_lib_module_get_module_data(void *inst) { - (void) inst; + (void)inst; return NULL; } -module_interface wasm_lib_module_interface = { wasm_lib_module_init, - wasm_lib_module_install, wasm_lib_module_uninstall, - wasm_lib_module_watchdog_kill, wasm_lib_module_handle_host_url, - wasm_lib_module_get_module_data, - NULL }; - +/* clang-format off */ +module_interface wasm_lib_module_interface = { + wasm_lib_module_init, + wasm_lib_module_install, + wasm_lib_module_uninstall, + wasm_lib_module_watchdog_kill, + wasm_lib_module_handle_host_url, + wasm_lib_module_get_module_data, + NULL +}; +/* clang-format on */ diff --git a/core/app-mgr/app-manager/platform/linux/app_mgr_linux.c b/core/app-mgr/app-manager/platform/linux/app_mgr_linux.c index 45957bc183..5e51788bcc 100644 --- a/core/app-mgr/app-manager/platform/linux/app_mgr_linux.c +++ b/core/app-mgr/app-manager/platform/linux/app_mgr_linux.c @@ -5,25 +5,28 @@ #include "app_manager.h" -void* -app_manager_timer_create(void (*timer_callback)(void*), - watchdog_timer *wd_timer) +void * +app_manager_timer_create(void (*timer_callback)(void *), + watchdog_timer *wd_timer) { /* TODO */ return NULL; } -void app_manager_timer_destroy(void *timer) +void +app_manager_timer_destroy(void *timer) { /* TODO */ } -void app_manager_timer_start(void *timer, int timeout) +void +app_manager_timer_start(void *timer, int timeout) { /* TODO */ } -void app_manager_timer_stop(void *timer) +void +app_manager_timer_stop(void *timer) { /* TODO */ } @@ -35,9 +38,9 @@ app_manager_get_wd_timer_from_timer_handle(void *timer) return NULL; } -int app_manager_signature_verify(const uint8_t *file, unsigned int file_len, - const uint8_t *signature, unsigned int sig_size) +int +app_manager_signature_verify(const uint8_t *file, unsigned int file_len, + const uint8_t *signature, unsigned int sig_size) { return 1; } - 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 cca66549c8..650e536f11 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 @@ -16,32 +16,36 @@ typedef struct k_timer_watchdog { watchdog_timer *wd_timer; } k_timer_watchdog; -void* -app_manager_timer_create(void (*timer_callback)(void*), - watchdog_timer *wd_timer) +void * +app_manager_timer_create(void (*timer_callback)(void *), + watchdog_timer *wd_timer) { - struct k_timer_watchdog *timer = APP_MGR_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, - NULL); + k_timer_init(&timer->timer, (void (*)(struct k_timer *))timer_callback, + NULL); timer->wd_timer = wd_timer; } return timer; } -void app_manager_timer_destroy(void *timer) +void +app_manager_timer_destroy(void *timer) { APP_MGR_FREE(timer); } -void app_manager_timer_start(void *timer, int timeout) +void +app_manager_timer_start(void *timer, int timeout) { k_timer_start(timer, Z_TIMEOUT_MS(timeout), Z_TIMEOUT_MS(0)); } -void app_manager_timer_stop(void *timer) +void +app_manager_timer_stop(void *timer) { k_timer_stop(timer); } @@ -49,7 +53,7 @@ void app_manager_timer_stop(void *timer) watchdog_timer * app_manager_get_wd_timer_from_timer_handle(void *timer) { - return ((k_timer_watchdog*) timer)->wd_timer; + return ((k_timer_watchdog *)timer)->wd_timer; } #if 0 int app_manager_signature_verify(const uint8_t *file, unsigned int file_len, diff --git a/core/app-mgr/app-manager/resource_reg.c b/core/app-mgr/app-manager/resource_reg.c index fbeb803ae7..4e930890e3 100644 --- a/core/app-mgr/app-manager/resource_reg.c +++ b/core/app-mgr/app-manager/resource_reg.c @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ - #include "native_interface.h" #include "app_manager.h" #include "app_manager_export.h" @@ -13,14 +12,15 @@ typedef struct _app_res_register { struct _app_res_register *next; - char * url; + char *url; void (*request_handler)(request_t *, void *); uint32 register_id; } app_res_register_t; -static app_res_register_t * g_resources = NULL; +static app_res_register_t *g_resources = NULL; -void module_request_handler(request_t *request, void *user_data) +void +module_request_handler(request_t *request, void *user_data) { unsigned int mod_id = (unsigned int)(uintptr_t)user_data; bh_message_t msg; @@ -54,10 +54,11 @@ void module_request_handler(request_t *request, void *user_data) } app_manager_printf("Send request to app %s success.\n", - m_data->module_name); + m_data->module_name); } -void targeted_app_request_handler(request_t *request, void *unused) +void +targeted_app_request_handler(request_t *request, void *unused) { char applet_name[128] = { 0 }; int offset; @@ -74,7 +75,8 @@ void targeted_app_request_handler(request_t *request, void *unused) char *p = strchr(applet_name, '/'); if (p) { *p = 0; - } else + } + else return; app_manager_printf("Send request to applet: %s\n", applet_name); @@ -84,16 +86,17 @@ void targeted_app_request_handler(request_t *request, void *unused) m_data = module_data_list_lookup(applet_name); if (!m_data) { SEND_ERR_RESPONSE(request->mid, - "Send request to applet failed: invalid applet name"); + "Send request to applet failed: invalid applet name"); goto end; } module_request_handler(request, (void *)(uintptr_t)m_data->id); - end: request->url = url; - +end: + request->url = url; } -void am_send_response(response_t *response) +void +am_send_response(response_t *response) { module_data *m_data; @@ -101,15 +104,15 @@ void am_send_response(response_t *response) m_data = module_data_list_lookup_id(response->reciever); if (!m_data) { send_response_to_host(response); - - } else { - response_t * resp_for_send = clone_response(response); + } + else { + response_t *resp_for_send = clone_response(response); if (!resp_for_send) { return; } bh_message_t msg = bh_new_msg(RESTFUL_RESPONSE, resp_for_send, - sizeof(*resp_for_send), response_cleaner); + sizeof(*resp_for_send), response_cleaner); if (!msg) { response_cleaner(resp_for_send); return; @@ -121,7 +124,8 @@ void am_send_response(response_t *response) } } -void * am_dispatch_request(request_t *request) +void * +am_dispatch_request(request_t *request) { app_res_register_t *r = g_resources; @@ -135,11 +139,12 @@ void * am_dispatch_request(request_t *request) return NULL; } -bool am_register_resource(const char *url, - void (*request_handler)(request_t *, void *), - uint32 register_id) +bool +am_register_resource(const char *url, + void (*request_handler)(request_t *, void *), + uint32 register_id) { - app_res_register_t * r = g_resources; + app_res_register_t *r = g_resources; int register_num = 0; while (r) { @@ -178,10 +183,11 @@ bool am_register_resource(const char *url, return true; } -void am_cleanup_registeration(uint32 register_id) +void +am_cleanup_registeration(uint32 register_id) { - app_res_register_t * r = g_resources; - app_res_register_t * prev = NULL; + app_res_register_t *r = g_resources; + app_res_register_t *prev = NULL; while (r) { app_res_register_t *next = r->next; @@ -194,7 +200,8 @@ void am_cleanup_registeration(uint32 register_id) APP_MGR_FREE(r->url); APP_MGR_FREE(r); - } else + } + else /* if r is freed, should not change prev. Only set prev to r when r isn't freed. */ prev = r; diff --git a/core/app-mgr/app-manager/watchdog.c b/core/app-mgr/app-manager/watchdog.c index 6ed88bbdbc..ba5bb05f5c 100644 --- a/core/app-mgr/app-manager/watchdog.c +++ b/core/app-mgr/app-manager/watchdog.c @@ -12,10 +12,11 @@ static bh_queue *watchdog_queue; #ifdef WATCHDOG_ENABLED /* TODO */ -static void watchdog_timer_callback(void *timer) +static void +watchdog_timer_callback(void *timer) { - watchdog_timer *wd_timer = app_manager_get_wd_timer_from_timer_handle( - timer); + watchdog_timer *wd_timer = + app_manager_get_wd_timer_from_timer_handle(timer); watchdog_timer_stop(wd_timer); @@ -26,14 +27,15 @@ static void watchdog_timer_callback(void *timer) wd_timer->is_interrupting = true; bh_post_msg(watchdog_queue, WD_TIMEOUT, wd_timer->module_data, - sizeof(module_data)); + sizeof(module_data)); } os_mutex_unlock(&wd_timer->lock); } #endif -bool watchdog_timer_init(module_data *m_data) +bool +watchdog_timer_init(module_data *m_data) { #ifdef WATCHDOG_ENABLED /* TODO */ watchdog_timer *wd_timer = &m_data->wd_timer; @@ -42,7 +44,7 @@ bool watchdog_timer_init(module_data *m_data) return false; if (!(wd_timer->timer_handle = - app_manager_timer_create(watchdog_timer_callback, wd_timer))) { + app_manager_timer_create(watchdog_timer_callback, wd_timer))) { os_mutex_destroy(&wd_timer->lock); return false; } @@ -54,7 +56,8 @@ bool watchdog_timer_init(module_data *m_data) return true; } -void watchdog_timer_destroy(watchdog_timer *wd_timer) +void +watchdog_timer_destroy(watchdog_timer *wd_timer) { #ifdef WATCHDOG_ENABLED /* TODO */ app_manager_timer_destroy(wd_timer->timer_handle); @@ -62,32 +65,35 @@ void watchdog_timer_destroy(watchdog_timer *wd_timer) #endif } -void watchdog_timer_start(watchdog_timer *wd_timer) +void +watchdog_timer_start(watchdog_timer *wd_timer) { os_mutex_lock(&wd_timer->lock); wd_timer->is_interrupting = false; wd_timer->is_stopped = false; app_manager_timer_start(wd_timer->timer_handle, - wd_timer->module_data->timeout); + wd_timer->module_data->timeout); os_mutex_unlock(&wd_timer->lock); } -void watchdog_timer_stop(watchdog_timer *wd_timer) +void +watchdog_timer_stop(watchdog_timer *wd_timer) { app_manager_timer_stop(wd_timer->timer_handle); } #ifdef WATCHDOG_ENABLED /* TODO */ -static void watchdog_queue_callback(void *queue_msg) +static void +watchdog_queue_callback(void *queue_msg) { if (bh_message_type(queue_msg) == WD_TIMEOUT) { - module_data *m_data = (module_data *) bh_message_payload(queue_msg); + module_data *m_data = (module_data *)bh_message_payload(queue_msg); if (g_module_interfaces[m_data->module_type] - && g_module_interfaces[m_data->module_type]->module_watchdog_kill) { + && g_module_interfaces[m_data->module_type]->module_watchdog_kill) { g_module_interfaces[m_data->module_type]->module_watchdog_kill( - m_data); + m_data); app_manager_post_applets_update_event(); } } @@ -95,22 +101,23 @@ static void watchdog_queue_callback(void *queue_msg) #endif #ifdef WATCHDOG_ENABLED /* TODO */ -static void* +static void * watchdog_thread_routine(void *arg) { /* Enter loop run */ bh_queue_enter_loop_run(watchdog_queue, watchdog_queue_callback); - (void) arg; + (void)arg; return NULL; } #endif -bool watchdog_startup() +bool +watchdog_startup() { if (!(watchdog_queue = bh_queue_create())) { app_manager_printf( - "App Manager start failed: create watchdog queue failed.\n"); + "App Manager start failed: create watchdog queue failed.\n"); return false; } #if 0 @@ -125,7 +132,8 @@ bool watchdog_startup() return true; } -void watchdog_destroy() +void +watchdog_destroy() { bh_queue_exit_loop_run(watchdog_queue); bh_queue_destroy(watchdog_queue); diff --git a/core/app-mgr/app-manager/watchdog.h b/core/app-mgr/app-manager/watchdog.h index c1478d40e0..d960df03bc 100644 --- a/core/app-mgr/app-manager/watchdog.h +++ b/core/app-mgr/app-manager/watchdog.h @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ - #ifndef _WATCHDOG_H_ #define _WATCHDOG_H_ @@ -25,7 +24,7 @@ watchdog_timer_start(watchdog_timer *wd_timer); void watchdog_timer_stop(watchdog_timer *wd_timer); -watchdog_timer* +watchdog_timer * app_manager_get_watchdog_timer(void *timer); bool diff --git a/core/app-mgr/app-mgr-shared/app_manager_export.h b/core/app-mgr/app-mgr-shared/app_manager_export.h index 4d8ced8d54..d9a8c04452 100644 --- a/core/app-mgr/app-mgr-shared/app_manager_export.h +++ b/core/app-mgr/app-mgr-shared/app_manager_export.h @@ -20,7 +20,7 @@ extern "C" { #define ID_HOST -3 #define ID_APP_MGR -2 /* Invalid module ID */ -#define ID_NONE (uint32)-1 +#define ID_NONE ((uint32)-1) struct attr_container_t; @@ -40,7 +40,10 @@ typedef enum QUEUE_MSG_TYPE { } QUEUE_MSG_TYPE; typedef enum { - Module_Jeff, Module_WASM_App, Module_WASM_Lib, Module_Max + Module_Jeff, + Module_WASM_App, + Module_WASM_Lib, + Module_Max } Module_Type; struct module_data; @@ -111,12 +114,13 @@ typedef module_data *(*module_get_module_data_func)(void *inst); * * @param ch the byte to be received and handled * @param total_size total size of the request - * @param received_total_size currently received total size when the function return + * @param received_total_size currently received total size when + * the function return * * @return true if success, false otherwise */ -typedef bool (*module_on_install_request_byte_arrive_func) ( - uint8 ch, int total_size, int *received_total_size); +typedef bool (*module_on_install_request_byte_arrive_func)( + uint8 ch, int total_size, int *received_total_size); /* Interfaces of each module */ typedef struct module_interface { @@ -148,7 +152,7 @@ typedef bool (*host_init_func)(void); * * @return size of the data sent in bytes */ -typedef int (*host_send_fun)(void * ctx, const char *buf, int size); +typedef int (*host_send_fun)(void *ctx, const char *buf, int size); /** * @typedef host_destroy_fun @@ -191,22 +195,22 @@ app_manager_get_module_name(uint32 module_type, void *module_inst); void * app_manager_get_module_heap(uint32 module_type, void *module_inst); -void* +void * get_app_manager_queue(); -module_data* +module_data * app_manager_get_module_data(uint32 module_type, void *module_inst); unsigned int app_manager_get_module_id(uint32 module_type, void *module_inst); -module_data* +module_data * app_manager_lookup_module_data(const char *name); -module_data* +module_data * module_data_list_lookup(const char *module_name); -module_data* +module_data * module_data_list_lookup_id(unsigned int module_id); void @@ -214,9 +218,11 @@ app_manager_post_applets_update_event(); bool am_register_resource(const char *url, - void (*request_handler)(request_t *, void *), uint32 register_id); + void (*request_handler)(request_t *, void *), + uint32 register_id); -void am_cleanup_registeration(uint32 register_id); +void +am_cleanup_registeration(uint32 register_id); bool am_register_event(const char *url, uint32_t reg_client); @@ -224,13 +230,17 @@ am_register_event(const char *url, uint32_t reg_client); bool am_unregister_event(const char *url, uint32_t reg_client); -void am_publish_event(request_t * event); +void +am_publish_event(request_t *event); -void * am_dispatch_request(request_t *request); +void * +am_dispatch_request(request_t *request); -void am_send_response(response_t *response); +void +am_send_response(response_t *response); -void module_request_handler(request_t *request, void *user_data); +void +module_request_handler(request_t *request, void *user_data); /** * Send request message to host @@ -291,4 +301,3 @@ app_manager_host_send_msg(int msg_type, const char *buf, int size); #endif #endif - diff --git a/core/iwasm/aot/arch/aot_reloc_x86_32.c b/core/iwasm/aot/arch/aot_reloc_x86_32.c index 40f8ec0cc9..5a8a944b4e 100644 --- a/core/iwasm/aot/arch/aot_reloc_x86_32.c +++ b/core/iwasm/aot/arch/aot_reloc_x86_32.c @@ -5,9 +5,9 @@ #include "aot_reloc.h" -#define R_386_32 1 /* Direct 32 bit */ -#define R_386_PC32 2 /* PC relative 32 bit */ -#define R_386_PLT32 4 /* 32bit address ProcedureLinkageTable */ +#define R_386_32 1 /* Direct 32 bit */ +#define R_386_PC32 2 /* PC relative 32 bit */ +#define R_386_PLT32 4 /* 32-bit address ProcedureLinkageTable */ #if !defined(_WIN32) && !defined(_WIN32_) /* clang-format off */ diff --git a/doc/build_wamr.md b/doc/build_wamr.md index 871f0708a8..881da8b6cf 100644 --- a/doc/build_wamr.md +++ b/doc/build_wamr.md @@ -302,7 +302,7 @@ Zephyr You need to download the Zephyr source code first and embed WAMR into it. ``` Bash git clone https://github.com/zephyrproject-rtos/zephyr.git -source ../zephyr-env.sh +source zephyr/zephyr-env.sh cd /product-mini/platforms/zephyr/simple # Execute the ./build_and_run.sh script with board name as parameter. Here take x86 as example: ./build_and_run.sh x86 diff --git a/test-tools/binarydump-tool/binarydump.c b/test-tools/binarydump-tool/binarydump.c index cd19eecad1..050de6dfa4 100644 --- a/test-tools/binarydump-tool/binarydump.c +++ b/test-tools/binarydump-tool/binarydump.c @@ -8,30 +8,30 @@ #include #include -static unsigned char* -read_file_to_buffer (const char *filename, int *ret_size) +static unsigned char * +read_file_to_buffer(const char *filename, int *ret_size) { unsigned char *buffer; FILE *file; int file_size, read_size; - if (!(file = fopen (filename, "r"))) + if (!(file = fopen(filename, "r"))) return NULL; - fseek (file, 0, SEEK_END); - file_size = ftell (file); - fseek (file, 0, SEEK_SET); + fseek(file, 0, SEEK_END); + file_size = ftell(file); + fseek(file, 0, SEEK_SET); - if (!(buffer = malloc (file_size))) { - fclose (file); + if (!(buffer = malloc(file_size))) { + fclose(file); return NULL; } - read_size = fread (buffer, 1, file_size, file); - fclose (file); + read_size = fread(buffer, 1, file_size, file); + fclose(file); if (read_size < file_size) { - free (buffer); + free(buffer); return NULL; } @@ -41,20 +41,19 @@ read_file_to_buffer (const char *filename, int *ret_size) } static int -print_help () +print_help() { - printf ("Usage: binarydump -o -n input_file\n"); - printf ("Options:\n"); - printf (" -o Place the output into \n"); - printf (" -n The name of array \n"); + printf("Usage: binarydump -o -n input_file\n"); + printf("Options:\n"); + printf(" -o Place the output into \n"); + printf(" -n The name of array \n"); return -1; } static bool -bin_file_dump (const unsigned char *file, int size, - const char *bin_file_output, - const char *array_name) +bin_file_dump(const unsigned char *file, int size, const char *bin_file_output, + const char *array_name) { unsigned i = 0; const unsigned char *p = file, *p_end = file + size; @@ -63,7 +62,8 @@ bin_file_dump (const unsigned char *file, int size, if (!file_output) return false; - fprintf(file_output, "\nunsigned char __aligned(4) %s[] = {\n ", array_name); + fprintf(file_output, "\nunsigned char __aligned(4) %s[] = {\n ", + array_name); while (p < p_end) { fprintf(file_output, "0x%02X", *p++); @@ -86,7 +86,7 @@ bin_file_dump (const unsigned char *file, int size, } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { unsigned char *file; int size; @@ -94,33 +94,33 @@ main (int argc, char *argv[]) const char *bin_file_input, *array_file_output = NULL, *array_name = NULL; for (argc--, argv++; argc > 0 && argv[0][0] == '-'; argc--, argv++) { - if (!strcmp (argv[0], "-o")) { + if (!strcmp(argv[0], "-o")) { ++argv; if (--argc == 0) - return print_help (); + return print_help(); array_file_output = *argv; } - else if (!strcmp (argv[0], "-n")) { + else if (!strcmp(argv[0], "-n")) { ++argv; if (--argc == 0) - return print_help (); + return print_help(); array_name = *argv; } else - return print_help (); + return print_help(); } if (!array_file_output || !array_name) - return print_help (); + return print_help(); bin_file_input = *argv; - if (!(file = read_file_to_buffer (bin_file_input, &size))) + if (!(file = read_file_to_buffer(bin_file_input, &size))) return -1; - ret = bin_file_dump (file, size, array_file_output, array_name); + ret = bin_file_dump(file, size, array_file_output, array_name); - free (file); + free(file); return ret ? 0 : -1; } diff --git a/test-tools/component_test/README.md b/test-tools/component-test/README.md similarity index 100% rename from test-tools/component_test/README.md rename to test-tools/component-test/README.md diff --git a/test-tools/component_test/__init__.py b/test-tools/component-test/__init__.py similarity index 100% rename from test-tools/component_test/__init__.py rename to test-tools/component-test/__init__.py diff --git a/test-tools/component_test/framework/__init__.py b/test-tools/component-test/framework/__init__.py similarity index 100% rename from test-tools/component_test/framework/__init__.py rename to test-tools/component-test/framework/__init__.py diff --git a/test-tools/component_test/framework/case_base.py b/test-tools/component-test/framework/case_base.py similarity index 100% rename from test-tools/component_test/framework/case_base.py rename to test-tools/component-test/framework/case_base.py diff --git a/test-tools/component_test/framework/engine.py b/test-tools/component-test/framework/engine.py similarity index 100% rename from test-tools/component_test/framework/engine.py rename to test-tools/component-test/framework/engine.py diff --git a/test-tools/component_test/framework/framework.py b/test-tools/component-test/framework/framework.py similarity index 100% rename from test-tools/component_test/framework/framework.py rename to test-tools/component-test/framework/framework.py diff --git a/test-tools/component_test/framework/suite.py b/test-tools/component-test/framework/suite.py similarity index 100% rename from test-tools/component_test/framework/suite.py rename to test-tools/component-test/framework/suite.py diff --git a/test-tools/component_test/framework/test_api.py b/test-tools/component-test/framework/test_api.py similarity index 100% rename from test-tools/component_test/framework/test_api.py rename to test-tools/component-test/framework/test_api.py diff --git a/test-tools/component_test/framework/test_utils.py b/test-tools/component-test/framework/test_utils.py similarity index 100% rename from test-tools/component_test/framework/test_utils.py rename to test-tools/component-test/framework/test_utils.py diff --git a/test-tools/component_test/harness/__init__.py b/test-tools/component-test/harness/__init__.py similarity index 100% rename from test-tools/component_test/harness/__init__.py rename to test-tools/component-test/harness/__init__.py diff --git a/test-tools/component_test/harness/harness_api.py b/test-tools/component-test/harness/harness_api.py similarity index 100% rename from test-tools/component_test/harness/harness_api.py rename to test-tools/component-test/harness/harness_api.py diff --git a/test-tools/component_test/host-clients/src/host_app_sample.c b/test-tools/component-test/host-clients/src/host_app_sample.c similarity index 81% rename from test-tools/component_test/host-clients/src/host_app_sample.c rename to test-tools/component-test/host-clients/src/host_app_sample.c index 1fb4ba1218..c4010de6ac 100644 --- a/test-tools/component_test/host-clients/src/host_app_sample.c +++ b/test-tools/component-test/host-clients/src/host_app_sample.c @@ -11,32 +11,36 @@ #include "bi-inc/attr_container.h" #include "er-coap-constants.h" -static char *read_file_to_buffer(const char *filename, int *ret_size); +static char * +read_file_to_buffer(const char *filename, int *ret_size); int send_request_to_applet_success = 0; const char *label_for_request = "request1"; int event_listener_counter = 0; char *applet_buf[1024 * 1024]; const char *host_agent_ip = "127.0.0.1"; -void f_aee_response_handler(void *usr_ctx, aee_response_t *response) +void +f_aee_response_handler(void *usr_ctx, aee_response_t *response) { if (response == NULL) { printf("########## request timeout!!! \n"); - } else { - char *str = (char *) usr_ctx; + } + else { + char *str = (char *)usr_ctx; printf("#### dump response ####\n"); printf("#### user data: %s \n", str); printf("#### status: %d \n", response->status); if (response->payload != NULL) - attr_container_dump((attr_container_t *) response->payload); + attr_container_dump((attr_container_t *)response->payload); } } -void f_aee_event_listener(const char *url, void *event, int fmt) +void +f_aee_event_listener(const char *url, void *event, int fmt) { printf("######## event is received. url: %s, fmt:%d ############\n", url, - fmt); + fmt); - attr_container_t *attr_obj = (attr_container_t *) event; + attr_container_t *attr_obj = (attr_container_t *)event; attr_container_dump(attr_obj); /* @@ -48,7 +52,8 @@ void f_aee_event_listener(const char *url, void *event, int fmt) */ } -static int print_menu_and_select(void) +static int +print_menu_and_select(void) { char s[256]; int choice; @@ -83,7 +88,8 @@ static int print_menu_and_select(void) return 0; } -static void install_applet(int index) +static void +install_applet(int index) { char applet_name[64]; char applet_file_name[64]; @@ -94,15 +100,15 @@ static void install_applet(int index) printf("Installing TestApplet%d...\n", index); snprintf(applet_name, sizeof(applet_name), "TestApplet%d", index); snprintf(applet_file_name, sizeof(applet_file_name), "./TestApplet%d.wasm", - index); + index); buf = read_file_to_buffer(applet_file_name, &size); if (!buf) { printf("Install Applet failed: read file %s error.\n", - applet_file_name); + applet_file_name); return; } - //step2. install applet + // step2. install applet ret = aee_applet_install(buf, "wasm", size, applet_name, 5000); if (ret) { printf("%s install success\n", applet_name); @@ -110,7 +116,8 @@ static void install_applet(int index) free(buf); } -static void uninstall_applet(int index) +static void +uninstall_applet(int index) { int ret; char applet_name[64]; @@ -118,51 +125,56 @@ static void uninstall_applet(int index) ret = aee_applet_uninstall(applet_name, "wasm", 5000); if (ret) { printf("uninstall %s success\n", applet_name); - } else { + } + else { printf("uninstall %s failed\n", applet_name); } } -static void send_request(int index) +static void +send_request(int index) { char url[64]; int ret; aee_request_t req; const char *user_context = "label for request"; - attr_container_t *attr_obj = attr_container_create( - "Send Request to Applet"); + attr_container_t *attr_obj = + attr_container_create("Send Request to Applet"); attr_container_set_string(&attr_obj, "String key", "Hello"); attr_container_set_int(&attr_obj, "Int key", 1000); attr_container_set_int64(&attr_obj, "Int64 key", 0x77BBCCDD11223344LL); - //specify the target wasm app + // specify the target wasm app snprintf(url, sizeof(url), "/app/TestApplet%d/url1", index); - //not specify the target wasm app - //snprintf(url, sizeof(url), "url1"); + // not specify the target wasm app + // snprintf(url, sizeof(url), "url1"); aee_request_init(&req, url, COAP_PUT); aee_request_set_payload(&req, attr_obj, - attr_container_get_serialize_length(attr_obj), - PAYLOAD_FORMAT_ATTRIBUTE_OBJECT); - ret = aee_request_send(&req, f_aee_response_handler, (void *) user_context, - 10000); + attr_container_get_serialize_length(attr_obj), + PAYLOAD_FORMAT_ATTRIBUTE_OBJECT); + ret = aee_request_send(&req, f_aee_response_handler, (void *)user_context, + 10000); if (ret) { printf("send request to TestApplet1 success\n"); } } -static void register_event(const char *event_path) +static void +register_event(const char *event_path) { hostclient_register_event(event_path, f_aee_event_listener); } -static void unregister_event(const char *event_path) +static void +unregister_event(const char *event_path) { hostclient_unregister_event(event_path); } -static void query_applets() +static void +query_applets() { aee_applet_list_t applet_lst; aee_applet_list_init(&applet_lst); @@ -189,7 +201,7 @@ read_file_to_buffer(const char *filename, int *ret_size) return NULL; } - if (!(buffer = (char *) malloc(file_size))) { + if (!(buffer = (char *)malloc(file_size))) { fclose(fl); return NULL; } @@ -206,7 +218,8 @@ read_file_to_buffer(const char *filename, int *ret_size) return buffer; } -static void auto_test() +static void +auto_test() { int i; int interval = 1000; /* ms */ @@ -228,7 +241,8 @@ static void auto_test() } } -void exit_program() +void +exit_program() { hostclient_shutdown(); exit(0); @@ -240,7 +254,7 @@ main() { bool ret; - //step1. host client init + // step1. host client init ret = hostclient_initialize(host_agent_ip, 3456); if (!ret) { @@ -281,5 +295,7 @@ main() // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors -// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project -// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file +// 5. Go to Project > Add New Item to create new code files, or +// Project > Add Existing Item to add existing code files to the project +// 6. In the future, to open this project again, go to File > Open > Project +// and select the .sln file diff --git a/test-tools/component_test/host-clients/src/makefile b/test-tools/component-test/host-clients/src/makefile similarity index 100% rename from test-tools/component_test/host-clients/src/makefile rename to test-tools/component-test/host-clients/src/makefile diff --git a/test-tools/component_test/set_dev_env.sh b/test-tools/component-test/set_dev_env.sh similarity index 100% rename from test-tools/component_test/set_dev_env.sh rename to test-tools/component-test/set_dev_env.sh diff --git a/test-tools/component_test/start.py b/test-tools/component-test/start.py similarity index 100% rename from test-tools/component_test/start.py rename to test-tools/component-test/start.py diff --git a/test-tools/component_test/suites/01-life-cycle/__init__.py b/test-tools/component-test/suites/01-life-cycle/__init__.py similarity index 100% rename from test-tools/component_test/suites/01-life-cycle/__init__.py rename to test-tools/component-test/suites/01-life-cycle/__init__.py diff --git a/test-tools/component_test/suites/01-life-cycle/cases/01-install/__init__.py b/test-tools/component-test/suites/01-life-cycle/cases/01-install/__init__.py similarity index 100% rename from test-tools/component_test/suites/01-life-cycle/cases/01-install/__init__.py rename to test-tools/component-test/suites/01-life-cycle/cases/01-install/__init__.py diff --git a/test-tools/component_test/suites/01-life-cycle/cases/01-install/case.py b/test-tools/component-test/suites/01-life-cycle/cases/01-install/case.py similarity index 100% rename from test-tools/component_test/suites/01-life-cycle/cases/01-install/case.py rename to test-tools/component-test/suites/01-life-cycle/cases/01-install/case.py diff --git a/test-tools/component_test/suites/01-life-cycle/cases/02-request/__init__.py b/test-tools/component-test/suites/01-life-cycle/cases/02-request/__init__.py similarity index 100% rename from test-tools/component_test/suites/01-life-cycle/cases/02-request/__init__.py rename to test-tools/component-test/suites/01-life-cycle/cases/02-request/__init__.py diff --git a/test-tools/component_test/suites/01-life-cycle/cases/02-request/case.py b/test-tools/component-test/suites/01-life-cycle/cases/02-request/case.py similarity index 100% rename from test-tools/component_test/suites/01-life-cycle/cases/02-request/case.py rename to test-tools/component-test/suites/01-life-cycle/cases/02-request/case.py diff --git a/test-tools/component_test/suites/01-life-cycle/cases/03-event/__init__.py b/test-tools/component-test/suites/01-life-cycle/cases/03-event/__init__.py similarity index 100% rename from test-tools/component_test/suites/01-life-cycle/cases/03-event/__init__.py rename to test-tools/component-test/suites/01-life-cycle/cases/03-event/__init__.py diff --git a/test-tools/component_test/suites/01-life-cycle/cases/03-event/case.py b/test-tools/component-test/suites/01-life-cycle/cases/03-event/case.py similarity index 100% rename from test-tools/component_test/suites/01-life-cycle/cases/03-event/case.py rename to test-tools/component-test/suites/01-life-cycle/cases/03-event/case.py diff --git a/test-tools/component_test/suites/01-life-cycle/cases/04-request-internal/__init__.py b/test-tools/component-test/suites/01-life-cycle/cases/04-request-internal/__init__.py similarity index 100% rename from test-tools/component_test/suites/01-life-cycle/cases/04-request-internal/__init__.py rename to test-tools/component-test/suites/01-life-cycle/cases/04-request-internal/__init__.py diff --git a/test-tools/component_test/suites/01-life-cycle/cases/04-request-internal/case.py b/test-tools/component-test/suites/01-life-cycle/cases/04-request-internal/case.py similarity index 100% rename from test-tools/component_test/suites/01-life-cycle/cases/04-request-internal/case.py rename to test-tools/component-test/suites/01-life-cycle/cases/04-request-internal/case.py diff --git a/test-tools/component_test/suites/01-life-cycle/cases/05-event-internal/__init__.py b/test-tools/component-test/suites/01-life-cycle/cases/05-event-internal/__init__.py similarity index 100% rename from test-tools/component_test/suites/01-life-cycle/cases/05-event-internal/__init__.py rename to test-tools/component-test/suites/01-life-cycle/cases/05-event-internal/__init__.py diff --git a/test-tools/component_test/suites/01-life-cycle/cases/05-event-internal/case.py b/test-tools/component-test/suites/01-life-cycle/cases/05-event-internal/case.py similarity index 100% rename from test-tools/component_test/suites/01-life-cycle/cases/05-event-internal/case.py rename to test-tools/component-test/suites/01-life-cycle/cases/05-event-internal/case.py diff --git a/test-tools/component_test/suites/01-life-cycle/cases/06-timer/__init__.py b/test-tools/component-test/suites/01-life-cycle/cases/06-timer/__init__.py similarity index 100% rename from test-tools/component_test/suites/01-life-cycle/cases/06-timer/__init__.py rename to test-tools/component-test/suites/01-life-cycle/cases/06-timer/__init__.py diff --git a/test-tools/component_test/suites/01-life-cycle/cases/06-timer/case.py b/test-tools/component-test/suites/01-life-cycle/cases/06-timer/case.py similarity index 100% rename from test-tools/component_test/suites/01-life-cycle/cases/06-timer/case.py rename to test-tools/component-test/suites/01-life-cycle/cases/06-timer/case.py diff --git a/test-tools/component_test/suites/01-life-cycle/cases/07-sensor/__init__.py b/test-tools/component-test/suites/01-life-cycle/cases/07-sensor/__init__.py similarity index 100% rename from test-tools/component_test/suites/01-life-cycle/cases/07-sensor/__init__.py rename to test-tools/component-test/suites/01-life-cycle/cases/07-sensor/__init__.py diff --git a/test-tools/component_test/suites/01-life-cycle/cases/07-sensor/case.py b/test-tools/component-test/suites/01-life-cycle/cases/07-sensor/case.py similarity index 100% rename from test-tools/component_test/suites/01-life-cycle/cases/07-sensor/case.py rename to test-tools/component-test/suites/01-life-cycle/cases/07-sensor/case.py diff --git a/test-tools/component_test/suites/01-life-cycle/cases/08-on-destroy/__init__.py b/test-tools/component-test/suites/01-life-cycle/cases/08-on-destroy/__init__.py similarity index 100% rename from test-tools/component_test/suites/01-life-cycle/cases/08-on-destroy/__init__.py rename to test-tools/component-test/suites/01-life-cycle/cases/08-on-destroy/__init__.py diff --git a/test-tools/component_test/suites/01-life-cycle/cases/08-on-destroy/case.py b/test-tools/component-test/suites/01-life-cycle/cases/08-on-destroy/case.py similarity index 100% rename from test-tools/component_test/suites/01-life-cycle/cases/08-on-destroy/case.py rename to test-tools/component-test/suites/01-life-cycle/cases/08-on-destroy/case.py diff --git a/test-tools/component_test/suites/01-life-cycle/cases/__init__.py b/test-tools/component-test/suites/01-life-cycle/cases/__init__.py similarity index 100% rename from test-tools/component_test/suites/01-life-cycle/cases/__init__.py rename to test-tools/component-test/suites/01-life-cycle/cases/__init__.py diff --git a/test-tools/component_test/suites/01-life-cycle/suite_setup.py b/test-tools/component-test/suites/01-life-cycle/suite_setup.py similarity index 100% rename from test-tools/component_test/suites/01-life-cycle/suite_setup.py rename to test-tools/component-test/suites/01-life-cycle/suite_setup.py diff --git a/test-tools/component-test/suites/01-life-cycle/test-app/01_install.c b/test-tools/component-test/suites/01-life-cycle/test-app/01_install.c new file mode 100644 index 0000000000..5c71535881 --- /dev/null +++ b/test-tools/component-test/suites/01-life-cycle/test-app/01_install.c @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include "wasm_app.h" + +void +on_init() +{ + printf("Hello, I was installed.\n"); +} + +void +on_destroy() +{ + /* real destroy work including killing timer and closing sensor is + * accomplished in wasm app library version of on_destroy() */ +} diff --git a/test-tools/component_test/suites/01-life-cycle/test-app/02_request.c b/test-tools/component-test/suites/01-life-cycle/test-app/02_request.c similarity index 66% rename from test-tools/component_test/suites/01-life-cycle/test-app/02_request.c rename to test-tools/component-test/suites/01-life-cycle/test-app/02_request.c index ee7ecafee9..251de6ff4a 100644 --- a/test-tools/component_test/suites/01-life-cycle/test-app/02_request.c +++ b/test-tools/component-test/suites/01-life-cycle/test-app/02_request.c @@ -1,12 +1,13 @@ /* -* Copyright (C) 2019 Intel Corporation. All rights reserved. -* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -*/ + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ #include "wasm_app.h" #include "wa-inc/request.h" -void res1_handler(request_t *request) +void +res1_handler(request_t *request) { response_t response[1]; attr_container_t *payload; @@ -18,9 +19,9 @@ void res1_handler(request_t *request) printf("url: %s\n", request->url); printf("action: %d\n", request->action); printf("payload:\n"); - if (request->payload - != NULL&& request->payload_len > 0 && request->fmt == FMT_ATTR_CONTAINER) - attr_container_dump((attr_container_t *) request->payload); + if (request->payload != NULL && request->payload_len > 0 + && request->fmt == FMT_ATTR_CONTAINER) + attr_container_dump((attr_container_t *)request->payload); printf("#### dump request end ###\n"); payload = attr_container_create("wasm app response payload"); @@ -31,15 +32,17 @@ void res1_handler(request_t *request) attr_container_set_string(&payload, "key2", "value2"); make_response_for_request(request, response); - set_response(response, CONTENT_2_05, - FMT_ATTR_CONTAINER, (const char *)payload, attr_container_get_serialize_length(payload)); + set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, + (const char *)payload, + attr_container_get_serialize_length(payload)); printf("reciver: %lu, mid:%d\n", response->reciever, response->mid); api_response_send(response); attr_container_destroy(payload); } -void res2_handler(request_t *request) +void +res2_handler(request_t *request) { response_t response[1]; make_response_for_request(request, response); @@ -49,14 +52,17 @@ void res2_handler(request_t *request) printf("### user resource 2 handler called\n"); } -void on_init() +void +on_init() { /* register resource uri */ api_register_resource_handler("/res1", res1_handler); api_register_resource_handler("/res2", res2_handler); } -void on_destroy() +void +on_destroy() { - /* real destroy work including killing timer and closing sensor is accomplished in wasm app library version of on_destroy() */ + /* real destroy work including killing timer and closing sensor is + * accomplished in wasm app library version of on_destroy() */ } diff --git a/test-tools/component_test/suites/01-life-cycle/test-app/03_event.c b/test-tools/component-test/suites/01-life-cycle/test-app/03_event.c similarity index 67% rename from test-tools/component_test/suites/01-life-cycle/test-app/03_event.c rename to test-tools/component-test/suites/01-life-cycle/test-app/03_event.c index 712110a9b0..59cfd0097c 100644 --- a/test-tools/component_test/suites/01-life-cycle/test-app/03_event.c +++ b/test-tools/component-test/suites/01-life-cycle/test-app/03_event.c @@ -1,7 +1,7 @@ /* -* Copyright (C) 2019 Intel Corporation. All rights reserved. -* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -*/ + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ #include "wasm_app.h" #include "wa-inc/timer_wasm_app.h" @@ -9,7 +9,8 @@ int num = 0; -void publish_overheat_event() +void +publish_overheat_event() { attr_container_t *event; @@ -19,7 +20,7 @@ void publish_overheat_event() printf("###app publish event begin ###\n"); api_publish_event("alert/overheat", FMT_ATTR_CONTAINER, event, - attr_container_get_serialize_length(event)); + attr_container_get_serialize_length(event)); printf("###app publish event end ###\n"); @@ -27,13 +28,15 @@ void publish_overheat_event() } /* Timer callback */ -void timer1_update(user_timer_t timer) +void +timer1_update(user_timer_t timer) { printf("Timer update %d\n", num++); publish_overheat_event(); } -void start_timer() +void +start_timer() { user_timer_t timer; @@ -42,12 +45,15 @@ void start_timer() api_timer_restart(timer, 1000); } -void on_init() +void +on_init() { start_timer(); } -void on_destroy() +void +on_destroy() { - /* real destroy work including killing timer and closing sensor is accomplished in wasm app library version of on_destroy() */ + /* real destroy work including killing timer and closing sensor is + * accomplished in wasm app library version of on_destroy() */ } diff --git a/test-tools/component_test/suites/01-life-cycle/test-app/04_request_internal_req.c b/test-tools/component-test/suites/01-life-cycle/test-app/04_request_internal_req.c similarity index 67% rename from test-tools/component_test/suites/01-life-cycle/test-app/04_request_internal_req.c rename to test-tools/component-test/suites/01-life-cycle/test-app/04_request_internal_req.c index 3e3ad0e605..99bab9704c 100644 --- a/test-tools/component_test/suites/01-life-cycle/test-app/04_request_internal_req.c +++ b/test-tools/component-test/suites/01-life-cycle/test-app/04_request_internal_req.c @@ -1,7 +1,7 @@ /* -* Copyright (C) 2019 Intel Corporation. All rights reserved. -* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -*/ + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ #include "wasm_app.h" #include "wa-inc/request.h" @@ -9,7 +9,8 @@ uint32 mid; unsigned long sender; -void my_response_handler(response_t *response, void *user_data) +void +my_response_handler(response_t *response, void *user_data) { attr_container_t *payload; printf("### user resource 1 handler called\n"); @@ -23,15 +24,17 @@ void my_response_handler(response_t *response, void *user_data) response->mid = mid; response->reciever = sender; - set_response(response, CONTENT_2_05, - FMT_ATTR_CONTAINER, (const char *)payload, attr_container_get_serialize_length(payload)); + set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, + (const char *)payload, + attr_container_get_serialize_length(payload)); printf("reciver: %lu, mid:%d\n", response->reciever, response->mid); api_response_send(response); attr_container_destroy(payload); } -static void test_send_request(const char *url, const char *tag) +static void +test_send_request(const char *url, const char *tag) { request_t request[1]; @@ -39,28 +42,33 @@ static void test_send_request(const char *url, const char *tag) api_send_request(request, my_response_handler, (void *)tag); } -void res1_handler(request_t *request) +void +res1_handler(request_t *request) { mid = request->mid; sender = request->sender; test_send_request("url1", "a general request"); } -void res2_handler(request_t *request) +void +res2_handler(request_t *request) { mid = request->mid; sender = request->sender; test_send_request("/app/App1/url1", "a general request"); } -void on_init() +void +on_init() { /* register resource uri */ api_register_resource_handler("/res1", res1_handler); api_register_resource_handler("/res2", res2_handler); } -void on_destroy() +void +on_destroy() { - /* real destroy work including killing timer and closing sensor is accomplished in wasm app library version of on_destroy() */ + /* real destroy work including killing timer and closing sensor is + * accomplished in wasm app library version of on_destroy() */ } diff --git a/test-tools/component_test/suites/01-life-cycle/test-app/04_request_internal_resp.c b/test-tools/component-test/suites/01-life-cycle/test-app/04_request_internal_resp.c similarity index 67% rename from test-tools/component_test/suites/01-life-cycle/test-app/04_request_internal_resp.c rename to test-tools/component-test/suites/01-life-cycle/test-app/04_request_internal_resp.c index 45b25cbd20..13aecb43aa 100644 --- a/test-tools/component_test/suites/01-life-cycle/test-app/04_request_internal_resp.c +++ b/test-tools/component-test/suites/01-life-cycle/test-app/04_request_internal_resp.c @@ -1,12 +1,13 @@ /* -* Copyright (C) 2019 Intel Corporation. All rights reserved. -* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -*/ + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ #include "wasm_app.h" #include "wa-inc/request.h" -void res1_handler(request_t *request) +void +res1_handler(request_t *request) { response_t response[1]; attr_container_t *payload; @@ -19,7 +20,7 @@ void res1_handler(request_t *request) printf("[resp] action: %d\n", request->action); printf("[resp] payload:\n"); if (request->payload != NULL && request->fmt == FMT_ATTR_CONTAINER) - attr_container_dump((attr_container_t *) request->payload); + attr_container_dump((attr_container_t *)request->payload); printf("[resp] #### dump request end ###\n"); payload = attr_container_create("wasm app response payload"); @@ -30,23 +31,27 @@ void res1_handler(request_t *request) attr_container_set_string(&payload, "key2", "value2"); make_response_for_request(request, response); - set_response(response, CONTENT_2_05, - FMT_ATTR_CONTAINER, (const char *)payload, attr_container_get_serialize_length(payload)); + set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, + (const char *)payload, + attr_container_get_serialize_length(payload)); printf("[resp] response payload len %d\n", - attr_container_get_serialize_length(payload)); + attr_container_get_serialize_length(payload)); printf("[resp] reciver: %lu, mid:%d\n", response->reciever, response->mid); api_response_send(response); attr_container_destroy(payload); } -void on_init() +void +on_init() { /* register resource uri */ api_register_resource_handler("/url1", res1_handler); } -void on_destroy() +void +on_destroy() { - /* real destroy work including killing timer and closing sensor is accomplished in wasm app library version of on_destroy() */ + /* real destroy work including killing timer and closing sensor is + * accomplished in wasm app library version of on_destroy() */ } diff --git a/test-tools/component_test/suites/01-life-cycle/test-app/05_event_internal_provider.c b/test-tools/component-test/suites/01-life-cycle/test-app/05_event_internal_provider.c similarity index 67% rename from test-tools/component_test/suites/01-life-cycle/test-app/05_event_internal_provider.c rename to test-tools/component-test/suites/01-life-cycle/test-app/05_event_internal_provider.c index 712110a9b0..59cfd0097c 100644 --- a/test-tools/component_test/suites/01-life-cycle/test-app/05_event_internal_provider.c +++ b/test-tools/component-test/suites/01-life-cycle/test-app/05_event_internal_provider.c @@ -1,7 +1,7 @@ /* -* Copyright (C) 2019 Intel Corporation. All rights reserved. -* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -*/ + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ #include "wasm_app.h" #include "wa-inc/timer_wasm_app.h" @@ -9,7 +9,8 @@ int num = 0; -void publish_overheat_event() +void +publish_overheat_event() { attr_container_t *event; @@ -19,7 +20,7 @@ void publish_overheat_event() printf("###app publish event begin ###\n"); api_publish_event("alert/overheat", FMT_ATTR_CONTAINER, event, - attr_container_get_serialize_length(event)); + attr_container_get_serialize_length(event)); printf("###app publish event end ###\n"); @@ -27,13 +28,15 @@ void publish_overheat_event() } /* Timer callback */ -void timer1_update(user_timer_t timer) +void +timer1_update(user_timer_t timer) { printf("Timer update %d\n", num++); publish_overheat_event(); } -void start_timer() +void +start_timer() { user_timer_t timer; @@ -42,12 +45,15 @@ void start_timer() api_timer_restart(timer, 1000); } -void on_init() +void +on_init() { start_timer(); } -void on_destroy() +void +on_destroy() { - /* real destroy work including killing timer and closing sensor is accomplished in wasm app library version of on_destroy() */ + /* real destroy work including killing timer and closing sensor is + * accomplished in wasm app library version of on_destroy() */ } diff --git a/test-tools/component_test/suites/01-life-cycle/test-app/05_event_internal_subscriber.c b/test-tools/component-test/suites/01-life-cycle/test-app/05_event_internal_subscriber.c similarity index 64% rename from test-tools/component_test/suites/01-life-cycle/test-app/05_event_internal_subscriber.c rename to test-tools/component-test/suites/01-life-cycle/test-app/05_event_internal_subscriber.c index dd031f80ad..00e4513697 100644 --- a/test-tools/component_test/suites/01-life-cycle/test-app/05_event_internal_subscriber.c +++ b/test-tools/component-test/suites/01-life-cycle/test-app/05_event_internal_subscriber.c @@ -1,7 +1,7 @@ /* -* Copyright (C) 2019 Intel Corporation. All rights reserved. -* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -*/ + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ #include "wasm_app.h" #include "wa-inc/request.h" @@ -9,7 +9,8 @@ uint32 mid; unsigned long sender; -void over_heat_event_handler(request_t *request) +void +over_heat_event_handler(request_t *request) { response_t response[1]; attr_container_t *payload; @@ -23,28 +24,33 @@ void over_heat_event_handler(request_t *request) response->mid = mid; response->reciever = sender; - set_response(response, CONTENT_2_05, - FMT_ATTR_CONTAINER, (const char *)payload, attr_container_get_serialize_length(payload)); + set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, + (const char *)payload, + attr_container_get_serialize_length(payload)); printf("reciver: %lu, mid:%d\n", response->reciever, response->mid); api_response_send(response); attr_container_destroy(payload); } -void res1_handler(request_t *request) +void +res1_handler(request_t *request) { mid = request->mid; sender = request->sender; api_subscribe_event("alert/overheat", over_heat_event_handler); } -void on_init() +void +on_init() { /* register resource uri */ api_register_resource_handler("/res1", res1_handler); } -void on_destroy() +void +on_destroy() { - /* real destroy work including killing timer and closing sensor is accomplished in wasm app library version of on_destroy() */ + /* real destroy work including killing timer and closing sensor is + * accomplished in wasm app library version of on_destroy() */ } diff --git a/test-tools/component_test/suites/01-life-cycle/test-app/06_timer.c b/test-tools/component-test/suites/01-life-cycle/test-app/06_timer.c similarity index 68% rename from test-tools/component_test/suites/01-life-cycle/test-app/06_timer.c rename to test-tools/component-test/suites/01-life-cycle/test-app/06_timer.c index c20365717f..6aa107d5c7 100644 --- a/test-tools/component_test/suites/01-life-cycle/test-app/06_timer.c +++ b/test-tools/component-test/suites/01-life-cycle/test-app/06_timer.c @@ -1,7 +1,7 @@ /* -* Copyright (C) 2019 Intel Corporation. All rights reserved. -* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -*/ + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ #include "wasm_app.h" #include "wa-inc/request.h" @@ -11,13 +11,15 @@ int num = 0; /* Timer callback */ -void timer1_update(user_timer_t timer) +void +timer1_update(user_timer_t timer) { if (num < 2) num++; } -void res1_handler(request_t *request) +void +res1_handler(request_t *request) { user_timer_t timer; @@ -29,13 +31,13 @@ void res1_handler(request_t *request) make_response_for_request(request, response); - set_response(response, CONTENT_2_05, - FMT_ATTR_CONTAINER, NULL, 0); + set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, NULL, 0); api_response_send(response); } -void res2_handler(request_t *request) +void +res2_handler(request_t *request) { response_t response[1]; attr_container_t *payload; @@ -52,25 +54,27 @@ void res2_handler(request_t *request) make_response_for_request(request, response); - set_response(response, CONTENT_2_05, - FMT_ATTR_CONTAINER, (const char *)payload, - attr_container_get_serialize_length(payload)); + set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, + (const char *)payload, + attr_container_get_serialize_length(payload)); printf("reciver: %lu, mid:%d\n", response->reciever, response->mid); api_response_send(response); attr_container_destroy(payload); } - } -void on_init() +void +on_init() { /* register resource uri */ api_register_resource_handler("/res1", res1_handler); api_register_resource_handler("/check_timer", res2_handler); } -void on_destroy() +void +on_destroy() { - /* real destroy work including killing timer and closing sensor is accomplished in wasm app library version of on_destroy() */ + /* real destroy work including killing timer and closing sensor is + * accomplished in wasm app library version of on_destroy() */ } diff --git a/test-tools/component_test/suites/01-life-cycle/test-app/07_sensor.c b/test-tools/component-test/suites/01-life-cycle/test-app/07_sensor.c similarity index 71% rename from test-tools/component_test/suites/01-life-cycle/test-app/07_sensor.c rename to test-tools/component-test/suites/01-life-cycle/test-app/07_sensor.c index 24af34c915..a6c24a8bcb 100644 --- a/test-tools/component_test/suites/01-life-cycle/test-app/07_sensor.c +++ b/test-tools/component-test/suites/01-life-cycle/test-app/07_sensor.c @@ -1,7 +1,7 @@ /* -* Copyright (C) 2019 Intel Corporation. All rights reserved. -* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -*/ + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ #include "wasm_app.h" #include "wa-inc/request.h" @@ -11,8 +11,8 @@ uint32 mid; unsigned long sender; /* Sensor event callback*/ -void sensor_event_handler(sensor_t sensor, attr_container_t *event, - void *user_data) +void +sensor_event_handler(sensor_t sensor, attr_container_t *event, void *user_data) { printf("### app get sensor event\n"); @@ -28,15 +28,17 @@ void sensor_event_handler(sensor_t sensor, attr_container_t *event, response->mid = mid; response->reciever = sender; - set_response(response, CONTENT_2_05, - FMT_ATTR_CONTAINER, (const char *)payload, attr_container_get_serialize_length(payload)); + set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, + (const char *)payload, + attr_container_get_serialize_length(payload)); printf("reciver: %lu, mid:%d\n", response->reciever, response->mid); api_response_send(response); attr_container_destroy(payload); } -void res1_handler(request_t *request) +void +res1_handler(request_t *request) { mid = request->mid; sender = request->sender; @@ -57,13 +59,16 @@ void res1_handler(request_t *request) printf("### app on_init 4\n"); } -void on_init() +void +on_init() { /* register resource uri */ api_register_resource_handler("/res1", res1_handler); } -void on_destroy() +void +on_destroy() { - /* real destroy work including killing timer and closing sensor is accomplished in wasm app library version of on_destroy() */ + /* real destroy work including killing timer and closing sensor is + * accomplished in wasm app library version of on_destroy() */ } diff --git a/test-tools/component-test/suites/01-life-cycle/test-app/08_on_destroy.c b/test-tools/component-test/suites/01-life-cycle/test-app/08_on_destroy.c new file mode 100644 index 0000000000..ac05a77da5 --- /dev/null +++ b/test-tools/component-test/suites/01-life-cycle/test-app/08_on_destroy.c @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include "wasm_app.h" +#include "wa-inc/request.h" +#include "wa-inc/sensor.h" + +uint32 mid; +unsigned long sender; +sensor_t sensor; + +/* Sensor event callback*/ +void +sensor_event_handler(sensor_t sensor, attr_container_t *event, void *user_data) +{ + printf("### app get sensor event\n"); + + response_t response[1]; + attr_container_t *payload; + + payload = attr_container_create("wasm app response payload"); + if (payload == NULL) + return; + + attr_container_set_string(&payload, "key1", "value1"); + + response->mid = mid; + response->reciever = sender; + set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, + (const char *)payload, + attr_container_get_serialize_length(payload)); + printf("reciver: %lu, mid:%d\n", response->reciever, response->mid); + api_response_send(response); + + attr_container_destroy(payload); +} + +void +res1_handler(request_t *request) +{ + mid = request->mid; + sender = request->sender; + + char *user_data; + attr_container_t *config; + + printf("### app on_init 1\n"); + /* open a sensor */ + user_data = malloc(100); + printf("### app on_init 2\n"); + sensor = sensor_open("sensor_test", 0, sensor_event_handler, user_data); + printf("### app on_init 3\n"); +} + +void +on_init() +{ + /* register resource uri */ + api_register_resource_handler("/res1", res1_handler); +} + +void +on_destroy() +{ + if (NULL != sensor) { + sensor_close(sensor); + } +} diff --git a/test-tools/component_test/suites/01-life-cycle/test-app/build.sh b/test-tools/component-test/suites/01-life-cycle/test-app/build.sh similarity index 100% rename from test-tools/component_test/suites/01-life-cycle/test-app/build.sh rename to test-tools/component-test/suites/01-life-cycle/test-app/build.sh diff --git a/test-tools/component_test/suites/01-life-cycle/tools/product/start.sh b/test-tools/component-test/suites/01-life-cycle/tools/product/start.sh similarity index 100% rename from test-tools/component_test/suites/01-life-cycle/tools/product/start.sh rename to test-tools/component-test/suites/01-life-cycle/tools/product/start.sh diff --git a/test-tools/component_test/suites/01-life-cycle/tools/product/stop.sh b/test-tools/component-test/suites/01-life-cycle/tools/product/stop.sh similarity index 100% rename from test-tools/component_test/suites/01-life-cycle/tools/product/stop.sh rename to test-tools/component-test/suites/01-life-cycle/tools/product/stop.sh diff --git a/test-tools/component_test/suites/__init__.py b/test-tools/component-test/suites/__init__.py similarity index 100% rename from test-tools/component_test/suites/__init__.py rename to test-tools/component-test/suites/__init__.py diff --git a/test-tools/component_test/suites/readme.txt b/test-tools/component-test/suites/readme.txt similarity index 100% rename from test-tools/component_test/suites/readme.txt rename to test-tools/component-test/suites/readme.txt diff --git a/test-tools/component_test/suites/01-life-cycle/test-app/01_install.c b/test-tools/component_test/suites/01-life-cycle/test-app/01_install.c deleted file mode 100644 index f8ec393739..0000000000 --- a/test-tools/component_test/suites/01-life-cycle/test-app/01_install.c +++ /dev/null @@ -1,16 +0,0 @@ -/* -* Copyright (C) 2019 Intel Corporation. All rights reserved. -* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -*/ - -#include "wasm_app.h" - -void on_init() -{ - printf("Hello, I was installed.\n"); -} - -void on_destroy() -{ - /* real destroy work including killing timer and closing sensor is accomplished in wasm app library version of on_destroy() */ -} diff --git a/test-tools/component_test/suites/01-life-cycle/test-app/08_on_destroy.c b/test-tools/component_test/suites/01-life-cycle/test-app/08_on_destroy.c deleted file mode 100644 index 637e0f7a62..0000000000 --- a/test-tools/component_test/suites/01-life-cycle/test-app/08_on_destroy.c +++ /dev/null @@ -1,67 +0,0 @@ -/* -* Copyright (C) 2019 Intel Corporation. All rights reserved. -* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -*/ - -#include "wasm_app.h" -#include "wa-inc/request.h" -#include "wa-inc/sensor.h" - -uint32 mid; -unsigned long sender; -sensor_t sensor; - -/* Sensor event callback*/ -void sensor_event_handler(sensor_t sensor, attr_container_t *event, void *user_data) { - printf("### app get sensor event\n"); - - response_t response[1]; - attr_container_t *payload; - - payload = attr_container_create("wasm app response payload"); - if (payload == NULL) - return; - - attr_container_set_string(&payload, "key1", "value1"); - - response->mid = mid; - response->reciever = sender; - set_response(response, - CONTENT_2_05, - FMT_ATTR_CONTAINER, - (const char *)payload, - attr_container_get_serialize_length(payload)); - printf("reciver: %lu, mid:%d\n", response->reciever, response->mid); - api_response_send(response); - - attr_container_destroy(payload); -} - -void res1_handler(request_t *request) -{ - mid = request->mid; - sender = request->sender; - - char *user_data; - attr_container_t *config; - - printf("### app on_init 1\n"); - /* open a sensor */ - user_data = malloc(100); - printf("### app on_init 2\n"); - sensor = sensor_open("sensor_test", 0, sensor_event_handler, user_data); - printf("### app on_init 3\n"); -} - -void on_init() -{ - /* register resource uri */ - api_register_resource_handler("/res1", res1_handler); -} - -void on_destroy() -{ - if(NULL != sensor){ - sensor_close(sensor); - } -} diff --git a/test-tools/host-tool/external/cJSON/cJSON.c b/test-tools/host-tool/external/cJSON/cJSON.c index b948d6d757..5bec53a7ac 100644 --- a/test-tools/host-tool/external/cJSON/cJSON.c +++ b/test-tools/host-tool/external/cJSON/cJSON.c @@ -32,9 +32,9 @@ #pragma GCC visibility push(default) #endif #if defined(_MSC_VER) -#pragma warning (push) +#pragma warning(push) /* disable warning about single line comments in system headers */ -#pragma warning (disable : 4001) +#pragma warning(disable : 4001) #endif #include @@ -49,7 +49,7 @@ #endif #if defined(_MSC_VER) -#pragma warning (pop) +#pragma warning(pop) #endif #ifdef __GNUC__ #pragma GCC visibility pop @@ -69,10 +69,11 @@ static error global_error = { NULL, 0 }; CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void) { - return (const char*) (global_error.json + global_error.position); + return (const char *)(global_error.json + global_error.position); } -CJSON_PUBLIC(char *) cJSON_GetStringValue(cJSON *item) { +CJSON_PUBLIC(char *) cJSON_GetStringValue(cJSON *item) +{ if (!cJSON_IsString(item)) { return NULL; } @@ -80,23 +81,27 @@ CJSON_PUBLIC(char *) cJSON_GetStringValue(cJSON *item) { return item->valuestring; } -/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */ -#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 10) +/* This is a safeguard to prevent copy-pasters from using incompatible C and + * header files */ +#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) \ + || (CJSON_VERSION_PATCH != 10) #error cJSON.h and cJSON.c have different versions. Make sure that both have the same. #endif -CJSON_PUBLIC(const char*) cJSON_Version(void) +CJSON_PUBLIC(const char *) cJSON_Version(void) { static char version[15]; - snprintf(version, sizeof(version), "%i.%i.%i", - CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH); + snprintf(version, sizeof(version), "%i.%i.%i", CJSON_VERSION_MAJOR, + CJSON_VERSION_MINOR, CJSON_VERSION_PATCH); return version; } -/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */ -static int case_insensitive_strcmp(const unsigned char *string1, - const unsigned char *string2) +/* Case insensitive string comparison, doesn't consider two NULL pointers equal + * though */ +static int +case_insensitive_strcmp(const unsigned char *string1, + const unsigned char *string2) { if ((string1 == NULL) || (string2 == NULL)) { return 1; @@ -106,8 +111,7 @@ static int case_insensitive_strcmp(const unsigned char *string1, return 0; } - for (; tolower(*string1) == tolower(*string2); - (void) string1++, string2++) { + for (; tolower(*string1) == tolower(*string2); (void)string1++, string2++) { if (*string1 == '\0') { return 0; } @@ -118,21 +122,25 @@ static int case_insensitive_strcmp(const unsigned char *string1, typedef struct internal_hooks { void *(CJSON_CDECL *allocate)(size_t size); - void (CJSON_CDECL *deallocate)(void *pointer); + void(CJSON_CDECL *deallocate)(void *pointer); void *(CJSON_CDECL *reallocate)(void *pointer, size_t size); } internal_hooks; #if defined(_MSC_VER) -/* work around MSVC error C2322: '...' address of dillimport '...' is not static */ -static void * CJSON_CDECL internal_malloc(size_t size) +/* work around MSVC error C2322: '...' address of dillimport '...' + is not static */ +static void *CJSON_CDECL +internal_malloc(size_t size) { return malloc(size); } -static void CJSON_CDECL internal_free(void *pointer) +static void CJSON_CDECL +internal_free(void *pointer) { free(pointer); } -static void * CJSON_CDECL internal_realloc(void *pointer, size_t size) +static void *CJSON_CDECL +internal_realloc(void *pointer, size_t size) { return realloc(pointer, size); } @@ -142,11 +150,16 @@ static void * CJSON_CDECL internal_realloc(void *pointer, size_t size) #define internal_realloc realloc #endif -static internal_hooks global_hooks = { internal_malloc, internal_free, -internal_realloc }; +/* clang-format off */ +static internal_hooks global_hooks = { + internal_malloc, + internal_free, + internal_realloc +}; +/* clang-format on */ -static unsigned char* cJSON_strdup(const unsigned char* string, - const internal_hooks * const hooks) +static unsigned char * +cJSON_strdup(const unsigned char *string, const internal_hooks *const hooks) { size_t length = 0; unsigned char *copy = NULL; @@ -155,8 +168,8 @@ static unsigned char* cJSON_strdup(const unsigned char* string, return NULL; } - length = strlen((const char*) string) + sizeof(""); - copy = (unsigned char*) hooks->allocate(length); + length = strlen((const char *)string) + sizeof(""); + copy = (unsigned char *)hooks->allocate(length); if (copy == NULL) { return NULL; } @@ -165,7 +178,7 @@ static unsigned char* cJSON_strdup(const unsigned char* string, return copy; } -CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks) +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks *hooks) { if (hooks == NULL) { /* Reset hooks */ @@ -188,15 +201,16 @@ CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks) /* use realloc only if both free and malloc are used */ global_hooks.reallocate = NULL; if ((global_hooks.allocate == malloc) - && (global_hooks.deallocate == free)) { + && (global_hooks.deallocate == free)) { global_hooks.reallocate = realloc; } } /* Internal constructor. */ -static cJSON *cJSON_New_Item(const internal_hooks * const hooks) +static cJSON * +cJSON_New_Item(const internal_hooks *const hooks) { - cJSON* node = (cJSON*) hooks->allocate(sizeof(cJSON)); + cJSON *node = (cJSON *)hooks->allocate(sizeof(cJSON)); if (node) { memset(node, '\0', sizeof(cJSON)); } @@ -225,11 +239,12 @@ CJSON_PUBLIC(void) cJSON_Delete(cJSON *item) } /* get the decimal point character of the current locale */ -static unsigned char get_decimal_point(void) +static unsigned char +get_decimal_point(void) { #ifdef ENABLE_LOCALES struct lconv *lconv = localeconv(); - return (unsigned char) lconv->decimal_point[0]; + return (unsigned char)lconv->decimal_point[0]; #else return '.'; #endif @@ -239,21 +254,27 @@ typedef struct { const unsigned char *content; size_t length; size_t offset; - size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */ + size_t depth; /* How deeply nested (in arrays/objects) is the input at the + current offset. */ internal_hooks hooks; } parse_buffer; -/* check if the given size is left to read in a given parse buffer (starting with 1) */ -#define can_read(buffer, size) ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length)) +/* check if the given size is left to read in a given parse buffer (starting + * with 1) */ +#define can_read(buffer, size) \ + ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length)) /* check if the buffer can be accessed at the given index (starting with 0) */ -#define can_access_at_index(buffer, index) ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length)) -#define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index)) +#define can_access_at_index(buffer, index) \ + ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length)) +#define cannot_access_at_index(buffer, index) \ + (!can_access_at_index(buffer, index)) /* get a pointer to the buffer at the position */ #define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset) -/* Parse the input text to generate a number, and populate the result into item. */ -static cJSON_bool parse_number(cJSON * const item, - parse_buffer * const input_buffer) +/* Parse the input text to generate a number, and populate the result + into item. */ +static cJSON_bool +parse_number(cJSON *const item, parse_buffer *const input_buffer) { double number = 0; unsigned char *after_end = NULL; @@ -265,41 +286,43 @@ static cJSON_bool parse_number(cJSON * const item, return false; } - /* copy the number into a temporary buffer and replace '.' with the decimal point - * of the current locale (for strtod) - * This also takes care of '\0' not necessarily being available for marking the end of the input */ - for (i = 0; - (i < (sizeof(number_c_string) - 1)) - && can_access_at_index(input_buffer, i); i++) { + /* copy the number into a temporary buffer and replace '.' with the decimal + * point of the current locale (for strtod) + * This also takes care of '\0' not necessarily being available for marking + * the end of the input */ + for (i = 0; (i < (sizeof(number_c_string) - 1)) + && can_access_at_index(input_buffer, i); + i++) { switch (buffer_at_offset(input_buffer)[i]) { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - case '+': - case '-': - case 'e': - case 'E': - number_c_string[i] = buffer_at_offset(input_buffer)[i]; - break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '+': + case '-': + case 'e': + case 'E': + number_c_string[i] = buffer_at_offset(input_buffer)[i]; + break; - case '.': - number_c_string[i] = decimal_point; - break; + case '.': + number_c_string[i] = decimal_point; + break; - default: - goto loop_end; + default: + goto loop_end; } } - loop_end: number_c_string[i] = '\0'; +loop_end: + number_c_string[i] = '\0'; - number = strtod((const char*) number_c_string, (char**) &after_end); + number = strtod((const char *)number_c_string, (char **)&after_end); if (number_c_string == after_end) { return false; /* parse_error */ } @@ -309,10 +332,12 @@ static cJSON_bool parse_number(cJSON * const item, /* use saturation in case of overflow */ if (number >= INT_MAX) { item->valueint = INT_MAX; - } else if (number <= (double) INT_MIN) { + } + else if (number <= (double)INT_MIN) { item->valueint = INT_MIN; - } else { - item->valueint = (int) number; + } + else { + item->valueint = (int)number; } item->type = cJSON_Number; @@ -321,15 +346,18 @@ static cJSON_bool parse_number(cJSON * const item, return true; } -/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */ +/* don't ask me, but the original cJSON_SetNumberValue returns an integer or + * double */ CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number) { if (number >= INT_MAX) { object->valueint = INT_MAX; - } else if (number <= (double) INT_MIN) { + } + else if (number <= (double)INT_MIN) { object->valueint = INT_MIN; - } else { - object->valueint = (int) number; + } + else { + object->valueint = (int)number; } return object->valuedouble = number; @@ -346,7 +374,8 @@ typedef struct { } printbuffer; /* realloc printbuffer if necessary to have at least "needed" bytes more */ -static unsigned char* ensure(printbuffer * const p, size_t needed) +static unsigned char * +ensure(printbuffer *const p, size_t needed) { unsigned char *newbuffer = NULL; size_t newsize = 0; @@ -379,16 +408,18 @@ static unsigned char* ensure(printbuffer * const p, size_t needed) /* overflow of int, use INT_MAX if possible */ if (needed <= INT_MAX) { newsize = INT_MAX; - } else { + } + else { return NULL; } - } else { + } + else { newsize = needed * 2; } if (p->hooks.reallocate != NULL) { /* reallocate with realloc if available */ - newbuffer = (unsigned char*) p->hooks.reallocate(p->buffer, newsize); + newbuffer = (unsigned char *)p->hooks.reallocate(p->buffer, newsize); if (newbuffer == NULL) { p->hooks.deallocate(p->buffer); p->length = 0; @@ -396,9 +427,10 @@ static unsigned char* ensure(printbuffer * const p, size_t needed) return NULL; } - } else { + } + else { /* otherwise reallocate manually */ - newbuffer = (unsigned char*) p->hooks.allocate(newsize); + newbuffer = (unsigned char *)p->hooks.allocate(newsize); if (!newbuffer) { p->hooks.deallocate(p->buffer); p->length = 0; @@ -417,8 +449,10 @@ static unsigned char* ensure(printbuffer * const p, size_t needed) return newbuffer + p->offset; } -/* calculate the new length of the string in a printbuffer and update the offset */ -static void update_offset(printbuffer * const buffer) +/* calculate the new length of the string in a printbuffer and update the offset + */ +static void +update_offset(printbuffer *const buffer) { const unsigned char *buffer_pointer = NULL; if ((buffer == NULL) || (buffer->buffer == NULL)) { @@ -426,18 +460,19 @@ static void update_offset(printbuffer * const buffer) } buffer_pointer = buffer->buffer + buffer->offset; - buffer->offset += strlen((const char*) buffer_pointer); + buffer->offset += strlen((const char *)buffer_pointer); } /* Render the number nicely from the given item into a string. */ -static cJSON_bool print_number(const cJSON * const item, - printbuffer * const output_buffer) +static cJSON_bool +print_number(const cJSON *const item, printbuffer *const output_buffer) { unsigned char *output_pointer = NULL; double d = item->valuedouble; int length = 0; size_t i = 0; - unsigned char number_buffer[26]; /* temporary buffer to print the number into */ + unsigned char + number_buffer[26]; /* temporary buffer to print the number into */ unsigned char decimal_point = get_decimal_point(); double test; @@ -447,33 +482,37 @@ static cJSON_bool print_number(const cJSON * const item, /* This checks for NaN and Infinity */ if ((d * 0) != 0) { - length = snprintf((char*) number_buffer, sizeof(number_buffer), "null"); - } else { - /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */ - length = snprintf((char*) number_buffer, sizeof(number_buffer), "%1.15g", d); + length = snprintf((char *)number_buffer, sizeof(number_buffer), "null"); + } + else { + /* Try 15 decimal places of precision to avoid nonsignificant nonzero + * digits */ + length = + snprintf((char *)number_buffer, sizeof(number_buffer), "%1.15g", d); /* Check whether the original double can be recovered */ - if ((sscanf((char*) number_buffer, "%lg", &test) != 1) - || ((double) test != d)) { + if ((sscanf((char *)number_buffer, "%lg", &test) != 1) + || ((double)test != d)) { /* If not, print with 17 decimal places of precision */ - length = snprintf((char*) number_buffer, sizeof(number_buffer), "%1.17g", d); + length = snprintf((char *)number_buffer, sizeof(number_buffer), + "%1.17g", d); } } /* snprintf failed or buffer overrun occured */ - if ((length < 0) || (length > (int) (sizeof(number_buffer) - 1))) { + if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1))) { return false; } /* reserve appropriate space in the output */ - output_pointer = ensure(output_buffer, (size_t) length + sizeof("")); + output_pointer = ensure(output_buffer, (size_t)length + sizeof("")); if (output_pointer == NULL) { return false; } /* copy the printed number to the output and replace locale * dependent decimal point with '.' */ - for (i = 0; i < ((size_t) length); i++) { + for (i = 0; i < ((size_t)length); i++) { if (number_buffer[i] == decimal_point) { output_pointer[i] = '.'; continue; @@ -483,13 +522,14 @@ static cJSON_bool print_number(const cJSON * const item, } output_pointer[i] = '\0'; - output_buffer->offset += (size_t) length; + output_buffer->offset += (size_t)length; return true; } /* parse 4 digit hexadecimal number */ -static unsigned parse_hex4(const unsigned char * const input) +static unsigned +parse_hex4(const unsigned char *const input) { unsigned int h = 0; size_t i = 0; @@ -497,12 +537,15 @@ static unsigned parse_hex4(const unsigned char * const input) for (i = 0; i < 4; i++) { /* parse digit */ if ((input[i] >= '0') && (input[i] <= '9')) { - h += (unsigned int) input[i] - '0'; - } else if ((input[i] >= 'A') && (input[i] <= 'F')) { - h += (unsigned int) 10 + input[i] - 'A'; - } else if ((input[i] >= 'a') && (input[i] <= 'f')) { - h += (unsigned int) 10 + input[i] - 'a'; - } else /* invalid */ + h += (unsigned int)input[i] - '0'; + } + else if ((input[i] >= 'A') && (input[i] <= 'F')) { + h += (unsigned int)10 + input[i] - 'A'; + } + else if ((input[i] >= 'a') && (input[i] <= 'f')) { + h += (unsigned int)10 + input[i] - 'a'; + } + else /* invalid */ { return 0; } @@ -518,9 +561,10 @@ static unsigned parse_hex4(const unsigned char * const input) /* converts a UTF-16 literal to UTF-8 * A literal can be one or two sequences of the form \uXXXX */ -static unsigned char utf16_literal_to_utf8( - const unsigned char * const input_pointer, - const unsigned char * const input_end, unsigned char **output_pointer) +static unsigned char +utf16_literal_to_utf8(const unsigned char *const input_pointer, + const unsigned char *const input_end, + unsigned char **output_pointer) { long unsigned int codepoint = 0; unsigned int first_code = 0; @@ -568,9 +612,10 @@ static unsigned char utf16_literal_to_utf8( } /* calculate the unicode codepoint from the surrogate pair */ - codepoint = 0x10000 - + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF)); - } else { + codepoint = + 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF)); + } + else { sequence_length = 6; /* \uXXXX */ codepoint = first_code; } @@ -581,49 +626,55 @@ static unsigned char utf16_literal_to_utf8( if (codepoint < 0x80) { /* normal ascii, encoding 0xxxxxxx */ utf8_length = 1; - } else if (codepoint < 0x800) { + } + else if (codepoint < 0x800) { /* two bytes, encoding 110xxxxx 10xxxxxx */ utf8_length = 2; first_byte_mark = 0xC0; /* 11000000 */ - } else if (codepoint < 0x10000) { + } + else if (codepoint < 0x10000) { /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */ utf8_length = 3; first_byte_mark = 0xE0; /* 11100000 */ - } else if (codepoint <= 0x10FFFF) { + } + else if (codepoint <= 0x10FFFF) { /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */ utf8_length = 4; first_byte_mark = 0xF0; /* 11110000 */ - } else { + } + else { /* invalid unicode codepoint */ goto fail; } /* encode as utf8 */ - for (utf8_position = (unsigned char) (utf8_length - 1); utf8_position > 0; - utf8_position--) { + for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; + utf8_position--) { /* 10xxxxxx */ - (*output_pointer)[utf8_position] = (unsigned char) ((codepoint | 0x80) - & 0xBF); + (*output_pointer)[utf8_position] = + (unsigned char)((codepoint | 0x80) & 0xBF); codepoint >>= 6; } /* encode first byte */ if (utf8_length > 1) { - (*output_pointer)[0] = (unsigned char) ((codepoint | first_byte_mark) - & 0xFF); - } else { - (*output_pointer)[0] = (unsigned char) (codepoint & 0x7F); + (*output_pointer)[0] = + (unsigned char)((codepoint | first_byte_mark) & 0xFF); + } + else { + (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F); } *output_pointer += utf8_length; return sequence_length; - fail: return 0; +fail: + return 0; } /* Parse the input text into an unescaped cinput, and populate item. */ -static cJSON_bool parse_string(cJSON * const item, - parse_buffer * const input_buffer) +static cJSON_bool +parse_string(cJSON *const item, parse_buffer *const input_buffer) { const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1; const unsigned char *input_end = buffer_at_offset(input_buffer) + 1; @@ -639,13 +690,15 @@ static cJSON_bool parse_string(cJSON * const item, /* calculate approximate size of the output (overestimate) */ size_t allocation_length = 0; size_t skipped_bytes = 0; - while (((size_t)(input_end - input_buffer->content) - < input_buffer->length) && (*input_end != '\"')) { + while ( + ((size_t)(input_end - input_buffer->content) < input_buffer->length) + && (*input_end != '\"')) { /* is escape sequence */ if (input_end[0] == '\\') { if ((size_t)(input_end + 1 - input_buffer->content) - >= input_buffer->length) { - /* prevent buffer overflow when last input character is a backslash */ + >= input_buffer->length) { + /* prevent buffer overflow when last input character is a + * backslash */ goto fail; } skipped_bytes++; @@ -653,17 +706,18 @@ static cJSON_bool parse_string(cJSON * const item, } input_end++; } - if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) - || (*input_end != '\"')) { + if (((size_t)(input_end - input_buffer->content) + >= input_buffer->length) + || (*input_end != '\"')) { goto fail; /* string ended unexpectedly */ } /* This is at most how much we need for the output */ allocation_length = (size_t)(input_end - buffer_at_offset(input_buffer)) - - skipped_bytes; - output = (unsigned char*) input_buffer->hooks.allocate( - allocation_length + sizeof("")); + - skipped_bytes; + output = (unsigned char *)input_buffer->hooks.allocate(allocation_length + + sizeof("")); if (output == NULL) { goto fail; /* allocation failure */ @@ -684,39 +738,39 @@ static cJSON_bool parse_string(cJSON * const item, } switch (input_pointer[1]) { - case 'b': - *output_pointer++ = '\b'; - break; - case 'f': - *output_pointer++ = '\f'; - break; - case 'n': - *output_pointer++ = '\n'; - break; - case 'r': - *output_pointer++ = '\r'; - break; - case 't': - *output_pointer++ = '\t'; - break; - case '\"': - case '\\': - case '/': - *output_pointer++ = input_pointer[1]; - break; - - /* UTF-16 literal */ - case 'u': - sequence_length = utf16_literal_to_utf8(input_pointer, - input_end, &output_pointer); - if (sequence_length == 0) { - /* failed to convert UTF16-literal to UTF-8 */ + case 'b': + *output_pointer++ = '\b'; + break; + case 'f': + *output_pointer++ = '\f'; + break; + case 'n': + *output_pointer++ = '\n'; + break; + case 'r': + *output_pointer++ = '\r'; + break; + case 't': + *output_pointer++ = '\t'; + break; + case '\"': + case '\\': + case '/': + *output_pointer++ = input_pointer[1]; + break; + + /* UTF-16 literal */ + case 'u': + sequence_length = utf16_literal_to_utf8( + input_pointer, input_end, &output_pointer); + if (sequence_length == 0) { + /* failed to convert UTF16-literal to UTF-8 */ + goto fail; + } + break; + + default: goto fail; - } - break; - - default: - goto fail; } input_pointer += sequence_length; } @@ -726,14 +780,15 @@ static cJSON_bool parse_string(cJSON * const item, *output_pointer = '\0'; item->type = cJSON_String; - item->valuestring = (char*) output; + item->valuestring = (char *)output; input_buffer->offset = (size_t)(input_end - input_buffer->content); input_buffer->offset++; return true; - fail: if (output != NULL) { +fail: + if (output != NULL) { input_buffer->hooks.deallocate(output); } @@ -745,8 +800,9 @@ static cJSON_bool parse_string(cJSON * const item, } /* Render the cstring provided to an escaped version that can be printed. */ -static cJSON_bool print_string_ptr(const unsigned char * const input, - printbuffer * const output_buffer) +static cJSON_bool +print_string_ptr(const unsigned char *const input, + printbuffer *const output_buffer) { const unsigned char *input_pointer = NULL; unsigned char *output = NULL, *output_end; @@ -765,7 +821,7 @@ static cJSON_bool print_string_ptr(const unsigned char * const input, if (output == NULL) { return false; } - strcpy((char*) output, "\"\""); + strcpy((char *)output, "\"\""); return true; } @@ -773,22 +829,22 @@ static cJSON_bool print_string_ptr(const unsigned char * const input, /* set "flag" to 1 if something needs to be escaped */ for (input_pointer = input; *input_pointer; input_pointer++) { switch (*input_pointer) { - case '\"': - case '\\': - case '\b': - case '\f': - case '\n': - case '\r': - case '\t': - /* one character escape sequence */ - escape_characters++; - break; - default: - if (*input_pointer < 32) { - /* UTF-16 escape sequence uXXXX */ - escape_characters += 5; - } - break; + case '\"': + case '\\': + case '\b': + case '\f': + case '\n': + case '\r': + case '\t': + /* one character escape sequence */ + escape_characters++; + break; + default: + if (*input_pointer < 32) { + /* UTF-16 escape sequence uXXXX */ + escape_characters += 5; + } + break; } } output_length = (size_t)(input_pointer - input) + escape_characters; @@ -813,42 +869,44 @@ static cJSON_bool print_string_ptr(const unsigned char * const input, output_pointer = output + 1; /* copy the string */ for (input_pointer = input; *input_pointer != '\0'; - (void) input_pointer++, output_pointer++) { + (void)input_pointer++, output_pointer++) { if ((*input_pointer > 31) && (*input_pointer != '\"') - && (*input_pointer != '\\')) { + && (*input_pointer != '\\')) { /* normal character, copy */ *output_pointer = *input_pointer; - } else { + } + else { /* character needs to be escaped */ *output_pointer++ = '\\'; switch (*input_pointer) { - case '\\': - *output_pointer = '\\'; - break; - case '\"': - *output_pointer = '\"'; - break; - case '\b': - *output_pointer = 'b'; - break; - case '\f': - *output_pointer = 'f'; - break; - case '\n': - *output_pointer = 'n'; - break; - case '\r': - *output_pointer = 'r'; - break; - case '\t': - *output_pointer = 't'; - break; - default: - /* escape and print as unicode codepoint */ - snprintf((char*) output_pointer, output_end - output_pointer, - "u%04x", *input_pointer); - output_pointer += 4; - break; + case '\\': + *output_pointer = '\\'; + break; + case '\"': + *output_pointer = '\"'; + break; + case '\b': + *output_pointer = 'b'; + break; + case '\f': + *output_pointer = 'f'; + break; + case '\n': + *output_pointer = 'n'; + break; + case '\r': + *output_pointer = 'r'; + break; + case '\t': + *output_pointer = 't'; + break; + default: + /* escape and print as unicode codepoint */ + snprintf((char *)output_pointer, + output_end - output_pointer, "u%04x", + *input_pointer); + output_pointer += 4; + break; } } } @@ -859,33 +917,36 @@ static cJSON_bool print_string_ptr(const unsigned char * const input, } /* Invoke print_string_ptr (which is useful) on an item. */ -static cJSON_bool print_string(const cJSON * const item, printbuffer * const p) +static cJSON_bool +print_string(const cJSON *const item, printbuffer *const p) { - return print_string_ptr((unsigned char*) item->valuestring, p); + return print_string_ptr((unsigned char *)item->valuestring, p); } /* Predeclare these prototypes. */ -static cJSON_bool parse_value(cJSON * const item, - parse_buffer * const input_buffer); -static cJSON_bool print_value(const cJSON * const item, - printbuffer * const output_buffer); -static cJSON_bool parse_array(cJSON * const item, - parse_buffer * const input_buffer); -static cJSON_bool print_array(const cJSON * const item, - printbuffer * const output_buffer); -static cJSON_bool parse_object(cJSON * const item, - parse_buffer * const input_buffer); -static cJSON_bool print_object(const cJSON * const item, - printbuffer * const output_buffer); +static cJSON_bool +parse_value(cJSON *const item, parse_buffer *const input_buffer); +static cJSON_bool +print_value(const cJSON *const item, printbuffer *const output_buffer); +static cJSON_bool +parse_array(cJSON *const item, parse_buffer *const input_buffer); +static cJSON_bool +print_array(const cJSON *const item, printbuffer *const output_buffer); +static cJSON_bool +parse_object(cJSON *const item, parse_buffer *const input_buffer); +static cJSON_bool +print_object(const cJSON *const item, printbuffer *const output_buffer); /* Utility to jump whitespace and cr/lf */ -static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer) +static parse_buffer * +buffer_skip_whitespace(parse_buffer *const buffer) { if ((buffer == NULL) || (buffer->content == NULL)) { return NULL; } - while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32)) { + while (can_access_at_index(buffer, 0) + && (buffer_at_offset(buffer)[0] <= 32)) { buffer->offset++; } @@ -897,16 +958,17 @@ static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer) } /* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */ -static parse_buffer *skip_utf8_bom(parse_buffer * const buffer) +static parse_buffer * +skip_utf8_bom(parse_buffer *const buffer) { if ((buffer == NULL) || (buffer->content == NULL) - || (buffer->offset != 0)) { + || (buffer->offset != 0)) { return NULL; } if (can_access_at_index(buffer, 4) - && (strncmp((const char*) buffer_at_offset(buffer), "\xEF\xBB\xBF", - 3) == 0)) { + && (strncmp((const char *)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) + == 0)) { buffer->offset += 3; } @@ -914,22 +976,23 @@ static parse_buffer *skip_utf8_bom(parse_buffer * const buffer) } /* Parse an object - create a new root, and populate. */ -CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated) +CJSON_PUBLIC(cJSON *) +cJSON_ParseWithOpts(const char *value, const char **return_parse_end, + cJSON_bool require_null_terminated) { - parse_buffer buffer = {0, 0, 0, 0, {0, 0, 0}}; + parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } }; cJSON *item = NULL; /* reset error position */ global_error.json = NULL; global_error.position = 0; - if (value == NULL) - { + if (value == NULL) { goto fail; } - buffer.content = (const unsigned char*)value; - buffer.length = strlen((const char*)value) + sizeof(""); + buffer.content = (const unsigned char *)value; + buffer.length = strlen((const char *)value) + sizeof(""); buffer.offset = 0; buffer.hooks = global_hooks; @@ -939,52 +1002,46 @@ CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return goto fail; } - if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer)))) - { + if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer)))) { /* parse failure. ep is set. */ goto fail; } - /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */ - if (require_null_terminated) - { + /* if we require null-terminated JSON without appended garbage, skip and + * then check for a null terminator */ + if (require_null_terminated) { buffer_skip_whitespace(&buffer); - if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0') - { + if ((buffer.offset >= buffer.length) + || buffer_at_offset(&buffer)[0] != '\0') { goto fail; } } - if (return_parse_end) - { - *return_parse_end = (const char*)buffer_at_offset(&buffer); + if (return_parse_end) { + *return_parse_end = (const char *)buffer_at_offset(&buffer); } return item; - fail: - if (item != NULL) - { +fail: + if (item != NULL) { cJSON_Delete(item); } - if (value != NULL) - { + if (value != NULL) { error local_error; - local_error.json = (const unsigned char*)value; + local_error.json = (const unsigned char *)value; local_error.position = 0; - if (buffer.offset < buffer.length) - { + if (buffer.offset < buffer.length) { local_error.position = buffer.offset; } - else if (buffer.length > 0) - { + else if (buffer.length > 0) { local_error.position = buffer.length - 1; } - if (return_parse_end != NULL) - { - *return_parse_end = (const char*)local_error.json + local_error.position; + if (return_parse_end != NULL) { + *return_parse_end = + (const char *)local_error.json + local_error.position; } global_error = local_error; @@ -1001,8 +1058,9 @@ CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value) #define cjson_min(a, b) ((a < b) ? a : b) -static unsigned char *print(const cJSON * const item, cJSON_bool format, - const internal_hooks * const hooks) +static unsigned char * +print(const cJSON *const item, cJSON_bool format, + const internal_hooks *const hooks) { static const size_t default_buffer_size = 256; printbuffer buffer[1]; @@ -1011,7 +1069,7 @@ static unsigned char *print(const cJSON * const item, cJSON_bool format, memset(buffer, 0, sizeof(buffer)); /* create buffer */ - buffer->buffer = (unsigned char*) hooks->allocate(default_buffer_size); + buffer->buffer = (unsigned char *)hooks->allocate(default_buffer_size); buffer->length = default_buffer_size; buffer->format = format; buffer->hooks = *hooks; @@ -1027,20 +1085,21 @@ static unsigned char *print(const cJSON * const item, cJSON_bool format, /* check if reallocate is available */ if (hooks->reallocate != NULL) { - printed = (unsigned char*) hooks->reallocate(buffer->buffer, - buffer->offset + 1); + printed = (unsigned char *)hooks->reallocate(buffer->buffer, + buffer->offset + 1); if (printed == NULL) { goto fail; } buffer->buffer = NULL; - } else /* otherwise copy the JSON over to a new buffer */ + } + else /* otherwise copy the JSON over to a new buffer */ { - printed = (unsigned char*) hooks->allocate(buffer->offset + 1); + printed = (unsigned char *)hooks->allocate(buffer->offset + 1); if (printed == NULL) { goto fail; } memcpy(printed, buffer->buffer, - cjson_min(buffer->length, buffer->offset + 1)); + cjson_min(buffer->length, buffer->offset + 1)); printed[buffer->offset] = '\0'; /* just to be sure */ /* free the buffer */ @@ -1049,7 +1108,8 @@ static unsigned char *print(const cJSON * const item, cJSON_bool format, return printed; - fail: if (buffer->buffer != NULL) { +fail: + if (buffer->buffer != NULL) { hooks->deallocate(buffer->buffer); } @@ -1063,26 +1123,25 @@ static unsigned char *print(const cJSON * const item, cJSON_bool format, /* Render a cJSON item/entity/structure to text. */ CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item) { - return (char*)print(item, true, &global_hooks); + return (char *)print(item, true, &global_hooks); } CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item) { - return (char*)print(item, false, &global_hooks); + return (char *)print(item, false, &global_hooks); } -CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt) +CJSON_PUBLIC(char *) +cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt) { - printbuffer p = {0, 0, 0, 0, 0, 0, {0, 0, 0}}; + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; - if (prebuffer < 0) - { + if (prebuffer < 0) { return NULL; } - p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer); - if (!p.buffer) - { + p.buffer = (unsigned char *)global_hooks.allocate((size_t)prebuffer); + if (!p.buffer) { return NULL; } @@ -1092,17 +1151,17 @@ CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON p.format = fmt; p.hooks = global_hooks; - if (!print_value(item, &p)) - { + if (!print_value(item, &p)) { global_hooks.deallocate(p.buffer); return NULL; } - return (char*)p.buffer; + return (char *)p.buffer; } -CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buf, - const int len, const cJSON_bool fmt) +CJSON_PUBLIC(cJSON_bool) +cJSON_PrintPreallocated(cJSON *item, char *buf, const int len, + const cJSON_bool fmt) { printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; @@ -1110,8 +1169,8 @@ CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buf, return false; } - p.buffer = (unsigned char*) buf; - p.length = (size_t) len; + p.buffer = (unsigned char *)buf; + p.length = (size_t)len; p.offset = 0; p.noalloc = true; p.format = fmt; @@ -1121,8 +1180,8 @@ CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buf, } /* Parser core - when encountering text, process appropriately. */ -static cJSON_bool parse_value(cJSON * const item, - parse_buffer * const input_buffer) +static cJSON_bool +parse_value(cJSON *const item, parse_buffer *const input_buffer) { if ((input_buffer == NULL) || (input_buffer->content == NULL)) { return false; /* no input */ @@ -1131,24 +1190,24 @@ static cJSON_bool parse_value(cJSON * const item, /* parse the different types of values */ /* null */ if (can_read(input_buffer, 4) - && (strncmp((const char*) buffer_at_offset(input_buffer), "null", 4) - == 0)) { + && (strncmp((const char *)buffer_at_offset(input_buffer), "null", 4) + == 0)) { item->type = cJSON_NULL; input_buffer->offset += 4; return true; } /* false */ if (can_read(input_buffer, 5) - && (strncmp((const char*) buffer_at_offset(input_buffer), "false", - 5) == 0)) { + && (strncmp((const char *)buffer_at_offset(input_buffer), "false", 5) + == 0)) { item->type = cJSON_False; input_buffer->offset += 5; return true; } /* true */ if (can_read(input_buffer, 4) - && (strncmp((const char*) buffer_at_offset(input_buffer), "true", 4) - == 0)) { + && (strncmp((const char *)buffer_at_offset(input_buffer), "true", 4) + == 0)) { item->type = cJSON_True; item->valueint = 1; input_buffer->offset += 4; @@ -1156,24 +1215,24 @@ static cJSON_bool parse_value(cJSON * const item, } /* string */ if (can_access_at_index(input_buffer, 0) - && (buffer_at_offset(input_buffer)[0] == '\"')) { + && (buffer_at_offset(input_buffer)[0] == '\"')) { return parse_string(item, input_buffer); } /* number */ if (can_access_at_index(input_buffer, 0) - && ((buffer_at_offset(input_buffer)[0] == '-') - || ((buffer_at_offset(input_buffer)[0] >= '0') - && (buffer_at_offset(input_buffer)[0] <= '9')))) { + && ((buffer_at_offset(input_buffer)[0] == '-') + || ((buffer_at_offset(input_buffer)[0] >= '0') + && (buffer_at_offset(input_buffer)[0] <= '9')))) { return parse_number(item, input_buffer); } /* array */ if (can_access_at_index(input_buffer, 0) - && (buffer_at_offset(input_buffer)[0] == '[')) { + && (buffer_at_offset(input_buffer)[0] == '[')) { return parse_array(item, input_buffer); } /* object */ if (can_access_at_index(input_buffer, 0) - && (buffer_at_offset(input_buffer)[0] == '{')) { + && (buffer_at_offset(input_buffer)[0] == '{')) { return parse_object(item, input_buffer); } @@ -1181,8 +1240,8 @@ static cJSON_bool parse_value(cJSON * const item, } /* Render a value to text. */ -static cJSON_bool print_value(const cJSON * const item, - printbuffer * const output_buffer) +static cJSON_bool +print_value(const cJSON *const item, printbuffer *const output_buffer) { unsigned char *output = NULL; @@ -1191,65 +1250,66 @@ static cJSON_bool print_value(const cJSON * const item, } switch ((item->type) & 0xFF) { - case cJSON_NULL: - output = ensure(output_buffer, 5); - if (output == NULL) { - return false; - } - strcpy((char*) output, "null"); - return true; + case cJSON_NULL: + output = ensure(output_buffer, 5); + if (output == NULL) { + return false; + } + strcpy((char *)output, "null"); + return true; - case cJSON_False: - output = ensure(output_buffer, 6); - if (output == NULL) { - return false; - } - strcpy((char*) output, "false"); - return true; + case cJSON_False: + output = ensure(output_buffer, 6); + if (output == NULL) { + return false; + } + strcpy((char *)output, "false"); + return true; - case cJSON_True: - output = ensure(output_buffer, 5); - if (output == NULL) { - return false; - } - strcpy((char*) output, "true"); - return true; + case cJSON_True: + output = ensure(output_buffer, 5); + if (output == NULL) { + return false; + } + strcpy((char *)output, "true"); + return true; - case cJSON_Number: - return print_number(item, output_buffer); + case cJSON_Number: + return print_number(item, output_buffer); - case cJSON_Raw: { - size_t raw_length = 0; - if (item->valuestring == NULL) { - return false; - } + case cJSON_Raw: + { + size_t raw_length = 0; + if (item->valuestring == NULL) { + return false; + } - raw_length = strlen(item->valuestring) + sizeof(""); - output = ensure(output_buffer, raw_length); - if (output == NULL) { - return false; + raw_length = strlen(item->valuestring) + sizeof(""); + output = ensure(output_buffer, raw_length); + if (output == NULL) { + return false; + } + memcpy(output, item->valuestring, raw_length); + return true; } - memcpy(output, item->valuestring, raw_length); - return true; - } - case cJSON_String: - return print_string(item, output_buffer); + case cJSON_String: + return print_string(item, output_buffer); - case cJSON_Array: - return print_array(item, output_buffer); + case cJSON_Array: + return print_array(item, output_buffer); - case cJSON_Object: - return print_object(item, output_buffer); + case cJSON_Object: + return print_object(item, output_buffer); - default: - return false; + default: + return false; } } /* Build an array from input text. */ -static cJSON_bool parse_array(cJSON * const item, - parse_buffer * const input_buffer) +static cJSON_bool +parse_array(cJSON *const item, parse_buffer *const input_buffer) { cJSON *head = NULL; /* head of the linked list */ cJSON *current_item = NULL; @@ -1267,7 +1327,7 @@ static cJSON_bool parse_array(cJSON * const item, input_buffer->offset++; buffer_skip_whitespace(input_buffer); if (can_access_at_index(input_buffer, 0) - && (buffer_at_offset(input_buffer)[0] == ']')) { + && (buffer_at_offset(input_buffer)[0] == ']')) { /* empty array */ goto success; } @@ -1293,7 +1353,8 @@ static cJSON_bool parse_array(cJSON * const item, if (head == NULL) { /* start the linked list */ current_item = head = new_item; - } else { + } + else { /* add to the end and advance */ current_item->next = new_item; new_item->prev = current_item; @@ -1309,15 +1370,16 @@ static cJSON_bool parse_array(cJSON * const item, } buffer_skip_whitespace(input_buffer); } while (can_access_at_index(input_buffer, 0) - && (buffer_at_offset(input_buffer)[0] == ',')); + && (buffer_at_offset(input_buffer)[0] == ',')); if (cannot_access_at_index(input_buffer, 0) - || buffer_at_offset(input_buffer)[0] != ']') { + || buffer_at_offset(input_buffer)[0] != ']') { goto fail; /* expected end of array */ } - success: input_buffer->depth--; +success: + input_buffer->depth--; item->type = cJSON_Array; item->child = head; @@ -1326,7 +1388,8 @@ static cJSON_bool parse_array(cJSON * const item, return true; - fail: if (head != NULL) { +fail: + if (head != NULL) { cJSON_Delete(head); } @@ -1334,8 +1397,8 @@ static cJSON_bool parse_array(cJSON * const item, } /* Render an array to text */ -static cJSON_bool print_array(const cJSON * const item, - printbuffer * const output_buffer) +static cJSON_bool +print_array(const cJSON *const item, printbuffer *const output_buffer) { unsigned char *output_pointer = NULL; size_t length = 0; @@ -1389,8 +1452,8 @@ static cJSON_bool print_array(const cJSON * const item, } /* Build an object from the text. */ -static cJSON_bool parse_object(cJSON * const item, - parse_buffer * const input_buffer) +static cJSON_bool +parse_object(cJSON *const item, parse_buffer *const input_buffer) { cJSON *head = NULL; /* linked list head */ cJSON *current_item = NULL; @@ -1401,7 +1464,7 @@ static cJSON_bool parse_object(cJSON * const item, input_buffer->depth++; if (cannot_access_at_index(input_buffer, 0) - || (buffer_at_offset(input_buffer)[0] != '{')) { + || (buffer_at_offset(input_buffer)[0] != '{')) { goto fail; /* not an object */ } @@ -1409,7 +1472,7 @@ static cJSON_bool parse_object(cJSON * const item, input_buffer->offset++; buffer_skip_whitespace(input_buffer); if (can_access_at_index(input_buffer, 0) - && (buffer_at_offset(input_buffer)[0] == '}')) { + && (buffer_at_offset(input_buffer)[0] == '}')) { goto success; /* empty object */ } @@ -1435,7 +1498,8 @@ static cJSON_bool parse_object(cJSON * const item, if (head == NULL) { /* start the linked list */ current_item = head = new_item; - } else { + } + else { /* add to the end and advance */ current_item->next = new_item; new_item->prev = current_item; @@ -1456,7 +1520,7 @@ static cJSON_bool parse_object(cJSON * const item, current_item->valuestring = NULL; if (cannot_access_at_index(input_buffer, 0) - || (buffer_at_offset(input_buffer)[0] != ':')) { + || (buffer_at_offset(input_buffer)[0] != ':')) { goto fail; /* invalid object */ } @@ -1470,15 +1534,16 @@ static cJSON_bool parse_object(cJSON * const item, } buffer_skip_whitespace(input_buffer); } while (can_access_at_index(input_buffer, 0) - && (buffer_at_offset(input_buffer)[0] == ',')); + && (buffer_at_offset(input_buffer)[0] == ',')); if (cannot_access_at_index(input_buffer, 0) - || (buffer_at_offset(input_buffer)[0] != '}')) { + || (buffer_at_offset(input_buffer)[0] != '}')) { goto fail; /* expected end of object */ } - success: input_buffer->depth--; +success: + input_buffer->depth--; item->type = cJSON_Object; item->child = head; @@ -1486,7 +1551,8 @@ static cJSON_bool parse_object(cJSON * const item, input_buffer->offset++; return true; - fail: if (head != NULL) { +fail: + if (head != NULL) { cJSON_Delete(head); } @@ -1494,8 +1560,8 @@ static cJSON_bool parse_object(cJSON * const item, } /* Render an object to text. */ -static cJSON_bool print_object(const cJSON * const item, - printbuffer * const output_buffer) +static cJSON_bool +print_object(const cJSON *const item, printbuffer *const output_buffer) { unsigned char *output_pointer = NULL; size_t length = 0; @@ -1533,8 +1599,8 @@ static cJSON_bool print_object(const cJSON * const item, } /* print key */ - if (!print_string_ptr((unsigned char*) current_item->string, - output_buffer)) { + if (!print_string_ptr((unsigned char *)current_item->string, + output_buffer)) { return false; } update_offset(output_buffer); @@ -1558,7 +1624,7 @@ static cJSON_bool print_object(const cJSON * const item, /* print comma if not last */ length = ((size_t)(output_buffer->format ? 1 : 0) - + (size_t)(current_item->next ? 1 : 0)); + + (size_t)(current_item->next ? 1 : 0)); output_pointer = ensure(output_buffer, length + 1); if (output_pointer == NULL) { return false; @@ -1576,8 +1642,8 @@ static cJSON_bool print_object(const cJSON * const item, current_item = current_item->next; } - output_pointer = ensure(output_buffer, - output_buffer->format ? (output_buffer->depth + 1) : 2); + output_pointer = ensure( + output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2); if (output_pointer == NULL) { return false; } @@ -1613,10 +1679,11 @@ CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array) /* FIXME: Can overflow here. Cannot be fixed without breaking the API */ - return (int) size; + return (int)size; } -static cJSON* get_array_item(const cJSON *array, size_t index) +static cJSON * +get_array_item(const cJSON *array, size_t index) { cJSON *current_child = NULL; @@ -1635,16 +1702,16 @@ static cJSON* get_array_item(const cJSON *array, size_t index) CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index) { - if (index < 0) - { + if (index < 0) { return NULL; } return get_array_item(array, (size_t)index); } -static cJSON *get_object_item(const cJSON * const object, - const char * const name, const cJSON_bool case_sensitive) +static cJSON * +get_object_item(const cJSON *const object, const char *const name, + const cJSON_bool case_sensitive) { cJSON *current_element = NULL; @@ -1655,13 +1722,16 @@ static cJSON *get_object_item(const cJSON * const object, current_element = object->child; if (case_sensitive) { while ((current_element != NULL) && (current_element->string != NULL) - && (strcmp(name, current_element->string) != 0)) { + && (strcmp(name, current_element->string) != 0)) { current_element = current_element->next; } - } else { + } + else { while ((current_element != NULL) - && (case_insensitive_strcmp((const unsigned char*) name, - (const unsigned char*) (current_element->string)) != 0)) { + && (case_insensitive_strcmp( + (const unsigned char *)name, + (const unsigned char *)(current_element->string)) + != 0)) { current_element = current_element->next; } } @@ -1673,32 +1743,36 @@ static cJSON *get_object_item(const cJSON * const object, return current_element; } -CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string) +CJSON_PUBLIC(cJSON *) +cJSON_GetObjectItem(const cJSON *const object, const char *const string) { return get_object_item(object, string, false); } -CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string) +CJSON_PUBLIC(cJSON *) +cJSON_GetObjectItemCaseSensitive(const cJSON *const object, + const char *const string) { return get_object_item(object, string, true); } -CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, - const char *string) +CJSON_PUBLIC(cJSON_bool) +cJSON_HasObjectItem(const cJSON *object, const char *string) { return cJSON_GetObjectItem(object, string) ? 1 : 0; } /* Utility for array list handling. */ -static void suffix_object(cJSON *prev, cJSON *item) +static void +suffix_object(cJSON *prev, cJSON *item) { prev->next = item; item->prev = prev; } /* Utility for handling references. */ -static cJSON *create_reference(const cJSON *item, - const internal_hooks * const hooks) +static cJSON * +create_reference(const cJSON *item, const internal_hooks *const hooks) { cJSON *reference = NULL; if (item == NULL) { @@ -1717,7 +1791,8 @@ static cJSON *create_reference(const cJSON *item, return reference; } -static cJSON_bool add_item_to_array(cJSON *array, cJSON *item) +static cJSON_bool +add_item_to_array(cJSON *array, cJSON *item) { cJSON *child = NULL; @@ -1730,7 +1805,8 @@ static cJSON_bool add_item_to_array(cJSON *array, cJSON *item) if (child == NULL) { /* list is empty, start new one */ array->child = item; - } else { + } + else { /* append to the end */ while (child->next) { child = child->next; @@ -1747,24 +1823,30 @@ CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item) add_item_to_array(array, item); } -#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) +#if defined(__clang__) \ + || (defined(__GNUC__) \ + && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) #pragma GCC diagnostic push #endif #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wcast-qual" #endif /* helper function to cast away const */ -static void* cast_away_const(const void* string) +static void * +cast_away_const(const void *string) { - return (void*) string; + return (void *)string; } -#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) +#if defined(__clang__) \ + || (defined(__GNUC__) \ + && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) #pragma GCC diagnostic pop #endif -static cJSON_bool add_item_to_object(cJSON * const object, - const char * const string, cJSON * const item, - const internal_hooks * const hooks, const cJSON_bool constant_key) +static cJSON_bool +add_item_to_object(cJSON *const object, const char *const string, + cJSON *const item, const internal_hooks *const hooks, + const cJSON_bool constant_key) { char *new_key = NULL; int new_type = cJSON_Invalid; @@ -1774,10 +1856,11 @@ static cJSON_bool add_item_to_object(cJSON * const object, } if (constant_key) { - new_key = (char*) cast_away_const(string); + new_key = (char *)cast_away_const(string); new_type = item->type | cJSON_StringIsConst; - } else { - new_key = (char*) cJSON_strdup((const unsigned char*) string, hooks); + } + else { + new_key = (char *)cJSON_strdup((const unsigned char *)string, hooks); if (new_key == NULL) { return false; } @@ -1795,15 +1878,15 @@ static cJSON_bool add_item_to_object(cJSON * const object, return add_item_to_array(object, item); } -CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, - cJSON *item) +CJSON_PUBLIC(void) +cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item) { add_item_to_object(object, string, item, &global_hooks, false); } /* Add an item to an object with constant string as key */ -CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, - cJSON *item) +CJSON_PUBLIC(void) +cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item) { add_item_to_object(object, string, item, &global_hooks, true); } @@ -1817,22 +1900,22 @@ CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) add_item_to_array(array, create_reference(item, &global_hooks)); } -CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, - const char *string, cJSON *item) +CJSON_PUBLIC(void) +cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item) { if ((object == NULL) || (string == NULL)) { return; } add_item_to_object(object, string, create_reference(item, &global_hooks), - &global_hooks, false); + &global_hooks, false); } -CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name) +CJSON_PUBLIC(cJSON *) +cJSON_AddNullToObject(cJSON *const object, const char *const name) { cJSON *null = cJSON_CreateNull(); - if (add_item_to_object(object, name, null, &global_hooks, false)) - { + if (add_item_to_object(object, name, null, &global_hooks, false)) { return null; } @@ -1840,11 +1923,11 @@ CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * co return NULL; } -CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name) +CJSON_PUBLIC(cJSON *) +cJSON_AddTrueToObject(cJSON *const object, const char *const name) { cJSON *true_item = cJSON_CreateTrue(); - if (add_item_to_object(object, name, true_item, &global_hooks, false)) - { + if (add_item_to_object(object, name, true_item, &global_hooks, false)) { return true_item; } @@ -1852,11 +1935,11 @@ CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * co return NULL; } -CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name) +CJSON_PUBLIC(cJSON *) +cJSON_AddFalseToObject(cJSON *const object, const char *const name) { cJSON *false_item = cJSON_CreateFalse(); - if (add_item_to_object(object, name, false_item, &global_hooks, false)) - { + if (add_item_to_object(object, name, false_item, &global_hooks, false)) { return false_item; } @@ -1864,11 +1947,12 @@ CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * c return NULL; } -CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean) +CJSON_PUBLIC(cJSON *) +cJSON_AddBoolToObject(cJSON *const object, const char *const name, + const cJSON_bool boolean) { cJSON *bool_item = cJSON_CreateBool(boolean); - if (add_item_to_object(object, name, bool_item, &global_hooks, false)) - { + if (add_item_to_object(object, name, bool_item, &global_hooks, false)) { return bool_item; } @@ -1876,11 +1960,12 @@ CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * co return NULL; } -CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number) +CJSON_PUBLIC(cJSON *) +cJSON_AddNumberToObject(cJSON *const object, const char *const name, + const double number) { cJSON *number_item = cJSON_CreateNumber(number); - if (add_item_to_object(object, name, number_item, &global_hooks, false)) - { + if (add_item_to_object(object, name, number_item, &global_hooks, false)) { return number_item; } @@ -1888,11 +1973,12 @@ CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * return NULL; } -CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string) +CJSON_PUBLIC(cJSON *) +cJSON_AddStringToObject(cJSON *const object, const char *const name, + const char *const string) { cJSON *string_item = cJSON_CreateString(string); - if (add_item_to_object(object, name, string_item, &global_hooks, false)) - { + if (add_item_to_object(object, name, string_item, &global_hooks, false)) { return string_item; } @@ -1900,11 +1986,12 @@ CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * return NULL; } -CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw) +CJSON_PUBLIC(cJSON *) +cJSON_AddRawToObject(cJSON *const object, const char *const name, + const char *const raw) { cJSON *raw_item = cJSON_CreateRaw(raw); - if (add_item_to_object(object, name, raw_item, &global_hooks, false)) - { + if (add_item_to_object(object, name, raw_item, &global_hooks, false)) { return raw_item; } @@ -1912,11 +1999,11 @@ CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * con return NULL; } -CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name) +CJSON_PUBLIC(cJSON *) +cJSON_AddObjectToObject(cJSON *const object, const char *const name) { cJSON *object_item = cJSON_CreateObject(); - if (add_item_to_object(object, name, object_item, &global_hooks, false)) - { + if (add_item_to_object(object, name, object_item, &global_hooks, false)) { return object_item; } @@ -1924,11 +2011,11 @@ CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * return NULL; } -CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name) +CJSON_PUBLIC(cJSON *) +cJSON_AddArrayToObject(cJSON *const object, const char *const name) { cJSON *array = cJSON_CreateArray(); - if (add_item_to_object(object, name, array, &global_hooks, false)) - { + if (add_item_to_object(object, name, array, &global_hooks, false)) { return array; } @@ -1936,26 +2023,23 @@ CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * c return NULL; } -CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item) +CJSON_PUBLIC(cJSON *) +cJSON_DetachItemViaPointer(cJSON *parent, cJSON *const item) { - if ((parent == NULL) || (item == NULL)) - { + if ((parent == NULL) || (item == NULL)) { return NULL; } - if (item->prev != NULL) - { + if (item->prev != NULL) { /* not the first element */ item->prev->next = item->next; } - if (item->next != NULL) - { + if (item->next != NULL) { /* not the last element */ item->next->prev = item->prev; } - if (item == parent->child) - { + if (item == parent->child) { /* first element */ parent->child = item->next; } @@ -1968,12 +2052,12 @@ CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const it CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which) { - if (which < 0) - { + if (which < 0) { return NULL; } - return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which)); + return cJSON_DetachItemViaPointer(array, + get_array_item(array, (size_t)which)); } CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which) @@ -1981,14 +2065,16 @@ CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which) cJSON_Delete(cJSON_DetachItemFromArray(array, which)); } -CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string) +CJSON_PUBLIC(cJSON *) +cJSON_DetachItemFromObject(cJSON *object, const char *string) { cJSON *to_detach = cJSON_GetObjectItem(object, string); return cJSON_DetachItemViaPointer(object, to_detach); } -CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string) +CJSON_PUBLIC(cJSON *) +cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string) { cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string); @@ -2000,15 +2086,15 @@ CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string) cJSON_Delete(cJSON_DetachItemFromObject(object, string)); } -CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, - const char *string) +CJSON_PUBLIC(void) +cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string) { cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string)); } /* Replace array/object items with new ones. */ -CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, - cJSON *newitem) +CJSON_PUBLIC(void) +cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem) { cJSON *after_inserted = NULL; @@ -2016,7 +2102,7 @@ CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, return; } - after_inserted = get_array_item(array, (size_t) which); + after_inserted = get_array_item(array, (size_t)which); if (after_inserted == NULL) { add_item_to_array(array, newitem); return; @@ -2027,13 +2113,15 @@ CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, after_inserted->prev = newitem; if (after_inserted == array->child) { array->child = newitem; - } else { + } + else { newitem->prev->next = newitem; } } -CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, - cJSON * const item, cJSON * replacement) +CJSON_PUBLIC(cJSON_bool) +cJSON_ReplaceItemViaPointer(cJSON *const parent, cJSON *const item, + cJSON *replacement) { if ((parent == NULL) || (replacement == NULL) || (item == NULL)) { return false; @@ -2063,19 +2151,20 @@ CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, return true; } -CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, - cJSON *newitem) +CJSON_PUBLIC(void) +cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem) { if (which < 0) { return; } - cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t) which), - newitem); + cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), + newitem); } -static cJSON_bool replace_item_in_object(cJSON *object, const char *string, - cJSON *replacement, cJSON_bool case_sensitive) +static cJSON_bool +replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, + cJSON_bool case_sensitive) { if ((replacement == NULL) || (string == NULL)) { return false; @@ -2083,27 +2172,28 @@ static cJSON_bool replace_item_in_object(cJSON *object, const char *string, /* replace the name in the replacement */ if (!(replacement->type & cJSON_StringIsConst) - && (replacement->string != NULL)) { + && (replacement->string != NULL)) { cJSON_free(replacement->string); } - replacement->string = (char*) cJSON_strdup((const unsigned char*) string, - &global_hooks); + replacement->string = + (char *)cJSON_strdup((const unsigned char *)string, &global_hooks); replacement->type &= ~cJSON_StringIsConst; - cJSON_ReplaceItemViaPointer(object, - get_object_item(object, string, case_sensitive), replacement); + cJSON_ReplaceItemViaPointer( + object, get_object_item(object, string, case_sensitive), replacement); return true; } -CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object, const char *string, - cJSON *newitem) +CJSON_PUBLIC(void) +cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem) { replace_item_in_object(object, string, newitem, false); } -CJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, - const char *string, cJSON *newitem) +CJSON_PUBLIC(void) +cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, + cJSON *newitem) { replace_item_in_object(object, string, newitem, true); } @@ -2112,8 +2202,7 @@ CJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void) { cJSON *item = cJSON_New_Item(&global_hooks); - if(item) - { + if (item) { item->type = cJSON_NULL; } @@ -2123,8 +2212,7 @@ CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void) CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void) { cJSON *item = cJSON_New_Item(&global_hooks); - if(item) - { + if (item) { item->type = cJSON_True; } @@ -2134,8 +2222,7 @@ CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void) CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void) { cJSON *item = cJSON_New_Item(&global_hooks); - if(item) - { + if (item) { item->type = cJSON_False; } @@ -2145,8 +2232,7 @@ CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void) CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool b) { cJSON *item = cJSON_New_Item(&global_hooks); - if(item) - { + if (item) { item->type = b ? cJSON_True : cJSON_False; } @@ -2156,22 +2242,18 @@ CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool b) CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num) { cJSON *item = cJSON_New_Item(&global_hooks); - if(item) - { + if (item) { item->type = cJSON_Number; item->valuedouble = num; /* use saturation in case of overflow */ - if (num >= INT_MAX) - { + if (num >= INT_MAX) { item->valueint = INT_MAX; } - else if (num <= (double)INT_MIN) - { + else if (num <= (double)INT_MIN) { item->valueint = INT_MIN; } - else - { + else { item->valueint = (int)num; } } @@ -2182,12 +2264,11 @@ CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num) CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string) { cJSON *item = cJSON_New_Item(&global_hooks); - if(item) - { + if (item) { item->type = cJSON_String; - item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); - if(!item->valuestring) - { + item->valuestring = + (char *)cJSON_strdup((const unsigned char *)string, &global_hooks); + if (!item->valuestring) { cJSON_Delete(item); return NULL; } @@ -2199,10 +2280,9 @@ CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string) CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string) { cJSON *item = cJSON_New_Item(&global_hooks); - if (item != NULL) - { + if (item != NULL) { item->type = cJSON_String | cJSON_IsReference; - item->valuestring = (char*)cast_away_const(string); + item->valuestring = (char *)cast_away_const(string); } return item; @@ -2213,17 +2293,18 @@ CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child) cJSON *item = cJSON_New_Item(&global_hooks); if (item != NULL) { item->type = cJSON_Object | cJSON_IsReference; - item->child = (cJSON*)cast_away_const(child); + item->child = (cJSON *)cast_away_const(child); } return item; } -CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) { +CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) +{ cJSON *item = cJSON_New_Item(&global_hooks); if (item != NULL) { item->type = cJSON_Array | cJSON_IsReference; - item->child = (cJSON*)cast_away_const(child); + item->child = (cJSON *)cast_away_const(child); } return item; @@ -2232,12 +2313,11 @@ CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) { CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw) { cJSON *item = cJSON_New_Item(&global_hooks); - if(item) - { + if (item) { item->type = cJSON_Raw; - item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks); - if(!item->valuestring) - { + item->valuestring = + (char *)cJSON_strdup((const unsigned char *)raw, &global_hooks); + if (!item->valuestring) { cJSON_Delete(item); return NULL; } @@ -2249,9 +2329,8 @@ CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw) CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void) { cJSON *item = cJSON_New_Item(&global_hooks); - if(item) - { - item->type=cJSON_Array; + if (item) { + item->type = cJSON_Array; } return item; @@ -2260,8 +2339,7 @@ CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void) CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void) { cJSON *item = cJSON_New_Item(&global_hooks); - if (item) - { + if (item) { item->type = cJSON_Object; } @@ -2276,26 +2354,21 @@ CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count) cJSON *p = NULL; cJSON *a = NULL; - if ((count < 0) || (numbers == NULL)) - { + if ((count < 0) || (numbers == NULL)) { return NULL; } a = cJSON_CreateArray(); - for(i = 0; a && (i < (size_t)count); i++) - { + for (i = 0; a && (i < (size_t)count); i++) { n = cJSON_CreateNumber(numbers[i]); - if (!n) - { + if (!n) { cJSON_Delete(a); return NULL; } - if(!i) - { + if (!i) { a->child = n; } - else - { + else { suffix_object(p, n); } p = n; @@ -2311,27 +2384,22 @@ CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count) cJSON *p = NULL; cJSON *a = NULL; - if ((count < 0) || (numbers == NULL)) - { + if ((count < 0) || (numbers == NULL)) { return NULL; } a = cJSON_CreateArray(); - for(i = 0; a && (i < (size_t)count); i++) - { + for (i = 0; a && (i < (size_t)count); i++) { n = cJSON_CreateNumber((double)numbers[i]); - if(!n) - { + if (!n) { cJSON_Delete(a); return NULL; } - if(!i) - { + if (!i) { a->child = n; } - else - { + else { suffix_object(p, n); } p = n; @@ -2347,27 +2415,22 @@ CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count) cJSON *p = NULL; cJSON *a = NULL; - if ((count < 0) || (numbers == NULL)) - { + if ((count < 0) || (numbers == NULL)) { return NULL; } a = cJSON_CreateArray(); - for(i = 0;a && (i < (size_t)count); i++) - { + for (i = 0; a && (i < (size_t)count); i++) { n = cJSON_CreateNumber(numbers[i]); - if(!n) - { + if (!n) { cJSON_Delete(a); return NULL; } - if(!i) - { + if (!i) { a->child = n; } - else - { + else { suffix_object(p, n); } p = n; @@ -2383,28 +2446,23 @@ CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char **strings, int count) cJSON *p = NULL; cJSON *a = NULL; - if ((count < 0) || (strings == NULL)) - { + if ((count < 0) || (strings == NULL)) { return NULL; } a = cJSON_CreateArray(); - for (i = 0; a && (i < (size_t)count); i++) - { + for (i = 0; a && (i < (size_t)count); i++) { n = cJSON_CreateString(strings[i]); - if(!n) - { + if (!n) { cJSON_Delete(a); return NULL; } - if(!i) - { + if (!i) { a->child = n; } - else - { - suffix_object(p,n); + else { + suffix_object(p, n); } p = n; } @@ -2421,59 +2479,55 @@ CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse) cJSON *newchild = NULL; /* Bail on bad ptr */ - if (!item) - { + if (!item) { goto fail; } /* Create new item */ newitem = cJSON_New_Item(&global_hooks); - if (!newitem) - { + if (!newitem) { goto fail; } /* Copy over all vars */ newitem->type = item->type & (~cJSON_IsReference); newitem->valueint = item->valueint; newitem->valuedouble = item->valuedouble; - if (item->valuestring) - { - newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks); - if (!newitem->valuestring) - { + if (item->valuestring) { + newitem->valuestring = (char *)cJSON_strdup( + (unsigned char *)item->valuestring, &global_hooks); + if (!newitem->valuestring) { goto fail; } } - if (item->string) - { - newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks); - if (!newitem->string) - { + if (item->string) { + newitem->string = (item->type & cJSON_StringIsConst) + ? item->string + : (char *)cJSON_strdup( + (unsigned char *)item->string, &global_hooks); + if (!newitem->string) { goto fail; } } /* If non-recursive, then we're done! */ - if (!recurse) - { + if (!recurse) { return newitem; } /* Walk the ->next chain for the child. */ child = item->child; - while (child != NULL) - { - newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */ - if (!newchild) - { + while (child != NULL) { + newchild = cJSON_Duplicate( + child, + true); /* Duplicate (with recurse) each item in the ->next chain */ + if (!newchild) { goto fail; } - if (next != NULL) - { - /* If newitem->child already set, then crosswire ->prev and ->next and move on */ + if (next != NULL) { + /* If newitem->child already set, then crosswire ->prev and ->next + * and move on */ next->next = newchild; newchild->prev = next; next = newchild; } - else - { + else { /* Set newitem->child and move to it */ newitem->child = newchild; next = newchild; @@ -2483,9 +2537,8 @@ CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse) return newitem; - fail: - if (newitem != NULL) - { +fail: + if (newitem != NULL) { cJSON_Delete(newitem); } @@ -2494,7 +2547,7 @@ CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse) CJSON_PUBLIC(void) cJSON_Minify(char *json) { - unsigned char *into = (unsigned char*) json; + unsigned char *into = (unsigned char *)json; if (json == NULL) { return; @@ -2503,37 +2556,44 @@ CJSON_PUBLIC(void) cJSON_Minify(char *json) while (*json) { if (*json == ' ') { json++; - } else if (*json == '\t') { + } + else if (*json == '\t') { /* Whitespace characters. */ json++; - } else if (*json == '\r') { + } + else if (*json == '\r') { json++; - } else if (*json == '\n') { + } + else if (*json == '\n') { json++; - } else if ((*json == '/') && (json[1] == '/')) { + } + else if ((*json == '/') && (json[1] == '/')) { /* double-slash comments, to end of line. */ while (*json && (*json != '\n')) { json++; } - } else if ((*json == '/') && (json[1] == '*')) { + } + else if ((*json == '/') && (json[1] == '*')) { /* multiline comments. */ while (*json && !((*json == '*') && (json[1] == '/'))) { json++; } json += 2; - } else if (*json == '\"') { + } + else if (*json == '\"') { /* string literals, which are \" sensitive. */ - *into++ = (unsigned char) *json++; + *into++ = (unsigned char)*json++; while (*json && (*json != '\"')) { if (*json == '\\') { - *into++ = (unsigned char) *json++; + *into++ = (unsigned char)*json++; } - *into++ = (unsigned char) *json++; + *into++ = (unsigned char)*json++; } - *into++ = (unsigned char) *json++; - } else { + *into++ = (unsigned char)*json++; + } + else { /* All other characters. */ - *into++ = (unsigned char) *json++; + *into++ = (unsigned char)*json++; } } @@ -2541,7 +2601,7 @@ CJSON_PUBLIC(void) cJSON_Minify(char *json) *into = '\0'; } -CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item) +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON *const item) { if (item == NULL) { return false; @@ -2550,7 +2610,7 @@ CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item) return (item->type & 0xFF) == cJSON_Invalid; } -CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item) +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON *const item) { if (item == NULL) { return false; @@ -2559,7 +2619,7 @@ CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item) return (item->type & 0xFF) == cJSON_False; } -CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item) +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON *const item) { if (item == NULL) { return false; @@ -2568,7 +2628,7 @@ CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item) return (item->type & 0xff) == cJSON_True; } -CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item) +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON *const item) { if (item == NULL) { return false; @@ -2576,7 +2636,7 @@ CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item) return (item->type & (cJSON_True | cJSON_False)) != 0; } -CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item) +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON *const item) { if (item == NULL) { return false; @@ -2585,7 +2645,7 @@ CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item) return (item->type & 0xFF) == cJSON_NULL; } -CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item) +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON *const item) { if (item == NULL) { return false; @@ -2594,7 +2654,7 @@ CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item) return (item->type & 0xFF) == cJSON_Number; } -CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item) +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON *const item) { if (item == NULL) { return false; @@ -2603,7 +2663,7 @@ CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item) return (item->type & 0xFF) == cJSON_String; } -CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item) +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON *const item) { if (item == NULL) { return false; @@ -2612,7 +2672,7 @@ CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item) return (item->type & 0xFF) == cJSON_Array; } -CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item) +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON *const item) { if (item == NULL) { return false; @@ -2621,7 +2681,7 @@ CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item) return (item->type & 0xFF) == cJSON_Object; } -CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item) +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON *const item) { if (item == NULL) { return false; @@ -2630,28 +2690,29 @@ CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item) return (item->type & 0xFF) == cJSON_Raw; } -CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, - const cJSON * const b, const cJSON_bool case_sensitive) +CJSON_PUBLIC(cJSON_bool) +cJSON_Compare(const cJSON *const a, const cJSON *const b, + const cJSON_bool case_sensitive) { if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF)) - || cJSON_IsInvalid(a)) { + || cJSON_IsInvalid(a)) { return false; } /* check if type is valid */ switch (a->type & 0xFF) { - case cJSON_False: - case cJSON_True: - case cJSON_NULL: - case cJSON_Number: - case cJSON_String: - case cJSON_Raw: - case cJSON_Array: - case cJSON_Object: - break; - - default: - return false; + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + case cJSON_Number: + case cJSON_String: + case cJSON_Raw: + case cJSON_Array: + case cJSON_Object: + break; + + default: + return false; } /* identical objects are equal */ @@ -2660,85 +2721,90 @@ CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, } switch (a->type & 0xFF) { - /* in these cases and equal type is enough */ - case cJSON_False: - case cJSON_True: - case cJSON_NULL: - return true; - - case cJSON_Number: - if (a->valuedouble == b->valuedouble) { + /* in these cases and equal type is enough */ + case cJSON_False: + case cJSON_True: + case cJSON_NULL: return true; - } - return false; - case cJSON_String: - case cJSON_Raw: - if ((a->valuestring == NULL) || (b->valuestring == NULL)) { + case cJSON_Number: + if (a->valuedouble == b->valuedouble) { + return true; + } return false; - } - if (strcmp(a->valuestring, b->valuestring) == 0) { - return true; - } - return false; - - case cJSON_Array: { - cJSON *a_element = a->child; - cJSON *b_element = b->child; - - for (; (a_element != NULL) && (b_element != NULL);) { - if (!cJSON_Compare(a_element, b_element, case_sensitive)) { + case cJSON_String: + case cJSON_Raw: + if ((a->valuestring == NULL) || (b->valuestring == NULL)) { return false; } + if (strcmp(a->valuestring, b->valuestring) == 0) { + return true; + } - a_element = a_element->next; - b_element = b_element->next; - } - - /* one of the arrays is longer than the other */ - if (a_element != b_element) { return false; - } - - return true; - } - case cJSON_Object: { - cJSON *a_element = NULL; - cJSON *b_element = NULL; - cJSON_ArrayForEach(a_element, a) + case cJSON_Array: { - /* TODO This has O(n^2) runtime, which is horrible! */ - b_element = get_object_item(b, a_element->string, case_sensitive); - if (b_element == NULL) { - return false; + cJSON *a_element = a->child; + cJSON *b_element = b->child; + + for (; (a_element != NULL) && (b_element != NULL);) { + if (!cJSON_Compare(a_element, b_element, case_sensitive)) { + return false; + } + + a_element = a_element->next; + b_element = b_element->next; } - if (!cJSON_Compare(a_element, b_element, case_sensitive)) { + /* one of the arrays is longer than the other */ + if (a_element != b_element) { return false; } + + return true; } - /* doing this twice, once on a and b to prevent true comparison if a subset of b - * TODO: Do this the proper way, this is just a fix for now */ - cJSON_ArrayForEach(b_element, b) + case cJSON_Object: { - a_element = get_object_item(a, b_element->string, case_sensitive); - if (a_element == NULL) { - return false; + cJSON *a_element = NULL; + cJSON *b_element = NULL; + cJSON_ArrayForEach(a_element, a) + { + /* TODO This has O(n^2) runtime, which is horrible! */ + b_element = + get_object_item(b, a_element->string, case_sensitive); + if (b_element == NULL) { + return false; + } + + if (!cJSON_Compare(a_element, b_element, case_sensitive)) { + return false; + } } - if (!cJSON_Compare(b_element, a_element, case_sensitive)) { - return false; + /* doing this twice, once on a and b to prevent true comparison if a + * subset of b + * TODO: Do this the proper way, this is just a fix for now */ + cJSON_ArrayForEach(b_element, b) + { + a_element = + get_object_item(a, b_element->string, case_sensitive); + if (a_element == NULL) { + return false; + } + + if (!cJSON_Compare(b_element, a_element, case_sensitive)) { + return false; + } } - } - return true; - } + return true; + } - default: - return false; + default: + return false; } } diff --git a/test-tools/host-tool/external/cJSON/cJSON.h b/test-tools/host-tool/external/cJSON/cJSON.h index 82e05af6e3..fc26d64ca4 100644 --- a/test-tools/host-tool/external/cJSON/cJSON.h +++ b/test-tools/host-tool/external/cJSON/cJSON.h @@ -27,51 +27,57 @@ extern "C" { #endif -#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32)) +#if !defined(__WINDOWS__) \ + && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) \ + || defined(_WIN32)) #define __WINDOWS__ #endif #ifdef __WINDOWS__ -/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options: - - CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols - CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default) - CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol - - For *nix builds that support visibility attribute, you can define similar behavior by - - setting default visibility to hidden by adding - -fvisibility=hidden (for gcc) - or - -xldscope=hidden (for sun cc) - to CFLAGS - - then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does - +/** + * When compiling for windows, we specify a specific calling convention to avoid + * issues where we are being called from a project with a different default + * calling convention. For windows you have 3 define options: + * CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever + * dllexport symbols + * CJSON_EXPORT_SYMBOLS - Define this on library build when you want to + * dllexport symbols (default) + * CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol + * + * For *nix builds that support visibility attribute, you can define similar + * behavior by setting default visibility to hidden by adding + * -fvisibility=hidden (for gcc) + * or + * -xldscope=hidden (for sun cc) + * to CFLAGS, then using the CJSON_API_VISIBILITY flag to "export" the same + * symbols the way CJSON_EXPORT_SYMBOLS does */ #define CJSON_CDECL __cdecl #define CJSON_STDCALL __stdcall -/* export symbols by default, this is necessary for copy pasting the C and header file */ -#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS) +/* export symbols by default, this is necessary for copy pasting the C and + header file */ +#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) \ + && !defined(CJSON_EXPORT_SYMBOLS) #define CJSON_EXPORT_SYMBOLS #endif #if defined(CJSON_HIDE_SYMBOLS) -#define CJSON_PUBLIC(type) type CJSON_STDCALL +#define CJSON_PUBLIC(type) type CJSON_STDCALL #elif defined(CJSON_EXPORT_SYMBOLS) -#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL +#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL #elif defined(CJSON_IMPORT_SYMBOLS) -#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL +#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL #endif #else /* !__WINDOWS__ */ #define CJSON_CDECL #define CJSON_STDCALL -#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY) -#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type +#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined(__SUNPRO_C)) \ + && defined(CJSON_API_VISIBILITY) +#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type #else #define CJSON_PUBLIC(type) type #endif @@ -86,24 +92,26 @@ extern "C" { /* cJSON Types: */ #define cJSON_Invalid (0) -#define cJSON_False (1 << 0) -#define cJSON_True (1 << 1) -#define cJSON_NULL (1 << 2) +#define cJSON_False (1 << 0) +#define cJSON_True (1 << 1) +#define cJSON_NULL (1 << 2) #define cJSON_Number (1 << 3) #define cJSON_String (1 << 4) -#define cJSON_Array (1 << 5) +#define cJSON_Array (1 << 5) #define cJSON_Object (1 << 6) -#define cJSON_Raw (1 << 7) /* raw json */ +#define cJSON_Raw (1 << 7) /* raw json */ #define cJSON_IsReference 256 #define cJSON_StringIsConst 512 /* The cJSON structure: */ typedef struct cJSON { - /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ + /* next/prev allow you to walk array/object chains. Alternatively, use + GetArraySize/GetArrayItem/GetObjectItem */ struct cJSON *next; struct cJSON *prev; - /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ + /* An array or object item will have a child pointer pointing to a chain of + the items in the array/object. */ struct cJSON *child; /* The type of the item, as above. */ @@ -116,74 +124,101 @@ typedef struct cJSON { /* The item's number, if type==cJSON_Number */ double valuedouble; - /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ + /* The item's name string, if this item is the child of, or is in the list + of subitems of an object. */ char *string; } cJSON; typedef struct cJSON_Hooks { - /* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */ + /* malloc/free are CDECL on Windows regardless of the default calling + * convention of the compiler, so ensure the hooks allow passing those + * functions directly. */ void *(CJSON_CDECL *malloc_fn)(size_t sz); - void (CJSON_CDECL *free_fn)(void *ptr); + void(CJSON_CDECL *free_fn)(void *ptr); } cJSON_Hooks; typedef int cJSON_bool; -/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them. - * This is to prevent stack overflows. */ +/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse + them. This is to prevent stack overflows. */ #ifndef CJSON_NESTING_LIMIT #define CJSON_NESTING_LIMIT 1000 #endif /* returns the version of cJSON as a string */ -CJSON_PUBLIC(const char*) cJSON_Version(void); +CJSON_PUBLIC(const char *) cJSON_Version(void); /* Supply malloc, realloc and free functions to cJSON */ -CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks); - -/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */ -/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */ +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks *hooks); + +/* Memory Management: the caller is always responsible to free the results from + * all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib + * free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is + * cJSON_PrintPreallocated, where the caller has full responsibility of the + * buffer. */ +/* Supply a block of JSON, and this returns a cJSON object you can interrogate. + */ CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); -/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */ -/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */ -CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated); +/* ParseWithOpts allows you to require (and check) that the JSON is null + * terminated, and to retrieve the pointer to the final byte parsed. */ +/* If you supply a ptr in return_parse_end and parsing fails, then + * return_parse_end will contain a pointer to the error so will match + * cJSON_GetErrorPtr(). */ +CJSON_PUBLIC(cJSON *) +cJSON_ParseWithOpts(const char *value, const char **return_parse_end, + cJSON_bool require_null_terminated); /* Render a cJSON entity to text for transfer/storage. */ CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item); /* Render a cJSON entity to text for transfer/storage without any formatting. */ CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item); -/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */ -CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt); -/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */ -/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */ -CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format); +/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess + * at the final size. guessing well reduces reallocation. fmt=0 gives + * unformatted, =1 gives formatted */ +CJSON_PUBLIC(char *) +cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt); +/* Render a cJSON entity to text using a buffer already allocated in memory with + * given length. Returns 1 on success and 0 on failure. */ +/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will + * use, so to be safe allocate 5 bytes more than you actually need */ +CJSON_PUBLIC(cJSON_bool) +cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, + const cJSON_bool format); /* Delete a cJSON entity and all subentities. */ CJSON_PUBLIC(void) cJSON_Delete(cJSON *c); /* Returns the number of items in an array (or object). */ CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array); -/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */ +/* Retrieve item number "index" from array "array". Returns NULL if + * unsuccessful. */ CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index); /* Get item "string" from object. Case insensitive. */ -CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string); -CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string); -CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string); -/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ +CJSON_PUBLIC(cJSON *) +cJSON_GetObjectItem(const cJSON *const object, const char *const string); +CJSON_PUBLIC(cJSON *) +cJSON_GetObjectItemCaseSensitive(const cJSON *const object, + const char *const string); +CJSON_PUBLIC(cJSON_bool) +cJSON_HasObjectItem(const cJSON *object, const char *string); +/* For analysing failed parses. This returns a pointer to the parse error. + * You'll probably need to look a few chars back to make sense of it. Defined + * when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void); /* Check if the item is a string and return its valuestring */ CJSON_PUBLIC(char *) cJSON_GetStringValue(cJSON *item); /* These functions check the type of an item */ -CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON *const item); /* These calls create a cJSON item of the appropriate type. */ CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void); @@ -198,10 +233,10 @@ CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void); CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void); /* Create a string where valuestring references a string so - * it will not be freed by cJSON_Delete */ + it will not be freed by cJSON_Delete */ CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string); /* Create an object/arrray that only references it's elements so - * they will not be freed by cJSON_Delete */ + they will not be freed by cJSON_Delete */ CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child); CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child); @@ -213,64 +248,110 @@ CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char **strings, int count); /* Append item to the specified array/object. */ CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item); -CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item); -/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object. - * WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before - * writing to `item->string` */ -CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item); -/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */ +CJSON_PUBLIC(void) +cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item); +/* Use this when string is definitely const (i.e. a literal, or as good as), and + * will definitely survive the cJSON object. WARNING: When this function was + * used, make sure to always check that (item->type & cJSON_StringIsConst) is + * zero before writing to `item->string` */ +CJSON_PUBLIC(void) +cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item); +/* Append reference to item to the specified array/object. Use this when you + * want to add an existing cJSON to a new cJSON, but don't want to corrupt your + * existing cJSON. */ CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); -CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item); +CJSON_PUBLIC(void) +cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item); /* Remove/Detatch items from Arrays/Objects. */ -CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item); +CJSON_PUBLIC(cJSON *) +cJSON_DetachItemViaPointer(cJSON *parent, cJSON *const item); CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which); CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which); -CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string); -CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string); -CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string); -CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string); +CJSON_PUBLIC(cJSON *) +cJSON_DetachItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(cJSON *) +cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string); +CJSON_PUBLIC(void) +cJSON_DeleteItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(void) +cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string); /* Update array items. */ -CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */ -CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement); -CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem); -CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem); -CJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem); +CJSON_PUBLIC(void) +cJSON_InsertItemInArray( + cJSON *array, int which, + cJSON *newitem); /* Shifts pre-existing items to the right. */ +CJSON_PUBLIC(cJSON_bool) +cJSON_ReplaceItemViaPointer(cJSON *const parent, cJSON *const item, + cJSON *replacement); +CJSON_PUBLIC(void) +cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem); +CJSON_PUBLIC(void) +cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem); +CJSON_PUBLIC(void) +cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, + cJSON *newitem); /* Duplicate a cJSON item */ CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse); -/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will - need to be released. With recurse!=0, it will duplicate any children connected to the item. - The item->next and ->prev pointers are always zero on return from Duplicate. */ -/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal. - * case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */ -CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive); +/* Duplicate will create a new, identical cJSON item to the one you pass, in new + memory that will need to be released. With recurse!=0, it will duplicate any + children connected to the item. The item->next and ->prev pointers are always + zero on return from Duplicate. */ +/* Recursively compare two cJSON items for equality. If either a or b is NULL or + * invalid, they will be considered unequal. + * case_sensitive determines if object keys are treated case sensitive (1) or + * case insensitive (0) */ +CJSON_PUBLIC(cJSON_bool) +cJSON_Compare(const cJSON *const a, const cJSON *const b, + const cJSON_bool case_sensitive); CJSON_PUBLIC(void) cJSON_Minify(char *json); /* Helper functions for creating and adding items to an object at the same time. - * They return the added item or NULL on failure. */ -CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name); -CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name); -CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name); -CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean); -CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number); -CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string); -CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw); -CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name); -CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name); - -/* When assigning an integer value, it needs to be propagated to valuedouble too. */ -#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number)) + They return the added item or NULL on failure. */ +CJSON_PUBLIC(cJSON *) +cJSON_AddNullToObject(cJSON *const object, const char *const name); +CJSON_PUBLIC(cJSON *) +cJSON_AddTrueToObject(cJSON *const object, const char *const name); +CJSON_PUBLIC(cJSON *) +cJSON_AddFalseToObject(cJSON *const object, const char *const name); +CJSON_PUBLIC(cJSON *) +cJSON_AddBoolToObject(cJSON *const object, const char *const name, + const cJSON_bool boolean); +CJSON_PUBLIC(cJSON *) +cJSON_AddNumberToObject(cJSON *const object, const char *const name, + const double number); +CJSON_PUBLIC(cJSON *) +cJSON_AddStringToObject(cJSON *const object, const char *const name, + const char *const string); +CJSON_PUBLIC(cJSON *) +cJSON_AddRawToObject(cJSON *const object, const char *const name, + const char *const raw); +CJSON_PUBLIC(cJSON *) +cJSON_AddObjectToObject(cJSON *const object, const char *const name); +CJSON_PUBLIC(cJSON *) +cJSON_AddArrayToObject(cJSON *const object, const char *const name); + +/* When assigning an integer value, it needs to be propagated to valuedouble + too. */ +#define cJSON_SetIntValue(object, number) \ + ((object) ? (object)->valueint = (object)->valuedouble = (number) \ + : (number)) /* helper for the cJSON_SetNumberValue macro */ CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number); -#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number)) +#define cJSON_SetNumberValue(object, number) \ + ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) \ + : (number)) /* Macro for iterating over an array or object */ -#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next) +#define cJSON_ArrayForEach(element, array) \ + for (element = (array != NULL) ? (array)->child : NULL; element != NULL; \ + element = element->next) -/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */ +/* malloc/free objects using the malloc/free functions that have been set with + cJSON_InitHooks */ CJSON_PUBLIC(void *) cJSON_malloc(size_t size); CJSON_PUBLIC(void) cJSON_free(void *object); diff --git a/test-tools/host-tool/src/host_tool_utils.c b/test-tools/host-tool/src/host_tool_utils.c index 183ed0d574..2b9051bbf4 100644 --- a/test-tools/host-tool/src/host_tool_utils.c +++ b/test-tools/host-tool/src/host_tool_utils.c @@ -24,37 +24,40 @@ typedef union jvalue { double d; } jvalue; - - -static inline int16_t get_int16(const char *buf) +static inline int16_t +get_int16(const char *buf) { int16_t ret; bh_memcpy_s(&ret, sizeof(int16_t), buf, sizeof(int16_t)); return ret; } -static inline uint16_t get_uint16(const char *buf) +static inline uint16_t +get_uint16(const char *buf) { return get_int16(buf); } -static inline int32_t get_int32(const char *buf) +static inline int32_t +get_int32(const char *buf) { int32_t ret; bh_memcpy_s(&ret, sizeof(int32_t), buf, sizeof(int32_t)); return ret; } -static inline uint32_t get_uint32(const char *buf) +static inline uint32_t +get_uint32(const char *buf) { return get_int32(buf); } -char* attr_container_get_attr_begin(const attr_container_t *attr_cont, - uint32_t *p_total_length, - uint16_t *p_attr_num); +char * +attr_container_get_attr_begin(const attr_container_t *attr_cont, + uint32_t *p_total_length, uint16_t *p_attr_num); -cJSON *attr2json(const attr_container_t *attr_cont) +cJSON * +attr2json(const attr_container_t *attr_cont) { uint32_t total_length; uint16_t attr_num, i, j, type; @@ -87,91 +90,95 @@ cJSON *attr2json(const attr_container_t *attr_cont) type = *p++; switch (type) { - case ATTR_TYPE_SHORT: - bh_memcpy_s(&value.s, sizeof(int16_t), p, sizeof(int16_t)); - if (NULL == (obj = cJSON_CreateNumber(value.s))) - goto fail; - cJSON_AddItemToObject(root, key, obj); - /* another approach: cJSON_AddNumberToObject(root, key, value.s) */ - p += 2; - break; - case ATTR_TYPE_INT: - bh_memcpy_s(&value.i, sizeof(int32_t), p, sizeof(int32_t)); - if (NULL == (obj = cJSON_CreateNumber(value.i))) - goto fail; - cJSON_AddItemToObject(root, key, obj); - p += 4; - break; - case ATTR_TYPE_INT64: - bh_memcpy_s(&value.j, sizeof(uint64_t), p, sizeof(uint64_t)); - if (NULL == (obj = cJSON_CreateNumber(value.j))) - goto fail; - cJSON_AddItemToObject(root, key, obj); - p += 8; - break; - case ATTR_TYPE_BYTE: - bh_memcpy_s(&value.b, 1, p, 1); - if (NULL == (obj = cJSON_CreateNumber(value.b))) - goto fail; - cJSON_AddItemToObject(root, key, obj); - p++; - break; - case ATTR_TYPE_UINT16: - bh_memcpy_s(&value.c, sizeof(uint16_t), p, sizeof(uint16_t)); - if (NULL == (obj = cJSON_CreateNumber(value.c))) - goto fail; - cJSON_AddItemToObject(root, key, obj); - p += 2; - break; - case ATTR_TYPE_FLOAT: - bh_memcpy_s(&value.f, sizeof(float), p, sizeof(float)); - if (NULL == (obj = cJSON_CreateNumber(value.f))) - goto fail; - cJSON_AddItemToObject(root, key, obj); - p += 4; - break; - case ATTR_TYPE_DOUBLE: - bh_memcpy_s(&value.d, sizeof(double), p, sizeof(double)); - if (NULL == (obj = cJSON_CreateNumber(value.d))) - goto fail; - cJSON_AddItemToObject(root, key, obj); - p += 8; - break; - case ATTR_TYPE_BOOLEAN: - bh_memcpy_s(&value.z, 1, p, 1); - if (NULL == (obj = cJSON_CreateBool(value.z))) - goto fail; - cJSON_AddItemToObject(root, key, obj); - p++; - break; - case ATTR_TYPE_STRING: - if (NULL == (obj = cJSON_CreateString(p + sizeof(uint16_t)))) - goto fail; - cJSON_AddItemToObject(root, key, obj); - p += sizeof(uint16_t) + get_uint16(p); - break; - case ATTR_TYPE_BYTEARRAY: - if (NULL == (obj = cJSON_CreateArray())) - goto fail; - cJSON_AddItemToObject(root, key, obj); - for (j = 0; j < get_uint32(p); j++) { - cJSON *item = cJSON_CreateNumber(*(p + sizeof(uint32_t) + j)); - if (item == NULL) + case ATTR_TYPE_SHORT: + bh_memcpy_s(&value.s, sizeof(int16_t), p, sizeof(int16_t)); + if (NULL == (obj = cJSON_CreateNumber(value.s))) goto fail; - cJSON_AddItemToArray(obj, item); - } - p += sizeof(uint32_t) + get_uint32(p); - break; + cJSON_AddItemToObject(root, key, obj); + /* another approach: cJSON_AddNumberToObject(root, key, value.s) + */ + p += 2; + break; + case ATTR_TYPE_INT: + bh_memcpy_s(&value.i, sizeof(int32_t), p, sizeof(int32_t)); + if (NULL == (obj = cJSON_CreateNumber(value.i))) + goto fail; + cJSON_AddItemToObject(root, key, obj); + p += 4; + break; + case ATTR_TYPE_INT64: + bh_memcpy_s(&value.j, sizeof(uint64_t), p, sizeof(uint64_t)); + if (NULL == (obj = cJSON_CreateNumber(value.j))) + goto fail; + cJSON_AddItemToObject(root, key, obj); + p += 8; + break; + case ATTR_TYPE_BYTE: + bh_memcpy_s(&value.b, 1, p, 1); + if (NULL == (obj = cJSON_CreateNumber(value.b))) + goto fail; + cJSON_AddItemToObject(root, key, obj); + p++; + break; + case ATTR_TYPE_UINT16: + bh_memcpy_s(&value.c, sizeof(uint16_t), p, sizeof(uint16_t)); + if (NULL == (obj = cJSON_CreateNumber(value.c))) + goto fail; + cJSON_AddItemToObject(root, key, obj); + p += 2; + break; + case ATTR_TYPE_FLOAT: + bh_memcpy_s(&value.f, sizeof(float), p, sizeof(float)); + if (NULL == (obj = cJSON_CreateNumber(value.f))) + goto fail; + cJSON_AddItemToObject(root, key, obj); + p += 4; + break; + case ATTR_TYPE_DOUBLE: + bh_memcpy_s(&value.d, sizeof(double), p, sizeof(double)); + if (NULL == (obj = cJSON_CreateNumber(value.d))) + goto fail; + cJSON_AddItemToObject(root, key, obj); + p += 8; + break; + case ATTR_TYPE_BOOLEAN: + bh_memcpy_s(&value.z, 1, p, 1); + if (NULL == (obj = cJSON_CreateBool(value.z))) + goto fail; + cJSON_AddItemToObject(root, key, obj); + p++; + break; + case ATTR_TYPE_STRING: + if (NULL == (obj = cJSON_CreateString(p + sizeof(uint16_t)))) + goto fail; + cJSON_AddItemToObject(root, key, obj); + p += sizeof(uint16_t) + get_uint16(p); + break; + case ATTR_TYPE_BYTEARRAY: + if (NULL == (obj = cJSON_CreateArray())) + goto fail; + cJSON_AddItemToObject(root, key, obj); + for (j = 0; j < get_uint32(p); j++) { + cJSON *item = + cJSON_CreateNumber(*(p + sizeof(uint32_t) + j)); + if (item == NULL) + goto fail; + cJSON_AddItemToArray(obj, item); + } + p += sizeof(uint32_t) + get_uint32(p); + break; } } return root; - fail: cJSON_Delete(root); +fail: + cJSON_Delete(root); return NULL; } -attr_container_t *json2attr(const cJSON *json_obj) +attr_container_t * +json2attr(const cJSON *json_obj) { attr_container_t *attr_cont; cJSON *item; @@ -187,20 +194,24 @@ attr_container_t *json2attr(const cJSON *json_obj) if (cJSON_IsNumber(item)) { attr_container_set_double(&attr_cont, item->string, - item->valuedouble); - } else if (cJSON_IsTrue(item)) { + item->valuedouble); + } + else if (cJSON_IsTrue(item)) { attr_container_set_bool(&attr_cont, item->string, true); - } else if (cJSON_IsFalse(item)) { + } + else if (cJSON_IsFalse(item)) { attr_container_set_bool(&attr_cont, item->string, false); - } else if (cJSON_IsString(item)) { + } + else if (cJSON_IsString(item)) { attr_container_set_string(&attr_cont, item->string, - item->valuestring); - } else if (cJSON_IsArray(item)) { + item->valuestring); + } + else if (cJSON_IsArray(item)) { int8_t *array; int i = 0, len = sizeof(int8_t) * cJSON_GetArraySize(item); cJSON *array_item; - if (0 == len || NULL == (array = (int8_t *) malloc(len))) + if (0 == len || NULL == (array = (int8_t *)malloc(len))) goto fail; memset(array, 0, len); @@ -210,24 +221,26 @@ attr_container_t *json2attr(const cJSON *json_obj) if (!cJSON_IsNumber(array_item)) break; /* TODO: if array_item->valuedouble > 127 or < -128 */ - array[i++] = (int8_t) array_item->valuedouble; + array[i++] = (int8_t)array_item->valuedouble; } if (i > 0) attr_container_set_bytearray(&attr_cont, item->string, array, - i); + i); free(array); } } return attr_cont; - fail: attr_container_destroy(attr_cont); +fail: + attr_container_destroy(attr_cont); return NULL; } int g_mid = 0; -int gen_random_id() +int +gen_random_id() { static bool init = false; int r; @@ -283,7 +296,8 @@ read_file_to_buffer(const char *filename, int *ret_size) return buffer; } -int wirte_buffer_to_file(const char *filename, const char *buffer, int size) +int +wirte_buffer_to_file(const char *filename, const char *buffer, int size) { int file, ret; diff --git a/test-tools/host-tool/src/host_tool_utils.h b/test-tools/host-tool/src/host_tool_utils.h index aaf427b9c3..9b30b41ab4 100644 --- a/test-tools/host-tool/src/host_tool_utils.h +++ b/test-tools/host-tool/src/host_tool_utils.h @@ -22,7 +22,8 @@ extern "C" { * * @warning the return object should be deleted with cJSON_Delete by caller */ -cJSON *attr2json(const attr_container_t *attr); +cJSON * +attr2json(const attr_container_t *attr); /** * @brief Convert cJSON object to attribute container object. @@ -33,14 +34,16 @@ cJSON *attr2json(const attr_container_t *attr); * * @warning the return object should be deleted with attr_container_destroy */ -attr_container_t *json2attr(const cJSON *json); +attr_container_t * +json2attr(const cJSON *json); /** * @brief Generate a random 32 bit integer. * * @return the generated random integer */ -int gen_random_id(); +int +gen_random_id(); /** * @brief Read file content to buffer. @@ -48,11 +51,13 @@ int gen_random_id(); * @param filename the file name to read * @param ret_size pointer of integer to save file size once return success * - * @return the created buffer which contains file content if not NULL, NULL means fail + * @return the created buffer which contains file content if not NULL, NULL + * means fail * * @warning the return buffer should be deleted with free by caller */ -char *read_file_to_buffer(const char *filename, int *ret_size); +char * +read_file_to_buffer(const char *filename, int *ret_size); /** * @brief Write buffer content to file. @@ -63,7 +68,8 @@ char *read_file_to_buffer(const char *filename, int *ret_size); * * @return < 0 means fail, > 0 means the number of bytes actually written */ -int wirte_buffer_to_file(const char *filename, const char *buffer, int size); +int +wirte_buffer_to_file(const char *filename, const char *buffer, int size); #ifdef __cplusplus } /* end of extern "C" */ diff --git a/test-tools/host-tool/src/main.c b/test-tools/host-tool/src/main.c index 305abc7adb..7db2f56143 100644 --- a/test-tools/host-tool/src/main.c +++ b/test-tools/host-tool/src/main.c @@ -17,7 +17,7 @@ #include "coap_ext.h" #include "cJSON.h" #include "app_manager_export.h" /* for Module_WASM_App */ -#include "host_link.h" /* for REQUEST_PACKET */ +#include "host_link.h" /* for REQUEST_PACKET */ #include "transport.h" #define BUF_SIZE 1024 @@ -105,7 +105,8 @@ extern int g_mid; extern unsigned char leading[2]; /* -1 fail, 0 success */ -static int send_request(request_t *request, uint16_t msg_type) +static int +send_request(request_t *request, uint16_t msg_type) { char *req_p; int req_size, req_size_n, ret = -1; @@ -119,12 +120,12 @@ static int send_request(request_t *request, uint16_t msg_type) /* message type */ msg_type = htons(msg_type); - if (!host_tool_send_data(g_conn_fd, (char *) &msg_type, sizeof(msg_type))) + if (!host_tool_send_data(g_conn_fd, (char *)&msg_type, sizeof(msg_type))) goto ret; /* payload length */ req_size_n = htonl(req_size); - if (!host_tool_send_data(g_conn_fd, (char *) &req_size_n, + if (!host_tool_send_data(g_conn_fd, (char *)&req_size_n, sizeof(req_size_n))) goto ret; @@ -144,7 +145,8 @@ static int send_request(request_t *request, uint16_t msg_type) /** * return: 0: success, others: fail */ -static int install(inst_info *info) +static int +install(inst_info *info) { request_t request[1] = { 0 }; char *app_file_buf; @@ -155,25 +157,25 @@ static int install(inst_info *info) if (info->module_type != NULL && url_remain_space > 0) snprintf(url + strlen(url), url_remain_space, "&type=%s", - info->module_type); + info->module_type); if (info->heap_size > 0 && url_remain_space > 0) snprintf(url + strlen(url), url_remain_space, "&heap=%d", - info->heap_size); + info->heap_size); if (info->timers > 0 && url_remain_space > 0) snprintf(url + strlen(url), url_remain_space, "&timers=%d", - info->timers); + info->timers); if (info->watchdog_interval > 0 && url_remain_space > 0) snprintf(url + strlen(url), url_remain_space, "&wd=%d", - info->watchdog_interval); + info->watchdog_interval); if ((app_file_buf = read_file_to_buffer(info->file, &app_size)) == NULL) return -1; - init_request(request, url, COAP_PUT, FMT_APP_RAW_BINARY, - app_file_buf, app_size); + init_request(request, url, COAP_PUT, FMT_APP_RAW_BINARY, app_file_buf, + app_size); request->mid = gen_random_id(); if (info->module_type == NULL || strcmp(info->module_type, "wasm") == 0) @@ -186,7 +188,8 @@ static int install(inst_info *info) return ret; } -static int uninstall(uninst_info *info) +static int +uninstall(uninst_info *info) { request_t request[1] = { 0 }; char url[URL_MAX_LEN] = { 0 }; @@ -197,14 +200,14 @@ static int uninstall(uninst_info *info) snprintf(url + strlen(url), url_remain_space, "&type=%s", info->module_type); - init_request(request, url, COAP_DELETE, FMT_ATTR_CONTAINER, - NULL, 0); + init_request(request, url, COAP_DELETE, FMT_ATTR_CONTAINER, NULL, 0); request->mid = gen_random_id(); return send_request(request, REQUEST_PACKET); } -static int query(query_info *info) +static int +query(query_info *info) { request_t request[1] = { 0 }; char url[URL_MAX_LEN] = { 0 }; @@ -220,7 +223,8 @@ static int query(query_info *info) return send_request(request, REQUEST_PACKET); } -static int request(req_info *info) +static int +request(req_info *info) { request_t request[1] = { 0 }; attr_container_t *payload = NULL; @@ -232,7 +236,8 @@ static int request(req_info *info) int payload_file_size; if ((payload_file = read_file_to_buffer(info->json_payload_file, - &payload_file_size)) == NULL) + &payload_file_size)) + == NULL) return -1; if (NULL == (json = cJSON_Parse(payload_file))) { @@ -251,8 +256,8 @@ static int request(req_info *info) free(payload_file); } - init_request(request, (char *)info->url, info->action, - FMT_ATTR_CONTAINER, payload, payload_len); + init_request(request, (char *)info->url, info->action, FMT_ATTR_CONTAINER, + payload, payload_len); request->mid = gen_random_id(); ret = send_request(request, REQUEST_PACKET); @@ -268,7 +273,8 @@ static int request(req_info *info) * TODO: currently only support 1 url. * how to handle multiple responses and set process's exit code? */ -static int subscribe(reg_info *info) +static int +subscribe(reg_info *info) { request_t request[1] = { 0 }; int ret = -1; @@ -293,15 +299,15 @@ static int subscribe(reg_info *info) char url[URL_MAX_LEN] = { 0 }; char *prefix = info->urls[0] == '/' ? "/event" : "/event/"; snprintf(url, URL_MAX_LEN, "%s%s", prefix, info->urls); - init_request(request, url, COAP_PUT, FMT_ATTR_CONTAINER, - NULL, 0); + init_request(request, url, COAP_PUT, FMT_ATTR_CONTAINER, NULL, 0); request->mid = gen_random_id(); ret = send_request(request, REQUEST_PACKET); #endif return ret; } -static int unsubscribe(unreg_info *info) +static int +unsubscribe(unreg_info *info) { request_t request[1] = { 0 }; int ret = -1; @@ -325,15 +331,15 @@ static int unsubscribe(unreg_info *info) #else char url[URL_MAX_LEN] = { 0 }; snprintf(url, URL_MAX_LEN, "%s%s", "/event/", info->urls); - init_request(request, url, COAP_DELETE, FMT_ATTR_CONTAINER, - NULL, 0); + init_request(request, url, COAP_DELETE, FMT_ATTR_CONTAINER, NULL, 0); request->mid = gen_random_id(); ret = send_request(request, REQUEST_PACKET); #endif return ret; } -static int init() +static int +init() { if (g_connection_mode == CONNECTION_MODE_TCP) { int fd; @@ -353,12 +359,14 @@ static int init() return -1; } -static void deinit() +static void +deinit() { close(g_conn_fd); } -static int parse_action(const char *str) +static int +parse_action(const char *str) { if (strcasecmp(str, "PUT") == 0) return COAP_PUT; @@ -371,70 +379,55 @@ static int parse_action(const char *str) return -1; } +/* clang-format off */ static void showUsage() { - printf("\n"); - printf("Usage:\n\thost_tool -i|-u|-q|-r|-s|-d ...\n\n"); - - printf("\thost_tool -i -f \n" - "\t\t [--type=]\n" - "\t\t [--heap=]\n" - "\t\t [--timers=]\n" - "\t\t [--watchdog=]\n" - "\t\t [ ...] \n"); - printf("\thost_tool -u [ ...]\n"); - printf("\thost_tool -q[][ ...]\n"); - printf( - "\thost_tool -r -A [-p ] [ ...]\n"); - printf("\thost_tool -s [ ...]\n"); - printf("\thost_tool -d [ ...]\n\n"); - - printf( - "\t-i, --install Install an application\n"); - printf( - "\t-u, --uninstall Uninstall an application\n"); - printf( - "\t-q, --query Query all applications\n"); - printf("\t-r, --request Send a request\n"); - printf("\t-s, --register Register event(s)\n"); - printf("\t-d, --deregister De-register event(s)\n"); - printf( - "\t-f, --file Specify app binary file path\n"); - printf( - "\t-A, --action Specify action of the request\n"); - printf( - "\t-p, --payload Specify payload of the request\n"); - printf("\n"); - - printf("\n\tControl Options:\n"); - printf(" \t-S
|--address=
Set server address, default to 127.0.0.1\n"); - printf(" \t-P |--port= Set server port, default to 8888\n"); - printf(" \t-D |--uart= Set uart device, default to /dev/ttyS2\n"); - printf(" \t-B |--baudrate= Set uart device baudrate, default to 115200\n"); - - printf( - "\t-t |--timeout= Operation timeout in ms, default to 5000\n"); - printf( - "\t-a |--alive= Alive time in ms after last operation done, default to 0\n"); - printf( - "\t-o |--output= Redirect the output to output a file\n"); - printf( - "\t-U |--udp= Redirect the output to an UDP port in local machine\n"); + printf("Usages:\n"); + printf(" host_tool -i|-u|-q|-r|-s|-d ...\n"); + printf(" host_tool -i -f \n" + " [--type=]\n" + " [--heap=]\n" + " [--timers=]\n" + " [--watchdog=]\n" + " [ ...] \n"); + printf(" host_tool -u [ ...]\n"); + printf(" host_tool -q [] [ ...]\n"); + printf(" host_tool -r -A [-p ] [ ...]\n"); + printf(" host_tool -s [ ...]\n"); + printf(" host_tool -d [ ...]\n"); + + printf("\nGeneral Options:\n"); + printf(" -i, --install Install an application\n"); + printf(" -u, --uninstall Uninstall an application\n"); + printf(" -q, --query Query all applications\n"); + printf(" -r, --request Send a request\n"); + printf(" -s, --register Register event(s)\n"); + printf(" -d, --deregister De-register event(s)\n"); + printf(" -f, --file Specify app binary file path\n"); + printf(" -A, --action Specify action of the request\n"); + printf(" -p, --payload Specify payload of the request\n"); + + printf("\nControl Options:\n"); + printf(" -S
|--address=
Set server address, default to 127.0.0.1\n"); + printf(" -P |--port= Set server port, default to 8888\n"); + printf(" -D |--uart= Set uart device, default to /dev/ttyS2\n"); + printf(" -B |--baudrate= Set uart device baudrate, default to 115200\n"); + printf(" -t |--timeout= Operation timeout in ms, default to 5000\n"); + printf(" -a |--alive= Alive time in ms after last operation done, default to 0\n"); + printf(" -o |--output= Redirect the output to output a file\n"); + printf(" -U |--udp= Redirect the output to an UDP port in local machine\n"); printf("\nNotes:\n"); - printf("\t=name of the application\n"); - printf("\t=path of the application binary file in wasm format\n"); - printf( - "\t=resource descriptor, such as /app//res1 or /res1\n"); - printf( - "\t=event url list separated by ',', such as /event1,/event2,/event3\n"); - printf( - "\t=action of the request, can be PUT, GET, DELETE or POST (case insensitive)\n"); - printf("\t=path of the payload file in json format\n"); - printf("\t=Type of app. Can be 'wasm'(default) or 'jeff'\n"); - printf("\t=Heap size of app.\n"); - printf("\t=Max timers number app can use.\n"); - printf("\t=Watchdog interval in ms.\n"); + printf(" =name of the application\n"); + printf(" =path of the application binary file in wasm format\n"); + printf(" =resource descriptor, such as /app//res1 or /res1\n"); + printf(" =event url list separated by ',', such as /event1,/event2,/event3\n"); + printf(" =action of the request, can be PUT, GET, DELETE or POST (case insensitive)\n"); + printf(" =path of the payload file in json format\n"); + printf(" =Type of app. Can be 'wasm'(default) or 'jeff'\n"); + printf(" =Heap size of app.\n"); + printf(" =Max timers number app can use.\n"); + printf(" =Watchdog interval in ms.\n"); } #define CHECK_DUPLICATE_OPERATION do { \ diff --git a/test-tools/host-tool/src/transport.c b/test-tools/host-tool/src/transport.c index a5d16d2bf2..edadde25fa 100644 --- a/test-tools/host-tool/src/transport.c +++ b/test-tools/host-tool/src/transport.c @@ -22,7 +22,8 @@ unsigned char leading[2] = { 0x12, 0x34 }; -bool tcp_init(const char *address, uint16_t port, int *fd) +bool +tcp_init(const char *address, uint16_t port, int *fd) { int sock; struct sockaddr_in servaddr; @@ -35,7 +36,7 @@ bool tcp_init(const char *address, uint16_t port, int *fd) servaddr.sin_addr.s_addr = inet_addr(address); servaddr.sin_port = htons(port); - if (connect(sock, (SA*) &servaddr, sizeof(servaddr)) != 0) { + if (connect(sock, (SA *)&servaddr, sizeof(servaddr)) != 0) { close(sock); return false; } @@ -44,7 +45,8 @@ bool tcp_init(const char *address, uint16_t port, int *fd) return true; } -int parse_baudrate(int baud) +int +parse_baudrate(int baud) { switch (baud) { case 9600: @@ -88,7 +90,8 @@ int parse_baudrate(int baud) } } -bool uart_init(const char *device, int baudrate, int *fd) +bool +uart_init(const char *device, int baudrate, int *fd) { int uart_fd; struct termios uart_term; @@ -118,12 +121,13 @@ bool uart_init(const char *device, int baudrate, int *fd) return true; } -bool udp_send(const char *address, int port, const char *buf, int len) +bool +udp_send(const char *address, int port, const char *buf, int len) { int sockfd; struct sockaddr_in servaddr; - if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) + if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) return false; memset(&servaddr, 0, sizeof(servaddr)); @@ -132,14 +136,15 @@ bool udp_send(const char *address, int port, const char *buf, int len) servaddr.sin_port = htons(port); servaddr.sin_addr.s_addr = INADDR_ANY; - sendto(sockfd, buf, len, MSG_CONFIRM, - (const struct sockaddr *)&servaddr, sizeof(servaddr)); + sendto(sockfd, buf, len, MSG_CONFIRM, (const struct sockaddr *)&servaddr, + sizeof(servaddr)); close(sockfd); return true; } -bool host_tool_send_data(int fd, const char *buf, unsigned int len) +bool +host_tool_send_data(int fd, const char *buf, unsigned int len) { int cnt = 0; ssize_t ret; @@ -170,7 +175,11 @@ bool host_tool_send_data(int fd, const char *buf, unsigned int len) return (ret == len); } -#define SET_RECV_PHASE(ctx, new_phase) {ctx->phase = new_phase; ctx->size_in_phase = 0;} +#define SET_RECV_PHASE(ctx, new_phase) \ + do { \ + ctx->phase = new_phase; \ + ctx->size_in_phase = 0; \ + } while (0) /* * input: 1 byte from remote @@ -180,7 +189,8 @@ bool host_tool_send_data(int fd, const char *buf, unsigned int len) * 0 completed packet * 2 in receiving payload */ -int on_imrt_link_byte_arrive(unsigned char ch, imrt_link_recv_context_t *ctx) +int +on_imrt_link_byte_arrive(unsigned char ch, imrt_link_recv_context_t *ctx) { if (ctx->phase == Phase_Non_Start) { if (ctx->message.payload) { @@ -206,7 +216,7 @@ int on_imrt_link_byte_arrive(unsigned char ch, imrt_link_recv_context_t *ctx) } } else if (ctx->phase == Phase_Type) { - unsigned char *p = (unsigned char *) &ctx->message.message_type; + unsigned char *p = (unsigned char *)&ctx->message.message_type; p[ctx->size_in_phase++] = ch; if (ctx->size_in_phase == sizeof(ctx->message.message_type)) { @@ -215,7 +225,7 @@ int on_imrt_link_byte_arrive(unsigned char ch, imrt_link_recv_context_t *ctx) } } else if (ctx->phase == Phase_Size) { - unsigned char * p = (unsigned char *) &ctx->message.payload_size; + unsigned char *p = (unsigned char *)&ctx->message.payload_size; p[ctx->size_in_phase++] = ch; if (ctx->size_in_phase == sizeof(ctx->message.payload_size)) { @@ -233,7 +243,7 @@ int on_imrt_link_byte_arrive(unsigned char ch, imrt_link_recv_context_t *ctx) return 0; } - ctx->message.payload = (char *) malloc(ctx->message.payload_size); + ctx->message.payload = (char *)malloc(ctx->message.payload_size); SET_RECV_PHASE(ctx, Phase_Payload); } } diff --git a/test-tools/host-tool/src/transport.h b/test-tools/host-tool/src/transport.h index ea180cf132..449f438f88 100644 --- a/test-tools/host-tool/src/transport.h +++ b/test-tools/host-tool/src/transport.h @@ -19,7 +19,11 @@ typedef struct { /* The receive phase of IMRT link message */ typedef enum { - Phase_Non_Start, Phase_Leading, Phase_Type, Phase_Size, Phase_Payload + Phase_Non_Start, + Phase_Leading, + Phase_Type, + Phase_Size, + Phase_Payload } recv_phase_t; /* The receive context of IMRT link message */ @@ -38,7 +42,8 @@ typedef struct { * * @return true if success, false if fail */ -bool host_tool_send_data(int fd, const char *buf, unsigned int len); +bool +host_tool_send_data(int fd, const char *buf, unsigned int len); /** * @brief Handle one byte of IMRT link message @@ -51,7 +56,8 @@ bool host_tool_send_data(int fd, const char *buf, unsigned int len); * 0 completed packet * 2 in receiving payload */ -int on_imrt_link_byte_arrive(unsigned char ch, imrt_link_recv_context_t *ctx); +int +on_imrt_link_byte_arrive(unsigned char ch, imrt_link_recv_context_t *ctx); /** * @brief Initialize TCP connection with remote server. @@ -62,7 +68,8 @@ int on_imrt_link_byte_arrive(unsigned char ch, imrt_link_recv_context_t *ctx); * * @return true if success, false if fail */ -bool tcp_init(const char *address, uint16_t port, int *fd); +bool +tcp_init(const char *address, uint16_t port, int *fd); /** * @brief Initialize UART connection with remote. @@ -73,7 +80,8 @@ bool tcp_init(const char *address, uint16_t port, int *fd); * * @return true if success, false if fail */ -bool uart_init(const char *device, int baudrate, int *fd); +bool +uart_init(const char *device, int baudrate, int *fd); /** * @brief Parse UART baudrate from an integer @@ -90,7 +98,8 @@ bool uart_init(const char *device, int baudrate, int *fd); * ... * @endcode */ -int parse_baudrate(int baud); +int +parse_baudrate(int baud); /** * @brief Send data over UDP. @@ -102,7 +111,8 @@ int parse_baudrate(int baud); * * @return true if success, false if fail */ -bool udp_send(const char *address, int port, const char *buf, int len); +bool +udp_send(const char *address, int port, const char *buf, int len); #ifdef __cplusplus } /* end of extern "C" */ diff --git a/wamr-compiler/main.c b/wamr-compiler/main.c index c57eff2d62..8fae66d773 100644 --- a/wamr-compiler/main.c +++ b/wamr-compiler/main.c @@ -9,315 +9,314 @@ #include "wasm_export.h" #include "aot_export.h" - #if WASM_ENABLE_REF_TYPES != 0 extern void wasm_set_ref_types_flag(bool enable); #endif +/* clang-format off */ static int print_help() { - printf("Usage: wamrc [options] -o output_file wasm_file\n"); - printf(" --target= Set the target arch, which has the general format: \n"); - printf(" = x86_64, i386, aarch64, arm, thumb, xtensa, mips,\n"); - printf(" riscv64, riscv32.\n"); - printf(" Default is host arch, e.g. x86_64\n"); - printf(" = for ex. on arm or thumb: v5, v6m, v7a, v7m, etc.\n"); - printf(" Use --target=help to list supported targets\n"); - printf(" --target-abi= Set the target ABI, e.g. gnu, eabi, gnueabihf, msvc, etc.\n"); - printf(" Default is gnu if target isn't riscv64 or riscv32\n"); - printf(" For target riscv64 and riscv32, default is lp64d and ilp32d\n"); - printf(" Use --target-abi=help to list all the ABI supported\n"); - printf(" --cpu= Set the target CPU (default: host CPU, e.g. skylake)\n"); - printf(" Use --cpu=help to list all the CPU supported\n"); - printf(" --cpu-features= Enable or disable the CPU features\n"); - printf(" Use +feature to enable a feature, or -feature to disable it\n"); - printf(" For example, --cpu-features=+feature1,-feature2\n"); - printf(" Use --cpu-features=+help to list all the features supported\n"); - printf(" --opt-level=n Set the optimization level (0 to 3, default is 3)\n"); - printf(" --size-level=n Set the code size level (0 to 3, default is 3)\n"); - printf(" -sgx Generate code for SGX platform (Intel Software Guard Extention)\n"); - printf(" --bounds-checks=1/0 Enable or disable the bounds checks for memory access:\n"); - printf(" by default it is disabled in all 64-bit platforms except SGX and\n"); - printf(" in these platforms runtime does bounds checks with hardware trap,\n"); - printf(" and by default it is enabled in all 32-bit platforms\n"); - printf(" --format= Specifies the format of the output file\n"); - printf(" The format supported:\n"); - printf(" aot (default) AoT file\n"); - printf(" object Native object file\n"); - printf(" llvmir-unopt Unoptimized LLVM IR\n"); - printf(" llvmir-opt Optimized LLVM IR\n"); - printf(" --enable-bulk-memory Enable the post-MVP bulk memory feature\n"); - printf(" --enable-multi-thread Enable multi-thread feature, the dependent features bulk-memory and\n"); - printf(" thread-mgr will be enabled automatically\n"); - printf(" --enable-tail-call Enable the post-MVP tail call feature\n"); - printf(" --disable-simd Disable the post-MVP 128-bit SIMD feature:\n"); - printf(" currently 128-bit SIMD is only supported for x86-64 target,\n"); - printf(" and by default it is enabled in x86-64 target and disabled\n"); - printf(" in other targets\n"); - printf(" --enable-ref-types Enable the post-MVP reference types feature\n"); - printf(" --disable-aux-stack-check Disable auxiliary stack overflow/underflow check\n"); - printf(" --enable-dump-call-stack Enable stack trace feature\n"); - printf(" --enable-perf-profiling Enable function performance profiling\n"); - printf(" --enable-indirect-mode Enalbe call function through symbol table but not direct call\n"); - printf(" --disable-llvm-intrinsics Disable the LLVM built-in intrinsics\n"); - printf(" -v=n Set log verbose level (0 to 5, default is 2), larger with more log\n"); - printf("Examples: wamrc -o test.aot test.wasm\n"); - printf(" wamrc --target=i386 -o test.aot test.wasm\n"); - printf(" wamrc --target=i386 --format=object -o test.o test.wasm\n"); - return 1; + printf("Usage: wamrc [options] -o output_file wasm_file\n"); + printf(" --target= Set the target arch, which has the general format: \n"); + printf(" = x86_64, i386, aarch64, arm, thumb, xtensa, mips,\n"); + printf(" riscv64, riscv32.\n"); + printf(" Default is host arch, e.g. x86_64\n"); + printf(" = for ex. on arm or thumb: v5, v6m, v7a, v7m, etc.\n"); + printf(" Use --target=help to list supported targets\n"); + printf(" --target-abi= Set the target ABI, e.g. gnu, eabi, gnueabihf, msvc, etc.\n"); + printf(" Default is gnu if target isn't riscv64 or riscv32\n"); + printf(" For target riscv64 and riscv32, default is lp64d and ilp32d\n"); + printf(" Use --target-abi=help to list all the ABI supported\n"); + printf(" --cpu= Set the target CPU (default: host CPU, e.g. skylake)\n"); + printf(" Use --cpu=help to list all the CPU supported\n"); + printf(" --cpu-features= Enable or disable the CPU features\n"); + printf(" Use +feature to enable a feature, or -feature to disable it\n"); + printf(" For example, --cpu-features=+feature1,-feature2\n"); + printf(" Use --cpu-features=+help to list all the features supported\n"); + printf(" --opt-level=n Set the optimization level (0 to 3, default is 3)\n"); + printf(" --size-level=n Set the code size level (0 to 3, default is 3)\n"); + printf(" -sgx Generate code for SGX platform (Intel Software Guard Extention)\n"); + printf(" --bounds-checks=1/0 Enable or disable the bounds checks for memory access:\n"); + printf(" by default it is disabled in all 64-bit platforms except SGX and\n"); + printf(" in these platforms runtime does bounds checks with hardware trap,\n"); + printf(" and by default it is enabled in all 32-bit platforms\n"); + printf(" --format= Specifies the format of the output file\n"); + printf(" The format supported:\n"); + printf(" aot (default) AoT file\n"); + printf(" object Native object file\n"); + printf(" llvmir-unopt Unoptimized LLVM IR\n"); + printf(" llvmir-opt Optimized LLVM IR\n"); + printf(" --enable-bulk-memory Enable the post-MVP bulk memory feature\n"); + printf(" --enable-multi-thread Enable multi-thread feature, the dependent features bulk-memory and\n"); + printf(" thread-mgr will be enabled automatically\n"); + printf(" --enable-tail-call Enable the post-MVP tail call feature\n"); + printf(" --disable-simd Disable the post-MVP 128-bit SIMD feature:\n"); + printf(" currently 128-bit SIMD is only supported for x86-64 target,\n"); + printf(" and by default it is enabled in x86-64 target and disabled\n"); + printf(" in other targets\n"); + printf(" --enable-ref-types Enable the post-MVP reference types feature\n"); + printf(" --disable-aux-stack-check Disable auxiliary stack overflow/underflow check\n"); + printf(" --enable-dump-call-stack Enable stack trace feature\n"); + printf(" --enable-perf-profiling Enable function performance profiling\n"); + printf(" --enable-indirect-mode Enalbe call function through symbol table but not direct call\n"); + printf(" --disable-llvm-intrinsics Disable the LLVM built-in intrinsics\n"); + printf(" -v=n Set log verbose level (0 to 5, default is 2), larger with more log\n"); + printf("Examples: wamrc -o test.aot test.wasm\n"); + printf(" wamrc --target=i386 -o test.aot test.wasm\n"); + printf(" wamrc --target=i386 --format=object -o test.o test.wasm\n"); + return 1; } +/* clang-format on */ int main(int argc, char *argv[]) { - char *wasm_file_name = NULL, *out_file_name = NULL; - uint8 *wasm_file = NULL; - uint32 wasm_file_size; - 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; - bool sgx_mode = false; - - option.opt_level = 3; - option.size_level = 3; - option.output_format = AOT_FORMAT_FILE; - /* default value, enable or disable depends on the platform */ - option.bounds_checks = 2; - option.enable_simd = true; - option.enable_aux_stack_check = true; - - /* Process options. */ - for (argc--, argv++; argc > 0 && argv[0][0] == '-'; argc--, argv++) { - if (!strcmp(argv[0], "-o")) { - argc--, argv++; - if (argc < 2) - return print_help(); - out_file_name = argv[0]; - } - else if (!strncmp(argv[0], "--target=", 9)) { - if (argv[0][9] == '\0') - return print_help(); - option.target_arch = argv[0] + 9; - } - else if (!strncmp(argv[0], "--target-abi=", 13)) { - if (argv[0][13] == '\0') - return print_help(); - option.target_abi = argv[0] + 13; - } - else if (!strncmp(argv[0], "--cpu=", 6)) { - if (argv[0][6] == '\0') - return print_help(); - option.target_cpu = argv[0] + 6; - } - else if (!strncmp(argv[0], "--cpu-features=", 15)) { - if (argv[0][15] == '\0') - return print_help(); - option.cpu_features = argv[0] + 15; - } - else if (!strncmp(argv[0], "--opt-level=", 12)) { - if (argv[0][12] == '\0') - return print_help(); - option.opt_level = (uint32)atoi(argv[0] + 12); - if (option.opt_level > 3) - option.opt_level = 3; - } - else if (!strncmp(argv[0], "--size-level=", 13)) { - if (argv[0][13] == '\0') - return print_help(); - option.size_level = (uint32)atoi(argv[0] + 13); - if (option.size_level > 3) - option.size_level = 3; - } - else if (!strcmp(argv[0], "-sgx")) { - sgx_mode = true; - } - else if (!strncmp(argv[0], "--bounds-checks=", 16)) { - option.bounds_checks = (atoi(argv[0] + 16) == 1) ? 1 : 0; - } - else if (!strncmp(argv[0], "--format=", 9)) { - if (argv[0][9] == '\0') - return print_help(); - if (!strcmp(argv[0] + 9, "aot")) - option.output_format = AOT_FORMAT_FILE; - else if (!strcmp(argv[0] + 9, "object")) - option.output_format = AOT_OBJECT_FILE; - else if (!strcmp(argv[0] + 9, "llvmir-unopt")) - option.output_format = AOT_LLVMIR_UNOPT_FILE; - else if (!strcmp(argv[0] + 9, "llvmir-opt")) - option.output_format = AOT_LLVMIR_OPT_FILE; - else { - printf("Invalid format %s.\n", argv[0] + 9); - return print_help(); + char *wasm_file_name = NULL, *out_file_name = NULL; + uint8 *wasm_file = NULL; + uint32 wasm_file_size; + 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; + bool sgx_mode = false; + + option.opt_level = 3; + option.size_level = 3; + option.output_format = AOT_FORMAT_FILE; + /* default value, enable or disable depends on the platform */ + option.bounds_checks = 2; + option.enable_simd = true; + option.enable_aux_stack_check = true; + + /* Process options */ + for (argc--, argv++; argc > 0 && argv[0][0] == '-'; argc--, argv++) { + if (!strcmp(argv[0], "-o")) { + argc--, argv++; + if (argc < 2) + return print_help(); + out_file_name = argv[0]; } - } - else if (!strncmp(argv[0], "-v=", 3)) { - log_verbose_level = atoi(argv[0] + 3); - if (log_verbose_level < 0 || log_verbose_level > 5) + else if (!strncmp(argv[0], "--target=", 9)) { + if (argv[0][9] == '\0') + return print_help(); + option.target_arch = argv[0] + 9; + } + else if (!strncmp(argv[0], "--target-abi=", 13)) { + if (argv[0][13] == '\0') + return print_help(); + option.target_abi = argv[0] + 13; + } + else if (!strncmp(argv[0], "--cpu=", 6)) { + if (argv[0][6] == '\0') + return print_help(); + option.target_cpu = argv[0] + 6; + } + else if (!strncmp(argv[0], "--cpu-features=", 15)) { + if (argv[0][15] == '\0') + return print_help(); + option.cpu_features = argv[0] + 15; + } + else if (!strncmp(argv[0], "--opt-level=", 12)) { + if (argv[0][12] == '\0') + return print_help(); + option.opt_level = (uint32)atoi(argv[0] + 12); + if (option.opt_level > 3) + option.opt_level = 3; + } + else if (!strncmp(argv[0], "--size-level=", 13)) { + if (argv[0][13] == '\0') + return print_help(); + option.size_level = (uint32)atoi(argv[0] + 13); + if (option.size_level > 3) + option.size_level = 3; + } + else if (!strcmp(argv[0], "-sgx")) { + sgx_mode = true; + } + else if (!strncmp(argv[0], "--bounds-checks=", 16)) { + option.bounds_checks = (atoi(argv[0] + 16) == 1) ? 1 : 0; + } + else if (!strncmp(argv[0], "--format=", 9)) { + if (argv[0][9] == '\0') + return print_help(); + if (!strcmp(argv[0] + 9, "aot")) + option.output_format = AOT_FORMAT_FILE; + else if (!strcmp(argv[0] + 9, "object")) + option.output_format = AOT_OBJECT_FILE; + else if (!strcmp(argv[0] + 9, "llvmir-unopt")) + option.output_format = AOT_LLVMIR_UNOPT_FILE; + else if (!strcmp(argv[0] + 9, "llvmir-opt")) + option.output_format = AOT_LLVMIR_OPT_FILE; + else { + printf("Invalid format %s.\n", argv[0] + 9); + return print_help(); + } + } + else if (!strncmp(argv[0], "-v=", 3)) { + log_verbose_level = atoi(argv[0] + 3); + if (log_verbose_level < 0 || log_verbose_level > 5) + return print_help(); + } + else if (!strcmp(argv[0], "--enable-bulk-memory")) { + option.enable_bulk_memory = true; + } + else if (!strcmp(argv[0], "--enable-multi-thread")) { + option.enable_bulk_memory = true; + option.enable_thread_mgr = true; + } + else if (!strcmp(argv[0], "--enable-tail-call")) { + option.enable_tail_call = true; + } + else if (!strcmp(argv[0], "--enable-simd")) { + /* obsolete option, kept for compatibility */ + option.enable_simd = true; + } + else if (!strcmp(argv[0], "--disable-simd")) { + option.enable_simd = false; + } + else if (!strcmp(argv[0], "--enable-ref-types")) { + option.enable_ref_types = true; + } + else if (!strcmp(argv[0], "--disable-aux-stack-check")) { + option.enable_aux_stack_check = false; + } + else if (!strcmp(argv[0], "--enable-dump-call-stack")) { + option.enable_aux_stack_frame = true; + } + else if (!strcmp(argv[0], "--enable-perf-profiling")) { + option.enable_aux_stack_frame = true; + } + else if (!strcmp(argv[0], "--enable-indirect-mode")) { + option.is_indirect_mode = true; + } + else if (!strcmp(argv[0], "--disable-llvm-intrinsics")) { + option.disable_llvm_intrinsics = true; + } + else return print_help(); } - else if (!strcmp(argv[0], "--enable-bulk-memory")) { - option.enable_bulk_memory = true; - } - else if (!strcmp(argv[0], "--enable-multi-thread")) { - option.enable_bulk_memory = true; - option.enable_thread_mgr = true; - } - else if (!strcmp(argv[0], "--enable-tail-call")) { - option.enable_tail_call = true; - } - else if (!strcmp(argv[0], "--enable-simd")) { - /* obsolete option, kept for compatibility */ - option.enable_simd = true; - } - else if (!strcmp(argv[0], "--disable-simd")) { - option.enable_simd = false; - } - else if (!strcmp(argv[0], "--enable-ref-types")) { - option.enable_ref_types = true; - } - else if (!strcmp(argv[0], "--disable-aux-stack-check")) { - option.enable_aux_stack_check = false; - } - else if (!strcmp(argv[0], "--enable-dump-call-stack")) { - option.enable_aux_stack_frame = true; - } - else if (!strcmp(argv[0], "--enable-perf-profiling")) { - option.enable_aux_stack_frame = true; - } - else if (!strcmp(argv[0], "--enable-indirect-mode")) { - option.is_indirect_mode = true; - } - else if (!strcmp(argv[0], "--disable-llvm-intrinsics")) { - option.disable_llvm_intrinsics = true; - } - else - return print_help(); - } - if (argc == 0 || !out_file_name) - return print_help(); + if (argc == 0 || !out_file_name) + return print_help(); - if (sgx_mode) { - option.size_level = 1; - option.is_sgx_platform = true; - } + if (sgx_mode) { + option.size_level = 1; + option.is_sgx_platform = true; + } #if WASM_ENABLE_REF_TYPES != 0 - wasm_set_ref_types_flag(option.enable_ref_types); + wasm_set_ref_types_flag(option.enable_ref_types); #endif - wasm_file_name = argv[0]; + wasm_file_name = argv[0]; - memset(&init_args, 0, sizeof(RuntimeInitArgs)); + 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; + 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_full_init(&init_args)) { - printf("Init runtime environment failed.\n"); - return -1; - } + /* initialize runtime environment */ + if (!wasm_runtime_full_init(&init_args)) { + printf("Init runtime environment failed.\n"); + return -1; + } - bh_log_set_verbose_level(log_verbose_level); + bh_log_set_verbose_level(log_verbose_level); - bh_print_time("Begin to load wasm file"); + bh_print_time("Begin to load wasm file"); - /* load WASM byte buffer from WASM bin file */ - if (!(wasm_file = (uint8*) - bh_read_file_to_buffer(wasm_file_name, &wasm_file_size))) - goto fail1; + /* load WASM byte buffer from WASM bin file */ + if (!(wasm_file = + (uint8 *)bh_read_file_to_buffer(wasm_file_name, &wasm_file_size))) + goto fail1; - /* load WASM module */ - if (!(wasm_module = wasm_runtime_load(wasm_file, wasm_file_size, - error_buf, sizeof(error_buf)))) { - printf("%s\n", error_buf); - goto fail2; - } + /* load WASM module */ + if (!(wasm_module = wasm_runtime_load(wasm_file, wasm_file_size, error_buf, + sizeof(error_buf)))) { + printf("%s\n", error_buf); + goto fail2; + } - if (!(comp_data = aot_create_comp_data(wasm_module))) { - printf("%s\n", aot_get_last_error()); - goto fail3; - } + if (!(comp_data = aot_create_comp_data(wasm_module))) { + printf("%s\n", aot_get_last_error()); + goto fail3; + } #if WASM_ENABLE_DEBUG_AOT != 0 - if (!create_dwarf_extractor(comp_data, wasm_file_name)) { - printf("%s:create dwarf extractor failed\n", wasm_file_name); - } + if (!create_dwarf_extractor(comp_data, wasm_file_name)) { + printf("%s:create dwarf extractor failed\n", wasm_file_name); + } #endif - bh_print_time("Begin to create compile context"); - - if (!(comp_ctx = aot_create_comp_context(comp_data, - &option))) { - printf("%s\n", aot_get_last_error()); - goto fail4; - } - - bh_print_time("Begin to compile"); - - if (!aot_compile_wasm(comp_ctx)) { - printf("%s\n", aot_get_last_error()); - goto fail5; - } - - switch (option.output_format) { - case AOT_LLVMIR_UNOPT_FILE: - case AOT_LLVMIR_OPT_FILE: - if (!aot_emit_llvm_file(comp_ctx, out_file_name)) { - printf("%s\n", aot_get_last_error()); - goto fail5; - } - break; - case AOT_OBJECT_FILE: - if (!aot_emit_object_file(comp_ctx, out_file_name)) { - printf("%s\n", aot_get_last_error()); - goto fail5; - } - break; - case AOT_FORMAT_FILE: - if (!aot_emit_aot_file(comp_ctx, comp_data, out_file_name)) { - printf("%s\n", aot_get_last_error()); - goto fail5; - } - break; - default: - break; - } - - bh_print_time("Compile end"); - - printf("Compile success, file %s was generated.\n", out_file_name); + bh_print_time("Begin to create compile context"); + + if (!(comp_ctx = aot_create_comp_context(comp_data, &option))) { + printf("%s\n", aot_get_last_error()); + goto fail4; + } + + bh_print_time("Begin to compile"); + + if (!aot_compile_wasm(comp_ctx)) { + printf("%s\n", aot_get_last_error()); + goto fail5; + } + + switch (option.output_format) { + case AOT_LLVMIR_UNOPT_FILE: + case AOT_LLVMIR_OPT_FILE: + if (!aot_emit_llvm_file(comp_ctx, out_file_name)) { + printf("%s\n", aot_get_last_error()); + goto fail5; + } + break; + case AOT_OBJECT_FILE: + if (!aot_emit_object_file(comp_ctx, out_file_name)) { + printf("%s\n", aot_get_last_error()); + goto fail5; + } + break; + case AOT_FORMAT_FILE: + if (!aot_emit_aot_file(comp_ctx, comp_data, out_file_name)) { + printf("%s\n", aot_get_last_error()); + goto fail5; + } + break; + default: + break; + } + + bh_print_time("Compile end"); + + printf("Compile success, file %s was generated.\n", out_file_name); fail5: - /* Destroy compiler context */ - aot_destroy_comp_context(comp_ctx); + /* Destroy compiler context */ + aot_destroy_comp_context(comp_ctx); fail4: - /* Destroy compile data */ - aot_destroy_comp_data(comp_data); + /* Destroy compile data */ + aot_destroy_comp_data(comp_data); fail3: - /* Unload WASM module */ - wasm_runtime_unload(wasm_module); + /* Unload WASM module */ + wasm_runtime_unload(wasm_module); fail2: - /* free the file buffer */ - wasm_runtime_free(wasm_file); + /* free the file buffer */ + wasm_runtime_free(wasm_file); fail1: - /* Destroy runtime environment */ - wasm_runtime_destroy(); + /* Destroy runtime environment */ + wasm_runtime_destroy(); - bh_print_time("wamrc return"); - return 0; + bh_print_time("wamrc return"); + return 0; } - From beaaf524c9f8bf3b61d056f29ed53e5c734d21e0 Mon Sep 17 00:00:00 2001 From: Wenyong Huang Date: Fri, 22 Oct 2021 23:53:33 +0800 Subject: [PATCH 5/8] Enable auto install wasi-sdk when build wamr-sdk And fix host_tool help show issue. --- test-tools/host-tool/src/main.c | 2 +- wamr-sdk/build_sdk.sh | 19 ++++++++++--------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/test-tools/host-tool/src/main.c b/test-tools/host-tool/src/main.c index 7db2f56143..f08e9490e9 100644 --- a/test-tools/host-tool/src/main.c +++ b/test-tools/host-tool/src/main.c @@ -391,7 +391,7 @@ static void showUsage() " [--watchdog=]\n" " [ ...] \n"); printf(" host_tool -u [ ...]\n"); - printf(" host_tool -q [] [ ...]\n"); + printf(" host_tool -q[] [ ...]\n"); printf(" host_tool -r -A [-p ] [ ...]\n"); printf(" host_tool -s [ ...]\n"); printf(" host_tool -d [ ...]\n"); diff --git a/wamr-sdk/build_sdk.sh b/wamr-sdk/build_sdk.sh index 0b819c5dbf..e592c2cd2a 100755 --- a/wamr-sdk/build_sdk.sh +++ b/wamr-sdk/build_sdk.sh @@ -65,14 +65,12 @@ done if [ ! -f "/opt/wasi-sdk/bin/clang" ]; then - echo "Can't find wasi-sdk under /opt/wasi-sdk" - echo "You can download wasi-sdk from here:" - echo "" - echo "https://github.com/CraneStation/wasi-sdk/releases/tag/wasi-sdk-7" - echo "" - echo "please install it to the default path for your convenience" - echo "" - exit 1 + echo "Intall wasi-sdk.." && + rm -fr wasi-sdk-* /opt/wasi-sdk && + wget https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-12/wasi-sdk-12.0-linux.tar.gz && + tar -zxf wasi-sdk-12.0-linux.tar.gz && + mv wasi-sdk-12.0 /opt/wasi-sdk && + rm -f wasi-sdk-12.0-linux.tar.gz fi @@ -190,7 +188,10 @@ if [ -n "$out" ]; then fi if [ "${LIBC_SUPPORT}" = "WASI" ]; then echo "using wasi toolchain" - cmake .. $CM_DEXTRA_SDK_INCLUDE_PATH -DWAMR_BUILD_SDK_PROFILE=${PROFILE} -DCONFIG_PATH=${wamr_config_cmake_file} -DCMAKE_TOOLCHAIN_FILE=../wasi_toolchain.cmake + cmake .. $CM_DEXTRA_SDK_INCLUDE_PATH \ + -DWAMR_BUILD_SDK_PROFILE=${PROFILE} \ + -DCONFIG_PATH=${wamr_config_cmake_file} \ + -DCMAKE_TOOLCHAIN_FILE=../wasi_toolchain.cmake else echo "using builtin libc toolchain" cmake .. $CM_DEXTRA_SDK_INCLUDE_PATH \ From 6e1f4c95dfd010668f9ee6a53de85210079b85bc Mon Sep 17 00:00:00 2001 From: Wenyong Huang Date: Sat, 30 Oct 2021 16:52:06 +0800 Subject: [PATCH 6/8] Fix workflow issue, fix dockerfile bug, refine code format --- .github/workflows/spec_test.yml | 2 +- ci/Dockerfile | 4 ++-- core/iwasm/libraries/libc-builtin/libc_builtin_wrapper.c | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/spec_test.yml b/.github/workflows/spec_test.yml index cab196966c..18a211adf2 100644 --- a/.github/workflows/spec_test.yml +++ b/.github/workflows/spec_test.yml @@ -34,7 +34,7 @@ concurrency: env: DEFAULT_TEST_OPTIONS: "-s spec" - LLVM_CACHE_SUFFIX: "build-llvm_libraries" + LLVM_CACHE_SUFFIX: "build-llvm_libraries_ex" MULTI_MODULES_TEST_OPTIONS: "-s spec -M" SIMD_TEST_OPTIONS: "-s spec -S" THREADS_TEST_OPTIONS: "-s spec -p" diff --git a/ci/Dockerfile b/ci/Dockerfile index 51a0deb4cc..f90e4cc7cc 100644 --- a/ci/Dockerfile +++ b/ci/Dockerfile @@ -1,7 +1,7 @@ # Copyright (C) 2019 Intel Corporation. All rights reserved. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -ARG VARIANT=need_to_assign +ARG VARIANT=focal FROM ubuntu:${VARIANT} ARG DEBIAN_FRONTEND=noninteractive @@ -13,7 +13,7 @@ RUN apt update \ libgcc-9-dev lib32gcc-9-dev lsb-release \ ninja-build ocaml ocamlbuild python2.7 \ software-properties-common tree tzdata \ - unzip url valgrind vim wget zip + unzip valgrind vim wget zip # # CMAKE (https://apt.kitware.com/) diff --git a/core/iwasm/libraries/libc-builtin/libc_builtin_wrapper.c b/core/iwasm/libraries/libc-builtin/libc_builtin_wrapper.c index 979e6e6cd4..11362f1201 100644 --- a/core/iwasm/libraries/libc-builtin/libc_builtin_wrapper.c +++ b/core/iwasm/libraries/libc-builtin/libc_builtin_wrapper.c @@ -1128,10 +1128,10 @@ print_f64_wrapper(wasm_exec_env_t exec_env, double f64) } #endif /* WASM_ENABLE_SPEC_TEST */ +/* clang-format off */ #define REG_NATIVE_FUNC(func_name, signature) \ - { \ -#func_name, func_name##_wrapper, signature, NULL \ - } + { #func_name, func_name##_wrapper, signature, NULL } +/* clang-format on */ static NativeSymbol native_symbols_libc_builtin[] = { REG_NATIVE_FUNC(printf, "($*)i"), From d44e6b0219a2ad4b336430548dd4c7195764da96 Mon Sep 17 00:00:00 2001 From: Wenyong Huang Date: Sat, 30 Oct 2021 16:57:42 +0800 Subject: [PATCH 7/8] Refine code format --- core/iwasm/libraries/libc-builtin/libc_builtin_wrapper.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/iwasm/libraries/libc-builtin/libc_builtin_wrapper.c b/core/iwasm/libraries/libc-builtin/libc_builtin_wrapper.c index 11362f1201..d7387804ba 100644 --- a/core/iwasm/libraries/libc-builtin/libc_builtin_wrapper.c +++ b/core/iwasm/libraries/libc-builtin/libc_builtin_wrapper.c @@ -1129,7 +1129,7 @@ print_f64_wrapper(wasm_exec_env_t exec_env, double f64) #endif /* WASM_ENABLE_SPEC_TEST */ /* clang-format off */ -#define REG_NATIVE_FUNC(func_name, signature) \ +#define REG_NATIVE_FUNC(func_name, signature) \ { #func_name, func_name##_wrapper, signature, NULL } /* clang-format on */ From 13bdd8c0c34f4980ef633ac4198962a8f7e31a58 Mon Sep 17 00:00:00 2001 From: Wenyong Huang Date: Sun, 31 Oct 2021 03:24:44 +0800 Subject: [PATCH 8/8] Build projets in wamr-test-suites with multiple cores --- tests/wamr-test-suites/test_wamr.sh | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/wamr-test-suites/test_wamr.sh b/tests/wamr-test-suites/test_wamr.sh index f1dac72db9..ca34c62873 100755 --- a/tests/wamr-test-suites/test_wamr.sh +++ b/tests/wamr-test-suites/test_wamr.sh @@ -208,7 +208,7 @@ function unit_test() # keep going and do not care if it is success or not make -ki clean | true - cmake ${compile_flag} ${WORK_DIR}/../../unit && make + cmake ${compile_flag} ${WORK_DIR}/../../unit && make -j 4 if [ "$?" != 0 ];then echo -e "\033[31mbuild unit test failed, you may need to change wamr into dev/aot branch and ensure llvm is built \033[0m" exit 1 @@ -311,7 +311,7 @@ function spec_test() echo "compile the reference intepreter" pushd interpreter - make opt + make opt -j 4 popd git apply ../../spec-test-script/simd_ignore_cases.patch @@ -359,7 +359,7 @@ function spec_test() git pull git reset --hard origin/main cd .. - make -C wabt gcc-release + make -C wabt gcc-release -j 4 fi ln -sf ${WORK_DIR}/../spec-test-script/all.sh . @@ -473,7 +473,7 @@ function build_iwasm_with_cfg() && if [ -d build ]; then rm -rf build/*; else mkdir build; fi \ && cd build \ && cmake $* .. \ - && make + && make -j 4 cd ${WAMR_DIR}/product-mini/platforms/linux-sgx/enclave-sample \ && make clean \ && make SPEC_TEST=1 @@ -482,7 +482,7 @@ function build_iwasm_with_cfg() && if [ -d build ]; then rm -rf build/*; else mkdir build; fi \ && cd build \ && cmake $* .. \ - && make + && make -j 4 fi if [ "$?" != 0 ];then @@ -506,7 +506,7 @@ function build_wamrc() && if [ -d build ]; then rm -r build/*; else mkdir build; fi \ && cd build \ && cmake .. \ - && make + && make -j 4 } ### Need to add a test suite?