Merge pull request #1855 from bytecodealliance/main

Merge branch main into dev/exce_handling
This commit is contained in:
Wenyong Huang 2023-01-04 09:46:18 +08:00 committed by GitHub
commit bbce8402af
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
46 changed files with 1081 additions and 527 deletions

View File

@ -50,7 +50,7 @@ jobs:
./core/deps/llvm-project/build/libexec ./core/deps/llvm-project/build/libexec
./core/deps/llvm-project/build/share ./core/deps/llvm-project/build/share
./core/deps/llvm-project/lldb/tools/ ./core/deps/llvm-project/lldb/tools/
./core/deps/llvm-project/inst/ ./core/deps/llvm-project/wamr-lldb/
key: ${{inputs.arch}}-${{ inputs.runner }}-lldb_build key: ${{inputs.arch}}-${{ inputs.runner }}-lldb_build
- name: setup xcode macos - name: setup xcode macos
@ -92,10 +92,10 @@ jobs:
if: steps.lldb_build_cache.outputs.cache-hit != 'true' && contains(inputs.runner, 'ubuntu') if: steps.lldb_build_cache.outputs.cache-hit != 'true' && contains(inputs.runner, 'ubuntu')
run: | run: |
echo "start to build lldb..." echo "start to build lldb..."
mkdir -p inst mkdir -p wamr-lldb
cmake -S ./llvm -B build \ cmake -S ./llvm -B build \
-G Ninja \ -G Ninja \
-DCMAKE_INSTALL_PREFIX=../inst \ -DCMAKE_INSTALL_PREFIX=../wamr-lldb \
-DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_PROJECTS="clang;lldb" \ -DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_PROJECTS="clang;lldb" \
-DLLVM_TARGETS_TO_BUILD=X86 \ -DLLVM_TARGETS_TO_BUILD=X86 \
-DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DLLVM_BUILD_BENCHMARKS:BOOL=OFF \ -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DLLVM_BUILD_BENCHMARKS:BOOL=OFF \
@ -111,10 +111,10 @@ jobs:
if: steps.lldb_build_cache.outputs.cache-hit != 'true' && contains(inputs.runner, 'macos') if: steps.lldb_build_cache.outputs.cache-hit != 'true' && contains(inputs.runner, 'macos')
run: | run: |
echo "start to build lldb..." echo "start to build lldb..."
mkdir -p inst mkdir -p wamr-lldb
cmake -S ./llvm -B build \ cmake -S ./llvm -B build \
-G Ninja \ -G Ninja \
-DCMAKE_INSTALL_PREFIX=../inst \ -DCMAKE_INSTALL_PREFIX=../wamr-lldb \
-DCMAKE_BUILD_TYPE:STRING="Release" \ -DCMAKE_BUILD_TYPE:STRING="Release" \
-DCMAKE_EXPORT_COMPILE_COMMANDS=ON \ -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
-DLLVM_ENABLE_PROJECTS="clang;lldb" \ -DLLVM_ENABLE_PROJECTS="clang;lldb" \
@ -134,30 +134,30 @@ jobs:
- name: pack a distribution - name: pack a distribution
if: steps.lldb_build_cache.outputs.cache-hit != 'true' if: steps.lldb_build_cache.outputs.cache-hit != 'true'
run: | run: |
mkdir -p inst/bin mkdir -p wamr-lldb/bin
mkdir -p inst/lib mkdir -p wamr-lldb/lib
cp build/bin/lldb* inst/bin cp build/bin/lldb* wamr-lldb/bin
cp lldb/tools/lldb-vscode/package.json inst cp lldb/tools/lldb-vscode/package.json wamr-lldb
cp -r lldb/tools/lldb-vscode/syntaxes/ inst cp -r lldb/tools/lldb-vscode/syntaxes/ wamr-lldb
working-directory: core/deps/llvm-project working-directory: core/deps/llvm-project
- name: pack ubuntu specific libraries - name: pack ubuntu specific libraries
if: steps.lldb_build_cache.outputs.cache-hit != 'true' && contains(inputs.runner, 'ubuntu') if: steps.lldb_build_cache.outputs.cache-hit != 'true' && contains(inputs.runner, 'ubuntu')
run: | run: |
cp build/lib/liblldb*.so inst/lib cp build/lib/liblldb*.so wamr-lldb/lib
cp build/lib/liblldb*.so.* inst/lib cp build/lib/liblldb*.so.* wamr-lldb/lib
working-directory: core/deps/llvm-project working-directory: core/deps/llvm-project
- name: pack macos specific libraries - name: pack macos specific libraries
if: steps.lldb_build_cache.outputs.cache-hit != 'true' && contains(inputs.runner, 'macos') if: steps.lldb_build_cache.outputs.cache-hit != 'true' && contains(inputs.runner, 'macos')
run: | run: |
cp build/lib/liblldb*.dylib inst/lib cp build/lib/liblldb*.dylib wamr-lldb/lib
working-directory: core/deps/llvm-project working-directory: core/deps/llvm-project
- name: compress the binary - name: compress the binary
run: | run: |
tar czf wamr-lldb-${{ inputs.ver_num }}-${{ inputs.runner }}.tar.gz inst tar czf wamr-lldb-${{ inputs.ver_num }}-${{ inputs.runner }}.tar.gz wamr-lldb
zip -r wamr-lldb-${{ inputs.ver_num }}-${{ inputs.runner }}.zip inst zip -r wamr-lldb-${{ inputs.ver_num }}-${{ inputs.runner }}.zip wamr-lldb
working-directory: core/deps/llvm-project working-directory: core/deps/llvm-project
- name: upload release tar.gz - name: upload release tar.gz

View File

@ -41,8 +41,9 @@ jobs:
- name: compress the vscode extension - name: compress the vscode extension
run: | run: |
tar czf wamr_ide-${{ inputs.ver_num }}.tar.gz wamride-*.vsix mv wamride-*.vsix wamr-ide.vsix
zip wamr_ide-${{ inputs.ver_num }}.zip wamride-*.vsix tar czf wamr-ide-${{ inputs.ver_num }}.tar.gz wamr-ide.vsix
zip wamr-ide-${{ inputs.ver_num }}.zip wamr-ide.vsix
working-directory: test-tools/wamr-ide/VSCode-Extension working-directory: test-tools/wamr-ide/VSCode-Extension
- name: upload release tar.gz - name: upload release tar.gz
@ -51,8 +52,8 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with: with:
upload_url: ${{ inputs.upload_url }} upload_url: ${{ inputs.upload_url }}
asset_path: test-tools/wamr-ide/VSCode-Extension/wamr_ide-${{ inputs.ver_num }}.tar.gz asset_path: test-tools/wamr-ide/VSCode-Extension/wamr-ide-${{ inputs.ver_num }}.tar.gz
asset_name: wamr_ide-${{ inputs.ver_num }}.tar.gz asset_name: wamr-ide-${{ inputs.ver_num }}.tar.gz
asset_content_type: application/x-gzip asset_content_type: application/x-gzip
- name: upload release zip - name: upload release zip
@ -61,6 +62,6 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with: with:
upload_url: ${{ inputs.upload_url }} upload_url: ${{ inputs.upload_url }}
asset_path: test-tools/wamr-ide/VSCode-Extension/wamr_ide-${{ inputs.ver_num }}.zip asset_path: test-tools/wamr-ide/VSCode-Extension/wamr-ide-${{ inputs.ver_num }}.zip
asset_name: wamr_ide-${{ inputs.ver_num }}.zip asset_name: wamr-ide-${{ inputs.ver_num }}.zip
asset_content_type: application/zip asset_content_type: application/zip

View File

@ -9,11 +9,21 @@ on:
workflow_dispatch: workflow_dispatch:
env:
LLVM_CACHE_SUFFIX: "build-llvm_libraries_ex"
jobs: jobs:
build_llvm_libraries:
uses: ./.github/workflows/build_llvm_libraries.yml
with:
runs-on: "['ubuntu-22.04']"
spec_test_on_qemu: spec_test_on_qemu:
runs-on: ubuntu-22.04 runs-on: ${{ matrix.os }}
needs: [build_llvm_libraries]
strategy: strategy:
matrix: matrix:
os: [ubuntu-22.04]
nuttx_board_config: [ nuttx_board_config: [
# cortex-a9 # cortex-a9
"boards/arm/imx6/sabre-6quad/configs/nsh", "boards/arm/imx6/sabre-6quad/configs/nsh",
@ -61,6 +71,25 @@ jobs:
repository: ${{ github.repository }} repository: ${{ github.repository }}
path: apps/interpreters/wamr/wamr path: apps/interpreters/wamr/wamr
- name: Get LLVM libraries
id: cache_llvm
uses: actions/cache@v3
with:
path: |
./core/deps/llvm/build/bin
./core/deps/llvm/build/include
./core/deps/llvm/build/lib
./core/deps/llvm/build/libexec
./core/deps/llvm/build/share
key: ${{ matrix.os }}-${{ env.LLVM_CACHE_SUFFIX }}
- name: Quit if cache miss
if: steps.cache_llvm.outputs.cache-hit != 'true'
run: echo "::error::can not get prebuilt llvm libraries" && exit 1
- name: Copy LLVM
run: cp -r core/deps/llvm apps/interpreters/wamr/wamr/core/deps/llvm
- name: Enable WAMR for NuttX - name: Enable WAMR for NuttX
run: | run: |
find nuttx/boards -name defconfig | xargs sed -i '$a\CONFIG_INTERPRETERS_WAMR=y\nCONFIG_INTERPRETERS_WAMR_AOT=y\nCONFIG_INTERPRETERS_WAMR_FAST=y\nCONFIG_INTERPRETERS_WAMR_LOG=y\nCONFIG_INTERPRETERS_WAMR_LIBC_BUILTIN=y\nCONFIG_INTERPRETERS_WAMR_REF_TYPES=y\nCONFIG_INTERPRETERS_WAMR_ENABLE_SPEC_TEST=y\nCONFIG_INTERPRETERS_WAMR_SHARED_MEMORY=y\nCONFIG_INTERPRETERS_WAMR_BULK_MEMORY=y\n' find nuttx/boards -name defconfig | xargs sed -i '$a\CONFIG_INTERPRETERS_WAMR=y\nCONFIG_INTERPRETERS_WAMR_AOT=y\nCONFIG_INTERPRETERS_WAMR_FAST=y\nCONFIG_INTERPRETERS_WAMR_LOG=y\nCONFIG_INTERPRETERS_WAMR_LIBC_BUILTIN=y\nCONFIG_INTERPRETERS_WAMR_REF_TYPES=y\nCONFIG_INTERPRETERS_WAMR_ENABLE_SPEC_TEST=y\nCONFIG_INTERPRETERS_WAMR_SHARED_MEMORY=y\nCONFIG_INTERPRETERS_WAMR_BULK_MEMORY=y\n'
@ -69,8 +98,7 @@ jobs:
- name: Build wamrc - name: Build wamrc
working-directory: apps/interpreters/wamr/wamr/wamr-compiler working-directory: apps/interpreters/wamr/wamr/wamr-compiler
run: | run: |
sudo apt install llvm-13-dev cmake -Bbuild .
cmake -Bbuild -DWAMR_BUILD_WITH_CUSTOM_LLVM=1 .
cmake --build build cmake --build build
- name: Build - name: Build

View File

@ -58,6 +58,8 @@ static const aot_intrinsic g_intrinsic_mapping[] = {
{ "i32_trunc_f64_u", "aot_intrinsic_f64_to_u32", AOT_INTRINSIC_FLAG_F64_TO_U32 }, { "i32_trunc_f64_u", "aot_intrinsic_f64_to_u32", AOT_INTRINSIC_FLAG_F64_TO_U32 },
{ "i32_trunc_f64_s", "aot_intrinsic_f64_to_i32", AOT_INTRINSIC_FLAG_F64_TO_I32 }, { "i32_trunc_f64_s", "aot_intrinsic_f64_to_i32", AOT_INTRINSIC_FLAG_F64_TO_I32 },
{ "i64_trunc_f64_u", "aot_intrinsic_f64_to_u64", AOT_INTRINSIC_FLAG_F64_TO_U64 }, { "i64_trunc_f64_u", "aot_intrinsic_f64_to_u64", AOT_INTRINSIC_FLAG_F64_TO_U64 },
{ "i64_trunc_f32_s", "aot_intrinsic_f32_to_i64", AOT_INTRINSIC_FLAG_F32_TO_I64 },
{ "i64_trunc_f32_u", "aot_intrinsic_f32_to_u64", AOT_INTRINSIC_FLAG_F32_TO_U64 },
{ "i64_trunc_f64_s", "aot_intrinsic_f64_to_i64", AOT_INTRINSIC_FLAG_F64_TO_I64 }, { "i64_trunc_f64_s", "aot_intrinsic_f64_to_i64", AOT_INTRINSIC_FLAG_F64_TO_I64 },
{ "f32_demote_f64", "aot_intrinsic_f64_to_f32", AOT_INTRINSIC_FLAG_F64_TO_F32 }, { "f32_demote_f64", "aot_intrinsic_f64_to_f32", AOT_INTRINSIC_FLAG_F64_TO_F32 },
{ "f64_promote_f32", "aot_intrinsic_f32_to_f64", AOT_INTRINSIC_FLAG_F32_TO_F64 }, { "f64_promote_f32", "aot_intrinsic_f32_to_f64", AOT_INTRINSIC_FLAG_F32_TO_F64 },
@ -134,7 +136,7 @@ aot_intrinsic_fdiv_f64(float64 a, float64 b)
float32 float32
aot_intrinsic_fabs_f32(float32 a) aot_intrinsic_fabs_f32(float32 a)
{ {
return (float32)fabs(a); return fabsf(a);
} }
float64 float64
@ -146,7 +148,7 @@ aot_intrinsic_fabs_f64(float64 a)
float32 float32
aot_intrinsic_ceil_f32(float32 a) aot_intrinsic_ceil_f32(float32 a)
{ {
return (float32)ceilf(a); return ceilf(a);
} }
float64 float64
@ -158,7 +160,7 @@ aot_intrinsic_ceil_f64(float64 a)
float32 float32
aot_intrinsic_floor_f32(float32 a) aot_intrinsic_floor_f32(float32 a)
{ {
return (float32)floorf(a); return floorf(a);
} }
float64 float64
@ -170,7 +172,7 @@ aot_intrinsic_floor_f64(float64 a)
float32 float32
aot_intrinsic_trunc_f32(float32 a) aot_intrinsic_trunc_f32(float32 a)
{ {
return (float32)trunc(a); return truncf(a);
} }
float64 float64
@ -182,7 +184,7 @@ aot_intrinsic_trunc_f64(float64 a)
float32 float32
aot_intrinsic_rint_f32(float32 a) aot_intrinsic_rint_f32(float32 a)
{ {
return (float32)rint(a); return rintf(a);
} }
float64 float64
@ -194,7 +196,7 @@ aot_intrinsic_rint_f64(float64 a)
float32 float32
aot_intrinsic_sqrt_f32(float32 a) aot_intrinsic_sqrt_f32(float32 a)
{ {
return (float32)sqrt(a); return sqrtf(a);
} }
float64 float64
@ -206,7 +208,7 @@ aot_intrinsic_sqrt_f64(float64 a)
float32 float32
aot_intrinsic_copysign_f32(float32 a, float32 b) aot_intrinsic_copysign_f32(float32 a, float32 b)
{ {
return signbit(b) ? (float32)-fabs(a) : (float32)fabs(a); return signbit(b) ? -fabsf(a) : fabsf(a);
} }
float64 float64
@ -218,41 +220,45 @@ aot_intrinsic_copysign_f64(float64 a, float64 b)
float32 float32
aot_intrinsic_fmin_f32(float32 a, float32 b) aot_intrinsic_fmin_f32(float32 a, float32 b)
{ {
if (isnan(a)) if (isnan(a) || isnan(b))
return a; return NAN;
else if (isnan(b)) else if (a == 0 && a == b)
return b; return signbit(a) ? a : b;
else else
return (float32)fmin(a, b); return a > b ? b : a;
} }
float64 float64
aot_intrinsic_fmin_f64(float64 a, float64 b) aot_intrinsic_fmin_f64(float64 a, float64 b)
{ {
float64 c = fmin(a, b); if (isnan(a) || isnan(b))
if (c == 0 && a == b) return NAN;
else if (a == 0 && a == b)
return signbit(a) ? a : b; return signbit(a) ? a : b;
return c; else
return a > b ? b : a;
} }
float32 float32
aot_intrinsic_fmax_f32(float32 a, float32 b) aot_intrinsic_fmax_f32(float32 a, float32 b)
{ {
if (isnan(a)) if (isnan(a) || isnan(b))
return a; return NAN;
else if (isnan(b)) else if (a == 0 && a == b)
return b; return signbit(a) ? b : a;
else else
return (float32)fmax(a, b); return a > b ? a : b;
} }
float64 float64
aot_intrinsic_fmax_f64(float64 a, float64 b) aot_intrinsic_fmax_f64(float64 a, float64 b)
{ {
float64 c = fmax(a, b); if (isnan(a) || isnan(b))
if (c == 0 && a == b) return NAN;
else if (a == 0 && a == b)
return signbit(a) ? b : a; return signbit(a) ? b : a;
return c; else
return a > b ? a : b;
} }
uint32 uint32
@ -442,7 +448,7 @@ aot_intrinsic_f32_cmp(AOTFloatCond cond, float32 lhs, float32 rhs)
{ {
switch (cond) { switch (cond) {
case FLOAT_EQ: case FLOAT_EQ:
return (float32)fabs(lhs - rhs) <= WA_FLT_EPSILON ? 1 : 0; return lhs == rhs ? 1 : 0;
case FLOAT_LT: case FLOAT_LT:
return lhs < rhs ? 1 : 0; return lhs < rhs ? 1 : 0;
@ -473,7 +479,7 @@ aot_intrinsic_f64_cmp(AOTFloatCond cond, float64 lhs, float64 rhs)
{ {
switch (cond) { switch (cond) {
case FLOAT_EQ: case FLOAT_EQ:
return fabs(lhs - rhs) <= WA_DBL_EPSILON ? 1 : 0; return lhs == rhs ? 1 : 0;
case FLOAT_LT: case FLOAT_LT:
return lhs < rhs ? 1 : 0; return lhs < rhs ? 1 : 0;
@ -631,6 +637,12 @@ add_f64_common_intrinsics(AOTCompContext *comp_ctx)
add_intrinsic_capability(comp_ctx, AOT_INTRINSIC_FLAG_F64_FADD); add_intrinsic_capability(comp_ctx, AOT_INTRINSIC_FLAG_F64_FADD);
add_intrinsic_capability(comp_ctx, AOT_INTRINSIC_FLAG_F64_FSUB); add_intrinsic_capability(comp_ctx, AOT_INTRINSIC_FLAG_F64_FSUB);
add_intrinsic_capability(comp_ctx, AOT_INTRINSIC_FLAG_F64_FMUL); add_intrinsic_capability(comp_ctx, AOT_INTRINSIC_FLAG_F64_FMUL);
add_intrinsic_capability(comp_ctx, AOT_INTRINSIC_FLAG_F64_MIN);
add_intrinsic_capability(comp_ctx, AOT_INTRINSIC_FLAG_F64_MAX);
add_intrinsic_capability(comp_ctx, AOT_INTRINSIC_FLAG_F64_CEIL);
add_intrinsic_capability(comp_ctx, AOT_INTRINSIC_FLAG_F64_FLOOR);
add_intrinsic_capability(comp_ctx, AOT_INTRINSIC_FLAG_F64_TRUNC);
add_intrinsic_capability(comp_ctx, AOT_INTRINSIC_FLAG_F64_RINT);
add_intrinsic_capability(comp_ctx, AOT_INTRINSIC_FLAG_F64_FDIV); add_intrinsic_capability(comp_ctx, AOT_INTRINSIC_FLAG_F64_FDIV);
add_intrinsic_capability(comp_ctx, AOT_INTRINSIC_FLAG_F64_SQRT); add_intrinsic_capability(comp_ctx, AOT_INTRINSIC_FLAG_F64_SQRT);
add_intrinsic_capability(comp_ctx, AOT_INTRINSIC_FLAG_F64_CMP); add_intrinsic_capability(comp_ctx, AOT_INTRINSIC_FLAG_F64_CMP);

View File

@ -101,6 +101,8 @@ typedef struct {
REG_SYM(aot_intrinsic_f64_to_f32), \ REG_SYM(aot_intrinsic_f64_to_f32), \
REG_SYM(aot_intrinsic_f32_to_i32), \ REG_SYM(aot_intrinsic_f32_to_i32), \
REG_SYM(aot_intrinsic_f32_to_u32), \ REG_SYM(aot_intrinsic_f32_to_u32), \
REG_SYM(aot_intrinsic_f32_to_i64), \
REG_SYM(aot_intrinsic_f32_to_u64), \
REG_SYM(aot_intrinsic_f64_to_i32), \ REG_SYM(aot_intrinsic_f64_to_i32), \
REG_SYM(aot_intrinsic_f64_to_u32), \ REG_SYM(aot_intrinsic_f64_to_u32), \
REG_SYM(aot_intrinsic_f64_to_i64), \ REG_SYM(aot_intrinsic_f64_to_i64), \

View File

@ -20,6 +20,7 @@ void __adddf3();
void __addsf3(); void __addsf3();
void __divdi3(); void __divdi3();
void __divsi3(); void __divsi3();
void __divdf3();
void __divsf3(); void __divsf3();
void __eqsf2(); void __eqsf2();
void __eqdf2(); void __eqdf2();
@ -42,9 +43,12 @@ void __floatunsisf();
void __floatunsidf(); void __floatunsidf();
void __gedf2(); void __gedf2();
void __gesf2(); void __gesf2();
void __gtdf2();
void __gtsf2(); void __gtsf2();
void __ledf2(); void __ledf2();
void __lesf2(); void __lesf2();
void __ltdf2();
void __ltsf2();
void __moddi3(); void __moddi3();
void __modsi3(); void __modsi3();
void __muldf3(); void __muldf3();
@ -70,12 +74,16 @@ static SymbolMap target_sym_map[] = {
#ifndef __riscv_flen #ifndef __riscv_flen
REG_SYM(__adddf3), REG_SYM(__adddf3),
REG_SYM(__addsf3), REG_SYM(__addsf3),
REG_SYM(__divdf3),
REG_SYM(__divsf3), REG_SYM(__divsf3),
REG_SYM(__gedf2), REG_SYM(__gedf2),
REG_SYM(__gesf2), REG_SYM(__gesf2),
REG_SYM(__gtdf2),
REG_SYM(__gtsf2), REG_SYM(__gtsf2),
REG_SYM(__ledf2), REG_SYM(__ledf2),
REG_SYM(__lesf2), REG_SYM(__lesf2),
REG_SYM(__ltdf2),
REG_SYM(__ltsf2),
REG_SYM(__muldf3), REG_SYM(__muldf3),
REG_SYM(__nedf2), REG_SYM(__nedf2),
REG_SYM(__nesf2), REG_SYM(__nesf2),

View File

@ -3,6 +3,7 @@
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*/ */
#include "bh_log.h"
#include "wasm_c_api_internal.h" #include "wasm_c_api_internal.h"
#include "bh_assert.h" #include "bh_assert.h"
@ -275,10 +276,14 @@ WASM_DEFINE_VEC_OWN(store, wasm_store_delete)
WASM_DEFINE_VEC_OWN(valtype, wasm_valtype_delete) WASM_DEFINE_VEC_OWN(valtype, wasm_valtype_delete)
#ifndef NDEBUG #ifndef NDEBUG
#if WAMR_BUILD_MEMORY_PROFILING != 0
#define WASM_C_DUMP_PROC_MEM() LOG_PROC_MEM() #define WASM_C_DUMP_PROC_MEM() LOG_PROC_MEM()
#else #else
#define WASM_C_DUMP_PROC_MEM() (void)0 #define WASM_C_DUMP_PROC_MEM() (void)0
#endif #endif
#else
#define WASM_C_DUMP_PROC_MEM() (void)0
#endif
/* Runtime Environment */ /* Runtime Environment */
own wasm_config_t * own wasm_config_t *
@ -1628,6 +1633,8 @@ wasm_val_to_rt_val(WASMModuleInstanceCommon *inst_comm_rt, uint8 val_type_rt,
ret = ret =
wasm_externref_obj2ref(inst_comm_rt, v->of.ref, (uint32 *)data); wasm_externref_obj2ref(inst_comm_rt, v->of.ref, (uint32 *)data);
break; break;
#else
(void)inst_comm_rt;
#endif #endif
default: default:
LOG_WARNING("unexpected value type %d", val_type_rt); LOG_WARNING("unexpected value type %d", val_type_rt);
@ -1907,6 +1914,9 @@ wasm_trap_new_internal(wasm_store_t *store,
frame_instance; frame_instance;
} }
} }
#else
(void)store;
(void)inst_comm_rt;
#endif /* WASM_ENABLE_DUMP_CALL_STACK != 0 */ #endif /* WASM_ENABLE_DUMP_CALL_STACK != 0 */
return trap; return trap;
@ -2034,6 +2044,7 @@ wasm_foreign_new_internal(wasm_store_t *store, uint32 foreign_idx_rt,
} }
foreign->ref_cnt++; foreign->ref_cnt++;
(void)inst_comm_rt;
return foreign; return foreign;
} }
@ -4291,6 +4302,7 @@ interp_link_func(const wasm_instance_t *inst, const WASMModule *module_interp,
imported_func_interp->u.function.func_ptr_linked = import->u.cb; imported_func_interp->u.function.func_ptr_linked = import->u.cb;
import->func_idx_rt = func_idx_rt; import->func_idx_rt = func_idx_rt;
(void)inst;
return true; return true;
} }
@ -4338,7 +4350,7 @@ interp_link_global(const WASMModule *module_interp, uint16 global_idx_rt,
return true; return true;
} }
static uint32 static bool
interp_link(const wasm_instance_t *inst, const WASMModule *module_interp, interp_link(const wasm_instance_t *inst, const WASMModule *module_interp,
wasm_extern_t *imports[]) wasm_extern_t *imports[])
{ {
@ -4383,11 +4395,11 @@ interp_link(const wasm_instance_t *inst, const WASMModule *module_interp,
} }
} }
return i; return true;
failed: failed:
LOG_DEBUG("%s failed", __FUNCTION__); LOG_DEBUG("%s failed", __FUNCTION__);
return (uint32)-1; return false;
} }
static bool static bool
@ -4550,7 +4562,7 @@ failed:
return false; return false;
} }
static uint32 static bool
aot_link(const wasm_instance_t *inst, const AOTModule *module_aot, aot_link(const wasm_instance_t *inst, const AOTModule *module_aot,
wasm_extern_t *imports[]) wasm_extern_t *imports[])
{ {
@ -4598,11 +4610,11 @@ aot_link(const wasm_instance_t *inst, const AOTModule *module_aot,
} }
} }
return i; return true;
failed: failed:
LOG_DEBUG("%s failed", __FUNCTION__); LOG_DEBUG("%s failed", __FUNCTION__);
return (uint32)-1; return false;
} }
static bool static bool
@ -4706,6 +4718,57 @@ wasm_instance_new(wasm_store_t *store, const wasm_module_t *module,
KILOBYTE(32), KILOBYTE(32)); KILOBYTE(32), KILOBYTE(32));
} }
static bool
compare_imports(const wasm_module_t *module, const wasm_extern_vec_t *imports)
{
unsigned import_func_count = 0;
unsigned import_global_count = 0;
unsigned import_memory_count = 0;
unsigned import_table_count = 0;
unsigned i = 0;
for (i = 0; imports && i < imports->num_elems; i++) {
wasm_extern_t *import = imports->data[i];
switch (wasm_extern_kind(import)) {
case WASM_EXTERN_FUNC:
import_func_count++;
break;
case WASM_EXTERN_GLOBAL:
import_global_count++;
break;
case WASM_EXTERN_MEMORY:
import_memory_count++;
break;
case WASM_EXTERN_TABLE:
import_table_count++;
break;
default:
UNREACHABLE();
return false;
}
}
#if WASM_ENABLE_INTERP != 0
if ((*module)->module_type == Wasm_Module_Bytecode)
return import_func_count == MODULE_INTERP(module)->import_function_count
&& import_global_count
== MODULE_INTERP(module)->import_global_count
&& import_memory_count
== MODULE_INTERP(module)->import_memory_count
&& import_table_count
== MODULE_INTERP(module)->import_table_count;
#endif
#if WASM_ENABLE_AOT != 0
if ((*module)->module_type == Wasm_Module_AoT)
return import_func_count == MODULE_AOT(module)->import_func_count
&& import_global_count == MODULE_AOT(module)->import_global_count
&& import_memory_count == MODULE_AOT(module)->import_memory_count
&& import_table_count == MODULE_AOT(module)->import_table_count;
#endif
return false;
}
wasm_instance_t * wasm_instance_t *
wasm_instance_new_with_args(wasm_store_t *store, const wasm_module_t *module, wasm_instance_new_with_args(wasm_store_t *store, const wasm_module_t *module,
const wasm_extern_vec_t *imports, const wasm_extern_vec_t *imports,
@ -4714,18 +4777,22 @@ wasm_instance_new_with_args(wasm_store_t *store, const wasm_module_t *module,
{ {
char sub_error_buf[128] = { 0 }; char sub_error_buf[128] = { 0 };
char error_buf[256] = { 0 }; char error_buf[256] = { 0 };
bool import_count_verified = false;
wasm_instance_t *instance = NULL; wasm_instance_t *instance = NULL;
WASMModuleInstance *inst_rt; WASMModuleInstance *inst_rt;
CApiFuncImport *func_import = NULL, **p_func_imports = NULL; CApiFuncImport *func_import = NULL, **p_func_imports = NULL;
uint32 i = 0, import_count = 0, import_func_count = 0; uint32 i = 0, import_func_count = 0;
uint64 total_size; uint64 total_size;
bool processed = false; bool build_exported = false;
bh_assert(singleton_engine); bh_assert(singleton_engine);
if (!module) { if (!module)
return NULL; return NULL;
if (!compare_imports(module, imports)) {
snprintf(sub_error_buf, sizeof(sub_error_buf),
"Failed to match imports");
goto failed;
} }
WASM_C_DUMP_PROC_MEM(); WASM_C_DUMP_PROC_MEM();
@ -4739,43 +4806,28 @@ wasm_instance_new_with_args(wasm_store_t *store, const wasm_module_t *module,
/* link module and imports */ /* link module and imports */
if (imports && imports->num_elems) { if (imports && imports->num_elems) {
bool link = false;
#if WASM_ENABLE_INTERP != 0 #if WASM_ENABLE_INTERP != 0
if ((*module)->module_type == Wasm_Module_Bytecode) { if ((*module)->module_type == Wasm_Module_Bytecode) {
import_count = MODULE_INTERP(module)->import_count; if (!interp_link(instance, MODULE_INTERP(module),
(wasm_extern_t **)imports->data)) {
if (import_count) { snprintf(sub_error_buf, sizeof(sub_error_buf),
uint32 actual_link_import_count = "Failed to validate imports");
interp_link(instance, MODULE_INTERP(module), goto failed;
(wasm_extern_t **)imports->data);
/* make sure a complete import list */
if ((int32)import_count < 0
|| import_count != actual_link_import_count) {
snprintf(sub_error_buf, sizeof(sub_error_buf),
"Failed to validate imports");
goto failed;
}
} }
import_count_verified = true; link = true;
} }
#endif #endif
#if WASM_ENABLE_AOT != 0 #if WASM_ENABLE_AOT != 0
if ((*module)->module_type == Wasm_Module_AoT) { if ((*module)->module_type == Wasm_Module_AoT) {
import_count = MODULE_AOT(module)->import_func_count if (!aot_link(instance, MODULE_AOT(module),
+ MODULE_AOT(module)->import_global_count (wasm_extern_t **)imports->data)) {
+ MODULE_AOT(module)->import_memory_count snprintf(sub_error_buf, sizeof(sub_error_buf),
+ MODULE_AOT(module)->import_table_count; "Failed to validate imports");
goto failed;
if (import_count) {
import_count = aot_link(instance, MODULE_AOT(module),
(wasm_extern_t **)imports->data);
if ((int32)import_count < 0) {
snprintf(sub_error_buf, sizeof(sub_error_buf),
"Failed to validate imports");
goto failed;
}
} }
import_count_verified = true; link = true;
} }
#endif #endif
@ -4783,7 +4835,7 @@ wasm_instance_new_with_args(wasm_store_t *store, const wasm_module_t *module,
* a wrong combination of module filetype and compilation flags * a wrong combination of module filetype and compilation flags
* also leads to below branch * also leads to below branch
*/ */
if (!import_count_verified) { if (!link) {
snprintf(sub_error_buf, sizeof(sub_error_buf), snprintf(sub_error_buf, sizeof(sub_error_buf),
"Failed to verify import count"); "Failed to verify import count");
goto failed; goto failed;
@ -4802,6 +4854,7 @@ wasm_instance_new_with_args(wasm_store_t *store, const wasm_module_t *module,
goto failed; goto failed;
} }
/* create the c-api func import list */
inst_rt = (WASMModuleInstance *)instance->inst_comm_rt; inst_rt = (WASMModuleInstance *)instance->inst_comm_rt;
#if WASM_ENABLE_INTERP != 0 #if WASM_ENABLE_INTERP != 0
if (instance->inst_comm_rt->module_type == Wasm_Module_Bytecode) { if (instance->inst_comm_rt->module_type == Wasm_Module_Bytecode) {
@ -4818,7 +4871,6 @@ wasm_instance_new_with_args(wasm_store_t *store, const wasm_module_t *module,
#endif #endif
bh_assert(p_func_imports); bh_assert(p_func_imports);
/* create the c-api func import list */
total_size = (uint64)sizeof(CApiFuncImport) * import_func_count; total_size = (uint64)sizeof(CApiFuncImport) * import_func_count;
if (total_size > 0 if (total_size > 0
&& !(*p_func_imports = func_import = malloc_internal(total_size))) { && !(*p_func_imports = func_import = malloc_internal(total_size))) {
@ -4828,7 +4880,7 @@ wasm_instance_new_with_args(wasm_store_t *store, const wasm_module_t *module,
} }
/* fill in c-api func import list */ /* fill in c-api func import list */
for (i = 0; i < import_count; i++) { for (i = 0; imports && i < imports->num_elems; i++) {
wasm_func_t *func_host; wasm_func_t *func_host;
wasm_extern_t *in; wasm_extern_t *in;
@ -4850,10 +4902,9 @@ wasm_instance_new_with_args(wasm_store_t *store, const wasm_module_t *module,
func_import++; func_import++;
} }
bh_assert((uint32)(func_import - *p_func_imports) == import_func_count);
/* fill with inst */ /* fill with inst */
for (i = 0; imports && imports->data && i < (uint32)import_count; ++i) { for (i = 0; imports && imports->data && i < imports->num_elems; ++i) {
wasm_extern_t *import = imports->data[i]; wasm_extern_t *import = imports->data[i];
switch (import->kind) { switch (import->kind) {
case WASM_EXTERN_FUNC: case WASM_EXTERN_FUNC:
@ -4896,7 +4947,7 @@ wasm_instance_new_with_args(wasm_store_t *store, const wasm_module_t *module,
goto failed; goto failed;
} }
processed = true; build_exported = true;
} }
#endif #endif
@ -4920,7 +4971,7 @@ wasm_instance_new_with_args(wasm_store_t *store, const wasm_module_t *module,
goto failed; goto failed;
} }
processed = true; build_exported = true;
} }
#endif #endif
@ -4928,7 +4979,7 @@ wasm_instance_new_with_args(wasm_store_t *store, const wasm_module_t *module,
* a wrong combination of module filetype and compilation flags * a wrong combination of module filetype and compilation flags
* leads to below branch * leads to below branch
*/ */
if (!processed) { if (!build_exported) {
snprintf(sub_error_buf, sizeof(sub_error_buf), snprintf(sub_error_buf, sizeof(sub_error_buf),
"Incorrect filetype and compilation flags"); "Incorrect filetype and compilation flags");
goto failed; goto failed;

View File

@ -2359,19 +2359,27 @@ wasm_runtime_set_wasi_args_ex(WASMModuleCommon *module, const char *dir_list[],
{ {
WASIArguments *wasi_args = get_wasi_args_from_module(module); WASIArguments *wasi_args = get_wasi_args_from_module(module);
if (wasi_args) { bh_assert(wasi_args);
wasi_args->dir_list = dir_list;
wasi_args->dir_count = dir_count; wasi_args->dir_list = dir_list;
wasi_args->map_dir_list = map_dir_list; wasi_args->dir_count = dir_count;
wasi_args->map_dir_count = map_dir_count; wasi_args->map_dir_list = map_dir_list;
wasi_args->env = env_list; wasi_args->map_dir_count = map_dir_count;
wasi_args->env_count = env_count; wasi_args->env = env_list;
wasi_args->argv = argv; wasi_args->env_count = env_count;
wasi_args->argc = (uint32)argc; wasi_args->argv = argv;
wasi_args->stdio[0] = stdinfd; wasi_args->argc = (uint32)argc;
wasi_args->stdio[1] = stdoutfd; wasi_args->stdio[0] = stdinfd;
wasi_args->stdio[2] = stderrfd; wasi_args->stdio[1] = stdoutfd;
wasi_args->stdio[2] = stderrfd;
#if WASM_ENABLE_MULTI_MODULE != 0
#if WASM_ENABLE_INTERP != 0
if (module->module_type == Wasm_Module_Bytecode) {
wasm_propagate_wasi_args((WASMModule *)module);
} }
#endif
#endif
} }
void void
@ -2488,7 +2496,8 @@ wasm_runtime_init_wasi(WASMModuleInstanceCommon *module_inst,
wasm_runtime_set_wasi_ctx(module_inst, wasi_ctx); wasm_runtime_set_wasi_ctx(module_inst, wasi_ctx);
/* process argv[0], trip the path and suffix, only keep the program name */ /* process argv[0], trip the path and suffix, only keep the program name
*/
if (!copy_string_array((const char **)argv, argc, &argv_buf, &argv_list, if (!copy_string_array((const char **)argv, argc, &argv_buf, &argv_list,
&argv_buf_size)) { &argv_buf_size)) {
set_error_buf(error_buf, error_buf_size, set_error_buf(error_buf, error_buf_size,
@ -3188,7 +3197,8 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr,
uint32 *argv_ret) uint32 *argv_ret)
{ {
WASMModuleInstanceCommon *module = wasm_runtime_get_module_inst(exec_env); WASMModuleInstanceCommon *module = wasm_runtime_get_module_inst(exec_env);
/* argv buf layout: int args(fix cnt) + float args(fix cnt) + stack args */ /* argv buf layout: int args(fix cnt) + float args(fix cnt) + stack args
*/
uint32 argv_buf[32], *argv1 = argv_buf, *ints, *stacks, size; uint32 argv_buf[32], *argv1 = argv_buf, *ints, *stacks, size;
uint32 *argv_src = argv, i, argc1, n_ints = 0, n_stacks = 0; uint32 *argv_src = argv, i, argc1, n_ints = 0, n_stacks = 0;
uint32 arg_i32, ptr_len; uint32 arg_i32, ptr_len;

View File

@ -2597,7 +2597,7 @@ fail:
} }
static bool static bool
veriy_module(AOTCompContext *comp_ctx) verify_module(AOTCompContext *comp_ctx)
{ {
char *msg = NULL; char *msg = NULL;
bool ret; bool ret;
@ -2697,7 +2697,7 @@ aot_compile_wasm(AOTCompContext *comp_ctx)
the compilation process */ the compilation process */
if (!comp_ctx->is_jit_mode) { if (!comp_ctx->is_jit_mode) {
bh_print_time("Begin to verify LLVM module"); bh_print_time("Begin to verify LLVM module");
if (!veriy_module(comp_ctx)) { if (!verify_module(comp_ctx)) {
return false; return false;
} }
} }

View File

@ -307,6 +307,14 @@ compile_op_float_min_max(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx,
param_types, 2, left, right))) param_types, 2, left, right)))
return NULL; return NULL;
/* The result of XIP intrinsic is 0 or 1, should return it directly */
if (comp_ctx->disable_llvm_intrinsics
&& aot_intrinsic_check_capability(comp_ctx,
is_f32 ? "f32_cmp" : "f64_cmp")) {
return cmp;
}
if (!(cmp = LLVMBuildSelect(comp_ctx->builder, is_eq, tmp, cmp, "cmp"))) { if (!(cmp = LLVMBuildSelect(comp_ctx->builder, is_eq, tmp, cmp, "cmp"))) {
aot_set_last_error("llvm build select fail."); aot_set_last_error("llvm build select fail.");
return NULL; return NULL;

View File

@ -684,7 +684,7 @@ adjust_table_max_size(uint32 init_size, uint32 max_size_flag, uint32 *max_size)
} }
} }
#if WASM_ENABLE_MULTI_MODULE != 0 #if WASM_ENABLE_LIBC_WASI != 0 || WASM_ENABLE_MULTI_MODULE != 0
/** /**
* Find export item of a module with export info: * Find export item of a module with export info:
* module name, field name and export kind * module name, field name and export kind
@ -718,11 +718,15 @@ wasm_loader_find_export(const WASMModule *module, const char *module_name,
return NULL; return NULL;
} }
(void)module_name;
/* since there is a validation in load_export_section(), it is for sure /* since there is a validation in load_export_section(), it is for sure
* export->index is valid*/ * export->index is valid*/
return export; return export;
} }
#endif
#if WASM_ENABLE_MULTI_MODULE != 0
static WASMFunction * static WASMFunction *
wasm_loader_resolve_function(const char *module_name, const char *function_name, wasm_loader_resolve_function(const char *module_name, const char *function_name,
const WASMType *expected_function_type, const WASMType *expected_function_type,
@ -1240,6 +1244,8 @@ load_table_import(const uint8 **p_buf, const uint8 *buf_end,
table->init_size = declare_init_size; table->init_size = declare_init_size;
table->flags = declare_max_size_flag; table->flags = declare_max_size_flag;
table->max_size = declare_max_size; table->max_size = declare_max_size;
(void)parent_module;
return true; return true;
fail: fail:
return false; return false;
@ -1373,6 +1379,8 @@ load_memory_import(const uint8 **p_buf, const uint8 *buf_end,
memory->num_bytes_per_page = DEFAULT_NUM_BYTES_PER_PAGE; memory->num_bytes_per_page = DEFAULT_NUM_BYTES_PER_PAGE;
*p_buf = p; *p_buf = p;
(void)parent_module;
return true; return true;
fail: fail:
return false; return false;
@ -1439,6 +1447,8 @@ load_global_import(const uint8 **p_buf, const uint8 *buf_end,
global->field_name = global_name; global->field_name = global_name;
global->type = declare_type; global->type = declare_type;
global->is_mutable = (declare_mutable == 1); global->is_mutable = (declare_mutable == 1);
(void)parent_module;
return true; return true;
fail: fail:
return false; return false;
@ -2381,6 +2391,7 @@ load_func_index_vec(const uint8 **p_buf, const uint8 *buf_end,
} }
#else #else
read_leb_uint32(p, p_end, function_index); read_leb_uint32(p, p_end, function_index);
(void)use_init_expr;
#endif #endif
/* since we are using -1 to indicate ref.null */ /* since we are using -1 to indicate ref.null */
@ -2690,6 +2701,7 @@ load_code_section(const uint8 *buf, const uint8 *buf_end, const uint8 *buf_func,
} }
LOG_VERBOSE("Load code segment section success.\n"); LOG_VERBOSE("Load code segment section success.\n");
(void)module;
return true; return true;
fail: fail:
return false; return false;
@ -2794,8 +2806,8 @@ handle_name_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module,
read_leb_uint32(p, p_end, func_name_len); read_leb_uint32(p, p_end, func_name_len);
CHECK_BUF(p, p_end, func_name_len); CHECK_BUF(p, p_end, func_name_len);
/* Skip the import functions */ /* Skip the import functions */
if (func_index >= module->import_count) { if (func_index >= module->import_function_count) {
func_index -= module->import_count; func_index -= module->import_function_count;
if (func_index >= module->function_count) { if (func_index >= module->function_count) {
set_error_buf(error_buf, error_buf_size, set_error_buf(error_buf, error_buf_size,
"out-of-range function index"); "out-of-range function index");
@ -2900,6 +2912,8 @@ load_user_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module,
LOG_VERBOSE("Ignore custom section [%s].", section_name); LOG_VERBOSE("Ignore custom section [%s].", section_name);
(void)is_load_from_file_buf;
(void)module;
return true; return true;
fail: fail:
return false; return false;
@ -4054,24 +4068,19 @@ fail:
return false; return false;
} }
#if (WASM_ENABLE_MULTI_MODULE != 0) && (WASM_ENABLE_LIBC_WASI != 0) #if WASM_ENABLE_LIBC_WASI != 0
/** /**
* refer to * refer to
* https://github.com/WebAssembly/WASI/blob/main/design/application-abi.md * https://github.com/WebAssembly/WASI/blob/main/design/application-abi.md
*/ */
static bool static bool
check_wasi_abi_compatibility(const WASMModule *module, bool main_module, check_wasi_abi_compatibility(const WASMModule *module,
#if WASM_ENABLE_MULTI_MODULE != 0
bool main_module,
#endif
char *error_buf, uint32 error_buf_size) char *error_buf, uint32 error_buf_size)
{ {
/** /**
* need to handle:
* - non-wasi compatiable modules
* - a fake wasi compatiable module
* - a command acts as a main_module
* - a command acts as a sub_module
* - a reactor acts as a main_module
* - a reactor acts as a sub_module
*
* be careful with: * be careful with:
* wasi compatiable modules(command/reactor) which don't import any wasi * wasi compatiable modules(command/reactor) which don't import any wasi
* APIs. Usually, a command has to import a "prox_exit" at least, but a * APIs. Usually, a command has to import a "prox_exit" at least, but a
@ -4087,8 +4096,20 @@ check_wasi_abi_compatibility(const WASMModule *module, bool main_module,
* - no one will define either `_start` or `_initialize` on purpose * - no one will define either `_start` or `_initialize` on purpose
* - `_start` should always be `void _start(void)` * - `_start` should always be `void _start(void)`
* - `_initialize` should always be `void _initialize(void)` * - `_initialize` should always be `void _initialize(void)`
*
*/ */
/* clang-format off */
/**
*
* | | import_wasi_api True | | import_wasi_api False | |
* | ----------- | -------------------- | ---------------- | --------------------- | ---------------- |
* | | \_initialize() Y | \_initialize() N | \_initialize() Y | \_initialize() N |
* | \_start() Y | N | COMMANDER | N | COMMANDER |
* | \_start() N | REACTOR | N | REACTOR | OTHERS |
*/
/* clang-format on */
WASMExport *initialize = NULL, *memory = NULL, *start = NULL; WASMExport *initialize = NULL, *memory = NULL, *start = NULL;
/* (func (export "_start") (...) */ /* (func (export "_start") (...) */
@ -4147,6 +4168,7 @@ check_wasi_abi_compatibility(const WASMModule *module, bool main_module,
return false; return false;
} }
#if WASM_ENABLE_MULTI_MODULE != 0
/* filter out commands (with `_start`) cases */ /* filter out commands (with `_start`) cases */
if (start && !main_module) { if (start && !main_module) {
set_error_buf( set_error_buf(
@ -4154,6 +4176,7 @@ check_wasi_abi_compatibility(const WASMModule *module, bool main_module,
"a command (with _start function) can not be a sub-module"); "a command (with _start function) can not be a sub-module");
return false; return false;
} }
#endif
/* /*
* it is ok a reactor acts as a main module, * it is ok a reactor acts as a main module,
@ -4193,10 +4216,13 @@ wasm_loader_load(uint8 *buf, uint32 size,
goto fail; goto fail;
} }
#if (WASM_ENABLE_MULTI_MODULE != 0) && (WASM_ENABLE_LIBC_WASI != 0) #if WASM_ENABLE_LIBC_WASI != 0
/* Check the WASI application ABI */ /* Check the WASI application ABI */
if (!check_wasi_abi_compatibility(module, main_module, error_buf, if (!check_wasi_abi_compatibility(module,
error_buf_size)) { #if WASM_ENABLE_MULTI_MODULE != 0
main_module,
#endif
error_buf, error_buf_size)) {
goto fail; goto fail;
} }
#endif #endif
@ -4982,6 +5008,7 @@ wasm_loader_find_block_addr(WASMExecEnv *exec_env, BlockAddr *block_addr_cache,
} }
(void)u8; (void)u8;
(void)exec_env;
return false; return false;
fail: fail:
return false; return false;
@ -5845,6 +5872,8 @@ preserve_referenced_local(WASMLoaderContext *loader_ctx, uint8 opcode,
i += 2; i += 2;
} }
(void)error_buf;
(void)error_buf_size;
return true; return true;
#if WASM_ENABLE_LABELS_AS_VALUES != 0 #if WASM_ENABLE_LABELS_AS_VALUES != 0
#if WASM_CPU_SUPPORTS_UNALIGNED_ADDR_ACCESS == 0 #if WASM_CPU_SUPPORTS_UNALIGNED_ADDR_ACCESS == 0
@ -6109,6 +6138,9 @@ wasm_loader_pop_frame_offset(WASMLoaderContext *ctx, uint8 type,
ctx->dynamic_offset -= 2; ctx->dynamic_offset -= 2;
} }
emit_operand(ctx, *(ctx->frame_offset)); emit_operand(ctx, *(ctx->frame_offset));
(void)error_buf;
(void)error_buf_size;
return true; return true;
} }

View File

@ -1708,8 +1708,8 @@ handle_name_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module,
read_leb_uint32(p, p_end, func_name_len); read_leb_uint32(p, p_end, func_name_len);
CHECK_BUF(p, p_end, func_name_len); CHECK_BUF(p, p_end, func_name_len);
/* Skip the import functions */ /* Skip the import functions */
if (func_index >= module->import_count) { if (func_index >= module->import_function_count) {
func_index -= module->import_count; func_index -= module->import_function_count;
bh_assert(func_index < module->function_count); bh_assert(func_index < module->function_count);
if (!(module->functions[func_index]->field_name = if (!(module->functions[func_index]->field_name =
const_str_list_insert( const_str_list_insert(
@ -1733,6 +1733,8 @@ handle_name_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module,
i++; i++;
} }
(void)previous_name_type;
(void)previous_func_index;
return true; return true;
} }
#endif #endif

View File

@ -983,6 +983,18 @@ export_globals_instantiate(const WASMModule *module,
} }
#endif #endif
#if WASM_ENABLE_LIBC_WASI != 0
static bool
execute_initialize_function(WASMModuleInstance *module_inst)
{
WASMFunctionInstance *initialize =
wasm_lookup_function(module_inst, "_initialize", NULL);
return !initialize
|| wasm_create_exec_env_and_call_function(module_inst, initialize, 0,
NULL);
}
#endif
static bool static bool
execute_post_inst_function(WASMModuleInstance *module_inst) execute_post_inst_function(WASMModuleInstance *module_inst)
{ {
@ -1175,28 +1187,6 @@ sub_module_instantiate(WASMModule *module, WASMModuleInstance *module_inst,
sub_module_list_node = bh_list_elem_next(sub_module_list_node); sub_module_list_node = bh_list_elem_next(sub_module_list_node);
#if WASM_ENABLE_LIBC_WASI != 0
{
/*
* reactor instances may assume that _initialize will be called by
* the environment at most once, and that none of their other
* exports are accessed before that call.
*
* let the loader decide how to act if there is no _initialize
* in a reactor
*/
WASMFunctionInstance *initialize =
wasm_lookup_function(sub_module_inst, "_initialize", NULL);
if (initialize
&& !wasm_create_exec_env_and_call_function(
sub_module_inst, initialize, 0, NULL)) {
set_error_buf(error_buf, error_buf_size,
"Call _initialize failed ");
goto failed;
}
}
#endif
continue; continue;
failed: failed:
if (sub_module_inst_list_node) { if (sub_module_inst_list_node) {
@ -1844,8 +1834,21 @@ wasm_instantiate(WASMModule *module, bool is_sub_inst, uint32 stack_size,
&module_inst->e->functions[module->start_function]; &module_inst->e->functions[module->start_function];
} }
/* Execute __post_instantiate function */ if (
if (!execute_post_inst_function(module_inst) #if WASM_ENABLE_LIBC_WASI != 0
/*
* reactor instances may assume that _initialize will be called by
* the environment at most once, and that none of their other
* exports are accessed before that call.
*
* let the loader decide how to act if there is no _initialize
* in a reactor
*/
!execute_initialize_function(module_inst) ||
#endif
/* Execute __post_instantiate function */
!execute_post_inst_function(module_inst)
/* Execute the function in "start" section */
|| !execute_start_function(module_inst)) { || !execute_start_function(module_inst)) {
set_error_buf(error_buf, error_buf_size, module_inst->cur_exception); set_error_buf(error_buf, error_buf_size, module_inst->cur_exception);
goto fail; goto fail;
@ -3231,3 +3234,26 @@ llvm_jit_free_frame(WASMExecEnv *exec_env)
|| WASM_ENABLE_PERF_PROFILING != 0 */ || WASM_ENABLE_PERF_PROFILING != 0 */
#endif /* end of WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 */ #endif /* end of WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 */
#if WASM_ENABLE_LIBC_WASI != 0 && WASM_ENABLE_MULTI_MODULE != 0
void
wasm_propagate_wasi_args(WASMModule *module)
{
if (!module->import_count)
return;
bh_assert(&module->import_module_list_head);
WASMRegisteredModule *node =
bh_list_first_elem(&module->import_module_list_head);
while (node) {
WASIArguments *wasi_args_impt_mod =
&((WASMModule *)(node->module))->wasi_args;
bh_assert(wasi_args_impt_mod);
bh_memcpy_s(wasi_args_impt_mod, sizeof(WASIArguments),
&module->wasi_args, sizeof(WASIArguments));
node = bh_list_elem_next(node);
}
}
#endif

View File

@ -626,6 +626,11 @@ llvm_jit_free_frame(WASMExecEnv *exec_env);
#endif #endif
#endif /* end of WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 */ #endif /* end of WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 */
#if WASM_ENABLE_LIBC_WASI != 0 && WASM_ENABLE_MULTI_MODULE != 0
void
wasm_propagate_wasi_args(WASMModule *module);
#endif
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif

View File

@ -2696,7 +2696,7 @@ wasmtime_ssp_poll_oneoff(
timeout = ts > INT_MAX ? -1 : (int)ts; timeout = ts > INT_MAX ? -1 : (int)ts;
} }
else { else {
timeout = 1000; timeout = -1;
} }
int ret = poll(pfds, nsubscriptions, timeout); int ret = poll(pfds, nsubscriptions, timeout);

View File

@ -0,0 +1,43 @@
/*
* Copyright (C) 2019 Intel Corporation. All rights reserved.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*/
#include "platform_api_vmcore.h"
int
bh_platform_init()
{
return 0;
}
void
bh_platform_destroy()
{}
int
os_printf(const char *format, ...)
{
int ret = 0;
va_list ap;
va_start(ap, format);
#ifndef BH_VPRINTF
ret += vprintf(format, ap);
#else
ret += BH_VPRINTF(format, ap);
#endif
va_end(ap);
return ret;
}
int
os_vprintf(const char *format, va_list ap)
{
#ifndef BH_VPRINTF
return vprintf(format, ap);
#else
return BH_VPRINTF(format, ap);
#endif
}

View File

@ -0,0 +1,108 @@
/*
* Copyright (C) 2019 Intel Corporation. All rights reserved.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*/
#ifndef _PLATFORM_INTERNAL_H
#define _PLATFORM_INTERNAL_H
#include <inttypes.h>
#include <stdbool.h>
#include <assert.h>
#include <time.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdarg.h>
#include <ctype.h>
#include <pthread.h>
#include <signal.h>
#include <semaphore.h>
#include <limits.h>
#include <dirent.h>
#include <fcntl.h>
#include <unistd.h>
#include <poll.h>
#include <sched.h>
#include <errno.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <sys/uio.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/resource.h>
#ifdef __cplusplus
extern "C" {
#endif
#ifndef BH_PLATFORM_FREEBSD
#define BH_PLATFORM_FREEBSD
#endif
#define BH_HAS_DLFCN 1
/* Stack size of applet threads's native part. */
#define BH_APPLET_PRESERVED_STACK_SIZE (32 * 1024)
/* Default thread priority */
#define BH_THREAD_DEFAULT_PRIORITY 0
typedef pthread_t korp_tid;
typedef pthread_mutex_t korp_mutex;
typedef pthread_cond_t korp_cond;
typedef pthread_t korp_thread;
typedef sem_t korp_sem;
#define OS_THREAD_MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER
#define os_thread_local_attribute __thread
#define bh_socket_t int
#if WASM_DISABLE_HW_BOUND_CHECK == 0
#if defined(BUILD_TARGET_X86_64) || defined(BUILD_TARGET_AMD_64) \
|| defined(BUILD_TARGET_AARCH64) || defined(BUILD_TARGET_RISCV64_LP64D) \
|| defined(BUILD_TARGET_RISCV64_LP64)
#include <setjmp.h>
#define OS_ENABLE_HW_BOUND_CHECK
typedef jmp_buf korp_jmpbuf;
#define os_setjmp setjmp
#define os_longjmp longjmp
#define os_alloca alloca
#define os_getpagesize getpagesize
typedef void (*os_signal_handler)(void *sig_addr);
int
os_thread_signal_init(os_signal_handler handler);
void
os_thread_signal_destroy();
bool
os_thread_signal_inited();
void
os_signal_unmask();
void
os_sigreturn();
#endif /* end of BUILD_TARGET_X86_64/AMD_64/AARCH64/RISCV64 */
#endif /* end of WASM_DISABLE_HW_BOUND_CHECK */
#ifdef __cplusplus
}
#endif
#endif /* end of _PLATFORM_INTERNAL_H */

View File

@ -0,0 +1,18 @@
# Copyright (C) 2019 Intel Corporation. All rights reserved.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
set (PLATFORM_SHARED_DIR ${CMAKE_CURRENT_LIST_DIR})
add_definitions(-DBH_PLATFORM_FREEBSD)
include_directories(${PLATFORM_SHARED_DIR})
include_directories(${PLATFORM_SHARED_DIR}/../include)
include (${CMAKE_CURRENT_LIST_DIR}/../common/posix/platform_api_posix.cmake)
file (GLOB_RECURSE source_all ${PLATFORM_SHARED_DIR}/*.c)
set (PLATFORM_SHARED_SOURCE ${source_all} ${PLATFORM_COMMON_POSIX_SOURCE})
file (GLOB header ${PLATFORM_SHARED_DIR}/../include/*.h)
LIST (APPEND RUNTIME_LIB_HEADER_LIST ${header})

View File

@ -35,9 +35,4 @@
#define WA_FREE wasm_runtime_free #define WA_FREE wasm_runtime_free
#endif #endif
/* The epsilon value is from https://www.cplusplus.com/reference/cfloat/ */
#define WA_FLT_EPSILON 1e-5f
#define WA_DBL_EPSILON 1e-9
#endif /* #ifndef _BH_PLATFORM_H */ #endif /* #ifndef _BH_PLATFORM_H */

View File

@ -637,3 +637,18 @@ $ ls ../build_out/
libvmlib.a ) and an executable binary (*iwasm*) and copy *iwasm* to libvmlib.a ) and an executable binary (*iwasm*) and copy *iwasm* to
*build_out*. All original generated files are still under *build_out*. All original generated files are still under
*product-mini/platforms/linux/build*. *product-mini/platforms/linux/build*.
FreeBSD
-------------------------
First, install the dependent packages:
```shell
sudo pkg install gcc cmake wget
```
Then you can run the following commands to build iwasm with default configurations:
```shell
cd product-mini/platforms/freebsd
mkdir build && cd build
cmake ..
make
```

View File

@ -0,0 +1,132 @@
# Copyright (C) 2019 Intel Corporation. All rights reserved.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
cmake_minimum_required (VERSION 2.9)
project (iwasm)
set (WAMR_BUILD_PLATFORM "freebsd")
# Reset default linker flags
set (CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "")
set (CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS "")
# Set WAMR_BUILD_TARGET, currently values supported:
# "X86_64", "AMD_64", "X86_32", "AARCH64[sub]", "ARM[sub]", "THUMB[sub]",
# "MIPS", "XTENSA", "RISCV64[sub]", "RISCV32[sub]"
if (NOT DEFINED WAMR_BUILD_TARGET)
if (CMAKE_SYSTEM_PROCESSOR MATCHES "^(arm64|aarch64)")
set (WAMR_BUILD_TARGET "AARCH64")
elseif (CMAKE_SYSTEM_PROCESSOR STREQUAL "riscv64")
set (WAMR_BUILD_TARGET "RISCV64")
elseif (CMAKE_SIZEOF_VOID_P EQUAL 8)
# Build as X86_64 by default in 64-bit platform
set (WAMR_BUILD_TARGET "X86_64")
elseif (CMAKE_SIZEOF_VOID_P EQUAL 4)
# Build as X86_32 by default in 32-bit platform
set (WAMR_BUILD_TARGET "X86_32")
else ()
message(SEND_ERROR "Unsupported build target platform!")
endif ()
endif ()
if (NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release)
endif ()
set(CMAKE_CXX_STANDARD 14)
if (NOT DEFINED WAMR_BUILD_INTERP)
# Enable Interpreter by default
set (WAMR_BUILD_INTERP 1)
endif ()
if (NOT DEFINED WAMR_BUILD_AOT)
# Enable AOT by default.
set (WAMR_BUILD_AOT 1)
endif ()
if (NOT DEFINED WAMR_BUILD_JIT)
# Disable JIT by default.
set (WAMR_BUILD_JIT 0)
endif ()
if (NOT DEFINED WAMR_BUILD_FAST_JIT)
# Disable Fast JIT by default
set (WAMR_BUILD_FAST_JIT 0)
endif ()
if (NOT DEFINED WAMR_BUILD_LIBC_BUILTIN)
# Enable libc builtin support by default
set (WAMR_BUILD_LIBC_BUILTIN 1)
endif ()
if (NOT DEFINED WAMR_BUILD_LIBC_WASI)
# Enable libc wasi support by default
set (WAMR_BUILD_LIBC_WASI 1)
endif ()
if (NOT DEFINED WAMR_BUILD_FAST_INTERP)
# Enable fast interpreter
set (WAMR_BUILD_FAST_INTERP 1)
endif ()
if (NOT DEFINED WAMR_BUILD_MULTI_MODULE)
# Disable multiple module by default
set (WAMR_BUILD_MULTI_MODULE 0)
endif ()
if (NOT DEFINED WAMR_BUILD_LIB_PTHREAD)
# Disable pthread library by default
set (WAMR_BUILD_LIB_PTHREAD 0)
endif ()
if (NOT DEFINED WAMR_BUILD_MINI_LOADER)
# Disable wasm mini loader by default
set (WAMR_BUILD_MINI_LOADER 0)
endif ()
if (NOT DEFINED WAMR_BUILD_SIMD)
# Enable SIMD by default
set (WAMR_BUILD_SIMD 1)
endif ()
if (NOT DEFINED WAMR_BUILD_DEBUG_INTERP)
# Disable Debug feature by default
set (WAMR_BUILD_DEBUG_INTERP 0)
endif ()
if (WAMR_BUILD_DEBUG_INTERP EQUAL 1)
set (WAMR_BUILD_FAST_INTERP 0)
set (WAMR_BUILD_MINI_LOADER 0)
set (WAMR_BUILD_SIMD 0)
endif ()
set (WAMR_DISABLE_HW_BOUND_CHECK 1)
set (CMAKE_SHARED_LINKER_FLAGS "-Wl")
set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS}")
set (CMAKE_MACOSX_RPATH True)
set (WAMR_ROOT_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../..)
include (${WAMR_ROOT_DIR}/build-scripts/runtime_lib.cmake)
add_library(vmlib ${WAMR_RUNTIME_LIB_SOURCE})
include (${SHARED_DIR}/utils/uncommon/shared_uncommon.cmake)
add_executable (iwasm main.c ${UNCOMMON_SHARED_SOURCE})
install (TARGETS iwasm DESTINATION bin)
target_link_libraries (iwasm vmlib ${LLVM_AVAILABLE_LIBS} ${UV_A_LIBS} -lm -ldl -lpthread)
add_library (libiwasm SHARED ${WAMR_RUNTIME_LIB_SOURCE})
install (TARGETS libiwasm DESTINATION lib)
set_target_properties (libiwasm PROPERTIES OUTPUT_NAME iwasm)
target_link_libraries (libiwasm ${LLVM_AVAILABLE_LIBS} ${UV_A_LIBS} -lm -ldl -lpthread)

View File

@ -0,0 +1,11 @@
#!/bin/sh
# Copyright (C) 2019 Intel Corporation. All rights reserved.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
rm -fr build && mkdir build
cd build
cmake .. -DWAMR_BUILD_JIT=1
nproc=$(sysctl -n hw.ncpu)
make -j ${nproc}
cd ..

View File

@ -0,0 +1,6 @@
#!/bin/sh
# Copyright (C) 2020 Intel Corporation. All rights reserved.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
/usr/bin/env python3 ../../../build-scripts/build_llvm.py "$@"

View File

@ -0,0 +1,6 @@
/*
* Copyright (C) 2019 Intel Corporation. All rights reserved.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*/
#include "../posix/main.c"

View File

@ -796,12 +796,7 @@ fail1:
/* Destroy runtime environment */ /* Destroy runtime environment */
destroy_runtime(); destroy_runtime();
#if WASM_ENABLE_SPEC_TEST != 0
(void)ret;
return 0;
#else
return ret; return ret;
#endif
} }
int int

View File

@ -696,10 +696,5 @@ fail1:
/* destroy runtime environment */ /* destroy runtime environment */
wasm_runtime_destroy(); wasm_runtime_destroy();
#if WASM_ENABLE_SPEC_TEST != 0
(void)ret;
return 0;
#else
return ret; return ret;
#endif
} }

View File

@ -496,10 +496,5 @@ fail1:
/* destroy runtime environment */ /* destroy runtime environment */
wasm_runtime_destroy(); wasm_runtime_destroy();
#if WASM_ENABLE_SPEC_TEST != 0
(void)ret;
return 0;
#else
return ret; return ret;
#endif
} }

View File

@ -159,6 +159,9 @@ endif()
check_pie_supported() check_pie_supported()
include(CTest)
enable_testing()
foreach(EX ${EXAMPLES}) foreach(EX ${EXAMPLES})
set(SRC ${CMAKE_CURRENT_LIST_DIR}/src/${EX}.c) set(SRC ${CMAKE_CURRENT_LIST_DIR}/src/${EX}.c)
@ -193,6 +196,12 @@ foreach(EX ${EXAMPLES})
) )
add_dependencies(${EX} ${EX}_AOT) add_dependencies(${EX} ${EX}_AOT)
endif() endif()
# run `ctest --test-dir build`
add_test(NAME Test_${EX}
COMMAND ./${EX}
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
)
endforeach() endforeach()
if (CMAKE_BUILD_TYPE STREQUAL "Debug") if (CMAKE_BUILD_TYPE STREQUAL "Debug")
@ -201,19 +210,5 @@ if (CMAKE_BUILD_TYPE STREQUAL "Debug")
REQUIRED REQUIRED
) )
if(VALGRIND) # run `ctest -T memcheck -V --test-dir build`
foreach(EX ${EXAMPLES}) endif()
add_custom_command(
OUTPUT ${EX}_leak_check.report
DEPENDS ${EX} ${EX}_WASM
COMMAND ${VALGRIND} --tool=memcheck --leak-check=full -- ./${EX} > ${EX}_leak_check.report 2>&1
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
)
add_custom_target(${EX}_LEAK_TEST ALL
DEPENDS ${EX}_leak_check.report
COMMAND grep "All heap blocks were freed -- no leaks are possible" ${EX}_leak_check.report
COMMENT "Please read ${EX}_leak_check.report when meeting Error"
)
endforeach()
endif (VALGRIND)
endif (CMAKE_BUILD_TYPE STREQUAL "Debug")

View File

@ -238,7 +238,7 @@ main(int argc, const char *argv[])
IMPORT_FUNCTION_LIST(CREATE_WASM_FUNCTION) IMPORT_FUNCTION_LIST(CREATE_WASM_FUNCTION)
#undef CREATE_WASM_FUNCTION #undef CREATE_WASM_FUNCTION
wasm_extern_t *fs[10] = { 0 }; wasm_extern_t *fs[2] = { 0 };
#define ADD_TO_FUNCTION_LIST(name, index, ...) \ #define ADD_TO_FUNCTION_LIST(name, index, ...) \
fs[index] = wasm_func_as_extern(function_##name); fs[index] = wasm_func_as_extern(function_##name);
IMPORT_FUNCTION_LIST(ADD_TO_FUNCTION_LIST) IMPORT_FUNCTION_LIST(ADD_TO_FUNCTION_LIST)

View File

@ -14,17 +14,17 @@ The WAMR-IDE is an Integrated Development Environment to develop WebAssembly app
## How to setup WAMR IDE ## How to setup WAMR IDE
Note: Please ensure that the scripts under `resource` directories have Now, we have same version tagged docker images, lldb binaries and VS Code installation file(.vsix file) packed for each GitHub release. So if you simply want to use WAMR debugging features in VS Code, the ideal(and effortless) way is following the tutorial in [this section](#21-download-wamr-vs-code-extension-from-the-github-releaserecommended-approach).
execution permission. While on git they have x bits, you might have dropped
them eg. by copying them from Windows.
Similarly, do not drop execution permission when copying `lldb` binaries
under `resource/debug/bin`.
#### 1. Install `VSCode` on host. Alternatively, if you want to build lldb, docker images, or .vsix file locally so that you can try the effect of your modification, you could refer to the tutorial in [this section](#22-build-wamr-vs-code-extension-locallyalternative-approach).
### 1. Preparation
#### 1.1. Install `VSCode` on host
- make sure the version of [vscode](https://code.visualstudio.com/Download) you installed is at least _1.59.0_ - make sure the version of [vscode](https://code.visualstudio.com/Download) you installed is at least _1.59.0_
#### 2. Install `Docker` on host. #### 1.2. Install `Docker` on host
1. [Windows: Docker Desktop](https://docs.docker.com/desktop/windows/install/) 1. [Windows: Docker Desktop](https://docs.docker.com/desktop/windows/install/)
2. [Ubuntu: Docker Engine](https://docs.docker.com/engine/install/ubuntu) 2. [Ubuntu: Docker Engine](https://docs.docker.com/engine/install/ubuntu)
@ -37,11 +37,13 @@ under `resource/debug/bin`.
- Ubuntu Bionic 18.04(LTS) - Ubuntu Bionic 18.04(LTS)
``` ```
#### 3. Load docker images from the release tar file or build docker images on the host ### 2. WAMR VS Code extension: download from the GitHub release or build locally
##### 3.1 Load docker images from the release tar file #### 2.1 Download WAMR VS Code extension from the GitHub release(Recommended approach)
From now on, for each release, we have the same version tagged docker image saved as a tar file, which you can find and download in the release. ##### 2.1.1 Load docker images from the GitHub release tar file
From now on, for each GitHub release, we have the same version tagged docker image saved as a tar file, which you can find and download in the GitHub release.
You could download the tar archive files for docker images from the release, and then load them using the following commands: You could download the tar archive files for docker images from the release, and then load them using the following commands:
@ -68,7 +70,23 @@ docker load --input ./wasm-toolchain.tar
docker load --input ./wasm-debug-server.tar docker load --input ./wasm-debug-server.tar
``` ```
##### 3.2 Build docker images on host ##### 2.1.2 Download the VS Code extension installation file from the GitHub release
From now on, for each GitHub release, we have the same version tagged zip/tar.gz file. For example, in release version 1.1.2, you can easily download and decompress `wamr-ide-1.1.2.tar.gz` `wamr-ide-1.1.2.zip`, which contains `wamr-ide.vsix` VS Code extension installation file. As you can imagine, in the future, when new releases are available, you can freely choose whichever version(for example, 1.2.0, 1.3.0, etc.) you prefer. It should work as long as you download the same version tagged docker image and .vsix file.
##### 2.1.3 Install extension from vsix
![install_from_vsix](./Media/install_from_vsix.png "install wamr-ide from vsix")
select `wamr-ide.vsix` which you have decompressed from `.tar.gz` or `.zip` file.
#### 2.2 Build WAMR VS Code extension locally(Alternative approach)
You could also build the VS Code extension locally, the following instruction provides a thorough tutorial. It's worth noting that in the local build tutorial we use hard-coded tag version 1.0 other than the semantic version of WAMR.
Note: Please ensure that the scripts under `resource` directories have execution permission. While on git they have x bits, you might have dropped them eg. by copying them from Windows. Similarly, do not drop execution permission when copying `lldb` binaries under `resource/debug/bin`.
##### 2.2.1 Build docker images on host
We have 2 docker images which should be built or loaded on your host, `wasm-toolchain` and `wasm-debug-server`. To build these 2 images, please enter the `WASM-Debug-Server/Docker` & `WASM-Toolchain/Docker`, then execute the `build_docker_image` script respectively. We have 2 docker images which should be built or loaded on your host, `wasm-toolchain` and `wasm-debug-server`. To build these 2 images, please enter the `WASM-Debug-Server/Docker` & `WASM-Toolchain/Docker`, then execute the `build_docker_image` script respectively.
@ -90,11 +108,11 @@ $ cd ./WASM-Debug-Server/Docker
$ ./build_docker_image.sh $ ./build_docker_image.sh
``` ```
#### After building, you can find `wasm-toolchain` and `wasm-debug-server` docker images on your local ##### 2.2.2 After building, you can find `wasm-toolchain` and `wasm-debug-server` docker images on your local
![docker-images](./Media/docker_images.png) ![docker-images](./Media/docker_images.png)
#### If building docker images fail during the process ##### 2.2.3 If building docker images fail during the process
Sometimes building the Docker images may fail due to bad network conditions. If the `wasm-toolchain` and `wasm-debug-server` images do not exist after building, please build them manually. Fix the proxy setting if needed and execute the following command to build docker images. Sometimes building the Docker images may fail due to bad network conditions. If the `wasm-toolchain` and `wasm-debug-server` images do not exist after building, please build them manually. Fix the proxy setting if needed and execute the following command to build docker images.
@ -114,15 +132,15 @@ $ docker build --no-cache --build-arg http_proxy=http://proxy.example.com:1234
--build-arg https_proxy=http://proxy.example.com:1234 -t wasm-toolchain:1.0 . --build-arg https_proxy=http://proxy.example.com:1234 -t wasm-toolchain:1.0 .
``` ```
#### If you encounter the problem `failed to solve with frontend dockerfile.v0: failed to create LLB definition`, please config your docker desktop ##### 2.2.4 If you encounter the problem `failed to solve with frontend dockerfile.v0: failed to create LLB definition`, please config your docker desktop
![docker-engine-config](./Media/docker_engine_config.png) ![docker-engine-config](./Media/docker_engine_config.png)
#### Points To Remember ##### 2.2.5 Points To Remember
- Make sure that the `wasm-toolchain:1.0` and `wasm-debug-server:1.0` docker images are both successfully built before using `WAMR IDE`, otherwise `Build`, `Run` and `Debug` will not work. - Make sure that the `wasm-toolchain:1.0` and `wasm-debug-server:1.0` docker images are both successfully built before using `WAMR IDE`, otherwise `Build`, `Run` and `Debug` will not work.
#### 4. Generate wamride extension package file ##### 2.2.6 Generate wamride extension package file
`wamride-1.0.0.vsix` can be packaged by [`npm vsce`](https://code.visualstudio.com/api/working-with-extensions/publishing-extension). `wamride-1.0.0.vsix` can be packaged by [`npm vsce`](https://code.visualstudio.com/api/working-with-extensions/publishing-extension).
@ -134,14 +152,29 @@ $ npm install
$ vsce package $ vsce package
``` ```
Note that patched `lldb` should be built and put into the `VSCode-Extension/resource/debug` folder before your package or extension debug process if you want to enable `source debugging` feature. ##### 2.2.7 Enable VS Code debugging feature
Please follow this [instruction](../../doc/source_debugging.md#debugging-with-interpreter) to build `lldb`.
Please follow this [instruction](./VSCode-Extension/resource/debug/README.md) By default, when you build .vsix locally, the debugging feature is off. Suppose you want to enable the source debugging feature. In that case, you could download `lldb` binaries from our GitHub release (for example, `wamr-lldb-1.1.2-x86_64-ubuntu-20.04.tar.gz`), decompress and put every subdirectory and file to the installed directory of your VS Code extension.
to copy the binaries.
For example, let's say you are on an Ubuntu 20.04 machine. You first download and decompress `wamr-lldb-1.1.2-x86_64-ubuntu-20.04.tar.gz`, and you will get a `wamr-lldb` folder (or `inst` folder in our earlier release). Then, you can simply copy the files and directory inside that folder to the relative path `resource/debug/linux/` under your VS Code extension installation directory.
Example commands on an Ubuntu 20.04 machine:
```shell
# decompress .tar.gz file and get the folder
$ ls wamr-lldb
bin lib package.json syntaxes
# copy everything to the vscode extension installation path(in this case, it's /home/{usrname}/.vscode-server/extensions/wamr.wamride-1.0.0/)
$ cp inst/* /home/{usrname}/.vscode-server/extensions/wamr.wamride-1.0.0/resource/debug/linux/
```
If you want to use your own patched `lldb`, you could follow this [instruction](../../doc/source_debugging.md#debugging-with-interpreter) to build `lldb`. And follow this [instruction](./VSCode-Extension/resource/debug/README.md)
to copy the binaries to replace the existing ones.
> **You can also debug the extension directly follow this [instruction](./VSCode-Extension/README.md) without packing the extension.** > **You can also debug the extension directly follow this [instruction](./VSCode-Extension/README.md) without packing the extension.**
#### 5. Install extension from vsix ##### 2.2.7 Install extension from vsix
![install_from_vsix](./Media/install_from_vsix.png "install wamr-ide from vsix") ![install_from_vsix](./Media/install_from_vsix.png "install wamr-ide from vsix")
@ -215,7 +248,7 @@ Click `Change workspace` button, a dialog will show as following. You can select
![right click menus](./Media/right_click_menus_2.png "right click menus") ![right click menus](./Media/right_click_menus_2.png "right click menus")
#### After setting up `include path` and `exclude files`, the corresponding folder and files will be decorated with color and icon as following picture shows. #### After setting up `include path` and `exclude files`, the corresponding folder and files will be decorated with color and icon as following picture shows
![decoration for files](./Media/decoration_for_files.png "decoration for files") ![decoration for files](./Media/decoration_for_files.png "decoration for files")

View File

@ -1,13 +1,12 @@
{ {
"root": true, "root": true,
"parser": "@typescript-eslint/parser", "parser": "@typescript-eslint/parser",
"extends": ["plugin:@typescript-eslint/recommended"],
"parserOptions": { "parserOptions": {
"ecmaVersion": 6, "ecmaVersion": "latest",
"sourceType": "module" "sourceType": "module"
}, },
"plugins": [ "plugins": ["@typescript-eslint"],
"@typescript-eslint"
],
"rules": { "rules": {
"@typescript-eslint/naming-convention": "warn", "@typescript-eslint/naming-convention": "warn",
"@typescript-eslint/semi": "warn", "@typescript-eslint/semi": "warn",
@ -16,9 +15,5 @@
"no-throw-literal": "warn", "no-throw-literal": "warn",
"semi": "off" "semi": "off"
}, },
"ignorePatterns": [ "ignorePatterns": ["out", "dist", "**/*.d.ts"]
"out",
"dist",
"**/*.d.ts"
]
} }

View File

@ -0,0 +1,34 @@
# CONTRIBUTING
## Pull requests
To submit your change:
- Make sure your code is in line with our
[coding conventions](##Coding-conventions).
- Create an [issue] describing the bug the PR fixes or the feature you intend
to implement.
- Submit a [pull request] into the main branch.
## Coding conventions
#### Format
The codebase is formatted by `Prettier` and the `.prettierrc.json` has been
configured.
- VSCode along with `Format on Save` configuration could easily format your
code during development.
- You can run `prettier-format-check` and `prettier-format-apply` to check and
format your codebase with `prettier` in terminal.
#### Lint
`ESlint` is used as linter for the codebase and the `.eslintrc.json` has been
configured.
- It's suggested to run `npm run lint` then fix errors and warnings before
committing.
[issue]: https://github.com/bytecodealliance/wasm-micro-runtime/issues
[pull request]: https://github.com/bytecodealliance/wasm-micro-runtime/pulls

View File

@ -6,10 +6,13 @@
> Note that when you download and > Note that when you download and
> decompress to get .vsix file from [our release](https://github.com/bytecodealliance/wasm-micro-runtime/releases). > decompress to get .vsix file from [our release](https://github.com/bytecodealliance/wasm-micro-runtime/releases).
> It's by default that the `source debugging` feature is not enabled. > It's by default that the `source debugging` feature is not enabled.
> If you want to enable `source debugging` feature of this extension, > If you want to enable the `source debugging` feature of this extension,
> you could either download `lldb` from [our release](https://github.com/bytecodealliance/wasm-micro-runtime/releases) and put them in correct path > you could download `lldb` from [our release](https://github.com/bytecodealliance/wasm-micro-runtime/releases)
mentioned in this [instruction](./resource/debug/README.md) (This is recommended way), > (This is the recommended way, and you could do it with a single click in VS Code).
> or you could build `lldb` yourself follow this [instruction](./resource/debug/README.md) > Then if you want to use your customized lldb patch,
> you could build your own version of `lldb`
> and then follow this [instruction](./resource/debug/README.md)
> to put them in the correct path
### 1. open `VSCode_Extension` directory with the `vscode` ### 1. open `VSCode_Extension` directory with the `vscode`

View File

@ -229,6 +229,7 @@
"watch": "tsc -watch -p ./", "watch": "tsc -watch -p ./",
"pretest": "npm run compile && npm run lint", "pretest": "npm run compile && npm run lint",
"lint": "eslint src --ext ts", "lint": "eslint src --ext ts",
"lint-fix": "eslint --fix src --ext ts",
"test": "node ./out/test/runTest.js", "test": "node ./out/test/runTest.js",
"prettier-format-check": "prettier --config .prettierrc.json 'src/**/*.ts' --check", "prettier-format-check": "prettier --config .prettierrc.json 'src/**/*.ts' --check",
"prettier-format-apply": "prettier --config .prettierrc.json 'src/**/*.ts' --write" "prettier-format-apply": "prettier --config .prettierrc.json 'src/**/*.ts' --write"

View File

@ -1,12 +1,14 @@
### If you want to enable `source debugging` for this extension, please build `lldb` firstly following this [instruction](../../../../../doc/source_debugging.md#debugging-with-interpreter). ### If you want to enable `source debugging` for this extension and use your own patched `lldb`, please build `lldb` firstly following this [instruction](../../../../../doc/source_debugging.md#debugging-with-interpreter)
### After building(`linux` for example), create `bin` folder and `lib` folder respectively in `linux` directory, add following necessary target files into the folders. ### After building(`linux` for example), create `bin` folder and `lib` folder respectively in `linux` directory, add following necessary target files into the folders
```shell ```shell
/llvm/build-lldb/bin/lldb # move this file to resource/debug/linux/bin/ /llvm/build-lldb/bin/lldb # move this file to {VS Code directory}/resource/debug/linux/bin/
/llvm/build-lldb/bin/lldb-vscode # move this file to resource/debug/linux/bin/ /llvm/build-lldb/bin/lldb-vscode # move this file to {VS Code directory}/resource/debug/linux/bin/
/llvm/build-lldb/lib/liblldb.so.13 # move this file to resource/debug/linux/lib/ /llvm/build-lldb/lib/liblldb.so.13 # move this file to {VS Code directory}/resource/debug/linux/lib/
``` ```
> If you are debugging this extension following this [tutorial](../../README.md), {VS Code directory} will be `{WAMR root directory}/test-tools/wamr-ide/VSCode-Extension`. If you want to replace the current lldb with your own patched version so that you can use your patched lldb in VS Code, {VS Code directory} will be `~/.vscode/extensions/wamr.wamride-1.1.2` or `~/.vscode-server/extensions/wamr.wamride-1.1.2`.
Note: For macOS, the library is named like `liblldb.13.0.1.dylib`. Note: For macOS, the library is named like `liblldb.13.0.1.dylib`.

View File

@ -3,7 +3,6 @@
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*/ */
const vscode = acquireVsCodeApi(); const vscode = acquireVsCodeApi();
document.getElementById('btn_submit').onclick = () => { document.getElementById('btn_submit').onclick = () => {
@ -12,16 +11,16 @@ document.getElementById('btn_submit').onclick = () => {
function submitFunc() { function submitFunc() {
let outputFileName = document.getElementById('output_file_name').value; let outputFileName = document.getElementById('output_file_name').value;
let initmemSize = document.getElementById('initial_mem_size').value; let initMemSize = document.getElementById('initial_mem_size').value;
let maxmemSize = document.getElementById('max_mem_size').value; let maxMemSize = document.getElementById('max_mem_size').value;
let stackSize = document.getElementById('stack_size').value; let stackSize = document.getElementById('stack_size').value;
let exportedSymbols = document.getElementById('exported_symbols').value; let exportedSymbols = document.getElementById('exported_symbols').value;
vscode.postMessage({ vscode.postMessage({
command: 'config_build_target', command: 'config_build_target',
outputFileName: outputFileName, outputFileName: outputFileName,
initmemSize: initmemSize, initMemSize: initMemSize,
maxmemSize: maxmemSize, maxMemSize: maxMemSize,
stackSize: stackSize, stackSize: stackSize,
exportedSymbols: exportedSymbols, exportedSymbols: exportedSymbols,
}); });

View File

@ -9,8 +9,6 @@ import * as os from 'os';
export class WasmDebugConfigurationProvider export class WasmDebugConfigurationProvider
implements vscode.DebugConfigurationProvider implements vscode.DebugConfigurationProvider
{ {
constructor() {}
/* default port set as 1234 */ /* default port set as 1234 */
private port = 1234; private port = 1234;
private hostPath!: string; private hostPath!: string;
@ -29,7 +27,7 @@ export class WasmDebugConfigurationProvider
return this.providerPromise; return this.providerPromise;
} }
public setDebugConfig(hostPath: string, port: number) { public setDebugConfig(hostPath: string, port: number): void {
this.port = port; this.port = port;
this.hostPath = hostPath; this.hostPath = hostPath;
/* linux and windows has different debug configuration */ /* linux and windows has different debug configuration */
@ -57,7 +55,7 @@ export class WasmDebugConfigurationProvider
} }
} }
public getDebugConfig() { public getDebugConfig(): vscode.DebugConfiguration {
return this.wasmDebugConfig; return this.wasmDebugConfig;
} }
} }

View File

@ -26,11 +26,11 @@ export class DecorationProvider implements vscode.FileDecorationProvider {
public onDidChangeFileDecorations: vscode.Event< public onDidChangeFileDecorations: vscode.Event<
vscode.Uri | vscode.Uri[] | undefined vscode.Uri | vscode.Uri[] | undefined
>; >;
private _eventEmiter: vscode.EventEmitter<vscode.Uri | vscode.Uri[]>; private eventEmitter: vscode.EventEmitter<vscode.Uri | vscode.Uri[]>;
constructor() { constructor() {
this._eventEmiter = new vscode.EventEmitter(); this.eventEmitter = new vscode.EventEmitter();
this.onDidChangeFileDecorations = this._eventEmiter.event; this.onDidChangeFileDecorations = this.eventEmitter.event;
this.disposables.push( this.disposables.push(
vscode.window.registerFileDecorationProvider(this) vscode.window.registerFileDecorationProvider(this)
); );
@ -39,34 +39,27 @@ export class DecorationProvider implements vscode.FileDecorationProvider {
public provideFileDecoration( public provideFileDecoration(
uri: vscode.Uri uri: vscode.Uri
): vscode.ProviderResult<vscode.FileDecoration> { ): vscode.ProviderResult<vscode.FileDecoration> {
let currentPrjDir, const currentPrjDir =
prjConfigDir,
configFilePath,
configData,
includePathArr = new Array(),
excludeFileArr = new Array(),
pathRelative;
/* Read include_paths and exclude_fils from the config file */
currentPrjDir =
os.platform() === 'win32' os.platform() === 'win32'
? (vscode.workspace.workspaceFolders?.[0].uri.fsPath as string) ? (vscode.workspace.workspaceFolders?.[0].uri.fsPath as string)
: os.platform() === 'linux' || os.platform() === 'darwin' : os.platform() === 'linux' || os.platform() === 'darwin'
? (currentPrjDir = vscode.workspace.workspaceFolders?.[0].uri ? (vscode.workspace.workspaceFolders?.[0].uri.path as string)
.path as string)
: ''; : '';
pathRelative = (uri.fsPath ? uri.fsPath : uri.toString()).replace( const pathRelative = (uri.fsPath ? uri.fsPath : uri.toString()).replace(
currentPrjDir, currentPrjDir,
'..' '..'
); );
prjConfigDir = path.join(currentPrjDir, '.wamr'); const prjConfigDir = path.join(currentPrjDir, '.wamr');
configFilePath = path.join(prjConfigDir, 'compilation_config.json'); const configFilePath = path.join(
prjConfigDir,
'compilation_config.json'
);
if (readFromFile(configFilePath) !== '') { if (readFromFile(configFilePath) !== '') {
configData = JSON.parse(readFromFile(configFilePath)); const configData = JSON.parse(readFromFile(configFilePath));
includePathArr = configData['include_paths']; const includePathArr = configData['includePaths'];
excludeFileArr = configData['exclude_files']; const excludeFileArr = configData['excludeFiles'];
if (includePathArr.indexOf(pathRelative) > -1) { if (includePathArr.indexOf(pathRelative) > -1) {
return DECORATION_INCLUDE_PATHS; return DECORATION_INCLUDE_PATHS;
@ -81,7 +74,7 @@ export class DecorationProvider implements vscode.FileDecorationProvider {
} }
public updateDecorationsForSource(uri: vscode.Uri): void { public updateDecorationsForSource(uri: vscode.Uri): void {
this._eventEmiter.fire(uri); this.eventEmitter.fire(uri);
} }
} }

View File

@ -26,13 +26,20 @@ import {
let wasmTaskProvider: WasmTaskProvider; let wasmTaskProvider: WasmTaskProvider;
let wasmDebugConfigProvider: WasmDebugConfigurationProvider; let wasmDebugConfigProvider: WasmDebugConfigurationProvider;
var currentPrjDir = ''; let currentPrjDir = '';
var extensionPath = ''; let isWasmProject = false;
var isWasmProject = false;
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export async function activate(context: vscode.ExtensionContext) { export async function activate(context: vscode.ExtensionContext) {
var OS_PLATFORM = '', const extensionPath = context.extensionPath;
buildScript = '', const osPlatform = os.platform();
const wamrVersion = getWAMRExtensionVersion(context);
const typeMap = new Map<string, string>();
const scriptMap = new Map<string, string>();
/* set relative path of build.bat|sh script */
const scriptPrefix = 'resource/scripts/';
let buildScript = '',
runScript = '', runScript = '',
debugScript = '', debugScript = '',
destroyScript = '', destroyScript = '',
@ -40,40 +47,27 @@ export async function activate(context: vscode.ExtensionContext) {
runScriptFullPath = '', runScriptFullPath = '',
debugScriptFullPath = '', debugScriptFullPath = '',
destroyScriptFullPath = '', destroyScriptFullPath = '',
typeMap = new Map(),
/* include paths array used for written into config file */ /* include paths array used for written into config file */
includePathArr = new Array(), includePathArr = new Array<string>(),
/* exclude files array used for written into config file */ /* exclude files array used for written into config file */
excludeFileArr = new Array(), excludeFileArr = new Array<string>();
scriptMap = new Map();
const wamrVersion = getWAMRExtensionVersion(context);
/**
* Get OS platform information for differ windows and linux execution script
*/
OS_PLATFORM = os.platform();
/** /**
* Provide Build & Run Task with Task Provider instead of "tasks.json" * Provide Build & Run Task with Task Provider instead of "tasks.json"
*/ */
/* set relative path of build.bat|sh script */ if (osPlatform === 'win32') {
let scriptPrefix = 'resource/scripts/';
if (OS_PLATFORM === 'win32') {
buildScript = scriptPrefix.concat('build.bat'); buildScript = scriptPrefix.concat('build.bat');
runScript = scriptPrefix.concat('run.bat'); runScript = scriptPrefix.concat('run.bat');
debugScript = scriptPrefix.concat('boot_debugger_server.bat'); debugScript = scriptPrefix.concat('boot_debugger_server.bat');
destroyScript = scriptPrefix.concat('destroy.bat'); destroyScript = scriptPrefix.concat('destroy.bat');
} else if (OS_PLATFORM === 'linux' || OS_PLATFORM === 'darwin') { } else if (osPlatform === 'linux' || osPlatform === 'darwin') {
buildScript = scriptPrefix.concat('build.sh'); buildScript = scriptPrefix.concat('build.sh');
runScript = scriptPrefix.concat('run.sh'); runScript = scriptPrefix.concat('run.sh');
debugScript = scriptPrefix.concat('boot_debugger_server.sh'); debugScript = scriptPrefix.concat('boot_debugger_server.sh');
destroyScript = scriptPrefix.concat('destroy.sh'); destroyScript = scriptPrefix.concat('destroy.sh');
} }
extensionPath = context.extensionPath;
buildScriptFullPath = path.join(extensionPath, buildScript); buildScriptFullPath = path.join(extensionPath, buildScript);
runScriptFullPath = path.join(extensionPath, runScript); runScriptFullPath = path.join(extensionPath, runScript);
debugScriptFullPath = path.join(extensionPath, debugScript); debugScriptFullPath = path.join(extensionPath, debugScript);
@ -94,10 +88,10 @@ export async function activate(context: vscode.ExtensionContext) {
vscode.tasks.registerTaskProvider('wasm', wasmTaskProvider); vscode.tasks.registerTaskProvider('wasm', wasmTaskProvider);
if (vscode.workspace.workspaceFolders?.[0]) { if (vscode.workspace.workspaceFolders?.[0]) {
if (OS_PLATFORM === 'win32') { if (osPlatform === 'win32') {
currentPrjDir = vscode.workspace.workspaceFolders?.[0].uri currentPrjDir = vscode.workspace.workspaceFolders?.[0].uri
.fsPath as string; .fsPath as string;
} else if (OS_PLATFORM === 'linux' || OS_PLATFORM === 'darwin') { } else if (osPlatform === 'linux' || osPlatform === 'darwin') {
currentPrjDir = vscode.workspace.workspaceFolders?.[0].uri currentPrjDir = vscode.workspace.workspaceFolders?.[0].uri
.path as string; .path as string;
} }
@ -107,7 +101,7 @@ export async function activate(context: vscode.ExtensionContext) {
* it not, `build`, `run` and `debug` will be disabled * it not, `build`, `run` and `debug` will be disabled
*/ */
if (currentPrjDir !== '') { if (currentPrjDir !== '') {
let wamrFolder = fileSystem const wamrFolder = fileSystem
.readdirSync(currentPrjDir, { .readdirSync(currentPrjDir, {
withFileTypes: true, withFileTypes: true,
}) })
@ -133,7 +127,7 @@ export async function activate(context: vscode.ExtensionContext) {
.getConfiguration() .getConfiguration()
.get('C_Cpp.default.systemIncludePath'); .get('C_Cpp.default.systemIncludePath');
let LibcBuiltinHeaderPath = path.join( const libcBuiltinHeaderPath = path.join(
extensionPath, extensionPath,
'resource/wamr-sdk/libc-builtin-sysroot/include' 'resource/wamr-sdk/libc-builtin-sysroot/include'
); );
@ -141,17 +135,17 @@ export async function activate(context: vscode.ExtensionContext) {
if (newIncludeInCppArr !== undefined) { if (newIncludeInCppArr !== undefined) {
/* in case the configuration has not been set up, push directly */ /* in case the configuration has not been set up, push directly */
if (newIncludeInCppArr === null) { if (newIncludeInCppArr === null) {
newIncludeInCppArr = new Array(); newIncludeInCppArr = [];
newIncludeInCppArr.push(LibcBuiltinHeaderPath); newIncludeInCppArr.push(libcBuiltinHeaderPath);
} else { } else {
/* if the configuration has been set up, check the condition */ /* if the configuration has been set up, check the condition */
if ( if (
/* include libc-builtin-sysroot */ /* include libc-builtin-sysroot */
newIncludeInCppArr.indexOf( newIncludeInCppArr.indexOf(
LibcBuiltinHeaderPath libcBuiltinHeaderPath
) < 0 ) < 0
) { ) {
newIncludeInCppArr.push(LibcBuiltinHeaderPath); newIncludeInCppArr.push(libcBuiltinHeaderPath);
} }
} }
@ -185,21 +179,21 @@ export async function activate(context: vscode.ExtensionContext) {
]); ]);
if (readFromConfigFile() !== '') { if (readFromConfigFile() !== '') {
let configData = JSON.parse(readFromConfigFile()); const configData = JSON.parse(readFromConfigFile());
includePathArr = configData['include_paths']; includePathArr = configData['includePaths'];
excludeFileArr = configData['exclude_files']; excludeFileArr = configData['excludeFiles'];
if (Object.keys(configData['build_args']).length !== 0) { if (Object.keys(configData['buildArgs']).length !== 0) {
TargetConfigPanel.BUILD_ARGS = configData['build_args']; TargetConfigPanel.buildArgs = configData['buildArgs'];
} }
} }
let disposableNewProj = vscode.commands.registerCommand( const disposableNewProj = vscode.commands.registerCommand(
'wamride.newProject', 'wamride.newProject',
() => { () => {
let _ok = 'Set up now'; const okStr = 'Set up now';
let _cancle = 'Maybe later'; const cancelStr = 'Maybe later';
let curWorkspace = vscode.workspace const curWorkspace = vscode.workspace
.getConfiguration() .getConfiguration()
.get('WAMR-IDE.configWorkspace'); .get('WAMR-IDE.configWorkspace');
@ -208,11 +202,11 @@ export async function activate(context: vscode.ExtensionContext) {
vscode.window vscode.window
.showWarningMessage( .showWarningMessage(
'Please setup your workspace firstly.', 'Please setup your workspace firstly.',
_ok, okStr,
_cancle cancelStr
) )
.then(item => { .then(item => {
if (item === _ok) { if (item === okStr) {
vscode.commands.executeCommand( vscode.commands.executeCommand(
'wamride.changeWorkspace' 'wamride.changeWorkspace'
); );
@ -233,10 +227,10 @@ export async function activate(context: vscode.ExtensionContext) {
.get('WAMR-IDE.configWorkspace') + .get('WAMR-IDE.configWorkspace') +
'', '',
}, },
_ok okStr
) )
.then(item => { .then(item => {
if (item === _ok) { if (item === okStr) {
vscode.commands.executeCommand( vscode.commands.executeCommand(
'wamride.changeWorkspace' 'wamride.changeWorkspace'
); );
@ -250,7 +244,7 @@ export async function activate(context: vscode.ExtensionContext) {
} }
); );
let disposableTargetConfig = vscode.commands.registerCommand( const disposableTargetConfig = vscode.commands.registerCommand(
'wamride.targetConfig', 'wamride.targetConfig',
() => { () => {
if (currentPrjDir !== '') { if (currentPrjDir !== '') {
@ -264,16 +258,16 @@ export async function activate(context: vscode.ExtensionContext) {
} }
); );
let disposableChangeWorkspace = vscode.commands.registerCommand( const disposableChangeWorkspace = vscode.commands.registerCommand(
'wamride.changeWorkspace', 'wamride.changeWorkspace',
async () => { async () => {
let options: vscode.OpenDialogOptions = { const options: vscode.OpenDialogOptions = {
canSelectFiles: false, canSelectFiles: false,
canSelectFolders: true, canSelectFolders: true,
openLabel: 'Select Workspace', openLabel: 'Select Workspace',
}; };
let Workspace = await vscode.window const workSpace = await vscode.window
.showOpenDialog(options) .showOpenDialog(options)
.then(res => { .then(res => {
if (res) { if (res) {
@ -284,21 +278,21 @@ export async function activate(context: vscode.ExtensionContext) {
}); });
/* update workspace value to vscode global settings */ /* update workspace value to vscode global settings */
if (Workspace !== '' && Workspace !== undefined) { if (workSpace !== '' && workSpace !== undefined) {
await vscode.workspace await vscode.workspace
.getConfiguration() .getConfiguration()
.update( .update(
'WAMR-IDE.configWorkspace', 'WAMR-IDE.configWorkspace',
Workspace.trim(), workSpace.trim(),
vscode.ConfigurationTarget.Global vscode.ConfigurationTarget.Global
) )
.then( .then(
success => { () => {
vscode.window.showInformationMessage( vscode.window.showInformationMessage(
'Workspace has been set up successfully!' 'Workspace has been set up successfully!'
); );
}, },
error => { () => {
vscode.window.showErrorMessage( vscode.window.showErrorMessage(
'Set up Workspace failed!' 'Set up Workspace failed!'
); );
@ -308,7 +302,7 @@ export async function activate(context: vscode.ExtensionContext) {
} }
); );
let disposableBuild = vscode.commands.registerCommand( const disposableBuild = vscode.commands.registerCommand(
'wamride.build', 'wamride.build',
() => { () => {
if (!isWasmProject) { if (!isWasmProject) {
@ -327,7 +321,7 @@ export async function activate(context: vscode.ExtensionContext) {
'Destroy: Wasm-Container-Before-Build' 'Destroy: Wasm-Container-Before-Build'
) )
.then(() => { .then(() => {
let disposable = vscode.tasks.onDidEndTaskProcess(t => { const disposable = vscode.tasks.onDidEndTaskProcess(t => {
if ( if (
t.execution.task.name === t.execution.task.name ===
'Wasm-Container-Before-Build' 'Wasm-Container-Before-Build'
@ -345,7 +339,7 @@ export async function activate(context: vscode.ExtensionContext) {
) )
.then(() => { .then(() => {
/* destroy the wasm-toolchain-ctr after building */ /* destroy the wasm-toolchain-ctr after building */
let disposable_aft = const disposableAft =
vscode.tasks.onDidEndTask(a => { vscode.tasks.onDidEndTask(a => {
if ( if (
a.execution.task.name === a.execution.task.name ===
@ -361,7 +355,7 @@ export async function activate(context: vscode.ExtensionContext) {
.then(() => { .then(() => {
/* dispose the event after this building process /* dispose the event after this building process
*/ */
disposable_aft.dispose(); disposableAft.dispose();
}); });
} }
}); });
@ -374,7 +368,7 @@ export async function activate(context: vscode.ExtensionContext) {
} }
); );
let disposableDebug = vscode.commands.registerCommand( const disposableDebug = vscode.commands.registerCommand(
'wamride.debug', 'wamride.debug',
async () => { async () => {
if (!isWasmProject) { if (!isWasmProject) {
@ -414,7 +408,7 @@ export async function activate(context: vscode.ExtensionContext) {
) )
.then(() => { .then(() => {
/* execute the debug task when destroy task finish */ /* execute the debug task when destroy task finish */
let disposable_bfr = vscode.tasks.onDidEndTask(t => { const disposableBfr = vscode.tasks.onDidEndTask(t => {
if ( if (
t.execution.task.name === t.execution.task.name ===
'Wasm-Container-Before-Debug' 'Wasm-Container-Before-Debug'
@ -432,7 +426,7 @@ export async function activate(context: vscode.ExtensionContext) {
) )
.then(() => { .then(() => {
/* register to listen debug session finish event */ /* register to listen debug session finish event */
let dispose_aft = const disposableAft =
vscode.debug.onDidTerminateDebugSession( vscode.debug.onDidTerminateDebugSession(
s => { s => {
if ( if (
@ -455,18 +449,19 @@ export async function activate(context: vscode.ExtensionContext) {
'Debug: Wasm' 'Debug: Wasm'
); );
dispose_aft.dispose(); disposableAft.dispose();
} }
); );
}); });
}); });
} }
disposable_bfr.dispose(); disposableBfr.dispose();
}); });
}); });
} }
); );
let disposableRun = vscode.commands.registerCommand('wamride.run', () => {
const disposableRun = vscode.commands.registerCommand('wamride.run', () => {
if (!isWasmProject) { if (!isWasmProject) {
vscode.window.showErrorMessage('run failed', { vscode.window.showErrorMessage('run failed', {
modal: true, modal: true,
@ -489,7 +484,7 @@ export async function activate(context: vscode.ExtensionContext) {
'Destroy: Wasm-Container-Before-Run' 'Destroy: Wasm-Container-Before-Run'
) )
.then(() => { .then(() => {
let dispose_bfr = vscode.tasks.onDidEndTaskProcess(e => { const disposableAft = vscode.tasks.onDidEndTaskProcess(e => {
if (e.execution.task.name === 'Wasm-Container-Before-Run') { if (e.execution.task.name === 'Wasm-Container-Before-Run') {
/* make sure that run wasm task will be executed after destroy task finish */ /* make sure that run wasm task will be executed after destroy task finish */
vscode.commands vscode.commands
@ -499,25 +494,24 @@ export async function activate(context: vscode.ExtensionContext) {
) )
.then(() => { .then(() => {
if (e.exitCode !== 0) { if (e.exitCode !== 0) {
dispose_bfr.dispose(); disposableAft.dispose();
return; return;
} }
}); });
dispose_bfr.dispose(); disposableAft.dispose();
} }
}); });
}); });
}); });
let disposableToggleIncludePath = vscode.commands.registerCommand( const disposableToggleIncludePath = vscode.commands.registerCommand(
'wamride.build.toggleStateIncludePath', 'wamride.build.toggleStateIncludePath',
fileUri => { fileUri => {
let pathRelative: string; const path =
let path =
fileUri._fsPath !== null && fileUri._fsPath !== undefined fileUri._fsPath !== null && fileUri._fsPath !== undefined
? fileUri._fsPath ? fileUri._fsPath
: vscode.Uri.parse(fileUri.path as string).fsPath; : vscode.Uri.parse(fileUri.path as string).fsPath;
pathRelative = path.replace(currentPrjDir, '..'); const pathRelative = path.replace(currentPrjDir, '..');
if (includePathArr.indexOf(pathRelative) > -1) { if (includePathArr.indexOf(pathRelative) > -1) {
/* this folder has been added to include path, remove it */ /* this folder has been added to include path, remove it */
@ -531,25 +525,23 @@ export async function activate(context: vscode.ExtensionContext) {
writeIntoConfigFile( writeIntoConfigFile(
includePathArr, includePathArr,
excludeFileArr, excludeFileArr,
TargetConfigPanel.BUILD_ARGS TargetConfigPanel.buildArgs
); );
decorationProvider.updateDecorationsForSource(fileUri); decorationProvider.updateDecorationsForSource(fileUri);
} }
); );
let disposableToggleExcludeFile = vscode.commands.registerCommand( const disposableToggleExcludeFile = vscode.commands.registerCommand(
'wamride.build.toggleStateExclude', 'wamride.build.toggleStateExclude',
fileUri => { fileUri => {
let pathRelative: string; const path =
let path =
fileUri._fsPath !== null && fileUri._fsPath !== undefined fileUri._fsPath !== null && fileUri._fsPath !== undefined
? fileUri._fsPath ? fileUri._fsPath
: vscode.Uri.parse(fileUri.path as string).fsPath; : vscode.Uri.parse(fileUri.path as string).fsPath;
/* replace the current project absolute path with .. to change to relative path */ /* replace the current project absolute path with .. to change to relative path */
pathRelative = path.replace(currentPrjDir, '..'); const pathRelative = path.replace(currentPrjDir, '..');
if (excludeFileArr.indexOf(pathRelative) > -1) { if (excludeFileArr.indexOf(pathRelative) > -1) {
excludeFileArr = excludeFileArr.filter(val => { excludeFileArr = excludeFileArr.filter(val => {
@ -562,7 +554,7 @@ export async function activate(context: vscode.ExtensionContext) {
writeIntoConfigFile( writeIntoConfigFile(
includePathArr, includePathArr,
excludeFileArr, excludeFileArr,
TargetConfigPanel.BUILD_ARGS TargetConfigPanel.buildArgs
); );
/* update decoration for this source file */ /* update decoration for this source file */
@ -570,14 +562,14 @@ export async function activate(context: vscode.ExtensionContext) {
} }
); );
let disposableOpenFolder = vscode.commands.registerCommand( const disposableOpenFolder = vscode.commands.registerCommand(
'wamride.openFolder', 'wamride.openFolder',
() => { () => {
/* get projects list under current workspace */ /* get projects list under current workspace */
let _ok = 'Set up now'; const okStr = 'Set up now';
let _cancle = 'Maybe later'; const cancelStr = 'Maybe later';
let _create = 'Create now'; const createStr = 'Create now';
let curWorkspace = vscode.workspace const curWorkspace = vscode.workspace
.getConfiguration() .getConfiguration()
.get('WAMR-IDE.configWorkspace') as string; .get('WAMR-IDE.configWorkspace') as string;
@ -586,11 +578,11 @@ export async function activate(context: vscode.ExtensionContext) {
vscode.window vscode.window
.showWarningMessage( .showWarningMessage(
'Please setup your workspace firstly.', 'Please setup your workspace firstly.',
_ok, okStr,
_cancle cancelStr
) )
.then(item => { .then(item => {
if (item === _ok) { if (item === okStr) {
vscode.commands.executeCommand( vscode.commands.executeCommand(
'wamride.changeWorkspace' 'wamride.changeWorkspace'
); );
@ -611,10 +603,10 @@ export async function activate(context: vscode.ExtensionContext) {
.get('WAMR-IDE.configWorkspace') + .get('WAMR-IDE.configWorkspace') +
'', '',
}, },
_ok okStr
) )
.then(item => { .then(item => {
if (item === _ok) { if (item === okStr) {
vscode.commands.executeCommand( vscode.commands.executeCommand(
'wamride.changeWorkspace' 'wamride.changeWorkspace'
); );
@ -640,7 +632,7 @@ export async function activate(context: vscode.ExtensionContext) {
.filter(dirent => dirent.isDirectory()) .filter(dirent => dirent.isDirectory())
.map(dirent => dirent.name); .map(dirent => dirent.name);
let projFilesArr = directoryArr.filter(obj => { const projFilesArr = directoryArr.filter(obj => {
if (checkIfWasmProj(path.join(curWorkspace, obj))) { if (checkIfWasmProj(path.join(curWorkspace, obj))) {
return true; return true;
} }
@ -650,11 +642,11 @@ export async function activate(context: vscode.ExtensionContext) {
vscode.window vscode.window
.showWarningMessage( .showWarningMessage(
'Current workspace is empty, please create your project firstly.', 'Current workspace is empty, please create your project firstly.',
_create, createStr,
_cancle cancelStr
) )
.then(item => { .then(item => {
if (item === _create) { if (item === createStr) {
vscode.commands.executeCommand( vscode.commands.executeCommand(
'wamride.newProject' 'wamride.newProject'
); );
@ -673,18 +665,18 @@ export async function activate(context: vscode.ExtensionContext) {
return; return;
} }
let _path = curWorkspace.concat( const path = curWorkspace.concat(
OS_PLATFORM === 'win32' osPlatform === 'win32'
? '\\' ? '\\'
: OS_PLATFORM === 'linux' || : osPlatform === 'linux' ||
OS_PLATFORM === 'darwin' osPlatform === 'darwin'
? '/' ? '/'
: '', : '',
option option
); );
/* open the selected wasm project */ /* open the selected wasm project */
openWindoWithSituation(vscode.Uri.file(_path)); openWindowWithSituation(vscode.Uri.file(path));
}); });
} }
} }
@ -713,13 +705,14 @@ export async function activate(context: vscode.ExtensionContext) {
} }
} }
function openWindoWithSituation(uri: vscode.Uri) { function openWindowWithSituation(uri: vscode.Uri) {
/** /**
* check if the workspace folder is empty, * check if the workspace folder is empty,
* if yes, open new window, else open in current window * if yes, open new window, else open in current window
*/ */
let isWorkspaceEmpty: boolean; const isWorkspaceEmpty = !vscode.workspace.workspaceFolders?.[0]
isWorkspaceEmpty = !vscode.workspace.workspaceFolders?.[0] ? true : false; ? true
: false;
isWorkspaceEmpty === false isWorkspaceEmpty === false
? vscode.commands.executeCommand('vscode.openFolder', uri, { ? vscode.commands.executeCommand('vscode.openFolder', uri, {
@ -731,11 +724,11 @@ function openWindoWithSituation(uri: vscode.Uri) {
} }
interface BuildArgs { interface BuildArgs {
output_file_name: string; outputFileName: string;
init_memory_size: string; initMemorySize: string;
max_memory_size: string; maxMemorySize: string;
stack_size: string; stackSize: string;
exported_symbols: string; exportedSymbols: string;
} }
/** /**
@ -748,25 +741,25 @@ export function writeIntoConfigFile(
includePathArr: string[], includePathArr: string[],
excludeFileArr: string[], excludeFileArr: string[],
buildArgs?: BuildArgs buildArgs?: BuildArgs
) { ): void {
let jsonStr = JSON.stringify( const jsonStr = JSON.stringify(
{ {
include_paths: includePathArr, includePaths: includePathArr,
exclude_files: excludeFileArr, excludeFiles: excludeFileArr,
build_args: buildArgs ? buildArgs : '{}', buildArgs: buildArgs ? buildArgs : '{}',
}, },
null, null,
'\t' '\t'
); );
let prjConfigDir = path.join(currentPrjDir, '.wamr'); const prjConfigDir = path.join(currentPrjDir, '.wamr');
let configFilePath = path.join(prjConfigDir, 'compilation_config.json'); const configFilePath = path.join(prjConfigDir, 'compilation_config.json');
writeIntoFile(configFilePath, jsonStr); writeIntoFile(configFilePath, jsonStr);
} }
export function readFromConfigFile(): string { export function readFromConfigFile(): string {
let prjConfigDir = path.join(currentPrjDir, '.wamr'); const prjConfigDir = path.join(currentPrjDir, '.wamr');
let configFilePath = path.join(prjConfigDir, 'compilation_config.json'); const configFilePath = path.join(prjConfigDir, 'compilation_config.json');
return readFromFile(configFilePath); return readFromFile(configFilePath);
} }
@ -778,9 +771,9 @@ function generateCMakeFile(
excludeFileArr: string[] excludeFileArr: string[]
): void { ): void {
// -Wl,--export=${EXPORT_SYMBOLS} // -Wl,--export=${EXPORT_SYMBOLS}
let srcFilePath = path.join(currentPrjDir, 'src'); const srcFilePath = path.join(currentPrjDir, 'src');
let prjConfigDir = path.join(currentPrjDir, '.wamr'); const prjConfigDir = path.join(currentPrjDir, '.wamr');
let cmakeFilePath = path.join(prjConfigDir, 'project.cmake'); const cmakeFilePath = path.join(prjConfigDir, 'project.cmake');
let strIncludeList = 'set (PROJECT_INCLUDES'; let strIncludeList = 'set (PROJECT_INCLUDES';
let strSrcList = 'set (PROJECT_SRC_LIST'; let strSrcList = 'set (PROJECT_SRC_LIST';
@ -795,17 +788,16 @@ function generateCMakeFile(
let i, s, e: number; let i, s, e: number;
/* change the absolute path into relative path */ /* change the absolute path into relative path */
let _re = currentPrjDir; const _re = currentPrjDir;
let _substr = '${CMAKE_CURRENT_SOURCE_DIR}/..'; const _substr = '${CMAKE_CURRENT_SOURCE_DIR}/..';
let srcPathArr: Array<{ path: string }> | undefined;
/** /**
* set PROJECT_SRC_LIST * set PROJECT_SRC_LIST
* default ADD every c OR c++ OR cpp under the src/ path * default ADD every c OR c++ OR cpp under the src/ path
* except the files saved in the exclude_files array * except the files saved in the excludeFiles array
*/ */
srcPathArr = getAllSrcFiles(srcFilePath); const srcPathArr = getAllSrcFiles(srcFilePath);
if (srcPathArr === undefined) { if (srcPathArr === undefined) {
return; return;
@ -818,46 +810,46 @@ function generateCMakeFile(
) === -1 ) === -1
) { ) {
/* replace currentPrjDir with ${CMAKE_CURRENT_SOURCE_DIR} */ /* replace currentPrjDir with ${CMAKE_CURRENT_SOURCE_DIR} */
let _newStr = srcPathArr[s].path const newStr = srcPathArr[s].path
.replace(_re, _substr) .replace(_re, _substr)
.replace(/\\/g, '/'); .replace(/\\/g, '/');
strSrcList = strSrcList.concat(' ', _newStr); strSrcList = strSrcList.concat(' ', newStr);
} }
} }
strSrcList = strSrcList.concat(' )'); strSrcList = strSrcList.concat(' )');
for (i = 0; i < includePathArr.length; i++) { for (i = 0; i < includePathArr.length; i++) {
let _newStr = includePathArr[i] const newStr = includePathArr[i]
.replace(/../, _substr) .replace(/../, _substr)
.replace(/\\/g, '/'); .replace(/\\/g, '/');
strIncludeList = strIncludeList.concat(' ', _newStr); strIncludeList = strIncludeList.concat(' ', newStr);
} }
strIncludeList = strIncludeList.concat(' )'); strIncludeList = strIncludeList.concat(' )');
/* set up user customized input in configBuildArgs webview */ /* set up user customized input in configBuildArgs webview */
strOutputFileName = strOutputFileName.concat( strOutputFileName = strOutputFileName.concat(
' ', ' ',
TargetConfigPanel.BUILD_ARGS.output_file_name + ')' TargetConfigPanel.buildArgs.outputFileName + ')'
); );
strInitMemSize = strInitMemSize.concat( strInitMemSize = strInitMemSize.concat(
' ', ' ',
TargetConfigPanel.BUILD_ARGS.init_memory_size + ')' TargetConfigPanel.buildArgs.initMemorySize + ')'
); );
strMaxMemSize = strMaxMemSize.concat( strMaxMemSize = strMaxMemSize.concat(
' ', ' ',
TargetConfigPanel.BUILD_ARGS.max_memory_size + ')' TargetConfigPanel.buildArgs.maxMemorySize + ')'
); );
strStackSize = strStackSize.concat( strStackSize = strStackSize.concat(
' ', ' ',
TargetConfigPanel.BUILD_ARGS.stack_size + ')' TargetConfigPanel.buildArgs.stackSize + ')'
); );
let exportedSymbolArr = const exportedSymbolArr =
TargetConfigPanel.BUILD_ARGS.exported_symbols.split(','); TargetConfigPanel.buildArgs.exportedSymbols.split(',');
strExportedSymbols = strExportedSymbols.concat(' "'); strExportedSymbols = strExportedSymbols.concat(' "');
@ -901,7 +893,7 @@ function getAllSrcFiles(_path: string) {
const folders = entries.filter(folder => folder.isDirectory()); const folders = entries.filter(folder => folder.isDirectory());
for (const folder of folders) { for (const folder of folders) {
let fileArr = getAllSrcFiles(path.join(_path, folder.name)); const fileArr = getAllSrcFiles(path.join(_path, folder.name));
fileArr ? files.push(...fileArr) : ''; fileArr ? files.push(...fileArr) : '';
} }
@ -911,7 +903,7 @@ function getAllSrcFiles(_path: string) {
} }
} }
function checkIfBuildSuccess(): Boolean { function checkIfBuildSuccess(): boolean {
try { try {
let wasmExist = false; let wasmExist = false;
const entries = fileSystem.readdirSync( const entries = fileSystem.readdirSync(
@ -933,10 +925,10 @@ function checkIfBuildSuccess(): Boolean {
} }
} }
function checkIfWasmProj(_path: string): Boolean { function checkIfWasmProj(path: string): boolean {
try { try {
let isWasmProj = false; let isWasmProj = false;
const entries = fileSystem.readdirSync(_path, { const entries = fileSystem.readdirSync(path, {
withFileTypes: true, withFileTypes: true,
}); });

View File

@ -29,8 +29,8 @@ export class WasmTaskProvider implements vscode.TaskProvider {
public provideTasks(): Thenable<vscode.Task[]> | undefined { public provideTasks(): Thenable<vscode.Task[]> | undefined {
if (!this.wasmPromise) { if (!this.wasmPromise) {
/* target name is used for generated aot target */ /* target name is used for generated aot target */
let targetName = const targetName =
TargetConfigPanel.BUILD_ARGS.output_file_name.split('.')[0]; TargetConfigPanel.buildArgs.outputFileName.split('.')[0];
if ( if (
os.platform() === 'linux' || os.platform() === 'linux' ||
@ -219,7 +219,10 @@ export class WasmTaskProvider implements vscode.TaskProvider {
* @param _task * @param _task
* @returns * @returns
*/ */
public resolveTask(_task: vscode.Task): vscode.Task | undefined { public resolveTask(task: vscode.Task): vscode.Task | undefined {
if (task) {
return task;
}
return undefined; return undefined;
} }
} }

View File

@ -31,7 +31,7 @@ export function createDirectory(
return false; return false;
} }
let parent = path.dirname(dest); const parent = path.dirname(dest);
if (!createDirectory(parent, mode)) { if (!createDirectory(parent, mode)) {
return false; return false;
} }
@ -44,6 +44,7 @@ export function createDirectory(
} }
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function copyFiles(src: string, dest: string, flags?: number): boolean { export function copyFiles(src: string, dest: string, flags?: number): boolean {
try { try {
fileSystem.copyFileSync(src, dest); fileSystem.copyFileSync(src, dest);
@ -64,7 +65,7 @@ export function writeIntoFile(path: string, data: string): void {
export function readFromFile(path: string): string { export function readFromFile(path: string): string {
try { try {
let data = fileSystem.readFileSync(path, { encoding: 'utf-8' }); const data = fileSystem.readFileSync(path, { encoding: 'utf-8' });
return data as string; return data as string;
} catch (err) { } catch (err) {
vscode.window.showErrorMessage(err as string); vscode.window.showErrorMessage(err as string);
@ -114,9 +115,9 @@ export function checkIfFileExists(path: string): boolean {
return false; return false;
} }
export function checkFolderName(folderName: string) { export function checkFolderName(folderName: string): boolean {
let invalidCharacterArr: string[] = []; let invalidCharacterArr: string[] = [];
var valid = true; let valid = true;
if (folderName.length > 255) { if (folderName.length > 255) {
valid = false; valid = false;
@ -143,6 +144,7 @@ export function downloadFile(
): Promise<void> { ): Promise<void> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const file = fileSystem.createWriteStream(destinationPath); const file = fileSystem.createWriteStream(destinationPath);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const stream = request(url, undefined, (error, response, body) => { const stream = request(url, undefined, (error, response, body) => {
if (response.statusCode !== 200) { if (response.statusCode !== 200) {
reject( reject(

View File

@ -9,6 +9,6 @@ export function getUri(
webview: Webview, webview: Webview,
extensionUri: Uri, extensionUri: Uri,
pathList: string[] pathList: string[]
) { ): Uri {
return webview.asWebviewUri(Uri.joinPath(extensionUri, ...pathList)); return webview.asWebviewUri(Uri.joinPath(extensionUri, ...pathList));
} }

View File

@ -27,7 +27,7 @@ const WAMR_LLDB_NOT_SUPPORTED_ERROR = new Error(
function getLLDBUnzipFilePath(destinationFolder: string, filename: string) { function getLLDBUnzipFilePath(destinationFolder: string, filename: string) {
const dirs = filename.split('/'); const dirs = filename.split('/');
if (dirs[0] === 'inst') { if (dirs[0] === 'wamr-lldb') {
dirs.shift(); dirs.shift();
} }
@ -37,6 +37,7 @@ function getLLDBUnzipFilePath(destinationFolder: string, filename: string) {
export function getWAMRExtensionVersion( export function getWAMRExtensionVersion(
context: vscode.ExtensionContext context: vscode.ExtensionContext
): string { ): string {
// eslint-disable-next-line @typescript-eslint/no-var-requires
return require(path.join(context.extensionPath, 'package.json')).version; return require(path.join(context.extensionPath, 'package.json')).version;
} }
@ -64,7 +65,9 @@ export function isLLDBInstalled(context: vscode.ExtensionContext): boolean {
return checkIfFileExists(lldbBinaryPath); return checkIfFileExists(lldbBinaryPath);
} }
export async function promptInstallLLDB(context: vscode.ExtensionContext) { export async function promptInstallLLDB(
context: vscode.ExtensionContext
): Promise<void> {
const extensionPath = context.extensionPath; const extensionPath = context.extensionPath;
const setupPrompt = 'setup'; const setupPrompt = 'setup';
const skipPrompt = 'skip'; const skipPrompt = 'skip';
@ -111,5 +114,7 @@ export async function promptInstallLLDB(context: vscode.ExtensionContext) {
); );
// Remove the bundle.zip // Remove the bundle.zip
fs.unlink(lldbZipPath, () => {}); fs.unlink(lldbZipPath, () => {
return;
});
} }

View File

@ -15,35 +15,37 @@ import {
import { getUri } from '../utilities/getUri'; import { getUri } from '../utilities/getUri';
export class NewProjectPanel { export class NewProjectPanel {
static USER_SET_WORKSPACE: string; public static userSetWorkSpace: string;
public static currentPanel: NewProjectPanel | undefined; public static currentPanel: NewProjectPanel | undefined;
private readonly _panel: vscode.WebviewPanel; private readonly viewPanel: vscode.WebviewPanel;
private _disposables: vscode.Disposable[] = []; private disposableArr: vscode.Disposable[] = [];
static readonly EXCUTION_SUCCESS: number = 0; private static readonly executionSuccess = 0;
static readonly DIR_EXSITED_ERR: number = -1; private static readonly dirExistedError = -1;
static readonly USER_INTPUT_ERR: number = -2; private static readonly userInputError = -2;
static readonly DIR_PATH_INVALID_ERR: number = -3; private static readonly dirPathInvalidError = -3;
constructor(extensionUri: vscode.Uri, panel: vscode.WebviewPanel) { constructor(extensionUri: vscode.Uri, panel: vscode.WebviewPanel) {
this._panel = panel; this.viewPanel = panel;
this._panel.webview.html = this._getHtmlForWebview( this.viewPanel.webview.html = this.getHtmlForWebview(
this._panel.webview, this.viewPanel.webview,
extensionUri, extensionUri,
'resource/webview/page/newProject.html' 'resource/webview/page/newProject.html'
); );
this._setWebviewMessageListener(this._panel.webview, extensionUri); this._setWebviewMessageListener(this.viewPanel.webview, extensionUri);
this._panel.onDidDispose(this.dispose, null, this._disposables); this.viewPanel.onDidDispose(this.dispose, null, this.disposableArr);
} }
public static render(context: vscode.ExtensionContext) { public static render(context: vscode.ExtensionContext): void {
NewProjectPanel.USER_SET_WORKSPACE = vscode.workspace NewProjectPanel.userSetWorkSpace = vscode.workspace
.getConfiguration() .getConfiguration()
.get('WAMR-IDE.configWorkspace') as string; .get('WAMR-IDE.configWorkspace') as string;
/* check if current panel is initialized */ /* check if current panel is initialized */
if (NewProjectPanel.currentPanel) { if (NewProjectPanel.currentPanel) {
NewProjectPanel.currentPanel._panel.reveal(vscode.ViewColumn.One); NewProjectPanel.currentPanel.viewPanel.reveal(
vscode.ViewColumn.One
);
} else { } else {
const panel = vscode.window.createWebviewPanel( const panel = vscode.window.createWebviewPanel(
'newProject', 'newProject',
@ -62,25 +64,25 @@ export class NewProjectPanel {
} }
} }
private _creatNewProject( private createNewProject(
projName: string, projName: string,
template: string, template: string,
extensionUri: vscode.Uri extensionUri: vscode.Uri
): number { ): number {
if (projName === '' || template === '') { if (projName === '' || template === '') {
return NewProjectPanel.USER_INTPUT_ERR; return NewProjectPanel.userInputError;
} }
if (!checkFolderName(projName)) { if (!checkFolderName(projName)) {
return NewProjectPanel.DIR_PATH_INVALID_ERR; return NewProjectPanel.dirPathInvalidError;
} }
let ROOT_PATH = path.join(NewProjectPanel.USER_SET_WORKSPACE, projName); const ROOT_PATH = path.join(NewProjectPanel.userSetWorkSpace, projName);
let EXT_PATH = extensionUri.fsPath; const EXT_PATH = extensionUri.fsPath;
if (fs.existsSync(ROOT_PATH)) { if (fs.existsSync(ROOT_PATH)) {
if (fs.lstatSync(ROOT_PATH).isDirectory()) { if (fs.lstatSync(ROOT_PATH).isDirectory()) {
return NewProjectPanel.DIR_EXSITED_ERR; return NewProjectPanel.dirExistedError;
} }
} }
@ -98,14 +100,14 @@ export class NewProjectPanel {
path.join(ROOT_PATH, '.wamr/project.cmake') path.join(ROOT_PATH, '.wamr/project.cmake')
); );
return NewProjectPanel.EXCUTION_SUCCESS; return NewProjectPanel.executionSuccess;
} }
public _getHtmlForWebview( public getHtmlForWebview(
webview: vscode.Webview, webview: vscode.Webview,
extensionUri: vscode.Uri, extensionUri: vscode.Uri,
templatePath: string templatePath: string
) { ): string {
const toolkitUri = getUri(webview, extensionUri, [ const toolkitUri = getUri(webview, extensionUri, [
'node_modules', 'node_modules',
'@vscode', '@vscode',
@ -146,14 +148,14 @@ export class NewProjectPanel {
message => { message => {
switch (message.command) { switch (message.command) {
case 'create_new_project': case 'create_new_project':
let createNewProjectStatus = this._creatNewProject( const createNewProjectStatus = this.createNewProject(
message.projectName, message.projectName,
message.template, message.template,
extensionUri extensionUri
); );
if ( if (
createNewProjectStatus === createNewProjectStatus ===
NewProjectPanel.EXCUTION_SUCCESS NewProjectPanel.executionSuccess
) { ) {
webview.postMessage({ webview.postMessage({
command: 'proj_creation_finish', command: 'proj_creation_finish',
@ -161,17 +163,17 @@ export class NewProjectPanel {
}); });
} else if ( } else if (
createNewProjectStatus === createNewProjectStatus ===
NewProjectPanel.DIR_EXSITED_ERR NewProjectPanel.dirExistedError
) { ) {
vscode.window.showErrorMessage( vscode.window.showErrorMessage(
'Project : ' + 'Project : ' +
message.projectName + message.projectName +
' exsits in your current root path, please change project name or root path!' ' exists in your current root path, please change project name or root path!'
); );
return; return;
} else if ( } else if (
createNewProjectStatus === createNewProjectStatus ===
NewProjectPanel.USER_INTPUT_ERR NewProjectPanel.userInputError
) { ) {
vscode.window.showErrorMessage( vscode.window.showErrorMessage(
'Please fill chart before your submit!' 'Please fill chart before your submit!'
@ -179,7 +181,7 @@ export class NewProjectPanel {
return; return;
} else if ( } else if (
createNewProjectStatus === createNewProjectStatus ===
NewProjectPanel.DIR_PATH_INVALID_ERR NewProjectPanel.dirPathInvalidError
) { ) {
if (os.platform() === 'win32') { if (os.platform() === 'win32') {
vscode.window.showErrorMessage( vscode.window.showErrorMessage(
@ -203,19 +205,18 @@ export class NewProjectPanel {
message.projectName + message.projectName +
' will be opened!' ' will be opened!'
); );
let isWorkspaceEmpty: boolean;
let projPath = path.join( const projPath = path.join(
NewProjectPanel.USER_SET_WORKSPACE, NewProjectPanel.userSetWorkSpace,
message.projectName message.projectName
); );
let uri = vscode.Uri.file(projPath); const uri = vscode.Uri.file(projPath);
/** /**
* check if the vscode workspace folder is empty, * check if the vscode workspace folder is empty,
* if yes, open new window, else open in current window * if yes, open new window, else open in current window
*/ */
isWorkspaceEmpty = !vscode.workspace const isWorkspaceEmpty = !vscode.workspace
.workspaceFolders?.[0] .workspaceFolders?.[0]
? true ? true
: false; : false;
@ -233,7 +234,7 @@ export class NewProjectPanel {
); );
case 'close_webview': case 'close_webview':
this._panel.dispose(); this.viewPanel.dispose();
return; return;
default: default:
@ -241,16 +242,16 @@ export class NewProjectPanel {
} }
}, },
undefined, undefined,
this._disposables this.disposableArr
); );
} }
private dispose() { private dispose() {
NewProjectPanel.currentPanel = undefined; NewProjectPanel.currentPanel = undefined;
this._panel.dispose(); this.viewPanel.dispose();
while (this._disposables.length) { while (this.disposableArr.length) {
const disposable = this._disposables.pop(); const disposable = this.disposableArr.pop();
if (disposable) { if (disposable) {
disposable.dispose(); disposable.dispose();
} }

View File

@ -11,19 +11,19 @@ import { getUri } from '../utilities/getUri';
export class TargetConfigPanel { export class TargetConfigPanel {
public static currentPanel: TargetConfigPanel | undefined; public static currentPanel: TargetConfigPanel | undefined;
private readonly _panel: vscode.WebviewPanel; private readonly viewPanel: vscode.WebviewPanel;
private _disposables: vscode.Disposable[] = []; private _disposables: vscode.Disposable[] = [];
public static BUILD_ARGS = { public static buildArgs = {
output_file_name: 'main.wasm', outputFileName: 'main.wasm',
init_memory_size: '131072', initMemorySize: '131072',
max_memory_size: '131072', maxMemorySize: '131072',
stack_size: '4096', stackSize: '4096',
exported_symbols: 'main', exportedSymbols: 'main',
}; };
static readonly USER_INTPUT_ERR: number = -2; private static readonly userInputError: number = -2;
static readonly EXCUTION_SUCCESS: number = 0; private static readonly executionSuccess: number = 0;
/** /**
* *
@ -31,24 +31,26 @@ export class TargetConfigPanel {
* @param panelName * @param panelName
*/ */
constructor(panel: vscode.WebviewPanel, extensionUri: vscode.Uri) { constructor(panel: vscode.WebviewPanel, extensionUri: vscode.Uri) {
this._panel = panel; this.viewPanel = panel;
this._panel.webview.html = this._getHtmlForWebview( this.viewPanel.webview.html = this._getHtmlForWebview(
this._panel.webview, this.viewPanel.webview,
extensionUri, extensionUri,
'resource/webview/page/configBuildTarget.html' 'resource/webview/page/configBuildTarget.html'
); );
this._panel.onDidDispose(this.dispose, null, this._disposables); this.viewPanel.onDidDispose(this.dispose, null, this._disposables);
this._setWebviewMessageListener(this._panel.webview); this._setWebviewMessageListener(this.viewPanel.webview);
} }
/** /**
* *
* @param context * @param context
*/ */
public static render(context: vscode.ExtensionContext) { public static render(context: vscode.ExtensionContext): void {
/* check if current panel is initialized */ /* check if current panel is initialized */
if (TargetConfigPanel.currentPanel) { if (TargetConfigPanel.currentPanel) {
TargetConfigPanel.currentPanel._panel.reveal(vscode.ViewColumn.One); TargetConfigPanel.currentPanel.viewPanel.reveal(
vscode.ViewColumn.One
);
} else { } else {
const panel = vscode.window.createWebviewPanel( const panel = vscode.window.createWebviewPanel(
'targetConfig', 'targetConfig',
@ -67,59 +69,56 @@ export class TargetConfigPanel {
} }
} }
private _configBuildArgs( private configBuildArgs(
outputFileName: string, outputFileName: string,
initmemSize: string, initMemSize: string,
maxmemSize: string, maxMemSize: string,
stackSize: string, stackSize: string,
exportedSymbols: string exportedSymbols: string
): number { ): number {
if ( if (
outputFileName === '' || outputFileName === '' ||
initmemSize === '' || initMemSize === '' ||
maxmemSize === '' || maxMemSize === '' ||
stackSize === '' || stackSize === '' ||
exportedSymbols === '' exportedSymbols === ''
) { ) {
return TargetConfigPanel.USER_INTPUT_ERR; return TargetConfigPanel.userInputError;
} }
let _configStr: string; let includePathArr = [];
let includePathArr = new Array(); let excludeFileArr = [];
let excludeFileArr = new Array();
let configJson: any;
let _configObj = { const configObj = {
output_file_name: outputFileName, outputFileName: outputFileName,
init_memory_size: initmemSize, initMemorySize: initMemSize,
max_memory_size: maxmemSize, maxMemorySize: maxMemSize,
stack_size: stackSize, stackSize: stackSize,
exported_symbols: exportedSymbols, exportedSymbols: exportedSymbols,
}; };
const configStr = readFromConfigFile();
TargetConfigPanel.BUILD_ARGS = _configObj; TargetConfigPanel.buildArgs = configObj;
_configStr = readFromConfigFile(); if (configStr !== '' && configStr !== undefined) {
const configJson = JSON.parse(configStr);
if (_configStr !== '' && _configStr !== undefined) {
configJson = JSON.parse(_configStr);
includePathArr = includePathArr =
configJson['include_paths'] === undefined configJson['includePaths'] === undefined
? [] ? []
: configJson['include_paths']; : configJson['includePaths'];
excludeFileArr = excludeFileArr =
configJson['exclude_files'] === undefined configJson['excludeFiles'] === undefined
? [] ? []
: configJson['exclude_files']; : configJson['excludeFiles'];
} }
writeIntoConfigFile( writeIntoConfigFile(
includePathArr, includePathArr,
excludeFileArr, excludeFileArr,
TargetConfigPanel.BUILD_ARGS TargetConfigPanel.buildArgs
); );
return TargetConfigPanel.EXCUTION_SUCCESS; return TargetConfigPanel.executionSuccess;
} }
private _getHtmlForWebview( private _getHtmlForWebview(
@ -158,23 +157,23 @@ export class TargetConfigPanel {
.replace(/(\${styleUri})/, styleUri.toString()) .replace(/(\${styleUri})/, styleUri.toString())
.replace( .replace(
/(\${output_file_val})/, /(\${output_file_val})/,
TargetConfigPanel.BUILD_ARGS.output_file_name TargetConfigPanel.buildArgs.outputFileName
) )
.replace( .replace(
/(\${initial_mem_size_val})/, /(\${initial_mem_size_val})/,
TargetConfigPanel.BUILD_ARGS.init_memory_size TargetConfigPanel.buildArgs.initMemorySize
) )
.replace( .replace(
/(\${max_mem_size_val})/, /(\${max_mem_size_val})/,
TargetConfigPanel.BUILD_ARGS.max_memory_size TargetConfigPanel.buildArgs.maxMemorySize
) )
.replace( .replace(
/(\${stack_size_val})/, /(\${stack_size_val})/,
TargetConfigPanel.BUILD_ARGS.stack_size TargetConfigPanel.buildArgs.stackSize
) )
.replace( .replace(
/(\${exported_symbols_val})/, /(\${exported_symbols_val})/,
TargetConfigPanel.BUILD_ARGS.exported_symbols TargetConfigPanel.buildArgs.exportedSymbols
); );
return html; return html;
@ -187,8 +186,8 @@ export class TargetConfigPanel {
case 'config_build_target': case 'config_build_target':
if ( if (
message.outputFileName === '' || message.outputFileName === '' ||
message.initmemSize === '' || message.initMemSize === '' ||
message.maxmemSize === '' || message.maxMemSize === '' ||
message.stackSize === '' || message.stackSize === '' ||
message.exportedSymbols === '' message.exportedSymbols === ''
) { ) {
@ -197,13 +196,13 @@ export class TargetConfigPanel {
); );
return; return;
} else if ( } else if (
this._configBuildArgs( this.configBuildArgs(
message.outputFileName, message.outputFileName,
message.initmemSize, message.initMemSize,
message.maxmemSize, message.maxMemSize,
message.stackSize, message.stackSize,
message.exportedSymbols message.exportedSymbols
) === TargetConfigPanel.EXCUTION_SUCCESS ) === TargetConfigPanel.executionSuccess
) { ) {
vscode.window vscode.window
.showInformationMessage( .showInformationMessage(
@ -211,7 +210,7 @@ export class TargetConfigPanel {
'OK' 'OK'
) )
.then(() => { .then(() => {
this._panel.dispose(); this.viewPanel.dispose();
return; return;
}); });
} }
@ -227,7 +226,7 @@ export class TargetConfigPanel {
private dispose() { private dispose() {
TargetConfigPanel.currentPanel = undefined; TargetConfigPanel.currentPanel = undefined;
this._panel.dispose(); this.viewPanel.dispose();
while (this._disposables.length) { while (this._disposables.length) {
const disposable = this._disposables.pop(); const disposable = this._disposables.pop();

View File

@ -1,21 +1,16 @@
{ {
"compilerOptions": { "compilerOptions": {
"module": "commonjs", "module": "commonjs",
"target": "es6", "target": "es6",
"outDir": "out", "outDir": "out",
"lib": [ "lib": ["es6"],
"es6" "sourceMap": true,
], "rootDir": "src",
"sourceMap": true, "strict": true /* enable all strict type-checking options */
"rootDir": "src", /* Additional Checks */
"strict": true /* enable all strict type-checking options */ // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
/* Additional Checks */ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ // "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ },
// "noUnusedParameters": true, /* Report errors on unused parameters. */ "exclude": ["node_modules", ".vscode-test"]
},
"exclude": [
"node_modules",
".vscode-test"
]
} }