diff --git a/.github/workflows/build_wamr_sdk.yml b/.github/workflows/build_wamr_sdk.yml index f4ca9afd4..69dbd7232 100644 --- a/.github/workflows/build_wamr_sdk.yml +++ b/.github/workflows/build_wamr_sdk.yml @@ -30,6 +30,10 @@ on: description: download WASI_SDK from this URL type: string required: true + wamr_app_framework_url: + description: download WAMR app framework to get wamr_sdk + type: string + required: true jobs: build: @@ -37,6 +41,14 @@ jobs: steps: - uses: actions/checkout@v4 + - name: download wamr-app-framework + run: | + git clone ${{ inputs.wamr_app_framework_url }} + cd wamr-app-framework + git submodule init + git submodule update + working-directory: wamr-sdk + - name: download and install wasi-sdk run: | cd /opt @@ -48,14 +60,16 @@ jobs: - name: generate wamr-sdk release run: | + cd ./wamr-app-framework/wamr-sdk ./build_sdk.sh -n wamr-sdk -x $(pwd)/${{ inputs.config_file }} working-directory: wamr-sdk - name: compress the binary run: | + cd wamr-app-framework/wamr-sdk/out tar czf wamr-sdk-${{ inputs.ver_num }}-${{ inputs.runner }}.tar.gz wamr-sdk zip -r wamr-sdk-${{ inputs.ver_num }}-${{ inputs.runner }}.zip wamr-sdk - working-directory: wamr-sdk/out + working-directory: wamr-sdk - name: upload release tar.gz uses: actions/upload-release-asset@v1 @@ -63,7 +77,7 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: upload_url: ${{ inputs.upload_url }} - asset_path: wamr-sdk/out/wamr-sdk-${{ inputs.ver_num }}-${{ inputs.runner }}.tar.gz + asset_path: wamr-sdk/wamr-app-framework/wamr-sdk/out/wamr-sdk-${{ inputs.ver_num }}-${{ inputs.runner }}.tar.gz asset_name: wamr-sdk-${{ inputs.ver_num }}-${{ inputs.arch }}-${{ inputs.runner }}.tar.gz asset_content_type: application/x-gzip @@ -73,6 +87,11 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: upload_url: ${{ inputs.upload_url }} - asset_path: wamr-sdk/out/wamr-sdk-${{ inputs.ver_num }}-${{ inputs.runner }}.zip + asset_path: wamr-sdk/wamr-app-framework/wamr-sdk/out/wamr-sdk-${{ inputs.ver_num }}-${{ inputs.runner }}.zip asset_name: wamr-sdk-${{ inputs.ver_num }}-${{ inputs.arch }}-${{ inputs.runner }}.zip asset_content_type: application/zip + + - name: delete wamr-app-framework + run: | + rm -rf wamr-app-framework + working-directory: wamr-sdk diff --git a/.github/workflows/compilation_on_android_ubuntu.yml b/.github/workflows/compilation_on_android_ubuntu.yml index 99260bfc8..d1d464d4d 100644 --- a/.github/workflows/compilation_on_android_ubuntu.yml +++ b/.github/workflows/compilation_on_android_ubuntu.yml @@ -20,7 +20,6 @@ on: - "!samples/workload/**" - "tests/wamr-test-suites/**" - "wamr-compiler/**" - - "wamr-sdk/**" - "test-tools/wamr-ide/**" # will be triggered on push events push: @@ -38,7 +37,6 @@ on: - "!samples/workload/**" - "tests/wamr-test-suites/**" - "wamr-compiler/**" - - "wamr-sdk/**" - "test-tools/wamr-ide/**" # allow to be triggered manually workflow_dispatch: @@ -65,7 +63,8 @@ env: THREADS_TEST_OPTIONS: "-s spec -b -p -P" X86_32_TARGET_TEST_OPTIONS: "-m x86_32 -P" WASI_TEST_OPTIONS: "-s wasi_certification -w" - WAMR_COMPILER_TEST_OPTIONS: "-s wamr_compiler -b -P" + WAMR_COMPILER_TEST_OPTIONS: "-s wamr_compiler -S -b -P" + GC_TEST_OPTIONS: "-s spec -G -b -P" jobs: build_llvm_libraries_on_ubuntu_2204: @@ -145,7 +144,6 @@ jobs: "-DWAMR_BUILD_SIMD=1", "-DWAMR_BUILD_TAIL_CALL=1", "-DWAMR_DISABLE_HW_BOUND_CHECK=1", - "-DWAMR_ENABLE_SHARED_MEMORY_MMAP=1", ] os: [ubuntu-22.04] platform: [android, linux] @@ -430,13 +428,6 @@ jobs: cmake --build . --config Debug --parallel 4 ./hello - - name: Build Sample [simple] - run: | - ./build.sh -p host-interp - python3 ./sample_test_run.py $(pwd)/out - exit $? - working-directory: ./samples/simple - - name: Build Sample [wasi-threads] run: | cd samples/wasi-threads @@ -485,6 +476,7 @@ jobs: $SIMD_TEST_OPTIONS, $THREADS_TEST_OPTIONS, $WASI_TEST_OPTIONS, + $GC_TEST_OPTIONS, ] wasi_sdk_release: [ @@ -518,10 +510,25 @@ jobs: test_option: $MULTI_MODULES_TEST_OPTIONS - running_mode: "multi-tier-jit" test_option: $SIMD_TEST_OPTIONS + # fast-jit and multi-tier-jit don't support GC + - running_mode: "fast-jit" + test_option: $GC_TEST_OPTIONS + - running_mode: "multi-tier-jit" + test_option: $GC_TEST_OPTIONS steps: - name: checkout uses: actions/checkout@v4 + - name: Set-up OCaml + uses: ocaml/setup-ocaml@v2 + if: matrix.test_option == '$GC_TEST_OPTIONS' + with: + ocaml-compiler: 4.13 + + - name: Set-up Ocamlbuild + if: matrix.test_option == '$GC_TEST_OPTIONS' + run: opam install ocamlbuild dune + - name: download and install wasi-sdk if: matrix.test_option == '$WASI_TEST_OPTIONS' run: | @@ -546,9 +553,9 @@ jobs: - name: set env variable(if x86_32 test needed) if: > - (matrix.test_option == '$DEFAULT_TEST_OPTIONS' || matrix.test_option == '$THREADS_TEST_OPTIONS' - || matrix.test_option == '$WASI_TEST_OPTIONS') - && matrix.running_mode != 'fast-jit' && matrix.running_mode != 'jit' && matrix.running_mode != 'multi-tier-jit' + ((matrix.test_option == '$DEFAULT_TEST_OPTIONS' || matrix.test_option == '$THREADS_TEST_OPTIONS' + || matrix.test_option == '$WASI_TEST_OPTIONS' || matrix.test_option == '$GC_TEST_OPTIONS') + && matrix.running_mode != 'fast-jit' && matrix.running_mode != 'jit' && matrix.running_mode != 'multi-tier-jit') run: echo "TEST_ON_X86_32=true" >> $GITHUB_ENV #only download llvm libraries in jit and aot mode @@ -585,9 +592,18 @@ jobs: - name: run tests timeout-minutes: 30 + if: matrix.test_option != '$GC_TEST_OPTIONS' run: ./test_wamr.sh ${{ matrix.test_option }} -t ${{ matrix.running_mode }} working-directory: ./tests/wamr-test-suites + - name: run gc tests + timeout-minutes: 20 + if: matrix.test_option == '$GC_TEST_OPTIONS' + run: | + eval $(opam env) + ./test_wamr.sh ${{ matrix.test_option }} -t ${{ matrix.running_mode }} + working-directory: ./tests/wamr-test-suites + #only install x32 support libraries when to run x86_32 cases - name: install x32 support libraries if: env.TEST_ON_X86_32 == 'true' @@ -601,10 +617,18 @@ jobs: - name: run tests x86_32 timeout-minutes: 30 - if: env.TEST_ON_X86_32 == 'true' + if: env.TEST_ON_X86_32 == 'true' && matrix.test_option != '$GC_TEST_OPTIONS' run: ./test_wamr.sh ${{ env.X86_32_TARGET_TEST_OPTIONS }} ${{ matrix.test_option }} -t ${{ matrix.running_mode }} working-directory: ./tests/wamr-test-suites + - name: run gc tests x86_32 + timeout-minutes: 20 + if: env.TEST_ON_X86_32 == 'true' && matrix.test_option == '$GC_TEST_OPTIONS' + run: | + eval $(opam env) + ./test_wamr.sh ${{ env.X86_32_TARGET_TEST_OPTIONS }} ${{ matrix.test_option }} -t ${{ matrix.running_mode }} + working-directory: ./tests/wamr-test-suites + test-wamr-ide: needs: [ @@ -626,6 +650,12 @@ jobs: npm install working-directory: test-tools/wamr-ide/VSCode-Extension + - name: code style check + run: | + npm install --save-dev prettier + npm run prettier-format-check + working-directory: test-tools/wamr-ide/VSCode-Extension + - name: build iwasm with source debugging feature run: | mkdir build diff --git a/.github/workflows/compilation_on_macos.yml b/.github/workflows/compilation_on_macos.yml index 19ff1874a..7bea5175e 100644 --- a/.github/workflows/compilation_on_macos.yml +++ b/.github/workflows/compilation_on_macos.yml @@ -1,7 +1,7 @@ # Copyright (C) 2019 Intel Corporation. All rights reserved. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -name: compilation on macos-latest +name: compilation on macos on: # will be triggered on PR events @@ -20,7 +20,6 @@ on: - "!samples/workload/**" - "tests/wamr-test-suites/**" - "wamr-compiler/**" - - "wamr-sdk/**" # will be triggered on push events push: branches: @@ -37,7 +36,6 @@ on: - "!samples/workload/**" - "tests/wamr-test-suites/**" - "wamr-compiler/**" - - "wamr-sdk/**" # allow to be triggered manually workflow_dispatch: @@ -55,20 +53,25 @@ env: LLVM_EAGER_JIT_BUILD_OPTIONS: "-DWAMR_BUILD_AOT=1 -DWAMR_BUILD_FAST_INTERP=0 -DWAMR_BUILD_INTERP=0 -DWAMR_BUILD_JIT=1 -DWAMR_BUILD_LAZY_JIT=0" jobs: - build_llvm_libraries: + build_llvm_libraries_on_intel_macos: uses: ./.github/workflows/build_llvm_libraries.yml with: os: "macos-latest" arch: "X86" + build_llvm_libraries_on_arm_macos: + uses: ./.github/workflows/build_llvm_libraries.yml + with: + os: "macos-14" + arch: "AArch64 ARM" build_wamrc: - needs: [build_llvm_libraries] + needs: [build_llvm_libraries_on_intel_macos] runs-on: ${{ matrix.os }} strategy: matrix: include: - os: macos-latest - llvm_cache_key: ${{ needs.build_llvm_libraries.outputs.cache_key }} + llvm_cache_key: ${{ needs.build_llvm_libraries_on_intel_macos.outputs.cache_key }} steps: - name: checkout uses: actions/checkout@v4 @@ -97,7 +100,7 @@ jobs: working-directory: wamr-compiler build_iwasm: - needs: [build_llvm_libraries] + needs: [build_llvm_libraries_on_intel_macos] runs-on: ${{ matrix.os }} strategy: matrix: @@ -171,7 +174,7 @@ jobs: make_options_feature: "-DWAMR_BUILD_MINI_LOADER=1" include: - os: macos-latest - llvm_cache_key: ${{ needs.build_llvm_libraries.outputs.cache_key }} + llvm_cache_key: ${{ needs.build_llvm_libraries_on_intel_macos.outputs.cache_key }} steps: - name: checkout uses: actions/checkout@v4 @@ -243,11 +246,11 @@ jobs: working-directory: samples/wasm-c-api build_samples_others: - needs: [build_iwasm, build_wamrc] + needs: [build_iwasm, build_wamrc, build_llvm_libraries_on_intel_macos, build_llvm_libraries_on_arm_macos] runs-on: ${{ matrix.os }} strategy: matrix: - os: [macos-latest] + os: [macos-latest, macos-14] wasi_sdk_release: [ "https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-20/wasi-sdk-20.0-macos.tar.gz", @@ -256,6 +259,11 @@ jobs: [ "https://github.com/WebAssembly/wabt/releases/download/1.0.31/wabt-1.0.31-macos-12.tar.gz", ] + include: + - os: macos-latest + llvm_cache_key: ${{ needs.build_llvm_libraries_on_intel_macos.outputs.cache_key }} + - os: macos-14 + llvm_cache_key: ${{ needs.build_llvm_libraries_on_arm_macos.outputs.cache_key }} steps: - name: checkout uses: actions/checkout@v4 @@ -320,6 +328,25 @@ jobs: cmake --build . --config Debug --parallel 4 ./hello + - name: Get LLVM libraries + id: retrieve_llvm_libs + uses: actions/cache@v4 + with: + path: | + ./core/deps/llvm/build/bin + ./core/deps/llvm/build/include + ./core/deps/llvm/build/lib + ./core/deps/llvm/build/libexec + ./core/deps/llvm/build/share + key: ${{ matrix.llvm_cache_key }} + + - name: Build wamrc + run: | + mkdir build && cd build + cmake .. + cmake --build . --config Release --parallel 4 + working-directory: wamr-compiler + - name: Build Sample [wasi-threads] run: | cd samples/wasi-threads @@ -328,6 +355,9 @@ jobs: cmake --build . --config Debug --parallel 4 ./iwasm wasm-apps/no_pthread.wasm + ../../../wamr-compiler/build/wamrc --size-level=0 --enable-multi-thread -o wasm-apps/no_pthread.aot wasm-apps/no_pthread.wasm + ./iwasm wasm-apps/no_pthread.aot + - name: Build Sample [shared-module] run: | cd samples/shared-module diff --git a/.github/workflows/compilation_on_nuttx.yml b/.github/workflows/compilation_on_nuttx.yml index 2eff73c2c..98cbb24ff 100644 --- a/.github/workflows/compilation_on_nuttx.yml +++ b/.github/workflows/compilation_on_nuttx.yml @@ -19,7 +19,6 @@ on: - "!samples/workload/**" - "tests/wamr-test-suites/**" - "wamr-compiler/**" - - "wamr-sdk/**" # will be triggered on push events push: branches: @@ -35,7 +34,6 @@ on: - "!samples/workload/**" - "tests/wamr-test-suites/**" - "wamr-compiler/**" - - "wamr-sdk/**" # allow to be triggered manually workflow_dispatch: diff --git a/.github/workflows/compilation_on_sgx.yml b/.github/workflows/compilation_on_sgx.yml index 8dadb518d..030c76524 100644 --- a/.github/workflows/compilation_on_sgx.yml +++ b/.github/workflows/compilation_on_sgx.yml @@ -20,7 +20,6 @@ on: - "!samples/workload/**" - "tests/wamr-test-suites/**" - "wamr-compiler/**" - - "wamr-sdk/**" # will be triggered on push events push: branches: @@ -37,7 +36,6 @@ on: - "!samples/workload/**" - "tests/wamr-test-suites/**" - "wamr-compiler/**" - - "wamr-sdk/**" # allow to be triggered manually workflow_dispatch: @@ -48,7 +46,8 @@ concurrency: cancel-in-progress: true env: - AOT_BUILD_OPTIONS: "-DWAMR_BUILD_AOT=1 -DWAMR_BUILD_FAST_INTERP=0 -DWAMR_BUILD_INTERP=0 -DWAMR_BUILD_JIT=0 -DWAMR_BUILD_LAZY_JIT=0" + # ref types enabled in wamrc by default, so we need to enable it for iwasm in AOT mode + AOT_BUILD_OPTIONS: "-DWAMR_BUILD_AOT=1 -DWAMR_BUILD_FAST_INTERP=0 -DWAMR_BUILD_INTERP=0 -DWAMR_BUILD_JIT=0 -DWAMR_BUILD_LAZY_JIT=0 -DWAMR_BUILD_REF_TYPES=1" CLASSIC_INTERP_BUILD_OPTIONS: "-DWAMR_BUILD_AOT=0 -DWAMR_BUILD_FAST_INTERP=0 -DWAMR_BUILD_INTERP=1 -DWAMR_BUILD_JIT=0 -DWAMR_BUILD_LAZY_JIT=0" FAST_INTERP_BUILD_OPTIONS: "-DWAMR_BUILD_AOT=0 -DWAMR_BUILD_FAST_INTERP=1 -DWAMR_BUILD_INTERP=1 -DWAMR_BUILD_JIT=0 -DWAMR_BUILD_LAZY_JIT=0" FAST_JIT_BUILD_OPTIONS: "-DWAMR_BUILD_AOT=1 -DWAMR_BUILD_FAST_INTERP=0 -DWAMR_BUILD_INTERP=1 -DWAMR_BUILD_FAST_JIT=1 -DWAMR_BUILD_JIT=0 -DWAMR_BUILD_LAZY_JIT=1" diff --git a/.github/workflows/compilation_on_windows.yml b/.github/workflows/compilation_on_windows.yml index a623ab1a7..8c5db4fdf 100644 --- a/.github/workflows/compilation_on_windows.yml +++ b/.github/workflows/compilation_on_windows.yml @@ -19,7 +19,6 @@ on: - "!samples/workload/**" - "tests/wamr-test-suites/**" - "wamr-compiler/**" - - "wamr-sdk/**" # will be triggered on push events push: branches: @@ -35,7 +34,6 @@ on: - "!samples/workload/**" - "tests/wamr-test-suites/**" - "wamr-compiler/**" - - "wamr-sdk/**" # allow to be triggered manually workflow_dispatch: diff --git a/.github/workflows/nightly_run.yml b/.github/workflows/nightly_run.yml index 8b9a0ed5e..cfc910ea2 100644 --- a/.github/workflows/nightly_run.yml +++ b/.github/workflows/nightly_run.yml @@ -13,7 +13,7 @@ on: paths: - ".github/workflows/nightly_run.yml" - "core/iwasm/libraries/lib-wasi-threads/stress-test/**" - + # midnight UTC schedule: - cron: "0 0 * * *" @@ -489,12 +489,6 @@ jobs: cmake .. cmake --build . --config Release --parallel 4 ./hello - - name: Build Sample [simple] - run: | - ./build.sh -p host-interp - python3 ./sample_test_run.py $(pwd)/out - exit $? - working-directory: ./samples/simple - name: Build Sample [wasi-threads] run: | diff --git a/.github/workflows/release_process.yml b/.github/workflows/release_process.yml index 5808b821c..de62867a8 100644 --- a/.github/workflows/release_process.yml +++ b/.github/workflows/release_process.yml @@ -147,6 +147,7 @@ jobs: upload_url: ${{ needs.create_release.outputs.upload_url }} ver_num: ${{ needs.create_tag.outputs.new_ver}} wasi_sdk_url: https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-19/wasi-sdk-19.0-linux.tar.gz + wamr_app_framework_url: https://github.com/bytecodealliance/wamr-app-framework.git release_wamr_sdk_on_ubuntu_2204: needs: [create_tag, create_release] @@ -157,6 +158,7 @@ jobs: upload_url: ${{ needs.create_release.outputs.upload_url }} ver_num: ${{ needs.create_tag.outputs.new_ver}} wasi_sdk_url: https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-19/wasi-sdk-19.0-linux.tar.gz + wamr_app_framework_url: https://github.com/bytecodealliance/wamr-app-framework.git release_wamr_sdk_on_macos: needs: [create_tag, create_release] @@ -167,6 +169,7 @@ jobs: upload_url: ${{ needs.create_release.outputs.upload_url }} ver_num: ${{ needs.create_tag.outputs.new_ver}} wasi_sdk_url: https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-19/wasi-sdk-19.0-macos.tar.gz + wamr_app_framework_url: https://github.com/bytecodealliance/wamr-app-framework.git # # vscode extension cross-platform diff --git a/.github/workflows/spec_test_on_nuttx.yml b/.github/workflows/spec_test_on_nuttx.yml index 5bdad8f23..1fa314010 100644 --- a/.github/workflows/spec_test_on_nuttx.yml +++ b/.github/workflows/spec_test_on_nuttx.yml @@ -10,7 +10,13 @@ on: - synchronize paths: - ".github/workflows/spec_test_on_nuttx.yml" - + - "core/**" + - "!core/deps/**" + - "product-mini/**" + - "!samples/workload/**" + - "tests/wamr-test-suites/**" + - "wamr-compiler/**" + - "wamr-sdk/**" schedule: - cron: '0 0 * * *' @@ -20,7 +26,7 @@ env: LLVM_CACHE_SUFFIX: "build-llvm_libraries_ex" WASI_SDK_PATH: "/opt/wasi-sdk" WAMR_COMMON_OPTION: - "CONFIG_INTERPRETERS_WAMR=y\\nCONFIG_INTERPRETERS_WAMR_STACKSIZE=32768\\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\\nCONFIG_EOL_IS_LF=y\\nCONFIG_ARM_SEMIHOSTING_HOSTFS=y\\nCONFIG_ARM_SEMIHOSTING_HOSTFS_CACHE_COHERENCE=y\\nCONFIG_RISCV_SEMIHOSTING_HOSTFS=y\\nCONFIG_FS_HOSTFS=y\\nCONFIG_LIBC_FLOATINGPOINT=y\\n" + "CONFIG_INTERPRETERS_WAMR=y\\nCONFIG_INTERPRETERS_WAMR_STACKSIZE=327680\\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\\nCONFIG_EOL_IS_LF=y\\nCONFIG_ARM_SEMIHOSTING_HOSTFS=y\\nCONFIG_ARM_SEMIHOSTING_HOSTFS_CACHE_COHERENCE=y\\nCONFIG_RISCV_SEMIHOSTING_HOSTFS=y\\nCONFIG_FS_HOSTFS=y\\nCONFIG_LIBC_FLOATINGPOINT=y\\n" jobs: build_llvm_libraries: @@ -28,13 +34,13 @@ jobs: with: os: "ubuntu-22.04" arch: "ARM RISCV AArch64" - container_image: ghcr.io/apache/nuttx/apache-nuttx-ci-linux@sha256:d9261eacf6c6ebe656c571757751c803e8f04c3ae9b820320a5ea5dd57b7205a + container_image: ghcr.io/no1wudi/nuttx/apache-nuttx-ci-linux@sha256:8c4e00b607d4d6d66ba8f51c4544819a616eac69d3a2ac669e2af2150e2eb0f9 spec_test_on_qemu: runs-on: ubuntu-latest needs: [build_llvm_libraries] container: - image: ghcr.io/apache/nuttx/apache-nuttx-ci-linux@sha256:d9261eacf6c6ebe656c571757751c803e8f04c3ae9b820320a5ea5dd57b7205a + image: ghcr.io/no1wudi/nuttx/apache-nuttx-ci-linux@sha256:8c4e00b607d4d6d66ba8f51c4544819a616eac69d3a2ac669e2af2150e2eb0f9 strategy: matrix: target_config: [ @@ -75,20 +81,25 @@ jobs: mode: "-t aot", option: "CONFIG_INTERPRETERS_WAMR_AOT=y\\n" }, - { - mode: "-t aot -X", - option: "CONFIG_INTERPRETERS_WAMR_AOT=y\\n" - }, - { - mode: "-t classic-interp", - option: "CONFIG_INTERPRETERS_WAMR_CLASSIC=y\\n" - }, - { - mode: "-t fast-interp", - option: "CONFIG_INTERPRETERS_WAMR_FAST=y\\n" - }, + # { + # mode: "-t aot -X", + # option: "CONFIG_INTERPRETERS_WAMR_AOT=y\\n" + # }, + # { + # mode: "-t classic-interp", + # option: "CONFIG_INTERPRETERS_WAMR_CLASSIC=y\\n" + # }, + # { + # mode: "-t fast-interp", + # option: "CONFIG_INTERPRETERS_WAMR_FAST=y\\n" + # }, ] + wamr_feature_option: + # Empty option for default + - { option: "", mode: "" } + - { option: "CONFIG_INTERPRETERS_WAMR_GC=y\\nCONFIG_INTERPRETERS_WAMR_AOT_STACK_FRAME=y\\n", mode: "-G" } + exclude: # XIP is not fully supported yet on RISCV64, some relocations can not be resolved - target_config: { config: "boards/risc-v/qemu-rv/rv-virt/configs/nsh64" } @@ -136,6 +147,23 @@ jobs: if: contains(matrix.wamr_test_option.mode, 'aot') run: cp -r core/deps/llvm apps/interpreters/wamr/wamr/core/deps/llvm + # Inject the config option to NuttX + # TODO: Merge this into NuttX once GC is generally available + - name: Modify Kconfig + run: | + echo "\n" >> apps/interpreters/wamr/Kconfig + echo "config INTERPRETERS_WAMR_GC" >> apps/interpreters/wamr/Kconfig + echo "\tbool \"Enable GC\"" >> apps/interpreters/wamr/Kconfig + echo "\tdefault n" >> apps/interpreters/wamr/Kconfig + echo "\n" >> apps/interpreters/wamr/Kconfig + echo "config INTERPRETERS_WAMR_AOT_STACK_FRAME" >> apps/interpreters/wamr/Kconfig + echo "\tbool \"Enable AOT stack frame\"" >> apps/interpreters/wamr/Kconfig + echo "\tdefault n" >> apps/interpreters/wamr/Kconfig + echo "\n" >> apps/interpreters/wamr/Kconfig + echo "config INTERPRETERS_WAMR_TAIL_CALL" >> apps/interpreters/wamr/Kconfig + echo "\tbool \"Enable Tail Call\"" >> apps/interpreters/wamr/Kconfig + echo "\tdefault y" >> apps/interpreters/wamr/Kconfig + - name: Enable WAMR for NuttX run: | find nuttx/boards -name defconfig | xargs sed -i '$a\${{ env.WAMR_COMMON_OPTION }}' @@ -144,6 +172,11 @@ jobs: run: | find nuttx/boards -name defconfig | xargs sed -i '$a\${{ matrix.wamr_test_option.option }}' + - name: Enable WAMR Feature for NuttX + if: matrix.wamr_feature_option.option != '' + run: | + find nuttx/boards -name defconfig | xargs sed -i '$a\${{ matrix.wamr_feature_option.option }}' + - name: Disable FPU for NuttX if: matrix.target_config.fpu_type == 'none' run: | @@ -172,4 +205,4 @@ jobs: - name: Test run: | cd apps/interpreters/wamr/wamr/tests/wamr-test-suites - ./test_wamr.sh -s spec ${{ matrix.wamr_test_option.mode }} -m ${{ matrix.target_config.target }} -b -Q -P -F ${{ steps.build_firmware.outputs.firmware }} + ./test_wamr.sh -s spec ${{ matrix.wamr_test_option.mode }} -m ${{ matrix.target_config.target }} -b -Q -P -F ${{ steps.build_firmware.outputs.firmware }} ${{ matrix.wamr_feature_option.mode}} diff --git a/.gitignore b/.gitignore index 99f1a502e..b85dd392c 100644 --- a/.gitignore +++ b/.gitignore @@ -9,17 +9,14 @@ *.obj *.a *.so +.clangd .DS_Store core/deps/** core/shared/mem-alloc/tlsf -core/app-framework/wgl core/iwasm/libraries/lib-wasi-threads/test/*.wasm core/iwasm/libraries/lib-socket/test/*.wasm -wamr-sdk/out/ -wamr-sdk/runtime/build_runtime_sdk/ -test-tools/host-tool/bin/ product-mini/app-samples/hello-world/test.wasm product-mini/platforms/linux-sgx/enclave-sample/App/ product-mini/platforms/linux-sgx/enclave-sample/Enclave/ diff --git a/ATTRIBUTIONS.md b/ATTRIBUTIONS.md index c772b9691..b249f7b02 100644 --- a/ATTRIBUTIONS.md +++ b/ATTRIBUTIONS.md @@ -2,10 +2,10 @@ WebAssembly Micro Runtime Attributions ====================================== WAMR project reused some components from other open source project: -- **cJson**: used in the host_tool for remotely managing wasm applications +- **cJson**: in the repository [wamr-app-framework](https://github.com/bytecodealliance/wamr-app-framework/), used in the host_tool for remotely managing wasm applications - **contiki-ng**: for the coap protocol implementation - **freebsd libm**: used in core/shared/platform/alios/bh_math.c -- **LVGL**: for the gui samples and wrapped the wasm graphic layer +- **LVGL**: in the repository [wamr-app-framework](https://github.com/bytecodealliance/wamr-app-framework/), for the gui samples and wrapped the wasm graphic layer - **llvm**: for the AOT/JIT compilation - **wasm-c-api**: to implement the C-APIs of wasm. using headers and sameples - **wasmtime**: for the wasi libc implementation @@ -42,7 +42,7 @@ The WAMR fast interpreter is a clean room development. We would acknowledge the ### cJson -[LICENSE](./test-tools/host-tool/external/cJSON/LICENSE) +[LICENSE](https://github.com/bytecodealliance/wamr-app-framework/blob/main/test-tools/host-tool/external/cJSON/LICENSE) ### contiki-ng @@ -54,9 +54,9 @@ The WAMR fast interpreter is a clean room development. We would acknowledge the ### LVGL -[LICENSE](./samples/littlevgl/LICENCE.txt) +[LICENSE](https://github.com/bytecodealliance/wamr-app-framework/blob/main/samples/littlevgl/LICENCE.txt) -[LICENSE](./core/app-framework/wgl/app/wa-inc/lvgl/LICENCE.txt) +[LICENSE](https://github.com/bytecodealliance/wamr-app-framework/blob/main/app-framework/wgl/app/wa-inc/lvgl/LICENCE.txt) ### llvm @@ -64,7 +64,7 @@ The WAMR fast interpreter is a clean room development. We would acknowledge the ### wasm-c-api -[LICENSE](./samples/wasm-c-api/src/LICENSE) +[LICENSE](https://github.com/bytecodealliance/wamr-app-framework/blob/main/samples/wasm-c-api/src/LICENSE) ### wasmtime @@ -76,7 +76,7 @@ The WAMR fast interpreter is a clean room development. We would acknowledge the ### zephyr -[LICENSE](./samples/gui/wasm-runtime-wgl/src/platform/zephyr/LICENSE) +[LICENSE](https://github.com/bytecodealliance/wamr-app-framework/blob/main/samples/gui/wasm-runtime-wgl/src/platform/zephyr/LICENSE) ### wac diff --git a/README.md b/README.md index 31156b9cc..13f777a2f 100644 --- a/README.md +++ b/README.md @@ -14,8 +14,8 @@ WebAssembly Micro Runtime (WAMR) is a lightweight standalone WebAssembly (Wasm) - [**iwasm**](./product-mini/): The executable binary built with WAMR VMcore supports WASI and command line interface. - [**wamrc**](./wamr-compiler/): The AOT compiler to compile Wasm file into AOT file - Useful components and tools for building real solutions with WAMR vmcore: - - [App-framework](./core/app-framework/README.md): A framework for supporting APIs for the Wasm applications - - [App-manager](./core/app-mgr/README.md): a framework for dynamical loading the Wasm module remotely + - [App-framework](https://github.com/bytecodealliance/wamr-app-framework/blob/main/app-framework/README.md): A framework for supporting APIs for the Wasm applications + - [App-manager](https://github.com/bytecodealliance/wamr-app-framework/blob/main/app-mgr/README.md): a framework for dynamical loading the Wasm module remotely - [WAMR-IDE](./test-tools/wamr-ide): An experimental VSCode extension for developping WebAssembly applications with C/C++ diff --git a/assembly-script/.gitignore b/assembly-script/.gitignore deleted file mode 100644 index 07e6e472c..000000000 --- a/assembly-script/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/node_modules diff --git a/assembly-script/README.md b/assembly-script/README.md deleted file mode 100644 index a1324e9d7..000000000 --- a/assembly-script/README.md +++ /dev/null @@ -1,124 +0,0 @@ -# AssemblyScript_on_WAMR -This project is based on [Wasm Micro Runtime](https://github.com/bytecodealliance/wasm-micro-runtime) (WAMR) and [AssemblyScript](https://github.com/AssemblyScript/assemblyscript). It implements some of the `wamr app framework` in *assemblyscript*, which allows you to write some applications in *assemblyscript* and dynamically installed on *WAMR Runtime* - -## Building -To build the samples in this repo, you need `npm` on your system -``` bash -sudo apt install npm -``` - -Then install all the dependencies under the repo's root dir -``` bash -cd $repo_root -npm install -``` - -Use the command to build all samples: -``` bash -npm run build:all -``` -or you can build every sample individually: -``` bash -npm run build:timer -npm run build:publisher -npm run build:subscriber -# ... -``` -You will get the compiled wasm file under `build` folder - -Please refer to [package.json](./package.json) for more commands. - -## Run -These applications require WAMR's application framework, you need to build WAMR first. - -``` bash -cd ${WAMR_ROOT}/samples/simple -./build.sh -``` - -You will get two executable files under `out` folder: - -`simple`: The wamr runtime with application framework - -`host_tool`: The tool used to dynamically install/uninstall applications - -1. Start the runtime: - ``` bash - ./simple -s - ``` - -2. Install the compiled wasm file using `host_tool`: - ``` bash - ./host_tool -i app_name -f your_compiled_wasm_file.wasm - ``` -You can also use the WAMR's AoT compiler `wamrc` to compile the wasm bytecode into native code before you run them. Please refer to this [guide](../README.md#build-wamrc-aot-compiler) to build and install `WAMR AoT compiler`. - -After installing `wamrc`, you can compile the wasm file using command: -``` bash -wamrc -o file_name.aot file_name.wasm -``` -and you can install the AoT file to the runtime: -``` bash -./host_tool -i app_name -f your_compiled_aot_file.aot -``` - -## Development -You can develop your own application based on the `wamr_app_lib` APIs. - -### Console APIs -``` typescript -function log(a: string): void; -function log_number(a: number): void; -``` - -### Timer APIs -``` typescript -function setTimeout(cb: () => void, timeout: i32): user_timer; -function setInterval(cb: () => void, timeout: i32): user_timer; -function timer_cancel(timer: user_timer): void; -function timer_restart(timer: user_timer, interval: number): void; -function now(): i32; - -// export to runtime -function on_timer_callback(on_timer_id: i32): void; -``` - -### Request APIs -``` typescript -// register handler -function register_resource_handler(url: string, - request_handle: request_handler_f): void; -// request -function post(url: string, payload: ArrayBuffer, payload_len: number, - tag: string, cb: (resp: wamr_response) => void): void; -function get(url: string, tag: string, - cb: (resp: wamr_response) => void): void; -function put(url: string, payload: ArrayBuffer, payload_len: number, tag: string, - cb: (resp: wamr_response) => void): void; -function del(url: string, tag: string, - cb: (resp: wamr_response) => void): void; - -// response -function make_response_for_request(req: wamr_request): wamr_response; -function api_response_send(resp: wamr_response): void; - -// event -function publish_event(url: string, fmt: number, - payload: ArrayBuffer, payload_len: number): void; -function subscribe_event(url: string, cb: request_handler_f): void; - -// export to runtime -function on_request(buffer_offset: i32, size: i32): void; -function on_response(buffer_offset : i32, size: i32): void; -``` - -You should export the `on_timer_callback`, `on_request` and `on_response` in your application entry file, refer to the samples for example. - -To build your application, you can use `asc`: -``` bash -asc app.ts -b build/app.wasm -t build/app.wat --sourceMap --validate --optimize -``` -or you can add a command into [package.json](./package.json): -``` json -"build:app": "asc app.ts -b build/app.wasm -t build/app.wat --sourceMap --validate --optimize", -``` diff --git a/assembly-script/package-lock.json b/assembly-script/package-lock.json deleted file mode 100644 index 0750cc05e..000000000 --- a/assembly-script/package-lock.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "assembly_script", - "version": "1.0.0", - "lockfileVersion": 1, - "requires": true, - "dependencies": { - "assemblyscript": { - "version": "0.17.4", - "resolved": "https://registry.npm.taobao.org/assemblyscript/download/assemblyscript-0.17.4.tgz", - "integrity": "sha1-1GEduJpClDNa1H7DxmYaJqRCh3E=", - "dev": true, - "requires": { - "binaryen": "98.0.0-nightly.20201109", - "long": "^4.0.0" - } - }, - "binaryen": { - "version": "98.0.0-nightly.20201109", - "resolved": "https://registry.npm.taobao.org/binaryen/download/binaryen-98.0.0-nightly.20201109.tgz", - "integrity": "sha1-USv2yhXGe/dAIURzSkg25jmTqgU=", - "dev": true - }, - "long": { - "version": "4.0.0", - "resolved": "https://registry.npm.taobao.org/long/download/long-4.0.0.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Flong%2Fdownload%2Flong-4.0.0.tgz", - "integrity": "sha1-mntxz7fTYaGU6lVSQckvdGjVvyg=", - "dev": true - } - } -} diff --git a/assembly-script/package.json b/assembly-script/package.json deleted file mode 100644 index b80145fae..000000000 --- a/assembly-script/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "assembly_script", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1", - "build:request_handler": "asc samples/request_handler.ts -b build/request_handler.wasm -t build/request_handler.wat --sourceMap --optimize --exportRuntime --use abort=", - "build:request_sender": "asc samples/request_sender.ts -b build/request_sender.wasm -t build/request_sender.wat --sourceMap --optimize --exportRuntime --use abort=", - "build:timer": "asc samples/timer.ts -b build/timer.wasm -t build/timer.wat --sourceMap --optimize --exportRuntime --use abort=", - "build:publisher": "asc samples/event_publisher.ts -b build/event_publisher.wasm -t build/event_publisher.wat --sourceMap --optimize --exportRuntime --use abort=", - "build:subscriber": "asc samples/event_subscriber.ts -b build/event_subscriber.wasm -t build/event_subscriber.wat --sourceMap --optimize --exportRuntime --use abort=", - "build:all": "npm run build:request_handler; npm run build:request_sender; npm run build:timer; npm run build:subscriber; npm run build:publisher" - }, - "author": "", - "license": "ISC", - "devDependencies": { - "assemblyscript": "^0.18.15" - } -} diff --git a/assembly-script/samples/event_publisher.ts b/assembly-script/samples/event_publisher.ts deleted file mode 100644 index 3ca133fdb..000000000 --- a/assembly-script/samples/event_publisher.ts +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -// The entry file of your WebAssembly module. -import * as console from "../wamr_app_lib/console" -import * as timer from "../wamr_app_lib/timer" -import * as request from "../wamr_app_lib/request" - -function publish_overheat_event(): void { - var payload = String.UTF8.encode("warning: temperature is over high"); - request.publish_event("alert/overheat", 0, payload, payload.byteLength); -} - -export function on_init() : void { - timer.setInterval(publish_overheat_event, 2000); -} - -export function on_destroy() : void { - -} - - -/* Function below are requred by wamr runtime, don't remove or modify them */ -export function _on_timer_callback(on_timer_id: i32): void { - timer.on_timer_callback(on_timer_id); -} - -export function _on_request(buffer_offset: i32, size: i32): void { - request.on_request(buffer_offset, size); -} - -export function _on_response(buffer_offset : i32, size: i32): void { - request.on_response(buffer_offset, size); -} \ No newline at end of file diff --git a/assembly-script/samples/event_subscriber.ts b/assembly-script/samples/event_subscriber.ts deleted file mode 100644 index c9aa52a8e..000000000 --- a/assembly-script/samples/event_subscriber.ts +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -// The entry file of your WebAssembly module. -import * as console from "../wamr_app_lib/console" -import * as timer from "../wamr_app_lib/timer" -import * as request from "../wamr_app_lib/request" - -export function on_init() : void { - request.subscribe_event("alert/overheat", (req) => { - console.log("### user over heat event handler called:"); - - console.log(""); - console.log(" " + String.UTF8.decode(req.payload) + "\n"); - }) -} - -export function on_destroy() : void { - -} - - -/* Function below are requred by wamr runtime, don't remove or modify them */ -export function _on_timer_callback(on_timer_id: i32): void { - timer.on_timer_callback(on_timer_id); -} - -export function _on_request(buffer_offset: i32, size: i32): void { - request.on_request(buffer_offset, size); -} - -export function _on_response(buffer_offset : i32, size: i32): void { - request.on_response(buffer_offset, size); -} \ No newline at end of file diff --git a/assembly-script/samples/request_handler.ts b/assembly-script/samples/request_handler.ts deleted file mode 100644 index ef9f58c58..000000000 --- a/assembly-script/samples/request_handler.ts +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - - // The entry file of your WebAssembly module. -import * as console from "../wamr_app_lib/console" -import * as timer from "../wamr_app_lib/timer" -import * as request from "../wamr_app_lib/request" - -export function on_init() : void { - request.register_resource_handler("/test", (req) => { - console.log("### Req: /test " + String.UTF8.decode(req.payload)); - - console.log(" request payload:"); - console.log(" " + String.UTF8.decode(req.payload) + "\n"); - - var resp = request.make_response_for_request(req); - resp.set_payload(String.UTF8.encode("Ok"), 2); - request.api_response_send(resp); - }); -} - -export function on_destroy() : void { - -} - - -/* Function below are requred by wamr runtime, don't remove or modify them */ -export function _on_timer_callback(on_timer_id: i32): void { - timer.on_timer_callback(on_timer_id); -} - -export function _on_request(buffer_offset: i32, size: i32): void { - request.on_request(buffer_offset, size); -} - -export function _on_response(buffer_offset : i32, size: i32): void { - request.on_response(buffer_offset, size); -} \ No newline at end of file diff --git a/assembly-script/samples/request_sender.ts b/assembly-script/samples/request_sender.ts deleted file mode 100644 index 5648985e7..000000000 --- a/assembly-script/samples/request_sender.ts +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -// The entry file of your WebAssembly module. -import * as console from "../wamr_app_lib/console" -import * as timer from "../wamr_app_lib/timer" -import * as request from "../wamr_app_lib/request" - -export function on_init() : void { - var payload = String.UTF8.encode("test message"); - request.post("/test", payload, payload.byteLength, "", (resp) => { - if (resp != null) { - console.log("Post Success"); - - if (resp.payload != null) { - console.log(" response payload:") - console.log(" " + String.UTF8.decode(resp.payload!) + "\n"); - } - } - else - console.log("Post Timeout"); - }); -} - -export function on_destroy() : void { - -} - - -/* Function below are requred by wamr runtime, don't remove or modify them */ -export function _on_timer_callback(on_timer_id: i32): void { - timer.on_timer_callback(on_timer_id); -} - -export function _on_request(buffer_offset: i32, size: i32): void { - request.on_request(buffer_offset, size); -} - -export function _on_response(buffer_offset : i32, size: i32): void { - request.on_response(buffer_offset, size); -} \ No newline at end of file diff --git a/assembly-script/samples/timer.ts b/assembly-script/samples/timer.ts deleted file mode 100644 index 2e3f69d29..000000000 --- a/assembly-script/samples/timer.ts +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -// The entry file of your WebAssembly module. -import * as console from '../wamr_app_lib/console' -import * as timer from '../wamr_app_lib/timer' - -/* clousure is not implemented yet, we need to declare global variables - so that they can be accessed inside a callback function */ -var cnt = 0; -var my_timer: timer.user_timer; - -export function on_init(): void { - /* The callback function will be called every 2 second, - and will stop after 10 calls */ - my_timer = timer.setInterval(() => { - cnt ++; - console.log((cnt * 2).toString() + " seconds passed"); - - if (cnt >= 10) { - timer.timer_cancel(my_timer); - console.log("Stop Timer"); - } - }, 2000); -} - -export function on_destroy(): void { - -} - -/* Function below are requred by wamr runtime, don't remove or modify them */ -export function _on_timer_callback(on_timer_id: i32): void { - timer.on_timer_callback(on_timer_id); -} \ No newline at end of file diff --git a/assembly-script/samples/tsconfig.json b/assembly-script/samples/tsconfig.json deleted file mode 100644 index c614e5c8e..000000000 --- a/assembly-script/samples/tsconfig.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "extends": "../node_modules/assemblyscript/std/assembly.json", - "include": [ - "./**/*.ts" - ] -} \ No newline at end of file diff --git a/assembly-script/wamr_app_lib/console.ts b/assembly-script/wamr_app_lib/console.ts deleted file mode 100644 index f20ede938..000000000 --- a/assembly-script/wamr_app_lib/console.ts +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -@external("env", "puts") -declare function printf(a: ArrayBuffer): i32; - -export function log(a: string): void { - printf(String.UTF8.encode(a, true)); -} - -export function log_number(a: number): void { - printf(String.UTF8.encode(a.toString())); -} \ No newline at end of file diff --git a/assembly-script/wamr_app_lib/request.ts b/assembly-script/wamr_app_lib/request.ts deleted file mode 100644 index 16a229277..000000000 --- a/assembly-script/wamr_app_lib/request.ts +++ /dev/null @@ -1,495 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -import * as console from './console' -import * as timer from './timer' - -@external("env", "wasm_response_send") -declare function wasm_response_send(buffer: ArrayBuffer, size: i32): bool; - -@external("env", "wasm_register_resource") -declare function wasm_register_resource(url: ArrayBuffer): void; - -@external("env", "wasm_post_request") -declare function wasm_post_request(buffer: ArrayBuffer, size: i32): void; - -@external("env", "wasm_sub_event") -declare function wasm_sub_event(url: ArrayBuffer): void; - -var COAP_GET = 1; -var COAP_POST = 2; -var COAP_PUT = 3; -var COAP_DELETE = 4; -var COAP_EVENT = COAP_DELETE + 2; - -/* CoAP response codes */ -export enum CoAP_Status { - NO_ERROR = 0, - - CREATED_2_01 = 65, /* CREATED */ - DELETED_2_02 = 66, /* DELETED */ - VALID_2_03 = 67, /* NOT_MODIFIED */ - CHANGED_2_04 = 68, /* CHANGED */ - CONTENT_2_05 = 69, /* OK */ - CONTINUE_2_31 = 95, /* CONTINUE */ - - BAD_REQUEST_4_00 = 128, /* BAD_REQUEST */ - UNAUTHORIZED_4_01 = 129, /* UNAUTHORIZED */ - BAD_OPTION_4_02 = 130, /* BAD_OPTION */ - FORBIDDEN_4_03 = 131, /* FORBIDDEN */ - NOT_FOUND_4_04 = 132, /* NOT_FOUND */ - METHOD_NOT_ALLOWED_4_05 = 133, /* METHOD_NOT_ALLOWED */ - NOT_ACCEPTABLE_4_06 = 134, /* NOT_ACCEPTABLE */ - PRECONDITION_FAILED_4_12 = 140, /* BAD_REQUEST */ - REQUEST_ENTITY_TOO_LARGE_4_13 = 141, /* REQUEST_ENTITY_TOO_LARGE */ - UNSUPPORTED_MEDIA_TYPE_4_15 = 143, /* UNSUPPORTED_MEDIA_TYPE */ - - INTERNAL_SERVER_ERROR_5_00 = 160, /* INTERNAL_SERVER_ERROR */ - NOT_IMPLEMENTED_5_01 = 161, /* NOT_IMPLEMENTED */ - BAD_GATEWAY_5_02 = 162, /* BAD_GATEWAY */ - SERVICE_UNAVAILABLE_5_03 = 163, /* SERVICE_UNAVAILABLE */ - GATEWAY_TIMEOUT_5_04 = 164, /* GATEWAY_TIMEOUT */ - PROXYING_NOT_SUPPORTED_5_05 = 165, /* PROXYING_NOT_SUPPORTED */ - - /* Erbium errors */ - MEMORY_ALLOCATION_ERROR = 192, PACKET_SERIALIZATION_ERROR, - - /* Erbium hooks */ - MANUAL_RESPONSE, PING_RESPONSE -}; - -var g_mid: i32 = 0; -class wamr_request { - mid: i32 = 0; - url: string = ""; - action: i32 = 0; - fmt: i32 = 0; - payload: ArrayBuffer; - payload_len: i32 = 0; - - sender: i32 = 0; - - constructor(mid: i32, url: string, action: i32, fmt: i32, - payload: ArrayBuffer, payload_len: number) { - this.mid = mid; - this.url = url; - this.action = action; - this.fmt = fmt; - this.payload = payload; - this.payload_len = i32(payload_len); - } -} - -class wamr_response { - mid: i32 = 0; - status: i32 = 0; - fmt: i32 = 0; - payload: ArrayBuffer | null; - payload_len: i32 = 0; - - receiver: i32 = 0; - - constructor(mid: i32, status: i32, fmt: i32, - payload: ArrayBuffer | null, payload_len: i32) { - this.mid = mid; - this.status = status; - this.fmt = fmt; - this.payload = payload; - this.payload_len = payload_len; - } - - set_status(status: number): void { - this.status = i32(status); - } - - set_payload(payload: ArrayBuffer, payload_len: number): void { - this.payload = payload; - this.payload_len = i32(payload_len); - } -} - -class wamr_resource { - url: string; - type: number; - cb: request_handler_f; - - constructor(url: string, type: number, cb: request_handler_f) { - this.url = url; - this.type = type; - this.cb = cb; - } -} - -function is_expire(trans: wamr_transaction, index: i32, array: Array): bool { - var now = timer.now(); - - var elapsed_ms = (now < trans.time) ? - (now + (0xFFFFFFFF - trans.time) + 1) : (now - trans.time); - - return elapsed_ms >= TRANSACTION_TIMEOUT_MS; -} - -function not_expire(trans: wamr_transaction, index: i32, array: Array): bool { - var now = timer.now(); - - var elapsed_ms = (now < trans.time) ? - (now + (0xFFFFFFFF - trans.time) + 1) : (now - trans.time); - - return elapsed_ms < TRANSACTION_TIMEOUT_MS; -} - -function transaction_timeout_handler(): void { - var now = timer.now(); - - var expired = transaction_list.filter(is_expire); - transaction_list = transaction_list.filter(not_expire); - - expired.forEach(item => { - item.cb(null); - transaction_remove(item); - }) - - if (transaction_list.length > 0) { - var elpased_ms: number, ms_to_expiry: number; - now = timer.now(); - if (now < transaction_list[0].time) { - elpased_ms = now + (0xFFFFFFFF - transaction_list[0].time) + 1; - } else { - elpased_ms = now - transaction_list[0].time; - } - ms_to_expiry = TRANSACTION_TIMEOUT_MS - elpased_ms; - timer.timer_restart(g_trans_timer, ms_to_expiry); - } else { - timer.timer_cancel(g_trans_timer); - } -} - -function transaction_find(mid: number): wamr_transaction | null { - for (let i = 0; i < transaction_list.length; i++) { - if (transaction_list[i].mid == mid) - return transaction_list[i]; - } - return null; -} - -function transaction_add(trans: wamr_transaction): void { - transaction_list.push(trans); - - if (transaction_list.length == 1) { - g_trans_timer = timer.setTimeout( - transaction_timeout_handler, - TRANSACTION_TIMEOUT_MS - ); - } -} - -function transaction_remove(trans: wamr_transaction): void { - var index = transaction_list.indexOf(trans); - transaction_list.splice(index, 1); -} - -var transaction_list = new Array(); -class wamr_transaction { - mid: number; - time: number; - cb: (resp: wamr_response | null) => void; - - constructor(mid: number, time: number, cb: (resp: wamr_response) => void) { - this.mid = mid; - this.time = time; - this.cb = cb; - } -} - -var REQUEST_PACKET_FIX_PART_LEN = 18; -var RESPONSE_PACKET_FIX_PART_LEN = 16; -var TRANSACTION_TIMEOUT_MS = 5000; -var g_trans_timer: timer.user_timer; - -var Reg_Event = 0; -var Reg_Request = 1; - -function pack_request(req: wamr_request): DataView { - var url_len = req.url.length + 1; - var len = REQUEST_PACKET_FIX_PART_LEN + url_len + req.payload_len - var buf = new ArrayBuffer(len); - - var dataview = new DataView(buf, 0, len); - - dataview.setUint8(0, 1); - dataview.setUint8(1, u8(req.action)); - dataview.setUint16(2, u16(req.fmt)); - dataview.setUint32(4, req.mid); - dataview.setUint32(8, req.sender); - dataview.setUint16(12, u16(url_len)) - dataview.setUint32(14, req.payload_len); - - var i = 0; - for (i = 0; i < url_len - 1; i++) { - dataview.setUint8(i + 18, u8(req.url.codePointAt(i))); - } - dataview.setUint8(i + 18, 0); - - var payload_view = new DataView(req.payload); - for (i = 0; i < req.payload_len; i++) { - dataview.setUint8(i + 18 + url_len, u8(payload_view.getUint8(i))); - } - - return dataview; -} - -function unpack_request(packet: ArrayBuffer, size: i32): wamr_request { - var dataview = new DataView(packet, 0, size); - - if (dataview.getUint8(0) != 1) - throw new Error("packet version mismatch"); - - if (size < REQUEST_PACKET_FIX_PART_LEN) - throw new Error("packet size error"); - - var url_len = dataview.getUint16(12); - var payload_len = dataview.getUint32(14); - - if (size != (REQUEST_PACKET_FIX_PART_LEN + url_len + payload_len)) - throw new Error("packet size error"); - - var action = dataview.getUint8(1); - var fmt = dataview.getUint16(2); - var mid = dataview.getUint32(4); - var sender = dataview.getUint32(8); - - var url = packet.slice(REQUEST_PACKET_FIX_PART_LEN, REQUEST_PACKET_FIX_PART_LEN + url_len - 1); - var payload = packet.slice(REQUEST_PACKET_FIX_PART_LEN + url_len, REQUEST_PACKET_FIX_PART_LEN + url_len + payload_len); - - var req = new wamr_request(mid, String.UTF8.decode(url), action, fmt, payload, payload_len); - req.sender = sender; - - return req; -} - -function pack_response(resp: wamr_response): DataView { - var len = RESPONSE_PACKET_FIX_PART_LEN + resp.payload_len - var buf = new ArrayBuffer(len); - - var dataview = new DataView(buf, 0, len); - - dataview.setUint8(0, 1); - dataview.setUint8(1, u8(resp.status)); - dataview.setUint16(2, u16(resp.fmt)); - dataview.setUint32(4, resp.mid); - dataview.setUint32(8, resp.receiver); - dataview.setUint32(12, resp.payload_len) - - if (resp.payload != null) { - var payload_view = new DataView(resp.payload!); - for (let i = 0; i < resp.payload_len; i++) { - dataview.setUint8(i + 16, payload_view.getUint8(i)); - } - } - - return dataview; -} - -function unpack_response(packet: ArrayBuffer, size: i32): wamr_response { - var dataview = new DataView(packet, 0, size); - - if (dataview.getUint8(0) != 1) - throw new Error("packet version mismatch"); - - if (size < RESPONSE_PACKET_FIX_PART_LEN) - throw new Error("packet size error"); - - var payload_len = dataview.getUint32(12); - if (size != RESPONSE_PACKET_FIX_PART_LEN + payload_len) - throw new Error("packet size error"); - - var status = dataview.getUint8(1); - var fmt = dataview.getUint16(2); - var mid = dataview.getUint32(4); - var receiver = dataview.getUint32(8); - - var payload = packet.slice(RESPONSE_PACKET_FIX_PART_LEN); - - var resp = new wamr_response(mid, status, fmt, payload, payload_len); - resp.receiver = receiver; - - return resp; -} - -function do_request(req: wamr_request, cb: (resp: wamr_response) => void): void { - var trans = new wamr_transaction(req.mid, timer.now(), cb); - var msg = pack_request(req); - - transaction_add(trans); - - wasm_post_request(msg.buffer, msg.byteLength); -} - -function do_response(resp: wamr_response): void { - var msg = pack_response(resp); - - wasm_response_send(msg.buffer, msg.byteLength); -} - -var resource_list = new Array(); -type request_handler_f = (req: wamr_request) => void; - -function registe_url_handler(url: string, cb: request_handler_f, type: number): void { - for (let i = 0; i < resource_list.length; i++) { - if (resource_list[i].type == type && resource_list[i].url == url) { - resource_list[i].cb = cb; - return; - } - } - - var res = new wamr_resource(url, type, cb); - resource_list.push(res); - - if (type == Reg_Request) - wasm_register_resource(String.UTF8.encode(url)); - else - wasm_sub_event(String.UTF8.encode(url)); -} - -function is_event_type(req: wamr_request): bool { - return req.action == COAP_EVENT; -} - -function check_url_start(url: string, leading_str: string): bool { - return url.split('/')[0] == leading_str.split('/')[0]; -} - -/* User APIs below */ -export function post(url: string, payload: ArrayBuffer, payload_len: number, tag: string, - cb: (resp: wamr_response) => void): void { - var req = new wamr_request(g_mid++, url, COAP_POST, 0, payload, payload_len); - - do_request(req, cb); -} - -export function get(url: string, tag: string, - cb: (resp: wamr_response) => void): void { - var req = new wamr_request(g_mid++, url, COAP_GET, 0, new ArrayBuffer(0), 0); - - do_request(req, cb); -} - -export function put(url: string, payload: ArrayBuffer, payload_len: number, tag: string, - cb: (resp: wamr_response) => void): void { - var req = new wamr_request(g_mid++, url, COAP_PUT, 0, payload, payload_len); - - do_request(req, cb); -} - -export function del(url: string, tag: string, - cb: (resp: wamr_response) => void): void { - var req = new wamr_request(g_mid++, url, COAP_DELETE, 0, new ArrayBuffer(0), 0); - - do_request(req, cb); -} - -export function make_response_for_request(req: wamr_request): wamr_response { - var resp = new wamr_response(req.mid, CoAP_Status.CONTENT_2_05, 0, null, 0); - resp.receiver = req.sender; - - return resp; -} - -export function api_response_send(resp: wamr_response): void { - do_response(resp); -} - -export function register_resource_handler(url: string, - request_handle: request_handler_f): void { - registe_url_handler(url, request_handle, Reg_Request); -} - -export function publish_event(url: string, fmt: number, - payload: ArrayBuffer, payload_len: number): void { - var req = new wamr_request(g_mid++, url, COAP_EVENT, i32(fmt), payload, payload_len); - - var msg = pack_request(req); - - wasm_post_request(msg.buffer, msg.byteLength); -} - -export function subscribe_event(url: string, cb: request_handler_f): void { - registe_url_handler(url, cb, Reg_Event); -} - - -/* These two APIs are required by wamr runtime, - use a wrapper to export them in the entry file - - e.g: - - import * as request from '.wamr_app_lib/request' - - // Your code here ... - - export function _on_request(buffer_offset: i32, size: i32): void { - on_request(buffer_offset, size); - } - - export function _on_response(buffer_offset: i32, size: i32): void { - on_response(buffer_offset, size); - } -*/ -export function on_request(buffer_offset: i32, size: i32): void { - var buffer = new ArrayBuffer(size); - var dataview = new DataView(buffer); - - for (let i = 0; i < size; i++) { - dataview.setUint8(i, load(buffer_offset + i, 0, 1)); - } - - var req = unpack_request(buffer, size); - - var is_event = is_event_type(req); - - for (let i = 0; i < resource_list.length; i++) { - if ((is_event && resource_list[i].type == Reg_Event) - || (!is_event && resource_list[i].type == Reg_Request)) { - if (check_url_start(req.url, resource_list[i].url)) { - resource_list[i].cb(req); - return; - } - } - } - - console.log("on_request: exit. no service handler."); -} - -export function on_response(buffer_offset: i32, size: i32): void { - var buffer = new ArrayBuffer(size); - var dataview = new DataView(buffer); - - for (let i = 0; i < size; i++) { - dataview.setUint8(i, load(buffer_offset + i, 0, 1)); - } - - var resp = unpack_response(buffer, size); - var trans = transaction_find(resp.mid); - - if (trans != null) { - if (transaction_list.indexOf(trans) == 0) { - if (transaction_list.length >= 2) { - var elpased_ms: number, ms_to_expiry: number; - var now = timer.now(); - if (now < transaction_list[1].time) { - elpased_ms = now + (0xFFFFFFFF - transaction_list[1].time) + 1; - } else { - elpased_ms = now - transaction_list[1].time; - } - ms_to_expiry = TRANSACTION_TIMEOUT_MS - elpased_ms; - timer.timer_restart(g_trans_timer, ms_to_expiry); - } else { - timer.timer_cancel(g_trans_timer); - } - } - - trans.cb(resp); - } -} diff --git a/assembly-script/wamr_app_lib/timer.ts b/assembly-script/wamr_app_lib/timer.ts deleted file mode 100644 index ea8363e8c..000000000 --- a/assembly-script/wamr_app_lib/timer.ts +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -@external("env", "wasm_create_timer") -declare function wasm_create_timer(a: i32, b: bool, c: bool): i32; - -@external("env", "wasm_timer_cancel") -declare function wasm_timer_cancel(a: i32): void; - -@external("env", "wasm_timer_restart") -declare function wasm_timer_restart(a: i32, b: i32): void; - -@external("env", "wasm_get_sys_tick_ms") -declare function wasm_get_sys_tick_ms(): i32; - -export var timer_list = new Array(); - -export class user_timer { - timer_id: i32 = 0; - timeout: i32; - period: bool = false; - cb: () => void; - - constructor(cb: () => void, timeout: i32, period: bool) { - this.cb = cb; - this.timeout = timeout; - this.period = period - this.timer_id = timer_create(this.timeout, this.period, true); - } -} - -export function timer_create(a: i32, b: bool, c: bool): i32 { - return wasm_create_timer(a, b, c); -} - -export function setTimeout(cb: () => void, timeout: i32): user_timer { - var timer = new user_timer(cb, timeout, false); - timer_list.push(timer); - - return timer; -} - -export function setInterval(cb: () => void, timeout: i32): user_timer { - var timer = new user_timer(cb, timeout, true); - timer_list.push(timer); - - return timer; -} - -export function timer_cancel(timer: user_timer): void { - wasm_timer_cancel(timer.timer_id); - - var i = 0; - for (i = 0; i < timer_list.length; i++) { - if (timer_list[i].timer_id == timer.timer_id) - break; - } - - timer_list.splice(i, 1); -} - -export function timer_restart(timer: user_timer, interval: number): void { - wasm_timer_restart(timer.timer_id, i32(interval)); -} - -export function now(): i32 { - return wasm_get_sys_tick_ms(); -} - -// This export function need to be copied to the top application file -// -export function on_timer_callback(on_timer_id: i32): void { - for (let i = 0; i < timer_list.length; i++) { - if (timer_list[i].timer_id == on_timer_id) { - timer_list[i].cb(); - } - } -} \ No newline at end of file diff --git a/assembly-script/wamr_app_lib/tsconfig.json b/assembly-script/wamr_app_lib/tsconfig.json deleted file mode 100644 index c614e5c8e..000000000 --- a/assembly-script/wamr_app_lib/tsconfig.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "extends": "../node_modules/assemblyscript/std/assembly.json", - "include": [ - "./**/*.ts" - ] -} \ No newline at end of file diff --git a/build-scripts/SConscript b/build-scripts/SConscript index d2bee9581..648373b38 100644 --- a/build-scripts/SConscript +++ b/build-scripts/SConscript @@ -13,8 +13,6 @@ objs = [] WAMR_ROOT_DIR = os.path.join(cwd, "..") SHARED_DIR = os.path.join(WAMR_ROOT_DIR, 'core', 'shared') IWASM_DIR = os.path.join(WAMR_ROOT_DIR, 'core', 'iwasm') -APP_MGR_DIR = os.path.join(WAMR_ROOT_DIR, 'core', 'app-mgr') -APP_FRAMEWORK_DIR = os.path.join(WAMR_ROOT_DIR, 'core', 'app-framework') DEPS_DIR = os.path.join(WAMR_ROOT_DIR, 'core', 'deps') if GetDepend(['WAMR_BUILD_INTERP']): @@ -28,12 +26,6 @@ if GetDepend(['WAMR_BUILD_AOT']): script_path = os.path.join(IWASM_DIR, 'compilation', 'SConscript') objs += SConscript(script_path) -if GetDepend(['WAMR_BUILD_APP_FRAMEWORK']): - objs += SConscript(os.path.join(APP_FRAMEWORK_DIR, 'SConscript')) - objs += SConscript(os.path.join(SHARED_DIR, 'coap', 'SConscript')) - objs += SConscript(os.path.join(APP_MGR_DIR, 'app-manager', 'SConscript')) - objs += SConscript(os.path.join(APP_MGR_DIR, 'app-mgr-shared', 'SConscript')) - if GetDepend(['WAMR_BUILD_LIBC_BUILTIN']): objs += SConscript(os.path.join(IWASM_DIR, 'libraries', 'libc-builtin', 'SConscript')) diff --git a/build-scripts/config_common.cmake b/build-scripts/config_common.cmake index 22783a509..773ff2837 100644 --- a/build-scripts/config_common.cmake +++ b/build-scripts/config_common.cmake @@ -248,12 +248,6 @@ if (WAMR_BUILD_SHARED_MEMORY EQUAL 1) else () add_definitions (-DWASM_ENABLE_SHARED_MEMORY=0) endif () -if (WAMR_ENABLE_SHARED_MEMORY_MMAP EQUAL 1) - add_definitions (-DWASM_ENABLE_SHARED_MEMORY_MMAP=1) - message (" Shared memory allocated using mmap enabled") -else () - add_definitions (-DWASM_ENABLE_SHARED_MEMORY_MMAP=0) -endif () if (WAMR_BUILD_THREAD_MGR EQUAL 1) message (" Thread manager enabled") endif () @@ -306,6 +300,10 @@ if (WAMR_BUILD_SIMD EQUAL 1) message (" SIMD disabled due to not supported on target RISCV64") endif () endif () +if (WAMR_BUILD_AOT_STACK_FRAME EQUAL 1) + add_definitions (-DWASM_ENABLE_AOT_STACK_FRAME=1) + message (" AOT stack frame enabled") +endif () if (WAMR_BUILD_MEMORY_PROFILING EQUAL 1) add_definitions (-DWASM_ENABLE_MEMORY_PROFILING=1) message (" Memory profiling enabled") @@ -335,6 +333,35 @@ if (WAMR_BUILD_REF_TYPES EQUAL 1) else () message (" Reference types disabled") endif () +if (WAMR_BUILD_GC EQUAL 1) + message (" GC enabled") + if (WAMR_TEST_GC EQUAL 1) + message(" GC testing enabled") + endif() +endif () +if (WAMR_BUILD_GC EQUAL 1 AND WAMR_BUILD_GC_PERF_PROFILING EQUAL 1) + add_definitions (-DWASM_ENABLE_GC_PERF_PROFILING=1) + message (" GC performance profiling enabled") +else () + message (" GC performance profiling disabled") +endif () +if (WAMR_BUILD_STRINGREF EQUAL 1) + message (" Stringref enabled") + if (NOT DEFINED WAMR_STRINGREF_IMPL_SOURCE) + message (" Using WAMR builtin implementation for stringref") + else () + message (" Using custom implementation for stringref") + endif() +endif () +if (WAMR_BUILD_PERF_PROFILING EQUAL 1 OR + WAMR_BUILD_DUMP_CALL_STACK EQUAL 1 OR + WAMR_BUILD_GC EQUAL 1) + # Enable AOT/JIT stack frame when perf-profiling, dump-call-stack + # or GC is enabled + if (WAMR_BUILD_AOT EQUAL 1 OR WAMR_BUILD_JIT EQUAL 1) + add_definitions (-DWASM_ENABLE_AOT_STACK_FRAME=1) + endif () +endif () if (WAMR_BUILD_EXCE_HANDLING EQUAL 1) add_definitions (-DWASM_ENABLE_EXCE_HANDLING=1) add_definitions (-DWASM_ENABLE_TAGS=1) diff --git a/build-scripts/runtime_lib.cmake b/build-scripts/runtime_lib.cmake index 811009df6..3ab0cff4f 100644 --- a/build-scripts/runtime_lib.cmake +++ b/build-scripts/runtime_lib.cmake @@ -10,12 +10,6 @@ endif () if (NOT DEFINED IWASM_DIR) set (IWASM_DIR ${WAMR_ROOT_DIR}/core/iwasm) endif () -if (NOT DEFINED APP_MGR_DIR) - set (APP_MGR_DIR ${WAMR_ROOT_DIR}/core/app-mgr) -endif () -if (NOT DEFINED APP_FRAMEWORK_DIR) - set (APP_FRAMEWORK_DIR ${WAMR_ROOT_DIR}/core/app-framework) -endif () if (NOT DEFINED DEPS_DIR) set (DEPS_DIR ${WAMR_ROOT_DIR}/core/deps) endif () @@ -78,11 +72,14 @@ if (WAMR_BUILD_AOT EQUAL 1) include (${IWASM_DIR}/aot/iwasm_aot.cmake) endif () -if (WAMR_BUILD_APP_FRAMEWORK EQUAL 1) - include (${APP_FRAMEWORK_DIR}/app_framework.cmake) - include (${SHARED_DIR}/coap/lib_coap.cmake) - include (${APP_MGR_DIR}/app-manager/app_mgr.cmake) - include (${APP_MGR_DIR}/app-mgr-shared/app_mgr_shared.cmake) +if (WAMR_BUILD_STRINGREF EQUAL 1) + set (WAMR_BUILD_GC 1) +endif () + +if (WAMR_BUILD_GC EQUAL 1) + include (${IWASM_DIR}/common/gc/iwasm_gc.cmake) + # Enable the dependent feature if GC is enabled + set (WAMR_BUILD_REF_TYPES 1) endif () if (WAMR_BUILD_LIBC_BUILTIN EQUAL 1) @@ -189,9 +186,7 @@ set (source_all ${IWASM_AOT_SOURCE} ${IWASM_COMPL_SOURCE} ${IWASM_FAST_JIT_SOURCE} - ${WASM_APP_LIB_SOURCE_ALL} - ${NATIVE_INTERFACE_SOURCE} - ${APP_MGR_SOURCE} + ${IWASM_GC_SOURCE} ${LIB_WASI_THREADS_SOURCE} ${LIB_PTHREAD_SOURCE} ${THREAD_MGR_SOURCE} diff --git a/ci/coding_guidelines_check.py b/ci/coding_guidelines_check.py index 062614597..924a24280 100644 --- a/ci/coding_guidelines_check.py +++ b/ci/coding_guidelines_check.py @@ -21,7 +21,6 @@ EXCLUDE_PATHS = [ "**/.git/*", "**/.github/*", "**/.vscode/*", - "**/assembly-script/*", "**/build/*", "**/build-scripts/*", "**/ci/*", @@ -30,9 +29,7 @@ EXCLUDE_PATHS = [ "**/samples/wasm-c-api/src/*.*", "**/samples/workload/*", "**/test-tools/wasi-sdk/*", - "**/test-tools/IoT-APP-Store-Demo/*", "**/tests/wamr-test-suites/workspace/*", - "**/wamr-sdk/*", ] C_SUFFIXES = [".c", ".cpp", ".h"] diff --git a/core/app-framework/README.md b/core/app-framework/README.md deleted file mode 100644 index d1476fd8b..000000000 --- a/core/app-framework/README.md +++ /dev/null @@ -1,120 +0,0 @@ -# Application framework - -By using the WAMR VM core, we are flexible to build different application frameworks for the specific domains, although it would take quite some effort. - -The WAMR has offered a comprehensive framework for programming WASM applications for device and IoT usages. The framework supports running multiple applications, that are based on the event driven programming model. Here are the supporting API sets by the [WAMR application framework library](../doc/wamr_api.md) : - -- Timer, Inter-app communication (request/response and pub/sub), Sensor, Connectivity and data transmission, 2D graphic UI - -Browse the folder [core/app-framework](./app-framework) for how to extend the application framework. - - -## Directory structure -This folder "app-native-shared" is for the source files shared by both WASM APP and native runtime - -- The c files in this directory are compiled into both the WASM APP and runtime. -- The header files for distributing to SDK are placed in the "bi-inc" folder. - -This folder "template" contains a pre-defined directory structure for a framework component. The developers can copy the template folder to create new components to the application framework. - -Every other subfolder is framework component. Each component contains two library parts: **app and native**. - -- The "base" component provide timer API and inter-app communication support. It must be enabled if other components are selected. -- Under the "app" folder of a component, the subfolder "wa_inc" holds all header files that should be included by the WASM applications - -## Application framework basic model - -The app framework is built on top of two fundamental operations: - -- [Native calls into WASM function](../../doc/embed_wamr.md) - -- [WASM app calls into native API](../../doc/export_native_api.md) - -Asynchronized programming model is supported for WASM applications - -- Every WASM app has its own sandbox and thread - -- Queue and messaging - - - - - -## Customized building of app framework - -A component can be compilation configurable to the runtime. The wamr SDK tool "build_sdk.sh" supports menu config to select app components for building a customized runtime. - -A number of CMAKE variables are defined to control build of framework and components. You can create a cmake file for defining these variables and include it in the CMakeList.txt for your software, or pass it in "-x" argument when run the [build_sdk.sh](../../wamr-sdk/build_sdk.sh) for building the runtime SDK. - -```cmake -set (WAMR_BUILD_APP_FRAMEWORK 1) -set (WAMR_BUILD_APP_LIST WAMR_APP_BUILD_BASE) -``` - -Variables: - -- **WAMR_BUILD_APP_FRAMEWORK**: enable the application framework -- **WAMR_BUILD_APP_LIST**: the selected components to be built into the final runtime - - - -The configuration file can be generated through the wamr-sdk menu config: - -```bash -cd wamr-sdk -./build_sdk -n [profile] -i -``` - - - -## Create new components - -Generally you should follow following steps to create a new component: - -- Copy the “template” for creating a new folder - -- Implement the app part - - - If your component exports native function to WASM, ensure your created a header file under app for declaring the function prototype. - - If you component provides header files for the WASM applications to include, ensure it is placed under subfolder "wa_inc". - -- Implement the native part - - - If your native function is exported to WASM, you need to create an inl file for the registration. It can be any file name, assuming the file name is "my_component.inl" here: - - ```c - //use right signature for your functions - EXPORT_WASM_API_WITH_SIG(wasm_my_component_api_1, "(i*~)i"), - EXPORT_WASM_API_WITH_SIG(wasm_my_component_api_2, "(i)i"), - ``` - - - Ensure "wasm_lib.cmake" is provided as it will be included by the WAMR SDK building script - - - Add a definition in "wasm_lib.cmake" for your component, e.g. - - ```cmake - add_definitions (-DAPP_FRAMEWORK_MY_COMPONENT) - ``` - -- Modify the file [app_ext_lib_export.c](./app_ext_lib_export.c) to register native APIs exported for the new introduced component. Skip it if not exporting native functions. - - ``` - #include "lib_export.h" - - ... - #ifdef APP_FRAMEWORK_MY_COMPONENT // this definition is created in wasm_lib.cmake - #include "my_component_native_api.h" - #endif - - static NativeSymbol extended_native_symbol_defs[] = { - ... - #ifdef APP_FRAMEWORK_MY_COMPONENT - #include "my_component.inl" - #endif - }; - ``` - - -## Sensor component working flow -![](../../doc/pics/sensor_callflow.PNG) - diff --git a/core/app-framework/app-native-shared/README.md b/core/app-framework/app-native-shared/README.md deleted file mode 100644 index b166e0b3a..000000000 --- a/core/app-framework/app-native-shared/README.md +++ /dev/null @@ -1,11 +0,0 @@ - Notes: -======= -This folder is for the source files shared by both WASM APP and native runtime - -- The c files in this directory are compiled into both the WASM APP and runtime. -- The header files for distributing to SDK are placed in the "bi-inc" folder. - - - - - diff --git a/core/app-framework/app-native-shared/attr_container.c b/core/app-framework/app-native-shared/attr_container.c deleted file mode 100644 index e1e9f4e35..000000000 --- a/core/app-framework/app-native-shared/attr_container.c +++ /dev/null @@ -1,986 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "bi-inc/attr_container.h" - -typedef union jvalue { - bool z; - int8_t i8; - uint8_t u8; - int16_t i16; - uint16_t u16; - int32_t i32; - uint32_t u32; - int64_t i64; - uint64_t u64; - float f; - double d; -} jvalue; - -static inline int16_t -get_int16(const char *buf) -{ - int16_t ret; - bh_memcpy_s(&ret, sizeof(int16_t), buf, sizeof(int16_t)); - return ret; -} - -static inline uint16_t -get_uint16(const char *buf) -{ - uint16_t ret; - bh_memcpy_s(&ret, sizeof(uint16_t), buf, sizeof(uint16_t)); - return ret; -} - -static inline int32_t -get_int32(const char *buf) -{ - int32_t ret; - bh_memcpy_s(&ret, sizeof(int32_t), buf, sizeof(int32_t)); - return ret; -} - -static inline uint32_t -get_uint32(const char *buf) -{ - uint32_t ret; - bh_memcpy_s(&ret, sizeof(uint32_t), buf, sizeof(uint32_t)); - return ret; -} - -static inline int64_t -get_int64(const char *buf) -{ - int64_t ret; - bh_memcpy_s(&ret, sizeof(int64_t), buf, sizeof(int64_t)); - return ret; -} - -static inline uint64_t -get_uint64(const char *buf) -{ - uint64_t ret; - bh_memcpy_s(&ret, sizeof(uint64_t), buf, sizeof(uint64_t)); - return ret; -} - -static inline void -set_int16(char *buf, int16_t v) -{ - bh_memcpy_s(buf, sizeof(int16_t), &v, sizeof(int16_t)); -} - -static inline void -set_uint16(char *buf, uint16_t v) -{ - bh_memcpy_s(buf, sizeof(uint16_t), &v, sizeof(uint16_t)); -} - -static inline void -set_int32(char *buf, int32_t v) -{ - bh_memcpy_s(buf, sizeof(int32_t), &v, sizeof(int32_t)); -} - -static inline void -set_uint32(char *buf, uint32_t v) -{ - bh_memcpy_s(buf, sizeof(uint32_t), &v, sizeof(uint32_t)); -} - -static inline void -set_int64(char *buf, int64_t v) -{ - bh_memcpy_s(buf, sizeof(int64_t), &v, sizeof(int64_t)); -} - -static inline void -set_uint64(char *buf, uint64_t v) -{ - bh_memcpy_s(buf, sizeof(uint64_t), &v, sizeof(uint64_t)); -} - -char * -attr_container_get_attr_begin(const attr_container_t *attr_cont, - uint32_t *p_total_length, uint16_t *p_attr_num) -{ - char *p = (char *)attr_cont->buf; - uint16_t str_len, attr_num; - uint32_t total_length; - - /* skip total length */ - total_length = get_uint32(p); - p += sizeof(uint32_t); - if (!total_length) - return NULL; - - /* tag length */ - str_len = get_uint16(p); - p += sizeof(uint16_t); - if (!str_len) - return NULL; - - /* tag content */ - p += str_len; - if ((uint32_t)(p - attr_cont->buf) >= total_length) - return NULL; - - /* attribute num */ - attr_num = get_uint16(p); - p += sizeof(uint16_t); - if ((uint32_t)(p - attr_cont->buf) >= total_length) - return NULL; - - if (p_total_length) - *p_total_length = total_length; - - if (p_attr_num) - *p_attr_num = attr_num; - - /* first attribute */ - return p; -} - -static char * -attr_container_get_attr_next(const char *curr_attr) -{ - char *p = (char *)curr_attr; - uint8_t type; - - /* key length and key */ - p += sizeof(uint16_t) + get_uint16(p); - type = *p++; - - /* Byte type to Boolean type */ - if (type >= ATTR_TYPE_BYTE && type <= ATTR_TYPE_BOOLEAN) { - p += 1 << (type & 3); - return p; - } - /* String type */ - else if (type == ATTR_TYPE_STRING) { - p += sizeof(uint16_t) + get_uint16(p); - return p; - } - /* ByteArray type */ - else if (type == ATTR_TYPE_BYTEARRAY) { - p += sizeof(uint32_t) + get_uint32(p); - return p; - } - - return NULL; -} - -static const char * -attr_container_find_attr(const attr_container_t *attr_cont, const char *key) -{ - uint32_t total_length; - uint16_t str_len, attr_num, i; - const char *p = attr_cont->buf; - - if (!key) - return NULL; - - if (!(p = attr_container_get_attr_begin(attr_cont, &total_length, - &attr_num))) - return NULL; - - for (i = 0; i < attr_num; i++) { - /* key length */ - if (!(str_len = get_uint16(p))) - return NULL; - - if (str_len == strlen(key) + 1 - && memcmp(p + sizeof(uint16_t), key, str_len) == 0) { - if ((uint32_t)(p + sizeof(uint16_t) + str_len - attr_cont->buf) - >= total_length) - return NULL; - return p; - } - - if (!(p = attr_container_get_attr_next(p))) - return NULL; - } - - return NULL; -} - -char * -attr_container_get_attr_end(const attr_container_t *attr_cont) -{ - uint32_t total_length; - uint16_t attr_num, i; - char *p; - - if (!(p = attr_container_get_attr_begin(attr_cont, &total_length, - &attr_num))) - return NULL; - - for (i = 0; i < attr_num; i++) - if (!(p = attr_container_get_attr_next(p))) - return NULL; - - return p; -} - -static char * -attr_container_get_msg_end(attr_container_t *attr_cont) -{ - char *p = attr_cont->buf; - return p + get_uint32(p); -} - -uint16_t -attr_container_get_attr_num(const attr_container_t *attr_cont) -{ - uint16_t str_len; - /* skip total length */ - const char *p = attr_cont->buf + sizeof(uint32_t); - - str_len = get_uint16(p); - /* skip tag length and tag */ - p += sizeof(uint16_t) + str_len; - - /* attribute num */ - return get_uint16(p); -} - -static void -attr_container_inc_attr_num(attr_container_t *attr_cont) -{ - uint16_t str_len, attr_num; - /* skip total length */ - char *p = attr_cont->buf + sizeof(uint32_t); - - str_len = get_uint16(p); - /* skip tag length and tag */ - p += sizeof(uint16_t) + str_len; - - /* attribute num */ - attr_num = get_uint16(p) + 1; - set_uint16(p, attr_num); -} - -attr_container_t * -attr_container_create(const char *tag) -{ - attr_container_t *attr_cont; - int length, tag_length; - char *p; - - tag_length = tag ? strlen(tag) + 1 : 1; - length = offsetof(attr_container_t, buf) + - /* total length + tag length + tag + reserved 100 bytes */ - sizeof(uint32_t) + sizeof(uint16_t) + tag_length + 100; - - if (!(attr_cont = attr_container_malloc(length))) { - attr_container_printf( - "Create attr_container failed: allocate memory failed.\r\n"); - return NULL; - } - - memset(attr_cont, 0, length); - p = attr_cont->buf; - - /* total length */ - set_uint32(p, length - offsetof(attr_container_t, buf)); - p += 4; - - /* tag length, tag */ - set_uint16(p, tag_length); - p += 2; - if (tag) - bh_memcpy_s(p, tag_length, tag, tag_length); - - return attr_cont; -} - -void -attr_container_destroy(const attr_container_t *attr_cont) -{ - if (attr_cont) - attr_container_free((char *)attr_cont); -} - -static bool -check_set_attr(attr_container_t **p_attr_cont, const char *key) -{ - uint32_t flags; - - if (!p_attr_cont || !*p_attr_cont || !key || strlen(key) == 0) { - attr_container_printf( - "Set attribute failed: invalid input arguments.\r\n"); - return false; - } - - flags = get_uint32((char *)*p_attr_cont); - if (flags & ATTR_CONT_READONLY_SHIFT) { - attr_container_printf( - "Set attribute failed: attribute container is readonly.\r\n"); - return false; - } - - return true; -} - -bool -attr_container_set_attr(attr_container_t **p_attr_cont, const char *key, - int type, const void *value, int value_length) -{ - attr_container_t *attr_cont, *attr_cont1; - uint16_t str_len; - uint32_t total_length, attr_len; - char *p, *p1, *attr_end, *msg_end, *attr_buf; - - if (!check_set_attr(p_attr_cont, key)) { - return false; - } - - attr_cont = *p_attr_cont; - p = attr_cont->buf; - total_length = get_uint32(p); - - if (!(attr_end = attr_container_get_attr_end(attr_cont))) { - attr_container_printf("Set attr failed: get attr end failed.\r\n"); - return false; - } - - msg_end = attr_container_get_msg_end(attr_cont); - - /* key len + key + '\0' + type */ - attr_len = sizeof(uint16_t) + strlen(key) + 1 + 1; - if (type >= ATTR_TYPE_BYTE && type <= ATTR_TYPE_BOOLEAN) - attr_len += 1 << (type & 3); - else if (type == ATTR_TYPE_STRING) - attr_len += sizeof(uint16_t) + value_length; - else if (type == ATTR_TYPE_BYTEARRAY) - attr_len += sizeof(uint32_t) + value_length; - - if (!(p = attr_buf = attr_container_malloc(attr_len))) { - attr_container_printf("Set attr failed: allocate memory failed.\r\n"); - return false; - } - - /* Set the attr buf */ - str_len = (uint16_t)(strlen(key) + 1); - set_uint16(p, str_len); - p += sizeof(uint16_t); - bh_memcpy_s(p, str_len, key, str_len); - p += str_len; - - *p++ = type; - if (type >= ATTR_TYPE_BYTE && type <= ATTR_TYPE_BOOLEAN) - bh_memcpy_s(p, 1 << (type & 3), value, 1 << (type & 3)); - else if (type == ATTR_TYPE_STRING) { - set_uint16(p, value_length); - p += sizeof(uint16_t); - bh_memcpy_s(p, value_length, value, value_length); - } - else if (type == ATTR_TYPE_BYTEARRAY) { - set_uint32(p, value_length); - p += sizeof(uint32_t); - bh_memcpy_s(p, value_length, value, value_length); - } - - if ((p = (char *)attr_container_find_attr(attr_cont, key))) { - /* key found */ - p1 = attr_container_get_attr_next(p); - - if (p1 - p == attr_len) { - bh_memcpy_s(p, attr_len, attr_buf, attr_len); - attr_container_free(attr_buf); - return true; - } - - if ((uint32_t)(p1 - p + msg_end - attr_end) >= attr_len) { - memmove(p, p1, attr_end - p1); - bh_memcpy_s(p + (attr_end - p1), attr_len, attr_buf, attr_len); - attr_container_free(attr_buf); - return true; - } - - total_length += attr_len + 100; - if (!(attr_cont1 = attr_container_malloc(offsetof(attr_container_t, buf) - + total_length))) { - attr_container_printf( - "Set attr failed: allocate memory failed.\r\n"); - attr_container_free(attr_buf); - return false; - } - - bh_memcpy_s(attr_cont1, p - (char *)attr_cont, attr_cont, - p - (char *)attr_cont); - bh_memcpy_s((char *)attr_cont1 + (unsigned)(p - (char *)attr_cont), - attr_end - p1, p1, attr_end - p1); - bh_memcpy_s((char *)attr_cont1 + (unsigned)(p - (char *)attr_cont) - + (unsigned)(attr_end - p1), - attr_len, attr_buf, attr_len); - p = attr_cont1->buf; - set_uint32(p, total_length); - *p_attr_cont = attr_cont1; - /* Free original buffer */ - attr_container_free(attr_cont); - attr_container_free(attr_buf); - return true; - } - else { - /* key not found */ - if ((uint32_t)(msg_end - attr_end) >= attr_len) { - bh_memcpy_s(attr_end, msg_end - attr_end, attr_buf, attr_len); - attr_container_inc_attr_num(attr_cont); - attr_container_free(attr_buf); - return true; - } - - total_length += attr_len + 100; - if (!(attr_cont1 = attr_container_malloc(offsetof(attr_container_t, buf) - + total_length))) { - attr_container_printf( - "Set attr failed: allocate memory failed.\r\n"); - attr_container_free(attr_buf); - return false; - } - - bh_memcpy_s(attr_cont1, attr_end - (char *)attr_cont, attr_cont, - attr_end - (char *)attr_cont); - bh_memcpy_s((char *)attr_cont1 - + (unsigned)(attr_end - (char *)attr_cont), - attr_len, attr_buf, attr_len); - attr_container_inc_attr_num(attr_cont1); - p = attr_cont1->buf; - set_uint32(p, total_length); - *p_attr_cont = attr_cont1; - /* Free original buffer */ - attr_container_free(attr_cont); - attr_container_free(attr_buf); - return true; - } - - return false; -} - -bool -attr_container_set_short(attr_container_t **p_attr_cont, const char *key, - short value) -{ - return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_SHORT, &value, - 2); -} - -bool -attr_container_set_int16(attr_container_t **p_attr_cont, const char *key, - int16_t value) -{ - return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_INT16, &value, - 2); -} - -bool -attr_container_set_int(attr_container_t **p_attr_cont, const char *key, - int value) -{ - return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_INT, &value, 4); -} - -bool -attr_container_set_int32(attr_container_t **p_attr_cont, const char *key, - int32_t value) -{ - return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_INT32, &value, - 4); -} - -bool -attr_container_set_uint32(attr_container_t **p_attr_cont, const char *key, - uint32_t value) -{ - return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_UINT32, &value, - 4); -} - -bool -attr_container_set_int64(attr_container_t **p_attr_cont, const char *key, - int64_t value) -{ - return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_INT64, &value, - 8); -} - -bool -attr_container_set_uint64(attr_container_t **p_attr_cont, const char *key, - uint64_t value) -{ - return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_UINT64, &value, - 8); -} - -bool -attr_container_set_byte(attr_container_t **p_attr_cont, const char *key, - int8_t value) -{ - return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_BYTE, &value, 1); -} - -bool -attr_container_set_int8(attr_container_t **p_attr_cont, const char *key, - int8_t value) -{ - return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_INT8, &value, 1); -} - -bool -attr_container_set_uint8(attr_container_t **p_attr_cont, const char *key, - uint8_t value) -{ - return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_UINT8, &value, - 1); -} - -bool -attr_container_set_uint16(attr_container_t **p_attr_cont, const char *key, - uint16_t value) -{ - return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_UINT16, &value, - 2); -} - -bool -attr_container_set_float(attr_container_t **p_attr_cont, const char *key, - float value) -{ - return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_FLOAT, &value, - 4); -} - -bool -attr_container_set_double(attr_container_t **p_attr_cont, const char *key, - double value) -{ - return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_DOUBLE, &value, - 8); -} - -bool -attr_container_set_bool(attr_container_t **p_attr_cont, const char *key, - bool value) -{ - int8_t value1 = value ? 1 : 0; - return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_BOOLEAN, &value1, - 1); -} - -bool -attr_container_set_string(attr_container_t **p_attr_cont, const char *key, - const char *value) -{ - if (!value) { - attr_container_printf("Set attr failed: invald input arguments.\r\n"); - return false; - } - return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_STRING, value, - strlen(value) + 1); -} - -bool -attr_container_set_bytearray(attr_container_t **p_attr_cont, const char *key, - const int8_t *value, unsigned length) -{ - if (!value) { - attr_container_printf("Set attr failed: invald input arguments.\r\n"); - return false; - } - return attr_container_set_attr(p_attr_cont, key, ATTR_TYPE_BYTEARRAY, value, - length); -} - -static const char * -attr_container_get_attr(const attr_container_t *attr_cont, const char *key) -{ - const char *attr_addr; - - if (!attr_cont || !key) { - attr_container_printf( - "Get attribute failed: invalid input arguments.\r\n"); - return NULL; - } - - if (!(attr_addr = attr_container_find_attr(attr_cont, key))) { - attr_container_printf("Get attribute failed: lookup key failed.\r\n"); - return NULL; - } - - /* key len + key + '\0' */ - return attr_addr + 2 + strlen(key) + 1; -} - -#define TEMPLATE_ATTR_BUF_TO_VALUE(attr, key, var_name) \ - do { \ - jvalue val; \ - const char *addr = attr_container_get_attr(attr, key); \ - uint8_t type; \ - if (!addr) \ - return 0; \ - val.i64 = 0; \ - type = *(uint8_t *)addr++; \ - switch (type) { \ - case ATTR_TYPE_BYTE: /* = ATTR_TYPE_INT8 */ \ - case ATTR_TYPE_SHORT: /* = ATTR_TYPE_INT16 */ \ - case ATTR_TYPE_INT: /* = ATTR_TYPE_INT32 */ \ - case ATTR_TYPE_INT64: \ - case ATTR_TYPE_UINT8: \ - case ATTR_TYPE_UINT16: \ - case ATTR_TYPE_UINT32: \ - case ATTR_TYPE_UINT64: \ - case ATTR_TYPE_FLOAT: \ - case ATTR_TYPE_DOUBLE: \ - case ATTR_TYPE_BOOLEAN: \ - bh_memcpy_s(&val, sizeof(val.var_name), addr, \ - 1 << (type & 3)); \ - break; \ - case ATTR_TYPE_STRING: \ - { \ - unsigned len = get_uint16(addr); \ - addr += 2; \ - if (len > sizeof(val.var_name)) \ - len = sizeof(val.var_name); \ - bh_memcpy_s(&val.var_name, sizeof(val.var_name), addr, len); \ - break; \ - } \ - case ATTR_TYPE_BYTEARRAY: \ - { \ - unsigned len = get_uint32(addr); \ - addr += 4; \ - if (len > sizeof(val.var_name)) \ - len = sizeof(val.var_name); \ - bh_memcpy_s(&val.var_name, sizeof(val.var_name), addr, len); \ - break; \ - } \ - default: \ - bh_assert(0); \ - break; \ - } \ - return val.var_name; \ - } while (0) - -short -attr_container_get_as_short(const attr_container_t *attr_cont, const char *key) -{ - TEMPLATE_ATTR_BUF_TO_VALUE(attr_cont, key, i16); -} - -int16_t -attr_container_get_as_int16(const attr_container_t *attr_cont, const char *key) -{ - return (int16_t)attr_container_get_as_short(attr_cont, key); -} - -int -attr_container_get_as_int(const attr_container_t *attr_cont, const char *key) -{ - TEMPLATE_ATTR_BUF_TO_VALUE(attr_cont, key, i32); -} - -int32_t -attr_container_get_as_int32(const attr_container_t *attr_cont, const char *key) -{ - return (int32_t)attr_container_get_as_int(attr_cont, key); -} - -uint32_t -attr_container_get_as_uint32(const attr_container_t *attr_cont, const char *key) -{ - return (uint32_t)attr_container_get_as_int(attr_cont, key); -} - -int64_t -attr_container_get_as_int64(const attr_container_t *attr_cont, const char *key) -{ - TEMPLATE_ATTR_BUF_TO_VALUE(attr_cont, key, i64); -} - -uint64_t -attr_container_get_as_uint64(const attr_container_t *attr_cont, const char *key) -{ - return (uint64_t)attr_container_get_as_int64(attr_cont, key); -} - -int8_t -attr_container_get_as_byte(const attr_container_t *attr_cont, const char *key) -{ - TEMPLATE_ATTR_BUF_TO_VALUE(attr_cont, key, i8); -} - -int8_t -attr_container_get_as_int8(const attr_container_t *attr_cont, const char *key) -{ - return attr_container_get_as_byte(attr_cont, key); -} - -uint8_t -attr_container_get_as_uint8(const attr_container_t *attr_cont, const char *key) -{ - return (uint8_t)attr_container_get_as_byte(attr_cont, key); -} - -uint16_t -attr_container_get_as_uint16(const attr_container_t *attr_cont, const char *key) -{ - return (uint16_t)attr_container_get_as_short(attr_cont, key); -} - -float -attr_container_get_as_float(const attr_container_t *attr_cont, const char *key) -{ - TEMPLATE_ATTR_BUF_TO_VALUE(attr_cont, key, f); -} - -double -attr_container_get_as_double(const attr_container_t *attr_cont, const char *key) -{ - TEMPLATE_ATTR_BUF_TO_VALUE(attr_cont, key, d); -} - -bool -attr_container_get_as_bool(const attr_container_t *attr_cont, const char *key) -{ - TEMPLATE_ATTR_BUF_TO_VALUE(attr_cont, key, z); -} - -const int8_t * -attr_container_get_as_bytearray(const attr_container_t *attr_cont, - const char *key, unsigned *array_length) -{ - const char *addr = attr_container_get_attr(attr_cont, key); - uint8_t type; - uint32_t length; - - if (!addr) - return NULL; - - if (!array_length) { - attr_container_printf("Get attribute failed: invalid input arguments."); - return NULL; - } - - type = *(uint8_t *)addr++; - switch (type) { - case ATTR_TYPE_BYTE: /* = ATTR_TYPE_INT8 */ - case ATTR_TYPE_SHORT: /* = ATTR_TYPE_INT16 */ - case ATTR_TYPE_INT: /* = ATTR_TYPE_INT32 */ - case ATTR_TYPE_INT64: - case ATTR_TYPE_UINT8: - case ATTR_TYPE_UINT16: - case ATTR_TYPE_UINT32: - case ATTR_TYPE_UINT64: - case ATTR_TYPE_FLOAT: - case ATTR_TYPE_DOUBLE: - case ATTR_TYPE_BOOLEAN: - length = 1 << (type & 3); - break; - case ATTR_TYPE_STRING: - length = get_uint16(addr); - addr += 2; - break; - case ATTR_TYPE_BYTEARRAY: - length = get_uint32(addr); - addr += 4; - break; - default: - return NULL; - } - - *array_length = length; - return (const int8_t *)addr; -} - -char * -attr_container_get_as_string(const attr_container_t *attr_cont, const char *key) -{ - unsigned array_length; - return (char *)attr_container_get_as_bytearray(attr_cont, key, - &array_length); -} - -const char * -attr_container_get_tag(const attr_container_t *attr_cont) -{ - return attr_cont ? attr_cont->buf + sizeof(uint32_t) + sizeof(uint16_t) - : NULL; -} - -bool -attr_container_contain_key(const attr_container_t *attr_cont, const char *key) -{ - if (!attr_cont || !key || !strlen(key)) { - attr_container_printf( - "Check contain key failed: invalid input arguments.\r\n"); - return false; - } - return attr_container_find_attr(attr_cont, key) ? true : false; -} - -unsigned int -attr_container_get_serialize_length(const attr_container_t *attr_cont) -{ - const char *p; - - if (!attr_cont) { - attr_container_printf("Get container serialize length failed: invalid " - "input arguments.\r\n"); - return 0; - } - - p = attr_cont->buf; - return sizeof(uint16_t) + get_uint32(p); -} - -bool -attr_container_serialize(char *buf, const attr_container_t *attr_cont) -{ - const char *p; - uint16_t flags; - uint32_t length; - - if (!buf || !attr_cont) { - attr_container_printf( - "Container serialize failed: invalid input arguments.\r\n"); - return false; - } - - p = attr_cont->buf; - length = sizeof(uint16_t) + get_uint32(p); - bh_memcpy_s(buf, length, attr_cont, length); - /* Set readonly */ - flags = get_uint16((const char *)attr_cont); - set_uint16(buf, flags | (1 << ATTR_CONT_READONLY_SHIFT)); - - return true; -} - -bool -attr_container_is_constant(const attr_container_t *attr_cont) -{ - uint16_t flags; - - if (!attr_cont) { - attr_container_printf( - "Container check const: invalid input arguments.\r\n"); - return false; - } - - flags = get_uint16((const char *)attr_cont); - return (flags & (1 << ATTR_CONT_READONLY_SHIFT)) ? true : false; -} - -void -attr_container_dump(const attr_container_t *attr_cont) -{ - uint32_t total_length; - uint16_t attr_num, i, type; - const char *p, *tag, *key; - jvalue value; - - if (!attr_cont) - return; - - tag = attr_container_get_tag(attr_cont); - if (!tag) - return; - - attr_container_printf("Attribute container dump:\n"); - attr_container_printf("Tag: %s\n", tag); - - p = attr_container_get_attr_begin(attr_cont, &total_length, &attr_num); - if (!p) - return; - - attr_container_printf("Attribute list:\n"); - for (i = 0; i < attr_num; i++) { - key = p + 2; - /* Skip key len and key */ - p += 2 + get_uint16(p); - type = *p++; - attr_container_printf(" key: %s", key); - - switch (type) { - case ATTR_TYPE_BYTE: /* = ATTR_TYPE_INT8 */ - bh_memcpy_s(&value.i8, 1, p, 1); - attr_container_printf(", type: byte, value: 0x%x\n", - value.i8 & 0xFF); - p++; - break; - case ATTR_TYPE_SHORT: /* = ATTR_TYPE_INT16 */ - bh_memcpy_s(&value.i16, sizeof(int16_t), p, sizeof(int16_t)); - attr_container_printf(", type: short, value: 0x%x\n", - value.i16 & 0xFFFF); - p += 2; - break; - case ATTR_TYPE_INT: /* = ATTR_TYPE_INT32 */ - bh_memcpy_s(&value.i32, sizeof(int32_t), p, sizeof(int32_t)); - attr_container_printf(", type: int, value: 0x%x\n", value.i32); - p += 4; - break; - case ATTR_TYPE_INT64: - bh_memcpy_s(&value.i64, sizeof(int64_t), p, sizeof(int64_t)); - attr_container_printf(", type: int64, value: 0x%llx\n", - (long long unsigned int)(value.i64)); - p += 8; - break; - case ATTR_TYPE_UINT8: - bh_memcpy_s(&value.u8, 1, p, 1); - attr_container_printf(", type: uint8, value: 0x%x\n", value.u8); - p++; - break; - case ATTR_TYPE_UINT16: - bh_memcpy_s(&value.u16, sizeof(uint16_t), p, sizeof(uint16_t)); - attr_container_printf(", type: uint16, value: 0x%x\n", - value.u16); - p += 2; - break; - case ATTR_TYPE_UINT32: - bh_memcpy_s(&value.u32, sizeof(uint32_t), p, sizeof(uint32_t)); - attr_container_printf(", type: uint32, value: 0x%x\n", - value.u32); - p += 4; - break; - case ATTR_TYPE_UINT64: - bh_memcpy_s(&value.u64, sizeof(uint64_t), p, sizeof(uint64_t)); - attr_container_printf(", type: int64, value: 0x%llx\n", - (long long unsigned int)(value.u64)); - p += 8; - break; - case ATTR_TYPE_FLOAT: - bh_memcpy_s(&value.f, sizeof(float), p, sizeof(float)); - attr_container_printf(", type: float, value: %f\n", value.f); - p += 4; - break; - case ATTR_TYPE_DOUBLE: - bh_memcpy_s(&value.d, sizeof(double), p, sizeof(double)); - attr_container_printf(", type: double, value: %f\n", value.d); - p += 8; - break; - case ATTR_TYPE_BOOLEAN: - bh_memcpy_s(&value.z, 1, p, 1); - attr_container_printf(", type: bool, value: 0x%x\n", value.z); - p++; - break; - case ATTR_TYPE_STRING: - attr_container_printf(", type: string, value: %s\n", - p + sizeof(uint16_t)); - p += sizeof(uint16_t) + get_uint16(p); - break; - case ATTR_TYPE_BYTEARRAY: - attr_container_printf(", type: byte array, length: %d\n", - get_uint32(p)); - p += sizeof(uint32_t) + get_uint32(p); - break; - default: - bh_assert(0); - break; - } - } - - attr_container_printf("\n"); -} diff --git a/core/app-framework/app-native-shared/bi-inc/attr_container.h b/core/app-framework/app-native-shared/bi-inc/attr_container.h deleted file mode 100644 index f5d8759b8..000000000 --- a/core/app-framework/app-native-shared/bi-inc/attr_container.h +++ /dev/null @@ -1,596 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _ATTR_CONTAINER_H_ -#define _ATTR_CONTAINER_H_ - -#include -#include -#include -#include -#include -#include -#include "bh_platform.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* Attribute type */ -enum { - ATTR_TYPE_BEGIN = 0, - ATTR_TYPE_BYTE = ATTR_TYPE_BEGIN, - ATTR_TYPE_INT8 = ATTR_TYPE_BYTE, - ATTR_TYPE_SHORT, - ATTR_TYPE_INT16 = ATTR_TYPE_SHORT, - ATTR_TYPE_INT, - ATTR_TYPE_INT32 = ATTR_TYPE_INT, - ATTR_TYPE_INT64, - ATTR_TYPE_UINT8, - ATTR_TYPE_UINT16, - ATTR_TYPE_UINT32, - ATTR_TYPE_UINT64, - /** - * Why ATTR_TYPE_FLOAT = 10? - * We determine the number of bytes that should be copied through 1<<(type & - * 3). ATTR_TYPE_BYTE = 0, so the number of bytes is 1 << 0 = 1. - * ATTR_TYPE_UINT64 = 7, so the number of bytes is 1 << 3 = 8. - * Since the float type takes up 4 bytes, ATTR_TYPE_FLOAT should be 10. - * Calculation: (1 << (10&3)) = (1 << 2) = 4 - */ - ATTR_TYPE_FLOAT = 10, - ATTR_TYPE_DOUBLE, - ATTR_TYPE_BOOLEAN, - ATTR_TYPE_STRING, - ATTR_TYPE_BYTEARRAY, - ATTR_TYPE_END = ATTR_TYPE_BYTEARRAY -}; - -#define ATTR_CONT_READONLY_SHIFT 2 - -typedef struct attr_container { - /* container flag: - * bit0, bit1 denote the implemenation algorithm, 00: buffer, 01: link list - * bit2 denotes the readonly flag: 1 is readonly and attr cannot be set - */ - char flags[2]; - /** - * Buffer format - * for buffer implementation: - * buf length (4 bytes) - * tag length (2 bytes) - * tag - * attr num (2bytes) - * attr[0..n-1]: - * attr key length (2 bytes) - * attr type (1byte) - * attr value (length depends on attr type) - */ - char buf[1]; -} attr_container_t; - -/** - * Create attribute container - * - * @param tag tag of current attribute container - * - * @return the created attribute container, NULL if failed - */ -attr_container_t * -attr_container_create(const char *tag); - -/** - * Destroy attribute container - * - * @param attr_cont the attribute container to destroy - */ -void -attr_container_destroy(const attr_container_t *attr_cont); - -/** - * Set short attribute in attribute container - * - * @param p_attr_cont pointer to attribute container to set attribute, and - * return the new attribute container if it is re-created - * @param key the attribute key - * @param value the attribute value - * - * @return true if success, false otherwise - */ -bool -attr_container_set_short(attr_container_t **p_attr_cont, const char *key, - short value); - -/** - * Set int16 attribute in attribute container - * - * @param p_attr_cont pointer to attribute container to set attribute, and - * return the new attribute container if it is re-created - * @param key the attribute key - * @param value the attribute value - * - * @return true if success, false otherwise - */ -bool -attr_container_set_int16(attr_container_t **p_attr_cont, const char *key, - int16_t value); - -/** - * Set int attribute in attribute container - * - * @param p_attr_cont pointer to attribute container to set attribute, and - * return the new attribute container if it is re-created - * @param key the attribute key - * @param value the attribute value - * - * @return true if success, false otherwise - */ -bool -attr_container_set_int(attr_container_t **p_attr_cont, const char *key, - int value); - -/** - * Set int32 attribute in attribute container - * - * @param p_attr_cont pointer to attribute container to set attribute, and - * return the new attribute container if it is re-created - * @param key the attribute key - * @param value the attribute value - * - * @return true if success, false otherwise - */ -bool -attr_container_set_int32(attr_container_t **p_attr_cont, const char *key, - int32_t value); - -/** - * Set uint32 attribute in attribute container - * - * @param p_attr_cont pointer to attribute container to set attribute, and - * return the new attribute container if it is re-created - * @param key the attribute key - * @param value the attribute value - * - * @return true if success, false otherwise - */ -bool -attr_container_set_uint32(attr_container_t **p_attr_cont, const char *key, - uint32_t value); - -/** - * Set int64 attribute in attribute container - * - * @param p_attr_cont pointer to attribute container to set attribute, and - * return the new attribute container if it is re-created - * @param key the attribute key - * @param value the attribute value - * - * @return true if success, false otherwise - */ -bool -attr_container_set_int64(attr_container_t **p_attr_cont, const char *key, - int64_t value); - -/** - * Set uint64 attribute in attribute container - * - * @param p_attr_cont pointer to attribute container to set attribute, and - * return the new attribute container if it is re-created - * @param key the attribute key - * @param value the attribute value - * - * @return true if success, false otherwise - */ -bool -attr_container_set_uint64(attr_container_t **p_attr_cont, const char *key, - uint64_t value); - -/** - * Set byte attribute in attribute container - * - * @param p_attr_cont pointer to attribute container to set attribute, and - * return the new attribute container if it is re-created - * @param key the attribute key - * @param value the attribute value - * - * @return true if success, false otherwise - */ -bool -attr_container_set_byte(attr_container_t **p_attr_cont, const char *key, - int8_t value); - -/** - * Set int8 attribute in attribute container - * - * @param p_attr_cont pointer to attribute container to set attribute, and - * return the new attribute container if it is re-created - * @param key the attribute key - * @param value the attribute value - * - * @return true if success, false otherwise - */ -bool -attr_container_set_int8(attr_container_t **p_attr_cont, const char *key, - int8_t value); - -/** - * Set uint8 attribute in attribute container - * - * @param p_attr_cont pointer to attribute container to set attribute, and - * return the new attribute container if it is re-created - * @param key the attribute key - * @param value the attribute value - * - * @return true if success, false otherwise - */ -bool -attr_container_set_uint8(attr_container_t **p_attr_cont, const char *key, - uint8_t value); - -/** - * Set uint16 attribute in attribute container - * - * @param p_attr_cont pointer to attribute container to set attribute, and - * return the new attribute container if it is re-created - * @param key the attribute key - * @param value the attribute value - * - * @return true if success, false otherwise - */ -bool -attr_container_set_uint16(attr_container_t **p_attr_cont, const char *key, - uint16_t value); - -/** - * Set float attribute in attribute container - * - * @param p_attr_cont pointer to attribute container to set attribute, and - * return the new attribute container if it is re-created - * @param key the attribute key - * @param value the attribute value - * - * @return true if success, false otherwise - */ -bool -attr_container_set_float(attr_container_t **p_attr_cont, const char *key, - float value); - -/** - * Set double attribute in attribute container - * - * @param p_attr_cont pointer to attribute container to set attribute, and - * return the new attribute container if it is re-created - * @param key the attribute key - * @param value the attribute value - * - * @return true if success, false otherwise - */ -bool -attr_container_set_double(attr_container_t **p_attr_cont, const char *key, - double value); - -/** - * Set bool attribute in attribute container - * - * @param p_attr_cont pointer to attribute container to set attribute, and - * return the new attribute container if it is re-created - * @param key the attribute key - * @param value the attribute value - * - * @return true if success, false otherwise - */ -bool -attr_container_set_bool(attr_container_t **p_attr_cont, const char *key, - bool value); - -/** - * Set string attribute in attribute container - * - * @param p_attr_cont pointer to attribute container to set attribute, and - * return the new attribute container if it is re-created - * @param key the attribute key - * @param value the attribute value - * - * @return true if success, false otherwise - */ -bool -attr_container_set_string(attr_container_t **p_attr_cont, const char *key, - const char *value); - -/** - * Set bytearray attribute in attribute container - * - * @param p_attr_cont pointer to attribute container to set attribute, and - * return the new attribute container if it is re-created - * @param key the attribute key - * @param value the bytearray buffer - * @param length the bytearray length - * - * @return true if success, false otherwise - */ -bool -attr_container_set_bytearray(attr_container_t **p_attr_cont, const char *key, - const int8_t *value, unsigned length); - -/** - * Get tag of current attribute container - * - * @param attr_cont the attribute container - * - * @return tag of current attribute container - */ -const char * -attr_container_get_tag(const attr_container_t *attr_cont); - -/** - * Get attribute number of current attribute container - * - * @param attr_cont the attribute container - * - * @return attribute number of current attribute container - */ -uint16_t -attr_container_get_attr_num(const attr_container_t *attr_cont); - -/** - * Whether the attribute container contains an attribute key. - * - * @param attr_cont the attribute container - * @param key the attribute key - * - * @return true if key is contained in message, false otherwise - */ -bool -attr_container_contain_key(const attr_container_t *attr_cont, const char *key); - -/** - * Get attribute from attribute container and return it as short value, - * return 0 if attribute isn't found in message. - * - * @param attr_cont the attribute container - * @param key the attribute key - * - * @return the short value of the attribute, 0 if key isn't found - */ -short -attr_container_get_as_short(const attr_container_t *attr_cont, const char *key); - -/** - * Get attribute from attribute container and return it as int16 value, - * return 0 if attribute isn't found in message. - * - * @param attr_cont the attribute container - * @param key the attribute key - * - * @return the short value of the attribute, 0 if key isn't found - */ -int16_t -attr_container_get_as_int16(const attr_container_t *attr_cont, const char *key); - -/** - * Get attribute from attribute container and return it as int value, - * return 0 if attribute isn't found in message. - * - * @param attr_cont the attribute container - * @param key the attribute key - * - * @return the int value of the attribute, 0 if key isn't found - */ -int -attr_container_get_as_int(const attr_container_t *attr_cont, const char *key); - -/** - * Get attribute from attribute container and return it as int32 value, - * return 0 if attribute isn't found in message. - * - * @param attr_cont the attribute container - * @param key the attribute key - * - * @return the int value of the attribute, 0 if key isn't found - */ -int32_t -attr_container_get_as_int32(const attr_container_t *attr_cont, const char *key); - -/** - * Get attribute from attribute container and return it as uint32 value, - * return 0 if attribute isn't found in message. - * - * @param attr_cont the attribute container - * @param key the attribute key - * - * @return the unsigned int value of the attribute, 0 if key isn't found - */ -uint32_t -attr_container_get_as_uint32(const attr_container_t *attr_cont, - const char *key); - -/** - * Get attribute from attribute container and return it as int64 value, - * return 0 if attribute isn't found in attribute container. - * - * @param attr_cont the attribute container - * @param key the attribute key - * - * @return the long value of the attribute, 0 if key isn't found - */ -int64_t -attr_container_get_as_int64(const attr_container_t *attr_cont, const char *key); - -/** - * Get attribute from attribute container and return it as uint64 value, - * return 0 if attribute isn't found in attribute container. - * - * @param attr_cont the attribute container - * @param key the attribute key - * - * @return the unsigned long value of the attribute, 0 if key isn't found - */ -uint64_t -attr_container_get_as_uint64(const attr_container_t *attr_cont, - const char *key); - -/** - * Get attribute from attribute container and return it as byte value, - * return 0 if attribute isn't found in attribute container. - * - * @param attr_cont the attribute container - * @param key the attribute key - * - * @return the byte value of the attribute, 0 if key isn't found - */ -int8_t -attr_container_get_as_byte(const attr_container_t *attr_cont, const char *key); - -/** - * Get attribute from attribute container and return it as int8 value, - * return 0 if attribute isn't found in attribute container. - * - * @param attr_cont the attribute container - * @param key the attribute key - * - * @return the byte value of the attribute, 0 if key isn't found - */ -int8_t -attr_container_get_as_int8(const attr_container_t *attr_cont, const char *key); - -/** - * Get attribute from attribute container and return it as uint8 value, - * return 0 if attribute isn't found in attribute container. - * - * @param attr_cont the attribute container - * @param key the attribute key - * - * @return the uint8 value of the attribute, 0 if key isn't found - */ -uint8_t -attr_container_get_as_uint8(const attr_container_t *attr_cont, const char *key); - -/** - * Get attribute from attribute container and return it as uint16 value, - * return 0 if attribute isn't found in attribute container. - * - * @param attr_cont the attribute container - * @param key the attribute key - * - * @return the char value of the attribute, 0 if key isn't found - */ -uint16_t -attr_container_get_as_uint16(const attr_container_t *attr_cont, - const char *key); - -/** - * Get attribute from attribute container and return it as float value, - * return 0 if attribute isn't found in attribute container. - * - * @param attr_cont the attribute container - * @param key the attribute key - * - * @return the float value of the attribute, 0 if key isn't found - */ -float -attr_container_get_as_float(const attr_container_t *attr_cont, const char *key); - -/** - * Get attribute from attribute container and return it as double value, - * return 0 if attribute isn't found in attribute container. - * - * @param attr_cont the attribute container - * @param key the attribute key - * - * @return the double value of the attribute, 0 if key isn't found - */ -double -attr_container_get_as_double(const attr_container_t *attr_cont, - const char *key); - -/** - * Get attribute from attribute container and return it as bool value, - * return false if attribute isn't found in attribute container. - * - * @param attr_cont the attribute container - * @param key the attribute key - * - * @return the bool value of the attribute, 0 if key isn't found - */ -bool -attr_container_get_as_bool(const attr_container_t *attr_cont, const char *key); - -/** - * Get attribute from attribute container and return it as string value, - * return NULL if attribute isn't found in attribute container. - * - * @param attr_cont the attribute container - * @param key the attribute key - * - * @return the string value of the attribute, NULL if key isn't found - */ -char * -attr_container_get_as_string(const attr_container_t *attr_cont, - const char *key); - -/** - * Get attribute from attribute container and return it as bytearray value, - * return 0 if attribute isn't found in attribute container. - * - * @param attr_cont the attribute container - * @param key the attribute key - * - * @return the bytearray value of the attribute, NULL if key isn't found - */ -const int8_t * -attr_container_get_as_bytearray(const attr_container_t *attr_cont, - const char *key, unsigned *array_length); - -/** - * Get the buffer size of attribute container - * - * @param attr_cont the attribute container - * - * @return the buffer size of attribute container - */ -unsigned -attr_container_get_serialize_length(const attr_container_t *attr_cont); - -/** - * Serialize attribute container to a buffer - * - * @param buf the buffer to receive the serialized data - * @param attr_cont the attribute container to be serialized - * - * @return true if success, false otherwise - */ -bool -attr_container_serialize(char *buf, const attr_container_t *attr_cont); - -/** - * Whether the attribute container is const, or set attribute isn't supported - * - * @param attr_cont the attribute container - * - * @return true if const, false otherwise - */ -bool -attr_container_is_constant(const attr_container_t *attr_cont); - -void -attr_container_dump(const attr_container_t *attr_cont); - -#ifndef attr_container_malloc -#define attr_container_malloc WA_MALLOC -#endif - -#ifndef attr_container_free -#define attr_container_free WA_FREE -#endif - -#ifndef attr_container_printf -#define attr_container_printf printf -#endif - -#ifdef __cplusplus -} /* end of extern "C" */ -#endif - -#endif /* end of _ATTR_CONTAINER_H_ */ diff --git a/core/app-framework/app-native-shared/bi-inc/shared_utils.h b/core/app-framework/app-native-shared/bi-inc/shared_utils.h deleted file mode 100644 index 8155ea1f7..000000000 --- a/core/app-framework/app-native-shared/bi-inc/shared_utils.h +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _SHARED_UTILS_H_ -#define _SHARED_UTILS_H_ - -#include "bh_platform.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define FMT_ATTR_CONTAINER 99 -#define FMT_APP_RAW_BINARY 98 - -/* the request structure */ -typedef struct request { - // message id - uint32 mid; - - // url of the request - char *url; - - // action of the request, can be PUT/GET/POST/DELETE - int action; - - // payload format, currently only support attr_container_t type - int fmt; - - // payload of the request, currently only support attr_container_t type - void *payload; - - // length in bytes of the payload - int payload_len; - - // sender of the request - unsigned long sender; -} request_t; - -/* the response structure */ -typedef struct response { - // message id - uint32 mid; - - // status of the response - int status; - - // payload format - int fmt; - - // payload of the response, - void *payload; - - // length in bytes of the payload - int payload_len; - - // receiver of the response - unsigned long reciever; -} response_t; - -int -check_url_start(const char *url, int url_len, const char *leading_str); - -bool -match_url(char *pattern, char *matched); - -char * -find_key_value(char *buffer, int buffer_len, char *key, char *value, - int value_len, char delimiter); - -request_t * -clone_request(request_t *request); - -void -request_cleaner(request_t *request); - -response_t * -clone_response(response_t *response); - -void -response_cleaner(response_t *response); - -/** - * @brief Set fields of response. - * - * @param response pointer of the response to be set - * @param status status of response - * @param fmt format of the response payload - * @param payload payload of the response - * @param payload_len length in bytes of the response payload - * - * @return pointer to the response - * - * @warning the response pointer MUST NOT be NULL - */ -response_t * -set_response(response_t *response, int status, int fmt, const char *payload, - int payload_len); - -/** - * @brief Make a response for a request. - * - * @param request pointer of the request - * @param response pointer of the response to be made - * - * @return pointer to the response - * - * @warning the request and response pointers MUST NOT be NULL - */ -response_t * -make_response_for_request(request_t *request, response_t *response); - -/** - * @brief Initialize a request. - * - * @param request pointer of the request to be initialized - * @param url url of the request - * @param action action of the request - * @param fmt format of the request payload - * @param payload payload of the request - * @param payload_len length in bytes of the request payload - * - * @return pointer to the request - * - * @warning the request pointer MUST NOT be NULL - */ -request_t * -init_request(request_t *request, char *url, int action, int fmt, void *payload, - int payload_len); - -char * -pack_request(request_t *request, int *size); - -request_t * -unpack_request(char *packet, int size, request_t *request); - -char * -pack_response(response_t *response, int *size); - -response_t * -unpack_response(char *packet, int size, response_t *response); - -void -free_req_resp_packet(char *packet); - -char * -wa_strdup(const char *str); - -#ifdef __cplusplus -} -#endif - -#endif /* end of _SHARED_UTILS_H_ */ diff --git a/core/app-framework/app-native-shared/bi-inc/wgl_shared_utils.h b/core/app-framework/app-native-shared/bi-inc/wgl_shared_utils.h deleted file mode 100644 index 86d864e41..000000000 --- a/core/app-framework/app-native-shared/bi-inc/wgl_shared_utils.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef WAMR_GRAPHIC_LIBRARY_SHARED_UTILS_H -#define WAMR_GRAPHIC_LIBRARY_SHARED_UTILS_H - -#include "bh_platform.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#include - -/* Object native function IDs */ -enum { - OBJ_FUNC_ID_DEL, - OBJ_FUNC_ID_DEL_ASYNC, - OBJ_FUNC_ID_CLEAN, - OBJ_FUNC_ID_SET_EVT_CB, - OBJ_FUNC_ID_ALIGN, - - /* Number of functions */ - _OBJ_FUNC_ID_NUM, -}; - -/* Button native function IDs */ -enum { - BTN_FUNC_ID_CREATE, - BTN_FUNC_ID_SET_TOGGLE, - BTN_FUNC_ID_SET_STATE, - BTN_FUNC_ID_TOGGLE, - BTN_FUNC_ID_SET_INK_IN_TIME, - BTN_FUNC_ID_SET_INK_WAIT_TIME, - BTN_FUNC_ID_SET_INK_OUT_TIME, - BTN_FUNC_ID_GET_STATE, - BTN_FUNC_ID_GET_TOGGLE, - BTN_FUNC_ID_GET_INK_IN_TIME, - BTN_FUNC_ID_GET_INK_WAIT_TIME, - BTN_FUNC_ID_GET_INK_OUT_TIME, - /* Number of functions */ - _BTN_FUNC_ID_NUM, -}; - -/* Check box native function IDs */ -enum { - CB_FUNC_ID_CREATE, - CB_FUNC_ID_SET_TEXT, - CB_FUNC_ID_SET_STATIC_TEXT, - CB_FUNC_ID_GET_TEXT, - CB_FUNC_ID_GET_TEXT_LENGTH, - - /* Number of functions */ - _CB_FUNC_ID_NUM, -}; - -/* List native function IDs */ -enum { - LIST_FUNC_ID_CREATE, - LIST_FUNC_ID_ADD_BTN, - - /* Number of functions */ - _LIST_FUNC_ID_NUM, -}; - -/* Label native function IDs */ -enum { - LABEL_FUNC_ID_CREATE, - LABEL_FUNC_ID_SET_TEXT, - LABEL_FUNC_ID_SET_ARRAY_TEXT, - LABEL_FUNC_ID_SET_STATIC_TEXT, - LABEL_FUNC_ID_SET_LONG_MODE, - LABEL_FUNC_ID_SET_ALIGN, - LABEL_FUNC_ID_SET_RECOLOR, - LABEL_FUNC_ID_SET_BODY_DRAW, - LABEL_FUNC_ID_SET_ANIM_SPEED, - LABEL_FUNC_ID_SET_TEXT_SEL_START, - LABEL_FUNC_ID_SET_TEXT_SEL_END, - LABEL_FUNC_ID_GET_TEXT, - LABEL_FUNC_ID_GET_TEXT_LENGTH, - LABEL_FUNC_ID_GET_LONG_MODE, - LABEL_FUNC_ID_GET_ALIGN, - LABEL_FUNC_ID_GET_RECOLOR, - LABEL_FUNC_ID_GET_BODY_DRAW, - LABEL_FUNC_ID_GET_ANIM_SPEED, - LABEL_FUNC_ID_GET_LETTER_POS, - LABEL_FUNC_ID_GET_TEXT_SEL_START, - LABEL_FUNC_ID_GET_TEXT_SEL_END, - LABEL_FUNC_ID_INS_TEXT, - LABEL_FUNC_ID_CUT_TEXT, - /* Number of functions */ - _LABEL_FUNC_ID_NUM, -}; - -#ifdef __cplusplus -} -#endif - -#endif /* WAMR_GRAPHIC_LIBRARY_SHARED_UTILS_H */ diff --git a/core/app-framework/app-native-shared/native_interface.cmake b/core/app-framework/app-native-shared/native_interface.cmake deleted file mode 100644 index 48ebe0a33..000000000 --- a/core/app-framework/app-native-shared/native_interface.cmake +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -set (NATIVE_INTERFACE_DIR ${CMAKE_CURRENT_LIST_DIR}) - -include_directories(${NATIVE_INTERFACE_DIR}) - - -file (GLOB_RECURSE source_all ${NATIVE_INTERFACE_DIR}/*.c) - -set (NATIVE_INTERFACE_SOURCE ${source_all}) - -set (WASM_APP_BI_INC_DIR "${NATIVE_INTERFACE_DIR}/bi-inc") -LIST (APPEND RUNTIME_LIB_HEADER_LIST "${NATIVE_INTERFACE_DIR}/native_interface.h") - diff --git a/core/app-framework/app-native-shared/native_interface.h b/core/app-framework/app-native-shared/native_interface.h deleted file mode 100644 index ce9f24780..000000000 --- a/core/app-framework/app-native-shared/native_interface.h +++ /dev/null @@ -1,13 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _NATIVE_INTERFACE_H_ -#define _NATIVE_INTERFACE_H_ - -/* Note: the bh_plaform.h is the only head file separately - implemented by both [app] and [native] worlds */ -#include "bh_platform.h" - -#endif /* end of _NATIVE_INTERFACE_H */ diff --git a/core/app-framework/app-native-shared/restful_utils.c b/core/app-framework/app-native-shared/restful_utils.c deleted file mode 100644 index 03e86a699..000000000 --- a/core/app-framework/app-native-shared/restful_utils.c +++ /dev/null @@ -1,493 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include -#include -#include -#include - -#include "bi-inc/shared_utils.h" - -/* Serialization of request and response message - * - * Choices: - * We considered a few options: - * 1. coap - * 2. flatbuffer - * 3. cbor - * 4. attr-containers of our own - * 5. customized serialization for request/response - * - * Now we choose the #5 mainly because we need to quickly get the URL for - * dispatching and sometimes we want to change the URL in the original packet. - * the request format: fixed part: version: (1 byte), code (1 byte), fmt(2 - * byte), mid (4 bytes), sender_id(4 bytes), url_len(2 bytes), - * payload_len(4bytes) dynamic part: url (bytes in url_len), payload - * - * response format: - * fixed part: (1 byte), code (1 byte), fmt(2 byte), mid (4 bytes), sender_id(4 - * bytes), payload_len(4bytes) dynamic part: payload - */ -#define REQUES_PACKET_VER 1 -#define REQUEST_PACKET_FIX_PART_LEN 18 -#define REQUEST_PACKET_URL_OFFSET REQUEST_PACKET_FIX_PART_LEN -#define REQUEST_PACKET_URL_LEN \ - *((uint16 *)((char *)buffer + 12)) /* to ensure little endian */ -#define REQUEST_PACKET_PAYLOAD_LEN \ - *((uint32 *)((char *)buffer + 14)) /* to ensure little endian */ -#define REQUEST_PACKET_URL(buffer) ((char *)buffer + REQUEST_PACKET_URL_OFFSET) -#define REQUEST_PACKET_PAYLOAD(buffer) \ - ((char *)buffer + REQUEST_PACKET_URL_OFFSET \ - + REQUEST_PACKET_URL_LEN(buffer)) - -#define RESPONSE_PACKET_FIX_PART_LEN 16 - -char * -pack_request(request_t *request, int *size) -{ - int url_len = strlen(request->url) + 1; - int len = REQUEST_PACKET_FIX_PART_LEN + url_len + request->payload_len; - uint16 u16; - uint32 u32; - char *packet; - - if ((packet = (char *)WA_MALLOC(len)) == NULL) - return NULL; - - /* TODO: ensure little endian for words and dwords */ - *packet = REQUES_PACKET_VER; - *((uint8 *)(packet + 1)) = request->action; - - u16 = htons(request->fmt); - memcpy(packet + 2, &u16, 2); - - u32 = htonl(request->mid); - memcpy(packet + 4, &u32, 4); - - u32 = htonl(request->sender); - memcpy(packet + 8, &u32, 4); - - u16 = htons(url_len); - memcpy(packet + 12, &u16, 2); - - u32 = htonl(request->payload_len); - memcpy(packet + 14, &u32, 4); - - strcpy(packet + REQUEST_PACKET_URL_OFFSET, request->url); - memcpy(packet + REQUEST_PACKET_URL_OFFSET + url_len, request->payload, - request->payload_len); - - *size = len; - return packet; -} - -void -free_req_resp_packet(char *packet) -{ - WA_FREE(packet); -} - -request_t * -unpack_request(char *packet, int size, request_t *request) -{ - uint16 url_len, u16; - uint32 payload_len, u32; - - if (*packet != REQUES_PACKET_VER) { - return NULL; - } - if (size < REQUEST_PACKET_FIX_PART_LEN) { - return NULL; - } - - memcpy(&u16, packet + 12, 2); - url_len = ntohs(u16); - - memcpy(&u32, packet + 14, 4); - payload_len = ntohl(u32); - - if (size != (REQUEST_PACKET_FIX_PART_LEN + url_len + payload_len)) { - return NULL; - } - - if (*(packet + REQUEST_PACKET_FIX_PART_LEN + url_len - 1) != 0) { - return NULL; - } - - request->action = *((uint8 *)(packet + 1)); - - memcpy(&u16, packet + 2, 2); - request->fmt = ntohs(u16); - - memcpy(&u32, packet + 4, 4); - request->mid = ntohl(u32); - - memcpy(&u32, packet + 8, 4); - request->sender = ntohl(u32); - - request->payload_len = payload_len; - request->url = REQUEST_PACKET_URL(packet); - - if (payload_len > 0) - request->payload = packet + REQUEST_PACKET_URL_OFFSET + url_len; - else - request->payload = NULL; - - return request; -} - -char * -pack_response(response_t *response, int *size) -{ - int len = RESPONSE_PACKET_FIX_PART_LEN + response->payload_len; - uint16 u16; - uint32 u32; - char *packet; - - if ((packet = (char *)WA_MALLOC(len)) == NULL) - return NULL; - - /* TODO: ensure little endian for words and dwords */ - *packet = REQUES_PACKET_VER; - *((uint8 *)(packet + 1)) = response->status; - - u16 = htons(response->fmt); - memcpy(packet + 2, &u16, 2); - - u32 = htonl(response->mid); - memcpy(packet + 4, &u32, 4); - - u32 = htonl(response->reciever); - memcpy(packet + 8, &u32, 4); - - u32 = htonl(response->payload_len); - memcpy(packet + 12, &u32, 4); - - memcpy(packet + RESPONSE_PACKET_FIX_PART_LEN, response->payload, - response->payload_len); - - *size = len; - return packet; -} - -response_t * -unpack_response(char *packet, int size, response_t *response) -{ - uint16 u16; - uint32 payload_len, u32; - - if (*packet != REQUES_PACKET_VER) - return NULL; - - if (size < RESPONSE_PACKET_FIX_PART_LEN) - return NULL; - - memcpy(&u32, packet + 12, 4); - payload_len = ntohl(u32); - if (size != (RESPONSE_PACKET_FIX_PART_LEN + payload_len)) - return NULL; - - response->status = *((uint8 *)(packet + 1)); - - memcpy(&u16, packet + 2, 2); - response->fmt = ntohs(u16); - - memcpy(&u32, packet + 4, 4); - response->mid = ntohl(u32); - - memcpy(&u32, packet + 8, 4); - response->reciever = ntohl(u32); - - response->payload_len = payload_len; - if (payload_len > 0) - response->payload = packet + RESPONSE_PACKET_FIX_PART_LEN; - else - response->payload = NULL; - - return response; -} - -request_t * -clone_request(request_t *request) -{ - /* deep clone */ - request_t *req = (request_t *)WA_MALLOC(sizeof(request_t)); - if (req == NULL) - return NULL; - - memset(req, 0, sizeof(*req)); - req->action = request->action; - req->fmt = request->fmt; - req->url = wa_strdup(request->url); - req->sender = request->sender; - req->mid = request->mid; - - if (req->url == NULL) - goto fail; - - req->payload_len = request->payload_len; - - if (request->payload_len) { - req->payload = (char *)WA_MALLOC(request->payload_len); - if (!req->payload) - goto fail; - memcpy(req->payload, request->payload, request->payload_len); - } - else { - /* when payload_len is 0, the payload may be used for - carrying some handle or integer */ - req->payload = request->payload; - } - - return req; - -fail: - request_cleaner(req); - return NULL; -} - -void -request_cleaner(request_t *request) -{ - if (request->url != NULL) - WA_FREE(request->url); - if (request->payload != NULL && request->payload_len > 0) - WA_FREE(request->payload); - - WA_FREE(request); -} - -void -response_cleaner(response_t *response) -{ - if (response->payload != NULL && response->payload_len > 0) - WA_FREE(response->payload); - - WA_FREE(response); -} - -response_t * -clone_response(response_t *response) -{ - response_t *clone = (response_t *)WA_MALLOC(sizeof(response_t)); - - if (clone == NULL) - return NULL; - - memset(clone, 0, sizeof(*clone)); - clone->fmt = response->fmt; - clone->mid = response->mid; - clone->status = response->status; - clone->reciever = response->reciever; - clone->payload_len = response->payload_len; - if (clone->payload_len) { - clone->payload = (char *)WA_MALLOC(response->payload_len); - if (!clone->payload) - goto fail; - memcpy(clone->payload, response->payload, response->payload_len); - } - else { - /* when payload_len is 0, the payload may be used for - carrying some handle or integer */ - clone->payload = response->payload; - } - return clone; - -fail: - response_cleaner(clone); - return NULL; -} - -response_t * -set_response(response_t *response, int status, int fmt, const char *payload, - int payload_len) -{ - response->payload = (void *)payload; - response->payload_len = payload_len; - response->status = status; - response->fmt = fmt; - return response; -} - -response_t * -make_response_for_request(request_t *request, response_t *response) -{ - response->mid = request->mid; - response->reciever = request->sender; - - return response; -} - -static unsigned int mid = 0; - -request_t * -init_request(request_t *request, char *url, int action, int fmt, void *payload, - int payload_len) -{ - request->url = url; - request->action = action; - request->fmt = fmt; - request->payload = payload; - request->payload_len = payload_len; - request->mid = ++mid; - - return request; -} - -/* - check if the "url" is starting with "leading_str" - return: 0 - not match; >0 - the offset of matched url, include any "/" at the - end notes: - 1. it ensures the leading_str "/abc" can pass "/abc/cde" and "/abc/, but fail - "/ab" and "/abcd". leading_str "/abc/" can pass "/abc" - 2. it omit the '/' at the first char - 3. it ensure the leading_str "/abc" can pass "/abc?cde - */ - -int -check_url_start(const char *url, int url_len, const char *leading_str) -{ - int offset = 0; - if (*leading_str == '/') - leading_str++; - if (url_len > 0 && *url == '/') { - url_len--; - url++; - offset++; - } - - int len = strlen(leading_str); - if (len == 0) - return 0; - - /* ensure leading_str not end with "/" */ - if (leading_str[len - 1] == '/') { - len--; - if (len == 0) - return 0; - } - - /* equal length */ - if (url_len == len) { - if (memcmp(url, leading_str, url_len) == 0) { - return (offset + len); - } - else { - return 0; - } - } - - if (url_len < len) - return 0; - else if (memcmp(url, leading_str, len) != 0) - return 0; - else if (url[len] != '/' && url[len] != '?') - return 0; - else - return (offset + len + 1); -} - -// * @pattern: -// * sample 1: /abcd, match /abcd only -// * sample 2: /abcd/ match match "/abcd" and "/abcd/*" -// * sample 3: /abcd*, match any url started with "/abcd" -// * sample 4: /abcd/*, exclude "/abcd" - -bool -match_url(char *pattern, char *matched) -{ - if (*pattern == '/') - pattern++; - if (*matched == '/') - matched++; - - int matched_len = strlen(matched); - if (matched_len == 0) - return false; - - if (matched[matched_len - 1] == '/') { - matched_len--; - if (matched_len == 0) - return false; - } - - int len = strlen(pattern); - if (len == 0) - return false; - - if (pattern[len - 1] == '/') { - len--; - if (strncmp(pattern, matched, len) != 0) - return false; - - if (len == matched_len) - return true; - - if (matched_len > len && matched[len] == '/') - return true; - - return false; - } - else if (pattern[len - 1] == '*') { - if (pattern[len - 2] == '/') { - if (strncmp(pattern, matched, len - 1) == 0) - return true; - else - return false; - } - else { - return (strncmp(pattern, matched, len - 1) == 0); - } - } - else { - return (strcmp(pattern, matched) == 0); - } -} - -/* - * get the value of the key from following format buffer: - * key1=value1;key2=value2;key3=value3 - */ -char * -find_key_value(char *buffer, int buffer_len, char *key, char *value, - int value_len, char delimiter) -{ - char *p = buffer; - int remaining = buffer_len; - int key_len = strlen(key); - - while (*p != 0 && remaining > 0) { - while (*p == ' ' || *p == delimiter) { - p++; - remaining--; - } - - if (remaining <= key_len) - return NULL; - - /* find the key */ - if (0 == strncmp(p, key, key_len) && p[key_len] == '=') { - p += (key_len + 1); - remaining -= (key_len + 1); - char *v = value; - memset(value, 0, value_len); - value_len--; /* ensure last char is 0 */ - while (*p != delimiter && remaining > 0 && value_len > 0) { - *v++ = *p++; - remaining--; - value_len--; - } - return value; - } - - /* goto next key */ - while (*p != delimiter && remaining > 0) { - p++; - remaining--; - } - } - - return NULL; -} diff --git a/core/app-framework/app_ext_lib_export.c b/core/app-framework/app_ext_lib_export.c deleted file mode 100644 index 532491b43..000000000 --- a/core/app-framework/app_ext_lib_export.c +++ /dev/null @@ -1,38 +0,0 @@ -#include "lib_export.h" - -#ifdef APP_FRAMEWORK_SENSOR -#include "sensor_native_api.h" -#endif - -#ifdef APP_FRAMEWORK_CONNECTION -#include "connection_native_api.h" -#endif - -#ifdef APP_FRAMEWORK_WGL -#include "gui_native_api.h" -#endif - -/* More header file here */ - -static NativeSymbol extended_native_symbol_defs[] = { -#ifdef APP_FRAMEWORK_SENSOR -#include "runtime_sensor.inl" -#endif - -#ifdef APP_FRAMEWORK_CONNECTION -#include "connection.inl" -#endif - -#ifdef APP_FRAMEWORK_WGL -#include "wamr_gui.inl" -#endif - - /* More inl file here */ -}; - -int -get_ext_lib_export_apis(NativeSymbol **p_ext_lib_apis) -{ - *p_ext_lib_apis = extended_native_symbol_defs; - return sizeof(extended_native_symbol_defs) / sizeof(NativeSymbol); -} diff --git a/core/app-framework/app_framework.cmake b/core/app-framework/app_framework.cmake deleted file mode 100644 index b8a63d856..000000000 --- a/core/app-framework/app_framework.cmake +++ /dev/null @@ -1,93 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - - -add_definitions (-DWASM_ENABLE_APP_FRAMEWORK=1) - -set (APP_FRAMEWORK_ROOT_DIR ${CMAKE_CURRENT_LIST_DIR}) - -if ( NOT DEFINED APP_FRAMEWORK_INCLUDE_TYPE ) - LIST (APPEND WASM_APP_LIB_SOURCE_ALL ${CMAKE_CURRENT_LIST_DIR}/app_ext_lib_export.c) -endif() - -# app-native-shared and base are required -include (${APP_FRAMEWORK_ROOT_DIR}/app-native-shared/native_interface.cmake) -LIST (APPEND WASM_APP_SOURCE_ALL ${NATIVE_INTERFACE_SOURCE}) - -MACRO(SUBDIRLIST result curdir) - FILE(GLOB children RELATIVE ${curdir} ${curdir}/*) - SET(dirlist "") - FOREACH(child ${children}) - IF(IS_DIRECTORY ${curdir}/${child}) - LIST(APPEND dirlist ${child}) - ENDIF() - ENDFOREACH() - SET(${result} ${dirlist}) -ENDMACRO() - -function (add_module_native arg) - message ("Add native module ${ARGV0}") - include (${APP_FRAMEWORK_ROOT_DIR}/${ARGV0}/native/wasm_lib.cmake) - - file (GLOB header - ${APP_FRAMEWORK_ROOT_DIR}/${ARGV0}/native/*.h - ${APP_FRAMEWORK_ROOT_DIR}/${ARGV0}/native/*.inl - ) - - LIST (APPEND WASM_APP_LIBS_DIR ${APP_FRAMEWORK_ROOT_DIR}/${ARGV0}/native) - set (WASM_APP_LIBS_DIR ${WASM_APP_LIBS_DIR} PARENT_SCOPE) - - LIST (APPEND RUNTIME_LIB_HEADER_LIST ${header}) - set (RUNTIME_LIB_HEADER_LIST ${RUNTIME_LIB_HEADER_LIST} PARENT_SCOPE) - - LIST (APPEND WASM_APP_LIB_SOURCE_ALL ${WASM_APP_LIB_CURRENT_SOURCE}) - set (WASM_APP_LIB_SOURCE_ALL ${WASM_APP_LIB_SOURCE_ALL} PARENT_SCOPE) -endfunction () - -function (add_module_app arg) - message ("Add app module ${ARGV0}") - include (${APP_FRAMEWORK_ROOT_DIR}/${ARGV0}/app/wasm_app.cmake) - - LIST (APPEND WASM_APP_WA_INC_DIR_LIST "${APP_FRAMEWORK_ROOT_DIR}/${ARGV0}/app/wa-inc") - set (WASM_APP_WA_INC_DIR_LIST ${WASM_APP_WA_INC_DIR_LIST} PARENT_SCOPE) - - LIST (APPEND WASM_APP_NAME ${ARGV0}) - set (WASM_APP_NAME ${WASM_APP_NAME} PARENT_SCOPE) - - LIST (APPEND WASM_APP_SOURCE_ALL ${WASM_APP_CURRENT_SOURCE}) - set (WASM_APP_SOURCE_ALL ${WASM_APP_SOURCE_ALL} PARENT_SCOPE) -endfunction () - -if ("${WAMR_BUILD_APP_LIST}" STREQUAL "WAMR_APP_BUILD_ALL") - # add all modules under this folder - SUBDIRLIST(SUBDIRS ${APP_FRAMEWORK_ROOT_DIR}) - - FOREACH(subdir ${SUBDIRS}) - if ("${subdir}" STREQUAL "app-native-shared") - continue() - endif () - if ("${subdir}" STREQUAL "template") - continue() - endif () - - if ( NOT DEFINED APP_FRAMEWORK_INCLUDE_TYPE ) - add_module_native (${subdir}) - else () - add_module_app (${subdir}) - endif () - ENDFOREACH() - -else () - # add each module in the list - FOREACH (dir IN LISTS WAMR_BUILD_APP_LIST) - string(REPLACE "WAMR_APP_BUILD_" "" dir ${dir}) - string(TOLOWER ${dir} dir) - - if ( NOT DEFINED APP_FRAMEWORK_INCLUDE_TYPE ) - add_module_native (${dir}) - else () - add_module_app (${dir}) - endif () - ENDFOREACH (dir) - -endif() diff --git a/core/app-framework/base/app/bh_platform.c b/core/app-framework/base/app/bh_platform.c deleted file mode 100644 index 1848d0792..000000000 --- a/core/app-framework/base/app/bh_platform.c +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "bh_platform.h" -#include -#include -#include - -/* - * - * - */ - -static bool -is_little_endian() -{ - long i = 0x01020304; - unsigned char *c = (unsigned char *)&i; - return (*c == 0x04) ? true : false; -} - -static void -swap32(uint8 *pData) -{ - uint8 value = *pData; - *pData = *(pData + 3); - *(pData + 3) = value; - - value = *(pData + 1); - *(pData + 1) = *(pData + 2); - *(pData + 2) = value; -} - -static void -swap16(uint8 *pData) -{ - uint8 value = *pData; - *(pData) = *(pData + 1); - *(pData + 1) = value; -} - -uint32 -htonl(uint32 value) -{ - uint32 ret; - if (is_little_endian()) { - ret = value; - swap32((uint8 *)&ret); - return ret; - } - - return value; -} - -uint32 -ntohl(uint32 value) -{ - return htonl(value); -} - -uint16 -htons(uint16 value) -{ - uint16 ret; - if (is_little_endian()) { - ret = value; - swap16((uint8 *)&ret); - return ret; - } - - return value; -} - -uint16 -ntohs(uint16 value) -{ - return htons(value); -} - -char * -wa_strdup(const char *s) -{ - char *s1 = NULL; - if (s && (s1 = WA_MALLOC(strlen(s) + 1))) - memcpy(s1, s, strlen(s) + 1); - return s1; -} diff --git a/core/app-framework/base/app/bh_platform.h b/core/app-framework/base/app/bh_platform.h deleted file mode 100644 index 8e10dcb64..000000000 --- a/core/app-framework/base/app/bh_platform.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef DEPS_IWASM_APP_LIBS_BASE_BH_PLATFORM_H_ -#define DEPS_IWASM_APP_LIBS_BASE_BH_PLATFORM_H_ - -#include - -typedef unsigned char uint8; -typedef char int8; -typedef unsigned short uint16; -typedef short int16; -typedef unsigned int uint32; -typedef int int32; - -#ifndef NULL -#define NULL ((void *)0) -#endif - -#ifndef __cplusplus -#define true 1 -#define false 0 -#define inline __inline -#endif - -// all wasm-app<->native shared source files should use WA_MALLOC/WA_FREE. -// they will be mapped to different implementations in each side -#ifndef WA_MALLOC -#define WA_MALLOC malloc -#endif - -#ifndef WA_FREE -#define WA_FREE free -#endif - -uint32 -htonl(uint32 value); -uint32 -ntohl(uint32 value); -uint16 -htons(uint16 value); -uint16 -ntohs(uint16 value); - -// We are not worried for the WASM world since the sandbox will catch it. -#define bh_memcpy_s(dst, dst_len, src, src_len) memcpy(dst, src, src_len) - -#ifdef NDEBUG -#define bh_assert(v) (void)0 -#else -#define bh_assert(v) \ - do { \ - if (!(v)) { \ - int _count; \ - printf("ASSERTION FAILED: %s, at %s, line %d", #v, __FILE__, \ - __LINE__); \ - _count = printf("\n"); \ - printf("%d\n", _count / (_count - 1)); \ - } \ - } while (0) -#endif - -#endif /* DEPS_IWASM_APP_LIBS_BASE_BH_PLATFORM_H_ */ diff --git a/core/app-framework/base/app/req_resp_api.h b/core/app-framework/base/app/req_resp_api.h deleted file mode 100644 index 575c35732..000000000 --- a/core/app-framework/base/app/req_resp_api.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _REQ_RESP_API_H_ -#define _REQ_RESP_API_H_ - -#include "bh_platform.h" - -#ifdef __cplusplus -extern "C" { -#endif - -bool -wasm_response_send(const char *buf, int size); - -void -wasm_register_resource(const char *url); - -void -wasm_post_request(const char *buf, int size); - -void -wasm_sub_event(const char *url); - -#ifdef __cplusplus -} -#endif - -#endif /* end of _REQ_RESP_API_H_ */ diff --git a/core/app-framework/base/app/request.c b/core/app-framework/base/app/request.c deleted file mode 100644 index 3ba44fbc7..000000000 --- a/core/app-framework/base/app/request.c +++ /dev/null @@ -1,365 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "bi-inc/attr_container.h" -#include "wa-inc/request.h" -#include "wa-inc/timer_wasm_app.h" -#include "bi-inc/shared_utils.h" -#include "wasm_app.h" -#include "req_resp_api.h" -#include "timer_api.h" - -#define TRANSACTION_TIMEOUT_MS 5000 - -typedef enum { Reg_Event, Reg_Request } reg_type_t; - -typedef struct _res_register { - struct _res_register *next; - const char *url; - reg_type_t reg_type; - void (*request_handler)(request_t *); -} res_register_t; - -typedef struct transaction { - struct transaction *next; - int mid; - unsigned int time; /* start time */ - response_handler_f handler; - void *user_data; -} transaction_t; - -static res_register_t *g_resources = NULL; - -static transaction_t *g_transactions = NULL; - -static user_timer_t g_trans_timer = NULL; - -static transaction_t * -transaction_find(int mid) -{ - transaction_t *t = g_transactions; - - while (t) { - if (t->mid == mid) - return t; - t = t->next; - } - - return NULL; -} - -/* - * new transaction is added to the tail of the list, so the list - * is sorted by expiry time naturally. - */ -static void -transaction_add(transaction_t *trans) -{ - transaction_t *t; - - if (g_transactions == NULL) { - g_transactions = trans; - return; - } - - t = g_transactions; - while (t) { - if (t->next == NULL) { - t->next = trans; - return; - } - } -} - -static void -transaction_remove(transaction_t *trans) -{ - transaction_t *prev = NULL, *current = g_transactions; - - while (current) { - if (current == trans) { - if (prev == NULL) { - g_transactions = current->next; - free(current); - return; - } - prev->next = current->next; - free(current); - return; - } - prev = current; - current = current->next; - } -} - -static bool -is_event_type(request_t *req) -{ - return req->action == COAP_EVENT; -} - -static bool -register_url_handler(const char *url, request_handler_f request_handler, - reg_type_t reg_type) -{ - res_register_t *r = g_resources; - - while (r) { - if (reg_type == r->reg_type && strcmp(r->url, url) == 0) { - r->request_handler = request_handler; - return true; - } - r = r->next; - } - - r = (res_register_t *)malloc(sizeof(res_register_t)); - if (r == NULL) - return false; - - memset(r, 0, sizeof(*r)); - - r->url = strdup(url); - if (!r->url) { - free(r); - return false; - } - - r->request_handler = request_handler; - r->reg_type = reg_type; - r->next = g_resources; - g_resources = r; - - // tell app mgr to route this url to me - if (reg_type == Reg_Request) - wasm_register_resource(url); - else - wasm_sub_event(url); - - return true; -} - -bool -api_register_resource_handler(const char *url, - request_handler_f request_handler) -{ - return register_url_handler(url, request_handler, Reg_Request); -} - -static void -transaction_timeout_handler(user_timer_t timer) -{ - transaction_t *cur, *expired = NULL; - unsigned int elpased_ms, now = wasm_get_sys_tick_ms(); - - /* - * Since he transaction list is sorted by expiry time naturally, - * we can easily get all expired transactions. - * */ - cur = g_transactions; - while (cur) { - if (now < cur->time) - elpased_ms = now + (0xFFFFFFFF - cur->time) + 1; - else - elpased_ms = now - cur->time; - - if (elpased_ms >= TRANSACTION_TIMEOUT_MS) { - g_transactions = cur->next; - cur->next = expired; - expired = cur; - cur = g_transactions; - } - else { - break; - } - } - - /* call each transaction's handler with response set to NULL */ - cur = expired; - while (cur) { - transaction_t *tmp = cur; - cur->handler(NULL, cur->user_data); - cur = cur->next; - free(tmp); - } - - /* - * If the transaction list is not empty, restart the timer according - * to the first transaction. Otherwise, stop the timer. - */ - if (g_transactions != NULL) { - unsigned int elpased_ms, ms_to_expiry, now = wasm_get_sys_tick_ms(); - if (now < g_transactions->time) { - elpased_ms = now + (0xFFFFFFFF - g_transactions->time) + 1; - } - else { - elpased_ms = now - g_transactions->time; - } - ms_to_expiry = TRANSACTION_TIMEOUT_MS - elpased_ms; - api_timer_restart(g_trans_timer, ms_to_expiry); - } - else { - api_timer_cancel(g_trans_timer); - g_trans_timer = NULL; - } -} - -void -api_send_request(request_t *request, response_handler_f response_handler, - void *user_data) -{ - int size; - char *buffer; - transaction_t *trans; - - if ((trans = (transaction_t *)malloc(sizeof(transaction_t))) == NULL) { - printf( - "send request: allocate memory for request transaction failed!\n"); - return; - } - - memset(trans, 0, sizeof(transaction_t)); - trans->handler = response_handler; - trans->mid = request->mid; - trans->time = wasm_get_sys_tick_ms(); - trans->user_data = user_data; - - if ((buffer = pack_request(request, &size)) == NULL) { - printf("send request: pack request failed!\n"); - free(trans); - return; - } - - transaction_add(trans); - - /* if the trans is the 1st one, start the timer */ - if (trans == g_transactions) { - /* assert(g_trans_timer == NULL); */ - if (g_trans_timer == NULL) { - g_trans_timer = api_timer_create(TRANSACTION_TIMEOUT_MS, false, - true, transaction_timeout_handler); - } - } - - wasm_post_request(buffer, size); - - free_req_resp_packet(buffer); -} - -/* - * - * APIs for the native layers to callback for request/response arrived to this - * app - * - */ - -void -on_response(char *buffer, int size) -{ - response_t response[1]; - transaction_t *trans; - - if (NULL == unpack_response(buffer, size, response)) { - printf("unpack response failed\n"); - return; - } - - if ((trans = transaction_find(response->mid)) == NULL) { - printf("cannot find the transaction\n"); - return; - } - - /* - * When the 1st transaction get response: - * 1. If the 2nd trans exist, restart the timer according to its expiry - * time; - * 2. Otherwise, stop the timer since there is no more transactions; - */ - if (trans == g_transactions) { - if (trans->next != NULL) { - unsigned int elpased_ms, ms_to_expiry, now = wasm_get_sys_tick_ms(); - if (now < trans->next->time) { - elpased_ms = now + (0xFFFFFFFF - trans->next->time) + 1; - } - else { - elpased_ms = now - trans->next->time; - } - ms_to_expiry = TRANSACTION_TIMEOUT_MS - elpased_ms; - api_timer_restart(g_trans_timer, ms_to_expiry); - } - else { - api_timer_cancel(g_trans_timer); - g_trans_timer = NULL; - } - } - - trans->handler(response, trans->user_data); - transaction_remove(trans); -} - -void -on_request(char *buffer, int size) -{ - request_t request[1]; - bool is_event; - res_register_t *r = g_resources; - - if (NULL == unpack_request(buffer, size, request)) { - printf("unpack request failed\n"); - return; - } - - is_event = is_event_type(request); - - while (r) { - if ((is_event && r->reg_type == Reg_Event) - || (!is_event && r->reg_type == Reg_Request)) { - if (check_url_start(request->url, strlen(request->url), r->url) - > 0) { - r->request_handler(request); - return; - } - } - - r = r->next; - } - - printf("on_request: exit. no service handler\n"); -} - -void -api_response_send(response_t *response) -{ - int size; - char *buffer = pack_response(response, &size); - if (buffer == NULL) - return; - - wasm_response_send(buffer, size); - free_req_resp_packet(buffer); -} - -/// event api - -bool -api_publish_event(const char *url, int fmt, void *payload, int payload_len) -{ - int size; - request_t request[1]; - init_request(request, (char *)url, COAP_EVENT, fmt, payload, payload_len); - char *buffer = pack_request(request, &size); - if (buffer == NULL) - return false; - wasm_post_request(buffer, size); - - free_req_resp_packet(buffer); - - return true; -} - -bool -api_subscribe_event(const char *url, request_handler_f handler) -{ - return register_url_handler(url, handler, Reg_Event); -} diff --git a/core/app-framework/base/app/timer.c b/core/app-framework/base/app/timer.c deleted file mode 100644 index 692626ca3..000000000 --- a/core/app-framework/base/app/timer.c +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include -#include - -#include "wa-inc/timer_wasm_app.h" -#include "timer_api.h" - -#if 1 -#include -#else -#define printf (...) -#endif - -struct user_timer { - struct user_timer *next; - int timer_id; - void (*user_timer_callback)(user_timer_t); -}; - -struct user_timer *g_timers = NULL; - -user_timer_t -api_timer_create(int interval, bool is_period, bool auto_start, - on_user_timer_update_f on_timer_update) -{ - - int timer_id = wasm_create_timer(interval, is_period, auto_start); - - // TODO - struct user_timer *timer = - (struct user_timer *)malloc(sizeof(struct user_timer)); - if (timer == NULL) { - // TODO: remove the timer_id - printf("### api_timer_create malloc faild!!! \n"); - return NULL; - } - - memset(timer, 0, sizeof(*timer)); - timer->timer_id = timer_id; - timer->user_timer_callback = on_timer_update; - - if (g_timers == NULL) - g_timers = timer; - else { - timer->next = g_timers; - g_timers = timer; - } - - return timer; -} - -void -api_timer_cancel(user_timer_t timer) -{ - user_timer_t t = g_timers, prev = NULL; - - wasm_timer_cancel(timer->timer_id); - - while (t) { - if (t == timer) { - if (prev == NULL) { - g_timers = t->next; - free(t); - } - else { - prev->next = t->next; - free(t); - } - return; - } - else { - prev = t; - t = t->next; - } - } -} - -void -api_timer_restart(user_timer_t timer, int interval) -{ - wasm_timer_restart(timer->timer_id, interval); -} - -void -on_timer_callback(int timer_id) -{ - struct user_timer *t = g_timers; - - while (t) { - if (t->timer_id == timer_id) { - t->user_timer_callback(t); - break; - } - t = t->next; - } -} diff --git a/core/app-framework/base/app/timer_api.h b/core/app-framework/base/app/timer_api.h deleted file mode 100644 index 1fc7555ef..000000000 --- a/core/app-framework/base/app/timer_api.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _TIMER_API_H_ -#define _TIMER_API_H_ - -#include "bh_platform.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef unsigned int timer_id_t; - -timer_id_t -wasm_create_timer(int interval, bool is_period, bool auto_start); - -void -wasm_timer_destroy(timer_id_t timer_id); - -void -wasm_timer_cancel(timer_id_t timer_id); - -void -wasm_timer_restart(timer_id_t timer_id, int interval); - -uint32 -wasm_get_sys_tick_ms(void); - -#ifdef __cplusplus -} -#endif - -#endif /* end of _TIMER_API_H_ */ diff --git a/core/app-framework/base/app/wa-inc/request.h b/core/app-framework/base/app/wa-inc/request.h deleted file mode 100644 index 25830f0a4..000000000 --- a/core/app-framework/base/app/wa-inc/request.h +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _AEE_REQUEST_H_ -#define _AEE_REQUEST_H_ - -#include "bi-inc/shared_utils.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* CoAP request method codes */ -typedef enum { - COAP_GET = 1, - COAP_POST, - COAP_PUT, - COAP_DELETE, - COAP_EVENT = (COAP_DELETE + 2) -} coap_method_t; - -/* CoAP response codes */ -typedef enum { - NO_ERROR = 0, - - CREATED_2_01 = 65, /* CREATED */ - DELETED_2_02 = 66, /* DELETED */ - VALID_2_03 = 67, /* NOT_MODIFIED */ - CHANGED_2_04 = 68, /* CHANGED */ - CONTENT_2_05 = 69, /* OK */ - CONTINUE_2_31 = 95, /* CONTINUE */ - - BAD_REQUEST_4_00 = 128, /* BAD_REQUEST */ - UNAUTHORIZED_4_01 = 129, /* UNAUTHORIZED */ - BAD_OPTION_4_02 = 130, /* BAD_OPTION */ - FORBIDDEN_4_03 = 131, /* FORBIDDEN */ - NOT_FOUND_4_04 = 132, /* NOT_FOUND */ - METHOD_NOT_ALLOWED_4_05 = 133, /* METHOD_NOT_ALLOWED */ - NOT_ACCEPTABLE_4_06 = 134, /* NOT_ACCEPTABLE */ - PRECONDITION_FAILED_4_12 = 140, /* BAD_REQUEST */ - REQUEST_ENTITY_TOO_LARGE_4_13 = 141, /* REQUEST_ENTITY_TOO_LARGE */ - UNSUPPORTED_MEDIA_TYPE_4_15 = 143, /* UNSUPPORTED_MEDIA_TYPE */ - - INTERNAL_SERVER_ERROR_5_00 = 160, /* INTERNAL_SERVER_ERROR */ - NOT_IMPLEMENTED_5_01 = 161, /* NOT_IMPLEMENTED */ - BAD_GATEWAY_5_02 = 162, /* BAD_GATEWAY */ - SERVICE_UNAVAILABLE_5_03 = 163, /* SERVICE_UNAVAILABLE */ - GATEWAY_TIMEOUT_5_04 = 164, /* GATEWAY_TIMEOUT */ - PROXYING_NOT_SUPPORTED_5_05 = 165, /* PROXYING_NOT_SUPPORTED */ - - /* Erbium errors */ - MEMORY_ALLOCATION_ERROR = 192, - PACKET_SERIALIZATION_ERROR, - - /* Erbium hooks */ - MANUAL_RESPONSE, - PING_RESPONSE -} coap_status_t; - -/** - * @typedef request_handler_f - * - * @brief Define the signature of callback function for API - * api_register_resource_handler() to handle request or for API - * api_subscribe_event() to handle event. - * - * @param request pointer of the request to be handled - * - * @see api_register_resource_handler - * @see api_subscribe_event - */ -typedef void (*request_handler_f)(request_t *request); - -/** - * @typedef response_handler_f - * - * @brief Define the signature of callback function for API - * api_send_request() to handle response of a request. - * - * @param response pointer of the response to be handled - * @param user_data user data associated with the request which is set when - * calling api_send_request(). - * - * @see api_send_request - */ -typedef void (*response_handler_f)(response_t *response, void *user_data); - -/* - ***************** - * Request APIs - ***************** - */ - -/** - * @brief Register resource. - * - * @param url url of the resource - * @param handler callback function to handle the request to the resource - * - * @return true if success, false otherwise - */ -bool -api_register_resource_handler(const char *url, request_handler_f handler); - -/** - * @brief Send request asynchronously. - * - * @param request pointer of the request to be sent - * @param response_handler callback function to handle the response - * @param user_data user data - */ -void -api_send_request(request_t *request, response_handler_f response_handler, - void *user_data); - -/** - * @brief Send response. - * - * @param response pointer of the response to be sent - * - * @par - * @code - * void res1_handler(request_t *request) - * { - * response_t response[1]; - * make_response_for_request(request, response); - * set_response(response, DELETED_2_02, 0, NULL, 0); - * api_response_send(response); - * } - * @endcode - */ -void -api_response_send(response_t *response); - -/* - ***************** - * Event APIs - ***************** - */ - -/** - * @brief Publish an event. - * - * @param url url of the event - * @param fmt format of the event payload - * @param payload payload of the event - * @param payload_len length in bytes of the event payload - * - * @return true if success, false otherwise - */ -bool -api_publish_event(const char *url, int fmt, void *payload, int payload_len); - -/** - * @brief Subscribe an event. - * - * @param url url of the event - * @param handler callback function to handle the event. - * - * @return true if success, false otherwise - */ -bool -api_subscribe_event(const char *url, request_handler_f handler); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/core/app-framework/base/app/wa-inc/timer_wasm_app.h b/core/app-framework/base/app/wa-inc/timer_wasm_app.h deleted file mode 100644 index cf158a365..000000000 --- a/core/app-framework/base/app/wa-inc/timer_wasm_app.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _AEE_TIMER_H_ -#define _AEE_TIMER_H_ - -#include "bh_platform.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* board producer define user_timer */ -struct user_timer; -typedef struct user_timer *user_timer_t; - -/** - * @typedef on_user_timer_update_f - * - * @brief Define the signature of callback function for API api_timer_create(). - * - * @param timer the timer - * - * @see api_timer_create - */ -typedef void (*on_user_timer_update_f)(user_timer_t timer); - -/* - ***************** - * Timer APIs - ***************** - */ - -/** - * @brief Create timer. - * - * @param interval timer interval - * @param is_period whether the timer is periodic - * @param auto_start whether start the timer immediately after created - * @param on_timer_update callback function called when timer expired - * - * @return the timer created if success, NULL otherwise - */ -user_timer_t -api_timer_create(int interval, bool is_period, bool auto_start, - on_user_timer_update_f on_timer_update); - -/** - * @brief Cancel timer. - * - * @param timer the timer to cancel - */ -void -api_timer_cancel(user_timer_t timer); - -/** - * @brief Restart timer. - * - * @param timer the timer to cancel - * @param interval the timer interval - */ -void -api_timer_restart(user_timer_t timer, int interval); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/core/app-framework/base/app/wasm_app.cmake b/core/app-framework/base/app/wasm_app.cmake deleted file mode 100644 index 2313df99d..000000000 --- a/core/app-framework/base/app/wasm_app.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -set (WASM_APP_BASE_DIR ${CMAKE_CURRENT_LIST_DIR}) - -include_directories(${WASM_APP_BASE_DIR}) - -add_definitions (-DWASM_ENABLE_BASE_LIB) - -file (GLOB_RECURSE source_all ${WASM_APP_BASE_DIR}/*.c) - -set (WASM_APP_CURRENT_SOURCE ${source_all}) -set (WASM_APP_BASE_DIR ${WASM_APP_BASE_DIR} PARENT_SCOPE) diff --git a/core/app-framework/base/app/wasm_app.h b/core/app-framework/base/app/wasm_app.h deleted file mode 100644 index e7be8a4c1..000000000 --- a/core/app-framework/base/app/wasm_app.h +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _LIB_AEE_H_ -#define _LIB_AEE_H_ - -#include "bi-inc/shared_utils.h" -#include "bi-inc/attr_container.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* end of _LIB_AEE_H_ */ diff --git a/core/app-framework/base/native/base_lib.inl b/core/app-framework/base/native/base_lib.inl deleted file mode 100644 index 3c228cc93..000000000 --- a/core/app-framework/base/native/base_lib.inl +++ /dev/null @@ -1,14 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - - EXPORT_WASM_API_WITH_SIG(wasm_register_resource, "($)"), - EXPORT_WASM_API_WITH_SIG(wasm_response_send, "(*~)i"), - EXPORT_WASM_API_WITH_SIG(wasm_post_request, "(*~)"), - EXPORT_WASM_API_WITH_SIG(wasm_sub_event, "($)"), - EXPORT_WASM_API_WITH_SIG(wasm_create_timer, "(iii)i"), - EXPORT_WASM_API_WITH_SIG(wasm_timer_destroy, "(i)"), - EXPORT_WASM_API_WITH_SIG(wasm_timer_cancel, "(i)"), - EXPORT_WASM_API_WITH_SIG(wasm_timer_restart, "(ii)"), - EXPORT_WASM_API_WITH_SIG(wasm_get_sys_tick_ms, "()i"), diff --git a/core/app-framework/base/native/base_lib_export.c b/core/app-framework/base/native/base_lib_export.c deleted file mode 100644 index 19ac7185c..000000000 --- a/core/app-framework/base/native/base_lib_export.c +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include -#include -#include -#include "lib_export.h" -#include "req_resp_native_api.h" -#include "timer_native_api.h" - -static NativeSymbol extended_native_symbol_defs[] = { -/* TODO: use macro EXPORT_WASM_API() or EXPORT_WASM_API2() to - add functions to register. */ -#include "base_lib.inl" -}; - -uint32 -get_base_lib_export_apis(NativeSymbol **p_base_lib_apis) -{ - *p_base_lib_apis = extended_native_symbol_defs; - return sizeof(extended_native_symbol_defs) / sizeof(NativeSymbol); -} diff --git a/core/app-framework/base/native/req_resp_native_api.h b/core/app-framework/base/native/req_resp_native_api.h deleted file mode 100644 index 3e5938772..000000000 --- a/core/app-framework/base/native/req_resp_native_api.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _REQ_RESP_API_H_ -#define _REQ_RESP_API_H_ - -#include "bh_platform.h" -#include "wasm_export.h" - -#ifdef __cplusplus -extern "C" { -#endif - -bool -wasm_response_send(wasm_exec_env_t exec_env, char *buffer, int size); -void -wasm_register_resource(wasm_exec_env_t exec_env, char *url); -void -wasm_post_request(wasm_exec_env_t exec_env, char *buffer, int size); -void -wasm_sub_event(wasm_exec_env_t exec_env, char *url); - -#ifdef __cplusplus -} -#endif - -#endif /* end of _REQ_RESP_API_H_ */ diff --git a/core/app-framework/base/native/request_response.c b/core/app-framework/base/native/request_response.c deleted file mode 100644 index 674ba5e9d..000000000 --- a/core/app-framework/base/native/request_response.c +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "app_manager_export.h" -#include "coap_ext.h" -#include "wasm_export.h" -#include "bh_assert.h" - -extern void -module_request_handler(request_t *request, void *user_data); - -bool -wasm_response_send(wasm_exec_env_t exec_env, char *buffer, int size) -{ - if (buffer != NULL) { - response_t response[1]; - - if (NULL == unpack_response(buffer, size, response)) - return false; - - am_send_response(response); - - return true; - } - - return false; -} - -void -wasm_register_resource(wasm_exec_env_t exec_env, char *url) -{ - wasm_module_inst_t module_inst = get_module_inst(exec_env); - - if (url != NULL) { - unsigned int mod_id = - app_manager_get_module_id(Module_WASM_App, module_inst); - bh_assert(mod_id != ID_NONE); - am_register_resource(url, module_request_handler, mod_id); - } -} - -void -wasm_post_request(wasm_exec_env_t exec_env, char *buffer, int size) -{ - wasm_module_inst_t module_inst = get_module_inst(exec_env); - - if (buffer != NULL) { - request_t req[1]; - - if (!unpack_request(buffer, size, req)) - return; - - // TODO: add permission check, ensure app can't do harm - - // set sender to help dispatch the response to the sender ap - unsigned int mod_id = - app_manager_get_module_id(Module_WASM_App, module_inst); - bh_assert(mod_id != ID_NONE); - req->sender = mod_id; - - if (req->action == COAP_EVENT) { - am_publish_event(req); - return; - } - - am_dispatch_request(req); - } -} - -void -wasm_sub_event(wasm_exec_env_t exec_env, char *url) -{ - wasm_module_inst_t module_inst = get_module_inst(exec_env); - - if (url != NULL) { - unsigned int mod_id = - app_manager_get_module_id(Module_WASM_App, module_inst); - - bh_assert(mod_id != ID_NONE); - am_register_event(url, mod_id); - } -} diff --git a/core/app-framework/base/native/runtime_lib.h b/core/app-framework/base/native/runtime_lib.h deleted file mode 100644 index 477b663b2..000000000 --- a/core/app-framework/base/native/runtime_lib.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef LIB_BASE_RUNTIME_LIB_H_ -#define LIB_BASE_RUNTIME_LIB_H_ - -#include "runtime_timer.h" - -bool -init_wasm_timer(); -void -exit_wasm_timer(); -timer_ctx_t -get_wasm_timer_ctx(); -timer_ctx_t -create_wasm_timer_ctx(unsigned int module_id, int prealloc_num); -void -destroy_module_timer_ctx(unsigned int module_id); - -#endif /* LIB_BASE_RUNTIME_LIB_H_ */ diff --git a/core/app-framework/base/native/timer_native_api.h b/core/app-framework/base/native/timer_native_api.h deleted file mode 100644 index 138e7c60d..000000000 --- a/core/app-framework/base/native/timer_native_api.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _TIMER_API_H_ -#define _TIMER_API_H_ - -#include "bh_platform.h" -#include "wasm_export.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef unsigned int timer_id_t; - -/* - * timer interfaces - */ - -typedef unsigned int timer_id_t; - -timer_id_t -wasm_create_timer(wasm_exec_env_t exec_env, int interval, bool is_period, - bool auto_start); -void -wasm_timer_destroy(wasm_exec_env_t exec_env, timer_id_t timer_id); -void -wasm_timer_cancel(wasm_exec_env_t exec_env, timer_id_t timer_id); -void -wasm_timer_restart(wasm_exec_env_t exec_env, timer_id_t timer_id, int interval); -uint32 -wasm_get_sys_tick_ms(wasm_exec_env_t exec_env); - -#ifdef __cplusplus -} -#endif - -#endif /* end of _TIMER_API_H_ */ diff --git a/core/app-framework/base/native/timer_wrapper.c b/core/app-framework/base/native/timer_wrapper.c deleted file mode 100644 index 246868849..000000000 --- a/core/app-framework/base/native/timer_wrapper.c +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "bh_platform.h" -#include "app_manager_export.h" -#include "../app-manager/module_wasm_app.h" -#include "timer_native_api.h" - -typedef struct { - bh_list_link l; - timer_ctx_t timer_ctx; -} timer_ctx_node_t; - -static bool timer_thread_run = true; - -static bh_list g_timer_ctx_list; -static korp_cond g_timer_ctx_list_cond; -static korp_mutex g_timer_ctx_list_mutex; - -void -wasm_timer_callback(timer_id_t id, unsigned int mod_id) -{ - module_data *module = module_data_list_lookup_id(mod_id); - if (module == NULL) - return; - - // !!! the length parameter must be 0, so the receiver will - // not free the payload pointer. - bh_post_msg(module->queue, TIMER_EVENT_WASM, (char *)(uintptr_t)id, 0); -} - -/** - * why we create a separate link for module timer contexts - * rather than traverse the module list? - * It helps to reduce the lock frequency for the module list. - * Also when we lock the module list and then call the callback for - * timer expire, the callback is request the list lock again for lookup - * the module from module id. It is for avoiding that situation. - */ - -void * -thread_modulers_timer_check(void *arg) -{ - uint32 ms_to_expiry; - uint64 us_to_wait; - - while (timer_thread_run) { - ms_to_expiry = (uint32)-1; - os_mutex_lock(&g_timer_ctx_list_mutex); - timer_ctx_node_t *elem = - (timer_ctx_node_t *)bh_list_first_elem(&g_timer_ctx_list); - while (elem) { - uint32 next = check_app_timers(elem->timer_ctx); - if (next != (uint32)-1) { - if (ms_to_expiry == (uint32)-1 || ms_to_expiry > next) - ms_to_expiry = next; - } - - elem = (timer_ctx_node_t *)bh_list_elem_next(elem); - } - os_mutex_unlock(&g_timer_ctx_list_mutex); - - if (ms_to_expiry == (uint32)-1) - us_to_wait = BHT_WAIT_FOREVER; - else - us_to_wait = (uint64)ms_to_expiry * 1000; - os_mutex_lock(&g_timer_ctx_list_mutex); - os_cond_reltimedwait(&g_timer_ctx_list_cond, &g_timer_ctx_list_mutex, - us_to_wait); - os_mutex_unlock(&g_timer_ctx_list_mutex); - } - - return NULL; -} - -void -wakeup_modules_timer_thread(timer_ctx_t ctx) -{ - os_mutex_lock(&g_timer_ctx_list_mutex); - os_cond_signal(&g_timer_ctx_list_cond); - os_mutex_unlock(&g_timer_ctx_list_mutex); -} - -bool -init_wasm_timer() -{ - korp_tid tm_tid; - bh_list_init(&g_timer_ctx_list); - - if (os_cond_init(&g_timer_ctx_list_cond) != 0) { - return false; - } - /* temp solution for: thread_modulers_timer_check thread - would recursive lock the mutex */ - if (os_recursive_mutex_init(&g_timer_ctx_list_mutex) != 0) { - goto fail1; - } - - if (0 - != os_thread_create(&tm_tid, thread_modulers_timer_check, NULL, - BH_APPLET_PRESERVED_STACK_SIZE)) { - goto fail2; - } - - return true; - -fail2: - os_mutex_destroy(&g_timer_ctx_list_mutex); - -fail1: - os_cond_destroy(&g_timer_ctx_list_cond); - - return false; -} - -void -exit_wasm_timer() -{ - timer_thread_run = false; -} - -timer_ctx_t -create_wasm_timer_ctx(unsigned int module_id, int prealloc_num) -{ - timer_ctx_t ctx = - create_timer_ctx(wasm_timer_callback, wakeup_modules_timer_thread, - prealloc_num, module_id); - - if (ctx == NULL) - return NULL; - - timer_ctx_node_t *node = - (timer_ctx_node_t *)wasm_runtime_malloc(sizeof(timer_ctx_node_t)); - if (node == NULL) { - destroy_timer_ctx(ctx); - return NULL; - } - memset(node, 0, sizeof(*node)); - node->timer_ctx = ctx; - - os_mutex_lock(&g_timer_ctx_list_mutex); - bh_list_insert(&g_timer_ctx_list, node); - os_mutex_unlock(&g_timer_ctx_list_mutex); - - return ctx; -} - -void -destroy_module_timer_ctx(unsigned int module_id) -{ - timer_ctx_node_t *elem; - - os_mutex_lock(&g_timer_ctx_list_mutex); - elem = (timer_ctx_node_t *)bh_list_first_elem(&g_timer_ctx_list); - while (elem) { - if (timer_ctx_get_owner(elem->timer_ctx) == module_id) { - bh_list_remove(&g_timer_ctx_list, elem); - destroy_timer_ctx(elem->timer_ctx); - wasm_runtime_free(elem); - break; - } - - elem = (timer_ctx_node_t *)bh_list_elem_next(elem); - } - os_mutex_unlock(&g_timer_ctx_list_mutex); -} - -timer_ctx_t -get_wasm_timer_ctx(wasm_module_inst_t module_inst) -{ - module_data *m = app_manager_get_module_data(Module_WASM_App, module_inst); - if (m == NULL) - return NULL; - return m->timer_ctx; -} - -timer_id_t -wasm_create_timer(wasm_exec_env_t exec_env, int interval, bool is_period, - bool auto_start) -{ - wasm_module_inst_t module_inst = get_module_inst(exec_env); - timer_ctx_t timer_ctx = get_wasm_timer_ctx(module_inst); - bh_assert(timer_ctx); - return sys_create_timer(timer_ctx, interval, is_period, auto_start); -} - -void -wasm_timer_destroy(wasm_exec_env_t exec_env, timer_id_t timer_id) -{ - wasm_module_inst_t module_inst = get_module_inst(exec_env); - timer_ctx_t timer_ctx = get_wasm_timer_ctx(module_inst); - bh_assert(timer_ctx); - sys_timer_destroy(timer_ctx, timer_id); -} - -void -wasm_timer_cancel(wasm_exec_env_t exec_env, timer_id_t timer_id) -{ - wasm_module_inst_t module_inst = get_module_inst(exec_env); - timer_ctx_t timer_ctx = get_wasm_timer_ctx(module_inst); - bh_assert(timer_ctx); - sys_timer_cancel(timer_ctx, timer_id); -} - -void -wasm_timer_restart(wasm_exec_env_t exec_env, timer_id_t timer_id, int interval) -{ - wasm_module_inst_t module_inst = get_module_inst(exec_env); - timer_ctx_t timer_ctx = get_wasm_timer_ctx(module_inst); - bh_assert(timer_ctx); - sys_timer_restart(timer_ctx, timer_id, interval); -} - -uint32 -wasm_get_sys_tick_ms(wasm_exec_env_t exec_env) -{ - return (uint32)bh_get_tick_ms(); -} diff --git a/core/app-framework/base/native/wasm_lib.cmake b/core/app-framework/base/native/wasm_lib.cmake deleted file mode 100644 index 223320b32..000000000 --- a/core/app-framework/base/native/wasm_lib.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -set (WASM_LIB_BASE_DIR ${CMAKE_CURRENT_LIST_DIR}) - -add_definitions (-DWASM_ENABLE_BASE_LIB) - -include_directories(${WASM_LIB_BASE_DIR}) - -file (GLOB_RECURSE source_all ${WASM_LIB_BASE_DIR}/*.c) - -set (WASM_APP_LIB_CURRENT_SOURCE ${source_all}) - diff --git a/core/app-framework/connection/app/connection.c b/core/app-framework/connection/app/connection.c deleted file mode 100644 index b5b2bfc54..000000000 --- a/core/app-framework/connection/app/connection.c +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "wa-inc/connection.h" -#include "connection_api.h" - -/* Raw connection structure */ -typedef struct _connection { - /* Next connection */ - struct _connection *next; - - /* Handle of the connection */ - uint32 handle; - - /* Callback function called when event on this connection occurs */ - on_connection_event_f on_event; - - /* User data */ - void *user_data; -} connection_t; - -/* Raw connections list */ -static connection_t *g_conns = NULL; - -connection_t * -api_open_connection(const char *name, attr_container_t *args, - on_connection_event_f on_event, void *user_data) -{ - connection_t *conn; - char *args_buffer = (char *)args; - uint32 handle, args_len = attr_container_get_serialize_length(args); - - handle = wasm_open_connection(name, args_buffer, args_len); - if (handle == -1) - return NULL; - - conn = (connection_t *)malloc(sizeof(*conn)); - if (conn == NULL) { - wasm_close_connection(handle); - return NULL; - } - - memset(conn, 0, sizeof(*conn)); - conn->handle = handle; - conn->on_event = on_event; - conn->user_data = user_data; - - if (g_conns != NULL) { - conn->next = g_conns; - g_conns = conn; - } - else { - g_conns = conn; - } - - return conn; -} - -void -api_close_connection(connection_t *c) -{ - connection_t *conn = g_conns, *prev = NULL; - - while (conn) { - if (conn == c) { - wasm_close_connection(c->handle); - if (prev != NULL) - prev->next = conn->next; - else - g_conns = conn->next; - free(conn); - return; - } - else { - prev = conn; - conn = conn->next; - } - } -} - -int -api_send_on_connection(connection_t *conn, const char *data, uint32 len) -{ - return wasm_send_on_connection(conn->handle, data, len); -} - -bool -api_config_connection(connection_t *conn, attr_container_t *cfg) -{ - char *cfg_buffer = (char *)cfg; - uint32 cfg_len = attr_container_get_serialize_length(cfg); - - return wasm_config_connection(conn->handle, cfg_buffer, cfg_len); -} - -void -on_connection_data(uint32 handle, char *buffer, uint32 len) -{ - connection_t *conn = g_conns; - - while (conn != NULL) { - if (conn->handle == handle) { - if (len == 0) { - conn->on_event(conn, CONN_EVENT_TYPE_DISCONNECT, NULL, 0, - conn->user_data); - } - else { - conn->on_event(conn, CONN_EVENT_TYPE_DATA, buffer, len, - conn->user_data); - } - - return; - } - conn = conn->next; - } -} diff --git a/core/app-framework/connection/app/connection_api.h b/core/app-framework/connection/app/connection_api.h deleted file mode 100644 index 22bd5a182..000000000 --- a/core/app-framework/connection/app/connection_api.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef CONNECTION_API_H_ -#define CONNECTION_API_H_ - -#include "bh_platform.h" - -#ifdef __cplusplus -extern "C" { -#endif - -uint32 -wasm_open_connection(const char *name, char *args_buf, uint32 args_buf_len); - -void -wasm_close_connection(uint32 handle); - -int -wasm_send_on_connection(uint32 handle, const char *data, uint32 data_len); - -bool -wasm_config_connection(uint32 handle, const char *cfg_buf, uint32 cfg_buf_len); - -#ifdef __cplusplus -} -#endif - -#endif /* end of CONNECTION_API_H_ */ diff --git a/core/app-framework/connection/app/wa-inc/connection.h b/core/app-framework/connection/app/wa-inc/connection.h deleted file mode 100644 index 823eaec74..000000000 --- a/core/app-framework/connection/app/wa-inc/connection.h +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _CONNECTION_H_ -#define _CONNECTION_H_ - -#include "bi-inc/attr_container.h" - -#ifdef __cplusplus -extern "C" { -#endif - -struct _connection; -typedef struct _connection connection_t; - -/* Connection event type */ -typedef enum { - /* Data is received */ - CONN_EVENT_TYPE_DATA = 1, - /* Connection is disconnected */ - CONN_EVENT_TYPE_DISCONNECT -} conn_event_type_t; - -/* - * @typedef on_connection_event_f - * - * @param conn the connection that the event belongs to - * @param type event type - * @param data the data received for CONN_EVENT_TYPE_DATA event - * @param len length of the data in byte - * @param user_data user data - */ -typedef void (*on_connection_event_f)(connection_t *conn, - conn_event_type_t type, const char *data, - uint32 len, void *user_data); - -/* - ***************** - * Connection API's - ***************** - */ - -/* - * @brief Open a connection. - * - * @param name name of the connection, "TCP", "UDP" or "UART" - * @param args connection arguments, such as: ip:127.0.0.1, port:8888 - * @param on_event callback function called when event occurs - * @param user_data user data - * - * @return the connection or NULL means fail - */ -connection_t * -api_open_connection(const char *name, attr_container_t *args, - on_connection_event_f on_event, void *user_data); - -/* - * @brief Close a connection. - * - * @param conn connection - */ -void -api_close_connection(connection_t *conn); - -/* - * Send data to the connection in non-blocking manner which returns immediately - * - * @param conn the connection - * @param data data buffer to be sent - * @param len length of the data in byte - * - * @return actual length sent, or -1 if fail(maybe underlying buffer is full) - */ -int -api_send_on_connection(connection_t *conn, const char *data, uint32 len); - -/* - * @brief Configure connection. - * - * @param conn the connection - * @param cfg configurations - * - * @return true if success, false otherwise - */ -bool -api_config_connection(connection_t *conn, attr_container_t *cfg); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/core/app-framework/connection/app/wasm_app.cmake b/core/app-framework/connection/app/wasm_app.cmake deleted file mode 100644 index ca4e02599..000000000 --- a/core/app-framework/connection/app/wasm_app.cmake +++ /dev/null @@ -1,11 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -set (WASM_APP_CONN_DIR ${CMAKE_CURRENT_LIST_DIR}) - -include_directories(${WASM_APP_CONN_DIR}) - - -file (GLOB source_all ${WASM_APP_CONN_DIR}/*.c) - -set (WASM_APP_CURRENT_SOURCE ${source_all}) diff --git a/core/app-framework/connection/native/connection.inl b/core/app-framework/connection/native/connection.inl deleted file mode 100644 index b2d01aa9f..000000000 --- a/core/app-framework/connection/native/connection.inl +++ /dev/null @@ -1,9 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -EXPORT_WASM_API_WITH_SIG(wasm_open_connection, "($*~)i"), -EXPORT_WASM_API_WITH_SIG(wasm_close_connection, "(i)"), -EXPORT_WASM_API_WITH_SIG(wasm_send_on_connection, "(i*~)i"), -EXPORT_WASM_API_WITH_SIG(wasm_config_connection, "(i*~)i"), diff --git a/core/app-framework/connection/native/connection_lib.h b/core/app-framework/connection/native/connection_lib.h deleted file mode 100644 index 3e182cbb8..000000000 --- a/core/app-framework/connection/native/connection_lib.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef CONNECTION_LIB_H_ -#define CONNECTION_LIB_H_ - -#include "bi-inc/attr_container.h" -#include "wasm_export.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * This file defines connection library which should be implemented by - * different platforms - */ - -/* - * @brief Open a connection. - * - * @param name name of the connection, "TCP", "UDP" or "UART" - * @param args connection arguments, such as: ip:127.0.0.1, port:8888 - * - * @return 0~0xFFFFFFFE means id of the connection, otherwise(-1) means fail - */ -typedef uint32 (*connection_open_f)(wasm_module_inst_t module_inst, - const char *name, attr_container_t *args); - -/* - * @brief Close a connection. - * - * @param handle of the connection - */ -typedef void (*connection_close_f)(uint32 handle); - -/* - * @brief Send data to the connection in non-blocking manner. - * - * @param handle of the connection - * @param data data buffer to be sent - * @param len length of the data in byte - * - * @return actual length sent, -1 if fail - */ -typedef int (*connection_send_f)(uint32 handle, const char *data, int len); - -/* - * @brief Configure connection. - * - * @param handle of the connection - * @param cfg configurations - * - * @return true if success, false otherwise - */ -typedef bool (*connection_config_f)(uint32 handle, attr_container_t *cfg); - -/* Raw connection interface for platform to implement */ -typedef struct _connection_interface { - connection_open_f _open; - connection_close_f _close; - connection_send_f _send; - connection_config_f _config; -} connection_interface_t; - -/* Platform must define this interface */ -extern connection_interface_t connection_impl; - -#ifdef __cplusplus -} -#endif - -#endif /* CONNECTION_LIB_H_ */ diff --git a/core/app-framework/connection/native/connection_native_api.h b/core/app-framework/connection/native/connection_native_api.h deleted file mode 100644 index 42a2508f1..000000000 --- a/core/app-framework/connection/native/connection_native_api.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef CONNECTION_API_H_ -#define CONNECTION_API_H_ - -#include "bh_platform.h" -#include "wasm_export.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * connection interfaces - */ - -uint32 -wasm_open_connection(wasm_exec_env_t exec_env, char *name, char *args_buf, - uint32 len); -void -wasm_close_connection(wasm_exec_env_t exec_env, uint32 handle); -int -wasm_send_on_connection(wasm_exec_env_t exec_env, uint32 handle, char *data, - uint32 len); -bool -wasm_config_connection(wasm_exec_env_t exec_env, uint32 handle, char *cfg_buf, - uint32 len); - -#ifdef __cplusplus -} -#endif - -#endif /* end of CONNECTION_API_H_ */ diff --git a/core/app-framework/connection/native/connection_wrapper.c b/core/app-framework/connection/native/connection_wrapper.c deleted file mode 100644 index 7c20b51d0..000000000 --- a/core/app-framework/connection/native/connection_wrapper.c +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "connection_lib.h" -#include "wasm_export.h" -#include "native_interface.h" -#include "connection_native_api.h" - -/* Note: - * - * This file is the consumer of connection lib which is implemented by different - * platforms - */ - -uint32 -wasm_open_connection(wasm_exec_env_t exec_env, char *name, char *args_buf, - uint32 len) -{ - wasm_module_inst_t module_inst = get_module_inst(exec_env); - attr_container_t *args; - - args = (attr_container_t *)args_buf; - - if (connection_impl._open != NULL) - return connection_impl._open(module_inst, name, args); - - return -1; -} - -void -wasm_close_connection(wasm_exec_env_t exec_env, uint32 handle) -{ - if (connection_impl._close != NULL) - connection_impl._close(handle); -} - -int -wasm_send_on_connection(wasm_exec_env_t exec_env, uint32 handle, char *data, - uint32 len) -{ - if (connection_impl._send != NULL) - return connection_impl._send(handle, data, len); - - return -1; -} - -bool -wasm_config_connection(wasm_exec_env_t exec_env, uint32 handle, char *cfg_buf, - uint32 len) -{ - attr_container_t *cfg; - - cfg = (attr_container_t *)cfg_buf; - - if (connection_impl._config != NULL) - return connection_impl._config(handle, cfg); - - return false; -} diff --git a/core/app-framework/connection/native/linux/conn_tcp.c b/core/app-framework/connection/native/linux/conn_tcp.c deleted file mode 100644 index 054eb59fd..000000000 --- a/core/app-framework/connection/native/linux/conn_tcp.c +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "conn_tcp.h" - -#include -#include -#include -#include -#include - -int -tcp_open(char *address, uint16 port) -{ - int sock, ret; - struct sockaddr_in servaddr; - - memset(&servaddr, 0, sizeof(servaddr)); - servaddr.sin_family = AF_INET; - servaddr.sin_addr.s_addr = inet_addr(address); - servaddr.sin_port = htons(port); - - sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if (sock == -1) - return -1; - - ret = connect(sock, (struct sockaddr *)&servaddr, sizeof(servaddr)); - if (ret == -1) { - close(sock); - return -1; - } - - /* Put the socket in non-blocking mode */ - if (fcntl(sock, F_SETFL, fcntl(sock, F_GETFL) | O_NONBLOCK) < 0) { - close(sock); - return -1; - } - - return sock; -} - -int -tcp_send(int sock, const char *data, int size) -{ - return send(sock, data, size, 0); -} - -int -tcp_recv(int sock, char *buffer, int buf_size) -{ - return recv(sock, buffer, buf_size, 0); -} diff --git a/core/app-framework/connection/native/linux/conn_tcp.h b/core/app-framework/connection/native/linux/conn_tcp.h deleted file mode 100644 index c4d5cc86a..000000000 --- a/core/app-framework/connection/native/linux/conn_tcp.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef CONN_LINUX_TCP_H_ -#define CONN_LINUX_TCP_H_ - -#include "bh_platform.h" - -#ifdef __cplusplus -extern "C" { -#endif - -int -tcp_open(char *address, uint16 port); - -int -tcp_send(int sock, const char *data, int size); - -int -tcp_recv(int sock, char *buffer, int buf_size); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/core/app-framework/connection/native/linux/conn_uart.c b/core/app-framework/connection/native/linux/conn_uart.c deleted file mode 100644 index 0bcdc93f7..000000000 --- a/core/app-framework/connection/native/linux/conn_uart.c +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "conn_uart.h" - -#include -#include -#include - -static int -parse_baudrate(int baud) -{ - switch (baud) { - case 9600: - return B9600; - case 19200: - return B19200; - case 38400: - return B38400; - case 57600: - return B57600; - case 115200: - return B115200; - case 230400: - return B230400; - case 460800: - return B460800; - case 500000: - return B500000; - case 576000: - return B576000; - case 921600: - return B921600; - case 1000000: - return B1000000; - case 1152000: - return B1152000; - case 1500000: - return B1500000; - case 2000000: - return B2000000; - case 2500000: - return B2500000; - case 3000000: - return B3000000; - case 3500000: - return B3500000; - case 4000000: - return B4000000; - default: - return -1; - } -} - -int -uart_open(char *device, int baudrate) -{ - int uart_fd; - struct termios uart_term; - - uart_fd = open(device, O_RDWR | O_NOCTTY); - - if (uart_fd < 0) - return -1; - - memset(&uart_term, 0, sizeof(uart_term)); - uart_term.c_cflag = parse_baudrate(baudrate) | CS8 | CLOCAL | CREAD; - uart_term.c_iflag = IGNPAR; - uart_term.c_oflag = 0; - - /* set noncanonical mode */ - uart_term.c_lflag = 0; - uart_term.c_cc[VTIME] = 30; - uart_term.c_cc[VMIN] = 1; - tcflush(uart_fd, TCIFLUSH); - - if (tcsetattr(uart_fd, TCSANOW, &uart_term) != 0) { - close(uart_fd); - return -1; - } - - /* Put the fd in non-blocking mode */ - if (fcntl(uart_fd, F_SETFL, fcntl(uart_fd, F_GETFL) | O_NONBLOCK) < 0) { - close(uart_fd); - return -1; - } - - return uart_fd; -} - -int -uart_send(int fd, const char *data, int size) -{ - return write(fd, data, size); -} - -int -uart_recv(int fd, char *buffer, int buf_size) -{ - return read(fd, buffer, buf_size); -} diff --git a/core/app-framework/connection/native/linux/conn_uart.h b/core/app-framework/connection/native/linux/conn_uart.h deleted file mode 100644 index 443167026..000000000 --- a/core/app-framework/connection/native/linux/conn_uart.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef CONN_LINUX_UART_H_ -#define CONN_LINUX_UART_H_ - -#include "bh_platform.h" - -#ifdef __cplusplus -extern "C" { -#endif - -int -uart_open(char *device, int baudrate); - -int -uart_send(int fd, const char *data, int size); - -int -uart_recv(int fd, char *buffer, int buf_size); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/core/app-framework/connection/native/linux/conn_udp.c b/core/app-framework/connection/native/linux/conn_udp.c deleted file mode 100644 index 61652b14d..000000000 --- a/core/app-framework/connection/native/linux/conn_udp.c +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "conn_udp.h" - -#include -#include -#include -#include -#include - -int -udp_open(uint16 port) -{ - int sock, ret; - struct sockaddr_in addr; - - sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock == -1) - return -1; - - memset(&addr, 0, sizeof(addr)); - addr.sin_family = AF_INET; - addr.sin_addr.s_addr = htonl(INADDR_ANY); - addr.sin_port = htons(port); - - ret = bind(sock, (struct sockaddr *)&addr, sizeof(addr)); - if (ret == -1) { - close(sock); - return -1; - } - - /* Put the socket in non-blocking mode */ - if (fcntl(sock, F_SETFL, fcntl(sock, F_GETFL) | O_NONBLOCK) < 0) { - close(sock); - return -1; - } - - return sock; -} - -int -udp_send(int sock, struct sockaddr *dest, const char *data, int size) -{ - return sendto(sock, data, size, MSG_CONFIRM, dest, sizeof(*dest)); -} - -int -udp_recv(int sock, char *buffer, int buf_size) -{ - struct sockaddr_in remaddr; - socklen_t addrlen = sizeof(remaddr); - - return recvfrom(sock, buffer, buf_size, 0, (struct sockaddr *)&remaddr, - &addrlen); -} diff --git a/core/app-framework/connection/native/linux/conn_udp.h b/core/app-framework/connection/native/linux/conn_udp.h deleted file mode 100644 index 377c26eb1..000000000 --- a/core/app-framework/connection/native/linux/conn_udp.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef CONN_LINUX_UDP_H_ -#define CONN_LINUX_UDP_H_ - -#include "bh_platform.h" - -#ifdef __cplusplus -extern "C" { -#endif - -int -udp_open(uint16 port); - -int -udp_send(int sock, struct sockaddr *dest, const char *data, int size); - -int -udp_recv(int sock, char *buffer, int buf_size); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/core/app-framework/connection/native/linux/connection_mgr.c b/core/app-framework/connection/native/linux/connection_mgr.c deleted file mode 100644 index 001446206..000000000 --- a/core/app-framework/connection/native/linux/connection_mgr.c +++ /dev/null @@ -1,609 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -/* - * Note: - * This file implements the linux version connection library which is - * defined in connection_lib.h. - * It also provides a reference implementation of connections manager. - */ - -#include "connection_lib.h" -#include "bh_platform.h" -#include "app_manager_export.h" -#include "module_wasm_app.h" -#include "conn_tcp.h" -#include "conn_udp.h" -#include "conn_uart.h" - -#include -#include -#include -#include -#include - -#define MAX_EVENTS 10 -#define IO_BUF_SIZE 256 - -static bool polling_thread_run = true; - -/* Connection type */ -typedef enum conn_type { - CONN_TYPE_TCP, - CONN_TYPE_UDP, - CONN_TYPE_UART, - CONN_TYPE_UNKNOWN -} conn_type_t; - -/* Sys connection */ -typedef struct sys_connection { - /* Next connection */ - struct sys_connection *next; - - /* Type */ - conn_type_t type; - - /* Handle to interact with wasm app */ - uint32 handle; - - /* Underlying connection ID, may be socket fd */ - int fd; - - /* Module id that the connection belongs to */ - uint32 module_id; - - /* Argument, such as dest addr for udp */ - void *arg; -} sys_connection_t; - -/* Epoll instance */ -static int epollfd; - -/* Connections list */ -static sys_connection_t *g_connections = NULL; - -/* Max handle */ -static uint32 g_handle_max = 0; - -/* Lock to protect g_connections and g_handle_max */ -static korp_mutex g_lock; - -/* Epoll events */ -static struct epoll_event epoll_events[MAX_EVENTS]; - -/* Buffer to receive data */ -static char io_buf[IO_BUF_SIZE]; - -static uint32 -_conn_open(wasm_module_inst_t module_inst, const char *name, - attr_container_t *args); -static void -_conn_close(uint32 handle); -static int -_conn_send(uint32 handle, const char *data, int len); -static bool -_conn_config(uint32 handle, attr_container_t *cfg); - -/* clang-format off */ -/* - * Platform implementation of connection library - */ -connection_interface_t connection_impl = { - ._open = _conn_open, - ._close = _conn_close, - ._send = _conn_send, - ._config = _conn_config -}; -/* clang-format on */ - -static void -add_connection(sys_connection_t *conn) -{ - os_mutex_lock(&g_lock); - - g_handle_max++; - if (g_handle_max == -1) - g_handle_max++; - conn->handle = g_handle_max; - - if (g_connections) { - conn->next = g_connections; - g_connections = conn; - } - else { - g_connections = conn; - } - - os_mutex_unlock(&g_lock); -} - -#define FREE_CONNECTION(conn) \ - do { \ - if (conn->arg) \ - wasm_runtime_free(conn->arg); \ - wasm_runtime_free(conn); \ - } while (0) - -static int -get_app_conns_num(uint32 module_id) -{ - sys_connection_t *conn; - int num = 0; - - os_mutex_lock(&g_lock); - - conn = g_connections; - while (conn) { - if (conn->module_id == module_id) - num++; - conn = conn->next; - } - - os_mutex_unlock(&g_lock); - - return num; -} - -static sys_connection_t * -find_connection(uint32 handle, bool remove_found) -{ - sys_connection_t *conn, *prev = NULL; - - os_mutex_lock(&g_lock); - - conn = g_connections; - while (conn) { - if (conn->handle == handle) { - if (remove_found) { - if (prev != NULL) { - prev->next = conn->next; - } - else { - g_connections = conn->next; - } - } - os_mutex_unlock(&g_lock); - return conn; - } - else { - prev = conn; - conn = conn->next; - } - } - - os_mutex_unlock(&g_lock); - - return NULL; -} - -static void -cleanup_connections(uint32 module_id) -{ - sys_connection_t *conn, *prev = NULL; - - os_mutex_lock(&g_lock); - - conn = g_connections; - while (conn) { - if (conn->module_id == module_id) { - epoll_ctl(epollfd, EPOLL_CTL_DEL, conn->fd, NULL); - close(conn->fd); - - if (prev != NULL) { - prev->next = conn->next; - FREE_CONNECTION(conn); - conn = prev->next; - } - else { - g_connections = conn->next; - FREE_CONNECTION(conn); - conn = g_connections; - } - } - else { - prev = conn; - conn = conn->next; - } - } - - os_mutex_unlock(&g_lock); -} - -static conn_type_t -get_conn_type(const char *name) -{ - if (strcmp(name, "TCP") == 0) - return CONN_TYPE_TCP; - if (strcmp(name, "UDP") == 0) - return CONN_TYPE_UDP; - if (strcmp(name, "UART") == 0) - return CONN_TYPE_UART; - - return CONN_TYPE_UNKNOWN; -} - -/* --- connection lib function --- */ -static uint32 -_conn_open(wasm_module_inst_t module_inst, const char *name, - attr_container_t *args) -{ - int fd; - sys_connection_t *conn; - struct epoll_event ev; - uint32 module_id = app_manager_get_module_id(Module_WASM_App, module_inst); - bh_assert(module_id != ID_NONE); - - if (get_app_conns_num(module_id) >= MAX_CONNECTION_PER_APP) - return -1; - - conn = (sys_connection_t *)wasm_runtime_malloc(sizeof(*conn)); - if (conn == NULL) - return -1; - - memset(conn, 0, sizeof(*conn)); - conn->module_id = module_id; - conn->type = get_conn_type(name); - - /* Generate a handle and add to list */ - add_connection(conn); - - if (conn->type == CONN_TYPE_TCP) { - char *address; - uint16 port; - - /* Check and parse connection parameters */ - if (!attr_container_contain_key(args, "address") - || !attr_container_contain_key(args, "port")) - goto fail; - - address = attr_container_get_as_string(args, "address"); - port = attr_container_get_as_uint16(args, "port"); - - /* Connect to TCP server */ - if (!address || (fd = tcp_open(address, port)) == -1) - goto fail; - } - else if (conn->type == CONN_TYPE_UDP) { - uint16 port; - - /* Check and parse connection parameters */ - if (!attr_container_contain_key(args, "bind port")) - goto fail; - port = attr_container_get_as_uint16(args, "bind port"); - - /* Bind port */ - if ((fd = udp_open(port)) == -1) - goto fail; - } - else if (conn->type == CONN_TYPE_UART) { - char *device; - int baud; - - /* Check and parse connection parameters */ - if (!attr_container_contain_key(args, "device") - || !attr_container_contain_key(args, "baudrate")) - goto fail; - device = attr_container_get_as_string(args, "device"); - baud = attr_container_get_as_int(args, "baudrate"); - - /* Open device */ - if (!device || (fd = uart_open(device, baud)) == -1) - goto fail; - } - else { - goto fail; - } - - conn->fd = fd; - - /* Set current connection as event data */ - ev.events = EPOLLIN; - ev.data.ptr = conn; - - /* Monitor incoming data */ - if (epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &ev) == -1) { - close(fd); - goto fail; - } - - return conn->handle; - -fail: - find_connection(conn->handle, true); - wasm_runtime_free(conn); - return -1; -} - -/* --- connection lib function --- */ -static void -_conn_close(uint32 handle) -{ - sys_connection_t *conn = find_connection(handle, true); - - if (conn != NULL) { - epoll_ctl(epollfd, EPOLL_CTL_DEL, conn->fd, NULL); - close(conn->fd); - FREE_CONNECTION(conn); - } -} - -/* --- connection lib function --- */ -static int -_conn_send(uint32 handle, const char *data, int len) -{ - sys_connection_t *conn = find_connection(handle, false); - - if (conn == NULL) - return -1; - - if (conn->type == CONN_TYPE_TCP) - return tcp_send(conn->fd, data, len); - - if (conn->type == CONN_TYPE_UDP) { - struct sockaddr *addr = (struct sockaddr *)conn->arg; - return udp_send(conn->fd, addr, data, len); - } - - if (conn->type == CONN_TYPE_UART) - return uart_send(conn->fd, data, len); - - return -1; -} - -/* --- connection lib function --- */ -static bool -_conn_config(uint32 handle, attr_container_t *cfg) -{ - sys_connection_t *conn = find_connection(handle, false); - - if (conn == NULL) - return false; - - if (conn->type == CONN_TYPE_UDP) { - char *address; - uint16_t port; - struct sockaddr_in *addr; - - /* Parse remote address/port */ - if (!attr_container_contain_key(cfg, "address") - || !attr_container_contain_key(cfg, "port")) - return false; - if (!(address = attr_container_get_as_string(cfg, "address"))) - return false; - port = attr_container_get_as_uint16(cfg, "port"); - - if (conn->arg == NULL) { - addr = (struct sockaddr_in *)wasm_runtime_malloc(sizeof(*addr)); - if (addr == NULL) - return false; - - memset(addr, 0, sizeof(*addr)); - addr->sin_family = AF_INET; - addr->sin_addr.s_addr = inet_addr(address); - addr->sin_port = htons(port); - - /* Set remote address as connection arg */ - conn->arg = addr; - } - else { - addr = (struct sockaddr_in *)conn->arg; - addr->sin_addr.s_addr = inet_addr(address); - addr->sin_port = htons(port); - } - - return true; - } - - return false; -} - -/* --- connection manager reference implementation ---*/ - -typedef struct connection_event { - uint32 handle; - char *data; - uint32 len; -} connection_event_t; - -static void -connection_event_cleaner(connection_event_t *conn_event) -{ - if (conn_event->data != NULL) - wasm_runtime_free(conn_event->data); - wasm_runtime_free(conn_event); -} - -static void -post_msg_to_module(sys_connection_t *conn, char *data, uint32 len) -{ - module_data *module = module_data_list_lookup_id(conn->module_id); - char *data_copy = NULL; - connection_event_t *conn_data_event; - bh_message_t msg; - - if (module == NULL) - return; - - conn_data_event = - (connection_event_t *)wasm_runtime_malloc(sizeof(*conn_data_event)); - if (conn_data_event == NULL) - return; - - if (len > 0) { - data_copy = (char *)wasm_runtime_malloc(len); - if (data_copy == NULL) { - wasm_runtime_free(conn_data_event); - return; - } - bh_memcpy_s(data_copy, len, data, len); - } - - memset(conn_data_event, 0, sizeof(*conn_data_event)); - conn_data_event->handle = conn->handle; - conn_data_event->data = data_copy; - conn_data_event->len = len; - - msg = bh_new_msg(CONNECTION_EVENT_WASM, conn_data_event, - sizeof(*conn_data_event), connection_event_cleaner); - if (!msg) { - connection_event_cleaner(conn_data_event); - return; - } - - bh_post_msg2(module->queue, msg); -} - -static void * -polling_thread_routine(void *arg) -{ - while (polling_thread_run) { - int i, n; - - n = epoll_wait(epollfd, epoll_events, MAX_EVENTS, -1); - - if (n == -1 && errno != EINTR) - continue; - - for (i = 0; i < n; i++) { - sys_connection_t *conn = - (sys_connection_t *)epoll_events[i].data.ptr; - - if (conn->type == CONN_TYPE_TCP) { - int count = tcp_recv(conn->fd, io_buf, IO_BUF_SIZE); - if (count <= 0) { - /* Connection is closed by peer */ - post_msg_to_module(conn, NULL, 0); - _conn_close(conn->handle); - } - else { - /* Data is received */ - post_msg_to_module(conn, io_buf, count); - } - } - else if (conn->type == CONN_TYPE_UDP) { - int count = udp_recv(conn->fd, io_buf, IO_BUF_SIZE); - if (count > 0) - post_msg_to_module(conn, io_buf, count); - } - else if (conn->type == CONN_TYPE_UART) { - int count = uart_recv(conn->fd, io_buf, IO_BUF_SIZE); - if (count > 0) - post_msg_to_module(conn, io_buf, count); - } - } - } - - return NULL; -} - -void -app_mgr_connection_event_callback(module_data *m_data, bh_message_t msg) -{ - uint32 argv[3]; - wasm_function_inst_t func_on_conn_data; - bh_assert(CONNECTION_EVENT_WASM == bh_message_type(msg)); - wasm_data *wasm_app_data = (wasm_data *)m_data->internal_data; - wasm_module_inst_t inst = wasm_app_data->wasm_module_inst; - connection_event_t *conn_event = - (connection_event_t *)bh_message_payload(msg); - int32 data_offset; - - if (conn_event == NULL) - return; - - func_on_conn_data = wasm_runtime_lookup_function( - inst, "_on_connection_data", "(i32i32i32)"); - if (!func_on_conn_data) - func_on_conn_data = wasm_runtime_lookup_function( - inst, "on_connection_data", "(i32i32i32)"); - if (!func_on_conn_data) { - printf("Cannot find function on_connection_data\n"); - return; - } - - /* 0 len means connection closed */ - if (conn_event->len == 0) { - argv[0] = conn_event->handle; - argv[1] = 0; - argv[2] = 0; - if (!wasm_runtime_call_wasm(wasm_app_data->exec_env, func_on_conn_data, - 3, argv)) { - const char *exception = wasm_runtime_get_exception(inst); - bh_assert(exception); - printf(":Got exception running wasm code: %s\n", exception); - wasm_runtime_clear_exception(inst); - return; - } - } - else { - data_offset = wasm_runtime_module_dup_data(inst, conn_event->data, - conn_event->len); - if (data_offset == 0) { - const char *exception = wasm_runtime_get_exception(inst); - if (exception) { - printf("Got exception running wasm code: %s\n", exception); - wasm_runtime_clear_exception(inst); - } - return; - } - - argv[0] = conn_event->handle; - argv[1] = (uint32)data_offset; - argv[2] = conn_event->len; - if (!wasm_runtime_call_wasm(wasm_app_data->exec_env, func_on_conn_data, - 3, argv)) { - const char *exception = wasm_runtime_get_exception(inst); - bh_assert(exception); - printf(":Got exception running wasm code: %s\n", exception); - wasm_runtime_clear_exception(inst); - wasm_runtime_module_free(inst, data_offset); - return; - } - wasm_runtime_module_free(inst, data_offset); - } -} - -bool -init_connection_framework() -{ - korp_tid tid; - - epollfd = epoll_create(MAX_EVENTS); - if (epollfd == -1) - return false; - - if (os_mutex_init(&g_lock) != 0) { - close(epollfd); - return false; - } - - if (!wasm_register_cleanup_callback(cleanup_connections)) { - goto fail; - } - - if (!wasm_register_msg_callback(CONNECTION_EVENT_WASM, - app_mgr_connection_event_callback)) { - goto fail; - } - - if (os_thread_create(&tid, polling_thread_routine, NULL, - BH_APPLET_PRESERVED_STACK_SIZE) - != 0) { - goto fail; - } - - return true; - -fail: - os_mutex_destroy(&g_lock); - close(epollfd); - return false; -} - -void -exit_connection_framework() -{ - polling_thread_run = false; -} diff --git a/core/app-framework/connection/native/linux/connection_mgr.cmake b/core/app-framework/connection/native/linux/connection_mgr.cmake deleted file mode 100644 index c8f2b487e..000000000 --- a/core/app-framework/connection/native/linux/connection_mgr.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -set (WASM_LIB_CONN_MGR_DIR ${CMAKE_CURRENT_LIST_DIR}) - -include_directories(${WASM_LIB_CONN_MGR_DIR}) - - -file (GLOB_RECURSE source_all ${WASM_LIB_CONN_MGR_DIR}/*.c) - -set (WASM_LIB_CONN_MGR_SOURCE ${source_all}) - - diff --git a/core/app-framework/connection/native/wasm_lib.cmake b/core/app-framework/connection/native/wasm_lib.cmake deleted file mode 100644 index 58db0c1d8..000000000 --- a/core/app-framework/connection/native/wasm_lib.cmake +++ /dev/null @@ -1,18 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -set (WASM_LIB_CONN_DIR ${CMAKE_CURRENT_LIST_DIR}) - -include_directories(${WASM_LIB_CONN_DIR}) - -add_definitions (-DAPP_FRAMEWORK_CONNECTION) - - -include (${CMAKE_CURRENT_LIST_DIR}/${WAMR_BUILD_PLATFORM}/connection_mgr.cmake) - -file (GLOB source_all - ${WASM_LIB_CONN_MGR_SOURCE} - ${WASM_LIB_CONN_DIR}/*.c -) - -set (WASM_APP_LIB_CURRENT_SOURCE ${source_all}) diff --git a/core/app-framework/connection/native/zephyr/connection_lib_impl.c b/core/app-framework/connection/native/zephyr/connection_lib_impl.c deleted file mode 100644 index a812a71a2..000000000 --- a/core/app-framework/connection/native/zephyr/connection_lib_impl.c +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -/* - * Note: - * This file implements the linux version connection library which is - * defined in connection_lib.h. - * It also provides a reference impl of connections manager. - */ - -#include "connection_lib.h" - -/* clang-format off */ -/* - * Platform implementation of connection library - */ -connection_interface_t connection_impl = { - ._open = NULL, - ._close = NULL, - ._send = NULL, - ._config = NULL -}; -/* clang-format on */ diff --git a/core/app-framework/connection/native/zephyr/connection_mgr.cmake b/core/app-framework/connection/native/zephyr/connection_mgr.cmake deleted file mode 100644 index c8f2b487e..000000000 --- a/core/app-framework/connection/native/zephyr/connection_mgr.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -set (WASM_LIB_CONN_MGR_DIR ${CMAKE_CURRENT_LIST_DIR}) - -include_directories(${WASM_LIB_CONN_MGR_DIR}) - - -file (GLOB_RECURSE source_all ${WASM_LIB_CONN_MGR_DIR}/*.c) - -set (WASM_LIB_CONN_MGR_SOURCE ${source_all}) - - diff --git a/core/app-framework/sensor/app/sensor.c b/core/app-framework/sensor/app/sensor.c deleted file mode 100644 index d898a1d3a..000000000 --- a/core/app-framework/sensor/app/sensor.c +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "wa-inc/sensor.h" - -#include "sensor_api.h" - -typedef struct _sensor { - struct _sensor *next; - char *name; - uint32 handle; - void (*sensor_callback)(sensor_t, attr_container_t *, void *); - void *user_data; -} sensor; - -static sensor_t g_sensors = NULL; - -sensor_t -sensor_open(const char *name, int index, - sensor_event_handler_f sensor_event_handler, void *user_data) -{ - uint32 id = wasm_sensor_open(name, index); - if (id == -1) - return NULL; - - // create local node for holding the user callback - sensor_t sensor = (sensor_t)malloc(sizeof(struct _sensor)); - if (sensor == NULL) - return NULL; - - memset(sensor, 0, sizeof(struct _sensor)); - sensor->handle = id; - sensor->name = strdup(name); - sensor->user_data = user_data; - sensor->sensor_callback = sensor_event_handler; - - if (!sensor->name) { - free(sensor); - return NULL; - } - - if (g_sensors == NULL) { - g_sensors = sensor; - } - else { - sensor->next = g_sensors; - g_sensors = sensor; - } - - return sensor; -} - -bool -sensor_config_with_attr_container(sensor_t sensor, attr_container_t *cfg) -{ - char *buffer = (char *)cfg; - int len = attr_container_get_serialize_length(cfg); - - return wasm_sensor_config_with_attr_container(sensor->handle, buffer, len); -} - -bool -sensor_config(sensor_t sensor, int interval, int bit_cfg, int delay) -{ - bool ret = wasm_sensor_config(sensor->handle, interval, bit_cfg, delay); - return ret; -} - -bool -sensor_close(sensor_t sensor) -{ - wasm_sensor_close(sensor->handle); - - // remove local node - sensor_t s = g_sensors; - sensor_t prev = NULL; - while (s) { - if (s == sensor) { - if (prev == NULL) { - g_sensors = s->next; - } - else { - prev->next = s->next; - } - free(s->name); - free(s); - return true; - } - else { - prev = s; - s = s->next; - } - } - - return false; -} - -/* - * - * API for native layer to callback for sensor events - * - */ - -void -on_sensor_event(uint32 sensor_id, char *buffer, int len) -{ - attr_container_t *sensor_data = (attr_container_t *)buffer; - - // lookup the sensor and call the handlers - sensor_t s = g_sensors; - sensor_t prev = NULL; - while (s) { - if (s->handle == sensor_id) { - s->sensor_callback(s, sensor_data, s->user_data); - break; - } - - s = s->next; - } -} diff --git a/core/app-framework/sensor/app/sensor_api.h b/core/app-framework/sensor/app/sensor_api.h deleted file mode 100644 index ad6a7aa24..000000000 --- a/core/app-framework/sensor/app/sensor_api.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _SENSOR_API_H_ -#define _SENSOR_API_H_ - -#include "bh_platform.h" - -#ifdef __cplusplus -extern "C" { -#endif - -uint32 -wasm_sensor_open(const char *name, int instance); - -bool -wasm_sensor_config(uint32 sensor, uint32 interval, int bit_cfg, uint32 delay); - -bool -wasm_sensor_config_with_attr_container(uint32 sensor, char *buffer, uint32 len); - -bool -wasm_sensor_close(uint32 sensor); - -#ifdef __cplusplus -} -#endif - -#endif /* end of _SENSOR_API_H_ */ diff --git a/core/app-framework/sensor/app/wa-inc/sensor.h b/core/app-framework/sensor/app/wa-inc/sensor.h deleted file mode 100644 index 109f895d3..000000000 --- a/core/app-framework/sensor/app/wa-inc/sensor.h +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _AEE_SENSOR_H_ -#define _AEE_SENSOR_H_ - -#include "bi-inc/attr_container.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* board producer define sensor */ -struct _sensor; -typedef struct _sensor *sensor_t; - -/** - * @typedef sensor_event_handler_f - * - * @brief Define the signature of callback function for API - * sensor_open() to handle sensor event. - * - * @param sensor the sensor which the event belong to - * @param sensor_event the sensor event - * @param user_data user data associated with the sensor which is set when - * calling sensor_open(). - * - * @see sensor_open - */ -typedef void (*sensor_event_handler_f)(sensor_t sensor, - attr_container_t *sensor_event, - void *user_data); - -/* - ***************** - * Sensor APIs - ***************** - */ - -/** - * @brief Open sensor. - * - * @param name sensor name - * @param index sensor index - * @param handler callback function to handle the sensor event - * @param user_data user data - * - * @return the sensor opened if success, NULL otherwise - */ -sensor_t -sensor_open(const char *name, int index, sensor_event_handler_f handler, - void *user_data); - -/** - * @brief Configure sensor with interval/bit_cfg/delay values. - * - * @param sensor the sensor to be configured - * @param interval sensor event interval - * @param bit_cfg sensor bit config - * @param delay sensor delay - * - * @return true if success, false otherwise - */ -bool -sensor_config(sensor_t sensor, int interval, int bit_cfg, int delay); - -/** - * @brief Configure sensor with attr_container_t object. - * - * @param sensor the sensor to be configured - * @param cfg the configuration - * - * @return true if success, false otherwise - */ -bool -sensor_config_with_attr_container(sensor_t sensor, attr_container_t *cfg); - -/** - * @brief Close sensor. - * - * @param sensor the sensor to be closed - * - * @return true if success, false otherwise - */ -bool -sensor_close(sensor_t sensor); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/core/app-framework/sensor/app/wasm_app.cmake b/core/app-framework/sensor/app/wasm_app.cmake deleted file mode 100644 index 4b14a8bef..000000000 --- a/core/app-framework/sensor/app/wasm_app.cmake +++ /dev/null @@ -1,11 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -set (WASM_APP_SENSOR_DIR ${CMAKE_CURRENT_LIST_DIR}) - -include_directories(${WASM_APP_SENSOR_DIR}) - - -file (GLOB_RECURSE source_all ${WASM_APP_SENSOR_DIR}/*.c) - -set (WASM_APP_CURRENT_SOURCE ${source_all}) diff --git a/core/app-framework/sensor/native/runtime_sensor.c b/core/app-framework/sensor/native/runtime_sensor.c deleted file mode 100644 index ad7a3fbf5..000000000 --- a/core/app-framework/sensor/native/runtime_sensor.c +++ /dev/null @@ -1,434 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "runtime_sensor.h" -#include "app_manager_export.h" -#include "module_wasm_app.h" -#include "bh_platform.h" - -static sys_sensor_t *g_sys_sensors = NULL; -static uint32 g_sensor_id_max = 0; - -static sensor_client_t * -find_sensor_client(sys_sensor_t *sensor, unsigned int client_id, - bool remove_if_found); - -void (*rechedule_sensor_callback)() = NULL; - -/* - * API for the applications to call - don't call it from the runtime - * - */ - -static void -sensor_event_cleaner(sensor_event_data_t *sensor_event) -{ - if (sensor_event->data != NULL) { - if (sensor_event->data_fmt == FMT_ATTR_CONTAINER) - attr_container_destroy(sensor_event->data); - else - wasm_runtime_free(sensor_event->data); - } - - wasm_runtime_free(sensor_event); -} - -static void -wasm_sensor_callback(void *client, uint32 sensor_id, void *user_data) -{ - attr_container_t *sensor_data = (attr_container_t *)user_data; - attr_container_t *sensor_data_clone; - int sensor_data_len; - sensor_event_data_t *sensor_event; - bh_message_t msg; - sensor_client_t *c = (sensor_client_t *)client; - - module_data *module = module_data_list_lookup_id(c->client_id); - if (module == NULL) - return; - - if (sensor_data == NULL) - return; - - sensor_data_len = attr_container_get_serialize_length(sensor_data); - sensor_data_clone = - (attr_container_t *)wasm_runtime_malloc(sensor_data_len); - if (sensor_data_clone == NULL) - return; - - /* multiple sensor clients may use/free the sensor data, so make a copy */ - bh_memcpy_s(sensor_data_clone, sensor_data_len, sensor_data, - sensor_data_len); - - sensor_event = - (sensor_event_data_t *)wasm_runtime_malloc(sizeof(*sensor_event)); - if (sensor_event == NULL) { - wasm_runtime_free(sensor_data_clone); - return; - } - - memset(sensor_event, 0, sizeof(*sensor_event)); - sensor_event->sensor_id = sensor_id; - sensor_event->data = sensor_data_clone; - sensor_event->data_fmt = FMT_ATTR_CONTAINER; - - msg = bh_new_msg(SENSOR_EVENT_WASM, sensor_event, sizeof(*sensor_event), - sensor_event_cleaner); - if (!msg) { - sensor_event_cleaner(sensor_event); - return; - } - - bh_post_msg2(module->queue, msg); -} - -bool -wasm_sensor_config(wasm_exec_env_t exec_env, uint32 sensor, uint32 interval, - int bit_cfg, uint32 delay) -{ - wasm_module_inst_t module_inst = get_module_inst(exec_env); - attr_container_t *attr_cont; - sensor_client_t *c; - sensor_obj_t s = find_sys_sensor_id(sensor); - if (s == NULL) - return false; - - unsigned int mod_id = - app_manager_get_module_id(Module_WASM_App, module_inst); - bh_assert(mod_id != ID_NONE); - - os_mutex_lock(&s->lock); - - c = find_sensor_client(s, mod_id, false); - if (c == NULL) { - os_mutex_unlock(&s->lock); - return false; - } - - c->interval = interval; - c->bit_cfg = bit_cfg; - c->delay = delay; - - os_mutex_unlock(&s->lock); - - if (s->config != NULL) { - attr_cont = attr_container_create("config sensor"); - attr_container_set_int(&attr_cont, "interval", (int)interval); - attr_container_set_int(&attr_cont, "bit_cfg", bit_cfg); - attr_container_set_int(&attr_cont, "delay", (int)delay); - s->config(s, attr_cont); - attr_container_destroy(attr_cont); - } - - refresh_read_interval(s); - - reschedule_sensor_read(); - - return true; -} - -uint32 -wasm_sensor_open(wasm_exec_env_t exec_env, char *name, int instance) -{ - wasm_module_inst_t module_inst = get_module_inst(exec_env); - - if (name != NULL) { - sensor_client_t *c; - sys_sensor_t *s = find_sys_sensor(name, instance); - if (s == NULL) - return (uint32)-1; - - unsigned int mod_id = - app_manager_get_module_id(Module_WASM_App, module_inst); - bh_assert(mod_id != ID_NONE); - - os_mutex_lock(&s->lock); - - c = find_sensor_client(s, mod_id, false); - if (c) { - // the app already opened this sensor - os_mutex_unlock(&s->lock); - return (uint32)-1; - } - - sensor_client_t *client = - (sensor_client_t *)wasm_runtime_malloc(sizeof(sensor_client_t)); - if (client == NULL) { - os_mutex_unlock(&s->lock); - return (uint32)-1; - } - - memset(client, 0, sizeof(sensor_client_t)); - client->client_id = mod_id; - client->client_callback = (void *)wasm_sensor_callback; - client->interval = s->default_interval; - client->next = s->clients; - s->clients = client; - - os_mutex_unlock(&s->lock); - - refresh_read_interval(s); - - reschedule_sensor_read(); - - return s->sensor_id; - } - - return (uint32)-1; -} - -bool -wasm_sensor_config_with_attr_container(wasm_exec_env_t exec_env, uint32 sensor, - char *buffer, int len) -{ - if (buffer != NULL) { - attr_container_t *cfg = (attr_container_t *)buffer; - sensor_obj_t s = find_sys_sensor_id(sensor); - if (s == NULL) - return false; - - if (s->config == NULL) - return false; - - return s->config(s, cfg); - } - - return false; -} - -bool -wasm_sensor_close(wasm_exec_env_t exec_env, uint32 sensor) -{ - wasm_module_inst_t module_inst = get_module_inst(exec_env); - unsigned int mod_id = - app_manager_get_module_id(Module_WASM_App, module_inst); - unsigned int client_id = mod_id; - sensor_obj_t s = find_sys_sensor_id(sensor); - sensor_client_t *c; - - bh_assert(mod_id != ID_NONE); - - if (s == NULL) - return false; - - os_mutex_lock(&s->lock); - if ((c = find_sensor_client(s, client_id, true)) != NULL) - wasm_runtime_free(c); - os_mutex_unlock(&s->lock); - - refresh_read_interval(s); - - reschedule_sensor_read(); - - return true; -} - -/* - * - * sensor framework API - don't expose to the applications - * - */ -void -set_sensor_reshceduler(void (*callback)()) -{ - rechedule_sensor_callback = callback; -} - -// used for other threads to wakeup the sensor read thread -void -reschedule_sensor_read() -{ - if (rechedule_sensor_callback) - rechedule_sensor_callback(); -} - -void -refresh_read_interval(sensor_obj_t sensor) -{ - sensor_client_t *c; - uint32 interval = sensor->default_interval; - os_mutex_lock(&sensor->lock); - - c = sensor->clients; - if (c) - interval = c->interval; - - while (c) { - if (c->interval < interval) - interval = c->interval; - c = c->next; - } - - os_mutex_unlock(&sensor->lock); - - sensor->read_interval = interval; -} - -sensor_obj_t -add_sys_sensor(char *name, char *description, int instance, - uint32 default_interval, void *read_func, void *config_func) -{ - sys_sensor_t *s = (sys_sensor_t *)wasm_runtime_malloc(sizeof(sys_sensor_t)); - if (s == NULL) - return NULL; - - memset(s, 0, sizeof(*s)); - s->name = bh_strdup(name); - s->sensor_instance = instance; - s->default_interval = default_interval; - - if (!s->name) { - wasm_runtime_free(s); - return NULL; - } - - if (description) { - s->description = bh_strdup(description); - if (!s->description) { - wasm_runtime_free(s->name); - wasm_runtime_free(s); - return NULL; - } - } - - g_sensor_id_max++; - if (g_sensor_id_max == UINT32_MAX) - g_sensor_id_max++; - s->sensor_id = g_sensor_id_max; - - s->read = read_func; - s->config = config_func; - - if (g_sys_sensors == NULL) { - g_sys_sensors = s; - } - else { - s->next = g_sys_sensors; - g_sys_sensors = s; - } - - if (os_mutex_init(&s->lock) != 0) { - if (s->description) { - wasm_runtime_free(s->description); - } - wasm_runtime_free(s->name); - wasm_runtime_free(s); - } - - return s; -} - -sensor_obj_t -find_sys_sensor(const char *name, int instance) -{ - sys_sensor_t *s = g_sys_sensors; - while (s) { - if (strcmp(s->name, name) == 0 && s->sensor_instance == instance) - return s; - - s = s->next; - } - return NULL; -} - -sensor_obj_t -find_sys_sensor_id(uint32 sensor_id) -{ - sys_sensor_t *s = g_sys_sensors; - while (s) { - if (s->sensor_id == sensor_id) - return s; - - s = s->next; - } - return NULL; -} - -sensor_client_t * -find_sensor_client(sys_sensor_t *sensor, unsigned int client_id, - bool remove_if_found) -{ - sensor_client_t *prev = NULL, *c = sensor->clients; - - while (c) { - sensor_client_t *next = c->next; - if (c->client_id == client_id) { - if (remove_if_found) { - if (prev) - prev->next = next; - else - sensor->clients = next; - } - return c; - } - else { - prev = c; - c = c->next; - } - } - - return NULL; -} - -// return the milliseconds to next check -uint32 -check_sensor_timers() -{ - uint32 ms_to_next_check = UINT32_MAX; - uint32 now = (uint32)bh_get_tick_ms(); - - sys_sensor_t *s = g_sys_sensors; - while (s) { - uint32 last_read = s->last_read; - uint32 elpased_ms = bh_get_elpased_ms(&last_read); - - if (s->read_interval <= 0 || s->clients == NULL) { - s = s->next; - continue; - } - - if (elpased_ms >= s->read_interval) { - attr_container_t *data = s->read(s); - if (data) { - sensor_client_t *client = s->clients; - while (client) { - client->client_callback(client, s->sensor_id, data); - client = client->next; - } - attr_container_destroy(data); - } - - s->last_read = now; - - if (s->read_interval < ms_to_next_check) - ms_to_next_check = s->read_interval; - } - else { - uint32 remaining = s->read_interval - elpased_ms; - if (remaining < ms_to_next_check) - ms_to_next_check = remaining; - } - - s = s->next; - } - - return ms_to_next_check; -} - -void -sensor_cleanup_callback(uint32 module_id) -{ - sys_sensor_t *s = g_sys_sensors; - - while (s) { - sensor_client_t *c; - os_mutex_lock(&s->lock); - if ((c = find_sensor_client(s, module_id, true)) != NULL) { - wasm_runtime_free(c); - } - os_mutex_unlock(&s->lock); - s = s->next; - } -} diff --git a/core/app-framework/sensor/native/runtime_sensor.h b/core/app-framework/sensor/native/runtime_sensor.h deleted file mode 100644 index d7c893111..000000000 --- a/core/app-framework/sensor/native/runtime_sensor.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef LIB_EXTENSION_RUNTIME_SENSOR_H_ -#define LIB_EXTENSION_RUNTIME_SENSOR_H_ - -#include "bh_platform.h" -#include "bi-inc/attr_container.h" -#include "wasm_export.h" -#include "sensor_native_api.h" - -struct _sys_sensor; -typedef struct _sys_sensor *sensor_obj_t; - -typedef struct _sensor_client { - struct _sensor_client *next; - unsigned int client_id; // the app id - uint32 interval; - int bit_cfg; - uint32 delay; - void (*client_callback)(void *client, uint32, attr_container_t *); -} sensor_client_t; - -typedef struct _sys_sensor { - struct _sys_sensor *next; - char *name; - int sensor_instance; - char *description; - uint32 sensor_id; - sensor_client_t *clients; - /* app, sensor mgr and app mgr may access the clients at the same time, - so need a lock to protect the clients */ - korp_mutex lock; - uint32 last_read; - uint32 read_interval; - uint32 default_interval; - - /* TODO: may support other type return value, such as 'cbor' */ - attr_container_t *(*read)(void *); - bool (*config)(void *, void *); - -} sys_sensor_t; - -sensor_obj_t -add_sys_sensor(char *name, char *description, int instance, - uint32 default_interval, void *read_func, void *config_func); -sensor_obj_t -find_sys_sensor(const char *name, int instance); -sensor_obj_t -find_sys_sensor_id(uint32 sensor_id); -void -refresh_read_interval(sensor_obj_t sensor); -void -sensor_cleanup_callback(uint32 module_id); -uint32 -check_sensor_timers(); -void -reschedule_sensor_read(); - -bool -init_sensor_framework(); -void -start_sensor_framework(); -void -exit_sensor_framework(); - -#endif /* LIB_EXTENSION_RUNTIME_SENSOR_H_ */ diff --git a/core/app-framework/sensor/native/runtime_sensor.inl b/core/app-framework/sensor/native/runtime_sensor.inl deleted file mode 100644 index a7b9f4778..000000000 --- a/core/app-framework/sensor/native/runtime_sensor.inl +++ /dev/null @@ -1,9 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -EXPORT_WASM_API_WITH_SIG(wasm_sensor_open, "($i)i"), -EXPORT_WASM_API_WITH_SIG(wasm_sensor_config, "(iiii)i"), -EXPORT_WASM_API_WITH_SIG(wasm_sensor_config_with_attr_container, "(i*~)i"), -EXPORT_WASM_API_WITH_SIG(wasm_sensor_close, "(i)i"), diff --git a/core/app-framework/sensor/native/sensor_mgr_ref.c b/core/app-framework/sensor/native/sensor_mgr_ref.c deleted file mode 100644 index 474ec738d..000000000 --- a/core/app-framework/sensor/native/sensor_mgr_ref.c +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "bh_platform.h" -#include "runtime_sensor.h" -#include "bi-inc/attr_container.h" -#include "module_wasm_app.h" -#include "wasm_export.h" - -/* - * - * One reference implementation for sensor manager - * - * - */ -static korp_cond cond; -static korp_mutex mutex; -static bool sensor_check_thread_run = true; - -void -app_mgr_sensor_event_callback(module_data *m_data, bh_message_t msg) -{ - uint32 argv[3]; - wasm_function_inst_t func_onSensorEvent; - - bh_assert(SENSOR_EVENT_WASM == bh_message_type(msg)); - wasm_data *wasm_app_data = (wasm_data *)m_data->internal_data; - wasm_module_inst_t inst = wasm_app_data->wasm_module_inst; - - sensor_event_data_t *payload = - (sensor_event_data_t *)bh_message_payload(msg); - if (payload == NULL) - return; - - func_onSensorEvent = - wasm_runtime_lookup_function(inst, "_on_sensor_event", "(i32i32i32)"); - if (!func_onSensorEvent) - func_onSensorEvent = wasm_runtime_lookup_function( - inst, "on_sensor_event", "(i32i32i32)"); - if (!func_onSensorEvent) { - printf("Cannot find function on_sensor_event\n"); - } - else { - int32 sensor_data_offset; - uint32 sensor_data_len; - - if (payload->data_fmt == FMT_ATTR_CONTAINER) { - sensor_data_len = - attr_container_get_serialize_length(payload->data); - } - else { - printf("Unsupported sensor data format: %d\n", payload->data_fmt); - return; - } - - sensor_data_offset = - wasm_runtime_module_dup_data(inst, payload->data, sensor_data_len); - if (sensor_data_offset == 0) { - const char *exception = wasm_runtime_get_exception(inst); - if (exception) { - printf("Got exception running wasm code: %s\n", exception); - wasm_runtime_clear_exception(inst); - } - return; - } - - argv[0] = payload->sensor_id; - argv[1] = (uint32)sensor_data_offset; - argv[2] = sensor_data_len; - - if (!wasm_runtime_call_wasm(wasm_app_data->exec_env, func_onSensorEvent, - 3, argv)) { - const char *exception = wasm_runtime_get_exception(inst); - bh_assert(exception); - printf(":Got exception running wasm code: %s\n", exception); - wasm_runtime_clear_exception(inst); - wasm_runtime_module_free(inst, sensor_data_offset); - return; - } - - wasm_runtime_module_free(inst, sensor_data_offset); - } -} - -static void -thread_sensor_check(void *arg) -{ - while (sensor_check_thread_run) { - uint32 ms_to_expiry = check_sensor_timers(); - if (ms_to_expiry == UINT32_MAX) - ms_to_expiry = 5000; - os_mutex_lock(&mutex); - os_cond_reltimedwait(&cond, &mutex, ms_to_expiry * 1000); - os_mutex_unlock(&mutex); - } -} - -static void -cb_wakeup_thread() -{ - os_cond_signal(&cond); -} - -void -set_sensor_reshceduler(void (*callback)()); - -bool -init_sensor_framework() -{ - /* init the mutext and conditions */ - if (os_cond_init(&cond) != 0) { - return false; - } - - if (os_mutex_init(&mutex) != 0) { - os_cond_destroy(&cond); - return false; - } - - set_sensor_reshceduler(cb_wakeup_thread); - - wasm_register_msg_callback(SENSOR_EVENT_WASM, - app_mgr_sensor_event_callback); - - wasm_register_cleanup_callback(sensor_cleanup_callback); - - return true; -} - -void -start_sensor_framework() -{ - korp_tid tid; - - os_thread_create(&tid, (void *)thread_sensor_check, NULL, - BH_APPLET_PRESERVED_STACK_SIZE); -} - -void -exit_sensor_framework() -{ - sensor_check_thread_run = false; - reschedule_sensor_read(); - - // todo: wait the sensor thread termination -} diff --git a/core/app-framework/sensor/native/sensor_native_api.h b/core/app-framework/sensor/native/sensor_native_api.h deleted file mode 100644 index 0bbb315ca..000000000 --- a/core/app-framework/sensor/native/sensor_native_api.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _SENSOR_NATIVE_API_H_ -#define _SENSOR_NATIVE_API_H_ - -#include "bh_platform.h" -#include "wasm_export.h" - -#ifdef __cplusplus -extern "C" { -#endif - -bool -wasm_sensor_config(wasm_exec_env_t exec_env, uint32 sensor, uint32 interval, - int bit_cfg, uint32 delay); -uint32 -wasm_sensor_open(wasm_exec_env_t exec_env, char *name, int instance); - -bool -wasm_sensor_config_with_attr_container(wasm_exec_env_t exec_env, uint32 sensor, - char *buffer, int len); - -bool -wasm_sensor_close(wasm_exec_env_t exec_env, uint32 sensor); - -#ifdef __cplusplus -} -#endif - -#endif /* end of _SENSOR_NATIVE_API_H_ */ diff --git a/core/app-framework/sensor/native/wasm_lib.cmake b/core/app-framework/sensor/native/wasm_lib.cmake deleted file mode 100644 index 65a83ba59..000000000 --- a/core/app-framework/sensor/native/wasm_lib.cmake +++ /dev/null @@ -1,14 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -set (WASM_LIB_SENSOR_DIR ${CMAKE_CURRENT_LIST_DIR}) - -add_definitions (-DAPP_FRAMEWORK_SENSOR) - -include_directories(${WASM_LIB_SENSOR_DIR}) - - -file (GLOB_RECURSE source_all ${WASM_LIB_SENSOR_DIR}/*.c) - -set (WASM_APP_LIB_CURRENT_SOURCE ${source_all}) - diff --git a/core/app-framework/template/app/wa-inc/app_xxx.h b/core/app-framework/template/app/wa-inc/app_xxx.h deleted file mode 100644 index ac30842f0..000000000 --- a/core/app-framework/template/app/wa-inc/app_xxx.h +++ /dev/null @@ -1,8 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -/* - header file for wasm application -*/ \ No newline at end of file diff --git a/core/app-framework/template/app/wasm_app.cmake b/core/app-framework/template/app/wasm_app.cmake deleted file mode 100644 index 16ca237ae..000000000 --- a/core/app-framework/template/app/wasm_app.cmake +++ /dev/null @@ -1,16 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -set (WASM_APP_CURRENT_DIR ${CMAKE_CURRENT_LIST_DIR}) - -include_directories( - ${WASM_APP_CURRENT_DIR} - # Add your include dir here -) - -file (GLOB_RECURSE source_all - ${WASM_APP_CURRENT_DIR}/*.c - # Add your source file here -) - -set (WASM_APP_CURRENT_SOURCE ${source_all}) diff --git a/core/app-framework/template/native/app_xxx.inl b/core/app-framework/template/native/app_xxx.inl deleted file mode 100644 index 2503fe454..000000000 --- a/core/app-framework/template/native/app_xxx.inl +++ /dev/null @@ -1,6 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -/* EXPORT_WASM_API(your_api_here), */ diff --git a/core/app-framework/template/native/wasm_lib.cmake b/core/app-framework/template/native/wasm_lib.cmake deleted file mode 100644 index 2601c1d27..000000000 --- a/core/app-framework/template/native/wasm_lib.cmake +++ /dev/null @@ -1,17 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -set (WASM_LIB_CURRENT_DIR ${CMAKE_CURRENT_LIST_DIR}) - -include_directories( - ${WASM_LIB_CURRENT_DIR} - # Add your include dir here -) - -file (GLOB_RECURSE source_all - ${WASM_LIB_CURRENT_DIR}/*.c - # Add your source file here -) - -set (WASM_APP_LIB_CURRENT_SOURCE ${source_all}) - diff --git a/core/app-framework/wgl/app/gui_api.h b/core/app-framework/wgl/app/gui_api.h deleted file mode 100644 index 7547cdcdc..000000000 --- a/core/app-framework/wgl/app/gui_api.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _GUI_API_H_ -#define _GUI_API_H_ - -#include "bh_platform.h" -#include "bi-inc/wgl_shared_utils.h" - -#ifdef __cplusplus -extern "C" { -#endif - -void -wasm_obj_native_call(int32 func_id, uint32 *argv, uint32 argc); - -void -wasm_btn_native_call(int32 func_id, uint32 *argv, uint32 argc); - -void -wasm_label_native_call(int32 func_id, uint32 *argv, uint32 argc); - -void -wasm_cb_native_call(int32 func_id, uint32 *argv, uint32 argc); - -void -wasm_list_native_call(int32 func_id, uint32 *argv, uint32 argc); - -#ifdef __cplusplus -} -#endif - -#endif /* end of _GUI_API_H_ */ diff --git a/core/app-framework/wgl/app/prepare_headers.sh b/core/app-framework/wgl/app/prepare_headers.sh deleted file mode 100755 index 261257952..000000000 --- a/core/app-framework/wgl/app/prepare_headers.sh +++ /dev/null @@ -1,46 +0,0 @@ -#!/bin/bash - -WGL_ROOT=$(cd "$(dirname "$0")/" && pwd) -LVGL_REPO_DIR=${WGL_ROOT}/../../../deps/lvgl -ls $LVGL_REPO_DIR - -#if [ ! -d "${LVGL_REPO_DIR}" ]; then -# echo "lvgl repo not exist, please git pull the lvgl v6.0 first" -# exit 1 -#fi - -cd ${WGL_ROOT}/wa-inc/lvgl -pwd - -if [ -d src ]; then - rm -rf src - echo "deleted the src folder from previous preparation." -fi - -mkdir src -cd src - -cp ${LVGL_REPO_DIR}/src/*.h ./ - -for folder in lv_core lv_draw lv_hal lv_objx lv_font lv_misc lv_themes -do - echo "Prepare fold $folder...done" - mkdir $folder - cp ${LVGL_REPO_DIR}/src/${folder}/*.h ./${folder}/ -done - -cp -f ../lv_obj.h ./lv_core/lv_obj.h - -echo "test the header files..." -cd .. - -gcc test.c -o test.out -if [ $? != 0 ];then - echo "failed to compile the test.c" - exit 1 -else - echo "okay" - rm test.out -fi - -echo "lvgl header files for WASM application ready." diff --git a/core/app-framework/wgl/app/src/wgl_btn.c b/core/app-framework/wgl/app/src/wgl_btn.c deleted file mode 100644 index 680124e5f..000000000 --- a/core/app-framework/wgl/app/src/wgl_btn.c +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "wa-inc/lvgl/lvgl.h" -#include "bh_platform.h" -#include "gui_api.h" - -#define ARGC sizeof(argv) / sizeof(uint32) -#define CALL_BTN_NATIVE_FUNC(id) wasm_btn_native_call(id, argv, ARGC) - -lv_obj_t * -lv_btn_create(lv_obj_t *par, const lv_obj_t *copy) -{ - uint32 argv[2] = { 0 }; - - argv[0] = (uint32)par; - argv[1] = (uint32)copy; - CALL_BTN_NATIVE_FUNC(BTN_FUNC_ID_CREATE); - return (lv_obj_t *)argv[0]; -} - -void -lv_btn_set_toggle(lv_obj_t *btn, bool tgl) -{ - uint32 argv[2] = { 0 }; - argv[0] = (uint32)btn; - argv[1] = tgl; - CALL_BTN_NATIVE_FUNC(BTN_FUNC_ID_SET_TOGGLE); -} - -void -lv_btn_set_state(lv_obj_t *btn, lv_btn_state_t state) -{ - uint32 argv[2] = { 0 }; - argv[0] = (uint32)btn; - argv[1] = state; - CALL_BTN_NATIVE_FUNC(BTN_FUNC_ID_SET_STATE); -} - -void -lv_btn_toggle(lv_obj_t *btn) -{ - uint32 argv[1] = { 0 }; - argv[0] = (uint32)btn; - CALL_BTN_NATIVE_FUNC(BTN_FUNC_ID_TOGGLE); -} - -void -lv_btn_set_ink_in_time(lv_obj_t *btn, uint16_t time) -{ - uint32 argv[2] = { 0 }; - argv[0] = (uint32)btn; - argv[1] = time; - CALL_BTN_NATIVE_FUNC(BTN_FUNC_ID_SET_INK_IN_TIME); -} - -void -lv_btn_set_ink_wait_time(lv_obj_t *btn, uint16_t time) -{ - uint32 argv[2] = { 0 }; - argv[0] = (uint32)btn; - argv[1] = time; - CALL_BTN_NATIVE_FUNC(BTN_FUNC_ID_SET_INK_WAIT_TIME); -} - -void -lv_btn_set_ink_out_time(lv_obj_t *btn, uint16_t time) -{ - uint32 argv[2] = { 0 }; - argv[0] = (uint32)btn; - argv[1] = time; - CALL_BTN_NATIVE_FUNC(BTN_FUNC_ID_SET_INK_OUT_TIME); -} - -// void wgl_btn_set_style(wgl_obj_t btn, wgl_btn_style_t type, -// const wgl_style_t *style) -//{ -// //TODO: pack style -// //wasm_btn_set_style(btn, type, style); -//} -// -lv_btn_state_t -lv_btn_get_state(const lv_obj_t *btn) -{ - uint32 argv[1] = { 0 }; - argv[0] = (uint32)btn; - CALL_BTN_NATIVE_FUNC(BTN_FUNC_ID_GET_STATE); - return (lv_btn_state_t)argv[0]; -} - -bool -lv_btn_get_toggle(const lv_obj_t *btn) -{ - uint32 argv[1] = { 0 }; - argv[0] = (uint32)btn; - CALL_BTN_NATIVE_FUNC(BTN_FUNC_ID_GET_TOGGLE); - return (bool)argv[0]; -} - -uint16_t -lv_btn_get_ink_in_time(const lv_obj_t *btn) -{ - uint32 argv[1] = { 0 }; - argv[0] = (uint32)btn; - CALL_BTN_NATIVE_FUNC(BTN_FUNC_ID_GET_INK_IN_TIME); - return (uint16_t)argv[0]; -} - -uint16_t -lv_btn_get_ink_wait_time(const lv_obj_t *btn) -{ - uint32 argv[1] = { 0 }; - argv[0] = (uint32)btn; - CALL_BTN_NATIVE_FUNC(BTN_FUNC_ID_GET_INK_WAIT_TIME); - return (uint16_t)argv[0]; -} - -uint16_t -lv_btn_get_ink_out_time(const lv_obj_t *btn) -{ - uint32 argv[1] = { 0 }; - argv[0] = (uint32)btn; - CALL_BTN_NATIVE_FUNC(BTN_FUNC_ID_GET_INK_OUT_TIME); - return (uint16_t)argv[0]; -} -// -// const wgl_style_t * wgl_btn_get_style(const wgl_obj_t btn, -// wgl_btn_style_t type) -//{ -// //TODO: pack style -// //wasm_btn_get_style(btn, type); -// return NULL; -//} diff --git a/core/app-framework/wgl/app/src/wgl_cb.c b/core/app-framework/wgl/app/src/wgl_cb.c deleted file mode 100644 index bd172d3b0..000000000 --- a/core/app-framework/wgl/app/src/wgl_cb.c +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "wa-inc/lvgl/lvgl.h" -#include "gui_api.h" - -#include - -#define ARGC sizeof(argv) / sizeof(uint32) -#define CALL_CB_NATIVE_FUNC(id) wasm_cb_native_call(id, argv, ARGC) - -lv_obj_t * -lv_cb_create(lv_obj_t *par, const lv_obj_t *copy) -{ - uint32 argv[2] = { 0 }; - - argv[0] = (uint32)par; - argv[1] = (uint32)copy; - CALL_CB_NATIVE_FUNC(CB_FUNC_ID_CREATE); - return (lv_obj_t *)argv[0]; -} - -void -lv_cb_set_text(lv_obj_t *cb, const char *txt) -{ - uint32 argv[3] = { 0 }; - argv[0] = (uint32)cb; - argv[1] = (uint32)txt; - argv[2] = strlen(txt) + 1; - CALL_CB_NATIVE_FUNC(CB_FUNC_ID_SET_TEXT); -} - -void -lv_cb_set_static_text(lv_obj_t *cb, const char *txt) -{ - uint32 argv[3] = { 0 }; - argv[0] = (uint32)cb; - argv[1] = (uint32)txt; - argv[2] = strlen(txt) + 1; - CALL_CB_NATIVE_FUNC(CB_FUNC_ID_SET_STATIC_TEXT); -} - -// void wgl_cb_set_style(wgl_obj_t cb, wgl_cb_style_t type, -// const wgl_style_t *style) -//{ -// //TODO: -//} -// - -static unsigned int -wgl_cb_get_text_length(lv_obj_t *cb) -{ - uint32 argv[1] = { 0 }; - argv[0] = (uint32)cb; - CALL_CB_NATIVE_FUNC(CB_FUNC_ID_GET_TEXT_LENGTH); - return argv[0]; -} - -static char * -wgl_cb_get_text(lv_obj_t *cb, char *buffer, int buffer_len) -{ - uint32 argv[3] = { 0 }; - argv[0] = (uint32)cb; - argv[1] = (uint32)buffer; - argv[2] = buffer_len; - CALL_CB_NATIVE_FUNC(CB_FUNC_ID_GET_TEXT); - return (char *)argv[0]; -} - -// TODO: need to use a global data buffer for the returned text -const char * -lv_cb_get_text(const lv_obj_t *cb) -{ - - return NULL; -} - -// const wgl_style_t * wgl_cb_get_style(const wgl_obj_t cb, -// wgl_cb_style_t type) -//{ -// //TODO -// return NULL; -//} -// diff --git a/core/app-framework/wgl/app/src/wgl_label.c b/core/app-framework/wgl/app/src/wgl_label.c deleted file mode 100644 index 81c6dcf5f..000000000 --- a/core/app-framework/wgl/app/src/wgl_label.c +++ /dev/null @@ -1,260 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "wa-inc/lvgl/lvgl.h" -#include "gui_api.h" -#include - -#define ARGC sizeof(argv) / sizeof(uint32) -#define CALL_LABEL_NATIVE_FUNC(id) wasm_label_native_call(id, argv, ARGC) - -lv_obj_t * -lv_label_create(lv_obj_t *par, const lv_obj_t *copy) -{ - uint32 argv[2] = { 0 }; - - argv[0] = (uint32)par; - argv[1] = (uint32)copy; - CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_CREATE); - return (lv_obj_t *)argv[0]; -} - -void -lv_label_set_text(lv_obj_t *label, const char *text) -{ - uint32 argv[3] = { 0 }; - argv[0] = (uint32)label; - argv[1] = (uint32)text; - argv[2] = strlen(text) + 1; - CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_SET_TEXT); -} - -void -lv_label_set_array_text(lv_obj_t *label, const char *array, uint16_t size) -{ - uint32 argv[3] = { 0 }; - argv[0] = (uint32)label; - argv[1] = (uint32)array; - argv[2] = size; - CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_SET_ARRAY_TEXT); -} - -void -lv_label_set_static_text(lv_obj_t *label, const char *text) -{ - uint32 argv[3] = { 0 }; - argv[0] = (uint32)label; - argv[1] = (uint32)text; - argv[2] = strlen(text) + 1; - CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_SET_STATIC_TEXT); -} - -void -lv_label_set_long_mode(lv_obj_t *label, lv_label_long_mode_t long_mode) -{ - uint32 argv[2] = { 0 }; - argv[0] = (uint32)label; - argv[1] = long_mode; - CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_SET_LONG_MODE); -} - -void -lv_label_set_align(lv_obj_t *label, lv_label_align_t align) -{ - uint32 argv[2] = { 0 }; - argv[0] = (uint32)label; - argv[1] = align; - CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_SET_ALIGN); -} - -void -lv_label_set_recolor(lv_obj_t *label, bool en) -{ - uint32 argv[2] = { 0 }; - argv[0] = (uint32)label; - argv[1] = en; - CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_SET_RECOLOR); -} - -void -lv_label_set_body_draw(lv_obj_t *label, bool en) -{ - uint32 argv[2] = { 0 }; - argv[0] = (uint32)label; - argv[1] = en; - CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_SET_BODY_DRAW); -} - -void -lv_label_set_anim_speed(lv_obj_t *label, uint16_t anim_speed) -{ - uint32 argv[2] = { 0 }; - argv[0] = (uint32)label; - argv[1] = anim_speed; - CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_SET_ANIM_SPEED); -} - -void -lv_label_set_text_sel_start(lv_obj_t *label, uint16_t index) -{ - uint32 argv[2] = { 0 }; - argv[0] = (uint32)label; - argv[1] = index; - CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_SET_TEXT_SEL_START); -} - -void -lv_label_set_text_sel_end(lv_obj_t *label, uint16_t index) -{ - uint32 argv[2] = { 0 }; - argv[0] = (uint32)label; - argv[1] = index; - CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_SET_TEXT_SEL_END); -} - -unsigned int -wgl_label_get_text_length(lv_obj_t *label) -{ - uint32 argv[1] = { 0 }; - argv[0] = (uint32)label; - CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_GET_TEXT_LENGTH); - return argv[0]; -} - -char * -wgl_label_get_text(lv_obj_t *label, char *buffer, int buffer_len) -{ - uint32 argv[3] = { 0 }; - argv[0] = (uint32)label; - argv[1] = (uint32)buffer; - argv[2] = buffer_len; - CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_GET_TEXT); - return (char *)argv[0]; -} - -// TODO: -char * -lv_label_get_text(const lv_obj_t *label) -{ - - return NULL; -} - -lv_label_long_mode_t -lv_label_get_long_mode(const lv_obj_t *label) -{ - uint32 argv[1] = { 0 }; - argv[0] = (uint32)label; - CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_GET_LONG_MODE); - return (lv_label_long_mode_t)argv[0]; -} - -lv_label_align_t -lv_label_get_align(const lv_obj_t *label) -{ - uint32 argv[1] = { 0 }; - argv[0] = (uint32)label; - CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_GET_ALIGN); - return (lv_label_align_t)argv[0]; -} - -bool -lv_label_get_recolor(const lv_obj_t *label) -{ - uint32 argv[1] = { 0 }; - argv[0] = (uint32)label; - CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_GET_RECOLOR); - return (bool)argv[0]; -} - -bool -lv_label_get_body_draw(const lv_obj_t *label) -{ - uint32 argv[1] = { 0 }; - argv[0] = (uint32)label; - CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_GET_BODY_DRAW); - return (bool)argv[0]; -} - -uint16_t -lv_label_get_anim_speed(const lv_obj_t *label) -{ - uint32 argv[1] = { 0 }; - argv[0] = (uint32)label; - CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_GET_ANIM_SPEED); - return (uint16_t)argv[0]; -} - -void -lv_label_get_letter_pos(const lv_obj_t *label, uint16_t index, lv_point_t *pos) -{ - uint32 argv[4] = { 0 }; - argv[0] = (uint32)label; - argv[1] = index; - CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_GET_LETTER_POS); - pos->x = argv[2]; - pos->y = argv[3]; -} - -uint16_t -lv_label_get_letter_on(const lv_obj_t *label, lv_point_t *pos) -{ - uint32 argv[3] = { 0 }; - argv[0] = (uint32)label; - argv[1] = pos->x; - argv[2] = pos->y; - CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_GET_LETTER_POS); - return (uint16_t)argv[0]; -} - -bool -lv_label_is_char_under_pos(const lv_obj_t *label, lv_point_t *pos) -{ - uint32 argv[3] = { 0 }; - argv[0] = (uint32)label; - argv[1] = pos->x; - argv[2] = pos->y; - CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_GET_LETTER_POS); - return (bool)argv[0]; -} - -uint16_t -lv_label_get_text_sel_start(const lv_obj_t *label) -{ - uint32 argv[1] = { 0 }; - argv[0] = (uint32)label; - CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_GET_TEXT_SEL_START); - return (uint16_t)argv[0]; -} - -uint16_t -lv_label_get_text_sel_end(const lv_obj_t *label) -{ - uint32 argv[1] = { 0 }; - argv[0] = (uint32)label; - CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_GET_TEXT_SEL_END); - return (uint16_t)argv[0]; -} - -void -lv_label_ins_text(lv_obj_t *label, uint32_t pos, const char *txt) -{ - uint32 argv[4] = { 0 }; - argv[0] = (uint32)label; - argv[1] = pos; - argv[2] = (uint32)txt; - argv[3] = strlen(txt) + 1; - CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_INS_TEXT); -} - -void -lv_label_cut_text(lv_obj_t *label, uint32_t pos, uint32_t cnt) -{ - uint32 argv[3] = { 0 }; - argv[0] = (uint32)label; - argv[1] = pos; - argv[2] = cnt; - CALL_LABEL_NATIVE_FUNC(LABEL_FUNC_ID_CUT_TEXT); -} diff --git a/core/app-framework/wgl/app/src/wgl_list.c b/core/app-framework/wgl/app/src/wgl_list.c deleted file mode 100644 index 1ca95a6e8..000000000 --- a/core/app-framework/wgl/app/src/wgl_list.c +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "wa-inc/lvgl/lvgl.h" -#include "gui_api.h" - -#include - -#define ARGC sizeof(argv) / sizeof(uint32) -#define CALL_LIST_NATIVE_FUNC(id) wasm_list_native_call(id, argv, ARGC) - -lv_obj_t * -lv_list_create(lv_obj_t *par, const lv_obj_t *copy) -{ - uint32 argv[2] = { 0 }; - - argv[0] = (uint32)par; - argv[1] = (uint32)copy; - - CALL_LIST_NATIVE_FUNC(LIST_FUNC_ID_CREATE); - return (lv_obj_t *)argv[0]; -} -// -// -// void wgl_list_clean(wgl_obj_t obj) -//{ -// wasm_list_clean(obj); -//} -// - -lv_obj_t * -lv_list_add_btn(lv_obj_t *list, const void *img_src, const char *txt) -{ - uint32 argv[3] = { 0 }; - - (void)img_src; /* doesn't support img src currently */ - - argv[0] = (uint32)list; - argv[1] = (uint32)txt; - argv[2] = strlen(txt) + 1; - CALL_LIST_NATIVE_FUNC(LIST_FUNC_ID_ADD_BTN); - return (lv_obj_t *)argv[0]; -} -// -// -// bool wgl_list_remove(const wgl_obj_t list, uint16_t index) -//{ -// return wasm_list_remove(list, index); -//} -// -// -// void wgl_list_set_single_mode(wgl_obj_t list, bool mode) -//{ -// wasm_list_set_single_mode(list, mode); -//} -// -//#if LV_USE_GROUP -// -// -// void wgl_list_set_btn_selected(wgl_obj_t list, wgl_obj_t btn) -//{ -// wasm_list_set_btn_selected(list, btn); -//} -//#endif -// -// -// void wgl_list_set_style(wgl_obj_t list, wgl_list_style_t type, -// const wgl_style_t * style) -//{ -// //TODO -//} -// -// -// bool wgl_list_get_single_mode(wgl_obj_t list) -//{ -// return wasm_list_get_single_mode(list); -//} -// -// -// const char * wgl_list_get_btn_text(const wgl_obj_t btn) -//{ -// return wasm_list_get_btn_text(btn); -//} -// -// wgl_obj_t wgl_list_get_btn_label(const wgl_obj_t btn) -//{ -// return wasm_list_get_btn_label(btn); -//} -// -// -// wgl_obj_t wgl_list_get_btn_img(const wgl_obj_t btn) -//{ -// return wasm_list_get_btn_img(btn); -//} -// -// -// wgl_obj_t wgl_list_get_prev_btn(const wgl_obj_t list, wgl_obj_t prev_btn) -//{ -// return wasm_list_get_prev_btn(list, prev_btn); -//} -// -// -// wgl_obj_t wgl_list_get_next_btn(const wgl_obj_t list, wgl_obj_t prev_btn) -//{ -// return wasm_list_get_next_btn(list, prev_btn); -//} -// -// -// int32_t wgl_list_get_btn_index(const wgl_obj_t list, const wgl_obj_t btn) -//{ -// return wasm_list_get_btn_index(list, btn); -//} -// -// -// uint16_t wgl_list_get_size(const wgl_obj_t list) -//{ -// return wasm_list_get_size(list); -//} -// -//#if LV_USE_GROUP -// -// wgl_obj_t wgl_list_get_btn_selected(const wgl_obj_t list) -//{ -// return wasm_list_get_btn_selected(list); -//} -//#endif -// -// -// -// const wgl_style_t * wgl_list_get_style(const wgl_obj_t list, -// wgl_list_style_t type) -//{ -// //TODO -// return NULL; -//} -// -// -// void wgl_list_up(const wgl_obj_t list) -//{ -// wasm_list_up(list); -//} -// -// void wgl_list_down(const wgl_obj_t list) -//{ -// wasm_list_down(list); -//} -// -// -// void wgl_list_focus(const wgl_obj_t btn, wgl_anim_enable_t anim) -//{ -// wasm_list_focus(btn, anim); -//} -// diff --git a/core/app-framework/wgl/app/src/wgl_obj.c b/core/app-framework/wgl/app/src/wgl_obj.c deleted file mode 100644 index e1fe152c5..000000000 --- a/core/app-framework/wgl/app/src/wgl_obj.c +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "wa-inc/lvgl/lvgl.h" -#include "gui_api.h" -#include -#include - -#define ARGC sizeof(argv) / sizeof(uint32) -#define CALL_OBJ_NATIVE_FUNC(id) wasm_obj_native_call(id, argv, ARGC) - -typedef struct _obj_evt_cb { - struct _obj_evt_cb *next; - - lv_obj_t *obj; - lv_event_cb_t event_cb; -} obj_evt_cb_t; - -static obj_evt_cb_t *g_obj_evt_cb_list = NULL; - -/* For lvgl compatible */ -char g_widget_text[100]; - -lv_res_t -lv_obj_del(lv_obj_t *obj) -{ - uint32 argv[1] = { 0 }; - argv[0] = (uint32)obj; - CALL_OBJ_NATIVE_FUNC(OBJ_FUNC_ID_DEL); - return (lv_res_t)argv[0]; -} - -void -lv_obj_del_async(struct _lv_obj_t *obj) -{ - uint32 argv[1] = { 0 }; - argv[0] = (uint32)obj; - CALL_OBJ_NATIVE_FUNC(OBJ_FUNC_ID_DEL_ASYNC); -} - -void -lv_obj_clean(lv_obj_t *obj) -{ - uint32 argv[1] = { 0 }; - argv[0] = (uint32)obj; - CALL_OBJ_NATIVE_FUNC(OBJ_FUNC_ID_CLEAN); -} - -void -lv_obj_align(lv_obj_t *obj, const lv_obj_t *base, lv_align_t align, - lv_coord_t x_mod, lv_coord_t y_mod) -{ - uint32 argv[5] = { 0 }; - argv[0] = (uint32)obj; - argv[1] = (uint32)base; - argv[2] = align; - argv[3] = x_mod; - argv[4] = y_mod; - CALL_OBJ_NATIVE_FUNC(OBJ_FUNC_ID_ALIGN); -} - -lv_event_cb_t -lv_obj_get_event_cb(const lv_obj_t *obj) -{ - obj_evt_cb_t *obj_evt_cb = g_obj_evt_cb_list; - while (obj_evt_cb != NULL) { - if (obj_evt_cb->obj == obj) { - return obj_evt_cb->event_cb; - } - obj_evt_cb = obj_evt_cb->next; - } - - return NULL; -} - -void -lv_obj_set_event_cb(lv_obj_t *obj, lv_event_cb_t event_cb) -{ - obj_evt_cb_t *obj_evt_cb; - uint32 argv[1] = { 0 }; - - obj_evt_cb = g_obj_evt_cb_list; - while (obj_evt_cb) { - if (obj_evt_cb->obj == obj) { - obj_evt_cb->event_cb = event_cb; - return; - } - } - - obj_evt_cb = (obj_evt_cb_t *)malloc(sizeof(*obj_evt_cb)); - if (obj_evt_cb == NULL) - return; - - memset(obj_evt_cb, 0, sizeof(*obj_evt_cb)); - obj_evt_cb->obj = obj; - obj_evt_cb->event_cb = event_cb; - - if (g_obj_evt_cb_list != NULL) { - obj_evt_cb->next = g_obj_evt_cb_list; - g_obj_evt_cb_list = obj_evt_cb; - } - else { - g_obj_evt_cb_list = obj_evt_cb; - } - - argv[0] = (uint32)obj; - CALL_OBJ_NATIVE_FUNC(OBJ_FUNC_ID_SET_EVT_CB); -} - -void -on_widget_event(lv_obj_t *obj, lv_event_t event) -{ - obj_evt_cb_t *obj_evt_cb = g_obj_evt_cb_list; - - while (obj_evt_cb != NULL) { - if (obj_evt_cb->obj == obj) { - obj_evt_cb->event_cb(obj, event); - return; - } - obj_evt_cb = obj_evt_cb->next; - } -} diff --git a/core/app-framework/wgl/app/wa-inc/lv_conf.h b/core/app-framework/wgl/app/wa-inc/lv_conf.h deleted file mode 100644 index b9f3de8c3..000000000 --- a/core/app-framework/wgl/app/wa-inc/lv_conf.h +++ /dev/null @@ -1,497 +0,0 @@ -/** - * @file lv_conf.h - * - */ - -/* - * COPY THIS FILE AS `lv_conf.h` NEXT TO the `lvgl` FOLDER - */ - -#if 1 /*Set it to "1" to enable content*/ - -#ifndef LV_CONF_H -#define LV_CONF_H -/* clang-format off */ - -#include - - - -/*==================== - Graphical settings - *====================*/ - -/* Maximal horizontal and vertical resolution to support by the library.*/ -#define LV_HOR_RES_MAX (480) -#define LV_VER_RES_MAX (320) - -/* Color depth: - * - 1: 1 byte per pixel - * - 8: RGB233 - * - 16: RGB565 - * - 32: ARGB8888 - */ -#define LV_COLOR_DEPTH 16 - -/* Swap the 2 bytes of RGB565 color. - * Useful if the display has a 8 bit interface (e.g. SPI)*/ -#define LV_COLOR_16_SWAP 0 - -/* 1: Enable screen transparency. - * Useful for OSD or other overlapping GUIs. - * Requires `LV_COLOR_DEPTH = 32` colors and the screen's style should be modified: `style.body.opa = ...`*/ -#define LV_COLOR_SCREEN_TRANSP 0 - -/*Images pixels with this color will not be drawn (with chroma keying)*/ -#define LV_COLOR_TRANSP LV_COLOR_LIME /*LV_COLOR_LIME: pure green*/ - -/* Enable anti-aliasing (lines, and radiuses will be smoothed) */ -#define LV_ANTIALIAS 1 - -/* Default display refresh period. - * Can be changed in the display driver (`lv_disp_drv_t`).*/ -#define LV_DISP_DEF_REFR_PERIOD 30 /*[ms]*/ - -/* Dot Per Inch: used to initialize default sizes. - * E.g. a button with width = LV_DPI / 2 -> half inch wide - * (Not so important, you can adjust it to modify default sizes and spaces)*/ -#define LV_DPI 100 /*[px]*/ - -/* Type of coordinates. Should be `int16_t` (or `int32_t` for extreme cases) */ -typedef int16_t lv_coord_t; - -/*========================= - Memory manager settings - *=========================*/ - -/* LittelvGL's internal memory manager's settings. - * The graphical objects and other related data are stored here. */ - -/* 1: use custom malloc/free, 0: use the built-in `lv_mem_alloc` and `lv_mem_free` */ -#define LV_MEM_CUSTOM 0 -#if LV_MEM_CUSTOM == 0 -/* Size of the memory used by `lv_mem_alloc` in bytes (>= 2kB)*/ -# define LV_MEM_SIZE (32U * 1024U) - -/* Complier prefix for a big array declaration */ -# define LV_MEM_ATTR - -/* Set an address for the memory pool instead of allocating it as an array. - * Can be in external SRAM too. */ -# define LV_MEM_ADR 0 - -/* Automatically defrag. on free. Defrag. means joining the adjacent free cells. */ -# define LV_MEM_AUTO_DEFRAG 1 -#else /*LV_MEM_CUSTOM*/ -# define LV_MEM_CUSTOM_INCLUDE /*Header for the dynamic memory function*/ -# define LV_MEM_CUSTOM_ALLOC malloc /*Wrapper to malloc*/ -# define LV_MEM_CUSTOM_FREE free /*Wrapper to free*/ -#endif /*LV_MEM_CUSTOM*/ - -/* Garbage Collector settings - * Used if lvgl is binded to higher level language and the memory is managed by that language */ -#define LV_ENABLE_GC 0 -#if LV_ENABLE_GC != 0 -# define LV_GC_INCLUDE "gc.h" /*Include Garbage Collector related things*/ -# define LV_MEM_CUSTOM_REALLOC your_realloc /*Wrapper to realloc*/ -# define LV_MEM_CUSTOM_GET_SIZE your_mem_get_size /*Wrapper to lv_mem_get_size*/ -#endif /* LV_ENABLE_GC */ - -/*======================= - Input device settings - *=======================*/ - -/* Input device default settings. - * Can be changed in the Input device driver (`lv_indev_drv_t`)*/ - -/* Input device read period in milliseconds */ -#define LV_INDEV_DEF_READ_PERIOD 30 - -/* Drag threshold in pixels */ -#define LV_INDEV_DEF_DRAG_LIMIT 10 - -/* Drag throw slow-down in [%]. Greater value -> faster slow-down */ -#define LV_INDEV_DEF_DRAG_THROW 20 - -/* Long press time in milliseconds. - * Time to send `LV_EVENT_LONG_PRESSSED`) */ -#define LV_INDEV_DEF_LONG_PRESS_TIME 400 - -/* Repeated trigger period in long press [ms] - * Time between `LV_EVENT_LONG_PRESSED_REPEAT */ -#define LV_INDEV_DEF_LONG_PRESS_REP_TIME 100 - -/*================== - * Feature usage - *==================*/ - -/*1: Enable the Animations */ -#define LV_USE_ANIMATION 1 -#if LV_USE_ANIMATION - -/*Declare the type of the user data of animations (can be e.g. `void *`, `int`, `struct`)*/ -typedef void * lv_anim_user_data_t; - -#endif - -/* 1: Enable shadow drawing*/ -#define LV_USE_SHADOW 1 - -/* 1: Enable object groups (for keyboard/encoder navigation) */ -#define LV_USE_GROUP 1 -#if LV_USE_GROUP -typedef void * lv_group_user_data_t; -#endif /*LV_USE_GROUP*/ - -/* 1: Enable GPU interface*/ -#define LV_USE_GPU 1 - -/* 1: Enable file system (might be required for images */ -#define LV_USE_FILESYSTEM 1 -#if LV_USE_FILESYSTEM -/*Declare the type of the user data of file system drivers (can be e.g. `void *`, `int`, `struct`)*/ -typedef void * lv_fs_drv_user_data_t; -#endif - -/*1: Add a `user_data` to drivers and objects*/ -#define LV_USE_USER_DATA 0 - -/*======================== - * Image decoder and cache - *========================*/ - -/* 1: Enable indexed (palette) images */ -#define LV_IMG_CF_INDEXED 1 - -/* 1: Enable alpha indexed images */ -#define LV_IMG_CF_ALPHA 1 - -/* Default image cache size. Image caching keeps the images opened. - * If only the built-in image formats are used there is no real advantage of caching. - * (I.e. no new image decoder is added) - * With complex image decoders (e.g. PNG or JPG) caching can save the continuous open/decode of images. - * However the opened images might consume additional RAM. - * LV_IMG_CACHE_DEF_SIZE must be >= 1 */ -#define LV_IMG_CACHE_DEF_SIZE 1 - -/*Declare the type of the user data of image decoder (can be e.g. `void *`, `int`, `struct`)*/ -typedef void * lv_img_decoder_user_data_t; - -/*===================== - * Compiler settings - *====================*/ -/* Define a custom attribute to `lv_tick_inc` function */ -#define LV_ATTRIBUTE_TICK_INC - -/* Define a custom attribute to `lv_task_handler` function */ -#define LV_ATTRIBUTE_TASK_HANDLER - -/* With size optimization (-Os) the compiler might not align data to - * 4 or 8 byte boundary. This alignment will be explicitly applied where needed. - * E.g. __attribute__((aligned(4))) */ -#define LV_ATTRIBUTE_MEM_ALIGN - -/* Attribute to mark large constant arrays for example - * font's bitmaps */ -#define LV_ATTRIBUTE_LARGE_CONST - -/*=================== - * HAL settings - *==================*/ - -/* 1: use a custom tick source. - * It removes the need to manually update the tick with `lv_tick_inc`) */ -#define LV_TICK_CUSTOM 0 -#if LV_TICK_CUSTOM == 1 -#define LV_TICK_CUSTOM_INCLUDE "something.h" /*Header for the sys time function*/ -#define LV_TICK_CUSTOM_SYS_TIME_EXPR (millis()) /*Expression evaluating to current systime in ms*/ -#endif /*LV_TICK_CUSTOM*/ - -typedef void * lv_disp_drv_user_data_t; /*Type of user data in the display driver*/ -typedef void * lv_indev_drv_user_data_t; /*Type of user data in the input device driver*/ - -/*================ - * Log settings - *===============*/ - -/*1: Enable the log module*/ -#define LV_USE_LOG 0 -#if LV_USE_LOG -/* How important log should be added: - * LV_LOG_LEVEL_TRACE A lot of logs to give detailed information - * LV_LOG_LEVEL_INFO Log important events - * LV_LOG_LEVEL_WARN Log if something unwanted happened but didn't cause a problem - * LV_LOG_LEVEL_ERROR Only critical issue, when the system may fail - * LV_LOG_LEVEL_NONE Do not log anything - */ -# define LV_LOG_LEVEL LV_LOG_LEVEL_WARN - -/* 1: Print the log with 'printf'; - * 0: user need to register a callback with `lv_log_register_print`*/ -# define LV_LOG_PRINTF 0 -#endif /*LV_USE_LOG*/ - -/*================ - * THEME USAGE - *================*/ -#define LV_THEME_LIVE_UPDATE 0 /*1: Allow theme switching at run time. Uses 8..10 kB of RAM*/ - -#define LV_USE_THEME_TEMPL 0 /*Just for test*/ -#define LV_USE_THEME_DEFAULT 0 /*Built mainly from the built-in styles. Consumes very few RAM*/ -#define LV_USE_THEME_ALIEN 0 /*Dark futuristic theme*/ -#define LV_USE_THEME_NIGHT 0 /*Dark elegant theme*/ -#define LV_USE_THEME_MONO 0 /*Mono color theme for monochrome displays*/ -#define LV_USE_THEME_MATERIAL 0 /*Flat theme with bold colors and light shadows*/ -#define LV_USE_THEME_ZEN 0 /*Peaceful, mainly light theme */ -#define LV_USE_THEME_NEMO 0 /*Water-like theme based on the movie "Finding Nemo"*/ - -/*================== - * FONT USAGE - *===================*/ - -/* The built-in fonts contains the ASCII range and some Symbols with 4 bit-per-pixel. - * The symbols are available via `LV_SYMBOL_...` defines - * More info about fonts: https://docs.littlevgl.com/#Fonts - * To create a new font go to: https://littlevgl.com/ttf-font-to-c-array - */ - -/* Robot fonts with bpp = 4 - * https://fonts.google.com/specimen/Roboto */ -#define LV_FONT_ROBOTO_12 0 -#define LV_FONT_ROBOTO_16 1 -#define LV_FONT_ROBOTO_22 0 -#define LV_FONT_ROBOTO_28 0 - -/*Pixel perfect monospace font - * http://pelulamu.net/unscii/ */ -#define LV_FONT_UNSCII_8 0 - -/* Optionally declare your custom fonts here. - * You can use these fonts as default font too - * and they will be available globally. E.g. - * #define LV_FONT_CUSTOM_DECLARE LV_FONT_DECLARE(my_font_1) \ - * LV_FONT_DECLARE(my_font_2) - */ -#define LV_FONT_CUSTOM_DECLARE - -/*Always set a default font from the built-in fonts*/ -#define LV_FONT_DEFAULT &lv_font_roboto_16 - -/* Enable it if you have fonts with a lot of characters. - * The limit depends on the font size, font face and bpp - * but with > 10,000 characters if you see issues probably you need to enable it.*/ -#define LV_FONT_FMT_TXT_LARGE 0 - -/*Declare the type of the user data of fonts (can be e.g. `void *`, `int`, `struct`)*/ -typedef void * lv_font_user_data_t; - -/*================= - * Text settings - *=================*/ - -/* Select a character encoding for strings. - * Your IDE or editor should have the same character encoding - * - LV_TXT_ENC_UTF8 - * - LV_TXT_ENC_ASCII - * */ -#define LV_TXT_ENC LV_TXT_ENC_UTF8 - - /*Can break (wrap) texts on these chars*/ -#define LV_TXT_BREAK_CHARS " ,.;:-_" - -/*=================== - * LV_OBJ SETTINGS - *==================*/ - -/*Declare the type of the user data of object (can be e.g. `void *`, `int`, `struct`)*/ -typedef void * lv_obj_user_data_t; - -/*1: enable `lv_obj_realaign()` based on `lv_obj_align()` parameters*/ -#define LV_USE_OBJ_REALIGN 1 - -/* Enable to make the object clickable on a larger area. - * LV_EXT_CLICK_AREA_OFF or 0: Disable this feature - * LV_EXT_CLICK_AREA_TINY: The extra area can be adjusted horizontally and vertically (0..255 px) - * LV_EXT_CLICK_AREA_FULL: The extra area can be adjusted in all 4 directions (-32k..+32k px) - */ -#define LV_USE_EXT_CLICK_AREA LV_EXT_CLICK_AREA_OFF - -/*================== - * LV OBJ X USAGE - *================*/ -/* - * Documentation of the object types: https://docs.littlevgl.com/#Object-types - */ - -/*Arc (dependencies: -)*/ -#define LV_USE_ARC 1 - -/*Bar (dependencies: -)*/ -#define LV_USE_BAR 1 - -/*Button (dependencies: lv_cont*/ -#define LV_USE_BTN 1 -#if LV_USE_BTN != 0 -/*Enable button-state animations - draw a circle on click (dependencies: LV_USE_ANIMATION)*/ -# define LV_BTN_INK_EFFECT 0 -#endif - -/*Button matrix (dependencies: -)*/ -#define LV_USE_BTNM 1 - -/*Calendar (dependencies: -)*/ -#define LV_USE_CALENDAR 1 - -/*Canvas (dependencies: lv_img)*/ -#define LV_USE_CANVAS 1 - -/*Check box (dependencies: lv_btn, lv_label)*/ -#define LV_USE_CB 1 - -/*Chart (dependencies: -)*/ -#define LV_USE_CHART 1 -#if LV_USE_CHART -# define LV_CHART_AXIS_TICK_LABEL_MAX_LEN 20 -#endif - -/*Container (dependencies: -*/ -#define LV_USE_CONT 1 - -/*Drop down list (dependencies: lv_page, lv_label, lv_symbol_def.h)*/ -#define LV_USE_DDLIST 1 -#if LV_USE_DDLIST != 0 -/*Open and close default animation time [ms] (0: no animation)*/ -# define LV_DDLIST_DEF_ANIM_TIME 200 -#endif - -/*Gauge (dependencies:lv_bar, lv_lmeter)*/ -#define LV_USE_GAUGE 1 - -/*Image (dependencies: lv_label*/ -#define LV_USE_IMG 1 - -/*Image Button (dependencies: lv_btn*/ -#define LV_USE_IMGBTN 1 -#if LV_USE_IMGBTN -/*1: The imgbtn requires left, mid and right parts and the width can be set freely*/ -# define LV_IMGBTN_TILED 0 -#endif - -/*Keyboard (dependencies: lv_btnm)*/ -#define LV_USE_KB 1 - -/*Label (dependencies: -*/ -#define LV_USE_LABEL 1 -#if LV_USE_LABEL != 0 -/*Hor, or ver. scroll speed [px/sec] in 'LV_LABEL_LONG_ROLL/ROLL_CIRC' mode*/ -# define LV_LABEL_DEF_SCROLL_SPEED 25 - -/* Waiting period at beginning/end of animation cycle */ -# define LV_LABEL_WAIT_CHAR_COUNT 3 - -/*Enable selecting text of the label */ -# define LV_LABEL_TEXT_SEL 0 - -/*Store extra some info in labels (12 bytes) to speed up drawing of very long texts*/ -# define LV_LABEL_LONG_TXT_HINT 0 -#endif - -/*LED (dependencies: -)*/ -#define LV_USE_LED 1 - -/*Line (dependencies: -*/ -#define LV_USE_LINE 1 - -/*List (dependencies: lv_page, lv_btn, lv_label, (lv_img optionally for icons ))*/ -#define LV_USE_LIST 1 -#if LV_USE_LIST != 0 -/*Default animation time of focusing to a list element [ms] (0: no animation) */ -# define LV_LIST_DEF_ANIM_TIME 100 -#endif - -/*Line meter (dependencies: *;)*/ -#define LV_USE_LMETER 1 - -/*Message box (dependencies: lv_rect, lv_btnm, lv_label)*/ -#define LV_USE_MBOX 1 - -/*Page (dependencies: lv_cont)*/ -#define LV_USE_PAGE 1 -#if LV_USE_PAGE != 0 -/*Focus default animation time [ms] (0: no animation)*/ -# define LV_PAGE_DEF_ANIM_TIME 400 -#endif - -/*Preload (dependencies: lv_arc, lv_anim)*/ -#define LV_USE_PRELOAD 1 -#if LV_USE_PRELOAD != 0 -# define LV_PRELOAD_DEF_ARC_LENGTH 60 /*[deg]*/ -# define LV_PRELOAD_DEF_SPIN_TIME 1000 /*[ms]*/ -# define LV_PRELOAD_DEF_ANIM LV_PRELOAD_TYPE_SPINNING_ARC -#endif - -/*Roller (dependencies: lv_ddlist)*/ -#define LV_USE_ROLLER 1 -#if LV_USE_ROLLER != 0 -/*Focus animation time [ms] (0: no animation)*/ -# define LV_ROLLER_DEF_ANIM_TIME 200 - -/*Number of extra "pages" when the roller is infinite*/ -# define LV_ROLLER_INF_PAGES 7 -#endif - -/*Slider (dependencies: lv_bar)*/ -#define LV_USE_SLIDER 1 - -/*Spinbox (dependencies: lv_ta)*/ -#define LV_USE_SPINBOX 1 - -/*Switch (dependencies: lv_slider)*/ -#define LV_USE_SW 1 - -/*Text area (dependencies: lv_label, lv_page)*/ -#define LV_USE_TA 1 -#if LV_USE_TA != 0 -# define LV_TA_DEF_CURSOR_BLINK_TIME 400 /*ms*/ -# define LV_TA_DEF_PWD_SHOW_TIME 1500 /*ms*/ -#endif - -/*Table (dependencies: lv_label)*/ -#define LV_USE_TABLE 1 -#if LV_USE_TABLE -# define LV_TABLE_COL_MAX 12 -#endif - -/*Tab (dependencies: lv_page, lv_btnm)*/ -#define LV_USE_TABVIEW 1 -# if LV_USE_TABVIEW != 0 -/*Time of slide animation [ms] (0: no animation)*/ -# define LV_TABVIEW_DEF_ANIM_TIME 300 -#endif - -/*Tileview (dependencies: lv_page) */ -#define LV_USE_TILEVIEW 1 -#if LV_USE_TILEVIEW -/*Time of slide animation [ms] (0: no animation)*/ -# define LV_TILEVIEW_DEF_ANIM_TIME 300 -#endif - -/*Window (dependencies: lv_cont, lv_btn, lv_label, lv_img, lv_page)*/ -#define LV_USE_WIN 1 - -/*================== - * Non-user section - *==================*/ - -#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) /* Disable warnings for Visual Studio*/ -# define _CRT_SECURE_NO_WARNINGS -#endif - -/*--END OF LV_CONF_H--*/ - -/*Be sure every define has a default value*/ -//#include "../lv_conf_checker.h" - -#endif /*LV_CONF_H*/ - -#endif /*End of "Content enable"*/ diff --git a/core/app-framework/wgl/app/wa-inc/lvgl/LICENCE.txt b/core/app-framework/wgl/app/wa-inc/lvgl/LICENCE.txt deleted file mode 100644 index beaef1d26..000000000 --- a/core/app-framework/wgl/app/wa-inc/lvgl/LICENCE.txt +++ /dev/null @@ -1,8 +0,0 @@ -MIT licence -Copyright (c) 2016 Gábor Kiss-Vámosi - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/core/app-framework/wgl/app/wa-inc/lvgl/lv_obj.h b/core/app-framework/wgl/app/wa-inc/lvgl/lv_obj.h deleted file mode 100644 index 5497b0b62..000000000 --- a/core/app-framework/wgl/app/wa-inc/lvgl/lv_obj.h +++ /dev/null @@ -1,1046 +0,0 @@ -/** - * @file lv_obj.h - * - */ - -#ifndef LV_OBJ_H -#define LV_OBJ_H - -#ifdef __cplusplus -extern "C" { -#endif - -/********************* - * INCLUDES - *********************/ -#ifdef LV_CONF_INCLUDE_SIMPLE -#include "lv_conf.h" -#else -#include "../../../lv_conf.h" -#endif - -#include -#include -#include "lv_style.h" -#include "../lv_misc/lv_types.h" -#include "../lv_misc/lv_area.h" -#include "../lv_misc/lv_mem.h" -#include "../lv_misc/lv_ll.h" -#include "../lv_misc/lv_color.h" -#include "../lv_misc/lv_log.h" -#include "../lv_hal/lv_hal.h" - -/********************* - * DEFINES - *********************/ - -/*Error check of lv_conf.h*/ -#if LV_HOR_RES_MAX == 0 || LV_VER_RES_MAX == 0 -#error "LittlevGL: LV_HOR_RES_MAX and LV_VER_RES_MAX must be greater than 0" -#endif - -#if LV_ANTIALIAS > 1 -#error "LittlevGL: LV_ANTIALIAS can be only 0 or 1" -#endif - -#define LV_MAX_ANCESTOR_NUM 8 - -#define LV_EXT_CLICK_AREA_OFF 0 -#define LV_EXT_CLICK_AREA_TINY 1 -#define LV_EXT_CLICK_AREA_FULL 2 - -/********************** - * TYPEDEFS - **********************/ - -struct _lv_obj_t; - -/** Design modes */ -enum { - LV_DESIGN_DRAW_MAIN, /* Draw the main portion of the object */ - LV_DESIGN_DRAW_POST, /* Draw extras on the object */ - LV_DESIGN_COVER_CHK, /* Check if the object fully covers the 'mask_p' - area */ -}; -typedef uint8_t lv_design_mode_t; - -/** - * The design callback is used to draw the object on the screen. - * It accepts the object, a mask area, and the mode in which to draw the object. - */ -typedef bool (*lv_design_cb_t)(struct _lv_obj_t *obj, const lv_area_t *mask_p, - lv_design_mode_t mode); - -enum { - LV_EVENT_PRESSED, /* The object has been pressed */ - LV_EVENT_PRESSING, /* The object is being pressed (called continuously - while pressing) */ - LV_EVENT_PRESS_LOST, /* User is still pressing but slid cursor/finger off - of the object */ - LV_EVENT_SHORT_CLICKED, /* User pressed object for a short period of time, - then released it. Not called if dragged. */ - LV_EVENT_LONG_PRESSED, /* Object has been pressed for at least - `LV_INDEV_LONG_PRESS_TIME`. Not called if - dragged. */ - LV_EVENT_LONG_PRESSED_REPEAT, /* Called after `LV_INDEV_LONG_PRESS_TIME` - in every `LV_INDEV_LONG_PRESS_REP_TIME` - ms. Not called if dragged.*/ - LV_EVENT_CLICKED, /* Called on release if not dragged (regardless to long - press) */ - LV_EVENT_RELEASED, /* Called in every cases when the object has been - released */ - LV_EVENT_DRAG_BEGIN, - LV_EVENT_DRAG_END, - LV_EVENT_DRAG_THROW_BEGIN, - LV_EVENT_KEY, - LV_EVENT_FOCUSED, - LV_EVENT_DEFOCUSED, - LV_EVENT_VALUE_CHANGED, /* The object's value has changed (i.e. slider - moved) */ - LV_EVENT_INSERT, - LV_EVENT_REFRESH, - LV_EVENT_APPLY, /* "Ok", "Apply" or similar specific button has clicked */ - LV_EVENT_CANCEL, /* "Close", "Cancel" or similar specific button has - clicked */ - LV_EVENT_DELETE, /* Object is being deleted */ -}; - -typedef uint8_t lv_event_t; /* Type of event being sent to the object. */ - -/** - * @brief Event callback. - * Events are used to notify the user of some action being taken on the object. - * For details, see ::lv_event_t. - */ -typedef void (*lv_event_cb_t)(struct _lv_obj_t *obj, lv_event_t event); - -/** Signals are for use by the object itself or to extend the object's - * functionality. Applications should use ::lv_obj_set_event_cb to be notified - * of events that occur on the object. */ -enum { - /*General signals*/ - LV_SIGNAL_CLEANUP, /* Object is being deleted */ - LV_SIGNAL_CHILD_CHG, /* Child was removed/added */ - LV_SIGNAL_CORD_CHG, /* Object coordinates/size have changed */ - LV_SIGNAL_PARENT_SIZE_CHG, /* Parent's size has changed */ - LV_SIGNAL_STYLE_CHG, /* Object's style has changed */ - LV_SIGNAL_REFR_EXT_DRAW_PAD, /* Object's extra padding has changed */ - LV_SIGNAL_GET_TYPE, /* LittlevGL needs to retrieve the object's type */ - - /*Input device related*/ - LV_SIGNAL_PRESSED, /* The object has been pressed*/ - LV_SIGNAL_PRESSING, /* The object is being pressed (called continuously - while pressing)*/ - LV_SIGNAL_PRESS_LOST, /* User is still pressing but slid cursor/finger off - of the object */ - LV_SIGNAL_RELEASED, /* User pressed object for a short period of time, - then released it. Not called if dragged. */ - LV_SIGNAL_LONG_PRESS, /* Object has been pressed for at least - `LV_INDEV_LONG_PRESS_TIME`. Not called if - dragged.*/ - LV_SIGNAL_LONG_PRESS_REP, /* Called after `LV_INDEV_LONG_PRESS_TIME` in - every `LV_INDEV_LONG_PRESS_REP_TIME` ms. Not - called if dragged.*/ - LV_SIGNAL_DRAG_BEGIN, - LV_SIGNAL_DRAG_END, - /*Group related*/ - LV_SIGNAL_FOCUS, - LV_SIGNAL_DEFOCUS, - LV_SIGNAL_CONTROL, - LV_SIGNAL_GET_EDITABLE, -}; - -typedef uint8_t lv_signal_t; - -typedef lv_res_t (*lv_signal_cb_t)(struct _lv_obj_t *obj, lv_signal_t sign, - void *param); - -/** Object alignment. */ -enum { - LV_ALIGN_CENTER = 0, - LV_ALIGN_IN_TOP_LEFT, - LV_ALIGN_IN_TOP_MID, - LV_ALIGN_IN_TOP_RIGHT, - LV_ALIGN_IN_BOTTOM_LEFT, - LV_ALIGN_IN_BOTTOM_MID, - LV_ALIGN_IN_BOTTOM_RIGHT, - LV_ALIGN_IN_LEFT_MID, - LV_ALIGN_IN_RIGHT_MID, - LV_ALIGN_OUT_TOP_LEFT, - LV_ALIGN_OUT_TOP_MID, - LV_ALIGN_OUT_TOP_RIGHT, - LV_ALIGN_OUT_BOTTOM_LEFT, - LV_ALIGN_OUT_BOTTOM_MID, - LV_ALIGN_OUT_BOTTOM_RIGHT, - LV_ALIGN_OUT_LEFT_TOP, - LV_ALIGN_OUT_LEFT_MID, - LV_ALIGN_OUT_LEFT_BOTTOM, - LV_ALIGN_OUT_RIGHT_TOP, - LV_ALIGN_OUT_RIGHT_MID, - LV_ALIGN_OUT_RIGHT_BOTTOM, -}; -typedef uint8_t lv_align_t; - -#if LV_USE_OBJ_REALIGN -typedef struct { - const struct _lv_obj_t *base; - lv_coord_t xofs; - lv_coord_t yofs; - lv_align_t align; - uint8_t auto_realign : 1; - uint8_t origo_align : 1; /* 1: the origo (center of the object) was - aligned with `lv_obj_align_origo`*/ -} lv_reailgn_t; -#endif - -enum { - LV_DRAG_DIR_HOR = 0x1, /* Object can be dragged horizontally. */ - LV_DRAG_DIR_VER = 0x2, /* Object can be dragged vertically. */ - LV_DRAG_DIR_ALL = 0x3, /* Object can be dragged in all directions. */ -}; - -typedef uint8_t lv_drag_dir_t; - -typedef void lv_obj_t; -typedef void lv_obj_type_t; - -/********************** - * GLOBAL PROTOTYPES - **********************/ - -/** - * Init. the 'lv' library. - */ -void -lv_init(void); - -/*-------------------- - * Create and delete - *-------------------*/ - -/** - * Create a basic object - * @param parent pointer to a parent object. - * If NULL then a screen will be created - * @param copy pointer to a base object, if not NULL then - * the new object will be copied from it - * @return pointer to the new object - */ -lv_obj_t * -lv_obj_create(lv_obj_t *parent, const lv_obj_t *copy); - -/** - * Delete 'obj' and all of its children - * @param obj pointer to an object to delete - * @return LV_RES_INV because the object is deleted - */ -lv_res_t -lv_obj_del(lv_obj_t *obj); - -/** - * Helper function for asynchronously deleting objects. - * Useful for cases where you can't delete an object directly in an - * `LV_EVENT_DELETE` handler (i.e. parent). - * @param obj object to delete - * @see lv_async_call - */ -void -lv_obj_del_async(struct _lv_obj_t *obj); - -/** - * Delete all children of an object - * @param obj pointer to an object - */ -void -lv_obj_clean(lv_obj_t *obj); - -/** - * Mark the object as invalid therefore its current position will be redrawn by - * 'lv_refr_task' - * @param obj pointer to an object - */ -void -lv_obj_invalidate(const lv_obj_t *obj); - -/*===================== - * Setter functions - *====================*/ - -/*-------------------- - * Parent/children set - *--------------------*/ - -/** - * Set a new parent for an object. Its relative position will be the same. - * @param obj pointer to an object. Can't be a screen. - * @param parent pointer to the new parent object. (Can't be NULL) - */ -void -lv_obj_set_parent(lv_obj_t *obj, lv_obj_t *parent); - -/** - * Move and object to the foreground - * @param obj pointer to an object - */ -void -lv_obj_move_foreground(lv_obj_t *obj); - -/** - * Move and object to the background - * @param obj pointer to an object - */ -void -lv_obj_move_background(lv_obj_t *obj); - -/*-------------------- - * Coordinate set - * ------------------*/ - -/** - * Set relative the position of an object (relative to the parent) - * @param obj pointer to an object - * @param x new distance from the left side of the parent - * @param y new distance from the top of the parent - */ -void -lv_obj_set_pos(lv_obj_t *obj, lv_coord_t x, lv_coord_t y); - -/** - * Set the x coordinate of a object - * @param obj pointer to an object - * @param x new distance from the left side from the parent - */ -void -lv_obj_set_x(lv_obj_t *obj, lv_coord_t x); - -/** - * Set the y coordinate of a object - * @param obj pointer to an object - * @param y new distance from the top of the parent - */ -void -lv_obj_set_y(lv_obj_t *obj, lv_coord_t y); - -/** - * Set the size of an object - * @param obj pointer to an object - * @param w new width - * @param h new height - */ -void -lv_obj_set_size(lv_obj_t *obj, lv_coord_t w, lv_coord_t h); - -/** - * Set the width of an object - * @param obj pointer to an object - * @param w new width - */ -void -lv_obj_set_width(lv_obj_t *obj, lv_coord_t w); - -/** - * Set the height of an object - * @param obj pointer to an object - * @param h new height - */ -void -lv_obj_set_height(lv_obj_t *obj, lv_coord_t h); - -/** - * Align an object to an other object. - * @param obj pointer to an object to align - * @param base pointer to an object (if NULL the parent is used). 'obj' will be - * aligned to it. - * @param align type of alignment (see 'lv_align_t' enum) - * @param x_mod x coordinate shift after alignment - * @param y_mod y coordinate shift after alignment - */ -void -lv_obj_align(lv_obj_t *obj, const lv_obj_t *base, lv_align_t align, - lv_coord_t x_mod, lv_coord_t y_mod); - -/** - * Align an object to an other object. - * @param obj pointer to an object to align - * @param base pointer to an object (if NULL the parent is used). 'obj' will be - * aligned to it. - * @param align type of alignment (see 'lv_align_t' enum) - * @param x_mod x coordinate shift after alignment - * @param y_mod y coordinate shift after alignment - */ -void -lv_obj_align_origo(lv_obj_t *obj, const lv_obj_t *base, lv_align_t align, - lv_coord_t x_mod, lv_coord_t y_mod); - -/** - * Realign the object based on the last `lv_obj_align` parameters. - * @param obj pointer to an object - */ -void -lv_obj_realign(lv_obj_t *obj); - -/** - * Enable the automatic realign of the object when its size has changed based on - * the last `lv_obj_align` parameters. - * @param obj pointer to an object - * @param en true: enable auto realign; false: disable auto realign - */ -void -lv_obj_set_auto_realign(lv_obj_t *obj, bool en); - -/** - * Set the size of an extended clickable area - * @param obj pointer to an object - * @param left extended clickable are on the left [px] - * @param right extended clickable are on the right [px] - * @param top extended clickable are on the top [px] - * @param bottom extended clickable are on the bottom [px] - */ -void -lv_obj_set_ext_click_area(lv_obj_t *obj, lv_coord_t left, lv_coord_t right, - lv_coord_t top, lv_coord_t bottom); - -/*--------------------- - * Appearance set - *--------------------*/ - -/** - * Set a new style for an object - * @param obj pointer to an object - * @param style_p pointer to the new style - */ -void -lv_obj_set_style(lv_obj_t *obj, const lv_style_t *style); - -/** - * Notify an object about its style is modified - * @param obj pointer to an object - */ -void -lv_obj_refresh_style(lv_obj_t *obj); - -/** - * Notify all object if a style is modified - * @param style pointer to a style. Only the objects with this style will be - * notified (NULL to notify all objects) - */ -void -lv_obj_report_style_mod(lv_style_t *style); - -/*----------------- - * Attribute set - *----------------*/ - -/** - * Hide an object. It won't be visible and clickable. - * @param obj pointer to an object - * @param en true: hide the object - */ -void -lv_obj_set_hidden(lv_obj_t *obj, bool en); - -/** - * Enable or disable the clicking of an object - * @param obj pointer to an object - * @param en true: make the object clickable - */ -void -lv_obj_set_click(lv_obj_t *obj, bool en); - -/** - * Enable to bring this object to the foreground if it - * or any of its children is clicked - * @param obj pointer to an object - * @param en true: enable the auto top feature - */ -void -lv_obj_set_top(lv_obj_t *obj, bool en); - -/** - * Enable the dragging of an object - * @param obj pointer to an object - * @param en true: make the object dragable - */ -void -lv_obj_set_drag(lv_obj_t *obj, bool en); - -/** - * Set the directions an object can be dragged in - * @param obj pointer to an object - * @param drag_dir bitwise OR of allowed drag directions - */ -void -lv_obj_set_drag_dir(lv_obj_t *obj, lv_drag_dir_t drag_dir); - -/** - * Enable the throwing of an object after is is dragged - * @param obj pointer to an object - * @param en true: enable the drag throw - */ -void -lv_obj_set_drag_throw(lv_obj_t *obj, bool en); - -/** - * Enable to use parent for drag related operations. - * If trying to drag the object the parent will be moved instead - * @param obj pointer to an object - * @param en true: enable the 'drag parent' for the object - */ -void -lv_obj_set_drag_parent(lv_obj_t *obj, bool en); - -/** - * Propagate the events to the parent too - * @param obj pointer to an object - * @param en true: enable the event propagation - */ -void -lv_obj_set_parent_event(lv_obj_t *obj, bool en); - -/** - * Set the opa scale enable parameter (required to set opa_scale with - * `lv_obj_set_opa_scale()`) - * @param obj pointer to an object - * @param en true: opa scaling is enabled for this object and all children; - * false: no opa scaling - */ -void -lv_obj_set_opa_scale_enable(lv_obj_t *obj, bool en); - -/** - * Set the opa scale of an object. - * The opacity of this object and all it's children will be scaled down with - * this factor. `lv_obj_set_opa_scale_enable(obj, true)` needs to be called to - * enable it. (not for all children just for the parent where to start the opa - * scaling) - * @param obj pointer to an object - * @param opa_scale a factor to scale down opacity [0..255] - */ -void -lv_obj_set_opa_scale(lv_obj_t *obj, lv_opa_t opa_scale); - -/** - * Set a bit or bits in the protect filed - * @param obj pointer to an object - * @param prot 'OR'-ed values from `lv_protect_t` - */ -void -lv_obj_set_protect(lv_obj_t *obj, uint8_t prot); - -/** - * Clear a bit or bits in the protect filed - * @param obj pointer to an object - * @param prot 'OR'-ed values from `lv_protect_t` - */ -void -lv_obj_clear_protect(lv_obj_t *obj, uint8_t prot); - -/** - * Set a an event handler function for an object. - * Used by the user to react on event which happens with the object. - * @param obj pointer to an object - * @param event_cb the new event function - */ -void -lv_obj_set_event_cb(lv_obj_t *obj, lv_event_cb_t event_cb); - -/** - * Send an event to the object - * @param obj pointer to an object - * @param event the type of the event from `lv_event_t`. - * @param data arbitrary data depending on the object type and the event. - * (Usually `NULL`) - * @return LV_RES_OK: `obj` was not deleted in the event; LV_RES_INV: `obj` - * was deleted in the event - */ -lv_res_t -lv_event_send(lv_obj_t *obj, lv_event_t event, const void *data); - -/** - * Call an event function with an object, event, and data. - * @param event_xcb an event callback function. If `NULL` `LV_RES_OK` will - * return without any actions. (the 'x' in the argument name indicates - * that its not a fully generic function because it not follows the - * `func_name(object, callback, ...)` convention) - * @param obj pointer to an object to associate with the event (can be `NULL` - * to simply call the `event_cb`) - * @param event an event - * @param data pointer to a custom data - * @return LV_RES_OK: `obj` was not deleted in the event; LV_RES_INV: `obj` - * was deleted in the event - */ -lv_res_t -lv_event_send_func(lv_event_cb_t event_xcb, lv_obj_t *obj, lv_event_t event, - const void *data); - -/** - * Get the `data` parameter of the current event - * @return the `data` parameter - */ -const void * -lv_event_get_data(void); - -/** - * Set the a signal function of an object. Used internally by the library. - * Always call the previous signal function in the new. - * @param obj pointer to an object - * @param signal_cb the new signal function - */ -void -lv_obj_set_signal_cb(lv_obj_t *obj, lv_signal_cb_t signal_cb); - -/** - * Send an event to the object - * @param obj pointer to an object - * @param event the type of the event from `lv_event_t`. - */ -void -lv_signal_send(lv_obj_t *obj, lv_signal_t signal, void *param); - -/** - * Set a new design function for an object - * @param obj pointer to an object - * @param design_cb the new design function - */ -void -lv_obj_set_design_cb(lv_obj_t *obj, lv_design_cb_t design_cb); - -/*---------------- - * Other set - *--------------*/ - -/** - * Allocate a new ext. data for an object - * @param obj pointer to an object - * @param ext_size the size of the new ext. data - * @return pointer to the allocated ext - */ -void * -lv_obj_allocate_ext_attr(lv_obj_t *obj, uint16_t ext_size); - -/** - * Send a 'LV_SIGNAL_REFR_EXT_SIZE' signal to the object - * @param obj pointer to an object - */ -void -lv_obj_refresh_ext_draw_pad(lv_obj_t *obj); - -/*======================= - * Getter functions - *======================*/ - -/** - * Return with the screen of an object - * @param obj pointer to an object - * @return pointer to a screen - */ -lv_obj_t * -lv_obj_get_screen(const lv_obj_t *obj); - -/** - * Get the display of an object - * @param scr pointer to an object - * @return pointer the object's display - */ -lv_disp_t * -lv_obj_get_disp(const lv_obj_t *obj); - -/*--------------------- - * Parent/children get - *--------------------*/ - -/** - * Returns with the parent of an object - * @param obj pointer to an object - * @return pointer to the parent of 'obj' - */ -lv_obj_t * -lv_obj_get_parent(const lv_obj_t *obj); - -/** - * Iterate through the children of an object (start from the "youngest, lastly - * created") - * @param obj pointer to an object - * @param child NULL at first call to get the next children - * and the previous return value later - * @return the child after 'act_child' or NULL if no more child - */ -lv_obj_t * -lv_obj_get_child(const lv_obj_t *obj, const lv_obj_t *child); - -/** - * Iterate through the children of an object (start from the "oldest", firstly - * created) - * @param obj pointer to an object - * @param child NULL at first call to get the next children - * and the previous return value later - * @return the child after 'act_child' or NULL if no more child - */ -lv_obj_t * -lv_obj_get_child_back(const lv_obj_t *obj, const lv_obj_t *child); - -/** - * Count the children of an object (only children directly on 'obj') - * @param obj pointer to an object - * @return children number of 'obj' - */ -uint16_t -lv_obj_count_children(const lv_obj_t *obj); - -/** Recursively count the children of an object - * @param obj pointer to an object - * @return children number of 'obj' - */ -uint16_t -lv_obj_count_children_recursive(const lv_obj_t *obj); - -/*--------------------- - * Coordinate get - *--------------------*/ - -/** - * Copy the coordinates of an object to an area - * @param obj pointer to an object - * @param cords_p pointer to an area to store the coordinates - */ -void -lv_obj_get_coords(const lv_obj_t *obj, lv_area_t *cords_p); - -/** - * Reduce area retried by `lv_obj_get_coords()` the get graphically usable area - * of an object. (Without the size of the border or other extra graphical - * elements) - * @param coords_p store the result area here - */ -void -lv_obj_get_inner_coords(const lv_obj_t *obj, lv_area_t *coords_p); - -/** - * Get the x coordinate of object - * @param obj pointer to an object - * @return distance of 'obj' from the left side of its parent - */ -lv_coord_t -lv_obj_get_x(const lv_obj_t *obj); - -/** - * Get the y coordinate of object - * @param obj pointer to an object - * @return distance of 'obj' from the top of its parent - */ -lv_coord_t -lv_obj_get_y(const lv_obj_t *obj); - -/** - * Get the width of an object - * @param obj pointer to an object - * @return the width - */ -lv_coord_t -lv_obj_get_width(const lv_obj_t *obj); - -/** - * Get the height of an object - * @param obj pointer to an object - * @return the height - */ -lv_coord_t -lv_obj_get_height(const lv_obj_t *obj); - -/** - * Get that width reduced by the left and right padding. - * @param obj pointer to an object - * @return the width which still fits into the container - */ -lv_coord_t -lv_obj_get_width_fit(lv_obj_t *obj); - -/** - * Get that height reduced by the top an bottom padding. - * @param obj pointer to an object - * @return the height which still fits into the container - */ -lv_coord_t -lv_obj_get_height_fit(lv_obj_t *obj); - -/** - * Get the automatic realign property of the object. - * @param obj pointer to an object - * @return true: auto realign is enabled; false: auto realign is disabled - */ -bool -lv_obj_get_auto_realign(lv_obj_t *obj); - -/** - * Get the left padding of extended clickable area - * @param obj pointer to an object - * @return the extended left padding - */ -lv_coord_t -lv_obj_get_ext_click_pad_left(const lv_obj_t *obj); - -/** - * Get the right padding of extended clickable area - * @param obj pointer to an object - * @return the extended right padding - */ -lv_coord_t -lv_obj_get_ext_click_pad_right(const lv_obj_t *obj); - -/** - * Get the top padding of extended clickable area - * @param obj pointer to an object - * @return the extended top padding - */ -lv_coord_t -lv_obj_get_ext_click_pad_top(const lv_obj_t *obj); - -/** - * Get the bottom padding of extended clickable area - * @param obj pointer to an object - * @return the extended bottom padding - */ -lv_coord_t -lv_obj_get_ext_click_pad_bottom(const lv_obj_t *obj); - -/** - * Get the extended size attribute of an object - * @param obj pointer to an object - * @return the extended size attribute - */ -lv_coord_t -lv_obj_get_ext_draw_pad(const lv_obj_t *obj); - -/*----------------- - * Appearance get - *---------------*/ - -/** - * Get the style pointer of an object (if NULL get style of the parent) - * @param obj pointer to an object - * @return pointer to a style - */ -const lv_style_t * -lv_obj_get_style(const lv_obj_t *obj); - -/*----------------- - * Attribute get - *----------------*/ - -/** - * Get the hidden attribute of an object - * @param obj pointer to an object - * @return true: the object is hidden - */ -bool -lv_obj_get_hidden(const lv_obj_t *obj); - -/** - * Get the click enable attribute of an object - * @param obj pointer to an object - * @return true: the object is clickable - */ -bool -lv_obj_get_click(const lv_obj_t *obj); - -/** - * Get the top enable attribute of an object - * @param obj pointer to an object - * @return true: the auto top feature is enabled - */ -bool -lv_obj_get_top(const lv_obj_t *obj); - -/** - * Get the drag enable attribute of an object - * @param obj pointer to an object - * @return true: the object is dragable - */ -bool -lv_obj_get_drag(const lv_obj_t *obj); - -/** - * Get the directions an object can be dragged - * @param obj pointer to an object - * @return bitwise OR of allowed directions an object can be dragged in - */ -lv_drag_dir_t -lv_obj_get_drag_dir(const lv_obj_t *obj); - -/** - * Get the drag throw enable attribute of an object - * @param obj pointer to an object - * @return true: drag throw is enabled - */ -bool -lv_obj_get_drag_throw(const lv_obj_t *obj); - -/** - * Get the drag parent attribute of an object - * @param obj pointer to an object - * @return true: drag parent is enabled - */ -bool -lv_obj_get_drag_parent(const lv_obj_t *obj); - -/** - * Get the drag parent attribute of an object - * @param obj pointer to an object - * @return true: drag parent is enabled - */ -bool -lv_obj_get_parent_event(const lv_obj_t *obj); - -/** - * Get the opa scale enable parameter - * @param obj pointer to an object - * @return true: opa scaling is enabled for this object and all children; false: - * no opa scaling - */ -lv_opa_t -lv_obj_get_opa_scale_enable(const lv_obj_t *obj); - -/** - * Get the opa scale parameter of an object - * @param obj pointer to an object - * @return opa scale [0..255] - */ -lv_opa_t -lv_obj_get_opa_scale(const lv_obj_t *obj); - -/** - * Get the protect field of an object - * @param obj pointer to an object - * @return protect field ('OR'ed values of `lv_protect_t`) - */ -uint8_t -lv_obj_get_protect(const lv_obj_t *obj); - -/** - * Check at least one bit of a given protect bitfield is set - * @param obj pointer to an object - * @param prot protect bits to test ('OR'ed values of `lv_protect_t`) - * @return false: none of the given bits are set, true: at least one bit is set - */ -bool -lv_obj_is_protected(const lv_obj_t *obj, uint8_t prot); - -/** - * Get the signal function of an object - * @param obj pointer to an object - * @return the signal function - */ -lv_signal_cb_t -lv_obj_get_signal_cb(const lv_obj_t *obj); - -/** - * Get the design function of an object - * @param obj pointer to an object - * @return the design function - */ -lv_design_cb_t -lv_obj_get_design_cb(const lv_obj_t *obj); - -/** - * Get the event function of an object - * @param obj pointer to an object - * @return the event function - */ -lv_event_cb_t -lv_obj_get_event_cb(const lv_obj_t *obj); - -/*------------------ - * Other get - *-----------------*/ - -/** - * Get the ext pointer - * @param obj pointer to an object - * @return the ext pointer but not the dynamic version - * Use it as ext->data1, and NOT da(ext)->data1 - */ -void * -lv_obj_get_ext_attr(const lv_obj_t *obj); - -/** - * Get object's and its ancestors type. Put their name in `type_buf` starting - * with the current type. E.g. buf.type[0]="lv_btn", buf.type[1]="lv_cont", - * buf.type[2]="lv_obj" - * @param obj pointer to an object which type should be get - * @param buf pointer to an `lv_obj_type_t` buffer to store the types - */ -void -lv_obj_get_type(lv_obj_t *obj, lv_obj_type_t *buf); - -#if LV_USE_USER_DATA -/** - * Get the object's user data - * @param obj pointer to an object - * @return user data - */ -lv_obj_user_data_t -lv_obj_get_user_data(lv_obj_t *obj); - -/** - * Get a pointer to the object's user data - * @param obj pointer to an object - * @return pointer to the user data - */ -lv_obj_user_data_t * -lv_obj_get_user_data_ptr(lv_obj_t *obj); - -/** - * Set the object's user data. The data will be copied. - * @param obj pointer to an object - * @param data user data - */ -void -lv_obj_set_user_data(lv_obj_t *obj, lv_obj_user_data_t data); - -#endif - -#if LV_USE_GROUP -/** - * Get the group of the object - * @param obj pointer to an object - * @return the pointer to group of the object - */ -void * -lv_obj_get_group(const lv_obj_t *obj); - -/** - * Tell whether the object is the focused object of a group or not. - * @param obj pointer to an object - * @return true: the object is focused, - * false: the object is not focused or not in a group - */ -bool -lv_obj_is_focused(const lv_obj_t *obj); - -#endif - -/********************** - * MACROS - **********************/ - -/** - * Helps to quickly declare an event callback function. - * Will be expanded to: `void (lv_obj_t * obj, lv_event_t e)` - * - * Examples: - * static LV_EVENT_CB_DECLARE(my_event1); //Protoype declaration - * - * static LV_EVENT_CB_DECLARE(my_event1) - * { - * if(e == LV_EVENT_CLICKED) { - * lv_obj_set_hidden(obj ,true); - * } - * } - */ -#define LV_EVENT_CB_DECLARE(name) void name(lv_obj_t *obj, lv_event_t e) - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /*LV_OBJ_H*/ diff --git a/core/app-framework/wgl/app/wa-inc/lvgl/lvgl.h b/core/app-framework/wgl/app/wa-inc/lvgl/lvgl.h deleted file mode 100644 index 7c4c7b2fe..000000000 --- a/core/app-framework/wgl/app/wa-inc/lvgl/lvgl.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef WAMR_GRAPHIC_LIBRARY_LVGL_COMPATIBLE_H -#define WAMR_GRAPHIC_LIBRARY_LVGL_COMPATIBLE_H - -#ifdef __cplusplus -extern "C" { -#endif - -//#include "bi-inc/wgl_shared_utils.h" /* shared types between app and native */ -/* -#include "lvgl-compatible/lv_types.h" -#include "lvgl-compatible/lv_obj.h" -#include "lvgl-compatible/lv_btn.h" -#include "lvgl-compatible/lv_cb.h" -#include "lvgl-compatible/lv_label.h" -#include "lvgl-compatible/lv_list.h" -*/ - -#include "src/lv_version.h" - -#include "src/lv_misc/lv_log.h" -#include "src/lv_misc/lv_task.h" -#include "src/lv_misc/lv_math.h" -//#include "src/lv_misc/lv_async.h" - -//#include "src/lv_hal/lv_hal.h" - -#include "src/lv_core/lv_obj.h" -#include "src/lv_core/lv_group.h" - -#include "src/lv_core/lv_refr.h" -#include "src/lv_core/lv_disp.h" - -#include "src/lv_themes/lv_theme.h" - -#include "src/lv_font/lv_font.h" -#include "src/lv_font/lv_font_fmt_txt.h" - -#include "src/lv_objx/lv_btn.h" -#include "src/lv_objx/lv_imgbtn.h" -#include "src/lv_objx/lv_img.h" -#include "src/lv_objx/lv_label.h" -#include "src/lv_objx/lv_line.h" -#include "src/lv_objx/lv_page.h" -#include "src/lv_objx/lv_cont.h" -#include "src/lv_objx/lv_list.h" -#include "src/lv_objx/lv_chart.h" -#include "src/lv_objx/lv_table.h" -#include "src/lv_objx/lv_cb.h" -#include "src/lv_objx/lv_bar.h" -#include "src/lv_objx/lv_slider.h" -#include "src/lv_objx/lv_led.h" -#include "src/lv_objx/lv_btnm.h" -#include "src/lv_objx/lv_kb.h" -#include "src/lv_objx/lv_ddlist.h" -#include "src/lv_objx/lv_roller.h" -#include "src/lv_objx/lv_ta.h" -#include "src/lv_objx/lv_canvas.h" -#include "src/lv_objx/lv_win.h" -#include "src/lv_objx/lv_tabview.h" -#include "src/lv_objx/lv_tileview.h" -#include "src/lv_objx/lv_mbox.h" -#include "src/lv_objx/lv_gauge.h" -#include "src/lv_objx/lv_lmeter.h" -#include "src/lv_objx/lv_sw.h" -#include "src/lv_objx/lv_kb.h" -#include "src/lv_objx/lv_arc.h" -#include "src/lv_objx/lv_preload.h" -#include "src/lv_objx/lv_calendar.h" -#include "src/lv_objx/lv_spinbox.h" - -#include "src/lv_draw/lv_img_cache.h" - -#ifdef __cplusplus -} -#endif - -#endif /* WAMR_GRAPHIC_LIBRARY_LVGL_COMPATIBLE_H */ diff --git a/core/app-framework/wgl/app/wa-inc/lvgl/test.c b/core/app-framework/wgl/app/wa-inc/lvgl/test.c deleted file mode 100644 index 2262aa551..000000000 --- a/core/app-framework/wgl/app/wa-inc/lvgl/test.c +++ /dev/null @@ -1,9 +0,0 @@ -#include "lvgl.h" - -int -main() - -{ - - return 0; -} diff --git a/core/app-framework/wgl/app/wasm_app.cmake b/core/app-framework/wgl/app/wasm_app.cmake deleted file mode 100644 index f01be9ff6..000000000 --- a/core/app-framework/wgl/app/wasm_app.cmake +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -set (WASM_APP_GUI_DIR ${CMAKE_CURRENT_LIST_DIR}) - -set (DEPS_DIR ${WASM_APP_GUI_DIR}/../../../deps) - -if (NOT EXISTS "${DEPS_DIR}/lvgl") - message (FATAL_ERROR "Can not find third party dependency: ${DEPS_DIR}/lvgl") -endif () - -include_directories(${WASM_APP_GUI_DIR} - ${DEPS_DIR} - ${DEPS_DIR}/lvgl - ${DEPS_DIR}/lvgl/src) - -file (GLOB_RECURSE source_all ${WASM_APP_GUI_DIR}/src/*.c) - -set (WASM_APP_CURRENT_SOURCE ${source_all}) diff --git a/core/app-framework/wgl/native/gui_native_api.h b/core/app-framework/wgl/native/gui_native_api.h deleted file mode 100644 index ee91b0eaa..000000000 --- a/core/app-framework/wgl/native/gui_native_api.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _GUI_API_H_ -#define _GUI_API_H_ - -#include "bh_platform.h" -#include "wasm_export.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * gui interfaces - */ - -void -wasm_obj_native_call(wasm_exec_env_t exec_env, int32 func_id, uint32 *argv, - uint32 argc); - -void -wasm_btn_native_call(wasm_exec_env_t exec_env, int32 func_id, uint32 *argv, - uint32 argc); - -void -wasm_label_native_call(wasm_exec_env_t exec_env, int32 func_id, uint32 *argv, - uint32 argc); - -void -wasm_cb_native_call(wasm_exec_env_t exec_env, int32 func_id, uint32 *argv, - uint32 argc); - -void -wasm_list_native_call(wasm_exec_env_t exec_env, int32 func_id, uint32 *argv, - uint32 argc); - -#ifdef __cplusplus -} -#endif - -#endif /* end of _GUI_API_H_ */ diff --git a/core/app-framework/wgl/native/wamr_gui.inl b/core/app-framework/wgl/native/wamr_gui.inl deleted file mode 100644 index c7855b17b..000000000 --- a/core/app-framework/wgl/native/wamr_gui.inl +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -/* button */ -EXPORT_WASM_API_WITH_SIG(wasm_btn_native_call, "(i*i)"), - -/* obj */ -EXPORT_WASM_API_WITH_SIG(wasm_obj_native_call, "(i*i)"), - -/* label */ -EXPORT_WASM_API_WITH_SIG(wasm_label_native_call, "(i*i)"), - -/* cont */ -//EXPORT_WASM_API_WITH_SIG(wasm_cont_native_call, "(i*i)"), - -/* page */ -//EXPORT_WASM_API_WITH_SIG(wasm_page_native_call, "(i*i)"), - -/* list */ -EXPORT_WASM_API_WITH_SIG(wasm_list_native_call, "(i*i)"), - -/* drop down list */ -//EXPORT_WASM_API_WITH_SIG(wasm_ddlist_native_call, "(i*i)"), - -/* check box */ -EXPORT_WASM_API_WITH_SIG(wasm_cb_native_call, "(i*i)"), diff --git a/core/app-framework/wgl/native/wasm_lib.cmake b/core/app-framework/wgl/native/wasm_lib.cmake deleted file mode 100644 index b452fb114..000000000 --- a/core/app-framework/wgl/native/wasm_lib.cmake +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -set (WASM_LIB_GUI_DIR ${CMAKE_CURRENT_LIST_DIR}) - -set (DEPS_DIR ${WASM_LIB_GUI_DIR}/../../../deps) - -add_definitions(-DLV_CONF_INCLUDE_SIMPLE) -add_definitions (-DAPP_FRAMEWORK_WGL) - -include_directories(${WASM_LIB_GUI_DIR} - ${DEPS_DIR} - ${DEPS_DIR}/lvgl - ${DEPS_DIR}/lvgl/src) - -file (GLOB_RECURSE lvgl_source ${DEPS_DIR}/lvgl/*.c) -file (GLOB_RECURSE wrapper_source ${WASM_LIB_GUI_DIR}/*.c) - -set (WASM_APP_LIB_CURRENT_SOURCE ${wrapper_source} ${lvgl_source}) diff --git a/core/app-framework/wgl/native/wgl.h b/core/app-framework/wgl/native/wgl.h deleted file mode 100644 index ad5843115..000000000 --- a/core/app-framework/wgl/native/wgl.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef WAMR_GRAPHIC_LIBRARY_H -#define WAMR_GRAPHIC_LIBRARY_H - -#ifdef __cplusplus -extern "C" { -#endif - -void -wgl_init(void); -void -wgl_exit(void); - -#ifdef __cplusplus -} -#endif - -#endif /* WAMR_GRAPHIC_LIBRARY_H */ diff --git a/core/app-framework/wgl/native/wgl_btn_wrapper.c b/core/app-framework/wgl/native/wgl_btn_wrapper.c deleted file mode 100644 index 4c3a23239..000000000 --- a/core/app-framework/wgl/native/wgl_btn_wrapper.c +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "native_interface.h" -#include "lvgl.h" -#include "module_wasm_app.h" -#include "wgl_native_utils.h" - -/* ------------------------------------------------------------------------- - * Button widget native function wrappers - * -------------------------------------------------------------------------*/ -DEFINE_WGL_NATIVE_WRAPPER(lv_btn_create_wrapper) -{ - int32 res; - wgl_native_return_type(int32); - wgl_native_get_arg(uint32, par_obj_id); - wgl_native_get_arg(uint32, copy_obj_id); - wasm_module_inst_t module_inst = get_module_inst(exec_env); - - res = wgl_native_wigdet_create(WIDGET_TYPE_BTN, par_obj_id, copy_obj_id, - module_inst); - wgl_native_set_return(res); -} - -DEFINE_WGL_NATIVE_WRAPPER(lv_btn_set_toggle_wrapper) -{ - wgl_native_get_arg(lv_obj_t *, btn); - wgl_native_get_arg(bool, tgl); - - (void)exec_env; - lv_btn_set_toggle(btn, tgl); -} - -DEFINE_WGL_NATIVE_WRAPPER(lv_btn_set_state_wrapper) -{ - wgl_native_get_arg(lv_obj_t *, btn); - wgl_native_get_arg(lv_btn_state_t, state); - - (void)exec_env; - lv_btn_set_state(btn, state); -} - -DEFINE_WGL_NATIVE_WRAPPER(lv_btn_set_ink_in_time_wrapper) -{ - wgl_native_get_arg(lv_obj_t *, btn); - wgl_native_get_arg(uint16_t, time); - - (void)exec_env; - lv_btn_set_ink_in_time(btn, time); -} - -DEFINE_WGL_NATIVE_WRAPPER(lv_btn_set_ink_out_time_wrapper) -{ - wgl_native_get_arg(lv_obj_t *, btn); - wgl_native_get_arg(uint16_t, time); - - (void)exec_env; - lv_btn_set_ink_out_time(btn, time); -} - -DEFINE_WGL_NATIVE_WRAPPER(lv_btn_set_ink_wait_time_wrapper) -{ - wgl_native_get_arg(lv_obj_t *, btn); - wgl_native_get_arg(uint16_t, time); - - (void)exec_env; - lv_btn_set_ink_wait_time(btn, time); -} - -DEFINE_WGL_NATIVE_WRAPPER(lv_btn_get_ink_in_time_wrapper) -{ - uint16_t res; - wgl_native_return_type(uint16_t); - wgl_native_get_arg(lv_obj_t *, btn); - - (void)exec_env; - res = lv_btn_get_ink_in_time(btn); - wgl_native_set_return(res); -} - -DEFINE_WGL_NATIVE_WRAPPER(lv_btn_get_ink_out_time_wrapper) -{ - uint16_t res; - wgl_native_return_type(uint16_t); - wgl_native_get_arg(lv_obj_t *, btn); - - (void)exec_env; - res = lv_btn_get_ink_out_time(btn); - wgl_native_set_return(res); -} - -DEFINE_WGL_NATIVE_WRAPPER(lv_btn_get_ink_wait_time_wrapper) -{ - uint16_t res; - wgl_native_return_type(uint16_t); - wgl_native_get_arg(lv_obj_t *, btn); - - (void)exec_env; - res = lv_btn_get_ink_wait_time(btn); - wgl_native_set_return(res); -} - -DEFINE_WGL_NATIVE_WRAPPER(lv_btn_get_state_wrapper) -{ - lv_btn_state_t res; - wgl_native_return_type(lv_btn_state_t); - wgl_native_get_arg(lv_obj_t *, btn); - - (void)exec_env; - res = lv_btn_get_state(btn); - wgl_native_set_return(res); -} - -DEFINE_WGL_NATIVE_WRAPPER(lv_btn_get_toggle_wrapper) -{ - bool res; - wgl_native_return_type(bool); - wgl_native_get_arg(lv_obj_t *, btn); - - (void)exec_env; - res = lv_btn_get_toggle(btn); - wgl_native_set_return(res); -} - -DEFINE_WGL_NATIVE_WRAPPER(lv_btn_toggle_wrapper) -{ - wgl_native_get_arg(lv_obj_t *, btn); - - (void)exec_env; - lv_btn_toggle(btn); -} - -/* clang-format off */ -static WGLNativeFuncDef btn_native_func_defs[] = { - { BTN_FUNC_ID_CREATE, lv_btn_create_wrapper, 2, false }, - { BTN_FUNC_ID_SET_TOGGLE, lv_btn_set_toggle_wrapper, 2, true }, - { BTN_FUNC_ID_SET_STATE, lv_btn_set_state_wrapper, 2, true }, - { BTN_FUNC_ID_SET_INK_IN_TIME, lv_btn_set_ink_in_time_wrapper, 2, true }, - { BTN_FUNC_ID_SET_INK_OUT_TIME, lv_btn_set_ink_out_time_wrapper, 2, true }, - { BTN_FUNC_ID_SET_INK_WAIT_TIME, lv_btn_set_ink_wait_time_wrapper, 2, true }, - { BTN_FUNC_ID_GET_INK_IN_TIME, lv_btn_get_ink_in_time_wrapper, 1, true }, - { BTN_FUNC_ID_GET_INK_OUT_TIME, lv_btn_get_ink_out_time_wrapper, 1, true }, - { BTN_FUNC_ID_GET_INK_WAIT_TIME, lv_btn_get_ink_wait_time_wrapper, 1, true }, - { BTN_FUNC_ID_GET_STATE, lv_btn_get_state_wrapper, 1, true }, - { BTN_FUNC_ID_GET_TOGGLE, lv_btn_get_toggle_wrapper, 1, true }, - { BTN_FUNC_ID_TOGGLE, lv_btn_toggle_wrapper, 1, true }, -}; -/* clang-format on */ - -/*************** Native Interface to Wasm App ***********/ -void -wasm_btn_native_call(wasm_exec_env_t exec_env, int32 func_id, uint32 *argv, - uint32 argc) -{ - uint32 size = sizeof(btn_native_func_defs) / sizeof(WGLNativeFuncDef); - - wgl_native_func_call(exec_env, btn_native_func_defs, size, func_id, argv, - argc); -} diff --git a/core/app-framework/wgl/native/wgl_cb_wrapper.c b/core/app-framework/wgl/native/wgl_cb_wrapper.c deleted file mode 100644 index 51510b997..000000000 --- a/core/app-framework/wgl/native/wgl_cb_wrapper.c +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "lvgl.h" -#include "wasm_export.h" -#include "native_interface.h" -#include "module_wasm_app.h" -#include "wgl_native_utils.h" - -/* ------------------------------------------------------------------------- - * Label widget native function wrappers - * -------------------------------------------------------------------------*/ -DEFINE_WGL_NATIVE_WRAPPER(lv_cb_create_wrapper) -{ - int32 res; - wgl_native_return_type(int32); - wgl_native_get_arg(uint32, par_obj_id); - wgl_native_get_arg(uint32, copy_obj_id); - wasm_module_inst_t module_inst = get_module_inst(exec_env); - - res = wgl_native_wigdet_create(WIDGET_TYPE_CB, par_obj_id, copy_obj_id, - module_inst); - wgl_native_set_return(res); -} - -DEFINE_WGL_NATIVE_WRAPPER(lv_cb_set_text_wrapper) -{ - char *text; - wgl_native_get_arg(lv_obj_t *, cb); - wgl_native_get_arg(uint32, text_offset); - wgl_native_get_arg(uint32, text_len); - wasm_module_inst_t module_inst = get_module_inst(exec_env); - - if (!validate_app_addr(text_offset, text_len) - || !(text = addr_app_to_native(text_offset))) - return; - - lv_cb_set_text(cb, text); -} - -DEFINE_WGL_NATIVE_WRAPPER(lv_cb_set_static_text_wrapper) -{ - char *text; - wgl_native_get_arg(lv_obj_t *, cb); - wgl_native_get_arg(uint32, text_offset); - wgl_native_get_arg(uint32, text_len); - wasm_module_inst_t module_inst = get_module_inst(exec_env); - - if (!validate_app_addr(text_offset, text_len) - || !(text = addr_app_to_native(text_offset))) - return; - - lv_cb_set_static_text(cb, text); -} - -DEFINE_WGL_NATIVE_WRAPPER(lv_cb_get_text_length_wrapper) -{ - const char *text; - wgl_native_return_type(int32); - wgl_native_get_arg(lv_obj_t *, cb); - - (void)exec_env; - - text = lv_cb_get_text(cb); - wgl_native_set_return(text ? strlen(text) : 0); -} - -DEFINE_WGL_NATIVE_WRAPPER(lv_cb_get_text_wrapper) -{ - const char *text; - char *buffer; - wgl_native_return_type(uint32); - wgl_native_get_arg(lv_obj_t *, cb); - wgl_native_get_arg(uint32, buffer_offset); - wgl_native_get_arg(int, buffer_len); - wasm_module_inst_t module_inst = get_module_inst(exec_env); - - if (!validate_app_addr(buffer_offset, buffer_len) - || !(buffer = addr_app_to_native(buffer_offset))) - return; - - if ((text = lv_cb_get_text(cb))) { - strncpy(buffer, text, buffer_len - 1); - buffer[buffer_len - 1] = '\0'; - } - - wgl_native_set_return(buffer_offset); -} - -static WGLNativeFuncDef cb_native_func_defs[] = { - { CB_FUNC_ID_CREATE, lv_cb_create_wrapper, 2, false }, - { CB_FUNC_ID_SET_TEXT, lv_cb_set_text_wrapper, 3, true }, - { CB_FUNC_ID_SET_STATIC_TEXT, lv_cb_set_static_text_wrapper, 3, true }, - { CB_FUNC_ID_GET_TEXT_LENGTH, lv_cb_get_text_length_wrapper, 1, true }, - { CB_FUNC_ID_GET_TEXT, lv_cb_get_text_wrapper, 3, true }, -}; - -/*************** Native Interface to Wasm App ***********/ -void -wasm_cb_native_call(wasm_exec_env_t exec_env, int32 func_id, uint32 *argv, - uint32 argc) -{ - uint32 size = sizeof(cb_native_func_defs) / sizeof(WGLNativeFuncDef); - - wgl_native_func_call(exec_env, cb_native_func_defs, size, func_id, argv, - argc); -} diff --git a/core/app-framework/wgl/native/wgl_cont_wrapper.c b/core/app-framework/wgl/native/wgl_cont_wrapper.c deleted file mode 100644 index 70eeb0f48..000000000 --- a/core/app-framework/wgl/native/wgl_cont_wrapper.c +++ /dev/null @@ -1,7 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "lvgl.h" -#include "module_wasm_app.h" diff --git a/core/app-framework/wgl/native/wgl_label_wrapper.c b/core/app-framework/wgl/native/wgl_label_wrapper.c deleted file mode 100644 index dbdefec14..000000000 --- a/core/app-framework/wgl/native/wgl_label_wrapper.c +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "lvgl.h" -#include "wasm_export.h" -#include "native_interface.h" -#include "module_wasm_app.h" -#include "wgl_native_utils.h" - -/* ------------------------------------------------------------------------- - * Label widget native function wrappers - * -------------------------------------------------------------------------*/ -DEFINE_WGL_NATIVE_WRAPPER(lv_label_create_wrapper) -{ - int32 res; - wgl_native_return_type(int32); - wgl_native_get_arg(uint32, par_obj_id); - wgl_native_get_arg(uint32, copy_obj_id); - wasm_module_inst_t module_inst = get_module_inst(exec_env); - - res = wgl_native_wigdet_create(WIDGET_TYPE_LABEL, par_obj_id, copy_obj_id, - module_inst); - wgl_native_set_return(res); -} - -DEFINE_WGL_NATIVE_WRAPPER(lv_label_set_text_wrapper) -{ - char *text; - wgl_native_get_arg(lv_obj_t *, label); - wgl_native_get_arg(uint32, text_offset); - wgl_native_get_arg(uint32, text_len); - wasm_module_inst_t module_inst = get_module_inst(exec_env); - - if (!validate_app_addr(text_offset, text_len) - || !(text = addr_app_to_native(text_offset))) - return; - - lv_label_set_text(label, text); -} - -DEFINE_WGL_NATIVE_WRAPPER(lv_label_get_text_length_wrapper) -{ - wgl_native_return_type(int32); - wgl_native_get_arg(lv_obj_t *, label); - const char *text; - - (void)exec_env; - - text = lv_label_get_text(label); - wgl_native_set_return(text ? strlen(text) : 0); -} - -DEFINE_WGL_NATIVE_WRAPPER(lv_label_get_text_wrapper) -{ - const char *text; - char *buffer; - wgl_native_return_type(uint32); - wgl_native_get_arg(lv_obj_t *, label); - wgl_native_get_arg(uint32, buffer_offset); - wgl_native_get_arg(int, buffer_len); - wasm_module_inst_t module_inst = get_module_inst(exec_env); - - if (!validate_app_addr(buffer_offset, buffer_len) - || !(buffer = addr_app_to_native(buffer_offset))) - return; - - if ((text = lv_label_get_text(label))) { - strncpy(buffer, text, buffer_len - 1); - buffer[buffer_len - 1] = '\0'; - } - - wgl_native_set_return(buffer_offset); -} - -/* clang-format off */ -static WGLNativeFuncDef label_native_func_defs[] = { - { LABEL_FUNC_ID_CREATE, lv_label_create_wrapper, 2, false }, - { LABEL_FUNC_ID_SET_TEXT, lv_label_set_text_wrapper, 3, true }, - { LABEL_FUNC_ID_GET_TEXT_LENGTH, lv_label_get_text_length_wrapper, 1, true }, - { LABEL_FUNC_ID_GET_TEXT, lv_label_get_text_wrapper, 3, true }, -}; -/* clang-format on */ - -/*************** Native Interface to Wasm App ***********/ -void -wasm_label_native_call(wasm_exec_env_t exec_env, int32 func_id, uint32 *argv, - uint32 argc) -{ - uint32 size = sizeof(label_native_func_defs) / sizeof(WGLNativeFuncDef); - - wgl_native_func_call(exec_env, label_native_func_defs, size, func_id, argv, - argc); -} diff --git a/core/app-framework/wgl/native/wgl_list_wrapper.c b/core/app-framework/wgl/native/wgl_list_wrapper.c deleted file mode 100644 index c77f44930..000000000 --- a/core/app-framework/wgl/native/wgl_list_wrapper.c +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "native_interface.h" -#include "lvgl.h" -#include "module_wasm_app.h" -#include "wgl_native_utils.h" -#include "bh_assert.h" - -/* ------------------------------------------------------------------------- - * List widget native function wrappers - * -------------------------------------------------------------------------*/ -DEFINE_WGL_NATIVE_WRAPPER(lv_list_create_wrapper) -{ - int32 res; - wgl_native_return_type(int32); - wgl_native_get_arg(uint32, par_obj_id); - wgl_native_get_arg(uint32, copy_obj_id); - wasm_module_inst_t module_inst = get_module_inst(exec_env); - - res = wgl_native_wigdet_create(WIDGET_TYPE_LIST, par_obj_id, copy_obj_id, - module_inst); - wgl_native_set_return(res); -} - -DEFINE_WGL_NATIVE_WRAPPER(lv_list_add_btn_wrapper) -{ - wgl_native_return_type(int32); - wgl_native_get_arg(lv_obj_t *, list); - wgl_native_get_arg(uint32, text_offset); - wgl_native_get_arg(uint32, text_len); - uint32 btn_obj_id; - lv_obj_t *btn; - uint32 mod_id; - char *text; - wasm_module_inst_t module_inst = get_module_inst(exec_env); - - if (!validate_app_addr(text_offset, text_len) - || !(text = addr_app_to_native(text_offset))) - return; - - if (!(btn = lv_list_add_btn(list, NULL, text))) { - wasm_runtime_set_exception(module_inst, "add button to list fail."); - return; - } - - mod_id = app_manager_get_module_id(Module_WASM_App, module_inst); - bh_assert(mod_id != ID_NONE); - - if (!wgl_native_add_object(btn, mod_id, &btn_obj_id)) { - wasm_runtime_set_exception(module_inst, - "add button to object list fail."); - return; - } - - wgl_native_set_return(btn_obj_id); -} - -static WGLNativeFuncDef list_native_func_defs[] = { - { LIST_FUNC_ID_CREATE, lv_list_create_wrapper, 2, false }, - { LIST_FUNC_ID_ADD_BTN, lv_list_add_btn_wrapper, 3, true }, -}; - -/*************** Native Interface to Wasm App ***********/ -void -wasm_list_native_call(wasm_exec_env_t exec_env, int32 func_id, uint32 *argv, - uint32 argc) -{ - uint32 size = sizeof(list_native_func_defs) / sizeof(WGLNativeFuncDef); - - wgl_native_func_call(exec_env, list_native_func_defs, size, func_id, argv, - argc); -} diff --git a/core/app-framework/wgl/native/wgl_native_utils.c b/core/app-framework/wgl/native/wgl_native_utils.c deleted file mode 100644 index 6683fff97..000000000 --- a/core/app-framework/wgl/native/wgl_native_utils.c +++ /dev/null @@ -1,126 +0,0 @@ - - -#include "wgl_native_utils.h" -#include "lvgl.h" -#include "module_wasm_app.h" -#include "wasm_export.h" -#include "bh_assert.h" - -#include - -#define THROW_EXC(msg) wasm_runtime_set_exception(module_inst, msg); - -uint32 -wgl_native_wigdet_create(int8 widget_type, uint32 par_obj_id, - uint32 copy_obj_id, wasm_module_inst_t module_inst) -{ - uint32 obj_id; - lv_obj_t *wigdet = NULL, *par = NULL, *copy = NULL; - uint32 mod_id; - - // TODO: limit total widget number - - /* validate the parent object id if not equal to 0 */ - if (par_obj_id != 0 && !wgl_native_validate_object(par_obj_id, &par)) { - THROW_EXC("create widget with invalid parent object."); - return 0; - } - /* validate the copy object id if not equal to 0 */ - if (copy_obj_id != 0 && !wgl_native_validate_object(copy_obj_id, ©)) { - THROW_EXC("create widget with invalid copy object."); - return 0; - } - - if (par == NULL) - par = lv_disp_get_scr_act(NULL); - - if (widget_type == WIDGET_TYPE_BTN) - wigdet = lv_btn_create(par, copy); - else if (widget_type == WIDGET_TYPE_LABEL) - wigdet = lv_label_create(par, copy); - else if (widget_type == WIDGET_TYPE_CB) - wigdet = lv_cb_create(par, copy); - else if (widget_type == WIDGET_TYPE_LIST) - wigdet = lv_list_create(par, copy); - else if (widget_type == WIDGET_TYPE_DDLIST) - wigdet = lv_ddlist_create(par, copy); - - if (wigdet == NULL) - return 0; - - mod_id = app_manager_get_module_id(Module_WASM_App, module_inst); - bh_assert(mod_id != ID_NONE); - - if (wgl_native_add_object(wigdet, mod_id, &obj_id)) - return obj_id; /* success return */ - - return 0; -} - -void -wgl_native_func_call(wasm_exec_env_t exec_env, WGLNativeFuncDef *funcs, - uint32 size, int32 func_id, uint32 *argv, uint32 argc) -{ - typedef void (*WGLNativeFuncPtr)(wasm_exec_env_t, uint64 *, uint32 *); - WGLNativeFuncPtr wglNativeFuncPtr; - wasm_module_inst_t module_inst = get_module_inst(exec_env); - WGLNativeFuncDef *func_def = funcs; - WGLNativeFuncDef *func_def_end = func_def + size; - - /* Note: argv is validated in wasm_runtime_invoke_native() - * with pointer length equals to 1. Here validate the argv - * buffer again but with its total length in bytes */ - if (!wasm_runtime_validate_native_addr(module_inst, argv, - argc * sizeof(uint32))) - return; - - while (func_def < func_def_end) { - if (func_def->func_id == func_id && (uint32)func_def->arg_num == argc) { - uint64 argv_copy_buf[16], size; - uint64 *argv_copy = argv_copy_buf; - int i; - - if (argc > sizeof(argv_copy_buf) / sizeof(uint64)) { - size = sizeof(uint64) * (uint64)argc; - if (size >= UINT32_MAX - || !(argv_copy = wasm_runtime_malloc((uint32)size))) { - THROW_EXC("allocate memory failed."); - return; - } - memset(argv_copy, 0, (uint32)size); - } - - /* Init argv_copy */ - for (i = 0; i < func_def->arg_num; i++) - *(uint32 *)&argv_copy[i] = argv[i]; - - /* Validate the first argument which is a lvgl object if needed */ - if (func_def->check_obj) { - lv_obj_t *obj = NULL; - if (!wgl_native_validate_object(argv[0], &obj)) { - THROW_EXC("the object is invalid"); - goto fail; - } - *(lv_obj_t **)&argv_copy[0] = obj; - } - - wglNativeFuncPtr = (WGLNativeFuncPtr)func_def->func_ptr; - wglNativeFuncPtr(exec_env, argv_copy, argv); - - if (argv_copy != argv_copy_buf) - wasm_runtime_free(argv_copy); - - /* success return */ - return; - - fail: - if (argv_copy != argv_copy_buf) - wasm_runtime_free(argv_copy); - return; - } - - func_def++; - } - - THROW_EXC("the native widget function is not found!"); -} diff --git a/core/app-framework/wgl/native/wgl_native_utils.h b/core/app-framework/wgl/native/wgl_native_utils.h deleted file mode 100644 index f550dcc71..000000000 --- a/core/app-framework/wgl/native/wgl_native_utils.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef WAMR_GRAPHIC_LIBRARY_NATIVE_UTILS_H -#define WAMR_GRAPHIC_LIBRARY_NATIVE_UTILS_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include "bh_platform.h" -#include "lvgl.h" -#include "wasm_export.h" -#include "bi-inc/wgl_shared_utils.h" - -#define wgl_native_return_type(type) type *wgl_ret = (type *)(args_ret) -#define wgl_native_get_arg(type, name) type name = *((type *)(args++)) -#define wgl_native_set_return(val) *wgl_ret = (val) - -#define DEFINE_WGL_NATIVE_WRAPPER(func_name) \ - static void func_name(wasm_exec_env_t exec_env, uint64 *args, \ - uint32 *args_ret) - -enum { - WIDGET_TYPE_BTN, - WIDGET_TYPE_LABEL, - WIDGET_TYPE_CB, - WIDGET_TYPE_LIST, - WIDGET_TYPE_DDLIST, - - _WIDGET_TYPE_NUM, -}; - -typedef struct WGLNativeFuncDef { - /* Function id */ - int32 func_id; - - /* Native function pointer */ - void *func_ptr; - - /* argument number */ - uint8 arg_num; - - /* whether the first argument is lvgl object and needs validate */ - bool check_obj; -} WGLNativeFuncDef; - -bool -wgl_native_validate_object(int32 obj_id, lv_obj_t **obj); - -bool -wgl_native_add_object(lv_obj_t *obj, uint32 module_id, uint32 *obj_id); - -uint32 -wgl_native_wigdet_create(int8 widget_type, uint32 par_obj_id, - uint32 copy_obj_id, wasm_module_inst_t module_inst); - -void -wgl_native_func_call(wasm_exec_env_t exec_env, WGLNativeFuncDef *funcs, - uint32 size, int32 func_id, uint32 *argv, uint32 argc); - -#ifdef __cplusplus -} -#endif - -#endif /* WAMR_GRAPHIC_LIBRARY_NATIVE_UTILS_H */ diff --git a/core/app-framework/wgl/native/wgl_obj_wrapper.c b/core/app-framework/wgl/native/wgl_obj_wrapper.c deleted file mode 100644 index 41f605b48..000000000 --- a/core/app-framework/wgl/native/wgl_obj_wrapper.c +++ /dev/null @@ -1,414 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "lvgl.h" -#include "app_manager_export.h" -#include "module_wasm_app.h" -#include "bh_platform.h" -#include "wgl_native_utils.h" -#include "wgl.h" - -typedef struct { - bh_list_link l; - - /* The object id. */ - uint32 obj_id; - - /* The lv object */ - lv_obj_t *obj; - - /* Module id that the obj belongs to */ - uint32 module_id; -} object_node_t; - -typedef struct { - int32 obj_id; - lv_event_t event; -} object_event_t; - -/* Max obj id */ -static uint32 g_obj_id_max = 0; - -static bh_list g_object_list; - -static korp_mutex g_object_list_mutex; - -static bool lv_task_handler_thread_run = true; - -static korp_mutex task_handler_lock; - -static korp_cond task_handler_cond; - -static void -app_mgr_object_event_callback(module_data *m_data, bh_message_t msg) -{ - uint32 argv[2]; - wasm_function_inst_t func_on_object_event; - bh_assert(WIDGET_EVENT_WASM == bh_message_type(msg)); - wasm_data *wasm_app_data = (wasm_data *)m_data->internal_data; - wasm_module_inst_t inst = wasm_app_data->wasm_module_inst; - object_event_t *object_event = (object_event_t *)bh_message_payload(msg); - - if (object_event == NULL) - return; - - func_on_object_event = - wasm_runtime_lookup_function(inst, "_on_widget_event", "(i32i32)"); - if (!func_on_object_event) - func_on_object_event = - wasm_runtime_lookup_function(inst, "on_widget_event", "(i32i32)"); - if (!func_on_object_event) { - printf("Cannot find function on_widget_event\n"); - return; - } - - argv[0] = object_event->obj_id; - argv[1] = object_event->event; - if (!wasm_runtime_call_wasm(wasm_app_data->exec_env, func_on_object_event, - 2, argv)) { - const char *exception = wasm_runtime_get_exception(inst); - bh_assert(exception); - printf(":Got exception running wasm code: %s\n", exception); - wasm_runtime_clear_exception(inst); - return; - } -} - -static void -cleanup_object_list(uint32 module_id) -{ - object_node_t *elem; - - os_mutex_lock(&g_object_list_mutex); - - while (true) { - bool found = false; - elem = (object_node_t *)bh_list_first_elem(&g_object_list); - while (elem) { - /* delete the leaf node belongs to the module firstly */ - if (module_id == elem->module_id - && lv_obj_count_children(elem->obj) == 0) { - object_node_t *next = (object_node_t *)bh_list_elem_next(elem); - - found = true; - lv_obj_del(elem->obj); - bh_list_remove(&g_object_list, elem); - wasm_runtime_free(elem); - elem = next; - } - else { - elem = (object_node_t *)bh_list_elem_next(elem); - } - } - - if (!found) - break; - } - - os_mutex_unlock(&g_object_list_mutex); -} - -static bool -init_object_event_callback_framework() -{ - if (!wasm_register_cleanup_callback(cleanup_object_list)) { - goto fail; - } - - if (!wasm_register_msg_callback(WIDGET_EVENT_WASM, - app_mgr_object_event_callback)) { - goto fail; - } - - return true; - -fail: - return false; -} - -bool -wgl_native_validate_object(int32 obj_id, lv_obj_t **obj) -{ - object_node_t *elem; - - os_mutex_lock(&g_object_list_mutex); - - elem = (object_node_t *)bh_list_first_elem(&g_object_list); - while (elem) { - if (obj_id == elem->obj_id) { - if (obj != NULL) - *obj = elem->obj; - os_mutex_unlock(&g_object_list_mutex); - return true; - } - elem = (object_node_t *)bh_list_elem_next(elem); - } - - os_mutex_unlock(&g_object_list_mutex); - - return false; -} - -bool -wgl_native_add_object(lv_obj_t *obj, uint32 module_id, uint32 *obj_id) -{ - object_node_t *node; - - node = (object_node_t *)wasm_runtime_malloc(sizeof(object_node_t)); - - if (node == NULL) - return false; - - /* Generate an obj id */ - g_obj_id_max++; - if (g_obj_id_max == -1) - g_obj_id_max = 1; - - memset(node, 0, sizeof(*node)); - node->obj = obj; - node->obj_id = g_obj_id_max; - node->module_id = module_id; - - os_mutex_lock(&g_object_list_mutex); - bh_list_insert(&g_object_list, node); - os_mutex_unlock(&g_object_list_mutex); - - if (obj_id != NULL) - *obj_id = node->obj_id; - - return true; -} - -static void -_obj_del_recursive(lv_obj_t *obj) -{ - object_node_t *elem; - lv_obj_t *i; - lv_obj_t *i_next; - - i = lv_ll_get_head(&(obj->child_ll)); - - while (i != NULL) { - /*Get the next object before delete this*/ - i_next = lv_ll_get_next(&(obj->child_ll), i); - - /*Call the recursive del to the child too*/ - _obj_del_recursive(i); - - /*Set i to the next node*/ - i = i_next; - } - - os_mutex_lock(&g_object_list_mutex); - - elem = (object_node_t *)bh_list_first_elem(&g_object_list); - while (elem) { - if (obj == elem->obj) { - bh_list_remove(&g_object_list, elem); - wasm_runtime_free(elem); - os_mutex_unlock(&g_object_list_mutex); - return; - } - elem = (object_node_t *)bh_list_elem_next(elem); - } - - os_mutex_unlock(&g_object_list_mutex); -} - -static void -_obj_clean_recursive(lv_obj_t *obj) -{ - lv_obj_t *i; - lv_obj_t *i_next; - - i = lv_ll_get_head(&(obj->child_ll)); - - while (i != NULL) { - /*Get the next object before delete this*/ - i_next = lv_ll_get_next(&(obj->child_ll), i); - - /*Call the recursive del to the child too*/ - _obj_del_recursive(i); - - /*Set i to the next node*/ - i = i_next; - } -} - -static void -post_widget_msg_to_module(object_node_t *object_node, lv_event_t event) -{ - module_data *module = module_data_list_lookup_id(object_node->module_id); - object_event_t *object_event; - - if (module == NULL) - return; - - object_event = (object_event_t *)wasm_runtime_malloc(sizeof(*object_event)); - if (object_event == NULL) - return; - - memset(object_event, 0, sizeof(*object_event)); - object_event->obj_id = object_node->obj_id; - object_event->event = event; - - bh_post_msg(module->queue, WIDGET_EVENT_WASM, object_event, - sizeof(*object_event)); -} - -static void -internal_lv_obj_event_cb(lv_obj_t *obj, lv_event_t event) -{ - object_node_t *elem; - - os_mutex_lock(&g_object_list_mutex); - - elem = (object_node_t *)bh_list_first_elem(&g_object_list); - while (elem) { - if (obj == elem->obj) { - post_widget_msg_to_module(elem, event); - os_mutex_unlock(&g_object_list_mutex); - return; - } - elem = (object_node_t *)bh_list_elem_next(elem); - } - - os_mutex_unlock(&g_object_list_mutex); -} - -static void * -lv_task_handler_thread_routine(void *arg) -{ - os_mutex_lock(&task_handler_lock); - - while (lv_task_handler_thread_run) { - os_cond_reltimedwait(&task_handler_cond, &task_handler_lock, - 100 * 1000); - lv_task_handler(); - } - - os_mutex_unlock(&task_handler_lock); - return NULL; -} - -void -wgl_init(void) -{ - korp_tid tid; - - if (os_mutex_init(&task_handler_lock) != 0) - return; - - if (os_cond_init(&task_handler_cond) != 0) { - os_mutex_destroy(&task_handler_lock); - return; - } - - lv_init(); - - bh_list_init(&g_object_list); - os_recursive_mutex_init(&g_object_list_mutex); - init_object_event_callback_framework(); - - /* new a thread, call lv_task_handler periodically */ - os_thread_create(&tid, lv_task_handler_thread_routine, NULL, - BH_APPLET_PRESERVED_STACK_SIZE); -} - -void -wgl_exit(void) -{ - lv_task_handler_thread_run = false; - os_cond_destroy(&task_handler_cond); - os_mutex_destroy(&task_handler_lock); -} - -/* ------------------------------------------------------------------------- - * Obj native function wrappers - * -------------------------------------------------------------------------*/ -DEFINE_WGL_NATIVE_WRAPPER(lv_obj_del_wrapper) -{ - lv_res_t res; - wgl_native_return_type(lv_res_t); - wgl_native_get_arg(lv_obj_t *, obj); - - (void)exec_env; - - /* Recursively delete object node in the list belong to this - * parent object including itself */ - _obj_del_recursive(obj); - res = lv_obj_del(obj); - wgl_native_set_return(res); -} - -DEFINE_WGL_NATIVE_WRAPPER(lv_obj_del_async_wrapper) -{ - wgl_native_get_arg(lv_obj_t *, obj); - - (void)exec_env; - lv_obj_del_async(obj); -} - -DEFINE_WGL_NATIVE_WRAPPER(lv_obj_clean_wrapper) -{ - wgl_native_get_arg(lv_obj_t *, obj); - - (void)exec_env; - - /* Recursively delete child object node in the list belong to this - * parent object */ - _obj_clean_recursive(obj); - - /* Delete all of its children */ - lv_obj_clean(obj); -} - -DEFINE_WGL_NATIVE_WRAPPER(lv_obj_align_wrapper) -{ - wgl_native_get_arg(lv_obj_t *, obj); - wgl_native_get_arg(uint32, base_obj_id); - wgl_native_get_arg(lv_align_t, align); - wgl_native_get_arg(lv_coord_t, x_mod); - wgl_native_get_arg(lv_coord_t, y_mod); - lv_obj_t *base = NULL; - wasm_module_inst_t module_inst = get_module_inst(exec_env); - - /* validate the base object id if not equal to 0 */ - if (base_obj_id != 0 && !wgl_native_validate_object(base_obj_id, &base)) { - wasm_runtime_set_exception(module_inst, - "align with invalid base object."); - return; - } - - lv_obj_align(obj, base, align, x_mod, y_mod); -} - -DEFINE_WGL_NATIVE_WRAPPER(lv_obj_set_event_cb_wrapper) -{ - wgl_native_get_arg(lv_obj_t *, obj); - (void)exec_env; - lv_obj_set_event_cb(obj, internal_lv_obj_event_cb); -} - -/* ------------------------------------------------------------------------- */ - -static WGLNativeFuncDef obj_native_func_defs[] = { - { OBJ_FUNC_ID_DEL, lv_obj_del_wrapper, 1, true }, - { OBJ_FUNC_ID_DEL_ASYNC, lv_obj_del_async_wrapper, 1, true }, - { OBJ_FUNC_ID_CLEAN, lv_obj_clean_wrapper, 1, true }, - { OBJ_FUNC_ID_ALIGN, lv_obj_align_wrapper, 5, true }, - { OBJ_FUNC_ID_SET_EVT_CB, lv_obj_set_event_cb_wrapper, 1, true }, -}; - -/*************** Native Interface to Wasm App ***********/ -void -wasm_obj_native_call(wasm_exec_env_t exec_env, int32 func_id, uint32 *argv, - uint32 argc) -{ - uint32 size = sizeof(obj_native_func_defs) / sizeof(WGLNativeFuncDef); - - wgl_native_func_call(exec_env, obj_native_func_defs, size, func_id, argv, - argc); -} diff --git a/core/app-framework/wgl/readme.MD b/core/app-framework/wgl/readme.MD deleted file mode 100644 index f929a5c11..000000000 --- a/core/app-framework/wgl/readme.MD +++ /dev/null @@ -1,97 +0,0 @@ -WASM Graphic Layer (WGL) -======= - -The WGL builds the littlevgl v6.0 into the runtime and exports a API layer for WASM appication programming graphic user interfaces. This approach will make the WASM application small footprint. Another option is to build the whole littlevgl library into WASM, which is how the sample littlevgl is implemented. - -# Challenges - -When the littlevgl library is compiled into the runtime, all the widget data is actually located in the runtime native space. As the WASM sandbox won't allow the WASM application to directly access the native data, it introduced a few problems for the littlevgl API exporting: - -1. Reference to the widget object - - Almost each littlevgl API takes the widget object as the first argument, which leads to either reading or writing the data associated with the object in native space. We have to prevent the WASM app utilize this method to access unauthorized memmory address. - - The solution is to track the objects created by the WASM App in the native layer. Every access to the object must be validated in advance. To simplify implementing native wrapper function, the wgl_native_func_call() will do the validation for the object presented in the first argument. - - When multiple WASM apps are creating their own UI, the object should also validated for its owner module instance. - -2. Access the object properties - - As the data structure of widget objects is no longer visible to the applications, the app has to call APIs to get/set the properties of an object. - -3. Pass function arguments in stucture pointers - - We have to do serialization for the structure passing between the WASM and native. - -4. Callbacks - -# API compatibility with littlevgl -We wish the application continue to use the littlevgl API and keep existing header files inclusion, however it is also a bit challenging since we have to redefine some data types such as lv_obj_t in the APIs exposed to the WASM app. - -''' -typedef void lv_obj_t; -''' - - - -# Prepare the lvgl header files for WASM applicaitons - -Run the below script to setup the lvgl header files for the wasm appliation. - -``` -core/app-framework/wgl/app/prepare_headers.sh -``` - -The script is also automatically executed after downloading the lvgl repo in the wamr-sdk building process. - - - -# How to extend a little vgl wideget -Currently the wgl has exported the API for a few common used widgets such as button, label etc. - -Refer to the implementation of these widgets for extending more widgets. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/core/app-mgr/app-manager/app_manager.c b/core/app-mgr/app-manager/app_manager.c deleted file mode 100644 index b27ee96eb..000000000 --- a/core/app-mgr/app-manager/app_manager.c +++ /dev/null @@ -1,431 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "app_manager.h" -#include "app_manager_host.h" -#include "bh_platform.h" -#include "bi-inc/attr_container.h" -#include "event.h" -#include "watchdog.h" -#include "coap_ext.h" - -/* Queue of app manager */ -static bh_queue *g_app_mgr_queue; -static bool g_app_mgr_started; - -void * -get_app_manager_queue() -{ - return g_app_mgr_queue; -} - -void -app_manager_post_applets_update_event() -{ - module_data *m_data; - attr_container_t *attr_cont; - request_t msg; - int num = 0, i = 0; - char *url = "/applets"; - - if (!event_is_registered(url)) - return; - - if (!(attr_cont = attr_container_create("All Applets"))) { - app_manager_printf("Post applets update event failed: " - "allocate memory failed."); - return; - } - - os_mutex_lock(&module_data_list_lock); - - m_data = module_data_list; - while (m_data) { - num++; - m_data = m_data->next; - } - - if (!(attr_container_set_int(&attr_cont, "num", num))) { - app_manager_printf("Post applets update event failed: " - "set attr container key failed."); - goto fail; - } - - m_data = module_data_list; - while (m_data) { - char buf[32]; - i++; - snprintf(buf, sizeof(buf), "%s%d", "applet", i); - if (!(attr_container_set_string(&attr_cont, buf, - m_data->module_name))) { - app_manager_printf("Post applets update event failed: " - "set attr applet name key failed."); - goto fail; - } - snprintf(buf, sizeof(buf), "%s%d", "heap", i); - if (!(attr_container_set_int(&attr_cont, buf, m_data->heap_size))) { - app_manager_printf("Post applets update event failed: " - "set attr heap key failed."); - goto fail; - } - m_data = m_data->next; - } - - memset(&msg, 0, sizeof(msg)); - msg.url = url; - msg.action = COAP_EVENT; - msg.payload = (char *)attr_cont; - send_request_to_host(&msg); - - app_manager_printf("Post applets update event success!\n"); - attr_container_dump(attr_cont); - -fail: - os_mutex_unlock(&module_data_list_lock); - attr_container_destroy(attr_cont); -} - -static int -get_applets_count() -{ - module_data *m_data; - int num = 0; - - os_mutex_lock(&module_data_list_lock); - - m_data = module_data_list; - while (m_data) { - num++; - m_data = m_data->next; - } - - os_mutex_unlock(&module_data_list_lock); - - return num; -} - -/* Query fw apps info if name = NULL, otherwise query specify app */ -static bool -app_manager_query_applets(request_t *msg, const char *name) -{ - module_data *m_data; - attr_container_t *attr_cont; - int num = 0, i = 0, len; - bool ret = false, found = false; - response_t response[1] = { 0 }; - - attr_cont = attr_container_create("Applets Info"); - if (!attr_cont) { - SEND_ERR_RESPONSE(msg->mid, - "Query Applets failed: allocate memory failed."); - return false; - } - - os_mutex_lock(&module_data_list_lock); - - m_data = module_data_list; - while (m_data) { - num++; - m_data = m_data->next; - } - - if (name == NULL && !(attr_container_set_int(&attr_cont, "num", num))) { - SEND_ERR_RESPONSE( - msg->mid, "Query Applets failed: set attr container key failed."); - goto fail; - } - - m_data = module_data_list; - while (m_data) { - char buf[32]; - - if (name == NULL) { - i++; - snprintf(buf, sizeof(buf), "%s%d", "applet", i); - if (!(attr_container_set_string(&attr_cont, buf, - m_data->module_name))) { - SEND_ERR_RESPONSE(msg->mid, "Query Applets failed: " - "set attr container key failed."); - goto fail; - } - snprintf(buf, sizeof(buf), "%s%d", "heap", i); - if (!(attr_container_set_int(&attr_cont, buf, m_data->heap_size))) { - SEND_ERR_RESPONSE(msg->mid, - "Query Applets failed: " - "set attr container heap key failed."); - goto fail; - } - } - else if (!strcmp(name, m_data->module_name)) { - found = true; - if (!(attr_container_set_string(&attr_cont, "name", - m_data->module_name))) { - SEND_ERR_RESPONSE(msg->mid, "Query Applet failed: " - "set attr container key failed."); - goto fail; - } - if (!(attr_container_set_int(&attr_cont, "heap", - m_data->heap_size))) { - SEND_ERR_RESPONSE(msg->mid, - "Query Applet failed: " - "set attr container heap key failed."); - goto fail; - } - } - - m_data = m_data->next; - } - - if (name != NULL && !found) { - SEND_ERR_RESPONSE(msg->mid, - "Query Applet failed: the app is not found."); - goto fail; - } - - len = attr_container_get_serialize_length(attr_cont); - - make_response_for_request(msg, response); - set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, (char *)attr_cont, - len); - send_response_to_host(response); - - ret = true; - app_manager_printf("Query Applets success!\n"); - attr_container_dump(attr_cont); - -fail: - os_mutex_unlock(&module_data_list_lock); - attr_container_destroy(attr_cont); - return ret; -} - -void -applet_mgt_reqeust_handler(request_t *request, void *unused) -{ - bh_message_t msg; - /* deep copy, but not use app self heap, but use global heap */ - request_t *req = clone_request(request); - - if (!req) - return; - - msg = bh_new_msg(RESTFUL_REQUEST, req, sizeof(*req), request_cleaner); - if (!msg) { - request_cleaner(req); - return; - } - - bh_post_msg2(get_app_manager_queue(), msg); -} - -/* return -1 for error */ -static int -get_module_type(char *kv_str) -{ - int module_type = -1; - char type_str[16] = { 0 }; - - find_key_value(kv_str, strlen(kv_str), "type", type_str, - sizeof(type_str) - 1, '&'); - - if (strlen(type_str) == 0) - module_type = Module_WASM_App; - else if (strcmp(type_str, "jeff") == 0) - module_type = Module_Jeff; - else if (strcmp(type_str, "wasm") == 0) - module_type = Module_WASM_App; - else if (strcmp(type_str, "wasmlib") == 0) - module_type = Module_WASM_Lib; - - return module_type; -} - -#define APP_NAME_MAX_LEN 128 - -/* Queue callback of App Manager */ - -static void -app_manager_queue_callback(void *message, void *arg) -{ - request_t *request = (request_t *)bh_message_payload((bh_message_t)message); - int mid = request->mid, module_type, offset; - - (void)arg; - - if ((offset = - check_url_start(request->url, strlen(request->url), "/applet")) - > 0) { - module_type = get_module_type(request->url + offset); - - if (module_type == -1) { - SEND_ERR_RESPONSE(mid, - "Applet Management failed: invalid module type."); - goto fail; - } - - /* Install Applet */ - if (request->action == COAP_PUT) { - if (get_applets_count() >= MAX_APP_INSTALLATIONS) { - SEND_ERR_RESPONSE( - mid, - "Install Applet failed: exceed max app installations."); - goto fail; - } - - if (!request->payload) { - SEND_ERR_RESPONSE(mid, - "Install Applet failed: invalid payload."); - goto fail; - } - if (g_module_interfaces[module_type] - && g_module_interfaces[module_type]->module_install) { - if (!g_module_interfaces[module_type]->module_install(request)) - goto fail; - } - } - /* Uninstall Applet */ - else if (request->action == COAP_DELETE) { - module_type = get_module_type(request->url + offset); - if (module_type == -1) { - SEND_ERR_RESPONSE( - mid, "Uninstall Applet failed: invalid module type."); - goto fail; - } - - if (g_module_interfaces[module_type] - && g_module_interfaces[module_type]->module_uninstall) { - if (!g_module_interfaces[module_type]->module_uninstall( - request)) - goto fail; - } - } - /* Query Applets installed */ - else if (request->action == COAP_GET) { - char name[APP_NAME_MAX_LEN] = { 0 }; - char *properties = request->url + offset; - find_key_value(properties, strlen(properties), "name", name, - sizeof(name) - 1, '&'); - if (strlen(name) > 0) - app_manager_query_applets(request, name); - else - app_manager_query_applets(request, NULL); - } - else { - SEND_ERR_RESPONSE(mid, "Invalid request of applet: invalid action"); - } - } - /* Event Register/Unregister */ - else if ((offset = check_url_start(request->url, strlen(request->url), - "/event/")) - > 0) { - char url_buf[256] = { 0 }; - - strncpy(url_buf, request->url + offset, sizeof(url_buf) - 1); - - if (!event_handle_event_request(request->action, url_buf, ID_HOST)) { - SEND_ERR_RESPONSE(mid, "Handle event request failed."); - goto fail; - } - send_error_response_to_host(mid, CONTENT_2_05, NULL); /* OK */ - } - else { - int i; - for (i = 0; i < Module_Max; i++) { - if (g_module_interfaces[i] - && g_module_interfaces[i]->module_handle_host_url) { - if (g_module_interfaces[i]->module_handle_host_url(request)) - break; - } - } - } - -fail: - return; -} - -static void -module_interfaces_init() -{ - int i; - for (i = 0; i < Module_Max; i++) { - if (g_module_interfaces[i] && g_module_interfaces[i]->module_init) - g_module_interfaces[i]->module_init(); - } -} - -void -app_manager_startup(host_interface *interface) -{ - module_interfaces_init(); - - /* Create queue of App Manager */ - g_app_mgr_queue = bh_queue_create(); - if (!g_app_mgr_queue) - return; - - if (!module_data_list_init()) - goto fail1; - - if (!watchdog_startup()) - goto fail2; - - /* Initialize Host */ - app_manager_host_init(interface); - - am_register_resource("/app/", targeted_app_request_handler, ID_APP_MGR); - - /* /app/ and /event/ are both processed by applet_mgt_reqeust_handler */ - am_register_resource("/applet", applet_mgt_reqeust_handler, ID_APP_MGR); - am_register_resource("/event/", applet_mgt_reqeust_handler, ID_APP_MGR); - - app_manager_printf("App Manager started.\n"); - - g_app_mgr_started = true; - - /* Enter loop run */ - bh_queue_enter_loop_run(g_app_mgr_queue, app_manager_queue_callback, NULL); - - g_app_mgr_started = false; - - /* Destroy registered resources */ - am_cleanup_registeration(ID_APP_MGR); - - /* Destroy watchdog */ - watchdog_destroy(); - -fail2: - module_data_list_destroy(); - -fail1: - bh_queue_destroy(g_app_mgr_queue); -} - -bool -app_manager_is_started(void) -{ - return g_app_mgr_started; -} - -#include "module_config.h" - -module_interface *g_module_interfaces[Module_Max] = { -#if ENABLE_MODULE_JEFF != 0 - &jeff_module_interface, -#else - NULL, -#endif - -#if ENABLE_MODULE_WASM_APP != 0 - &wasm_app_module_interface, -#else - NULL, -#endif - -#if ENABLE_MODULE_WASM_LIB != 0 - &wasm_lib_module_interface -#else - NULL -#endif -}; diff --git a/core/app-mgr/app-manager/app_manager.h b/core/app-mgr/app-manager/app_manager.h deleted file mode 100644 index ce83bd170..000000000 --- a/core/app-mgr/app-manager/app_manager.h +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef APP_MANAGER_H -#define APP_MANAGER_H - -#include "bh_platform.h" -#include "app_manager_export.h" -#include "native_interface.h" -#include "bi-inc/shared_utils.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define APP_MGR_MALLOC wasm_runtime_malloc -#define APP_MGR_FREE wasm_runtime_free - -/* os_printf is defined in each platform */ -#define app_manager_printf os_printf - -#define SEND_ERR_RESPONSE(mid, err_msg) \ - do { \ - app_manager_printf("%s\n", err_msg); \ - send_error_response_to_host(mid, INTERNAL_SERVER_ERROR_5_00, err_msg); \ - } while (0) - -extern module_interface *g_module_interfaces[Module_Max]; - -/* Lock of the module data list */ -extern korp_mutex module_data_list_lock; - -/* Module data list */ -extern module_data *module_data_list; - -void -app_manager_add_module_data(module_data *m_data); - -void -app_manager_del_module_data(module_data *m_data); - -bool -module_data_list_init(); - -void -module_data_list_destroy(); - -bool -app_manager_is_interrupting_module(uint32 module_type, void *module_inst); - -void -release_module(module_data *m_data); - -void -module_data_list_remove(module_data *m_data); - -void * -app_manager_timer_create(void (*timer_callback)(void *), - watchdog_timer *wd_timer); - -void -app_manager_timer_destroy(void *timer); - -void -app_manager_timer_start(void *timer, int timeout); - -void -app_manager_timer_stop(void *timer); - -watchdog_timer * -app_manager_get_wd_timer_from_timer_handle(void *timer); - -int -app_manager_signature_verify(const uint8_t *file, unsigned int file_len, - const uint8_t *signature, unsigned int sig_size); - -void -targeted_app_request_handler(request_t *request, void *unused); - -#ifdef __cplusplus -} /* end of extern "C" */ -#endif - -#endif diff --git a/core/app-mgr/app-manager/app_manager_host.c b/core/app-mgr/app-manager/app_manager_host.c deleted file mode 100644 index 08b5df309..000000000 --- a/core/app-mgr/app-manager/app_manager_host.c +++ /dev/null @@ -1,324 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "bh_platform.h" -#include "app_manager_host.h" -#include "app_manager.h" -#include "app_manager_export.h" -#include "coap_ext.h" - -/* host communication interface */ -static host_interface host_commu; - -/* IMRTLink Two leading bytes */ -static unsigned char leadings[] = { (unsigned char)0x12, (unsigned char)0x34 }; - -/* IMRTLink Receiving Phase */ -typedef enum recv_phase_t { - Phase_Non_Start, - Phase_Leading, - Phase_Type, - Phase_Size, - Phase_Payload, - Phase_Ignoring -} recv_phase_t; - -/* IMRTLink Receive Context */ -typedef struct recv_context_t { - recv_phase_t phase; - bh_link_msg_t message; - int size_in_phase; -} recv_context_t; - -/* Current IMRTLink receive context */ -static recv_context_t recv_ctx; - -/* Lock for device write */ -static korp_mutex host_lock; - -static bool enable_log = false; - -static bool -is_little_endian() -{ - long i = 0x01020304; - unsigned char *c = (unsigned char *)&i; - return (*c == 0x04) ? true : false; -} - -static void -exchange32(uint8 *pData) -{ - uint8 value = *pData; - *pData = *(pData + 3); - *(pData + 3) = value; - - value = *(pData + 1); - *(pData + 1) = *(pData + 2); - *(pData + 2) = value; -} - -/* return: - * 1: complete message received - * 0: incomplete message received - */ -static int -on_imrt_link_byte_arrive(unsigned char ch, recv_context_t *ctx) -{ - if (ctx->phase == Phase_Non_Start) { - ctx->message.payload_size = 0; - - if (ctx->message.payload) { - APP_MGR_FREE(ctx->message.payload); - ctx->message.payload = NULL; - } - - if (ch == leadings[0]) { - if (enable_log) - app_manager_printf("##On byte arrive: got leading 0\n"); - ctx->phase = Phase_Leading; - } - - return 0; - } - else if (ctx->phase == Phase_Leading) { - if (ch == leadings[1]) { - if (enable_log) - app_manager_printf("##On byte arrive: got leading 1\n"); - ctx->phase = Phase_Type; - } - else - ctx->phase = Phase_Non_Start; - - return 0; - } - else if (ctx->phase == Phase_Type) { - if (ctx->size_in_phase++ == 0) { - if (enable_log) - app_manager_printf("##On byte arrive: got type 0\n"); - ctx->message.message_type = ch; - } - else { - if (enable_log) - app_manager_printf("##On byte arrive: got type 1\n"); - ctx->message.message_type |= (ch << 8); - ctx->message.message_type = ntohs(ctx->message.message_type); - ctx->phase = Phase_Size; - ctx->size_in_phase = 0; - } - - return 0; - } - else if (ctx->phase == Phase_Size) { - unsigned char *p = (unsigned char *)&ctx->message.payload_size; - - if (enable_log) - app_manager_printf("##On byte arrive: got payload_size, byte %d\n", - ctx->size_in_phase); - p[ctx->size_in_phase++] = ch; - - if (ctx->size_in_phase == sizeof(ctx->message.payload_size)) { - ctx->message.payload_size = ntohl(ctx->message.payload_size); - ctx->phase = Phase_Payload; - - if (enable_log) - app_manager_printf("##On byte arrive: payload_size: %d\n", - ctx->message.payload_size); - if (ctx->message.payload) { - APP_MGR_FREE(ctx->message.payload); - ctx->message.payload = NULL; - } - - /* message completion */ - if (ctx->message.payload_size == 0) { - ctx->phase = Phase_Non_Start; - if (enable_log) - app_manager_printf("##On byte arrive: receive end, " - "payload_size is 0.\n"); - return 1; - } - - if (ctx->message.message_type != INSTALL_WASM_APP) { - ctx->message.payload = - (char *)APP_MGR_MALLOC(ctx->message.payload_size); - if (!ctx->message.payload) { - ctx->phase = Phase_Non_Start; - return 0; - } - } - - ctx->phase = Phase_Payload; - ctx->size_in_phase = 0; - } - - return 0; - } - else if (ctx->phase == Phase_Payload) { - if (ctx->message.message_type == INSTALL_WASM_APP) { - int received_size; - module_on_install_request_byte_arrive_func module_on_install = - g_module_interfaces[Module_WASM_App]->module_on_install; - - ctx->size_in_phase++; - - if (module_on_install != NULL) { - if (module_on_install(ch, ctx->message.payload_size, - &received_size)) { - if (received_size == ctx->message.payload_size) { - /* whole wasm app received */ - ctx->phase = Phase_Non_Start; - return 1; - } - } - else { - /* receive or handle fail */ - if (ctx->size_in_phase < ctx->message.payload_size) { - ctx->phase = Phase_Ignoring; - } - else { - ctx->phase = Phase_Non_Start; - ctx->size_in_phase = 0; - } - return 0; - } - } - else { - ctx->phase = Phase_Non_Start; - ctx->size_in_phase = 0; - return 0; - } - } - else { - ctx->message.payload[ctx->size_in_phase++] = ch; - - if (ctx->size_in_phase == ctx->message.payload_size) { - ctx->phase = Phase_Non_Start; - if (enable_log) - app_manager_printf("##On byte arrive: receive end, " - "payload_size is %d.\n", - ctx->message.payload_size); - return 1; - } - return 0; - } - } - else if (ctx->phase == Phase_Ignoring) { - ctx->size_in_phase++; - if (ctx->size_in_phase == ctx->message.payload_size) { - if (ctx->message.payload) - APP_MGR_FREE(ctx->message.payload); - memset(ctx, 0, sizeof(*ctx)); - return 0; - } - } - - return 0; -} - -int -aee_host_msg_callback(void *msg, uint32_t msg_len) -{ - unsigned char *p = msg, *p_end = p + msg_len; - - /*app_manager_printf("App Manager receive %d bytes from Host\n", msg_len);*/ - - for (; p < p_end; p++) { - int ret = on_imrt_link_byte_arrive(*p, &recv_ctx); - - if (ret == 1) { - if (recv_ctx.message.payload) { - int msg_type = recv_ctx.message.message_type; - - if (msg_type == REQUEST_PACKET) { - request_t request; - memset(&request, 0, sizeof(request)); - - if (!unpack_request(recv_ctx.message.payload, - recv_ctx.message.payload_size, - &request)) - continue; - - request.sender = ID_HOST; - - am_dispatch_request(&request); - } - else { - app_manager_printf("unexpected host msg type: %d\n", - msg_type); - } - - APP_MGR_FREE(recv_ctx.message.payload); - recv_ctx.message.payload = NULL; - recv_ctx.message.payload_size = 0; - } - - memset(&recv_ctx, 0, sizeof(recv_ctx)); - } - } - - return 0; -} - -bool -app_manager_host_init(host_interface *interface) -{ - if (os_mutex_init(&host_lock) != 0) { - return false; - } - memset(&recv_ctx, 0, sizeof(recv_ctx)); - - host_commu.init = interface->init; - host_commu.send = interface->send; - host_commu.destroy = interface->destroy; - - if (host_commu.init != NULL) { - if (!host_commu.init()) { - os_mutex_destroy(&host_lock); - return false; - } - } - - return true; -} - -int -app_manager_host_send_msg(int msg_type, const char *buf, int size) -{ - /* send an IMRT LINK message contains the buf as payload */ - if (host_commu.send != NULL) { - int size_s = size, n; - char header[16]; - - os_mutex_lock(&host_lock); - /* leading bytes */ - bh_memcpy_s(header, 2, leadings, 2); - - /* message type */ - /* TODO: check if use network byte order!!! */ - *((uint16 *)(header + 2)) = htons(msg_type); - - /* payload length */ - if (is_little_endian()) - exchange32((uint8 *)&size_s); - - bh_memcpy_s(header + 4, 4, &size_s, 4); - n = host_commu.send(NULL, header, 8); - if (n != 8) { - os_mutex_unlock(&host_lock); - return 0; - } - - /* payload */ - n = host_commu.send(NULL, buf, size); - os_mutex_unlock(&host_lock); - - app_manager_printf("sent %d bytes to host\n", n); - return n; - } - else { - app_manager_printf("no send api provided\n"); - } - return 0; -} diff --git a/core/app-mgr/app-manager/app_manager_host.h b/core/app-mgr/app-manager/app_manager_host.h deleted file mode 100644 index b19404f91..000000000 --- a/core/app-mgr/app-manager/app_manager_host.h +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _APP_MANAGER_HOST_H_ -#define _APP_MANAGER_HOST_H_ - -#include "wasm_export.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define HOST_MODE_AON 1 -#define HOST_MODE_UART 2 -#define HOST_MODE_TEST 3 - -#ifdef __cplusplus -} /* end of extern "C" */ -#endif - -#endif diff --git a/core/app-mgr/app-manager/app_mgr.cmake b/core/app-mgr/app-manager/app_mgr.cmake deleted file mode 100644 index fd6e69098..000000000 --- a/core/app-mgr/app-manager/app_mgr.cmake +++ /dev/null @@ -1,17 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -set (__APP_MGR_DIR ${CMAKE_CURRENT_LIST_DIR}) - -include_directories(${__APP_MGR_DIR}) - - -file (GLOB source_all ${__APP_MGR_DIR}/*.c ${__APP_MGR_DIR}/platform/${WAMR_BUILD_PLATFORM}/*.c) - -set (APP_MGR_SOURCE ${source_all}) - -file (GLOB header - ${__APP_MGR_DIR}/module_wasm_app.h -) -LIST (APPEND RUNTIME_LIB_HEADER_LIST ${header}) - diff --git a/core/app-mgr/app-manager/ble_msg.c b/core/app-mgr/app-manager/ble_msg.c deleted file mode 100644 index 1d19dddaf..000000000 --- a/core/app-mgr/app-manager/ble_msg.c +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#if 0 - -#define BLUETOOTH_INTERFACE_ADVERTISMENT_DATA_LENGTH 31 -/* ble_device_info */ -typedef struct ble_device_info { - - /* address type */ - uint8_t address_type; - /* MAC of Device */ - uint8_t mac[6]; - /* security level */ - uint8_t security_level; - /* signal strength */ - int8_t rssi; - /* uuid_16_type */ - int8_t uuid_16_type; - /* uuid_32_type */ - int8_t uuid_32_type; - /* uuid_128_type */ - int8_t uuid_128_type; - /* error code */ - uint8_t error_code; - /* scan response length*/ - uint16_t adv_data_len; - /* advertisement data */ - uint8_t *adv_data; - /* scan response length*/ - uint16_t scan_response_len; - /* scan response */ - uint8_t *scan_response; - /* next device */ - struct ble_device_info *next; - /* private data length */ - int private_data_length; - /* private data */ - uint8_t *private_data; - /* value handle*/ - uint16_t value_handle; - /* ccc handle*/ - uint16_t ccc_handle; - -}ble_device_info; - -/* BLE message sub type */ -typedef enum BLE_SUB_EVENT_TYPE { - BLE_SUB_EVENT_DISCOVERY, - BLE_SUB_EVENT_CONNECTED, - BLE_SUB_EVENT_DISCONNECTED, - BLE_SUB_EVENT_NOTIFICATION, - BLE_SUB_EVENT_INDICATION, - BLE_SUB_EVENT_PASSKEYENTRY, - BLE_SUB_EVENT_SECURITY_LEVEL_CHANGE -}BLE_SUB_EVENT_TYPE; - -/* Queue message, for BLE Event */ -typedef struct bh_queue_ble_sub_msg_t { - /* message type, should be one of QUEUE_MSG_TYPE */ - BLE_SUB_EVENT_TYPE type; - /* payload size */ - /*uint32_t payload_size;*/ - char payload[1]; -}bh_queue_ble_sub_msg_t; - -static void -app_instance_free_ble_msg(char *msg) -{ - bh_queue_ble_sub_msg_t *ble_msg = (bh_queue_ble_sub_msg_t *)msg; - ble_device_info *dev_info; - - dev_info = (ble_device_info *) ble_msg->payload; - - if (dev_info->scan_response != NULL) - APP_MGR_FREE(dev_info->scan_response); - - if (dev_info->private_data != NULL) - APP_MGR_FREE(dev_info->private_data); - - if (dev_info->adv_data != NULL) - APP_MGR_FREE(dev_info->adv_data); - - if (dev_info != NULL) - APP_MGR_FREE(dev_info); -} - -static void -app_instance_queue_free_callback(bh_message_t queue_msg) -{ - - char * payload = (char *)bh_message_payload(queue_msg); - if(payload == NULL) - return; - - switch (bh_message_type(queue_msg)) - { - /* - case SENSOR_EVENT: { - bh_sensor_event_t *sensor_event = (bh_sensor_event_t *) payload; - attr_container_t *event = sensor_event->event; - attr_container_destroy(event); - } - break; - */ - case BLE_EVENT: { - app_instance_free_ble_msg(payload); - break; - } - } -} - -#endif diff --git a/core/app-mgr/app-manager/coding_rule.txt b/core/app-mgr/app-manager/coding_rule.txt deleted file mode 100644 index 4598872a3..000000000 --- a/core/app-mgr/app-manager/coding_rule.txt +++ /dev/null @@ -1,15 +0,0 @@ -Coding rules: - -1. module implementation can include the export head files of associated runtime - -2. app manager only call access the module implementation through the interface API - -3. module implementation can call the app manager API from following files: - - util.c - - message.c - -4. platform API: To define it - -5. Any platform dependent implementation of app manager should be implemented in the - platform specific source file, such as app_mgr_zephyr.c - diff --git a/core/app-mgr/app-manager/event.c b/core/app-mgr/app-manager/event.c deleted file mode 100644 index a21065fab..000000000 --- a/core/app-mgr/app-manager/event.c +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include - -#include "event.h" - -#include "app_manager.h" -#include "coap_ext.h" - -typedef struct _subscribe { - struct _subscribe *next; - uint32 subscriber_id; -} subscribe_t; - -typedef struct _event { - struct _event *next; - int subscriber_size; - subscribe_t *subscribers; - char url[1]; /* event url */ -} event_reg_t; - -event_reg_t *g_events = NULL; - -static bool -find_subscriber(event_reg_t *reg, uint32 id, bool remove_found) -{ - subscribe_t *c = reg->subscribers; - subscribe_t *prev = NULL; - while (c) { - subscribe_t *next = c->next; - if (c->subscriber_id == id) { - if (remove_found) { - if (prev) - prev->next = next; - else - reg->subscribers = next; - - APP_MGR_FREE(c); - } - - return true; - } - else { - prev = c; - c = next; - } - } - - return false; -} - -static bool -check_url(const char *url) -{ - if (*url == 0) - return false; - - return true; -} - -bool -am_register_event(const char *url, uint32_t reg_client) -{ - event_reg_t *current = g_events; - - app_manager_printf("am_register_event adding url:(%s)\n", url); - - if (!check_url(url)) { - app_manager_printf("am_register_event: invaild url:(%s)\n", url); - return false; - } - while (current) { - if (strcmp(url, current->url) == 0) - break; - current = current->next; - } - - if (current == NULL) { - if (NULL - == (current = (event_reg_t *)APP_MGR_MALLOC( - offsetof(event_reg_t, url) + strlen(url) + 1))) { - app_manager_printf("am_register_event: malloc fail\n"); - return false; - } - - memset(current, 0, sizeof(event_reg_t)); - bh_strcpy_s(current->url, strlen(url) + 1, url); - current->next = g_events; - g_events = current; - } - - if (find_subscriber(current, reg_client, false)) { - return true; - } - else { - subscribe_t *s = (subscribe_t *)APP_MGR_MALLOC(sizeof(subscribe_t)); - if (s == NULL) - return false; - - memset(s, 0, sizeof(subscribe_t)); - s->subscriber_id = reg_client; - s->next = current->subscribers; - current->subscribers = s; - app_manager_printf("client: %d registered event (%s)\n", reg_client, - url); - } - - return true; -} - -// @url: NULL means the client wants to unregister all its subscribed items -bool -am_unregister_event(const char *url, uint32_t reg_client) -{ - event_reg_t *current = g_events, *pre = NULL; - - while (current != NULL) { - if (url == NULL || strcmp(current->url, url) == 0) { - event_reg_t *next = current->next; - if (find_subscriber(current, reg_client, true)) { - app_manager_printf("client: %d deregistered event (%s)\n", - reg_client, current->url); - } - - // remove the registration if no client subscribe it - if (current->subscribers == NULL) { - app_manager_printf("unregister for event deleted url:(%s)\n", - current->url); - if (pre) - pre->next = next; - else - g_events = next; - APP_MGR_FREE(current); - current = next; - continue; - } - } - pre = current; - current = current->next; - } - - return true; -} - -bool -event_handle_event_request(uint8_t code, const char *event_url, - uint32_t reg_client) -{ - if (code == COAP_PUT) { /* register */ - return am_register_event(event_url, reg_client); - } - else if (code == COAP_DELETE) { /* unregister */ - return am_unregister_event(event_url, reg_client); - } - else { - /* invalid request */ - return false; - } -} - -void -am_publish_event(request_t *event) -{ - bh_assert(event->action == COAP_EVENT); - - event_reg_t *current = g_events; - while (current) { - if (0 == strcmp(event->url, current->url)) { - subscribe_t *c = current->subscribers; - while (c) { - if (c->subscriber_id == ID_HOST) { - send_request_to_host(event); - } - else { - module_request_handler(event, - (void *)(uintptr_t)c->subscriber_id); - } - c = c->next; - } - - return; - } - - current = current->next; - } -} - -bool -event_is_registered(const char *event_url) -{ - event_reg_t *current = g_events; - - while (current != NULL) { - if (strcmp(current->url, event_url) == 0) { - return true; - } - current = current->next; - } - - return false; -} diff --git a/core/app-mgr/app-manager/event.h b/core/app-mgr/app-manager/event.h deleted file mode 100644 index 36ced521d..000000000 --- a/core/app-mgr/app-manager/event.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _EVENT_H_ -#define _EVENT_H_ - -#include "bh_platform.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * Handle event request from host agent - * - * @param code the coap packet code - * @param event_url the event url - * - * @return true if success, false otherwise - */ -bool -event_handle_event_request(uint8_t code, const char *event_url, - uint32_t register); - -/** - * Test whether the event is registered - * - * @param event_url the event url - * - * @return true for registered, false for not registered - */ -bool -event_is_registered(const char *event_url); - -#ifdef __cplusplus -} /* end of extern "C" */ -#endif - -#endif /* _EVENT_H_ */ diff --git a/core/app-mgr/app-manager/message.c b/core/app-mgr/app-manager/message.c deleted file mode 100644 index aac7a2364..000000000 --- a/core/app-mgr/app-manager/message.c +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "app_manager.h" -#include "app_manager_host.h" -#include "event.h" -#include "bi-inc/attr_container.h" -#include "coap_ext.h" - -#if 0 -bool send_coap_packet_to_host(coap_packet_t * packet) -{ - int size; - uint8_t *buf; - - size = coap_serialize_message_tcp(&packet, &buf); - if (!buf || size == 0) - return false; - - app_manager_host_send_msg(buf, size); - APP_MGR_FREE(buf); - - return true; -} -#endif - -bool -send_request_to_host(request_t *msg) -{ - if (COAP_EVENT == msg->action && !event_is_registered(msg->url)) { - app_manager_printf("Event is not registered\n"); - return false; - } - - int size; - char *packet = pack_request(msg, &size); - if (packet == NULL) - return false; - - app_manager_host_send_msg(REQUEST_PACKET, packet, size); - - free_req_resp_packet(packet); - - return true; -} - -bool -send_response_to_host(response_t *response) -{ - int size; - char *packet = pack_response(response, &size); - if (packet == NULL) - return false; - - app_manager_host_send_msg(RESPONSE_PACKET, packet, size); - - free_req_resp_packet(packet); - - return true; -} - -bool -send_error_response_to_host(int mid, int status, const char *msg) -{ - int payload_len = 0; - attr_container_t *payload = NULL; - response_t response[1] = { 0 }; - - if (msg) { - payload = attr_container_create(""); - if (payload) { - attr_container_set_string(&payload, "error message", msg); - payload_len = attr_container_get_serialize_length(payload); - } - } - - set_response(response, status, FMT_ATTR_CONTAINER, (const char *)payload, - payload_len); - response->mid = mid; - - send_response_to_host(response); - - if (payload) - attr_container_destroy(payload); - return true; -} diff --git a/core/app-mgr/app-manager/module_config.h b/core/app-mgr/app-manager/module_config.h deleted file mode 100644 index b742fed3a..000000000 --- a/core/app-mgr/app-manager/module_config.h +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _MODULE_CONFIG_H_ -#define _MODULE_CONFIG_H_ - -#define ENABLE_MODULE_JEFF 0 -#define ENABLE_MODULE_WASM_APP 1 -#define ENABLE_MODULE_WASM_LIB 1 - -#ifdef ENABLE_MODULE_JEFF -#include "module_jeff.h" -#endif -#ifdef ENABLE_MODULE_WASM_APP -#include "module_wasm_app.h" -#endif -#ifdef ENABLE_MODULE_WASM_LIB -#include "module_wasm_lib.h" -#endif - -#endif /* _MODULE_CONFIG_H_ */ diff --git a/core/app-mgr/app-manager/module_jeff.c b/core/app-mgr/app-manager/module_jeff.c deleted file mode 100644 index 7c7f9510d..000000000 --- a/core/app-mgr/app-manager/module_jeff.c +++ /dev/null @@ -1,1883 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifdef ENABLE_JEFF - -#include "module_jeff.h" -#include "jeff_export.h" -#include "../vmcore_jeff/jeff-runtime.h" -#include "../vmcore_jeff/jeff-thread.h" -#include "../vmcore_jeff/jeff-buffer.h" -#include "../vmcore_jeff/jeff-tool.h" -#include "../vmcore_jeff/jeff-tool-priv.h" -#include "app_manager-host.h" -#include "bh_queue.h" -#include "attr-container.h" -#include "attr-container-util.h" -#include "bh_thread.h" -#include "ems_gc.h" -#include "coap_ext.h" -#include "libcore.h" -#include "event.h" -#include "watchdog.h" - -#define DEFAULT_APPLET_TIMEOUT (3 * 60 * 1000) -#define DEFAULT_APPLET_HEAP_SIZE (48 * 1024) -#define MIN_APPLET_HEAP_SIZE (2 * 1024) -#define MAX_APPLET_HEAP_SIZE (1024 * 1024) - -typedef struct jeff_applet_data { - /* Java Applet Object */ - JeffObjectRef applet_obj; - -#if BEIHAI_ENABLE_TOOL_AGENT != 0 - /* Whether the applet is in debug mode */ - bool debug_mode; - /* Queue of the tool agent */ - bh_queue *tool_agent_queue; -#endif - - /* VM instance */ - JeffInstanceLocalRoot *vm_instance; - /* Applet Main file */ - JeffFileHeaderLinked *main_file; - /* Permissions of the Java Applet */ - char *perms; -} jeff_applet_data; - -/* Jeff class com.intel.aee.AEEApplet */ -static JeffClassHeaderLinked *class_AEEApplet; -/* Jeff class com.intel.aee.Request */ -static JeffClassHeaderLinked *class_AEERequest; -/* Jeff class com.intel.aee.Timer */ -static JeffClassHeaderLinked *class_Timer; -/* Jeff class com.intel.aee.Sensor */ -static JeffClassHeaderLinked *class_Sensor; -/* Jeff class com.intel.aee.ble.BLEManager */ -static JeffClassHeaderLinked *class_BLEManager; -/* Jeff class com.intel.aee.ble.BLEDevice */ -static JeffClassHeaderLinked *class_BLEDevice; -/* Jeff class com.intel.aee.ble.BLEGattService */ -JeffClassHeaderLinked *class_BLEGattService; -/* Jeff class com.intel.aee.ble.BLEGattCharacteristic */ -JeffClassHeaderLinked *class_BLEGattCharacteristic; -/* Jeff class com.intel.aee.ble.BLEGattDescriptor */ -JeffClassHeaderLinked *class_BLEGattDescriptor; -/* Jeff class com.intel.aee.gpio.GPIOChannel */ -static JeffClassHeaderLinked *class_GPIOChannel; -/* Jeff method void com.intel.aee.AEEApplet.onInit() */ -static JeffMethodLinked *method_AEEApplet_onInit; -/* Jeff method void com.intel.aee.AEEApplet.onDestroy() */ -static JeffMethodLinked *method_AEEApplet_onDestroy; -/* Jeff method void com.intel.aee.AEEApplet.callOnRequest(Request request) */ -static JeffMethodLinked *method_AEEApplet_callOnRequest; -/* Jeff method void com.intel.aee.Timer.callOnTimer() */ -static JeffMethodLinked *method_callOnTimer; -/* Jeff method void com.intel.aee.Sensor.callOnSensorEvent() */ -static JeffMethodLinked *method_callOnSensorEvent; -/* Jeff method void com.intel.aee.ble.BLEManager.callOnBLEStartDiscovery() */ -static JeffMethodLinked *method_callOnBLEStartDiscovery; -/* Jeff method void com.intel.aee.ble.BLEManager.callOnBLEConnected() */ -static JeffMethodLinked *method_callOnBLEConnected; -/* Jeff method void com.intel.aee.ble.BLEManager.callOnBLEDisonnected() */ -static JeffMethodLinked *method_callOnBLEDisconnected; -/* Jeff method void com.intel.aee.ble.BLEManager.callOnBLENotification() */ -static JeffMethodLinked *method_callOnBLENotification; -/* Jeff method void com.intel.aee.ble.BLEManager.callOnBLEIndication() */ -static JeffMethodLinked *method_callOnBLEIndication; -/* Jeff method void com.intel.aee.ble.BLEManager.callOnBLEPasskeyEntry() */ -static JeffMethodLinked *method_callOnBLEPasskeyEntry; -/* Jeff method void com.intel.aee.gpio.GPIOChannel.callOnGPIOInterrupt() */ -static JeffMethodLinked *method_callOnGPIOInterrupt; -/* Jeff method void com.intel.aee.ble.BLEManager.getBLEDevice() */ -static JeffMethodLinked *method_callOnBLEManagerGetBLEDevice; - -static jeff_applet_data * -app_manager_get_jeff_applet_data() -{ - module_data *m_data = app_manager_get_module_data(Module_Jeff); - return (jeff_applet_data *)m_data->internal_data; -} - -#if BEIHAI_ENABLE_TOOL_AGENT != 0 -void * -app_manager_get_tool_agent_queue() -{ - return app_manager_get_jeff_applet_data()->tool_agent_queue; -} -#endif - -#if BEIHAI_ENABLE_TOOL_AGENT != 0 -static bool -is_tool_agent_running(module_data *m_data) -{ - jeff_applet_data *applet_data = (jeff_applet_data *)m_data->internal_data; - return (applet_data->debug_mode && applet_data->tool_agent_queue - && applet_data->vm_instance->tool_agent); -} -#endif - -static char * -get_class_qname(const JeffString *pname, const JeffString *cname) -{ - unsigned int length = - pname->length ? pname->length + 2 + cname->length : cname->length + 1; - char *buf = APP_MGR_MALLOC(length), *p; - - if (!buf) - return NULL; - - p = buf; - if (pname->length) { - bh_memcpy_s(p, pname->length, pname->value, pname->length); - p += pname->length; - *p++ = '.'; - } - - bh_memcpy_s(p, cname->length, cname->value, cname->length); - p += cname->length; - *p = '\0'; - - return buf; -} - -static void -send_exception_event_to_host(const char *applet_name, const char *exc_name) -{ - attr_container_t *payload; - bh_request_msg_t msg; - char *url; - int url_len; - - payload = attr_container_create("exception detail"); - if (!payload) { - app_manager_printf("Send exception to host fail: allocate memory"); - return; - } - - if (!attr_container_set_string(&payload, "exception name", exc_name) - || !attr_container_set_string(&payload, "stack trace", "TODO") - || !attr_container_set_string(&payload, "applet name", applet_name)) { - app_manager_printf("Send exception to host fail: set attr"); - goto fail; - } - - url_len = strlen("/exception/") + strlen(applet_name); - url = APP_MGR_MALLOC(url_len + 1); - if (!url) { - app_manager_printf("Send exception to host fail: allocate memory"); - goto fail; - } - memset(url, 0, url_len + 1); - bh_strcpy_s(url, url_len + 1, "/exception/"); - bh_strcat_s(url, url_len + 1, applet_name); - - memset(&msg, 0, sizeof(msg)); - msg.url = url; - msg.action = COAP_PUT; - msg.payload = (char *)payload; - - app_send_request_msg_to_host(&msg); - - APP_MGR_FREE(url); - -fail: - attr_container_destroy(payload); -} - -static bool -check_exception() -{ - if (jeff_runtime_get_exception()) { - jeff_printf("V1.Exception thrown when running applet '%s':\n", - app_manager_get_module_name(Module_Jeff)); - jeff_runtime_print_exception(); - jeff_printf("\n"); - jeff_printf(NULL); - } - - if (!app_manager_is_interrupting_module(Module_Jeff)) { - attr_container_t *payload; - int payload_len; - JeffClassHeaderLinked *exc_class = - jeff_object_class_pointer(jeff_runtime_get_exception()); - char *qname_buf = get_class_qname(jeff_get_class_pname(exc_class), - jeff_get_class_cname(exc_class)); - - /* Send exception event to host */ - if (qname_buf) { - send_exception_event_to_host( - app_manager_get_module_name(Module_Jeff), qname_buf); - APP_MGR_FREE(qname_buf); - } - - /* Uninstall the applet */ - if ((payload = attr_container_create("uninstall myself"))) { - if (attr_container_set_string( - &payload, "name", app_manager_get_module_name(Module_Jeff)) - /* Set special flag to prevent app manager making response - since this is an internal message */ - && attr_container_set_bool(&payload, "do not reply me", true)) { - request_t request = { 0 }; - payload_len = attr_container_get_serialize_length(payload); - - init_request(request, "/applet", COAP_DELETE, (char *)payload, payload_len)); - app_mgr_lookup_resource(&request); - - // TODO: confirm this is right - attr_container_destroy(payload); - } - } - - jeff_runtime_set_exception(NULL); - return true; - } - - return false; -} - -static bool -app_manager_initialize_class(JeffClassHeaderLinked *c) -{ - jeff_runtime_initialize_class(c); - return !check_exception(); -} - -static bool -app_manager_initialize_object(JeffObjectRef obj) -{ - jeff_runtime_initialize_object(obj); - return !check_exception(); -} - -static bool -app_manager_call_java(JeffMethodLinked *method, unsigned int argc, - uint32 argv[], uint8 argt[]) -{ - module_data *m_data = app_manager_get_module_data(Module_Jeff); - watchdog_timer *wd_timer = &m_data->wd_timer; - bool is_wd_started = false; - -#if BEIHAI_ENABLE_TOOL_AGENT != 0 - /* Only start watchdog when debugger is not running */ - if (!is_tool_agent_running(m_data)) { -#endif - watchdog_timer_start(wd_timer); - is_wd_started = true; -#if BEIHAI_ENABLE_TOOL_AGENT != 0 - } -#endif - - jeff_runtime_call_java(method, argc, argv, argt); - - if (is_wd_started) { - os_mutex_lock(&wd_timer->lock); - if (!wd_timer->is_interrupting) { - wd_timer->is_stopped = true; - watchdog_timer_stop(wd_timer); - } - os_mutex_unlock(&wd_timer->lock); - } - - return !check_exception(); -} - -static AEEBLEDevice -create_object_BLEDevice(ble_device_info *dev_info) -{ - JeffLocalObjectRef ref; - AEEBLEDevice dev_struct; - - jeff_runtime_push_local_object_ref(&ref); - - ref.val = jeff_runtime_new_object(class_BLEDevice); - - if (!ref.val) { - jeff_runtime_pop_local_object_ref(1); - return NULL; - } - - dev_struct = (AEEBLEDevice)(ref.val); - dev_struct->rssi = dev_info->rssi; - dev_struct->mac = - (jbyteArray)jeff_runtime_create_byte_array((int8 *)dev_info->mac, 6); - - app_manager_printf("adv_data_len:%d,scan_response_len:%d\n", - dev_info->adv_data_len, dev_info->scan_response_len); - - dev_struct->advData = (jbyteArray)jeff_runtime_create_byte_array( - (int8 *)dev_info->adv_data, dev_info->adv_data_len); - dev_struct->scanResponse = (jbyteArray)jeff_runtime_create_byte_array( - (int8 *)dev_info->scan_response, dev_info->scan_response_len); - dev_struct->addressType = dev_info->address_type; - jeff_runtime_initialize_object(ref.val); - jeff_runtime_pop_local_object_ref(1); - if ((dev_struct->mac == NULL) || (dev_struct->advData == NULL) - || (dev_struct->scanResponse == NULL)) { - return NULL; - } - return (AEEBLEDevice)ref.val; -} - -static void -app_instance_process_ble_msg(char *msg) -{ - bh_queue_ble_sub_msg_t *ble_msg = (bh_queue_ble_sub_msg_t *)msg; - unsigned int argv[5]; - uint8 argt[5]; - - ble_device_info *dev_info; - - dev_info = (ble_device_info *)ble_msg->payload; - AEEBLEDevice ble_dev; - - argv[0] = (unsigned int)(jbyteArray)jeff_runtime_create_byte_array( - (int8 *)dev_info->mac, 6); - argt[0] = 1; - if (!app_manager_call_java(method_callOnBLEManagerGetBLEDevice, 1, argv, - argt)) { - app_manager_printf( - "app_manager_call_java BLEManagerGetBLEDevice fail error\n"); - goto fail; - } - ble_dev = (AEEBLEDevice)argv[0]; - if (ble_dev == NULL) { - ble_dev = create_object_BLEDevice(dev_info); - if (ble_dev == NULL) { - goto fail; - } - } - - switch (ble_msg->type) { - case BLE_SUB_EVENT_DISCOVERY: - { - argv[0] = (unsigned int)ble_dev; - argt[0] = 1; - ble_dev->rssi = dev_info->rssi; - if (!app_manager_call_java(method_callOnBLEStartDiscovery, 1, argv, - argt)) { - app_manager_printf( - "app_manager_call_java method_callOnBLEStartDiscovery " - "fail error\n"); - goto fail; - } - break; - } - - case BLE_SUB_EVENT_CONNECTED: - { - if (ble_dev) { - argv[0] = (unsigned int)ble_dev; - argv[1] = 0; - argt[0] = 1; - argt[1] = 1; - if (!app_manager_call_java(method_callOnBLEConnected, 2, argv, - argt)) { - app_manager_printf( - "app_manager_call_java method_callOnBLEConnected " - "fail error\n"); - goto fail; - } - } - break; - } - - case BLE_SUB_EVENT_DISCONNECTED: - { - app_manager_printf("app instance received disconnected\n"); - - if (ble_dev) { - argv[0] = (unsigned int)ble_dev; - argv[1] = 0; - argt[0] = 1; - argt[1] = 1; - ble_dev->rssi = dev_info->rssi; - if (!app_manager_call_java(method_callOnBLEDisconnected, 2, - argv, argt)) { - app_manager_printf( - "app_manager_call_java " - "method_callOnBLEDisconnected fail error\n"); - goto fail; - } - } - break; - } - - case BLE_SUB_EVENT_NOTIFICATION: - { - if (ble_dev) { - argv[0] = (unsigned int)ble_dev; - argv[1] = - (unsigned int)(jbyteArray)jeff_runtime_create_byte_array( - (int8 *)dev_info->private_data, - dev_info->private_data_length); - argv[2] = dev_info->value_handle; - argv[3] = dev_info->ccc_handle; - argt[1] = 1; - argt[2] = 0; - argt[3] = 0; - ble_dev->rssi = dev_info->rssi; - if (!app_manager_call_java(method_callOnBLENotification, 4, - argv, argt)) { - app_manager_printf( - "app_manager_call_java " - "method_callOnBLENotification fail error\n"); - goto fail; - } - } - break; - } - - case BLE_SUB_EVENT_INDICATION: - { - if (ble_dev) { - argv[0] = (unsigned int)ble_dev; - argv[1] = - (unsigned int)(jbyteArray)jeff_runtime_create_byte_array( - (int8 *)dev_info->private_data, - dev_info->private_data_length); - argv[2] = dev_info->value_handle; - argv[3] = dev_info->ccc_handle; - argt[0] = 1; - argt[1] = 1; - argt[2] = 0; - argt[3] = 0; - ble_dev->rssi = dev_info->rssi; - if (!app_manager_call_java(method_callOnBLEIndication, 4, argv, - argt)) { - app_manager_printf( - "app_manager_call_java method_callOnBLEIndication " - "fail error\n"); - goto fail; - } - } - break; - } - - case BLE_SUB_EVENT_PASSKEYENTRY: - { - - if (ble_dev) { - argv[0] = (unsigned int)ble_dev; - argt[0] = 1; - argt[1] = 1; - ble_dev->rssi = dev_info->rssi; - if (!app_manager_call_java(method_callOnBLEPasskeyEntry, 1, - argv, argt)) { - app_manager_printf( - "app_manager_call_java " - "method_callOnBLEPasskeyEntry fail error\n"); - goto fail; - } - } - break; - } - - case BLE_SUB_EVENT_SECURITY_LEVEL_CHANGE: - { - if (ble_dev) { - ble_dev->securityLevel = dev_info->security_level; - } - break; - } - - default: - break; - } - -fail: - if (dev_info->scan_response != NULL) { - APP_MGR_FREE(dev_info->scan_response); - } - if (dev_info->private_data != NULL) { - APP_MGR_FREE(dev_info->private_data); - } - - if (dev_info->adv_data != NULL) { - APP_MGR_FREE(dev_info->adv_data); - } - if (dev_info != NULL) { - APP_MGR_FREE(dev_info); - } -} - -static void -app_instance_free_ble_msg(char *msg) -{ - bh_queue_ble_sub_msg_t *ble_msg = (bh_queue_ble_sub_msg_t *)msg; - ble_device_info *dev_info; - - dev_info = (ble_device_info *)ble_msg->payload; - - if (dev_info->scan_response != NULL) - APP_MGR_FREE(dev_info->scan_response); - - if (dev_info->private_data != NULL) - APP_MGR_FREE(dev_info->private_data); - - if (dev_info->adv_data != NULL) - APP_MGR_FREE(dev_info->adv_data); - - if (dev_info != NULL) - APP_MGR_FREE(dev_info); -} - -static void -app_instance_queue_free_callback(void *queue_msg) -{ - bh_queue_msg_t *msg = (bh_queue_msg_t *)queue_msg; - - switch (msg->message_type) { - case APPLET_REQUEST: - { - bh_request_msg_t *req_msg = (bh_request_msg_t *)msg->payload; - APP_MGR_FREE(req_msg); - break; - } - - case TIMER_EVENT: - { - break; - } - - case SENSOR_EVENT: - { - if (msg->payload) { - bh_sensor_event_t *sensor_event = - (bh_sensor_event_t *)msg->payload; - attr_container_t *event = sensor_event->event; - - attr_container_destroy(event); - APP_MGR_FREE(sensor_event); - } - break; - } - - case BLE_EVENT: - { - if (msg->payload) { - app_instance_free_ble_msg(msg->payload); - APP_MGR_FREE(msg->payload); - } - break; - } - - case GPIO_INTERRUPT_EVENT: - { - break; - } - - default: - { - break; - } - } - - APP_MGR_FREE(msg); -} - -static void -app_instance_queue_callback(void *queue_msg) -{ - bh_queue_msg_t *msg = (bh_queue_msg_t *)queue_msg; - unsigned int argv[5]; - uint8 argt[5]; - - if (app_manager_is_interrupting_module(Module_Jeff)) { - app_instance_queue_free_callback(queue_msg); - return; - } - - switch (msg->message_type) { - case APPLET_REQUEST: - { - JeffLocalObjectRef ref; - AEERequest req_obj; - bh_request_msg_t *req_msg = (bh_request_msg_t *)msg->payload; - attr_container_t *attr_cont = (attr_container_t *)req_msg->payload; - module_data *m_data = app_manager_get_module_data(Module_Jeff); - jeff_applet_data *applet_data = - (jeff_applet_data *)m_data->internal_data; - - app_manager_printf("Applet %s got request, url %s, action %d\n", - m_data->module_name, req_msg->url, - req_msg->action); - - /* Create Request object */ - req_obj = - (AEERequest)jeff_object_new(m_data->heap, class_AEERequest); - if (!req_obj) { - app_manager_printf("Applet process request failed: create " - "request obj failed.\n"); - goto fail1; - } - - jeff_runtime_push_local_object_ref(&ref); - ref.val = (JeffObjectRef)req_obj; - - req_obj->mid = req_msg->mid; - req_obj->action = req_msg->action; - req_obj->fmt = req_msg->fmt; - - /* Create Java url string */ - if (req_msg->url) { - req_obj->url = - (jstring)jeff_runtime_create_java_string(req_msg->url); - if (!req_obj->url) { - app_manager_printf("Applet process request failed: " - "create url string failed.\n"); - goto fail2; - } - } - - /* Create Java AttributeObject payload */ - if (attr_cont - && !attr_container_to_attr_obj(attr_cont, &req_obj->payload)) { - app_manager_printf("Applet process request failed: convert " - "payload failed.\n"); - goto fail2; - } - - /* Call AEEApplet.callOnRequest(Request request) method */ - argv[0] = (unsigned int)applet_data->applet_obj; - argv[1] = (unsigned int)req_obj; - argt[0] = argt[1] = 1; - app_manager_call_java(method_AEEApplet_callOnRequest, 2, argv, - argt); - app_manager_printf("Applet process request success.\n"); - - fail2: - jeff_runtime_pop_local_object_ref(1); - fail1: - APP_MGR_FREE(req_msg); - break; - } - - case TIMER_EVENT: - { - if (msg->payload) { - /* Call Timer.callOnTimer() method */ - argv[0] = (unsigned int)msg->payload; - argt[0] = 1; - app_manager_call_java(method_callOnTimer, 1, argv, argt); - } - break; - } - - case SENSOR_EVENT: - { - if (msg->payload) { - bh_sensor_event_t *sensor_event = - (bh_sensor_event_t *)msg->payload; - AEESensor sensor = sensor_event->sensor; - attr_container_t *event = sensor_event->event; - bool ret = attr_container_to_attr_obj(event, &sensor->event); - - attr_container_destroy(event); - APP_MGR_FREE(sensor_event); - - if (ret) { - /* Call Sensor.callOnSensorEvent() method */ - argv[0] = (unsigned int)sensor; - argt[0] = 1; - app_manager_call_java(method_callOnSensorEvent, 1, argv, - argt); - } - } - break; - } - - case BLE_EVENT: - { - if (msg->payload) { - app_instance_process_ble_msg(msg->payload); - APP_MGR_FREE(msg->payload); - } - break; - } - - case GPIO_INTERRUPT_EVENT: - { - AEEGPIOChannel gpio_ch = (AEEGPIOChannel)msg->payload; - - if ((gpio_ch == NULL) || (gpio_ch->callback == 0) - || (gpio_ch->listener == NULL)) { - break; - } - argv[0] = (unsigned int)gpio_ch; - argt[0] = 1; - bool ret_value = app_manager_call_java(method_callOnGPIOInterrupt, - 1, argv, argt); - - if (!ret_value) { - app_manager_printf( - "app_manager_call_java " - "method_method_callOnGPIOInterrupt return false\n"); - } - break; - } - - default: - { - app_manager_printf( - "Invalid message type of applet queue message.\n"); - break; - } - } - - APP_MGR_FREE(msg); -} - -static JeffClassHeaderLinked * -find_main_class(JeffFileHeaderLinked *main_file) -{ - JeffClassHeaderLinked *c = NULL, *ci; - unsigned int i; - - for (i = 0; i < main_file->internal_class_count; i++) { - ci = main_file->class_header[i]; - - if (jeff_is_super_class(class_AEEApplet, ci) - && (ci->access_flag & JEFF_ACC_PUBLIC)) { - if (c) { - jeff_printe_more_than_one_main_class(); - return NULL; - } - - c = ci; - } - } - - if (!c) - jeff_printe_no_main_class(); - - return c; -} - -/* Java applet thread main routine */ -static void * -app_instance_main(void *arg) -{ - module_data *m_data = (module_data *)arg; - jeff_applet_data *applet_data = (jeff_applet_data *)m_data->internal_data; - JeffClassHeaderLinked *object_class; - JeffMethodLinked *m; - unsigned int argv[1]; - uint8 argt[1]; - - app_manager_printf("Java Applet '%s' started\n", m_data->module_name); - -#if BEIHAI_ENABLE_TOOL_AGENT != 0 - if (applet_data->debug_mode) - jeff_tool_suspend_self(); -#endif - - applet_data->vm_instance->applet_object = applet_data->applet_obj; - object_class = jeff_object_class_pointer(applet_data->applet_obj); - m = jeff_select_method_virtual(object_class, method_AEEApplet_onInit); - bh_assert(m != NULL); - /* Initialize applet class which call */ - if (!app_manager_initialize_class(object_class)) { - app_manager_printf("Call fail\n"); - goto fail; - } - - /* Initialize applet object which call */ - if (!app_manager_initialize_object(applet_data->applet_obj)) { - app_manager_printf("Call fail\n"); - goto fail; - } - - /* Call applet's onInit() method */ - argv[0] = (unsigned int)applet_data->applet_obj; - argt[0] = 1; - if (app_manager_call_java(m, 1, argv, argt)) - /* Enter queue loop run to receive and process applet queue message - */ - bh_queue_enter_loop_run(m_data->queue, app_instance_queue_callback); - -fail: - applet_data->vm_instance->applet_object = applet_data->applet_obj; - object_class = jeff_object_class_pointer(applet_data->applet_obj); - m = jeff_select_method_virtual(object_class, method_AEEApplet_onDestroy); - bh_assert(m != NULL); - /* Call User Applet or AEEApplet onDestroy() method */ - app_manager_call_java(m, 1, argv, argt); - if (m != method_AEEApplet_onDestroy) { - /*If 'm' is user onDestroy, then Call AEEApplet.onDestroy() method*/ - app_manager_call_java(method_AEEApplet_onDestroy, 1, argv, argt); - } - app_manager_printf("Applet instance main thread exit.\n"); - return NULL; -} - -static bool -verify_signature(JeffFileHeader *file, unsigned size) -{ - uint8 *sig; - unsigned sig_size; - -#if BEIHAI_ENABLE_NO_SIGNATURE != 0 - /* no signature */ - if (file->file_signature == 0) - return true; -#endif - - if (file->file_length != size -#if BEIHAI_ENABLE_NO_SIGNATURE == 0 - || file->file_signature == 0 -#endif - || file->file_signature >= file->file_length) - return false; - - sig = (uint8 *)file + file->file_signature; - sig_size = file->file_length - file->file_signature; - - if (0 - == app_manager_signature_verify((uint8_t *)file, file->file_signature, - sig, sig_size)) - return false; - - return true; -} - -/* Install Java Applet */ -static bool -jeff_module_install(bh_request_msg_t *msg) -{ - unsigned int size, bpk_file_len, main_file_len, heap_size, timeout; - uint8 *bpk_file; - JeffFileHeaderLinked *main_file; - JeffClassHeaderLinked *main_class; - module_data *m_data; - jeff_applet_data *applet_data; - char *applet_name, *applet_perm; - attr_container_t *attr_cont; - bool debug = false; - - /* Check url */ - if (!msg->url || strcmp(msg->url, "/applet") != 0) { - SEND_ERR_RESPONSE(msg->mid, "Install Applet failed: invalid url."); - return false; - } - - /* Check payload */ - attr_cont = (attr_container_t *)msg->payload; - if (!attr_cont - || !(bpk_file = (uint8 *)attr_container_get_as_bytearray( - attr_cont, "bpk", &bpk_file_len))) { - SEND_ERR_RESPONSE(msg->mid, "Install Applet failed: invalid bpk file."); - return false; - } - - /* Check applet name */ - applet_name = attr_container_get_as_string(attr_cont, "name"); - - if (!applet_name || strlen(applet_name) == 0) { - SEND_ERR_RESPONSE(msg->mid, - "Install Applet failed: invalid applet name."); - return false; - } - - if (app_manager_lookup_module_data(applet_name)) { - SEND_ERR_RESPONSE(msg->mid, - "Install Applet failed: applet already installed."); - return false; - } - - /* TODO: convert bpk file to Jeff file */ - main_file_len = bpk_file_len; - main_file = APP_MGR_MALLOC(main_file_len); - if (!main_file) { - SEND_ERR_RESPONSE(msg->mid, - "Install Applet failed: allocate memory failed."); - return false; - } - bh_memcpy_s(main_file, main_file_len, bpk_file, main_file_len); - - /* Verify signature */ - if (!verify_signature((JeffFileHeader *)main_file, main_file_len)) { - SEND_ERR_RESPONSE( - msg->mid, - "Install Applet failed: verify Jeff file signature failed."); - goto fail1; - } - - /* Load Jeff main file */ - if (!jeff_runtime_load(main_file, main_file_len, false, NULL, NULL)) { - SEND_ERR_RESPONSE(msg->mid, - "Install Applet failed: load Jeff file failed."); - goto fail1; - } - - /* Find main class */ - main_class = find_main_class(main_file); - if (!main_class) { - SEND_ERR_RESPONSE(msg->mid, - "Install Applet failed: find applet class failed."); - goto fail2; - } - - /* Create module data */ - size = offsetof(module_data, module_name) + strlen(applet_name) + 1; - size = align_uint(size, 4); - m_data = APP_MGR_MALLOC(size + sizeof(jeff_applet_data)); - if (!m_data) { - SEND_ERR_RESPONSE(msg->mid, - "Install Applet failed: allocate memory failed."); - goto fail2; - } - - memset(m_data, 0, size + sizeof(jeff_applet_data)); - m_data->module_type = Module_Jeff; - m_data->internal_data = (uint8 *)m_data + size; - applet_data = (jeff_applet_data *)m_data->internal_data; - bh_strcpy_s(m_data->module_name, strlen(applet_name) + 1, applet_name); - applet_data->main_file = main_file; - - /* Set applet execution timeout */ - timeout = DEFAULT_APPLET_TIMEOUT; - if (attr_container_contain_key(attr_cont, "execution timeout")) - timeout = attr_container_get_as_int(attr_cont, "execution timeout"); - m_data->timeout = timeout; - - /* Create applet permissions */ - applet_perm = attr_container_get_as_string(attr_cont, "perm"); - if (applet_perm != NULL) { - applet_data->perms = APP_MGR_MALLOC(strlen(applet_perm) + 1); - if (!applet_data->perms) { - SEND_ERR_RESPONSE(msg->mid, - "Install Applet failed: allocate memory for " - "applet permissions failed."); - goto fail3; - } - - bh_strcpy_s(applet_data->perms, strlen(applet_perm) + 1, applet_perm); - } - - /* Create applet queue */ - m_data->queue = bh_queue_create(); - if (!m_data->queue) { - SEND_ERR_RESPONSE(msg->mid, - "Install Applet failed: create applet queue failed."); - goto fail3_1; - } - - /* Set heap size */ - heap_size = DEFAULT_APPLET_HEAP_SIZE; - if (attr_container_contain_key(attr_cont, "heap size")) { - heap_size = attr_container_get_as_int(attr_cont, "heap size"); - if (heap_size < MIN_APPLET_HEAP_SIZE) - heap_size = MIN_APPLET_HEAP_SIZE; - else if (heap_size > MAX_APPLET_HEAP_SIZE) - heap_size = MAX_APPLET_HEAP_SIZE; - } - - m_data->heap_size = heap_size; - - /* Create applet heap */ - m_data->heap = gc_init_for_instance(heap_size); - if (!m_data->heap) { - SEND_ERR_RESPONSE(msg->mid, - "Install Applet failed: create heap failed."); - goto fail4; - } - - /* Create applet object */ - applet_data->applet_obj = jeff_object_new(m_data->heap, main_class); - if (!applet_data->applet_obj) { - SEND_ERR_RESPONSE( - msg->mid, "Install Applet failed: create applet object failed."); - goto fail5; - } - - /* Initialize watchdog timer */ - if (!watchdog_timer_init(m_data)) { - SEND_ERR_RESPONSE( - msg->mid, - "Install Applet failed: create applet watchdog timer failed."); - goto fail5; - } - -#if BEIHAI_ENABLE_TOOL_AGENT != 0 - /* Check whether applet is debuggable */ - if (attr_container_contain_key(attr_cont, "debug")) - debug = attr_container_get_as_bool(attr_cont, "debug"); - - applet_data->debug_mode = debug; - - /* Create tool agent queue */ - if (debug && !(applet_data->tool_agent_queue = bh_queue_create())) { - SEND_ERR_RESPONSE( - msg->mid, "Install Applet failed: create tool agent queue failed."); - goto fail5_1; - } -#endif - - /* Create applet instance */ - applet_data->vm_instance = jeff_runtime_create_instance( - main_file, m_data->heap, 16, app_instance_main, m_data, NULL); - if (!applet_data->vm_instance) { - SEND_ERR_RESPONSE(msg->mid, - "Install Applet failed: create Java VM failed"); - goto fail6; - } - - /* Add applet data to applet data list */ - applet_data->vm_instance->applet_object = applet_data->applet_obj; - app_manager_add_module_data(m_data); - app_manager_post_applets_update_event(); - -#if BEIHAI_ENABLE_TOOL_AGENT != 0 - /* Start tool agent thread */ - if (debug - && !jeff_tool_start_agent(applet_data->vm_instance, - applet_data->tool_agent_queue)) { - SEND_ERR_RESPONSE(msg->mid, - "Install Applet failed: start tool agent failed"); - goto fail6; - } -#endif - - app_manager_printf("Install Applet success!\n"); - app_send_response_to_host(msg->mid, CREATED_2_01, NULL); /* CREATED */ - return true; - -fail6: -#if BEIHAI_ENABLE_TOOL_AGENT != 0 - if (debug) - bh_queue_destroy(applet_data->tool_agent_queue); -#endif - -fail5_1: - watchdog_timer_destroy(&m_data->wd_timer); - -fail5: - gc_destroy_for_instance(m_data->heap); - -fail4: - bh_queue_destroy(m_data->queue, NULL); - -fail3_1: - APP_MGR_FREE(applet_data->perms); - -fail3: - APP_MGR_FREE(applet_data); - -fail2: - jeff_runtime_unload(main_file); - -fail1: - APP_MGR_FREE(main_file); - - return false; -} - -static void -cleanup_applet_resource(module_data *m_data) -{ - jeff_applet_data *applet_data = (jeff_applet_data *)m_data->internal_data; - - /* Unload Jeff main file and free it */ - jeff_runtime_unload(applet_data->main_file); - APP_MGR_FREE(applet_data->main_file); - - /* Destroy queue */ - bh_queue_destroy(m_data->queue, app_instance_queue_free_callback); - - /* Destroy heap */ - gc_destroy_for_instance(m_data->heap); - - /* Destroy watchdog timer */ - watchdog_timer_destroy(&m_data->wd_timer); - - /* Remove module data from module data list and free it */ - app_manager_del_module_data(m_data); - APP_MGR_FREE(applet_data->perms); - APP_MGR_FREE(m_data); -} - -/* Uninstall Java Applet */ -static bool -jeff_module_uninstall(bh_request_msg_t *msg) -{ - module_data *m_data; - jeff_applet_data *applet_data; - attr_container_t *attr_cont; - char *applet_name; - bool do_not_reply = false; - - /* Check payload and applet name*/ - attr_cont = (attr_container_t *)msg->payload; - - /* Check whether need to reply this request */ - if (attr_container_contain_key(attr_cont, "do not reply me")) - do_not_reply = attr_container_get_as_bool(attr_cont, "do not reply me"); - - /* Check url */ - if (!msg->url || strcmp(msg->url, "/applet") != 0) { - if (!do_not_reply) - SEND_ERR_RESPONSE(msg->mid, - "Uninstall Applet failed: invalid url."); - else - app_manager_printf("Uninstall Applet failed: invalid url."); - return false; - } - - if (!attr_cont - || !(applet_name = attr_container_get_as_string(attr_cont, "name")) - || strlen(applet_name) == 0) { - if (!do_not_reply) - SEND_ERR_RESPONSE(msg->mid, - "Uninstall Applet failed: invalid applet name."); - else - app_manager_printf("Uninstall Applet failed: invalid applet name."); - return false; - } - - m_data = app_manager_lookup_module_data(applet_name); - if (!m_data) { - if (!do_not_reply) - SEND_ERR_RESPONSE(msg->mid, - "Uninstall Applet failed: no applet found."); - else - app_manager_printf("Uninstall Applet failed: no applet found."); - return false; - } - - if (m_data->module_type != Module_Jeff) { - if (!do_not_reply) - SEND_ERR_RESPONSE(msg->mid, - "Uninstall Applet failed: invlaid module type."); - else - app_manager_printf("Uninstall Applet failed: invalid module type."); - return false; - } - - if (m_data->wd_timer.is_interrupting) { - if (!do_not_reply) - SEND_ERR_RESPONSE(msg->mid, - "Uninstall Applet failed: applet is being " - "interrupted by watchdog."); - else - app_manager_printf("Uninstall Applet failed: applet is being " - "interrupted by watchdog."); - return false; - } - - /* Exit applet queue loop run */ - bh_queue_exit_loop_run(m_data->queue); - - applet_data = (jeff_applet_data *)m_data->internal_data; -#if BEIHAI_ENABLE_TOOL_AGENT != 0 - /* Exit tool agent queue loop run */ - if (is_tool_agent_running(m_data)) { - bh_queue_exit_loop_run(applet_data->tool_agent_queue); - } -#endif - - /* Wait the end of the applet instance and then destroy it */ - if (applet_data->vm_instance->main_file) - jeff_runtime_wait_for_instance(applet_data->vm_instance, -1); - jeff_runtime_destroy_instance(applet_data->vm_instance); - - cleanup_applet_resource(m_data); - app_manager_post_applets_update_event(); - - app_manager_printf("Uninstall Applet success!\n"); - - if (!do_not_reply) - app_send_response_to_host(msg->mid, DELETED_2_02, NULL); /* DELETED */ - return true; -} - -#define PERM_PREFIX "AEE.permission." - -static bool -check_permission_format(const char *perm) -{ - const char *prefix = PERM_PREFIX; - const char *p; - - if (perm == NULL || strncmp(perm, prefix, strlen(prefix)) != 0 - || *(p = perm + strlen(prefix)) == '\0') - return false; - - do { - if (!(*p == '.' || ('A' <= *p && *p <= 'Z') - || ('a' <= *p && *p <= 'z'))) - return false; - } while (*++p != '\0'); - - return true; -} - -static bool -match(const char *haystack, const char *needle, char delim) -{ - const char *p = needle; - - if (haystack == NULL || *haystack == '\0' || needle == NULL - || *needle == '\0') - return false; - - while (true) { - while (true) { - if ((*haystack == '\0' || *haystack == delim) && *p == '\0') { - return true; - } - else if (*p == *haystack) { - ++p; - ++haystack; - } - else { - break; - } - } - while (*haystack != '\0' && *haystack != delim) { - ++haystack; - } - if (*haystack == '\0') { - return false; - } - else { - ++haystack; - p = needle; - } - } -} - -bool -bh_applet_check_permission(const char *perm) -{ - return check_permission_format(perm) - && match(app_manager_get_jeff_applet_data()->perms, - perm + strlen(PERM_PREFIX), ' '); -} - -static bool -jeff_module_init() -{ - JeffDescriptorFull d[] = { { JEFF_TYPE_VOID, 0, NULL } }; - JeffDescriptorFull d1[] = { { JEFF_TYPE_OBJECT | JEFF_TYPE_REF, 0, NULL }, - { JEFF_TYPE_VOID, 0, NULL } }; - - /* Resolve class com.intel.aee.AEEApplet */ - class_AEEApplet = - jeff_runtime_resolve_class_full_name("com.intel.aee.AEEApplet"); - if (!class_AEEApplet) { - app_manager_printf( - "App Manager start failed: resolve class AEEApplet failed.\n"); - return false; - } - - /* Resolve class com.intel.aee.Request */ - class_AEERequest = - jeff_runtime_resolve_class_full_name("com.intel.aee.Request"); - if (!class_AEERequest) { - app_manager_printf( - "App Manager start failed: resolve class Request failed.\n"); - return false; - } - - /* Resolve class com.intel.aee.Timer */ - class_Timer = jeff_runtime_resolve_class_full_name("com.intel.aee.Timer"); - if (!class_Timer) { - app_manager_printf( - "App Manager start failed: resolve class Timer failed.\n"); - return false; - } - - /* Resolve class com.intel.aee.Sensor */ - class_Sensor = jeff_runtime_resolve_class_full_name("com.intel.aee.Sensor"); - if (!class_Sensor) { - app_manager_printf( - "App Manager start failed: resolve class Sensor failed.\n"); - return false; - } - - /* Resolve class com.intel.aee.ble.BLEManager */ - class_BLEManager = - jeff_runtime_resolve_class_full_name("com.intel.aee.ble.BLEManager"); - if (!class_BLEManager) { - app_manager_printf( - "App Manager start failed: resolve class BLEManager failed.\n"); - return false; - } - - /* Resolve class com.intel.aee.ble.BLEDevice */ - class_BLEDevice = - jeff_runtime_resolve_class_full_name("com.intel.aee.ble.BLEDevice"); - if (!class_BLEDevice) { - app_manager_printf( - "App Manager start failed: resolve class BLEDevice failed.\n"); - return false; - } - /* Resolve class com.intel.aee.ble.BLEDevice */ - class_BLEGattService = jeff_runtime_resolve_class_full_name( - "com.intel.aee.ble.BLEGattService"); - if (!class_BLEGattService) { - app_manager_printf("App Manager start failed: resolve class " - "BLEGattService failed.\n"); - return false; - } - - /* Resolve class com.intel.aee.ble.BLEDevice */ - class_BLEGattCharacteristic = jeff_runtime_resolve_class_full_name( - "com.intel.aee.ble.BLEGattCharacteristic"); - if (!class_BLEGattCharacteristic) { - app_manager_printf("App Manager start failed: resolve class " - "BLEGattCharacteristic failed.\n"); - return false; - } - - /* Resolve class com.intel.aee.ble.BLEDevice */ - class_BLEGattDescriptor = jeff_runtime_resolve_class_full_name( - "com.intel.aee.ble.BLEGattDescriptor"); - if (!class_BLEGattDescriptor) { - app_manager_printf("App Manager start failed: resolve class " - "BLEGattDescriptor failed.\n"); - return false; - } - /* Resolve class com.intel.aee.gpio.GPIOChannel */ - class_GPIOChannel = - jeff_runtime_resolve_class_full_name("com.intel.aee.gpio.GPIOChannel"); - if (!class_GPIOChannel) { - app_manager_printf("App Manager start failed: resolve class " - "GPIOChannel failed.\n"); - return false; - } - - /* Resolve method com.intel.aee.AEEApplet.onInit() */ - method_AEEApplet_onInit = - jeff_lookup_method(class_AEEApplet, "onInit", 0, d); - if (!method_AEEApplet_onInit) { - app_manager_printf("App Manager start failed: resolve method " - "Applet.onInit() failed.\n"); - return false; - } - - /* Resolve method com.intel.aee.AEEApplet.onDestroy() */ - method_AEEApplet_onDestroy = - jeff_lookup_method(class_AEEApplet, "onDestroy", 0, d); - if (!method_AEEApplet_onDestroy) { - app_manager_printf("App Manager start failed: resolve method " - "AEEApplet.onDestroy() failed.\n"); - return false; - } - - /* Resolve method com.intel.aee.AEEApplet.callOnRequest(Request) */ - d1[0].class_header = class_AEERequest; - method_AEEApplet_callOnRequest = - jeff_lookup_method(class_AEEApplet, "callOnRequest", 1, d1); - if (!method_AEEApplet_callOnRequest) { - app_manager_printf("App Manager start failed: resolve method " - "AEEApplet.callOnRequest() failed.\n"); - return false; - } - - /* Resolve method com.intel.aee.Timer.callOnTimer() */ - method_callOnTimer = jeff_lookup_method(class_Timer, "callOnTimer", 0, d); - if (!method_callOnTimer) { - app_manager_printf("App Manager start failed: resolve method " - "Timer.callOnTimer() failed.\n"); - return false; - } - - /* Resolve method com.intel.aee.Sensor.callOnSensorEvent() */ - method_callOnSensorEvent = - jeff_lookup_method(class_Sensor, "callOnSensorEvent", 0, d); - if (!method_callOnSensorEvent) { - app_manager_printf("App Manager start failed: resolve method " - "Sensor.callOnSensorEvent() failed.\n"); - return false; - } - - /* Resovle method - * com.intel.aee.ble.BLEManager.callOnBLEStartDiscovery(BLEDevice) */ - d1[0].class_header = class_BLEDevice; - method_callOnBLEStartDiscovery = - jeff_lookup_method(class_BLEManager, "callOnBLEStartDiscovery", 1, d1); - if (!method_callOnBLEStartDiscovery) { - app_manager_printf("App Manager start failed: resolve method " - "BLEManager.callOnBLEStartDiscovery() failed.\n"); - return false; - } - - /* Resovle method - * com.intel.aee.ble.BLEManager.callOnBLEConnected(BLEDevice) */ - JeffDescriptorFull d2_1[] = { { JEFF_TYPE_OBJECT | JEFF_TYPE_REF, 0, - class_BLEDevice }, - { JEFF_TYPE_INT, 0, NULL }, - { JEFF_TYPE_VOID, 0, NULL } }; - method_callOnBLEConnected = - jeff_lookup_method(class_BLEManager, "callOnBLEConnected", 2, d2_1); - if (!method_callOnBLEConnected) { - app_manager_printf("App Manager start failed: resolve method " - "BLEManager.callOnBLEConnected() failed.\n"); - return false; - } - - /* Resovle method - * com.intel.aee.ble.BLEManager.method_callOnBLENotification(BLEDevice,byte[]) - */ - JeffDescriptorFull d2_2[] = { - { JEFF_TYPE_OBJECT | JEFF_TYPE_REF, 0, class_BLEDevice }, - { JEFF_TYPE_BYTE | JEFF_TYPE_REF | JEFF_TYPE_MONO, 1, NULL }, - { JEFF_TYPE_INT, 0, NULL }, - { JEFF_TYPE_INT, 0, NULL }, - { JEFF_TYPE_VOID, 0, NULL } - }; - method_callOnBLENotification = - jeff_lookup_method(class_BLEManager, "callOnBLENotification", 4, d2_2); - if (!method_callOnBLENotification) { - app_manager_printf("App Manager start failed: resolve method " - "BLEManager.callOnBLENotification() failed.\n"); - return false; - } - - /* Resovle method - * com.intel.aee.ble.BLEManager.callOnBLEConnected(BLEDevice,byte[]) */ - method_callOnBLEIndication = - jeff_lookup_method(class_BLEManager, "callOnBLEIndication", 4, d2_2); - if (!method_callOnBLEIndication) { - app_manager_printf("App Manager start failed: resolve method " - "BLEManager.callOnBLEIndication() failed.\n"); - return false; - } - - /* Resovle method - * com.intel.aee.ble.BLEManager.callOnBLEConnected(BLEDevice) */ - d1[0].class_header = class_BLEDevice; - method_callOnBLEDisconnected = - jeff_lookup_method(class_BLEManager, "callOnBLEDisconnected", 1, d1); - if (!method_callOnBLEDisconnected) { - app_manager_printf("App Manager start failed: resolve method " - "BLEManager.callOnBLEDisconnected() failed.\n"); - return false; - } - - /* Resovle method - * com.intel.aee.ble.BLEManager.callOnBLEConnected(BLEDevice) */ - method_callOnBLEPasskeyEntry = - jeff_lookup_method(class_BLEManager, "callOnBLEPasskeyEntry", 1, d1); - if (!method_callOnBLEPasskeyEntry) { - app_manager_printf("App Manager start failed: resolve method " - "BLEManager.callOnBLEPasskeyEntry() failed.\n"); - return false; - } - /* Resovle method void - * com.intel.aee.gpio.GPIOChannel.callOnGPIOInterrupt() */ - method_callOnGPIOInterrupt = - jeff_lookup_method(class_GPIOChannel, "callOnGPIOInterrupt", 0, d); - if (!method_callOnGPIOInterrupt) { - app_manager_printf("App Manager start failed: resolve method " - "GPIOChannel.callOnGPIOInterrupt() failed.\n"); - return false; - } - - JeffDescriptorFull d2[] = { - { JEFF_TYPE_BYTE | JEFF_TYPE_REF | JEFF_TYPE_MONO, 1, NULL }, - { JEFF_TYPE_OBJECT | JEFF_TYPE_REF, 0, class_BLEDevice } - }; - /* Resovle method com.intel.aee.ble.BLEManager.getBLEDevice(byte []) */ - method_callOnBLEManagerGetBLEDevice = - jeff_lookup_method(class_BLEManager, "getBLEDevice", 1, d2); - if (!method_callOnBLEManagerGetBLEDevice) { - app_manager_printf("App Manager start failed: resolve method " - "BLEManager.getBLEDevice() failed.\n"); - return false; - } - - return true; -} - -static void -jeff_module_watchdog_kill(module_data *m_data) -{ - jeff_applet_data *applet_data = (jeff_applet_data *)m_data->internal_data; - - app_manager_printf("Watchdog interrupt the applet %s\n", - m_data->module_name); - - jeff_runtime_interrupt_instance(applet_data->vm_instance, true); - - /* Exit applet queue loop run */ - bh_queue_exit_loop_run(m_data->queue); - - /* Wait the end of the applet instance. If timeout, it means applet - * is busy executing native code, then try to cancle the main thread. */ - if (applet_data->vm_instance->main_file) - jeff_runtime_wait_for_instance(applet_data->vm_instance, 3000); - - if (applet_data->vm_instance->main_file) { - app_manager_printf("Watchdog cancel applet main thread.\n"); - os_thread_cancel(applet_data->vm_instance->main_tlr.handle); - /* k_thread_abort(applet_data->vm_instance->main_tlr.handle); */ - } - - send_exception_event_to_host(m_data->module_name, - "java.lang.InterruptedException"); - cleanup_applet_resource(m_data); - app_manager_printf("Watchdog interrupt Jeff applet done.\n"); -} - -static bool -jeff_module_handle_host_url(void *queue_msg) -{ -#if BEIHAI_ENABLE_TOOL_AGENT != 0 - bh_queue_msg_t *msg = (bh_queue_msg_t *)queue_msg; - - if (msg->message_type == COAP_PARSED) { - coap_packet_t *packet = (coap_packet_t *)msg->payload; - attr_container_t *attr_cont = (attr_container_t *)packet->payload; - const char *url = NULL; - int url_len = 0, mid; - - bh_memcpy_s(&mid, sizeof(uint32), packet->token, sizeof(uint32)); - url_len = coap_get_header_uri_path(packet, &url); - - /* Send request to tool agent */ - if (url_len >= 12 && memcmp(url, "/tool_agent/", 12) == 0) { - module_data *m_data; - jeff_applet_data *applet_data; - unsigned attr_cont_len = 0, req_msg_len; - bh_queue_msg_t *tool_agent_msg; - bh_request_msg_t *req_msg; - char url_buf[256] = { 0 }, *p = url_buf; - char applet_name[128] = { 0 }; - - /* Resolve applet name */ - bh_memcpy_s(url_buf, sizeof(url_buf), url + 12, url_len - 12); - while (*p != '/' && *p != '\0') - p++; - - bh_memcpy_s(applet_name, sizeof(applet_name), url_buf, p - url_buf); - app_manager_printf("Send request to tool agent of applet: %s\n", - applet_name); - - /* Check applet name */ - if (!(m_data = app_manager_lookup_module_data(applet_name))) { - SEND_ERR_RESPONSE(mid, "Send request to tool agent failed: " - "invalid applet name"); - return false; - } - - applet_data = (jeff_applet_data *)m_data->internal_data; - /* Attach debug: start the tool agent firstly */ - if (packet->code == COAP_PUT) { - if (is_tool_agent_running(m_data)) { - SEND_ERR_RESPONSE(mid, "Attach debug failed: tool " - "agent is already exist."); - return false; - } - - applet_data->debug_mode = true; - - /* Create tool agent queue */ - if (!(applet_data->tool_agent_queue = bh_queue_create())) { - SEND_ERR_RESPONSE(mid, "Attach debug failed: create " - "tool agent queue failed."); - return false; - } - - /* Start tool agent thread */ - if (!jeff_tool_start_agent(applet_data->vm_instance, - applet_data->tool_agent_queue)) { - bh_queue_destroy(applet_data->tool_agent_queue, NULL); - SEND_ERR_RESPONSE( - mid, "Attach debug failed: start tool agent failed"); - return false; - } - - app_manager_printf("Attach debug: start tool agent of " - "applet %s success.\n", - applet_name); - app_send_response_to_host(mid, CREATED_2_01, NULL); /* OK */ - } - else { - /* Check tool agent running */ - if (!is_tool_agent_running(m_data)) { - SEND_ERR_RESPONSE(mid, "Send request to tool agent failed: " - "tool agent is not running"); - return false; - } - - /* Create queue message for tool agent */ - if (!(tool_agent_msg = - APP_MGR_MALLOC(sizeof(bh_queue_msg_t)))) { - SEND_ERR_RESPONSE(mid, "Send request to tool agent failed: " - "allocate memory failed"); - return false; - } - - if (attr_cont) - attr_cont_len = - attr_container_get_serialize_length(attr_cont); - - req_msg_len = - sizeof(bh_request_msg_t) + strlen(p) + 1 + attr_cont_len; - - /* Create request message */ - if (!(req_msg = APP_MGR_MALLOC(req_msg_len))) { - SEND_ERR_RESPONSE(mid, "Send request to applet failed: " - "allocate memory failed"); - APP_MGR_FREE(tool_agent_msg); - return false; - } - - /* Set request message */ - memset(req_msg, 0, req_msg_len); - req_msg->mid = mid; - req_msg->url = (char *)req_msg + sizeof(bh_request_msg_t); - bh_strcpy_s(req_msg->url, strlen(p) + 1, - p); /* Actual url sent to tool agent */ - req_msg->action = packet->code; - req_msg->fmt = 0; - if (attr_cont) { - req_msg->payload = (char *)req_msg - + sizeof(bh_request_msg_t) + strlen(p) - + 1; - attr_container_serialize(req_msg->payload, attr_cont); - } - - /* Set queue message and send to tool agent's queue */ - tool_agent_msg->message_type = JDWP_REQUEST; - tool_agent_msg->payload_size = req_msg_len; - tool_agent_msg->payload = (char *)req_msg; - if (!bh_queue_send_message(applet_data->tool_agent_queue, - tool_agent_msg)) { - APP_MGR_FREE(req_msg); - APP_MGR_FREE(tool_agent_msg); - SEND_ERR_RESPONSE(mid, "Send request to tool agent failed: " - "send queue msg failed."); - return false; - } - - /* app_manager_printf("Send request to tool agent of applet - * %s success.\n", applet_name); */ - } - - return true; - } - } -#endif /* BEIHAI_ENABLE_TOOL_AGENT != 0 */ - return false; -} - -static module_data * -jeff_module_get_module_data(void) -{ - JeffThreadLocalRoot *self = jeff_runtime_get_tlr(); - return (module_data *)self->il_root->start_routine_arg; -} - -#if BEIHAI_ENABLE_TOOL_AGENT != 0 - -#define JDWP_HANDSHAKE_MAGIC "JDWP-Handshake" -#define JDWP_HANDSHAKE_LEN (sizeof(JDWP_HANDSHAKE_MAGIC) - 1) - -#define JDWP_PAYLOAD_KEY "jdwp" - -static bool debug = true; - -static bool -send_msg_to_host(int mid, const char *url, int code, const uint8 *msg, - unsigned size) -{ - bool ret; - int payload_len = 0; - attr_container_t *payload = NULL; - - if (msg) { - if ((payload = attr_container_create(""))) { - attr_container_set_bytearray(&payload, JDWP_PAYLOAD_KEY, - (const int8_t *)msg, size); - payload_len = attr_container_get_serialize_length(payload); - } - } - ret = app_send_msg_to_host(mid, url, code, (char *)payload, payload_len); - - if (payload) - attr_container_destroy(payload); - - return ret; -} - -static bool -send_response(int mid, int code, const uint8 *msg, unsigned size) -{ - return send_msg_to_host(mid, NULL, code, msg, size); -} - -static bool -send_packet_response(int mid, int code, JeffBuffer *packet) -{ - int size; - - if ((size = jeff_buffer_size(packet)) == 0) - /* No data need to be written, succeed. */ - return true; - - return send_msg_to_host(mid, NULL, code, jeff_buffer_at(packet, 0), size); -} - -void -jeff_tool_event_publish(uint8 *evtbuf, unsigned size) -{ - char *prefix = "/jdwp/", *url = NULL; - int url_len; - - url_len = strlen(prefix) + strlen(app_manager_get_module_name(Module_Jeff)); - if (NULL == (url = jeff_runtime_malloc(url_len + 1))) - return; - - bh_strcpy_s(url, url_len + 1, prefix); - bh_strcat_s(url, url_len + 1, app_manager_get_module_name(Module_Jeff)); - - /* Event is sent as request so we set code as COAP_PUT */ - if (event_is_registered(url)) - send_msg_to_host(0, url, COAP_PUT, evtbuf, size); - - jeff_runtime_free(url); -} - -#define SEND_ERROR_RESPONSE(err_msg) \ - do { \ - app_manager_printf("%s\n", err_msg); \ - send_response(req_msg->mid, INTERNAL_SERVER_ERROR_5_00, \ - (uint8 *)err_msg, strlen(err_msg) + 1); \ - } while (0) - -/* Queue callback of tool agent */ -void -tool_agent_queue_callback(void *arg) -{ - bh_queue_msg_t *msg = (bh_queue_msg_t *)arg; - - if (msg->message_type == JDWP_REQUEST) { - bh_request_msg_t *req_msg = (bh_request_msg_t *)msg->payload; - attr_container_t *attr_cont = (attr_container_t *)req_msg->payload; - JeffThreadLocalRoot *self = jeff_runtime_get_tlr(); - JeffInstanceLocalRoot *cur_instance = self->il_root; - JeffToolAgent *agent = cur_instance->tool_agent; - bh_queue *queue = (bh_queue *)self->start_routine_arg; - - if (debug) - app_manager_printf( - "Tool Agent of applet %s got request, url %s, action %d\n", - app_manager_get_module_name(Module_Jeff), req_msg->url, - req_msg->action); - - /* Handshake or Process Request */ - if (req_msg->action == COAP_GET) { - uint8 *buf; - unsigned buf_len; - - if (!attr_cont - || !(buf = (uint8 *)attr_container_get_as_bytearray( - attr_cont, JDWP_PAYLOAD_KEY, &buf_len))) { - SEND_ERROR_RESPONSE("Tool Agent fail: invalid JDWP payload."); - goto fail; - } - - if (!agent->connected) { - if (buf_len != JDWP_HANDSHAKE_LEN - || memcmp(buf, JDWP_HANDSHAKE_MAGIC, JDWP_HANDSHAKE_LEN)) { - SEND_ERROR_RESPONSE("Tool Agent fail: handshake fail."); - goto fail; - } - - /* Handshake success and response */ - agent->connected = true; - send_response(req_msg->mid, CONTENT_2_05, buf, buf_len); - } - else { - /* TODO: tool-agent thread should reuse the request/reply - * buffer to avoid allocating memory repeatedly */ - JeffBuffer request, reply; - - /* Initialize the package buffers. */ - jeff_buffer_init(&request); - jeff_buffer_init(&reply); - - if (!jeff_buffer_resize(&request, buf_len)) { - SEND_ERROR_RESPONSE("Tool Agent fail: resize buffer fail."); - jeff_buffer_destroy(&request); - jeff_buffer_destroy(&reply); - goto fail; - } - - /* Copy data from request to jeff buffer */ - bh_memcpy_s(jeff_buffer_at(&request, 0), - jeff_buffer_size(&request), buf, buf_len); - - /* Handle JDWP request */ - if (!jeff_tool_handle_packet(agent, &request, &reply)) { - SEND_ERROR_RESPONSE( - "Tool agent fail: handle request fail."); - jeff_buffer_destroy(&request); - jeff_buffer_destroy(&reply); - goto fail; - } - - /* Response JDWP reply */ - send_packet_response(req_msg->mid, CONTENT_2_05, &reply); - - /* Destroy the package buffers. */ - jeff_buffer_destroy(&request); - jeff_buffer_destroy(&reply); - } - } - /* Debugger disconnect */ - else if (req_msg->action == COAP_DELETE) { - send_response(req_msg->mid, DELETED_2_02, NULL, 0); - bh_queue_exit_loop_run(queue); - } - else { - SEND_ERROR_RESPONSE("Tool agent fail: invalid request."); - goto fail; - } - - APP_MGR_FREE(req_msg); - APP_MGR_FREE(msg); - return; - - fail: - bh_queue_exit_loop_run(queue); - APP_MGR_FREE(req_msg); - } - - APP_MGR_FREE(msg); -} - -void -tool_agent_queue_free_callback(void *message) -{ - bh_queue_msg_t *msg = (bh_queue_msg_t *)message; - - if (msg->message_type == JDWP_REQUEST) { - bh_request_msg_t *req_msg = (bh_request_msg_t *)msg->payload; - APP_MGR_FREE(req_msg); - } - - APP_MGR_FREE(msg); -} - -#endif /* BEIHAI_ENABLE_TOOL_AGENT != 0 */ - -/* clang-format off */ -module_interface jeff_module_interface = { - jeff_module_init, - jeff_module_install, - jeff_module_uninstall, - jeff_module_watchdog_kill, - jeff_module_handle_host_url, - jeff_module_get_module_data, - NULL -}; -/* clang-format on */ - -#endif diff --git a/core/app-mgr/app-manager/module_jeff.h b/core/app-mgr/app-manager/module_jeff.h deleted file mode 100644 index bb39f27e4..000000000 --- a/core/app-mgr/app-manager/module_jeff.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _MODULE_JEFF_H_ -#define _MODULE_JEFF_H_ - -#include "app_manager.h" - -#ifdef __cplusplus -extern "C" { -#endif - -extern module_interface jeff_module_interface; - -/* sensor event */ -typedef struct bh_sensor_event_t { - /* Java sensor object */ - void *sensor; - /* event of attribute container from context core */ - void *event; -} bh_sensor_event_t; - -#ifdef __cplusplus -} /* end of extern "C" */ -#endif - -#endif /* _MODULE_JEFF_H_ */ diff --git a/core/app-mgr/app-manager/module_utils.c b/core/app-mgr/app-manager/module_utils.c deleted file mode 100644 index b4b25e4a9..000000000 --- a/core/app-mgr/app-manager/module_utils.c +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "app_manager.h" -#include "app_manager_host.h" -#include "bh_platform.h" -#include "bi-inc/attr_container.h" -#include "event.h" -#include "watchdog.h" -#include "coap_ext.h" - -/* Lock of the module data list */ -korp_mutex module_data_list_lock; - -/* Module data list */ -module_data *module_data_list; - -bool -module_data_list_init() -{ - module_data_list = NULL; - return !os_mutex_init(&module_data_list_lock) ? true : false; -} - -void -module_data_list_destroy() -{ - - os_mutex_lock(&module_data_list_lock); - if (module_data_list) { - while (module_data_list) { - module_data *p = module_data_list->next; - APP_MGR_FREE(module_data_list); - module_data_list = p; - } - } - os_mutex_unlock(&module_data_list_lock); - os_mutex_destroy(&module_data_list_lock); -} - -static void -module_data_list_add(module_data *m_data) -{ - static uint32 module_id_max = 1; - os_mutex_lock(&module_data_list_lock); - // reserve some special ID - // TODO: check the new id is not already occupied! - if (module_id_max == 0xFFFFFFF0) - module_id_max = 1; - m_data->id = module_id_max++; - if (!module_data_list) { - module_data_list = m_data; - } - else { - /* Set as head */ - m_data->next = module_data_list; - module_data_list = m_data; - } - os_mutex_unlock(&module_data_list_lock); -} - -void -module_data_list_remove(module_data *m_data) -{ - os_mutex_lock(&module_data_list_lock); - if (module_data_list) { - if (module_data_list == m_data) - module_data_list = module_data_list->next; - else { - /* Search and remove it */ - module_data *p = module_data_list; - - while (p && p->next != m_data) - p = p->next; - if (p && p->next == m_data) - p->next = p->next->next; - } - } - os_mutex_unlock(&module_data_list_lock); -} - -module_data * -module_data_list_lookup(const char *module_name) -{ - os_mutex_lock(&module_data_list_lock); - if (module_data_list) { - module_data *p = module_data_list; - - while (p) { - /* Search by module name */ - if (!strcmp(module_name, p->module_name)) { - os_mutex_unlock(&module_data_list_lock); - return p; - } - p = p->next; - } - } - os_mutex_unlock(&module_data_list_lock); - return NULL; -} - -module_data * -module_data_list_lookup_id(unsigned int module_id) -{ - os_mutex_lock(&module_data_list_lock); - if (module_data_list) { - module_data *p = module_data_list; - - while (p) { - /* Search by module name */ - if (module_id == p->id) { - os_mutex_unlock(&module_data_list_lock); - return p; - } - p = p->next; - } - } - os_mutex_unlock(&module_data_list_lock); - return NULL; -} - -module_data * -app_manager_get_module_data(uint32 module_type, void *module_inst) -{ - if (module_type < Module_Max && g_module_interfaces[module_type] - && g_module_interfaces[module_type]->module_get_module_data) - return g_module_interfaces[module_type]->module_get_module_data( - module_inst); - return NULL; -} - -void * -app_manager_get_module_queue(uint32 module_type, void *module_inst) -{ - module_data *m_data = app_manager_get_module_data(module_type, module_inst); - return m_data ? m_data->queue : NULL; -} - -const char * -app_manager_get_module_name(uint32 module_type, void *module_inst) -{ - module_data *m_data = app_manager_get_module_data(module_type, module_inst); - return m_data ? m_data->module_name : NULL; -} - -unsigned int -app_manager_get_module_id(uint32 module_type, void *module_inst) -{ - module_data *m_data = app_manager_get_module_data(module_type, module_inst); - return m_data ? m_data->id : ID_NONE; -} - -void * -app_manager_get_module_heap(uint32 module_type, void *module_inst) -{ - module_data *m_data = app_manager_get_module_data(module_type, module_inst); - return m_data ? m_data->heap : NULL; -} - -module_data * -app_manager_lookup_module_data(const char *name) -{ - return module_data_list_lookup(name); -} - -void -app_manager_add_module_data(module_data *m_data) -{ - module_data_list_add(m_data); -} - -void -app_manager_del_module_data(module_data *m_data) -{ - module_data_list_remove(m_data); - - release_module(m_data); -} - -bool -app_manager_is_interrupting_module(uint32 module_type, void *module_inst) -{ - module_data *m_data = app_manager_get_module_data(module_type, module_inst); - return m_data ? m_data->wd_timer.is_interrupting : false; -} - -extern void -destroy_module_timer_ctx(unsigned int module_id); - -void -release_module(module_data *m_data) -{ - watchdog_timer_destroy(&m_data->wd_timer); - -#ifdef HEAP_ENABLED /* TODO */ - if (m_data->heap) - gc_destroy_for_instance(m_data->heap); -#endif - - if (m_data->queue) - bh_queue_destroy(m_data->queue); - - m_data->timer_ctx = NULL; - - destroy_module_timer_ctx(m_data->id); - - APP_MGR_FREE(m_data); -} - -uint32 -check_modules_timer_expiry() -{ - os_mutex_lock(&module_data_list_lock); - module_data *p = module_data_list; - uint32 ms_to_expiry = (uint32)-1; - - while (p) { - uint32 next = get_expiry_ms(p->timer_ctx); - if (next != (uint32)-1) { - if (ms_to_expiry == (uint32)-1 || ms_to_expiry > next) - ms_to_expiry = next; - } - - p = p->next; - } - os_mutex_unlock(&module_data_list_lock); - return ms_to_expiry; -} diff --git a/core/app-mgr/app-manager/module_wasm_app.c b/core/app-mgr/app-manager/module_wasm_app.c index 6fd929b10..cee62e906 100644 --- a/core/app-mgr/app-manager/module_wasm_app.c +++ b/core/app-mgr/app-manager/module_wasm_app.c @@ -1230,8 +1230,12 @@ wasm_app_module_on_install_request_byte_arrive(uint8 ch, int request_total_size, uint8 section_type = ch; #if WASM_ENABLE_BULK_MEMORY == 0 uint8 section_type_max = SECTION_TYPE_DATA; +#else +#if WASM_ENABLE_STRINGREF != 0 + uint8 section_type_max = SECTION_TYPE_STRINGREF; #else uint8 section_type_max = SECTION_TYPE_DATACOUNT; +#endif /* end of WASM_ENABLE_STRINGREF != 0 */ #endif if (section_type <= section_type_max) { wasm_section_t *new_section; diff --git a/core/app-mgr/app-manager/module_wasm_app.h b/core/app-mgr/app-manager/module_wasm_app.h deleted file mode 100644 index 8a7ae4e54..000000000 --- a/core/app-mgr/app-manager/module_wasm_app.h +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _MODULE_WASM_APP_H_ -#define _MODULE_WASM_APP_H_ - -#include "bh_queue.h" -#include "app_manager_export.h" -#include "wasm_export.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define SECTION_TYPE_USER 0 -#define SECTION_TYPE_TYPE 1 -#define SECTION_TYPE_IMPORT 2 -#define SECTION_TYPE_FUNC 3 -#define SECTION_TYPE_TABLE 4 -#define SECTION_TYPE_MEMORY 5 -#define SECTION_TYPE_GLOBAL 6 -#define SECTION_TYPE_EXPORT 7 -#define SECTION_TYPE_START 8 -#define SECTION_TYPE_ELEM 9 -#define SECTION_TYPE_CODE 10 -#define SECTION_TYPE_DATA 11 - -typedef enum AOTSectionType { - AOT_SECTION_TYPE_TARGET_INFO = 0, - AOT_SECTION_TYPE_INIT_DATA = 1, - AOT_SECTION_TYPE_TEXT = 2, - AOT_SECTION_TYPE_FUNCTION = 3, - AOT_SECTION_TYPE_EXPORT = 4, - AOT_SECTION_TYPE_RELOCATION = 5, - AOT_SECTION_TYPE_SIGANATURE = 6, - AOT_SECTION_TYPE_CUSTOM = 100, -} AOTSectionType; - -enum { - WASM_Msg_Start = BASE_EVENT_MAX, - TIMER_EVENT_WASM, - SENSOR_EVENT_WASM, - CONNECTION_EVENT_WASM, - WIDGET_EVENT_WASM, - WASM_Msg_End = WASM_Msg_Start + 100 -}; - -typedef struct wasm_data { - /* for easily access the containing wasm module */ - wasm_module_t wasm_module; - wasm_module_inst_t wasm_module_inst; - /* Permissions of the WASM app */ - char *perms; - /* thread list mapped with this WASM module */ - korp_tid thread_id; - /* for easily access the containing module data */ - module_data *m_data; - /* is bytecode or aot */ - bool is_bytecode; - /* sections of wasm bytecode or aot file */ - void *sections; - /* execution environment */ - wasm_exec_env_t exec_env; -} wasm_data; - -/* sensor event */ -typedef struct _sensor_event_data { - uint32 sensor_id; - - int data_fmt; - /* event of attribute container from context core */ - void *data; -} sensor_event_data_t; - -/* WASM Bytecode File */ -typedef struct wasm_bytecode_file { - /* magics */ - int magic; - /* current version */ - int version; - /* WASM section list */ - wasm_section_list_t sections; - /* Last WASM section in the list */ - wasm_section_t *section_end; -} wasm_bytecode_file_t; - -/* WASM AOT File */ -typedef struct wasm_aot_file { - /* magics */ - int magic; - /* current version */ - int version; - /* AOT section list */ - aot_section_list_t sections; - /* Last AOT section in the list */ - aot_section_t *section_end; -} wasm_aot_file_t; - -/* WASM App File */ -typedef struct wasm_app_file_t { - union { - wasm_bytecode_file_t bytecode; - wasm_aot_file_t aot; - } u; -} wasm_app_file_t; - -extern module_interface wasm_app_module_interface; - -typedef void (*message_type_handler_t)(module_data *m_data, bh_message_t msg); -extern bool -wasm_register_msg_callback(int msg_type, - message_type_handler_t message_handler); - -typedef void (*resource_cleanup_handler_t)(uint32 module_id); -extern bool -wasm_register_cleanup_callback(resource_cleanup_handler_t handler); - -/** - * Set WASI root dir for modules. On each wasm app installation, a sub dir named - * with the app's name will be created autamically. That wasm app can only - * access this sub dir. - * - * @param root_dir the root dir to set - * @return true for success, false otherwise - */ -bool -wasm_set_wasi_root_dir(const char *root_dir); - -/** - * Get WASI root dir - * - * @return the WASI root dir - */ -const char * -wasm_get_wasi_root_dir(); - -#ifdef __cplusplus -} /* end of extern "C" */ -#endif - -#endif /* _MODULE_WASM_APP_H_ */ diff --git a/core/app-mgr/app-manager/module_wasm_lib.c b/core/app-mgr/app-manager/module_wasm_lib.c deleted file mode 100644 index 0b5c07ea7..000000000 --- a/core/app-mgr/app-manager/module_wasm_lib.c +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "module_wasm_lib.h" - -static bool -wasm_lib_module_init(void) -{ - return false; -} - -static bool -wasm_lib_module_install(request_t *msg) -{ - (void)msg; - return false; -} - -static bool -wasm_lib_module_uninstall(request_t *msg) -{ - (void)msg; - return false; -} - -static void -wasm_lib_module_watchdog_kill(module_data *m_data) -{ - (void)m_data; -} - -static bool -wasm_lib_module_handle_host_url(void *queue_msg) -{ - (void)queue_msg; - return false; -} - -static module_data * -wasm_lib_module_get_module_data(void *inst) -{ - (void)inst; - return NULL; -} - -/* clang-format off */ -module_interface wasm_lib_module_interface = { - wasm_lib_module_init, - wasm_lib_module_install, - wasm_lib_module_uninstall, - wasm_lib_module_watchdog_kill, - wasm_lib_module_handle_host_url, - wasm_lib_module_get_module_data, - NULL -}; -/* clang-format on */ diff --git a/core/app-mgr/app-manager/module_wasm_lib.h b/core/app-mgr/app-manager/module_wasm_lib.h deleted file mode 100644 index 63ffd92b5..000000000 --- a/core/app-mgr/app-manager/module_wasm_lib.h +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _MODULE_WASM_LIB_H_ -#define _MODULE_WASM_LIB_H_ - -#include "app_manager.h" - -#ifdef __cplusplus -extern "C" { -#endif - -extern module_interface wasm_lib_module_interface; - -#ifdef __cplusplus -} /* end of extern "C" */ -#endif - -#endif /* _MODULE_WASM_LIB_H_ */ diff --git a/core/app-mgr/app-manager/platform/darwin/app_mgr_darwin.c b/core/app-mgr/app-manager/platform/darwin/app_mgr_darwin.c deleted file mode 100644 index 1c7409f55..000000000 --- a/core/app-mgr/app-manager/platform/darwin/app_mgr_darwin.c +++ /dev/null @@ -1 +0,0 @@ -#include "../linux/app_mgr_linux.c" diff --git a/core/app-mgr/app-manager/platform/linux/app_mgr_linux.c b/core/app-mgr/app-manager/platform/linux/app_mgr_linux.c deleted file mode 100644 index 5e51788bc..000000000 --- a/core/app-mgr/app-manager/platform/linux/app_mgr_linux.c +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "app_manager.h" - -void * -app_manager_timer_create(void (*timer_callback)(void *), - watchdog_timer *wd_timer) -{ - /* TODO */ - return NULL; -} - -void -app_manager_timer_destroy(void *timer) -{ - /* TODO */ -} - -void -app_manager_timer_start(void *timer, int timeout) -{ - /* TODO */ -} - -void -app_manager_timer_stop(void *timer) -{ - /* TODO */ -} - -watchdog_timer * -app_manager_get_wd_timer_from_timer_handle(void *timer) -{ - /* TODO */ - return NULL; -} - -int -app_manager_signature_verify(const uint8_t *file, unsigned int file_len, - const uint8_t *signature, unsigned int sig_size) -{ - return 1; -} diff --git a/core/app-mgr/app-manager/resource_reg.c b/core/app-mgr/app-manager/resource_reg.c deleted file mode 100644 index 4e930890e..000000000 --- a/core/app-mgr/app-manager/resource_reg.c +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "native_interface.h" -#include "app_manager.h" -#include "app_manager_export.h" -#include "bi-inc/shared_utils.h" -#include "bi-inc/attr_container.h" -#include "coap_ext.h" - -typedef struct _app_res_register { - struct _app_res_register *next; - char *url; - void (*request_handler)(request_t *, void *); - uint32 register_id; -} app_res_register_t; - -static app_res_register_t *g_resources = NULL; - -void -module_request_handler(request_t *request, void *user_data) -{ - unsigned int mod_id = (unsigned int)(uintptr_t)user_data; - bh_message_t msg; - module_data *m_data; - request_t *req; - - /* Check module name */ - m_data = module_data_list_lookup_id(mod_id); - if (!m_data) { - return; - } - - if (m_data->wd_timer.is_interrupting) { - return; - } - - req = clone_request(request); - if (!req) { - return; - } - - /* Set queue message and send to applet's queue */ - msg = bh_new_msg(RESTFUL_REQUEST, req, sizeof(*req), request_cleaner); - if (!msg) { - request_cleaner(req); - return; - } - - if (!bh_post_msg2(m_data->queue, msg)) { - return; - } - - app_manager_printf("Send request to app %s success.\n", - m_data->module_name); -} - -void -targeted_app_request_handler(request_t *request, void *unused) -{ - char applet_name[128] = { 0 }; - int offset; - char *url = request->url; - module_data *m_data; - - offset = check_url_start(request->url, strlen(request->url), "/app/"); - - if (offset <= 0) { - return; - } - - strncpy(applet_name, request->url + offset, sizeof(applet_name) - 1); - char *p = strchr(applet_name, '/'); - if (p) { - *p = 0; - } - else - return; - app_manager_printf("Send request to applet: %s\n", applet_name); - - request->url = p + 1; - - /* Check module name */ - m_data = module_data_list_lookup(applet_name); - if (!m_data) { - SEND_ERR_RESPONSE(request->mid, - "Send request to applet failed: invalid applet name"); - goto end; - } - - module_request_handler(request, (void *)(uintptr_t)m_data->id); -end: - request->url = url; -} - -void -am_send_response(response_t *response) -{ - module_data *m_data; - - // if the receiver is not any of modules, just forward it to the host - m_data = module_data_list_lookup_id(response->reciever); - if (!m_data) { - send_response_to_host(response); - } - else { - response_t *resp_for_send = clone_response(response); - if (!resp_for_send) { - return; - } - - bh_message_t msg = bh_new_msg(RESTFUL_RESPONSE, resp_for_send, - sizeof(*resp_for_send), response_cleaner); - if (!msg) { - response_cleaner(resp_for_send); - return; - } - - if (!bh_post_msg2(m_data->queue, msg)) { - return; - } - } -} - -void * -am_dispatch_request(request_t *request) -{ - app_res_register_t *r = g_resources; - - while (r) { - if (check_url_start(request->url, strlen(request->url), r->url) > 0) { - r->request_handler(request, (void *)(uintptr_t)r->register_id); - return r; - } - r = r->next; - } - return NULL; -} - -bool -am_register_resource(const char *url, - void (*request_handler)(request_t *, void *), - uint32 register_id) -{ - app_res_register_t *r = g_resources; - int register_num = 0; - - while (r) { - if (strcmp(r->url, url) == 0) { - return false; - } - - if (r->register_id == register_id) - register_num++; - - r = r->next; - } - - if (strlen(url) > RESOUCE_EVENT_URL_LEN_MAX) - return false; - - if (register_num >= RESOURCE_REGISTRATION_NUM_MAX) - return false; - - r = (app_res_register_t *)APP_MGR_MALLOC(sizeof(app_res_register_t)); - if (r == NULL) - return false; - - memset(r, 0, sizeof(*r)); - r->url = bh_strdup(url); - if (r->url == NULL) { - APP_MGR_FREE(r); - return false; - } - - r->request_handler = request_handler; - r->next = g_resources; - r->register_id = register_id; - g_resources = r; - - return true; -} - -void -am_cleanup_registeration(uint32 register_id) -{ - app_res_register_t *r = g_resources; - app_res_register_t *prev = NULL; - - while (r) { - app_res_register_t *next = r->next; - - if (register_id == r->register_id) { - if (prev) - prev->next = next; - else - g_resources = next; - - APP_MGR_FREE(r->url); - APP_MGR_FREE(r); - } - else - /* if r is freed, should not change prev. Only set prev to r - when r isn't freed. */ - prev = r; - - r = next; - } -} diff --git a/core/app-mgr/app-manager/watchdog.c b/core/app-mgr/app-manager/watchdog.c deleted file mode 100644 index ba5bb05f5..000000000 --- a/core/app-mgr/app-manager/watchdog.c +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "watchdog.h" -#include "bh_platform.h" - -#define WATCHDOG_THREAD_PRIORITY 5 - -/* Queue of watchdog */ -static bh_queue *watchdog_queue; - -#ifdef WATCHDOG_ENABLED /* TODO */ -static void -watchdog_timer_callback(void *timer) -{ - watchdog_timer *wd_timer = - app_manager_get_wd_timer_from_timer_handle(timer); - - watchdog_timer_stop(wd_timer); - - os_mutex_lock(&wd_timer->lock); - - if (!wd_timer->is_stopped) { - - wd_timer->is_interrupting = true; - - bh_post_msg(watchdog_queue, WD_TIMEOUT, wd_timer->module_data, - sizeof(module_data)); - } - - os_mutex_unlock(&wd_timer->lock); -} -#endif - -bool -watchdog_timer_init(module_data *m_data) -{ -#ifdef WATCHDOG_ENABLED /* TODO */ - watchdog_timer *wd_timer = &m_data->wd_timer; - - if (0 != os_mutex_init(&wd_timer->lock)) - return false; - - if (!(wd_timer->timer_handle = - app_manager_timer_create(watchdog_timer_callback, wd_timer))) { - os_mutex_destroy(&wd_timer->lock); - return false; - } - - wd_timer->module_data = m_data; - wd_timer->is_interrupting = false; - wd_timer->is_stopped = false; -#endif - return true; -} - -void -watchdog_timer_destroy(watchdog_timer *wd_timer) -{ -#ifdef WATCHDOG_ENABLED /* TODO */ - app_manager_timer_destroy(wd_timer->timer_handle); - os_mutex_destroy(&wd_timer->lock); -#endif -} - -void -watchdog_timer_start(watchdog_timer *wd_timer) -{ - os_mutex_lock(&wd_timer->lock); - - wd_timer->is_interrupting = false; - wd_timer->is_stopped = false; - app_manager_timer_start(wd_timer->timer_handle, - wd_timer->module_data->timeout); - - os_mutex_unlock(&wd_timer->lock); -} - -void -watchdog_timer_stop(watchdog_timer *wd_timer) -{ - app_manager_timer_stop(wd_timer->timer_handle); -} - -#ifdef WATCHDOG_ENABLED /* TODO */ -static void -watchdog_queue_callback(void *queue_msg) -{ - if (bh_message_type(queue_msg) == WD_TIMEOUT) { - module_data *m_data = (module_data *)bh_message_payload(queue_msg); - if (g_module_interfaces[m_data->module_type] - && g_module_interfaces[m_data->module_type]->module_watchdog_kill) { - g_module_interfaces[m_data->module_type]->module_watchdog_kill( - m_data); - app_manager_post_applets_update_event(); - } - } -} -#endif - -#ifdef WATCHDOG_ENABLED /* TODO */ -static void * -watchdog_thread_routine(void *arg) -{ - /* Enter loop run */ - bh_queue_enter_loop_run(watchdog_queue, watchdog_queue_callback); - - (void)arg; - return NULL; -} -#endif - -bool -watchdog_startup() -{ - if (!(watchdog_queue = bh_queue_create())) { - app_manager_printf( - "App Manager start failed: create watchdog queue failed.\n"); - return false; - } -#if 0 -//todo: enable watchdog - /* Start watchdog thread */ - if (!jeff_runtime_create_supervisor_thread_with_prio(watchdog_thread_routine, NULL, - WATCHDOG_THREAD_PRIORITY)) { - bh_queue_destroy(watchdog_queue); - return false; - } -#endif - return true; -} - -void -watchdog_destroy() -{ - bh_queue_exit_loop_run(watchdog_queue); - bh_queue_destroy(watchdog_queue); -} diff --git a/core/app-mgr/app-manager/watchdog.h b/core/app-mgr/app-manager/watchdog.h deleted file mode 100644 index d960df03b..000000000 --- a/core/app-mgr/app-manager/watchdog.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _WATCHDOG_H_ -#define _WATCHDOG_H_ - -#include "app_manager.h" - -#ifdef __cplusplus -extern "C" { -#endif - -bool -watchdog_timer_init(module_data *module_data); - -void -watchdog_timer_destroy(watchdog_timer *wd_timer); - -void -watchdog_timer_start(watchdog_timer *wd_timer); - -void -watchdog_timer_stop(watchdog_timer *wd_timer); - -watchdog_timer * -app_manager_get_watchdog_timer(void *timer); - -bool -watchdog_startup(); - -void -watchdog_destroy(); - -#ifdef __cplusplus -} /* end of extern "C" */ -#endif - -#endif /* _WATCHDOG_H_ */ diff --git a/core/app-mgr/app-mgr-shared/app_manager_export.h b/core/app-mgr/app-mgr-shared/app_manager_export.h deleted file mode 100644 index 54b59b944..000000000 --- a/core/app-mgr/app-mgr-shared/app_manager_export.h +++ /dev/null @@ -1,307 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _APP_MANAGER_EXPORT_H_ -#define _APP_MANAGER_EXPORT_H_ - -#include "native_interface.h" -#include "bi-inc/shared_utils.h" -#include "bh_queue.h" -#include "host_link.h" -#include "runtime_timer.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* Special module IDs */ -#define ID_HOST -3 -#define ID_APP_MGR -2 -/* Invalid module ID */ -#define ID_NONE ((uint32)-1) - -struct attr_container; - -/* Queue message type */ -typedef enum QUEUE_MSG_TYPE { - COAP_PARSED = LINK_MSG_TYPE_MAX + 1, - RESTFUL_REQUEST, - RESTFUL_RESPONSE, - TIMER_EVENT = 5, - SENSOR_EVENT = 6, - GPIO_INTERRUPT_EVENT = 7, - BLE_EVENT = 8, - JDWP_REQUEST = 9, - WD_TIMEOUT = 10, - BASE_EVENT_MAX = 100 - -} QUEUE_MSG_TYPE; - -typedef enum { - Module_Jeff, - Module_WASM_App, - Module_WASM_Lib, - Module_Max -} Module_Type; - -struct module_data; - -/* Watchdog timer of module */ -typedef struct watchdog_timer { - /* Timer handle of the platform */ - void *timer_handle; - /* Module of the watchdog timer */ - struct module_data *module_data; - /* Lock of the watchdog timer */ - korp_mutex lock; - /* Flag indicates module is being interrupted by watchdog */ - bool is_interrupting; - /* Flag indicates watchdog timer is stopped */ - bool is_stopped; -} watchdog_timer; - -typedef struct module_data { - struct module_data *next; - - /* ID of the module */ - uint32 id; - - /* Type of the module */ - Module_Type module_type; - - /* Heap of the module */ - void *heap; - - /* Heap size of the module */ - int heap_size; - - /* Module execution timeout in millisecond */ - int timeout; - - /* Queue of the module */ - bh_queue *queue; - - /* Watchdog timer of the module*/ - struct watchdog_timer wd_timer; - - timer_ctx_t timer_ctx; - - /* max timers number app can create */ - int timers; - - /* Internal data of the module */ - void *internal_data; - - /* Module name */ - char module_name[1]; -} module_data; - -/* Module function types */ -typedef bool (*module_init_func)(void); -typedef bool (*module_install_func)(request_t *msg); -typedef bool (*module_uninstall_func)(request_t *msg); -typedef void (*module_watchdog_kill_func)(module_data *module_data); -typedef bool (*module_handle_host_url_func)(void *queue_msg); -typedef module_data *(*module_get_module_data_func)(void *inst); - -/** - * @typedef module_on_install_request_byte_arrive_func - * - * @brief Define the signature of function to handle one byte of - * module app install request for struct module_interface. - * - * @param ch the byte to be received and handled - * @param total_size total size of the request - * @param received_total_size currently received total size when - * the function return - * - * @return true if success, false otherwise - */ -typedef bool (*module_on_install_request_byte_arrive_func)( - uint8 ch, int total_size, int *received_total_size); - -/* Interfaces of each module */ -typedef struct module_interface { - module_init_func module_init; - module_install_func module_install; - module_uninstall_func module_uninstall; - module_watchdog_kill_func module_watchdog_kill; - module_handle_host_url_func module_handle_host_url; - module_get_module_data_func module_get_module_data; - module_on_install_request_byte_arrive_func module_on_install; -} module_interface; - -/** - * @typedef host_init_func - * @brief Define the host initialize callback function signature for - * struct host_interface. - * - * @return true if success, false if fail - */ -typedef bool (*host_init_func)(void); - -/** - * @typedef host_send_fun - * @brief Define the host send callback function signature for - * struct host_interface. - * - * @param buf data buffer to send. - * @param size size of the data to send. - * - * @return size of the data sent in bytes - */ -typedef int (*host_send_fun)(void *ctx, const char *buf, int size); - -/** - * @typedef host_destroy_fun - * @brief Define the host receive callback function signature for - * struct host_interface. - * - */ -typedef void (*host_destroy_fun)(); - -/* Interfaces of host communication */ -typedef struct host_interface { - host_init_func init; - host_send_fun send; - host_destroy_fun destroy; -} host_interface; - -/** - * Initialize communication with Host - * - * @param interface host communication interface - * - * @return true if success, false otherwise - */ -bool -app_manager_host_init(host_interface *intf); - -/* Startup app manager */ -void -app_manager_startup(host_interface *intf); - -/* Return whether app manager is started */ -bool -app_manager_is_started(void); - -/* Get queue of current applet */ -void * -app_manager_get_module_queue(uint32 module_type, void *module_inst); - -/* Get applet name of current applet */ -const char * -app_manager_get_module_name(uint32 module_type, void *module_inst); - -/* Get heap of current applet */ -void * -app_manager_get_module_heap(uint32 module_type, void *module_inst); - -void * -get_app_manager_queue(); - -module_data * -app_manager_get_module_data(uint32 module_type, void *module_inst); - -unsigned int -app_manager_get_module_id(uint32 module_type, void *module_inst); - -module_data * -app_manager_lookup_module_data(const char *name); - -module_data * -module_data_list_lookup(const char *module_name); - -module_data * -module_data_list_lookup_id(unsigned int module_id); - -void -app_manager_post_applets_update_event(); - -bool -am_register_resource(const char *url, - void (*request_handler)(request_t *, void *), - uint32 register_id); - -void -am_cleanup_registeration(uint32 register_id); - -bool -am_register_event(const char *url, uint32_t reg_client); - -bool -am_unregister_event(const char *url, uint32_t reg_client); - -void -am_publish_event(request_t *event); - -void * -am_dispatch_request(request_t *request); - -void -am_send_response(response_t *response); - -void -module_request_handler(request_t *request, void *user_data); - -/** - * Send request message to host - * - * @param msg the request or event message. - * It is event when msg->action==COAP_EVENT - * - * @return true if success, false otherwise - */ -bool -send_request_to_host(request_t *msg); - -/** - * Send response message to host - * - * @param msg the response message - * - * @return true if success, false otherwise - */ -bool -send_response_to_host(response_t *msg); - -/** - * Send response with mid and code to host - * - * @param mid the message id of response - * @param code the code/status of response - * @param msg the detailed message - * - * @return true if success, false otherwise - */ -bool -send_error_response_to_host(int mid, int code, const char *msg); - -/** - * Check whether the applet has the permission - * - * @param perm the permission needed to check - * - * @return true if success, false otherwise - */ -bool -bh_applet_check_permission(const char *perm); - -/** - * Send message to Host - * - * @param buf buffer to send - * @param size size of buffer - * - * @return size of buffer sent - */ -int -app_manager_host_send_msg(int msg_type, const char *buf, int size); - -#ifdef __cplusplus -} /* end of extern "C" */ -#endif - -#endif diff --git a/core/app-mgr/app-mgr-shared/app_mgr_shared.cmake b/core/app-mgr/app-mgr-shared/app_mgr_shared.cmake deleted file mode 100644 index f370e8b29..000000000 --- a/core/app-mgr/app-mgr-shared/app_mgr_shared.cmake +++ /dev/null @@ -1,16 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -set (APP_MGR_SHARED_DIR ${CMAKE_CURRENT_LIST_DIR}) - -include_directories(${APP_MGR_SHARED_DIR}) - - -file (GLOB_RECURSE source_all ${APP_MGR_SHARED_DIR}/*.c) - -set (APP_MGR_SHARED_SOURCE ${source_all}) - -file (GLOB header - ${APP_MGR_SHARED_DIR}/*.h -) -LIST (APPEND RUNTIME_LIB_HEADER_LIST ${header}) diff --git a/core/app-mgr/app-mgr-shared/host_link.h b/core/app-mgr/app-mgr-shared/host_link.h deleted file mode 100644 index e3a37fb40..000000000 --- a/core/app-mgr/app-mgr-shared/host_link.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef DEPS_APP_MGR_APP_MGR_SHARED_HOST_LINK_H_ -#define DEPS_APP_MGR_APP_MGR_SHARED_HOST_LINK_H_ - -typedef enum LINK_MSG_TYPE { - COAP_TCP_RAW = 0, - COAP_UDP_RAW = 1, - REQUEST_PACKET, - RESPONSE_PACKET, - INSTALL_WASM_APP, - CBOR_GENERIC = 30, - - LINK_MSG_TYPE_MAX = 50 -} LINK_MSG_TYPE; - -/* Link message, or message between host and app manager */ -typedef struct bh_link_msg_t { - /* 2 bytes leading */ - uint16_t leading_bytes; - /* message type, must be COAP_TCP or COAP_UDP */ - uint16_t message_type; - /* size of payload */ - uint32_t payload_size; - char *payload; -} bh_link_msg_t; - -#endif /* DEPS_APP_MGR_APP_MGR_SHARED_HOST_LINK_H_ */ diff --git a/core/app-mgr/module.json b/core/app-mgr/module.json deleted file mode 100644 index b2faeca5f..000000000 --- a/core/app-mgr/module.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "name": "aee", - "version": "0.0.1", - "description": "aee", - "type": "source", - "category": "middleware", - "arch": "x86, arc, posix", - "includes": [ - "Beihai/classlib/include", - "Beihai/runtime/include", - "Beihai/runtime/platform/include", - "Beihai/runtime/platform/zephyr", - "Beihai/runtime/utils/coap/er-coap", - "Beihai/runtime/utils/coap/extension", - "iwasm/runtime/include", - "iwasm/runtime/platform/include", - "iwasm/runtime/platform/zephyr", - "iwasm/runtime/vmcore_wasm" - ], - "sources": [ - "Beihai/classlib/native/internal/*.c", - "Beihai/classlib/native/*.c", - "Beihai/runtime/gc/*.c", - "Beihai/runtime/platform/zephyr/*.c", - "Beihai/runtime/utils/*.c", - "Beihai/runtime/utils/coap/er-coap/*.c", - "Beihai/runtime/utils/coap/extension/*.c", - "Beihai/runtime/vmcore_jeff/*.c", - "app-manager/app-manager.c", - "app-manager/app-manager-host.c", - "app-manager/app_mgr_zephyr.c", - "app-manager/event.c", - "app-manager/message.c", - "app-manager/module_jeff.c", - "app-manager/module_wasm_lib.c", - "app-manager/module_wasm_app.c", - "app-manager/watchdog.c", - "Beihai/products/iMRT/*.c", - "iwasm/runtime/utils/*.c", - "iwasm/runtime/platform/zephyr/*.c", - "iwasm/runtime/vmcore_wasm/*.c", - "iwasm/lib/lib-export\.c", - "iwasm/lib/aee/*.c", - "iwasm/products/zephyr/sample/src/*.c" - ], - "compile_definitions": [ - "__JLF__", - "__ZEPHYR__" - ], - "target": "aee", - "dependencies": [] -} diff --git a/core/config.h b/core/config.h index 25c45107e..be9ebfc3a 100644 --- a/core/config.h +++ b/core/config.h @@ -188,6 +188,10 @@ #define WASM_ENABLE_APP_FRAMEWORK 0 #endif +#ifndef WASM_HAVE_MREMAP +#define WASM_HAVE_MREMAP 0 +#endif + /* Bulk memory operation */ #ifndef WASM_ENABLE_BULK_MEMORY #define WASM_ENABLE_BULK_MEMORY 0 @@ -301,6 +305,11 @@ #define WASM_ENABLE_SIMD 0 #endif +/* GC performance profiling */ +#ifndef WASM_ENABLE_GC_PERF_PROFILING +#define WASM_ENABLE_GC_PERF_PROFILING 0 +#endif + /* Memory profiling */ #ifndef WASM_ENABLE_MEMORY_PROFILING #define WASM_ENABLE_MEMORY_PROFILING 0 @@ -321,6 +330,11 @@ #define WASM_ENABLE_DUMP_CALL_STACK 0 #endif +/* AOT stack frame */ +#ifndef WASM_ENABLE_AOT_STACK_FRAME +#define WASM_ENABLE_AOT_STACK_FRAME 0 +#endif + /* Heap verification */ #ifndef BH_ENABLE_GC_VERIFY #define BH_ENABLE_GC_VERIFY 0 @@ -384,6 +398,13 @@ #define APP_HEAP_SIZE_MIN (256) #define APP_HEAP_SIZE_MAX (512 * 1024 * 1024) +/* Default min/max gc heap size of each app */ +#ifndef GC_HEAP_SIZE_DEFAULT +#define GC_HEAP_SIZE_DEFAULT (128 * 1024) +#endif +#define GC_HEAP_SIZE_MIN (4 * 1024) +#define GC_HEAP_SIZE_MAX (1024 * 1024 * 1024) + /* Default wasm stack size of each app */ #if defined(BUILD_TARGET_X86_64) || defined(BUILD_TARGET_AMD_64) #define DEFAULT_WASM_STACK_SIZE (16 * 1024) @@ -457,6 +478,30 @@ #define WASM_ENABLE_REF_TYPES 0 #endif +#ifndef WASM_ENABLE_GC +#define WASM_ENABLE_GC 0 +#endif + +#ifndef WASM_CONST_EXPR_STACK_SIZE +#if WASM_ENABLE_GC != 0 +#define WASM_CONST_EXPR_STACK_SIZE 8 +#else +#define WASM_CONST_EXPR_STACK_SIZE 4 +#endif +#endif + +#ifndef WASM_ENABLE_STRINGREF +#define WASM_ENABLE_STRINGREF 0 +#endif + +#ifndef GC_REFTYPE_MAP_SIZE_DEFAULT +#define GC_REFTYPE_MAP_SIZE_DEFAULT 64 +#endif + +#ifndef GC_RTTOBJ_MAP_SIZE_DEFAULT +#define GC_RTTOBJ_MAP_SIZE_DEFAULT 64 +#endif + #ifndef WASM_ENABLE_EXCE_HANDLING #define WASM_ENABLE_EXCE_HANDLING 0 #endif @@ -521,9 +566,8 @@ #define WASM_ENABLE_QUICK_AOT_ENTRY 1 #endif -/* Disable mmap based shared memory by default */ -#ifndef WASM_ENABLE_SHARED_MEMORY_MMAP -#define WASM_ENABLE_SHARED_MEMORY_MMAP 0 +#ifndef WASM_TABLE_MAX_SIZE +#define WASM_TABLE_MAX_SIZE 1024 #endif #endif /* end of _CONFIG_H_ */ diff --git a/core/deps/download.sh b/core/deps/download.sh deleted file mode 100755 index 46b30d7ef..000000000 --- a/core/deps/download.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/bash - -DEPS_ROOT=$(cd "$(dirname "$0")/" && pwd) -cd ${DEPS_ROOT} - - -if [ ! -d "lvgl" ]; then - echo "git pull lvgl..." - git clone https://github.com/lvgl/lvgl.git --branch v6.0.1 - [ $? -eq 0 ] || exit $? - - ../app-framework/wgl/app/prepare_headers.sh -fi -if [ ! -d "lv_drivers" ]; then - echo "git pull lv_drivers..." - git clone https://github.com/lvgl/lv_drivers.git --branch v6.0.1 - [ $? -eq 0 ] || exit $? -fi - -exit 0 diff --git a/core/iwasm/aot/aot_loader.c b/core/iwasm/aot/aot_loader.c index 282dc1d67..5803f5391 100644 --- a/core/iwasm/aot/aot_loader.c +++ b/core/iwasm/aot/aot_loader.c @@ -310,19 +310,18 @@ const_str_set_insert(const uint8 *str, int32 len, AOTModule *module, } /* Lookup const string set, use the string if found */ - if (!(c_str = loader_malloc((uint32)len + 1, error_buf, error_buf_size))) { + if (!(c_str = loader_malloc((uint32)len, error_buf, error_buf_size))) { return NULL; } #if (WASM_ENABLE_WORD_ALIGN_READ != 0) if (is_vram_word_align) { - bh_memcpy_wa(c_str, (uint32)(len + 1), str, (uint32)len); + bh_memcpy_wa(c_str, (uint32)len, str, (uint32)len); } else #endif { - bh_memcpy_s(c_str, (uint32)(len + 1), str, (uint32)len); + bh_memcpy_s(c_str, len, str, (uint32)len); } - c_str[len] = '\0'; if ((value = bh_hash_map_find(set, c_str))) { wasm_runtime_free(c_str); @@ -367,22 +366,18 @@ load_string(uint8 **p_buf, const uint8 *buf_end, AOTModule *module, } } #endif - else if (p[str_len - 1] == '\0') { - /* The string is terminated with '\0', use it directly */ - str = (char *)p; - } else if (is_load_from_file_buf) { - /* As the file buffer can be referred to after loading, - we use the 2 bytes of size to adjust the string: - move string 2 byte backward and then append '\0' */ - str = (char *)(p - 2); - bh_memmove_s(str, (uint32)(str_len + 1), p, (uint32)str_len); - str[str_len] = '\0'; + /* The string is always terminated with '\0', use it directly. + * In this case, the file buffer can be reffered to after loading. + */ + bh_assert(p[str_len - 1] == '\0'); + str = (char *)p; } else { /* Load from sections, the file buffer cannot be reffered to after loading, we must create another string and insert it into const string set */ + bh_assert(p[str_len - 1] == '\0'); if (!(str = const_str_set_insert((uint8 *)p, str_len, module, #if (WASM_ENABLE_WORD_ALIGN_READ != 0) is_vram_word_align, @@ -469,6 +464,68 @@ check_machine_info(AOTTargetInfo *target_info, char *error_buf, return true; } +static bool +check_feature_flags(char *error_buf, uint32 error_buf_size, + uint64 feature_flags) +{ +#if WASM_ENABLE_SIMD == 0 + if (feature_flags & WASM_FEATURE_SIMD_128BIT) { + set_error_buf(error_buf, error_buf_size, + "SIMD is not enabled in this build"); + return false; + } +#endif + +#if WASM_ENABLE_BULK_MEMORY == 0 + if (feature_flags & WASM_FEATURE_BULK_MEMORY) { + set_error_buf(error_buf, error_buf_size, + "bulk memory is not enabled in this build"); + return false; + } +#endif + +#if WASM_ENABLE_THREAD_MGR == 0 + if (feature_flags & WASM_FEATURE_MULTI_THREAD) { + set_error_buf(error_buf, error_buf_size, + "thread is not enabled in this build"); + return false; + } +#endif + +#if WASM_ENABLE_REF_TYPES == 0 + if (feature_flags & WASM_FEATURE_REF_TYPES) { + set_error_buf(error_buf, error_buf_size, + "reference types is not enabled in this build"); + return false; + } +#endif + +#if WASM_ENABLE_GC == 0 + if (feature_flags & WASM_FEATURE_GARBAGE_COLLECTION) { + set_error_buf(error_buf, error_buf_size, + "garbage collection is not enabled in this build"); + return false; + } +#endif + + return true; +} + +#if WASM_ENABLE_GC != 0 +static WASMRefType * +reftype_set_insert(HashMap *ref_type_set, const WASMRefType *ref_type, + char *error_buf, uint32 error_buf_size) +{ + WASMRefType *ret = wasm_reftype_set_insert(ref_type_set, ref_type); + + if (!ret) { + set_error_buf(error_buf, error_buf_size, + "insert ref type to hash set failed"); + } + return ret; +} +#endif + static bool load_target_info_section(const uint8 *buf, const uint8 *buf_end, AOTModule *module, char *error_buf, @@ -484,7 +541,8 @@ load_target_info_section(const uint8 *buf, const uint8 *buf_end, read_uint16(p, p_end, target_info.e_machine); read_uint32(p, p_end, target_info.e_version); read_uint32(p, p_end, target_info.e_flags); - read_uint32(p, p_end, target_info.reserved); + read_uint64(p, p_end, target_info.feature_flags); + read_uint64(p, p_end, target_info.reserved); read_byte_array(p, p_end, target_info.arch, sizeof(target_info.arch)); if (p != buf_end) { @@ -531,7 +589,9 @@ load_target_info_section(const uint8 *buf, const uint8 *buf_end, return false; } - return true; + /* Finally, check feature flags */ + return check_feature_flags(error_buf, error_buf_size, + target_info.feature_flags); fail: return false; } @@ -596,20 +656,22 @@ aot_loader_resolve_function(const char *module_name, const char *function_name, } else { target_function_type = - module->func_types[module->func_type_indexes - [export->index - module->import_func_count]]; + (AOTFuncType *)module + ->types[module->func_type_indexes[export->index + - module->import_func_count]]; function = (module->func_ptrs[export->index - module->import_func_count]); } /* check function type */ - if (!wasm_type_equal(expected_function_type, target_function_type)) { + if (!wasm_type_equal((WASMType *)expected_function_type, + (WASMType *)target_function_type, module->types, + module->type_count)) { LOG_DEBUG("%s.%s failed the type check", module_name, function_name); set_error_buf(error_buf, error_buf_size, "incompatible import type"); return NULL; } return function; } - #endif /* end of WASM_ENABLE_MULTI_MODULE */ static bool @@ -805,6 +867,59 @@ fail: #endif /* WASM_ENABLE_CUSTOM_NAME_SECTION != 0 */ } +#if WASM_ENABLE_STRINGREF != 0 +static bool +load_string_literal_section(const uint8 *buf, const uint8 *buf_end, + AOTModule *module, bool is_load_from_file_buf, + char *error_buf, uint32 error_buf_size) +{ + const uint8 *p = buf, *p_end = buf_end; + uint32 reserved = 0, string_count = 0, i; + uint64 size; + + read_uint32(p, p_end, reserved); + if (reserved != 0) { + set_error_buf(error_buf, error_buf_size, + "invalid reserved slot in string literal count"); + goto fail; + } + + read_uint32(p, p_end, string_count); + if (string_count == 0) { + set_error_buf(error_buf, error_buf_size, + "invalid string literal count"); + goto fail; + } + module->string_literal_count = string_count; + + size = (uint64)sizeof(char *) * string_count; + if (!(module->string_literal_ptrs = + loader_malloc(size, error_buf, error_buf_size))) { + goto fail; + } + + size = (uint64)sizeof(uint32) * string_count; + if (!(module->string_literal_lengths = + loader_malloc(size, error_buf, error_buf_size))) { + goto fail; + } + + for (i = 0; i < string_count; i++) { + read_uint32(p, p_end, module->string_literal_lengths[i]); + } + + for (i = 0; i < string_count; i++) { + module->string_literal_ptrs[i] = p; + p += module->string_literal_lengths[i]; + } + + return true; + +fail: + return false; +} +#endif /* end of WASM_ENABLE_STRINGREF != 0 */ + static bool load_custom_section(const uint8 *buf, const uint8 *buf_end, AOTModule *module, bool is_load_from_file_buf, char *error_buf, @@ -830,6 +945,14 @@ load_custom_section(const uint8 *buf, const uint8 *buf_end, AOTModule *module, else LOG_VERBOSE("Load name section success."); break; +#if WASM_ENABLE_STRINGREF != 0 + case AOT_CUSTOM_SECTION_STRING_LITERAL: + if (!load_string_literal_section(buf, buf_end, module, + is_load_from_file_buf, error_buf, + error_buf_size)) + goto fail; + break; +#endif #if WASM_ENABLE_LOAD_CUSTOM_SECTION != 0 case AOT_CUSTOM_SECTION_RAW: { @@ -885,6 +1008,11 @@ destroy_mem_init_data_list(AOTMemInitData **data_list, uint32 count) wasm_runtime_free(data_list); } +static bool +load_init_expr(const uint8 **p_buf, const uint8 *buf_end, AOTModule *module, + InitializerExpression *expr, char *error_buf, + uint32 error_buf_size); + static bool load_mem_init_data_list(const uint8 **p_buf, const uint8 *buf_end, AOTModule *module, char *error_buf, @@ -904,15 +1032,17 @@ load_mem_init_data_list(const uint8 **p_buf, const uint8 *buf_end, /* Create each memory data segment */ for (i = 0; i < module->mem_init_data_count; i++) { - uint32 init_expr_type, byte_count; - uint64 init_expr_value; + uint32 byte_count; uint32 is_passive; uint32 memory_index; + InitializerExpression init_value; read_uint32(buf, buf_end, is_passive); read_uint32(buf, buf_end, memory_index); - read_uint32(buf, buf_end, init_expr_type); - read_uint64(buf, buf_end, init_expr_value); + if (!load_init_expr(&buf, buf_end, module, &init_value, error_buf, + error_buf_size)) { + return false; + } read_uint32(buf, buf_end, byte_count); size = offsetof(AOTMemInitData, bytes) + (uint64)byte_count; if (!(data_list[i] = loader_malloc(size, error_buf, error_buf_size))) { @@ -924,8 +1054,8 @@ load_mem_init_data_list(const uint8 **p_buf, const uint8 *buf_end, data_list[i]->is_passive = (bool)is_passive; data_list[i]->memory_index = memory_index; #endif - data_list[i]->offset.init_expr_type = (uint8)init_expr_type; - data_list[i]->offset.u.i64 = (int64)init_expr_value; + data_list[i]->offset.init_expr_type = init_value.init_expr_type; + data_list[i]->offset.u = init_value.u; data_list[i]->byte_count = byte_count; read_byte_array(buf, buf_end, data_list[i]->bytes, data_list[i]->byte_count); @@ -977,6 +1107,18 @@ fail: return false; } +#if WASM_ENABLE_GC != 0 +static void +destroy_init_expr(InitializerExpression *expr) +{ + if (expr->init_expr_type == INIT_EXPR_TYPE_STRUCT_NEW + || expr->init_expr_type == INIT_EXPR_TYPE_ARRAY_NEW + || expr->init_expr_type == INIT_EXPR_TYPE_ARRAY_NEW_FIXED) { + wasm_runtime_free(expr->u.data); + } +} +#endif /* end of WASM_ENABLE_GC != 0 */ + static void destroy_import_tables(AOTImportTable *import_tables) { @@ -994,11 +1136,198 @@ destroy_table_init_data_list(AOTTableInitData **data_list, uint32 count) { uint32 i; for (i = 0; i < count; i++) - if (data_list[i]) + if (data_list[i]) { +#if WASM_ENABLE_GC != 0 + uint32 j; + for (j = 0; j < data_list[i]->value_count; j++) { + destroy_init_expr(&data_list[i]->init_values[j]); + } +#endif wasm_runtime_free(data_list[i]); + } wasm_runtime_free(data_list); } +static bool +load_init_expr(const uint8 **p_buf, const uint8 *buf_end, AOTModule *module, + InitializerExpression *expr, char *error_buf, + uint32 error_buf_size) +{ + const uint8 *buf = *p_buf; + uint32 init_expr_type = 0; + uint64 *i64x2 = NULL; + bool free_if_fail = false; + + buf = (uint8 *)align_ptr(buf, 4); + + read_uint32(buf, buf_end, init_expr_type); + + switch (init_expr_type) { + case INIT_EXPR_NONE: + break; + case INIT_EXPR_TYPE_I32_CONST: + case INIT_EXPR_TYPE_F32_CONST: + read_uint32(buf, buf_end, expr->u.i32); + break; + case INIT_EXPR_TYPE_I64_CONST: + case INIT_EXPR_TYPE_F64_CONST: + read_uint64(buf, buf_end, expr->u.i64); + break; + case INIT_EXPR_TYPE_V128_CONST: + i64x2 = (uint64 *)expr->u.v128.i64x2; + CHECK_BUF(buf, buf_end, sizeof(uint64) * 2); + wasm_runtime_read_v128(buf, &i64x2[0], &i64x2[1]); + buf += sizeof(uint64) * 2; + break; + case INIT_EXPR_TYPE_GET_GLOBAL: + read_uint32(buf, buf_end, expr->u.global_index); + break; + /* INIT_EXPR_TYPE_FUNCREF_CONST can be used when + both reference types and GC are disabled */ + case INIT_EXPR_TYPE_FUNCREF_CONST: + read_uint32(buf, buf_end, expr->u.ref_index); + break; +#if WASM_ENABLE_GC != 0 || WASM_ENABLE_REF_TYPES != 0 + case INIT_EXPR_TYPE_REFNULL_CONST: + read_uint32(buf, buf_end, expr->u.ref_index); + break; +#endif /* end of WASM_ENABLE_GC != 0 || WASM_ENABLE_REF_TYPES != 0 */ +#if WASM_ENABLE_GC != 0 + case INIT_EXPR_TYPE_I31_NEW: + read_uint32(buf, buf_end, expr->u.i32); + break; + case INIT_EXPR_TYPE_STRUCT_NEW: + { + uint64 size; + uint32 type_idx, field_count; + AOTStructType *struct_type = NULL; + WASMStructNewInitValues *init_values = NULL; + + read_uint32(buf, buf_end, type_idx); + read_uint32(buf, buf_end, field_count); + + size = offsetof(WASMStructNewInitValues, fields) + + sizeof(WASMValue) * (uint64)field_count; + if (!(init_values = + loader_malloc(size, error_buf, error_buf_size))) { + return false; + } + free_if_fail = true; + init_values->count = field_count; + expr->u.data = init_values; + + if (type_idx >= module->type_count) { + set_error_buf(error_buf, error_buf_size, + "unknown struct type."); + goto fail; + } + + struct_type = (AOTStructType *)module->types[type_idx]; + + if (struct_type->field_count != field_count) { + set_error_buf(error_buf, error_buf_size, + "invalid field count."); + goto fail; + } + + if (field_count > 0) { + uint32 i; + + for (i = 0; i < field_count; i++) { + uint32 field_size = + wasm_value_type_size(struct_type->fields[i].field_type); + if (field_size <= sizeof(uint32)) + read_uint32(buf, buf_end, init_values->fields[i].u32); + else if (field_size == sizeof(uint64)) + read_uint64(buf, buf_end, init_values->fields[i].u64); + else if (field_size == sizeof(uint64) * 2) + read_byte_array(buf, buf_end, &init_values->fields[i], + field_size); + else { + bh_assert(0); + } + } + } + + break; + } + case INIT_EXPR_TYPE_STRUCT_NEW_DEFAULT: + read_uint32(buf, buf_end, expr->u.type_index); + break; + case INIT_EXPR_TYPE_ARRAY_NEW: + case INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT: + case INIT_EXPR_TYPE_ARRAY_NEW_FIXED: + { + uint32 array_elem_type; + uint32 type_idx, length; + WASMArrayNewInitValues *init_values = NULL; + + /* Note: at this time the aot types haven't been loaded */ + read_uint32(buf, buf_end, array_elem_type); + read_uint32(buf, buf_end, type_idx); + read_uint32(buf, buf_end, length); + + if (init_expr_type == INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT) { + expr->u.array_new_default.type_index = type_idx; + expr->u.array_new_default.length = length; + } + else { + uint32 i, elem_size, elem_data_count; + uint64 size = offsetof(WASMArrayNewInitValues, elem_data) + + sizeof(WASMValue) * (uint64)length; + if (!(init_values = + loader_malloc(size, error_buf, error_buf_size))) { + return false; + } + free_if_fail = true; + expr->u.data = init_values; + + init_values->type_idx = type_idx; + init_values->length = length; + + elem_data_count = + (init_expr_type == INIT_EXPR_TYPE_ARRAY_NEW_FIXED) ? length + : 1; + elem_size = wasm_value_type_size((uint8)array_elem_type); + + for (i = 0; i < elem_data_count; i++) { + if (elem_size <= sizeof(uint32)) + read_uint32(buf, buf_end, + init_values->elem_data[i].u32); + else if (elem_size == sizeof(uint64)) + read_uint64(buf, buf_end, + init_values->elem_data[i].u64); + else if (elem_size == sizeof(uint64) * 2) + read_byte_array(buf, buf_end, + &init_values->elem_data[i], elem_size); + else { + bh_assert(0); + } + } + } + break; + } +#endif /* end of WASM_ENABLE_GC != 0 */ + default: + set_error_buf(error_buf, error_buf_size, "invalid init expr type."); + return false; + } + + expr->init_expr_type = (uint8)init_expr_type; + + *p_buf = buf; + return true; +fail: +#if WASM_ENABLE_GC != 0 + if (free_if_fail) { + wasm_runtime_free(expr->u.data); + } +#else + (void)free_if_fail; +#endif + return false; +} + static bool load_import_table_list(const uint8 **p_buf, const uint8 *buf_end, AOTModule *module, char *error_buf, @@ -1006,8 +1335,11 @@ load_import_table_list(const uint8 **p_buf, const uint8 *buf_end, { const uint8 *buf = *p_buf; AOTImportTable *import_table; +#if WASM_ENABLE_GC != 0 + WASMRefType ref_type; +#endif uint64 size; - uint32 i, possible_grow; + uint32 i; /* Allocate memory */ size = sizeof(AOTImportTable) * (uint64)module->import_table_count; @@ -1018,11 +1350,30 @@ load_import_table_list(const uint8 **p_buf, const uint8 *buf_end, /* keep sync with aot_emit_table_info() aot_emit_aot_file */ for (i = 0; i < module->import_table_count; i++, import_table++) { - read_uint32(buf, buf_end, import_table->elem_type); + read_uint8(buf, buf_end, import_table->elem_type); + read_uint8(buf, buf_end, import_table->table_flags); + read_uint8(buf, buf_end, import_table->possible_grow); +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_multi_byte_type(import_table->elem_type)) { + read_uint8(buf, buf_end, ref_type.ref_ht_common.nullable); + } +#endif read_uint32(buf, buf_end, import_table->table_init_size); read_uint32(buf, buf_end, import_table->table_max_size); - read_uint32(buf, buf_end, possible_grow); - import_table->possible_grow = (possible_grow & 0x1); +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_multi_byte_type(import_table->elem_type)) { + read_uint32(buf, buf_end, ref_type.ref_ht_common.heap_type); + + ref_type.ref_type = import_table->elem_type; + /* TODO: check ref_type */ + if (!(import_table->elem_ref_type = wasm_reftype_set_insert( + module->ref_type_set, &ref_type))) { + set_error_buf(error_buf, error_buf_size, + "insert ref type to hash set failed"); + return false; + } + } +#endif } *p_buf = buf; @@ -1037,8 +1388,11 @@ load_table_list(const uint8 **p_buf, const uint8 *buf_end, AOTModule *module, { const uint8 *buf = *p_buf; AOTTable *table; +#if WASM_ENABLE_GC != 0 + WASMRefType ref_type; +#endif uint64 size; - uint32 i, possible_grow; + uint32 i; /* Allocate memory */ size = sizeof(AOTTable) * (uint64)module->table_count; @@ -1049,12 +1403,41 @@ load_table_list(const uint8 **p_buf, const uint8 *buf_end, AOTModule *module, /* Create each table data segment */ for (i = 0; i < module->table_count; i++, table++) { - read_uint32(buf, buf_end, table->elem_type); - read_uint32(buf, buf_end, table->table_flags); + read_uint8(buf, buf_end, table->elem_type); + read_uint8(buf, buf_end, table->table_flags); + read_uint8(buf, buf_end, table->possible_grow); +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_multi_byte_type(table->elem_type)) { + read_uint8(buf, buf_end, ref_type.ref_ht_common.nullable); + } +#endif read_uint32(buf, buf_end, table->table_init_size); read_uint32(buf, buf_end, table->table_max_size); - read_uint32(buf, buf_end, possible_grow); - table->possible_grow = (possible_grow & 0x1); +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_multi_byte_type(table->elem_type)) { + read_uint32(buf, buf_end, ref_type.ref_ht_common.heap_type); + + ref_type.ref_type = table->elem_type; + /* TODO: check ref_type */ + if (!(table->elem_ref_type = wasm_reftype_set_insert( + module->ref_type_set, &ref_type))) { + set_error_buf(error_buf, error_buf_size, + "insert ref type to hash set failed"); + return false; + } + } + if (!load_init_expr(&buf, buf_end, module, &table->init_expr, error_buf, + error_buf_size)) + return false; + + if (table->init_expr.init_expr_type >= INIT_EXPR_TYPE_STRUCT_NEW + && table->init_expr.init_expr_type + <= INIT_EXPR_TYPE_EXTERN_CONVERT_ANY) { + set_error_buf(error_buf, error_buf_size, + "unsupported initializer expression for table"); + return false; + } +#endif } *p_buf = buf; @@ -1070,8 +1453,11 @@ load_table_init_data_list(const uint8 **p_buf, const uint8 *buf_end, { const uint8 *buf = *p_buf; AOTTableInitData **data_list; +#if WASM_ENABLE_GC != 0 + WASMRefType reftype; +#endif uint64 size; - uint32 i; + uint32 i, j; /* Allocate memory */ size = sizeof(AOTTableInitData *) * (uint64)module->table_init_data_count; @@ -1083,7 +1469,7 @@ load_table_init_data_list(const uint8 **p_buf, const uint8 *buf_end, /* Create each table data segment */ for (i = 0; i < module->table_init_data_count; i++) { uint32 mode, elem_type; - uint32 table_index, init_expr_type, func_index_count; + uint32 table_index, init_expr_type, value_count; uint64 init_expr_value, size1; read_uint32(buf, buf_end, mode); @@ -1091,10 +1477,24 @@ load_table_init_data_list(const uint8 **p_buf, const uint8 *buf_end, read_uint32(buf, buf_end, table_index); read_uint32(buf, buf_end, init_expr_type); read_uint64(buf, buf_end, init_expr_value); - read_uint32(buf, buf_end, func_index_count); +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_multi_byte_type(elem_type)) { + /* TODO: check ref_type */ + read_uint16(buf, buf_end, reftype.ref_ht_common.ref_type); + read_uint16(buf, buf_end, reftype.ref_ht_common.nullable); + read_uint32(buf, buf_end, reftype.ref_ht_common.heap_type); + } + else +#endif + { + /* Skip 8 byte for ref type info */ + buf += 8; + } - size1 = sizeof(uint32) * (uint64)func_index_count; - size = offsetof(AOTTableInitData, func_indexes) + size1; + read_uint32(buf, buf_end, value_count); + + size1 = sizeof(InitializerExpression) * (uint64)value_count; + size = offsetof(AOTTableInitData, init_values) + size1; if (!(data_list[i] = loader_malloc(size, error_buf, error_buf_size))) { return false; } @@ -1102,11 +1502,24 @@ load_table_init_data_list(const uint8 **p_buf, const uint8 *buf_end, data_list[i]->mode = mode; data_list[i]->elem_type = elem_type; data_list[i]->table_index = table_index; +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_multi_byte_type(elem_type)) { + if (!(data_list[i]->elem_ref_type = + reftype_set_insert(module->ref_type_set, &reftype, + error_buf, error_buf_size))) { + goto fail; + } + } +#endif data_list[i]->offset.init_expr_type = (uint8)init_expr_type; data_list[i]->offset.u.i64 = (int64)init_expr_value; - data_list[i]->func_index_count = func_index_count; - read_byte_array(buf, buf_end, data_list[i]->func_indexes, - (uint32)size1); + data_list[i]->value_count = value_count; + for (j = 0; j < data_list[i]->value_count; j++) { + if (!load_init_expr(&buf, buf_end, module, + &data_list[i]->init_values[j], error_buf, + error_buf_size)) + return false; + } } *p_buf = buf; @@ -1147,18 +1560,375 @@ fail: } static void -destroy_func_types(AOTFuncType **func_types, uint32 count) +destroy_types(AOTType **types, uint32 count) { uint32 i; - for (i = 0; i < count; i++) - if (func_types[i]) - wasm_runtime_free(func_types[i]); - wasm_runtime_free(func_types); + for (i = 0; i < count; i++) { + + if (types[i]) { +#if WASM_ENABLE_GC != 0 + if (types[i]->type_flag == WASM_TYPE_FUNC) { + AOTFuncType *func_type = (AOTFuncType *)types[i]; + if (func_type->ref_type_maps != NULL) { + bh_assert(func_type->ref_type_map_count > 0); + wasm_runtime_free(func_type->ref_type_maps); + } + } + else if (types[i]->type_flag == WASM_TYPE_STRUCT) { + AOTStructType *struct_type = (AOTStructType *)types[i]; + if (struct_type->ref_type_maps != NULL) { + bh_assert(struct_type->ref_type_map_count > 0); + wasm_runtime_free(struct_type->ref_type_maps); + } + } +#endif + wasm_runtime_free(types[i]); + } + } + wasm_runtime_free(types); +} + +#if WASM_ENABLE_GC != 0 +static void +init_base_type(AOTType *base_type, uint16 type_flag, bool is_sub_final, + uint32 parent_type_idx, uint16 rec_count, uint16 rec_idx) +{ + base_type->type_flag = type_flag; + base_type->is_sub_final = is_sub_final; + base_type->parent_type_idx = parent_type_idx; + base_type->rec_count = rec_count; + base_type->rec_idx = rec_idx; } static bool -load_func_types(const uint8 **p_buf, const uint8 *buf_end, AOTModule *module, - char *error_buf, uint32 error_buf_size) +load_types(const uint8 **p_buf, const uint8 *buf_end, AOTModule *module, + char *error_buf, uint32 error_buf_size) +{ + const uint8 *buf = *p_buf; + AOTType **types; + uint64 size; + uint32 i, j; + uint32 type_flag, param_cell_num, ret_cell_num; + uint16 param_count, result_count, ref_type_map_count, rec_count, rec_idx; + bool is_sub_final; + uint32 parent_type_idx; + WASMRefType ref_type; + + /* Allocate memory */ + size = sizeof(AOTFuncType *) * (uint64)module->type_count; + if (!(types = loader_malloc(size, error_buf, error_buf_size))) { + return false; + } + + module->types = types; + + /* Create each type */ + for (i = 0; i < module->type_count; i++) { + + buf = align_ptr(buf, 4); + + /* Read base type info */ + read_uint16(buf, buf_end, type_flag); + read_uint16(buf, buf_end, is_sub_final); + read_uint32(buf, buf_end, parent_type_idx); + read_uint16(buf, buf_end, rec_count); + read_uint16(buf, buf_end, rec_idx); + + if (type_flag == WASM_TYPE_FUNC) { + AOTFuncType *func_type; + + /* Read param count */ + read_uint16(buf, buf_end, param_count); + /* Read result count */ + read_uint16(buf, buf_end, result_count); + /* Read ref_type_map_count */ + read_uint16(buf, buf_end, ref_type_map_count); + + func_type = + loader_malloc(sizeof(AOTFuncType) + param_count + result_count, + error_buf, error_buf_size); + + if (!func_type) { + goto fail; + } + + types[i] = (AOTType *)func_type; + + init_base_type((AOTType *)func_type, type_flag, is_sub_final, + parent_type_idx, rec_count, rec_idx); + func_type->param_count = param_count; + func_type->result_count = result_count; + + /* Read types of params */ + read_byte_array(buf, buf_end, func_type->types, + func_type->param_count + func_type->result_count); + + func_type->ref_type_map_count = ref_type_map_count; + + param_cell_num = wasm_get_cell_num(func_type->types, param_count); + ret_cell_num = + wasm_get_cell_num(func_type->types + param_count, result_count); + if (param_cell_num > UINT16_MAX || ret_cell_num > UINT16_MAX) { + set_error_buf(error_buf, error_buf_size, + "param count or result count too large"); + goto fail; + } + + func_type->param_cell_num = param_cell_num; + func_type->ret_cell_num = ret_cell_num; + +#if WASM_ENABLE_QUICK_AOT_ENTRY != 0 + func_type->quick_aot_entry = + wasm_native_lookup_quick_aot_entry(func_type); +#endif + + LOG_VERBOSE("type %u: func, param count: %d, result count: %d, " + "ref type map count: %d", + i, param_count, result_count, ref_type_map_count); + + /* If ref_type_map is not empty, read ref_type_map */ + if (ref_type_map_count > 0) { + bh_assert(func_type->ref_type_map_count + <= func_type->param_count + func_type->result_count); + + /* align to 4 since param_count + result_count may be odd */ + buf = align_ptr(buf, 4); + + if (!(func_type->ref_type_maps = + loader_malloc(sizeof(WASMRefTypeMap) + * func_type->ref_type_map_count, + error_buf, error_buf_size))) { + goto fail; + } + + for (j = 0; j < func_type->ref_type_map_count; j++) { + read_uint16(buf, buf_end, + func_type->ref_type_maps[j].index); + read_uint8(buf, buf_end, ref_type.ref_ht_common.ref_type); + read_uint8(buf, buf_end, ref_type.ref_ht_common.nullable); + read_uint32(buf, buf_end, ref_type.ref_ht_common.heap_type); + /* TODO: check ref_type */ + if (!(func_type->ref_type_maps[j].ref_type = + wasm_reftype_set_insert(module->ref_type_set, + &ref_type))) { + set_error_buf(error_buf, error_buf_size, + "insert ref type to hash set failed"); + goto fail; + } + } + + func_type->result_ref_type_maps = func_type->ref_type_maps; + for (j = 0; j < func_type->param_count; j++) { + if (wasm_is_type_multi_byte_type(func_type->types[j])) + func_type->result_ref_type_maps++; + } + } + } + else if (type_flag == WASM_TYPE_STRUCT) { + AOTStructType *struct_type; + const uint8 *buf_org; + uint16 *reference_table; + uint16 field_count, ref_field_count = 0; + uint32 offset; + + read_uint16(buf, buf_end, field_count); + read_uint16(buf, buf_end, ref_type_map_count); + + buf_org = buf; + + /* Traverse first time to get ref_field_count */ + for (j = 0; j < field_count; j++) { + uint8 field_flags, field_type; + + read_uint8(buf, buf_end, field_flags); + read_uint8(buf, buf_end, field_type); + if (wasm_is_type_reftype(field_type)) + ref_field_count++; + + (void)field_flags; + } + + struct_type = loader_malloc( + sizeof(AOTStructType) + + sizeof(WASMStructFieldType) * (uint64)field_count + + sizeof(uint16) * (uint64)(ref_field_count + 1), + error_buf, error_buf_size); + if (!struct_type) { + goto fail; + } + + offset = (uint32)offsetof(WASMStructObject, field_data); + types[i] = (AOTType *)struct_type; + + init_base_type((AOTType *)struct_type, type_flag, is_sub_final, + parent_type_idx, rec_count, rec_idx); + struct_type->field_count = field_count; + struct_type->ref_type_map_count = ref_type_map_count; + + struct_type->reference_table = reference_table = + (uint16 *)((uint8 *)struct_type + + offsetof(AOTStructType, fields) + + sizeof(WASMStructFieldType) * field_count); + *reference_table++ = ref_field_count; + + LOG_VERBOSE( + "type %u: struct, field count: %d, ref type map count: %d", i, + field_count, ref_type_map_count); + + buf = buf_org; + + /* Traverse again to read each field */ + for (j = 0; j < field_count; j++) { + uint8 field_type, field_size; + + read_uint8(buf, buf_end, struct_type->fields[j].field_flags); + read_uint8(buf, buf_end, field_type); + struct_type->fields[j].field_type = field_type; + struct_type->fields[j].field_size = field_size = + (uint8)wasm_reftype_size(field_type); +#if !(defined(BUILD_TARGET_X86_64) || defined(BUILD_TARGET_AMD_64) \ + || defined(BUILD_TARGET_X86_32)) + if (field_size == 2) + offset = align_uint(offset, 2); + else if (field_size >= 4) /* field size is 4 or 8 */ + offset = align_uint(offset, 4); +#endif + struct_type->fields[j].field_offset = offset; + if (wasm_is_type_reftype(field_type)) + *reference_table++ = offset; + offset += field_size; + LOG_VERBOSE(" field: %d, flags: %d, type: %d", j, + struct_type->fields[j].field_flags, + struct_type->fields[j].field_type); + } + + struct_type->total_size = offset; + buf = align_ptr(buf, 4); + + /* If ref_type_map is not empty, read ref_type_map */ + if (ref_type_map_count > 0) { + + bh_assert(struct_type->ref_type_map_count <= field_count); + + if (!(struct_type->ref_type_maps = + loader_malloc(sizeof(WASMRefTypeMap) + * struct_type->ref_type_map_count, + error_buf, error_buf_size))) { + goto fail; + } + + for (j = 0; j < struct_type->ref_type_map_count; j++) { + read_uint16(buf, buf_end, + struct_type->ref_type_maps[j].index); + read_uint8(buf, buf_end, ref_type.ref_ht_common.ref_type); + read_uint8(buf, buf_end, ref_type.ref_ht_common.nullable); + read_uint32(buf, buf_end, ref_type.ref_ht_common.heap_type); + /* TODO: check ref_type */ + if (!(struct_type->ref_type_maps[j].ref_type = + wasm_reftype_set_insert(module->ref_type_set, + &ref_type))) { + set_error_buf(error_buf, error_buf_size, + "insert ref type to hash set failed"); + goto fail; + } + } + } + } + else if (type_flag == WASM_TYPE_ARRAY) { + AOTArrayType *array_type; + + array_type = + loader_malloc(sizeof(AOTArrayType), error_buf, error_buf_size); + + if (!array_type) { + goto fail; + } + + types[i] = (AOTType *)array_type; + + init_base_type((AOTType *)array_type, type_flag, is_sub_final, + parent_type_idx, rec_count, rec_idx); + read_uint16(buf, buf_end, array_type->elem_flags); + read_uint8(buf, buf_end, array_type->elem_type); + if (wasm_is_type_multi_byte_type(array_type->elem_type)) { + read_uint8(buf, buf_end, ref_type.ref_ht_common.nullable); + read_uint32(buf, buf_end, ref_type.ref_ht_common.heap_type); + ref_type.ref_type = array_type->elem_type; + /* TODO: check ref_type */ + if (!(array_type->elem_ref_type = wasm_reftype_set_insert( + module->ref_type_set, &ref_type))) { + set_error_buf(error_buf, error_buf_size, + "insert ref type to hash set failed"); + goto fail; + } + } + + LOG_VERBOSE("type %u: array", i); + } + else { + set_error_buf_v(error_buf, error_buf_size, + "invalid type flag: %" PRIu32, type_flag); + goto fail; + } + + if ((rec_count == 0) || (rec_idx == rec_count - 1)) { + if (rec_count == 0) { + bh_assert(rec_idx == 0); + } + + for (j = i - rec_idx; j <= i; j++) { + AOTType *cur_type = module->types[j]; + parent_type_idx = cur_type->parent_type_idx; + if (parent_type_idx != (uint32)-1) { /* has parent */ + AOTType *parent_type = module->types[parent_type_idx]; + + module->types[j]->parent_type = parent_type; + module->types[j]->root_type = parent_type->root_type; + module->types[j]->inherit_depth = + parent_type->inherit_depth + 1; + } + else { + module->types[j]->parent_type = NULL; + module->types[j]->root_type = module->types[j]; + module->types[j]->inherit_depth = 0; + } + } + + for (j = i - rec_idx; j <= i; j++) { + AOTType *cur_type = module->types[j]; + parent_type_idx = cur_type->parent_type_idx; + if (parent_type_idx != (uint32)-1) { /* has parent */ + AOTType *parent_type = module->types[parent_type_idx]; + /* subtyping has been checked during compilation */ + bh_assert(wasm_type_is_subtype_of( + module->types[j], parent_type, module->types, i)); + (void)parent_type; + } + } + } + } + + if (module->type_count) { + if (!(module->rtt_types = loader_malloc((uint64)sizeof(WASMRttType *) + * module->type_count, + error_buf, error_buf_size))) { + goto fail; + } + } + + *p_buf = buf; + return true; + +fail: + /* Destroy all types */ + destroy_types(types, module->type_count); + module->types = NULL; + return false; +} +#else +static bool +load_types(const uint8 **p_buf, const uint8 *buf_end, AOTModule *module, + char *error_buf, uint32 error_buf_size) { const uint8 *buf = *p_buf; AOTFuncType **func_types; @@ -1166,26 +1936,24 @@ load_func_types(const uint8 **p_buf, const uint8 *buf_end, AOTModule *module, uint32 i; /* Allocate memory */ - size = sizeof(AOTFuncType *) * (uint64)module->func_type_count; - if (!(module->func_types = func_types = - loader_malloc(size, error_buf, error_buf_size))) { + size = sizeof(AOTFuncType *) * (uint64)module->type_count; + if (!(func_types = loader_malloc(size, error_buf, error_buf_size))) { return false; } + module->types = (AOTType **)func_types; + /* Create each function type */ - for (i = 0; i < module->func_type_count; i++) { + for (i = 0; i < module->type_count; i++) { + uint32 type_flag; uint32 param_count, result_count; uint32 param_cell_num, ret_cell_num; uint64 size1; - read_uint32(buf, buf_end, param_count); - read_uint32(buf, buf_end, result_count); - - if (param_count > UINT16_MAX || result_count > UINT16_MAX) { - set_error_buf(error_buf, error_buf_size, - "param count or result count too large"); - return false; - } + buf = align_ptr(buf, 4); + read_uint16(buf, buf_end, type_flag); + read_uint16(buf, buf_end, param_count); + read_uint16(buf, buf_end, result_count); size1 = (uint64)param_count + (uint64)result_count; size = offsetof(AOTFuncType, types) + size1; @@ -1220,18 +1988,19 @@ load_func_types(const uint8 **p_buf, const uint8 *buf_end, AOTModule *module, fail: return false; } +#endif /* end of WASM_ENABLE_GC != 0 */ static bool -load_func_type_info(const uint8 **p_buf, const uint8 *buf_end, - AOTModule *module, char *error_buf, uint32 error_buf_size) +load_type_info(const uint8 **p_buf, const uint8 *buf_end, AOTModule *module, + char *error_buf, uint32 error_buf_size) { const uint8 *buf = *p_buf; - read_uint32(buf, buf_end, module->func_type_count); + read_uint32(buf, buf_end, module->type_count); /* load function type */ - if (module->func_type_count > 0 - && !load_func_types(&buf, buf_end, module, error_buf, error_buf_size)) + if (module->type_count > 0 + && !load_types(&buf, buf_end, module, error_buf, error_buf_size)) return false; *p_buf = buf; @@ -1357,23 +2126,14 @@ load_globals(const uint8 **p_buf, const uint8 *buf_end, AOTModule *module, /* Create each global */ for (i = 0; i < module->global_count; i++) { - uint16 init_expr_type; - read_uint8(buf, buf_end, globals[i].type); read_uint8(buf, buf_end, globals[i].is_mutable); - read_uint16(buf, buf_end, init_expr_type); - if (init_expr_type != INIT_EXPR_TYPE_V128_CONST) { - read_uint64(buf, buf_end, globals[i].init_expr.u.i64); - } - else { - uint64 *i64x2 = (uint64 *)globals[i].init_expr.u.v128.i64x2; - CHECK_BUF(buf, buf_end, sizeof(uint64) * 2); - wasm_runtime_read_v128(buf, &i64x2[0], &i64x2[1]); - buf += sizeof(uint64) * 2; - } + buf = align_ptr(buf, 4); - globals[i].init_expr.init_expr_type = (uint8)init_expr_type; + if (!load_init_expr(&buf, buf_end, module, &globals[i].init_expr, + error_buf, error_buf_size)) + return false; globals[i].size = wasm_value_type_size(globals[i].type); globals[i].data_offset = data_offset; @@ -1425,7 +2185,7 @@ load_import_funcs(const uint8 **p_buf, const uint8 *buf_end, AOTModule *module, #if WASM_ENABLE_MULTI_MODULE != 0 AOTModule *sub_module = NULL; AOTFunc *linked_func = NULL; - WASMType *declare_func_type = NULL; + AOTFuncType *declare_func_type = NULL; #endif /* Allocate memory */ @@ -1438,13 +2198,14 @@ load_import_funcs(const uint8 **p_buf, const uint8 *buf_end, AOTModule *module, /* Create each import func */ for (i = 0; i < module->import_func_count; i++) { read_uint16(buf, buf_end, import_funcs[i].func_type_index); - if (import_funcs[i].func_type_index >= module->func_type_count) { + if (import_funcs[i].func_type_index >= module->type_count) { set_error_buf(error_buf, error_buf_size, "unknown type"); return false; } #if WASM_ENABLE_MULTI_MODULE != 0 - declare_func_type = module->func_types[import_funcs[i].func_type_index]; + declare_func_type = + (AOTFuncType *)module->types[import_funcs[i].func_type_index]; read_string(buf, buf_end, module_name); read_string(buf, buf_end, field_name); @@ -1472,7 +2233,7 @@ load_import_funcs(const uint8 **p_buf, const uint8 *buf_end, AOTModule *module, #else import_funcs[i].func_type = - module->func_types[import_funcs[i].func_type_index]; + (AOTFuncType *)module->types[import_funcs[i].func_type_index]; read_string(buf, buf_end, import_funcs[i].module_name); read_string(buf, buf_end, import_funcs[i].func_name); module_name = import_funcs[i].module_name; @@ -1640,7 +2401,7 @@ load_init_data_section(const uint8 *buf, const uint8 *buf_end, if (!load_memory_info(&p, p_end, module, error_buf, error_buf_size) || !load_table_info(&p, p_end, module, error_buf, error_buf_size) - || !load_func_type_info(&p, p_end, module, error_buf, error_buf_size) + || !load_type_info(&p, p_end, module, error_buf, error_buf_size) || !load_import_global_info(&p, p_end, module, is_load_from_file_buf, error_buf, error_buf_size) || !load_global_info(&p, p_end, module, error_buf, error_buf_size) @@ -1791,12 +2552,76 @@ load_function_section(const uint8 *buf, const uint8 *buf_end, AOTModule *module, for (i = 0; i < module->func_count; i++) { read_uint32(p, p_end, module->func_type_indexes[i]); - if (module->func_type_indexes[i] >= module->func_type_count) { + if (module->func_type_indexes[i] >= module->type_count) { set_error_buf(error_buf, error_buf_size, "unknown type"); return false; } } + size = sizeof(uint32) * (uint64)module->func_count; + + if (size > 0) { +#if WASM_ENABLE_AOT_STACK_FRAME != 0 + if (!(module->max_local_cell_nums = + loader_malloc(size, error_buf, error_buf_size))) { + return false; + } + + for (i = 0; i < module->func_count; i++) { + read_uint32(p, p_end, module->max_local_cell_nums[i]); + } + + if (!(module->max_stack_cell_nums = + loader_malloc(size, error_buf, error_buf_size))) { + return false; + } + + for (i = 0; i < module->func_count; i++) { + read_uint32(p, p_end, module->max_stack_cell_nums[i]); + } +#else + /* Ignore max_local_cell_num and max_stack_cell_num of each function */ + CHECK_BUF(p, p_end, ((uint32)size * 2)); + p += (uint32)size * 2; +#endif + } + +#if WASM_ENABLE_GC != 0 + /* Local(params and locals) ref flags for all import and non-imported + * functions. The flags indicate whether each cell in the AOTFrame local + * area is a GC reference. */ + size = sizeof(LocalRefFlag) + * (uint64)(module->import_func_count + module->func_count); + if (size > 0) { + if (!(module->func_local_ref_flags = + loader_malloc(size, error_buf, error_buf_size))) { + return false; + } + + for (i = 0; i < module->import_func_count + module->func_count; i++) { + uint32 local_ref_flag_cell_num; + + buf = (uint8 *)align_ptr(buf, sizeof(uint32)); + read_uint32( + p, p_end, + module->func_local_ref_flags[i].local_ref_flag_cell_num); + + local_ref_flag_cell_num = + module->func_local_ref_flags[i].local_ref_flag_cell_num; + size = sizeof(uint8) * (uint64)local_ref_flag_cell_num; + if (size > 0) { + if (!(module->func_local_ref_flags[i].local_ref_flags = + loader_malloc(size, error_buf, error_buf_size))) { + return false; + } + read_byte_array(p, p_end, + module->func_local_ref_flags[i].local_ref_flags, + local_ref_flag_cell_num); + } + } + } +#endif /* end of WASM_ENABLE_GC != 0 */ + if (p != buf_end) { set_error_buf(error_buf, error_buf_size, "invalid function section size"); @@ -2974,7 +3799,7 @@ load_from_sections(AOTModule *module, AOTSection *sections, if (!strcmp(exports[i].name, "malloc")) { func_index = exports[i].index - module->import_func_count; func_type_index = module->func_type_indexes[func_index]; - func_type = module->func_types[func_type_index]; + func_type = (AOTFuncType *)module->types[func_type_index]; if (func_type->param_count == 1 && func_type->result_count == 1 && func_type->types[0] == VALUE_TYPE_I32 && func_type->types[1] == VALUE_TYPE_I32) { @@ -2987,7 +3812,7 @@ load_from_sections(AOTModule *module, AOTSection *sections, else if (!strcmp(exports[i].name, "__new")) { func_index = exports[i].index - module->import_func_count; func_type_index = module->func_type_indexes[func_index]; - func_type = module->func_types[func_type_index]; + func_type = (AOTFuncType *)module->types[func_type_index]; if (func_type->param_count == 2 && func_type->result_count == 1 && func_type->types[0] == VALUE_TYPE_I32 && func_type->types[1] == VALUE_TYPE_I32 @@ -3011,7 +3836,8 @@ load_from_sections(AOTModule *module, AOTSection *sections, export_tmp->index - module->import_func_count; func_type_index = module->func_type_indexes[func_index]; - func_type = module->func_types[func_type_index]; + func_type = + (AOTFuncType *)module->types[func_type_index]; if (func_type->param_count == 1 && func_type->result_count == 1 && func_type->types[0] == VALUE_TYPE_I32 @@ -3039,7 +3865,7 @@ load_from_sections(AOTModule *module, AOTSection *sections, || (!strcmp(exports[i].name, "__unpin"))) { func_index = exports[i].index - module->import_func_count; func_type_index = module->func_type_indexes[func_index]; - func_type = module->func_types[func_type_index]; + func_type = (AOTFuncType *)module->types[func_type_index]; if (func_type->param_count == 1 && func_type->result_count == 0 && func_type->types[0] == VALUE_TYPE_I32) { bh_assert(module->free_func_index == (uint32)-1); @@ -3089,7 +3915,27 @@ create_module(char *error_buf, uint32 error_buf_size) #endif (void)ret; +#if WASM_ENABLE_GC != 0 + if (!(module->ref_type_set = + wasm_reftype_set_create(GC_REFTYPE_MAP_SIZE_DEFAULT))) { + set_error_buf(error_buf, error_buf_size, "create reftype map failed"); + goto fail1; + } + + if (os_mutex_init(&module->rtt_type_lock)) { + set_error_buf(error_buf, error_buf_size, "init rtt type lock failed"); + goto fail2; + } +#endif + return module; +#if WASM_ENABLE_GC != 0 +fail2: + bh_hash_map_destroy(module->ref_type_set); +fail1: +#endif + wasm_runtime_free(module); + return NULL; } AOTModule * @@ -3335,7 +4181,7 @@ load(const uint8 *buf, uint32 size, AOTModule *module, char *error_buf, { uint32 i; for (i = 0; i < module->func_count; i++) { - os_printf("AOT func %u, addr: %p\n", i, module->func_ptrs[i]); + LOG_VERBOSE("AOT func %u, addr: %p\n", i, module->func_ptrs[i]); } } #endif @@ -3391,21 +4237,35 @@ aot_unload(AOTModule *module) if (module->import_tables) destroy_import_tables(module->import_tables); - if (module->tables) + if (module->tables) { +#if WASM_ENABLE_GC != 0 + uint32 i; + for (i = 0; i < module->table_count; i++) { + destroy_init_expr(&module->tables[i].init_expr); + } +#endif destroy_tables(module->tables); + } if (module->table_init_data_list) destroy_table_init_data_list(module->table_init_data_list, module->table_init_data_count); - if (module->func_types) - destroy_func_types(module->func_types, module->func_type_count); + if (module->types) + destroy_types(module->types, module->type_count); if (module->import_globals) destroy_import_globals(module->import_globals); - if (module->globals) + if (module->globals) { +#if WASM_ENABLE_GC != 0 + uint32 i; + for (i = 0; i < module->global_count; i++) { + destroy_init_expr(&module->globals[i].init_expr); + } +#endif destroy_globals(module->globals); + } if (module->import_funcs) destroy_import_funcs(module->import_funcs); @@ -3416,6 +4276,27 @@ aot_unload(AOTModule *module) if (module->func_type_indexes) wasm_runtime_free(module->func_type_indexes); +#if WASM_ENABLE_AOT_STACK_FRAME != 0 + if (module->max_local_cell_nums) + wasm_runtime_free(module->max_local_cell_nums); + if (module->max_stack_cell_nums) + wasm_runtime_free(module->max_stack_cell_nums); +#endif + +#if WASM_ENABLE_GC != 0 + if (module->func_local_ref_flags) { + uint32 i; + for (i = 0; i < module->import_func_count + module->func_count; i++) { + if (module->func_local_ref_flags[i].local_ref_flags) { + wasm_runtime_free( + module->func_local_ref_flags[i].local_ref_flags); + } + } + + wasm_runtime_free(module->func_local_ref_flags); + } +#endif + if (module->func_ptrs) wasm_runtime_free(module->func_ptrs); @@ -3487,6 +4368,39 @@ aot_unload(AOTModule *module) wasm_runtime_destroy_custom_sections(module->custom_section_list); #endif +#if WASM_ENABLE_GC != 0 + if (module->ref_type_set) { + bh_hash_map_destroy(module->ref_type_set); + } + os_mutex_destroy(&module->rtt_type_lock); + if (module->rtt_types) { + uint32 i; + for (i = 0; i < module->type_count; i++) { + if (module->rtt_types[i]) + wasm_runtime_free(module->rtt_types[i]); + } + wasm_runtime_free(module->rtt_types); + } +#if WASM_ENABLE_STRINGREF != 0 + { + uint32 i; + for (i = 0; i < WASM_TYPE_STRINGVIEWITER - WASM_TYPE_STRINGREF + 1; + i++) { + if (module->stringref_rtts[i]) + wasm_runtime_free(module->stringref_rtts[i]); + } + + if (module->string_literal_lengths) { + wasm_runtime_free(module->string_literal_lengths); + } + + if (module->string_literal_ptrs) { + wasm_runtime_free(module->string_literal_ptrs); + } + } +#endif +#endif + wasm_runtime_free(module); } diff --git a/core/iwasm/aot/aot_reloc.h b/core/iwasm/aot/aot_reloc.h index 797eacc11..c250f20a7 100644 --- a/core/iwasm/aot/aot_reloc.h +++ b/core/iwasm/aot/aot_reloc.h @@ -9,6 +9,10 @@ #include "aot_runtime.h" #include "aot_intrinsic.h" +#if WASM_ENABLE_STRINGREF != 0 +#include "string_object.h" +#endif + #ifdef __cplusplus extern "C" { #endif @@ -49,10 +53,11 @@ typedef struct { #define REG_REF_TYPES_SYM() #endif -#if (WASM_ENABLE_PERF_PROFILING != 0) || (WASM_ENABLE_DUMP_CALL_STACK != 0) +#if WASM_ENABLE_AOT_STACK_FRAME != 0 #define REG_AOT_TRACE_SYM() \ REG_SYM(aot_alloc_frame), \ - REG_SYM(aot_free_frame), + REG_SYM(aot_free_frame), \ + REG_SYM(aot_frame_update_profile_info), #else #define REG_AOT_TRACE_SYM() #endif @@ -129,6 +134,48 @@ typedef struct { #define REG_LLVM_PGO_SYM() #endif +#if WASM_ENABLE_GC != 0 +#define REG_GC_SYM() \ + REG_SYM(aot_array_init_with_data), \ + REG_SYM(aot_create_func_obj), \ + REG_SYM(aot_obj_is_instance_of), \ + REG_SYM(aot_rtt_type_new), \ + REG_SYM(wasm_array_obj_copy), \ + REG_SYM(wasm_array_obj_new), \ + REG_SYM(wasm_externref_obj_to_internal_obj), \ + REG_SYM(wasm_internal_obj_to_externref_obj), \ + REG_SYM(wasm_obj_is_type_of), \ + REG_SYM(wasm_struct_obj_new), +#else +#define REG_GC_SYM() +#endif + +#if WASM_ENABLE_STRINGREF != 0 +#define REG_STRINGREF_SYM() \ + REG_SYM(wasm_stringref_obj_new), \ + REG_SYM(wasm_stringview_wtf8_obj_new), \ + REG_SYM(wasm_stringview_wtf16_obj_new), \ + REG_SYM(wasm_stringview_iter_obj_new), \ + REG_SYM(wasm_string_destroy), \ + REG_SYM(wasm_string_new_const), \ + REG_SYM(wasm_string_new_with_encoding), \ + REG_SYM(wasm_string_measure), \ + REG_SYM(wasm_string_wtf16_get_length), \ + REG_SYM(wasm_string_encode), \ + REG_SYM(wasm_string_concat), \ + REG_SYM(wasm_string_eq), \ + REG_SYM(wasm_string_is_usv_sequence), \ + REG_SYM(wasm_string_create_view), \ + REG_SYM(wasm_string_advance), \ + REG_SYM(wasm_string_slice), \ + REG_SYM(wasm_string_get_wtf16_codeunit),\ + REG_SYM(wasm_string_next_codepoint), \ + REG_SYM(wasm_string_rewind), \ + REG_SYM(wasm_string_dump), +#else +#define REG_STRINGREF_SYM() +#endif + #define REG_COMMON_SYMBOLS \ REG_SYM(aot_set_exception_with_id), \ REG_SYM(aot_invoke_native), \ @@ -160,6 +207,8 @@ typedef struct { REG_AOT_TRACE_SYM() \ REG_INTRINSIC_SYM() \ REG_LLVM_PGO_SYM() \ + REG_GC_SYM() \ + REG_STRINGREF_SYM() \ #define CHECK_RELOC_OFFSET(data_size) do { \ if (!check_reloc_offset(target_section_size, \ diff --git a/core/iwasm/aot/aot_runtime.c b/core/iwasm/aot/aot_runtime.c index 731cacbea..abfccc7b7 100644 --- a/core/iwasm/aot/aot_runtime.c +++ b/core/iwasm/aot/aot_runtime.c @@ -21,6 +21,7 @@ * AoT compilation code: aot_create_func_context, check_suspend_flags. */ +bh_static_assert(offsetof(WASMExecEnv, cur_frame) == 1 * sizeof(uintptr_t)); bh_static_assert(offsetof(WASMExecEnv, module_inst) == 2 * sizeof(uintptr_t)); bh_static_assert(offsetof(WASMExecEnv, argv_buf) == 3 * sizeof(uintptr_t)); bh_static_assert(offsetof(WASMExecEnv, native_stack_boundary) @@ -33,6 +34,12 @@ bh_static_assert(offsetof(WASMExecEnv, aux_stack_bottom) bh_static_assert(offsetof(WASMExecEnv, native_symbol) == 8 * sizeof(uintptr_t)); bh_static_assert(offsetof(WASMExecEnv, native_stack_top_min) == 9 * sizeof(uintptr_t)); +bh_static_assert(offsetof(WASMExecEnv, wasm_stack.top_boundary) + == 10 * sizeof(uintptr_t)); +bh_static_assert(offsetof(WASMExecEnv, wasm_stack.top) + == 11 * sizeof(uintptr_t)); +bh_static_assert(offsetof(WASMExecEnv, wasm_stack.bottom) + == 12 * sizeof(uintptr_t)); bh_static_assert(offsetof(AOTModuleInstance, memories) == 1 * sizeof(uint64)); bh_static_assert(offsetof(AOTModuleInstance, func_ptrs) == 5 * sizeof(uint64)); @@ -44,7 +51,7 @@ bh_static_assert(offsetof(AOTModuleInstance, global_table_data) == 13 * sizeof(uint64) + 128 + 11 * sizeof(uint64)); bh_static_assert(sizeof(AOTMemoryInstance) == 104); -bh_static_assert(offsetof(AOTTableInstance, elems) == 8); +bh_static_assert(offsetof(AOTTableInstance, elems) == 24); bh_static_assert(offsetof(AOTModuleInstanceExtra, stack_sizes) == 0); bh_static_assert(offsetof(AOTModuleInstanceExtra, common.c_api_func_imports) @@ -55,6 +62,16 @@ bh_static_assert(sizeof(CApiFuncImport) == sizeof(uintptr_t) * 3); bh_static_assert(sizeof(wasm_val_t) == 16); bh_static_assert(offsetof(wasm_val_t, of) == 8); +bh_static_assert(offsetof(AOTFrame, prev_frame) == sizeof(uintptr_t) * 0); +bh_static_assert(offsetof(AOTFrame, func_index) == sizeof(uintptr_t) * 1); +bh_static_assert(offsetof(AOTFrame, time_started) == sizeof(uintptr_t) * 2); +bh_static_assert(offsetof(AOTFrame, func_perf_prof_info) + == sizeof(uintptr_t) * 3); +bh_static_assert(offsetof(AOTFrame, ip_offset) == sizeof(uintptr_t) * 4); +bh_static_assert(offsetof(AOTFrame, sp) == sizeof(uintptr_t) * 5); +bh_static_assert(offsetof(AOTFrame, frame_ref) == sizeof(uintptr_t) * 6); +bh_static_assert(offsetof(AOTFrame, lp) == sizeof(uintptr_t) * 7); + static void set_error_buf(char *error_buf, uint32 error_buf_size, const char *string) { @@ -103,6 +120,7 @@ check_global_init_expr(const AOTModule *module, uint32 global_index, return false; } +#if WASM_ENABLE_GC == 0 /** * Currently, constant expressions occurring as initializers of * globals are further constrained in that contained global.get @@ -116,6 +134,19 @@ check_global_init_expr(const AOTModule *module, uint32 global_index, "constant expression required"); return false; } +#else + if (global_index >= module->import_global_count + module->global_count) { + set_error_buf_v(error_buf, error_buf_size, "unknown global %u", + global_index); + return false; + } + if (global_index < module->import_global_count + && module->import_globals[global_index].is_mutable) { + set_error_buf(error_buf, error_buf_size, + "constant expression required"); + return false; + } +#endif return true; } @@ -144,10 +175,206 @@ init_global_data(uint8 *global_data, uint8 type, WASMValue *initial_value) break; #endif default: +#if WASM_ENABLE_GC != 0 + if ((type >= (uint8)REF_TYPE_ARRAYREF + && type <= (uint8)REF_TYPE_NULLFUNCREF) + || (type >= (uint8)REF_TYPE_HT_NULLABLE + && type <= (uint8)REF_TYPE_HT_NON_NULLABLE) +#if WASM_ENABLE_STRINGREF != 0 + || (type >= (uint8)REF_TYPE_STRINGVIEWWTF8 + && type <= (uint8)REF_TYPE_STRINGREF) + || (type >= (uint8)REF_TYPE_STRINGVIEWITER + && type <= (uint8)REF_TYPE_STRINGVIEWWTF16) +#endif + ) { + bh_memcpy_s(global_data, sizeof(wasm_obj_t), + &initial_value->gc_obj, sizeof(wasm_obj_t)); + break; + } +#endif /* end of WASM_ENABLE_GC */ bh_assert(0); } } +#if WASM_ENABLE_GC != 0 +static bool +assign_table_init_value(AOTModuleInstance *module_inst, AOTModule *module, + InitializerExpression *init_expr, void *addr, + char *error_buf, uint32 error_buf_size) +{ + uint8 flag = init_expr->init_expr_type; + + bh_assert(flag >= INIT_EXPR_TYPE_GET_GLOBAL + && flag <= INIT_EXPR_TYPE_EXTERN_CONVERT_ANY); + + switch (flag) { + case INIT_EXPR_TYPE_GET_GLOBAL: + { + if (!check_global_init_expr(module, init_expr->u.global_index, + error_buf, error_buf_size)) { + return false; + } + if (init_expr->u.global_index < module->import_global_count) { + PUT_REF_TO_ADDR( + addr, module->import_globals[init_expr->u.global_index] + .global_data_linked.gc_obj); + } + else { + uint32 global_idx = + init_expr->u.global_index - module->import_global_count; + return assign_table_init_value( + module_inst, module, &module->globals[global_idx].init_expr, + addr, error_buf, error_buf_size); + } + break; + } + case INIT_EXPR_TYPE_REFNULL_CONST: + { + WASMObjectRef gc_obj = NULL_REF; + PUT_REF_TO_ADDR(addr, gc_obj); + break; + } + case INIT_EXPR_TYPE_FUNCREF_CONST: + { + WASMFuncObjectRef func_obj = NULL; + uint32 func_idx = init_expr->u.u32; + + if (func_idx != UINT32_MAX) { + if (!(func_obj = + aot_create_func_obj(module_inst, func_idx, false, + error_buf, error_buf_size))) { + return false; + } + } + + PUT_REF_TO_ADDR(addr, func_obj); + break; + } + case INIT_EXPR_TYPE_I31_NEW: + { + WASMI31ObjectRef i31_obj = wasm_i31_obj_new(init_expr->u.i32); + PUT_REF_TO_ADDR(addr, i31_obj); + break; + } + case INIT_EXPR_TYPE_STRUCT_NEW: + case INIT_EXPR_TYPE_STRUCT_NEW_DEFAULT: + { + WASMRttType *rtt_type; + WASMStructObjectRef struct_obj; + WASMStructType *struct_type; + WASMStructNewInitValues *init_values = NULL; + uint32 type_idx; + + if (flag == INIT_EXPR_TYPE_STRUCT_NEW) { + init_values = (WASMStructNewInitValues *)init_expr->u.data; + type_idx = init_values->type_idx; + } + else { + type_idx = init_expr->u.type_index; + } + + struct_type = (WASMStructType *)module->types[type_idx]; + + if (!(rtt_type = wasm_rtt_type_new( + (WASMType *)struct_type, type_idx, module->rtt_types, + module->type_count, &module->rtt_type_lock))) { + set_error_buf(error_buf, error_buf_size, + "create rtt object failed"); + return false; + } + + if (!(struct_obj = wasm_struct_obj_new_internal( + ((AOTModuleInstanceExtra *)module_inst->e) + ->common.gc_heap_handle, + rtt_type))) { + set_error_buf(error_buf, error_buf_size, + "create struct object failed"); + return false; + } + + if (flag == INIT_EXPR_TYPE_STRUCT_NEW) { + uint32 field_idx; + + bh_assert(init_values->count == struct_type->field_count); + + for (field_idx = 0; field_idx < init_values->count; + field_idx++) { + wasm_struct_obj_set_field(struct_obj, field_idx, + &init_values->fields[field_idx]); + } + } + + PUT_REF_TO_ADDR(addr, struct_obj); + break; + } + case INIT_EXPR_TYPE_ARRAY_NEW: + case INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT: + case INIT_EXPR_TYPE_ARRAY_NEW_FIXED: + { + WASMRttType *rtt_type; + WASMArrayObjectRef array_obj; + WASMArrayType *array_type; + WASMArrayNewInitValues *init_values = NULL; + WASMValue *arr_init_val = NULL, empty_val = { 0 }; + uint32 type_idx, len; + + if (flag == INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT) { + type_idx = init_expr->u.array_new_default.type_index; + len = init_expr->u.array_new_default.length; + arr_init_val = &empty_val; + } + else { + init_values = (WASMArrayNewInitValues *)init_expr->u.data; + type_idx = init_values->type_idx; + len = init_values->length; + + if (flag == INIT_EXPR_TYPE_ARRAY_NEW) { + arr_init_val = init_values->elem_data; + } + } + + array_type = (WASMArrayType *)module->types[type_idx]; + + if (!(rtt_type = wasm_rtt_type_new( + (WASMType *)array_type, type_idx, module->rtt_types, + module->type_count, &module->rtt_type_lock))) { + set_error_buf(error_buf, error_buf_size, + "create rtt object failed"); + return false; + } + + if (!(array_obj = wasm_array_obj_new_internal( + ((AOTModuleInstanceExtra *)module_inst->e) + ->common.gc_heap_handle, + rtt_type, len, arr_init_val))) { + set_error_buf(error_buf, error_buf_size, + "create array object failed"); + return false; + } + + if (flag == INIT_EXPR_TYPE_ARRAY_NEW_FIXED) { + uint32 elem_idx; + + bh_assert(init_values); + + for (elem_idx = 0; elem_idx < len; elem_idx++) { + wasm_array_obj_set_elem(array_obj, elem_idx, + &init_values->elem_data[elem_idx]); + } + } + + PUT_REF_TO_ADDR(addr, array_obj); + break; + } + default: + set_error_buf(error_buf, error_buf_size, "invalid init expr type."); + return false; + } + + return true; +} +#endif /* end of WASM_ENABLE_GC != 0 */ + static bool global_instantiate(AOTModuleInstance *module_inst, AOTModule *module, char *error_buf, uint32 error_buf_size) @@ -169,29 +396,189 @@ global_instantiate(AOTModuleInstance *module_inst, AOTModule *module, /* Initialize defined global data */ for (i = 0; i < module->global_count; i++, global++) { + uint8 flag; bh_assert(global->data_offset == (uint32)(p - module_inst->global_data)); init_expr = &global->init_expr; - switch (init_expr->init_expr_type) { + flag = init_expr->init_expr_type; + switch (flag) { case INIT_EXPR_TYPE_GET_GLOBAL: { if (!check_global_init_expr(module, init_expr->u.global_index, error_buf, error_buf_size)) { return false; } +#if WASM_ENABLE_GC == 0 init_global_data( p, global->type, &module->import_globals[init_expr->u.global_index] .global_data_linked); +#else + if (init_expr->u.global_index < module->import_global_count) { + init_global_data( + p, global->type, + &module->import_globals[init_expr->u.global_index] + .global_data_linked); + } + else { + uint32 global_idx = + init_expr->u.global_index - module->import_global_count; + init_global_data(p, global->type, + &module->globals[global_idx].init_expr.u); + } +#endif break; } -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case INIT_EXPR_TYPE_REFNULL_CONST: { *(uint32 *)p = NULL_REF; break; } +#elif WASM_ENABLE_GC != 0 + case INIT_EXPR_TYPE_REFNULL_CONST: + { + WASMObjectRef gc_obj = NULL_REF; + PUT_REF_TO_ADDR(p, gc_obj); + break; + } #endif +#if WASM_ENABLE_GC != 0 + case INIT_EXPR_TYPE_FUNCREF_CONST: + { + WASMFuncObjectRef func_obj = NULL; + uint32 func_idx = init_expr->u.u32; + + if (func_idx != UINT32_MAX) { + if (!(func_obj = + aot_create_func_obj(module_inst, func_idx, false, + error_buf, error_buf_size))) { + return false; + } + } + + PUT_REF_TO_ADDR(p, func_obj); + break; + } + case INIT_EXPR_TYPE_I31_NEW: + { + WASMI31ObjectRef i31_obj = wasm_i31_obj_new(init_expr->u.i32); + PUT_REF_TO_ADDR(p, i31_obj); + break; + } + case INIT_EXPR_TYPE_STRUCT_NEW: + case INIT_EXPR_TYPE_STRUCT_NEW_DEFAULT: + { + WASMRttType *rtt_type; + WASMStructObjectRef struct_obj; + WASMStructType *struct_type; + WASMStructNewInitValues *init_values = NULL; + uint32 type_idx; + + if (flag == INIT_EXPR_TYPE_STRUCT_NEW) { + init_values = (WASMStructNewInitValues *)init_expr->u.data; + type_idx = init_values->type_idx; + } + else { + type_idx = init_expr->u.type_index; + } + + struct_type = (WASMStructType *)module->types[type_idx]; + + if (!(rtt_type = wasm_rtt_type_new( + (WASMType *)struct_type, type_idx, module->rtt_types, + module->type_count, &module->rtt_type_lock))) { + set_error_buf(error_buf, error_buf_size, + "create rtt object failed"); + return false; + } + + if (!(struct_obj = wasm_struct_obj_new_internal( + ((AOTModuleInstanceExtra *)module_inst->e) + ->common.gc_heap_handle, + rtt_type))) { + set_error_buf(error_buf, error_buf_size, + "create struct object failed"); + return false; + } + + if (flag == INIT_EXPR_TYPE_STRUCT_NEW) { + uint32 field_idx; + + bh_assert(init_values->count == struct_type->field_count); + + for (field_idx = 0; field_idx < init_values->count; + field_idx++) { + wasm_struct_obj_set_field( + struct_obj, field_idx, + &init_values->fields[field_idx]); + } + } + + PUT_REF_TO_ADDR(p, struct_obj); + break; + } + case INIT_EXPR_TYPE_ARRAY_NEW: + case INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT: + case INIT_EXPR_TYPE_ARRAY_NEW_FIXED: + { + WASMRttType *rtt_type; + WASMArrayObjectRef array_obj; + WASMArrayType *array_type; + WASMArrayNewInitValues *init_values = NULL; + WASMValue *arr_init_val = NULL, empty_val = { 0 }; + uint32 type_idx, len; + + if (flag == INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT) { + type_idx = init_expr->u.array_new_default.type_index; + len = init_expr->u.array_new_default.length; + arr_init_val = &empty_val; + } + else { + init_values = (WASMArrayNewInitValues *)init_expr->u.data; + type_idx = init_values->type_idx; + len = init_values->length; + + if (flag == INIT_EXPR_TYPE_ARRAY_NEW) { + arr_init_val = init_values->elem_data; + } + } + + array_type = (WASMArrayType *)module->types[type_idx]; + + if (!(rtt_type = wasm_rtt_type_new( + (WASMType *)array_type, type_idx, module->rtt_types, + module->type_count, &module->rtt_type_lock))) { + set_error_buf(error_buf, error_buf_size, + "create rtt object failed"); + return false; + } + + if (!(array_obj = wasm_array_obj_new_internal( + ((AOTModuleInstanceExtra *)module_inst->e) + ->common.gc_heap_handle, + rtt_type, len, arr_init_val))) { + set_error_buf(error_buf, error_buf_size, + "create array object failed"); + return false; + } + + if (flag == INIT_EXPR_TYPE_ARRAY_NEW_FIXED) { + uint32 elem_idx; + + bh_assert(init_values); + + for (elem_idx = 0; elem_idx < len; elem_idx++) { + wasm_array_obj_set_elem( + array_obj, elem_idx, + &init_values->elem_data[elem_idx]); + } + } + + PUT_REF_TO_ADDR(p, array_obj); + break; + } +#endif /* end of WASM_ENABLE_GC != 0 */ default: { init_global_data(p, global->type, &init_expr->u); @@ -216,7 +603,7 @@ tables_instantiate(AOTModuleInstance *module_inst, AOTModule *module, AOTTableInitData *table_seg; AOTTableInstance *tbl_inst = first_tbl_inst; - total_size = (uint64)sizeof(WASMTableInstance *) * module_inst->table_count; + total_size = (uint64)sizeof(AOTTableInstance *) * module_inst->table_count; if (total_size > 0 && !(module_inst->tables = runtime_malloc(total_size, error_buf, error_buf_size))) { @@ -233,27 +620,48 @@ tables_instantiate(AOTModuleInstance *module_inst, AOTModule *module, tbl_inst->cur_size = import_table->table_init_size; tbl_inst->max_size = aot_get_imp_tbl_data_slots(import_table, false); +#if WASM_ENABLE_GC != 0 + tbl_inst->elem_type = module->tables[i].elem_type; + tbl_inst->elem_ref_type.elem_ref_type = + module->tables[i].elem_ref_type; +#endif } else { AOTTable *table = module->tables + (i - module->import_table_count); tbl_inst->cur_size = table->table_init_size; tbl_inst->max_size = aot_get_tbl_data_slots(table, false); +#if WASM_ENABLE_GC != 0 + tbl_inst->elem_type = module->tables[i].elem_type; + tbl_inst->elem_ref_type.elem_ref_type = + module->tables[i].elem_ref_type; +#endif } - /* Set all elements to -1 to mark them as uninitialized elements */ - memset(tbl_inst->elems, 0xff, sizeof(uint32) * tbl_inst->max_size); + /* Set all elements to -1 or NULL_REF to mark them as uninitialized + * elements */ +#if WASM_ENABLE_GC == 0 + memset(tbl_inst->elems, 0xff, + sizeof(table_elem_type_t) * tbl_inst->max_size); +#else + memset(tbl_inst->elems, 0x00, + sizeof(table_elem_type_t) * tbl_inst->max_size); +#endif module_inst->tables[i] = tbl_inst; tbl_inst = (AOTTableInstance *)((uint8 *)tbl_inst + offsetof(AOTTableInstance, elems) - + sizeof(uint32) * tbl_inst->max_size); + + sizeof(table_elem_type_t) + * tbl_inst->max_size); } /* fill table with element segment content */ for (i = 0; i < module->table_init_data_count; i++) { +#if WASM_ENABLE_GC == 0 + uint32 j; +#endif table_seg = module->table_init_data_list[i]; -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 if (!wasm_elem_is_active(table_seg->mode)) continue; #endif @@ -307,20 +715,20 @@ tables_instantiate(AOTModuleInstance *module_inst, AOTModule *module, "out of bounds table access"); #else set_error_buf(error_buf, error_buf_size, - "elements segment does not fit"); + "type mismatch: elements segment does not fit"); #endif return false; } /* base_offset + length(could be zero) */ - length = table_seg->func_index_count; + length = table_seg->value_count; if (base_offset + length > tbl_inst->cur_size) { #if WASM_ENABLE_REF_TYPES != 0 set_error_buf(error_buf, error_buf_size, "out of bounds table access"); #else set_error_buf(error_buf, error_buf_size, - "elements segment does not fit"); + "type mismatch: elements segment does not fit"); #endif return false; } @@ -329,9 +737,12 @@ tables_instantiate(AOTModuleInstance *module_inst, AOTModule *module, * Check function index in the current module inst for now. * will check the linked table inst owner in future */ - bh_memcpy_s(tbl_inst->elems + base_offset, - (tbl_inst->max_size - base_offset) * sizeof(uint32), - table_seg->func_indexes, length * sizeof(uint32)); +#if WASM_ENABLE_GC == 0 + for (j = 0; j < length; j++) { + tbl_inst->elems[base_offset + j] = + table_seg->init_values[j].u.ref_index; + } +#endif } return true; @@ -340,9 +751,6 @@ tables_instantiate(AOTModuleInstance *module_inst, AOTModule *module, static void memories_deinstantiate(AOTModuleInstance *module_inst) { -#ifdef WASM_LINEAR_MEMORY_MMAP - uint64 map_size; -#endif uint32 i; AOTMemoryInstance *memory_inst; @@ -364,23 +772,7 @@ memories_deinstantiate(AOTModuleInstance *module_inst) } if (memory_inst->memory_data) { -#ifndef OS_ENABLE_HW_BOUND_CHECK -#ifdef WASM_LINEAR_MEMORY_MMAP - if (shared_memory_is_shared(memory_inst)) { - map_size = (uint64)memory_inst->num_bytes_per_page - * memory_inst->max_page_count; - wasm_munmap_linear_memory(memory_inst->memory_data, - map_size, map_size); - } - else -#endif - wasm_runtime_free(memory_inst->memory_data); -#else - map_size = (uint64)memory_inst->num_bytes_per_page - * memory_inst->cur_page_count; - wasm_munmap_linear_memory(memory_inst->memory_data, map_size, - 8 * (uint64)BH_GB); -#endif + wasm_deallocate_linear_memory(memory_inst); } } } @@ -402,14 +794,10 @@ memory_instantiate(AOTModuleInstance *module_inst, AOTModuleInstance *parent, uint32 heap_offset = num_bytes_per_page * init_page_count; uint64 memory_data_size, max_memory_data_size; uint8 *p = NULL, *global_addr; -#ifdef WASM_LINEAR_MEMORY_MMAP - uint8 *mapped_mem = NULL; - uint64 map_size; -#endif + bool is_shared_memory = false; #if WASM_ENABLE_SHARED_MEMORY != 0 - bool is_shared_memory = memory->memory_flags & 0x02 ? true : false; - + is_shared_memory = memory->memory_flags & 0x02 ? true : false; /* Shared memory */ if (is_shared_memory && parent != NULL) { AOTMemoryInstance *shared_memory_instance; @@ -519,55 +907,18 @@ memory_instantiate(AOTModuleInstance *module_inst, AOTModuleInstance *parent, module->aux_stack_size); LOG_VERBOSE(" heap offset: %u, heap size: %d\n", heap_offset, heap_size); - memory_data_size = (uint64)num_bytes_per_page * init_page_count; max_memory_data_size = (uint64)num_bytes_per_page * max_page_count; - bh_assert(memory_data_size <= UINT32_MAX); bh_assert(max_memory_data_size <= 4 * (uint64)BH_GB); (void)max_memory_data_size; -#ifndef OS_ENABLE_HW_BOUND_CHECK -#if WASM_ENABLE_SHARED_MEMORY != 0 - if (is_shared_memory) { -#if WASM_ENABLE_SHARED_MEMORY_MMAP != 0 - map_size = max_memory_data_size; - if (max_memory_data_size > 0 - && !(p = mapped_mem = - wasm_mmap_linear_memory(map_size, &max_memory_data_size, - error_buf, error_buf_size))) { - return NULL; - } -#else - /* Allocate maximum memory size when memory is shared */ - if (max_memory_data_size > 0 - && !(p = runtime_malloc(max_memory_data_size, error_buf, - error_buf_size))) { - return NULL; - } -#endif - } - else -#endif /* end of WASM_ENABLE_SHARED_MEMORY != 0 */ - { - /* Allocate initial memory size when memory is not shared */ - if (memory_data_size > 0 - && !(p = runtime_malloc(memory_data_size, error_buf, - error_buf_size))) { - return NULL; - } - } -#else /* else of OS_ENABLE_HW_BOUND_CHECK */ - /* Totally 8G is mapped, the opcode load/store address range is 0 to 8G: - * ea = i + memarg.offset - * both i and memarg.offset are u32 in range 0 to 4G - * so the range of ea is 0 to 8G - */ - map_size = 8 * (uint64)BH_GB; - if (!(p = mapped_mem = wasm_mmap_linear_memory( - map_size, &memory_data_size, error_buf, error_buf_size))) { - set_error_buf(error_buf, error_buf_size, "mmap memory failed"); + if (wasm_allocate_linear_memory(&p, is_shared_memory, num_bytes_per_page, + init_page_count, max_page_count, + &memory_data_size) + != BHT_OK) { + set_error_buf(error_buf, error_buf_size, + "allocate linear memory failed"); return NULL; } -#endif /* end of OS_ENABLE_HW_BOUND_CHECK */ memory_inst->module_type = Wasm_Module_AoT; memory_inst->num_bytes_per_page = num_bytes_per_page; @@ -617,16 +968,8 @@ fail2: if (heap_size > 0) wasm_runtime_free(memory_inst->heap_handle); fail1: -#ifdef WASM_LINEAR_MEMORY_MMAP - if (mapped_mem) - wasm_munmap_linear_memory(mapped_mem, memory_data_size, map_size); - else -#endif - { - if (memory_inst->memory_data) - wasm_runtime_free(memory_inst->memory_data); - } - memory_inst->memory_data = NULL; + wasm_deallocate_linear_memory(memory_inst); + return NULL; } @@ -856,7 +1199,7 @@ create_export_funcs(AOTModuleInstance *module_inst, AOTModule *module, export_func->func_index - module->import_func_count; ftype_index = module->func_type_indexes[func_index]; export_func->u.func.func_type = - module->func_types[ftype_index]; + (AOTFuncType *)module->types[ftype_index]; export_func->u.func.func_ptr = module->func_ptrs[func_index]; } @@ -1032,7 +1375,8 @@ execute_post_instantiate_functions(AOTModuleInstance *module_inst, start_func.is_import_func = false; func_type_idx = module->func_type_indexes[module->start_func_index - module->import_func_count]; - start_func.u.func.func_type = module->func_types[func_type_idx]; + start_func.u.func.func_type = + (AOTFuncType *)module->types[func_type_idx]; start_func.u.func.func_ptr = module->start_function; if (!aot_call_function(exec_env, &start_func, 0, NULL)) { goto fail; @@ -1126,7 +1470,7 @@ aot_instantiate(AOTModule *module, AOTModuleInstance *parent, */ for (i = 0; i != module->import_table_count; ++i) { table_size += offsetof(AOTTableInstance, elems); - table_size += (uint64)sizeof(uint32) + table_size += (uint64)sizeof(table_elem_type_t) * (uint64)aot_get_imp_tbl_data_slots( module->import_tables + i, false); } @@ -1134,7 +1478,7 @@ aot_instantiate(AOTModule *module, AOTModuleInstance *parent, for (i = 0; i != module->table_count; ++i) { table_size += offsetof(AOTTableInstance, elems); table_size += - (uint64)sizeof(uint32) + (uint64)sizeof(table_elem_type_t) * (uint64)aot_get_tbl_data_slots(module->tables + i, false); } total_size += table_size; @@ -1155,6 +1499,31 @@ aot_instantiate(AOTModule *module, AOTModuleInstance *parent, module_inst->e = (WASMModuleInstanceExtra *)((uint8 *)module_inst + extra_info_offset); +#if WASM_ENABLE_GC != 0 + /* Initialize gc heap first since it may be used when initializing + globals and others */ + if (!is_sub_inst) { + uint32 gc_heap_size = wasm_runtime_get_gc_heap_size_default(); + AOTModuleInstanceExtra *extra = + (AOTModuleInstanceExtra *)module_inst->e; + + if (gc_heap_size < GC_HEAP_SIZE_MIN) + gc_heap_size = GC_HEAP_SIZE_MIN; + if (gc_heap_size > GC_HEAP_SIZE_MAX) + gc_heap_size = GC_HEAP_SIZE_MAX; + + extra->common.gc_heap_pool = + runtime_malloc(gc_heap_size, error_buf, error_buf_size); + if (!extra->common.gc_heap_pool) + goto fail; + + extra->common.gc_heap_handle = + mem_allocator_create(extra->common.gc_heap_pool, gc_heap_size); + if (!extra->common.gc_heap_handle) + goto fail; + } +#endif + #if WASM_ENABLE_MULTI_MODULE != 0 ((AOTModuleInstanceExtra *)module_inst->e)->sub_module_inst_list = &((AOTModuleInstanceExtra *)module_inst->e)->sub_module_inst_list_head; @@ -1167,6 +1536,11 @@ aot_instantiate(AOTModule *module, AOTModuleInstance *parent, } #endif + /* Initialize function type indexes before initializing global info, + module_inst->func_type_indexes may be used in the latter */ + if (!init_func_type_indexes(module_inst, module, error_buf, error_buf_size)) + goto fail; + #if WASM_ENABLE_BULK_MEMORY != 0 || WASM_ENABLE_REF_TYPES != 0 common = &((AOTModuleInstanceExtra *)module_inst->e)->common; #endif @@ -1225,10 +1599,6 @@ aot_instantiate(AOTModule *module, AOTModuleInstance *parent, if (!init_func_ptrs(module_inst, module, error_buf, error_buf_size)) goto fail; - /* Initialize function type indexes */ - if (!init_func_type_indexes(module_inst, module, error_buf, error_buf_size)) - goto fail; - if (!check_linked_symbol(module, error_buf, error_buf_size)) goto fail; @@ -1256,8 +1626,14 @@ aot_instantiate(AOTModule *module, AOTModuleInstance *parent, if (stack_size == 0) stack_size = DEFAULT_WASM_STACK_SIZE; #if WASM_ENABLE_SPEC_TEST != 0 - if (stack_size < 48 * 1024) - stack_size = 48 * 1024; +#if WASM_ENABLE_TAIL_CALL == 0 + if (stack_size < 128 * 1024) + stack_size = 128 * 1024; +#else + /* Some tail-call cases require large operand stack */ + if (stack_size < 10 * 1024 * 1024) + stack_size = 10 * 1024 * 1024; +#endif #endif module_inst->default_wasm_stack_size = stack_size; @@ -1273,6 +1649,144 @@ aot_instantiate(AOTModule *module, AOTModuleInstance *parent, } #endif +#if WASM_ENABLE_GC != 0 + for (i = 0; i < module_inst->table_count; i++) { + uint32 j; + AOTTable *table; + AOTTableInstance *table_inst; + table_elem_type_t *table_data; + + table = &module->tables[i]; + bh_assert(table); + + if (table->init_expr.init_expr_type == INIT_EXPR_NONE) { + continue; + } + + table_inst = module_inst->tables[i]; + bh_assert(table_inst); + + table_data = table_inst->elems; + bh_assert(table_data); + + for (j = 0; j < table_inst->cur_size; j++) { + if (!assign_table_init_value(module_inst, module, &table->init_expr, + table_data + j, error_buf, + error_buf_size)) { + goto fail; + } + } + } + + /* Initialize the table data with table init data */ + for (i = 0; + module_inst->table_count > 0 && i < module->table_init_data_count; + i++) { + + AOTTableInitData *table_init_data = module->table_init_data_list[i]; + AOTTableInstance *table; + table_elem_type_t *table_data; + uint8 tbl_elem_type; + uint32 tbl_init_size, tbl_max_size, j; + WASMRefType *tbl_elem_ref_type; + + bh_assert(table_init_data); + + table = module_inst->tables[table_init_data->table_index]; + bh_assert(table); + + table_data = table->elems; + bh_assert(table_data); + + wasm_runtime_get_table_inst_elem_type( + (WASMModuleInstanceCommon *)module_inst, i, &tbl_elem_type, + &tbl_elem_ref_type, &tbl_init_size, &tbl_max_size); + + if (!wasm_elem_is_declarative(table_init_data->mode) + && !wasm_reftype_is_subtype_of( + table_init_data->elem_type, table_init_data->elem_ref_type, + table->elem_type, table->elem_ref_type.elem_ref_type, + module->types, module->type_count)) { + set_error_buf(error_buf, error_buf_size, + "type mismatch: elements segment does not fit"); + goto fail; + } + + (void)tbl_init_size; + (void)tbl_max_size; + + if (!wasm_elem_is_active(table_init_data->mode)) { + continue; + } + + bh_assert(table_init_data->offset.init_expr_type + == INIT_EXPR_TYPE_I32_CONST + || table_init_data->offset.init_expr_type + == INIT_EXPR_TYPE_GET_GLOBAL + || table_init_data->offset.init_expr_type + == INIT_EXPR_TYPE_FUNCREF_CONST + || table_init_data->offset.init_expr_type + == INIT_EXPR_TYPE_REFNULL_CONST); + + /* init vec(funcidx) or vec(expr) */ + if (table_init_data->offset.init_expr_type + == INIT_EXPR_TYPE_GET_GLOBAL) { + uint32 data_offset; + if (!check_global_init_expr(module, + table_init_data->offset.u.global_index, + error_buf, error_buf_size)) { + goto fail; + } + + if (table_init_data->offset.u.global_index + < module->import_global_count) { + data_offset = + module + ->import_globals[table_init_data->offset.u.global_index] + .data_offset; + } + else { + data_offset = + module + ->globals[table_init_data->offset.u.global_index + - module->import_global_count] + .data_offset; + } + + table_init_data->offset.u.i32 = + *(uint32 *)(module_inst->global_data + data_offset); + } + + /* check offset since length might negative */ + if ((uint32)table_init_data->offset.u.i32 > table->cur_size) { + LOG_DEBUG("base_offset(%d) > table->cur_size(%d)", + table_init_data->offset.u.i32, table->cur_size); + set_error_buf(error_buf, error_buf_size, + "out of bounds table access"); + goto fail; + } + + if ((uint32)table_init_data->offset.u.i32 + table_init_data->value_count + > table->cur_size) { + LOG_DEBUG("base_offset(%d) + length(%d) > table->cur_size(%d)", + table_init_data->offset.u.i32, + table_init_data->value_count, table->cur_size); + set_error_buf(error_buf, error_buf_size, + "out of bounds table access"); + goto fail; + } + + for (j = 0; j < module->table_init_data_list[i]->value_count; j++) { + if (!assign_table_init_value( + module_inst, module, &table_init_data->init_values[j], + table_data + table_init_data->offset.u.i32 + j, error_buf, + error_buf_size)) { + goto fail; + } + } + } +#endif + #if WASM_ENABLE_DUMP_CALL_STACK != 0 if (!(module_inst->frames = runtime_malloc(sizeof(Vector), error_buf, error_buf_size))) { @@ -1298,6 +1812,29 @@ fail: return NULL; } +#if WASM_ENABLE_DUMP_CALL_STACK != 0 +static void +destroy_c_api_frames(Vector *frames) +{ + WASMCApiFrame frame = { 0 }; + uint32 i, total_frames, ret; + + total_frames = (uint32)bh_vector_size(frames); + + for (i = 0; i < total_frames; i++) { + ret = bh_vector_get(frames, i, &frame); + bh_assert(ret); + + if (frame.lp) + wasm_runtime_free(frame.lp); + } + + ret = bh_vector_destroy(frames); + bh_assert(ret); + (void)ret; +} +#endif + void aot_deinstantiate(AOTModuleInstance *module_inst, bool is_sub_inst) { @@ -1319,7 +1856,7 @@ aot_deinstantiate(AOTModuleInstance *module_inst, bool is_sub_inst) #if WASM_ENABLE_DUMP_CALL_STACK != 0 if (module_inst->frames) { - bh_vector_destroy(module_inst->frames); + destroy_c_api_frames(module_inst->frames); wasm_runtime_free(module_inst->frames); module_inst->frames = NULL; } @@ -1349,6 +1886,17 @@ aot_deinstantiate(AOTModuleInstance *module_inst, bool is_sub_inst) wasm_runtime_free(((AOTModuleInstanceExtra *)module_inst->e) ->common.c_api_func_imports); +#if WASM_ENABLE_GC != 0 + if (!is_sub_inst) { + AOTModuleInstanceExtra *extra = + (AOTModuleInstanceExtra *)module_inst->e; + if (extra->common.gc_heap_handle) + mem_allocator_destroy(extra->common.gc_heap_handle); + if (extra->common.gc_heap_pool) + wasm_runtime_free(extra->common.gc_heap_pool); + } +#endif + if (!is_sub_inst) { #if WASM_ENABLE_WASI_NN != 0 wasi_nn_destroy(module_inst); @@ -1384,7 +1932,7 @@ aot_lookup_function(const AOTModuleInstance *module_inst, const char *name, #ifdef OS_ENABLE_HW_BOUND_CHECK static bool invoke_native_with_hw_bound_check(WASMExecEnv *exec_env, void *func_ptr, - const WASMType *func_type, + const WASMFuncType *func_type, const char *signature, void *attachment, uint32 *argv, uint32 argc, uint32 *argv_ret) { @@ -1478,7 +2026,7 @@ invoke_native_with_hw_bound_check(WASMExecEnv *exec_env, void *func_ptr, #else /* else of OS_ENABLE_HW_BOUND_CHECK */ static inline bool invoke_native_internal(WASMExecEnv *exec_env, void *func_ptr, - const WASMType *func_type, const char *signature, + const WASMFuncType *func_type, const char *signature, void *attachment, uint32 *argv, uint32 argc, uint32 *argv_ret) { @@ -1498,6 +2046,18 @@ invoke_native_internal(WASMExecEnv *exec_env, void *func_ptr, } #endif /* end of OS_ENABLE_HW_BOUND_CHECK */ +#ifdef AOT_STACK_FRAME_DEBUG +typedef void (*stack_frame_callback_t)(struct WASMExecEnv *exec_env); +static stack_frame_callback_t aot_stack_frame_callback; + +/* set the callback, only for debug purpose */ +void +aot_set_stack_frame_callback(stack_frame_callback_t callback) +{ + aot_stack_frame_callback = callback; +} +#endif + bool aot_call_function(WASMExecEnv *exec_env, AOTFunctionInstance *function, unsigned argc, uint32 argv[]) @@ -1581,6 +2141,9 @@ aot_call_function(WASMExecEnv *exec_env, AOTFunctionInstance *function, uint32 *argv_ret = argv; uint32 ext_ret_cell = wasm_get_cell_num(ext_ret_types, ext_ret_count); uint64 size; +#if WASM_ENABLE_AOT_STACK_FRAME != 0 + struct WASMInterpFrame *prev_frame = exec_env->cur_frame; +#endif /* Allocate memory all arguments */ size = @@ -1609,7 +2172,7 @@ aot_call_function(WASMExecEnv *exec_env, AOTFunctionInstance *function, cell_num += wasm_value_type_cell_num(ext_ret_types[i]); } -#if (WASM_ENABLE_DUMP_CALL_STACK != 0) || (WASM_ENABLE_PERF_PROFILING != 0) +#if WASM_ENABLE_AOT_STACK_FRAME != 0 if (!aot_alloc_frame(exec_env, function->func_index)) { if (argv1 != argv1_buf) wasm_runtime_free(argv1); @@ -1620,16 +2183,25 @@ aot_call_function(WASMExecEnv *exec_env, AOTFunctionInstance *function, ret = invoke_native_internal(exec_env, function->u.func.func_ptr, func_type, NULL, NULL, argv1, argc, argv); -#if WASM_ENABLE_DUMP_CALL_STACK != 0 if (!ret) { +#ifdef AOT_STACK_FRAME_DEBUG + if (aot_stack_frame_callback) { + aot_stack_frame_callback(exec_env); + } +#endif +#if WASM_ENABLE_DUMP_CALL_STACK != 0 if (aot_create_call_stack(exec_env)) { aot_dump_call_stack(exec_env, true, NULL, 0); } - } #endif + } -#if (WASM_ENABLE_DUMP_CALL_STACK != 0) || (WASM_ENABLE_PERF_PROFILING != 0) - aot_free_frame(exec_env); +#if WASM_ENABLE_AOT_STACK_FRAME != 0 + /* Free all frames allocated, note that some frames + may be allocated in AOT code and havent' been + freed if exception occured */ + while (exec_env->cur_frame != prev_frame) + aot_free_frame(exec_env); #endif if (!ret) { if (argv1 != argv1_buf) @@ -1670,7 +2242,9 @@ aot_call_function(WASMExecEnv *exec_env, AOTFunctionInstance *function, return true; } else { -#if (WASM_ENABLE_DUMP_CALL_STACK != 0) || (WASM_ENABLE_PERF_PROFILING != 0) +#if WASM_ENABLE_AOT_STACK_FRAME != 0 + struct WASMInterpFrame *prev_frame = exec_env->cur_frame; + if (!aot_alloc_frame(exec_env, function->func_index)) { return false; } @@ -1679,16 +2253,25 @@ aot_call_function(WASMExecEnv *exec_env, AOTFunctionInstance *function, ret = invoke_native_internal(exec_env, func_ptr, func_type, NULL, NULL, argv, argc, argv); -#if WASM_ENABLE_DUMP_CALL_STACK != 0 if (aot_copy_exception(module_inst, NULL)) { +#ifdef AOT_STACK_FRAME_DEBUG + if (aot_stack_frame_callback) { + aot_stack_frame_callback(exec_env); + } +#endif +#if WASM_ENABLE_DUMP_CALL_STACK != 0 if (aot_create_call_stack(exec_env)) { aot_dump_call_stack(exec_env, true, NULL, 0); } - } #endif + } -#if (WASM_ENABLE_DUMP_CALL_STACK != 0) || (WASM_ENABLE_PERF_PROFILING != 0) - aot_free_frame(exec_env); +#if WASM_ENABLE_AOT_STACK_FRAME != 0 + /* Free all frames allocated, note that some frames + may be allocated in AOT code and havent' been + freed if exception occured */ + while (exec_env->cur_frame != prev_frame) + aot_free_frame(exec_env); #endif return ret && !aot_copy_exception(module_inst, NULL) ? true : false; @@ -2070,7 +2653,7 @@ aot_invoke_native(WASMExecEnv *exec_env, uint32 func_idx, uint32 argc, : NULL; uint32 *func_type_indexes = module_inst->func_type_indexes; uint32 func_type_idx = func_type_indexes[func_idx]; - AOTFuncType *func_type = aot_module->func_types[func_type_idx]; + AOTFuncType *func_type = (AOTFuncType *)aot_module->types[func_type_idx]; void **func_ptrs = module_inst->func_ptrs; void *func_ptr = func_ptrs[func_idx]; AOTImportFunc *import_func; @@ -2158,6 +2741,7 @@ aot_call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 table_elem_idx, AOTFuncType *func_type; void **func_ptrs = module_inst->func_ptrs, *func_ptr; uint32 func_type_idx, func_idx, ext_ret_count; + table_elem_type_t tbl_elem_val = NULL_REF; AOTImportFunc *import_func; const char *signature = NULL; void *attachment = NULL; @@ -2182,14 +2766,21 @@ aot_call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 table_elem_idx, goto fail; } - func_idx = tbl_inst->elems[table_elem_idx]; - if (func_idx == NULL_REF) { + tbl_elem_val = ((table_elem_type_t *)tbl_inst->elems)[table_elem_idx]; + if (tbl_elem_val == NULL_REF) { aot_set_exception_with_id(module_inst, EXCE_UNINITIALIZED_ELEMENT); goto fail; } +#if WASM_ENABLE_GC == 0 + func_idx = tbl_elem_val; +#else + func_idx = + wasm_func_obj_get_func_idx_bound((WASMFuncObjectRef)tbl_elem_val); +#endif + func_type_idx = func_type_indexes[func_idx]; - func_type = aot_module->func_types[func_type_idx]; + func_type = (AOTFuncType *)aot_module->types[func_type_idx]; if (func_idx >= aot_module->import_func_count) { /* func pointer was looked up previously */ @@ -2487,9 +3078,9 @@ aot_get_module_mem_consumption(const AOTModule *module, mem_conspn->module_struct_size = sizeof(AOTModule); - mem_conspn->types_size = sizeof(AOTFuncType *) * module->func_type_count; - for (i = 0; i < module->func_type_count; i++) { - AOTFuncType *type = module->func_types[i]; + mem_conspn->types_size = sizeof(AOTFuncType *) * module->type_count; + for (i = 0; i < module->type_count; i++) { + AOTFuncType *type = (AOTFuncType *)module->types[i]; size = offsetof(AOTFuncType, types) + sizeof(uint8) * (type->param_count + type->result_count); mem_conspn->types_size += size; @@ -2515,8 +3106,8 @@ aot_get_module_mem_consumption(const AOTModule *module, sizeof(AOTTableInitData *) * module->table_init_data_count; for (i = 0; i < module->table_init_data_count; i++) { AOTTableInitData *init_data = module->table_init_data_list[i]; - size = offsetof(AOTTableInitData, func_indexes) - + sizeof(uint32) * init_data->func_index_count; + size = offsetof(AOTTableInitData, init_values) + + sizeof(InitializerExpression) * init_data->value_count; mem_conspn->table_segs_size += size; } @@ -2613,7 +3204,7 @@ aot_get_module_inst_mem_consumption(const AOTModuleInstance *module_inst, #endif /* end of (WASM_ENABLE_MEMORY_PROFILING != 0) \ || (WASM_ENABLE_MEMORY_TRACING != 0) */ -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 void aot_drop_table_seg(AOTModuleInstance *module_inst, uint32 tbl_seg_idx) { @@ -2629,8 +3220,13 @@ aot_table_init(AOTModuleInstance *module_inst, uint32 tbl_idx, { AOTTableInstance *tbl_inst; AOTTableInitData *tbl_seg; - uint32 *tbl_seg_elems = NULL, tbl_seg_len = 0; const AOTModule *module = (AOTModule *)module_inst->module; + table_elem_type_t *table_elems; + InitializerExpression *tbl_seg_init_values = NULL, *init_values; + uint32 i, tbl_seg_len = 0; +#if WASM_ENABLE_GC != 0 + void *func_obj; +#endif tbl_inst = module_inst->tables[tbl_idx]; bh_assert(tbl_inst); @@ -2642,8 +3238,8 @@ aot_table_init(AOTModuleInstance *module_inst, uint32 tbl_idx, ((AOTModuleInstanceExtra *)module_inst->e)->common.elem_dropped, tbl_seg_idx)) { /* table segment isn't dropped */ - tbl_seg_elems = tbl_seg->func_indexes; - tbl_seg_len = tbl_seg->func_index_count; + tbl_seg_init_values = tbl_seg->init_values; + tbl_seg_len = tbl_seg->value_count; } if (offset_len_out_of_bounds(src_offset, length, tbl_seg_len) @@ -2656,10 +3252,28 @@ aot_table_init(AOTModuleInstance *module_inst, uint32 tbl_idx, return; } - bh_memcpy_s((uint8 *)tbl_inst + offsetof(AOTTableInstance, elems) - + dst_offset * sizeof(uint32), - (tbl_inst->cur_size - dst_offset) * sizeof(uint32), - tbl_seg_elems + src_offset, length * sizeof(uint32)); + table_elems = tbl_inst->elems + dst_offset; + init_values = tbl_seg_init_values + src_offset; + + for (i = 0; i < length; i++) { +#if WASM_ENABLE_GC != 0 + /* UINT32_MAX indicates that it is a null ref */ + if (init_values[i].u.ref_index != UINT32_MAX) { + if (!(func_obj = aot_create_func_obj(module_inst, + init_values[i].u.ref_index, + true, NULL, 0))) { + aot_set_exception_with_id(module_inst, EXCE_NULL_FUNC_OBJ); + return; + } + table_elems[i] = func_obj; + } + else { + table_elems[i] = NULL_REF; + } +#else + table_elems[i] = init_values[i].u.ref_index; +#endif + } } void @@ -2686,16 +3300,17 @@ aot_table_copy(AOTModuleInstance *module_inst, uint32 src_tbl_idx, /* if src_offset < dst_offset, copy from back to front */ /* merge all together */ bh_memmove_s((uint8 *)dst_tbl_inst + offsetof(AOTTableInstance, elems) - + dst_offset * sizeof(uint32), - (dst_tbl_inst->cur_size - dst_offset) * sizeof(uint32), + + dst_offset * sizeof(table_elem_type_t), + (dst_tbl_inst->cur_size - dst_offset) + * sizeof(table_elem_type_t), (uint8 *)src_tbl_inst + offsetof(AOTTableInstance, elems) - + src_offset * sizeof(uint32), - length * sizeof(uint32)); + + src_offset * sizeof(table_elem_type_t), + length * sizeof(table_elem_type_t)); } void aot_table_fill(AOTModuleInstance *module_inst, uint32 tbl_idx, uint32 length, - uint32 val, uint32 data_offset) + table_elem_type_t val, uint32 data_offset) { AOTTableInstance *tbl_inst; @@ -2714,7 +3329,7 @@ aot_table_fill(AOTModuleInstance *module_inst, uint32 tbl_idx, uint32 length, uint32 aot_table_grow(AOTModuleInstance *module_inst, uint32 tbl_idx, - uint32 inc_entries, uint32 init_val) + uint32 inc_entries, table_elem_type_t init_val) { uint32 entry_count, i, orig_tbl_sz; AOTTableInstance *tbl_inst; @@ -2747,9 +3362,10 @@ aot_table_grow(AOTModuleInstance *module_inst, uint32 tbl_idx, tbl_inst->cur_size = entry_count; return orig_tbl_sz; } -#endif /* WASM_ENABLE_REF_TYPES != 0 */ +#endif /* WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */ -#if (WASM_ENABLE_DUMP_CALL_STACK != 0) || (WASM_ENABLE_PERF_PROFILING != 0) +#if WASM_ENABLE_AOT_STACK_FRAME != 0 +#if WASM_ENABLE_DUMP_CALL_STACK != 0 || WASM_ENABLE_PERF_PROFILING != 0 #if WASM_ENABLE_CUSTOM_NAME_SECTION != 0 static const char * lookup_func_name(const char **func_names, uint32 *func_indexes, @@ -2808,29 +3424,134 @@ get_func_name_from_index(const AOTModuleInstance *module_inst, return func_name; } +#endif /* end of WASM_ENABLE_DUMP_CALL_STACK != 0 || \ + WASM_ENABLE_PERF_PROFILING != 0 */ + +#if WASM_ENABLE_GC == 0 +bool +aot_alloc_frame(WASMExecEnv *exec_env, uint32 func_index) +{ + AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst; +#if WASM_ENABLE_PERF_PROFILING != 0 + AOTFuncPerfProfInfo *func_perf_prof = + module_inst->func_perf_profilings + func_index; +#endif + AOTFrame *cur_frame, *frame; + uint32 size = (uint32)offsetof(AOTFrame, lp); + + cur_frame = (AOTFrame *)exec_env->cur_frame; + if (!cur_frame) + frame = (AOTFrame *)exec_env->wasm_stack.bottom; + else + frame = (AOTFrame *)((uint8 *)cur_frame + size); + + if ((uint8 *)frame + size > exec_env->wasm_stack.top_boundary) { + aot_set_exception(module_inst, "wasm operand stack overflow"); + return false; + } + + frame->func_index = func_index; + /* No need to initialize ip, it will be committed in jitted code + when needed */ + /* frame->ip = NULL; */ + frame->prev_frame = (AOTFrame *)exec_env->cur_frame; + +#if WASM_ENABLE_PERF_PROFILING != 0 + frame->time_started = (uintptr_t)os_time_thread_cputime_us(); + frame->func_perf_prof_info = func_perf_prof; +#endif +#if WASM_ENABLE_MEMORY_PROFILING != 0 + { + uint32 wasm_stack_used = + (uint8 *)frame + size - exec_env->wasm_stack.bottom; + if (wasm_stack_used > exec_env->max_wasm_stack_used) + exec_env->max_wasm_stack_used = wasm_stack_used; + } +#endif + + exec_env->cur_frame = (struct WASMInterpFrame *)frame; + + return true; +} + +static inline void +aot_free_frame_internal(WASMExecEnv *exec_env) +{ + AOTFrame *cur_frame = (AOTFrame *)exec_env->cur_frame; + AOTFrame *prev_frame = cur_frame->prev_frame; + +#if WASM_ENABLE_PERF_PROFILING != 0 + uint64 time_elapsed = + (uintptr_t)os_time_thread_cputime_us() - cur_frame->time_started; + + cur_frame->func_perf_prof_info->total_exec_time += time_elapsed; + cur_frame->func_perf_prof_info->total_exec_cnt++; + + /* parent function */ + if (prev_frame) + prev_frame->func_perf_prof_info->children_exec_time += time_elapsed; +#endif + + exec_env->cur_frame = (struct WASMInterpFrame *)prev_frame; +} + +void +aot_free_frame(WASMExecEnv *exec_env) +{ + aot_free_frame_internal(exec_env); +} + +#else /* else of WASM_ENABLE_GC == 0 */ bool aot_alloc_frame(WASMExecEnv *exec_env, uint32 func_index) { - AOTFrame *frame = - wasm_exec_env_alloc_wasm_frame(exec_env, sizeof(AOTFrame)); -#if WASM_ENABLE_PERF_PROFILING != 0 AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst; + AOTModule *module = (AOTModule *)module_inst->module; +#if WASM_ENABLE_PERF_PROFILING != 0 AOTFuncPerfProfInfo *func_perf_prof = module_inst->func_perf_profilings + func_index; #endif + AOTFrame *frame; + uint32 max_local_cell_num, max_stack_cell_num, all_cell_num; + uint32 aot_func_idx, frame_size; + + if (func_index >= module->import_func_count) { + aot_func_idx = func_index - module->import_func_count; + max_local_cell_num = module->max_local_cell_nums[aot_func_idx]; + max_stack_cell_num = module->max_stack_cell_nums[aot_func_idx]; + } + else { + AOTFuncType *func_type = module->import_funcs[func_index].func_type; + max_local_cell_num = + func_type->param_cell_num > 2 ? func_type->param_cell_num : 2; + max_stack_cell_num = 0; + } + + all_cell_num = max_local_cell_num + max_stack_cell_num; +#if WASM_ENABLE_GC == 0 + frame_size = (uint32)offsetof(AOTFrame, lp) + all_cell_num * 4; +#else + frame_size = + (uint32)offsetof(AOTFrame, lp) + align_uint(all_cell_num * 5, 4); +#endif + frame = wasm_exec_env_alloc_wasm_frame(exec_env, frame_size); if (!frame) { - aot_set_exception((AOTModuleInstance *)exec_env->module_inst, - "auxiliary call stack overflow"); + aot_set_exception(module_inst, "wasm operand stack overflow"); return false; } #if WASM_ENABLE_PERF_PROFILING != 0 - frame->time_started = os_time_thread_cputime_us(); + frame->time_started = (uintptr_t)os_time_thread_cputime_us(); frame->func_perf_prof_info = func_perf_prof; #endif +#if WASM_ENABLE_GC != 0 + frame->sp = frame->lp + max_local_cell_num; + frame->frame_ref = (uint8 *)(frame->sp + max_stack_cell_num); +#endif + frame->prev_frame = (AOTFrame *)exec_env->cur_frame; exec_env->cur_frame = (struct WASMInterpFrame *)frame; @@ -2838,27 +3559,79 @@ aot_alloc_frame(WASMExecEnv *exec_env, uint32 func_index) return true; } -void -aot_free_frame(WASMExecEnv *exec_env) +static inline void +aot_free_frame_internal(WASMExecEnv *exec_env) { AOTFrame *cur_frame = (AOTFrame *)exec_env->cur_frame; AOTFrame *prev_frame = cur_frame->prev_frame; #if WASM_ENABLE_PERF_PROFILING != 0 - uint64 elapsed = os_time_thread_cputime_us() - cur_frame->time_started; - cur_frame->func_perf_prof_info->total_exec_time += elapsed; + uint64 time_elapsed = + (uintptr_t)os_time_thread_cputime_us() - cur_frame->time_started; + + cur_frame->func_perf_prof_info->total_exec_time += time_elapsed; cur_frame->func_perf_prof_info->total_exec_cnt++; /* parent function */ if (prev_frame) - prev_frame->func_perf_prof_info->children_exec_time += elapsed; + prev_frame->func_perf_prof_info->children_exec_time += time_elapsed; #endif wasm_exec_env_free_wasm_frame(exec_env, cur_frame); exec_env->cur_frame = (struct WASMInterpFrame *)prev_frame; } -#endif /* end of (WASM_ENABLE_DUMP_CALL_STACK != 0) \ - || (WASM_ENABLE_PERF_PROFILING != 0) */ + +void +aot_free_frame(WASMExecEnv *exec_env) +{ + aot_free_frame_internal(exec_env); +} + +#endif /* end of WASM_ENABLE_GC == 0 */ + +void +aot_frame_update_profile_info(WASMExecEnv *exec_env, bool alloc_frame) +{ +#if WASM_ENABLE_PERF_PROFILING != 0 + AOTFrame *cur_frame = (AOTFrame *)exec_env->cur_frame; + AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst; + AOTFuncPerfProfInfo *func_perf_prof = + module_inst->func_perf_profilings + cur_frame->func_index; + + if (alloc_frame) { + cur_frame->time_started = (uintptr_t)os_time_thread_cputime_us(); + cur_frame->func_perf_prof_info = func_perf_prof; + } + else { + AOTFrame *prev_frame = cur_frame->prev_frame; + uint64 time_elapsed = + (uintptr_t)os_time_thread_cputime_us() - cur_frame->time_started; + + cur_frame->func_perf_prof_info->total_exec_time += time_elapsed; + cur_frame->func_perf_prof_info->total_exec_cnt++; + + /* parent function */ + if (prev_frame) + prev_frame->func_perf_prof_info->children_exec_time += time_elapsed; + } +#endif + +#if WASM_ENABLE_MEMORY_PROFILING != 0 + if (alloc_frame) { +#if WASM_ENABLE_GC == 0 + uint32 wasm_stack_used = (uint8 *)exec_env->cur_frame + + (uint32)offsetof(AOTFrame, lp) + - exec_env->wasm_stack.bottom; +#else + uint32 wasm_stack_used = + exec_env->wasm_stack.top - exec_env->wasm_stack.bottom; +#endif + if (wasm_stack_used > exec_env->max_wasm_stack_used) + exec_env->max_wasm_stack_used = wasm_stack_used; + } +#endif +} +#endif /* end of WASM_ENABLE_AOT_STACK_FRAME != 0 */ #if WASM_ENABLE_DUMP_CALL_STACK != 0 bool @@ -2867,6 +3640,7 @@ aot_create_call_stack(struct WASMExecEnv *exec_env) AOTFrame *cur_frame = (AOTFrame *)exec_env->cur_frame, *first_frame = cur_frame; AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst; + AOTModule *module = (AOTModule *)module_inst->module; uint32 n = 0; while (cur_frame) { @@ -2875,24 +3649,70 @@ aot_create_call_stack(struct WASMExecEnv *exec_env) } /* release previous stack frames and create new ones */ - if (!bh_vector_destroy(module_inst->frames) - || !bh_vector_init(module_inst->frames, n, sizeof(WASMCApiFrame), - false)) { + destroy_c_api_frames(module_inst->frames); + if (!bh_vector_init(module_inst->frames, n, sizeof(WASMCApiFrame), false)) { return false; } cur_frame = first_frame; while (cur_frame) { WASMCApiFrame frame = { 0 }; + uint32 max_local_cell_num, max_stack_cell_num; + uint32 all_cell_num, lp_size; + frame.instance = module_inst; frame.module_offset = 0; frame.func_index = cur_frame->func_index; - frame.func_offset = 0; + frame.func_offset = cur_frame->ip_offset; frame.func_name_wp = get_func_name_from_index(module_inst, cur_frame->func_index); + if (cur_frame->func_index >= module->import_func_count) { + uint32 aot_func_idx = + cur_frame->func_index - module->import_func_count; + max_local_cell_num = module->max_local_cell_nums[aot_func_idx]; + max_stack_cell_num = module->max_stack_cell_nums[aot_func_idx]; + } + else { + AOTFuncType *func_type = + module->import_funcs[cur_frame->func_index].func_type; + max_local_cell_num = + func_type->param_cell_num > 2 ? func_type->param_cell_num : 2; + max_stack_cell_num = 0; + } + + all_cell_num = max_local_cell_num + max_stack_cell_num; +#if WASM_ENABLE_GC == 0 + lp_size = all_cell_num * 4; +#else + lp_size = align_uint(all_cell_num * 5, 4); +#endif + if (lp_size > 0) { + if (!(frame.lp = wasm_runtime_malloc(lp_size))) { + destroy_c_api_frames(module_inst->frames); + return false; + } + bh_memcpy_s(frame.lp, lp_size, cur_frame->lp, lp_size); + +#if WASM_ENABLE_GC != 0 + uint32 local_ref_flags_cell_num = + module->func_local_ref_flags[frame.func_index] + .local_ref_flag_cell_num; + uint8 *local_ref_flags = + module->func_local_ref_flags[frame.func_index].local_ref_flags; + frame.sp = frame.lp + (cur_frame->sp - cur_frame->lp); + frame.frame_ref = (uint8 *)frame.lp + + (cur_frame->frame_ref - (uint8 *)cur_frame->lp); + /* copy local ref flags from AOT module */ + bh_memcpy_s(frame.frame_ref, local_ref_flags_cell_num, + local_ref_flags, lp_size); +#endif + } + if (!bh_vector_append(module_inst->frames, &frame)) { - bh_vector_destroy(module_inst->frames); + if (frame.lp) + wasm_runtime_free(frame.lp); + destroy_c_api_frames(module_inst->frames); return false; } @@ -2945,14 +3765,14 @@ aot_dump_call_stack(WASMExecEnv *exec_env, bool print, char *buf, uint32 len) /* function name not exported, print number instead */ if (frame.func_name_wp == NULL) { - line_length = - snprintf(line_buf, sizeof(line_buf), - "#%02" PRIu32 " $f%" PRIu32 "\n", n, frame.func_index); + line_length = snprintf(line_buf, sizeof(line_buf), + "#%02" PRIu32 ": 0x%04x - $f%" PRIu32 "\n", + n, frame.func_offset, frame.func_index); } else { - line_length = - snprintf(line_buf, sizeof(line_buf), "#%02" PRIu32 " %s\n", n, - frame.func_name_wp); + line_length = snprintf(line_buf, sizeof(line_buf), + "#%02" PRIu32 ": 0x%04x - %s\n", n, + frame.func_offset, frame.func_name_wp); } if (line_length >= sizeof(line_buf)) { @@ -2974,7 +3794,7 @@ aot_dump_call_stack(WASMExecEnv *exec_env, bool print, char *buf, uint32 len) return total_len + 1; } -#endif /* end of WASM_ENABLE_DUMP_CALL_STACK */ +#endif /* end of WASM_ENABLE_DUMP_CALL_STACK != 0 */ #if WASM_ENABLE_PERF_PROFILING != 0 void @@ -3047,7 +3867,7 @@ aot_get_wasm_func_exec_time(const AOTModuleInstance *inst, return -1.0; } -#endif /* end of WASM_ENABLE_PERF_PROFILING */ +#endif /* end of WASM_ENABLE_PERF_PROFILING != 0 */ #if WASM_ENABLE_STATIC_PGO != 0 @@ -3565,3 +4385,247 @@ aot_dump_pgo_prof_data_to_buf(AOTModuleInstance *module_inst, char *buf, return total_size; } #endif /* end of WASM_ENABLE_STATIC_PGO != 0 */ + +#if WASM_ENABLE_GC != 0 +void * +aot_create_func_obj(AOTModuleInstance *module_inst, uint32 func_idx, + bool throw_exce, char *error_buf, uint32 error_buf_size) +{ + AOTModule *module = (AOTModule *)module_inst->module; + WASMRttTypeRef rtt_type; + WASMFuncObjectRef func_obj; + AOTFuncType *func_type; + uint32 type_idx; + + if (throw_exce) { + error_buf = module_inst->cur_exception; + error_buf_size = sizeof(module_inst->cur_exception); + } + + if (func_idx >= module->import_func_count + module->func_count) { + set_error_buf_v(error_buf, error_buf_size, "unknown function %d", + func_idx); + return NULL; + } + + type_idx = module_inst->func_type_indexes[func_idx]; + func_type = (AOTFuncType *)module->types[type_idx]; + + if (!(rtt_type = wasm_rtt_type_new((AOTType *)func_type, type_idx, + module->rtt_types, module->type_count, + &module->rtt_type_lock))) { + set_error_buf(error_buf, error_buf_size, "create rtt object failed"); + return NULL; + } + + if (!(func_obj = wasm_func_obj_new_internal( + ((AOTModuleInstanceExtra *)module_inst->e)->common.gc_heap_handle, + rtt_type, func_idx))) { + set_error_buf(error_buf, error_buf_size, "create func object failed"); + return NULL; + } + + return func_obj; +} + +bool +aot_obj_is_instance_of(AOTModuleInstance *module_inst, WASMObjectRef gc_obj, + uint32 type_index) +{ + AOTModule *aot_module = (AOTModule *)module_inst->module; + AOTType **types = aot_module->types; + uint32 type_count = aot_module->type_count; + + return wasm_obj_is_instance_of(gc_obj, type_index, types, type_count); +} + +WASMRttTypeRef +aot_rtt_type_new(AOTModuleInstance *module_inst, uint32 type_index) +{ + AOTModule *aot_module = (AOTModule *)module_inst->module; + AOTType *defined_type = aot_module->types[type_index]; + WASMRttType **rtt_types = aot_module->rtt_types; + uint32 rtt_type_count = aot_module->type_count; + korp_mutex *rtt_type_lock = &aot_module->rtt_type_lock; + + return wasm_rtt_type_new(defined_type, type_index, rtt_types, + rtt_type_count, rtt_type_lock); +} + +bool +aot_array_init_with_data(AOTModuleInstance *module_inst, uint32 seg_index, + uint32 data_seg_offset, WASMArrayObjectRef array_obj, + uint32 elem_size, uint32 array_len) +{ + AOTModule *aot_module; + uint8 *data = NULL; + uint8 *array_elem_base; + uint64 seg_len = 0; + uint64 total_size = (int64)elem_size * array_len; + + aot_module = (AOTModule *)module_inst->module; + seg_len = aot_module->mem_init_data_list[seg_index]->byte_count; + data = aot_module->mem_init_data_list[seg_index]->bytes; + + if (data_seg_offset >= seg_len || total_size > seg_len - data_seg_offset) { + aot_set_exception(module_inst, "out of bounds memory access"); + return false; + } + + array_elem_base = (uint8 *)wasm_array_obj_first_elem_addr(array_obj); + bh_memcpy_s(array_elem_base, (uint32)total_size, data + data_seg_offset, + (uint32)total_size); + + return true; +} + +static bool +aot_global_traverse_gc_rootset(AOTModuleInstance *module_inst, void *heap) +{ + AOTModule *module = (AOTModule *)module_inst->module; + uint8 *global_data = module_inst->global_data; + AOTImportGlobal *import_global = module->import_globals; + AOTGlobal *global = module->globals; + WASMObjectRef gc_obj; + uint32 i; + + for (i = 0; i < module->import_global_count; i++, import_global++) { + if (wasm_is_type_reftype(import_global->type)) { + gc_obj = GET_REF_FROM_ADDR((uint32 *)global_data); + if (wasm_obj_is_created_from_heap(gc_obj)) { + if (0 != mem_allocator_add_root((mem_allocator_t)heap, gc_obj)) + return false; + } + } + global_data += import_global->size; + } + + for (i = 0; i < module->global_count; i++, global++) { + if (wasm_is_type_reftype(global->type)) { + gc_obj = GET_REF_FROM_ADDR((uint32 *)global_data); + if (wasm_obj_is_created_from_heap(gc_obj)) { + if (0 != mem_allocator_add_root((mem_allocator_t)heap, gc_obj)) + return false; + } + } + global_data += global->size; + } + + return true; +} + +static bool +aot_table_traverse_gc_rootset(WASMModuleInstance *module_inst, void *heap) +{ + AOTTableInstance **tables = (AOTTableInstance **)module_inst->tables; + AOTTableInstance *table; + uint32 table_count = module_inst->table_count, i, j; + WASMObjectRef gc_obj, *table_elems; + + for (i = 0; i < table_count; i++) { + table = tables[i]; + table_elems = (WASMObjectRef *)table->elems; + for (j = 0; j < table->cur_size; j++) { + gc_obj = table_elems[j]; + if (wasm_obj_is_created_from_heap(gc_obj)) { + if (0 != mem_allocator_add_root((mem_allocator_t)heap, gc_obj)) + return false; + } + } + } + + return true; +} + +static bool +local_object_refs_traverse_gc_rootset(WASMExecEnv *exec_env, void *heap) +{ + WASMLocalObjectRef *r; + WASMObjectRef gc_obj; + + for (r = exec_env->cur_local_object_ref; r; r = r->prev) { + gc_obj = r->val; + if (wasm_obj_is_created_from_heap(gc_obj)) { + if (0 != mem_allocator_add_root((mem_allocator_t)heap, gc_obj)) + return false; + } + } + return true; +} + +static bool +aot_frame_traverse_gc_rootset(WASMExecEnv *exec_env, void *heap) +{ + AOTFrame *frame; + AOTModule *module; + LocalRefFlag frame_local_flags; + WASMObjectRef gc_obj; + uint32 i, local_ref_flag_cell_num; + + module = (AOTModule *)wasm_exec_env_get_module(exec_env); + frame = (AOTFrame *)wasm_exec_env_get_cur_frame(exec_env); + for (; frame; frame = frame->prev_frame) { + /* local ref flags */ + frame_local_flags = module->func_local_ref_flags[frame->func_index]; + local_ref_flag_cell_num = frame_local_flags.local_ref_flag_cell_num; + for (i = 0; i < local_ref_flag_cell_num; i++) { + if (frame_local_flags.local_ref_flags[i]) { + gc_obj = GET_REF_FROM_ADDR(frame->lp + i); + if (wasm_obj_is_created_from_heap(gc_obj)) { + if (mem_allocator_add_root((mem_allocator_t)heap, gc_obj)) { + return false; + } + } +#if UINTPTR_MAX == UINT64_MAX + bh_assert(frame_local_flags.local_ref_flags[i + 1]); + i++; +#endif + } + } + + /* stack ref flags */ + uint8 *frame_ref = frame->frame_ref; + for (i = local_ref_flag_cell_num; i < (uint32)(frame->sp - frame->lp); + i++) { + if (frame_ref[i]) { + gc_obj = GET_REF_FROM_ADDR(frame->lp + i); + if (wasm_obj_is_created_from_heap(gc_obj)) { + if (mem_allocator_add_root((mem_allocator_t)heap, gc_obj)) { + return false; + } + } +#if UINTPTR_MAX == UINT64_MAX + bh_assert(frame_ref[i + 1]); + i++; +#endif + } + } + } + return true; +} + +bool +aot_traverse_gc_rootset(WASMExecEnv *exec_env, void *heap) +{ + AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst; + bool ret; + + ret = aot_global_traverse_gc_rootset(module_inst, heap); + if (!ret) + return ret; + + ret = aot_table_traverse_gc_rootset(module_inst, heap); + if (!ret) + return ret; + + ret = local_object_refs_traverse_gc_rootset(exec_env, heap); + if (!ret) + return ret; + + ret = aot_frame_traverse_gc_rootset(exec_env, heap); + if (!ret) + return ret; + + return true; +} +#endif /* end of WASM_ENABLE_GC != 0 */ diff --git a/core/iwasm/aot/aot_runtime.h b/core/iwasm/aot/aot_runtime.h index 47d8a2021..71baeb171 100644 --- a/core/iwasm/aot/aot_runtime.h +++ b/core/iwasm/aot/aot_runtime.h @@ -10,6 +10,9 @@ #include "../common/wasm_runtime_common.h" #include "../interpreter/wasm_runtime.h" #include "../compilation/aot.h" +#if WASM_ENABLE_GC != 0 +#include "gc_export.h" +#endif #if WASM_ENABLE_WASI_NN != 0 #include "../libraries/wasi-nn/src/wasi_nn_private.h" @@ -19,6 +22,20 @@ extern "C" { #endif +/* Wasm feature supported, mainly used by AOTTargetInfo now */ +#define WASM_FEATURE_SIMD_128BIT (1 << 0) +#define WASM_FEATURE_BULK_MEMORY (1 << 1) +#define WASM_FEATURE_MULTI_THREAD (1 << 2) +#define WASM_FEATURE_REF_TYPES (1 << 3) +#define WASM_FEATURE_GARBAGE_COLLECTION (1 << 4) +#define WASM_FEATURE_EXCEPTION_HANDLING (1 << 5) +#define WASM_FEATURE_MEMORY64 (1 << 6) +#define WASM_FEATURE_MULTI_MEMORY (1 << 7) +#define WASM_FEATURE_DYNAMIC_LINKING (1 << 8) +#define WASM_FEATURE_COMPONENT_MODEL (1 << 9) +#define WASM_FEATURE_RELAXED_SIMD (1 << 10) +#define WASM_FEATURE_FLEXIBLE_VECTORS (1 << 11) + typedef enum AOTSectionType { AOT_SECTION_TYPE_TARGET_INFO = 0, AOT_SECTION_TYPE_INIT_DATA = 1, @@ -35,6 +52,7 @@ typedef enum AOTCustomSectionType { AOT_CUSTOM_SECTION_NATIVE_SYMBOL = 1, AOT_CUSTOM_SECTION_ACCESS_CONTROL = 2, AOT_CUSTOM_SECTION_NAME = 3, + AOT_CUSTOM_SECTION_STRING_LITERAL = 4, } AOTCustomSectionType; typedef struct AOTObjectDataSection { @@ -103,6 +121,13 @@ typedef struct GOTItem { } GOTItem, *GOTItemList; #endif +#if WASM_ENABLE_GC != 0 +typedef struct LocalRefFlag { + uint32 local_ref_flag_cell_num; + uint8 *local_ref_flags; +} LocalRefFlag; +#endif + typedef struct AOTModule { uint32 module_type; @@ -133,9 +158,9 @@ typedef struct AOTModule { uint32 table_init_data_count; AOTTableInitData **table_init_data_list; - /* function type info */ - uint32 func_type_count; - AOTFuncType **func_types; + /* type info */ + uint32 type_count; + AOTType **types; /* import global variable info */ uint32 import_global_count; @@ -158,6 +183,17 @@ typedef struct AOTModule { void **func_ptrs; /* func type indexes of AOTed (un-imported) functions */ uint32 *func_type_indexes; +#if WASM_ENABLE_AOT_STACK_FRAME != 0 + /* max local cell nums of AOTed (un-imported) functions */ + uint32 *max_local_cell_nums; + /* max stack cell nums of AOTed (un-imported) functions */ + uint32 *max_stack_cell_nums; +#endif + +#if WASM_ENABLE_GC != 0 + /* params + locals ref flags of (both import and AOTed) functions */ + LocalRefFlag *func_local_ref_flags; +#endif /* export info */ uint32 export_count; @@ -239,6 +275,26 @@ typedef struct AOTModule { bh_list import_module_list_head; bh_list *import_module_list; #endif + +#if WASM_ENABLE_GC != 0 + /* Ref types hash set */ + HashMap *ref_type_set; + struct WASMRttType **rtt_types; + korp_mutex rtt_type_lock; +#if WASM_ENABLE_STRINGREF != 0 + /* special rtts for stringref types + - stringref + - stringview_wtf8 + - stringview_wtf16 + - stringview_iter + */ + struct WASMRttType *stringref_rtts[4]; + uint32 string_literal_count; + uint32 *string_literal_lengths; + const uint8 **string_literal_ptrs; +#endif +#endif + #if WASM_ENABLE_DEBUG_AOT != 0 void *elf_hdr; uint32 elf_size; @@ -275,8 +331,10 @@ typedef struct AOTTargetInfo { uint32 e_version; /* Processor-specific flags */ uint32 e_flags; + /* Specify wasm features supported */ + uint64 feature_flags; /* Reserved */ - uint32 reserved; + uint64 reserved; /* Arch name */ char arch[16]; } AOTTargetInfo; @@ -292,12 +350,37 @@ typedef struct AOTFuncPerfProfInfo { /* AOT auxiliary call stack */ typedef struct AOTFrame { + /* The frame of the caller which is calling current function */ struct AOTFrame *prev_frame; - uint32 func_index; -#if WASM_ENABLE_PERF_PROFILING != 0 - uint64 time_started; + + /* The non-imported function index of current function */ + uintptr_t func_index; + + /* Used when performance profiling is enabled */ + uintptr_t time_started; + + /* Used when performance profiling is enabled */ AOTFuncPerfProfInfo *func_perf_prof_info; -#endif + + /* Instruction pointer: offset to the bytecode array */ + uintptr_t ip_offset; + + /* Operand stack top pointer of the current frame */ + uint32 *sp; + + /* Frame ref flags (GC only) */ + uint8 *frame_ref; + + /** + * Frame data, the layout is: + * local area: parameters and local variables + * stack area: wasm operand stack + * frame ref flags (GC only): + * whether each cell in local and stack area is a GC obj + * currently local's ref flags are stored in AOTModule, + * here we only reserve the padding bytes + */ + uint32 lp[1]; } AOTFrame; #if WASM_ENABLE_STATIC_PGO != 0 @@ -564,7 +647,7 @@ void aot_get_module_inst_mem_consumption(const AOTModuleInstance *module_inst, WASMModuleInstMemConsumption *mem_conspn); -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 void aot_drop_table_seg(AOTModuleInstance *module_inst, uint32 tbl_seg_idx); @@ -580,11 +663,11 @@ aot_table_copy(AOTModuleInstance *module_inst, uint32 src_tbl_idx, void aot_table_fill(AOTModuleInstance *module_inst, uint32 tbl_idx, uint32 length, - uint32 val, uint32 data_offset); + table_elem_type_t val, uint32 data_offset); uint32 aot_table_grow(AOTModuleInstance *module_inst, uint32 tbl_idx, - uint32 inc_entries, uint32 init_val); + uint32 inc_entries, table_elem_type_t init_val); #endif bool @@ -593,6 +676,9 @@ aot_alloc_frame(WASMExecEnv *exec_env, uint32 func_index); void aot_free_frame(WASMExecEnv *exec_env); +void +aot_frame_update_profile_info(WASMExecEnv *exec_env, bool alloc_frame); + bool aot_create_call_stack(struct WASMExecEnv *exec_env); @@ -655,6 +741,27 @@ void aot_exchange_uint64(uint8 *p_data); #endif /* end of WASM_ENABLE_STATIC_PGO != 0 */ +#if WASM_ENABLE_GC != 0 +void * +aot_create_func_obj(AOTModuleInstance *module_inst, uint32 func_idx, + bool throw_exce, char *error_buf, uint32 error_buf_size); + +bool +aot_obj_is_instance_of(AOTModuleInstance *module_inst, WASMObjectRef gc_obj, + uint32 type_index); + +WASMRttTypeRef +aot_rtt_type_new(AOTModuleInstance *module_inst, uint32 type_index); + +bool +aot_array_init_with_data(AOTModuleInstance *module_inst, uint32 seg_index, + uint32 data_seg_offset, WASMArrayObjectRef array_obj, + uint32 elem_size, uint32 array_len); + +bool +aot_traverse_gc_rootset(WASMExecEnv *exec_env, void *heap); +#endif /* end of WASM_ENABLE_GC != 0 */ + #ifdef __cplusplus } /* end of extern "C" */ #endif diff --git a/core/iwasm/common/gc/gc_common.c b/core/iwasm/common/gc/gc_common.c new file mode 100644 index 000000000..80936f34a --- /dev/null +++ b/core/iwasm/common/gc/gc_common.c @@ -0,0 +1,1001 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include "../wasm_runtime_common.h" +#include "gc_export.h" +#if WASM_ENABLE_INTERP != 0 +#include "../interpreter/wasm_runtime.h" +#endif +#if WASM_ENABLE_AOT != 0 +#include "../aot/aot_runtime.h" +#endif + +static bool +wasm_ref_type_normalize(wasm_ref_type_t *ref_type) +{ + wasm_value_type_t value_type = ref_type->value_type; + int32 heap_type = ref_type->heap_type; + + if (!((value_type >= VALUE_TYPE_I16 && value_type <= VALUE_TYPE_I32) + || ((value_type >= (uint8)REF_TYPE_ARRAYREF + && value_type <= (uint8)REF_TYPE_NULLFUNCREF) + || (value_type >= (uint8)REF_TYPE_HT_NULLABLE + && value_type <= (uint8)REF_TYPE_HT_NON_NULLABLE) +#if WASM_ENABLE_STRINGREF != 0 + || (value_type >= (uint8)REF_TYPE_STRINGVIEWWTF8 + && value_type <= (uint8)REF_TYPE_STRINGREF) + || (value_type >= (uint8)REF_TYPE_STRINGVIEWITER + && value_type <= (uint8)REF_TYPE_STRINGVIEWWTF16) +#endif + ))) { + return false; + } + if (value_type == VALUE_TYPE_HT_NULLABLE_REF + || value_type == VALUE_TYPE_HT_NON_NULLABLE_REF) { + if (heap_type < 0 && !wasm_is_valid_heap_type(heap_type)) { + return false; + } + } + + if (value_type != REF_TYPE_HT_NULLABLE) { + ref_type->nullable = false; + } + else { + if (wasm_is_valid_heap_type(heap_type)) { + ref_type->value_type = +#if WASM_ENABLE_STRINGREF != 0 + (uint8)(REF_TYPE_STRINGVIEWITER + heap_type + - HEAP_TYPE_STRINGVIEWITER); +#else + (uint8)(REF_TYPE_ARRAYREF + heap_type - HEAP_TYPE_ARRAY); +#endif + ref_type->nullable = false; + ref_type->heap_type = 0; + } + else { + ref_type->nullable = true; + } + } + + return true; +} + +uint32 +wasm_get_defined_type_count(WASMModuleCommon *const module) +{ + uint32 type_count = 0; + +#if WASM_ENABLE_INTERP != 0 + if (module->module_type == Wasm_Module_Bytecode) { + WASMModule *wasm_module = (WASMModule *)module; + type_count = wasm_module->type_count; + } +#endif +#if WASM_ENABLE_AOT != 0 + if (module->module_type == Wasm_Module_AoT) { + AOTModule *aot_module = (AOTModule *)module; + type_count = aot_module->type_count; + } +#endif + + return type_count; +} + +WASMType * +wasm_get_defined_type(WASMModuleCommon *const module, uint32 index) +{ + WASMType *type = NULL; + +#if WASM_ENABLE_INTERP != 0 + if (module->module_type == Wasm_Module_Bytecode) { + WASMModule *wasm_module = (WASMModule *)module; + + bh_assert(index < wasm_module->type_count); + type = wasm_module->types[index]; + } +#endif +#if WASM_ENABLE_AOT != 0 + if (module->module_type == Wasm_Module_AoT) { + AOTModule *aot_module = (AOTModule *)module; + + bh_assert(index < aot_module->type_count); + type = aot_module->types[index]; + } +#endif + + return type; +} + +WASMType * +wasm_obj_get_defined_type(const WASMObjectRef obj) +{ + if ((!wasm_obj_is_struct_obj(obj)) && (!wasm_obj_is_array_obj(obj)) + && (!wasm_obj_is_func_obj(obj))) { + bh_assert(false); + } + + return ((WASMRttTypeRef)(obj->header))->defined_type; +} + +int32 +wasm_obj_get_defined_type_idx(WASMModuleCommon *const module, + const WASMObjectRef obj) +{ + WASMType *type = wasm_obj_get_defined_type(obj); + uint32 i, type_idx = (uint32)-1; + +#if WASM_ENABLE_INTERP != 0 + if (module->module_type == Wasm_Module_Bytecode) { + WASMModule *wasm_module = (WASMModule *)module; + uint32 type_count = wasm_module->type_count; + + for (i = 0; i < type_count; i++) { + if (wasm_module->types[i] == type) { + type_idx = i; + break; + } + } + bh_assert(type_idx < type_count); + } +#endif +#if WASM_ENABLE_AOT != 0 + if (module->module_type == Wasm_Module_AoT) { + AOTModule *aot_module = (AOTModule *)module; + uint32 type_count = aot_module->type_count; + + for (i = 0; i < type_count; i++) { + if (aot_module->types[i] == type) { + type_idx = i; + break; + } + } + bh_assert(type_idx < type_count); + } +#endif + + return type_idx; +} + +bool +wasm_defined_type_is_func_type(WASMType *const def_type) +{ + return wasm_type_is_func_type(def_type); +} + +bool +wasm_defined_type_is_struct_type(WASMType *const def_type) +{ + return wasm_type_is_struct_type(def_type); +} + +bool +wasm_defined_type_is_array_type(WASMType *const def_type) +{ + return wasm_type_is_array_type(def_type); +} + +uint32 +wasm_func_type_get_param_count(WASMFuncType *const func_type) +{ + return func_type->param_count; +} + +wasm_ref_type_t +wasm_func_type_get_param_type(WASMFuncType *const func_type, uint32 param_idx) +{ + wasm_ref_type_t ref_type = { 0 }; + + bh_assert(param_idx < func_type->param_count); + + ref_type.value_type = func_type->types[param_idx]; + + if (wasm_is_type_multi_byte_type(func_type->types[param_idx])) { + WASMRefType *param_ref_type = wasm_reftype_map_find( + func_type->ref_type_maps, func_type->ref_type_map_count, param_idx); + bh_assert(param_ref_type); + ref_type.nullable = param_ref_type->ref_ht_common.nullable; + ref_type.heap_type = param_ref_type->ref_ht_common.heap_type; + } + + return ref_type; +} + +uint32 +wasm_func_type_get_result_count(WASMFuncType *const func_type) +{ + return (uint32)func_type->result_count; +} + +wasm_ref_type_t +wasm_func_type_get_result_type(WASMFuncType *const func_type, uint32 result_idx) +{ + wasm_ref_type_t ref_type = { 0 }; + uint32 result_idx_with_param; + + result_idx_with_param = func_type->param_count + result_idx; + bh_assert(result_idx < func_type->result_count); + + ref_type.value_type = func_type->types[result_idx_with_param]; + + if (wasm_is_type_multi_byte_type(func_type->types[result_idx_with_param])) { + WASMRefType *result_ref_type = wasm_reftype_map_find( + func_type->ref_type_maps, func_type->ref_type_map_count, + result_idx_with_param); + bh_assert(result_ref_type); + ref_type.nullable = result_ref_type->ref_ht_common.nullable; + ref_type.heap_type = result_ref_type->ref_ht_common.heap_type; + } + + return ref_type; +} + +uint32 +wasm_struct_type_get_field_count(WASMStructType *const struct_type) +{ + bh_assert(struct_type->base_type.type_flag == WASM_TYPE_STRUCT); + return struct_type->field_count; +} + +wasm_ref_type_t +wasm_struct_type_get_field_type(WASMStructType *const struct_type, + uint32 field_idx, bool *p_is_mutable) +{ + wasm_ref_type_t ref_type = { 0 }; + WASMStructFieldType field; + + bh_assert(struct_type->base_type.type_flag == WASM_TYPE_STRUCT); + bh_assert(field_idx < struct_type->field_count); + + field = struct_type->fields[field_idx]; + ref_type.value_type = field.field_type; + + if (wasm_is_type_multi_byte_type(field.field_type)) { + WASMRefType *field_ref_type = + wasm_reftype_map_find(struct_type->ref_type_maps, + struct_type->ref_type_map_count, field_idx); + bh_assert(field_ref_type); + ref_type.nullable = field_ref_type->ref_ht_common.nullable; + ref_type.heap_type = field_ref_type->ref_ht_common.heap_type; + } + + if (p_is_mutable) { + *p_is_mutable = field.field_flags & 1; + } + + return ref_type; +} + +wasm_ref_type_t +wasm_array_type_get_elem_type(WASMArrayType *const array_type, + bool *p_is_mutable) +{ + wasm_ref_type_t ref_type = { 0 }; + + ref_type.value_type = array_type->elem_type; + + if (wasm_is_type_multi_byte_type(array_type->elem_type)) { + WASMRefType *elem_ref_type = array_type->elem_ref_type; + ref_type.nullable = elem_ref_type->ref_ht_common.nullable; + ref_type.heap_type = elem_ref_type->ref_ht_common.heap_type; + } + + if (p_is_mutable) { + *p_is_mutable = array_type->elem_flags & 1; + } + + return ref_type; +} + +bool +wasm_defined_type_equal(WASMType *const def_type1, WASMType *const def_type2, + WASMModuleCommon *const module) +{ + WASMTypePtr *types = NULL; + uint32 type_count = 0; + +#if WASM_ENABLE_INTERP != 0 + if (module->module_type == Wasm_Module_Bytecode) { + WASMModule *wasm_module = (WASMModule *)module; + + types = wasm_module->types; + type_count = wasm_module->type_count; + } +#endif +#if WASM_ENABLE_AOT != 0 + /* TODO */ +#endif + + bh_assert(types); + + return wasm_type_equal(def_type1, def_type2, types, type_count); +} + +bool +wasm_defined_type_is_subtype_of(WASMType *const def_type1, + WASMType *const def_type2, + WASMModuleCommon *const module) +{ + WASMTypePtr *types = NULL; + uint32 type_count = 0; + +#if WASM_ENABLE_INTERP != 0 + if (module->module_type == Wasm_Module_Bytecode) { + WASMModule *wasm_module = (WASMModule *)module; + + types = wasm_module->types; + type_count = wasm_module->type_count; + } +#endif +#if WASM_ENABLE_AOT != 0 + if (module->module_type == Wasm_Module_AoT) { + AOTModule *aot_module = (AOTModule *)module; + + types = aot_module->types; + type_count = aot_module->type_count; + } +#endif + + bh_assert(types); + + return wasm_type_is_subtype_of(def_type1, def_type2, types, type_count); +} + +void +wasm_ref_type_set_type_idx(wasm_ref_type_t *ref_type, bool nullable, + int32 type_idx) +{ + bh_assert(type_idx >= 0); + ref_type->value_type = + nullable ? VALUE_TYPE_HT_NULLABLE_REF : VALUE_TYPE_HT_NON_NULLABLE_REF; + ref_type->nullable = nullable; + ref_type->heap_type = type_idx; +} + +void +wasm_ref_type_set_heap_type(wasm_ref_type_t *ref_type, bool nullable, + int32 heap_type) +{ + bool ret; + + bh_assert(heap_type <= HEAP_TYPE_FUNC && heap_type >= HEAP_TYPE_NONE); + ref_type->value_type = + nullable ? VALUE_TYPE_HT_NULLABLE_REF : VALUE_TYPE_HT_NON_NULLABLE_REF; + ref_type->nullable = nullable; + ref_type->heap_type = heap_type; + ret = wasm_ref_type_normalize(ref_type); + bh_assert(ret); + (void)ret; +} + +bool +wasm_ref_type_equal(const wasm_ref_type_t *ref_type1, + const wasm_ref_type_t *ref_type2, + WASMModuleCommon *const module) +{ + wasm_ref_type_t ref_type1_norm = { 0 }; + wasm_ref_type_t ref_type2_norm = { 0 }; + uint32 type_count = 0; + WASMTypePtr *types = NULL; + uint8 type1; + uint8 type2; + + bh_memcpy_s(&ref_type1_norm, (uint32)sizeof(wasm_ref_type_t), ref_type1, + (uint32)sizeof(wasm_ref_type_t)); + bh_memcpy_s(&ref_type2_norm, (uint32)sizeof(wasm_ref_type_t), ref_type2, + (uint32)sizeof(wasm_ref_type_t)); + if (!wasm_ref_type_normalize(&ref_type1_norm)) { + return false; + } + if (!wasm_ref_type_normalize(&ref_type2_norm)) { + return false; + } + type1 = ref_type1_norm.value_type; + type2 = ref_type2_norm.value_type; + +#if WASM_ENABLE_INTERP != 0 + if (module->module_type == Wasm_Module_Bytecode) { + types = ((WASMModule *)module)->types; + type_count = wasm_get_defined_type_count(module); + } +#endif +#if WASM_ENABLE_AOT != 0 + if (module->module_type == Wasm_Module_AoT) { + types = ((AOTModule *)module)->types; + type_count = wasm_get_defined_type_count(module); + } +#endif + + return wasm_reftype_equal(type1, (WASMRefType *)&ref_type1_norm, type2, + (WASMRefType *)&ref_type2_norm, types, + type_count); +} + +bool +wasm_ref_type_is_subtype_of(const wasm_ref_type_t *ref_type1, + const wasm_ref_type_t *ref_type2, + WASMModuleCommon *const module) +{ + wasm_ref_type_t ref_type1_norm = { 0 }; + wasm_ref_type_t ref_type2_norm = { 0 }; + uint8 type1; + uint8 type2; + WASMTypePtr *types = NULL; + uint32 type_count = 0; + + bh_memcpy_s(&ref_type1_norm, (uint32)sizeof(wasm_ref_type_t), ref_type1, + (uint32)sizeof(wasm_ref_type_t)); + bh_memcpy_s(&ref_type2_norm, (uint32)sizeof(wasm_ref_type_t), ref_type2, + (uint32)sizeof(wasm_ref_type_t)); + if (!wasm_ref_type_normalize(&ref_type1_norm)) { + return false; + } + if (!wasm_ref_type_normalize(&ref_type2_norm)) { + return false; + } + type1 = ref_type1_norm.value_type; + type2 = ref_type2_norm.value_type; + +#if WASM_ENABLE_INTERP != 0 + if (module->module_type == Wasm_Module_Bytecode) { + types = ((WASMModule *)module)->types; + type_count = wasm_get_defined_type_count(module); + } +#endif +#if WASM_ENABLE_AOT != 0 + if (module->module_type == Wasm_Module_AoT) { + types = ((AOTModule *)module)->types; + type_count = wasm_get_defined_type_count(module); + } +#endif + + bh_assert(types); + + return wasm_reftype_is_subtype_of(type1, (WASMRefType *)&ref_type1_norm, + type2, (WASMRefType *)&ref_type2_norm, + types, type_count); +} + +WASMStructObjectRef +wasm_struct_obj_new_with_typeidx(WASMExecEnv *exec_env, uint32 type_idx) +{ + WASMStructObjectRef struct_obj; + WASMModuleInstanceCommon *module_inst = + wasm_runtime_get_module_inst(exec_env); + WASMType *type = NULL; + WASMRttTypeRef rtt_type = NULL; + +#if WASM_ENABLE_INTERP != 0 + if (module_inst->module_type == Wasm_Module_Bytecode) { + WASMModule *module = ((WASMModuleInstance *)module_inst)->module; + + bh_assert(type_idx < module->type_count); + type = module->types[type_idx]; + bh_assert(wasm_defined_type_is_struct_type(type)); + rtt_type = + wasm_rtt_type_new(type, type_idx, module->rtt_types, + module->type_count, &module->rtt_type_lock); + } +#endif +#if WASM_ENABLE_AOT != 0 + if (module_inst->module_type == Wasm_Module_AoT) { + AOTModule *module = + (AOTModule *)((AOTModuleInstance *)module_inst)->module; + + bh_assert(type_idx < module->type_count); + type = module->types[type_idx]; + bh_assert(wasm_defined_type_is_struct_type(type)); + rtt_type = + wasm_rtt_type_new(type, type_idx, module->rtt_types, + module->type_count, &module->rtt_type_lock); + } +#endif + + if (!rtt_type) { + return NULL; + } + struct_obj = wasm_struct_obj_new(exec_env, rtt_type); + + return struct_obj; +} + +WASMStructObjectRef +wasm_struct_obj_new_with_type(WASMExecEnv *exec_env, WASMStructType *type) +{ + WASMStructObjectRef struct_obj; + WASMModuleInstanceCommon *module_inst = + wasm_runtime_get_module_inst(exec_env); + WASMRttTypeRef rtt_type = NULL; + uint32 i = 0; + uint32 type_count = 0; + + bh_assert(type->base_type.type_flag == WASM_TYPE_STRUCT); + +#if WASM_ENABLE_INTERP != 0 + if (module_inst->module_type == Wasm_Module_Bytecode) { + WASMModule *module = ((WASMModuleInstance *)module_inst)->module; + + type_count = module->type_count; + + for (i = 0; i < type_count; i++) { + if (module->types[i] == (WASMType *)type) { + break; + } + } + bh_assert(i < type_count); + rtt_type = + wasm_rtt_type_new((WASMType *)type, i, module->rtt_types, + module->type_count, &module->rtt_type_lock); + } +#endif +#if WASM_ENABLE_AOT != 0 + if (module_inst->module_type == Wasm_Module_AoT) { + AOTModule *module = + (AOTModule *)((AOTModuleInstance *)module_inst)->module; + + type_count = module->type_count; + + for (i = 0; i < type_count; i++) { + if (module->types[i] == (AOTType *)type) { + break; + } + } + bh_assert(i < type_count); + rtt_type = + wasm_rtt_type_new((AOTType *)type, i, module->rtt_types, + module->type_count, &module->rtt_type_lock); + } +#endif + + if (!rtt_type) { + return NULL; + } + struct_obj = wasm_struct_obj_new(exec_env, rtt_type); + + return struct_obj; +} + +WASMArrayObjectRef +wasm_array_obj_new_with_typeidx(WASMExecEnv *exec_env, uint32 type_idx, + uint32 length, wasm_value_t *init_value) +{ + WASMArrayObjectRef array_obj; + WASMModuleCommon *module = wasm_exec_env_get_module(exec_env); + WASMType *defined_type = wasm_get_defined_type(module, type_idx); + WASMRttTypeRef rtt_type = NULL; + + bh_assert(wasm_defined_type_is_array_type(defined_type)); + +#if WASM_ENABLE_INTERP != 0 + if (module->module_type == Wasm_Module_Bytecode) { + WASMModule *wasm_module = (WASMModule *)module; + + rtt_type = wasm_rtt_type_new( + defined_type, type_idx, wasm_module->rtt_types, + wasm_module->type_count, &wasm_module->rtt_type_lock); + } +#endif +#if WASM_ENABLE_AOT != 0 + if (module->module_type == Wasm_Module_AoT) { + AOTModule *aot_module = (AOTModule *)module; + + rtt_type = wasm_rtt_type_new( + defined_type, type_idx, aot_module->rtt_types, + aot_module->type_count, &aot_module->rtt_type_lock); + } +#endif + + if (!rtt_type) { + return NULL; + } + array_obj = wasm_array_obj_new(exec_env, rtt_type, length, init_value); + + return array_obj; +} + +WASMArrayObjectRef +wasm_array_obj_new_with_type(WASMExecEnv *exec_env, WASMArrayType *type, + uint32 length, wasm_value_t *init_value) +{ + WASMArrayObjectRef array_obj; + uint32 i, type_count, type_idx = 0; + WASMModuleCommon *module = wasm_exec_env_get_module(exec_env); + + bh_assert(type->base_type.type_flag == WASM_TYPE_ARRAY); + +#if WASM_ENABLE_INTERP != 0 + if (module->module_type == Wasm_Module_Bytecode) { + WASMModule *wasm_module = (WASMModule *)module; + + type_count = wasm_module->type_count; + for (i = 0; i < type_count; i++) { + if (wasm_module->types[i] == (WASMType *)type) { + break; + } + } + bh_assert(i < wasm_module->type_count); + + type_idx = i; + } +#endif +#if WASM_ENABLE_AOT != 0 + if (module->module_type == Wasm_Module_AoT) { + AOTModule *aot_module = (AOTModule *)module; + + type_count = aot_module->type_count; + for (i = 0; i < type_count; i++) { + if (aot_module->types[i] == (AOTType *)type) { + break; + } + } + bh_assert(i < aot_module->type_count); + + type_idx = i; + } +#endif + + array_obj = + wasm_array_obj_new_with_typeidx(exec_env, type_idx, length, init_value); + + return array_obj; +} + +WASMFuncObjectRef +wasm_func_obj_new_with_typeidx(WASMExecEnv *exec_env, uint32 type_idx, + uint32 func_idx_bound) +{ + WASMFuncObjectRef func_obj; + WASMRttTypeRef rtt_type = NULL; + WASMModuleCommon *module = wasm_exec_env_get_module(exec_env); + WASMType *defined_type = wasm_get_defined_type(module, type_idx); + +#if WASM_ENABLE_INTERP != 0 + if (module->module_type == Wasm_Module_Bytecode) { + WASMModule *wasm_module = (WASMModule *)module; + + rtt_type = wasm_rtt_type_new( + defined_type, type_idx, wasm_module->rtt_types, + wasm_module->type_count, &wasm_module->rtt_type_lock); + } +#endif +#if WASM_ENABLE_AOT != 0 + if (module->module_type == Wasm_Module_AoT) { + AOTModule *aot_module = (AOTModule *)module; + + rtt_type = wasm_rtt_type_new( + defined_type, type_idx, aot_module->rtt_types, + aot_module->type_count, &aot_module->rtt_type_lock); + } +#endif + + if (!rtt_type) { + return NULL; + } + func_obj = wasm_func_obj_new(exec_env, rtt_type, func_idx_bound); + + return func_obj; +} + +WASMFuncObjectRef +wasm_func_obj_new_with_type(WASMExecEnv *exec_env, WASMFuncType *type, + uint32 func_idx_bound) +{ + WASMFuncObjectRef func_obj; + uint32 i, type_count, type_idx = 0; + WASMModuleCommon *module = wasm_exec_env_get_module(exec_env); + + bh_assert(type->base_type.type_flag == WASM_TYPE_FUNC); + +#if WASM_ENABLE_INTERP != 0 + if (module->module_type == Wasm_Module_Bytecode) { + WASMModule *wasm_module = (WASMModule *)module; + + type_count = wasm_module->type_count; + for (i = 0; i < type_count; i++) { + if (wasm_module->types[i] == (WASMType *)type) { + break; + } + } + bh_assert(i < wasm_module->type_count); + + type_idx = i; + } +#endif +#if WASM_ENABLE_AOT != 0 + if (module->module_type == Wasm_Module_AoT) { + AOTModule *aot_module = (AOTModule *)module; + + type_count = aot_module->type_count; + for (i = 0; i < type_count; i++) { + if (aot_module->types[i] == (AOTType *)type) { + break; + } + } + bh_assert(i < aot_module->type_count); + + type_idx = i; + } +#endif + + func_obj = + wasm_func_obj_new_with_typeidx(exec_env, type_idx, func_idx_bound); + + return func_obj; +} + +bool +wasm_runtime_call_func_ref(WASMExecEnv *exec_env, + const WASMFuncObjectRef func_obj, uint32 argc, + uint32 argv[]) +{ + WASMFunctionInstanceCommon *func_inst = NULL; + uint32 func_idx = wasm_func_obj_get_func_idx_bound(func_obj); +#if WASM_ENABLE_AOT != 0 + AOTFunctionInstance aot_func_inst = { 0 }; +#endif + +#if WASM_ENABLE_INTERP != 0 + if (exec_env->module_inst->module_type == Wasm_Module_Bytecode) { + WASMFunctionInstance *wasm_func_inst; + WASMModuleInstance *module_inst = + (WASMModuleInstance *)exec_env->module_inst; + + bh_assert(func_idx < module_inst->module->import_function_count + + module_inst->module->function_count); + wasm_func_inst = module_inst->e->functions + func_idx; + func_inst = (WASMFunctionInstanceCommon *)wasm_func_inst; + } +#endif +#if WASM_ENABLE_AOT != 0 + if (exec_env->module_inst->module_type == Wasm_Module_AoT) { + uint32 func_type_idx; + AOTModuleInstance *module_inst = + (AOTModuleInstance *)exec_env->module_inst; + AOTModule *module = (AOTModule *)module_inst->module; + (void)module_inst; + + bh_assert(func_idx < module->import_func_count + module->func_count); + + aot_func_inst.func_name = ""; + aot_func_inst.func_index = func_idx; + aot_func_inst.is_import_func = false; + func_type_idx = + module->func_type_indexes[func_idx - module->import_func_count]; + aot_func_inst.u.func.func_type = + (AOTFuncType *)module->types[func_type_idx]; + aot_func_inst.u.func.func_ptr = + module->func_ptrs[func_idx - module->import_func_count]; + + func_inst = (WASMFunctionInstanceCommon *)(&aot_func_inst); + } +#endif + + bh_assert(func_inst); + return wasm_runtime_call_wasm(exec_env, func_inst, argc, argv); +} + +bool +wasm_runtime_call_func_ref_a(WASMExecEnv *exec_env, + const WASMFuncObjectRef func_obj, + uint32 num_results, wasm_val_t results[], + uint32 num_args, wasm_val_t *args) +{ + /* TODO */ + return false; +} + +bool +wasm_runtime_call_func_ref_v(wasm_exec_env_t exec_env, + const WASMFuncObjectRef func_obj, + uint32 num_results, wasm_val_t results[], + uint32 num_args, ...) +{ + /* TODO */ + return false; +} + +bool +wasm_obj_is_instance_of_defined_type(WASMObjectRef obj, WASMType *defined_type, + WASMModuleCommon *const module) +{ + WASMType **types = NULL; + uint32 type_count = 0; + uint32 type_idx = 0; + +#if WASM_ENABLE_INTERP != 0 + if (module->module_type == Wasm_Module_Bytecode) { + WASMModule *wasm_module = (WASMModule *)module; + + type_count = wasm_module->type_count; + types = wasm_module->types; + } +#endif +#if WASM_ENABLE_AOT != 0 + if (module->module_type == Wasm_Module_AoT) { + AOTModule *aot_module = (AOTModule *)module; + + type_count = aot_module->type_count; + types = (WASMType **)aot_module->types; + } +#endif + + for (type_idx = 0; type_idx < type_count; type_idx++) { + if (types[type_idx] == defined_type) { + break; + } + } + bh_assert(type_idx < type_count); + + return wasm_obj_is_instance_of(obj, type_idx, types, type_count); +} + +bool +wasm_obj_is_instance_of_type_idx(WASMObjectRef obj, uint32 type_idx, + WASMModuleCommon *const module) +{ + WASMType **types = NULL; + uint32 type_count = 0; + +#if WASM_ENABLE_INTERP != 0 + if (module->module_type == Wasm_Module_Bytecode) { + WASMModule *wasm_module = (WASMModule *)module; + + types = wasm_module->types; + } +#endif +#if WASM_ENABLE_AOT != 0 + if (module->module_type == Wasm_Module_AoT) { + AOTModule *aot_module = (AOTModule *)module; + + types = (WASMType **)aot_module->types; + } +#endif + + bh_assert(types); + + return wasm_obj_is_instance_of(obj, type_idx, types, type_count); +} + +bool +wasm_obj_is_instance_of_ref_type(const WASMObjectRef obj, + const wasm_ref_type_t *ref_type) +{ + int32 heap_type = ref_type->heap_type; + return wasm_obj_is_type_of(obj, heap_type); +} + +void +wasm_runtime_push_local_obj_ref(WASMExecEnv *exec_env, WASMLocalObjectRef *ref) +{ + ref->val = NULL; + ref->prev = exec_env->cur_local_object_ref; + exec_env->cur_local_object_ref = ref; +} + +WASMLocalObjectRef * +wasm_runtime_pop_local_obj_ref(WASMExecEnv *exec_env) +{ + WASMLocalObjectRef *local_ref = exec_env->cur_local_object_ref; + exec_env->cur_local_object_ref = exec_env->cur_local_object_ref->prev; + return local_ref; +} + +void +wasm_runtime_pop_local_obj_refs(WASMExecEnv *exec_env, uint32 n) +{ + bh_assert(n > 0); + + do { + exec_env->cur_local_object_ref = exec_env->cur_local_object_ref->prev; + } while (--n > 0); +} + +WASMLocalObjectRef * +wasm_runtime_get_cur_local_obj_ref(WASMExecEnv *exec_env) +{ + WASMLocalObjectRef *local_ref = exec_env->cur_local_object_ref; + + bh_assert(local_ref); + return local_ref; +} + +void +wasm_runtime_gc_prepare(WASMExecEnv *exec_env) +{ +#if 0 + /* TODO: implement wasm_runtime_gc_prepare for multi-thread */ + exec_env->is_gc_reclaiming = false; + wasm_thread_suspend_all(); + exec_env->is_gc_reclaim = 1; + exec_env->requesting_suspend = 0; +#endif +} + +void +wasm_runtime_gc_finalize(WASMExecEnv *exec_env) +{ +#if 0 + /* TODO: implement wasm_runtime_gc_finalize for multi-thread */ + wasm_thread_resume_all(); + exec_env->doing_gc_reclaim = 0; +#endif +} + +bool +wasm_runtime_get_wasm_object_ref_list(WASMObjectRef obj, + bool *p_is_compact_mode, + uint32 *p_ref_num, uint16 **p_ref_list, + uint32 *p_ref_start_offset) +{ + return wasm_object_get_ref_list(obj, p_is_compact_mode, p_ref_num, + p_ref_list, p_ref_start_offset); +} + +bool +wasm_runtime_traverse_gc_rootset(WASMExecEnv *exec_env, void *heap) +{ +#if WASM_ENABLE_INTERP != 0 + if (exec_env->module_inst->module_type == Wasm_Module_Bytecode) { + return wasm_traverse_gc_rootset(exec_env, heap); + } +#endif +#if WASM_ENABLE_AOT != 0 + if (exec_env->module_inst->module_type == Wasm_Module_AoT) { + return aot_traverse_gc_rootset(exec_env, heap); + } +#endif + return false; +} + +void +wasm_runtime_set_gc_heap_handle(WASMModuleInstanceCommon *module_inst, + void *gc_heap_handle) +{ +#if WASM_ENABLE_INTERP != 0 + if (module_inst->module_type == Wasm_Module_Bytecode) + ((WASMModuleInstance *)module_inst)->e->common.gc_heap_handle = + gc_heap_handle; +#endif +#if WASM_ENABLE_AOT != 0 + if (module_inst->module_type == Wasm_Module_AoT) { + AOTModuleInstanceExtra *e = + (AOTModuleInstanceExtra *)((AOTModuleInstance *)module_inst)->e; + e->common.gc_heap_handle = gc_heap_handle; + } +#endif +} + +void * +wasm_runtime_get_gc_heap_handle(WASMModuleInstanceCommon *module_inst) +{ +#if WASM_ENABLE_INTERP != 0 + if (module_inst->module_type == Wasm_Module_Bytecode) + return ((WASMModuleInstance *)module_inst)->e->common.gc_heap_handle; +#endif +#if WASM_ENABLE_AOT != 0 + if (module_inst->module_type == Wasm_Module_AoT) { + AOTModuleInstanceExtra *e = + (AOTModuleInstanceExtra *)((AOTModuleInstance *)module_inst)->e; + return e->common.gc_heap_handle; + } +#endif + return NULL; +} + +bool +wasm_runtime_get_wasm_object_extra_info_flag(WASMObjectRef obj) +{ + return obj->header & WASM_OBJ_EXTRA_INFO_FLAG; +} + +void +wasm_runtime_set_wasm_object_extra_info_flag(WASMObjectRef obj, bool set) +{ + if (set) { + obj->header |= WASM_OBJ_EXTRA_INFO_FLAG; + } + else { + obj->header &= ~WASM_OBJ_EXTRA_INFO_FLAG; + } +} diff --git a/core/iwasm/common/gc/gc_object.c b/core/iwasm/common/gc/gc_object.c new file mode 100644 index 000000000..57743a35d --- /dev/null +++ b/core/iwasm/common/gc/gc_object.c @@ -0,0 +1,1071 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include "gc_object.h" +#include "mem_alloc.h" +#include "../wasm_runtime_common.h" +#if WASM_ENABLE_INTERP != 0 +#include "../interpreter/wasm_runtime.h" +#endif +#if WASM_ENABLE_AOT != 0 +#include "../aot/aot_runtime.h" +#endif +#if WASM_ENABLE_STRINGREF != 0 +#include "string_object.h" +#endif + +WASMRttTypeRef +wasm_rtt_type_new(WASMType *defined_type, uint32 defined_type_idx, + WASMRttType **rtt_types, uint32 rtt_type_count, + korp_mutex *rtt_type_lock) +{ + WASMRttType *rtt_type; + + bh_assert(defined_type_idx < rtt_type_count); + + os_mutex_lock(rtt_type_lock); + + if (rtt_types[defined_type_idx]) { + os_mutex_unlock(rtt_type_lock); + return rtt_types[defined_type_idx]; + } + + if ((rtt_type = wasm_runtime_malloc(sizeof(WASMRttType)))) { + rtt_type->type_flag = defined_type->type_flag; + rtt_type->inherit_depth = defined_type->inherit_depth; + rtt_type->defined_type = defined_type; + rtt_type->root_type = defined_type->root_type; + + rtt_types[defined_type_idx] = rtt_type; + } + + os_mutex_unlock(rtt_type_lock); + return rtt_type; +} + +static void * +gc_obj_malloc(void *heap_handle, uint64 size) +{ + void *mem; + + if (size >= UINT32_MAX + || !(mem = mem_allocator_malloc_with_gc(heap_handle, (uint32)size))) { + LOG_WARNING("warning: failed to allocate memory for gc object"); + return NULL; + } + + memset(mem, 0, (uint32)size); + return mem; +} + +static void * +get_gc_heap_handle(WASMExecEnv *exec_env) +{ + void *gc_heap_handle = NULL; + WASMModuleInstanceCommon *module_inst = exec_env->module_inst; + +#if WASM_ENABLE_INTERP != 0 + if (module_inst->module_type == Wasm_Module_Bytecode) + gc_heap_handle = + ((WASMModuleInstance *)module_inst)->e->common.gc_heap_handle; +#endif +#if WASM_ENABLE_AOT != 0 + if (module_inst->module_type == Wasm_Module_AoT) + gc_heap_handle = + ((AOTModuleInstanceExtra *)((AOTModuleInstance *)module_inst)->e) + ->common.gc_heap_handle; +#endif + + bh_assert(gc_heap_handle); + return gc_heap_handle; +} + +WASMStructObjectRef +wasm_struct_obj_new_internal(void *heap_handle, WASMRttTypeRef rtt_type) +{ + WASMStructObjectRef struct_obj; + WASMStructType *struct_type; + + bh_assert(rtt_type->type_flag == WASM_TYPE_STRUCT); + + struct_type = (WASMStructType *)rtt_type->defined_type; + if (!(struct_obj = gc_obj_malloc(heap_handle, struct_type->total_size))) { + return NULL; + } + + struct_obj->header = (WASMObjectHeader)rtt_type; + + return struct_obj; +} + +WASMStructObjectRef +wasm_struct_obj_new(WASMExecEnv *exec_env, WASMRttTypeRef rtt_type) +{ + void *heap_handle = get_gc_heap_handle(exec_env); + return wasm_struct_obj_new_internal(heap_handle, rtt_type); +} + +void +wasm_struct_obj_set_field(WASMStructObjectRef struct_obj, uint32 field_idx, + const WASMValue *value) +{ + WASMRttTypeRef rtt_type = + (WASMRttTypeRef)wasm_object_header((WASMObjectRef)struct_obj); + WASMStructType *struct_type = (WASMStructType *)rtt_type->defined_type; + WASMStructFieldType *field; + uint8 field_size, *field_data; + + bh_assert(field_idx < struct_type->field_count); + + field = struct_type->fields + field_idx; + field_data = (uint8 *)struct_obj + field->field_offset; + field_size = field->field_size; + + if (field_size == 4) { + *(int32 *)field_data = value->i32; + } + else if (field_size == 8) { +#if defined(BUILD_TARGET_X86_64) || defined(BUILD_TARGET_AMD_64) \ + || defined(BUILD_TARGET_X86_32) + *(int64 *)field_data = value->i64; +#else + PUT_I64_TO_ADDR((uint32 *)field_data, value->i64); +#endif + } + else if (field_size == 1) { + *(int8 *)field_data = (int8)value->i32; + } + else if (field_size == 2) { + *(int16 *)field_data = (int16)value->i32; + } + else { + bh_assert(0); + } +} + +void +wasm_struct_obj_get_field(const WASMStructObjectRef struct_obj, + uint32 field_idx, bool sign_extend, WASMValue *value) +{ + WASMRttTypeRef rtt_type = + (WASMRttTypeRef)wasm_object_header((WASMObjectRef)struct_obj); + WASMStructType *struct_type = (WASMStructType *)rtt_type->defined_type; + WASMStructFieldType *field; + uint8 *field_data, field_size; + + bh_assert(field_idx < struct_type->field_count); + + field = struct_type->fields + field_idx; + field_data = (uint8 *)struct_obj + field->field_offset; + field_size = field->field_size; + + if (field_size == 4) { + value->i32 = *(int32 *)field_data; + } + else if (field_size == 8) { +#if defined(BUILD_TARGET_X86_64) || defined(BUILD_TARGET_AMD_64) \ + || defined(BUILD_TARGET_X86_32) + value->i64 = *(int64 *)field_data; +#else + value->i64 = GET_I64_FROM_ADDR((uint32 *)field_data); +#endif + } + else if (field_size == 1) { + if (sign_extend) + value->i32 = (int32)(*(int8 *)field_data); + else + value->u32 = (uint32)(*(uint8 *)field_data); + } + else if (field_size == 2) { + if (sign_extend) + value->i32 = (int32)(*(int16 *)field_data); + else + value->u32 = (uint32)(*(uint16 *)field_data); + } + else { + bh_assert(0); + } +} + +WASMArrayObjectRef +wasm_array_obj_new_internal(void *heap_handle, WASMRttTypeRef rtt_type, + uint32 length, WASMValue *init_value) +{ + WASMArrayObjectRef array_obj; + WASMArrayType *array_type; + uint64 total_size; + uint32 elem_size, elem_size_log, i; + + bh_assert(rtt_type->type_flag == WASM_TYPE_ARRAY); + + if (length >= (1 << 29)) + return NULL; + + array_type = (WASMArrayType *)rtt_type->defined_type; + if (array_type->elem_type == PACKED_TYPE_I8) { + elem_size = 1; + elem_size_log = 0; + } + else if (array_type->elem_type == PACKED_TYPE_I16) { + elem_size = 2; + elem_size_log = 1; + } + else { + elem_size = wasm_value_type_size(array_type->elem_type); + elem_size_log = (elem_size == 4) ? 2 : 3; + } + + total_size = + offsetof(WASMArrayObject, elem_data) + (uint64)elem_size * length; + if (!(array_obj = gc_obj_malloc(heap_handle, total_size))) { + return NULL; + } + + array_obj->header = (WASMObjectHeader)rtt_type; + array_obj->length = (length << 2) | elem_size_log; + + if (init_value != NULL) { + for (i = 0; i < length; i++) { + if (wasm_is_type_reftype(array_type->elem_type)) { + uint32 *elem_addr = + (uint32 *)array_obj->elem_data + REF_CELL_NUM * i; + PUT_REF_TO_ADDR(elem_addr, init_value->gc_obj); + } + else if (array_type->elem_type == VALUE_TYPE_I32 + || array_type->elem_type == VALUE_TYPE_F32) { + ((int32 *)array_obj->elem_data)[i] = init_value->i32; + } + else if (array_type->elem_type == PACKED_TYPE_I8) { + ((int8 *)array_obj->elem_data)[i] = (int8)init_value->i32; + } + else if (array_type->elem_type == PACKED_TYPE_I16) { + ((int16 *)array_obj->elem_data)[i] = (int16)init_value->i32; + } + else { + uint32 *elem_addr = (uint32 *)array_obj->elem_data + 2 * i; + PUT_I64_TO_ADDR(elem_addr, init_value->i64); + } + } + } + + return array_obj; +} + +WASMArrayObjectRef +wasm_array_obj_new(WASMExecEnv *exec_env, WASMRttTypeRef rtt_type, + uint32 length, WASMValue *init_value) +{ + void *heap_handle = get_gc_heap_handle(exec_env); + return wasm_array_obj_new_internal(heap_handle, rtt_type, length, + init_value); +} + +void +wasm_array_obj_set_elem(WASMArrayObjectRef array_obj, uint32 elem_idx, + const WASMValue *value) +{ + uint8 *elem_data = wasm_array_obj_elem_addr(array_obj, elem_idx); + uint32 elem_size = 1 << wasm_array_obj_elem_size_log(array_obj); + + switch (elem_size) { + case 1: + *(int8 *)elem_data = (int8)value->i32; + break; + case 2: + *(int16 *)elem_data = (int16)value->i32; + break; + case 4: + *(int32 *)elem_data = value->i32; + break; + case 8: + PUT_I64_TO_ADDR((uint32 *)elem_data, value->i64); + break; + } +} + +void +wasm_array_obj_get_elem(const WASMArrayObjectRef array_obj, uint32 elem_idx, + bool sign_extend, WASMValue *value) +{ + uint8 *elem_data = wasm_array_obj_elem_addr(array_obj, elem_idx); + uint32 elem_size = 1 << wasm_array_obj_elem_size_log(array_obj); + + switch (elem_size) { + case 1: + value->i32 = sign_extend ? (int32)(*(int8 *)elem_data) + : (int32)(uint32)(*(uint8 *)elem_data); + break; + case 2: + value->i32 = sign_extend ? (int32)(*(int16 *)elem_data) + : (int32)(uint32)(*(uint16 *)elem_data); + break; + case 4: + value->i32 = *(int32 *)elem_data; + break; + case 8: + value->i64 = GET_I64_FROM_ADDR((uint32 *)elem_data); + break; + } +} + +void +wasm_array_obj_fill(const WASMArrayObjectRef array_obj, uint32 elem_idx, + uint32 len, WASMValue *value) +{ + uint32 i; + uint8 *elem_data = wasm_array_obj_elem_addr(array_obj, elem_idx); + uint32 elem_size = 1 << wasm_array_obj_elem_size_log(array_obj); + + if (elem_size == 1) { + memset(elem_data, (int8)value->i32, len); + return; + } + + for (i = 0; i < len; i++) { + switch (elem_size) { + case 2: + *(int16 *)elem_data = (int16)value->i32; + break; + case 4: + *(int32 *)elem_data = value->i32; + break; + case 8: + PUT_I64_TO_ADDR((uint32 *)elem_data, value->i64); + break; + } + elem_data += elem_size; + } +} + +void +wasm_array_obj_copy(WASMArrayObjectRef dst_obj, uint32 dst_idx, + WASMArrayObjectRef src_obj, uint32 src_idx, uint32 len) +{ + uint8 *dst_data = wasm_array_obj_elem_addr(dst_obj, dst_idx); + uint8 *src_data = wasm_array_obj_elem_addr(src_obj, src_idx); + uint32 elem_size = 1 << wasm_array_obj_elem_size_log(dst_obj); + + bh_memmove_s(dst_data, elem_size * len, src_data, elem_size * len); +} + +uint32 +wasm_array_obj_length(const WASMArrayObjectRef array_obj) +{ + return array_obj->length >> WASM_ARRAY_LENGTH_SHIFT; +} + +void * +wasm_array_obj_first_elem_addr(const WASMArrayObjectRef array_obj) +{ + return array_obj->elem_data; +} + +void * +wasm_array_obj_elem_addr(const WASMArrayObjectRef array_obj, uint32 elem_idx) +{ + return array_obj->elem_data + + (elem_idx << wasm_array_obj_elem_size_log(array_obj)); +} + +WASMFuncObjectRef +wasm_func_obj_new_internal(void *heap_handle, WASMRttTypeRef rtt_type, + uint32 func_idx_bound) +{ + WASMFuncObjectRef func_obj; + uint64 total_size; + + bh_assert(rtt_type->type_flag == WASM_TYPE_FUNC); + + total_size = sizeof(WASMFuncObject); + if (!(func_obj = gc_obj_malloc(heap_handle, total_size))) { + return NULL; + } + + func_obj->header = (WASMObjectHeader)rtt_type; + func_obj->func_idx_bound = func_idx_bound; + + return func_obj; +} + +WASMFuncObjectRef +wasm_func_obj_new(WASMExecEnv *exec_env, WASMRttTypeRef rtt_type, + uint32 func_idx_bound) +{ + void *heap_handle = get_gc_heap_handle(exec_env); + return wasm_func_obj_new_internal(heap_handle, rtt_type, func_idx_bound); +} + +uint32 +wasm_func_obj_get_func_idx_bound(const WASMFuncObjectRef func_obj) +{ + return func_obj->func_idx_bound; +} + +WASMFuncType * +wasm_func_obj_get_func_type(const WASMFuncObjectRef func_obj) +{ + WASMRttTypeRef rtt_type = + (WASMRttTypeRef)wasm_object_header((WASMObjectRef)func_obj); + bh_assert(rtt_type->type_flag == WASM_TYPE_FUNC); + return (WASMFuncType *)rtt_type->defined_type; +} + +WASMExternrefObjectRef +wasm_externref_obj_new(WASMExecEnv *exec_env, const void *host_obj) +{ + void *heap_handle = get_gc_heap_handle(exec_env); + WASMAnyrefObjectRef anyref_obj; + WASMExternrefObjectRef externref_obj; + WASMLocalObjectRef local_ref; + + if (!(anyref_obj = gc_obj_malloc(heap_handle, sizeof(WASMAnyrefObject)))) { + return NULL; + } + + anyref_obj->header = WASM_OBJ_ANYREF_OBJ_FLAG; + anyref_obj->host_obj = host_obj; + + /* Lock anyref_obj in case it is reclaimed when allocating memory below */ + wasm_runtime_push_local_obj_ref(exec_env, &local_ref); + local_ref.val = (WASMObjectRef)anyref_obj; + + if (!(externref_obj = + gc_obj_malloc(heap_handle, sizeof(WASMExternrefObject)))) { + wasm_runtime_pop_local_obj_ref(exec_env); + return NULL; + } + + externref_obj->header = WASM_OBJ_EXTERNREF_OBJ_FLAG; + externref_obj->internal_obj = (WASMObjectRef)anyref_obj; + + wasm_runtime_pop_local_obj_ref(exec_env); + return externref_obj; +} + +WASMAnyrefObjectRef +wasm_anyref_obj_new(WASMExecEnv *exec_env, const void *host_obj) +{ + void *heap_handle = get_gc_heap_handle(exec_env); + WASMAnyrefObjectRef anyref_obj; + + if (!(anyref_obj = gc_obj_malloc(heap_handle, sizeof(WASMAnyrefObject)))) { + return NULL; + } + + anyref_obj->header = WASM_OBJ_ANYREF_OBJ_FLAG; + anyref_obj->host_obj = host_obj; + + return anyref_obj; +} + +WASMObjectRef +wasm_externref_obj_to_internal_obj(WASMExternrefObjectRef externref_obj) +{ + return externref_obj->internal_obj; +} + +WASMExternrefObjectRef +wasm_internal_obj_to_externref_obj(WASMExecEnv *exec_env, + WASMObjectRef internal_obj) +{ + void *heap_handle = get_gc_heap_handle(exec_env); + WASMExternrefObjectRef externref_obj; + + if (!(externref_obj = + gc_obj_malloc(heap_handle, sizeof(WASMExternrefObject)))) { + return NULL; + } + + externref_obj->header = WASM_OBJ_EXTERNREF_OBJ_FLAG; + externref_obj->internal_obj = internal_obj; + + return externref_obj; +} + +const void * +wasm_anyref_obj_get_value(WASMAnyrefObjectRef anyref_obj) +{ + return anyref_obj->host_obj; +} + +const void * +wasm_externref_obj_get_value(const WASMExternrefObjectRef externref_obj) +{ + if (wasm_obj_is_anyref_obj(externref_obj->internal_obj)) + return ((WASMAnyrefObjectRef)externref_obj->internal_obj)->host_obj; + else + return externref_obj->internal_obj; +} + +WASMI31ObjectRef +wasm_i31_obj_new(uint32 i31_value) +{ + return (WASMI31ObjectRef)((i31_value << 1) | 1); +} + +uint32 +wasm_i31_obj_get_value(WASMI31ObjectRef i31_obj, bool sign_extend) +{ + uint32 i31_value = (uint32)(((uintptr_t)i31_obj) >> 1); + if (sign_extend && (i31_value & 0x40000000)) /* bit 30 is 1 */ + /* set bit 31 to 1 */ + i31_value |= 0x80000000; + return i31_value; +} + +bool +wasm_obj_is_i31_obj(WASMObjectRef obj) +{ + bh_assert(obj); + return (((uintptr_t)obj) & 1) ? true : false; +} + +bool +wasm_obj_is_externref_obj(WASMObjectRef obj) +{ + bh_assert(obj); + return (!wasm_obj_is_i31_obj(obj) + && (obj->header & WASM_OBJ_EXTERNREF_OBJ_FLAG)) + ? true + : false; +} + +bool +wasm_obj_is_anyref_obj(WASMObjectRef obj) +{ + bh_assert(obj); + return (!wasm_obj_is_i31_obj(obj) + && (obj->header & WASM_OBJ_ANYREF_OBJ_FLAG)) + ? true + : false; +} + +bool +wasm_obj_is_i31_externref_or_anyref_obj(WASMObjectRef obj) +{ + bh_assert(obj); + return (wasm_obj_is_i31_obj(obj) + || (obj->header + & (WASM_OBJ_EXTERNREF_OBJ_FLAG | WASM_OBJ_ANYREF_OBJ_FLAG))) + ? true + : false; +} + +bool +wasm_obj_is_struct_obj(WASMObjectRef obj) +{ + WASMRttTypeRef rtt_type; + + bh_assert(obj); + + if (wasm_obj_is_i31_externref_or_anyref_obj(obj)) + return false; + + rtt_type = (WASMRttTypeRef)wasm_object_header(obj); + return rtt_type->type_flag == WASM_TYPE_STRUCT ? true : false; +} + +bool +wasm_obj_is_array_obj(WASMObjectRef obj) +{ + WASMRttTypeRef rtt_type; + + bh_assert(obj); + + if (wasm_obj_is_i31_externref_or_anyref_obj(obj)) + return false; + + rtt_type = (WASMRttTypeRef)wasm_object_header(obj); + return rtt_type->type_flag == WASM_TYPE_ARRAY ? true : false; +} + +bool +wasm_obj_is_func_obj(WASMObjectRef obj) +{ + WASMRttTypeRef rtt_type; + + bh_assert(obj); + + if (wasm_obj_is_i31_externref_or_anyref_obj(obj)) + return false; + + rtt_type = (WASMRttTypeRef)wasm_object_header(obj); + return rtt_type->type_flag == WASM_TYPE_FUNC ? true : false; +} + +bool +wasm_obj_is_internal_obj(WASMObjectRef obj) +{ + WASMRttTypeRef rtt_type; + + bh_assert(obj); + + if (wasm_obj_is_i31_obj(obj)) + return true; + else if (obj->header & WASM_OBJ_ANYREF_OBJ_FLAG) + return true; + else if (obj->header & WASM_OBJ_EXTERNREF_OBJ_FLAG) + return false; + else { + rtt_type = (WASMRttTypeRef)wasm_object_header(obj); + return (rtt_type->type_flag == WASM_TYPE_STRUCT + || rtt_type->type_flag == WASM_TYPE_ARRAY) + ? true + : false; + } +} + +bool +wasm_obj_is_eq_obj(WASMObjectRef obj) +{ + WASMRttTypeRef rtt_type; + + bh_assert(obj); + + if (wasm_obj_is_i31_obj(obj)) + return true; + else if ((obj->header & WASM_OBJ_ANYREF_OBJ_FLAG) + || (obj->header & WASM_OBJ_EXTERNREF_OBJ_FLAG)) + return false; + else { + rtt_type = (WASMRttTypeRef)wasm_object_header(obj); + return (rtt_type->type_flag == WASM_TYPE_STRUCT + || rtt_type->type_flag == WASM_TYPE_ARRAY) + ? true + : false; + } +} + +bool +wasm_obj_is_instance_of(WASMObjectRef obj, uint32 type_idx, WASMType **types, + uint32 type_count) +{ + WASMRttTypeRef rtt_type_sub; + WASMType *type_sub, *type_parent; + uint32 distance, i; + + bh_assert(obj); + bh_assert(type_idx < type_count); + + if (wasm_obj_is_i31_externref_or_anyref_obj(obj)) + return false; + + rtt_type_sub = (WASMRttTypeRef)wasm_object_header(obj); + type_parent = types[type_idx]; + + if (!(rtt_type_sub->root_type == type_parent->root_type + && rtt_type_sub->inherit_depth >= type_parent->inherit_depth)) + return false; + + type_sub = rtt_type_sub->defined_type; + distance = type_sub->inherit_depth - type_parent->inherit_depth; + + for (i = 0; i < distance; i++) { + type_sub = type_sub->parent_type; + } + + return (type_sub == type_parent) ? true : false; +} + +bool +wasm_obj_is_type_of(WASMObjectRef obj, int32 heap_type) +{ + bh_assert(obj); + + switch (heap_type) { + case HEAP_TYPE_FUNC: + return wasm_obj_is_func_obj(obj); + case HEAP_TYPE_EXTERN: + return wasm_obj_is_externref_obj(obj); + case HEAP_TYPE_ANY: + return wasm_obj_is_internal_obj(obj); + case HEAP_TYPE_EQ: + return wasm_obj_is_eq_obj(obj); + case HEAP_TYPE_I31: + return wasm_obj_is_i31_obj(obj); + case HEAP_TYPE_STRUCT: + return wasm_obj_is_struct_obj(obj); + case HEAP_TYPE_ARRAY: + return wasm_obj_is_array_obj(obj); +#if WASM_ENABLE_STRINGREF != 0 + case HEAP_TYPE_STRINGREF: + return wasm_obj_is_stringref_obj(obj); + case HEAP_TYPE_STRINGVIEWWTF8: + return wasm_obj_is_stringview_wtf8_obj(obj); + case HEAP_TYPE_STRINGVIEWWTF16: + return wasm_obj_is_stringview_wtf16_obj(obj); +#endif + case HEAP_TYPE_NONE: + case HEAP_TYPE_NOFUNC: + case HEAP_TYPE_NOEXTERN: + return false; + default: + bh_assert(0); + break; + } + return false; +} + +bool +wasm_obj_equal(WASMObjectRef obj1, WASMObjectRef obj2) +{ + /* TODO: do we need to compare the internal details of the objects */ + return obj1 == obj2 ? true : false; +} + +bool +wasm_object_get_ref_list(WASMObjectRef obj, bool *p_is_compact_mode, + uint32 *p_ref_num, uint16 **p_ref_list, + uint32 *p_ref_start_offset) +{ + WASMRttTypeRef rtt_type; + + bh_assert(wasm_obj_is_created_from_heap(obj)); + + rtt_type = (WASMRttTypeRef)wasm_object_header(obj); + + if (obj->header & WASM_OBJ_EXTERNREF_OBJ_FLAG) { + /* externref object */ + static uint16 externref_obj_ref_list[] = { (uint16)offsetof( + WASMExternrefObject, internal_obj) }; + *p_is_compact_mode = false; + *p_ref_num = 1; + *p_ref_list = externref_obj_ref_list; + return true; + } + else if (obj->header & WASM_OBJ_ANYREF_OBJ_FLAG) { + /* anyref object */ + *p_is_compact_mode = false; + *p_ref_num = 0; + *p_ref_list = NULL; + return true; + } +#if WASM_ENABLE_STRINGREF != 0 + else if (rtt_type->type_flag == WASM_TYPE_STRINGREF + || rtt_type->type_flag == WASM_TYPE_STRINGVIEWWTF8 + || rtt_type->type_flag == WASM_TYPE_STRINGVIEWWTF16 + || rtt_type->type_flag == WASM_TYPE_STRINGVIEWITER) { + /* stringref/stringview_wtf8/stringview_wtf16/stringview_iter object */ + *p_is_compact_mode = false; + *p_ref_num = 0; + *p_ref_list = NULL; + return true; + } +#endif /* end of WASM_ENABLE_STRINGREF != 0 */ + else if (rtt_type->defined_type->type_flag == WASM_TYPE_FUNC) { + /* function object */ + *p_is_compact_mode = false; + *p_ref_num = 0; + *p_ref_list = NULL; + return true; + } + else if (rtt_type->defined_type->type_flag == WASM_TYPE_STRUCT) { + /* struct object */ + WASMStructType *type = (WASMStructType *)rtt_type->defined_type; + *p_is_compact_mode = false; + *p_ref_num = *type->reference_table; + *p_ref_list = type->reference_table + 1; + return true; + } + else if (rtt_type->defined_type->type_flag == WASM_TYPE_ARRAY) { + /* array object */ + WASMArrayType *type = (WASMArrayType *)rtt_type->defined_type; + if (wasm_is_type_reftype(type->elem_type)) { + *p_is_compact_mode = true; + *p_ref_num = wasm_array_obj_length((WASMArrayObjectRef)obj); + *p_ref_start_offset = (uint16)offsetof(WASMArrayObject, elem_data); + } + else { + *p_is_compact_mode = false; + *p_ref_num = 0; + *p_ref_list = NULL; + } + + return true; + } + else { + bh_assert(0); + return false; + } +} + +bool +wasm_obj_set_gc_finalizer(wasm_exec_env_t exec_env, const wasm_obj_t obj, + wasm_obj_finalizer_t cb, void *data) +{ + void *heap_handle = get_gc_heap_handle(exec_env); + return mem_allocator_set_gc_finalizer(heap_handle, obj, (gc_finalizer_t)cb, + data); +} + +void +wasm_obj_unset_gc_finalizer(wasm_exec_env_t exec_env, void *obj) +{ + void *heap_handle = get_gc_heap_handle(exec_env); + mem_allocator_unset_gc_finalizer(heap_handle, obj); +} + +#if WASM_ENABLE_STRINGREF != 0 +WASMRttTypeRef +wasm_stringref_rtt_type_new(uint16 type_flag, WASMRttType **rtt_types, + korp_mutex *rtt_type_lock) +{ + WASMRttType *rtt_type; + uint32 index; + + bh_assert(type_flag >= WASM_TYPE_STRINGREF + && type_flag <= WASM_TYPE_STRINGVIEWITER); + + index = type_flag - WASM_TYPE_STRINGREF; + + os_mutex_lock(rtt_type_lock); + + if (rtt_types[index]) { + os_mutex_unlock(rtt_type_lock); + return rtt_types[index]; + } + + if ((rtt_type = wasm_runtime_malloc(sizeof(WASMRttType)))) { + memset(rtt_type, 0, sizeof(WASMRttType)); + rtt_type->type_flag = type_flag; + + rtt_types[index] = rtt_type; + } + + os_mutex_unlock(rtt_type_lock); + return rtt_type; +} + +static void +wasm_stringref_obj_finalizer(WASMStringrefObjectRef stringref_obj, void *data) +{ + wasm_string_destroy( + (WASMString)wasm_stringref_obj_get_value(stringref_obj)); +} + +static void +wasm_stringview_wtf8_obj_finalizer(WASMStringviewWTF8ObjectRef stringref_obj, + void *data) +{ + wasm_string_destroy( + (WASMString)wasm_stringview_wtf8_obj_get_value(stringref_obj)); +} + +static void +wasm_stringview_wtf16_obj_finalizer(WASMStringviewWTF16ObjectRef stringref_obj, + void *data) +{ + wasm_string_destroy( + (WASMString)wasm_stringview_wtf16_obj_get_value(stringref_obj)); +} + +static void +wasm_stringview_iter_obj_finalizer(WASMStringviewIterObjectRef stringref_obj, + void *data) +{ + wasm_string_destroy( + (WASMString)wasm_stringview_iter_obj_get_value(stringref_obj)); +} + +static WASMObjectRef +stringref_obj_new(WASMExecEnv *exec_env, uint32 type, const void *str_obj, + int32 pos) +{ + WASMObjectRef stringref_obj = NULL; + void *heap_handle = get_gc_heap_handle(exec_env); + WASMModuleInstanceCommon *module_inst = + wasm_runtime_get_module_inst(exec_env); + WASMRttTypeRef rtt_type = NULL; + +#if WASM_ENABLE_INTERP != 0 + if (module_inst->module_type == Wasm_Module_Bytecode) { + WASMModule *module = ((WASMModuleInstance *)module_inst)->module; + rtt_type = wasm_stringref_rtt_type_new(type, module->stringref_rtts, + &module->rtt_type_lock); + } +#endif +#if WASM_ENABLE_AOT != 0 + if (module_inst->module_type == Wasm_Module_AoT) { + AOTModule *module = + (AOTModule *)((AOTModuleInstance *)module_inst)->module; + rtt_type = wasm_stringref_rtt_type_new(type, module->stringref_rtts, + &module->rtt_type_lock); + } +#endif + + if (!rtt_type) { + return NULL; + } + + if (type == WASM_TYPE_STRINGREF) { + if (!(stringref_obj = + gc_obj_malloc(heap_handle, sizeof(WASMStringrefObject)))) { + return NULL; + } + ((WASMStringrefObjectRef)stringref_obj)->header = + (WASMObjectHeader)rtt_type; + ((WASMStringrefObjectRef)stringref_obj)->str_obj = str_obj; + wasm_obj_set_gc_finalizer( + exec_env, (wasm_obj_t)stringref_obj, + (wasm_obj_finalizer_t)wasm_stringref_obj_finalizer, NULL); + } + else if (type == WASM_TYPE_STRINGVIEWWTF8) { + if (!(stringref_obj = gc_obj_malloc( + heap_handle, sizeof(WASMStringviewWTF8Object)))) { + return NULL; + } + ((WASMStringviewWTF8ObjectRef)stringref_obj)->header = + (WASMObjectHeader)rtt_type; + ((WASMStringviewWTF8ObjectRef)stringref_obj)->str_obj = str_obj; + wasm_obj_set_gc_finalizer( + exec_env, (wasm_obj_t)stringref_obj, + (wasm_obj_finalizer_t)wasm_stringview_wtf8_obj_finalizer, NULL); + } + else if (type == WASM_TYPE_STRINGVIEWWTF16) { + if (!(stringref_obj = gc_obj_malloc( + heap_handle, sizeof(WASMStringviewWTF16Object)))) { + return NULL; + } + ((WASMStringviewWTF16ObjectRef)stringref_obj)->header = + (WASMObjectHeader)rtt_type; + ((WASMStringviewWTF16ObjectRef)stringref_obj)->str_obj = str_obj; + wasm_obj_set_gc_finalizer( + exec_env, (wasm_obj_t)stringref_obj, + (wasm_obj_finalizer_t)wasm_stringview_wtf16_obj_finalizer, NULL); + } + else if (type == WASM_TYPE_STRINGVIEWITER) { + if (!(stringref_obj = gc_obj_malloc( + heap_handle, sizeof(WASMStringviewIterObject)))) { + return NULL; + } + ((WASMStringviewIterObjectRef)stringref_obj)->header = + (WASMObjectHeader)rtt_type; + ((WASMStringviewIterObjectRef)stringref_obj)->str_obj = str_obj; + ((WASMStringviewIterObjectRef)stringref_obj)->pos = pos; + wasm_obj_set_gc_finalizer( + exec_env, (wasm_obj_t)stringref_obj, + (wasm_obj_finalizer_t)wasm_stringview_iter_obj_finalizer, NULL); + } + + return stringref_obj; +} + +WASMStringrefObjectRef +wasm_stringref_obj_new(WASMExecEnv *exec_env, const void *str_obj) +{ + WASMStringrefObjectRef stringref_obj; + + stringref_obj = (WASMStringrefObjectRef)stringref_obj_new( + exec_env, WASM_TYPE_STRINGREF, str_obj, 0); + + return stringref_obj; +} + +WASMStringviewWTF8ObjectRef +wasm_stringview_wtf8_obj_new(WASMExecEnv *exec_env, const void *str_obj) +{ + WASMStringviewWTF8ObjectRef stringview_wtf8_obj; + + stringview_wtf8_obj = (WASMStringviewWTF8ObjectRef)stringref_obj_new( + exec_env, WASM_TYPE_STRINGVIEWWTF8, str_obj, 0); + + return stringview_wtf8_obj; +} + +WASMStringviewWTF16ObjectRef +wasm_stringview_wtf16_obj_new(WASMExecEnv *exec_env, const void *str_obj) +{ + WASMStringviewWTF16ObjectRef stringview_wtf16_obj; + + stringview_wtf16_obj = (WASMStringviewWTF16ObjectRef)stringref_obj_new( + exec_env, WASM_TYPE_STRINGVIEWWTF16, str_obj, 0); + + return stringview_wtf16_obj; +} + +WASMStringviewIterObjectRef +wasm_stringview_iter_obj_new(WASMExecEnv *exec_env, const void *str_obj, + int32 pos) +{ + WASMStringviewIterObjectRef stringview_iter_obj; + + stringview_iter_obj = (WASMStringviewIterObjectRef)stringref_obj_new( + exec_env, WASM_TYPE_STRINGVIEWITER, str_obj, pos); + + return stringview_iter_obj; +} + +const void * +wasm_stringref_obj_get_value(WASMStringrefObjectRef stringref_obj) +{ + return stringref_obj->str_obj; +} + +const void * +wasm_stringview_wtf8_obj_get_value( + WASMStringviewWTF8ObjectRef stringview_wtf8_obj) +{ + return stringview_wtf8_obj->str_obj; +} + +const void * +wasm_stringview_wtf16_obj_get_value( + WASMStringviewWTF16ObjectRef stringview_wtf16_obj) +{ + return stringview_wtf16_obj->str_obj; +} + +const void * +wasm_stringview_iter_obj_get_value( + WASMStringviewIterObjectRef stringview_iter_obj) +{ + return stringview_iter_obj->str_obj; +} + +int32 +wasm_stringview_iter_obj_get_pos( + WASMStringviewIterObjectRef stringview_iter_obj) +{ + return stringview_iter_obj->pos; +} + +void +wasm_stringview_iter_obj_update_pos( + WASMStringviewIterObjectRef stringview_iter_obj, int32 pos) +{ + stringview_iter_obj->pos = pos; +} + +#define WASM_OBJ_IS_STRINGREF_IMPL(flag) \ + WASMRttTypeRef rtt_type; \ + \ + bh_assert(obj); \ + \ + if (wasm_obj_is_i31_externref_or_anyref_obj(obj)) \ + return false; \ + \ + rtt_type = (WASMRttTypeRef)wasm_object_header(obj); \ + return rtt_type->type_flag == flag ? true : false + +bool +wasm_obj_is_stringref_obj(WASMObjectRef obj) +{ + WASM_OBJ_IS_STRINGREF_IMPL(WASM_TYPE_STRINGREF); +} + +bool +wasm_obj_is_stringview_wtf8_obj(WASMObjectRef obj) +{ + WASM_OBJ_IS_STRINGREF_IMPL(WASM_TYPE_STRINGVIEWWTF8); +} + +bool +wasm_obj_is_stringview_wtf16_obj(WASMObjectRef obj) +{ + WASM_OBJ_IS_STRINGREF_IMPL(WASM_TYPE_STRINGVIEWWTF16); +} +#undef WASM_OBJ_IS_STRINGREF_IMPL + +#endif /* end of WASM_ENABLE_STRINGREF != 0 */ diff --git a/core/iwasm/common/gc/gc_object.h b/core/iwasm/common/gc/gc_object.h new file mode 100644 index 000000000..4c0cc4538 --- /dev/null +++ b/core/iwasm/common/gc/gc_object.h @@ -0,0 +1,378 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef _GC_OBJECT_H_ +#define _GC_OBJECT_H_ + +#include "gc_type.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Object header of a WASM object, as the adddress of allocated memory + * must be 8-byte aligned, the lowest 3 bits are zero, we use them to + * mark the object: + * bits[0] is 1: the object is an externref object + * bits[1] is 1: the object is an anyref object + * bits[2] is 1: the object has extra information + * if both bits[0] and bits[1] are 0, then this object header must + * be a pointer of a WASMRttType, denotes that the object is a + * struct object, or an array object, or a function object + */ +typedef uintptr_t WASMObjectHeader; + +#define WASM_OBJ_HEADER_MASK (~((uintptr_t)7)) + +#define WASM_OBJ_EXTERNREF_OBJ_FLAG (((uintptr_t)1) << 0) + +#define WASM_OBJ_ANYREF_OBJ_FLAG (((uintptr_t)1) << 1) + +#define WASM_OBJ_EXTRA_INFO_FLAG (((uintptr_t)1) << 2) + +/* Representation of WASM objects */ +typedef struct WASMObject { + WASMObjectHeader header; +} WASMObject, *WASMObjectRef; + +/* Representation of WASM rtt types */ +typedef struct WASMRttType { + /* type_flag must be WASM_TYPE_FUNC/STRUCT/ARRAY to + denote an object of func, struct or array */ + uint32 type_flag; + uint32 inherit_depth; + WASMType *defined_type; + WASMType *root_type; +} WASMRttType, *WASMRttTypeRef; + +/* Representation of WASM externref objects */ +typedef struct WASMExternrefObject { + /* bits[0] must be 1, denotes an externref object */ + WASMObjectHeader header; + /* an object of WASMAnyrefObjectRef which encapsulates the external + object passed from host, or other internal objects passed to + opcode extern.externalize */ + WASMObjectRef internal_obj; +} WASMExternrefObject, *WASMExternrefObjectRef; + +/* Representation of WASM anyref objects which encapsulate the + external object passed from host */ +typedef struct WASMAnyrefObject { + /* bits[1] must be 1, denotes an anyref object */ + WASMObjectHeader header; + const void *host_obj; +} WASMAnyrefObject, *WASMAnyrefObjectRef; + +/** + * Representation of WASM i31 objects, the lowest bit is 1: + * for a pointer of WASMObjectRef, if the lowest bit is 1, then it is an + * i31 object and bits[1..31] stores the actual i31 value, otherwise + * it is a normal object of rtt/externref/struct/array/func */ +typedef uintptr_t WASMI31ObjectRef; + +/* Representation of WASM struct objects */ +typedef struct WASMStructObject { + /* Must be pointer of WASMRttObject of struct type */ + WASMObjectHeader header; + uint8 field_data[1]; +} WASMStructObject, *WASMStructObjectRef; + +/* Representation of WASM array objects */ +typedef struct WASMArrayObject { + /* Must be pointer of WASMRttObject of array type */ + WASMObjectHeader header; + /* ( << 2) | , + * elem_count = lenght >> 2 + * elem_size = 2 ^ (length & 0x3) + */ + uint32 length; + uint8 elem_data[1]; +} WASMArrayObject, *WASMArrayObjectRef; + +#define WASM_ARRAY_LENGTH_SHIFT 2 +#define WASM_ARRAY_ELEM_SIZE_MASK 3 + +/* Representation of WASM function objects */ +typedef struct WASMFuncObject { + /* must be pointer of WASMRttObject of func type */ + WASMObjectHeader header; + uint32 func_idx_bound; +} WASMFuncObject, *WASMFuncObjectRef; + +/* Representation of WASM stringref objects */ +typedef struct WASMStringrefObject { + WASMObjectHeader header; + const void *str_obj; +} WASMStringrefObject, *WASMStringrefObjectRef; + +typedef struct WASMStringviewWTF8Object { + WASMObjectHeader header; + const void *str_obj; +} WASMStringviewWTF8Object, *WASMStringviewWTF8ObjectRef; + +typedef struct WASMStringviewWTF16Object { + WASMObjectHeader header; + const void *str_obj; +} WASMStringviewWTF16Object, *WASMStringviewWTF16ObjectRef; + +typedef struct WASMStringviewIterObject { + WASMObjectHeader header; + const void *str_obj; + int32 pos; +} WASMStringviewIterObject, *WASMStringviewIterObjectRef; + +struct WASMExecEnv; + +inline static WASMObjectHeader +wasm_object_header(const WASMObjectRef obj) +{ + return (obj->header & WASM_OBJ_HEADER_MASK); +} + +WASMRttTypeRef +wasm_rtt_type_new(WASMType *defined_type, uint32 defined_type_idx, + WASMRttType **rtt_types, uint32 rtt_type_count, + korp_mutex *rtt_type_lock); + +inline static WASMType * +wasm_rtt_type_get_defined_type(const WASMRttTypeRef rtt_type) +{ + return rtt_type->defined_type; +} + +WASMStructObjectRef +wasm_struct_obj_new_internal(void *heap_handle, WASMRttTypeRef rtt_type); + +WASMStructObjectRef +wasm_struct_obj_new(struct WASMExecEnv *exec_env, WASMRttTypeRef rtt_type); + +void +wasm_struct_obj_set_field(WASMStructObjectRef struct_obj, uint32 field_idx, + const WASMValue *value); + +void +wasm_struct_obj_get_field(const WASMStructObjectRef struct_obj, + uint32 field_idx, bool sign_extend, WASMValue *value); + +WASMArrayObjectRef +wasm_array_obj_new_internal(void *heap_handle, WASMRttTypeRef rtt_type, + uint32 length, WASMValue *init_value); + +WASMArrayObjectRef +wasm_array_obj_new(struct WASMExecEnv *exec_env, WASMRttTypeRef rtt_type, + uint32 length, WASMValue *init_value); + +void +wasm_array_obj_set_elem(WASMArrayObjectRef array_obj, uint32 elem_idx, + const WASMValue *value); + +void +wasm_array_obj_get_elem(const WASMArrayObjectRef array_obj, uint32 elem_idx, + bool sign_extend, WASMValue *value); + +void +wasm_array_obj_fill(const WASMArrayObjectRef array_obj, uint32 elem_idx, + uint32 len, WASMValue *value); + +void +wasm_array_obj_copy(WASMArrayObjectRef dst_obj, uint32 dst_idx, + WASMArrayObjectRef src_obj, uint32 src_idx, uint32 len); + +/** + * Return the logarithm of the size of array element. + * + * @param array the WASM array object + * + * @return log(size of the array element) + */ +inline static uint32 +wasm_array_obj_elem_size_log(const WASMArrayObjectRef array_obj) +{ + return (array_obj->length & WASM_ARRAY_ELEM_SIZE_MASK); +} + +/** + * Return the length of the array. + * + * @param array_obj the WASM array object + * + * @return the length of the array + */ +uint32 +wasm_array_obj_length(const WASMArrayObjectRef array_obj); + +/** + * Return the address of the first element of an array object. + * + * @param array_obj the WASM array object + * + * @return the address of the first element of the array object + */ +void * +wasm_array_obj_first_elem_addr(const WASMArrayObjectRef array_obj); + +/** + * Return the address of the i-th element of an array object. + * + * @param array_obj the WASM array object + * @param index the index of the element + * + * @return the address of the i-th element of the array object + */ +void * +wasm_array_obj_elem_addr(const WASMArrayObjectRef array_obj, uint32 elem_idx); + +WASMFuncObjectRef +wasm_func_obj_new_internal(void *heap_handle, WASMRttTypeRef rtt_type, + uint32 func_idx_bound); + +WASMFuncObjectRef +wasm_func_obj_new(struct WASMExecEnv *exec_env, WASMRttTypeRef rtt_type, + uint32 func_idx_bound); + +uint32 +wasm_func_obj_get_func_idx_bound(const WASMFuncObjectRef func_obj); + +WASMFuncType * +wasm_func_obj_get_func_type(const WASMFuncObjectRef func_obj); + +WASMExternrefObjectRef +wasm_externref_obj_new(struct WASMExecEnv *exec_env, const void *host_obj); + +WASMAnyrefObjectRef +wasm_anyref_obj_new(struct WASMExecEnv *exec_env, const void *host_obj); + +/* Implementation of opcode extern.internalize */ +WASMObjectRef +wasm_externref_obj_to_internal_obj(const WASMExternrefObjectRef externref_obj); + +/* Implementation of opcode extern.externalize */ +WASMExternrefObjectRef +wasm_internal_obj_to_externref_obj(struct WASMExecEnv *exec_env, + const WASMObjectRef internal_obj); + +const void * +wasm_anyref_obj_get_value(const WASMAnyrefObjectRef anyref_obj); + +const void * +wasm_externref_obj_get_value(const WASMExternrefObjectRef externref_obj); + +WASMI31ObjectRef +wasm_i31_obj_new(uint32 i31_value); + +uint32 +wasm_i31_obj_get_value(WASMI31ObjectRef i31_obj, bool sign_extend); + +bool +wasm_obj_is_i31_obj(WASMObjectRef obj); + +bool +wasm_obj_is_externref_obj(WASMObjectRef obj); + +bool +wasm_obj_is_anyref_obj(WASMObjectRef obj); + +bool +wasm_obj_is_i31_externref_or_anyref_obj(WASMObjectRef obj); + +bool +wasm_obj_is_struct_obj(WASMObjectRef obj); + +bool +wasm_obj_is_array_obj(WASMObjectRef obj); + +bool +wasm_obj_is_func_obj(WASMObjectRef obj); + +bool +wasm_obj_is_internal_obj(WASMObjectRef obj); + +bool +wasm_obj_is_eq_obj(WASMObjectRef obj); + +inline static bool +wasm_obj_is_null_obj(WASMObjectRef obj) +{ + return obj == NULL_REF ? true : false; +} + +inline static bool +wasm_obj_is_created_from_heap(WASMObjectRef obj) +{ + if (obj == NULL || (((uintptr_t)obj) & 1)) + /* null object or i31 object */ + return false; + return true; +} + +bool +wasm_obj_is_instance_of(WASMObjectRef obj, uint32 type_idx, WASMType **types, + uint32 type_count); + +bool +wasm_obj_is_type_of(WASMObjectRef obj, int32 heap_type); + +bool +wasm_obj_equal(WASMObjectRef obj1, WASMObjectRef obj2); + +bool +wasm_object_get_ref_list(WASMObjectRef obj, bool *p_is_compact_mode, + uint32 *p_ref_num, uint16 **p_ref_list, + uint32 *p_ref_start_offset); + +#if WASM_ENABLE_STRINGREF != 0 +WASMStringrefObjectRef +wasm_stringref_obj_new(struct WASMExecEnv *exec_env, const void *str_obj); + +WASMStringviewWTF8ObjectRef +wasm_stringview_wtf8_obj_new(struct WASMExecEnv *exec_env, const void *str_obj); + +WASMStringviewWTF16ObjectRef +wasm_stringview_wtf16_obj_new(struct WASMExecEnv *exec_env, + const void *str_obj); + +WASMStringviewIterObjectRef +wasm_stringview_iter_obj_new(struct WASMExecEnv *exec_env, const void *str_obj, + int32 pos); + +const void * +wasm_stringref_obj_get_value(WASMStringrefObjectRef stringref_obj); + +const void * +wasm_stringview_wtf8_obj_get_value( + WASMStringviewWTF8ObjectRef stringview_wtf8_obj); + +const void * +wasm_stringview_wtf16_obj_get_value( + WASMStringviewWTF16ObjectRef stringview_wtf16_obj); + +const void * +wasm_stringview_iter_obj_get_value( + WASMStringviewIterObjectRef stringview_iter_obj); + +int32 +wasm_stringview_iter_obj_get_pos( + WASMStringviewIterObjectRef stringview_iter_obj); + +void +wasm_stringview_iter_obj_update_pos( + WASMStringviewIterObjectRef stringview_iter_obj, int32 pos); + +bool +wasm_obj_is_stringref_obj(WASMObjectRef obj); + +bool +wasm_obj_is_stringview_wtf8_obj(WASMObjectRef obj); + +bool +wasm_obj_is_stringview_wtf16_obj(WASMObjectRef obj); +#endif /* end of WASM_ENABLE_STRINGREF != 0 */ + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif + +#endif /* end of _GC_OBJECT_H_ */ diff --git a/core/iwasm/common/gc/gc_type.c b/core/iwasm/common/gc/gc_type.c new file mode 100644 index 000000000..0c9271c87 --- /dev/null +++ b/core/iwasm/common/gc/gc_type.c @@ -0,0 +1,1253 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include "gc_type.h" + +void +wasm_dump_value_type(uint8 type, const WASMRefType *ref_type) +{ + switch (type) { + case VALUE_TYPE_I32: + os_printf("i32"); + break; + case VALUE_TYPE_I64: + os_printf("i64"); + break; + case VALUE_TYPE_F32: + os_printf("f32"); + break; + case VALUE_TYPE_F64: + os_printf("f64"); + break; + case VALUE_TYPE_V128: + os_printf("v128"); + break; + case PACKED_TYPE_I8: + os_printf("i8"); + break; + case PACKED_TYPE_I16: + os_printf("i16"); + break; + case REF_TYPE_FUNCREF: + os_printf("funcref"); + break; + case REF_TYPE_EXTERNREF: + os_printf("externref"); + break; + case REF_TYPE_ANYREF: + os_printf("anyref"); + break; + case REF_TYPE_EQREF: + os_printf("eqref"); + break; + case REF_TYPE_HT_NULLABLE: + case REF_TYPE_HT_NON_NULLABLE: + { + os_printf("(ref "); + if (ref_type->ref_ht_common.nullable) + os_printf("null "); + if (wasm_is_refheaptype_common(&ref_type->ref_ht_common)) { + switch (ref_type->ref_ht_common.heap_type) { + case HEAP_TYPE_FUNC: + os_printf("func"); + break; + case HEAP_TYPE_EXTERN: + os_printf("extern"); + break; + case HEAP_TYPE_ANY: + os_printf("any"); + break; + case HEAP_TYPE_EQ: + os_printf("eq"); + break; + case HEAP_TYPE_I31: + os_printf("i31"); + break; + case HEAP_TYPE_STRUCT: + os_printf("struct"); + break; + case HEAP_TYPE_ARRAY: + os_printf("array"); + break; + case HEAP_TYPE_NONE: + os_printf("none"); + break; + case HEAP_TYPE_NOFUNC: + os_printf("nofunc"); + break; + case HEAP_TYPE_NOEXTERN: + os_printf("noextern"); + break; + default: + bh_assert(0); + break; + } + } + else if (wasm_is_refheaptype_typeidx(&ref_type->ref_ht_common)) { + os_printf("%" PRId32, ref_type->ref_ht_typeidx.type_idx); + } + else { + bh_assert(0); + } + os_printf(")"); + break; + } + case REF_TYPE_I31REF: + os_printf("i31ref"); + break; + case REF_TYPE_STRUCTREF: + os_printf("structref"); + break; + case REF_TYPE_ARRAYREF: + os_printf("arrayref"); + break; + case REF_TYPE_NULLREF: + os_printf("nullref"); + break; + case REF_TYPE_NULLFUNCREF: + os_printf("nullfuncref"); + break; + case REF_TYPE_NULLEXTERNREF: + os_printf("nullexternref"); + break; + default: + bh_assert(0); + } +} + +void +wasm_dump_func_type(const WASMFuncType *type) +{ + uint32 i, j = 0; + const WASMRefType *ref_type = NULL; + + if (type->base_type.parent_type_idx != (uint32)-1) { + if (!type->base_type.is_sub_final) + os_printf("sub "); + else + os_printf("sub final "); + os_printf("%" PRIu32 " ", type->base_type.parent_type_idx); + } + + os_printf("func ["); + + for (i = 0; i < type->param_count; i++) { + if (wasm_is_type_multi_byte_type(type->types[i])) { + bh_assert(j < type->ref_type_map_count); + bh_assert(i == type->ref_type_maps[j].index); + ref_type = type->ref_type_maps[j++].ref_type; + } + else + ref_type = NULL; + wasm_dump_value_type(type->types[i], ref_type); + if (i < (uint32)type->param_count - 1) + os_printf(" "); + } + + os_printf("] -> ["); + + for (; i < type->param_count + type->result_count; i++) { + if (wasm_is_type_multi_byte_type(type->types[i])) { + bh_assert(j < type->ref_type_map_count); + bh_assert(i == type->ref_type_maps[j].index); + ref_type = type->ref_type_maps[j++].ref_type; + } + else + ref_type = NULL; + wasm_dump_value_type(type->types[i], ref_type); + if (i < (uint32)type->param_count + type->result_count - 1) + os_printf(" "); + } + + os_printf("]\n"); +} + +void +wasm_dump_struct_type(const WASMStructType *type) +{ + uint32 i, j = 0; + const WASMRefType *ref_type = NULL; + + if (type->base_type.parent_type_idx != (uint32)-1) { + if (!type->base_type.is_sub_final) + os_printf("sub "); + else + os_printf("sub final "); + os_printf("%" PRIu32 " ", type->base_type.parent_type_idx); + } + + os_printf("struct"); + + for (i = 0; i < type->field_count; i++) { + os_printf(" (field "); + if (type->fields[i].field_flags & 1) + os_printf("(mut "); + if (wasm_is_type_multi_byte_type(type->fields[i].field_type)) { + bh_assert(j < type->ref_type_map_count); + bh_assert(i == type->ref_type_maps[j].index); + ref_type = type->ref_type_maps[j++].ref_type; + } + else + ref_type = NULL; + wasm_dump_value_type(type->fields[i].field_type, ref_type); + if (type->fields[i].field_flags & 1) + os_printf(")"); + os_printf(")"); + } + + os_printf("\n"); +} + +void +wasm_dump_array_type(const WASMArrayType *type) +{ + if (type->base_type.parent_type_idx != (uint32)-1) { + if (!type->base_type.is_sub_final) + os_printf("sub "); + else + os_printf("sub final "); + os_printf("%" PRIu32 " ", type->base_type.parent_type_idx); + } + + os_printf("array "); + + if (type->elem_flags & 1) + os_printf("(mut "); + wasm_dump_value_type(type->elem_type, type->elem_ref_type); + if (type->elem_flags & 1) + os_printf(")"); + os_printf("\n"); +} + +bool +wasm_value_types_is_subtype_of(const uint8 *types1, + const WASMRefTypeMap *ref_type_maps1, + const uint8 *types2, + const WASMRefTypeMap *ref_type_maps2, + uint32 value_type_count, + const WASMTypePtr *types, uint32 type_count) +{ + uint32 i; + WASMRefType *ref_type1, *ref_type2; + + for (i = 0; i < value_type_count; i++) { + ref_type1 = ref_type2 = NULL; + if (wasm_is_type_multi_byte_type(types1[i])) { + ref_type1 = ref_type_maps1->ref_type; + ref_type_maps1++; + } + if (wasm_is_type_multi_byte_type(types2[i])) { + ref_type2 = ref_type_maps2->ref_type; + ref_type_maps2++; + } + if (!wasm_reftype_is_subtype_of(types1[i], ref_type1, types2[i], + ref_type2, types, type_count)) { + return false; + } + } + return true; +} + +bool +wasm_func_type_equal(const WASMFuncType *type1, const WASMFuncType *type2, + const WASMTypePtr *types, uint32 type_count) +{ + uint32 i, j = 0; + + if (type1 == type2) + return true; + + if (type1->param_count != type2->param_count + || type1->result_count != type2->result_count + || type1->ref_type_map_count != type2->ref_type_map_count) + return false; + + for (i = 0; i < type1->param_count + type1->result_count; i++) { + if (type1->types[i] != type2->types[i]) + return false; + + if (wasm_is_type_multi_byte_type(type1->types[i])) { + const WASMRefType *ref_type1, *ref_type2; + + bh_assert(j < type1->ref_type_map_count); + bh_assert(i == type1->ref_type_maps[j].index + && i == type2->ref_type_maps[j].index); + + ref_type1 = type1->ref_type_maps[j].ref_type; + ref_type2 = type2->ref_type_maps[j].ref_type; + if (!wasm_reftype_equal(ref_type1->ref_type, ref_type1, + ref_type2->ref_type, ref_type2, types, + type_count)) + return false; + + j++; + } + } + + return true; +} + +bool +wasm_struct_type_equal(const WASMStructType *type1, const WASMStructType *type2, + const WASMTypePtr *types, uint32 type_count) +{ + uint32 i, j = 0; + + if (type1 == type2) + return true; + + if (type1->field_count != type2->field_count + || type1->ref_type_map_count != type2->ref_type_map_count) + return false; + + for (i = 0; i < type1->field_count; i++) { + if (type1->fields[i].field_type != type2->fields[i].field_type + || type1->fields[i].field_flags != type2->fields[i].field_flags) + return false; + + if (wasm_is_type_multi_byte_type(type1->fields[i].field_type)) { + const WASMRefType *ref_type1, *ref_type2; + + bh_assert(j < type1->ref_type_map_count); + bh_assert(i == type1->ref_type_maps[j].index + && i == type2->ref_type_maps[j].index); + + ref_type1 = type1->ref_type_maps[j].ref_type; + ref_type2 = type2->ref_type_maps[j].ref_type; + if (!wasm_reftype_equal(ref_type1->ref_type, ref_type1, + ref_type2->ref_type, ref_type2, types, + type_count)) + return false; + + j++; + } + } + + return true; +} + +bool +wasm_array_type_equal(const WASMArrayType *type1, const WASMArrayType *type2, + const WASMTypePtr *types, uint32 type_count) +{ + if (type1 == type2) + return true; + + if (type1->elem_flags != type2->elem_flags) + return false; + + return wasm_reftype_equal(type1->elem_type, type1->elem_ref_type, + type2->elem_type, type2->elem_ref_type, types, + type_count); +} + +bool +wasm_type_equal(const WASMType *type1, const WASMType *type2, + const WASMTypePtr *types, uint32 type_count) +{ + if (type1 == type2) + return true; + + if (type1->type_flag != type2->type_flag) + return false; + + if (wasm_type_is_func_type(type1)) + return wasm_func_type_equal((WASMFuncType *)type1, + (WASMFuncType *)type2, types, type_count); + else if (wasm_type_is_struct_type(type1)) + return wasm_struct_type_equal((WASMStructType *)type1, + (WASMStructType *)type2, types, + type_count); + else if (wasm_type_is_array_type(type1)) + return wasm_array_type_equal((WASMArrayType *)type1, + (WASMArrayType *)type2, types, type_count); + + bh_assert(0); + return false; +} + +bool +wasm_func_type_is_subtype_of(const WASMFuncType *type1, + const WASMFuncType *type2, + const WASMTypePtr *types, uint32 type_count) +{ + const WASMRefType *ref_type1 = NULL, *ref_type2 = NULL; + uint32 i, j1 = 0, j2 = 0; + + if (type1 == type2) + return true; + + if (type1->param_count != type2->param_count + || type1->result_count != type2->result_count) + return false; + + for (i = 0; i < type1->param_count; i++) { + if (wasm_is_type_multi_byte_type(type1->types[i])) { + bh_assert(j1 < type1->ref_type_map_count); + ref_type1 = type1->ref_type_maps[j1++].ref_type; + } + if (wasm_is_type_multi_byte_type(type2->types[i])) { + bh_assert(j2 < type2->ref_type_map_count); + ref_type2 = type2->ref_type_maps[j2++].ref_type; + } + if (!wasm_reftype_is_subtype_of(type2->types[i], ref_type2, + type1->types[i], ref_type1, types, + type_count)) { + return false; + } + } + + for (; i < type1->param_count + type1->result_count; i++) { + if (wasm_is_type_multi_byte_type(type1->types[i])) { + bh_assert(j1 < type1->ref_type_map_count); + ref_type1 = type1->ref_type_maps[j1++].ref_type; + } + if (wasm_is_type_multi_byte_type(type2->types[i])) { + bh_assert(j2 < type2->ref_type_map_count); + ref_type2 = type2->ref_type_maps[j2++].ref_type; + } + if (!wasm_reftype_is_subtype_of(type1->types[i], ref_type1, + type2->types[i], ref_type2, types, + type_count)) { + return false; + } + } + + return true; +} + +bool +wasm_func_type_result_is_subtype_of(const WASMFuncType *type1, + const WASMFuncType *type2, + const WASMTypePtr *types, uint32 type_count) +{ + const WASMRefType *ref_type1 = NULL, *ref_type2 = NULL; + const WASMRefTypeMap *ref_type_map1, *ref_type_map2; + uint32 i; + + if (type1 == type2) + return true; + + if (type1->result_count != type2->result_count) + return false; + + ref_type_map1 = type1->result_ref_type_maps; + ref_type_map2 = type2->result_ref_type_maps; + + for (i = 0; i < type1->result_count; i++) { + ref_type1 = ref_type2 = NULL; + if (wasm_is_type_multi_byte_type( + type1->types[type1->param_count + i])) { + bh_assert(ref_type_map1 + && ref_type_map1->index == type1->param_count + i); + ref_type1 = ref_type_map1->ref_type; + ref_type_map1++; + } + if (wasm_is_type_multi_byte_type( + type2->types[type2->param_count + i])) { + bh_assert(ref_type_map2 + && ref_type_map2->index == type1->param_count + i); + ref_type2 = ref_type_map2->ref_type; + ref_type_map2++; + } + if (!wasm_reftype_is_subtype_of(type1->types[type1->param_count + i], + ref_type1, + type2->types[type2->param_count + i], + ref_type2, types, type_count)) { + return false; + } + } + return true; +} + +bool +wasm_struct_type_is_subtype_of(const WASMStructType *type1, + const WASMStructType *type2, + const WASMTypePtr *types, uint32 type_count) +{ + const WASMRefType *ref_type1 = NULL, *ref_type2 = NULL; + uint32 i, j1 = 0, j2 = 0; + + /** + * A structure type is a supertype of another structure type if + * its field list is a prefix of the other (width subtyping). + * A structure type also is a supertype of another structure type + * if they have the same fields and for each field type: + * The field is mutable in both types and the storage types + * are the same. + * The field is immutable in both types and their storage types + * are in (covariant) subtype relation (depth subtyping). + */ + + if (type1 == type2) + return true; + + if (type1->field_count > type2->field_count) { + /* Check whether type1's field list is a prefix of type2 */ + for (i = 0; i < type2->field_count; i++) { + if (type1->fields[i].field_flags != type2->fields[i].field_flags) + return false; + if (wasm_is_type_multi_byte_type(type1->fields[i].field_type)) { + bh_assert(j1 < type1->ref_type_map_count); + ref_type1 = type1->ref_type_maps[j1++].ref_type; + } + if (wasm_is_type_multi_byte_type(type2->fields[i].field_type)) { + bh_assert(j2 < type2->ref_type_map_count); + ref_type2 = type2->ref_type_maps[j2++].ref_type; + } + if (!wasm_reftype_is_subtype_of(type1->fields[i].field_type, + ref_type1, + type2->fields[i].field_type, + ref_type2, types, type_count)) { + return false; + } + } + return true; + } + else if (type1->field_count == type2->field_count) { + /* Check each field's flag and type */ + for (i = 0; i < type1->field_count; i++) { + if (type1->fields[i].field_flags != type2->fields[i].field_flags) + return false; + + if (type1->fields[i].field_flags & 1) { + /* The field is mutable in both types: the storage types + must be the same */ + if (type1->fields[i].field_type != type2->fields[i].field_type) + return false; + if (wasm_is_type_multi_byte_type(type1->fields[i].field_type)) { + bh_assert(j1 < type1->ref_type_map_count); + bh_assert(j2 < type2->ref_type_map_count); + ref_type1 = type1->ref_type_maps[j1++].ref_type; + ref_type2 = type2->ref_type_maps[j2++].ref_type; + if (!wasm_reftype_equal(ref_type1->ref_type, ref_type1, + ref_type2->ref_type, ref_type2, + types, type_count)) + return false; + } + } + else { + /* The field is immutable in both types: their storage types + must be in (covariant) subtype relation (depth subtyping) */ + if (wasm_is_type_multi_byte_type(type1->fields[i].field_type)) { + bh_assert(j1 < type1->ref_type_map_count); + ref_type1 = type1->ref_type_maps[j1++].ref_type; + } + if (wasm_is_type_multi_byte_type(type2->fields[i].field_type)) { + bh_assert(j2 < type2->ref_type_map_count); + ref_type2 = type2->ref_type_maps[j2++].ref_type; + } + if (!wasm_reftype_is_subtype_of(type1->fields[i].field_type, + ref_type1, + type2->fields[i].field_type, + ref_type2, types, type_count)) + return false; + } + } + return true; + } + + return false; +} + +bool +wasm_array_type_is_subtype_of(const WASMArrayType *type1, + const WASMArrayType *type2, + const WASMTypePtr *types, uint32 type_count) +{ + /** + * An array type is a supertype of another array type if: + * Both element types are mutable and the storage types are the same. + * Both element types are immutable and their storage types are in + * (covariant) subtype relation (depth subtyping). + */ + + if (type1->elem_flags != type2->elem_flags) + return false; + + if (type1->elem_flags & 1) { + /* The elem is mutable in both types: the storage types + must be the same */ + return wasm_reftype_equal(type1->elem_type, type1->elem_ref_type, + type2->elem_type, type2->elem_ref_type, types, + type_count); + } + else { + /* The elem is immutable in both types: their storage types + must be in (covariant) subtype relation (depth subtyping) */ + return wasm_reftype_is_subtype_of( + type1->elem_type, type1->elem_ref_type, type2->elem_type, + type2->elem_ref_type, types, type_count); + } + return false; +} + +bool +wasm_type_is_subtype_of(const WASMType *type1, const WASMType *type2, + const WASMTypePtr *types, uint32 type_count) +{ + if (type1 == type2) + return true; + + if (type1->type_flag != type2->type_flag) + return false; + + if (wasm_type_is_func_type(type1)) + return wasm_func_type_is_subtype_of( + (WASMFuncType *)type1, (WASMFuncType *)type2, types, type_count); + else if (wasm_type_is_struct_type(type1)) + return wasm_struct_type_is_subtype_of((WASMStructType *)type1, + (WASMStructType *)type2, types, + type_count); + else if (wasm_type_is_array_type(type1)) + return wasm_array_type_is_subtype_of( + (WASMArrayType *)type1, (WASMArrayType *)type2, types, type_count); + + bh_assert(0); + return false; +} + +uint32 +wasm_reftype_size(uint8 type) +{ + if (type == VALUE_TYPE_I32 || type == VALUE_TYPE_F32) + return 4; + else if (type == VALUE_TYPE_I64 || type == VALUE_TYPE_F64) + return 8; + else if ((type >= (uint8)REF_TYPE_ARRAYREF + && type <= (uint8)REF_TYPE_NULLFUNCREF) + || (type >= (uint8)REF_TYPE_HT_NULLABLE + && type <= (uint8)REF_TYPE_HT_NON_NULLABLE) +#if WASM_ENABLE_STRINGREF != 0 + || (type >= (uint8)REF_TYPE_STRINGVIEWWTF8 + && type <= (uint8)REF_TYPE_STRINGREF) + || (type >= (uint8)REF_TYPE_STRINGVIEWITER + && type <= (uint8)REF_TYPE_STRINGVIEWWTF16) +#endif + ) + return sizeof(uintptr_t); + else if (type == PACKED_TYPE_I8) + return 1; + else if (type == PACKED_TYPE_I16) + return 2; + else if (type == VALUE_TYPE_V128) + return 16; + else { + bh_assert(0); + return 0; + } + + return 0; +} + +uint32 +wasm_reftype_struct_size(const WASMRefType *ref_type) +{ + bh_assert(wasm_is_reftype_htref_nullable(ref_type->ref_type) + || wasm_is_reftype_htref_non_nullable(ref_type->ref_type)); + bh_assert(wasm_is_refheaptype_typeidx(&ref_type->ref_ht_common) + || wasm_is_refheaptype_common(&ref_type->ref_ht_common)); + + return (uint32)sizeof(RefHeapType_Common); +} + +static bool +type_idx_equal(uint32 type_idx1, uint32 type_idx2) +{ + return (type_idx1 == type_idx2) ? true : false; +} + +bool +wasm_refheaptype_equal(const RefHeapType_Common *ref_heap_type1, + const RefHeapType_Common *ref_heap_type2, + const WASMTypePtr *types, uint32 type_count) +{ + if (ref_heap_type1 == ref_heap_type2) + return true; + + if (ref_heap_type1->ref_type != ref_heap_type2->ref_type) + return false; + + if (ref_heap_type1->heap_type != ref_heap_type2->heap_type) { + if (wasm_is_refheaptype_typeidx(ref_heap_type1) + && wasm_is_refheaptype_typeidx(ref_heap_type2)) { + return type_idx_equal(ref_heap_type1->heap_type, + ref_heap_type2->heap_type); + } + return false; + } + + /* No need to check extra info for common types and (type i) + as their heap_types are the same */ + return true; +} + +bool +wasm_reftype_equal(uint8 type1, const WASMRefType *reftype1, uint8 type2, + const WASMRefType *reftype2, const WASMTypePtr *types, + uint32 type_count) +{ + /* For (ref null func/extern/any/eq/i31/struct/array/none/nofunc/noextern), + they are same as funcref/externref/anyref/eqref/i31ref/structref/arayref/ + nullref/nullfuncref/nullexternref, and have been converted into to the + related one-byte type when loading, so here we don't consider the + situations again: + one is (ref null func/extern/any/eq/i31/struct/array/..), + the other is + funcref/externref/anyref/eqref/i31ref/structref/arrayref/.. */ + if (type1 != type2) + return false; + + if (!wasm_is_type_multi_byte_type(type1)) + /* one byte type */ + return true; + + bh_assert(type1 == (uint8)REF_TYPE_HT_NULLABLE + || type1 == (uint8)REF_TYPE_HT_NON_NULLABLE); + + /* (ref null ht) or (ref ht) */ + return wasm_refheaptype_equal((RefHeapType_Common *)reftype1, + (RefHeapType_Common *)reftype2, types, + type_count); +} + +inline static bool +wasm_is_reftype_supers_of_eq(uint8 type) +{ + return (type == REF_TYPE_EQREF || type == REF_TYPE_ANYREF) ? true : false; +} + +inline static bool +wasm_is_reftype_supers_of_i31(uint8 type) +{ + return (type == REF_TYPE_I31REF || wasm_is_reftype_supers_of_eq(type)) + ? true + : false; +} + +inline static bool +wasm_is_reftype_supers_of_struct(uint8 type) +{ + return (type == REF_TYPE_STRUCTREF || wasm_is_reftype_supers_of_eq(type)) + ? true + : false; +} + +inline static bool +wasm_is_reftype_supers_of_array(uint8 type) +{ + return (type == REF_TYPE_ARRAYREF || wasm_is_reftype_supers_of_eq(type)) + ? true + : false; +} + +inline static bool +wasm_is_reftype_supers_of_func(uint8 type) +{ + return (type == REF_TYPE_FUNCREF) ? true : false; +} + +inline static bool +wasm_is_reftype_supers_of_extern(uint8 type) +{ + return (type == REF_TYPE_EXTERNREF) ? true : false; +} + +#if WASM_ENABLE_STRINGREF != 0 +inline static bool +wasm_is_reftype_supers_of_string(uint8 type) +{ + return (type == REF_TYPE_STRINGREF || type == REF_TYPE_ANYREF) ? true + : false; +} +#endif + +inline static bool +wasm_is_reftype_supers_of_none(uint8 type, const WASMRefType *ref_type, + const WASMTypePtr *types, uint32 type_count) +{ + if (type == REF_TYPE_NULLREF || type == REF_TYPE_I31REF + || type == REF_TYPE_STRUCTREF || type == REF_TYPE_ARRAYREF + || wasm_is_reftype_supers_of_eq(type) +#if WASM_ENABLE_STRINGREF != 0 + || type == REF_TYPE_STRINGREF +#endif + ) + return true; + + if (type == REF_TYPE_HT_NULLABLE && ref_type != NULL + && wasm_is_refheaptype_typeidx(&ref_type->ref_ht_common) + && (types[ref_type->ref_ht_typeidx.type_idx]->type_flag + == WASM_TYPE_STRUCT + || types[ref_type->ref_ht_typeidx.type_idx]->type_flag + == WASM_TYPE_ARRAY)) + return true; + + return false; +} + +inline static bool +wasm_is_reftype_supers_of_nofunc(uint8 type, const WASMRefType *ref_type, + const WASMTypePtr *types, uint32 type_count) +{ + if (type == REF_TYPE_NULLFUNCREF || type == REF_TYPE_FUNCREF) + return true; + + if (type == REF_TYPE_HT_NULLABLE && ref_type != NULL + && wasm_is_refheaptype_typeidx(&ref_type->ref_ht_common) + && (types[ref_type->ref_ht_typeidx.type_idx]->type_flag + == WASM_TYPE_FUNC)) + return true; + + return false; +} + +inline static bool +wasm_is_reftype_supers_of_noextern(uint8 type) +{ + return (type == REF_TYPE_NULLEXTERNREF || type == REF_TYPE_EXTERNREF) + ? true + : false; +} + +/* Whether type1 is one of super types of type2 */ +static bool +wasm_type_is_supers_of(const WASMType *type1, const WASMType *type2) +{ + uint32 i, inherit_depth_diff; + + if (type1 == type2) + return true; + + if (!(type1->root_type == type2->root_type + && type1->inherit_depth < type2->inherit_depth)) + return false; + + inherit_depth_diff = type2->inherit_depth - type1->inherit_depth; + for (i = 0; i < inherit_depth_diff; i++) { + type2 = type2->parent_type; + if (type2 == type1) + return true; + } + + return false; +} + +bool +wasm_reftype_is_subtype_of(uint8 type1, const WASMRefType *ref_type1, + uint8 type2, const WASMRefType *ref_type2, + const WASMTypePtr *types, uint32 type_count) +{ + if (type1 >= PACKED_TYPE_I16 && type1 <= VALUE_TYPE_I32) { + /* Primitive types (I32/I64/F32/F64/V128/I8/I16) are not + subtypes of each other */ + return type1 == type2 ? true : false; + } + + /** + * Check subtype relationship of two ref types, the ref type hierarchy can + * be described as: + * + * anyref -> eqref + * |-> i31ref + * |-> structref -> (ref null $t) -> (ref $t), $t is struct + * |-> arrayref -> (ref null $t) -> (ref $t), $t is array + * + * funcref -> (ref null $t) -> (ref $t), $t is func + * externref + */ + + if (type1 == REF_TYPE_ANYREF) { + /* any <: any */ + return type2 == REF_TYPE_ANYREF ? true : false; + } + else if (type1 == REF_TYPE_FUNCREF) { + /* func <: func */ + return type2 == REF_TYPE_FUNCREF ? true : false; + } + else if (type1 == REF_TYPE_EXTERNREF) { + /* extern <: extern */ + return type2 == REF_TYPE_EXTERNREF ? true : false; + } + else if (type1 == REF_TYPE_EQREF) { + /* eq <: [eq, any] */ + return wasm_is_reftype_supers_of_eq(type2); + } + else if (type1 == REF_TYPE_I31REF) { + /* i31 <: [i31, eq, any] */ + return wasm_is_reftype_supers_of_i31(type2); + } + else if (type1 == REF_TYPE_STRUCTREF) { + /* struct <: [struct, eq, any] */ + return wasm_is_reftype_supers_of_struct(type2); + } + else if (type1 == REF_TYPE_ARRAYREF) { + /* array <: [array, eq, any] */ + return wasm_is_reftype_supers_of_array(type2); + } + else if (type1 == REF_TYPE_NULLREF) { + return wasm_is_reftype_supers_of_none(type2, ref_type2, types, + type_count); + } + else if (type1 == REF_TYPE_NULLFUNCREF) { + return wasm_is_reftype_supers_of_nofunc(type2, ref_type2, types, + type_count); + } + else if (type1 == REF_TYPE_NULLEXTERNREF) { + return wasm_is_reftype_supers_of_noextern(type2); + } +#if WASM_ENABLE_STRINGREF != 0 + else if (type1 == REF_TYPE_STRINGREF) { + return wasm_is_reftype_supers_of_string(type2); + } + else if (type1 == REF_TYPE_STRINGVIEWWTF8) { + return type2 == REF_TYPE_STRINGVIEWWTF8 ? true : false; + } + else if (type1 == REF_TYPE_STRINGVIEWWTF16) { + return type2 == REF_TYPE_STRINGVIEWWTF16 ? true : false; + } + else if (type1 == REF_TYPE_STRINGVIEWITER) { + return type2 == REF_TYPE_STRINGVIEWITER ? true : false; + } +#endif + else if (type1 == REF_TYPE_HT_NULLABLE) { + if (wasm_is_refheaptype_typeidx(&ref_type1->ref_ht_common)) { + /* reftype1 is (ref null $t) */ + if (type2 == REF_TYPE_HT_NULLABLE && ref_type2 != NULL + && wasm_is_refheaptype_typeidx(&ref_type2->ref_ht_common)) { + return type_idx_equal(ref_type1->ref_ht_typeidx.type_idx, + ref_type2->ref_ht_typeidx.type_idx) + || wasm_type_is_supers_of( + types[ref_type2->ref_ht_typeidx.type_idx], + types[ref_type1->ref_ht_typeidx.type_idx]); + } + else if (types[ref_type1->ref_ht_typeidx.type_idx]->type_flag + == WASM_TYPE_STRUCT) + return wasm_is_reftype_supers_of_struct(type2); + else if (types[ref_type1->ref_ht_typeidx.type_idx]->type_flag + == WASM_TYPE_ARRAY) + return wasm_is_reftype_supers_of_array(type2); + else if (types[ref_type1->ref_ht_typeidx.type_idx]->type_flag + == WASM_TYPE_FUNC) + return wasm_is_reftype_supers_of_func(type2); +#if WASM_ENABLE_STRINGREF != 0 + else if (types[ref_type1->ref_ht_typeidx.type_idx]->type_flag + == WASM_TYPE_STRINGREF) + return wasm_is_reftype_supers_of_string(type2); + else if (types[ref_type1->ref_ht_typeidx.type_idx]->type_flag + == WASM_TYPE_STRINGVIEWWTF8) { + return type2 == REF_TYPE_STRINGVIEWWTF8 ? true : false; + } + else if (types[ref_type1->ref_ht_typeidx.type_idx]->type_flag + == WASM_TYPE_STRINGVIEWWTF16) { + return type2 == REF_TYPE_STRINGVIEWWTF16 ? true : false; + } + else if (types[ref_type1->ref_ht_typeidx.type_idx]->type_flag + == WASM_TYPE_STRINGVIEWITER) { + return type2 == REF_TYPE_STRINGVIEWITER ? true : false; + } +#endif + else + return false; + } + else { + /* (ref null func/extern/any/eq/i31/struct/array/..) have been + converted into + funcref/externref/anyref/eqref/i31ref/structref/arrayref/.. + when loading */ + bh_assert(0); + } + } + else if (type1 == REF_TYPE_HT_NON_NULLABLE) { + bh_assert(ref_type1); + if (wasm_is_refheaptype_typeidx(&ref_type1->ref_ht_common)) { + /* reftype1 is (ref $t) */ + if ((type2 == REF_TYPE_HT_NULLABLE + || type2 == REF_TYPE_HT_NON_NULLABLE) + && ref_type2 != NULL + && wasm_is_refheaptype_typeidx(&ref_type2->ref_ht_common)) { + return type_idx_equal(ref_type1->ref_ht_typeidx.type_idx, + ref_type2->ref_ht_typeidx.type_idx) + || wasm_type_is_supers_of( + types[ref_type2->ref_ht_typeidx.type_idx], + types[ref_type1->ref_ht_typeidx.type_idx]); + } + else if (types[ref_type1->ref_ht_typeidx.type_idx]->type_flag + == WASM_TYPE_STRUCT) { + /* the super type is (ref null struct) or (ref struct) */ + if (type2 == REF_TYPE_HT_NULLABLE + || type2 == REF_TYPE_HT_NON_NULLABLE) { + bh_assert(ref_type2); + uint8 ref_type = + (uint8)(ref_type2->ref_ht_common.heap_type + + REF_TYPE_FUNCREF - HEAP_TYPE_FUNC); + return wasm_is_reftype_supers_of_struct(ref_type); + } + else + /* the super type is structref or anyref */ + return wasm_is_reftype_supers_of_struct(type2); + } + else if (types[ref_type1->ref_ht_typeidx.type_idx]->type_flag + == WASM_TYPE_ARRAY) { + /* the super type is (ref null array) or (ref array) */ + if (type2 == REF_TYPE_HT_NULLABLE + || type2 == REF_TYPE_HT_NON_NULLABLE) { + bh_assert(ref_type2); + uint8 ref_type = + (uint8)(ref_type2->ref_ht_common.heap_type + + REF_TYPE_FUNCREF - HEAP_TYPE_FUNC); + return wasm_is_reftype_supers_of_array(ref_type); + } + else + /* the super type is arrayref, eqref or anyref */ + return wasm_is_reftype_supers_of_array(type2); + } + else if (types[ref_type1->ref_ht_typeidx.type_idx]->type_flag + == WASM_TYPE_FUNC) { + /* the super type is (ref null func) or (ref func) */ + if (type2 == REF_TYPE_HT_NULLABLE + || type2 == REF_TYPE_HT_NON_NULLABLE) { + bh_assert(ref_type2); + uint8 ref_type = + (uint8)(ref_type2->ref_ht_common.heap_type + + REF_TYPE_FUNCREF - HEAP_TYPE_FUNC); + return wasm_is_reftype_supers_of_func(ref_type); + } + else + /* the super type is funcref */ + return wasm_is_reftype_supers_of_func(type2); + } + else if (types[ref_type1->ref_ht_typeidx.type_idx]->type_flag + == REF_TYPE_I31REF) { + /* the super type is (ref null i31) or (ref i31) */ + if (type2 == REF_TYPE_HT_NULLABLE + || type2 == REF_TYPE_HT_NON_NULLABLE) { + bh_assert(ref_type2); + uint8 ref_type = + (uint8)(ref_type2->ref_ht_common.heap_type + + REF_TYPE_FUNCREF - HEAP_TYPE_FUNC); + return wasm_is_reftype_supers_of_i31(ref_type); + } + else + /* the super type is i31ref, eqref or anyref */ + return wasm_is_reftype_supers_of_i31(type2); + } + else { + return false; + } + } + else if (wasm_is_refheaptype_common(&ref_type1->ref_ht_common)) { + /* reftype1 is (ref func/extern/any/eq/i31/struct/array/..) */ + if (wasm_reftype_equal(type1, ref_type1, type2, ref_type2, types, + type_count)) + return true; + else { + int32 heap_type = ref_type1->ref_ht_common.heap_type; + if (heap_type == HEAP_TYPE_ANY) { + /* (ref any) <: anyref */ + return type2 == REF_TYPE_ANYREF ? true : false; + } + else if (heap_type == HEAP_TYPE_EXTERN) { + /* (ref extern) <: externref */ + return type2 == REF_TYPE_EXTERNREF ? true : false; + } + else if (heap_type == HEAP_TYPE_EQ) { + /* (ref eq) <: [eqref, anyref] */ + return wasm_is_reftype_supers_of_eq(type2); + } + else if (heap_type == HEAP_TYPE_I31) { + /* (ref i31) <: [i31ref, eqref, anyref] */ + return wasm_is_reftype_supers_of_i31(type2); + } + else if (heap_type == HEAP_TYPE_STRUCT) { + /* (ref struct) <: [structref, eqref, anyref] */ + return wasm_is_reftype_supers_of_struct(type2); + } + else if (heap_type == HEAP_TYPE_ARRAY) { + /* (ref array) <: [arrayref, eqref, anyref] */ + return wasm_is_reftype_supers_of_array(type2); + } + else if (heap_type == HEAP_TYPE_FUNC) { + /* (ref func) <: [funcref] */ + return wasm_is_reftype_supers_of_func(type2); + } +#if WASM_ENABLE_STRINGREF != 0 + else if (heap_type == HEAP_TYPE_STRINGREF) { + return wasm_is_reftype_supers_of_string(type2); + } + else if (heap_type == HEAP_TYPE_STRINGVIEWWTF8) { + return type2 == REF_TYPE_STRINGVIEWWTF8 ? true : false; + } + else if (heap_type == HEAP_TYPE_STRINGVIEWWTF16) { + return type2 == REF_TYPE_STRINGVIEWWTF16 ? true : false; + } + else if (heap_type == HEAP_TYPE_STRINGVIEWITER) { + return type2 == REF_TYPE_STRINGVIEWITER ? true : false; + } +#endif + else if (heap_type == HEAP_TYPE_NONE) { + /* (ref none) */ + /* TODO */ + bh_assert(0); + } + else if (heap_type == HEAP_TYPE_NOEXTERN) { + /* (ref noextern) */ + /* TODO */ + bh_assert(0); + } + else if (heap_type == HEAP_TYPE_NOFUNC) { + /* (ref nofunc) */ + /* TODO */ + bh_assert(0); + } + else { + bh_assert(0); + } + } + } + else { + /* unknown type detected */ + LOG_ERROR("unknown sub type 0x%02x", type1); + bh_assert(0); + } + } + else { + bh_assert(0); + } + + return false; +} + +static uint32 +reftype_hash(const void *key) +{ + WASMRefType *reftype = (WASMRefType *)key; + + switch (reftype->ref_type) { + case (uint8)REF_TYPE_HT_NULLABLE: + case (uint8)REF_TYPE_HT_NON_NULLABLE: + { + RefHeapType_Common *ref_heap_type = (RefHeapType_Common *)reftype; + + if (wasm_is_refheaptype_common(ref_heap_type) + /* type indexes of defined type are same */ + || wasm_is_refheaptype_typeidx(ref_heap_type)) { + return (uint32)reftype->ref_type + ^ (uint32)ref_heap_type->heap_type; + } + + break; + } + + default: + break; + } + + bh_assert(0); + return 0; +} + +static bool +reftype_equal(void *type1, void *type2) +{ + WASMRefType *reftype1 = (WASMRefType *)type1; + WASMRefType *reftype2 = (WASMRefType *)type2; + + return wasm_reftype_equal(reftype1->ref_type, reftype1, reftype2->ref_type, + reftype2, NULL, 0); +} + +WASMRefType * +wasm_reftype_dup(const WASMRefType *ref_type) +{ + if (wasm_is_reftype_htref_nullable(ref_type->ref_type) + || wasm_is_reftype_htref_non_nullable(ref_type->ref_type)) { + if (wasm_is_refheaptype_common(&ref_type->ref_ht_common) + || wasm_is_refheaptype_typeidx(&ref_type->ref_ht_common)) { + RefHeapType_Common *ht_common; + if (!(ht_common = wasm_runtime_malloc(sizeof(RefHeapType_Common)))) + return NULL; + + ht_common->ref_type = ref_type->ref_ht_common.ref_type; + ht_common->nullable = ref_type->ref_ht_common.nullable; + ht_common->heap_type = ref_type->ref_ht_common.heap_type; + return (WASMRefType *)ht_common; + } + } + + bh_assert(0); + return NULL; +} + +void +wasm_set_refheaptype_typeidx(RefHeapType_TypeIdx *ref_ht_typeidx, bool nullable, + int32 type_idx) +{ + ref_ht_typeidx->ref_type = + nullable ? REF_TYPE_HT_NULLABLE : REF_TYPE_HT_NON_NULLABLE; + ref_ht_typeidx->nullable = nullable; + ref_ht_typeidx->type_idx = type_idx; +} + +void +wasm_set_refheaptype_common(RefHeapType_Common *ref_ht_common, bool nullable, + int32 heap_type) +{ + ref_ht_common->ref_type = + nullable ? REF_TYPE_HT_NULLABLE : REF_TYPE_HT_NON_NULLABLE; + ref_ht_common->nullable = nullable; + ref_ht_common->heap_type = heap_type; +} + +WASMRefType * +wasm_reftype_map_find(WASMRefTypeMap *ref_type_maps, uint32 ref_type_map_count, + uint32 index_to_find) +{ + int low = 0, mid; + int high = (int32)ref_type_map_count - 1; + uint32 index; + + while (low <= high) { + mid = (low + high) / 2; + index = ref_type_maps[mid].index; + if (index_to_find == index) { + return ref_type_maps[mid].ref_type; + } + else if (index_to_find < index) + high = mid - 1; + else + low = mid + 1; + } + + return NULL; +} + +HashMap * +wasm_reftype_set_create(uint32 size) +{ + HashMap *ref_type_set = bh_hash_map_create( + size, false, reftype_hash, reftype_equal, NULL, wasm_runtime_free); + + return ref_type_set; +} + +WASMRefType * +wasm_reftype_set_insert(HashMap *ref_type_set, const WASMRefType *ref_type) +{ + WASMRefType *ref_type_ret; + + if ((ref_type_ret = bh_hash_map_find(ref_type_set, (void *)ref_type))) + return ref_type_ret; + + if (!(ref_type_ret = wasm_reftype_dup(ref_type))) + return NULL; + + if (!bh_hash_map_insert(ref_type_set, ref_type_ret, ref_type_ret)) { + wasm_runtime_free(ref_type_ret); + return NULL; + } + + return ref_type_ret; +} diff --git a/core/iwasm/common/gc/gc_type.h b/core/iwasm/common/gc/gc_type.h new file mode 100644 index 000000000..5b3840e45 --- /dev/null +++ b/core/iwasm/common/gc/gc_type.h @@ -0,0 +1,378 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef _GC_TYPE_H_ +#define _GC_TYPE_H_ + +#include "../interpreter/wasm.h" + +#ifdef __cplusplus +extern "C" { +#endif + +void +wasm_dump_value_type(uint8 type, const WASMRefType *ref_type); + +void +wasm_dump_func_type(const WASMFuncType *type); + +void +wasm_dump_struct_type(const WASMStructType *type); + +void +wasm_dump_array_type(const WASMArrayType *type); + +/* Whether a group of value types is subtype of + another group of value types */ +bool +wasm_value_types_is_subtype_of(const uint8 *types1, + const WASMRefTypeMap *ref_type_maps1, + const uint8 *types2, + const WASMRefTypeMap *ref_type_maps2, + uint32 value_type_count, + const WASMTypePtr *types, uint32 type_count); + +/* Operations of function type */ + +/* Whether two function types are equal */ +bool +wasm_func_type_equal(const WASMFuncType *type1, const WASMFuncType *type2, + const WASMTypePtr *types, uint32 type_count); + +/* Whether func type1 is subtype of func type2 */ +bool +wasm_func_type_is_subtype_of(const WASMFuncType *type1, + const WASMFuncType *type2, + const WASMTypePtr *types, uint32 type_count); + +/* Whether func type1's result types are subtype of + func type2's result types */ +bool +wasm_func_type_result_is_subtype_of(const WASMFuncType *type, + const WASMFuncType *type2, + const WASMTypePtr *types, + uint32 type_count); + +/* Operations of struct type */ + +/* Whether two struct types are equal */ +bool +wasm_struct_type_equal(const WASMStructType *type1, const WASMStructType *type2, + const WASMTypePtr *types, uint32 type_count); + +/* Whether struct type1 is subtype of struct type2 */ +bool +wasm_struct_type_is_subtype_of(const WASMStructType *type1, + const WASMStructType *type2, + const WASMTypePtr *types, uint32 type_count); + +/* Operations of array type */ + +/* Whether two array types are equal */ +bool +wasm_array_type_equal(const WASMArrayType *type1, const WASMArrayType *type2, + const WASMTypePtr *types, uint32 type_count); + +/* Whether array type1 is subtype of array type2 */ +bool +wasm_array_type_is_subtype_of(const WASMArrayType *type1, + const WASMArrayType *type2, + const WASMTypePtr *types, uint32 type_count); + +/* Operations of wasm type */ + +/* Whether a wasm type is a function type */ +inline static bool +wasm_type_is_func_type(const WASMType *type) +{ + return type->type_flag == WASM_TYPE_FUNC ? true : false; +} + +/* Whether a wasm type is a struct type */ +inline static bool +wasm_type_is_struct_type(const WASMType *type) +{ + return type->type_flag == WASM_TYPE_STRUCT ? true : false; +} + +/* Whether a wasm type is an array type */ +inline static bool +wasm_type_is_array_type(const WASMType *type) +{ + return type->type_flag == WASM_TYPE_ARRAY ? true : false; +} + +/* Whether two wasm types are equal */ +bool +wasm_type_equal(const WASMType *type1, const WASMType *type2, + const WASMTypePtr *types, uint32 type_count); + +/* Whether wasm type1 is subtype of wasm type2 */ +bool +wasm_type_is_subtype_of(const WASMType *type1, const WASMType *type2, + const WASMTypePtr *types, uint32 type_count); + +/* Operations of reference type */ + +/* Whether a value type is a reference type */ +inline static bool +wasm_is_type_reftype(uint8 type) +{ + return ((type >= (uint8)REF_TYPE_ARRAYREF + && type <= (uint8)REF_TYPE_NULLFUNCREF) + || (type >= (uint8)REF_TYPE_HT_NULLABLE + && type <= (uint8)REF_TYPE_HT_NON_NULLABLE) +#if WASM_ENABLE_STRINGREF != 0 + || (type >= (uint8)REF_TYPE_STRINGVIEWWTF8 + && type <= (uint8)REF_TYPE_STRINGREF) + || (type >= (uint8)REF_TYPE_STRINGVIEWITER + && type <= (uint8)REF_TYPE_STRINGVIEWWTF16) +#endif + ) + ? true + : false; +} + +/* Whether a negative value is a valid heap type */ +inline static bool +wasm_is_valid_heap_type(int32 heap_type) +{ + return ((heap_type <= HEAP_TYPE_NOFUNC && heap_type >= HEAP_TYPE_ARRAY) +#if WASM_ENABLE_STRINGREF != 0 + || heap_type == HEAP_TYPE_STRINGREF + || heap_type == HEAP_TYPE_STRINGVIEWWTF8 + || heap_type == HEAP_TYPE_STRINGVIEWWTF16 + || heap_type == HEAP_TYPE_STRINGVIEWITER +#endif + ) + ? true + : false; +} + +/* Whether a value type is multi-byte type, or, requires ref type map + to retrieve extra info */ +inline static bool +wasm_is_type_multi_byte_type(uint8 type) +{ + return (type == (uint8)REF_TYPE_HT_NULLABLE + || type == (uint8)REF_TYPE_HT_NON_NULLABLE) + ? true + : false; +} + +/* Whether a reference type is a funcref type */ +inline static bool +wasm_is_reftype_funcref(uint8 type) +{ + return type == (uint8)REF_TYPE_FUNCREF ? true : false; +} + +/* Whether a reference type is an externref type */ +inline static bool +wasm_is_reftype_externref(uint8 type) +{ + return type == (uint8)REF_TYPE_EXTERNREF ? true : false; +} + +/* Whether a reference type is an anyref type */ +inline static bool +wasm_is_reftype_anyref(uint8 type) +{ + return type == (uint8)REF_TYPE_ANYREF ? true : false; +} + +/* Whether a reference type is an eqref type */ +inline static bool +wasm_is_reftype_eqref(uint8 type) +{ + return type == (uint8)REF_TYPE_EQREF ? true : false; +} + +/* Whether a reference type is a (ref null ht) type */ +inline static bool +wasm_is_reftype_htref_nullable(uint8 type) +{ + return type == (uint8)REF_TYPE_HT_NULLABLE ? true : false; +} + +/* Whether a reference type is a (ref ht) type */ +inline static bool +wasm_is_reftype_htref_non_nullable(uint8 type) +{ + return type == (uint8)REF_TYPE_HT_NON_NULLABLE ? true : false; +} + +/* Whether a reference type is an i31ref type */ +inline static bool +wasm_is_reftype_i31ref(uint8 type) +{ + return type == (uint8)REF_TYPE_I31REF ? true : false; +} + +/* Whether a reference type is a structref type */ +inline static bool +wasm_is_reftype_structref(uint8 type) +{ + return type == (uint8)REF_TYPE_STRUCTREF ? true : false; +} + +/* Whether a reference type is an arrayref type */ +inline static bool +wasm_is_reftype_arrayref(uint8 type) +{ + return type == (uint8)REF_TYPE_ARRAYREF ? true : false; +} + +/* Whether a reference type is a nullref type */ +inline static bool +wasm_is_reftype_nullref(uint8 type) +{ + return type == (uint8)REF_TYPE_NULLREF ? true : false; +} + +/* Whether a reference type is a nullfuncref type */ +inline static bool +wasm_is_reftype_nullfuncref(uint8 type) +{ + return type == (uint8)REF_TYPE_NULLFUNCREF ? true : false; +} + +/* Whether a reference type is a nullexternref type */ +inline static bool +wasm_is_reftype_nullexternref(uint8 type) +{ + return type == (uint8)REF_TYPE_NULLEXTERNREF ? true : false; +} + +/* Return the size of a reference type */ +uint32 +wasm_reftype_size(uint8 type); + +/* Return the actual WASMRefType struct size required of a reference type */ +uint32 +wasm_reftype_struct_size(const WASMRefType *ref_type); + +/* Operations of ref heap type */ + +/* Whether a ref heap type is (type i), i : typeidx, >= 0 */ +inline static bool +wasm_is_refheaptype_typeidx(const RefHeapType_Common *ref_heap_type) +{ + return ref_heap_type->heap_type >= 0 ? true : false; +} + +/* Whether a ref heap type is a common type: func/any/eq/i31/data, + not (type i) or (rtt n i) or (rtt i) */ +inline static bool +wasm_is_refheaptype_common(const RefHeapType_Common *ref_heap_type) +{ + return ((ref_heap_type->heap_type >= (int32)HEAP_TYPE_ARRAY + && ref_heap_type->heap_type <= (int32)HEAP_TYPE_NONE) +#if WASM_ENABLE_STRINGREF != 0 + || (ref_heap_type->heap_type >= (int32)HEAP_TYPE_STRINGVIEWITER + && ref_heap_type->heap_type <= (int32)HEAP_TYPE_I31) +#endif + ) + ? true + : false; +} + +/* Whether a ref heap type is a func type */ +inline static bool +wasm_is_refheaptype_func(const RefHeapType_Common *ref_heap_type) +{ + return ref_heap_type->heap_type == (int32)HEAP_TYPE_FUNC ? true : false; +} + +/* Whether a ref heap type is an any type */ +inline static bool +wasm_is_refheaptype_any(const RefHeapType_Common *ref_heap_type) +{ + return ref_heap_type->heap_type == (int32)HEAP_TYPE_ANY ? true : false; +} + +/* Whether a ref heap type is an eq type */ +inline static bool +wasm_is_refheaptype_eq(const RefHeapType_Common *ref_heap_type) +{ + return ref_heap_type->heap_type == (int32)HEAP_TYPE_EQ ? true : false; +} + +/* Whether a ref heap type is an i31 type */ +inline static bool +wasm_is_refheaptype_i31(const RefHeapType_Common *ref_heap_type) +{ + return ref_heap_type->heap_type == (int32)HEAP_TYPE_I31 ? true : false; +} + +/* Whether a ref heap type is an array type */ +inline static bool +wasm_is_refheaptype_array(const RefHeapType_Common *ref_heap_type) +{ + return ref_heap_type->heap_type == (int32)HEAP_TYPE_ARRAY ? true : false; +} + +#if WASM_ENABLE_STRINGREF != 0 +inline static bool +wasm_is_refheaptype_stringrefs(const RefHeapType_Common *ref_heap_type) +{ + return ref_heap_type->heap_type <= (int32)HEAP_TYPE_STRINGREF + && ref_heap_type->heap_type >= HEAP_TYPE_STRINGVIEWITER + ? true + : false; +} +#endif + +/* Whether two ref heap types are equal */ +bool +wasm_refheaptype_equal(const RefHeapType_Common *ref_heap_type1, + const RefHeapType_Common *ref_heap_type2, + const WASMTypePtr *types, uint32 type_count); + +/* Whether two ref types are equal */ +bool +wasm_reftype_equal(uint8 type1, const WASMRefType *reftype1, uint8 type2, + const WASMRefType *reftype2, const WASMTypePtr *types, + uint32 type_count); + +/* Whether ref type1 is subtype of ref type2 */ +bool +wasm_reftype_is_subtype_of(uint8 type1, const WASMRefType *reftype1, + uint8 type2, const WASMRefType *reftype2, + const WASMTypePtr *types, uint32 type_count); + +/* Returns a new reference type which is a duplication of ref_type, + the caller should use wasm_runtime_free() to free the new ref type */ +WASMRefType * +wasm_reftype_dup(const WASMRefType *ref_type); + +/* Set fields of RefHeapType_TypeIdx */ +void +wasm_set_refheaptype_typeidx(RefHeapType_TypeIdx *ref_ht_typeidx, bool nullable, + int32 type_idx); + +/* Set fields of RefHeapType_Common */ +void +wasm_set_refheaptype_common(RefHeapType_Common *ref_ht_common, bool nullable, + int32 heap_type); + +/* Find the related reftype in reftype map array with index */ +WASMRefType * +wasm_reftype_map_find(WASMRefTypeMap *ref_type_maps, uint32 ref_type_map_count, + uint32 index_to_find); + +/* Create a new hash set of reference type */ +HashMap * +wasm_reftype_set_create(uint32 size); + +/* Insert a reference type into the hash set */ +WASMRefType * +wasm_reftype_set_insert(HashMap *ref_type_set, const WASMRefType *ref_type); + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif + +#endif /* end of _GC_TYPE_H_ */ diff --git a/core/iwasm/common/gc/iwasm_gc.cmake b/core/iwasm/common/gc/iwasm_gc.cmake new file mode 100644 index 000000000..5e243c396 --- /dev/null +++ b/core/iwasm/common/gc/iwasm_gc.cmake @@ -0,0 +1,36 @@ +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +set (IWASM_GC_DIR ${CMAKE_CURRENT_LIST_DIR}) + +add_definitions (-DWASM_ENABLE_GC=1) + +if (WAMR_TEST_GC EQUAL 1) + add_definitions (-DGC_MANUALLY=1 -DGC_IN_EVERY_ALLOCATION=1) +endif () + +include_directories (${IWASM_GC_DIR}) + +file (GLOB source_all ${IWASM_GC_DIR}/*.c) + +set (IWASM_GC_SOURCE ${source_all}) + +if (WAMR_BUILD_STRINGREF EQUAL 1) + set (IWASM_STRINGREF_DIR ${CMAKE_CURRENT_LIST_DIR}/stringref) + + add_definitions (-DWASM_ENABLE_STRINGREF=1) + + include_directories (${IWASM_STRINGREF_DIR}) + + if (NOT DEFINED WAMR_STRINGREF_IMPL_SOURCE) + message(FATAL_ERROR "stringref feature enabled, but WAMR_STRINGREF_IMPL_SOURCE not set" ) + else () + if (${WAMR_STRINGREF_IMPL_SOURCE} STREQUAL "STUB") + set (IWASM_STRINGREF_SOURCE ${IWASM_STRINGREF_DIR}/stringref_stub.c) + else() + set (IWASM_STRINGREF_SOURCE ${WAMR_STRINGREF_IMPL_SOURCE}) + endif() + endif () + + set (IWASM_GC_SOURCE ${IWASM_GC_SOURCE} ${IWASM_STRINGREF_SOURCE}) +endif () diff --git a/core/iwasm/common/gc/stringref/string_object.h b/core/iwasm/common/gc/stringref/string_object.h new file mode 100644 index 000000000..88135a6e0 --- /dev/null +++ b/core/iwasm/common/gc/stringref/string_object.h @@ -0,0 +1,121 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef _STRING_OBJECT_H_ +#define _STRING_OBJECT_H_ + +#include "wasm.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum EncodingFlag { + UTF8, + WTF8, + WTF16, + LOSSY_UTF8, +} EncodingFlag; + +typedef enum StringViewType { + STRING_VIEW_WTF8, + STRING_VIEW_WTF16, + STRING_VIEW_ITER, +} StringViewType; + +typedef enum ErrorCode { + Insufficient_Space = -3, + Encode_Fail = -2, + Isolated_Surrogate = -1, +} ErrorCode; + +/******************* gc finalizer *****************/ +void +wasm_string_destroy(WASMString str_obj); + +/******************* opcode functions *****************/ + +/* string.const */ +WASMString +wasm_string_new_const(const char *content, uint32 length); + +/* string.new_xx8/new_wtf16 */ +/* string.new_xx8_array */ +/* string.new_wtf16_array */ +WASMString +wasm_string_new_with_encoding(void *addr, uint32 count, EncodingFlag flag); + +/* string.measure */ +int32 +wasm_string_measure(WASMString str_obj, EncodingFlag flag); + +/* stringview_wtf16.length */ +int32 +wasm_string_wtf16_get_length(WASMString str_obj); + +/* string.encode_xx8 */ +/* string.encode_wtf16 */ +/* stringview_wtf8.encode_xx */ +/* stringview_wtf16.encode */ +/* string.encode_xx8_array */ +/* string.encode_wtf16_array */ +int32 +wasm_string_encode(WASMString str_obj, uint32 pos, uint32 count, void *addr, + uint32 *next_pos, EncodingFlag flag); + +/* string.concat */ +WASMString +wasm_string_concat(WASMString str_obj1, WASMString str_obj2); + +/* string.eq */ +int32 +wasm_string_eq(WASMString str_obj1, WASMString str_obj2); + +/* string.is_usv_sequence */ +int32 +wasm_string_is_usv_sequence(WASMString str_obj); + +/* string.as_wtf8 */ +/* string.as_wtf16 */ +/* string.as_iter */ +WASMString +wasm_string_create_view(WASMString str_obj, StringViewType type); + +/* stringview_wtf8.advance */ +/* stringview_iter.advance */ +int32 +wasm_string_advance(WASMString str_obj, uint32 pos, uint32 count, + uint32 *target_pos); + +/* stringview_wtf8.slice */ +/* stringview_wtf16.slice */ +/* stringview_iter.slice */ +WASMString +wasm_string_slice(WASMString str_obj, uint32 start, uint32 end, + StringViewType type); + +/* stringview_wtf16.get_codeunit */ +int16 +wasm_string_get_wtf16_codeunit(WASMString str_obj, int32 pos); + +/* stringview_iter.next */ +uint32 +wasm_string_next_codepoint(WASMString str_obj, uint32 pos); + +/* stringview_iter.rewind */ +uint32 +wasm_string_rewind(WASMString str_obj, uint32 pos, uint32 count, + uint32 *target_pos); + +/******************* application functions *****************/ + +void +wasm_string_dump(WASMString str_obj); + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif + +#endif /* end of _STRING_OBJECT_H_ */ diff --git a/core/iwasm/common/gc/stringref/stringref_stub.c b/core/iwasm/common/gc/stringref/stringref_stub.c new file mode 100644 index 000000000..8a6d62496 --- /dev/null +++ b/core/iwasm/common/gc/stringref/stringref_stub.c @@ -0,0 +1,136 @@ +/* + * Copyright (C) 2023 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +/* This file is the stub for stringref implementation, only used for wamrc + * compiler. The runtime embedder SHOULD NOT use this file */ + +#include "string_object.h" + +/******************* gc finalizer *****************/ +void +wasm_string_destroy(WASMString str_obj) +{} + +/******************* opcode functions *****************/ + +/* string.const */ +WASMString +wasm_string_new_const(const char *str, uint32 length) +{ + return NULL; +} + +/* string.new_xx8 */ +/* string.new_wtf16 */ +/* string.new_xx8_array */ +/* string.new_wtf16_array */ +WASMString +wasm_string_new_with_encoding(void *addr, uint32 count, EncodingFlag flag) +{ + return NULL; +} + +/* string.measure */ +/* stringview_wtf16.length */ +int32 +wasm_string_measure(WASMString str_obj, EncodingFlag flag) +{ + return 0; +} + +/* stringview_wtf16.length */ +int32 +wasm_string_wtf16_get_length(WASMString str_obj) +{ + return 0; +} + +/* string.encode_xx8 */ +/* string.encode_wtf16 */ +/* stringview_wtf8.encode_xx */ +/* stringview_wtf16.encode */ +/* string.encode_xx8_array */ +/* string.encode_wtf16_array */ +int32 +wasm_string_encode(WASMString str_obj, uint32 pos, uint32 count, void *addr, + uint32 *next_pos, EncodingFlag flag) +{ + return 0; +} + +/* string.concat */ +WASMString +wasm_string_concat(WASMString str_obj1, WASMString str_obj2) +{ + return NULL; +} + +/* string.eq */ +int32 +wasm_string_eq(WASMString str_obj1, WASMString str_obj2) +{ + return 0; +} + +/* string.is_usv_sequence */ +int32 +wasm_string_is_usv_sequence(WASMString str_obj) +{ + return 0; +} + +/* string.as_wtf8 */ +/* string.as_wtf16 */ +/* string.as_iter */ +WASMString +wasm_string_create_view(WASMString str_obj, StringViewType type) +{ + return NULL; +} + +/* stringview_wtf8.advance */ +/* stringview_iter.advance */ +int32 +wasm_string_advance(WASMString str_obj, uint32 pos, uint32 count, + uint32 *consumed) +{ + return 0; +} + +/* stringview_wtf8.slice */ +/* stringview_wtf16.slice */ +/* stringview_iter.slice */ +WASMString +wasm_string_slice(WASMString str_obj, uint32 start, uint32 end, + StringViewType type) +{ + return NULL; +} + +/* stringview_wtf16.get_codeunit */ +int16 +wasm_string_get_wtf16_codeunit(WASMString str_obj, int32 pos) +{ + return 0; +} + +/* stringview_iter.next */ +uint32 +wasm_string_next_codepoint(WASMString str_obj, uint32 pos) +{ + return 0; +} + +/* stringview_iter.rewind */ +uint32 +wasm_string_rewind(WASMString str_obj, uint32 pos, uint32 count, + uint32 *consumed) +{ + return 0; +} + +void +wasm_string_dump(WASMString str_obj) +{} diff --git a/core/iwasm/common/wasm_application.c b/core/iwasm/common/wasm_application.c index e13f7f843..4e5d17deb 100644 --- a/core/iwasm/common/wasm_application.c +++ b/core/iwasm/common/wasm_application.c @@ -13,6 +13,15 @@ #if WASM_ENABLE_THREAD_MGR != 0 #include "../libraries/thread-mgr/thread_manager.h" #endif +#if WASM_ENABLE_GC != 0 +#include "gc/gc_object.h" +#if WASM_ENABLE_STRINGREF != 0 +#include "string_object.h" +#endif +#if WASM_ENABLE_GC_PERF_PROFILING != 0 +#include "../../shared/mem-alloc/mem_alloc.h" +#endif +#endif static void set_error_buf(char *error_buf, uint32 error_buf_size, const char *string) @@ -52,7 +61,7 @@ static union { * Implementation of wasm_application_execute_main() */ static bool -check_main_func_type(const WASMType *type) +check_main_func_type(const WASMFuncType *type) { if (!(type->param_count == 0 || type->param_count == 2) || type->result_count > 1) { @@ -83,7 +92,7 @@ static bool execute_main(WASMModuleInstanceCommon *module_inst, int32 argc, char *argv[]) { WASMFunctionInstanceCommon *func; - WASMType *func_type = NULL; + WASMFuncType *func_type = NULL; WASMExecEnv *exec_env = NULL; uint32 argc1 = 0, argv1[2] = { 0 }; uint32 total_argv_size = 0; @@ -244,6 +253,11 @@ wasm_application_execute_main(WASMModuleInstanceCommon *module_inst, int32 argc, } #endif +#if WASM_ENABLE_GC_PERF_PROFILING != 0 + void *handle = wasm_runtime_get_gc_heap_handle(module_inst); + mem_allocator_dump_perf_profiling(handle); +#endif + #if WASM_ENABLE_PERF_PROFILING != 0 wasm_runtime_dump_perf_profiling(module_inst); #endif @@ -304,10 +318,15 @@ execute_func(WASMModuleInstanceCommon *module_inst, const char *name, int32 argc, char *argv[]) { WASMFunctionInstanceCommon *target_func; - WASMType *type = NULL; + WASMFuncType *type = NULL; WASMExecEnv *exec_env = NULL; +#if WASM_ENABLE_GC != 0 + WASMRefTypeMap *ref_type_map; + WASMLocalObjectRef *local_ref; + uint32 num_local_ref_pushed = 0; +#endif uint32 argc1, *argv1 = NULL, cell_num = 0, j, k = 0; -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 uint32 param_size_in_double_world = 0, result_size_in_double_world = 0; #endif int32 i, p, module_type; @@ -337,7 +356,14 @@ execute_func(WASMModuleInstanceCommon *module_inst, const char *name, goto fail; } -#if WASM_ENABLE_REF_TYPES != 0 + exec_env = wasm_runtime_get_exec_env_singleton(module_inst); + if (!exec_env) { + wasm_runtime_set_exception(module_inst, + "create singleton exec_env failed"); + goto fail; + } + +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 for (i = 0; i < type->param_count; i++) { param_size_in_double_world += wasm_value_type_cell_num_outside(type->types[i]); @@ -360,6 +386,9 @@ execute_func(WASMModuleInstanceCommon *module_inst, const char *name, goto fail; } +#if WASM_ENABLE_GC != 0 + ref_type_map = type->ref_type_maps; +#endif /* Parse arguments */ for (i = 0, p = 0; i < argc; i++) { char *endptr = NULL; @@ -482,8 +511,11 @@ execute_func(WASMModuleInstanceCommon *module_inst, const char *name, break; } #endif /* WASM_ENABLE_SIMD != 0 */ -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case VALUE_TYPE_FUNCREF: +#if UINTPTR_MAX == UINT32_MAX + case VALUE_TYPE_EXTERNREF: +#endif { if (strncasecmp(argv[i], "null", 4) == 0) { argv1[p++] = (uint32)-1; @@ -493,16 +525,9 @@ execute_func(WASMModuleInstanceCommon *module_inst, const char *name, } break; } +#if UINTPTR_MAX == UINT64_MAX case VALUE_TYPE_EXTERNREF: { -#if UINTPTR_MAX == UINT32_MAX - if (strncasecmp(argv[i], "null", 4) == 0) { - argv1[p++] = (uint32)-1; - } - else { - argv1[p++] = strtoul(argv[i], &endptr, 0); - } -#else union { uintptr_t val; uint32 parts[2]; @@ -515,13 +540,97 @@ execute_func(WASMModuleInstanceCommon *module_inst, const char *name, } argv1[p++] = u.parts[0]; argv1[p++] = u.parts[1]; -#endif break; } -#endif /* WASM_ENABLE_REF_TYPES */ +#endif +#endif /* WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 */ default: + { +#if WASM_ENABLE_GC != 0 + bool is_extern_ref = false; + bool is_anyref = false; + + if (wasm_is_type_reftype(type->types[i])) { + if (strncasecmp(argv[i], "null", 4) == 0) { + PUT_REF_TO_ADDR(argv1 + p, NULL_REF); + p += REF_CELL_NUM; + break; + } + else if (type->types[i] == VALUE_TYPE_EXTERNREF) { + is_extern_ref = true; + } + else if (type->types[i] == VALUE_TYPE_ANYREF) { + is_anyref = true; + } + + if (wasm_is_type_multi_byte_type( + type->types[type->param_count + i])) { + WASMRefType *ref_type = ref_type_map->ref_type; + if (wasm_is_refheaptype_common( + &ref_type->ref_ht_common)) { + int32 heap_type = ref_type->ref_ht_common.heap_type; + if (heap_type == HEAP_TYPE_EXTERN) { + is_extern_ref = true; + } + else if (heap_type == HEAP_TYPE_ANY) { + is_anyref = true; + } + } + + ref_type_map++; + } + + if (is_extern_ref) { + WASMExternrefObjectRef gc_obj; + void *extern_obj = + (void *)(uintptr_t)strtoull(argv[i], &endptr, 0); + gc_obj = wasm_externref_obj_new(exec_env, extern_obj); + if (!gc_obj) { + wasm_runtime_set_exception( + module_inst, "create extern object failed"); + goto fail; + } + if (!(local_ref = + runtime_malloc(sizeof(WASMLocalObjectRef), + module_inst, NULL, 0))) { + goto fail; + } + wasm_runtime_push_local_obj_ref(exec_env, local_ref); + local_ref->val = (WASMObjectRef)gc_obj; + num_local_ref_pushed++; + PUT_REF_TO_ADDR(argv1 + p, gc_obj); + p += REF_CELL_NUM; + } + else if (is_anyref) { + /* If a parameter type is (ref null? any) and its value + * is not null, then we treat the value as host ptr */ + WASMAnyrefObjectRef gc_obj; + void *host_obj = + (void *)(uintptr_t)strtoull(argv[i], &endptr, 0); + gc_obj = wasm_anyref_obj_new(exec_env, host_obj); + if (!gc_obj) { + wasm_runtime_set_exception( + module_inst, "create anyref object failed"); + goto fail; + } + if (!(local_ref = + runtime_malloc(sizeof(WASMLocalObjectRef), + module_inst, NULL, 0))) { + goto fail; + } + wasm_runtime_push_local_obj_ref(exec_env, local_ref); + local_ref->val = (WASMObjectRef)gc_obj; + num_local_ref_pushed++; + PUT_REF_TO_ADDR(argv1 + p, gc_obj); + p += REF_CELL_NUM; + } + + break; + } +#endif /* end of WASM_ENABLE_GC != 0 */ bh_assert(0); break; + } } if (endptr && *endptr != '\0' && *endptr != '_') { snprintf(buf, sizeof(buf), "invalid input argument %" PRId32 ": %s", @@ -532,21 +641,17 @@ execute_func(WASMModuleInstanceCommon *module_inst, const char *name, } wasm_runtime_set_exception(module_inst, NULL); -#if WASM_ENABLE_REF_TYPES == 0 +#if WASM_ENABLE_REF_TYPES == 0 && WASM_ENABLE_GC == 0 bh_assert(p == (int32)argc1); #endif - exec_env = wasm_runtime_get_exec_env_singleton(module_inst); - if (!exec_env) { - wasm_runtime_set_exception(module_inst, - "create singleton exec_env failed"); - goto fail; - } - if (!wasm_runtime_call_wasm(exec_env, target_func, argc1, argv1)) { goto fail; } +#if WASM_ENABLE_GC != 0 + ref_type_map = type->result_ref_type_maps; +#endif /* print return value */ for (j = 0; j < type->result_count; j++) { switch (type->types[type->param_count + j]) { @@ -586,7 +691,7 @@ execute_func(WASMModuleInstanceCommon *module_inst, const char *name, os_printf("%.7g:f64", u.val); break; } -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case VALUE_TYPE_FUNCREF: { if (argv1[k] != NULL_REF) @@ -619,7 +724,7 @@ execute_func(WASMModuleInstanceCommon *module_inst, const char *name, #endif break; } -#endif +#endif /* end of WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 */ #if WASM_ENABLE_SIMD != 0 case VALUE_TYPE_V128: { @@ -631,14 +736,117 @@ execute_func(WASMModuleInstanceCommon *module_inst, const char *name, } #endif /* WASM_ENABLE_SIMD != 0 */ default: + { +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_reftype(type->types[type->param_count + j])) { + void *gc_obj = GET_REF_FROM_ADDR(argv1 + k); + k += REF_CELL_NUM; + if (!gc_obj) { + uint8 type1 = type->types[type->param_count + j]; + WASMRefType *ref_type1 = NULL; + WASMType **types = NULL; + uint32 type_count = 0; + + if (wasm_is_type_multi_byte_type( + type->types[type->param_count + j])) + ref_type1 = ref_type_map->ref_type; + +#if WASM_ENABLE_INTERP != 0 + if (module_inst->module_type == Wasm_Module_Bytecode) { + WASMModule *module = + ((WASMModuleInstance *)module_inst)->module; + types = module->types; + type_count = module->type_count; + } +#endif +#if WASM_ENABLE_AOT != 0 + if (module_inst->module_type == Wasm_Module_AoT) { + AOTModule *module = + (AOTModule *)((AOTModuleInstance *)module_inst) + ->module; + types = module->types; + type_count = module->type_count; + } +#endif + bh_assert(type); + if (wasm_reftype_is_subtype_of(type1, ref_type1, + REF_TYPE_ANYREF, NULL, + types, type_count)) + os_printf("any:"); + else if (wasm_reftype_is_subtype_of( + type1, ref_type1, REF_TYPE_FUNCREF, NULL, + types, type_count)) + os_printf("func:"); + if (wasm_reftype_is_subtype_of(type1, ref_type1, + REF_TYPE_EXTERNREF, NULL, + types, type_count)) + os_printf("extern:"); + os_printf("ref.null"); + } + else if (wasm_obj_is_func_obj(gc_obj)) + os_printf("ref.func"); +#if WASM_ENABLE_STRINGREF != 0 + else if (wasm_obj_is_stringref_obj(gc_obj) + || wasm_obj_is_stringview_wtf8_obj(gc_obj)) { + wasm_string_dump( + (WASMString)wasm_stringref_obj_get_value(gc_obj)); + } + else if (wasm_obj_is_stringview_wtf16_obj(gc_obj)) { + wasm_string_dump( + (WASMString)wasm_stringview_wtf16_obj_get_value( + gc_obj)); + } +#endif + else if (wasm_obj_is_externref_obj(gc_obj)) { +#if WASM_ENABLE_SPEC_TEST != 0 + WASMObjectRef obj = wasm_externref_obj_to_internal_obj( + (WASMExternrefObjectRef)gc_obj); + if (wasm_obj_is_anyref_obj(obj)) + os_printf("0x%" PRIxPTR ":ref.extern", + (uintptr_t)wasm_anyref_obj_get_value( + (WASMAnyrefObjectRef)obj)); + else +#endif + os_printf("ref.extern"); + } + else if (wasm_obj_is_i31_obj(gc_obj)) + os_printf("ref.i31"); + else if (wasm_obj_is_array_obj(gc_obj)) + os_printf("ref.array"); + else if (wasm_obj_is_struct_obj(gc_obj)) + os_printf("ref.struct"); + else if (wasm_obj_is_eq_obj(gc_obj)) + os_printf("ref.eq"); + else if (wasm_obj_is_anyref_obj(gc_obj)) + os_printf("0x%" PRIxPTR ":ref.host", + (uintptr_t)wasm_anyref_obj_get_value( + (WASMAnyrefObjectRef)gc_obj)); + else if (wasm_obj_is_internal_obj(gc_obj)) + os_printf("ref.any"); + + if (wasm_is_type_multi_byte_type( + type->types[type->param_count + j])) + ref_type_map++; + + break; + } +#endif /* endof WASM_ENABLE_GC != 0 */ bh_assert(0); break; + } } if (j < (uint32)(type->result_count - 1)) os_printf(","); } os_printf("\n"); +#if WASM_ENABLE_GC != 0 + for (j = 0; j < num_local_ref_pushed; j++) { + local_ref = wasm_runtime_pop_local_obj_ref(exec_env); + wasm_runtime_free(local_ref); + } +#endif + wasm_runtime_free(argv1); return true; @@ -646,6 +854,13 @@ fail: if (argv1) wasm_runtime_free(argv1); +#if WASM_ENABLE_GC != 0 + for (j = 0; j < num_local_ref_pushed; j++) { + local_ref = wasm_runtime_pop_local_obj_ref(exec_env); + wasm_runtime_free(local_ref); + } +#endif + bh_assert(wasm_runtime_get_exception(module_inst)); return false; } @@ -668,6 +883,11 @@ wasm_application_execute_func(WASMModuleInstanceCommon *module_inst, } #endif +#if WASM_ENABLE_GC_PERF_PROFILING != 0 + void *handle = wasm_runtime_get_gc_heap_handle(module_inst); + mem_allocator_dump_perf_profiling(handle); +#endif + #if WASM_ENABLE_PERF_PROFILING != 0 wasm_runtime_dump_perf_profiling(module_inst); #endif diff --git a/core/iwasm/common/wasm_c_api.c b/core/iwasm/common/wasm_c_api.c index a9fac87ba..bffa870cf 100644 --- a/core/iwasm/common/wasm_c_api.c +++ b/core/iwasm/common/wasm_c_api.c @@ -774,7 +774,7 @@ wasm_valtype_new(wasm_valkind_t kind) wasm_valtype_t *val_type; if (kind > WASM_F64 && WASM_FUNCREF != kind -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 && WASM_ANYREF != kind #endif ) { @@ -811,7 +811,7 @@ wasm_valtype_kind(const wasm_valtype_t *val_type) } static wasm_functype_t * -wasm_functype_new_internal(WASMType *type_rt) +wasm_functype_new_internal(WASMFuncType *type_rt) { wasm_functype_t *type = NULL; wasm_valtype_t *param_type = NULL, *result_type = NULL; @@ -827,7 +827,7 @@ wasm_functype_new_internal(WASMType *type_rt) type->extern_kind = WASM_EXTERN_FUNC; - /* WASMType->types[0 : type_rt->param_count) -> type->params */ + /* WASMFuncType->types[0 : type_rt->param_count) -> type->params */ INIT_VEC(type->params, wasm_valtype_vec_new_uninitialized, type_rt->param_count); for (i = 0; i < type_rt->param_count; ++i) { @@ -841,7 +841,7 @@ wasm_functype_new_internal(WASMType *type_rt) } } - /* WASMType->types[type_rt->param_count : type_rt->result_count) -> + /* WASMFuncType->types[type_rt->param_count : type_rt->result_count) -> * type->results */ INIT_VEC(type->results, wasm_valtype_vec_new_uninitialized, type_rt->result_count); @@ -983,7 +983,7 @@ cmp_val_kind_with_val_type(wasm_valkind_t v_k, uint8 v_t) */ static bool wasm_functype_same_internal(const wasm_functype_t *type, - const WASMType *type_intl) + const WASMFuncType *type_intl) { uint32 i = 0; @@ -1132,7 +1132,7 @@ wasm_tabletype_new(own wasm_valtype_t *val_type, const wasm_limits_t *limits) } if (wasm_valtype_kind(val_type) != WASM_FUNCREF -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 && wasm_valtype_kind(val_type) != WASM_ANYREF #endif ) { @@ -1646,7 +1646,7 @@ rt_val_to_wasm_val(const uint8 *data, uint8 val_type_rt, wasm_val_t *out) out->kind = WASM_F64; out->of.f64 = *((float64 *)data); break; -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case VALUE_TYPE_EXTERNREF: out->kind = WASM_ANYREF; if (NULL_REF == *(uint32 *)data) { @@ -1687,7 +1687,7 @@ wasm_val_to_rt_val(WASMModuleInstanceCommon *inst_comm_rt, uint8 val_type_rt, bh_assert(WASM_F64 == v->kind); *((float64 *)data) = v->of.f64; break; -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case VALUE_TYPE_EXTERNREF: bh_assert(WASM_ANYREF == v->kind); ret = @@ -2470,7 +2470,7 @@ wasm_module_imports(const wasm_module_t *module, own wasm_importtype_vec_t *out) if (i < import_func_count) { wasm_functype_t *type = NULL; - WASMType *type_rt = NULL; + WASMFuncType *type_rt = NULL; #if WASM_ENABLE_INTERP != 0 if ((*module)->module_type == Wasm_Module_Bytecode) { @@ -2715,13 +2715,13 @@ wasm_module_exports(const wasm_module_t *module, wasm_exporttype_vec_t *out) goto failed; } - /* WASMExport -> (WASMType, (uint8, bool)) -> (wasm_functype_t, + /* WASMExport -> (WASMFuncType, (uint8, bool)) -> (wasm_functype_t, * wasm_globaltype_t) -> wasm_externtype_t*/ switch (export->kind) { case EXPORT_KIND_FUNC: { wasm_functype_t *type = NULL; - WASMType *type_rt; + WASMFuncType *type_rt; if (!wasm_runtime_get_export_func_type(*module, export, &type_rt)) { @@ -2776,12 +2776,22 @@ wasm_module_exports(const wasm_module_t *module, wasm_exporttype_vec_t *out) { wasm_tabletype_t *type = NULL; uint8 elem_type_rt = 0; +#if WASM_ENABLE_GC != 0 + WASMRefType *elem_ref_type_rt; +#endif uint32 min_size = 0, max_size = 0; - if (!wasm_runtime_get_export_table_type( - *module, export, &elem_type_rt, &min_size, &max_size)) { + if (!wasm_runtime_get_export_table_type(*module, export, + &elem_type_rt, +#if WASM_ENABLE_GC != 0 + &elem_ref_type_rt, +#endif + &min_size, &max_size)) { goto failed; } +#if WASM_ENABLE_GC != 0 + (void)elem_ref_type_rt; /* TODO */ +#endif if (!(type = wasm_tabletype_new_internal(elem_type_rt, min_size, max_size))) { @@ -3032,7 +3042,7 @@ wasm_func_new_internal(wasm_store_t *store, uint16 func_idx_rt, WASMModuleInstanceCommon *inst_comm_rt) { wasm_func_t *func = NULL; - WASMType *type_rt = NULL; + WASMFuncType *type_rt = NULL; bh_assert(singleton_engine); @@ -3070,9 +3080,9 @@ wasm_func_new_internal(wasm_store_t *store, uint16 func_idx_rt, } else { type_rt = - module_aot->func_types[module_aot->func_type_indexes - [func_idx_rt - - module_aot->import_func_count]]; + (AOTFuncType *)module_aot + ->types[module_aot->func_type_indexes + [func_idx_rt - module_aot->import_func_count]]; } } #endif @@ -3204,8 +3214,7 @@ params_to_argv(const wasm_val_vec_t *params, *(int64 *)argv = param->of.i64; argv += 2; break; - break; -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case WASM_ANYREF: *(uintptr_t *)argv = (uintptr_t)param->of.ref; argv += sizeof(uintptr_t) / sizeof(uint32); @@ -3247,7 +3256,7 @@ argv_to_results(const uint32 *argv, const wasm_valtype_vec_t *result_defs, result->of.i64 = *(int64 *)argv; argv += 2; break; -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case WASM_ANYREF: result->of.ref = (struct wasm_ref_t *)(*(uintptr_t *)argv); argv += sizeof(uintptr_t) / sizeof(uint32); @@ -3830,6 +3839,9 @@ wasm_table_new_internal(wasm_store_t *store, uint16 table_idx_rt, { wasm_table_t *table = NULL; uint8 val_type_rt = 0; +#if WASM_ENABLE_GC != 0 + WASMRefType *val_ref_type_rt; +#endif uint32 init_size = 0, max_size = 0; bh_assert(singleton_engine); @@ -3845,14 +3857,21 @@ wasm_table_new_internal(wasm_store_t *store, uint16 table_idx_rt, table->store = store; table->kind = WASM_EXTERN_TABLE; - if (!wasm_runtime_get_table_inst_elem_type( - inst_comm_rt, table_idx_rt, &val_type_rt, &init_size, &max_size)) { + if (!wasm_runtime_get_table_inst_elem_type(inst_comm_rt, table_idx_rt, + &val_type_rt, +#if WASM_ENABLE_GC != 0 + &val_ref_type_rt, +#endif + &init_size, &max_size)) { /* * a wrong combination of module filetype and compilation flags * leads to below branch */ goto failed; } +#if WASM_ENABLE_GC != 0 + (void)val_ref_type_rt; /* TODO */ +#endif if (!(table->type = wasm_tabletype_new_internal(val_type_rt, init_size, max_size))) { @@ -3922,6 +3941,7 @@ wasm_table_type(const wasm_table_t *table) return wasm_tabletype_copy(table->type); } +#if WASM_ENABLE_GC == 0 own wasm_ref_t * wasm_table_get(const wasm_table_t *table, wasm_table_size_t index) { @@ -4010,7 +4030,7 @@ wasm_table_set(wasm_table_t *table, wasm_table_size_t index, return false; } - p_ref_idx = table_interp->elems + index; + p_ref_idx = (uint32 *)(table_interp->elems + index); function_count = ((WASMModuleInstance *)table->inst_comm_rt)->e->function_count; } @@ -4026,7 +4046,7 @@ wasm_table_set(wasm_table_t *table, wasm_table_size_t index, return false; } - p_ref_idx = table_aot->elems + index; + p_ref_idx = (uint32 *)(table_aot->elems + index); function_count = module_aot->func_count; } #endif @@ -4062,6 +4082,22 @@ wasm_table_set(wasm_table_t *table, wasm_table_size_t index, return true; } +#else /* else of WASM_ENABLE_GC == 0 */ +own wasm_ref_t * +wasm_table_get(const wasm_table_t *table, wasm_table_size_t index) +{ + /* TODO */ + return NULL; +} + +bool +wasm_table_set(wasm_table_t *table, wasm_table_size_t index, + own wasm_ref_t *ref) +{ + /* TODO */ + return false; +} +#endif /* end of WASM_ENABLE_GC == 0 */ wasm_table_size_t wasm_table_size(const wasm_table_t *table) diff --git a/core/iwasm/common/wasm_exec_env.c b/core/iwasm/common/wasm_exec_env.c index d524c7de0..0b3778e60 100644 --- a/core/iwasm/common/wasm_exec_env.c +++ b/core/iwasm/common/wasm_exec_env.c @@ -5,6 +5,9 @@ #include "wasm_exec_env.h" #include "wasm_runtime_common.h" +#if WASM_ENABLE_GC != 0 +#include "mem_alloc.h" +#endif #if WASM_ENABLE_INTERP != 0 #include "../interpreter/wasm_runtime.h" #endif @@ -28,7 +31,7 @@ wasm_exec_env_create_internal(struct WASMModuleInstanceCommon *module_inst, uint32 stack_size) { uint64 total_size = - offsetof(WASMExecEnv, wasm_stack.s.bottom) + (uint64)stack_size; + offsetof(WASMExecEnv, wasm_stack_u.bottom) + (uint64)stack_size; WASMExecEnv *exec_env; if (total_size >= UINT32_MAX @@ -65,9 +68,10 @@ wasm_exec_env_create_internal(struct WASMModuleInstanceCommon *module_inst, exec_env->module_inst = module_inst; exec_env->wasm_stack_size = stack_size; - exec_env->wasm_stack.s.top_boundary = - exec_env->wasm_stack.s.bottom + stack_size; - exec_env->wasm_stack.s.top = exec_env->wasm_stack.s.bottom; + exec_env->wasm_stack.bottom = exec_env->wasm_stack_u.bottom; + exec_env->wasm_stack.top_boundary = + exec_env->wasm_stack.bottom + stack_size; + exec_env->wasm_stack.top = exec_env->wasm_stack.bottom; #if WASM_ENABLE_AOT != 0 if (module_inst->module_type == Wasm_Module_AoT) { @@ -134,6 +138,9 @@ wasm_exec_env_create(struct WASMModuleInstanceCommon *module_inst, #endif WASMExecEnv *exec_env = wasm_exec_env_create_internal(module_inst, stack_size); +#if WASM_ENABLE_GC != 0 + void *gc_heap_handle = NULL; +#endif if (!exec_env) return NULL; @@ -145,6 +152,10 @@ wasm_exec_env_create(struct WASMModuleInstanceCommon *module_inst, exec_env->aux_stack_bottom.bottom = module->aux_stack_bottom; exec_env->aux_stack_boundary.boundary = module->aux_stack_bottom - module->aux_stack_size; +#if WASM_ENABLE_GC != 0 + gc_heap_handle = + ((WASMModuleInstance *)module_inst)->e->common.gc_heap_pool; +#endif } #endif #if WASM_ENABLE_AOT != 0 @@ -155,6 +166,11 @@ wasm_exec_env_create(struct WASMModuleInstanceCommon *module_inst, exec_env->aux_stack_bottom.bottom = module->aux_stack_bottom; exec_env->aux_stack_boundary.boundary = module->aux_stack_bottom - module->aux_stack_size; +#if WASM_ENABLE_GC != 0 + gc_heap_handle = + ((AOTModuleInstanceExtra *)((AOTModuleInstance *)module_inst)->e) + ->common.gc_heap_handle; +#endif } #endif @@ -164,6 +180,13 @@ wasm_exec_env_create(struct WASMModuleInstanceCommon *module_inst, wasm_exec_env_destroy_internal(exec_env); return NULL; } +#if WASM_ENABLE_GC != 0 + mem_allocator_enable_gc_reclaim(gc_heap_handle, cluster); +#endif +#else +#if WASM_ENABLE_GC != 0 + mem_allocator_enable_gc_reclaim(gc_heap_handle, exec_env); +#endif #endif /* end of WASM_ENABLE_THREAD_MGR */ return exec_env; diff --git a/core/iwasm/common/wasm_exec_env.h b/core/iwasm/common/wasm_exec_env.h index 132642ea8..4f93493ef 100644 --- a/core/iwasm/common/wasm_exec_env.h +++ b/core/iwasm/common/wasm_exec_env.h @@ -38,8 +38,8 @@ typedef struct WASMExecEnv { /* Next thread's exec env of a WASM module instance. */ struct WASMExecEnv *next; - /* Previous thread's exec env of a WASM module instance. */ - struct WASMExecEnv *prev; + /* Current interpreter/AOT frame of current thread */ + struct WASMInterpFrame *cur_frame; /* Note: field module_inst, argv_buf, native_stack_boundary, suspend_flags, aux_stack_boundary, aux_stack_bottom, and @@ -84,6 +84,15 @@ typedef struct WASMExecEnv { */ uint8 *native_stack_top_min; + struct { + /* The top boundary of the stack. */ + uint8 *top_boundary; + /* The top to of the wasm stack which is free. */ + uint8 *top; + /* The bottom of the wasm stack. */ + uint8 *bottom; + } wasm_stack; + #if WASM_ENABLE_FAST_JIT != 0 /** * Cache for @@ -116,6 +125,11 @@ typedef struct WASMExecEnv { bool thread_is_detached; #endif +#if WASM_ENABLE_GC != 0 + /* Current local object reference variable */ + struct WASMLocalObjectRef *cur_local_object_ref; +#endif + #if WASM_ENABLE_DEBUG_INTERP != 0 WASMCurrentEnvStatus *current_status; #endif @@ -125,9 +139,6 @@ typedef struct WASMExecEnv { void *user_data; - /* Current interpreter frame of current thread */ - struct WASMInterpFrame *cur_frame; - /* The native thread handle of current thread */ korp_tid handle; @@ -151,18 +162,9 @@ typedef struct WASMExecEnv { /* The WASM stack of current thread */ union { uint64 __make_it_8_byte_aligned_; - - struct { - /* The top boundary of the stack. */ - uint8 *top_boundary; - - /* Top cell index which is free. */ - uint8 *top; - - /* The WASM stack. */ - uint8 bottom[1]; - } s; - } wasm_stack; + /* The WASM stack. */ + uint8 bottom[1]; + } wasm_stack_u; } WASMExecEnv; #if WASM_ENABLE_MEMORY_PROFILING != 0 @@ -209,7 +211,7 @@ wasm_exec_env_is_aux_stack_managed_by_runtime(WASMExecEnv *exec_env) static inline void * wasm_exec_env_alloc_wasm_frame(WASMExecEnv *exec_env, unsigned size) { - uint8 *addr = exec_env->wasm_stack.s.top; + uint8 *addr = exec_env->wasm_stack.top; bh_assert(!(size & 3)); @@ -220,17 +222,17 @@ wasm_exec_env_alloc_wasm_frame(WASMExecEnv *exec_env, unsigned size) frame size, we should check again before putting the function arguments into the outs area. */ if (size * 2 - > (uint32)(uintptr_t)(exec_env->wasm_stack.s.top_boundary - addr)) { + > (uint32)(uintptr_t)(exec_env->wasm_stack.top_boundary - addr)) { /* WASM stack overflow. */ return NULL; } - exec_env->wasm_stack.s.top += size; + exec_env->wasm_stack.top += size; #if WASM_ENABLE_MEMORY_PROFILING != 0 { uint32 wasm_stack_used = - exec_env->wasm_stack.s.top - exec_env->wasm_stack.s.bottom; + exec_env->wasm_stack.top - exec_env->wasm_stack.bottom; if (wasm_stack_used > exec_env->max_wasm_stack_used) exec_env->max_wasm_stack_used = wasm_stack_used; } @@ -241,8 +243,8 @@ wasm_exec_env_alloc_wasm_frame(WASMExecEnv *exec_env, unsigned size) static inline void wasm_exec_env_free_wasm_frame(WASMExecEnv *exec_env, void *prev_top) { - bh_assert((uint8 *)prev_top >= exec_env->wasm_stack.s.bottom); - exec_env->wasm_stack.s.top = (uint8 *)prev_top; + bh_assert((uint8 *)prev_top >= exec_env->wasm_stack.bottom); + exec_env->wasm_stack.top = (uint8 *)prev_top; } /** @@ -255,7 +257,7 @@ wasm_exec_env_free_wasm_frame(WASMExecEnv *exec_env, void *prev_top) static inline void * wasm_exec_env_wasm_stack_top(WASMExecEnv *exec_env) { - return exec_env->wasm_stack.s.top; + return exec_env->wasm_stack.top; } /** diff --git a/core/iwasm/common/wasm_memory.c b/core/iwasm/common/wasm_memory.c index 3941c224a..ee39242b1 100644 --- a/core/iwasm/common/wasm_memory.c +++ b/core/iwasm/common/wasm_memory.c @@ -6,7 +6,6 @@ #include "wasm_runtime_common.h" #include "../interpreter/wasm_runtime.h" #include "../aot/aot_runtime.h" -#include "bh_platform.h" #include "mem_alloc.h" #include "wasm_memory.h" @@ -42,14 +41,22 @@ static void (*free_func)(void *ptr) = NULL; static unsigned int global_pool_size; +static uint32 +align_as_and_cast(uint64 size, uint64 alignment) +{ + uint64 aligned_size = (size + alignment - 1) & ~(alignment - 1); + + return aligned_size > UINT32_MAX ? UINT32_MAX : (uint32)aligned_size; +} + static bool wasm_memory_init_with_pool(void *mem, unsigned int bytes) { - mem_allocator_t _allocator = mem_allocator_create(mem, bytes); + mem_allocator_t allocator = mem_allocator_create(mem, bytes); - if (_allocator) { + if (allocator) { memory_mode = MEMORY_MODE_POOL; - pool_allocator = _allocator; + pool_allocator = allocator; global_pool_size = bytes; return true; } @@ -76,18 +83,18 @@ wasm_memory_init_with_allocator(void *_user_data, void *_malloc_func, } #else static bool -wasm_memory_init_with_allocator(void *_malloc_func, void *_realloc_func, - void *_free_func) +wasm_memory_init_with_allocator(void *malloc_func_ptr, void *realloc_func_ptr, + void *free_func_ptr) { - if (_malloc_func && _free_func && _malloc_func != _free_func) { + if (malloc_func_ptr && free_func_ptr && malloc_func_ptr != free_func_ptr) { memory_mode = MEMORY_MODE_ALLOCATOR; - malloc_func = _malloc_func; - realloc_func = _realloc_func; - free_func = _free_func; + malloc_func = malloc_func_ptr; + realloc_func = realloc_func_ptr; + free_func = free_func_ptr; return true; } - LOG_ERROR("Init memory with allocator (%p, %p, %p) failed.\n", _malloc_func, - _realloc_func, _free_func); + LOG_ERROR("Init memory with allocator (%p, %p, %p) failed.\n", + malloc_func_ptr, realloc_func_ptr, free_func_ptr); return false; } #endif @@ -96,6 +103,10 @@ static inline bool is_bounds_checks_enabled(WASMModuleInstanceCommon *module_inst) { #if WASM_CONFIGURABLE_BOUNDS_CHECKS != 0 + if (!module_inst) { + return true; + } + return wasm_runtime_is_bounds_checks_enabled(module_inst); #else return true; @@ -111,18 +122,13 @@ wasm_runtime_memory_init(mem_alloc_type_t mem_alloc_type, alloc_option->pool.heap_size); } else if (mem_alloc_type == Alloc_With_Allocator) { + return wasm_memory_init_with_allocator( #if WASM_MEM_ALLOC_WITH_USER_DATA != 0 - return wasm_memory_init_with_allocator( alloc_option->allocator.user_data, - alloc_option->allocator.malloc_func, - alloc_option->allocator.realloc_func, - alloc_option->allocator.free_func); -#else - return wasm_memory_init_with_allocator( - alloc_option->allocator.malloc_func, - alloc_option->allocator.realloc_func, - alloc_option->allocator.free_func); #endif + alloc_option->allocator.malloc_func, + alloc_option->allocator.realloc_func, + alloc_option->allocator.free_func); } else if (mem_alloc_type == Alloc_With_System_Allocator) { memory_mode = MEMORY_MODE_SYSTEM_ALLOCATOR; @@ -629,7 +635,61 @@ wasm_runtime_set_mem_bound_check_bytes(WASMMemoryInstance *memory, #endif } -#ifndef OS_ENABLE_HW_BOUND_CHECK +static void +wasm_munmap_linear_memory(void *mapped_mem, uint64 commit_size, uint64 map_size) +{ +#ifdef BH_PLATFORM_WINDOWS + os_mem_decommit(mapped_mem, commit_size); +#else + (void)commit_size; +#endif + os_munmap(mapped_mem, map_size); +} + +static void * +wasm_mremap_linear_memory(void *mapped_mem, uint64 old_size, uint64 new_size, + uint64 commit_size) +{ + void *new_mem; + + bh_assert(new_size > 0); + bh_assert(new_size > old_size); + + if (mapped_mem) { + new_mem = os_mremap(mapped_mem, old_size, new_size); + } + else { + new_mem = os_mmap(NULL, new_size, MMAP_PROT_NONE, MMAP_MAP_NONE, + os_get_invalid_handle()); + } + if (!new_mem) { + return NULL; + } + +#ifdef BH_PLATFORM_WINDOWS + if (commit_size > 0 + && !os_mem_commit(new_mem, commit_size, + MMAP_PROT_READ | MMAP_PROT_WRITE)) { + os_munmap(new_mem, new_size); + return NULL; + } +#endif + + if (os_mprotect(new_mem, commit_size, MMAP_PROT_READ | MMAP_PROT_WRITE) + != 0) { + wasm_munmap_linear_memory(new_mem, new_size, new_size); + return NULL; + } + + return new_mem; +} + +static void * +wasm_mmap_linear_memory(uint64_t map_size, uint64 commit_size) +{ + return wasm_mremap_linear_memory(NULL, 0, map_size, commit_size); +} + bool wasm_enlarge_memory_internal(WASMModuleInstance *module, uint32 inc_page_count) { @@ -638,7 +698,7 @@ wasm_enlarge_memory_internal(WASMModuleInstance *module, uint32 inc_page_count) uint32 num_bytes_per_page, heap_size, total_size_old = 0; uint32 cur_page_count, max_page_count, total_page_count; uint64 total_size_new; - bool ret = true; + bool ret = true, full_size_mmaped; enlarge_memory_error_reason_t failure_reason = INTERNAL_ERROR; if (!memory) { @@ -646,12 +706,20 @@ wasm_enlarge_memory_internal(WASMModuleInstance *module, uint32 inc_page_count) goto return_func; } - heap_data_old = memory->heap_data; - heap_size = (uint32)(memory->heap_data_end - memory->heap_data); +#ifdef OS_ENABLE_HW_BOUND_CHECK + full_size_mmaped = true; +#elif WASM_ENABLE_SHARED_MEMORY != 0 + full_size_mmaped = shared_memory_is_shared(memory); +#else + full_size_mmaped = false; +#endif memory_data_old = memory->memory_data; total_size_old = memory->memory_data_size; + heap_data_old = memory->heap_data; + heap_size = (uint32)(memory->heap_data_end - memory->heap_data); + num_bytes_per_page = memory->num_bytes_per_page; cur_page_count = memory->cur_page_count; max_page_count = memory->max_page_count; @@ -681,166 +749,65 @@ wasm_enlarge_memory_internal(WASMModuleInstance *module, uint32 inc_page_count) total_size_new = UINT32_MAX; } -#if WASM_ENABLE_SHARED_MEMORY != 0 - if (shared_memory_is_shared(memory)) { - memory->num_bytes_per_page = num_bytes_per_page; - memory->cur_page_count = total_page_count; - memory->max_page_count = max_page_count; - SET_LINEAR_MEMORY_SIZE(memory, (uint32)total_size_new); - memory->memory_data_end = memory->memory_data + (uint32)total_size_new; - - wasm_runtime_set_mem_bound_check_bytes(memory, total_size_new); - return true; - } + if (full_size_mmaped) { +#ifdef BH_PLATFORM_WINDOWS + if (!os_mem_commit(memory->memory_data_end, + (uint32)total_size_new - total_size_old, + MMAP_PROT_READ | MMAP_PROT_WRITE)) { + ret = false; + goto return_func; + } #endif - if (heap_size > 0) { - if (mem_allocator_is_heap_corrupted(memory->heap_handle)) { - wasm_runtime_show_app_heap_corrupted_prompt(); - ret = false; - goto return_func; - } - } - - if (!(memory_data_new = - wasm_runtime_realloc(memory_data_old, (uint32)total_size_new))) { - if (!(memory_data_new = wasm_runtime_malloc((uint32)total_size_new))) { - ret = false; - goto return_func; - } - if (memory_data_old) { - bh_memcpy_s(memory_data_new, (uint32)total_size_new, - memory_data_old, total_size_old); - wasm_runtime_free(memory_data_old); - } - } - - memset(memory_data_new + total_size_old, 0, - (uint32)total_size_new - total_size_old); - - if (heap_size > 0) { - if (mem_allocator_migrate(memory->heap_handle, - (char *)heap_data_old - + (memory_data_new - memory_data_old), - heap_size) + if (os_mprotect(memory->memory_data_end, + (uint32)total_size_new - total_size_old, + MMAP_PROT_READ | MMAP_PROT_WRITE) != 0) { - /* Don't return here as memory->memory_data is obsolete and - must be updated to be correctly used later. */ +#ifdef BH_PLATFORM_WINDOWS + os_mem_decommit(memory->memory_data_end, + (uint32)total_size_new - total_size_old); +#endif ret = false; + goto return_func; } } + else { + if (heap_size > 0) { + if (mem_allocator_is_heap_corrupted(memory->heap_handle)) { + wasm_runtime_show_app_heap_corrupted_prompt(); + ret = false; + goto return_func; + } + } - memory->heap_data = memory_data_new + (heap_data_old - memory_data_old); - memory->heap_data_end = memory->heap_data + heap_size; + if (!(memory_data_new = wasm_mremap_linear_memory( + memory_data_old, total_size_old, (uint32)total_size_new, + (uint32)total_size_new))) { + ret = false; + goto return_func; + } - memory->num_bytes_per_page = num_bytes_per_page; - memory->cur_page_count = total_page_count; - memory->max_page_count = max_page_count; - memory->memory_data_size = (uint32)total_size_new; - - memory->memory_data = memory_data_new; - memory->memory_data_end = memory_data_new + (uint32)total_size_new; - - wasm_runtime_set_mem_bound_check_bytes(memory, total_size_new); + if (heap_size > 0) { + if (mem_allocator_migrate(memory->heap_handle, + (char *)heap_data_old + + (memory_data_new - memory_data_old), + heap_size) + != 0) { + /* Don't return here as memory->memory_data is obsolete and + must be updated to be correctly used later. */ + ret = false; + } + } + memory->heap_data = memory_data_new + (heap_data_old - memory_data_old); + memory->heap_data_end = memory->heap_data + heap_size; + memory->memory_data = memory_data_new; #if defined(os_writegsbase) - /* write base addr of linear memory to GS segment register */ - os_writegsbase(memory_data_new); + /* write base addr of linear memory to GS segment register */ + os_writegsbase(memory_data_new); #endif - -return_func: - if (!ret && enlarge_memory_error_cb) { - WASMExecEnv *exec_env = NULL; - -#if WASM_ENABLE_INTERP != 0 - if (module->module_type == Wasm_Module_Bytecode) - exec_env = - ((WASMModuleInstanceExtra *)module->e)->common.cur_exec_env; -#endif -#if WASM_ENABLE_AOT != 0 - if (module->module_type == Wasm_Module_AoT) - exec_env = - ((AOTModuleInstanceExtra *)module->e)->common.cur_exec_env; -#endif - - enlarge_memory_error_cb(inc_page_count, total_size_old, 0, - failure_reason, - (WASMModuleInstanceCommon *)module, exec_env, - enlarge_memory_error_user_data); } - return ret; -} -#else -bool -wasm_enlarge_memory_internal(WASMModuleInstance *module, uint32 inc_page_count) -{ - WASMMemoryInstance *memory = wasm_get_default_memory(module); - uint32 num_bytes_per_page, total_size_old = 0; - uint32 cur_page_count, max_page_count, total_page_count; - uint64 total_size_new; - bool ret = true; - enlarge_memory_error_reason_t failure_reason = INTERNAL_ERROR; - - if (!memory) { - ret = false; - goto return_func; - } - - num_bytes_per_page = memory->num_bytes_per_page; - cur_page_count = memory->cur_page_count; - max_page_count = memory->max_page_count; - total_size_old = num_bytes_per_page * cur_page_count; - total_page_count = inc_page_count + cur_page_count; - total_size_new = num_bytes_per_page * (uint64)total_page_count; - - if (inc_page_count <= 0) - /* No need to enlarge memory */ - return true; - - if (total_page_count < cur_page_count) { /* integer overflow */ - ret = false; - goto return_func; - } - - if (total_page_count > max_page_count) { - failure_reason = MAX_SIZE_REACHED; - ret = false; - goto return_func; - } - - bh_assert(total_size_new <= 4 * (uint64)BH_GB); - if (total_size_new > UINT32_MAX) { - /* Resize to 1 page with size 4G-1 */ - num_bytes_per_page = UINT32_MAX; - total_page_count = max_page_count = 1; - total_size_new = UINT32_MAX; - } - -#ifdef BH_PLATFORM_WINDOWS - if (!os_mem_commit(memory->memory_data_end, - (uint32)total_size_new - total_size_old, - MMAP_PROT_READ | MMAP_PROT_WRITE)) { - ret = false; - goto return_func; - } -#endif - - if (os_mprotect(memory->memory_data_end, - (uint32)total_size_new - total_size_old, - MMAP_PROT_READ | MMAP_PROT_WRITE) - != 0) { -#ifdef BH_PLATFORM_WINDOWS - os_mem_decommit(memory->memory_data_end, - (uint32)total_size_new - total_size_old); -#endif - ret = false; - goto return_func; - } - - /* The increased pages are filled with zero by the OS when os_mmap, - no need to memset it again here */ - memory->num_bytes_per_page = num_bytes_per_page; memory->cur_page_count = total_page_count; memory->max_page_count = max_page_count; @@ -872,7 +839,6 @@ return_func: return ret; } -#endif /* end of OS_ENABLE_HW_BOUND_CHECK */ void wasm_runtime_set_enlarge_mem_error_callback( @@ -899,3 +865,75 @@ wasm_enlarge_memory(WASMModuleInstance *module, uint32 inc_page_count) return ret; } + +void +wasm_deallocate_linear_memory(WASMMemoryInstance *memory_inst) +{ + uint64 map_size; + + bh_assert(memory_inst); + bh_assert(memory_inst->memory_data); + +#ifndef OS_ENABLE_HW_BOUND_CHECK +#if WASM_ENABLE_SHARED_MEMORY != 0 + if (shared_memory_is_shared(memory_inst)) { + map_size = (uint64)memory_inst->num_bytes_per_page + * memory_inst->max_page_count; + } + else +#endif + { + map_size = (uint64)memory_inst->num_bytes_per_page + * memory_inst->cur_page_count; + } +#else + map_size = 8 * (uint64)BH_GB; +#endif + wasm_munmap_linear_memory(memory_inst->memory_data, + memory_inst->memory_data_size, map_size); + memory_inst->memory_data = NULL; +} + +int +wasm_allocate_linear_memory(uint8 **data, bool is_shared_memory, + uint64 num_bytes_per_page, uint64 init_page_count, + uint64 max_page_count, uint64 *memory_data_size) +{ + uint64 map_size, page_size; + + bh_assert(data); + bh_assert(memory_data_size); + +#ifndef OS_ENABLE_HW_BOUND_CHECK +#if WASM_ENABLE_SHARED_MEMORY != 0 + if (is_shared_memory) { + /* Allocate maximum memory size when memory is shared */ + map_size = max_page_count * num_bytes_per_page; + } + else +#endif + { + map_size = init_page_count * num_bytes_per_page; + } +#else /* else of OS_ENABLE_HW_BOUND_CHECK */ + /* Totally 8G is mapped, the opcode load/store address range is 0 to 8G: + * ea = i + memarg.offset + * both i and memarg.offset are u32 in range 0 to 4G + * so the range of ea is 0 to 8G + */ + map_size = 8 * (uint64)BH_GB; +#endif /* end of OS_ENABLE_HW_BOUND_CHECK */ + + page_size = os_getpagesize(); + *memory_data_size = init_page_count * num_bytes_per_page; + bh_assert(*memory_data_size <= UINT32_MAX); + align_as_and_cast(*memory_data_size, page_size); + + if (map_size > 0) { + if (!(*data = wasm_mmap_linear_memory(map_size, *memory_data_size))) { + return BHT_ERROR; + } + } + + return BHT_OK; +} \ No newline at end of file diff --git a/core/iwasm/common/wasm_memory.h b/core/iwasm/common/wasm_memory.h index 9b74db526..381266b61 100644 --- a/core/iwasm/common/wasm_memory.h +++ b/core/iwasm/common/wasm_memory.h @@ -42,6 +42,14 @@ void wasm_runtime_set_enlarge_mem_error_callback( const enlarge_memory_error_callback_t callback, void *user_data); +void +wasm_deallocate_linear_memory(WASMMemoryInstance *memory_inst); + +int +wasm_allocate_linear_memory(uint8 **data, bool is_shared_memory, + uint64 num_bytes_per_page, uint64 init_page_count, + uint64 max_page_count, uint64 *memory_data_size); + #ifdef __cplusplus } #endif diff --git a/core/iwasm/common/wasm_native.c b/core/iwasm/common/wasm_native.c index d2492bc49..3cf7451e3 100644 --- a/core/iwasm/common/wasm_native.c +++ b/core/iwasm/common/wasm_native.c @@ -81,7 +81,17 @@ compare_type_with_signautre(uint8 type, const char signature) } #if WASM_ENABLE_REF_TYPES != 0 - if ('r' == signature && type == VALUE_TYPE_EXTERNREF) + if ('r' == signature +#if WASM_ENABLE_GC != 0 +#if WASM_ENABLE_STRINGREF != 0 + && (type >= REF_TYPE_STRINGVIEWITER && type <= REF_TYPE_FUNCREF) +#else + && (type >= REF_TYPE_NULLREF && type <= REF_TYPE_FUNCREF) +#endif +#else + && type == VALUE_TYPE_EXTERNREF +#endif + ) return true; #endif @@ -90,7 +100,7 @@ compare_type_with_signautre(uint8 type, const char signature) } static bool -check_symbol_signature(const WASMType *type, const char *signature) +check_symbol_signature(const WASMFuncType *type, const char *signature) { const char *p = signature, *p_end; char sig; @@ -189,8 +199,9 @@ lookup_symbol(NativeSymbol *native_symbols, uint32 n_native_symbols, */ void * wasm_native_resolve_symbol(const char *module_name, const char *field_name, - const WASMType *func_type, const char **p_signature, - void **p_attachment, bool *p_call_conv_raw) + const WASMFuncType *func_type, + const char **p_signature, void **p_attachment, + bool *p_call_conv_raw) { NativeSymbolsNode *node, *node_next; const char *signature = NULL; @@ -1442,7 +1453,7 @@ quick_aot_entry_init() } void * -wasm_native_lookup_quick_aot_entry(const WASMType *func_type) +wasm_native_lookup_quick_aot_entry(const WASMFuncType *func_type) { char signature[16] = { 0 }; uint32 param_count = func_type->param_count; diff --git a/core/iwasm/common/wasm_native.h b/core/iwasm/common/wasm_native.h index 591bbe2ff..5cb78bf91 100644 --- a/core/iwasm/common/wasm_native.h +++ b/core/iwasm/common/wasm_native.h @@ -51,8 +51,9 @@ wasm_native_lookup_libc_builtin_global(const char *module_name, */ void * wasm_native_resolve_symbol(const char *module_name, const char *field_name, - const WASMType *func_type, const char **p_signature, - void **p_attachment, bool *p_call_conv_raw); + const WASMFuncType *func_type, + const char **p_signature, void **p_attachment, + bool *p_call_conv_raw); bool wasm_native_register_natives(const char *module_name, @@ -106,7 +107,7 @@ wasm_native_destroy(); #if WASM_ENABLE_QUICK_AOT_ENTRY != 0 void * -wasm_native_lookup_quick_aot_entry(const WASMType *func_type); +wasm_native_lookup_quick_aot_entry(const WASMFuncType *func_type); #endif #ifdef __cplusplus diff --git a/core/iwasm/common/wasm_runtime_common.c b/core/iwasm/common/wasm_runtime_common.c index eaee4f225..86bf14ffe 100644 --- a/core/iwasm/common/wasm_runtime_common.c +++ b/core/iwasm/common/wasm_runtime_common.c @@ -19,6 +19,9 @@ #include "../aot/debug/jit_debug.h" #endif #endif +#if WASM_ENABLE_GC != 0 +#include "gc/gc_object.h" +#endif #if WASM_ENABLE_THREAD_MGR != 0 #include "../libraries/thread-mgr/thread_manager.h" #if WASM_ENABLE_DEBUG_INTERP != 0 @@ -88,7 +91,7 @@ wasm_runtime_destroy_registered_module_list(); #define E_TYPE_XIP 4 -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 /* Initialize externref hashmap */ static bool wasm_externref_map_init(); @@ -96,7 +99,7 @@ wasm_externref_map_init(); /* Destroy externref hashmap */ static void wasm_externref_map_destroy(); -#endif /* WASM_ENABLE_REF_TYPES */ +#endif /* end of WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 */ static void set_error_buf(char *error_buf, uint32 error_buf_size, const char *string) @@ -163,6 +166,10 @@ static JitCompOptions jit_options = { 0 }; static LLVMJITOptions llvm_jit_options = { 3, 3, 0, false }; #endif +#if WASM_ENABLE_GC != 0 +static uint32 gc_heap_size_default = GC_HEAP_SIZE_DEFAULT; +#endif + static RunningMode runtime_running_mode = Mode_Default; #ifdef OS_ENABLE_HW_BOUND_CHECK @@ -376,7 +383,7 @@ runtime_exception_handler(EXCEPTION_POINTERS *exce_info) #endif } - os_printf("Unhandled exception thrown: exception code: 0x%lx, " + LOG_ERROR("Unhandled exception thrown: exception code: 0x%lx, " "exception address: %p, exception information: %p\n", ExceptionRecord->ExceptionCode, ExceptionRecord->ExceptionAddress, sig_addr); @@ -469,7 +476,7 @@ wasm_runtime_env_init() #endif #endif -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 if (!wasm_externref_map_init()) { goto fail8; } @@ -510,11 +517,11 @@ fail10: #endif #if WASM_ENABLE_FAST_JIT != 0 fail9: -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 wasm_externref_map_destroy(); #endif #endif -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 fail8: #endif #if WASM_ENABLE_AOT != 0 @@ -552,9 +559,9 @@ static bool wasm_runtime_exec_env_check(WASMExecEnv *exec_env) { return exec_env && exec_env->module_inst && exec_env->wasm_stack_size > 0 - && exec_env->wasm_stack.s.top_boundary - == exec_env->wasm_stack.s.bottom + exec_env->wasm_stack_size - && exec_env->wasm_stack.s.top <= exec_env->wasm_stack.s.top_boundary; + && exec_env->wasm_stack.top_boundary + == exec_env->wasm_stack.bottom + exec_env->wasm_stack_size + && exec_env->wasm_stack.top <= exec_env->wasm_stack.top_boundary; } bool @@ -574,7 +581,7 @@ wasm_runtime_init() void wasm_runtime_destroy() { -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 wasm_externref_map_destroy(); #endif @@ -647,6 +654,14 @@ wasm_runtime_get_llvm_jit_options(void) } #endif +#if WASM_ENABLE_GC != 0 +uint32 +wasm_runtime_get_gc_heap_size_default(void) +{ + return gc_heap_size_default; +} +#endif + bool wasm_runtime_full_init(RuntimeInitArgs *init_args) { @@ -663,6 +678,10 @@ wasm_runtime_full_init(RuntimeInitArgs *init_args) jit_options.code_cache_size = init_args->fast_jit_code_cache_size; #endif +#if WASM_ENABLE_GC != 0 + gc_heap_size_default = init_args->gc_heap_size; +#endif + #if WASM_ENABLE_JIT != 0 llvm_jit_options.size_level = init_args->llvm_jit_size_level; llvm_jit_options.opt_level = init_args->llvm_jit_opt_level; @@ -1572,11 +1591,11 @@ void wasm_runtime_dump_exec_env_mem_consumption(const WASMExecEnv *exec_env) { uint32 total_size = - offsetof(WASMExecEnv, wasm_stack.s.bottom) + exec_env->wasm_stack_size; + offsetof(WASMExecEnv, wasm_stack_u.bottom) + exec_env->wasm_stack_size; os_printf("Exec env memory consumption, total size: %u\n", total_size); os_printf(" exec env struct size: %u\n", - offsetof(WASMExecEnv, wasm_stack.s.bottom)); + offsetof(WASMExecEnv, wasm_stack_u.bottom)); #if WASM_ENABLE_INTERP != 0 && WASM_ENABLE_FAST_INTERP == 0 os_printf(" block addr cache size: %u\n", sizeof(exec_env->block_addr_cache)); @@ -1637,7 +1656,7 @@ wasm_runtime_dump_mem_consumption(WASMExecEnv *exec_env) app_heap_peak_size = gc_get_heap_highmark_size(heap_handle); } - total_size = offsetof(WASMExecEnv, wasm_stack.s.bottom) + total_size = offsetof(WASMExecEnv, wasm_stack_u.bottom) + exec_env->wasm_stack_size + module_mem_consps.total_size + module_inst_mem_consps.total_size; @@ -1771,11 +1790,11 @@ wasm_runtime_access_exce_check_guard_page() } #endif -WASMType * +WASMFuncType * wasm_runtime_get_function_type(const WASMFunctionInstanceCommon *function, uint32 module_type) { - WASMType *type = NULL; + WASMFuncType *type = NULL; #if WASM_ENABLE_INTERP != 0 if (module_type == Wasm_Module_Bytecode) { @@ -1816,7 +1835,7 @@ uint32 wasm_func_get_param_count(WASMFunctionInstanceCommon *const func_inst, WASMModuleInstanceCommon *const module_inst) { - WASMType *type = + WASMFuncType *type = wasm_runtime_get_function_type(func_inst, module_inst->module_type); bh_assert(type); @@ -1827,7 +1846,7 @@ uint32 wasm_func_get_result_count(WASMFunctionInstanceCommon *const func_inst, WASMModuleInstanceCommon *const module_inst) { - WASMType *type = + WASMFuncType *type = wasm_runtime_get_function_type(func_inst, module_inst->module_type); bh_assert(type); @@ -1861,7 +1880,7 @@ wasm_func_get_param_types(WASMFunctionInstanceCommon *const func_inst, WASMModuleInstanceCommon *const module_inst, wasm_valkind_t *param_types) { - WASMType *type = + WASMFuncType *type = wasm_runtime_get_function_type(func_inst, module_inst->module_type); uint32 i; @@ -1877,7 +1896,7 @@ wasm_func_get_result_types(WASMFunctionInstanceCommon *const func_inst, WASMModuleInstanceCommon *const module_inst, wasm_valkind_t *result_types) { - WASMType *type = + WASMFuncType *type = wasm_runtime_get_function_type(func_inst, module_inst->module_type); uint32 i; @@ -1889,7 +1908,7 @@ wasm_func_get_result_types(WASMFunctionInstanceCommon *const func_inst, } } -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 /* (uintptr_t)externref -> (uint32)index */ /* argv -> *ret_argv */ static bool @@ -1903,7 +1922,7 @@ wasm_runtime_prepare_call_function(WASMExecEnv *exec_env, result_i = 0; bool need_param_transform = false, need_result_transform = false; uint64 size = 0; - WASMType *func_type = wasm_runtime_get_function_type( + WASMFuncType *func_type = wasm_runtime_get_function_type( function, exec_env->module_inst->module_type); bh_assert(func_type); @@ -1996,7 +2015,7 @@ wasm_runtime_finalize_call_function(WASMExecEnv *exec_env, uint32 *argv, uint32 argc, uint32 *ret_argv) { uint32 argv_i = 0, result_i = 0, ret_argv_i = 0; - WASMType *func_type; + WASMFuncType *func_type; bh_assert((argv && ret_argv) || (argc == 0)); @@ -2058,7 +2077,7 @@ wasm_runtime_call_wasm(WASMExecEnv *exec_env, { bool ret = false; uint32 *new_argv = NULL, param_argc; -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 uint32 result_argc = 0; #endif @@ -2067,7 +2086,7 @@ wasm_runtime_call_wasm(WASMExecEnv *exec_env, return false; } -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 if (!wasm_runtime_prepare_call_function(exec_env, function, argv, argc, &new_argv, ¶m_argc, &result_argc)) { @@ -2097,7 +2116,7 @@ wasm_runtime_call_wasm(WASMExecEnv *exec_env, return false; } -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 if (!wasm_runtime_finalize_call_function(exec_env, function, new_argv, result_argc, argv)) { wasm_runtime_set_exception(exec_env->module_inst, @@ -2110,7 +2129,8 @@ wasm_runtime_call_wasm(WASMExecEnv *exec_env, } static void -parse_args_to_uint32_array(WASMType *type, wasm_val_t *args, uint32 *out_argv) +parse_args_to_uint32_array(WASMFuncType *type, wasm_val_t *args, + uint32 *out_argv) { uint32 i, p; @@ -2152,11 +2172,15 @@ parse_args_to_uint32_array(WASMType *type, wasm_val_t *args, uint32 *out_argv) break; } #if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 case WASM_FUNCREF: { out_argv[p++] = args[i].of.i32; break; } +#else + case WASM_FUNCREF: +#endif case WASM_ANYREF: { #if UINTPTR_MAX == UINT32_MAX @@ -2182,7 +2206,7 @@ parse_args_to_uint32_array(WASMType *type, wasm_val_t *args, uint32 *out_argv) } static void -parse_uint32_array_to_results(WASMType *type, uint32 *argv, +parse_uint32_array_to_results(WASMFuncType *type, uint32 *argv, wasm_val_t *out_results) { uint32 i, p; @@ -2229,6 +2253,7 @@ parse_uint32_array_to_results(WASMType *type, uint32 *argv, break; } #if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 case VALUE_TYPE_FUNCREF: { out_results[i].kind = WASM_I32; @@ -2236,6 +2261,20 @@ parse_uint32_array_to_results(WASMType *type, uint32 *argv, break; } case VALUE_TYPE_EXTERNREF: +#else + case REF_TYPE_FUNCREF: + case REF_TYPE_EXTERNREF: + case REF_TYPE_ANYREF: + case REF_TYPE_EQREF: + case REF_TYPE_HT_NULLABLE: + case REF_TYPE_HT_NON_NULLABLE: + case REF_TYPE_I31REF: + case REF_TYPE_NULLFUNCREF: + case REF_TYPE_NULLEXTERNREF: + case REF_TYPE_STRUCTREF: + case REF_TYPE_ARRAYREF: + case REF_TYPE_NULLREF: +#endif /* end of WASM_ENABLE_GC == 0 */ { #if UINTPTR_MAX == UINT32_MAX out_results[i].kind = WASM_ANYREF; @@ -2252,7 +2291,7 @@ parse_uint32_array_to_results(WASMType *type, uint32 *argv, #endif break; } -#endif +#endif /* end of WASM_ENABLE_REF_TYPES != 0 */ default: bh_assert(0); break; @@ -2267,11 +2306,11 @@ wasm_runtime_call_wasm_a(WASMExecEnv *exec_env, uint32 num_args, wasm_val_t args[]) { uint32 argc, argv_buf[16] = { 0 }, *argv = argv_buf, cell_num, module_type; -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 uint32 i, param_size_in_double_world = 0, result_size_in_double_world = 0; #endif uint64 total_size; - WASMType *type; + WASMFuncType *type; bool ret = false; module_type = exec_env->module_inst->module_type; @@ -2283,7 +2322,7 @@ wasm_runtime_call_wasm_a(WASMExecEnv *exec_env, goto fail1; } -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 for (i = 0; i < type->param_count; i++) { param_size_in_double_world += wasm_value_type_cell_num_outside(type->types[i]); @@ -2341,7 +2380,7 @@ wasm_runtime_call_wasm_v(WASMExecEnv *exec_env, uint32 num_args, ...) { wasm_val_t args_buf[8] = { 0 }, *args = args_buf; - WASMType *type = NULL; + WASMFuncType *type = NULL; bool ret = false; uint64 total_size; uint32 i = 0, module_type; @@ -2389,7 +2428,7 @@ wasm_runtime_call_wasm_v(WASMExecEnv *exec_env, args[i].kind = WASM_F64; args[i].of.f64 = va_arg(vargs, float64); break; -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case VALUE_TYPE_FUNCREF: { args[i].kind = WASM_FUNCREF; @@ -2506,6 +2545,23 @@ static const char *exception_msgs[] = { "out of bounds table access", /* EXCE_OUT_OF_BOUNDS_TABLE_ACCESS */ "wasm operand stack overflow", /* EXCE_OPERAND_STACK_OVERFLOW */ "failed to compile fast jit function", /* EXCE_FAILED_TO_COMPILE_FAST_JIT_FUNC */ + /* GC related exceptions */ + "null function object", /* EXCE_NULL_FUNC_OBJ */ + "null structure object", /* EXCE_NULL_STRUCT_OBJ */ + "null array reference", /* EXCE_NULL_ARRAY_OBJ */ + "null i31 reference", /* EXCE_NULL_I31_OBJ */ + "null reference", /* EXCE_NULL_REFERENCE */ + "create rtt type failed", /* EXCE_FAILED_TO_CREATE_RTT_TYPE */ + "create struct object failed", /* EXCE_FAILED_TO_CREATE_STRUCT_OBJ */ + "create array object failed", /* EXCE_FAILED_TO_CREATE_ARRAY_OBJ */ + "create externref object failed", /* EXCE_FAILED_TO_CREATE_EXTERNREF_OBJ */ + "cast failure", /* EXCE_CAST_FAILURE */ + "out of bounds array access", /* EXCE_ARRAY_IDX_OOB */ + /* stringref related exceptions */ + "create string object failed", /* EXCE_FAILED_TO_CREATE_STRING */ + "create stringref failed", /* EXCE_FAILED_TO_CREATE_STRINGREF */ + "create stringview failed", /* EXCE_FAILED_TO_CREATE_STRINGVIEW */ + "encode failed", /* EXCE_FAILED_TO_ENCODE_STRING */ "", /* EXCE_ALREADY_THROWN */ }; /* clang-format on */ @@ -3568,13 +3624,13 @@ wasm_runtime_unregister_natives(const char *module_name, bool wasm_runtime_invoke_native_raw(WASMExecEnv *exec_env, void *func_ptr, - const WASMType *func_type, const char *signature, - void *attachment, uint32 *argv, uint32 argc, - uint32 *argv_ret) + const WASMFuncType *func_type, + const char *signature, void *attachment, + uint32 *argv, uint32 argc, uint32 *argv_ret) { WASMModuleInstanceCommon *module = wasm_runtime_get_module_inst(exec_env); typedef void (*NativeRawFuncPtr)(WASMExecEnv *, uint64 *); - NativeRawFuncPtr invokeNativeRaw = (NativeRawFuncPtr)func_ptr; + NativeRawFuncPtr invoke_native_raw = (NativeRawFuncPtr)func_ptr; uint64 argv_buf[16] = { 0 }, *argv1 = argv_buf, *argv_dst, size; uint32 *argv_src = argv, i, argc1, ptr_len; uint32 arg_i32; @@ -3595,7 +3651,7 @@ wasm_runtime_invoke_native_raw(WASMExecEnv *exec_env, void *func_ptr, for (i = 0; i < func_type->param_count; i++, argv_dst++) { switch (func_type->types[i]) { case VALUE_TYPE_I32: -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case VALUE_TYPE_FUNCREF: #endif { @@ -3640,7 +3696,7 @@ wasm_runtime_invoke_native_raw(WASMExecEnv *exec_env, void *func_ptr, case VALUE_TYPE_F32: *(float32 *)argv_dst = *(float32 *)argv_src++; break; -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case VALUE_TYPE_EXTERNREF: { uint32 externref_idx = *argv_src++; @@ -3654,6 +3710,32 @@ wasm_runtime_invoke_native_raw(WASMExecEnv *exec_env, void *func_ptr, sizeof(uintptr_t)); break; } +#endif +#if WASM_ENABLE_GC != 0 + case REF_TYPE_FUNCREF: + case REF_TYPE_EXTERNREF: + case REF_TYPE_ANYREF: + case REF_TYPE_EQREF: + case REF_TYPE_HT_NULLABLE: + case REF_TYPE_HT_NON_NULLABLE: + case REF_TYPE_I31REF: + case REF_TYPE_NULLFUNCREF: + case REF_TYPE_NULLEXTERNREF: + case REF_TYPE_STRUCTREF: + case REF_TYPE_ARRAYREF: + case REF_TYPE_NULLREF: +#if WASM_ENABLE_STRINGREF != 0 + case REF_TYPE_STRINGREF: + case REF_TYPE_STRINGVIEWWTF8: + case REF_TYPE_STRINGVIEWWTF16: + case REF_TYPE_STRINGVIEWITER: +#endif + { + bh_memcpy_s(argv_dst, sizeof(uintptr_t), argv_src, + sizeof(uintptr_t)); + argv_src += sizeof(uintptr_t) / sizeof(uint32); + break; + } #endif default: bh_assert(0); @@ -3662,13 +3744,13 @@ wasm_runtime_invoke_native_raw(WASMExecEnv *exec_env, void *func_ptr, } exec_env->attachment = attachment; - invokeNativeRaw(exec_env, argv1); + invoke_native_raw(exec_env, argv1); exec_env->attachment = NULL; if (func_type->result_count > 0) { switch (func_type->types[func_type->param_count]) { case VALUE_TYPE_I32: -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case VALUE_TYPE_FUNCREF: #endif argv_ret[0] = *(uint32 *)argv1; @@ -3681,7 +3763,7 @@ wasm_runtime_invoke_native_raw(WASMExecEnv *exec_env, void *func_ptr, bh_memcpy_s(argv_ret, sizeof(uint32) * 2, argv1, sizeof(uint64)); break; -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case VALUE_TYPE_EXTERNREF: { uint32 externref_idx; @@ -3697,6 +3779,31 @@ wasm_runtime_invoke_native_raw(WASMExecEnv *exec_env, void *func_ptr, argv_ret[0] = externref_idx; break; } +#endif +#if WASM_ENABLE_GC != 0 + case REF_TYPE_FUNCREF: + case REF_TYPE_EXTERNREF: + case REF_TYPE_ANYREF: + case REF_TYPE_EQREF: + case REF_TYPE_HT_NULLABLE: + case REF_TYPE_HT_NON_NULLABLE: + case REF_TYPE_I31REF: + case REF_TYPE_NULLFUNCREF: + case REF_TYPE_NULLEXTERNREF: + case REF_TYPE_STRUCTREF: + case REF_TYPE_ARRAYREF: + case REF_TYPE_NULLREF: +#if WASM_ENABLE_STRINGREF != 0 + case REF_TYPE_STRINGREF: + case REF_TYPE_STRINGVIEWWTF8: + case REF_TYPE_STRINGVIEWWTF16: + case REF_TYPE_STRINGVIEWITER: +#endif + { + bh_memcpy_s(argv_ret, sizeof(uintptr_t), argv1, + sizeof(uintptr_t)); + break; + } #endif default: bh_assert(0); @@ -3751,7 +3858,7 @@ static volatile VoidFuncPtr invokeNative_Void = bool wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, - const WASMType *func_type, const char *signature, + const WASMFuncType *func_type, const char *signature, void *attachment, uint32 *argv, uint32 argc, uint32 *argv_ret) { @@ -3764,7 +3871,7 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, uint32 result_count = func_type->result_count; uint32 ext_ret_count = result_count > 1 ? result_count - 1 : 0; bool ret = false; -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 bool is_aot_func = (NULL == signature); #endif #if !defined(BUILD_TARGET_RISCV32_ILP32) && !defined(BUILD_TARGET_ARC) @@ -3781,7 +3888,27 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, for (i = 0; i < func_type->param_count; i++) { switch (func_type->types[i]) { case VALUE_TYPE_I32: -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC != 0 + case REF_TYPE_FUNCREF: + case REF_TYPE_EXTERNREF: + case REF_TYPE_ANYREF: + case REF_TYPE_EQREF: + case REF_TYPE_HT_NULLABLE: + case REF_TYPE_HT_NON_NULLABLE: + case REF_TYPE_I31REF: + case REF_TYPE_NULLFUNCREF: + case REF_TYPE_NULLEXTERNREF: + case REF_TYPE_STRUCTREF: + case REF_TYPE_ARRAYREF: + case REF_TYPE_NULLREF: +#if WASM_ENABLE_STRINGREF != 0 + case REF_TYPE_STRINGREF: + case REF_TYPE_STRINGVIEWWTF8: + case REF_TYPE_STRINGVIEWWTF16: + case REF_TYPE_STRINGVIEWITER: +#endif +#endif +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case VALUE_TYPE_FUNCREF: case VALUE_TYPE_EXTERNREF: #endif @@ -3925,7 +4052,27 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, for (i = 0; i < func_type->param_count; i++) { switch (func_type->types[i]) { case VALUE_TYPE_I32: -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC != 0 + case REF_TYPE_FUNCREF: + case REF_TYPE_EXTERNREF: + case REF_TYPE_ANYREF: + case REF_TYPE_EQREF: + case REF_TYPE_HT_NULLABLE: + case REF_TYPE_HT_NON_NULLABLE: + case REF_TYPE_I31REF: + case REF_TYPE_NULLFUNCREF: + case REF_TYPE_NULLEXTERNREF: + case REF_TYPE_STRUCTREF: + case REF_TYPE_ARRAYREF: + case REF_TYPE_NULLREF: +#if WASM_ENABLE_STRINGREF != 0 + case REF_TYPE_STRINGREF: + case REF_TYPE_STRINGVIEWWTF8: + case REF_TYPE_STRINGVIEWWTF16: + case REF_TYPE_STRINGVIEWITER: +#endif +#endif +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case VALUE_TYPE_FUNCREF: #endif { @@ -4082,7 +4229,7 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, break; } #endif /* BUILD_TARGET_RISCV32_ILP32D */ -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case VALUE_TYPE_EXTERNREF: { uint32 externref_idx = *argv_src++; @@ -4128,7 +4275,27 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, else { switch (func_type->types[func_type->param_count]) { case VALUE_TYPE_I32: -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC != 0 + case REF_TYPE_FUNCREF: + case REF_TYPE_EXTERNREF: + case REF_TYPE_ANYREF: + case REF_TYPE_EQREF: + case REF_TYPE_HT_NULLABLE: + case REF_TYPE_HT_NON_NULLABLE: + case REF_TYPE_I31REF: + case REF_TYPE_NULLFUNCREF: + case REF_TYPE_NULLEXTERNREF: + case REF_TYPE_STRUCTREF: + case REF_TYPE_ARRAYREF: + case REF_TYPE_NULLREF: +#if WASM_ENABLE_STRINGREF != 0 + case REF_TYPE_STRINGREF: + case REF_TYPE_STRINGVIEWWTF8: + case REF_TYPE_STRINGVIEWWTF16: + case REF_TYPE_STRINGVIEWITER: +#endif +#endif +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case VALUE_TYPE_FUNCREF: #endif argv_ret[0] = @@ -4146,7 +4313,7 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, PUT_F64_TO_ADDR( argv_ret, invokeNative_Float64(func_ptr, argv1, n_stacks)); break; -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case VALUE_TYPE_EXTERNREF: { if (is_aot_func) { @@ -4223,7 +4390,7 @@ word_copy(uint32 *dest, uint32 *src, unsigned num) bool wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, - const WASMType *func_type, const char *signature, + const WASMFuncType *func_type, const char *signature, void *attachment, uint32 *argv, uint32 argc, uint32 *argv_ret) { @@ -4234,7 +4401,7 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, uint32 ext_ret_count = result_count > 1 ? result_count - 1 : 0; uint64 size; bool ret = false; -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 bool is_aot_func = (NULL == signature); #endif @@ -4260,7 +4427,27 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, for (i = 0; i < func_type->param_count; i++) { switch (func_type->types[i]) { case VALUE_TYPE_I32: -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC != 0 + case REF_TYPE_FUNCREF: + case REF_TYPE_EXTERNREF: + case REF_TYPE_ANYREF: + case REF_TYPE_EQREF: + case REF_TYPE_HT_NULLABLE: + case REF_TYPE_HT_NON_NULLABLE: + case REF_TYPE_I31REF: + case REF_TYPE_NULLFUNCREF: + case REF_TYPE_NULLEXTERNREF: + case REF_TYPE_STRUCTREF: + case REF_TYPE_ARRAYREF: + case REF_TYPE_NULLREF: +#if WASM_ENABLE_STRINGREF != 0 + case REF_TYPE_STRINGREF: + case REF_TYPE_STRINGVIEWWTF8: + case REF_TYPE_STRINGVIEWWTF16: + case REF_TYPE_STRINGVIEWITER: +#endif +#endif +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case VALUE_TYPE_FUNCREF: #endif { @@ -4311,7 +4498,7 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, case VALUE_TYPE_F32: argv1[j++] = *argv++; break; -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case VALUE_TYPE_EXTERNREF: { uint32 externref_idx = *argv++; @@ -4346,7 +4533,27 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, else { switch (func_type->types[func_type->param_count]) { case VALUE_TYPE_I32: -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC != 0 + case REF_TYPE_FUNCREF: + case REF_TYPE_EXTERNREF: + case REF_TYPE_ANYREF: + case REF_TYPE_EQREF: + case REF_TYPE_HT_NULLABLE: + case REF_TYPE_HT_NON_NULLABLE: + case REF_TYPE_I31REF: + case REF_TYPE_NULLFUNCREF: + case REF_TYPE_NULLEXTERNREF: + case REF_TYPE_STRUCTREF: + case REF_TYPE_ARRAYREF: + case REF_TYPE_NULLREF: +#if WASM_ENABLE_STRINGREF != 0 + case REF_TYPE_STRINGREF: + case REF_TYPE_STRINGVIEWWTF8: + case REF_TYPE_STRINGVIEWWTF16: + case REF_TYPE_STRINGVIEWITER: +#endif +#endif +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case VALUE_TYPE_FUNCREF: #endif argv_ret[0] = @@ -4364,7 +4571,7 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, PUT_F64_TO_ADDR(argv_ret, invokeNative_Float64(func_ptr, argv1, argc1)); break; -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case VALUE_TYPE_EXTERNREF: { if (is_aot_func) { @@ -4491,7 +4698,7 @@ __attribute__((no_sanitize_address)) #endif bool wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, - const WASMType *func_type, const char *signature, + const WASMFuncType *func_type, const char *signature, void *attachment, uint32 *argv, uint32 argc, uint32 *argv_ret) { @@ -4503,7 +4710,7 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, uint32 result_count = func_type->result_count; uint32 ext_ret_count = result_count > 1 ? result_count - 1 : 0; bool ret = false; -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 bool is_aot_func = (NULL == signature); #endif #ifndef BUILD_TARGET_RISCV64_LP64 @@ -4555,7 +4762,7 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, for (i = 0; i < func_type->param_count; i++) { switch (func_type->types[i]) { case VALUE_TYPE_I32: -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case VALUE_TYPE_FUNCREF: #endif { @@ -4595,6 +4802,26 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, break; } case VALUE_TYPE_I64: +#if WASM_ENABLE_GC != 0 + case REF_TYPE_FUNCREF: + case REF_TYPE_EXTERNREF: + case REF_TYPE_ANYREF: + case REF_TYPE_EQREF: + case REF_TYPE_HT_NULLABLE: + case REF_TYPE_HT_NON_NULLABLE: + case REF_TYPE_I31REF: + case REF_TYPE_NULLFUNCREF: + case REF_TYPE_NULLEXTERNREF: + case REF_TYPE_STRUCTREF: + case REF_TYPE_ARRAYREF: + case REF_TYPE_NULLREF: +#if WASM_ENABLE_STRINGREF != 0 + case REF_TYPE_STRINGREF: + case REF_TYPE_STRINGVIEWWTF8: + case REF_TYPE_STRINGVIEWWTF16: + case REF_TYPE_STRINGVIEWITER: +#endif +#endif if (n_ints < MAX_REG_INTS) ints[n_ints++] = *(uint64 *)argv_src; else @@ -4618,7 +4845,7 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, } argv_src += 2; break; -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case VALUE_TYPE_EXTERNREF: { uint32 externref_idx = *argv_src++; @@ -4677,13 +4904,33 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, /* Invoke the native function and get the first result value */ switch (func_type->types[func_type->param_count]) { case VALUE_TYPE_I32: -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case VALUE_TYPE_FUNCREF: #endif argv_ret[0] = (uint32)invokeNative_Int32(func_ptr, argv1, n_stacks); break; case VALUE_TYPE_I64: +#if WASM_ENABLE_GC != 0 + case REF_TYPE_FUNCREF: + case REF_TYPE_EXTERNREF: + case REF_TYPE_ANYREF: + case REF_TYPE_EQREF: + case REF_TYPE_HT_NULLABLE: + case REF_TYPE_HT_NON_NULLABLE: + case REF_TYPE_I31REF: + case REF_TYPE_NULLFUNCREF: + case REF_TYPE_NULLEXTERNREF: + case REF_TYPE_STRUCTREF: + case REF_TYPE_ARRAYREF: + case REF_TYPE_NULLREF: +#if WASM_ENABLE_STRINGREF != 0 + case REF_TYPE_STRINGREF: + case REF_TYPE_STRINGVIEWWTF8: + case REF_TYPE_STRINGVIEWWTF16: + case REF_TYPE_STRINGVIEWITER: +#endif +#endif PUT_I64_TO_ADDR(argv_ret, invokeNative_Int64(func_ptr, argv1, n_stacks)); break; @@ -4695,7 +4942,7 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, PUT_F64_TO_ADDR( argv_ret, invokeNative_Float64(func_ptr, argv1, n_stacks)); break; -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case VALUE_TYPE_EXTERNREF: { if (is_aot_func) { @@ -4887,7 +5134,7 @@ wasm_runtime_join_thread(wasm_thread_t tid, void **retval) #endif /* end of WASM_ENABLE_THREAD_MGR */ -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 static korp_mutex externref_lock; static uint32 externref_global_id = 1; @@ -5167,7 +5414,8 @@ mark_externref(uint32 externref_idx) static void interp_mark_all_externrefs(WASMModuleInstance *module_inst) { - uint32 i, j, externref_idx, *table_data; + uint32 i, j, externref_idx; + table_elem_type_t *table_data; uint8 *global_data = module_inst->global_data; WASMGlobalInstance *global; WASMTableInstance *table; @@ -5289,7 +5537,7 @@ wasm_externref_retain(uint32 externref_idx) os_mutex_unlock(&externref_lock); return false; } -#endif /* end of WASM_ENABLE_REF_TYPES */ +#endif /* end of WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 */ #if WASM_ENABLE_DUMP_CALL_STACK != 0 uint32 @@ -5405,6 +5653,9 @@ wasm_runtime_dump_pgo_prof_data_to_buf(WASMModuleInstanceCommon *module_inst, bool wasm_runtime_get_table_elem_type(const WASMModuleCommon *module_comm, uint32 table_idx, uint8 *out_elem_type, +#if WASM_ENABLE_GC != 0 + WASMRefType **out_ref_type, +#endif uint32 *out_min_size, uint32 *out_max_size) { #if WASM_ENABLE_INTERP != 0 @@ -5415,6 +5666,9 @@ wasm_runtime_get_table_elem_type(const WASMModuleCommon *module_comm, WASMTableImport *import_table = &((module->import_tables + table_idx)->u.table); *out_elem_type = import_table->elem_type; +#if WASM_ENABLE_GC != 0 + *out_ref_type = import_table->elem_ref_type; +#endif *out_min_size = import_table->init_size; *out_max_size = import_table->max_size; } @@ -5422,6 +5676,9 @@ wasm_runtime_get_table_elem_type(const WASMModuleCommon *module_comm, WASMTable *table = module->tables + (table_idx - module->import_table_count); *out_elem_type = table->elem_type; +#if WASM_ENABLE_GC != 0 + *out_ref_type = table->elem_ref_type; +#endif *out_min_size = table->init_size; *out_max_size = table->max_size; } @@ -5435,7 +5692,10 @@ wasm_runtime_get_table_elem_type(const WASMModuleCommon *module_comm, if (table_idx < module->import_table_count) { AOTImportTable *import_table = module->import_tables + table_idx; - *out_elem_type = VALUE_TYPE_FUNCREF; + *out_elem_type = import_table->elem_type; +#if WASM_ENABLE_GC != 0 + *out_ref_type = NULL; /* TODO */ +#endif *out_min_size = import_table->table_init_size; *out_max_size = import_table->table_max_size; } @@ -5443,6 +5703,9 @@ wasm_runtime_get_table_elem_type(const WASMModuleCommon *module_comm, AOTTable *table = module->tables + (table_idx - module->import_table_count); *out_elem_type = table->elem_type; +#if WASM_ENABLE_GC != 0 + *out_ref_type = NULL; /* TODO */ +#endif *out_min_size = table->table_init_size; *out_max_size = table->table_max_size; } @@ -5456,31 +5719,28 @@ wasm_runtime_get_table_elem_type(const WASMModuleCommon *module_comm, bool wasm_runtime_get_table_inst_elem_type( const WASMModuleInstanceCommon *module_inst_comm, uint32 table_idx, - uint8 *out_elem_type, uint32 *out_min_size, uint32 *out_max_size) + uint8 *out_elem_type, +#if WASM_ENABLE_GC != 0 + WASMRefType **out_ref_type, +#endif + uint32 *out_min_size, uint32 *out_max_size) { -#if WASM_ENABLE_INTERP != 0 - if (module_inst_comm->module_type == Wasm_Module_Bytecode) { - WASMModuleInstance *module_inst = - (WASMModuleInstance *)module_inst_comm; - return wasm_runtime_get_table_elem_type( - (WASMModuleCommon *)module_inst->module, table_idx, out_elem_type, - out_min_size, out_max_size); - } + WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm; + + bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode + || module_inst_comm->module_type == Wasm_Module_AoT); + + return wasm_runtime_get_table_elem_type( + (WASMModuleCommon *)module_inst->module, table_idx, out_elem_type, +#if WASM_ENABLE_GC != 0 + out_ref_type, #endif -#if WASM_ENABLE_AOT != 0 - if (module_inst_comm->module_type == Wasm_Module_AoT) { - AOTModuleInstance *module_inst = (AOTModuleInstance *)module_inst_comm; - return wasm_runtime_get_table_elem_type( - (WASMModuleCommon *)module_inst->module, table_idx, out_elem_type, - out_min_size, out_max_size); - } -#endif - return false; + out_min_size, out_max_size); } bool wasm_runtime_get_export_func_type(const WASMModuleCommon *module_comm, - const WASMExport *export, WASMType **out) + const WASMExport *export, WASMFuncType **out) { #if WASM_ENABLE_INTERP != 0 if (module_comm->module_type == Wasm_Module_Bytecode) { @@ -5503,13 +5763,14 @@ wasm_runtime_get_export_func_type(const WASMModuleCommon *module_comm, AOTModule *module = (AOTModule *)module_comm; if (export->index < module->import_func_count) { - *out = module->func_types[module->import_funcs[export->index] - .func_type_index]; + *out = (WASMFuncType *) + module->types[module->import_funcs[export->index] + .func_type_index]; } else { - *out = module->func_types - [module->func_type_indexes[export->index - - module->import_func_count]]; + *out = (WASMFuncType *)module + ->types[module->func_type_indexes + [export->index - module->import_func_count]]; } return true; } @@ -5615,15 +5876,23 @@ wasm_runtime_get_export_memory_type(const WASMModuleCommon *module_comm, bool wasm_runtime_get_export_table_type(const WASMModuleCommon *module_comm, const WASMExport *export, - uint8 *out_elem_type, uint32 *out_min_size, - uint32 *out_max_size) + uint8 *out_elem_type, +#if WASM_ENABLE_GC != 0 + WASMRefType **out_ref_type, +#endif + uint32 *out_min_size, uint32 *out_max_size) { - return wasm_runtime_get_table_elem_type( - module_comm, export->index, out_elem_type, out_min_size, out_max_size); + return wasm_runtime_get_table_elem_type(module_comm, export->index, + out_elem_type, +#if WASM_ENABLE_GC != 0 + out_ref_type, +#endif + out_min_size, out_max_size); } static inline bool -argv_to_params(wasm_val_t *out_params, const uint32 *argv, WASMType *func_type) +argv_to_params(wasm_val_t *out_params, const uint32 *argv, + WASMFuncType *func_type) { wasm_val_t *param = out_params; uint32 i = 0, *u32; @@ -5650,7 +5919,7 @@ argv_to_params(wasm_val_t *out_params, const uint32 *argv, WASMType *func_type) u32[0] = *argv++; u32[1] = *argv++; break; -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case VALUE_TYPE_EXTERNREF: param->kind = WASM_ANYREF; @@ -5672,7 +5941,7 @@ argv_to_params(wasm_val_t *out_params, const uint32 *argv, WASMType *func_type) static inline bool results_to_argv(WASMModuleInstanceCommon *module_inst, uint32 *out_argv, - const wasm_val_t *results, WASMType *func_type) + const wasm_val_t *results, WASMFuncType *func_type) { const wasm_val_t *result = results; uint32 *argv = out_argv, *u32, i; @@ -5690,10 +5959,11 @@ results_to_argv(WASMModuleInstanceCommon *module_inst, uint32 *out_argv, *argv++ = u32[0]; *argv++ = u32[1]; break; -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case VALUE_TYPE_EXTERNREF: if (!wasm_externref_obj2ref(module_inst, - (void *)result->of.foreign, argv)) { + (void *)result->of.foreign, + (uint32 *)argv)) { return false; } argv++; @@ -5709,7 +5979,7 @@ results_to_argv(WASMModuleInstanceCommon *module_inst, uint32 *out_argv, bool wasm_runtime_invoke_c_api_native(WASMModuleInstanceCommon *module_inst, - void *func_ptr, WASMType *func_type, + void *func_ptr, WASMFuncType *func_type, uint32 argc, uint32 *argv, bool with_env, void *wasm_c_api_env) { @@ -6269,67 +6539,3 @@ wasm_runtime_set_linux_perf(bool flag) enable_linux_perf = flag; } #endif - -#ifdef WASM_LINEAR_MEMORY_MMAP -void -wasm_munmap_linear_memory(void *mapped_mem, uint64 commit_size, uint64 map_size) -{ -#ifdef BH_PLATFORM_WINDOWS - os_mem_decommit(mapped_mem, commit_size); -#else - (void)commit_size; -#endif - os_munmap(mapped_mem, map_size); -} - -void * -wasm_mmap_linear_memory(uint64_t map_size, uint64 *io_memory_data_size, - char *error_buf, uint32 error_buf_size) -{ - uint64 page_size = os_getpagesize(); - void *mapped_mem = NULL; - uint64 memory_data_size; - - bh_assert(io_memory_data_size); - - memory_data_size = - (*io_memory_data_size + page_size - 1) & ~(page_size - 1); - - if (memory_data_size > UINT32_MAX) - memory_data_size = UINT32_MAX; - - if (!(mapped_mem = os_mmap(NULL, map_size, MMAP_PROT_NONE, MMAP_MAP_NONE, - os_get_invalid_handle()))) { - set_error_buf(error_buf, error_buf_size, "mmap memory failed"); - goto fail1; - } - -#ifdef BH_PLATFORM_WINDOWS - if (memory_data_size > 0 - && !os_mem_commit(mapped_mem, memory_data_size, - MMAP_PROT_READ | MMAP_PROT_WRITE)) { - set_error_buf(error_buf, error_buf_size, "commit memory failed"); - os_munmap(mapped_mem, map_size); - goto fail1; - } -#endif - - if (os_mprotect(mapped_mem, memory_data_size, - MMAP_PROT_READ | MMAP_PROT_WRITE) - != 0) { - set_error_buf(error_buf, error_buf_size, "mprotect memory failed"); - goto fail2; - } - - /* Newly allocated pages are filled with zero by the OS, we don't fill it - * again here */ - - *io_memory_data_size = memory_data_size; - - return mapped_mem; -fail2: - wasm_munmap_linear_memory(mapped_mem, memory_data_size, map_size); -fail1: - return NULL; -} -#endif diff --git a/core/iwasm/common/wasm_runtime_common.h b/core/iwasm/common/wasm_runtime_common.h index 039244ff6..0d449c328 100644 --- a/core/iwasm/common/wasm_runtime_common.h +++ b/core/iwasm/common/wasm_runtime_common.h @@ -12,6 +12,9 @@ #include "wasm_native.h" #include "../include/wasm_export.h" #include "../interpreter/wasm.h" +#if WASM_ENABLE_GC != 0 +#include "gc/gc_object.h" +#endif #if WASM_ENABLE_LIBC_WASI != 0 #if WASM_ENABLE_UVWASI == 0 @@ -38,9 +41,14 @@ extern "C" { do { \ *(float64 *)(addr) = (float64)(value); \ } while (0) +#define PUT_REF_TO_ADDR(addr, value) \ + do { \ + *(void **)(addr) = (void *)(value); \ + } while (0) #define GET_I64_FROM_ADDR(addr) (*(int64 *)(addr)) #define GET_F64_FROM_ADDR(addr) (*(float64 *)(addr)) +#define GET_REF_FROM_ADDR(addr) (*(void **)(addr)) /* For STORE opcodes */ #define STORE_I64 PUT_I64_TO_ADDR @@ -97,6 +105,24 @@ STORE_U8(void *addr, uint8_t value) addr_u32[0] = u.parts[0]; \ addr_u32[1] = u.parts[1]; \ } while (0) +#if UINTPTR_MAX == UINT64_MAX +#define PUT_REF_TO_ADDR(addr, value) \ + do { \ + uint32 *addr_u32 = (uint32 *)(addr); \ + union { \ + void *val; \ + uint32 parts[2]; \ + } u; \ + u.val = (void *)(value); \ + addr_u32[0] = u.parts[0]; \ + addr_u32[1] = u.parts[1]; \ + } while (0) +#else +#define PUT_REF_TO_ADDR(addr, value) \ + do { \ + *(void **)(addr) = (void *)(value); \ + } while (0) +#endif static inline int64 GET_I64_FROM_ADDR(uint32 *addr) @@ -122,6 +148,22 @@ GET_F64_FROM_ADDR(uint32 *addr) return u.val; } +#if UINTPTR_MAX == UINT64_MAX +static inline void * +GET_REF_FROM_ADDR(uint32 *addr) +{ + union { + void *val; + uint32 parts[2]; + } u; + u.parts[0] = addr[0]; + u.parts[1] = addr[1]; + return u.val; +} +#else +#define GET_REF_FROM_ADDR(addr) (*(void **)(addr)) +#endif + /* For STORE opcodes */ #define STORE_I64(addr, value) \ do { \ @@ -320,11 +362,6 @@ LOAD_I16(void *addr) #define SHARED_MEMORY_UNLOCK(memory) (void)0 #endif -#if defined(OS_ENABLE_HW_BOUND_CHECK) \ - || (WASM_ENABLE_SHARED_MEMORY != 0 && WASM_ENABLE_SHARED_MEMORY_MMAP != 0) -#define WASM_LINEAR_MEMORY_MMAP -#endif - typedef struct WASMModuleCommon { /* Module type, for module loaded from WASM bytecode binary, this field is Wasm_Module_Bytecode, and this structure should @@ -421,16 +458,6 @@ typedef struct WASMRegisteredModule { } WASMRegisteredModule; #endif -typedef struct WASMMemoryInstanceCommon { - uint32 module_type; - - /* The following uint8[1] member is a dummy just to indicate - some module_type dependent members follow. - Typically it should be accessed by casting to the corresponding - actual module_type dependent structure, not via this member. */ - uint8 memory_inst_data[1]; -} WASMMemoryInstanceCommon; - typedef package_type_t PackageType; typedef wasm_section_t WASMSection, AOTSection; @@ -441,6 +468,10 @@ typedef struct wasm_frame_t { uint32 func_index; uint32 func_offset; const char *func_name_wp; + + uint32 *sp; + uint8 *frame_ref; + uint32 *lp; } WASMCApiFrame; #if WASM_ENABLE_JIT != 0 @@ -486,6 +517,12 @@ LLVMJITOptions * wasm_runtime_get_llvm_jit_options(void); #endif +#if WASM_ENABLE_GC != 0 +/* Internal API */ +uint32 +wasm_runtime_get_gc_heap_size_default(void); +#endif + /* See wasm_export.h for description */ WASM_RUNTIME_API_EXTERN bool wasm_runtime_full_init(RuntimeInitArgs *init_args); @@ -566,7 +603,7 @@ wasm_runtime_lookup_function(WASMModuleInstanceCommon *const module_inst, const char *name, const char *signature); /* Internal API */ -WASMType * +WASMFuncType * wasm_runtime_get_function_type(const WASMFunctionInstanceCommon *function, uint32 module_type); @@ -933,6 +970,15 @@ wasm_runtime_set_wasi_ns_lookup_pool(wasm_module_t module, uint32 ns_lookup_pool_size); #endif /* end of WASM_ENABLE_LIBC_WASI */ +#if WASM_ENABLE_GC != 0 +void +wasm_runtime_set_gc_heap_handle(WASMModuleInstanceCommon *module_inst, + void *gc_heap_handle); + +void * +wasm_runtime_get_gc_heap_handle(WASMModuleInstanceCommon *module_inst); +#endif + #if WASM_ENABLE_REF_TYPES != 0 /* See wasm_export.h for description */ WASM_RUNTIME_API_EXTERN bool @@ -1026,15 +1072,15 @@ wasm_runtime_get_context(WASMModuleInstanceCommon *inst, void *key); bool wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, - const WASMType *func_type, const char *signature, + const WASMFuncType *func_type, const char *signature, void *attachment, uint32 *argv, uint32 argc, uint32 *ret); bool wasm_runtime_invoke_native_raw(WASMExecEnv *exec_env, void *func_ptr, - const WASMType *func_type, const char *signature, - void *attachment, uint32 *argv, uint32 argc, - uint32 *ret); + const WASMFuncType *func_type, + const char *signature, void *attachment, + uint32 *argv, uint32 argc, uint32 *ret); void wasm_runtime_read_v128(const uint8 *bytes, uint64 *ret1, uint64 *ret2); @@ -1052,16 +1098,24 @@ wasm_runtime_dump_exec_env_mem_consumption(const WASMExecEnv *exec_env); bool wasm_runtime_get_table_elem_type(const WASMModuleCommon *module_comm, uint32 table_idx, uint8 *out_elem_type, +#if WASM_ENABLE_GC != 0 + WASMRefType **out_ref_type, +#endif uint32 *out_min_size, uint32 *out_max_size); bool wasm_runtime_get_table_inst_elem_type( const WASMModuleInstanceCommon *module_inst_comm, uint32 table_idx, - uint8 *out_elem_type, uint32 *out_min_size, uint32 *out_max_size); + uint8 *out_elem_type, +#if WASM_ENABLE_GC != 0 + WASMRefType **out_ref_type, +#endif + uint32 *out_min_size, uint32 *out_max_size); bool wasm_runtime_get_export_func_type(const WASMModuleCommon *module_comm, - const WASMExport *export_, WASMType **out); + const WASMExport *export_, + WASMFuncType **out); bool wasm_runtime_get_export_global_type(const WASMModuleCommon *module_comm, @@ -1076,12 +1130,15 @@ wasm_runtime_get_export_memory_type(const WASMModuleCommon *module_comm, bool wasm_runtime_get_export_table_type(const WASMModuleCommon *module_comm, const WASMExport *export_, - uint8 *out_elem_type, uint32 *out_min_size, - uint32 *out_max_size); + uint8 *out_elem_type, +#if WASM_ENABLE_GC != 0 + WASMRefType **out_ref_type, +#endif + uint32 *out_min_size, uint32 *out_max_size); bool wasm_runtime_invoke_c_api_native(WASMModuleInstanceCommon *module_inst, - void *func_ptr, WASMType *func_type, + void *func_ptr, WASMFuncType *func_type, uint32 argc, uint32 *argv, bool with_env, void *wasm_c_api_env); @@ -1098,14 +1155,6 @@ wasm_runtime_quick_invoke_c_api_native(WASMModuleInstanceCommon *module_inst, void wasm_runtime_show_app_heap_corrupted_prompt(); -void -wasm_munmap_linear_memory(void *mapped_mem, uint64 commit_size, - uint64 map_size); - -void * -wasm_mmap_linear_memory(uint64_t map_size, uint64 *io_memory_data_size, - char *error_buf, uint32 error_buf_size); - #if WASM_ENABLE_LOAD_CUSTOM_SECTION != 0 void wasm_runtime_destroy_custom_sections(WASMCustomSection *section_list); diff --git a/core/iwasm/common/wasm_shared_memory.c b/core/iwasm/common/wasm_shared_memory.c index e7110c0f1..3856b7d19 100644 --- a/core/iwasm/common/wasm_shared_memory.c +++ b/core/iwasm/common/wasm_shared_memory.c @@ -232,14 +232,14 @@ destroy_wait_info(void *wait_info) } static void -map_try_release_wait_info(HashMap *wait_map_, AtomicWaitInfo *wait_info, +map_try_release_wait_info(HashMap *wait_hash_map, AtomicWaitInfo *wait_info, void *address) { if (wait_info->wait_list->len > 0) { return; } - bh_hash_map_remove(wait_map_, address, NULL, NULL); + bh_hash_map_remove(wait_hash_map, address, NULL, NULL); destroy_wait_info(wait_info); } diff --git a/core/iwasm/compilation/aot.c b/core/iwasm/compilation/aot.c index 8162d006e..f4532a5f7 100644 --- a/core/iwasm/compilation/aot.c +++ b/core/iwasm/compilation/aot.c @@ -114,9 +114,9 @@ aot_create_table_init_data_list(const WASMModule *module) /* Create each table data segment */ for (i = 0; i < module->table_seg_count; i++) { - size = - offsetof(AOTTableInitData, func_indexes) - + sizeof(uint32) * (uint64)module->table_segments[i].function_count; + size = offsetof(AOTTableInitData, init_values) + + sizeof(InitializerExpression) + * (uint64)module->table_segments[i].value_count; if (size >= UINT32_MAX || !(data_list[i] = wasm_runtime_malloc((uint32)size))) { aot_set_last_error("allocate memory failed."); @@ -124,8 +124,7 @@ aot_create_table_init_data_list(const WASMModule *module) } data_list[i]->offset = module->table_segments[i].base_offset; - data_list[i]->func_index_count = - module->table_segments[i].function_count; + data_list[i]->value_count = module->table_segments[i].value_count; data_list[i]->mode = module->table_segments[i].mode; data_list[i]->elem_type = module->table_segments[i].elem_type; /* runtime control it */ @@ -133,12 +132,16 @@ aot_create_table_init_data_list(const WASMModule *module) bh_memcpy_s(&data_list[i]->offset, sizeof(AOTInitExpr), &module->table_segments[i].base_offset, sizeof(AOTInitExpr)); - data_list[i]->func_index_count = - module->table_segments[i].function_count; - bh_memcpy_s(data_list[i]->func_indexes, - sizeof(uint32) * module->table_segments[i].function_count, - module->table_segments[i].func_indexes, - sizeof(uint32) * module->table_segments[i].function_count); + data_list[i]->value_count = module->table_segments[i].value_count; +#if WASM_ENABLE_GC != 0 + data_list[i]->elem_ref_type = module->table_segments[i].elem_ref_type; +#endif + bh_memcpy_s(data_list[i]->init_values, + sizeof(InitializerExpression) + * module->table_segments[i].value_count, + module->table_segments[i].init_values, + sizeof(InitializerExpression) + * module->table_segments[i].value_count); } return data_list; @@ -148,13 +151,60 @@ fail: return NULL; } +static void +get_value_type_size(uint8 value_type, bool gc_enabled, uint32 *p_size_64bit, + uint32 *p_size_32bit) +{ + uint32 size_64bit = 0, size_32bit = 0; + + if (value_type == VALUE_TYPE_I32 || value_type == VALUE_TYPE_F32) + size_64bit = size_32bit = sizeof(int32); + else if (value_type == VALUE_TYPE_I64 || value_type == VALUE_TYPE_F64) + size_64bit = size_32bit = sizeof(int64); + else if (value_type == VALUE_TYPE_V128) + size_64bit = size_32bit = sizeof(int64) * 2; + else if (!gc_enabled + && (value_type == VALUE_TYPE_FUNCREF + || value_type == VALUE_TYPE_EXTERNREF)) + size_64bit = size_32bit = sizeof(int32); + else if (gc_enabled + && ((value_type >= (uint8)REF_TYPE_ARRAYREF + && value_type <= (uint8)REF_TYPE_NULLFUNCREF) + || (value_type >= (uint8)REF_TYPE_HT_NULLABLE + && value_type <= (uint8)REF_TYPE_HT_NON_NULLABLE) +#if WASM_ENABLE_STRINGREF != 0 + || (value_type >= (uint8)REF_TYPE_STRINGVIEWWTF8 + && value_type <= (uint8)REF_TYPE_STRINGREF) + || (value_type >= (uint8)REF_TYPE_STRINGVIEWITER + && value_type <= (uint8)REF_TYPE_STRINGVIEWWTF16) +#endif + )) { + size_64bit = sizeof(uint64); + size_32bit = sizeof(uint32); + } + else if (gc_enabled && value_type == PACKED_TYPE_I8) { + size_64bit = size_32bit = sizeof(int8); + } + else if (gc_enabled && value_type == PACKED_TYPE_I16) { + size_64bit = size_32bit = sizeof(int16); + } + else { + bh_assert(0); + } + + *p_size_64bit = size_64bit; + *p_size_32bit = size_32bit; +} + static AOTImportGlobal * -aot_create_import_globals(const WASMModule *module, - uint32 *p_import_global_data_size) +aot_create_import_globals(const WASMModule *module, bool gc_enabled, + uint32 *p_import_global_data_size_64bit, + uint32 *p_import_global_data_size_32bit) { AOTImportGlobal *import_globals; uint64 size; - uint32 i, data_offset = 0; + uint32 i, data_offset_64bit = 0, data_offset_32bit = 0; + uint32 value_size_64bit, value_size_32bit; /* Allocate memory */ size = sizeof(AOTImportGlobal) * (uint64)module->import_global_count; @@ -175,23 +225,37 @@ aot_create_import_globals(const WASMModule *module, import_globals[i].is_mutable = import_global->is_mutable; import_globals[i].global_data_linked = import_global->global_data_linked; - import_globals[i].size = wasm_value_type_size(import_global->type); - /* Calculate data offset */ - import_globals[i].data_offset = data_offset; - data_offset += wasm_value_type_size(import_global->type); + + import_globals[i].data_offset_64bit = data_offset_64bit; + import_globals[i].data_offset_32bit = data_offset_32bit; + + get_value_type_size(import_global->type, gc_enabled, &value_size_64bit, + &value_size_32bit); + + import_globals[i].size_64bit = value_size_64bit; + import_globals[i].size_32bit = value_size_32bit; + data_offset_64bit += value_size_64bit; + data_offset_32bit += value_size_32bit; } - *p_import_global_data_size = data_offset; + *p_import_global_data_size_64bit = data_offset_64bit; + *p_import_global_data_size_32bit = data_offset_32bit; return import_globals; } static AOTGlobal * -aot_create_globals(const WASMModule *module, uint32 global_data_start_offset, - uint32 *p_global_data_size) +aot_create_globals(const WASMModule *module, bool gc_enabled, + uint32 global_data_start_offset_64bit, + uint32 global_data_start_offset_32bit, + uint32 *p_global_data_size_64bit, + uint32 *p_global_data_size_32bit) { AOTGlobal *globals; uint64 size; - uint32 i, data_offset = global_data_start_offset; + uint32 i; + uint32 data_offset_64bit = global_data_start_offset_64bit; + uint32 data_offset_32bit = global_data_start_offset_32bit; + uint32 value_size_64bit, value_size_32bit; /* Allocate memory */ size = sizeof(AOTGlobal) * (uint64)module->global_count; @@ -207,65 +271,28 @@ aot_create_globals(const WASMModule *module, uint32 global_data_start_offset, WASMGlobal *global = &module->globals[i]; globals[i].type = global->type; globals[i].is_mutable = global->is_mutable; - globals[i].size = wasm_value_type_size(global->type); memcpy(&globals[i].init_expr, &global->init_expr, sizeof(global->init_expr)); - /* Calculate data offset */ - globals[i].data_offset = data_offset; - data_offset += wasm_value_type_size(global->type); + + globals[i].data_offset_64bit = data_offset_64bit; + globals[i].data_offset_32bit = data_offset_32bit; + + get_value_type_size(global->type, gc_enabled, &value_size_64bit, + &value_size_32bit); + + globals[i].size_64bit = value_size_64bit; + globals[i].size_32bit = value_size_32bit; + data_offset_64bit += value_size_64bit; + data_offset_32bit += value_size_32bit; } - *p_global_data_size = data_offset - global_data_start_offset; + *p_global_data_size_64bit = + data_offset_64bit - global_data_start_offset_64bit; + *p_global_data_size_32bit = + data_offset_32bit - global_data_start_offset_32bit; return globals; } -static void -aot_destroy_func_types(AOTFuncType **func_types, uint32 count) -{ - uint32 i; - for (i = 0; i < count; i++) - if (func_types[i]) - wasm_runtime_free(func_types[i]); - wasm_runtime_free(func_types); -} - -static AOTFuncType ** -aot_create_func_types(const WASMModule *module) -{ - AOTFuncType **func_types; - uint64 size; - uint32 i; - - /* Allocate memory */ - size = sizeof(AOTFuncType *) * (uint64)module->type_count; - if (size >= UINT32_MAX - || !(func_types = wasm_runtime_malloc((uint32)size))) { - aot_set_last_error("allocate memory failed."); - return NULL; - } - - memset(func_types, 0, size); - - /* Create each function type */ - for (i = 0; i < module->type_count; i++) { - size = offsetof(AOTFuncType, types) - + (uint64)module->types[i]->param_count - + (uint64)module->types[i]->result_count; - if (size >= UINT32_MAX - || !(func_types[i] = wasm_runtime_malloc((uint32)size))) { - aot_set_last_error("allocate memory failed."); - goto fail; - } - memcpy(func_types[i], module->types[i], size); - } - - return func_types; - -fail: - aot_destroy_func_types(func_types, module->type_count); - return NULL; -} - static AOTImportFunc * aot_create_import_funcs(const WASMModule *module) { @@ -295,7 +322,7 @@ aot_create_import_funcs(const WASMModule *module) import_funcs[i].call_conv_wasm_c_api = false; /* Resolve function type index */ for (j = 0; j < module->type_count; j++) - if (import_func->func_type == module->types[j]) { + if (import_func->func_type == (WASMFuncType *)module->types[j]) { import_funcs[i].func_type_index = j; break; } @@ -310,13 +337,16 @@ aot_destroy_funcs(AOTFunc **funcs, uint32 count) uint32 i; for (i = 0; i < count; i++) - if (funcs[i]) + if (funcs[i]) { + if (funcs[i]->local_offsets) + wasm_runtime_free(funcs[i]->local_offsets); wasm_runtime_free(funcs[i]); + } wasm_runtime_free(funcs); } static AOTFunc ** -aot_create_funcs(const WASMModule *module) +aot_create_funcs(const WASMModule *module, uint32 pointer_size) { AOTFunc **funcs; uint64 size; @@ -334,28 +364,70 @@ aot_create_funcs(const WASMModule *module) /* Create each function */ for (i = 0; i < module->function_count; i++) { WASMFunction *func = module->functions[i]; + AOTFuncType *func_type = NULL; + AOTFunc *aot_func = NULL; + uint64 total_size; + uint32 offset = 0; + size = sizeof(AOTFunc); - if (!(funcs[i] = wasm_runtime_malloc((uint32)size))) { + if (!(aot_func = funcs[i] = wasm_runtime_malloc((uint32)size))) { + aot_set_last_error("allocate memory failed."); + goto fail; + } + memset(aot_func, 0, sizeof(AOTFunc)); + + func_type = aot_func->func_type = func->func_type; + + /* Resolve function type index */ + for (j = 0; j < module->type_count; j++) { + if (func_type == (WASMFuncType *)module->types[j]) { + aot_func->func_type_index = j; + break; + } + } + + total_size = sizeof(uint16) + * ((uint64)func_type->param_count + func->local_count); + if ((total_size > 0) + && (total_size >= UINT32_MAX + || !(aot_func->local_offsets = + wasm_runtime_malloc((uint32)total_size)))) { aot_set_last_error("allocate memory failed."); goto fail; } - funcs[i]->func_type = func->func_type; - - /* Resolve function type index */ - for (j = 0; j < module->type_count; j++) - if (func->func_type == module->types[j]) { - funcs[i]->func_type_index = j; - break; - } - /* Resolve local variable info and code info */ - funcs[i]->local_count = func->local_count; - funcs[i]->local_types = func->local_types; - funcs[i]->param_cell_num = func->param_cell_num; - funcs[i]->local_cell_num = func->local_cell_num; - funcs[i]->code = func->code; - funcs[i]->code_size = func->code_size; + aot_func->local_count = func->local_count; + aot_func->local_types_wp = func->local_types; + aot_func->code = func->code; + aot_func->code_size = func->code_size; + + /* Resolve local offsets */ + for (j = 0; j < func_type->param_count; j++) { + aot_func->local_offsets[j] = (uint16)offset; + offset += wasm_value_type_cell_num_internal(func_type->types[j], + pointer_size); + } + aot_func->param_cell_num = offset; + + for (j = 0; j < func->local_count; j++) { + aot_func->local_offsets[func_type->param_count + j] = + (uint16)offset; + offset += wasm_value_type_cell_num_internal(func->local_types[j], + pointer_size); + } + aot_func->local_cell_num = offset - aot_func->param_cell_num; + + aot_func->max_stack_cell_num = func->max_stack_cell_num; + /* We use max_stack_cell_num calculated from wasm_loader, which is based + * on wamrc's target type. + * - If the wamrc is compiled as 64bit, then the number is enough for + * both 32bit and 64bit runtime target + * - If the wamrc is compiled as 32bit, then we multiply this number by + * two to avoid overflow on 64bit runtime target */ + if (sizeof(uintptr_t) == 4) { + aot_func->max_stack_cell_num *= 2; + } } return funcs; @@ -365,12 +437,94 @@ fail: return NULL; } +#if WASM_ENABLE_GC != 0 +static void +calculate_struct_field_sizes_offsets(AOTCompData *comp_data, bool is_target_x86, + bool gc_enabled) +{ + uint32 i; + + for (i = 0; i < comp_data->type_count; i++) { + if (comp_data->types[i]->type_flag == WASM_TYPE_STRUCT) { + WASMStructType *struct_type = (WASMStructType *)comp_data->types[i]; + WASMStructFieldType *fields = struct_type->fields; + uint32 field_offset_64bit, field_offset_32bit; + uint32 field_size_64bit, field_size_32bit, j; + + /* offsetof(WASMStructObject, field_data) in 64-bit */ + field_offset_64bit = sizeof(uint64); + + /* offsetof(WASMStructObject, field_data) in 32-bit */ + field_offset_32bit = sizeof(uint32); + + for (j = 0; j < struct_type->field_count; j++) { + get_value_type_size(fields[j].field_type, gc_enabled, + &field_size_64bit, &field_size_32bit); + + fields[j].field_size_64bit = field_size_64bit; + fields[j].field_size_32bit = field_size_32bit; + + if (!is_target_x86) { + if (field_size_64bit == 2) + field_offset_64bit = align_uint(field_offset_64bit, 2); + else if (field_size_64bit >= 4) + field_offset_64bit = align_uint(field_offset_64bit, 4); + + if (field_size_32bit == 2) + field_offset_32bit = align_uint(field_offset_32bit, 2); + else if (field_size_32bit >= 4) + field_offset_32bit = align_uint(field_offset_32bit, 4); + } + + fields[j].field_offset_64bit = field_offset_64bit; + fields[j].field_offset_32bit = field_offset_32bit; + + field_offset_64bit += field_size_64bit; + field_offset_32bit += field_size_32bit; + } + } + } +} +#endif + AOTCompData * -aot_create_comp_data(WASMModule *module) +aot_create_comp_data(WASMModule *module, const char *target_arch, + bool gc_enabled) { AOTCompData *comp_data; - uint32 import_global_data_size = 0, global_data_size = 0, i, j; + uint32 import_global_data_size_64bit = 0, global_data_size_64bit = 0, i, j; + uint32 import_global_data_size_32bit = 0, global_data_size_32bit = 0; uint64 size; + bool is_64bit_target = false; +#if WASM_ENABLE_GC != 0 + bool is_target_x86 = false; +#endif + +#if WASM_ENABLE_GC != 0 + if (!target_arch) { +#if defined(BUILD_TARGET_X86_64) || defined(BUILD_TARGET_AMD_64) \ + || defined(BUILD_TARGET_X86_32) + is_target_x86 = true; +#endif + } + else { + if (!strncmp(target_arch, "x86_64", 6) + || !strncmp(target_arch, "i386", 4)) + is_target_x86 = true; + } +#endif + + if (!target_arch) { +#if UINTPTR_MAX == UINT64_MAX + is_64bit_target = true; +#endif + } + else { + /* All 64bit targets contains "64" string in their target name */ + if (strstr(target_arch, "64") != NULL) { + is_64bit_target = true; + } + } /* Allocate memory */ if (!(comp_data = wasm_runtime_malloc(sizeof(AOTCompData)))) { @@ -457,6 +611,10 @@ aot_create_comp_data(WASMModule *module) module->import_tables[i].u.table.init_size; comp_data->tables[i].table_max_size = module->import_tables[i].u.table.max_size; +#if WASM_ENABLE_GC != 0 + comp_data->tables[i].elem_ref_type = + module->import_tables[i].u.table.elem_ref_type; +#endif comp_data->tables[i].possible_grow = module->import_tables[i].u.table.possible_grow; } @@ -470,6 +628,16 @@ aot_create_comp_data(WASMModule *module) module->tables[j].max_size; comp_data->tables[i].possible_grow = module->tables[j].possible_grow; +#if WASM_ENABLE_GC != 0 + comp_data->tables[j].elem_ref_type = + module->tables[j].elem_ref_type; + /* Note: if the init_expr contains extra data for struct/array + * initialization information (init_expr.u.data), the pointer is + * copied. + * The pointers should still belong to wasm module, so DO NOT + * free the pointers copied to comp_data */ + comp_data->tables[j].init_expr = module->tables[j].init_expr; +#endif } } } @@ -484,24 +652,33 @@ aot_create_comp_data(WASMModule *module) /* Create import globals */ comp_data->import_global_count = module->import_global_count; if (comp_data->import_global_count > 0 - && !(comp_data->import_globals = - aot_create_import_globals(module, &import_global_data_size))) + && !(comp_data->import_globals = aot_create_import_globals( + module, gc_enabled, &import_global_data_size_64bit, + &import_global_data_size_32bit))) goto fail; /* Create globals */ comp_data->global_count = module->global_count; if (comp_data->global_count && !(comp_data->globals = aot_create_globals( - module, import_global_data_size, &global_data_size))) + module, gc_enabled, import_global_data_size_64bit, + import_global_data_size_32bit, &global_data_size_64bit, + &global_data_size_32bit))) goto fail; - comp_data->global_data_size = import_global_data_size + global_data_size; + comp_data->global_data_size_64bit = + import_global_data_size_64bit + global_data_size_64bit; + comp_data->global_data_size_32bit = + import_global_data_size_32bit + global_data_size_32bit; - /* Create function types */ - comp_data->func_type_count = module->type_count; - if (comp_data->func_type_count - && !(comp_data->func_types = aot_create_func_types(module))) - goto fail; + /* Create types, they are checked by wasm loader */ + comp_data->type_count = module->type_count; + comp_data->types = module->types; +#if WASM_ENABLE_GC != 0 + /* Calculate the field sizes and field offsets for 64-bit and 32-bit + targets since they may vary in 32-bit target and 64-bit target */ + calculate_struct_field_sizes_offsets(comp_data, is_target_x86, gc_enabled); +#endif /* Create import functions */ comp_data->import_func_count = module->import_function_count; @@ -511,7 +688,9 @@ aot_create_comp_data(WASMModule *module) /* Create functions */ comp_data->func_count = module->function_count; - if (comp_data->func_count && !(comp_data->funcs = aot_create_funcs(module))) + if (comp_data->func_count + && !(comp_data->funcs = + aot_create_funcs(module, is_64bit_target ? 8 : 4))) goto fail; #if WASM_ENABLE_CUSTOM_NAME_SECTION != 0 @@ -534,6 +713,12 @@ aot_create_comp_data(WASMModule *module) comp_data->free_func_index = module->free_function; comp_data->retain_func_index = module->retain_function; +#if WASM_ENABLE_STRINGREF != 0 + comp_data->string_literal_count = module->string_literal_count; + comp_data->string_literal_ptrs_wp = module->string_literal_ptrs; + comp_data->string_literal_lengths_wp = module->string_literal_lengths; +#endif + comp_data->wasm_module = module; return comp_data; @@ -576,10 +761,6 @@ aot_destroy_comp_data(AOTCompData *comp_data) if (comp_data->globals) wasm_runtime_free(comp_data->globals); - if (comp_data->func_types) - aot_destroy_func_types(comp_data->func_types, - comp_data->func_type_count); - if (comp_data->import_funcs) wasm_runtime_free(comp_data->import_funcs); diff --git a/core/iwasm/compilation/aot.h b/core/iwasm/compilation/aot.h index 4bee70f9c..484531426 100644 --- a/core/iwasm/compilation/aot.h +++ b/core/iwasm/compilation/aot.h @@ -39,7 +39,12 @@ extern const char *aot_stack_sizes_alias_name; extern const char *aot_stack_sizes_section_name; typedef InitializerExpression AOTInitExpr; -typedef WASMType AOTFuncType; +typedef WASMType AOTType; +typedef WASMFuncType AOTFuncType; +#if WASM_ENABLE_GC != 0 +typedef WASMStructType AOTStructType; +typedef WASMArrayType AOTArrayType; +#endif typedef WASMExport AOTExport; #if WASM_ENABLE_DEBUG_AOT != 0 @@ -117,22 +122,30 @@ typedef struct AOTMemInitData { typedef struct AOTImportTable { char *module_name; char *table_name; - uint32 elem_type; - uint32 table_flags; + uint8 elem_type; + uint8 table_flags; + bool possible_grow; uint32 table_init_size; uint32 table_max_size; - bool possible_grow; +#if WASM_ENABLE_GC != 0 + WASMRefType *elem_ref_type; +#endif } AOTImportTable; /** * Table */ typedef struct AOTTable { - uint32 elem_type; - uint32 table_flags; + uint8 elem_type; + uint8 table_flags; + bool possible_grow; uint32 table_init_size; uint32 table_max_size; - bool possible_grow; +#if WASM_ENABLE_GC != 0 + WASMRefType *elem_ref_type; + /* init expr for the whole table */ + InitializerExpression init_expr; +#endif } AOTTable; /** @@ -143,14 +156,17 @@ typedef struct AOTTableInitData { uint32 mode; /* funcref or externref, elemkind will be considered as funcref */ uint32 elem_type; +#if WASM_ENABLE_GC != 0 + WASMRefType *elem_ref_type; +#endif /* optional, only for active */ uint32 table_index; /* Start address of init data */ AOTInitExpr offset; /* Function index count */ - uint32 func_index_count; + uint32 value_count; /* Function index array */ - uint32 func_indexes[1]; + InitializerExpression init_values[1]; } AOTTableInitData; /** @@ -165,6 +181,19 @@ typedef struct AOTImportGlobal { uint32 size; /* The data offset of current global in global data */ uint32 data_offset; +#if WASM_ENABLE_WAMR_COMPILER != 0 || WASM_ENABLE_JIT != 0 + /* + * The data size and data offset of a wasm global may vary + * in 32-bit target and 64-bit target, e.g., the size of a + * GC obj is 4 bytes in the former and 8 bytes in the + * latter, the AOT compiler needs to use the correct data + * offset according to the target info. + */ + uint32 size_64bit; + uint32 size_32bit; + uint32 data_offset_64bit; + uint32 data_offset_32bit; +#endif /* global data after linked */ WASMValue global_data_linked; bool is_linked; @@ -180,6 +209,13 @@ typedef struct AOTGlobal { uint32 size; /* The data offset of current global in global data */ uint32 data_offset; +#if WASM_ENABLE_WAMR_COMPILER != 0 || WASM_ENABLE_JIT != 0 + /* See comments in AOTImportGlobal */ + uint32 size_64bit; + uint32 size_32bit; + uint32 data_offset_64bit; + uint32 data_offset_32bit; +#endif AOTInitExpr init_expr; } AOTGlobal; @@ -209,11 +245,15 @@ typedef struct AOTFunc { AOTFuncType *func_type; uint32 func_type_index; uint32 local_count; - uint8 *local_types; + uint8 *local_types_wp; uint16 param_cell_num; uint16 local_cell_num; + uint32 max_stack_cell_num; uint32 code_size; uint8 *code; + /* offset of each local, including function parameters + and local variables */ + uint16 *local_offsets; } AOTFunc; typedef struct AOTCompData { @@ -250,8 +290,8 @@ typedef struct AOTCompData { AOTGlobal *globals; /* Function types */ - uint32 func_type_count; - AOTFuncType **func_types; + uint32 type_count; + AOTType **types; /* Import functions */ uint32 import_func_count; @@ -267,7 +307,8 @@ typedef struct AOTCompData { uint8 *aot_name_section_buf; uint32 aot_name_section_size; - uint32 global_data_size; + uint32 global_data_size_64bit; + uint32 global_data_size_32bit; uint32 start_func_index; uint32 malloc_func_index; @@ -282,6 +323,12 @@ typedef struct AOTCompData { uint32 aux_stack_bottom; uint32 aux_stack_size; +#if WASM_ENABLE_STRINGREF != 0 + uint32 string_literal_count; + uint32 *string_literal_lengths_wp; + const uint8 **string_literal_ptrs_wp; +#endif + WASMModule *wasm_module; #if WASM_ENABLE_DEBUG_AOT != 0 dwarf_extractor_handle_t extractor; @@ -295,7 +342,8 @@ typedef struct AOTNativeSymbol { } AOTNativeSymbol; AOTCompData * -aot_create_comp_data(WASMModule *module); +aot_create_comp_data(WASMModule *module, const char *target_arch, + bool gc_enabled); void aot_destroy_comp_data(AOTCompData *comp_data); diff --git a/core/iwasm/compilation/aot_compiler.c b/core/iwasm/compilation/aot_compiler.c index fada0abc8..81ad9b7a3 100644 --- a/core/iwasm/compilation/aot_compiler.c +++ b/core/iwasm/compilation/aot_compiler.c @@ -15,6 +15,7 @@ #include "aot_emit_function.h" #include "aot_emit_parametric.h" #include "aot_emit_table.h" +#include "aot_emit_gc.h" #include "simd/simd_access_lanes.h" #include "simd/simd_bitmask_extracts.h" #include "simd/simd_bit_shifts.h" @@ -36,6 +37,11 @@ #include "debug/dwarf_extractor.h" #endif +#if WASM_ENABLE_STRINGREF != 0 +#include "string_object.h" +#include "aot_emit_stringref.h" +#endif + #define CHECK_BUF(buf, buf_end, length) \ do { \ if (buf + length > buf_end) { \ @@ -77,6 +83,7 @@ read_leb(const uint8 *buf, const uint8 *buf_end, uint32 *p_offset, return true; } +/* NOLINTNEXTLINE */ #define read_leb_uint32(p, p_end, res) \ do { \ uint32 off = 0; \ @@ -87,6 +94,7 @@ read_leb(const uint8 *buf, const uint8 *buf_end, uint32 *p_offset, res = (uint32)res64; \ } while (0) +/* NOLINTNEXTLINE */ #define read_leb_int32(p, p_end, res) \ do { \ uint32 off = 0; \ @@ -97,6 +105,7 @@ read_leb(const uint8 *buf, const uint8 *buf_end, uint32 *p_offset, res = (int32)res64; \ } while (0) +/* NOLINTNEXTLINE */ #define read_leb_int64(p, p_end, res) \ do { \ uint32 off = 0; \ @@ -108,7 +117,7 @@ read_leb(const uint8 *buf, const uint8 *buf_end, uint32 *p_offset, } while (0) /** - * Since Wamrc uses a full feature Wasm loader, + * Since wamrc uses a full feature Wasm loader, * add a post-validator here to run checks according * to options, like enable_tail_call, enable_ref_types, * and so on. @@ -116,7 +125,7 @@ read_leb(const uint8 *buf, const uint8 *buf_end, uint32 *p_offset, static bool aot_validate_wasm(AOTCompContext *comp_ctx) { - if (!comp_ctx->enable_ref_types) { + if (!comp_ctx->enable_ref_types && !comp_ctx->enable_gc) { /* Doesn't support multiple tables unless enabling reference type */ if (comp_ctx->comp_data->import_table_count + comp_ctx->comp_data->table_count @@ -160,6 +169,757 @@ aot_validate_wasm(AOTCompContext *comp_ctx) OP_ATOMIC_##OP : bin_op = LLVMAtomicRMWBinOp##OP; \ goto build_atomic_rmw; +uint32 +offset_of_local_in_outs_area(AOTCompContext *comp_ctx, unsigned n) +{ + AOTCompFrame *frame = comp_ctx->aot_frame; + return frame->cur_frame_size + offset_of_local(comp_ctx, n); +} + +static bool +store_value(AOTCompContext *comp_ctx, LLVMValueRef value, uint8 value_type, + LLVMValueRef cur_frame, uint32 offset) +{ + LLVMValueRef value_offset, value_addr, value_ptr = NULL, res; + LLVMTypeRef value_ptr_type = NULL; + + if (!(value_offset = I32_CONST(offset))) { + aot_set_last_error("llvm build const failed"); + return false; + } + + if (!(value_addr = + LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, cur_frame, + &value_offset, 1, "value_addr"))) { + aot_set_last_error("llvm build in bounds gep failed"); + return false; + } + + switch (value_type) { + case VALUE_TYPE_I32: + value_ptr_type = INT32_PTR_TYPE; + break; + case VALUE_TYPE_I64: + value_ptr_type = INT64_PTR_TYPE; + break; + case VALUE_TYPE_F32: + value_ptr_type = F32_PTR_TYPE; + break; + case VALUE_TYPE_F64: + value_ptr_type = F64_PTR_TYPE; + break; + case VALUE_TYPE_V128: + value_ptr_type = V128_PTR_TYPE; + break; +#if WASM_ENABLE_GC != 0 + case VALUE_TYPE_GC_REF: + value_ptr_type = GC_REF_PTR_TYPE; + break; +#endif + default: + bh_assert(0); + break; + } + + if (!(value_ptr = LLVMBuildBitCast(comp_ctx->builder, value_addr, + value_ptr_type, "value_ptr"))) { + aot_set_last_error("llvm build bit cast failed"); + return false; + } + + if (!(res = LLVMBuildStore(comp_ctx->builder, value, value_ptr))) { + aot_set_last_error("llvm build store failed"); + return false; + } + + LLVMSetAlignment(res, 4); + + return true; +} + +bool +aot_frame_store_value(AOTCompContext *comp_ctx, LLVMValueRef value, + uint8 value_type, LLVMValueRef cur_frame, uint32 offset) +{ + return store_value(comp_ctx, value, value_type, cur_frame, offset); +} + +static bool +store_ref(AOTCompContext *comp_ctx, uint32 ref, LLVMValueRef cur_frame, + uint32 offset, uint32 nbytes) +{ + LLVMValueRef value_ref = NULL, value_offset, value_addr, res; + + if (!(value_offset = I32_CONST(offset))) { + aot_set_last_error("llvm build const failed"); + return false; + } + + if (!(value_addr = + LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, cur_frame, + &value_offset, 1, "value_addr"))) { + aot_set_last_error("llvm build in bounds gep failed"); + return false; + } + + switch (nbytes) { + case 1: + if (!(value_ref = I8_CONST((uint8)ref))) { + aot_set_last_error("llvm build const failed"); + } + break; + case 2: + ref = (ref << 8) | ref; + + if (!(value_ref = LLVMConstInt(INT16_TYPE, (uint16)ref, false))) { + aot_set_last_error("llvm build const failed"); + return false; + } + + if (!(value_addr = + LLVMBuildBitCast(comp_ctx->builder, value_addr, + INT16_PTR_TYPE, "value_addr"))) { + aot_set_last_error("llvm build bit cast failed"); + return false; + } + break; + case 4: + ref = (ref << 24) | (ref << 16) | (ref << 8) | ref; + + if (!(value_ref = I32_CONST(ref))) { + aot_set_last_error("llvm build const failed"); + return false; + } + + if (!(value_addr = + LLVMBuildBitCast(comp_ctx->builder, value_addr, + INT32_PTR_TYPE, "value_addr"))) { + aot_set_last_error("llvm build bit cast failed"); + return false; + } + break; + default: + bh_assert(0); + break; + } + + if (!(res = LLVMBuildStore(comp_ctx->builder, value_ref, value_addr))) { + aot_set_last_error("llvm build store failed"); + return false; + } + LLVMSetAlignment(res, 1); + + return true; +} + +bool +aot_gen_commit_values(AOTCompFrame *frame) +{ + AOTCompContext *comp_ctx = frame->comp_ctx; + AOTFuncContext *func_ctx = frame->func_ctx; + AOTValueSlot *p, *end; + LLVMValueRef value; + uint32 n; + + /* First, commit reference flags + * For LLVM JIT, iterate all local and stack ref flags + * For AOT, ignore local(params + locals) ref flags */ + for (p = comp_ctx->is_jit_mode ? frame->lp + : frame->lp + frame->max_local_cell_num; + p < frame->sp; p++) { + if (!p->dirty) + continue; + + n = p - frame->lp; + + /* Commit reference flag */ + if (comp_ctx->enable_gc) { + switch (p->type) { + case VALUE_TYPE_I32: + case VALUE_TYPE_F32: + case VALUE_TYPE_I1: + if (p->ref != p->committed_ref - 1) { + if (!store_ref(comp_ctx, p->ref, func_ctx->cur_frame, + offset_of_ref(comp_ctx, n), 1)) + return false; + p->committed_ref = p->ref + 1; + } + break; + + case VALUE_TYPE_I64: + case VALUE_TYPE_F64: + bh_assert(p->ref == (p + 1)->ref); + if (p->ref != p->committed_ref - 1 + || p->ref != (p + 1)->committed_ref - 1) { + if (!store_ref(comp_ctx, p->ref, func_ctx->cur_frame, + offset_of_ref(comp_ctx, n), 2)) + return false; + p->committed_ref = (p + 1)->committed_ref = p->ref + 1; + } + p++; + break; + + case VALUE_TYPE_V128: + bh_assert(p->ref == (p + 1)->ref && p->ref == (p + 2)->ref + && p->ref == (p + 3)->ref); + if (p->ref != p->committed_ref - 1 + || p->ref != (p + 1)->committed_ref - 1 + || p->ref != (p + 2)->committed_ref - 1 + || p->ref != (p + 3)->committed_ref - 1) { + if (!store_ref(comp_ctx, p->ref, func_ctx->cur_frame, + offset_of_ref(comp_ctx, n), 4)) + return false; + p->committed_ref = (p + 1)->committed_ref = + (p + 2)->committed_ref = (p + 3)->committed_ref = + p->ref + 1; + } + p += 3; + break; + + case REF_TYPE_NULLFUNCREF: + case REF_TYPE_NULLEXTERNREF: + case REF_TYPE_NULLREF: + case REF_TYPE_FUNCREF: + case REF_TYPE_EXTERNREF: + case REF_TYPE_ANYREF: + case REF_TYPE_EQREF: + case REF_TYPE_HT_NULLABLE: + case REF_TYPE_HT_NON_NULLABLE: + case REF_TYPE_I31REF: + case REF_TYPE_STRUCTREF: + case REF_TYPE_ARRAYREF: +#if WASM_ENABLE_STRINGREF != 0 + case REF_TYPE_STRINGREF: + case REF_TYPE_STRINGVIEWWTF8: + case REF_TYPE_STRINGVIEWWTF16: + case REF_TYPE_STRINGVIEWITER: +#endif + case VALUE_TYPE_GC_REF: + if (comp_ctx->pointer_size == sizeof(uint64)) { + bh_assert(p->ref == (p + 1)->ref); + if (p->ref != p->committed_ref - 1 + || p->ref != (p + 1)->committed_ref - 1) { + if (!store_ref(comp_ctx, p->ref, + func_ctx->cur_frame, + offset_of_ref(comp_ctx, n), 2)) + return false; + p->committed_ref = (p + 1)->committed_ref = + p->ref + 1; + } + p++; + } + else { + if (p->ref != p->committed_ref - 1) { + if (!store_ref(comp_ctx, p->ref, + func_ctx->cur_frame, + offset_of_ref(comp_ctx, n), 1)) + return false; + p->committed_ref = p->ref + 1; + } + } + break; + + default: + bh_assert(0); + break; + } + } + } + + /* Second, commit all values */ + for (p = frame->lp; p < frame->sp; p++) { + if (!p->dirty) + continue; + + p->dirty = 0; + n = p - frame->lp; + + /* Commit values */ + switch (p->type) { + case VALUE_TYPE_I32: + if (!store_value(comp_ctx, p->value, VALUE_TYPE_I32, + func_ctx->cur_frame, + offset_of_local(comp_ctx, n))) + return false; + break; + case VALUE_TYPE_I64: + (++p)->dirty = 0; + if (!store_value(comp_ctx, p->value, VALUE_TYPE_I64, + func_ctx->cur_frame, + offset_of_local(comp_ctx, n))) + return false; + break; + case VALUE_TYPE_F32: + if (!store_value(comp_ctx, p->value, VALUE_TYPE_F32, + func_ctx->cur_frame, + offset_of_local(comp_ctx, n))) + return false; + break; + case VALUE_TYPE_F64: + (++p)->dirty = 0; + if (!store_value(comp_ctx, p->value, VALUE_TYPE_F64, + func_ctx->cur_frame, + offset_of_local(comp_ctx, n))) + return false; + break; + case VALUE_TYPE_V128: + (++p)->dirty = 0; + (++p)->dirty = 0; + (++p)->dirty = 0; + if (!store_value(comp_ctx, p->value, VALUE_TYPE_V128, + func_ctx->cur_frame, + offset_of_local(comp_ctx, n))) + return false; + break; + case VALUE_TYPE_I1: + if (!(value = LLVMBuildZExt(comp_ctx->builder, p->value, + I32_TYPE, "i32_val"))) { + aot_set_last_error("llvm build bit cast failed"); + return false; + } + if (!store_value(comp_ctx, value, VALUE_TYPE_I32, + func_ctx->cur_frame, + offset_of_local(comp_ctx, n))) + return false; + break; + case VALUE_TYPE_FUNCREF: + case VALUE_TYPE_EXTERNREF: + if (comp_ctx->enable_ref_types) { + if (!store_value(comp_ctx, p->value, VALUE_TYPE_I32, + func_ctx->cur_frame, + offset_of_local(comp_ctx, n))) + return false; + } +#if WASM_ENABLE_GC != 0 + else if (comp_ctx->enable_gc) { + if (comp_ctx->pointer_size == sizeof(uint64)) + (++p)->dirty = 0; + if (!store_value(comp_ctx, p->value, VALUE_TYPE_GC_REF, + func_ctx->cur_frame, + offset_of_local(comp_ctx, n))) + return false; + } +#endif + else { + bh_assert(0); + } + break; +#if WASM_ENABLE_GC != 0 + case REF_TYPE_NULLFUNCREF: + case REF_TYPE_NULLEXTERNREF: + case REF_TYPE_NULLREF: + /* case REF_TYPE_FUNCREF: */ + /* case REF_TYPE_EXTERNREF: */ + case REF_TYPE_ANYREF: + case REF_TYPE_EQREF: + case REF_TYPE_HT_NULLABLE: + case REF_TYPE_HT_NON_NULLABLE: + case REF_TYPE_I31REF: + case REF_TYPE_STRUCTREF: + case REF_TYPE_ARRAYREF: + case VALUE_TYPE_GC_REF: + if (comp_ctx->pointer_size == sizeof(uint64)) + (++p)->dirty = 0; + if (!store_value(comp_ctx, p->value, VALUE_TYPE_GC_REF, + func_ctx->cur_frame, + offset_of_local(comp_ctx, n))) + return false; + break; +#endif + default: + bh_assert(0); + break; + } + } + + if (comp_ctx->enable_gc) { + end = frame->lp + frame->max_local_cell_num + frame->max_stack_cell_num; + + /* Clear reference flags for unused stack slots. */ + for (p = frame->sp; p < end; p++) { + bh_assert(!p->ref); + n = p - frame->lp; + + /* Commit reference flag. */ + if (p->ref != p->committed_ref - 1) { + if (!store_ref(comp_ctx, p->ref, func_ctx->cur_frame, + offset_of_ref(comp_ctx, n), 1)) + return false; + p->committed_ref = 1 + p->ref; + } + } + } + + return true; +} + +bool +aot_gen_commit_sp_ip(AOTCompFrame *frame, bool commit_sp, bool commit_ip) +{ + AOTCompContext *comp_ctx = frame->comp_ctx; + AOTFuncContext *func_ctx = frame->func_ctx; + LLVMValueRef cur_frame = func_ctx->cur_frame; + LLVMValueRef value_offset, value_addr, value_ptr, value; + LLVMTypeRef int8_ptr_ptr_type; + uint32 offset_ip, offset_sp, n; + bool is_64bit = (comp_ctx->pointer_size == sizeof(uint64)) ? true : false; + const AOTValueSlot *sp = frame->sp; + const uint8 *ip = frame->frame_ip; + + if (!comp_ctx->is_jit_mode) { + offset_ip = frame->comp_ctx->pointer_size * 4; + offset_sp = frame->comp_ctx->pointer_size * 5; + } + else { + offset_ip = offsetof(WASMInterpFrame, ip); + offset_sp = offsetof(WASMInterpFrame, sp); + } + + if (commit_ip) { + if (!(value_offset = I32_CONST(offset_ip))) { + aot_set_last_error("llvm build const failed"); + return false; + } + + if (!(value_addr = + LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, cur_frame, + &value_offset, 1, "ip_addr"))) { + aot_set_last_error("llvm build in bounds gep failed"); + return false; + } + + if (!(value_ptr = LLVMBuildBitCast( + comp_ctx->builder, value_addr, + is_64bit ? INT64_PTR_TYPE : INT32_PTR_TYPE, "ip_ptr"))) { + aot_set_last_error("llvm build bit cast failed"); + return false; + } + + if (!comp_ctx->is_jit_mode) { + WASMModule *module = comp_ctx->comp_data->wasm_module; + if (is_64bit) + value = I64_CONST((uint64)(uintptr_t)(ip - module->load_addr)); + else + value = I32_CONST((uint32)(uintptr_t)(ip - module->load_addr)); + } + else { + if (is_64bit) + value = I64_CONST((uint64)(uintptr_t)ip); + else + value = I32_CONST((uint32)(uintptr_t)ip); + } + + if (!value) { + aot_set_last_error("llvm build const failed"); + return false; + } + + if (!LLVMBuildStore(comp_ctx->builder, value, value_ptr)) { + aot_set_last_error("llvm build store failed"); + return false; + } + } + + if (commit_sp) { + n = sp - frame->lp; + value = I32_CONST(offset_of_local(comp_ctx, n)); + if (!value) { + aot_set_last_error("llvm build const failed"); + return false; + } + + if (!(value = LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, + cur_frame, &value, 1, "sp"))) { + aot_set_last_error("llvm build in bounds gep failed"); + return false; + } + + if (!(value_offset = I32_CONST(offset_sp))) { + aot_set_last_error("llvm build const failed"); + return false; + } + + if (!(value_addr = + LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, cur_frame, + &value_offset, 1, "sp_addr"))) { + aot_set_last_error("llvm build in bounds gep failed"); + return false; + } + + if (!(int8_ptr_ptr_type = LLVMPointerType(INT8_PTR_TYPE, 0))) { + aot_set_last_error("llvm build pointer type failed"); + return false; + } + + if (!(value_ptr = LLVMBuildBitCast(comp_ctx->builder, value_addr, + int8_ptr_ptr_type, "sp_ptr"))) { + aot_set_last_error("llvm build bit cast failed"); + return false; + } + + if (!LLVMBuildStore(comp_ctx->builder, value, value_ptr)) { + aot_set_last_error("llvm build store failed"); + return false; + } + } + + return true; +} + +static uint32 +get_cur_frame_size(const AOTCompContext *comp_ctx, uint32 max_local_cell_num, + uint32 max_stack_cell_num) +{ + uint32 all_cell_num = max_local_cell_num + max_stack_cell_num; + uint32 frame_size; + + if (!comp_ctx->is_jit_mode) { + /* Refer to aot_alloc_frame */ + if (!comp_ctx->enable_gc) + frame_size = comp_ctx->pointer_size + * (offsetof(AOTFrame, lp) / sizeof(uintptr_t)) + + all_cell_num * 4; + else + frame_size = comp_ctx->pointer_size + * (offsetof(AOTFrame, lp) / sizeof(uintptr_t)) + + align_uint(all_cell_num * 5, 4); + } + else { + /* Refer to wasm_interp_interp_frame_size */ + if (!comp_ctx->enable_gc) + frame_size = offsetof(WASMInterpFrame, lp) + all_cell_num * 4; + else + frame_size = + offsetof(WASMInterpFrame, lp) + align_uint(all_cell_num * 5, 4); + } + + return frame_size; +} + +static bool +init_comp_frame(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 func_idx) +{ + AOTCompFrame *aot_frame; + AOTFunc *aot_func = func_ctx->aot_func; + AOTFuncType *func_type = aot_func->func_type; + AOTBlock *block = func_ctx->block_stack.block_list_end; + LLVMValueRef local_value; + uint32 max_local_cell_num = + aot_func->param_cell_num + aot_func->local_cell_num; + uint32 max_stack_cell_num = aot_func->max_stack_cell_num; + uint32 all_cell_num = max_local_cell_num + max_stack_cell_num; + uint32 i, n; + uint64 total_size; + uint8 local_type; + + /* Free aot_frame if it was allocated previously for + compiling other functions */ + if (comp_ctx->aot_frame) { + wasm_runtime_free(comp_ctx->aot_frame); + comp_ctx->aot_frame = NULL; + } + + /* Allocate extra 2 cells since some operations may push more + operands than the number calculated in wasm loader, such as + PUSH_F64(F64_CONST(1.0)) in aot_compile_op_f64_promote_f32 */ + all_cell_num += 2; + total_size = offsetof(AOTCompFrame, lp) + + (uint64)sizeof(AOTValueSlot) * all_cell_num; + + if (total_size > UINT32_MAX + || !(comp_ctx->aot_frame = aot_frame = + wasm_runtime_malloc((uint32)total_size))) { + aot_set_last_error("allocate memory failed."); + return false; + } + memset(aot_frame, 0, (uint32)total_size); + + aot_frame->comp_ctx = comp_ctx; + aot_frame->func_ctx = func_ctx; + + aot_frame->max_local_cell_num = max_local_cell_num; + aot_frame->max_stack_cell_num = max_stack_cell_num; + aot_frame->cur_frame_size = + get_cur_frame_size(comp_ctx, max_local_cell_num, max_stack_cell_num); + + aot_frame->sp = aot_frame->lp + max_local_cell_num; + + /* Init the frame_sp_begin and frame_sp_max_reached + of the function block */ + block->frame_sp_begin = block->frame_sp_max_reached = aot_frame->sp; + + n = 0; + + /* Set all params dirty since they were set to llvm value but + haven't been committed to the AOT/JIT stack frame */ + for (i = 0; i < func_type->param_count; i++) { + local_type = func_type->types[i]; + local_value = LLVMGetParam(func_ctx->func, i + 1); + + switch (local_type) { + case VALUE_TYPE_I32: + set_local_i32(comp_ctx->aot_frame, n, local_value); + n++; + break; + case VALUE_TYPE_I64: + set_local_i64(comp_ctx->aot_frame, n, local_value); + n += 2; + break; + case VALUE_TYPE_F32: + set_local_f32(comp_ctx->aot_frame, n, local_value); + n++; + break; + case VALUE_TYPE_F64: + set_local_f64(comp_ctx->aot_frame, n, local_value); + n += 2; + break; + case VALUE_TYPE_V128: + set_local_v128(comp_ctx->aot_frame, n, local_value); + n += 4; + break; + case VALUE_TYPE_FUNCREF: + case VALUE_TYPE_EXTERNREF: + { + if (comp_ctx->enable_ref_types) { + set_local_ref(comp_ctx->aot_frame, n, local_value, + local_type); + n++; + } +#if WASM_ENABLE_GC != 0 + else if (comp_ctx->enable_gc) { + set_local_gc_ref(comp_ctx->aot_frame, n, local_value, + VALUE_TYPE_GC_REF); + n += comp_ctx->pointer_size / sizeof(uint32); + } +#endif + else { + bh_assert(0); + } + break; + } +#if WASM_ENABLE_GC != 0 + case REF_TYPE_NULLFUNCREF: + case REF_TYPE_NULLEXTERNREF: + case REF_TYPE_NULLREF: + /* case REF_TYPE_FUNCREF: */ + /* case REF_TYPE_EXTERNREF: */ + case REF_TYPE_ANYREF: + case REF_TYPE_EQREF: + case REF_TYPE_HT_NULLABLE: + case REF_TYPE_HT_NON_NULLABLE: + case REF_TYPE_I31REF: + case REF_TYPE_STRUCTREF: + case REF_TYPE_ARRAYREF: +#if WASM_ENABLE_STRINGREF != 0 + case REF_TYPE_STRINGREF: + case REF_TYPE_STRINGVIEWWTF8: + case REF_TYPE_STRINGVIEWWTF16: + case REF_TYPE_STRINGVIEWITER: +#endif + bh_assert(comp_ctx->enable_gc); + set_local_gc_ref(comp_ctx->aot_frame, n, local_value, + VALUE_TYPE_GC_REF); + n += comp_ctx->pointer_size / sizeof(uint32); + break; +#endif + default: + bh_assert(0); + break; + } + } + + /* TODO: re-calculate param_cell_num according to the build target + after creating comp_ctx */ + /* bh_assert(n == aot_func->param_cell_num); */ + + /* Set all locals dirty since they were set to llvm value but + haven't been committed to the AOT/JIT stack frame */ + for (i = 0; i < aot_func->local_count; i++) { + local_type = aot_func->local_types_wp[i]; + + switch (local_type) { + case VALUE_TYPE_I32: + set_local_i32(comp_ctx->aot_frame, n, I32_ZERO); + n++; + break; + case VALUE_TYPE_I64: + set_local_i64(comp_ctx->aot_frame, n, I64_ZERO); + n += 2; + break; + case VALUE_TYPE_F32: + set_local_f32(comp_ctx->aot_frame, n, F32_ZERO); + n++; + break; + case VALUE_TYPE_F64: + set_local_f64(comp_ctx->aot_frame, n, F64_ZERO); + n += 2; + break; + case VALUE_TYPE_V128: + set_local_v128(comp_ctx->aot_frame, n, V128_f64x2_ZERO); + n += 4; + break; + case VALUE_TYPE_FUNCREF: + case VALUE_TYPE_EXTERNREF: + { + if (comp_ctx->enable_ref_types) { + set_local_ref(comp_ctx->aot_frame, n, I32_ZERO, local_type); + n++; + } +#if WASM_ENABLE_GC != 0 + else if (comp_ctx->enable_gc) { + set_local_gc_ref(comp_ctx->aot_frame, n, GC_REF_NULL, + VALUE_TYPE_GC_REF); + n += comp_ctx->pointer_size / sizeof(uint32); + } +#endif + else { + bh_assert(0); + } + break; + } +#if WASM_ENABLE_GC != 0 + case REF_TYPE_NULLFUNCREF: + case REF_TYPE_NULLEXTERNREF: + case REF_TYPE_NULLREF: + /* case REF_TYPE_FUNCREF: */ + /* case REF_TYPE_EXTERNREF: */ + case REF_TYPE_ANYREF: + case REF_TYPE_EQREF: + case REF_TYPE_HT_NULLABLE: + case REF_TYPE_HT_NON_NULLABLE: + case REF_TYPE_I31REF: + case REF_TYPE_STRUCTREF: + case REF_TYPE_ARRAYREF: +#if WASM_ENABLE_STRINGREF != 0 + case REF_TYPE_STRINGREF: + case REF_TYPE_STRINGVIEWWTF8: + case REF_TYPE_STRINGVIEWWTF16: + case REF_TYPE_STRINGVIEWITER: +#endif + bh_assert(comp_ctx->enable_gc); + set_local_gc_ref(comp_ctx->aot_frame, n, GC_REF_NULL, + VALUE_TYPE_GC_REF); + n += comp_ctx->pointer_size / sizeof(uint32); + break; +#endif + default: + bh_assert(0); + break; + } + } + + /* TODO: re-calculate local_cell_num according to the build target + after creating comp_ctx */ + /* bh_assert(n == aot_func->param_cell_num + aot_func->local_cell_num); */ + + /* No need to initialize aot_frame all cells' committed_ref flags + and all stack cells' ref flags since they have been initialized + as 0 (uncommitted and not-reference) by the memset above */ + + return true; +} + static bool aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) { @@ -185,6 +945,12 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) LLVMMetadataRef location; #endif + if (comp_ctx->enable_aux_stack_frame) { + if (!init_comp_frame(comp_ctx, func_ctx, func_index)) { + return false; + } + } + /* Start to translate the opcodes */ LLVMPositionBuilderAtEnd( comp_ctx->builder, @@ -192,6 +958,10 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) while (frame_ip < frame_ip_end) { opcode = *frame_ip++; + if (comp_ctx->aot_frame) { + comp_ctx->aot_frame->frame_ip = frame_ip - 1; + } + #if WASM_ENABLE_DEBUG_AOT != 0 location = dwarf_gen_location( comp_ctx, func_ctx, @@ -218,8 +988,11 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) || value_type == VALUE_TYPE_F64 || value_type == VALUE_TYPE_V128 || value_type == VALUE_TYPE_VOID - || value_type == VALUE_TYPE_FUNCREF - || value_type == VALUE_TYPE_EXTERNREF) { + || (comp_ctx->enable_ref_types + && (value_type == VALUE_TYPE_FUNCREF + || value_type == VALUE_TYPE_EXTERNREF)) + || (comp_ctx->enable_gc /* single byte type */ + && aot_is_type_gc_reftype(value_type))) { param_count = 0; param_types = NULL; if (value_type == VALUE_TYPE_VOID) { @@ -227,6 +1000,9 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) result_types = NULL; } else { + if (comp_ctx->enable_gc + && aot_is_type_gc_reftype(value_type)) + value_type = VALUE_TYPE_GC_REF; result_count = 1; result_types = &value_type; } @@ -234,7 +1010,8 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) else { frame_ip--; read_leb_uint32(frame_ip, frame_ip_end, type_index); - func_type = comp_ctx->comp_data->func_types[type_index]; + func_type = + (AOTFuncType *)comp_ctx->comp_data->types[type_index]; param_count = func_type->param_count; param_types = func_type->types; result_count = func_type->result_count; @@ -253,7 +1030,8 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) case EXT_OP_IF: { read_leb_uint32(frame_ip, frame_ip_end, type_index); - func_type = comp_ctx->comp_data->func_types[type_index]; + func_type = + (AOTFuncType *)comp_ctx->comp_data->types[type_index]; param_count = func_type->param_count; param_types = func_type->types; result_count = func_type->result_count; @@ -277,19 +1055,24 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) break; case WASM_OP_BR: + { read_leb_uint32(frame_ip, frame_ip_end, br_depth); if (!aot_compile_op_br(comp_ctx, func_ctx, br_depth, &frame_ip)) return false; break; + } case WASM_OP_BR_IF: + { read_leb_uint32(frame_ip, frame_ip_end, br_depth); if (!aot_compile_op_br_if(comp_ctx, func_ctx, br_depth, &frame_ip)) return false; break; + } case WASM_OP_BR_TABLE: + { read_leb_uint32(frame_ip, frame_ip_end, br_count); if (!(br_depths = wasm_runtime_malloc((uint32)sizeof(uint32) * (br_count + 1)))) { @@ -312,6 +1095,7 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) wasm_runtime_free(br_depths); break; + } #if WASM_ENABLE_FAST_INTERP == 0 case EXT_OP_BR_TABLE_CACHE: @@ -319,13 +1103,13 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) BrTableCache *node = bh_list_first_elem( comp_ctx->comp_data->wasm_module->br_table_cache_list); BrTableCache *node_next; - uint8 *p_opcode = frame_ip - 1; + const uint8 *frame_ip_org = frame_ip - 1; read_leb_uint32(frame_ip, frame_ip_end, br_count); while (node) { node_next = bh_list_elem_next(node); - if (node->br_table_op_addr == p_opcode) { + if (node->br_table_op_addr == frame_ip_org) { br_depths = node->br_depths; if (!aot_compile_op_br_table(comp_ctx, func_ctx, br_depths, br_count, @@ -348,10 +1132,12 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) break; case WASM_OP_CALL: + { read_leb_uint32(frame_ip, frame_ip_end, func_idx); if (!aot_compile_op_call(comp_ctx, func_ctx, func_idx, false)) return false; break; + } case WASM_OP_CALL_INDIRECT: { @@ -359,13 +1145,10 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) read_leb_uint32(frame_ip, frame_ip_end, type_idx); -#if WASM_ENABLE_REF_TYPES != 0 - if (comp_ctx->enable_ref_types) { + if (comp_ctx->enable_gc || comp_ctx->enable_ref_types) { read_leb_uint32(frame_ip, frame_ip_end, tbl_idx); } - else -#endif - { + else { frame_ip++; tbl_idx = 0; } @@ -378,16 +1161,19 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) #if WASM_ENABLE_TAIL_CALL != 0 case WASM_OP_RETURN_CALL: + { if (!comp_ctx->enable_tail_call) { aot_set_last_error("unsupported opcode"); return false; } + read_leb_uint32(frame_ip, frame_ip_end, func_idx); if (!aot_compile_op_call(comp_ctx, func_ctx, func_idx, true)) return false; if (!aot_compile_op_return(comp_ctx, func_ctx, &frame_ip)) return false; break; + } case WASM_OP_RETURN_CALL_INDIRECT: { @@ -399,13 +1185,10 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) } read_leb_uint32(frame_ip, frame_ip_end, type_idx); -#if WASM_ENABLE_REF_TYPES != 0 - if (comp_ctx->enable_ref_types) { + if (comp_ctx->enable_gc || comp_ctx->enable_ref_types) { read_leb_uint32(frame_ip, frame_ip_end, tbl_idx); } - else -#endif - { + else { frame_ip++; tbl_idx = 0; } @@ -439,13 +1222,13 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) return false; break; -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 case WASM_OP_SELECT_T: { uint32 vec_len; - if (!comp_ctx->enable_ref_types) { - goto unsupport_ref_types; + if (!comp_ctx->enable_ref_types && !comp_ctx->enable_gc) { + goto unsupport_gc_and_ref_types; } read_leb_uint32(frame_ip, frame_ip_end, vec_len); @@ -453,18 +1236,26 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) (void)vec_len; type_idx = *frame_ip++; - if (!aot_compile_op_select(comp_ctx, func_ctx, - (type_idx != VALUE_TYPE_I64) - && (type_idx != VALUE_TYPE_F64))) + if (!aot_compile_op_select( + comp_ctx, func_ctx, + (type_idx != VALUE_TYPE_I64) + && (type_idx != VALUE_TYPE_F64) +#if WASM_ENABLE_GC != 0 + && !(comp_ctx->enable_gc + && comp_ctx->pointer_size == sizeof(uint64) + && wasm_is_type_reftype(type_idx)) +#endif + )) return false; + break; } case WASM_OP_TABLE_GET: { uint32 tbl_idx; - if (!comp_ctx->enable_ref_types) { - goto unsupport_ref_types; + if (!comp_ctx->enable_ref_types && !comp_ctx->enable_gc) { + goto unsupport_gc_and_ref_types; } read_leb_uint32(frame_ip, frame_ip_end, tbl_idx); @@ -476,8 +1267,8 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) { uint32 tbl_idx; - if (!comp_ctx->enable_ref_types) { - goto unsupport_ref_types; + if (!comp_ctx->enable_ref_types && !comp_ctx->enable_gc) { + goto unsupport_gc_and_ref_types; } read_leb_uint32(frame_ip, frame_ip_end, tbl_idx); @@ -489,8 +1280,8 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) { uint32 type; - if (!comp_ctx->enable_ref_types) { - goto unsupport_ref_types; + if (!comp_ctx->enable_ref_types && !comp_ctx->enable_gc) { + goto unsupport_gc_and_ref_types; } read_leb_uint32(frame_ip, frame_ip_end, type); @@ -503,8 +1294,8 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) } case WASM_OP_REF_IS_NULL: { - if (!comp_ctx->enable_ref_types) { - goto unsupport_ref_types; + if (!comp_ctx->enable_ref_types && !comp_ctx->enable_gc) { + goto unsupport_gc_and_ref_types; } if (!aot_compile_op_ref_is_null(comp_ctx, func_ctx)) @@ -513,8 +1304,8 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) } case WASM_OP_REF_FUNC: { - if (!comp_ctx->enable_ref_types) { - goto unsupport_ref_types; + if (!comp_ctx->enable_ref_types && !comp_ctx->enable_gc) { + goto unsupport_gc_and_ref_types; } read_leb_uint32(frame_ip, frame_ip_end, func_idx); @@ -522,7 +1313,532 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) return false; break; } -#endif +#endif /* end of WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */ + +#if WASM_ENABLE_GC != 0 + case WASM_OP_CALL_REF: + { + if (!comp_ctx->enable_gc) { + goto unsupport_gc; + } + + read_leb_uint32(frame_ip, frame_ip_end, type_idx); + if (!aot_compile_op_call_ref(comp_ctx, func_ctx, type_idx, + false)) + return false; + break; + } + + case WASM_OP_RETURN_CALL_REF: + { + if (!comp_ctx->enable_gc) { + goto unsupport_gc; + } + + read_leb_uint32(frame_ip, frame_ip_end, type_idx); + if (!aot_compile_op_call_ref(comp_ctx, func_ctx, type_idx, + true)) + return false; + if (!aot_compile_op_return(comp_ctx, func_ctx, &frame_ip)) + return false; + break; + } + + case WASM_OP_REF_EQ: + if (!comp_ctx->enable_gc) { + goto unsupport_gc; + } + + if (!aot_compile_op_ref_eq(comp_ctx, func_ctx)) + return false; + break; + + case WASM_OP_REF_AS_NON_NULL: + if (!comp_ctx->enable_gc) { + goto unsupport_gc; + } + + if (!aot_compile_op_ref_as_non_null(comp_ctx, func_ctx)) + return false; + break; + + case WASM_OP_BR_ON_NULL: + { + if (!comp_ctx->enable_gc) { + goto unsupport_gc; + } + + read_leb_uint32(frame_ip, frame_ip_end, br_depth); + if (!aot_compile_op_br_on_null(comp_ctx, func_ctx, br_depth, + &frame_ip)) + return false; + break; + } + + case WASM_OP_BR_ON_NON_NULL: + { + if (!comp_ctx->enable_gc) { + goto unsupport_gc; + } + + read_leb_uint32(frame_ip, frame_ip_end, br_depth); + if (!aot_compile_op_br_on_non_null(comp_ctx, func_ctx, br_depth, + &frame_ip)) + return false; + break; + } + + case WASM_OP_GC_PREFIX: + { + uint32 opcode1, field_idx, data_seg_idx, array_len; + + if (!comp_ctx->enable_gc) { + goto unsupport_gc; + } + + read_leb_uint32(frame_ip, frame_ip_end, opcode1); + /* opcode1 was checked in loader and is no larger than + UINT8_MAX */ + opcode = (uint8)opcode1; + + switch (opcode) { + case WASM_OP_STRUCT_NEW: + case WASM_OP_STRUCT_NEW_DEFAULT: + read_leb_uint32(frame_ip, frame_ip_end, type_index); + if (!aot_compile_op_struct_new( + comp_ctx, func_ctx, type_index, + opcode == WASM_OP_STRUCT_NEW_DEFAULT)) + return false; + break; + + case WASM_OP_STRUCT_GET: + case WASM_OP_STRUCT_GET_S: + case WASM_OP_STRUCT_GET_U: + read_leb_uint32(frame_ip, frame_ip_end, type_index); + read_leb_uint32(frame_ip, frame_ip_end, field_idx); + if (!aot_compile_op_struct_get( + comp_ctx, func_ctx, type_index, field_idx, + opcode == WASM_OP_STRUCT_GET_S)) + return false; + break; + + case WASM_OP_STRUCT_SET: + read_leb_uint32(frame_ip, frame_ip_end, type_index); + read_leb_uint32(frame_ip, frame_ip_end, field_idx); + if (!aot_compile_op_struct_set(comp_ctx, func_ctx, + type_index, field_idx)) + return false; + break; + + case WASM_OP_ARRAY_NEW: + case WASM_OP_ARRAY_NEW_DEFAULT: + case WASM_OP_ARRAY_NEW_FIXED: + read_leb_uint32(frame_ip, frame_ip_end, type_index); + if (opcode == WASM_OP_ARRAY_NEW_FIXED) + read_leb_uint32(frame_ip, frame_ip_end, array_len); + else + array_len = 0; + if (!aot_compile_op_array_new( + comp_ctx, func_ctx, type_index, + opcode == WASM_OP_ARRAY_NEW_DEFAULT, + opcode == WASM_OP_ARRAY_NEW_FIXED, array_len)) + return false; + break; + + case WASM_OP_ARRAY_NEW_DATA: + read_leb_uint32(frame_ip, frame_ip_end, type_index); + read_leb_uint32(frame_ip, frame_ip_end, data_seg_idx); + if (!aot_compile_op_array_new_data( + comp_ctx, func_ctx, type_index, data_seg_idx)) + return false; + break; + + case WASM_OP_ARRAY_NEW_ELEM: + /* TODO */ + aot_set_last_error("unsupported opcode"); + return false; + + case WASM_OP_ARRAY_GET: + case WASM_OP_ARRAY_GET_S: + case WASM_OP_ARRAY_GET_U: + read_leb_uint32(frame_ip, frame_ip_end, type_index); + if (!aot_compile_op_array_get( + comp_ctx, func_ctx, type_index, + opcode == WASM_OP_ARRAY_GET_S)) + return false; + break; + + case WASM_OP_ARRAY_SET: + read_leb_uint32(frame_ip, frame_ip_end, type_index); + if (!aot_compile_op_array_set(comp_ctx, func_ctx, + type_index)) + return false; + break; + + case WASM_OP_ARRAY_FILL: + read_leb_uint32(frame_ip, frame_ip_end, type_index); + if (!aot_compile_op_array_fill(comp_ctx, func_ctx, + type_index)) + return false; + break; + + case WASM_OP_ARRAY_COPY: + { + uint32 src_type_index; + + read_leb_uint32(frame_ip, frame_ip_end, type_index); + read_leb_uint32(frame_ip, frame_ip_end, src_type_index); + if (!aot_compile_op_array_copy( + comp_ctx, func_ctx, type_index, src_type_index)) + return false; + break; + } + + case WASM_OP_ARRAY_LEN: + if (!aot_compile_op_array_len(comp_ctx, func_ctx)) + return false; + break; + + case WASM_OP_REF_I31: + if (!aot_compile_op_i31_new(comp_ctx, func_ctx)) + return false; + break; + + case WASM_OP_I31_GET_S: + case WASM_OP_I31_GET_U: + if (!aot_compile_op_i31_get( + comp_ctx, func_ctx, + opcode == WASM_OP_I31_GET_S ? true : false)) + return false; + break; + + case WASM_OP_REF_TEST: + case WASM_OP_REF_TEST_NULLABLE: + { + int32 heap_type; + + read_leb_int32(frame_ip, frame_ip_end, heap_type); + if (!aot_compile_op_ref_test( + comp_ctx, func_ctx, heap_type, + opcode == WASM_OP_REF_TEST_NULLABLE ? true + : false)) + return false; + break; + } + + case WASM_OP_REF_CAST: + case WASM_OP_REF_CAST_NULLABLE: + { + int32 heap_type; + + read_leb_int32(frame_ip, frame_ip_end, heap_type); + if (!aot_compile_op_ref_cast( + comp_ctx, func_ctx, heap_type, + opcode == WASM_OP_REF_CAST_NULLABLE ? true + : false)) + return false; + break; + } + + case WASM_OP_BR_ON_CAST: + case WASM_OP_BR_ON_CAST_FAIL: + { + uint8 castflags; + int32 heap_type, dst_heap_type; + + CHECK_BUF(frame_ip, frame_ip_end, 1); + castflags = *frame_ip++; + read_leb_uint32(frame_ip, frame_ip_end, br_depth); + read_leb_int32(frame_ip, frame_ip_end, heap_type); + read_leb_int32(frame_ip, frame_ip_end, dst_heap_type); + + /* + * castflags should be 0~3: + * 0: (non-null, non-null) + * 1: (null, non-null) + * 2: (non-null, null) + * 3: (null, null) + * The nullability of source type has been checked in + * wasm loader, here we just need the dst nullability + */ + if (!aot_compile_op_br_on_cast( + comp_ctx, func_ctx, dst_heap_type, + castflags & 0x02, + opcode == WASM_OP_BR_ON_CAST_FAIL, br_depth, + &frame_ip)) + return false; + + (void)heap_type; + break; + } + + case WASM_OP_ANY_CONVERT_EXTERN: + if (!aot_compile_op_extern_internalize(comp_ctx, + func_ctx)) + return false; + break; + + case WASM_OP_EXTERN_CONVERT_ANY: + if (!aot_compile_op_extern_externalize(comp_ctx, + func_ctx)) + return false; + break; + +#if WASM_ENABLE_STRINGREF != 0 + case WASM_OP_STRING_NEW_UTF8: + case WASM_OP_STRING_NEW_WTF16: + case WASM_OP_STRING_NEW_LOSSY_UTF8: + case WASM_OP_STRING_NEW_WTF8: + { + EncodingFlag flag = WTF8; + + read_leb_uint32(frame_ip, frame_ip_end, mem_idx); + bh_assert(mem_idx == 0); + + if (opcode == WASM_OP_STRING_NEW_WTF16) { + flag = WTF16; + } + else if (opcode == WASM_OP_STRING_NEW_UTF8) { + flag = UTF8; + } + else if (opcode == WASM_OP_STRING_NEW_LOSSY_UTF8) { + flag = LOSSY_UTF8; + } + else if (opcode == WASM_OP_STRING_NEW_WTF8) { + flag = WTF8; + } + + if (!aot_compile_op_string_new(comp_ctx, func_ctx, + flag)) + return false; + break; + } + case WASM_OP_STRING_CONST: + { + uint32 contents; + read_leb_uint32(frame_ip, frame_ip_end, contents); + + if (!aot_compile_op_string_const(comp_ctx, func_ctx, + contents)) + return false; + break; + } + case WASM_OP_STRING_MEASURE_UTF8: + case WASM_OP_STRING_MEASURE_WTF8: + case WASM_OP_STRING_MEASURE_WTF16: + { + EncodingFlag flag = WTF8; + + if (opcode == WASM_OP_STRING_MEASURE_WTF16) { + flag = WTF16; + } + else if (opcode == WASM_OP_STRING_MEASURE_UTF8) { + flag = UTF8; + } + else if (opcode == WASM_OP_STRING_MEASURE_WTF8) { + flag = LOSSY_UTF8; + } + + if (!aot_compile_op_string_measure(comp_ctx, func_ctx, + flag)) + return false; + break; + } + case WASM_OP_STRING_ENCODE_UTF8: + case WASM_OP_STRING_ENCODE_WTF16: + case WASM_OP_STRING_ENCODE_LOSSY_UTF8: + case WASM_OP_STRING_ENCODE_WTF8: + { + EncodingFlag flag = WTF8; + + read_leb_uint32(frame_ip, frame_ip_end, mem_idx); + bh_assert(mem_idx == 0); + + if (opcode == WASM_OP_STRING_ENCODE_WTF16) { + flag = WTF16; + } + else if (opcode == WASM_OP_STRING_ENCODE_UTF8) { + flag = UTF8; + } + else if (opcode == WASM_OP_STRING_ENCODE_LOSSY_UTF8) { + flag = LOSSY_UTF8; + } + else if (opcode == WASM_OP_STRING_ENCODE_WTF8) { + flag = WTF8; + } + + if (!aot_compile_op_string_encode(comp_ctx, func_ctx, + mem_idx, flag)) + return false; + break; + } + case WASM_OP_STRING_CONCAT: + if (!aot_compile_op_string_concat(comp_ctx, func_ctx)) + return false; + break; + case WASM_OP_STRING_EQ: + if (!aot_compile_op_string_eq(comp_ctx, func_ctx)) + return false; + break; + case WASM_OP_STRING_IS_USV_SEQUENCE: + if (!aot_compile_op_string_is_usv_sequence(comp_ctx, + func_ctx)) + return false; + break; + case WASM_OP_STRING_AS_WTF8: + if (!aot_compile_op_string_as_wtf8(comp_ctx, func_ctx)) + return false; + break; + case WASM_OP_STRINGVIEW_WTF8_ADVANCE: + if (!aot_compile_op_stringview_wtf8_advance(comp_ctx, + func_ctx)) + return false; + break; + case WASM_OP_STRINGVIEW_WTF8_ENCODE_UTF8: + case WASM_OP_STRINGVIEW_WTF8_ENCODE_LOSSY_UTF8: + case WASM_OP_STRINGVIEW_WTF8_ENCODE_WTF8: + { + EncodingFlag flag = WTF8; + + read_leb_uint32(frame_ip, frame_ip_end, mem_idx); + bh_assert(mem_idx == 0); + + if (opcode == WASM_OP_STRINGVIEW_WTF8_ENCODE_UTF8) { + flag = UTF8; + } + else if (opcode + == WASM_OP_STRINGVIEW_WTF8_ENCODE_LOSSY_UTF8) { + flag = LOSSY_UTF8; + } + else if (opcode + == WASM_OP_STRINGVIEW_WTF8_ENCODE_WTF8) { + flag = WTF8; + } + + if (!aot_compile_op_stringview_wtf8_encode( + comp_ctx, func_ctx, mem_idx, flag)) + return false; + break; + } + case WASM_OP_STRINGVIEW_WTF8_SLICE: + if (!aot_compile_op_stringview_wtf8_slice(comp_ctx, + func_ctx)) + return false; + break; + case WASM_OP_STRING_AS_WTF16: + if (!aot_compile_op_string_as_wtf16(comp_ctx, func_ctx)) + return false; + break; + case WASM_OP_STRINGVIEW_WTF16_LENGTH: + if (!aot_compile_op_stringview_wtf16_length(comp_ctx, + func_ctx)) + return false; + break; + case WASM_OP_STRINGVIEW_WTF16_GET_CODEUNIT: + if (!aot_compile_op_stringview_wtf16_get_codeunit( + comp_ctx, func_ctx)) + return false; + break; + case WASM_OP_STRINGVIEW_WTF16_ENCODE: + { + read_leb_uint32(frame_ip, frame_ip_end, mem_idx); + bh_assert(mem_idx == 0); + + if (!aot_compile_op_stringview_wtf16_encode( + comp_ctx, func_ctx, mem_idx)) + return false; + break; + } + case WASM_OP_STRINGVIEW_WTF16_SLICE: + if (!aot_compile_op_stringview_wtf16_slice(comp_ctx, + func_ctx)) + return false; + break; + case WASM_OP_STRING_AS_ITER: + if (!aot_compile_op_string_as_iter(comp_ctx, func_ctx)) + return false; + break; + case WASM_OP_STRINGVIEW_ITER_NEXT: + if (!aot_compile_op_stringview_iter_next(comp_ctx, + func_ctx)) + return false; + break; + case WASM_OP_STRINGVIEW_ITER_ADVANCE: + if (!aot_compile_op_stringview_iter_advance(comp_ctx, + func_ctx)) + return false; + break; + case WASM_OP_STRINGVIEW_ITER_REWIND: + if (!aot_compile_op_stringview_iter_rewind(comp_ctx, + func_ctx)) + return false; + break; + case WASM_OP_STRINGVIEW_ITER_SLICE: + if (!aot_compile_op_stringview_iter_slice(comp_ctx, + func_ctx)) + return false; + break; + case WASM_OP_STRING_NEW_UTF8_ARRAY: + case WASM_OP_STRING_NEW_WTF16_ARRAY: + case WASM_OP_STRING_NEW_LOSSY_UTF8_ARRAY: + case WASM_OP_STRING_NEW_WTF8_ARRAY: + { + EncodingFlag flag = WTF8; + + if (opcode == WASM_OP_STRING_NEW_WTF16) { + flag = WTF16; + } + else if (opcode == WASM_OP_STRING_NEW_UTF8) { + flag = UTF8; + } + else if (opcode == WASM_OP_STRING_NEW_LOSSY_UTF8) { + flag = LOSSY_UTF8; + } + else if (opcode == WASM_OP_STRING_NEW_WTF8) { + flag = WTF8; + } + + if (!aot_compile_op_string_new_array(comp_ctx, func_ctx, + flag)) + return false; + + break; + } + case WASM_OP_STRING_ENCODE_UTF8_ARRAY: + case WASM_OP_STRING_ENCODE_WTF16_ARRAY: + case WASM_OP_STRING_ENCODE_LOSSY_UTF8_ARRAY: + case WASM_OP_STRING_ENCODE_WTF8_ARRAY: + { + EncodingFlag flag = WTF8; + + if (opcode == WASM_OP_STRING_ENCODE_WTF16) { + flag = WTF16; + } + else if (opcode == WASM_OP_STRING_ENCODE_UTF8) { + flag = UTF8; + } + else if (opcode == WASM_OP_STRING_ENCODE_LOSSY_UTF8) { + flag = LOSSY_UTF8; + } + else if (opcode == WASM_OP_STRING_ENCODE_WTF8) { + flag = WTF8; + } + + if (!aot_compile_op_string_encode_array(comp_ctx, + func_ctx, flag)) + return false; + break; + } +#endif /* end of WASM_ENABLE_STRINGREF != 0 */ + + default: + aot_set_last_error("unsupported opcode"); + return false; + } + break; + } + +#endif /* end of WASM_ENABLE_GC != 0 */ case WASM_OP_GET_LOCAL: read_leb_uint32(frame_ip, frame_ip_end, local_idx); @@ -1062,9 +2378,9 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) } #endif -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 if (WASM_OP_TABLE_INIT <= opcode && opcode <= WASM_OP_TABLE_FILL - && !comp_ctx->enable_ref_types) { + && (!comp_ctx->enable_ref_types && !comp_ctx->enable_gc)) { goto unsupport_ref_types; } #endif @@ -1137,7 +2453,7 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) break; } #endif /* WASM_ENABLE_BULK_MEMORY */ -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 case WASM_OP_TABLE_INIT: { uint32 tbl_idx, tbl_seg_idx; @@ -1201,7 +2517,7 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) return false; break; } -#endif /* WASM_ENABLE_REF_TYPES */ +#endif /* WASM_ENABLE_REF_TYPES || WASM_ENABLE_GC */ default: aot_set_last_error("unsupported opcode"); return false; @@ -2591,10 +3907,26 @@ unsupport_simd: return false; #endif -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 unsupport_ref_types: aot_set_last_error("reference type instruction was found, " - "try removing --disable-ref-types option"); + "try removing --disable-ref-types option " + "or adding --enable-gc option"); + return false; +#endif + +#if WASM_ENABLE_GC != 0 +unsupport_gc: + aot_set_last_error("GC instruction was found, " + "try adding --enable-gc option"); + return false; +#endif + +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 +unsupport_gc_and_ref_types: + aot_set_last_error( + "reference type or gc instruction was found, try removing " + "--disable-ref-types option or adding --enable-gc option"); return false; #endif diff --git a/core/iwasm/compilation/aot_compiler.h b/core/iwasm/compilation/aot_compiler.h index b6347c89d..5038a4130 100644 --- a/core/iwasm/compilation/aot_compiler.h +++ b/core/iwasm/compilation/aot_compiler.h @@ -8,6 +8,8 @@ #include "aot.h" #include "aot_llvm.h" +#include "../interpreter/wasm_interp.h" +#include "../aot/aot_runtime.h" #ifdef __cplusplus extern "C" { @@ -78,8 +80,33 @@ typedef enum FloatArithmetic { FLOAT_MAX, } FloatArithmetic; +/** + * Check whether a value type is a GC reference type, + * don't use wasm_is_type_reftype since it requires + * GC feature and may result in compilation error when + * GC feature isn't compiled + */ static inline bool -check_type_compatible(uint8 src_type, uint8 dst_type) +aot_is_type_gc_reftype(uint8 type) +{ + return ((type >= (uint8)REF_TYPE_ARRAYREF + && type <= (uint8)REF_TYPE_NULLFUNCREF) + || (type >= (uint8)REF_TYPE_HT_NULLABLE + && type <= (uint8)REF_TYPE_HT_NON_NULLABLE) +#if WASM_ENABLE_STRINGREF != 0 + || (type >= (uint8)REF_TYPE_STRINGVIEWWTF8 + && type <= (uint8)REF_TYPE_STRINGREF) + || (type >= (uint8)REF_TYPE_STRINGVIEWITER + && type <= (uint8)REF_TYPE_STRINGVIEWWTF16) +#endif + ) + ? true + : false; +} + +static inline bool +check_type_compatible(const AOTCompContext *comp_ctx, uint8 src_type, + uint8 dst_type) { if (src_type == dst_type) { return true; @@ -92,20 +119,332 @@ check_type_compatible(uint8 src_type, uint8 dst_type) /* i32 <==> func.ref, i32 <==> extern.ref */ if (src_type == VALUE_TYPE_I32 - && (dst_type == VALUE_TYPE_EXTERNREF - || dst_type == VALUE_TYPE_FUNCREF)) { + && (comp_ctx->enable_ref_types + && (dst_type == VALUE_TYPE_EXTERNREF + || dst_type == VALUE_TYPE_FUNCREF))) { return true; } if (dst_type == VALUE_TYPE_I32 - && (src_type == VALUE_TYPE_FUNCREF - || src_type == VALUE_TYPE_EXTERNREF)) { + && (comp_ctx->enable_ref_types + && (src_type == VALUE_TYPE_FUNCREF + || src_type == VALUE_TYPE_EXTERNREF))) { return true; } return false; } +/** + * Operations for AOTCompFrame + */ + +/** + * Get the offset from frame pointer to the n-th local variable slot. + * + * @param n the index to the local variable array + * + * @return the offset from frame pointer to the local variable slot + */ +static inline uint32 +offset_of_local(AOTCompContext *comp_ctx, unsigned n) +{ + if (!comp_ctx->is_jit_mode) + /* In AOTFrame, there are 7 pointers before field lp */ + return comp_ctx->pointer_size + * (offsetof(AOTFrame, lp) / sizeof(uintptr_t)) + + sizeof(uint32) * n; + else + return offsetof(WASMInterpFrame, lp) + sizeof(uint32) * n; +} + +uint32 +offset_of_local_in_outs_area(AOTCompContext *comp_ctx, unsigned n); + +/** + * Get the offset from frame pointer to the n-th local variable's + * reference flag slot. + * + * @param n the index to the local variable array + * + * @return the offset from frame pointer to the local variable slot + */ +static inline unsigned +offset_of_ref(AOTCompContext *comp_ctx, unsigned n) +{ + AOTCompFrame *frame = comp_ctx->aot_frame; + uint32 all_cell_num = frame->max_local_cell_num + frame->max_stack_cell_num; + return offset_of_local(comp_ctx, all_cell_num) + n; +} + +/** + * Generate instructions to commit computation result to the frame. + * The general principle is to only commit values that will be used + * through the frame. + * + * @param frame the frame information + */ +bool +aot_gen_commit_values(AOTCompFrame *frame); + +/** + * Generate instructions to commit SP and IP pointers to the frame. + * + * @param frame the frame information + */ +bool +aot_gen_commit_sp_ip(AOTCompFrame *frame, bool commit_sp, bool commit_ip); + +bool +aot_frame_store_value(AOTCompContext *comp_ctx, LLVMValueRef value, + uint8 value_type, LLVMValueRef cur_frame, uint32 offset); + +static inline void +push_32bit(AOTCompFrame *frame, AOTValue *aot_value) +{ + frame->sp->value = aot_value->value; + frame->sp->type = aot_value->type; + frame->sp->dirty = 1; + frame->sp++; +} + +static inline void +push_64bit(AOTCompFrame *frame, AOTValue *aot_value) +{ + push_32bit(frame, aot_value); + push_32bit(frame, aot_value); +} + +static inline void +push_i32(AOTCompFrame *frame, AOTValue *aot_value) +{ + bh_assert(aot_value->type == VALUE_TYPE_I32 + || aot_value->type == VALUE_TYPE_I1); + push_32bit(frame, aot_value); +} + +static inline void +push_i64(AOTCompFrame *frame, AOTValue *aot_value) +{ + bh_assert(aot_value->type == VALUE_TYPE_I64); + push_64bit(frame, aot_value); +} + +static inline void +push_f32(AOTCompFrame *frame, AOTValue *aot_value) +{ + bh_assert(aot_value->type == VALUE_TYPE_F32); + push_32bit(frame, aot_value); +} + +static inline void +push_f64(AOTCompFrame *frame, AOTValue *aot_value) +{ + bh_assert(aot_value->type == VALUE_TYPE_F64); + push_64bit(frame, aot_value); +} + +static inline void +push_v128(AOTCompFrame *frame, AOTValue *aot_value) +{ + bh_assert(aot_value->type == VALUE_TYPE_V128); + push_64bit(frame, aot_value); + push_64bit(frame, aot_value); +} + +static inline void +push_ref(AOTCompFrame *frame, AOTValue *aot_value) +{ + bh_assert(frame->comp_ctx->enable_ref_types); + push_32bit(frame, aot_value); +} + +#if WASM_ENABLE_GC != 0 +static inline void +push_gc_ref(AOTCompFrame *frame, AOTValue *aot_value) +{ + bh_assert(frame->comp_ctx->enable_gc); + bh_assert(aot_value->type == VALUE_TYPE_GC_REF); + if (frame->comp_ctx->pointer_size == sizeof(uint64)) { + push_64bit(frame, aot_value); + (frame->sp - 1)->ref = (frame->sp - 2)->ref = 1; + } + else { + push_32bit(frame, aot_value); + (frame->sp - 1)->ref = 1; + } +} +#endif + +/* Clear value slots except ref and committed_ref */ +static inline void +clear_frame_value_slots(AOTValueSlot *slots, uint32 n) +{ + uint32 i; + for (i = 0; i < n; i++) { + slots[i].value = 0; + slots[i].type = 0; + slots[i].dirty = 0; + } +} + +static inline void +pop_i32(AOTCompFrame *frame) +{ + bh_assert(frame->sp - frame->lp >= 1); + bh_assert((frame->sp - 1)->type == VALUE_TYPE_I32 + || (frame->sp - 1)->type == VALUE_TYPE_I1); + frame->sp--; + clear_frame_value_slots(frame->sp, 1); +} + +static inline void +pop_i64(AOTCompFrame *frame) +{ + bh_assert(frame->sp - frame->lp >= 2); + bh_assert((frame->sp - 1)->type == VALUE_TYPE_I64 + && (frame->sp - 2)->type == VALUE_TYPE_I64); + frame->sp -= 2; + clear_frame_value_slots(frame->sp, 2); +} + +static inline void +pop_f32(AOTCompFrame *frame) +{ + bh_assert(frame->sp - frame->lp >= 1); + bh_assert((frame->sp - 1)->type == VALUE_TYPE_F32); + frame->sp--; + clear_frame_value_slots(frame->sp, 1); +} + +static inline void +pop_f64(AOTCompFrame *frame) +{ + bh_assert(frame->sp - frame->lp >= 2); + bh_assert((frame->sp - 1)->type == VALUE_TYPE_F64 + && (frame->sp - 2)->type == VALUE_TYPE_F64); + frame->sp -= 2; + clear_frame_value_slots(frame->sp, 2); +} + +static inline void +pop_v128(AOTCompFrame *frame) +{ + bh_assert(frame->sp - frame->lp >= 4); + bh_assert((frame->sp - 1)->type == VALUE_TYPE_V128 + && (frame->sp - 2)->type == VALUE_TYPE_V128 + && (frame->sp - 3)->type == VALUE_TYPE_V128 + && (frame->sp - 4)->type == VALUE_TYPE_V128); + frame->sp -= 4; + clear_frame_value_slots(frame->sp, 4); +} + +static inline void +pop_ref(AOTCompFrame *frame) +{ + bh_assert(frame->sp - frame->lp >= 1); + bh_assert((frame->sp - 1)->type == VALUE_TYPE_FUNCREF + || (frame->sp - 1)->type == VALUE_TYPE_EXTERNREF); + frame->sp -= 1; + clear_frame_value_slots(frame->sp, 1); +} + +#if WASM_ENABLE_GC != 0 +static inline void +pop_gc_ref(AOTCompFrame *frame) +{ + bh_assert(frame->sp - frame->lp >= 1); + bh_assert((frame->sp - 1)->type == VALUE_TYPE_GC_REF); + frame->sp -= 1; + clear_frame_value_slots(frame->sp, 1); + frame->sp->ref = 0; + if (frame->comp_ctx->pointer_size == sizeof(uint64)) { + bh_assert(frame->sp - frame->lp >= 1); + bh_assert((frame->sp - 1)->type == VALUE_TYPE_GC_REF); + frame->sp -= 1; + clear_frame_value_slots(frame->sp, 1); + frame->sp->ref = 0; + } +} +#endif + +static inline void +set_local_i32(AOTCompFrame *frame, int n, LLVMValueRef value) +{ + frame->lp[n].value = value; + frame->lp[n].type = VALUE_TYPE_I32; + frame->lp[n].dirty = 1; +} + +static inline void +set_local_i64(AOTCompFrame *frame, int n, LLVMValueRef value) +{ + frame->lp[n].value = value; + frame->lp[n].type = VALUE_TYPE_I64; + frame->lp[n].dirty = 1; + frame->lp[n + 1].value = value; + frame->lp[n + 1].type = VALUE_TYPE_I64; + frame->lp[n + 1].dirty = 1; +} + +static inline void +set_local_f32(AOTCompFrame *frame, int n, LLVMValueRef value) +{ + frame->lp[n].value = value; + frame->lp[n].type = VALUE_TYPE_F32; + frame->lp[n].dirty = 1; +} + +static inline void +set_local_f64(AOTCompFrame *frame, int n, LLVMValueRef value) +{ + frame->lp[n].value = value; + frame->lp[n].type = VALUE_TYPE_F64; + frame->lp[n].dirty = 1; + frame->lp[n + 1].value = value; + frame->lp[n + 1].type = VALUE_TYPE_F64; + frame->lp[n + 1].dirty = 1; +} + +static inline void +set_local_v128(AOTCompFrame *frame, int n, LLVMValueRef value) +{ + uint32 i; + for (i = 0; i < 4; i++) { + frame->lp[n + i].value = value; + frame->lp[n + i].type = VALUE_TYPE_V128; + frame->lp[n + i].dirty = 1; + } +} + +static inline void +set_local_ref(AOTCompFrame *frame, int n, LLVMValueRef value, uint8 ref_type) +{ + bh_assert(frame->comp_ctx->enable_ref_types); + frame->lp[n].value = value; + frame->lp[n].type = ref_type; + frame->lp[n].dirty = 1; +} + +#if WASM_ENABLE_GC != 0 +static inline void +set_local_gc_ref(AOTCompFrame *frame, int n, LLVMValueRef value, uint8 ref_type) +{ + bh_assert(frame->comp_ctx->enable_gc); + bh_assert(ref_type == VALUE_TYPE_GC_REF); + frame->lp[n].value = value; + frame->lp[n].type = ref_type; + frame->lp[n].dirty = 1; + frame->lp[n].ref = 1; + if (frame->comp_ctx->pointer_size == sizeof(uint64)) { + frame->lp[n + 1].value = value; + frame->lp[n + 1].type = ref_type; + frame->lp[n + 1].dirty = 1; + frame->lp[n + 1].ref = 1; + } +} +#endif + #define CHECK_STACK() \ do { \ if (!func_ctx->block_stack.block_list_end) { \ @@ -119,37 +458,61 @@ check_type_compatible(uint8 src_type, uint8 dst_type) } \ } while (0) +#if WASM_ENABLE_GC != 0 + +#define GET_GC_REF_FROM_STACK(llvm_value) \ + do { \ + AOTValue *aot_value; \ + CHECK_STACK(); \ + aot_value = \ + func_ctx->block_stack.block_list_end->value_stack.value_list_end; \ + if (aot_value->type != VALUE_TYPE_GC_REF) { \ + aot_set_last_error("WASM stack data type is not reference"); \ + goto fail; \ + } \ + llvm_value = aot_value->value; \ + } while (0) + +#endif + #define POP(llvm_value, value_type) \ do { \ AOTValue *aot_value; \ + uint8 val_type_to_pop = value_type; \ CHECK_STACK(); \ aot_value = aot_value_stack_pop( \ - &func_ctx->block_stack.block_list_end->value_stack); \ - if (!check_type_compatible(aot_value->type, value_type)) { \ + comp_ctx, &func_ctx->block_stack.block_list_end->value_stack); \ + if (comp_ctx->enable_gc && aot_is_type_gc_reftype(value_type)) \ + val_type_to_pop = VALUE_TYPE_GC_REF; \ + if (!check_type_compatible(comp_ctx, aot_value->type, \ + val_type_to_pop)) { \ aot_set_last_error("invalid WASM stack data type."); \ wasm_runtime_free(aot_value); \ goto fail; \ } \ - if (aot_value->type == value_type) \ + if (aot_value->type == val_type_to_pop) \ llvm_value = aot_value->value; \ else { \ if (aot_value->type == VALUE_TYPE_I1) { \ if (!(llvm_value = \ LLVMBuildZExt(comp_ctx->builder, aot_value->value, \ I32_TYPE, "i1toi32"))) { \ - aot_set_last_error("invalid WASM stack " \ - "data type."); \ + aot_set_last_error("invalid WASM stack data type."); \ wasm_runtime_free(aot_value); \ goto fail; \ } \ } \ else { \ - bh_assert(aot_value->type == VALUE_TYPE_I32 \ - || aot_value->type == VALUE_TYPE_FUNCREF \ - || aot_value->type == VALUE_TYPE_EXTERNREF); \ - bh_assert(value_type == VALUE_TYPE_I32 \ - || value_type == VALUE_TYPE_FUNCREF \ - || value_type == VALUE_TYPE_EXTERNREF); \ + bh_assert( \ + aot_value->type == VALUE_TYPE_I32 \ + || (comp_ctx->enable_ref_types \ + && (aot_value->type == VALUE_TYPE_FUNCREF \ + || aot_value->type == VALUE_TYPE_EXTERNREF))); \ + bh_assert( \ + val_type_to_pop == VALUE_TYPE_I32 \ + || (comp_ctx->enable_ref_types \ + && (val_type_to_pop == VALUE_TYPE_FUNCREF \ + || val_type_to_pop == VALUE_TYPE_EXTERNREF))); \ llvm_value = aot_value->value; \ } \ } \ @@ -163,13 +526,14 @@ check_type_compatible(uint8 src_type, uint8 dst_type) #define POP_V128(v) POP(v, VALUE_TYPE_V128) #define POP_FUNCREF(v) POP(v, VALUE_TYPE_FUNCREF) #define POP_EXTERNREF(v) POP(v, VALUE_TYPE_EXTERNREF) +#define POP_GC_REF(v) POP(v, VALUE_TYPE_GC_REF) #define POP_COND(llvm_value) \ do { \ AOTValue *aot_value; \ CHECK_STACK(); \ aot_value = aot_value_stack_pop( \ - &func_ctx->block_stack.block_list_end->value_stack); \ + comp_ctx, &func_ctx->block_stack.block_list_end->value_stack); \ if (aot_value->type != VALUE_TYPE_I1 \ && aot_value->type != VALUE_TYPE_I32) { \ aot_set_last_error("invalid WASM stack data type."); \ @@ -190,23 +554,31 @@ check_type_compatible(uint8 src_type, uint8 dst_type) wasm_runtime_free(aot_value); \ } while (0) -#define PUSH(llvm_value, value_type) \ - do { \ - AOTValue *aot_value; \ - if (!func_ctx->block_stack.block_list_end) { \ - aot_set_last_error("WASM block stack underflow."); \ - goto fail; \ - } \ - aot_value = wasm_runtime_malloc(sizeof(AOTValue)); \ - if (!aot_value) { \ - aot_set_last_error("allocate memory failed."); \ - goto fail; \ - } \ - memset(aot_value, 0, sizeof(AOTValue)); \ - aot_value->type = value_type; \ - aot_value->value = llvm_value; \ - aot_value_stack_push( \ - &func_ctx->block_stack.block_list_end->value_stack, aot_value); \ +#define PUSH(llvm_value, value_type) \ + do { \ + AOTValue *aot_value; \ + if (!func_ctx->block_stack.block_list_end) { \ + aot_set_last_error("WASM block stack underflow."); \ + goto fail; \ + } \ + aot_value = wasm_runtime_malloc(sizeof(AOTValue)); \ + if (!aot_value) { \ + aot_set_last_error("allocate memory failed."); \ + goto fail; \ + } \ + memset(aot_value, 0, sizeof(AOTValue)); \ + if (comp_ctx->enable_gc && aot_is_type_gc_reftype(value_type)) \ + aot_value->type = VALUE_TYPE_GC_REF; \ + else if (comp_ctx->enable_ref_types \ + && (value_type == VALUE_TYPE_FUNCREF \ + || value_type == VALUE_TYPE_EXTERNREF)) \ + aot_value->type = VALUE_TYPE_I32; \ + else \ + aot_value->type = value_type; \ + aot_value->value = llvm_value; \ + aot_value_stack_push( \ + comp_ctx, &func_ctx->block_stack.block_list_end->value_stack, \ + aot_value); \ } while (0) #define PUSH_I32(v) PUSH(v, VALUE_TYPE_I32) @@ -217,9 +589,10 @@ check_type_compatible(uint8 src_type, uint8 dst_type) #define PUSH_COND(v) PUSH(v, VALUE_TYPE_I1) #define PUSH_FUNCREF(v) PUSH(v, VALUE_TYPE_FUNCREF) #define PUSH_EXTERNREF(v) PUSH(v, VALUE_TYPE_EXTERNREF) +#define PUSH_GC_REF(v) PUSH(v, VALUE_TYPE_GC_REF) #define TO_LLVM_TYPE(wasm_type) \ - wasm_type_to_llvm_type(&comp_ctx->basic_types, wasm_type) + wasm_type_to_llvm_type(comp_ctx, &comp_ctx->basic_types, wasm_type) #define I32_TYPE comp_ctx->basic_types.int32_type #define I64_TYPE comp_ctx->basic_types.int64_type @@ -229,15 +602,19 @@ check_type_compatible(uint8 src_type, uint8 dst_type) #define INT1_TYPE comp_ctx->basic_types.int1_type #define INT8_TYPE comp_ctx->basic_types.int8_type #define INT16_TYPE comp_ctx->basic_types.int16_type +#define INTPTR_T_TYPE comp_ctx->basic_types.intptr_t_type #define MD_TYPE comp_ctx->basic_types.meta_data_type #define INT8_PTR_TYPE comp_ctx->basic_types.int8_ptr_type #define INT16_PTR_TYPE comp_ctx->basic_types.int16_ptr_type #define INT32_PTR_TYPE comp_ctx->basic_types.int32_ptr_type #define INT64_PTR_TYPE comp_ctx->basic_types.int64_ptr_type +#define INTPTR_T_PTR_TYPE comp_ctx->basic_types.intptr_t_ptr_type #define F32_PTR_TYPE comp_ctx->basic_types.float32_ptr_type #define F64_PTR_TYPE comp_ctx->basic_types.float64_ptr_type #define FUNC_REF_TYPE comp_ctx->basic_types.funcref_type #define EXTERN_REF_TYPE comp_ctx->basic_types.externref_type +#define GC_REF_TYPE comp_ctx->basic_types.gc_ref_type +#define GC_REF_PTR_TYPE comp_ctx->basic_types.gc_ref_ptr_type #define INT8_PTR_TYPE_GS comp_ctx->basic_types.int8_ptr_type_gs #define INT16_PTR_TYPE_GS comp_ctx->basic_types.int16_ptr_type_gs @@ -253,7 +630,10 @@ check_type_compatible(uint8 src_type, uint8 dst_type) #define I8_CONST(v) LLVMConstInt(INT8_TYPE, v, true) #define LLVM_CONST(name) (comp_ctx->llvm_consts.name) +#define I1_ZERO LLVM_CONST(i1_zero) +#define I1_ONE LLVM_CONST(i1_one) #define I8_ZERO LLVM_CONST(i8_zero) +#define I8_ONE LLVM_CONST(i8_one) #define I32_ZERO LLVM_CONST(i32_zero) #define I64_ZERO LLVM_CONST(i64_zero) #define F32_ZERO LLVM_CONST(f32_zero) @@ -267,6 +647,9 @@ check_type_compatible(uint8 src_type, uint8 dst_type) #define I32_SEVEN LLVM_CONST(i32_seven) #define I32_EIGHT LLVM_CONST(i32_eight) #define I32_NINE LLVM_CONST(i32_nine) +#define I32_TEN LLVM_CONST(i32_ten) +#define I32_ELEVEN LLVM_CONST(i32_eleven) +#define I32_TWELVE LLVM_CONST(i32_twelve) #define I32_NEG_ONE LLVM_CONST(i32_neg_one) #define I64_NEG_ONE LLVM_CONST(i64_neg_one) #define I32_MIN LLVM_CONST(i32_min) @@ -276,6 +659,8 @@ check_type_compatible(uint8 src_type, uint8 dst_type) #define I64_63 LLVM_CONST(i64_63) #define I64_64 LLVM_CONST(i64_64) #define REF_NULL I32_NEG_ONE +#define GC_REF_NULL LLVM_CONST(gc_ref_null) +#define I8_PTR_NULL LLVM_CONST(i8_ptr_null) #define V128_TYPE comp_ctx->basic_types.v128_type #define V128_PTR_TYPE comp_ctx->basic_types.v128_ptr_type diff --git a/core/iwasm/compilation/aot_emit_aot_file.c b/core/iwasm/compilation/aot_emit_aot_file.c index d674b022c..b7f3a2e47 100644 --- a/core/iwasm/compilation/aot_emit_aot_file.c +++ b/core/iwasm/compilation/aot_emit_aot_file.c @@ -196,10 +196,8 @@ get_file_header_size() static uint32 get_string_size(AOTCompContext *comp_ctx, const char *s) { - /* string size (2 bytes) + string content */ - return (uint32)sizeof(uint16) + (uint32)strlen(s) + - /* emit string with '\0' only in XIP mode */ - (comp_ctx->is_indirect_mode ? 1 : 0); + /* string size (2 bytes) + string content + '\0' */ + return (uint32)sizeof(uint16) + (uint32)strlen(s) + 1; } static uint32 @@ -209,12 +207,19 @@ get_target_info_section_size() } static uint32 -get_mem_init_data_size(AOTMemInitData *mem_init_data) +get_init_expr_size(const AOTCompContext *comp_ctx, const AOTCompData *comp_data, + InitializerExpression *expr); + +static uint32 +get_mem_init_data_size(AOTCompContext *comp_ctx, AOTMemInitData *mem_init_data) { - /* init expr type (4 bytes) + init expr value (8 bytes) - + byte count (4 bytes) + bytes */ - uint32 total_size = (uint32)(sizeof(uint32) + sizeof(uint64) - + sizeof(uint32) + mem_init_data->byte_count); + /* init expr type (4 bytes) + * + init expr value (4 bytes, valid value can only be i32/get_global) + * + byte count (4 bytes) + bytes */ + uint32 total_size = + (uint32)(get_init_expr_size(comp_ctx, comp_ctx->comp_data, + &mem_init_data->offset) + + sizeof(uint32) + mem_init_data->byte_count); /* bulk_memory enabled: is_passive (4 bytes) + memory_index (4 bytes) @@ -227,7 +232,8 @@ get_mem_init_data_size(AOTMemInitData *mem_init_data) } static uint32 -get_mem_init_data_list_size(AOTMemInitData **mem_init_data_list, +get_mem_init_data_list_size(AOTCompContext *comp_ctx, + AOTMemInitData **mem_init_data_list, uint32 mem_init_data_count) { AOTMemInitData **mem_init_data = mem_init_data_list; @@ -235,7 +241,7 @@ get_mem_init_data_list_size(AOTMemInitData **mem_init_data_list, for (i = 0; i < mem_init_data_count; i++, mem_init_data++) { size = align_uint(size, 4); - size += get_mem_init_data_size(*mem_init_data); + size += get_mem_init_data_size(comp_ctx, *mem_init_data); } return size; } @@ -257,33 +263,156 @@ get_memory_size(AOTCompData *comp_data) } static uint32 -get_mem_info_size(AOTCompData *comp_data) +get_mem_info_size(AOTCompContext *comp_ctx, AOTCompData *comp_data) { /* import_memory_size + memory_size + init_data_count + init_data_list */ return get_import_memory_size(comp_data) + get_memory_size(comp_data) + (uint32)sizeof(uint32) - + get_mem_init_data_list_size(comp_data->mem_init_data_list, + + get_mem_init_data_list_size(comp_ctx, + comp_data->mem_init_data_list, comp_data->mem_init_data_count); } static uint32 -get_table_init_data_size(AOTTableInitData *table_init_data) +get_init_expr_size(const AOTCompContext *comp_ctx, const AOTCompData *comp_data, + InitializerExpression *expr) { + /* init_expr_type */ + uint32 size = sizeof(uint32); +#if WASM_ENABLE_GC != 0 + WASMModule *module = comp_data->wasm_module; +#endif + + /* + init value size */ + switch (expr->init_expr_type) { + case INIT_EXPR_NONE: + /* no init value, used in table initializer */ + break; + case INIT_EXPR_TYPE_I32_CONST: + case INIT_EXPR_TYPE_F32_CONST: + case INIT_EXPR_TYPE_GET_GLOBAL: + size += sizeof(uint32); + break; + case INIT_EXPR_TYPE_I64_CONST: + case INIT_EXPR_TYPE_F64_CONST: + size += sizeof(uint64); + break; + case INIT_EXPR_TYPE_V128_CONST: + size += sizeof(uint64) * 2; + break; + case INIT_EXPR_TYPE_FUNCREF_CONST: + case INIT_EXPR_TYPE_REFNULL_CONST: + /* ref_index */ + size += sizeof(uint32); + break; +#if WASM_ENABLE_GC != 0 + case INIT_EXPR_TYPE_I31_NEW: + /* i32 */ + size += sizeof(uint32); + break; + case INIT_EXPR_TYPE_STRUCT_NEW: + { + uint32 i; + WASMStructNewInitValues *struct_new_init_values = + (WASMStructNewInitValues *)expr->u.data; + + /* type_index + field_count + fields */ + size += sizeof(uint32) + sizeof(uint32); + + bh_assert(struct_new_init_values->type_idx < module->type_count); + + for (i = 0; i < struct_new_init_values->count; i++) { + WASMStructType *struct_type = + (WASMStructType *) + module->types[struct_new_init_values->type_idx]; + uint32 field_size; + + bh_assert(struct_type); + bh_assert(struct_type->field_count + == struct_new_init_values->count); + + field_size = wasm_value_type_size_internal( + struct_type->fields[i].field_type, comp_ctx->pointer_size); + if (field_size < sizeof(uint32)) + field_size = sizeof(uint32); + size += field_size; + } + break; + } + case INIT_EXPR_TYPE_STRUCT_NEW_DEFAULT: + /* type_index */ + size += sizeof(uint32); + break; + case INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT: + /* array_elem_type + type_index + len */ + size += sizeof(uint32) * 3; + break; + case INIT_EXPR_TYPE_ARRAY_NEW: + case INIT_EXPR_TYPE_ARRAY_NEW_FIXED: + { + WASMArrayNewInitValues *array_new_init_values = + (WASMArrayNewInitValues *)expr->u.data; + WASMArrayType *array_type = NULL; + uint32 value_count; + + array_type = + (WASMArrayType *)module->types[array_new_init_values->type_idx]; + + bh_assert(array_type); + bh_assert(array_new_init_values->type_idx < module->type_count); + + value_count = + (expr->init_expr_type == INIT_EXPR_TYPE_ARRAY_NEW_FIXED) + ? array_new_init_values->length + : 1; + + /* array_elem_type + type_index + len + elems */ + size += sizeof(uint32) * 3 + + wasm_value_type_size_internal(array_type->elem_type, + comp_ctx->pointer_size) + * value_count; + break; + } +#endif /* end of WASM_ENABLE_GC != 0 */ + default: + bh_assert(0); + } + + return size; +} + +static uint32 +get_table_init_data_size(AOTCompContext *comp_ctx, + AOTTableInitData *table_init_data) +{ + uint32 size, i; + /* * mode (4 bytes), elem_type (4 bytes) * * table_index(4 bytes) + init expr type (4 bytes) + init expr value (8 * bytes) - * + func index count (4 bytes) + func indexes */ - return (uint32)(sizeof(uint32) * 2 + sizeof(uint32) + sizeof(uint32) - + sizeof(uint64) + sizeof(uint32) - + sizeof(uint32) * table_init_data->func_index_count); + size = (uint32)(sizeof(uint32) * 2 + sizeof(uint32) + sizeof(uint32) + + sizeof(uint64)) + /* Size of WasmRefType - inner padding (ref type + nullable + + heap_type) */ + + 8; + + /* + value count/func index count (4 bytes) + init_values */ + size += sizeof(uint32); + for (i = 0; i < table_init_data->value_count; i++) { + size += get_init_expr_size(comp_ctx, comp_ctx->comp_data, + &table_init_data->init_values[i]); + } + + return size; } static uint32 -get_table_init_data_list_size(AOTTableInitData **table_init_data_list, +get_table_init_data_list_size(AOTCompContext *comp_ctx, + AOTTableInitData **table_init_data_list, uint32 table_init_data_count) { /* @@ -295,60 +424,90 @@ get_table_init_data_list_size(AOTTableInitData **table_init_data_list, * | | U32 table_index * | | U32 offset.init_expr_type * | | U64 offset.u.i64 - * | | U32 func_index_count - * | | U32[func_index_count] + * | | U32 func_index_count / elem_count + * | | UINTPTR [func_index_count] / [elem_count] * ------------------------------ */ AOTTableInitData **table_init_data = table_init_data_list; uint32 size = 0, i; + /* table_init_data_count(4 bytes) */ size = (uint32)sizeof(uint32); for (i = 0; i < table_init_data_count; i++, table_init_data++) { size = align_uint(size, 4); - size += get_table_init_data_size(*table_init_data); + size += get_table_init_data_size(comp_ctx, *table_init_data); } return size; } static uint32 -get_import_table_size(AOTCompData *comp_data) +get_import_table_size(const AOTCompContext *comp_ctx, + const AOTCompData *comp_data) { /* * ------------------------------ * | import_table_count * ------------------------------ - * | | U32 table_init_size - * | | ---------------------- - * | AOTImpotTable[N] | U32 table_init_size - * | | ---------------------- - * | | U32 possible_grow (convenient than U8) + * | | U8 elem_type + * | | U8 table_flags + * | | U8 possible_grow + * | AOTImportTable[N] | U8 elem_ref_type.nullable (for GC only) + * | | U32 table_init_size + * | | U32 table_max_size + * | | U32 elem_ref_type.heap_type (for GC only) * ------------------------------ */ - return (uint32)(sizeof(uint32) - + comp_data->import_table_count * (sizeof(uint32) * 3)); + uint32 size = 0, i; + + size = (uint32)sizeof(uint32); + for (i = 0; i < comp_data->import_table_count; i++) { + size += sizeof(uint32) * 3; +#if WASM_ENABLE_GC != 0 + if (comp_ctx->enable_gc && comp_data->import_tables[i].elem_ref_type) + size += sizeof(uint32); +#endif + } + return size; } static uint32 -get_table_size(AOTCompData *comp_data) +get_table_size(const AOTCompContext *comp_ctx, const AOTCompData *comp_data) { /* * ------------------------------ * | table_count * ------------------------------ - * | | U32 elem_type - * | AOTTable[N] | U32 table_flags + * | | U8 elem_type + * | | U8 table_flags + * | | U8 possible_grow + * | AOTTable[N] | U8 elem_ref_type.nullable (for GC only) * | | U32 table_init_size * | | U32 table_max_size - * | | U32 possible_grow (convenient than U8) + * | | U32 elem_ref_type.heap_type (for GC only) + * | | N init_expr (for GC only) * ------------------------------ */ - return (uint32)(sizeof(uint32) - + comp_data->table_count * (sizeof(uint32) * 5)); + uint32 size = 0, i; + + size = (uint32)sizeof(uint32); + for (i = 0; i < comp_data->table_count; i++) { + size += sizeof(uint32) * 3; +#if WASM_ENABLE_GC != 0 + if (comp_ctx->enable_gc) { + if (comp_data->tables[i].elem_ref_type) { + size += sizeof(uint32); + } + size += get_init_expr_size(comp_ctx, comp_data, + &comp_data->tables[i].init_expr); + } +#endif + } + return size; } static uint32 -get_table_info_size(AOTCompData *comp_data) +get_table_info_size(AOTCompContext *comp_ctx, AOTCompData *comp_data) { /* * ------------------------------ @@ -371,39 +530,155 @@ get_table_info_size(AOTCompData *comp_data) * | * ------------------------------ */ - return get_import_table_size(comp_data) + get_table_size(comp_data) - + get_table_init_data_list_size(comp_data->table_init_data_list, + return get_import_table_size(comp_ctx, comp_data) + + get_table_size(comp_ctx, comp_data) + + get_table_init_data_list_size(comp_ctx, + comp_data->table_init_data_list, comp_data->table_init_data_count); } static uint32 -get_func_type_size(AOTFuncType *func_type) +get_func_type_size(AOTCompContext *comp_ctx, AOTFuncType *func_type) { - /* param count + result count + types */ - return (uint32)sizeof(uint32) * 2 + func_type->param_count - + func_type->result_count; +#if WASM_ENABLE_GC != 0 + /* type flag + is_sub_final + parent_type_idx + rec_count + rec_idx + param + * count + result count + * + ref_type_map_count + types + context of ref_type_map */ + if (comp_ctx->enable_gc) { + uint32 size = 0; + + /* type flag */ + size += sizeof(func_type->base_type.type_flag); + /* is_sub_final */ + size += sizeof(uint16); + /* parent_type_idx */ + size += sizeof(func_type->base_type.parent_type_idx); + /* rec_count */ + size += sizeof(func_type->base_type.rec_count); + /* rec_idx */ + size += sizeof(func_type->base_type.rec_idx); + /* param count */ + size += sizeof(func_type->param_count); + /* result count */ + size += sizeof(func_type->result_count); + /* ref_type_map_count */ + size += sizeof(func_type->ref_type_map_count); + /* param and result types */ + size += func_type->param_count + func_type->result_count; + /* align size */ + size = align_uint(size, 4); + /* ref_type_map */ + size += func_type->ref_type_map_count * 8; + + return size; + } + else +#endif + { + /* type flag + param count + result count + types */ + return (uint32)sizeof(uint16) * 3 + func_type->param_count + + func_type->result_count; + } } +#if WASM_ENABLE_GC != 0 static uint32 -get_func_types_size(AOTFuncType **func_types, uint32 func_type_count) +get_struct_type_size(AOTCompContext *comp_ctx, AOTStructType *struct_type) { - AOTFuncType **func_type = func_types; - uint32 size = 0, i; + uint32 size = 0; + /* type flag + is_sub_final + parent_type_idx + rec_count + rec_idx + field + * count + fields */ - for (i = 0; i < func_type_count; i++, func_type++) { - size = align_uint(size, 4); - size += get_func_type_size(*func_type); - } + /* type flag */ + size += sizeof(struct_type->base_type.type_flag); + /* is_sub_final */ + size += sizeof(uint16); + /* parent_type_idx */ + size += sizeof(struct_type->base_type.parent_type_idx); + /* rec_count */ + size += sizeof(struct_type->base_type.rec_count); + /* rec_idx */ + size += sizeof(struct_type->base_type.rec_idx); + /* field count */ + size += sizeof(struct_type->field_count); + /* field types */ + size += struct_type->field_count * 2; + /* ref_type_map_count */ + size += sizeof(struct_type->ref_type_map_count); + size = align_uint(size, 4); + /* ref_type_map */ + size += struct_type->ref_type_map_count * 8; return size; } static uint32 -get_func_type_info_size(AOTCompData *comp_data) +get_array_type_size(AOTCompContext *comp_ctx, AOTArrayType *array_type) { - /* func type count + func type list */ - return (uint32)sizeof(uint32) - + get_func_types_size(comp_data->func_types, - comp_data->func_type_count); + uint32 size = 0; + /* type flag + is_sub_final + parent_type_idx + rec_count + rec_idx + + elem_flags + elem_type + elem_ref_type */ + + /* type flag */ + size += sizeof(array_type->base_type.type_flag); + /* is_sub_final */ + size += sizeof(uint16); + /* parent_type_idx (u32) */ + size += sizeof(array_type->base_type.parent_type_idx); + /* rec_count */ + size += sizeof(array_type->base_type.rec_count); + /* rec_idx */ + size += sizeof(array_type->base_type.rec_idx); + /* elem_flags (u16) */ + size += sizeof(array_type->elem_flags); + /* elem_type (u8) */ + size += sizeof(array_type->elem_type); + /* elem_ref_type */ + if (array_type->elem_ref_type) { + /* nullable (u8) */ + size += sizeof(uint8); + /* heap type (u32) */ + size += sizeof(uint32); + } + + return size; +} +#endif + +static uint32 +get_type_info_size(AOTCompContext *comp_ctx, AOTCompData *comp_data) +{ + /* Initial size with size of type count */ + uint32 size = 4; + uint32 i; + +#if WASM_ENABLE_GC != 0 + if (comp_ctx->enable_gc) { + for (i = 0; i < comp_data->type_count; i++) { + size = align_uint(size, 4); + if (comp_data->types[i]->type_flag == WASM_TYPE_FUNC) + size += get_func_type_size(comp_ctx, + (AOTFuncType *)comp_data->types[i]); + else if (comp_data->types[i]->type_flag == WASM_TYPE_STRUCT) + size += get_struct_type_size( + comp_ctx, (AOTStructType *)comp_data->types[i]); + else if (comp_data->types[i]->type_flag == WASM_TYPE_ARRAY) + size += get_array_type_size( + comp_ctx, (AOTArrayType *)comp_data->types[i]); + else + bh_assert(0); + } + } + else +#endif + { + for (i = 0; i < comp_data->type_count; i++) { + size = align_uint(size, 4); + size += get_func_type_size(comp_ctx, + (AOTFuncType *)comp_data->types[i]); + } + } + + return size; } static uint32 @@ -442,37 +717,36 @@ get_import_global_info_size(AOTCompContext *comp_ctx, AOTCompData *comp_data) } static uint32 -get_global_size(AOTGlobal *global) +get_global_size(AOTCompContext *comp_ctx, AOTGlobal *global) { - if (global->init_expr.init_expr_type != INIT_EXPR_TYPE_V128_CONST) - /* type (1 byte) + is_mutable (1 byte) - + init expr type (2 byes) + init expr value (8 byes) */ - return sizeof(uint8) * 2 + sizeof(uint16) + sizeof(uint64); - else - /* type (1 byte) + is_mutable (1 byte) - + init expr type (2 byes) + v128 value (16 byes) */ - return sizeof(uint8) * 2 + sizeof(uint16) + sizeof(uint64) * 2; + /* type (1 byte) + is_mutable (1 byte) + padding (2 bytes) + + init expr value (include init expr type) */ + return sizeof(uint8) * 2 + sizeof(uint8) * 2 + + get_init_expr_size(comp_ctx, comp_ctx->comp_data, + &global->init_expr); } static uint32 -get_globals_size(AOTGlobal *globals, uint32 global_count) +get_globals_size(AOTCompContext *comp_ctx, AOTGlobal *globals, + uint32 global_count) { AOTGlobal *global = globals; uint32 size = 0, i; for (i = 0; i < global_count; i++, global++) { size = align_uint(size, 4); - size += get_global_size(global); + size += get_global_size(comp_ctx, global); } return size; } static uint32 -get_global_info_size(AOTCompData *comp_data) +get_global_info_size(AOTCompContext *comp_ctx, AOTCompData *comp_data) { /* global count + globals */ return (uint32)sizeof(uint32) - + get_globals_size(comp_data->globals, comp_data->global_count); + + get_globals_size(comp_ctx, comp_data->globals, + comp_data->global_count); } static uint32 @@ -544,19 +818,19 @@ get_init_data_section_size(AOTCompContext *comp_ctx, AOTCompData *comp_data, { uint32 size = 0; - size += get_mem_info_size(comp_data); + size += get_mem_info_size(comp_ctx, comp_data); size = align_uint(size, 4); - size += get_table_info_size(comp_data); + size += get_table_info_size(comp_ctx, comp_data); size = align_uint(size, 4); - size += get_func_type_info_size(comp_data); + size += get_type_info_size(comp_ctx, comp_data); size = align_uint(size, 4); size += get_import_global_info_size(comp_ctx, comp_data); size = align_uint(size, 4); - size += get_global_info_size(comp_data); + size += get_global_info_size(comp_ctx, comp_data); size = align_uint(size, 4); size += get_import_func_info_size(comp_ctx, comp_data); @@ -582,17 +856,60 @@ get_text_section_size(AOTObjectData *obj_data) } static uint32 -get_func_section_size(AOTCompData *comp_data, AOTObjectData *obj_data) +get_func_section_size(AOTCompContext *comp_ctx, AOTCompData *comp_data, + AOTObjectData *obj_data) { - /* text offsets + function type indexs */ uint32 size = 0; + /* text offsets */ if (is_32bit_binary(obj_data)) size = (uint32)sizeof(uint32) * comp_data->func_count; else size = (uint32)sizeof(uint64) * comp_data->func_count; + /* function type indexes */ size += (uint32)sizeof(uint32) * comp_data->func_count; + + /* max_local_cell_nums */ + size += (uint32)sizeof(uint32) * comp_data->func_count; + + /* max_stack_cell_nums */ + size += (uint32)sizeof(uint32) * comp_data->func_count; + +#if WASM_ENABLE_GC != 0 + /* func_local_ref_flags */ + if (comp_ctx->enable_gc) { + AOTFuncType *func_type; + uint32 i, j, local_ref_flags_cell_num; + + for (i = 0; i < comp_data->import_func_count; i++) { + func_type = comp_data->import_funcs[i].func_type; + /* recalculate cell_num based on target pointer size */ + local_ref_flags_cell_num = 0; + for (j = 0; j < func_type->param_count; j++) { + local_ref_flags_cell_num += wasm_value_type_cell_num_internal( + func_type->types[j], comp_ctx->pointer_size); + } + local_ref_flags_cell_num = + local_ref_flags_cell_num > 2 ? local_ref_flags_cell_num : 2; + + size = align_uint(size, 4); + size += (uint32)sizeof(uint32); + size += (uint32)sizeof(uint8) * local_ref_flags_cell_num; + } + + for (i = 0; i < comp_data->func_count; i++) { + func_type = comp_data->funcs[i]->func_type; + local_ref_flags_cell_num = comp_data->funcs[i]->param_cell_num + + comp_data->funcs[i]->local_cell_num; + + size = align_uint(size, 4); + size += (uint32)sizeof(uint32); + size += (uint32)sizeof(uint8) * local_ref_flags_cell_num; + } + } +#endif + return size; } @@ -915,6 +1232,12 @@ get_native_symbol_list_size(AOTCompContext *comp_ctx) return len; } +#if WASM_ENABLE_STRINGREF != 0 +static uint32 +get_string_literal_section_size(AOTCompContext *comp_ctx, + AOTCompData *comp_data); +#endif + static uint32 get_custom_sections_size(AOTCompContext *comp_ctx, AOTCompData *comp_data); @@ -924,6 +1247,9 @@ get_aot_file_size(AOTCompContext *comp_ctx, AOTCompData *comp_data, { uint32 size = 0; uint32 size_custom_section = 0; +#if WASM_ENABLE_STRINGREF != 0 + uint32 size_string_literal_section = 0; +#endif /* aot file header */ size += get_file_header_size(); @@ -950,7 +1276,7 @@ get_aot_file_size(AOTCompContext *comp_ctx, AOTCompData *comp_data, size = align_uint(size, 4); /* section id + section size */ size += (uint32)sizeof(uint32) * 2; - size += get_func_section_size(comp_data, obj_data); + size += get_func_section_size(comp_ctx, comp_data, obj_data); /* export section */ size = align_uint(size, 4); @@ -978,6 +1304,18 @@ get_aot_file_size(AOTCompContext *comp_ctx, AOTCompData *comp_data, size += size_custom_section; } +#if WASM_ENABLE_STRINGREF != 0 + /* string literal section */ + size_string_literal_section = + get_string_literal_section_size(comp_ctx, comp_data); + if (size_string_literal_section > 0) { + size = align_uint(size, 4); + /* section id + section size + sub section id */ + size += (uint32)sizeof(uint32) * 3; + size += size_string_literal_section; + } +#endif + return size; } @@ -1004,28 +1342,28 @@ exchange_uint32(uint8 *p_data) } static void -exchange_uint64(uint8 *pData) +exchange_uint64(uint8 *p_data) { uint32 value; - value = *(uint32 *)pData; - *(uint32 *)pData = *(uint32 *)(pData + 4); - *(uint32 *)(pData + 4) = value; - exchange_uint32(pData); - exchange_uint32(pData + 4); + value = *(uint32 *)p_data; + *(uint32 *)p_data = *(uint32 *)(p_data + 4); + *(uint32 *)(p_data + 4) = value; + exchange_uint32(p_data); + exchange_uint32(p_data + 4); } static void -exchange_uint128(uint8 *pData) +exchange_uint128(uint8 *p_data) { /* swap high 64bit and low 64bit */ - uint64 value = *(uint64 *)pData; - *(uint64 *)pData = *(uint64 *)(pData + 8); - *(uint64 *)(pData + 8) = value; + uint64 value = *(uint64 *)p_data; + *(uint64 *)p_data = *(uint64 *)(p_data + 8); + *(uint64 *)(p_data + 8) = value; /* exchange high 64bit */ - exchange_uint64(pData); + exchange_uint64(p_data); /* exchange low 64bit */ - exchange_uint64(pData + 8); + exchange_uint64(p_data + 8); } static union { @@ -1099,17 +1437,16 @@ static union { offset += len; \ } while (0) +/* Emit string with '\0' + */ #define EMIT_STR(s) \ do { \ - uint32 str_len = (uint32)strlen(s); \ + uint32 str_len = (uint32)strlen(s) + 1; \ if (str_len > INT16_MAX) { \ aot_set_last_error("emit string failed: " \ "string too long"); \ return false; \ } \ - if (comp_ctx->is_indirect_mode) \ - /* emit '\0' only in XIP mode */ \ - str_len++; \ EMIT_U16(str_len); \ EMIT_BUF(s, str_len); \ } while (0) @@ -1192,6 +1529,7 @@ fail_integer_too_large: return false; } +/* NOLINTNEXTLINE */ #define read_leb_uint32(p, p_end, res) \ do { \ uint64 res64; \ @@ -1315,6 +1653,30 @@ fail: } #endif /* end of WASM_ENABLE_LOAD_CUSTOM_SECTION != 0 */ +#if WASM_ENABLE_STRINGREF != 0 +static uint32 +get_string_literal_section_size(AOTCompContext *comp_ctx, + AOTCompData *comp_data) +{ + uint32 i; + uint32 size = 0; + uint32 string_count = comp_data->string_literal_count; + + if (string_count == 0) { + return 0; + } + + /* reserved slot + string count + string_lengths */ + size += sizeof(uint32) * (2 + string_count); + + for (i = 0; i < string_count; i++) { + size += comp_data->string_literal_lengths_wp[i]; + } + + return size; +} +#endif /* end of WASM_ENABLE_STRINGREF != 0 */ + static uint32 get_custom_sections_size(AOTCompContext *comp_ctx, AOTCompData *comp_data) { @@ -1401,7 +1763,8 @@ aot_emit_target_info_section(uint8 *buf, uint8 *buf_end, uint32 *p_offset, EMIT_U16(target_info->e_machine); EMIT_U32(target_info->e_version); EMIT_U32(target_info->e_flags); - EMIT_U32(target_info->reserved); + EMIT_U64(target_info->feature_flags); + EMIT_U64(target_info->reserved); EMIT_BUF(target_info->arch, sizeof(target_info->arch)); if (offset - *p_offset != section_size + sizeof(uint32) * 2) { @@ -1414,6 +1777,10 @@ aot_emit_target_info_section(uint8 *buf, uint8 *buf_end, uint32 *p_offset, return true; } +static bool +aot_emit_init_expr(uint8 *buf, uint8 *buf_end, uint32 *p_offset, + AOTCompContext *comp_ctx, InitializerExpression *expr); + static bool aot_emit_mem_info(uint8 *buf, uint8 *buf_end, uint32 *p_offset, AOTCompContext *comp_ctx, AOTCompData *comp_data, @@ -1456,13 +1823,14 @@ aot_emit_mem_info(uint8 *buf, uint8 *buf_end, uint32 *p_offset, EMIT_U32(0); EMIT_U32(0); } - EMIT_U32(init_datas[i]->offset.init_expr_type); - EMIT_U64(init_datas[i]->offset.u.i64); + if (!aot_emit_init_expr(buf, buf_end, &offset, comp_ctx, + &init_datas[i]->offset)) + return false; EMIT_U32(init_datas[i]->byte_count); EMIT_BUF(init_datas[i]->bytes, init_datas[i]->byte_count); } - if (offset - *p_offset != get_mem_info_size(comp_data)) { + if (offset - *p_offset != get_mem_info_size(comp_ctx, comp_data)) { aot_set_last_error("emit memory info failed."); return false; } @@ -1472,6 +1840,141 @@ aot_emit_mem_info(uint8 *buf, uint8 *buf_end, uint32 *p_offset, return true; } +static bool +aot_emit_init_expr(uint8 *buf, uint8 *buf_end, uint32 *p_offset, + AOTCompContext *comp_ctx, InitializerExpression *expr) +{ + uint32 offset = *p_offset; +#if WASM_ENABLE_GC != 0 + WASMModule *module = comp_ctx->comp_data->wasm_module; +#endif + + *p_offset = offset = align_uint(offset, 4); + + EMIT_U32(expr->init_expr_type); + switch (expr->init_expr_type) { + case INIT_EXPR_NONE: + break; + case INIT_EXPR_TYPE_I32_CONST: + case INIT_EXPR_TYPE_F32_CONST: + EMIT_U32(expr->u.i32); + break; + case INIT_EXPR_TYPE_I64_CONST: + case INIT_EXPR_TYPE_F64_CONST: + EMIT_U64(expr->u.i64); + break; + case INIT_EXPR_TYPE_V128_CONST: + EMIT_V128(expr->u.v128); + break; + case INIT_EXPR_TYPE_GET_GLOBAL: + EMIT_U32(expr->u.global_index); + break; + case INIT_EXPR_TYPE_FUNCREF_CONST: + case INIT_EXPR_TYPE_REFNULL_CONST: + EMIT_U32(expr->u.ref_index); + break; +#if WASM_ENABLE_GC != 0 + case INIT_EXPR_TYPE_I31_NEW: + EMIT_U32(expr->u.i32); + break; + case INIT_EXPR_TYPE_STRUCT_NEW: + { + uint32 i; + WASMStructNewInitValues *init_values = + (WASMStructNewInitValues *)expr->u.data; + WASMStructType *struct_type = NULL; + + EMIT_U32(init_values->type_idx); + EMIT_U32(init_values->count); + + bh_assert(init_values->type_idx < module->type_count); + + struct_type = + (WASMStructType *)module->types[init_values->type_idx]; + + bh_assert(struct_type); + bh_assert(struct_type->field_count == init_values->count); + + for (i = 0; i < init_values->count; i++) { + uint32 field_size = wasm_value_type_size_internal( + struct_type->fields[i].field_type, comp_ctx->pointer_size); + if (field_size <= sizeof(uint32)) + EMIT_U32(init_values->fields[i].u32); + else if (field_size == sizeof(uint64)) + EMIT_U64(init_values->fields[i].u64); + else if (field_size == sizeof(uint64) * 2) + EMIT_V128(init_values->fields[i].v128); + else { + bh_assert(0); + } + } + + break; + } + case INIT_EXPR_TYPE_STRUCT_NEW_DEFAULT: + EMIT_U32(expr->u.type_index); + break; + case INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT: + { + WASMArrayType *array_type = NULL; + + bh_assert(expr->u.array_new_default.type_index + < module->type_count); + array_type = + (WASMArrayType *) + module->types[expr->u.array_new_default.type_index]; + + EMIT_U32(array_type->elem_type); + EMIT_U32(expr->u.array_new_default.type_index); + EMIT_U32(expr->u.array_new_default.length); + break; + } + case INIT_EXPR_TYPE_ARRAY_NEW: + case INIT_EXPR_TYPE_ARRAY_NEW_FIXED: + { + uint32 value_count, i, field_size; + WASMArrayNewInitValues *init_values = + (WASMArrayNewInitValues *)expr->u.data; + WASMArrayType *array_type = NULL; + + bh_assert(init_values->type_idx < module->type_count); + array_type = (WASMArrayType *)module->types[init_values->type_idx]; + + EMIT_U32(array_type->elem_type); + EMIT_U32(init_values->type_idx); + EMIT_U32(init_values->length); + + value_count = + (expr->init_expr_type == INIT_EXPR_TYPE_ARRAY_NEW_FIXED) + ? init_values->length + : 1; + + field_size = wasm_value_type_size_internal(array_type->elem_type, + comp_ctx->pointer_size); + + for (i = 0; i < value_count; i++) { + if (field_size <= sizeof(uint32)) + EMIT_U32(init_values->elem_data[i].u32); + else if (field_size == sizeof(uint64)) + EMIT_U64(init_values->elem_data[i].u64); + else if (field_size == sizeof(uint64) * 2) + EMIT_V128(init_values->elem_data[i].v128); + else { + bh_assert(0); + } + } + break; + } +#endif /* end of WASM_ENABLE_GC != 0 */ + default: + aot_set_last_error("invalid init expr type."); + return false; + } + + *p_offset = offset; + return true; +} + static bool aot_emit_table_info(uint8 *buf, uint8 *buf_end, uint32 *p_offset, AOTCompContext *comp_ctx, AOTCompData *comp_data, @@ -1490,21 +1993,65 @@ aot_emit_table_info(uint8 *buf, uint8 *buf_end, uint32 *p_offset, * EMIT_STR(comp_data->import_tables[i].module_name ); * EMIT_STR(comp_data->import_tables[i].table_name); */ - EMIT_U32(comp_data->import_tables[i].elem_type); + EMIT_U8(comp_data->import_tables[i].elem_type); + EMIT_U8(comp_data->import_tables[i].table_flags); + EMIT_U8(comp_data->import_tables[i].possible_grow); +#if WASM_ENABLE_GC != 0 + if (comp_ctx->enable_gc && comp_data->import_tables[i].elem_ref_type) { + EMIT_U8(comp_data->import_tables[i] + .elem_ref_type->ref_ht_common.nullable); + } + else +#endif + { + /* emit one placeholder to keep the same size */ + EMIT_U8(0); + } EMIT_U32(comp_data->import_tables[i].table_init_size); EMIT_U32(comp_data->import_tables[i].table_max_size); - EMIT_U32(comp_data->import_tables[i].possible_grow & 0x000000FF); +#if WASM_ENABLE_GC != 0 + if (comp_ctx->enable_gc && comp_data->import_tables[i].elem_ref_type) { + bh_assert(wasm_is_type_multi_byte_type( + comp_data->import_tables[i].elem_type)); + EMIT_U32(comp_data->import_tables[i] + .elem_ref_type->ref_ht_common.heap_type); + } +#endif } /* Emit table count */ EMIT_U32(comp_data->table_count); /* Emit table items */ for (i = 0; i < comp_data->table_count; i++) { - EMIT_U32(comp_data->tables[i].elem_type); - EMIT_U32(comp_data->tables[i].table_flags); + EMIT_U8(comp_data->tables[i].elem_type); + EMIT_U8(comp_data->tables[i].table_flags); + EMIT_U8(comp_data->tables[i].possible_grow); +#if WASM_ENABLE_GC != 0 + if (comp_ctx->enable_gc && comp_data->tables[i].elem_ref_type) { + EMIT_U8(comp_data->tables[i].elem_ref_type->ref_ht_common.nullable); + } + else +#endif + { + /* emit one placeholder to keep the same size */ + EMIT_U8(0); + } EMIT_U32(comp_data->tables[i].table_init_size); EMIT_U32(comp_data->tables[i].table_max_size); - EMIT_U32(comp_data->tables[i].possible_grow & 0x000000FF); +#if WASM_ENABLE_GC != 0 + if (comp_ctx->enable_gc) { + if (comp_data->tables[i].elem_ref_type) { + bh_assert(wasm_is_type_multi_byte_type( + comp_data->tables[i].elem_type)); + EMIT_U32(comp_data->tables[i] + .elem_ref_type->ref_ht_common.heap_type); + } + if (!aot_emit_init_expr(buf, buf_end, &offset, comp_ctx, + &comp_data->tables[i].init_expr)) { + return false; + } + } +#endif } /* Emit table init data count */ @@ -1517,12 +2064,28 @@ aot_emit_table_info(uint8 *buf, uint8 *buf_end, uint32 *p_offset, EMIT_U32(init_datas[i]->table_index); EMIT_U32(init_datas[i]->offset.init_expr_type); EMIT_U64(init_datas[i]->offset.u.i64); - EMIT_U32(init_datas[i]->func_index_count); - for (j = 0; j < init_datas[i]->func_index_count; j++) - EMIT_U32(init_datas[i]->func_indexes[j]); +#if WASM_ENABLE_GC != 0 + if (comp_ctx->enable_gc && init_datas[i]->elem_ref_type) { + EMIT_U16(init_datas[i]->elem_ref_type->ref_ht_common.ref_type); + EMIT_U16(init_datas[i]->elem_ref_type->ref_ht_common.nullable); + EMIT_U32(init_datas[i]->elem_ref_type->ref_ht_common.heap_type); + } + else +#endif + { + EMIT_U16(init_datas[i]->elem_type); + EMIT_U16(0); + EMIT_U32(0); + } + EMIT_U32(init_datas[i]->value_count); + for (j = 0; j < init_datas[i]->value_count; j++) { + if (!aot_emit_init_expr(buf, buf_end, &offset, comp_ctx, + &init_datas[i]->init_values[j])) + return false; + } } - if (offset - *p_offset != get_table_info_size(comp_data)) { + if (offset - *p_offset != get_table_info_size(comp_ctx, comp_data)) { aot_set_last_error("emit table info failed."); return false; } @@ -1532,31 +2095,139 @@ aot_emit_table_info(uint8 *buf, uint8 *buf_end, uint32 *p_offset, return true; } +#if WASM_ENABLE_GC != 0 static bool -aot_emit_func_type_info(uint8 *buf, uint8 *buf_end, uint32 *p_offset, - AOTCompData *comp_data, AOTObjectData *obj_data) +aot_emit_reftype_map(uint8 *buf, uint8 *buf_end, uint32 *p_offset, uint32 count, + WASMRefTypeMap *refmap) { uint32 offset = *p_offset, i; - AOTFuncType **func_types = comp_data->func_types; - *p_offset = offset = align_uint(offset, 4); + for (i = 0; i < count; i++) { + EMIT_U16(refmap->index); + WASMRefType *ref_type = refmap->ref_type; - EMIT_U32(comp_data->func_type_count); + /* Note: WASMRefType is a union type */ + EMIT_U8(ref_type->ref_ht_common.ref_type); + EMIT_U8(ref_type->ref_ht_common.nullable); + EMIT_U32(ref_type->ref_ht_common.heap_type); - for (i = 0; i < comp_data->func_type_count; i++) { - offset = align_uint(offset, 4); - EMIT_U32(func_types[i]->param_count); - EMIT_U32(func_types[i]->result_count); - EMIT_BUF(func_types[i]->types, - func_types[i]->param_count + func_types[i]->result_count); - } - - if (offset - *p_offset != get_func_type_info_size(comp_data)) { - aot_set_last_error("emit function type info failed."); - return false; + refmap++; } *p_offset = offset; + return true; +} +#endif + +static bool +aot_emit_type_info(uint8 *buf, uint8 *buf_end, uint32 *p_offset, + AOTCompContext *comp_ctx, AOTCompData *comp_data, + AOTObjectData *obj_data) +{ + uint32 offset = *p_offset, i; + + *p_offset = offset = align_uint(offset, 4); + + EMIT_U32(comp_data->type_count); + +#if WASM_ENABLE_GC != 0 + if (comp_ctx->enable_gc) { + int32 idx; + AOTType **types = comp_data->types; + + for (i = 0; i < comp_data->type_count; i++) { + offset = align_uint(offset, 4); + EMIT_U16(types[i]->type_flag); + EMIT_U16(types[i]->is_sub_final); + EMIT_U32(types[i]->parent_type_idx); + + EMIT_U16(types[i]->rec_count); + EMIT_U16(types[i]->rec_idx); + + /* Emit WASM_TYPE_FUNC */ + if (types[i]->type_flag == WASM_TYPE_FUNC) { + AOTFuncType *func_type = (AOTFuncType *)types[i]; + EMIT_U16(func_type->param_count); + EMIT_U16(func_type->result_count); + EMIT_U16(func_type->ref_type_map_count); + EMIT_BUF(func_type->types, + func_type->param_count + func_type->result_count); + + offset = align_uint(offset, 4); + + aot_emit_reftype_map(buf, buf_end, &offset, + func_type->ref_type_map_count, + func_type->ref_type_maps); + } + /* Emit WASM_TYPE_STRUCT */ + else if (types[i]->type_flag == WASM_TYPE_STRUCT) { + AOTStructType *struct_type = (AOTStructType *)types[i]; + EMIT_U16(struct_type->field_count); + EMIT_U16(struct_type->ref_type_map_count); + + for (idx = 0; idx < struct_type->field_count; idx++) { + EMIT_U8(struct_type->fields[idx].field_flags); + EMIT_U8(struct_type->fields[idx].field_type); + } + + offset = align_uint(offset, 4); + + aot_emit_reftype_map(buf, buf_end, &offset, + struct_type->ref_type_map_count, + struct_type->ref_type_maps); + } + /* Emit WASM_TYPE_ARRAY */ + else if (types[i]->type_flag == WASM_TYPE_ARRAY) { + AOTArrayType *array_type = (AOTArrayType *)types[i]; + EMIT_U16(array_type->elem_flags); + EMIT_U8(array_type->elem_type); + if (array_type->elem_ref_type) { + bh_assert( + wasm_is_type_multi_byte_type(array_type->elem_type)); + EMIT_U8(array_type->elem_ref_type->ref_ht_common.nullable); + EMIT_U32( + array_type->elem_ref_type->ref_ht_common.heap_type); + } + } + else { + aot_set_last_error("invalid type flag."); + return false; + } + } + + if (offset - *p_offset != get_type_info_size(comp_ctx, comp_data)) { + aot_set_last_error("emit function type info failed."); + return false; + } + + *p_offset = offset; + } + else +#endif + { + AOTFuncType **func_types = (AOTFuncType **)comp_data->types; + + for (i = 0; i < comp_data->type_count; i++) { + offset = align_uint(offset, 4); + /* If GC is disabled, only emit function type info */ + EMIT_U16(WASM_TYPE_FUNC); + /* Omit to emit dummy padding for is_sub_final, + * parent_type_index, rec_count, rec_idx, 10 bytes in total */ + EMIT_U16(func_types[i]->param_count); + EMIT_U16(func_types[i]->result_count); + /* Omit to emit dummy padding for ref_type_map_count, 2 bytes in + * total */ + EMIT_BUF(func_types[i]->types, + func_types[i]->param_count + func_types[i]->result_count); + } + + if (offset - *p_offset != get_type_info_size(comp_ctx, comp_data)) { + aot_set_last_error("emit function type info failed."); + return false; + } + + *p_offset = offset; + } return true; } @@ -1595,7 +2266,8 @@ aot_emit_import_global_info(uint8 *buf, uint8 *buf_end, uint32 *p_offset, static bool aot_emit_global_info(uint8 *buf, uint8 *buf_end, uint32 *p_offset, - AOTCompData *comp_data, AOTObjectData *obj_data) + AOTCompContext *comp_ctx, AOTCompData *comp_data, + AOTObjectData *obj_data) { uint32 offset = *p_offset, i; AOTGlobal *global = comp_data->globals; @@ -1608,14 +2280,14 @@ aot_emit_global_info(uint8 *buf, uint8 *buf_end, uint32 *p_offset, offset = align_uint(offset, 4); EMIT_U8(global->type); EMIT_U8(global->is_mutable); - EMIT_U16(global->init_expr.init_expr_type); - if (global->init_expr.init_expr_type != INIT_EXPR_TYPE_V128_CONST) - EMIT_U64(global->init_expr.u.i64); - else - EMIT_V128(global->init_expr.u.v128); + + offset = align_uint(offset, 4); + if (!aot_emit_init_expr(buf, buf_end, &offset, comp_ctx, + &global->init_expr)) + return false; } - if (offset - *p_offset != get_global_info_size(comp_data)) { + if (offset - *p_offset != get_global_info_size(comp_ctx, comp_data)) { aot_set_last_error("emit global info failed."); return false; } @@ -1727,10 +2399,12 @@ aot_emit_init_data_section(uint8 *buf, uint8 *buf_end, uint32 *p_offset, if (!aot_emit_mem_info(buf, buf_end, &offset, comp_ctx, comp_data, obj_data) || !aot_emit_table_info(buf, buf_end, &offset, comp_ctx, comp_data, obj_data) - || !aot_emit_func_type_info(buf, buf_end, &offset, comp_data, obj_data) + || !aot_emit_type_info(buf, buf_end, &offset, comp_ctx, comp_data, + obj_data) || !aot_emit_import_global_info(buf, buf_end, &offset, comp_ctx, comp_data, obj_data) - || !aot_emit_global_info(buf, buf_end, &offset, comp_data, obj_data) + || !aot_emit_global_info(buf, buf_end, &offset, comp_ctx, comp_data, + obj_data) || !aot_emit_import_func_info(buf, buf_end, &offset, comp_ctx, comp_data, obj_data)) return false; @@ -1875,11 +2549,36 @@ aot_emit_text_section(uint8 *buf, uint8 *buf_end, uint32 *p_offset, return true; } +#if WASM_ENABLE_GC != 0 +static bool +aot_emit_ref_flag(uint8 *buf, uint8 *buf_end, uint32 *p_offset, + uint8 pointer_size, int8 type) +{ + uint32 j, offset = *p_offset; + uint16 value_type_cell_num; + + if (wasm_is_type_reftype(type) && !wasm_is_reftype_i31ref(type)) { + EMIT_U8(1); + if (pointer_size == sizeof(uint64)) + EMIT_U8(1); + } + else { + value_type_cell_num = wasm_value_type_cell_num(type); + for (j = 0; j < value_type_cell_num; j++) + EMIT_U8(0); + } + + *p_offset = offset; + return true; +} +#endif + static bool aot_emit_func_section(uint8 *buf, uint8 *buf_end, uint32 *p_offset, - AOTCompData *comp_data, AOTObjectData *obj_data) + AOTCompContext *comp_ctx, AOTCompData *comp_data, + AOTObjectData *obj_data) { - uint32 section_size = get_func_section_size(comp_data, obj_data); + uint32 section_size = get_func_section_size(comp_ctx, comp_data, obj_data); uint32 i, offset = *p_offset; AOTObjectFunc *func = obj_data->funcs; AOTFunc **funcs = comp_data->funcs; @@ -1899,6 +2598,69 @@ aot_emit_func_section(uint8 *buf, uint8 *buf_end, uint32 *p_offset, for (i = 0; i < comp_data->func_count; i++) EMIT_U32(funcs[i]->func_type_index); + for (i = 0; i < comp_data->func_count; i++) { + uint32 max_local_cell_num = + funcs[i]->param_cell_num + funcs[i]->local_cell_num; + EMIT_U32(max_local_cell_num); + } + + for (i = 0; i < comp_data->func_count; i++) + EMIT_U32(funcs[i]->max_stack_cell_num); + +#if WASM_ENABLE_GC != 0 + if (comp_ctx->enable_gc) { + /* emit func_local_ref_flag arrays for both import and AOTed funcs */ + AOTFuncType *func_type; + uint32 j, local_ref_flags_cell_num; + + for (i = 0; i < comp_data->import_func_count; i++) { + func_type = comp_data->import_funcs[i].func_type; + /* recalculate cell_num based on target pointer size */ + local_ref_flags_cell_num = 0; + for (j = 0; j < func_type->param_count; j++) { + local_ref_flags_cell_num += wasm_value_type_cell_num_internal( + func_type->types[j], comp_ctx->pointer_size); + } + local_ref_flags_cell_num = + local_ref_flags_cell_num > 2 ? local_ref_flags_cell_num : 2; + + offset = align_uint(offset, 4); + EMIT_U32(local_ref_flags_cell_num); + for (j = 0; j < func_type->param_count; j++) { + if (!aot_emit_ref_flag(buf, buf_end, &offset, + comp_ctx->pointer_size, + func_type->types[j])) + return false; + } + for (; j < 2; j++) + EMIT_U8(0); + } + + for (i = 0; i < comp_data->func_count; i++) { + func_type = funcs[i]->func_type; + local_ref_flags_cell_num = + funcs[i]->param_cell_num + funcs[i]->local_cell_num; + + offset = align_uint(offset, 4); + EMIT_U32(local_ref_flags_cell_num); + /* emit local_ref_flag for param variables */ + for (j = 0; j < func_type->param_count; j++) { + if (!aot_emit_ref_flag(buf, buf_end, &offset, + comp_ctx->pointer_size, + func_type->types[j])) + return false; + } + /* emit local_ref_flag for local variables */ + for (j = 0; j < funcs[i]->local_count; j++) { + if (!aot_emit_ref_flag(buf, buf_end, &offset, + comp_ctx->pointer_size, + funcs[i]->local_types_wp[j])) + return false; + } + } + } +#endif /* end of WASM_ENABLE_GC != 0 */ + if (offset - *p_offset != section_size + sizeof(uint32) * 2) { aot_set_last_error("emit function section failed."); return false; @@ -2099,6 +2861,50 @@ aot_emit_name_section(uint8 *buf, uint8 *buf_end, uint32 *p_offset, } #endif +#if WASM_ENABLE_STRINGREF != 0 +static bool +aot_emit_string_literal_section(uint8 *buf, uint8 *buf_end, uint32 *p_offset, + AOTCompData *comp_data, + AOTCompContext *comp_ctx) +{ + uint32 string_count = comp_data->string_literal_count; + + if (string_count > 0) { + uint32 offset = *p_offset; + uint32 i; + + *p_offset = offset = align_uint(offset, 4); + + EMIT_U32(AOT_SECTION_TYPE_CUSTOM); + /* sub section id + string literal section size */ + EMIT_U32(sizeof(uint32) * 1 + + get_string_literal_section_size(comp_ctx, comp_data)); + EMIT_U32(AOT_CUSTOM_SECTION_STRING_LITERAL); + + /* reserved */ + EMIT_U32(0); + + /* string literal count */ + EMIT_U32(string_count); + + for (i = 0; i < string_count; i++) { + EMIT_U32(comp_data->string_literal_lengths_wp[i]); + } + + for (i = 0; i < string_count; i++) { + uint32 string_length = comp_data->string_literal_lengths_wp[i]; + bh_memcpy_s((uint8 *)(buf + offset), (uint32)(buf_end - buf), + comp_data->string_literal_ptrs_wp[i], string_length); + offset += string_length; + } + + *p_offset = offset; + } + + return true; +} +#endif /* end of WASM_ENABLE_STRINGREF != 0 */ + static bool aot_emit_custom_sections(uint8 *buf, uint8 *buf_end, uint32 *p_offset, AOTCompData *comp_data, AOTCompContext *comp_ctx) @@ -2755,7 +3561,7 @@ aot_resolve_stack_sizes(AOTCompContext *comp_ctx, AOTObjectData *obj_data) } /* * Note: We can't always modify stack_sizes in-place. - * Eg. When WAMRC_LLC_COMPILER is used, LLVM sometimes uses + * E.g. When WAMRC_LLC_COMPILER is used, LLVM sometimes uses * read-only mmap of the temporary file to back * LLVMGetSectionContents. */ @@ -3057,7 +3863,7 @@ aot_resolve_object_relocation_group(AOTObjectData *obj_data, goto fail; } - /* parse relocation addend from reloction content */ + /* parse relocation addend from relocation content */ if (has_addend) { if (is_binary_32bit) { int32 addend = @@ -3523,7 +4329,7 @@ aot_obj_data_create(AOTCompContext *comp_ctx) aot_set_last_error("emit object file on Windows is unsupported."); goto fail; #else - /* Emit to assmelby file instead for arc target + /* Emit to assembly file instead for arc target as it cannot emit to object file */ char file_name[] = "wasm-XXXXXX", buf[128]; int fd, ret; @@ -3609,6 +4415,24 @@ aot_obj_data_create(AOTCompContext *comp_ctx) goto fail; } + /* Create wasm feature flags form compile options */ + obj_data->target_info.feature_flags = 0; + if (comp_ctx->enable_simd) { + obj_data->target_info.feature_flags |= WASM_FEATURE_SIMD_128BIT; + } + if (comp_ctx->enable_bulk_memory) { + obj_data->target_info.feature_flags |= WASM_FEATURE_BULK_MEMORY; + } + if (comp_ctx->enable_thread_mgr) { + obj_data->target_info.feature_flags |= WASM_FEATURE_MULTI_THREAD; + } + if (comp_ctx->enable_ref_types) { + obj_data->target_info.feature_flags |= WASM_FEATURE_REF_TYPES; + } + if (comp_ctx->enable_gc) { + obj_data->target_info.feature_flags |= WASM_FEATURE_GARBAGE_COLLECTION; + } + bh_print_time("Begin to resolve object file info"); /* resolve target info/text/relocations/functions */ @@ -3657,14 +4481,19 @@ aot_emit_aot_file_buf(AOTCompContext *comp_ctx, AOTCompData *comp_data, || !aot_emit_init_data_section(buf, buf_end, &offset, comp_ctx, comp_data, obj_data) || !aot_emit_text_section(buf, buf_end, &offset, comp_data, obj_data) - || !aot_emit_func_section(buf, buf_end, &offset, comp_data, obj_data) + || !aot_emit_func_section(buf, buf_end, &offset, comp_ctx, comp_data, + obj_data) || !aot_emit_export_section(buf, buf_end, &offset, comp_ctx, comp_data, obj_data) || !aot_emit_relocation_section(buf, buf_end, &offset, comp_ctx, comp_data, obj_data) || !aot_emit_native_symbol(buf, buf_end, &offset, comp_ctx) - || !aot_emit_custom_sections(buf, buf_end, &offset, comp_data, - comp_ctx)) + || !aot_emit_custom_sections(buf, buf_end, &offset, comp_data, comp_ctx) +#if WASM_ENABLE_STRINGREF != 0 + || !aot_emit_string_literal_section(buf, buf_end, &offset, comp_data, + comp_ctx) +#endif + ) goto fail2; #if 0 diff --git a/core/iwasm/compilation/aot_emit_compare.c b/core/iwasm/compilation/aot_emit_compare.c index a38263264..c57bdee40 100644 --- a/core/iwasm/compilation/aot_emit_compare.c +++ b/core/iwasm/compilation/aot_emit_compare.c @@ -230,3 +230,27 @@ aot_compile_op_f64_compare(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, fail: return false; } + +bool +aot_compile_op_ref_eq(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) +{ + LLVMValueRef gc_obj1 = NULL, gc_obj2 = NULL, res; + + POP_GC_REF(gc_obj1); + POP_GC_REF(gc_obj2); + + /* LLVM pointer values pointers are compared using LLVMBuildICmp */ + res = LLVMBuildICmp(comp_ctx->builder, LLVMIntEQ, gc_obj1, gc_obj2, + "cmp_gc_obj_eq"); + + if (!res) { + aot_set_last_error("llvm build compare failed."); + return false; + } + + PUSH_COND(res); + + return true; +fail: + return false; +} diff --git a/core/iwasm/compilation/aot_emit_compare.h b/core/iwasm/compilation/aot_emit_compare.h index 6ac37794c..f0bfa8ad4 100644 --- a/core/iwasm/compilation/aot_emit_compare.h +++ b/core/iwasm/compilation/aot_emit_compare.h @@ -28,6 +28,13 @@ bool aot_compile_op_f64_compare(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, FloatCond cond); +#if WASM_ENABLE_GC != 0 + +bool +aot_compile_op_ref_eq(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx); + +#endif + #ifdef __cplusplus } /* end of extern "C" */ #endif diff --git a/core/iwasm/compilation/aot_emit_control.c b/core/iwasm/compilation/aot_emit_control.c index a8ee938f2..8b24bcab8 100644 --- a/core/iwasm/compilation/aot_emit_control.c +++ b/core/iwasm/compilation/aot_emit_control.c @@ -6,6 +6,9 @@ #include "aot_emit_control.h" #include "aot_compiler.h" #include "aot_emit_exception.h" +#if WASM_ENABLE_GC != 0 +#include "aot_emit_gc.h" +#endif #include "../aot/aot_runtime.h" #include "../interpreter/wasm_loader.h" @@ -155,12 +158,81 @@ get_target_block(AOTFuncContext *func_ctx, uint32 br_depth) return block; } +static void +clear_frame_locals(AOTCompFrame *aot_frame) +{ + uint32 i; + + for (i = 0; i < aot_frame->max_local_cell_num; i++) { + aot_frame->lp[i].dirty = 0; + aot_frame->lp[i].value = NULL; + if (aot_frame->comp_ctx->enable_gc) + /* Mark the ref flag as committed */ + aot_frame->lp[i].committed_ref = aot_frame->lp[i].ref + 1; + } +} + +static void +restore_frame_sp_for_op_else(AOTBlock *block, AOTCompFrame *aot_frame) +{ + uint32 all_cell_num = + aot_frame->max_local_cell_num + aot_frame->max_stack_cell_num; + AOTValueSlot *p_end = aot_frame->lp + all_cell_num, *p; + + /* Reset all the value slots from current frame sp for the else + branch since they be the same as starting to translate the + if branch */ + for (p = block->frame_sp_begin; p < p_end; p++) { + p->dirty = 0; + p->value = NULL; + p->type = 0; + if (aot_frame->comp_ctx->enable_gc) { + p->ref = 0; + p->committed_ref = 1; + } + } + + bh_assert(aot_frame->sp >= block->frame_sp_begin); + aot_frame->sp = block->frame_sp_begin; +} + +static void +restore_frame_sp_for_op_end(AOTBlock *block, AOTCompFrame *aot_frame) +{ + uint32 all_cell_num = + aot_frame->max_local_cell_num + aot_frame->max_stack_cell_num; + AOTValueSlot *p_end = aot_frame->lp + all_cell_num, *p; + + bh_assert(block->frame_sp_max_reached >= block->frame_sp_begin); + + /* Reset all the value slots from current frame sp to be same as + starting to translate this block, except for the frame ref + flags: set the flags to uncommitted before the max frame sp + ever reached, set the flags to committed non-ref after that */ + for (p = block->frame_sp_begin; p < p_end; p++) { + p->dirty = 0; + p->value = NULL; + p->type = 0; + if (aot_frame->comp_ctx->enable_gc) { + p->ref = 0; + if (p < block->frame_sp_max_reached) + p->committed_ref = 0; + else + p->committed_ref = 1; + } + } + + bh_assert(aot_frame->sp >= block->frame_sp_begin); + aot_frame->sp = block->frame_sp_begin; +} + static bool handle_next_reachable_block(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, uint8 **p_frame_ip) { AOTBlock *block = func_ctx->block_stack.block_list_end; AOTBlock *block_prev; + AOTCompFrame *aot_frame = comp_ctx->aot_frame; uint8 *frame_ip = NULL; uint32 i; AOTFuncType *func_type; @@ -177,10 +249,22 @@ handle_next_reachable_block(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, comp_ctx, func_ctx, (*p_frame_ip - 1) - comp_ctx->comp_data->wasm_module->buf_code); #endif + + if (aot_frame) { + /* Clear frame local variables since they have been committed */ + clear_frame_locals(aot_frame); + } + if (block->label_type == LABEL_TYPE_IF && block->llvm_else_block && *p_frame_ip <= block->wasm_code_else) { /* Clear value stack and start to translate else branch */ - aot_value_stack_destroy(&block->value_stack); + aot_value_stack_destroy(comp_ctx, &block->value_stack); + + if (aot_frame) { + /* Restore the frame sp */ + restore_frame_sp_for_op_else(block, aot_frame); + } + /* Recover parameters of else branch */ for (i = 0; i < block->param_count; i++) PUSH(block->else_param_phis[i], block->param_types[i]); @@ -197,7 +281,13 @@ handle_next_reachable_block(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, if (block->llvm_else_block && !block->skip_wasm_code_else && *p_frame_ip <= block->wasm_code_else) { /* Clear value stack and start to translate else branch */ - aot_value_stack_destroy(&block->value_stack); + aot_value_stack_destroy(comp_ctx, &block->value_stack); + + if (aot_frame) { + /* Restore the frame sp */ + restore_frame_sp_for_op_else(block, aot_frame); + } + SET_BUILDER_POS(block->llvm_else_block); *p_frame_ip = block->wasm_code_else + 1; /* Push back the block */ @@ -215,7 +305,7 @@ handle_next_reachable_block(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, } frame_ip = block->wasm_code_end; - aot_block_destroy(block); + aot_block_destroy(comp_ctx, block); block = block_prev; } @@ -228,7 +318,13 @@ handle_next_reachable_block(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, && !block->skip_wasm_code_else && *p_frame_ip <= block->wasm_code_else) { /* Clear value stack and start to translate else branch */ - aot_value_stack_destroy(&block->value_stack); + aot_value_stack_destroy(comp_ctx, &block->value_stack); + + if (aot_frame) { + /* Restore the frame sp */ + restore_frame_sp_for_op_else(block, aot_frame); + } + /* Recover parameters of else branch */ for (i = 0; i < block->param_count; i++) PUSH(block->else_param_phis[i], block->param_types[i]); @@ -242,6 +338,12 @@ handle_next_reachable_block(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, /* Pop block, push its return value, and destroy the block */ block = aot_block_stack_pop(&func_ctx->block_stack); + + if (aot_frame) { + /* Restore the frame sp */ + restore_frame_sp_for_op_end(block, aot_frame); + } + func_type = func_ctx->aot_func->func_type; for (i = 0; i < block->result_count; i++) { bh_assert(block->result_phis[i]); @@ -285,7 +387,7 @@ handle_next_reachable_block(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, #endif } } - aot_block_destroy(block); + aot_block_destroy(comp_ctx, block); return true; fail: return false; @@ -381,6 +483,10 @@ push_aot_block_to_stack_and_pass_params(AOTCompContext *comp_ctx, /* Push the new block to block stack */ aot_block_stack_push(&func_ctx->block_stack, block); + if (comp_ctx->aot_frame) { + block->frame_sp_begin = block->frame_sp_max_reached = + comp_ctx->aot_frame->sp; + } /* Push param phis to the new block */ for (i = 0; i < block->param_count; i++) { @@ -473,6 +579,13 @@ aot_compile_op_block(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, block->block_index = func_ctx->block_stack.block_index[label_type]; func_ctx->block_stack.block_index[label_type]++; + if (comp_ctx->aot_frame) { + if (label_type != LABEL_TYPE_BLOCK && comp_ctx->enable_gc + && !aot_gen_commit_values(comp_ctx->aot_frame)) { + goto fail; + } + } + if (label_type == LABEL_TYPE_BLOCK || label_type == LABEL_TYPE_LOOP) { /* Create block */ format_block_name(name, sizeof(name), block->block_index, label_type, @@ -500,7 +613,7 @@ aot_compile_op_block(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, false, NULL, NULL))) { goto fail; } - aot_block_destroy(block); + aot_block_destroy(comp_ctx, block); return aot_handle_next_reachable_block(comp_ctx, func_ctx, p_frame_ip); } @@ -580,7 +693,7 @@ aot_compile_op_block(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, } else { /* skip the block */ - aot_block_destroy(block); + aot_block_destroy(comp_ctx, block); *p_frame_ip = end_addr + 1; } } @@ -593,7 +706,7 @@ aot_compile_op_block(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, return true; fail: - aot_block_destroy(block); + aot_block_destroy(comp_ctx, block); return false; } @@ -603,6 +716,7 @@ aot_compile_op_else(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, { AOTBlock *block = func_ctx->block_stack.block_list_end; LLVMValueRef value; + AOTCompFrame *aot_frame = comp_ctx->aot_frame; char name[32]; uint32 i, result_index; @@ -638,14 +752,26 @@ aot_compile_op_else(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, ADD_TO_RESULT_PHIS(block, value, result_index); } + if (aot_frame) { + bh_assert(block->frame_sp_begin == aot_frame->sp); + if (comp_ctx->enable_gc && !aot_gen_commit_values(aot_frame)) { + goto fail; + } + } + /* Jump to end block */ BUILD_BR(block->llvm_end_block); if (!block->skip_wasm_code_else && block->llvm_else_block) { /* Clear value stack, recover param values - * and start to translate else branch. - */ - aot_value_stack_destroy(&block->value_stack); + and start to translate else branch. */ + aot_value_stack_destroy(comp_ctx, &block->value_stack); + + if (comp_ctx->aot_frame) { + clear_frame_locals(aot_frame); + restore_frame_sp_for_op_else(block, aot_frame); + } + for (i = 0; i < block->param_count; i++) PUSH(block->else_param_phis[i], block->param_types[i]); SET_BUILDER_POS(block->llvm_else_block); @@ -685,6 +811,13 @@ aot_compile_op_end(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, MOVE_BLOCK_BEFORE(block->llvm_end_block, next_llvm_end_block); } + if (comp_ctx->aot_frame) { + if (block->label_type != LABEL_TYPE_FUNCTION && comp_ctx->enable_gc + && !aot_gen_commit_values(comp_ctx->aot_frame)) { + return false; + } + } + /* Handle block result values */ CREATE_RESULT_VALUE_PHIS(block); for (i = 0; i < block->result_count; i++) { @@ -695,6 +828,10 @@ aot_compile_op_end(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, ADD_TO_RESULT_PHIS(block, value, result_index); } + if (comp_ctx->aot_frame) { + bh_assert(comp_ctx->aot_frame->sp == block->frame_sp_begin); + } + /* Jump to the end block */ BUILD_BR(block->llvm_end_block); @@ -704,9 +841,9 @@ fail: return false; } -#if WASM_ENABLE_THREAD_MGR != 0 bool -check_suspend_flags(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) +check_suspend_flags(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + bool check_terminate_and_suspend) { LLVMValueRef terminate_addr, terminate_flags, flag, offset, res; LLVMBasicBlockRef terminate_block, non_terminate_block; @@ -774,7 +911,6 @@ check_suspend_flags(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) fail: return false; } -#endif /* End of WASM_ENABLE_THREAD_MGR */ bool aot_compile_op_br(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, @@ -786,18 +922,35 @@ aot_compile_op_br(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, char name[32]; uint32 i, param_index, result_index; -#if WASM_ENABLE_THREAD_MGR != 0 - /* Insert suspend check point */ - if (comp_ctx->enable_thread_mgr) { - if (!check_suspend_flags(comp_ctx, func_ctx)) - return false; - } -#endif - if (!(block_dst = get_target_block(func_ctx, br_depth))) { return false; } + if (comp_ctx->aot_frame) { + if (comp_ctx->enable_gc && !aot_gen_commit_values(comp_ctx->aot_frame)) + return false; + + if (block_dst->label_type == LABEL_TYPE_LOOP) { + if (comp_ctx->enable_thread_mgr) { + /* Commit sp when GC is enabled, don't commit ip */ + if (!aot_gen_commit_sp_ip(comp_ctx->aot_frame, + comp_ctx->enable_gc, false)) + return false; + } + } + else { + if (comp_ctx->aot_frame->sp > block_dst->frame_sp_max_reached) + block_dst->frame_sp_max_reached = comp_ctx->aot_frame->sp; + } + } + + /* Terminate or suspend current thread only when this is a backward jump */ + if (comp_ctx->enable_thread_mgr + && block_dst->label_type == LABEL_TYPE_LOOP) { + if (!check_suspend_flags(comp_ctx, func_ctx, true)) + return false; + } + if (block_dst->label_type == LABEL_TYPE_LOOP) { /* Dest block is Loop block */ /* Handle Loop parameters */ @@ -838,26 +991,47 @@ fail: return false; } -bool -aot_compile_op_br_if(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, - uint32 br_depth, uint8 **p_frame_ip) +static bool +aot_compile_conditional_br(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 br_depth, LLVMValueRef value_cmp, + uint8 **p_frame_ip) { AOTBlock *block_dst; - LLVMValueRef value_cmp, value, *values = NULL; + LLVMValueRef value, *values = NULL; LLVMBasicBlockRef llvm_else_block, next_llvm_end_block; char name[32]; uint32 i, param_index, result_index; uint64 size; -#if WASM_ENABLE_THREAD_MGR != 0 - /* Insert suspend check point */ - if (comp_ctx->enable_thread_mgr) { - if (!check_suspend_flags(comp_ctx, func_ctx)) + if (!(block_dst = get_target_block(func_ctx, br_depth))) { + return false; + } + + if (comp_ctx->aot_frame) { + if (comp_ctx->enable_gc && !aot_gen_commit_values(comp_ctx->aot_frame)) + return false; + + if (block_dst->label_type == LABEL_TYPE_LOOP) { + if (comp_ctx->enable_thread_mgr) { + /* Commit sp when GC is enabled, don't commit ip */ + if (!aot_gen_commit_sp_ip(comp_ctx->aot_frame, + comp_ctx->enable_gc, false)) + return false; + } + } + else { + if (comp_ctx->aot_frame->sp > block_dst->frame_sp_max_reached) + block_dst->frame_sp_max_reached = comp_ctx->aot_frame->sp; + } + } + + /* Terminate or suspend current thread only when this is + a backward jump */ + if (comp_ctx->enable_thread_mgr + && block_dst->label_type == LABEL_TYPE_LOOP) { + if (!check_suspend_flags(comp_ctx, func_ctx, true)) return false; } -#endif - - POP_COND(value_cmp); if (LLVMIsUndef(value_cmp) #if LLVM_VERSION_NUMBER >= 12 @@ -873,9 +1047,6 @@ aot_compile_op_br_if(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, if (!LLVMIsEfficientConstInt(value_cmp)) { /* Compare value is not constant, create condition br IR */ - if (!(block_dst = get_target_block(func_ctx, br_depth))) { - return false; - } /* Create llvm else block */ CREATE_BLOCK(llvm_else_block, "br_if_else"); @@ -972,6 +1143,20 @@ fail: return false; } +bool +aot_compile_op_br_if(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 br_depth, uint8 **p_frame_ip) +{ + LLVMValueRef value_cmp; + + POP_COND(value_cmp); + + return aot_compile_conditional_br(comp_ctx, func_ctx, br_depth, value_cmp, + p_frame_ip); +fail: + return false; +} + bool aot_compile_op_br_table(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, uint32 *br_depths, uint32 br_count, uint8 **p_frame_ip) @@ -986,14 +1171,6 @@ aot_compile_op_br_table(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, uint64 size; char name[32]; -#if WASM_ENABLE_THREAD_MGR != 0 - /* Insert suspend check point */ - if (comp_ctx->enable_thread_mgr) { - if (!check_suspend_flags(comp_ctx, func_ctx)) - return false; - } -#endif - POP_I32(value_cmp); if (LLVMIsUndef(value_cmp) @@ -1009,6 +1186,46 @@ aot_compile_op_br_table(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, } if (!LLVMIsEfficientConstInt(value_cmp)) { + if (comp_ctx->aot_frame) { + if (comp_ctx->enable_gc + && !aot_gen_commit_values(comp_ctx->aot_frame)) + return false; + + if (comp_ctx->enable_thread_mgr) { + /* Commit sp when GC is enabled, don't commit ip */ + if (!aot_gen_commit_sp_ip(comp_ctx->aot_frame, + comp_ctx->enable_gc, false)) + return false; + } + + for (i = 0; i <= br_count; i++) { + target_block = get_target_block(func_ctx, br_depths[i]); + if (!target_block) + return false; + if (target_block->label_type != LABEL_TYPE_LOOP) { + if (comp_ctx->aot_frame->sp + > target_block->frame_sp_max_reached) + target_block->frame_sp_max_reached = + comp_ctx->aot_frame->sp; + } + } + } + + if (comp_ctx->enable_thread_mgr) { + for (i = 0; i <= br_count; i++) { + target_block = get_target_block(func_ctx, br_depths[i]); + if (!target_block) + return false; + /* Terminate or suspend current thread only when this is a + backward jump */ + if (target_block->label_type == LABEL_TYPE_LOOP) { + if (!check_suspend_flags(comp_ctx, func_ctx, true)) + return false; + break; + } + } + } + /* Compare value is not constant, create switch IR */ for (i = 0; i <= br_count; i++) { target_block = get_target_block(func_ctx, br_depths[i]); @@ -1137,6 +1354,7 @@ aot_compile_op_return(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, comp_ctx, func_ctx, (*p_frame_ip - 1) - comp_ctx->comp_data->wasm_module->buf_code); #endif + if (block_func->result_count) { /* Store extra result values to function parameters */ for (i = 0; i < block_func->result_count - 1; i++) { @@ -1194,3 +1412,284 @@ aot_handle_next_reachable_block(AOTCompContext *comp_ctx, { return handle_next_reachable_block(comp_ctx, func_ctx, p_frame_ip); } + +#if WASM_ENABLE_GC != 0 +static bool +commit_gc_and_check_suspend_flags(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx, uint32 br_depth) +{ + AOTBlock *block_dst; + + if (!(block_dst = get_target_block(func_ctx, br_depth))) { + return false; + } + + if (comp_ctx->aot_frame) { + /* Note that GC is enabled, no need to check it again */ + if (!aot_gen_commit_values(comp_ctx->aot_frame)) + return false; + + if (block_dst->label_type == LABEL_TYPE_LOOP) { + if (comp_ctx->enable_thread_mgr) { + /* Note that GC is enabled, no need to check it again */ + if (!aot_gen_commit_sp_ip(comp_ctx->aot_frame, true, false)) + return false; + } + } + else { + if (comp_ctx->aot_frame->sp > block_dst->frame_sp_max_reached) + block_dst->frame_sp_max_reached = comp_ctx->aot_frame->sp; + } + } + + /* Terminate or suspend current thread only when this is + a backward jump */ + if (comp_ctx->enable_thread_mgr + && block_dst->label_type == LABEL_TYPE_LOOP) { + if (!check_suspend_flags(comp_ctx, func_ctx, true)) + return false; + } + + return true; +} + +static bool +compile_gc_cond_br(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 br_depth, LLVMValueRef value_cmp) +{ + AOTBlock *block_dst; + LLVMValueRef value, *values = NULL; + LLVMBasicBlockRef llvm_else_block, next_llvm_end_block; + char name[32]; + uint32 i, param_index, result_index; + uint64 size; + + if (!(block_dst = get_target_block(func_ctx, br_depth))) { + return false; + } + + /* Create llvm else block */ + CREATE_BLOCK(llvm_else_block, "br_if_else"); + MOVE_BLOCK_AFTER_CURR(llvm_else_block); + + if (block_dst->label_type == LABEL_TYPE_LOOP) { + /* Dest block is Loop block */ + /* Handle Loop parameters */ + if (block_dst->param_count) { + size = sizeof(LLVMValueRef) * (uint64)block_dst->param_count; + if (size >= UINT32_MAX + || !(values = wasm_runtime_malloc((uint32)size))) { + aot_set_last_error("allocate memory failed."); + goto fail; + } + for (i = 0; i < block_dst->param_count; i++) { + param_index = block_dst->param_count - 1 - i; + POP(value, block_dst->param_types[param_index]); + ADD_TO_PARAM_PHIS(block_dst, value, param_index); + values[param_index] = value; + } + for (i = 0; i < block_dst->param_count; i++) { + PUSH(values[i], block_dst->param_types[i]); + } + wasm_runtime_free(values); + values = NULL; + } + + BUILD_COND_BR(value_cmp, block_dst->llvm_entry_block, llvm_else_block); + + /* Move builder to else block */ + SET_BUILDER_POS(llvm_else_block); + } + else { + /* Dest block is Block/If/Function block */ + /* Create the end block */ + if (!block_dst->llvm_end_block) { + format_block_name(name, sizeof(name), block_dst->block_index, + block_dst->label_type, LABEL_END); + CREATE_BLOCK(block_dst->llvm_end_block, name); + if ((next_llvm_end_block = find_next_llvm_end_block(block_dst))) + MOVE_BLOCK_BEFORE(block_dst->llvm_end_block, + next_llvm_end_block); + } + + /* Set reachable flag and create condition br IR */ + block_dst->is_reachable = true; + + /* Handle result values */ + if (block_dst->result_count) { + size = sizeof(LLVMValueRef) * (uint64)block_dst->result_count; + if (size >= UINT32_MAX + || !(values = wasm_runtime_malloc((uint32)size))) { + aot_set_last_error("allocate memory failed."); + goto fail; + } + CREATE_RESULT_VALUE_PHIS(block_dst); + for (i = 0; i < block_dst->result_count; i++) { + result_index = block_dst->result_count - 1 - i; + POP(value, block_dst->result_types[result_index]); + values[result_index] = value; + ADD_TO_RESULT_PHIS(block_dst, value, result_index); + } + for (i = 0; i < block_dst->result_count; i++) { + PUSH(values[i], block_dst->result_types[i]); + } + wasm_runtime_free(values); + values = NULL; + } + + /* Condition jump to end block */ + BUILD_COND_BR(value_cmp, block_dst->llvm_end_block, llvm_else_block); + + /* Move builder to else block */ + SET_BUILDER_POS(llvm_else_block); + } + + return true; +fail: + if (values) + wasm_runtime_free(values); + return false; +} + +bool +aot_compile_op_br_on_null(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 br_depth, uint8 **p_frame_ip) +{ + LLVMValueRef gc_obj, value_cmp; + + if (!commit_gc_and_check_suspend_flags(comp_ctx, func_ctx, br_depth)) { + return false; + } + + POP_GC_REF(gc_obj); + + if (!(value_cmp = + LLVMBuildIsNull(comp_ctx->builder, gc_obj, "cmp_gc_obj"))) { + aot_set_last_error("llvm build isnull failed."); + goto fail; + } + + if (!compile_gc_cond_br(comp_ctx, func_ctx, br_depth, value_cmp)) { + goto fail; + } + + PUSH_GC_REF(gc_obj); + return true; +fail: + return false; +} + +bool +aot_compile_op_br_on_non_null(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx, uint32 br_depth, + uint8 **p_frame_ip) +{ + LLVMValueRef gc_obj, value_cmp; + + if (!commit_gc_and_check_suspend_flags(comp_ctx, func_ctx, br_depth)) { + return false; + } + + GET_GC_REF_FROM_STACK(gc_obj); + + if (!(value_cmp = + LLVMBuildIsNotNull(comp_ctx->builder, gc_obj, "cmp_gc_obj"))) { + aot_set_last_error("llvm build isnotnull failed."); + goto fail; + } + + if (!compile_gc_cond_br(comp_ctx, func_ctx, br_depth, value_cmp)) { + goto fail; + } + + POP_GC_REF(gc_obj); + return true; +fail: + return false; +} + +bool +aot_compile_op_br_on_cast(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + int32 heap_type, bool nullable, bool br_on_fail, + uint32 br_depth, uint8 **p_frame_ip) +{ + LLVMValueRef gc_obj, is_null, castable, not_castable, br_if_phi; + LLVMBasicBlockRef block_curr, block_non_null, block_br_if; + + if (!commit_gc_and_check_suspend_flags(comp_ctx, func_ctx, br_depth)) { + return false; + } + + GET_GC_REF_FROM_STACK(gc_obj); + + block_curr = CURR_BLOCK(); + + CREATE_BLOCK(block_non_null, "obj_non_null"); + MOVE_BLOCK_AFTER_CURR(block_non_null); + CREATE_BLOCK(block_br_if, "br_if"); + MOVE_BLOCK_AFTER(block_br_if, block_non_null); + + SET_BUILDER_POS(block_br_if); + if (!(br_if_phi = + LLVMBuildPhi(comp_ctx->builder, INT1_TYPE, "br_if_phi"))) { + aot_set_last_error("llvm build phi failed."); + goto fail; + } + + SET_BUILDER_POS(block_curr); + + if (!(is_null = LLVMBuildIsNull(comp_ctx->builder, gc_obj, "is_null"))) { + aot_set_last_error("llvm build isnull failed."); + goto fail; + } + + BUILD_COND_BR(is_null, block_br_if, block_non_null); + + if ((!br_on_fail && nullable) || (br_on_fail && !nullable)) { + LLVMAddIncoming(br_if_phi, &I1_ONE, &block_curr, 1); + } + else { /* (!br_on_fail && !nullable) || (br_on_fail && nullable)) */ + LLVMAddIncoming(br_if_phi, &I1_ZERO, &block_curr, 1); + } + + SET_BUILDER_POS(block_non_null); + if (heap_type >= 0) { + if (!aot_call_aot_obj_is_instance_of(comp_ctx, func_ctx, gc_obj, + I32_CONST(heap_type), &castable)) + goto fail; + } + else { + if (!aot_call_wasm_obj_is_type_of(comp_ctx, func_ctx, gc_obj, + I32_CONST(heap_type), &castable)) + goto fail; + } + + if (!br_on_fail) { + if (!(castable = LLVMBuildICmp(comp_ctx->builder, LLVMIntNE, castable, + I8_ZERO, "castable"))) { + aot_set_last_error("llvm build icmp failed."); + return false; + } + LLVMAddIncoming(br_if_phi, &castable, &block_non_null, 1); + } + else { + if (!(not_castable = LLVMBuildICmp(comp_ctx->builder, LLVMIntEQ, + castable, I8_ZERO, "castable"))) { + aot_set_last_error("llvm build icmp failed."); + return false; + } + LLVMAddIncoming(br_if_phi, ¬_castable, &block_non_null, 1); + } + BUILD_BR(block_br_if); + + SET_BUILDER_POS(block_br_if); + if (!compile_gc_cond_br(comp_ctx, func_ctx, br_depth, br_if_phi)) { + goto fail; + } + + return true; +fail: + return false; +} + +#endif /* End of WASM_ENABLE_GC != 0 */ diff --git a/core/iwasm/compilation/aot_emit_control.h b/core/iwasm/compilation/aot_emit_control.h index a203876c1..fd538495d 100644 --- a/core/iwasm/compilation/aot_emit_control.h +++ b/core/iwasm/compilation/aot_emit_control.h @@ -50,9 +50,25 @@ bool aot_handle_next_reachable_block(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, uint8 **p_frame_ip); -#if WASM_ENABLE_THREAD_MGR != 0 bool -check_suspend_flags(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx); +check_suspend_flags(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + bool check_terminate_and_suspend); + +#if WASM_ENABLE_GC != 0 +bool +aot_compile_op_br_on_null(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 br_depth, uint8 **p_frame_ip); + +bool +aot_compile_op_br_on_non_null(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx, uint32 br_depth, + + uint8 **p_frame_ip); + +bool +aot_compile_op_br_on_cast(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + int32 heap_type, bool nullable, bool br_on_fail, + uint32 br_depth, uint8 **p_frame_ip); #endif #ifdef __cplusplus diff --git a/core/iwasm/compilation/aot_emit_exception.c b/core/iwasm/compilation/aot_emit_exception.c index d40ccc6a4..1e4cccbe6 100644 --- a/core/iwasm/compilation/aot_emit_exception.c +++ b/core/iwasm/compilation/aot_emit_exception.c @@ -7,6 +7,46 @@ #include "../interpreter/wasm_runtime.h" #include "../aot/aot_runtime.h" +static bool +commit_ip(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + LLVMValueRef exce_ip, bool is_64bit) +{ + LLVMValueRef cur_frame = func_ctx->cur_frame; + LLVMValueRef value_offset, value_addr, value_ptr; + uint32 offset_ip; + + if (!comp_ctx->is_jit_mode) + offset_ip = comp_ctx->pointer_size * 4; + else + offset_ip = offsetof(WASMInterpFrame, ip); + + if (!(value_offset = I32_CONST(offset_ip))) { + aot_set_last_error("llvm build const failed"); + return false; + } + + if (!(value_addr = + LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, cur_frame, + &value_offset, 1, "ip_addr"))) { + aot_set_last_error("llvm build in bounds gep failed"); + return false; + } + + if (!(value_ptr = LLVMBuildBitCast( + comp_ctx->builder, value_addr, + is_64bit ? INT64_PTR_TYPE : INT32_PTR_TYPE, "ip_ptr"))) { + aot_set_last_error("llvm build bit cast failed"); + return false; + } + + if (!LLVMBuildStore(comp_ctx->builder, exce_ip, value_ptr)) { + aot_set_last_error("llvm build store failed"); + return false; + } + + return true; +} + bool aot_emit_exception(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, int32 exception_id, bool is_cond_br, LLVMValueRef cond_br_if, @@ -16,6 +56,7 @@ aot_emit_exception(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, LLVMValueRef exce_id = I32_CONST((uint32)exception_id), func_const, func; LLVMTypeRef param_types[2], ret_type, func_type, func_ptr_type; LLVMValueRef param_values[2]; + bool is_64bit = (comp_ctx->pointer_size == sizeof(uint64)) ? true : false; bh_assert(exception_id >= 0 && exception_id < EXCE_NUM); @@ -32,13 +73,23 @@ aot_emit_exception(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, LLVMPositionBuilderAtEnd(comp_ctx->builder, func_ctx->got_exception_block); - /* Create exection id phi */ + /* Create exception id phi */ if (!(func_ctx->exception_id_phi = LLVMBuildPhi( comp_ctx->builder, I32_TYPE, "exception_id_phi"))) { aot_set_last_error("llvm build phi failed."); return false; } + if (comp_ctx->aot_frame) { + /* Create exception ip phi */ + if (!(func_ctx->exception_ip_phi = LLVMBuildPhi( + comp_ctx->builder, is_64bit ? I64_TYPE : I32_TYPE, + "exception_ip_phi"))) { + aot_set_last_error("llvm build phi failed."); + return false; + } + } + /* Call aot_set_exception_with_id() to throw exception */ param_types[0] = INT8_PTR_TYPE; param_types[1] = I32_TYPE; @@ -103,6 +154,12 @@ aot_emit_exception(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, return false; } + if (comp_ctx->aot_frame) { + if (!commit_ip(comp_ctx, func_ctx, func_ctx->exception_ip_phi, + is_64bit)) + return false; + } + /* Create return IR */ AOTFuncType *aot_func_type = func_ctx->aot_func->func_type; if (!aot_build_zero_function_ret(comp_ctx, func_ctx, aot_func_type)) { @@ -116,6 +173,35 @@ aot_emit_exception(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, /* Add phi incoming value to got_exception block */ LLVMAddIncoming(func_ctx->exception_id_phi, &exce_id, &block_curr, 1); + if (comp_ctx->aot_frame) { + const uint8 *ip = comp_ctx->aot_frame->frame_ip; + LLVMValueRef exce_ip = NULL; + + if (!comp_ctx->is_jit_mode) { + WASMModule *module = comp_ctx->comp_data->wasm_module; + if (is_64bit) + exce_ip = + I64_CONST((uint64)(uintptr_t)(ip - module->load_addr)); + else + exce_ip = + I32_CONST((uint32)(uintptr_t)(ip - module->load_addr)); + } + else { + if (is_64bit) + exce_ip = I64_CONST((uint64)(uintptr_t)ip); + else + exce_ip = I32_CONST((uint32)(uintptr_t)ip); + } + + if (!exce_ip) { + aot_set_last_error("llvm build const failed"); + return false; + } + + /* Add phi incoming value to got_exception block */ + LLVMAddIncoming(func_ctx->exception_ip_phi, &exce_ip, &block_curr, 1); + } + if (!is_cond_br) { /* not condition br, create br IR */ if (!LLVMBuildBr(comp_ctx->builder, func_ctx->got_exception_block)) { diff --git a/core/iwasm/compilation/aot_emit_function.c b/core/iwasm/compilation/aot_emit_function.c index 4fb072401..36bbc2222 100644 --- a/core/iwasm/compilation/aot_emit_function.c +++ b/core/iwasm/compilation/aot_emit_function.c @@ -8,6 +8,9 @@ #include "aot_emit_control.h" #include "aot_emit_table.h" #include "../aot/aot_runtime.h" +#if WASM_ENABLE_GC != 0 +#include "aot_emit_gc.h" +#endif #define ADD_BASIC_BLOCK(block, name) \ do { \ @@ -86,7 +89,7 @@ check_exception_thrown(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) return false; } - /* Add check exection success block */ + /* Add check exception success block */ if (!(check_exce_succ = LLVMAppendBasicBlockInContext( comp_ctx->context, func_ctx->func, "check_exce_succ"))) { aot_set_last_error("llvm add basic block failed."); @@ -126,7 +129,7 @@ check_call_return(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, return false; } - /* Add check exection success block */ + /* Add check exception success block */ if (!(check_call_succ = LLVMAppendBasicBlockInContext( comp_ctx->context, func_ctx->func, "check_call_succ"))) { aot_set_last_error("llvm add basic block failed."); @@ -244,7 +247,8 @@ call_aot_invoke_native_func(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, } LLVMSetAlignment(res, 1); - cell_num += wasm_value_type_cell_num(aot_func_type->types[i]); + cell_num += wasm_value_type_cell_num_internal(aot_func_type->types[i], + comp_ctx->pointer_size); } func_param_values[0] = func_ctx->exec_env; @@ -495,7 +499,7 @@ fail: return false; } -#if (WASM_ENABLE_DUMP_CALL_STACK != 0) || (WASM_ENABLE_PERF_PROFILING != 0) +#if WASM_ENABLE_AOT_STACK_FRAME != 0 static bool call_aot_alloc_frame_func(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, LLVMValueRef func_idx) @@ -510,9 +514,11 @@ call_aot_alloc_frame_func(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, param_types[1] = I32_TYPE; ret_type = INT8_TYPE; +#if WASM_ENABLE_JIT != 0 if (comp_ctx->is_jit_mode) GET_AOT_FUNCTION(llvm_jit_alloc_frame, 2); else +#endif GET_AOT_FUNCTION(aot_alloc_frame, 2); param_values[0] = func_ctx->exec_env; @@ -559,33 +565,590 @@ fail: } static bool -call_aot_free_frame_func(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) +alloc_frame_for_aot_func(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 func_idx) { - LLVMValueRef param_values[1], ret_value, value, func; - LLVMTypeRef param_types[1], ret_type, func_type, func_ptr_type; + LLVMValueRef wasm_stack_top_bound = func_ctx->wasm_stack_top_bound; + LLVMValueRef wasm_stack_top_ptr = func_ctx->wasm_stack_top_ptr, + wasm_stack_top; + LLVMValueRef wasm_stack_top_max, offset, cmp; + LLVMValueRef cur_frame, new_frame, prev_frame_ptr; + LLVMValueRef cur_frame_ptr = func_ctx->cur_frame_ptr; + LLVMValueRef func_idx_ptr, func_idx_val, func_inst_ptr, func_inst; + LLVMTypeRef int8_ptr_type; + LLVMBasicBlockRef check_wasm_stack_succ; + uint32 import_func_count = comp_ctx->comp_data->import_func_count; + uint32 param_cell_num = 0, local_cell_num = 0, i; + uint32 max_local_cell_num, max_stack_cell_num; + uint32 all_cell_num, frame_size, frame_size_with_outs_area; + uint32 aot_frame_ptr_num = offsetof(AOTFrame, lp) / sizeof(uintptr_t); + AOTImportFunc *import_funcs = comp_ctx->comp_data->import_funcs; + AOTFuncType *aot_func_type; + AOTFunc *aot_func = NULL; - param_types[0] = comp_ctx->exec_env_type; - ret_type = INT8_TYPE; - - if (comp_ctx->is_jit_mode) - GET_AOT_FUNCTION(llvm_jit_free_frame, 1); - else - GET_AOT_FUNCTION(aot_free_frame, 1); - - param_values[0] = func_ctx->exec_env; - - if (!(ret_value = LLVMBuildCall2(comp_ctx->builder, func_type, func, - param_values, 1, "call_aot_free_frame"))) { - aot_set_last_error("llvm build call failed."); + /* `int8 **` type */ + int8_ptr_type = LLVMPointerType(INT8_PTR_TYPE, 0); + if (!int8_ptr_type) { + aot_set_last_error("create llvm pointer type failed"); return false; } + /* Get param_cell_num, local_cell_num and max_stack_cell_num */ + if (func_idx < import_func_count) { + aot_func_type = import_funcs[func_idx].func_type; + for (i = 0; i < aot_func_type->param_count; i++) + param_cell_num += wasm_value_type_cell_num_internal( + aot_func_type->types[i], comp_ctx->pointer_size); + max_local_cell_num = param_cell_num > 2 ? param_cell_num : 2; + max_stack_cell_num = 0; + } + else { + aot_func = comp_ctx->comp_data->funcs[func_idx - import_func_count]; + param_cell_num = aot_func->param_cell_num; + local_cell_num = aot_func->local_cell_num; + max_local_cell_num = param_cell_num + local_cell_num; + max_stack_cell_num = aot_func->max_stack_cell_num; + } + + all_cell_num = max_local_cell_num + max_stack_cell_num; + + /* Get size of the frame to allocate and get size with outs_area to + check whether wasm operand stack is overflow */ + if (!comp_ctx->is_jit_mode) { + /* Refer to aot_alloc_frame */ + if (!comp_ctx->enable_gc) { + frame_size = frame_size_with_outs_area = + comp_ctx->pointer_size * aot_frame_ptr_num; + } + else { + frame_size = comp_ctx->pointer_size * aot_frame_ptr_num + + align_uint(all_cell_num * 5, 4); + frame_size_with_outs_area = + frame_size + comp_ctx->pointer_size * aot_frame_ptr_num + + max_stack_cell_num * 4; + } + } + else { + /* Refer to wasm_interp_interp_frame_size */ + if (!comp_ctx->enable_gc) { + frame_size = frame_size_with_outs_area = + offsetof(WASMInterpFrame, lp); + } + else { + frame_size = + offsetof(WASMInterpFrame, lp) + align_uint(all_cell_num * 5, 4); + frame_size_with_outs_area = frame_size + + offsetof(WASMInterpFrame, lp) + + max_stack_cell_num * 4; + } + } + + cur_frame = func_ctx->cur_frame; + + if (!comp_ctx->enable_gc) { + offset = I32_CONST(frame_size); + CHECK_LLVM_CONST(offset); + if (!(wasm_stack_top = + LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, cur_frame, + &offset, 1, "wasm_stack_top"))) { + aot_set_last_error("llvm build in bounds gep failed"); + return false; + } + + offset = I32_CONST(frame_size * 2); + CHECK_LLVM_CONST(offset); + if (!(wasm_stack_top_max = + LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, cur_frame, + &offset, 1, "wasm_stack_top_max"))) { + aot_set_last_error("llvm build in bounds gep failed"); + return false; + } + } + else { + /* Get exec_env->wasm_stack.top */ + if (!(wasm_stack_top = + LLVMBuildLoad2(comp_ctx->builder, INT8_PTR_TYPE, + wasm_stack_top_ptr, "wasm_stack_top"))) { + aot_set_last_error("load wasm_stack.top failed"); + return false; + } + + /* Check whether wasm operand stack is overflow */ + offset = I32_CONST(frame_size_with_outs_area); + CHECK_LLVM_CONST(offset); + if (!(wasm_stack_top_max = LLVMBuildInBoundsGEP2( + comp_ctx->builder, INT8_TYPE, wasm_stack_top, &offset, 1, + "wasm_stack_top_max"))) { + aot_set_last_error("llvm build in bounds gep failed"); + return false; + } + } + + new_frame = wasm_stack_top; + + if (!(check_wasm_stack_succ = LLVMAppendBasicBlockInContext( + comp_ctx->context, func_ctx->func, "check_wasm_stack_succ"))) { + aot_set_last_error("llvm add basic block failed."); + return false; + } + + LLVMMoveBasicBlockAfter(check_wasm_stack_succ, + LLVMGetInsertBlock(comp_ctx->builder)); + + if (!(cmp = LLVMBuildICmp(comp_ctx->builder, LLVMIntUGT, wasm_stack_top_max, + wasm_stack_top_bound, "cmp"))) { + aot_set_last_error("llvm build icmp failed"); + return false; + } + + if (!(aot_emit_exception(comp_ctx, func_ctx, EXCE_OPERAND_STACK_OVERFLOW, + true, cmp, check_wasm_stack_succ))) { + return false; + } + +#if WASM_ENABLE_GC != 0 + if (comp_ctx->enable_gc) { + LLVMValueRef wasm_stack_top_new, frame_ref, frame_ref_ptr; + uint32 j, k; + + /* exec_env->wasm_stack.top += frame_size */ + offset = I32_CONST(frame_size); + CHECK_LLVM_CONST(offset); + if (!(wasm_stack_top_new = LLVMBuildInBoundsGEP2( + comp_ctx->builder, INT8_TYPE, wasm_stack_top, &offset, 1, + "wasm_stack_top_new"))) { + aot_set_last_error("llvm build in bounds gep failed"); + return false; + } + if (!LLVMBuildStore(comp_ctx->builder, wasm_stack_top_new, + wasm_stack_top_ptr)) { + aot_set_last_error("llvm build store failed"); + return false; + } + + if (func_idx < import_func_count) { + LLVMValueRef frame_sp, frame_sp_ptr; + + /* Only need to initialize new_frame->sp when it's import function + otherwise they will be committed in AOT code if needed */ + + /* new_frame->sp = new_frame->lp + max_local_cell_num */ + if (!comp_ctx->is_jit_mode) + offset = I32_CONST(comp_ctx->pointer_size * 5); + else + offset = I32_CONST(offsetof(WASMInterpFrame, sp)); + CHECK_LLVM_CONST(offset); + if (!(frame_sp_ptr = LLVMBuildInBoundsGEP2( + comp_ctx->builder, INT8_TYPE, new_frame, &offset, 1, + "frame_sp_addr")) + || !(frame_sp_ptr = + LLVMBuildBitCast(comp_ctx->builder, frame_sp_ptr, + int8_ptr_type, "frame_sp_ptr"))) { + aot_set_last_error("llvm get frame_sp_ptr failed"); + return false; + } + + if (!comp_ctx->is_jit_mode) + offset = I32_CONST(comp_ctx->pointer_size * aot_frame_ptr_num + + max_local_cell_num * sizeof(uint32)); + else + offset = I32_CONST(offsetof(WASMInterpFrame, lp) + + max_local_cell_num * sizeof(uint32)); + CHECK_LLVM_CONST(offset); + if (!(frame_sp = LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, + new_frame, &offset, 1, + "frame_sp"))) { + aot_set_last_error("llvm build in bounds gep failed"); + return false; + } + if (!LLVMBuildStore(comp_ctx->builder, frame_sp, frame_sp_ptr)) { + aot_set_last_error("llvm build store failed"); + return false; + } + } + + if (!comp_ctx->is_jit_mode) { + /* new_frame->frame_ref = new_frame->lp + max_local_cell_num + + max_stack_cell_num */ + offset = I32_CONST(comp_ctx->pointer_size * 6); + CHECK_LLVM_CONST(offset); + if (!(frame_ref_ptr = LLVMBuildInBoundsGEP2( + comp_ctx->builder, INT8_TYPE, new_frame, &offset, 1, + "frame_ref_addr")) + || !(frame_ref_ptr = + LLVMBuildBitCast(comp_ctx->builder, frame_ref_ptr, + int8_ptr_type, "frame_ref_ptr"))) { + aot_set_last_error("llvm get frame_ref_ptr failed"); + return false; + } + + offset = I32_CONST(comp_ctx->pointer_size * aot_frame_ptr_num + + (max_local_cell_num + max_stack_cell_num) + * sizeof(uint32)); + CHECK_LLVM_CONST(offset); + if (!(frame_ref = LLVMBuildInBoundsGEP2(comp_ctx->builder, + INT8_TYPE, new_frame, + &offset, 1, "frame_ref"))) { + aot_set_last_error("llvm build in bounds gep failed"); + return false; + } + if (!LLVMBuildStore(comp_ctx->builder, frame_ref, frame_ref_ptr)) { + aot_set_last_error("llvm build store failed"); + return false; + } + } + else { + /* Get frame_ref in WASMInterpFrame */ + offset = I32_CONST(offsetof(WASMInterpFrame, lp) + + (max_local_cell_num + max_stack_cell_num) + * sizeof(uint32)); + CHECK_LLVM_CONST(offset); + if (!(frame_ref = LLVMBuildInBoundsGEP2(comp_ctx->builder, + INT8_TYPE, new_frame, + &offset, 1, "frame_ref"))) { + aot_set_last_error("llvm build in bounds gep failed"); + return false; + } + } + + /* Initialize frame ref flags for import function only in JIT mode */ + if (func_idx < import_func_count && comp_ctx->is_jit_mode) { + aot_func_type = import_funcs[func_idx].func_type; + for (i = 0, j = 0; i < aot_func_type->param_count; i++) { + if (aot_is_type_gc_reftype(aot_func_type->types[i]) + && !wasm_is_reftype_i31ref(aot_func_type->types[i])) { + for (k = 0; k < comp_ctx->pointer_size / sizeof(uint32); + k++) { + /* frame_ref[j++] = 1 */ + offset = I32_CONST(j); + CHECK_LLVM_CONST(offset); + frame_ref_ptr = LLVMBuildInBoundsGEP2( + comp_ctx->builder, INT8_TYPE, frame_ref, &offset, 1, + "frame_ref_ptr"); + if (!LLVMBuildStore(comp_ctx->builder, I8_ONE, + frame_ref_ptr)) { + aot_set_last_error("llvm build store failed"); + return false; + } + j++; + } + } + else { + uint32 value_type_cell_num = + wasm_value_type_cell_num_internal( + aot_func_type->types[i], comp_ctx->pointer_size); + for (k = 0; k < value_type_cell_num; k++) { + /* frame_ref[j++] = 0 */ + offset = I32_CONST(j); + CHECK_LLVM_CONST(offset); + frame_ref_ptr = LLVMBuildInBoundsGEP2( + comp_ctx->builder, INT8_TYPE, frame_ref, &offset, 1, + "frame_ref_ptr"); + if (!LLVMBuildStore(comp_ctx->builder, I8_ZERO, + frame_ref_ptr)) { + aot_set_last_error("llvm build store failed"); + return false; + } + j++; + } + } + } + + for (; j < 2; j++) { + /* frame_ref[j++] = 0 */ + offset = I32_CONST(j); + CHECK_LLVM_CONST(offset); + frame_ref_ptr = LLVMBuildInBoundsGEP2( + comp_ctx->builder, INT8_TYPE, frame_ref, &offset, 1, + "frame_ref_ptr"); + if (!LLVMBuildStore(comp_ctx->builder, I8_ZERO, + frame_ref_ptr)) { + aot_set_last_error("llvm build store failed"); + return false; + } + } + } + } +#endif /* end of WASM_ENABLE_GC != 0 */ + + /* new_frame->prev_frame = cur_frame */ + if (!(prev_frame_ptr = LLVMBuildBitCast(comp_ctx->builder, new_frame, + int8_ptr_type, "prev_frame_ptr"))) { + aot_set_last_error("llvm build bitcast failed"); + return false; + } + if (!LLVMBuildStore(comp_ctx->builder, cur_frame, prev_frame_ptr)) { + aot_set_last_error("llvm build store failed"); + return false; + } + + if (!comp_ctx->is_jit_mode) { + /* aot mode: new_frame->func_idx = func_idx */ + func_idx_val = comp_ctx->pointer_size == sizeof(uint64) + ? I64_CONST(func_idx) + : I32_CONST(func_idx); + offset = I32_CONST(comp_ctx->pointer_size); + CHECK_LLVM_CONST(func_idx_val); + CHECK_LLVM_CONST(offset); + if (!(func_idx_ptr = + LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, new_frame, + &offset, 1, "func_idx_addr")) + || !(func_idx_ptr = + LLVMBuildBitCast(comp_ctx->builder, func_idx_ptr, + INTPTR_T_PTR_TYPE, "func_idx_ptr"))) { + aot_set_last_error("llvm get func_idx_ptr failed"); + return false; + } + if (!LLVMBuildStore(comp_ctx->builder, func_idx_val, func_idx_ptr)) { + aot_set_last_error("llvm build store failed"); + return false; + } + } + else { + /* jit mode: frame->function = module_inst->e->functions + func_index */ + LLVMValueRef functions; + uint32 offset_functions = + get_module_inst_extra_offset(comp_ctx) + + offsetof(WASMModuleInstanceExtra, functions); + + offset = I32_CONST(offset_functions); + CHECK_LLVM_CONST(offset); + if (!(functions = LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, + func_ctx->aot_inst, &offset, 1, + "functions_addr"))) { + aot_set_last_error("llvm build inbounds gep failed"); + return false; + } + + if (!(functions = LLVMBuildBitCast(comp_ctx->builder, functions, + int8_ptr_type, "functions_ptr"))) { + aot_set_last_error("llvm build bitcast failed"); + return false; + } + + if (!(functions = LLVMBuildLoad2(comp_ctx->builder, INT8_PTR_TYPE, + functions, "functions"))) { + aot_set_last_error("llvm build load failed"); + return false; + } + + offset = I32_CONST(sizeof(WASMFunctionInstance) * func_idx); + CHECK_LLVM_CONST(offset); + if (!(func_inst = + LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, functions, + &offset, 1, "func_inst"))) { + aot_set_last_error("llvm build inbounds gep failed"); + return false; + } + + offset = I32_CONST(offsetof(WASMInterpFrame, function)); + CHECK_LLVM_CONST(offset); + if (!(func_inst_ptr = + LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, new_frame, + &offset, 1, "func_inst_addr")) + || !(func_inst_ptr = + LLVMBuildBitCast(comp_ctx->builder, func_inst_ptr, + int8_ptr_type, "func_inst_ptr"))) { + aot_set_last_error("llvm get func_inst_ptr failed"); + return false; + } + + if (!LLVMBuildStore(comp_ctx->builder, func_inst, func_inst_ptr)) { + aot_set_last_error("llvm build store failed"); + return false; + } + } + + /* No need to initialize new_frame->sp and new_frame->ip_offset + since they will be committed in AOT/JIT code if needed */ + + /* exec_env->cur_frame = new_frame */ + if (!LLVMBuildStore(comp_ctx->builder, new_frame, cur_frame_ptr)) { + aot_set_last_error("llvm build store failed"); + return false; + } + + if (comp_ctx->enable_perf_profiling || comp_ctx->enable_memory_profiling) { + LLVMTypeRef param_types[2], func_type, func_ptr_type; + LLVMValueRef param_values[2], func = NULL, res; + char *func_name = "aot_frame_update_profile_info"; + + /* Call aot_frame_update_profile_info for AOT or + llvm_jit_frame_update_profile_info for JIT */ + + param_types[0] = comp_ctx->exec_env_type; + param_types[1] = INT8_TYPE; + + if (!(func_type = LLVMFunctionType(VOID_TYPE, param_types, 2, false))) { + aot_set_last_error("llvm add function type failed."); + return false; + } + + if (comp_ctx->is_jit_mode) { + if (!(func_ptr_type = LLVMPointerType(func_type, 0))) { + aot_set_last_error("create LLVM function type failed."); + return false; + } + +#if WASM_ENABLE_JIT != 0 \ + && (WASM_ENABLE_PERF_PROFILING != 0 || WASM_ENABLE_MEMORY_PROFILING != 0) + /* JIT mode, call the function directly */ + if (!(func = I64_CONST( + (uint64)(uintptr_t)llvm_jit_frame_update_profile_info)) + || !(func = LLVMConstIntToPtr(func, func_ptr_type))) { + aot_set_last_error("create LLVM value failed."); + return false; + } +#endif + } + else if (comp_ctx->is_indirect_mode) { + int32 func_index; + if (!(func_ptr_type = LLVMPointerType(func_type, 0))) { + aot_set_last_error("create LLVM function type failed."); + return false; + } + func_index = aot_get_native_symbol_index(comp_ctx, func_name); + if (func_index < 0) { + return false; + } + if (!(func = + aot_get_func_from_table(comp_ctx, func_ctx->native_symbol, + func_ptr_type, func_index))) { + return false; + } + } + else { + if (!(func = LLVMGetNamedFunction(func_ctx->module, func_name)) + && !(func = LLVMAddFunction(func_ctx->module, func_name, + func_type))) { + aot_set_last_error("add LLVM function failed."); + return false; + } + } + + param_values[0] = func_ctx->exec_env; + param_values[1] = I8_ONE; + + if (!(res = LLVMBuildCall2(comp_ctx->builder, func_type, func, + param_values, 2, ""))) { + aot_set_last_error("llvm build call failed."); + return false; + } + } + return true; fail: + return false; } -#endif /* end of (WASM_ENABLE_DUMP_CALL_STACK != 0) \ - || (WASM_ENABLE_PERF_PROFILING != 0) */ + +static bool +free_frame_for_aot_func(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) +{ + LLVMValueRef cur_frame_ptr = func_ctx->cur_frame_ptr, cur_frame; + LLVMValueRef wasm_stack_top_ptr = func_ctx->wasm_stack_top_ptr; + LLVMTypeRef int8_ptr_type; + + /* `int8 **` type */ + int8_ptr_type = LLVMPointerType(INT8_PTR_TYPE, 0); + if (!int8_ptr_type) { + aot_set_last_error("create llvm pointer type failed"); + return false; + } + + if (comp_ctx->enable_perf_profiling) { + LLVMTypeRef param_types[2], func_type, func_ptr_type; + LLVMValueRef param_values[2], func = NULL, res; + char *func_name = "aot_frame_update_profile_info"; + + /* call aot_frame_update_profile_info for AOT or + llvm_jit_frame_update_profile_info for JIT */ + + param_types[0] = comp_ctx->exec_env_type; + param_types[1] = INT8_TYPE; + + if (!(func_type = LLVMFunctionType(VOID_TYPE, param_types, 2, false))) { + aot_set_last_error("llvm add function type failed."); + return false; + } + + if (comp_ctx->is_jit_mode) { + if (!(func_ptr_type = LLVMPointerType(func_type, 0))) { + aot_set_last_error("create LLVM function type failed."); + return false; + } + +#if WASM_ENABLE_JIT != 0 \ + && (WASM_ENABLE_PERF_PROFILING != 0 || WASM_ENABLE_MEMORY_PROFILING != 0) + /* JIT mode, call the function directly */ + if (!(func = I64_CONST( + (uint64)(uintptr_t)llvm_jit_frame_update_profile_info)) + || !(func = LLVMConstIntToPtr(func, func_ptr_type))) { + aot_set_last_error("create LLVM value failed."); + return false; + } +#endif + } + else if (comp_ctx->is_indirect_mode) { + int32 func_index; + if (!(func_ptr_type = LLVMPointerType(func_type, 0))) { + aot_set_last_error("create LLVM function type failed."); + return false; + } + func_index = aot_get_native_symbol_index(comp_ctx, func_name); + if (func_index < 0) { + return false; + } + if (!(func = + aot_get_func_from_table(comp_ctx, func_ctx->native_symbol, + func_ptr_type, func_index))) { + return false; + } + } + else { + if (!(func = LLVMGetNamedFunction(func_ctx->module, func_name)) + && !(func = LLVMAddFunction(func_ctx->module, func_name, + func_type))) { + aot_set_last_error("add LLVM function failed."); + return false; + } + } + + param_values[0] = func_ctx->exec_env; + param_values[1] = I8_ZERO; + + if (!(res = LLVMBuildCall2(comp_ctx->builder, func_type, func, + param_values, 2, ""))) { + aot_set_last_error("llvm build call failed."); + return false; + } + } + + if (comp_ctx->enable_gc) { + /* cur_frame = exec_env->cur_frame */ + if (!(cur_frame = LLVMBuildLoad2(comp_ctx->builder, INT8_PTR_TYPE, + cur_frame_ptr, "cur_frame"))) { + aot_set_last_error("llvm build load failed"); + return false; + } + + /* exec_env->wasm_stack.top = cur_frame */ + if (!LLVMBuildStore(comp_ctx->builder, cur_frame, wasm_stack_top_ptr)) { + aot_set_last_error("llvm build store failed"); + return false; + } + } + + /* exec_env->cur_frame = prev_frame */ + if (!LLVMBuildStore(comp_ctx->builder, func_ctx->cur_frame, + cur_frame_ptr)) { + aot_set_last_error("llvm build store failed"); + return false; + } + + return true; +} +#endif /* end of WASM_ENABLE_AOT_STACK_FRAME != 0 */ /** * Check whether the app address and its buffer are inside the linear memory, @@ -718,6 +1281,108 @@ aot_estimate_and_record_stack_usage_for_function_call( } } +static bool +commit_params_to_frame_of_import_func(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx, + AOTFuncType *func_type, + const LLVMValueRef *param_values) +{ + uint32 i, n; + + for (i = 0, n = 0; i < func_type->param_count; i++, n++) { + switch (func_type->types[i]) { + case VALUE_TYPE_I32: + if (!aot_frame_store_value( + comp_ctx, param_values[i], VALUE_TYPE_I32, + func_ctx->cur_frame, + offset_of_local_in_outs_area(comp_ctx, n))) + return false; + break; + case VALUE_TYPE_I64: + if (!aot_frame_store_value( + comp_ctx, param_values[i], VALUE_TYPE_I64, + func_ctx->cur_frame, + offset_of_local_in_outs_area(comp_ctx, n))) + return false; + n++; + break; + case VALUE_TYPE_F32: + if (!aot_frame_store_value( + comp_ctx, param_values[i], VALUE_TYPE_F32, + func_ctx->cur_frame, + offset_of_local_in_outs_area(comp_ctx, n))) + return false; + break; + case VALUE_TYPE_F64: + if (!aot_frame_store_value( + comp_ctx, param_values[i], VALUE_TYPE_F64, + func_ctx->cur_frame, + offset_of_local_in_outs_area(comp_ctx, n))) + return false; + n++; + break; + case VALUE_TYPE_FUNCREF: + case VALUE_TYPE_EXTERNREF: + if (comp_ctx->enable_ref_types) { + if (!aot_frame_store_value( + comp_ctx, param_values[i], VALUE_TYPE_I32, + func_ctx->cur_frame, + offset_of_local_in_outs_area(comp_ctx, n))) + return false; + } +#if WASM_ENABLE_GC != 0 + else if (comp_ctx->enable_gc) { + if (!aot_frame_store_value( + comp_ctx, param_values[i], VALUE_TYPE_GC_REF, + func_ctx->cur_frame, + offset_of_local_in_outs_area(comp_ctx, n))) + return false; + if (comp_ctx->pointer_size == sizeof(uint64)) + n++; + } +#endif + else { + bh_assert(0); + } + break; +#if WASM_ENABLE_GC != 0 + case REF_TYPE_NULLFUNCREF: + case REF_TYPE_NULLEXTERNREF: + case REF_TYPE_NULLREF: + /* case REF_TYPE_FUNCREF: */ + /* case REF_TYPE_EXTERNREF: */ + case REF_TYPE_ANYREF: + case REF_TYPE_EQREF: + case REF_TYPE_HT_NULLABLE: + case REF_TYPE_HT_NON_NULLABLE: + case REF_TYPE_I31REF: + case REF_TYPE_STRUCTREF: + case REF_TYPE_ARRAYREF: + case VALUE_TYPE_GC_REF: +#if WASM_ENABLE_STRINGREF != 0 + case REF_TYPE_STRINGREF: + case REF_TYPE_STRINGVIEWWTF8: + case REF_TYPE_STRINGVIEWWTF16: + case REF_TYPE_STRINGVIEWITER: +#endif + if (!aot_frame_store_value( + comp_ctx, param_values[i], VALUE_TYPE_GC_REF, + func_ctx->cur_frame, + offset_of_local_in_outs_area(comp_ctx, n))) + return false; + if (comp_ctx->pointer_size == sizeof(uint64)) + n++; + break; +#endif + default: + bh_assert(0); + break; + } + } + + return true; +} + bool aot_compile_op_call(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, uint32 func_idx, bool tail_call) @@ -742,14 +1407,6 @@ aot_compile_op_call(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, char buf[32]; bool quick_invoke_c_api_import = false; -#if WASM_ENABLE_THREAD_MGR != 0 - /* Insert suspend check point */ - if (comp_ctx->enable_thread_mgr) { - if (!check_suspend_flags(comp_ctx, func_ctx)) - return false; - } -#endif - /* Check function index */ if (func_idx >= import_func_count + func_count) { aot_set_last_error("Function index out of range."); @@ -768,21 +1425,32 @@ aot_compile_op_call(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, aot_estimate_and_record_stack_usage_for_function_call(comp_ctx, func_ctx, func_type); - /* Get param cell number */ - param_cell_num = func_type->param_cell_num; - -#if (WASM_ENABLE_DUMP_CALL_STACK != 0) || (WASM_ENABLE_PERF_PROFILING != 0) - if (comp_ctx->enable_aux_stack_frame) { - LLVMValueRef func_idx_const; - - if (!(func_idx_const = I32_CONST(func_idx))) { - aot_set_last_error("llvm build const failed."); + /* Commit stack operands, sp and ip */ + if (comp_ctx->aot_frame) { + if (comp_ctx->enable_gc && !aot_gen_commit_values(comp_ctx->aot_frame)) return false; - } - if (!call_aot_alloc_frame_func(comp_ctx, func_ctx, func_idx_const)) + + /* Commit sp if gc is enabled and commit ip for func call */ + if (!aot_gen_commit_sp_ip(comp_ctx->aot_frame, comp_ctx->enable_gc, + true)) return false; } + + /* Insert suspend check point */ + if (comp_ctx->enable_thread_mgr) { + if (!check_suspend_flags(comp_ctx, func_ctx, true)) + return false; + } + + if (comp_ctx->enable_aux_stack_frame) { +#if WASM_ENABLE_AOT_STACK_FRAME != 0 + if (!alloc_frame_for_aot_func(comp_ctx, func_ctx, func_idx)) + return false; #endif + } + + /* Get param cell number */ + param_cell_num = func_type->param_cell_num; /* Allocate memory for parameters. * Parameters layout: @@ -843,11 +1511,18 @@ aot_compile_op_call(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, goto fail; } param_values[param_count + 1 + i] = ext_ret_ptr; - cell_num += wasm_value_type_cell_num(ext_ret_types[i]); + cell_num += wasm_value_type_cell_num_internal( + ext_ret_types[i], comp_ctx->pointer_size); } } if (func_idx < import_func_count) { + if (comp_ctx->enable_aux_stack_frame + && !commit_params_to_frame_of_import_func( + comp_ctx, func_ctx, func_type, param_values + 1)) { + goto fail; + } + if (!(import_func_idx = I32_CONST(func_idx))) { aot_set_last_error("llvm build inbounds gep failed."); goto fail; @@ -1088,10 +1763,6 @@ aot_compile_op_call(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, goto fail; } - /* Set calling convention for the call with the func's calling - convention */ - LLVMSetInstructionCallConv(value_ret, LLVMGetFunctionCallConv(func)); - if (tail_call) LLVMSetTailCall(value_ret, true); @@ -1119,20 +1790,18 @@ aot_compile_op_call(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, } } -#if (WASM_ENABLE_DUMP_CALL_STACK != 0) || (WASM_ENABLE_PERF_PROFILING != 0) if (comp_ctx->enable_aux_stack_frame) { - if (!call_aot_free_frame_func(comp_ctx, func_ctx)) +#if WASM_ENABLE_AOT_STACK_FRAME != 0 + if (!free_frame_for_aot_func(comp_ctx, func_ctx)) goto fail; - } #endif + } -#if WASM_ENABLE_THREAD_MGR != 0 /* Insert suspend check point */ if (comp_ctx->enable_thread_mgr) { - if (!check_suspend_flags(comp_ctx, func_ctx)) + if (!check_suspend_flags(comp_ctx, func_ctx, false)) goto fail; } -#endif ret = true; fail: @@ -1245,7 +1914,8 @@ call_aot_call_indirect_func(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, } LLVMSetAlignment(res, 1); - cell_num += wasm_value_type_cell_num(aot_func_type->types[i]); + cell_num += wasm_value_type_cell_num_internal(aot_func_type->types[i], + comp_ctx->pointer_size); } func_param_values[0] = func_ctx->exec_env; @@ -1292,7 +1962,8 @@ call_aot_call_indirect_func(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, aot_set_last_error("llvm build load failed."); return false; } - cell_num += wasm_value_type_cell_num(wasm_ret_types[i]); + cell_num += wasm_value_type_cell_num_internal(wasm_ret_types[i], + comp_ctx->pointer_size); } *p_res = res; @@ -1304,9 +1975,10 @@ aot_compile_op_call_indirect(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, uint32 type_idx, uint32 tbl_idx) { AOTFuncType *func_type; - LLVMValueRef tbl_idx_value, elem_idx, table_elem, func_idx; + LLVMValueRef tbl_idx_value, elem_idx, func_idx; + LLVMValueRef table_elem_base, table_elem_addr, table_elem; LLVMValueRef ftype_idx_ptr, ftype_idx, ftype_idx_const; - LLVMValueRef cmp_elem_idx, cmp_func_idx, cmp_ftype_idx; + LLVMValueRef cmp_func_obj, cmp_elem_idx, cmp_func_idx, cmp_ftype_idx; LLVMValueRef func, func_ptr, table_size_const; LLVMValueRef ext_ret_offset, ext_ret_ptr, ext_ret, res; LLVMValueRef *param_values = NULL, *value_rets = NULL; @@ -1314,7 +1986,8 @@ aot_compile_op_call_indirect(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, LLVMTypeRef *param_types = NULL, ret_type; LLVMTypeRef llvm_func_type, llvm_func_ptr_type; LLVMTypeRef ext_ret_ptr_type; - LLVMBasicBlockRef check_elem_idx_succ, check_ftype_idx_succ; + LLVMBasicBlockRef check_func_obj_succ, check_elem_idx_succ, + check_ftype_idx_succ; LLVMBasicBlockRef check_func_idx_succ, block_return, block_curr; LLVMBasicBlockRef block_call_import, block_call_non_import; LLVMValueRef offset; @@ -1326,7 +1999,7 @@ aot_compile_op_call_indirect(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, bool ret = false; /* Check function type index */ - if (type_idx >= comp_ctx->comp_data->func_type_count) { + if (type_idx >= comp_ctx->comp_data->type_count) { aot_set_last_error("function type index out of range"); return false; } @@ -1337,15 +2010,32 @@ aot_compile_op_call_indirect(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, are equal (the type index of call_indirect opcode and callee func), we don't need to check whether the whole function types are equal, including param types and result types. */ - type_idx = wasm_get_smallest_type_idx(comp_ctx->comp_data->func_types, - comp_ctx->comp_data->func_type_count, - type_idx); + type_idx = + wasm_get_smallest_type_idx((WASMTypePtr *)comp_ctx->comp_data->types, + comp_ctx->comp_data->type_count, type_idx); ftype_idx_const = I32_CONST(type_idx); CHECK_LLVM_CONST(ftype_idx_const); - func_type = comp_ctx->comp_data->func_types[type_idx]; + func_type = (AOTFuncType *)comp_ctx->comp_data->types[type_idx]; aot_estimate_and_record_stack_usage_for_function_call(comp_ctx, func_ctx, func_type); + /* Commit stack operands, sp and ip */ + if (comp_ctx->aot_frame) { + if (comp_ctx->enable_gc && !aot_gen_commit_values(comp_ctx->aot_frame)) + return false; + + /* Commit sp if gc is enabled and always commit ip for call_indirect */ + if (!aot_gen_commit_sp_ip(comp_ctx->aot_frame, comp_ctx->enable_gc, + true)) + return false; + } + + /* Insert suspend check point */ + if (comp_ctx->enable_thread_mgr) { + if (!check_suspend_flags(comp_ctx, func_ctx, true)) + return false; + } + func_param_count = func_type->param_count; func_result_count = func_type->result_count; @@ -1406,54 +2096,136 @@ aot_compile_op_call_indirect(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, goto fail; } - if (!(table_elem = LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, - func_ctx->aot_inst, &offset, 1, - "table_elem_i8p"))) { + if (!(table_elem_base = LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, + func_ctx->aot_inst, &offset, + 1, "table_elem_base_i8p"))) { aot_set_last_error("llvm build add failed."); goto fail; } - if (!(table_elem = LLVMBuildBitCast(comp_ctx->builder, table_elem, - INT32_PTR_TYPE, "table_elem_i32p"))) { - HANDLE_FAILURE("LLVMBuildBitCast"); - goto fail; - } - /* Load function index */ - if (!(table_elem = - LLVMBuildInBoundsGEP2(comp_ctx->builder, I32_TYPE, table_elem, - &elem_idx, 1, "table_elem"))) { - HANDLE_FAILURE("LLVMBuildNUWAdd"); - goto fail; + if (comp_ctx->enable_gc) { + /* table elem is func_obj when gc is enabled */ + if (!(table_elem_base = + LLVMBuildBitCast(comp_ctx->builder, table_elem_base, + GC_REF_PTR_TYPE, "table_elem_base"))) { + HANDLE_FAILURE("LLVMBuildBitCast"); + goto fail; + } + + if (!(table_elem_addr = LLVMBuildInBoundsGEP2( + comp_ctx->builder, GC_REF_TYPE, table_elem_base, &elem_idx, 1, + "table_elem_addr"))) { + HANDLE_FAILURE("LLVMBuildNUWAdd"); + goto fail; + } + + if (!(table_elem = LLVMBuildLoad2(comp_ctx->builder, GC_REF_TYPE, + table_elem_addr, "table_elem"))) { + aot_set_last_error("llvm build load failed."); + goto fail; + } + + /* Check if func object is NULL */ + if (!(cmp_func_obj = LLVMBuildIsNull(comp_ctx->builder, table_elem, + "cmp_func_obj"))) { + aot_set_last_error("llvm build isnull failed."); + goto fail; + } + + /* Throw exception if func object is NULL */ + if (!(check_func_obj_succ = LLVMAppendBasicBlockInContext( + comp_ctx->context, func_ctx->func, "check_func_obj_succ"))) { + aot_set_last_error("llvm add basic block failed."); + goto fail; + } + + LLVMMoveBasicBlockAfter(check_func_obj_succ, + LLVMGetInsertBlock(comp_ctx->builder)); + + if (!(aot_emit_exception(comp_ctx, func_ctx, EXCE_UNINITIALIZED_ELEMENT, + true, cmp_func_obj, check_func_obj_succ))) + goto fail; + + /* Get the func idx bound of the WASMFuncObject, the offset may be + * different in 32-bit runtime and 64-bit runtime since WASMObjectHeader + * is uintptr_t. Use comp_ctx->pointer_size as the + * offsetof(WASMFuncObject, func_idx_bound) + */ + if (!(offset = I32_CONST(comp_ctx->pointer_size))) { + HANDLE_FAILURE("LLVMConstInt"); + goto fail; + } + + if (!(func_idx = LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, + table_elem, &offset, 1, + "func_idx_bound_i8p"))) { + HANDLE_FAILURE("LLVMBuildGEP"); + goto fail; + } + + if (!(func_idx = + LLVMBuildBitCast(comp_ctx->builder, func_idx, INT32_PTR_TYPE, + "func_idx_bound_i32p"))) { + HANDLE_FAILURE("LLVMBuildBitCast"); + goto fail; + } + + if (!(func_idx = LLVMBuildLoad2(comp_ctx->builder, I32_TYPE, func_idx, + "func_idx_bound"))) { + HANDLE_FAILURE("LLVMBuildLoad"); + goto fail; + } } + else { + if (!(table_elem_base = + LLVMBuildBitCast(comp_ctx->builder, table_elem_base, + INTPTR_T_PTR_TYPE, "table_elem_base"))) { + HANDLE_FAILURE("LLVMBuildBitCast"); + goto fail; + } - if (!(func_idx = LLVMBuildLoad2(comp_ctx->builder, I32_TYPE, table_elem, - "func_idx"))) { - aot_set_last_error("llvm build load failed."); - goto fail; + if (!(table_elem_addr = LLVMBuildInBoundsGEP2( + comp_ctx->builder, INTPTR_T_TYPE, table_elem_base, &elem_idx, + 1, "table_elem_addr"))) { + HANDLE_FAILURE("LLVMBuildNUWAdd"); + goto fail; + } + + if (!(func_idx = LLVMBuildLoad2(comp_ctx->builder, INTPTR_T_TYPE, + table_elem_addr, "func_idx"))) { + aot_set_last_error("llvm build load failed."); + goto fail; + } + + if (!(func_idx = LLVMBuildIntCast2(comp_ctx->builder, func_idx, + I32_TYPE, true, "func_idx_i32"))) { + aot_set_last_error("llvm build int cast failed."); + goto fail; + } + + /* Check if func_idx == -1 */ + if (!(cmp_func_idx = + LLVMBuildICmp(comp_ctx->builder, LLVMIntEQ, func_idx, + I32_NEG_ONE, "cmp_func_idx"))) { + aot_set_last_error("llvm build icmp failed."); + goto fail; + } + + /* Throw exception if func_idx == -1 */ + if (!(check_func_idx_succ = LLVMAppendBasicBlockInContext( + comp_ctx->context, func_ctx->func, "check_func_idx_succ"))) { + aot_set_last_error("llvm add basic block failed."); + goto fail; + } + + LLVMMoveBasicBlockAfter(check_func_idx_succ, + LLVMGetInsertBlock(comp_ctx->builder)); + + if (!(aot_emit_exception(comp_ctx, func_ctx, EXCE_UNINITIALIZED_ELEMENT, + true, cmp_func_idx, check_func_idx_succ))) + goto fail; } - - /* Check if func_idx == -1 */ - if (!(cmp_func_idx = LLVMBuildICmp(comp_ctx->builder, LLVMIntEQ, func_idx, - I32_NEG_ONE, "cmp_func_idx"))) { - aot_set_last_error("llvm build icmp failed."); - goto fail; - } - - /* Throw exception if func_idx == -1 */ - if (!(check_func_idx_succ = LLVMAppendBasicBlockInContext( - comp_ctx->context, func_ctx->func, "check_func_idx_succ"))) { - aot_set_last_error("llvm add basic block failed."); - goto fail; - } - - LLVMMoveBasicBlockAfter(check_func_idx_succ, - LLVMGetInsertBlock(comp_ctx->builder)); - - if (!(aot_emit_exception(comp_ctx, func_ctx, EXCE_UNINITIALIZED_ELEMENT, - true, cmp_func_idx, check_func_idx_succ))) - goto fail; - /* Load function type index */ if (!(ftype_idx_ptr = LLVMBuildInBoundsGEP2( comp_ctx->builder, I32_TYPE, func_ctx->func_type_indexes, @@ -1568,8 +2340,8 @@ aot_compile_op_call_indirect(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, } param_values[func_param_count + i] = ext_ret_ptr; - ext_cell_num += - wasm_value_type_cell_num(func_type->types[func_param_count + i]); + ext_cell_num += wasm_value_type_cell_num_internal( + func_type->types[func_param_count + i], comp_ctx->pointer_size); } if (ext_cell_num > 64) { @@ -1578,20 +2350,14 @@ aot_compile_op_call_indirect(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, goto fail; } -#if WASM_ENABLE_THREAD_MGR != 0 - /* Insert suspend check point */ - if (comp_ctx->enable_thread_mgr) { - if (!check_suspend_flags(comp_ctx, func_ctx)) - goto fail; - } -#endif - -#if (WASM_ENABLE_DUMP_CALL_STACK != 0) || (WASM_ENABLE_PERF_PROFILING != 0) if (comp_ctx->enable_aux_stack_frame) { +#if WASM_ENABLE_AOT_STACK_FRAME != 0 + /* TODO: use current frame instead of allocating new frame + for WASM_OP_RETURN_CALL_INDIRECT */ if (!call_aot_alloc_frame_func(comp_ctx, func_ctx, func_idx)) goto fail; - } #endif + } /* Add basic blocks */ block_call_import = LLVMAppendBasicBlockInContext( @@ -1653,6 +2419,12 @@ aot_compile_op_call_indirect(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, /* Translate call import block */ LLVMPositionBuilderAtEnd(comp_ctx->builder, block_call_import); + if (comp_ctx->enable_aux_stack_frame + && !commit_params_to_frame_of_import_func(comp_ctx, func_ctx, func_type, + param_values + 1)) { + goto fail; + } + /* Allocate memory for result values */ if (func_result_count > 0) { total_size = sizeof(LLVMValueRef) * (uint64)func_result_count; @@ -1768,20 +2540,18 @@ aot_compile_op_call_indirect(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, PUSH(result_phis[i], func_type->types[func_param_count + i]); } -#if (WASM_ENABLE_DUMP_CALL_STACK != 0) || (WASM_ENABLE_PERF_PROFILING != 0) if (comp_ctx->enable_aux_stack_frame) { - if (!call_aot_free_frame_func(comp_ctx, func_ctx)) +#if WASM_ENABLE_AOT_STACK_FRAME != 0 + if (!free_frame_for_aot_func(comp_ctx, func_ctx)) goto fail; - } #endif + } -#if WASM_ENABLE_THREAD_MGR != 0 /* Insert suspend check point */ if (comp_ctx->enable_thread_mgr) { - if (!check_suspend_flags(comp_ctx, func_ctx)) + if (!check_suspend_flags(comp_ctx, func_ctx, false)) goto fail; } -#endif ret = true; @@ -1800,7 +2570,10 @@ fail: bool aot_compile_op_ref_null(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) { - PUSH_I32(REF_NULL); + if (comp_ctx->enable_gc) + PUSH_GC_REF(GC_REF_NULL); + else + PUSH_I32(REF_NULL); return true; fail: @@ -1810,14 +2583,24 @@ fail: bool aot_compile_op_ref_is_null(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) { - LLVMValueRef lhs, res; + LLVMValueRef lhs = NULL, res; - POP_I32(lhs); + if (comp_ctx->enable_gc) { + POP_GC_REF(lhs); - if (!(res = LLVMBuildICmp(comp_ctx->builder, LLVMIntEQ, lhs, REF_NULL, - "cmp_w_null"))) { - HANDLE_FAILURE("LLVMBuildICmp"); - goto fail; + if (!(res = LLVMBuildIsNull(comp_ctx->builder, lhs, "lhs is null"))) { + HANDLE_FAILURE("LLVMBuildIsNull"); + goto fail; + } + } + else { + POP_I32(lhs); + + if (!(res = LLVMBuildICmp(comp_ctx->builder, LLVMIntEQ, lhs, REF_NULL, + "cmp_w_null"))) { + HANDLE_FAILURE("LLVMBuildICmp"); + goto fail; + } } if (!(res = LLVMBuildZExt(comp_ctx->builder, res, I32_TYPE, "r_i"))) { @@ -1837,15 +2620,453 @@ aot_compile_op_ref_func(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, uint32 func_idx) { LLVMValueRef ref_idx; +#if WASM_ENABLE_GC != 0 + LLVMValueRef gc_obj; +#endif if (!(ref_idx = I32_CONST(func_idx))) { HANDLE_FAILURE("LLVMConstInt"); goto fail; } - PUSH_I32(ref_idx); +#if WASM_ENABLE_GC != 0 + if (comp_ctx->enable_gc) { + if (!aot_gen_commit_values(comp_ctx->aot_frame)) + return false; + + /* Commit sp and ip if gc is enabled */ + if (!aot_gen_commit_sp_ip(comp_ctx->aot_frame, true, true)) + return false; + + if (!aot_call_aot_create_func_obj(comp_ctx, func_ctx, ref_idx, + &gc_obj)) { + goto fail; + } + + PUSH_GC_REF(gc_obj); + } + else +#endif + { + PUSH_I32(ref_idx); + } return true; fail: return false; } + +#if WASM_ENABLE_GC != 0 +bool +aot_compile_op_call_ref(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 type_idx, bool tail_call) +{ + AOTFuncType *func_type; + LLVMValueRef func_obj, func_idx; + LLVMValueRef cmp_func_obj, cmp_func_idx; + LLVMValueRef func, func_ptr; + LLVMValueRef ext_ret_offset, ext_ret_ptr, ext_ret, res; + LLVMValueRef *param_values = NULL; + LLVMValueRef *result_phis = NULL, value_ret, import_func_count; + LLVMTypeRef *param_types = NULL, ret_type; + LLVMTypeRef llvm_func_type, llvm_func_ptr_type; + LLVMTypeRef ext_ret_ptr_type; + LLVMBasicBlockRef check_func_obj_succ, block_return, block_curr; + LLVMBasicBlockRef block_call_import, block_call_non_import; + LLVMValueRef offset; + uint32 total_param_count, func_param_count, func_result_count; + uint32 ext_cell_num, param_cell_num, i, j; + uint8 wasm_ret_type; + uint64 total_size; + char buf[32]; + bool ret = false; + + /* Check function type index */ + bh_assert(type_idx < comp_ctx->comp_data->type_count); + + func_type = (AOTFuncType *)comp_ctx->comp_data->types[type_idx]; + aot_estimate_and_record_stack_usage_for_function_call(comp_ctx, func_ctx, + func_type); + func_param_count = func_type->param_count; + func_result_count = func_type->result_count; + param_cell_num = func_type->param_cell_num; + + /* Commit stack operands, sp and ip to aot frame */ + if (comp_ctx->aot_frame) { + /* Note that GC is enabled, no need to check it again */ + if (!aot_gen_commit_values(comp_ctx->aot_frame)) + return false; + + /* Commit sp if gc is enabled and always commit ip for call_ref */ + if (!aot_gen_commit_sp_ip(comp_ctx->aot_frame, true, true)) + return false; + } + + /* Insert suspend check point */ + if (comp_ctx->enable_thread_mgr) { + if (!check_suspend_flags(comp_ctx, func_ctx, true)) + return false; + } + + POP_GC_REF(func_obj); + + /* Check if func object is NULL */ + if (!(cmp_func_obj = + LLVMBuildIsNull(comp_ctx->builder, func_obj, "cmp_func_obj"))) { + aot_set_last_error("llvm build isnull failed."); + goto fail; + } + + /* Throw exception if func object is NULL */ + if (!(check_func_obj_succ = LLVMAppendBasicBlockInContext( + comp_ctx->context, func_ctx->func, "check_func_obj_succ"))) { + aot_set_last_error("llvm add basic block failed."); + goto fail; + } + + LLVMMoveBasicBlockAfter(check_func_obj_succ, + LLVMGetInsertBlock(comp_ctx->builder)); + + if (!(aot_emit_exception(comp_ctx, func_ctx, EXCE_NULL_FUNC_OBJ, true, + cmp_func_obj, check_func_obj_succ))) + goto fail; + + /* Get the func idx bound of the WASMFuncObject, the offset may be + * different in 32-bit runtime and 64-bit runtime since WASMObjectHeader + * is uintptr_t. Use comp_ctx->pointer_size as the + * offsetof(WASMFuncObject, func_idx_bound) */ + if (!(offset = I32_CONST(comp_ctx->pointer_size))) { + HANDLE_FAILURE("LLVMConstInt"); + goto fail; + } + + if (!(func_idx = + LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, func_obj, + &offset, 1, "func_idx_bound_i8p"))) { + HANDLE_FAILURE("LLVMBuildGEP"); + goto fail; + } + + if (!(func_idx = LLVMBuildBitCast(comp_ctx->builder, func_idx, + INT32_PTR_TYPE, "func_idx_bound_i32p"))) { + HANDLE_FAILURE("LLVMBuildBitCast"); + goto fail; + } + + if (!(func_idx = LLVMBuildLoad2(comp_ctx->builder, I32_TYPE, func_idx, + "func_idx_bound"))) { + HANDLE_FAILURE("LLVMBuildLoad"); + goto fail; + } + + /* Initialize parameter types of the LLVM function */ + total_param_count = 1 + func_param_count; + + /* Extra function results' addresses (except the first one) are + appended to aot function parameters. */ + if (func_result_count > 1) + total_param_count += func_result_count - 1; + + total_size = sizeof(LLVMTypeRef) * (uint64)total_param_count; + if (total_size >= UINT32_MAX + || !(param_types = wasm_runtime_malloc((uint32)total_size))) { + aot_set_last_error("allocate memory failed."); + goto fail; + } + + /* Prepare param types */ + j = 0; + param_types[j++] = comp_ctx->exec_env_type; + for (i = 0; i < func_param_count; i++) + param_types[j++] = TO_LLVM_TYPE(func_type->types[i]); + + for (i = 1; i < func_result_count; i++, j++) { + param_types[j] = TO_LLVM_TYPE(func_type->types[func_param_count + i]); + if (!(param_types[j] = LLVMPointerType(param_types[j], 0))) { + aot_set_last_error("llvm get pointer type failed."); + goto fail; + } + } + + /* Resolve return type of the LLVM function */ + if (func_result_count) { + wasm_ret_type = func_type->types[func_param_count]; + ret_type = TO_LLVM_TYPE(wasm_ret_type); + } + else { + wasm_ret_type = VALUE_TYPE_VOID; + ret_type = VOID_TYPE; + } + + /* Allocate memory for parameters */ + total_size = sizeof(LLVMValueRef) * (uint64)total_param_count; + if (total_size >= UINT32_MAX + || !(param_values = wasm_runtime_malloc((uint32)total_size))) { + aot_set_last_error("allocate memory failed."); + goto fail; + } + + /* First parameter is exec env */ + j = 0; + param_values[j++] = func_ctx->exec_env; + + /* Pop parameters from stack */ + for (i = func_param_count - 1; (int32)i >= 0; i--) + POP(param_values[i + j], func_type->types[i]); + + /* Prepare extra parameters */ + ext_cell_num = 0; + for (i = 1; i < func_result_count; i++) { + ext_ret_offset = I32_CONST(ext_cell_num); + CHECK_LLVM_CONST(ext_ret_offset); + + snprintf(buf, sizeof(buf), "ext_ret%d_ptr", i - 1); + if (!(ext_ret_ptr = LLVMBuildInBoundsGEP2(comp_ctx->builder, I32_TYPE, + func_ctx->argv_buf, + &ext_ret_offset, 1, buf))) { + aot_set_last_error("llvm build GEP failed."); + goto fail; + } + + ext_ret_ptr_type = param_types[func_param_count + i]; + snprintf(buf, sizeof(buf), "ext_ret%d_ptr_cast", i - 1); + if (!(ext_ret_ptr = LLVMBuildBitCast(comp_ctx->builder, ext_ret_ptr, + ext_ret_ptr_type, buf))) { + aot_set_last_error("llvm build bit cast failed."); + goto fail; + } + + param_values[func_param_count + i] = ext_ret_ptr; + ext_cell_num += wasm_value_type_cell_num_internal( + func_type->types[func_param_count + i], comp_ctx->pointer_size); + } + + if (ext_cell_num > 64) { + aot_set_last_error("prepare call-indirect arguments failed: " + "maximum 64 extra cell number supported."); + goto fail; + } + + if (comp_ctx->enable_aux_stack_frame) { +#if WASM_ENABLE_AOT_STACK_FRAME != 0 + /* TODO: use current frame instead of allocating new frame + for WASM_OP_RETURN_CALL_REF */ + if (!call_aot_alloc_frame_func(comp_ctx, func_ctx, func_idx)) + goto fail; +#endif + } + + /* Add basic blocks */ + block_call_import = LLVMAppendBasicBlockInContext( + comp_ctx->context, func_ctx->func, "call_import"); + block_call_non_import = LLVMAppendBasicBlockInContext( + comp_ctx->context, func_ctx->func, "call_non_import"); + block_return = LLVMAppendBasicBlockInContext(comp_ctx->context, + func_ctx->func, "func_return"); + if (!block_call_import || !block_call_non_import || !block_return) { + aot_set_last_error("llvm add basic block failed."); + goto fail; + } + + LLVMMoveBasicBlockAfter(block_call_import, + LLVMGetInsertBlock(comp_ctx->builder)); + LLVMMoveBasicBlockAfter(block_call_non_import, block_call_import); + LLVMMoveBasicBlockAfter(block_return, block_call_non_import); + + import_func_count = I32_CONST(comp_ctx->comp_data->import_func_count); + CHECK_LLVM_CONST(import_func_count); + + /* Check if func_idx < import_func_count */ + if (!(cmp_func_idx = LLVMBuildICmp(comp_ctx->builder, LLVMIntULT, func_idx, + import_func_count, "cmp_func_idx"))) { + aot_set_last_error("llvm build icmp failed."); + goto fail; + } + + /* If func_idx < import_func_count, jump to call import block, + else jump to call non-import block */ + if (!LLVMBuildCondBr(comp_ctx->builder, cmp_func_idx, block_call_import, + block_call_non_import)) { + aot_set_last_error("llvm build cond br failed."); + goto fail; + } + + /* Add result phis for return block */ + LLVMPositionBuilderAtEnd(comp_ctx->builder, block_return); + + if (func_result_count > 0) { + total_size = sizeof(LLVMValueRef) * (uint64)func_result_count; + if (total_size >= UINT32_MAX + || !(result_phis = wasm_runtime_malloc((uint32)total_size))) { + aot_set_last_error("allocate memory failed."); + goto fail; + } + memset(result_phis, 0, (uint32)total_size); + for (i = 0; i < func_result_count; i++) { + LLVMTypeRef tmp_type = + TO_LLVM_TYPE(func_type->types[func_param_count + i]); + if (!(result_phis[i] = + LLVMBuildPhi(comp_ctx->builder, tmp_type, "phi"))) { + aot_set_last_error("llvm build phi failed."); + goto fail; + } + } + } + + /* Translate call import block */ + LLVMPositionBuilderAtEnd(comp_ctx->builder, block_call_import); + + if (comp_ctx->enable_aux_stack_frame + && !commit_params_to_frame_of_import_func(comp_ctx, func_ctx, func_type, + param_values + 1)) { + goto fail; + } + + /* Similar to opcode call_indirect, but for opcode ref.func needs to call + * aot_invoke_native_func instead */ + if (!call_aot_invoke_native_func(comp_ctx, func_ctx, func_idx, func_type, + param_types + 1, param_values + 1, + func_param_count, param_cell_num, ret_type, + wasm_ret_type, &value_ret, &res)) + goto fail; + + /* Check whether exception was thrown when executing the function */ + if (comp_ctx->enable_bound_check + && !check_call_return(comp_ctx, func_ctx, res)) + goto fail; + + block_curr = LLVMGetInsertBlock(comp_ctx->builder); + + /* Get function return values, for aot_invoke_native_func, the extra ret + * values are put into param's array */ + if (func_result_count > 0) { + /* Push the first result to stack */ + LLVMAddIncoming(result_phis[0], &value_ret, &block_curr, 1); + + /* Load extra result from its address and push to stack */ + for (i = 1; i < func_result_count; i++) { + ret_type = TO_LLVM_TYPE(func_type->types[func_param_count + i]); + snprintf(buf, sizeof(buf), "ext_ret%d", i - 1); + if (!(ext_ret = LLVMBuildLoad2(comp_ctx->builder, ret_type, + param_values[func_param_count + i], + buf))) { + aot_set_last_error("llvm build load failed."); + goto fail; + } + LLVMAddIncoming(result_phis[i], &ext_ret, &block_curr, 1); + } + } + + if (!LLVMBuildBr(comp_ctx->builder, block_return)) { + aot_set_last_error("llvm build br failed."); + goto fail; + } + + /* Translate call non-import block */ + LLVMPositionBuilderAtEnd(comp_ctx->builder, block_call_non_import); + + /* Load function pointer */ + if (!(func_ptr = LLVMBuildInBoundsGEP2(comp_ctx->builder, OPQ_PTR_TYPE, + func_ctx->func_ptrs, &func_idx, 1, + "func_ptr_tmp"))) { + aot_set_last_error("llvm build inbounds gep failed."); + goto fail; + } + + if (!(func_ptr = LLVMBuildLoad2(comp_ctx->builder, OPQ_PTR_TYPE, func_ptr, + "func_ptr"))) { + aot_set_last_error("llvm build load failed."); + goto fail; + } + + if (!(llvm_func_type = + LLVMFunctionType(ret_type, param_types, total_param_count, false)) + || !(llvm_func_ptr_type = LLVMPointerType(llvm_func_type, 0))) { + aot_set_last_error("llvm add function type failed."); + goto fail; + } + + if (!(func = LLVMBuildBitCast(comp_ctx->builder, func_ptr, + llvm_func_ptr_type, "indirect_func"))) { + aot_set_last_error("llvm build bit cast failed."); + goto fail; + } + + if (!(value_ret = LLVMBuildCall2(comp_ctx->builder, llvm_func_type, func, + param_values, total_param_count, + func_result_count > 0 ? "ret" : ""))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + + /* Set calling convention for the call with the func's calling + convention */ + LLVMSetInstructionCallConv(value_ret, LLVMGetFunctionCallConv(func)); + + if (tail_call) + LLVMSetTailCall(value_ret, true); + + /* Check whether exception was thrown when executing the function */ + if (!tail_call + && (comp_ctx->enable_bound_check || is_win_platform(comp_ctx)) + && !check_exception_thrown(comp_ctx, func_ctx)) + goto fail; + + if (func_result_count > 0) { + block_curr = LLVMGetInsertBlock(comp_ctx->builder); + + /* Push the first result to stack */ + LLVMAddIncoming(result_phis[0], &value_ret, &block_curr, 1); + + /* Load extra result from its address and push to stack */ + for (i = 1; i < func_result_count; i++) { + ret_type = TO_LLVM_TYPE(func_type->types[func_param_count + i]); + snprintf(buf, sizeof(buf), "ext_ret%d", i - 1); + if (!(ext_ret = LLVMBuildLoad2(comp_ctx->builder, ret_type, + param_values[func_param_count + i], + buf))) { + aot_set_last_error("llvm build load failed."); + goto fail; + } + LLVMAddIncoming(result_phis[i], &ext_ret, &block_curr, 1); + } + } + + if (!LLVMBuildBr(comp_ctx->builder, block_return)) { + aot_set_last_error("llvm build br failed."); + goto fail; + } + + /* Translate function return block */ + LLVMPositionBuilderAtEnd(comp_ctx->builder, block_return); + + for (i = 0; i < func_result_count; i++) { + PUSH(result_phis[i], func_type->types[func_param_count + i]); + } + + if (comp_ctx->enable_aux_stack_frame) { +#if WASM_ENABLE_AOT_STACK_FRAME != 0 + if (!free_frame_for_aot_func(comp_ctx, func_ctx)) + goto fail; +#endif + } + + /* Insert suspend check point */ + if (comp_ctx->enable_thread_mgr) { + if (!check_suspend_flags(comp_ctx, func_ctx, false)) + goto fail; + } + + ret = true; + +fail: + if (param_values) + wasm_runtime_free(param_values); + if (param_types) + wasm_runtime_free(param_types); + if (result_phis) + wasm_runtime_free(result_phis); + return ret; +} + +#endif /* end of WASM_ENABLE_GC != 0 */ diff --git a/core/iwasm/compilation/aot_emit_function.h b/core/iwasm/compilation/aot_emit_function.h index 798243e60..45f7bbe59 100644 --- a/core/iwasm/compilation/aot_emit_function.h +++ b/core/iwasm/compilation/aot_emit_function.h @@ -30,6 +30,12 @@ bool aot_compile_op_ref_func(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, uint32 func_idx); +#if WASM_ENABLE_GC != 0 +bool +aot_compile_op_call_ref(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 type_idx, bool tail_call); +#endif + #ifdef __cplusplus } /* end of extern "C" */ #endif diff --git a/core/iwasm/compilation/aot_emit_gc.c b/core/iwasm/compilation/aot_emit_gc.c new file mode 100644 index 000000000..55f14710f --- /dev/null +++ b/core/iwasm/compilation/aot_emit_gc.c @@ -0,0 +1,2144 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include "aot_emit_gc.h" +#include "aot_compiler.h" +#include "aot_emit_exception.h" + +#if WASM_ENABLE_GC != 0 + +#define BUILD_ISNULL(ptr, res, name) \ + do { \ + if (!(res = LLVMBuildIsNull(comp_ctx->builder, ptr, name))) { \ + aot_set_last_error("llvm build isnull failed."); \ + goto fail; \ + } \ + } while (0) + +#define BUILD_ISNOTNULL(ptr, res, name) \ + do { \ + if (!(res = LLVMBuildIsNotNull(comp_ctx->builder, ptr, name))) { \ + aot_set_last_error("llvm build isnotnull failed."); \ + goto fail; \ + } \ + } while (0) + +#define ADD_BASIC_BLOCK(block, name) \ + do { \ + if (!(block = LLVMAppendBasicBlockInContext(comp_ctx->context, \ + func_ctx->func, name))) { \ + aot_set_last_error("llvm add basic block failed."); \ + goto fail; \ + } \ + } while (0) + +#define CURR_BLOCK() LLVMGetInsertBlock(comp_ctx->builder) + +#define MOVE_BLOCK_AFTER(llvm_block, llvm_block_after) \ + LLVMMoveBasicBlockAfter(llvm_block, llvm_block_after) + +#define MOVE_BLOCK_AFTER_CURR(llvm_block) \ + LLVMMoveBasicBlockAfter(llvm_block, CURR_BLOCK()) + +#define MOVE_BLOCK_BEFORE(llvm_block, llvm_block_before) \ + LLVMMoveBasicBlockBefore(llvm_block, llvm_block_before) + +#define BUILD_COND_BR(value_if, block_then, block_else) \ + do { \ + if (!LLVMBuildCondBr(comp_ctx->builder, value_if, block_then, \ + block_else)) { \ + aot_set_last_error("llvm build cond br failed."); \ + goto fail; \ + } \ + } while (0) + +#define SET_BUILDER_POS(llvm_block) \ + LLVMPositionBuilderAtEnd(comp_ctx->builder, llvm_block) + +#define BUILD_BR(llvm_block) \ + do { \ + if (!LLVMBuildBr(comp_ctx->builder, llvm_block)) { \ + aot_set_last_error("llvm build br failed."); \ + goto fail; \ + } \ + } while (0) + +#define BUILD_ICMP(op, left, right, res, name) \ + do { \ + if (!(res = \ + LLVMBuildICmp(comp_ctx->builder, op, left, right, name))) { \ + aot_set_last_error("llvm build icmp failed."); \ + goto fail; \ + } \ + } while (0) + +static bool +is_target_x86(AOTCompContext *comp_ctx) +{ + return !strncmp(comp_ctx->target_arch, "x86_64", 6) + || !strncmp(comp_ctx->target_arch, "i386", 4); +} + +bool +aot_call_aot_create_func_obj(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + LLVMValueRef func_idx, LLVMValueRef *p_gc_obj) +{ + LLVMValueRef gc_obj, cmp_gc_obj, param_values[5], func, value; + LLVMTypeRef param_types[5], ret_type, func_type, func_ptr_type; + AOTFuncType *aot_func_type = func_ctx->aot_func->func_type; + LLVMBasicBlockRef block_curr = LLVMGetInsertBlock(comp_ctx->builder); + LLVMBasicBlockRef init_gc_obj_fail, init_gc_obj_succ; + + param_types[0] = INT8_PTR_TYPE; + param_types[1] = I32_TYPE; + param_types[2] = INT8_TYPE; + param_types[3] = INT8_PTR_TYPE; + param_types[4] = I32_TYPE; + ret_type = GC_REF_TYPE; + + if (comp_ctx->is_jit_mode) + GET_AOT_FUNCTION(llvm_jit_create_func_obj, 5); + else + GET_AOT_FUNCTION(aot_create_func_obj, 5); + + /* Call function llvm_jit/aot_create_func_obj() */ + param_values[0] = func_ctx->aot_inst; + param_values[1] = func_idx; + param_values[2] = I8_CONST(1); + param_values[3] = I8_PTR_NULL; + param_values[4] = I32_ZERO; + if (!(gc_obj = LLVMBuildCall2(comp_ctx->builder, func_type, func, + param_values, 5, "call"))) { + aot_set_last_error("llvm build call failed."); + return false; + } + + BUILD_ISNOTNULL(gc_obj, cmp_gc_obj, "gc_obj_not_null"); + + ADD_BASIC_BLOCK(init_gc_obj_fail, "init_gc_obj_fail"); + ADD_BASIC_BLOCK(init_gc_obj_succ, "init_gc_obj_success"); + + LLVMMoveBasicBlockAfter(init_gc_obj_fail, block_curr); + LLVMMoveBasicBlockAfter(init_gc_obj_succ, block_curr); + + if (!LLVMBuildCondBr(comp_ctx->builder, cmp_gc_obj, init_gc_obj_succ, + init_gc_obj_fail)) { + aot_set_last_error("llvm build cond br failed."); + goto fail; + } + + /* If init gc_obj failed, return this function + so the runtime can catch the exception */ + LLVMPositionBuilderAtEnd(comp_ctx->builder, init_gc_obj_fail); + if (!aot_build_zero_function_ret(comp_ctx, func_ctx, aot_func_type)) { + goto fail; + } + + LLVMPositionBuilderAtEnd(comp_ctx->builder, init_gc_obj_succ); + *p_gc_obj = gc_obj; + + return true; +fail: + return false; +} + +bool +aot_call_aot_obj_is_instance_of(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx, LLVMValueRef gc_obj, + LLVMValueRef heap_type, LLVMValueRef *castable) +{ + LLVMValueRef param_values[3], func, value, res; + LLVMTypeRef param_types[3], ret_type, func_type, func_ptr_type; + + param_types[0] = INT8_PTR_TYPE; + param_types[1] = GC_REF_TYPE; + param_types[2] = I32_TYPE; + ret_type = INT8_TYPE; + + if (comp_ctx->is_jit_mode) + GET_AOT_FUNCTION(llvm_jit_obj_is_instance_of, 3); + else + GET_AOT_FUNCTION(aot_obj_is_instance_of, 3); + + /* Call function aot_obj_is_instance_of() or llvm_jit_obj_is_instance_of() + */ + param_values[0] = func_ctx->aot_inst; + param_values[1] = gc_obj; + param_values[2] = heap_type; + + if (!(res = LLVMBuildCall2(comp_ctx->builder, func_type, func, param_values, + 3, "call"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + + *castable = res; + + return true; +fail: + return false; +} + +bool +aot_call_wasm_obj_is_type_of(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + LLVMValueRef gc_obj, LLVMValueRef heap_type, + LLVMValueRef *castable) +{ + LLVMValueRef param_values[2], func, value, res; + LLVMTypeRef param_types[2], ret_type, func_type, func_ptr_type; + + param_types[0] = GC_REF_TYPE; + param_types[1] = I32_TYPE; + ret_type = INT8_TYPE; + + GET_AOT_FUNCTION(wasm_obj_is_type_of, 2); + + /* Call function wasm_obj_is_type_of() */ + param_values[0] = gc_obj; + param_values[1] = heap_type; + if (!(res = LLVMBuildCall2(comp_ctx->builder, func_type, func, param_values, + 2, "call"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + + *castable = res; + + return true; +fail: + return false; +} + +bool +aot_call_aot_rtt_type_new(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + LLVMValueRef type_index, LLVMValueRef *rtt_type) +{ + LLVMValueRef param_values[2], func, value, res; + LLVMTypeRef param_types[2], ret_type, func_type, func_ptr_type; + + param_types[0] = INT8_PTR_TYPE; + param_types[1] = I32_TYPE; + ret_type = GC_REF_TYPE; + + if (comp_ctx->is_jit_mode) + GET_AOT_FUNCTION(llvm_jit_rtt_type_new, 2); + else + GET_AOT_FUNCTION(aot_rtt_type_new, 2); + + /* Call function llvm_jit/aot_rtt_type_new() */ + param_values[0] = func_ctx->aot_inst; + param_values[1] = type_index; + if (!(res = LLVMBuildCall2(comp_ctx->builder, func_type, func, param_values, + 2, "call"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + + *rtt_type = res; + return true; +fail: + return false; +} + +bool +aot_compile_op_ref_as_non_null(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx) +{ + LLVMValueRef gc_obj, cmp_gc_obj; + LLVMBasicBlockRef check_gc_obj_succ; + + GET_GC_REF_FROM_STACK(gc_obj); + + /* Check if gc object is NULL */ + BUILD_ISNULL(gc_obj, cmp_gc_obj, "cmp_gc_obj"); + + ADD_BASIC_BLOCK(check_gc_obj_succ, "check_gc_obj_succ"); + MOVE_BLOCK_AFTER_CURR(check_gc_obj_succ); + + /* Throw exception if it is NULL */ + if (!aot_emit_exception(comp_ctx, func_ctx, EXCE_NULL_REFERENCE, true, + cmp_gc_obj, check_gc_obj_succ)) + goto fail; + + return true; +fail: + return false; +} + +static bool +aot_call_wasm_struct_obj_new(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + LLVMValueRef rtt_type, LLVMValueRef *struct_obj) +{ + LLVMValueRef param_values[2], func, value, res; + LLVMTypeRef param_types[2], ret_type, func_type, func_ptr_type; + + param_types[0] = INT8_PTR_TYPE; + param_types[1] = INT8_PTR_TYPE; + ret_type = GC_REF_TYPE; + + GET_AOT_FUNCTION(wasm_struct_obj_new, 2); + + /* Call function wasm_struct_obj_new() */ + param_values[0] = func_ctx->exec_env; + param_values[1] = rtt_type; + if (!(res = LLVMBuildCall2(comp_ctx->builder, func_type, func, param_values, + 2, "call"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + + *struct_obj = res; + return true; +fail: + return false; +} + +static void +get_struct_field_data_types(const AOTCompContext *comp_ctx, uint8 field_type, + LLVMTypeRef *p_field_data_type, + LLVMTypeRef *p_field_data_ptr_type, + bool *p_trunc_or_extend) +{ + LLVMTypeRef field_data_type = NULL, field_data_ptr_type = NULL; + bool trunc_or_extend = false; + + if (wasm_is_type_reftype(field_type)) { + field_data_type = GC_REF_TYPE; + field_data_ptr_type = GC_REF_PTR_TYPE; + } + else { + switch (field_type) { + case VALUE_TYPE_I32: + field_data_type = I32_TYPE; + field_data_ptr_type = INT32_PTR_TYPE; + break; + case VALUE_TYPE_I64: + field_data_type = I64_TYPE; + field_data_ptr_type = INT64_PTR_TYPE; + break; + case VALUE_TYPE_F32: + field_data_type = F32_TYPE; + field_data_ptr_type = F32_PTR_TYPE; + break; + case VALUE_TYPE_F64: + field_data_type = F64_TYPE; + field_data_ptr_type = F64_PTR_TYPE; + break; + case PACKED_TYPE_I8: + field_data_type = INT8_TYPE; + field_data_ptr_type = INT8_PTR_TYPE; + trunc_or_extend = true; + break; + case PACKED_TYPE_I16: + field_data_type = INT16_TYPE; + field_data_ptr_type = INT16_PTR_TYPE; + trunc_or_extend = true; + break; + default: + bh_assert(0); + break; + } + } + + *p_field_data_type = field_data_type; + *p_field_data_ptr_type = field_data_ptr_type; + *p_trunc_or_extend = trunc_or_extend; +} + +static bool +aot_struct_obj_set_field(AOTCompContext *comp_ctx, LLVMValueRef struct_obj, + LLVMValueRef field_offset, LLVMValueRef field_value, + uint8 field_type) +{ + bool trunc = false; + LLVMValueRef field_data_ptr, res; + LLVMTypeRef field_data_type = NULL, field_data_ptr_type = NULL; + + get_struct_field_data_types(comp_ctx, field_type, &field_data_type, + &field_data_ptr_type, &trunc); + + /* Truncate field_value if necessary */ + if (trunc) { + if (!(field_value = + LLVMBuildTrunc(comp_ctx->builder, field_value, + field_data_type, "field_value_trunc"))) { + aot_set_last_error("llvm build trunc failed."); + goto fail; + } + } + + if (!(struct_obj = LLVMBuildBitCast(comp_ctx->builder, struct_obj, + INT8_PTR_TYPE, "struct_obj_i8p"))) { + aot_set_last_error("llvm build bitcast failed."); + goto fail; + } + + /* Build field data ptr and store the value */ + if (!(field_data_ptr = + LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, struct_obj, + &field_offset, 1, "field_data_i8p"))) { + aot_set_last_error("llvm build gep failed."); + goto fail; + } + + /* Cast to the field data type ptr */ + if (!(field_data_ptr = + LLVMBuildBitCast(comp_ctx->builder, field_data_ptr, + field_data_ptr_type, "field_value_ptr"))) { + aot_set_last_error("llvm build bitcast failed."); + goto fail; + } + + if (!(res = + LLVMBuildStore(comp_ctx->builder, field_value, field_data_ptr))) { + aot_set_last_error("llvm build store failed."); + goto fail; + } + + if (!is_target_x86(comp_ctx) + && (field_data_type == I64_TYPE || field_data_type == F64_TYPE + || field_data_type == GC_REF_TYPE)) { + LLVMSetAlignment(res, 4); + } + + return true; +fail: + return false; +} + +static bool +aot_struct_obj_get_field(AOTCompContext *comp_ctx, LLVMValueRef struct_obj, + LLVMValueRef field_offset, LLVMValueRef *p_field_value, + uint8 field_type, bool sign_extend) +{ + bool extend = false; + LLVMValueRef field_value, field_data_ptr; + LLVMTypeRef field_data_type = NULL, field_data_ptr_type = NULL; + + get_struct_field_data_types(comp_ctx, field_type, &field_data_type, + &field_data_ptr_type, &extend); + + if (!(struct_obj = LLVMBuildBitCast(comp_ctx->builder, struct_obj, + INT8_PTR_TYPE, "struct_obj_i8p"))) { + aot_set_last_error("llvm build bitcast failed."); + goto fail; + } + + if (!(field_data_ptr = + LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, struct_obj, + &field_offset, 1, "field_data_i8p"))) { + aot_set_last_error("llvm build gep failed."); + goto fail; + } + + if (!(field_data_ptr = + LLVMBuildBitCast(comp_ctx->builder, field_data_ptr, + field_data_ptr_type, "field_value_ptr"))) { + aot_set_last_error("llvm build bitcast failed."); + goto fail; + } + + if (!(field_value = LLVMBuildLoad2(comp_ctx->builder, field_data_type, + field_data_ptr, "field_value"))) { + aot_set_last_error("llvm build load failed."); + goto fail; + } + + if (!is_target_x86(comp_ctx) + && (field_data_type == I64_TYPE || field_data_type == F64_TYPE + || field_data_type == GC_REF_TYPE)) { + LLVMSetAlignment(field_value, 4); + } + + if (extend) { + if (sign_extend) { + if (!(field_value = LLVMBuildSExt(comp_ctx->builder, field_value, + I32_TYPE, "field_value_sext"))) { + aot_set_last_error("llvm build signed ext failed."); + goto fail; + } + } + else { + if (!(field_value = LLVMBuildZExt(comp_ctx->builder, field_value, + I32_TYPE, "field_value_zext"))) { + aot_set_last_error("llvm build unsigned ext failed."); + goto fail; + } + } + } + + *p_field_value = field_value; + return true; +fail: + return false; +} + +static bool +struct_new_canon_init_fields(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 type_index, LLVMValueRef struct_obj) +{ + LLVMValueRef field_value = NULL; + /* Used in compile time, to distinguish what type of AOTValue POP, + * field_data offset, size */ + WASMStructType *compile_time_struct_type = + (WASMStructType *)comp_ctx->comp_data->types[type_index]; + WASMStructFieldType *fields = compile_time_struct_type->fields; + int32 field_count = (int32)compile_time_struct_type->field_count; + int32 field_idx; + uint32 field_offset; + uint8 field_type; + + for (field_idx = field_count - 1; field_idx >= 0; field_idx--) { + field_type = fields[field_idx].field_type; + field_offset = comp_ctx->pointer_size == sizeof(uint64) + ? fields[field_idx].field_offset_64bit + : fields[field_idx].field_offset_32bit; + + if (wasm_is_type_reftype(field_type)) { + POP_GC_REF(field_value); + } + else if (field_type == VALUE_TYPE_I32 || field_type == PACKED_TYPE_I8 + || field_type == PACKED_TYPE_I16) { + POP_I32(field_value); + } + else if (field_type == VALUE_TYPE_I64) { + POP_I64(field_value); + } + else if (field_type == VALUE_TYPE_F32) { + POP_F32(field_value); + } + else if (field_type == VALUE_TYPE_F64) { + POP_F64(field_value); + } + else { + bh_assert(0); + } + + if (!aot_struct_obj_set_field(comp_ctx, struct_obj, + I32_CONST(field_offset), field_value, + field_type)) + goto fail; + } + + return true; +fail: + return false; +} + +bool +aot_compile_op_struct_new(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 type_index, bool init_with_default) +{ + LLVMValueRef rtt_type, struct_obj, cmp; + LLVMBasicBlockRef check_rtt_type_succ, check_struct_obj_succ; + + if (!aot_gen_commit_values(comp_ctx->aot_frame)) + return false; + + if (!aot_gen_commit_sp_ip(comp_ctx->aot_frame, true, true)) + return false; + + /* Generate call wasm_rtt_type_new and check for exception */ + if (!aot_call_aot_rtt_type_new(comp_ctx, func_ctx, I32_CONST(type_index), + &rtt_type)) + goto fail; + + ADD_BASIC_BLOCK(check_rtt_type_succ, "check rtt type succ"); + MOVE_BLOCK_AFTER_CURR(check_rtt_type_succ); + + BUILD_ISNULL(rtt_type, cmp, "cmp_rtt_type"); + if (!aot_emit_exception(comp_ctx, func_ctx, EXCE_FAILED_TO_CREATE_RTT_TYPE, + true, cmp, check_rtt_type_succ)) + goto fail; + + /* Generate call wasm_struct_obj_new and check for exception */ + if (!aot_call_wasm_struct_obj_new(comp_ctx, func_ctx, rtt_type, + &struct_obj)) + goto fail; + + ADD_BASIC_BLOCK(check_struct_obj_succ, "check struct obj succ"); + MOVE_BLOCK_AFTER(check_struct_obj_succ, check_rtt_type_succ); + + BUILD_ISNULL(struct_obj, cmp, "cmp_struct_obj"); + if (!aot_emit_exception(comp_ctx, func_ctx, + EXCE_FAILED_TO_CREATE_STRUCT_OBJ, true, cmp, + check_struct_obj_succ)) + goto fail; + + SET_BUILDER_POS(check_struct_obj_succ); + + /* For WASM_OP_STRUCT_NEW, init filed with poped value */ + if (!init_with_default + && !struct_new_canon_init_fields(comp_ctx, func_ctx, type_index, + struct_obj)) { + goto fail; + } + + PUSH_GC_REF(struct_obj); + + return true; +fail: + return false; +} + +bool +aot_compile_op_struct_get(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 type_index, uint32 field_idx, bool sign) +{ + LLVMValueRef struct_obj, cmp, field_value; + LLVMBasicBlockRef check_struct_obj_succ; + + /* Used in compile time, to distinguish what type of AOTValue PUSH, + * field_data offset, size */ + WASMStructType *compile_time_struct_type = + (WASMStructType *)comp_ctx->comp_data->types[type_index]; + WASMStructFieldType *field; + uint32 field_offset; + uint8 field_type; + + field = compile_time_struct_type->fields + field_idx; + field_type = field->field_type; + field_offset = comp_ctx->pointer_size == sizeof(uint64) + ? field->field_offset_64bit + : field->field_offset_32bit; + + if (field_idx >= compile_time_struct_type->field_count) { + aot_set_last_error("struct field index out of bounds"); + goto fail; + } + + POP_GC_REF(struct_obj); + + ADD_BASIC_BLOCK(check_struct_obj_succ, "check struct obj succ"); + MOVE_BLOCK_AFTER_CURR(check_struct_obj_succ); + + BUILD_ISNULL(struct_obj, cmp, "cmp_struct_obj"); + if (!aot_emit_exception(comp_ctx, func_ctx, EXCE_NULL_STRUCT_OBJ, true, cmp, + check_struct_obj_succ)) + goto fail; + + if (!aot_struct_obj_get_field(comp_ctx, struct_obj, I32_CONST(field_offset), + &field_value, field_type, sign)) + goto fail; + + if (wasm_is_type_reftype(field_type)) { + PUSH_GC_REF(field_value); + } + else if (field_type == VALUE_TYPE_I32 || field_type == PACKED_TYPE_I8 + || field_type == PACKED_TYPE_I16) { + PUSH_I32(field_value); + } + else if (field_type == VALUE_TYPE_I64) { + PUSH_I64(field_value); + } + else if (field_type == VALUE_TYPE_F32) { + PUSH_F32(field_value); + } + else if (field_type == VALUE_TYPE_F64) { + PUSH_F64(field_value); + } + else { + bh_assert(0); + } + + return true; +fail: + return false; +} + +bool +aot_compile_op_struct_set(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 type_index, uint32 field_idx) +{ + LLVMValueRef struct_obj, cmp, field_value = NULL; + LLVMBasicBlockRef check_struct_obj_succ; + /* Used in compile time, to distinguish what type of AOTValue POP, + * field_data offset, size */ + WASMStructType *compile_time_struct_type = + (WASMStructType *)comp_ctx->comp_data->types[type_index]; + WASMStructFieldType *field; + uint32 field_offset; + uint8 field_type; + + field = compile_time_struct_type->fields + field_idx; + field_type = field->field_type; + field_offset = comp_ctx->pointer_size == sizeof(uint64) + ? field->field_offset_64bit + : field->field_offset_32bit; + + if (field_idx >= compile_time_struct_type->field_count) { + aot_set_last_error("struct field index out of bounds"); + goto fail; + } + + if (wasm_is_type_reftype(field_type)) { + POP_GC_REF(field_value); + } + else if (field_type == VALUE_TYPE_I32 || field_type == PACKED_TYPE_I8 + || field_type == PACKED_TYPE_I16) { + POP_I32(field_value); + } + else if (field_type == VALUE_TYPE_I64) { + POP_I64(field_value); + } + else if (field_type == VALUE_TYPE_F32) { + POP_F32(field_value); + } + else if (field_type == VALUE_TYPE_F64) { + POP_F64(field_value); + } + else { + bh_assert(0); + } + + POP_GC_REF(struct_obj); + + ADD_BASIC_BLOCK(check_struct_obj_succ, "check struct obj succ"); + MOVE_BLOCK_AFTER_CURR(check_struct_obj_succ); + + BUILD_ISNULL(struct_obj, cmp, "cmp_struct_obj"); + if (!aot_emit_exception(comp_ctx, func_ctx, EXCE_NULL_STRUCT_OBJ, true, cmp, + check_struct_obj_succ)) + goto fail; + + if (!aot_struct_obj_set_field(comp_ctx, struct_obj, I32_CONST(field_offset), + field_value, field_type)) + goto fail; + + return true; +fail: + return false; +} + +static bool +aot_call_wasm_array_obj_new(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + LLVMValueRef rtt_type, LLVMValueRef array_len, + LLVMValueRef array_elem, LLVMValueRef *array_obj) +{ + LLVMValueRef param_values[4], func, value, res, array_elem_ptr; + LLVMTypeRef param_types[4], ret_type, func_type, func_ptr_type; + + if (!(array_elem_ptr = LLVMBuildAlloca( + comp_ctx->builder, LLVMTypeOf(array_elem), "array_elem_ptr"))) { + aot_set_last_error("llvm build alloca failed."); + goto fail; + } + if (!LLVMBuildStore(comp_ctx->builder, array_elem, array_elem_ptr)) { + aot_set_last_error("llvm build store failed."); + goto fail; + } + if (!(array_elem_ptr = LLVMBuildBitCast(comp_ctx->builder, array_elem_ptr, + INT8_PTR_TYPE, "array_elem_ptr"))) { + aot_set_last_error("llvm build bitcast failed."); + goto fail; + } + + param_types[0] = INT8_PTR_TYPE; + param_types[1] = INT8_PTR_TYPE; + param_types[2] = I32_TYPE; + param_types[3] = INT8_PTR_TYPE; + ret_type = GC_REF_TYPE; + + GET_AOT_FUNCTION(wasm_array_obj_new, 4); + + /* Call function wasm_array_obj_new() */ + param_values[0] = func_ctx->exec_env; + param_values[1] = rtt_type; + param_values[2] = array_len; + param_values[3] = array_elem_ptr; + if (!(res = LLVMBuildCall2(comp_ctx->builder, func_type, func, param_values, + 4, "call"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + + *array_obj = res; + return true; +fail: + return false; +} + +static uint32 +aot_array_obj_elem_size_log(AOTCompContext *comp_ctx, uint8 array_elem_type) +{ + uint32 elem_size_log = 0; + + if (wasm_is_type_reftype(array_elem_type)) { + elem_size_log = comp_ctx->pointer_size == sizeof(uint32) ? 2 : 3; + } + else if (array_elem_type == PACKED_TYPE_I8) { + elem_size_log = 0; + } + else if (array_elem_type == PACKED_TYPE_I16) { + elem_size_log = 1; + } + else if (array_elem_type == VALUE_TYPE_I32 + || array_elem_type == VALUE_TYPE_F32) { + elem_size_log = 2; + } + else if (array_elem_type == VALUE_TYPE_I64 + || array_elem_type == VALUE_TYPE_F64) { + elem_size_log = 3; + } + else { + bh_assert(0); + } + + return elem_size_log; +} + +/* array_obj->elem_data + (elem_idx << elem_size_log) */ +bool +aot_array_obj_elem_addr(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + LLVMValueRef array_obj, LLVMValueRef elem_idx, + LLVMValueRef *p_elem_data, uint8 array_elem_type) +{ + uint32 elem_size_log = 0; + LLVMValueRef start_offset, elem_offset, elem_data; + + elem_size_log = aot_array_obj_elem_size_log(comp_ctx, array_elem_type); + + /* Get the elem data start offset of the WASMArrayObject, the offset may be + * different in 32-bit runtime and 64-bit runtime since WASMObjectHeader + * is uintptr_t. Use comp_ctx->pointer_size + 4(uint32 for length) as the + * offsetof(WASMArrayObject, length)*/ + if (!(start_offset = I32_CONST(comp_ctx->pointer_size + sizeof(uint32)))) { + aot_set_last_error("llvm build const failed."); + goto fail; + } + + if (!(elem_offset = + LLVMBuildShl(comp_ctx->builder, elem_idx, + I32_CONST(elem_size_log), "elem_offset"))) { + aot_set_last_error("llvm build shl failed."); + goto fail; + } + + if (!(elem_offset = LLVMBuildAdd(comp_ctx->builder, start_offset, + elem_offset, "total_offset"))) { + aot_set_last_error("llvm build add failed."); + goto fail; + } + + if (!(elem_data = LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, + array_obj, &elem_offset, 1, + "array_obj_elem_data_i8p"))) { + aot_set_last_error("llvm build gep failed."); + goto fail; + } + + *p_elem_data = elem_data; + return true; +fail: + return false; +} + +static bool +aot_array_obj_set_elem(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + LLVMValueRef array_obj, LLVMValueRef elem_idx, + LLVMValueRef array_elem, uint8 array_elem_type) +{ + bool trunc = false; + LLVMValueRef elem_data_ptr, res; + LLVMTypeRef elem_data_type = NULL, elem_data_ptr_type = NULL; + + if (!aot_array_obj_elem_addr(comp_ctx, func_ctx, array_obj, elem_idx, + &elem_data_ptr, array_elem_type)) + goto fail; + + if (wasm_is_type_reftype(array_elem_type)) { + elem_data_type = GC_REF_TYPE; + elem_data_ptr_type = GC_REF_PTR_TYPE; + } + else + switch (array_elem_type) { + case PACKED_TYPE_I8: + elem_data_type = INT8_TYPE; + elem_data_ptr_type = INT8_PTR_TYPE; + trunc = true; + break; + case PACKED_TYPE_I16: + elem_data_type = INT16_TYPE; + elem_data_ptr_type = INT16_PTR_TYPE; + trunc = true; + break; + case VALUE_TYPE_I32: + elem_data_type = I32_TYPE; + elem_data_ptr_type = INT32_PTR_TYPE; + break; + case VALUE_TYPE_I64: + elem_data_type = I64_TYPE; + elem_data_ptr_type = INT64_PTR_TYPE; + break; + case VALUE_TYPE_F32: + elem_data_type = F32_TYPE; + elem_data_ptr_type = F32_PTR_TYPE; + break; + case VALUE_TYPE_F64: + elem_data_type = F64_TYPE; + elem_data_ptr_type = F64_PTR_TYPE; + break; + default: + bh_assert(0); + break; + } + + /* Based on elem_size, trunc array_elem if necessary */ + if (trunc) { + if (!(array_elem = + LLVMBuildTrunc(comp_ctx->builder, array_elem, elem_data_type, + "array_elem_trunc"))) { + aot_set_last_error("llvm build trunc failed."); + goto fail; + } + } + + /* Cast to the field data type ptr */ + if (!(elem_data_ptr = + LLVMBuildBitCast(comp_ctx->builder, elem_data_ptr, + elem_data_ptr_type, "elem_data_ptr"))) { + aot_set_last_error("llvm build bitcast failed."); + goto fail; + } + + if (!(res = LLVMBuildStore(comp_ctx->builder, array_elem, elem_data_ptr))) { + aot_set_last_error("llvm build store failed."); + goto fail; + } + + if (!is_target_x86(comp_ctx) + && (elem_data_type == I64_TYPE || elem_data_type == F64_TYPE + || elem_data_type == GC_REF_TYPE)) { + LLVMSetAlignment(res, 4); + } + + return true; +fail: + return false; +} + +static bool +aot_call_aot_array_init_with_data( + AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, LLVMValueRef seg_index, + LLVMValueRef data_seg_offset, LLVMValueRef array_obj, + LLVMValueRef elem_size, LLVMValueRef array_len) +{ + LLVMValueRef param_values[6], func, value, res, cmp; + LLVMTypeRef param_types[6], ret_type, func_type, func_ptr_type; + LLVMBasicBlockRef init_success; + + ADD_BASIC_BLOCK(init_success, "init success"); + MOVE_BLOCK_AFTER_CURR(init_success); + + param_types[0] = INT8_PTR_TYPE; + param_types[1] = I32_TYPE; + param_types[2] = I32_TYPE; + param_types[3] = INT8_PTR_TYPE; + param_types[4] = I32_TYPE; + param_types[5] = I32_TYPE; + ret_type = INT8_TYPE; + + if (comp_ctx->is_jit_mode) + GET_AOT_FUNCTION(llvm_array_init_with_data, 6); + else + GET_AOT_FUNCTION(aot_array_init_with_data, 6); + + /* Call function aot_array_init_with_data() */ + param_values[0] = func_ctx->aot_inst; + param_values[1] = seg_index; + param_values[2] = data_seg_offset; + param_values[3] = array_obj; + param_values[4] = elem_size; + param_values[5] = array_len; + if (!(res = LLVMBuildCall2(comp_ctx->builder, func_type, func, param_values, + 6, "call"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + + BUILD_ICMP(LLVMIntEQ, res, I8_ZERO, cmp, "array_init_ret"); + if (!aot_emit_exception(comp_ctx, func_ctx, EXCE_ARRAY_IDX_OOB, true, cmp, + init_success)) + goto fail; + + return true; +fail: + return false; +} + +static bool +aot_call_wasm_array_get_elem(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + LLVMValueRef array_obj, LLVMValueRef elem_idx, + LLVMValueRef *p_array_elem, uint8 array_elem_type, + bool sign) +{ + bool extend = false; + LLVMValueRef elem_data_ptr, array_elem; + LLVMTypeRef elem_data_type = NULL, elem_data_ptr_type = NULL; + + if (!aot_array_obj_elem_addr(comp_ctx, func_ctx, array_obj, elem_idx, + &elem_data_ptr, array_elem_type)) + goto fail; + + if (wasm_is_type_reftype(array_elem_type)) { + elem_data_type = GC_REF_TYPE; + elem_data_ptr_type = GC_REF_PTR_TYPE; + } + else + switch (array_elem_type) { + case PACKED_TYPE_I8: + elem_data_type = INT8_TYPE; + elem_data_ptr_type = INT8_PTR_TYPE; + extend = true; + break; + case PACKED_TYPE_I16: + elem_data_type = INT16_TYPE; + elem_data_ptr_type = INT16_PTR_TYPE; + extend = true; + break; + case VALUE_TYPE_I32: + elem_data_type = I32_TYPE; + elem_data_ptr_type = INT32_PTR_TYPE; + break; + case VALUE_TYPE_I64: + elem_data_type = I64_TYPE; + elem_data_ptr_type = INT64_PTR_TYPE; + break; + case VALUE_TYPE_F32: + elem_data_type = F32_TYPE; + elem_data_ptr_type = F32_PTR_TYPE; + break; + case VALUE_TYPE_F64: + elem_data_type = F64_TYPE; + elem_data_ptr_type = F64_PTR_TYPE; + break; + default: + bh_assert(0); + break; + } + + /* Based on elem_size, trunc array_elem if necessary */ + if (!(elem_data_ptr = + LLVMBuildBitCast(comp_ctx->builder, elem_data_ptr, + elem_data_ptr_type, "elem_data_ptr"))) { + aot_set_last_error("llvm build bitcast failed."); + goto fail; + } + + if (!(array_elem = LLVMBuildLoad2(comp_ctx->builder, elem_data_type, + elem_data_ptr, "array_elem"))) { + aot_set_last_error("llvm build load failed."); + goto fail; + } + + if (!is_target_x86(comp_ctx) + && (elem_data_type == I64_TYPE || elem_data_type == F64_TYPE + || elem_data_type == GC_REF_TYPE)) { + LLVMSetAlignment(array_elem, 4); + } + + if (extend) { + if (sign) { + if (!(array_elem = LLVMBuildSExt(comp_ctx->builder, array_elem, + I32_TYPE, "array_elem_sext"))) { + aot_set_last_error("llvm build signed ext failed."); + goto fail; + } + } + else { + if (!(array_elem = LLVMBuildZExt(comp_ctx->builder, array_elem, + I32_TYPE, "array_elem_zext"))) { + aot_set_last_error("llvm build unsigned ext failed."); + goto fail; + } + } + } + + *p_array_elem = array_elem; + return true; +fail: + return false; +} + +/* array_obj->length >> WASM_ARRAY_LENGTH_SHIFT */ +bool +aot_array_obj_length(AOTCompContext *comp_ctx, LLVMValueRef array_obj, + LLVMValueRef *p_array_len) +{ + LLVMValueRef offset, array_len; + + /* Get the length of the WASMArrayObject, the offset may be + * different in 32-bit runtime and 64-bit runtime since WASMObjectHeader + * is uintptr_t. Use comp_ctx->pointer_size as the + * offsetof(WASMArrayObject, length)*/ + if (!(offset = I32_CONST(comp_ctx->pointer_size))) { + aot_set_last_error("llvm build const failed."); + goto fail; + } + + if (!(array_len = + LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, array_obj, + &offset, 1, "array_obj_length_i8p"))) { + aot_set_last_error("llvm build gep failed."); + goto fail; + } + + if (!(array_len = + LLVMBuildBitCast(comp_ctx->builder, array_len, INT32_PTR_TYPE, + "array_obj_length_i32ptr"))) { + aot_set_last_error("llvm build bitcast failed."); + goto fail; + } + + if (!(array_len = LLVMBuildLoad2(comp_ctx->builder, I32_TYPE, array_len, + "array_obj_length"))) { + aot_set_last_error("llvm build load failed."); + goto fail; + } + + if (!(array_len = LLVMBuildLShr(comp_ctx->builder, array_len, + I32_CONST(WASM_ARRAY_LENGTH_SHIFT), + "array_obj_length_shr"))) { + aot_set_last_error("llvm build lshr failed."); + goto fail; + } + + *p_array_len = array_len; + return true; +fail: + return false; +} + +bool +aot_compile_op_array_new(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 type_index, bool init_with_default, + bool fixed_size, uint32 array_len) +{ + LLVMValueRef array_length, array_elem = NULL, array_obj; + LLVMValueRef rtt_type, cmp, elem_idx; + LLVMBasicBlockRef check_rtt_type_succ, check_array_obj_succ; + /* Use for distinguish what type of AOTValue POP */ + WASMArrayType *compile_time_array_type = + (WASMArrayType *)comp_ctx->comp_data->types[type_index]; + uint8 array_elem_type = compile_time_array_type->elem_type; + uint32 i; + + if (!aot_gen_commit_values(comp_ctx->aot_frame)) + return false; + + if (!aot_gen_commit_sp_ip(comp_ctx->aot_frame, true, true)) + return false; + + /* Generate call aot_rtt_type_new and check for exception */ + if (!aot_call_aot_rtt_type_new(comp_ctx, func_ctx, I32_CONST(type_index), + &rtt_type)) + goto fail; + + ADD_BASIC_BLOCK(check_rtt_type_succ, "check rtt type succ"); + MOVE_BLOCK_AFTER_CURR(check_rtt_type_succ); + + BUILD_ISNULL(rtt_type, cmp, "cmp_rtt_type"); + if (!aot_emit_exception(comp_ctx, func_ctx, EXCE_FAILED_TO_CREATE_RTT_TYPE, + true, cmp, check_rtt_type_succ)) + goto fail; + + if (!fixed_size) + POP_I32(array_length); + else + array_length = I32_CONST(array_len); + + /* For WASM_OP_ARRAY_NEW */ + if (!fixed_size && !init_with_default) { + if (wasm_is_type_reftype(array_elem_type)) { + POP_GC_REF(array_elem); + } + else if (array_elem_type == VALUE_TYPE_I32 + || array_elem_type == PACKED_TYPE_I8 + || array_elem_type == PACKED_TYPE_I16) { + POP_I32(array_elem); + } + else if (array_elem_type == VALUE_TYPE_I64) { + POP_I64(array_elem); + } + else if (array_elem_type == VALUE_TYPE_F32) { + POP_F32(array_elem); + } + else if (array_elem_type == VALUE_TYPE_F64) { + POP_F64(array_elem); + } + else { + bh_assert(0); + } + } + else { + /* I64 will alloca large enough space for all union access includes + * array_elem.gc_ob, i32, i64 to be interpreted as 0*/ + array_elem = I64_ZERO; + } + + /* Generate call wasm_array_obj_new and check for exception */ + if (!aot_call_wasm_array_obj_new(comp_ctx, func_ctx, rtt_type, array_length, + array_elem, &array_obj)) + goto fail; + + ADD_BASIC_BLOCK(check_array_obj_succ, "check array obj succ"); + MOVE_BLOCK_AFTER(check_array_obj_succ, check_rtt_type_succ); + + BUILD_ISNULL(array_obj, cmp, "cmp_array_obj"); + if (!aot_emit_exception(comp_ctx, func_ctx, EXCE_FAILED_TO_CREATE_ARRAY_OBJ, + true, cmp, check_array_obj_succ)) + goto fail; + + if (fixed_size) { + for (i = 0; i < array_len; i++) { + if (wasm_is_type_reftype(array_elem_type)) { + POP_GC_REF(array_elem); + } + else if (array_elem_type == VALUE_TYPE_I32 + || array_elem_type == PACKED_TYPE_I8 + || array_elem_type == PACKED_TYPE_I16) { + POP_I32(array_elem); + } + else if (array_elem_type == VALUE_TYPE_I64) { + POP_I64(array_elem); + } + else if (array_elem_type == VALUE_TYPE_F32) { + POP_F32(array_elem); + } + else if (array_elem_type == VALUE_TYPE_F64) { + POP_F64(array_elem); + } + else { + bh_assert(0); + } + + /* array_len - 1 - i */ + if (!(elem_idx = LLVMBuildSub(comp_ctx->builder, array_length, + I32_CONST(i + 1), "elem_idx"))) { + aot_set_last_error("llvm build sub failed."); + goto fail; + } + + if (!aot_array_obj_set_elem(comp_ctx, func_ctx, array_obj, elem_idx, + array_elem, array_elem_type)) + goto fail; + } + } + + PUSH_GC_REF(array_obj); + + return true; +fail: + return false; +} + +bool +aot_compile_op_array_new_data(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx, uint32 type_index, + uint32 data_seg_index) +{ + LLVMValueRef array_length, data_seg_offset, rtt_type, + elem_size = NULL, array_elem, array_obj, cmp; + LLVMBasicBlockRef check_rtt_type_succ, check_array_obj_succ; + /* Use for distinguish what type of element in array */ + WASMArrayType *compile_time_array_type = + (WASMArrayType *)comp_ctx->comp_data->types[type_index]; + uint8 array_elem_type = compile_time_array_type->elem_type; + + if (!aot_gen_commit_values(comp_ctx->aot_frame)) + return false; + + if (!aot_gen_commit_sp_ip(comp_ctx->aot_frame, true, true)) + return false; + + /* Generate call aot_rtt_type_new and check for exception */ + if (!aot_call_aot_rtt_type_new(comp_ctx, func_ctx, I32_CONST(type_index), + &rtt_type)) + goto fail; + + ADD_BASIC_BLOCK(check_rtt_type_succ, "check rtt type succ"); + MOVE_BLOCK_AFTER_CURR(check_rtt_type_succ); + + BUILD_ISNULL(rtt_type, cmp, "cmp_rtt_type"); + if (!aot_emit_exception(comp_ctx, func_ctx, EXCE_FAILED_TO_CREATE_RTT_TYPE, + true, cmp, check_rtt_type_succ)) + goto fail; + + POP_I32(array_length); + POP_I32(data_seg_offset); + + switch (array_elem_type) { + case PACKED_TYPE_I8: + elem_size = I32_ONE; + break; + case PACKED_TYPE_I16: + elem_size = I32_TWO; + break; + case VALUE_TYPE_I32: + case VALUE_TYPE_F32: + elem_size = I32_FOUR; + break; + case VALUE_TYPE_I64: + case VALUE_TYPE_F64: + elem_size = I32_EIGHT; + break; + default: + bh_assert(0); + } + + if (elem_size == I32_EIGHT) + array_elem = I64_ZERO; + else + array_elem = I32_ZERO; + + /* Generate call wasm_array_obj_new and check for exception */ + if (!aot_call_wasm_array_obj_new(comp_ctx, func_ctx, rtt_type, array_length, + array_elem, &array_obj)) + goto fail; + + ADD_BASIC_BLOCK(check_array_obj_succ, "check array obj succ"); + MOVE_BLOCK_AFTER(check_array_obj_succ, check_rtt_type_succ); + + BUILD_ISNULL(array_obj, cmp, "cmp_array_obj"); + if (!aot_emit_exception(comp_ctx, func_ctx, EXCE_FAILED_TO_CREATE_ARRAY_OBJ, + true, cmp, check_array_obj_succ)) + goto fail; + + if (!aot_call_aot_array_init_with_data( + comp_ctx, func_ctx, I32_CONST(data_seg_index), data_seg_offset, + array_obj, elem_size, array_length)) + goto fail; + + PUSH_GC_REF(array_obj); + + return true; +fail: + return false; +} + +bool +aot_compile_op_array_get(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 type_index, bool sign) +{ + LLVMValueRef elem_idx, array_obj, cmp, array_len, array_elem; + LLVMBasicBlockRef check_array_obj_succ, check_boundary_succ; + /* Use for distinguish what type of AOTValue PUSH */ + WASMArrayType *compile_time_array_type = + (WASMArrayType *)comp_ctx->comp_data->types[type_index]; + uint8 array_elem_type = compile_time_array_type->elem_type; + + POP_I32(elem_idx); + POP_GC_REF(array_obj); + + ADD_BASIC_BLOCK(check_array_obj_succ, "check array obj succ"); + MOVE_BLOCK_AFTER_CURR(check_array_obj_succ); + + BUILD_ISNULL(array_obj, cmp, "cmp_array_obj"); + if (!aot_emit_exception(comp_ctx, func_ctx, EXCE_NULL_ARRAY_OBJ, true, cmp, + check_array_obj_succ)) + goto fail; + + SET_BUILDER_POS(check_array_obj_succ); + if (!aot_array_obj_length(comp_ctx, array_obj, &array_len)) + goto fail; + + ADD_BASIC_BLOCK(check_boundary_succ, "check boundary succ"); + MOVE_BLOCK_AFTER(check_boundary_succ, check_array_obj_succ); + + BUILD_ICMP(LLVMIntUGE, elem_idx, array_len, cmp, "cmp_array_obj"); + if (!aot_emit_exception(comp_ctx, func_ctx, EXCE_ARRAY_IDX_OOB, true, cmp, + check_boundary_succ)) + goto fail; + + SET_BUILDER_POS(check_boundary_succ); + if (!aot_call_wasm_array_get_elem(comp_ctx, func_ctx, array_obj, elem_idx, + &array_elem, array_elem_type, sign)) + goto fail; + + if (wasm_is_type_reftype(array_elem_type)) { + PUSH_GC_REF(array_elem); + } + else if (array_elem_type == VALUE_TYPE_I32 + || array_elem_type == PACKED_TYPE_I8 + || array_elem_type == PACKED_TYPE_I16) { + PUSH_I32(array_elem); + } + else if (array_elem_type == VALUE_TYPE_I64) { + PUSH_I64(array_elem); + } + else if (array_elem_type == VALUE_TYPE_F32) { + PUSH_F32(array_elem); + } + else if (array_elem_type == VALUE_TYPE_F64) { + PUSH_F64(array_elem); + } + else { + bh_assert(0); + } + + return true; +fail: + return false; +} + +bool +aot_compile_op_array_set(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 type_index) +{ + LLVMValueRef elem_idx, array_obj, cmp, array_len, array_elem = NULL; + LLVMBasicBlockRef check_array_obj_succ, check_boundary_succ; + /* Use for distinguish what type of AOTValue POP */ + WASMArrayType *compile_time_array_type = + (WASMArrayType *)comp_ctx->comp_data->types[type_index]; + uint8 array_elem_type = compile_time_array_type->elem_type; + + /* Get LLVM type based on array_elem_type */ + if (wasm_is_type_reftype(array_elem_type)) { + POP_GC_REF(array_elem); + } + else if (array_elem_type == VALUE_TYPE_I32 + || array_elem_type == PACKED_TYPE_I8 + || array_elem_type == PACKED_TYPE_I16) { + POP_I32(array_elem); + } + else if (array_elem_type == VALUE_TYPE_I64) { + POP_I64(array_elem); + } + else if (array_elem_type == VALUE_TYPE_F32) { + POP_F32(array_elem); + } + else if (array_elem_type == VALUE_TYPE_F64) { + POP_F64(array_elem); + } + else { + bh_assert(0); + } + + POP_I32(elem_idx); + POP_GC_REF(array_obj); + + ADD_BASIC_BLOCK(check_array_obj_succ, "check array obj succ"); + MOVE_BLOCK_AFTER_CURR(check_array_obj_succ); + + BUILD_ISNULL(array_obj, cmp, "cmp_array_obj"); + if (!aot_emit_exception(comp_ctx, func_ctx, EXCE_NULL_ARRAY_OBJ, true, cmp, + check_array_obj_succ)) + goto fail; + + SET_BUILDER_POS(check_array_obj_succ); + if (!aot_array_obj_length(comp_ctx, array_obj, &array_len)) + goto fail; + + ADD_BASIC_BLOCK(check_boundary_succ, "check boundary succ"); + MOVE_BLOCK_AFTER(check_boundary_succ, check_array_obj_succ); + + BUILD_ICMP(LLVMIntUGE, elem_idx, array_len, cmp, "cmp_array_obj"); + if (!aot_emit_exception(comp_ctx, func_ctx, EXCE_ARRAY_IDX_OOB, true, cmp, + check_boundary_succ)) + goto fail; + + SET_BUILDER_POS(check_boundary_succ); + if (!aot_array_obj_set_elem(comp_ctx, func_ctx, array_obj, elem_idx, + array_elem, array_elem_type)) { + aot_set_last_error("llvm build alloca failed."); + goto fail; + } + + return true; +fail: + return false; +} + +bool +aot_compile_op_array_fill(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 type_index) +{ + LLVMValueRef len, array_obj, fill_value = NULL, offset, array_len, cmp[2], + boundary, loop_counter_addr, loop_counter_val; + LLVMBasicBlockRef check_obj_succ, len_gt_zero, len_le_zero, inner_else; + LLVMBasicBlockRef fill_loop_header, fill_loop_body; + WASMArrayType *compile_time_array_type = + (WASMArrayType *)comp_ctx->comp_data->types[type_index]; + uint8 array_elem_type = compile_time_array_type->elem_type; + + POP_I32(len); + /* Get LLVM type based on array_elem_type */ + if (wasm_is_type_reftype(array_elem_type)) { + POP_GC_REF(fill_value); + } + else if (array_elem_type == VALUE_TYPE_I32 + || array_elem_type == PACKED_TYPE_I8 + || array_elem_type == PACKED_TYPE_I16) { + POP_I32(fill_value); + } + else if (array_elem_type == VALUE_TYPE_I64) { + POP_I64(fill_value); + } + else if (array_elem_type == VALUE_TYPE_F32) { + POP_F32(fill_value); + } + else if (array_elem_type == VALUE_TYPE_F64) { + POP_F64(fill_value); + } + else { + bh_assert(0); + } + + POP_I32(offset); + POP_GC_REF(array_obj); + + ADD_BASIC_BLOCK(check_obj_succ, "check array objs succ"); + MOVE_BLOCK_AFTER_CURR(check_obj_succ); + + BUILD_ISNULL(array_obj, cmp[0], "cmp_obj"); + + if (!aot_emit_exception(comp_ctx, func_ctx, EXCE_NULL_ARRAY_OBJ, true, + cmp[0], check_obj_succ)) + goto fail; + + /* Create if block */ + ADD_BASIC_BLOCK(len_gt_zero, "len_gt_zero"); + MOVE_BLOCK_AFTER_CURR(len_gt_zero); + + /* Create inner else block */ + ADD_BASIC_BLOCK(inner_else, "inner_else"); + MOVE_BLOCK_AFTER(inner_else, len_gt_zero); + + /* Create fill_loop_header block */ + ADD_BASIC_BLOCK(fill_loop_header, "fill_loop_header"); + MOVE_BLOCK_AFTER(fill_loop_header, len_gt_zero); + + /* Create fill_loop_body block */ + ADD_BASIC_BLOCK(fill_loop_body, "fill_loop_body"); + MOVE_BLOCK_AFTER(fill_loop_body, len_gt_zero); + + /* Create else(end) block */ + ADD_BASIC_BLOCK(len_le_zero, "len_le_zero"); + MOVE_BLOCK_AFTER(len_le_zero, len_gt_zero); + + BUILD_ICMP(LLVMIntSGT, len, I32_ZERO, cmp[0], "cmp_len"); + BUILD_COND_BR(cmp[0], len_gt_zero, len_le_zero); + + /* Move builder to len > 0 block */ + SET_BUILDER_POS(len_gt_zero); + /* dst_offset > UINT32_MAX - len */ + if (!(boundary = LLVMBuildAdd(comp_ctx->builder, offset, len, ""))) { + aot_set_last_error("llvm build failed."); + goto fail; + } + BUILD_ICMP(LLVMIntUGT, boundary, I32_CONST(UINT32_MAX), cmp[0], + "boundary_check1"); + /* dst_offset + len > wasm_array_obj_length(dst_obj) */ + if (!aot_array_obj_length(comp_ctx, array_obj, &array_len)) + goto fail; + BUILD_ICMP(LLVMIntUGT, boundary, array_len, cmp[1], "boundary_check2"); + + if (!(cmp[0] = LLVMBuildOr(comp_ctx->builder, cmp[0], cmp[1], ""))) { + aot_set_last_error("llvm build failed."); + goto fail; + } + + if (!aot_emit_exception(comp_ctx, func_ctx, EXCE_ARRAY_IDX_OOB, true, + cmp[0], inner_else)) + goto fail; + + if (!(loop_counter_addr = LLVMBuildAlloca(comp_ctx->builder, I32_TYPE, + "fill_loop_counter"))) { + aot_set_last_error("llvm build alloc failed."); + goto fail; + } + + if (!is_target_x86(comp_ctx)) { + LLVMSetAlignment(loop_counter_addr, 4); + } + + if (!LLVMBuildStore(comp_ctx->builder, offset, loop_counter_addr)) { + aot_set_last_error("llvm build store failed."); + goto fail; + } + + BUILD_BR(fill_loop_header); + SET_BUILDER_POS(fill_loop_header); + + if (!(loop_counter_val = + LLVMBuildLoad2(comp_ctx->builder, I32_TYPE, loop_counter_addr, + "fill_loop_counter"))) { + aot_set_last_error("llvm build load failed."); + goto fail; + } + + BUILD_ICMP(LLVMIntULT, loop_counter_val, boundary, cmp[0], + "cmp_loop_counter"); + BUILD_COND_BR(cmp[0], fill_loop_body, len_le_zero); + + SET_BUILDER_POS(fill_loop_body); + + if (!aot_array_obj_set_elem(comp_ctx, func_ctx, array_obj, loop_counter_val, + fill_value, array_elem_type)) + goto fail; + + if (!(loop_counter_val = LLVMBuildAdd(comp_ctx->builder, loop_counter_val, + I32_ONE, "fill_loop_counter"))) { + aot_set_last_error("llvm build add failed."); + goto fail; + } + + if (!LLVMBuildStore(comp_ctx->builder, loop_counter_val, + loop_counter_addr)) { + aot_set_last_error("llvm build store failed."); + goto fail; + } + + BUILD_BR(fill_loop_header); + + SET_BUILDER_POS(len_le_zero); + + return true; +fail: + return false; +} + +static bool +aot_call_wasm_array_obj_copy(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + LLVMValueRef dst_obj, LLVMValueRef dst_offset, + LLVMValueRef src_obj, LLVMValueRef src_offset, + LLVMValueRef len) +{ + LLVMValueRef param_values[5], func, value; + LLVMTypeRef param_types[5], ret_type, func_type, func_ptr_type; + + param_types[0] = GC_REF_TYPE; + param_types[1] = I32_TYPE; + param_types[2] = GC_REF_TYPE; + param_types[3] = I32_TYPE; + param_types[4] = I32_TYPE; + ret_type = VOID_TYPE; + + GET_AOT_FUNCTION(wasm_array_obj_copy, 5); + + /* Call function wasm_array_obj_copy() */ + param_values[0] = dst_obj; + param_values[1] = dst_offset; + param_values[2] = src_obj; + param_values[3] = src_offset; + param_values[4] = len; + if (!LLVMBuildCall2(comp_ctx->builder, func_type, func, param_values, 5, + "")) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + + return true; +fail: + return false; +} + +bool +aot_compile_op_array_copy(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 type_index, uint32 src_type_index) +{ + LLVMValueRef len, src_offset, src_obj, dst_offset, dst_obj, array_len, + cmp[4], boundary; + LLVMBasicBlockRef check_objs_succ, len_gt_zero, len_le_zero, inner_else; + int i; + + POP_I32(len); + POP_I32(src_offset); + POP_GC_REF(src_obj); + POP_I32(dst_offset); + POP_GC_REF(dst_obj); + + ADD_BASIC_BLOCK(check_objs_succ, "check array objs succ"); + MOVE_BLOCK_AFTER_CURR(check_objs_succ); + + BUILD_ISNULL(src_obj, cmp[0], "cmp_src_obj"); + BUILD_ISNULL(dst_obj, cmp[1], "cmp_dst_obj"); + + /* src_obj is null or dst_obj is null, throw exception */ + if (!(cmp[0] = LLVMBuildOr(comp_ctx->builder, cmp[0], cmp[1], ""))) { + aot_set_last_error("llvm build or failed."); + goto fail; + } + + if (!aot_emit_exception(comp_ctx, func_ctx, EXCE_NULL_ARRAY_OBJ, true, + cmp[0], check_objs_succ)) + goto fail; + + /* Create if block */ + ADD_BASIC_BLOCK(len_gt_zero, "len_gt_zero"); + MOVE_BLOCK_AFTER_CURR(len_gt_zero); + + /* Create else(end) block */ + ADD_BASIC_BLOCK(len_le_zero, "len_le_zero"); + MOVE_BLOCK_AFTER(len_le_zero, len_gt_zero); + + /* Create inner else block */ + ADD_BASIC_BLOCK(inner_else, "inner_else"); + MOVE_BLOCK_AFTER(inner_else, len_gt_zero); + + BUILD_ICMP(LLVMIntSGT, len, I32_ZERO, cmp[0], "cmp_len"); + BUILD_COND_BR(cmp[0], len_gt_zero, len_le_zero); + + /* Move builder to len > 0 block */ + SET_BUILDER_POS(len_gt_zero); + /* dst_offset > UINT32_MAX - len */ + if (!(boundary = LLVMBuildAdd(comp_ctx->builder, dst_offset, len, ""))) { + aot_set_last_error("llvm build failed."); + goto fail; + } + BUILD_ICMP(LLVMIntUGT, boundary, I32_CONST(UINT32_MAX), cmp[0], + "boundary_check1"); + /* dst_offset + len > wasm_array_obj_length(dst_obj) */ + if (!aot_array_obj_length(comp_ctx, dst_obj, &array_len)) + goto fail; + BUILD_ICMP(LLVMIntUGT, boundary, array_len, cmp[1], "boundary_check2"); + /* src_offset > UINT32_MAX - len */ + if (!(boundary = LLVMBuildAdd(comp_ctx->builder, src_offset, len, ""))) { + aot_set_last_error("llvm build failed."); + goto fail; + } + BUILD_ICMP(LLVMIntUGT, boundary, I32_CONST(UINT32_MAX), cmp[2], + "boundary_check3"); + /* src_offset + len > wasm_array_obj_length(src_obj) */ + if (!aot_array_obj_length(comp_ctx, src_obj, &array_len)) + goto fail; + BUILD_ICMP(LLVMIntUGT, boundary, array_len, cmp[3], "boundary_check4"); + + /* logical or above 4 boundary checks */ + for (i = 1; i < 4; ++i) { + if (!(cmp[0] = LLVMBuildOr(comp_ctx->builder, cmp[0], cmp[i], ""))) { + aot_set_last_error("llvm build failed."); + goto fail; + } + } + + if (!aot_emit_exception(comp_ctx, func_ctx, EXCE_ARRAY_IDX_OOB, true, + cmp[0], inner_else)) + goto fail; + + if (!aot_call_wasm_array_obj_copy(comp_ctx, func_ctx, dst_obj, dst_offset, + src_obj, src_offset, len)) + goto fail; + + BUILD_BR(len_le_zero); + SET_BUILDER_POS(len_le_zero); + + return true; +fail: + return false; +} + +bool +aot_compile_op_array_len(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) +{ + LLVMValueRef array_obj, cmp, array_len; + LLVMBasicBlockRef check_array_obj_succ; + + POP_GC_REF(array_obj); + + ADD_BASIC_BLOCK(check_array_obj_succ, "check array obj succ"); + MOVE_BLOCK_AFTER_CURR(check_array_obj_succ); + + BUILD_ISNULL(array_obj, cmp, "cmp_array_obj"); + if (!aot_emit_exception(comp_ctx, func_ctx, EXCE_NULL_ARRAY_OBJ, true, cmp, + check_array_obj_succ)) + goto fail; + + if (!aot_array_obj_length(comp_ctx, array_obj, &array_len)) + goto fail; + + PUSH_I32(array_len); + + return true; +fail: + return false; +} + +bool +aot_compile_op_i31_new(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) +{ + LLVMValueRef i31_val, i31_obj; + + POP_I32(i31_val); + + /* i31_val <<= 1 */ + if (!(i31_val = LLVMBuildShl(comp_ctx->builder, i31_val, I32_ONE, + "i31_val_shl"))) { + aot_set_last_error("llvm build shl failed."); + goto fail; + } + + /* i31_val |= 1 */ + if (!(i31_val = + LLVMBuildOr(comp_ctx->builder, i31_val, I32_ONE, "i31_val_or"))) { + aot_set_last_error("llvm build or failed."); + goto fail; + } + + if (!(i31_obj = LLVMBuildIntToPtr(comp_ctx->builder, i31_val, GC_REF_TYPE, + "i31_obj"))) { + aot_set_last_error("llvm build bit cast failed."); + goto fail; + } + + PUSH_GC_REF(i31_obj); + + return true; +fail: + return false; +} + +bool +aot_compile_op_i31_get(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + bool sign) +{ + LLVMValueRef i31_obj, i31_val, cmp_i31_obj; + LLVMBasicBlockRef check_i31_obj_succ; + + POP_GC_REF(i31_obj); + + ADD_BASIC_BLOCK(check_i31_obj_succ, "check_i31_obj_succ"); + MOVE_BLOCK_AFTER_CURR(check_i31_obj_succ); + + /* Check if i31 object is NULL, throw exception if it is */ + BUILD_ISNULL(i31_obj, cmp_i31_obj, "cmp_i31_obj"); + if (!aot_emit_exception(comp_ctx, func_ctx, EXCE_NULL_I31_OBJ, true, + cmp_i31_obj, check_i31_obj_succ)) { + goto fail; + } + + if (!(i31_val = LLVMBuildPtrToInt(comp_ctx->builder, i31_obj, I32_TYPE, + "i31_val"))) { + aot_set_last_error("llvm build ptr to init failed."); + goto fail; + } + + if (!sign) { + if (!(i31_val = LLVMBuildLShr(comp_ctx->builder, i31_val, I32_ONE, + "i31_value"))) { + aot_set_last_error("llvm build lshr failed."); + goto fail; + } + } + else { + if (!(i31_val = LLVMBuildAShr(comp_ctx->builder, i31_val, I32_ONE, + "i31_value"))) { + aot_set_last_error("llvm build ashr failed."); + goto fail; + } + } + + PUSH_I32(i31_val); + + return true; +fail: + return false; +} + +bool +aot_compile_op_ref_test(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + int32 heap_type, bool nullable) +{ + LLVMValueRef gc_obj, ref_test_phi, cmp, castable; + LLVMBasicBlockRef block_curr, block_obj_non_null, block_end; + + POP_GC_REF(gc_obj); + + block_curr = CURR_BLOCK(); + + /* Create non-null object block */ + ADD_BASIC_BLOCK(block_obj_non_null, "non_null_obj"); + MOVE_BLOCK_AFTER_CURR(block_obj_non_null); + + /* Create end block */ + ADD_BASIC_BLOCK(block_end, "ref_test_end"); + MOVE_BLOCK_AFTER(block_end, block_obj_non_null); + + /* Create ref test result phi */ + SET_BUILDER_POS(block_end); + if (!(ref_test_phi = + LLVMBuildPhi(comp_ctx->builder, INT1_TYPE, "ref_test_res"))) { + aot_set_last_error("llvm build phi failed"); + return false; + } + + /* Check if gc object is NULL */ + SET_BUILDER_POS(block_curr); + BUILD_ISNULL(gc_obj, cmp, "cmp_gc_obj"); + BUILD_COND_BR(cmp, block_end, block_obj_non_null); + + if (nullable) + LLVMAddIncoming(ref_test_phi, &I1_ONE, &block_curr, 1); + else + LLVMAddIncoming(ref_test_phi, &I1_ZERO, &block_curr, 1); + + /* Move builder to non-null object block */ + SET_BUILDER_POS(block_obj_non_null); + + if (heap_type >= 0) { + if (!aot_call_aot_obj_is_instance_of(comp_ctx, func_ctx, gc_obj, + I32_CONST(heap_type), &castable)) + return false; + } + else { + if (!aot_call_wasm_obj_is_type_of(comp_ctx, func_ctx, gc_obj, + I32_CONST(heap_type), &castable)) + return false; + } + + if (!(castable = LLVMBuildICmp(comp_ctx->builder, LLVMIntNE, castable, + I8_ZERO, "castable"))) { + aot_set_last_error("llvm build icmp failed."); + return false; + } + + BUILD_BR(block_end); + LLVMAddIncoming(ref_test_phi, &castable, &block_obj_non_null, 1); + + SET_BUILDER_POS(block_end); + PUSH_COND(ref_test_phi); + + return true; +fail: + return false; +} + +bool +aot_compile_op_ref_cast(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + int32 heap_type, bool nullable) +{ + LLVMValueRef gc_obj, cmp, castable; + LLVMBasicBlockRef block_obj_non_null, block_end; + + GET_GC_REF_FROM_STACK(gc_obj); + + /* Create non null block */ + ADD_BASIC_BLOCK(block_obj_non_null, "non_null_obj"); + MOVE_BLOCK_AFTER_CURR(block_obj_non_null); + + /* Create end block */ + ADD_BASIC_BLOCK(block_end, "ref_cast_end"); + MOVE_BLOCK_AFTER(block_end, block_obj_non_null); + + BUILD_ISNULL(gc_obj, cmp, "obj_is_null"); + if (nullable) { + BUILD_COND_BR(cmp, block_end, block_obj_non_null); + } + else { + if (!aot_emit_exception(comp_ctx, func_ctx, EXCE_CAST_FAILURE, true, + cmp, block_obj_non_null)) { + return false; + } + } + + SET_BUILDER_POS(block_obj_non_null); + + if (heap_type >= 0) { + if (!aot_call_aot_obj_is_instance_of(comp_ctx, func_ctx, gc_obj, + I32_CONST(heap_type), &castable)) + return false; + } + else { + if (!aot_call_wasm_obj_is_type_of(comp_ctx, func_ctx, gc_obj, + I32_CONST(heap_type), &castable)) + return false; + } + + if (!(cmp = LLVMBuildICmp(comp_ctx->builder, LLVMIntEQ, castable, I8_ZERO, + "is_uncastable"))) { + aot_set_last_error("llvm build not failed"); + return false; + } + + if (!aot_emit_exception(comp_ctx, func_ctx, EXCE_CAST_FAILURE, true, cmp, + block_end)) { + return false; + } + + SET_BUILDER_POS(block_end); + + return true; +fail: + return false; +} + +static bool +aot_call_wasm_externref_obj_to_internal_obj(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx, + LLVMValueRef externref_obj, + LLVMValueRef *gc_obj) +{ + LLVMValueRef param_values[1], func, value, res; + LLVMTypeRef param_types[1], ret_type, func_type, func_ptr_type; + + param_types[0] = GC_REF_TYPE; + ret_type = GC_REF_TYPE; + + GET_AOT_FUNCTION(wasm_externref_obj_to_internal_obj, 1); + + /* Call function wasm_externref_obj_to_internal_obj */ + param_values[0] = externref_obj; + if (!(res = LLVMBuildCall2(comp_ctx->builder, func_type, func, param_values, + 1, "call"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + + *gc_obj = res; + + return true; +fail: + return false; +} + +bool +aot_compile_op_extern_internalize(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx) +{ + LLVMValueRef externref_obj, gc_obj, cmp, internal_obj_phi; + LLVMBasicBlockRef block_curr, block_obj_non_null, block_end; + + POP_GC_REF(externref_obj); + + block_curr = CURR_BLOCK(); + + /* Create non-null object block */ + ADD_BASIC_BLOCK(block_obj_non_null, "non_null_obj"); + MOVE_BLOCK_AFTER_CURR(block_obj_non_null); + + /* Create end block */ + ADD_BASIC_BLOCK(block_end, "internalize_end"); + MOVE_BLOCK_AFTER(block_end, block_obj_non_null); + + /* Create internalized object phi */ + SET_BUILDER_POS(block_end); + if (!(internal_obj_phi = + LLVMBuildPhi(comp_ctx->builder, GC_REF_TYPE, "internal_obj"))) { + aot_set_last_error("llvm build phi failed"); + return false; + } + + /* Check if externref object is NULL */ + SET_BUILDER_POS(block_curr); + BUILD_ISNULL(externref_obj, cmp, "cmp_externref_obj"); + BUILD_COND_BR(cmp, block_end, block_obj_non_null); + LLVMAddIncoming(internal_obj_phi, &GC_REF_NULL, &block_curr, 1); + + /* Move builder to non-null object block */ + SET_BUILDER_POS(block_obj_non_null); + if (!aot_call_wasm_externref_obj_to_internal_obj(comp_ctx, func_ctx, + externref_obj, &gc_obj)) { + return false; + } + BUILD_BR(block_end); + LLVMAddIncoming(internal_obj_phi, &gc_obj, &block_obj_non_null, 1); + + /* Move builder to end block */ + SET_BUILDER_POS(block_end); + PUSH_GC_REF(internal_obj_phi); + + return true; +fail: + return false; +} + +static bool +aot_call_wasm_internal_obj_to_external_obj(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx, + LLVMValueRef gc_obj, + LLVMValueRef *externref_obj) +{ + LLVMValueRef param_values[2], func, value, res; + LLVMTypeRef param_types[2], ret_type, func_type, func_ptr_type; + + param_types[0] = INT8_PTR_TYPE; + param_types[1] = GC_REF_TYPE; + ret_type = GC_REF_TYPE; + + GET_AOT_FUNCTION(wasm_internal_obj_to_externref_obj, 2); + + /* Call function wasm_internal_obj_to_externref_obj() */ + param_values[0] = func_ctx->exec_env; + param_values[1] = gc_obj; + if (!(res = LLVMBuildCall2(comp_ctx->builder, func_type, func, param_values, + 2, "call"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + + *externref_obj = res; + + return true; +fail: + return false; +} + +bool +aot_compile_op_extern_externalize(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx) +{ + LLVMValueRef gc_obj, cmp, external_obj_phi, externref_obj; + LLVMBasicBlockRef block_curr, block_obj_non_null, block_end; + + if (!aot_gen_commit_values(comp_ctx->aot_frame)) + return false; + + if (!aot_gen_commit_sp_ip(comp_ctx->aot_frame, true, true)) + return false; + + POP_GC_REF(gc_obj); + + block_curr = CURR_BLOCK(); + + /* Create non-null object block */ + ADD_BASIC_BLOCK(block_obj_non_null, "non_null_obj"); + MOVE_BLOCK_AFTER_CURR(block_obj_non_null); + + /* Create end block */ + ADD_BASIC_BLOCK(block_end, "externalize_end"); + MOVE_BLOCK_AFTER(block_end, block_obj_non_null); + + /* Create externalized object phi */ + SET_BUILDER_POS(block_end); + if (!(external_obj_phi = + LLVMBuildPhi(comp_ctx->builder, GC_REF_TYPE, "external_obj"))) { + aot_set_last_error("llvm build phi failed"); + return false; + } + + /* Check if gc object is NULL */ + SET_BUILDER_POS(block_curr); + BUILD_ISNULL(gc_obj, cmp, "cmp_gc_obj"); + BUILD_COND_BR(cmp, block_end, block_obj_non_null); + LLVMAddIncoming(external_obj_phi, &GC_REF_NULL, &block_curr, 1); + + /* Move builder to non-null object block */ + SET_BUILDER_POS(block_obj_non_null); + + if (!aot_call_wasm_internal_obj_to_external_obj(comp_ctx, func_ctx, gc_obj, + &externref_obj)) { + return false; + } + + /* Check whether failed to externalize */ + BUILD_ISNULL(externref_obj, cmp, "cmp_externref_obj"); + if (!aot_emit_exception(comp_ctx, func_ctx, + EXCE_FAILED_TO_CREATE_EXTERNREF_OBJ, true, cmp, + block_end)) { + return false; + } + + LLVMAddIncoming(external_obj_phi, &externref_obj, &block_obj_non_null, 1); + + /* Move builder to end block */ + SET_BUILDER_POS(block_end); + PUSH_GC_REF(external_obj_phi); + + return true; +fail: + return false; +} + +#endif /* end of WASM_ENABLE_GC != 0 */ diff --git a/core/iwasm/compilation/aot_emit_gc.h b/core/iwasm/compilation/aot_emit_gc.h new file mode 100644 index 000000000..40a3c2360 --- /dev/null +++ b/core/iwasm/compilation/aot_emit_gc.h @@ -0,0 +1,119 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef _AOT_EMIT_GC_H_ +#define _AOT_EMIT_GC_H_ + +#include "aot_compiler.h" +#include "aot_runtime.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if WASM_ENABLE_GC != 0 + +bool +aot_call_aot_create_func_obj(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + LLVMValueRef func_idx, LLVMValueRef *p_gc_obj); + +bool +aot_call_aot_obj_is_instance_of(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx, LLVMValueRef gc_obj, + LLVMValueRef heap_type, LLVMValueRef *castable); + +bool +aot_call_wasm_obj_is_type_of(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + LLVMValueRef gc_obj, LLVMValueRef heap_type, + LLVMValueRef *castable); + +bool +aot_call_aot_rtt_type_new(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + LLVMValueRef type_index, LLVMValueRef *rtt_type); + +bool +aot_compile_op_ref_as_non_null(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx); + +bool +aot_compile_op_struct_new(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 type_index, bool init_with_default); + +bool +aot_compile_op_struct_get(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 type_index, uint32 field_idx, bool sign); + +bool +aot_compile_op_struct_set(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 type_index, uint32 field_idx); + +bool +aot_compile_op_array_new(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 type_index, bool init_with_default, + bool fixed_size, uint32 array_len); + +bool +aot_compile_op_array_new_data(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx, uint32 type_index, + uint32 data_seg_index); + +bool +aot_array_obj_length(AOTCompContext *comp_ctx, LLVMValueRef array_obj, + LLVMValueRef *p_array_len); + +bool +aot_array_obj_elem_addr(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + LLVMValueRef array_obj, LLVMValueRef elem_idx, + LLVMValueRef *p_elem_data, uint8 array_elem_type); + +bool +aot_compile_op_array_get(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 type_index, bool sign); + +bool +aot_compile_op_array_set(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 type_index); + +bool +aot_compile_op_array_fill(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 type_index); + +bool +aot_compile_op_array_copy(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 type_index, uint32 src_type_index); + +bool +aot_compile_op_array_len(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx); + +bool +aot_compile_op_i31_new(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx); + +bool +aot_compile_op_i31_get(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + bool sign); + +bool +aot_compile_op_ref_test(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + int32 heap_type, bool nullable); + +bool +aot_compile_op_ref_cast(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + int32 heap_type, bool nullable); + +bool +aot_compile_op_extern_internalize(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx); + +bool +aot_compile_op_extern_externalize(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx); + +#endif + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif + +#endif /* end of _AOT_EMIT_GC_H_ */ diff --git a/core/iwasm/compilation/aot_emit_memory.c b/core/iwasm/compilation/aot_emit_memory.c index 8c35c3fe6..fc9952de0 100644 --- a/core/iwasm/compilation/aot_emit_memory.c +++ b/core/iwasm/compilation/aot_emit_memory.c @@ -338,7 +338,7 @@ fail: } \ } while (0) -#if WASM_ENABLE_SHARED_MEMORY != 0 +#if WASM_ENABLE_SHARED_MEMORY != 0 || WASM_ENABLE_STRINGREF != 0 bool check_memory_alignment(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, LLVMValueRef addr, uint32 align) @@ -376,7 +376,9 @@ check_memory_alignment(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, fail: return false; } +#endif /* WASM_ENABLE_SHARED_MEMORY != 0 || WASM_ENABLE_STRINGREF != 0 */ +#if WASM_ENABLE_SHARED_MEMORY != 0 #define BUILD_ATOMIC_LOAD(align, data_type) \ do { \ if (!(check_memory_alignment(comp_ctx, func_ctx, maddr, align))) { \ @@ -874,9 +876,8 @@ fail: return false; } -#if WASM_ENABLE_BULK_MEMORY != 0 - -static LLVMValueRef +#if WASM_ENABLE_BULK_MEMORY != 0 || WASM_ENABLE_STRINGREF != 0 +LLVMValueRef check_bulk_memory_overflow(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, LLVMValueRef offset, LLVMValueRef bytes) { @@ -971,7 +972,9 @@ check_bulk_memory_overflow(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, fail: return NULL; } +#endif /* end of WASM_ENABLE_BULK_MEMORY != 0 or WASM_ENABLE_STRINGREF != 0 */ +#if WASM_ENABLE_BULK_MEMORY != 0 bool aot_compile_op_memory_init(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, uint32 seg_index) @@ -1501,13 +1504,11 @@ aot_compile_op_atomic_wait(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, PUSH_I32(ret_value); -#if WASM_ENABLE_THREAD_MGR != 0 /* Insert suspend check point */ if (comp_ctx->enable_thread_mgr) { - if (!check_suspend_flags(comp_ctx, func_ctx)) + if (!check_suspend_flags(comp_ctx, func_ctx, false)) return false; } -#endif return true; fail: diff --git a/core/iwasm/compilation/aot_emit_memory.h b/core/iwasm/compilation/aot_emit_memory.h index 1c2db503a..e174aa3de 100644 --- a/core/iwasm/compilation/aot_emit_memory.h +++ b/core/iwasm/compilation/aot_emit_memory.h @@ -61,6 +61,14 @@ aot_compile_op_memory_size(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx); bool aot_compile_op_memory_grow(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx); +bool +check_memory_alignment(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + LLVMValueRef addr, uint32 align); + +LLVMValueRef +check_bulk_memory_overflow(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + LLVMValueRef offset, LLVMValueRef bytes); + #if WASM_ENABLE_BULK_MEMORY != 0 bool aot_compile_op_memory_init(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, diff --git a/core/iwasm/compilation/aot_emit_parametric.c b/core/iwasm/compilation/aot_emit_parametric.c index 8b1a9e6da..198e04522 100644 --- a/core/iwasm/compilation/aot_emit_parametric.c +++ b/core/iwasm/compilation/aot_emit_parametric.c @@ -21,8 +21,8 @@ pop_value_from_wasm_stack(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, return false; } - aot_value = - aot_value_stack_pop(&func_ctx->block_stack.block_list_end->value_stack); + aot_value = aot_value_stack_pop( + comp_ctx, &func_ctx->block_stack.block_list_end->value_stack); type = aot_value->type; if (aot_value->type == VALUE_TYPE_I1) { @@ -44,19 +44,34 @@ pop_value_from_wasm_stack(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, wasm_runtime_free(aot_value); - /* is_32: i32, f32, ref.func, ref.extern, v128 */ - if (is_32 - && !(type == VALUE_TYPE_I32 || type == VALUE_TYPE_F32 - || type == VALUE_TYPE_FUNCREF || type == VALUE_TYPE_EXTERNREF - || type == VALUE_TYPE_V128)) { - aot_set_last_error("invalid WASM stack data type."); - return false; + if (is_32) { + /* is_32: i32, f32, ref.func, ref.extern, v128, + or GC ref types */ + if (!(type == VALUE_TYPE_I32 || type == VALUE_TYPE_F32 + || type == VALUE_TYPE_V128 + || (comp_ctx->enable_ref_types + && (type == VALUE_TYPE_FUNCREF + || type == VALUE_TYPE_EXTERNREF)) +#if WASM_ENABLE_GC != 0 + || (comp_ctx->enable_gc && type == VALUE_TYPE_GC_REF) +#endif + )) { + aot_set_last_error("invalid WASM stack data type."); + return false; + } } - - /* !is_32: i64, f64 */ - if (!is_32 && !(type == VALUE_TYPE_I64 || type == VALUE_TYPE_F64)) { - aot_set_last_error("invalid WASM stack data type."); - return false; + else { + /* !is_32: i64, f64, or GC ref types */ + if (!(type == VALUE_TYPE_I64 || type == VALUE_TYPE_F64 +#if WASM_ENABLE_GC != 0 + || (comp_ctx->enable_gc && type == VALUE_TYPE_GC_REF) + /* may be i32 which denotes funcref/externref */ + || (!comp_ctx->enable_gc && type == VALUE_TYPE_I32) +#endif + )) { + aot_set_last_error("invalid WASM stack data type."); + return false; + } } return true; diff --git a/core/iwasm/compilation/aot_emit_stringref.c b/core/iwasm/compilation/aot_emit_stringref.c new file mode 100644 index 000000000..1642cee00 --- /dev/null +++ b/core/iwasm/compilation/aot_emit_stringref.c @@ -0,0 +1,1443 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#if WASM_ENABLE_STRINGREF != 0 + +#include "aot_emit_stringref.h" +#include "aot_emit_exception.h" +#include "aot_emit_memory.h" +#include "aot_emit_gc.h" +#include "aot.h" +#include "aot_compiler.h" +#include "aot_emit_memory.h" +#include "gc_object.h" +#include "string_object.h" + +#define BUILD_ISNULL(ptr, res, name) \ + do { \ + if (!(res = LLVMBuildIsNull(comp_ctx->builder, ptr, name))) { \ + aot_set_last_error("llvm build isnull failed."); \ + goto fail; \ + } \ + } while (0) + +#define BUILD_ISNOTNULL(ptr, res, name) \ + do { \ + if (!(res = LLVMBuildIsNotNull(comp_ctx->builder, ptr, name))) { \ + aot_set_last_error("llvm build isnotnull failed."); \ + goto fail; \ + } \ + } while (0) + +#define ADD_BASIC_BLOCK(block, name) \ + do { \ + if (!(block = LLVMAppendBasicBlockInContext(comp_ctx->context, \ + func_ctx->func, name))) { \ + aot_set_last_error("llvm add basic block failed."); \ + goto fail; \ + } \ + } while (0) + +#define CURR_BLOCK() LLVMGetInsertBlock(comp_ctx->builder) + +#define MOVE_BLOCK_AFTER(llvm_block, llvm_block_after) \ + LLVMMoveBasicBlockAfter(llvm_block, llvm_block_after) + +#define MOVE_BLOCK_AFTER_CURR(llvm_block) \ + LLVMMoveBasicBlockAfter(llvm_block, CURR_BLOCK()) + +#define DEFINE_STRINGREF_CHECK_VAR() \ + LLVMBasicBlockRef check_string_obj_succ, check_stringref_obj_succ; \ + LLVMValueRef cmp + +#define CHECK_STRING_OBJ(str_obj) \ + do { \ + ADD_BASIC_BLOCK(check_string_obj_succ, "check string obj succ"); \ + MOVE_BLOCK_AFTER_CURR(check_string_obj_succ); \ + \ + BUILD_ISNULL(str_obj, cmp, "cmp_string_obj"); \ + if (!aot_emit_exception(comp_ctx, func_ctx, \ + EXCE_FAILED_TO_CREATE_STRING, true, cmp, \ + check_string_obj_succ)) \ + goto fail; \ + } while (0) + +#define CHECK_STRINGREF_INTERNAL(stringref_obj, exce_id, name) \ + do { \ + ADD_BASIC_BLOCK(check_stringref_obj_succ, "check " name " obj succ"); \ + MOVE_BLOCK_AFTER(check_stringref_obj_succ, check_string_obj_succ); \ + \ + BUILD_ISNULL(stringref_obj, cmp, "cmp_" name "_obj"); \ + if (!aot_emit_exception(comp_ctx, func_ctx, exce_id, true, cmp, \ + check_stringref_obj_succ)) \ + goto fail; \ + } while (0) + +#define CHECK_STRINGREF_OBJ(stringref_obj) \ + CHECK_STRINGREF_INTERNAL(stringref_obj, EXCE_FAILED_TO_CREATE_STRINGREF, \ + "stringref") + +#define CHECK_STRINGVIEW_OBJ(stringview_obj) \ + CHECK_STRINGREF_INTERNAL(stringview_obj, EXCE_FAILED_TO_CREATE_STRINGVIEW, \ + "stringview") + +#define CHECK_STRING_ENCODE(value) \ + do { \ + ADD_BASIC_BLOCK(check_string_encode_succ, "check string encode succ"); \ + MOVE_BLOCK_AFTER_CURR(check_string_encode_succ); \ + \ + if (!(cmp = LLVMBuildICmp(comp_ctx->builder, LLVMIntSLT, value, \ + I32_ZERO, "cmp_string_encode"))) { \ + aot_set_last_error("llvm build icmp failed."); \ + goto fail; \ + } \ + \ + if (!aot_emit_exception(comp_ctx, func_ctx, \ + EXCE_FAILED_TO_ENCODE_STRING, true, cmp, \ + check_string_encode_succ)) \ + goto fail; \ + } while (0) + +static bool +aot_call_wasm_stringref_obj_new(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx, LLVMValueRef str_obj, + uint32 stringref_type, uint32 pos, + LLVMValueRef *stringref_obj) +{ + LLVMValueRef param_values[3], func, value, res; + LLVMTypeRef param_types[3], ret_type, func_type, func_ptr_type; + uint32 argc = 2; + + param_types[0] = INT8_PTR_TYPE; + param_types[1] = INT8_PTR_TYPE; + param_types[2] = I32_TYPE; + ret_type = INT8_PTR_TYPE; + + if (stringref_type == WASM_TYPE_STRINGREF) { + GET_AOT_FUNCTION(wasm_stringref_obj_new, argc); + } + else if (stringref_type == WASM_TYPE_STRINGVIEWWTF8) { + GET_AOT_FUNCTION(wasm_stringview_wtf8_obj_new, argc); + } + else if (stringref_type == WASM_TYPE_STRINGVIEWWTF16) { + GET_AOT_FUNCTION(wasm_stringview_wtf16_obj_new, argc); + } + else { + argc = 3; + GET_AOT_FUNCTION(wasm_stringview_iter_obj_new, argc); + } + + param_values[0] = func_ctx->exec_env; + param_values[1] = str_obj; + if (stringref_type == WASM_TYPE_STRINGVIEWITER) { + param_values[2] = I32_CONST(pos); + } + + if (!(res = LLVMBuildCall2(comp_ctx->builder, func_type, func, param_values, + argc, "create_stringref"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + + *stringref_obj = res; + + return true; +fail: + return false; +} + +static LLVMValueRef +aot_stringref_obj_get_value(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + LLVMValueRef stringref_obj) +{ + LLVMValueRef str_obj_ptr, str_obj, host_ptr_offset; + + /* header */ + host_ptr_offset = I32_CONST(comp_ctx->pointer_size); + + if (!(stringref_obj = + LLVMBuildBitCast(comp_ctx->builder, stringref_obj, INT8_PTR_TYPE, + "stringref_obj_i8p"))) { + aot_set_last_error("llvm build bitcast failed."); + goto fail; + } + + if (!(str_obj_ptr = + LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, stringref_obj, + &host_ptr_offset, 1, "str_obj_i8p"))) { + aot_set_last_error("llvm build gep failed."); + goto fail; + } + + if (!(str_obj_ptr = LLVMBuildBitCast(comp_ctx->builder, str_obj_ptr, + GC_REF_PTR_TYPE, "str_obj_gcref_p"))) { + aot_set_last_error("llvm build bitcast failed."); + goto fail; + } + + if (!(str_obj = LLVMBuildLoad2(comp_ctx->builder, GC_REF_TYPE, str_obj_ptr, + "str_obj"))) { + aot_set_last_error("llvm build load failed."); + goto fail; + } + + LLVMSetAlignment(str_obj, 4); + + return str_obj; + +fail: + return NULL; +} + +static LLVMValueRef +get_stringview_iter_pos_addr(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + LLVMValueRef stringview_iter_obj) +{ + LLVMValueRef iter_pos_ptr, host_ptr_offset; + + /* header + str_obj */ + host_ptr_offset = I32_CONST(comp_ctx->pointer_size * 2); + + if (!(stringview_iter_obj = + LLVMBuildBitCast(comp_ctx->builder, stringview_iter_obj, + INT8_PTR_TYPE, "stringview_iter_obj_i8p"))) { + aot_set_last_error("llvm build bitcast failed."); + goto fail; + } + + if (!(iter_pos_ptr = LLVMBuildInBoundsGEP2( + comp_ctx->builder, INT8_TYPE, stringview_iter_obj, + &host_ptr_offset, 1, "iter_pos_i8p"))) { + aot_set_last_error("llvm build gep failed."); + goto fail; + } + + if (!(iter_pos_ptr = LLVMBuildBitCast(comp_ctx->builder, iter_pos_ptr, + INT32_PTR_TYPE, "iter_pos_i32p"))) { + aot_set_last_error("llvm build bitcast failed."); + goto fail; + } + + return iter_pos_ptr; + +fail: + return NULL; +} + +static LLVMValueRef +aot_call_wasm_string_measure(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + LLVMValueRef stringref_obj, uint32 encoding) +{ + LLVMValueRef param_values[3], func, value, str_obj; + LLVMTypeRef param_types[3], ret_type, func_type, func_ptr_type; + + if (!(str_obj = + aot_stringref_obj_get_value(comp_ctx, func_ctx, stringref_obj))) { + goto fail; + } + + param_types[0] = INT8_PTR_TYPE; + param_types[1] = I32_TYPE; + ret_type = I32_TYPE; + + GET_AOT_FUNCTION(wasm_string_measure, 2); + + /* Call function wasm_string_measure() */ + param_values[0] = str_obj; + param_values[1] = I32_CONST(encoding); + + if (!(value = LLVMBuildCall2(comp_ctx->builder, func_type, func, + param_values, 2, "string_measure"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + + return value; +fail: + return NULL; +} + +static LLVMValueRef +aot_call_wasm_string_create_view(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx, + LLVMValueRef stringref_obj, uint32 encoding) +{ + LLVMValueRef param_values[3], func, value, str_obj; + LLVMTypeRef param_types[3], ret_type, func_type, func_ptr_type; + + if (!(str_obj = + aot_stringref_obj_get_value(comp_ctx, func_ctx, stringref_obj))) { + goto fail; + } + + param_types[0] = INT8_PTR_TYPE; + param_types[1] = I32_TYPE; + ret_type = INT8_PTR_TYPE; + + GET_AOT_FUNCTION(wasm_string_create_view, 2); + + /* Call function wasm_string_create_view() */ + param_values[0] = str_obj; + param_values[1] = I32_CONST(encoding); + + if (!(value = LLVMBuildCall2(comp_ctx->builder, func_type, func, + param_values, 2, "string_create_view"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + + return value; +fail: + return NULL; +} + +static LLVMValueRef +aot_call_wasm_string_advance(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + LLVMValueRef stringref_obj, LLVMValueRef bytes, + LLVMValueRef pos) +{ + LLVMValueRef param_values[4], func, value, str_obj; + LLVMTypeRef param_types[4], ret_type, func_type, func_ptr_type; + + if (!(str_obj = + aot_stringref_obj_get_value(comp_ctx, func_ctx, stringref_obj))) { + goto fail; + } + + param_types[0] = INT8_PTR_TYPE; + param_types[1] = I32_TYPE; + param_types[2] = I32_TYPE; + param_types[3] = INT32_PTR_TYPE; + ret_type = INT8_PTR_TYPE; + + GET_AOT_FUNCTION(wasm_string_advance, 4); + + /* Call function wasm_string_advance() */ + param_values[0] = str_obj; + param_values[1] = pos; + param_values[2] = bytes; + param_values[3] = I8_PTR_NULL; + + if (!(value = LLVMBuildCall2(comp_ctx->builder, func_type, func, + param_values, 4, "string_advance"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + + return value; +fail: + return NULL; +} + +static LLVMValueRef +aot_call_wasm_string_slice(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + LLVMValueRef stringref_obj, LLVMValueRef start, + LLVMValueRef end, StringViewType stringview_type) +{ + LLVMValueRef param_values[4], func, value, str_obj; + LLVMTypeRef param_types[4], ret_type, func_type, func_ptr_type; + + if (!(str_obj = + aot_stringref_obj_get_value(comp_ctx, func_ctx, stringref_obj))) { + goto fail; + } + + param_types[0] = INT8_PTR_TYPE; + param_types[1] = I32_TYPE; + param_types[2] = I32_TYPE; + param_types[3] = I32_TYPE; + ret_type = INT8_PTR_TYPE; + + GET_AOT_FUNCTION(wasm_string_slice, 4); + + /* Call function wasm_string_slice() */ + param_values[0] = str_obj; + param_values[1] = start; + param_values[2] = end; + param_values[3] = I32_CONST(stringview_type); + + if (!(value = LLVMBuildCall2(comp_ctx->builder, func_type, func, + param_values, 4, "string_slice"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + + return value; +fail: + return NULL; +} + +bool +aot_compile_op_string_new(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 encoding) +{ + LLVMValueRef maddr, byte_length, offset, str_obj, stringref_obj; + LLVMValueRef param_values[5], func, value; + LLVMTypeRef param_types[5], ret_type, func_type, func_ptr_type; + DEFINE_STRINGREF_CHECK_VAR(); + + if (!aot_gen_commit_values(comp_ctx->aot_frame)) + return false; + + if (!aot_gen_commit_sp_ip(comp_ctx->aot_frame, true, true)) + return false; + + POP_I32(byte_length); + POP_I32(offset); + + if (!(maddr = check_bulk_memory_overflow(comp_ctx, func_ctx, offset, + byte_length))) + goto fail; + + param_types[0] = INT8_PTR_TYPE; + param_types[1] = I32_TYPE; + param_types[2] = I32_TYPE; + ret_type = INT8_PTR_TYPE; + + GET_AOT_FUNCTION(wasm_string_new_with_encoding, 3); + + /* Call function wasm_struct_obj_new() */ + param_values[0] = maddr; + param_values[1] = byte_length; + param_values[2] = I32_CONST(encoding); + + if (!(str_obj = LLVMBuildCall2(comp_ctx->builder, func_type, func, + param_values, 3, "wasm_string_new"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + CHECK_STRING_OBJ(str_obj); + + if (!aot_call_wasm_stringref_obj_new(comp_ctx, func_ctx, str_obj, + WASM_TYPE_STRINGREF, 0, + &stringref_obj)) { + goto fail; + } + CHECK_STRINGREF_OBJ(stringref_obj); + + PUSH_GC_REF(stringref_obj); + + return true; +fail: + return false; +} + +bool +aot_compile_op_string_const(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 contents) +{ + LLVMValueRef param_values[2], func, value, str_obj, stringref_obj; + LLVMTypeRef param_types[2], ret_type, func_type, func_ptr_type; + DEFINE_STRINGREF_CHECK_VAR(); + + if (!aot_gen_commit_values(comp_ctx->aot_frame)) + return false; + + if (!aot_gen_commit_sp_ip(comp_ctx->aot_frame, true, true)) + return false; + + param_types[0] = INT8_PTR_TYPE; + param_types[1] = I32_TYPE; + ret_type = INT8_PTR_TYPE; + + GET_AOT_FUNCTION(wasm_string_new_const, 2); + + bh_assert(contents < comp_ctx->comp_data->string_literal_count); + param_values[0] = LLVMConstIntToPtr( + I64_CONST((unsigned long long)(uintptr_t) + comp_ctx->comp_data->string_literal_ptrs_wp[contents]), + INT8_PTR_TYPE); + param_values[1] = + I32_CONST(comp_ctx->comp_data->string_literal_lengths_wp[contents]); + + if (!(str_obj = LLVMBuildCall2(comp_ctx->builder, func_type, func, + param_values, 2, "create_stringref"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + CHECK_STRING_OBJ(str_obj); + + if (!aot_call_wasm_stringref_obj_new(comp_ctx, func_ctx, str_obj, + WASM_TYPE_STRINGREF, 0, + &stringref_obj)) { + goto fail; + } + CHECK_STRINGREF_OBJ(stringref_obj); + + PUSH_GC_REF(stringref_obj); + + return true; +fail: + return false; +} + +bool +aot_compile_op_string_measure(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx, uint32 encoding) +{ + LLVMValueRef stringref_obj, value; + + POP_GC_REF(stringref_obj); + + if (!(value = aot_call_wasm_string_measure(comp_ctx, func_ctx, + stringref_obj, encoding))) { + goto fail; + } + + PUSH_I32(value); + + return true; +fail: + return false; +} + +bool +aot_compile_op_string_encode(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 mem_idx, uint32 encoding) +{ + LLVMValueRef param_values[6], func, value, offset, length, maddr, str_obj, + stringref_obj; + LLVMTypeRef param_types[6], ret_type, func_type, func_ptr_type; + LLVMBasicBlockRef check_string_encode_succ; + LLVMValueRef cmp; + + POP_I32(offset); + POP_GC_REF(stringref_obj); + + if (!(str_obj = + aot_stringref_obj_get_value(comp_ctx, func_ctx, stringref_obj))) { + goto fail; + } + + if (!(length = aot_call_wasm_string_measure(comp_ctx, func_ctx, + stringref_obj, encoding))) { + goto fail; + } + + if (!(maddr = + check_bulk_memory_overflow(comp_ctx, func_ctx, offset, length))) + goto fail; + + param_types[0] = INT8_PTR_TYPE; + param_types[1] = I32_TYPE; + param_types[2] = I32_TYPE; + param_types[3] = INT8_PTR_TYPE; + param_types[4] = INT8_PTR_TYPE; + param_types[5] = I32_TYPE; + ret_type = I32_TYPE; + + GET_AOT_FUNCTION(wasm_string_encode, 6); + + /* Call function wasm_string_measure() */ + param_values[0] = str_obj; + param_values[1] = I32_ZERO; + param_values[2] = length; + param_values[3] = maddr; + param_values[4] = I8_PTR_NULL; + param_values[5] = I32_CONST(encoding); + + if (!(value = LLVMBuildCall2(comp_ctx->builder, func_type, func, + param_values, 6, "string_encode"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + + CHECK_STRING_ENCODE(value); + + PUSH_I32(value); + + return true; +fail: + return false; +} + +bool +aot_compile_op_string_concat(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) +{ + LLVMValueRef param_values[2], func, value, str_obj_lhs, str_obj_rhs, + stringref_obj_lhs, stringref_obj_rhs, stringref_obj_new; + LLVMTypeRef param_types[2], ret_type, func_type, func_ptr_type; + DEFINE_STRINGREF_CHECK_VAR(); + + if (!aot_gen_commit_values(comp_ctx->aot_frame)) + return false; + + if (!aot_gen_commit_sp_ip(comp_ctx->aot_frame, true, true)) + return false; + + POP_GC_REF(stringref_obj_rhs); + POP_GC_REF(stringref_obj_lhs); + + if (!(str_obj_lhs = aot_stringref_obj_get_value(comp_ctx, func_ctx, + stringref_obj_lhs))) { + goto fail; + } + + if (!(str_obj_rhs = aot_stringref_obj_get_value(comp_ctx, func_ctx, + stringref_obj_rhs))) { + goto fail; + } + + param_types[0] = INT8_PTR_TYPE; + param_types[1] = INT8_PTR_TYPE; + ret_type = INT8_PTR_TYPE; + + GET_AOT_FUNCTION(wasm_string_concat, 2); + + /* Call function wasm_string_concat() */ + param_values[0] = str_obj_lhs; + param_values[1] = str_obj_rhs; + + if (!(str_obj_lhs = LLVMBuildCall2(comp_ctx->builder, func_type, func, + param_values, 2, "string_concat"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + CHECK_STRING_OBJ(str_obj_lhs); + + if (!aot_call_wasm_stringref_obj_new(comp_ctx, func_ctx, str_obj_lhs, + WASM_TYPE_STRINGREF, 0, + &stringref_obj_new)) { + goto fail; + } + CHECK_STRINGREF_OBJ(stringref_obj_new); + + PUSH_GC_REF(stringref_obj_new); + + return true; +fail: + return false; +} + +bool +aot_compile_op_string_eq(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) +{ + LLVMValueRef param_values[2], func, value, str_obj_lhs, str_obj_rhs, + stringref_obj_lhs, stringref_obj_rhs; + LLVMTypeRef param_types[2], ret_type, func_type, func_ptr_type; + + POP_GC_REF(stringref_obj_lhs); + POP_GC_REF(stringref_obj_rhs); + + if (!(str_obj_lhs = aot_stringref_obj_get_value(comp_ctx, func_ctx, + stringref_obj_lhs))) { + goto fail; + } + + if (!(str_obj_rhs = aot_stringref_obj_get_value(comp_ctx, func_ctx, + stringref_obj_rhs))) { + goto fail; + } + + param_types[0] = INT8_PTR_TYPE; + param_types[1] = INT8_PTR_TYPE; + ret_type = I32_TYPE; + + GET_AOT_FUNCTION(wasm_string_eq, 2); + + /* Call function wasm_string_eq() */ + param_values[0] = str_obj_lhs; + param_values[1] = str_obj_rhs; + + if (!(value = LLVMBuildCall2(comp_ctx->builder, func_type, func, + param_values, 2, "string_eq"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + + PUSH_I32(value); + + return true; +fail: + return false; +} + +bool +aot_compile_op_string_is_usv_sequence(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx) +{ + LLVMValueRef param_values[1], func, value, str_obj, stringref_obj; + LLVMTypeRef param_types[1], ret_type, func_type, func_ptr_type; + + POP_GC_REF(stringref_obj); + + if (!(str_obj = + aot_stringref_obj_get_value(comp_ctx, func_ctx, stringref_obj))) { + goto fail; + } + + param_types[0] = INT8_PTR_TYPE; + ret_type = I32_TYPE; + + GET_AOT_FUNCTION(wasm_string_is_usv_sequence, 1); + + /* Call function wasm_string_is_usv_sequence() */ + param_values[0] = str_obj; + + if (!(value = LLVMBuildCall2(comp_ctx->builder, func_type, func, + param_values, 1, "string_is_usv_sequence"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + + PUSH_I32(value); + + return true; +fail: + return false; +} + +bool +aot_compile_op_string_as_wtf8(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx) +{ + LLVMValueRef str_obj, stringref_obj, stringview_wtf8_obj; + DEFINE_STRINGREF_CHECK_VAR(); + + if (!aot_gen_commit_values(comp_ctx->aot_frame)) + return false; + + if (!aot_gen_commit_sp_ip(comp_ctx->aot_frame, true, true)) + return false; + + POP_GC_REF(stringref_obj); + + if (!(str_obj = aot_call_wasm_string_create_view( + comp_ctx, func_ctx, stringref_obj, STRING_VIEW_WTF8))) { + goto fail; + } + CHECK_STRING_OBJ(str_obj); + + if (!aot_call_wasm_stringref_obj_new(comp_ctx, func_ctx, str_obj, + WASM_TYPE_STRINGVIEWWTF8, 0, + &stringview_wtf8_obj)) { + goto fail; + } + CHECK_STRINGVIEW_OBJ(stringref_obj); + + PUSH_GC_REF(stringview_wtf8_obj); + + return true; +fail: + return false; +} + +bool +aot_compile_op_stringview_wtf8_advance(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx) +{ + LLVMValueRef stringref_obj, bytes, pos, value; + + POP_I32(bytes); + POP_I32(pos); + POP_GC_REF(stringref_obj); + + if (!(value = aot_call_wasm_string_advance(comp_ctx, func_ctx, + stringref_obj, bytes, pos))) { + goto fail; + } + + PUSH_I32(value); + + return true; +fail: + return false; +} + +bool +aot_compile_op_stringview_wtf8_encode(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx, uint32 mem_idx, + uint32 encoding) +{ + LLVMValueRef param_values[6], func, value, offset, maddr, str_obj, + stringref_obj; + LLVMValueRef bytes, pos, next_pos; + LLVMTypeRef param_types[6], ret_type, func_type, func_ptr_type; + LLVMBasicBlockRef check_string_encode_succ; + LLVMValueRef cmp; + + POP_I32(bytes); + POP_I32(pos); + POP_I32(offset); + + next_pos = LLVMBuildAlloca(comp_ctx->builder, I32_TYPE, "next_pos"); + if (!next_pos) { + aot_set_last_error("failed to build alloca"); + goto fail; + } + + if (!(maddr = + check_bulk_memory_overflow(comp_ctx, func_ctx, offset, bytes))) + goto fail; + + POP_GC_REF(stringref_obj); + + if (!(str_obj = + aot_stringref_obj_get_value(comp_ctx, func_ctx, stringref_obj))) { + goto fail; + } + + param_types[0] = INT8_PTR_TYPE; + param_types[1] = I32_TYPE; + param_types[2] = I32_TYPE; + param_types[3] = INT8_PTR_TYPE; + param_types[4] = INT8_PTR_TYPE; + param_types[5] = I32_TYPE; + ret_type = I32_TYPE; + + GET_AOT_FUNCTION(wasm_string_encode, 6); + + /* Call function wasm_string_measure() */ + param_values[0] = str_obj; + param_values[1] = pos; + param_values[2] = bytes; + param_values[3] = maddr; + param_values[4] = next_pos; + param_values[5] = I32_CONST(encoding); + + if (!(value = LLVMBuildCall2(comp_ctx->builder, func_type, func, + param_values, 6, "string_encode"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + + CHECK_STRING_ENCODE(value); + + next_pos = + LLVMBuildLoad2(comp_ctx->builder, I32_TYPE, next_pos, "next_pos"); + if (!next_pos) { + aot_set_last_error("llvm build load failed."); + goto fail; + } + + LLVMSetAlignment(next_pos, 4); + + PUSH_I32(next_pos); + PUSH_I32(value); + + return true; +fail: + return false; +} + +bool +aot_compile_op_stringview_wtf8_slice(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx) +{ + LLVMValueRef stringref_obj, start, end, stringref_obj_new, value; + DEFINE_STRINGREF_CHECK_VAR(); + + if (!aot_gen_commit_values(comp_ctx->aot_frame)) + return false; + + if (!aot_gen_commit_sp_ip(comp_ctx->aot_frame, true, true)) + return false; + + POP_I32(start); + POP_I32(end); + POP_GC_REF(stringref_obj); + + if (!(value = aot_call_wasm_string_slice(comp_ctx, func_ctx, stringref_obj, + start, end, STRING_VIEW_WTF8))) { + goto fail; + } + CHECK_STRING_OBJ(value); + + if (!aot_call_wasm_stringref_obj_new(comp_ctx, func_ctx, value, + WASM_TYPE_STRINGREF, 0, + &stringref_obj_new)) { + goto fail; + } + CHECK_STRINGREF_OBJ(stringref_obj_new); + + PUSH_GC_REF(stringref_obj_new); + + return true; +fail: + return false; +} + +bool +aot_compile_op_string_as_wtf16(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx) +{ + LLVMValueRef str_obj, stringref_obj, stringview_wtf16_obj; + DEFINE_STRINGREF_CHECK_VAR(); + + if (!aot_gen_commit_values(comp_ctx->aot_frame)) + return false; + + if (!aot_gen_commit_sp_ip(comp_ctx->aot_frame, true, true)) + return false; + + POP_GC_REF(stringref_obj); + + if (!(str_obj = aot_call_wasm_string_create_view( + comp_ctx, func_ctx, stringref_obj, STRING_VIEW_WTF16))) { + goto fail; + } + CHECK_STRING_OBJ(str_obj); + + if (!aot_call_wasm_stringref_obj_new(comp_ctx, func_ctx, str_obj, + WASM_TYPE_STRINGVIEWWTF16, 0, + &stringview_wtf16_obj)) { + goto fail; + } + CHECK_STRINGVIEW_OBJ(stringview_wtf16_obj); + + PUSH_GC_REF(stringview_wtf16_obj); + + return true; +fail: + return false; +} + +bool +aot_compile_op_stringview_wtf16_length(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx) +{ + LLVMValueRef param_values[2], func, value, str_obj, stringview_wtf16_obj; + LLVMTypeRef param_types[2], ret_type, func_type, func_ptr_type; + + POP_GC_REF(stringview_wtf16_obj); + + if (!(str_obj = aot_stringref_obj_get_value(comp_ctx, func_ctx, + stringview_wtf16_obj))) { + goto fail; + } + + param_types[0] = INT8_PTR_TYPE; + ret_type = I32_TYPE; + + GET_AOT_FUNCTION(wasm_string_wtf16_get_length, 6); + + /* Call function wasm_string_wtf16_get_length() */ + param_values[0] = str_obj; + + if (!(value = LLVMBuildCall2(comp_ctx->builder, func_type, func, + param_values, 1, "stringview_wtf16_length"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + + PUSH_I32(value); + + return true; +fail: + return false; +} + +bool +aot_compile_op_stringview_wtf16_get_codeunit(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx) +{ + LLVMValueRef param_values[2], func, value, str_obj, stringview_wtf16_obj, + pos; + LLVMTypeRef param_types[2], ret_type, func_type, func_ptr_type; + + POP_I32(pos); + POP_GC_REF(stringview_wtf16_obj); + + if (!(str_obj = aot_stringref_obj_get_value(comp_ctx, func_ctx, + stringview_wtf16_obj))) { + goto fail; + } + + param_types[0] = INT8_PTR_TYPE; + param_types[1] = I32_TYPE; + ret_type = I32_TYPE; + + GET_AOT_FUNCTION(wasm_string_get_wtf16_codeunit, 2); + + /* Call function wasm_string_get_wtf16_codeunit() */ + param_values[0] = str_obj; + param_values[1] = pos; + + if (!(value = + LLVMBuildCall2(comp_ctx->builder, func_type, func, param_values, + 2, "stringview_wtf16_get_codeunit"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + + PUSH_I32(value); + + return true; +fail: + return false; +} + +bool +aot_compile_op_stringview_wtf16_encode(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx, uint32 mem_idx) +{ + LLVMValueRef param_values[6], func, value, offset, maddr, str_obj, + stringref_obj; + LLVMValueRef len, pos; + LLVMTypeRef param_types[6], ret_type, func_type, func_ptr_type; + LLVMBasicBlockRef check_string_encode_succ; + LLVMValueRef cmp; + + POP_I32(len); + POP_I32(pos); + POP_I32(offset); + + if (!(maddr = check_bulk_memory_overflow( + comp_ctx, func_ctx, offset, + LLVMBuildMul(comp_ctx->builder, len, I32_CONST(2), "wtf16_len")))) + goto fail; + + POP_GC_REF(stringref_obj); + + if (!check_memory_alignment(comp_ctx, func_ctx, maddr, 2)) { + goto fail; + } + + if (!(str_obj = + aot_stringref_obj_get_value(comp_ctx, func_ctx, stringref_obj))) { + goto fail; + } + + param_types[0] = INT8_PTR_TYPE; + param_types[1] = I32_TYPE; + param_types[2] = I32_TYPE; + param_types[3] = INT8_PTR_TYPE; + param_types[4] = INT8_PTR_TYPE; + param_types[5] = I32_TYPE; + ret_type = I32_TYPE; + + GET_AOT_FUNCTION(wasm_string_encode, 6); + + /* Call function wasm_string_measure() */ + param_values[0] = str_obj; + param_values[1] = pos; + param_values[2] = len; + param_values[3] = maddr; + param_values[4] = I8_PTR_NULL; + param_values[5] = I32_CONST(WTF16); + + if (!(value = LLVMBuildCall2(comp_ctx->builder, func_type, func, + param_values, 6, "string_encode"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + + CHECK_STRING_ENCODE(value); + + PUSH_I32(value); + + return true; +fail: + return false; +} + +bool +aot_compile_op_stringview_wtf16_slice(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx) +{ + LLVMValueRef stringref_obj, start, end, stringref_obj_new, value; + DEFINE_STRINGREF_CHECK_VAR(); + + if (!aot_gen_commit_values(comp_ctx->aot_frame)) + return false; + + if (!aot_gen_commit_sp_ip(comp_ctx->aot_frame, true, true)) + return false; + + POP_I32(end); + POP_I32(start); + POP_GC_REF(stringref_obj); + + if (!(value = aot_call_wasm_string_slice(comp_ctx, func_ctx, stringref_obj, + start, end, STRING_VIEW_WTF16))) { + goto fail; + } + CHECK_STRING_OBJ(value); + + if (!aot_call_wasm_stringref_obj_new(comp_ctx, func_ctx, value, + WASM_TYPE_STRINGREF, 0, + &stringref_obj_new)) { + goto fail; + } + CHECK_STRINGREF_OBJ(stringref_obj_new); + + PUSH_GC_REF(stringref_obj_new); + + return true; +fail: + return false; +} + +bool +aot_compile_op_string_as_iter(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx) +{ + LLVMValueRef stringref_obj, stringview_iter_obj, str_obj; + DEFINE_STRINGREF_CHECK_VAR(); + + if (!aot_gen_commit_values(comp_ctx->aot_frame)) + return false; + + if (!aot_gen_commit_sp_ip(comp_ctx->aot_frame, true, true)) + return false; + + POP_GC_REF(stringref_obj); + + if (!(str_obj = aot_call_wasm_string_create_view( + comp_ctx, func_ctx, stringref_obj, STRING_VIEW_WTF8))) { + goto fail; + } + CHECK_STRING_OBJ(str_obj); + + if (!aot_call_wasm_stringref_obj_new(comp_ctx, func_ctx, stringref_obj, + WASM_TYPE_STRINGVIEWITER, 0, + &stringview_iter_obj)) { + goto fail; + } + CHECK_STRINGVIEW_OBJ(stringview_iter_obj); + + PUSH_GC_REF(stringview_iter_obj); + + return true; +fail: + return false; +} + +bool +aot_compile_op_stringview_iter_next(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx) +{ + LLVMValueRef param_values[2], func, value, stringview_iter_obj, str_obj, + iter_pos_addr, pos; + LLVMTypeRef param_types[2], ret_type, func_type, func_ptr_type; + + POP_GC_REF(stringview_iter_obj); + + if (!(str_obj = aot_stringref_obj_get_value(comp_ctx, func_ctx, + stringview_iter_obj))) { + goto fail; + } + + if (!(iter_pos_addr = get_stringview_iter_pos_addr(comp_ctx, func_ctx, + stringview_iter_obj))) { + goto fail; + } + + pos = LLVMBuildLoad2(comp_ctx->builder, I32_TYPE, iter_pos_addr, + "get_iter_pos"); + LLVMSetAlignment(pos, 4); + + param_types[0] = INT8_PTR_TYPE; + param_types[1] = I32_TYPE; + ret_type = I32_TYPE; + + GET_AOT_FUNCTION(wasm_string_next_codepoint, 2); + + /* Call function wasm_string_measure() */ + param_values[0] = str_obj; + param_values[1] = pos; + + if (!(value = LLVMBuildCall2(comp_ctx->builder, func_type, func, + param_values, 2, "stringview_iter_next"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + + PUSH_I32(value); + + return true; +fail: + return false; +} + +static bool +stringview_iter_advance_or_rewind(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx, bool is_rewind) +{ + LLVMValueRef param_values[4], func, value, stringview_iter_obj, str_obj, + code_points_consumed, iter_pos_addr, pos, code_points_count, res; + LLVMTypeRef param_types[4], ret_type, func_type, func_ptr_type; + + POP_I32(code_points_count); + POP_GC_REF(stringview_iter_obj); + + if (!(str_obj = aot_stringref_obj_get_value(comp_ctx, func_ctx, + stringview_iter_obj))) { + goto fail; + } + + if (!(iter_pos_addr = get_stringview_iter_pos_addr(comp_ctx, func_ctx, + stringview_iter_obj))) { + goto fail; + } + + if (!(pos = LLVMBuildLoad2(comp_ctx->builder, I32_TYPE, iter_pos_addr, + "get_iter_pos"))) { + goto fail; + } + LLVMSetAlignment(pos, 4); + + if (!(code_points_consumed = LLVMBuildAlloca(comp_ctx->builder, I32_TYPE, + "code_points_consumed"))) { + goto fail; + } + + param_types[0] = INT8_PTR_TYPE; + param_types[1] = I32_TYPE; + param_types[2] = I32_TYPE; + param_types[3] = INT32_PTR_TYPE; + ret_type = I32_TYPE; + + if (is_rewind) { + GET_AOT_FUNCTION(wasm_string_rewind, 4); + } + else { + GET_AOT_FUNCTION(wasm_string_advance, 4); + } + + /* Call function wasm_string_advance() */ + param_values[0] = str_obj; + param_values[1] = pos; + param_values[2] = code_points_count; + param_values[3] = code_points_consumed; + + if (!(value = LLVMBuildCall2(comp_ctx->builder, func_type, func, + param_values, 4, "string_advance"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + + if (!(code_points_consumed = + LLVMBuildLoad2(comp_ctx->builder, I32_TYPE, code_points_consumed, + "get_code_points_consumed"))) { + aot_set_last_error("llvm build load failed."); + goto fail; + } + LLVMSetAlignment(code_points_consumed, 4); + + if (!(res = LLVMBuildStore(comp_ctx->builder, code_points_consumed, + iter_pos_addr))) { + aot_set_last_error("llvm build store failed."); + goto fail; + } + LLVMSetAlignment(res, 4); + + PUSH_I32(code_points_consumed); +fail: + return false; +} + +bool +aot_compile_op_stringview_iter_advance(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx) +{ + return stringview_iter_advance_or_rewind(comp_ctx, func_ctx, false); +} + +bool +aot_compile_op_stringview_iter_rewind(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx) +{ + return stringview_iter_advance_or_rewind(comp_ctx, func_ctx, true); +} + +bool +aot_compile_op_stringview_iter_slice(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx) +{ + LLVMValueRef stringview_iter_obj, start, end, stringref_obj_new, value, + iter_pos_addr, code_points_count; + DEFINE_STRINGREF_CHECK_VAR(); + + if (!aot_gen_commit_values(comp_ctx->aot_frame)) + return false; + + if (!aot_gen_commit_sp_ip(comp_ctx->aot_frame, true, true)) + return false; + + POP_I32(code_points_count); + POP_GC_REF(stringview_iter_obj); + + if (!(iter_pos_addr = get_stringview_iter_pos_addr(comp_ctx, func_ctx, + stringview_iter_obj))) { + goto fail; + } + + if (!(start = LLVMBuildLoad2(comp_ctx->builder, I32_TYPE, iter_pos_addr, + "get_iter_pos"))) { + goto fail; + } + LLVMSetAlignment(start, 4); + + if (!(end = LLVMBuildAdd(comp_ctx->builder, start, code_points_count, + "calc_slice_end"))) { + goto fail; + } + + if (!(value = aot_call_wasm_string_slice(comp_ctx, func_ctx, + stringview_iter_obj, start, end, + STRING_VIEW_ITER))) { + goto fail; + } + CHECK_STRING_OBJ(value); + + if (!aot_call_wasm_stringref_obj_new(comp_ctx, func_ctx, value, + WASM_TYPE_STRINGREF, 0, + &stringref_obj_new)) { + goto fail; + } + CHECK_STRINGREF_OBJ(stringref_obj_new); + + PUSH_GC_REF(stringref_obj_new); + + return true; +fail: + return false; +} + +bool +aot_compile_op_string_new_array(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx, uint32 encoding) +{ + LLVMValueRef start, end, count, str_obj, stringref_obj, array_obj, + elem_data_ptr; + LLVMValueRef param_values[5], func, value; + LLVMTypeRef param_types[5], ret_type, func_type, func_ptr_type; + DEFINE_STRINGREF_CHECK_VAR(); + + if (!aot_gen_commit_values(comp_ctx->aot_frame)) + return false; + + if (!aot_gen_commit_sp_ip(comp_ctx->aot_frame, true, true)) + return false; + + POP_I32(end); + POP_I32(start); + POP_GC_REF(array_obj); + + if (!aot_array_obj_elem_addr( + comp_ctx, func_ctx, array_obj, start, &elem_data_ptr, + encoding == WTF16 ? PACKED_TYPE_I16 : PACKED_TYPE_I8)) { + goto fail; + } + + if (!(count = LLVMBuildSub(comp_ctx->builder, end, start, "calc_count"))) { + goto fail; + } + + param_types[0] = INT8_PTR_TYPE; + param_types[1] = I32_TYPE; + param_types[2] = I32_TYPE; + ret_type = INT8_PTR_TYPE; + + GET_AOT_FUNCTION(wasm_string_new_with_encoding, 3); + + /* Call function wasm_struct_obj_new() */ + param_values[0] = elem_data_ptr; + param_values[1] = count; + param_values[2] = I32_CONST(encoding); + + if (!(str_obj = LLVMBuildCall2(comp_ctx->builder, func_type, func, + param_values, 3, "wasm_string_new"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + CHECK_STRING_OBJ(str_obj); + + if (!aot_call_wasm_stringref_obj_new(comp_ctx, func_ctx, str_obj, + WASM_TYPE_STRINGREF, 0, + &stringref_obj)) { + goto fail; + } + CHECK_STRINGREF_OBJ(stringref_obj); + + PUSH_GC_REF(stringref_obj); + + return true; +fail: + return false; +} + +bool +aot_compile_op_string_encode_array(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx, uint32 encoding) +{ + LLVMValueRef param_values[6], func, value, count, start, str_obj, + stringref_obj, array_obj, elem_data_ptr, array_len; + LLVMTypeRef param_types[6], ret_type, func_type, func_ptr_type; + LLVMBasicBlockRef check_string_encode_succ, check_array_index_succ; + LLVMValueRef cmp; + + POP_I32(start); + POP_GC_REF(array_obj); + POP_GC_REF(stringref_obj); + + if (!(str_obj = + aot_stringref_obj_get_value(comp_ctx, func_ctx, stringref_obj))) { + goto fail; + } + + if (!aot_array_obj_length(comp_ctx, array_obj, &array_len)) + goto fail; + + if (!(cmp = LLVMBuildICmp(comp_ctx->builder, LLVMIntUGE, start, array_len, + "check_array_index"))) { + aot_set_last_error("llvm build icmp failed."); + goto fail; + } + + ADD_BASIC_BLOCK(check_array_index_succ, "check array index succ"); + MOVE_BLOCK_AFTER_CURR(check_array_index_succ); + + if (!aot_emit_exception(comp_ctx, func_ctx, EXCE_ARRAY_IDX_OOB, true, cmp, + check_array_index_succ)) { + goto fail; + } + + if (!aot_array_obj_elem_addr( + comp_ctx, func_ctx, stringref_obj, start, &elem_data_ptr, + encoding == WTF16 ? PACKED_TYPE_I16 : PACKED_TYPE_I8)) { + goto fail; + } + + if (!(count = aot_call_wasm_string_measure(comp_ctx, func_ctx, + stringref_obj, encoding))) { + goto fail; + } + + param_types[0] = INT8_PTR_TYPE; + param_types[1] = I32_TYPE; + param_types[2] = I32_TYPE; + param_types[3] = INT8_PTR_TYPE; + param_types[4] = INT8_PTR_TYPE; + param_types[5] = I32_TYPE; + ret_type = I32_TYPE; + + GET_AOT_FUNCTION(wasm_string_encode, 6); + + /* Call function wasm_string_measure() */ + param_values[0] = str_obj; + param_values[1] = start; + param_values[2] = count; + param_values[3] = elem_data_ptr; + param_values[4] = I8_PTR_NULL; + param_values[5] = I32_CONST(encoding); + + if (!(value = LLVMBuildCall2(comp_ctx->builder, func_type, func, + param_values, 6, "string_encode"))) { + aot_set_last_error("llvm build call failed."); + goto fail; + } + + CHECK_STRING_ENCODE(value); + + PUSH_I32(value); + + return true; +fail: + return false; +} + +#endif /* WASM_ENABLE_STRINGREF != 0 */ diff --git a/core/iwasm/compilation/aot_emit_stringref.h b/core/iwasm/compilation/aot_emit_stringref.h new file mode 100644 index 000000000..a1b68a44e --- /dev/null +++ b/core/iwasm/compilation/aot_emit_stringref.h @@ -0,0 +1,112 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef _AOT_EMIT_STRINGREF_H_ +#define _AOT_EMIT_STRINGREF_H_ + +#include "aot_compiler.h" + +#ifdef __cplusplus +extern "C" { +#endif + +bool +aot_compile_op_string_new(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 encoding); + +bool +aot_compile_op_string_const(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 contents); + +bool +aot_compile_op_string_measure(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx, uint32 encoding); + +bool +aot_compile_op_string_encode(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 mem_idx, uint32 encoding); + +bool +aot_compile_op_string_concat(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx); + +bool +aot_compile_op_string_eq(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx); + +bool +aot_compile_op_string_is_usv_sequence(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx); + +bool +aot_compile_op_string_as_wtf8(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx); + +bool +aot_compile_op_stringview_wtf8_advance(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx); + +bool +aot_compile_op_stringview_wtf8_encode(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx, uint32 mem_idx, + uint32 encoding); + +bool +aot_compile_op_stringview_wtf8_slice(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx); + +bool +aot_compile_op_string_as_wtf16(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx); + +bool +aot_compile_op_stringview_wtf16_length(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx); + +bool +aot_compile_op_stringview_wtf16_get_codeunit(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx); + +bool +aot_compile_op_stringview_wtf16_encode(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx, + uint32 mem_idx); + +bool +aot_compile_op_stringview_wtf16_slice(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx); + +bool +aot_compile_op_string_as_iter(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx); + +bool +aot_compile_op_stringview_iter_next(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx); + +bool +aot_compile_op_stringview_iter_advance(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx); + +bool +aot_compile_op_stringview_iter_rewind(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx); + +bool +aot_compile_op_stringview_iter_slice(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx); + +bool +aot_compile_op_string_new_array(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx, uint32 encoding); + +bool +aot_compile_op_string_encode_array(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx, uint32 encoding); + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif + +#endif /* end of _AOT_EMIT_STRINGREF_H_ */ diff --git a/core/iwasm/compilation/aot_emit_table.c b/core/iwasm/compilation/aot_emit_table.c index 34e7d9700..6ce3295fa 100644 --- a/core/iwasm/compilation/aot_emit_table.c +++ b/core/iwasm/compilation/aot_emit_table.c @@ -6,6 +6,9 @@ #include "aot_emit_table.h" #include "aot_emit_exception.h" #include "../aot/aot_runtime.h" +#if WASM_ENABLE_GC != 0 +#include "aot_emit_gc.h" +#endif uint64 get_tbl_inst_offset(const AOTCompContext *comp_ctx, @@ -18,13 +21,16 @@ get_tbl_inst_offset(const AOTCompContext *comp_ctx, offset = offsetof(AOTModuleInstance, global_table_data.bytes) + (uint64)comp_ctx->comp_data->memory_count * sizeof(AOTMemoryInstance) - + comp_ctx->comp_data->global_data_size; + /* Get global data size according to target info */ + + (comp_ctx->pointer_size == sizeof(uint64) + ? comp_ctx->comp_data->global_data_size_64bit + : comp_ctx->comp_data->global_data_size_32bit); while (i < tbl_idx && i < comp_ctx->comp_data->import_table_count) { offset += offsetof(AOTTableInstance, elems); /* avoid loading from current AOTTableInstance */ offset += - sizeof(uint32) + (uint64)comp_ctx->pointer_size * aot_get_imp_tbl_data_slots(imp_tbls + i, comp_ctx->is_jit_mode); ++i; } @@ -38,7 +44,7 @@ get_tbl_inst_offset(const AOTCompContext *comp_ctx, while (i < tbl_idx && i < comp_ctx->comp_data->table_count) { offset += offsetof(AOTTableInstance, elems); /* avoid loading from current AOTTableInstance */ - offset += sizeof(uint32) + offset += (uint64)comp_ctx->pointer_size * aot_get_tbl_data_slots(tbls + i, comp_ctx->is_jit_mode); ++i; } @@ -58,7 +64,7 @@ get_module_inst_extra_offset(AOTCompContext *comp_ctx) return offset_32; } -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 LLVMValueRef aot_compile_get_tbl_inst(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, @@ -183,7 +189,8 @@ bool aot_compile_op_table_get(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, uint32 tbl_idx) { - LLVMValueRef elem_idx, offset, table_elem, func_idx; + LLVMValueRef elem_idx, offset, func_idx; + LLVMValueRef table_elem_base, table_elem_addr, table_elem; POP_I32(elem_idx); @@ -198,34 +205,66 @@ aot_compile_op_table_get(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, goto fail; } - if (!(table_elem = LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, - func_ctx->aot_inst, &offset, 1, - "table_elem_i8p"))) { + if (!(table_elem_base = LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, + func_ctx->aot_inst, &offset, + 1, "table_elem_base_i8p"))) { aot_set_last_error("llvm build add failed."); goto fail; } - if (!(table_elem = LLVMBuildBitCast(comp_ctx->builder, table_elem, - INT32_PTR_TYPE, "table_elem_i32p"))) { - HANDLE_FAILURE("LLVMBuildBitCast"); - goto fail; - } + /* Load function object reference or function index */ + if (comp_ctx->enable_gc) { + if (!(table_elem_base = + LLVMBuildBitCast(comp_ctx->builder, table_elem_base, + GC_REF_PTR_TYPE, "table_elem_base"))) { + HANDLE_FAILURE("LLVMBuildBitCast"); + goto fail; + } - /* Load function index */ - if (!(table_elem = - LLVMBuildInBoundsGEP2(comp_ctx->builder, I32_TYPE, table_elem, - &elem_idx, 1, "table_elem"))) { - HANDLE_FAILURE("LLVMBuildNUWAdd"); - goto fail; - } + if (!(table_elem_addr = LLVMBuildInBoundsGEP2( + comp_ctx->builder, GC_REF_TYPE, table_elem_base, &elem_idx, 1, + "table_elem_addr"))) { + HANDLE_FAILURE("LLVMBuildNUWAdd"); + goto fail; + } - if (!(func_idx = LLVMBuildLoad2(comp_ctx->builder, I32_TYPE, table_elem, - "func_idx"))) { - HANDLE_FAILURE("LLVMBuildLoad"); - goto fail; - } + if (!(table_elem = LLVMBuildLoad2(comp_ctx->builder, GC_REF_TYPE, + table_elem_addr, "table_elem"))) { + HANDLE_FAILURE("LLVMBuildLoad"); + goto fail; + } - PUSH_I32(func_idx); + PUSH_GC_REF(table_elem); + } + else { + if (!(table_elem_base = + LLVMBuildBitCast(comp_ctx->builder, table_elem_base, + INTPTR_T_PTR_TYPE, "table_elem_base"))) { + HANDLE_FAILURE("LLVMBuildBitCast"); + goto fail; + } + + if (!(table_elem_addr = LLVMBuildInBoundsGEP2( + comp_ctx->builder, INTPTR_T_TYPE, table_elem_base, &elem_idx, + 1, "table_elem_addr"))) { + HANDLE_FAILURE("LLVMBuildNUWAdd"); + goto fail; + } + + if (!(table_elem = LLVMBuildLoad2(comp_ctx->builder, INTPTR_T_TYPE, + table_elem_addr, "table_elem"))) { + HANDLE_FAILURE("LLVMBuildLoad"); + goto fail; + } + + if (!(func_idx = LLVMBuildIntCast2(comp_ctx->builder, table_elem, + I32_TYPE, true, "func_idx"))) { + HANDLE_FAILURE("LLVMBuildIntCast"); + goto fail; + } + + PUSH_I32(func_idx); + } return true; fail: @@ -236,44 +275,72 @@ bool aot_compile_op_table_set(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, uint32 tbl_idx) { - LLVMValueRef val, elem_idx, offset, table_elem; + LLVMValueRef val = NULL, elem_idx, offset, table_elem_base, table_elem_addr; + + if (comp_ctx->enable_gc) + POP_GC_REF(val); + else { + POP_I32(val); + + if (!(val = LLVMBuildIntCast2(comp_ctx->builder, val, INTPTR_T_TYPE, + true, "val_intptr_t"))) { + HANDLE_FAILURE("LLVMBuildBitCast"); + goto fail; + } + } - POP_I32(val); POP_I32(elem_idx); if (!aot_check_table_access(comp_ctx, func_ctx, tbl_idx, elem_idx)) { goto fail; } - /* load data as i32* */ + /* load data as gc_obj_ref* or i32* */ if (!(offset = I32_CONST(get_tbl_inst_offset(comp_ctx, func_ctx, tbl_idx) + offsetof(AOTTableInstance, elems)))) { HANDLE_FAILURE("LLVMConstInt"); goto fail; } - if (!(table_elem = LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, - func_ctx->aot_inst, &offset, 1, - "table_elem_i8p"))) { + if (!(table_elem_base = LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, + func_ctx->aot_inst, &offset, + 1, "table_elem_base_i8p"))) { HANDLE_FAILURE("LLVMBuildInBoundsGEP"); goto fail; } - if (!(table_elem = LLVMBuildBitCast(comp_ctx->builder, table_elem, - INT32_PTR_TYPE, "table_elem_i32p"))) { - HANDLE_FAILURE("LLVMBuildBitCast"); - goto fail; + if (comp_ctx->enable_gc) { + if (!(table_elem_base = + LLVMBuildBitCast(comp_ctx->builder, table_elem_base, + GC_REF_PTR_TYPE, "table_elem_base"))) { + HANDLE_FAILURE("LLVMBuildBitCast"); + goto fail; + } + + if (!(table_elem_addr = LLVMBuildInBoundsGEP2( + comp_ctx->builder, GC_REF_TYPE, table_elem_base, &elem_idx, 1, + "table_elem_addr"))) { + HANDLE_FAILURE("LLVMBuildInBoundsGEP"); + goto fail; + } + } + else { + if (!(table_elem_base = + LLVMBuildBitCast(comp_ctx->builder, table_elem_base, + INTPTR_T_PTR_TYPE, "table_elem_base"))) { + HANDLE_FAILURE("LLVMBuildBitCast"); + goto fail; + } + + if (!(table_elem_addr = LLVMBuildInBoundsGEP2( + comp_ctx->builder, INTPTR_T_TYPE, table_elem_base, &elem_idx, + 1, "table_elem_addr"))) { + HANDLE_FAILURE("LLVMBuildInBoundsGEP"); + goto fail; + } } - /* Load function index */ - if (!(table_elem = - LLVMBuildInBoundsGEP2(comp_ctx->builder, I32_TYPE, table_elem, - &elem_idx, 1, "table_elem"))) { - HANDLE_FAILURE("LLVMBuildInBoundsGEP"); - goto fail; - } - - if (!(LLVMBuildStore(comp_ctx->builder, val, table_elem))) { + if (!(LLVMBuildStore(comp_ctx->builder, val, table_elem_addr))) { HANDLE_FAILURE("LLVMBuildStore"); goto fail; } @@ -434,7 +501,7 @@ aot_compile_op_table_grow(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, param_types[0] = INT8_PTR_TYPE; param_types[1] = I32_TYPE; param_types[2] = I32_TYPE; - param_types[3] = I32_TYPE; + param_types[3] = INT8_PTR_TYPE; ret_type = I32_TYPE; if (comp_ctx->is_jit_mode) @@ -452,7 +519,25 @@ aot_compile_op_table_grow(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, /* n */ POP_I32(param_values[2]); /* v */ - POP_I32(param_values[3]); + + if (comp_ctx->enable_gc) { + POP_GC_REF(param_values[3]); + if (!(param_values[3] = + LLVMBuildBitCast(comp_ctx->builder, param_values[3], + INT8_PTR_TYPE, "table_elem_i8p"))) { + HANDLE_FAILURE("LLVMBuildBitCast"); + goto fail; + } + } + else { + POP_I32(param_values[3]); + if (!(param_values[3] = + LLVMBuildIntToPtr(comp_ctx->builder, param_values[3], + INT8_PTR_TYPE, "table_elem_i8p"))) { + HANDLE_FAILURE("LLVMBuildIntToPtr"); + goto fail; + } + } if (!(ret = LLVMBuildCall2(comp_ctx->builder, func_type, func, param_values, 4, "table_grow"))) { @@ -477,7 +562,7 @@ aot_compile_op_table_fill(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, param_types[0] = INT8_PTR_TYPE; param_types[1] = I32_TYPE; param_types[2] = I32_TYPE; - param_types[3] = I32_TYPE; + param_types[3] = INT8_PTR_TYPE; param_types[4] = I32_TYPE; ret_type = VOID_TYPE; @@ -496,7 +581,25 @@ aot_compile_op_table_fill(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, /* n */ POP_I32(param_values[2]); /* v */ - POP_I32(param_values[3]); + + if (comp_ctx->enable_gc) { + POP_GC_REF(param_values[3]); + if (!(param_values[3] = + LLVMBuildBitCast(comp_ctx->builder, param_values[3], + INT8_PTR_TYPE, "table_elem_i8p"))) { + HANDLE_FAILURE("LLVMBuildBitCast"); + goto fail; + } + } + else { + POP_I32(param_values[3]); + if (!(param_values[3] = + LLVMBuildIntToPtr(comp_ctx->builder, param_values[3], + INT8_PTR_TYPE, "table_elem_i8p"))) { + HANDLE_FAILURE("LLVMBuildIntToPtr"); + goto fail; + } + } /* i */ POP_I32(param_values[4]); @@ -512,4 +615,4 @@ fail: return false; } -#endif /* WASM_ENABLE_REF_TYPES != 0 */ +#endif /* WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC !=0 */ diff --git a/core/iwasm/compilation/aot_emit_variable.c b/core/iwasm/compilation/aot_emit_variable.c index 31d803553..73edbf085 100644 --- a/core/iwasm/compilation/aot_emit_variable.c +++ b/core/iwasm/compilation/aot_emit_variable.c @@ -17,13 +17,21 @@ } while (0) static uint8 -get_local_type(AOTFuncContext *func_ctx, uint32 local_idx) +get_local_type(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 local_idx) { AOTFunc *aot_func = func_ctx->aot_func; uint32 param_count = aot_func->func_type->param_count; - return local_idx < param_count - ? aot_func->func_type->types[local_idx] - : aot_func->local_types[local_idx - param_count]; + uint8 local_type; + + local_type = local_idx < param_count + ? aot_func->func_type->types[local_idx] + : aot_func->local_types_wp[local_idx - param_count]; + + if (comp_ctx->enable_gc && aot_is_type_gc_reftype(local_type)) + local_type = VALUE_TYPE_GC_REF; + + return local_type; } bool @@ -37,7 +45,7 @@ aot_compile_op_get_local(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, CHECK_LOCAL(local_idx); - local_type = get_local_type(func_ctx, local_idx); + local_type = get_local_type(comp_ctx, func_ctx, local_idx); snprintf(name, sizeof(name), "%s%d%s", "local", local_idx, "#"); if (!(value = LLVMBuildLoad2(comp_ctx->builder, TO_LLVM_TYPE(local_type), @@ -58,15 +66,56 @@ fail: return false; } -bool -aot_compile_op_set_local(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, - uint32 local_idx) +static bool +aot_compile_op_set_or_tee_local(AOTCompContext *comp_ctx, + AOTFuncContext *func_ctx, uint32 local_idx, + bool is_tee_local) { LLVMValueRef value; + uint8 local_type; + uint32 n; CHECK_LOCAL(local_idx); - POP(value, get_local_type(func_ctx, local_idx)); + local_type = get_local_type(comp_ctx, func_ctx, local_idx); + + POP(value, local_type); + + if (comp_ctx->aot_frame) { + /* Get the slot index */ + n = func_ctx->aot_func->local_offsets[local_idx]; + bh_assert(comp_ctx->aot_frame->lp[n].type == local_type); + + switch (local_type) { + case VALUE_TYPE_I32: + set_local_i32(comp_ctx->aot_frame, n, value); + break; + case VALUE_TYPE_I64: + set_local_i64(comp_ctx->aot_frame, n, value); + break; + case VALUE_TYPE_F32: + set_local_f32(comp_ctx->aot_frame, n, value); + break; + case VALUE_TYPE_F64: + set_local_f64(comp_ctx->aot_frame, n, value); + break; + case VALUE_TYPE_V128: + set_local_v128(comp_ctx->aot_frame, n, value); + break; + case VALUE_TYPE_FUNCREF: + case VALUE_TYPE_EXTERNREF: + set_local_ref(comp_ctx->aot_frame, n, value, local_type); + break; +#if WASM_ENABLE_GC != 0 + case VALUE_TYPE_GC_REF: + set_local_gc_ref(comp_ctx->aot_frame, n, value, local_type); + break; +#endif + default: + bh_assert(0); + break; + } + } if (!LLVMBuildStore(comp_ctx->builder, value, func_ctx->locals[local_idx])) { @@ -74,6 +123,10 @@ aot_compile_op_set_local(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, return false; } + if (is_tee_local) { + PUSH(value, local_type); + } + aot_checked_addr_list_del(func_ctx, local_idx); return true; @@ -81,31 +134,19 @@ fail: return false; } +bool +aot_compile_op_set_local(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, + uint32 local_idx) +{ + return aot_compile_op_set_or_tee_local(comp_ctx, func_ctx, local_idx, + false); +} + bool aot_compile_op_tee_local(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, uint32 local_idx) { - LLVMValueRef value; - uint8 type; - - CHECK_LOCAL(local_idx); - - type = get_local_type(func_ctx, local_idx); - - POP(value, type); - - if (!LLVMBuildStore(comp_ctx->builder, value, - func_ctx->locals[local_idx])) { - aot_set_last_error("llvm build store fail"); - return false; - } - - PUSH(value, type); - aot_checked_addr_list_del(func_ctx, local_idx); - return true; - -fail: - return false; + return aot_compile_op_set_or_tee_local(comp_ctx, func_ctx, local_idx, true); } static bool @@ -127,17 +168,29 @@ compile_global(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, bh_assert(global_idx < import_global_count + comp_data->global_count); if (global_idx < import_global_count) { - global_offset = global_base_offset - + comp_data->import_globals[global_idx].data_offset; + global_offset = + global_base_offset + /* Get global data offset according to target info */ + + (comp_ctx->pointer_size == sizeof(uint64) + ? comp_data->import_globals[global_idx].data_offset_64bit + : comp_data->import_globals[global_idx].data_offset_32bit); global_type = comp_data->import_globals[global_idx].type; } else { global_offset = global_base_offset - + comp_data->globals[global_idx - import_global_count].data_offset; + /* Get global data offset according to target info */ + + (comp_ctx->pointer_size == sizeof(uint64) + ? comp_data->globals[global_idx - import_global_count] + .data_offset_64bit + : comp_data->globals[global_idx - import_global_count] + .data_offset_32bit); global_type = comp_data->globals[global_idx - import_global_count].type; } + if (comp_ctx->enable_gc && aot_is_type_gc_reftype(global_type)) + global_type = VALUE_TYPE_GC_REF; + offset = I32_CONST(global_offset); if (!(global_ptr = LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, func_ctx->aot_inst, &offset, 1, @@ -150,20 +203,25 @@ compile_global(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, case VALUE_TYPE_I32: case VALUE_TYPE_EXTERNREF: case VALUE_TYPE_FUNCREF: - ptr_type = comp_ctx->basic_types.int32_ptr_type; + ptr_type = INT32_PTR_TYPE; break; case VALUE_TYPE_I64: - ptr_type = comp_ctx->basic_types.int64_ptr_type; + ptr_type = INT64_PTR_TYPE; break; case VALUE_TYPE_F32: - ptr_type = comp_ctx->basic_types.float32_ptr_type; + ptr_type = F32_PTR_TYPE; break; case VALUE_TYPE_F64: - ptr_type = comp_ctx->basic_types.float64_ptr_type; + ptr_type = F64_PTR_TYPE; break; case VALUE_TYPE_V128: - ptr_type = comp_ctx->basic_types.v128_ptr_type; + ptr_type = V128_PTR_TYPE; break; +#if WASM_ENABLE_GC != 0 + case VALUE_TYPE_GC_REF: + ptr_type = GC_REF_PTR_TYPE; + break; +#endif default: bh_assert("unknown type"); break; diff --git a/core/iwasm/compilation/aot_llvm.c b/core/iwasm/compilation/aot_llvm.c index 028faf6e4..f287b9719 100644 --- a/core/iwasm/compilation/aot_llvm.c +++ b/core/iwasm/compilation/aot_llvm.c @@ -10,6 +10,7 @@ #include "aot_emit_table.h" #include "../aot/aot_runtime.h" #include "../aot/aot_intrinsic.h" +#include "../interpreter/wasm_runtime.h" #if WASM_ENABLE_DEBUG_AOT != 0 #include "debug/dwarf_extractor.h" @@ -25,13 +26,20 @@ create_native_stack_top_min(const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx); LLVMTypeRef -wasm_type_to_llvm_type(const AOTLLVMTypes *llvm_types, uint8 wasm_type) +wasm_type_to_llvm_type(const AOTCompContext *comp_ctx, + const AOTLLVMTypes *llvm_types, uint8 wasm_type) { switch (wasm_type) { case VALUE_TYPE_I32: + return llvm_types->int32_type; case VALUE_TYPE_FUNCREF: case VALUE_TYPE_EXTERNREF: - return llvm_types->int32_type; + if (comp_ctx->enable_ref_types) + return llvm_types->int32_type; + else { + bh_assert(comp_ctx->enable_gc); + return llvm_types->gc_ref_type; + } case VALUE_TYPE_I64: return llvm_types->int64_type; case VALUE_TYPE_F32: @@ -42,9 +50,31 @@ wasm_type_to_llvm_type(const AOTLLVMTypes *llvm_types, uint8 wasm_type) return llvm_types->i64x2_vec_type; case VALUE_TYPE_VOID: return llvm_types->void_type; + case REF_TYPE_NULLFUNCREF: + case REF_TYPE_NULLEXTERNREF: + case REF_TYPE_NULLREF: + /* case REF_TYPE_FUNCREF: */ + /* case REF_TYPE_EXTERNREF: */ + case REF_TYPE_ANYREF: + case REF_TYPE_EQREF: + case REF_TYPE_HT_NULLABLE: + case REF_TYPE_HT_NON_NULLABLE: + case REF_TYPE_I31REF: + case REF_TYPE_STRUCTREF: + case REF_TYPE_ARRAYREF: +#if WASM_ENABLE_STRINGREF != 0 + case REF_TYPE_STRINGREF: + case REF_TYPE_STRINGVIEWWTF8: + case REF_TYPE_STRINGVIEWWTF16: + case REF_TYPE_STRINGVIEWITER: +#endif + case VALUE_TYPE_GC_REF: + bh_assert(comp_ctx->enable_gc); + return llvm_types->gc_ref_type; default: break; } + bh_assert(0); return NULL; } @@ -245,30 +275,17 @@ aot_estimate_stack_usage_for_function_call(const AOTCompContext *comp_ctx, return size; } -static uint32 -get_inst_extra_offset(AOTCompContext *comp_ctx) -{ - const AOTCompData *comp_data = comp_ctx->comp_data; - uint32 table_count = comp_data->import_table_count + comp_data->table_count; - uint64 offset = get_tbl_inst_offset(comp_ctx, NULL, table_count); - uint32 offset_32 = (uint32)offset; - bh_assert(offset <= UINT32_MAX); - offset_32 = align_uint((uint32)offset_32, 8); - return offset_32; -} - /* * a "precheck" function performs a few things before calling wrapped_func. * * - update native_stack_top_min if necessary * - stack overflow check (if it does, trap) */ -static LLVMValueRef -aot_add_precheck_function(AOTCompContext *comp_ctx, LLVMModuleRef module, - uint32 func_index, uint32 orig_param_count, - LLVMTypeRef func_type, LLVMValueRef wrapped_func) +static bool +aot_build_precheck_function(AOTCompContext *comp_ctx, LLVMModuleRef module, + LLVMValueRef precheck_func, uint32 func_index, + LLVMTypeRef func_type, LLVMValueRef wrapped_func) { - LLVMValueRef precheck_func; LLVMBasicBlockRef begin = NULL; LLVMBasicBlockRef check_top_block = NULL; LLVMBasicBlockRef update_top_block = NULL; @@ -276,12 +293,6 @@ aot_add_precheck_function(AOTCompContext *comp_ctx, LLVMModuleRef module, LLVMBasicBlockRef call_wrapped_func_block = NULL; LLVMValueRef *params = NULL; - precheck_func = - aot_add_llvm_func1(comp_ctx, module, func_index, orig_param_count, - func_type, AOT_FUNC_PREFIX); - if (!precheck_func) { - goto fail; - } begin = LLVMAppendBasicBlockInContext(comp_ctx->context, precheck_func, "begin"); check_top_block = LLVMAppendBasicBlockInContext( @@ -360,7 +371,7 @@ aot_add_precheck_function(AOTCompContext *comp_ctx, LLVMModuleRef module, LLVMValueRef offset; LLVMValueRef stack_sizes_p; - offset_u32 = get_inst_extra_offset(comp_ctx); + offset_u32 = get_module_inst_extra_offset(comp_ctx); offset_u32 += offsetof(AOTModuleInstanceExtra, stack_sizes); offset = I32_CONST(offset_u32); if (!offset) { @@ -550,13 +561,51 @@ aot_add_precheck_function(AOTCompContext *comp_ctx, LLVMModuleRef module, } } - return precheck_func; + return true; fail: if (params != NULL) { wasm_runtime_free(params); } aot_set_last_error("failed to build precheck wrapper function."); - return NULL; + return false; +} + +static bool +check_wasm_type(AOTCompContext *comp_ctx, uint8 type) +{ + if (type == VALUE_TYPE_FUNCREF || type == VALUE_TYPE_EXTERNREF) { + if (!comp_ctx->enable_ref_types && !comp_ctx->enable_gc) { + aot_set_last_error("funcref or externref type was found, " + "try removing --disable-ref-types option " + "or adding --enable-gc option."); + return false; + } + else + return true; + } + else if (aot_is_type_gc_reftype(type)) { + if (!comp_ctx->enable_gc) { + aot_set_last_error("GC reference type was found, " + "try adding --enable-gc option."); + return false; + } + else + return true; + } + else if (type == VALUE_TYPE_V128) { + if (!comp_ctx->enable_simd) { + aot_set_last_error("SIMD type was found, try removing " + " --disable-simd option."); + return false; + } + return true; + } + else if (type != VALUE_TYPE_I32 && type != VALUE_TYPE_I64 + && type != VALUE_TYPE_F32 && type != VALUE_TYPE_F64) { + bh_assert(0); + } + + return true; } /** @@ -567,6 +616,8 @@ aot_add_llvm_func(AOTCompContext *comp_ctx, LLVMModuleRef module, const AOTFuncType *aot_func_type, uint32 func_index, LLVMTypeRef *p_func_type, LLVMValueRef *p_precheck_func) { + WASMFunction *aot_func = + comp_ctx->comp_data->wasm_module->functions[func_index]; LLVMValueRef func = NULL; LLVMTypeRef *param_types, ret_type, func_type; LLVMTypeRef func_type_wrapper; @@ -577,6 +628,18 @@ aot_add_llvm_func(AOTCompContext *comp_ctx, LLVMModuleRef module, uint32 i, j = 0, param_count = (uint64)aot_func_type->param_count; uint32 backend_thread_num, compile_thread_num; + /* Check function parameter types and result types */ + for (i = 0; i < aot_func_type->param_count + aot_func_type->result_count; + i++) { + if (!check_wasm_type(comp_ctx, aot_func_type->types[i])) + return NULL; + } + /* Check function local types */ + for (i = 0; i < aot_func->local_count; i++) { + if (!check_wasm_type(comp_ctx, aot_func->local_types[i])) + return NULL; + } + /* exec env as first parameter */ param_count++; @@ -623,10 +686,19 @@ aot_add_llvm_func(AOTCompContext *comp_ctx, LLVMModuleRef module, bh_assert(func_index < comp_ctx->func_ctx_count); bh_assert(LLVMGetReturnType(func_type) == ret_type); + const char *prefix = AOT_FUNC_PREFIX; const bool need_precheck = comp_ctx->enable_stack_bound_check || comp_ctx->enable_stack_estimation; + LLVMValueRef precheck_func = NULL; + if (need_precheck) { + precheck_func = aot_add_llvm_func1(comp_ctx, module, func_index, + aot_func_type->param_count, + func_type, AOT_FUNC_PREFIX); + if (!precheck_func) { + goto fail; + } /* * REVISIT: probably this breaks windows hw bound check * (the RtlAddFunctionTable stuff) @@ -671,10 +743,8 @@ aot_add_llvm_func(AOTCompContext *comp_ctx, LLVMModuleRef module, LLVMAddAttributeAtIndex(func, LLVMAttributeFunctionIndex, attr_noinline); - LLVMValueRef precheck_func = aot_add_precheck_function( - comp_ctx, module, func_index, aot_func_type->param_count, func_type, - func); - if (!precheck_func) + if (!aot_build_precheck_function(comp_ctx, module, precheck_func, + func_index, func_type, func)) goto fail; LLVMAddAttributeAtIndex(precheck_func, LLVMAttributeFunctionIndex, attr_noinline); @@ -923,6 +993,49 @@ create_aux_stack_info(const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) return true; } +static bool +create_aux_stack_frame(const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) +{ + LLVMValueRef wasm_stack_top_bound_ptr, offset; + + offset = I32_ONE; + if (!(func_ctx->cur_frame_ptr = LLVMBuildInBoundsGEP2( + comp_ctx->builder, OPQ_PTR_TYPE, func_ctx->exec_env, &offset, 1, + "cur_frame_ptr"))) { + aot_set_last_error("llvm build in bounds gep failed"); + return false; + } + + if (!(func_ctx->cur_frame = + LLVMBuildLoad2(comp_ctx->builder, OPQ_PTR_TYPE, + func_ctx->cur_frame_ptr, "cur_frame"))) { + aot_set_last_error("llvm build load failed"); + return false; + } + + /* Get exec_env->wasm_stack.top_boundary and its address */ + offset = I32_TEN; + if (!(wasm_stack_top_bound_ptr = LLVMBuildInBoundsGEP2( + comp_ctx->builder, OPQ_PTR_TYPE, func_ctx->exec_env, &offset, 1, + "wasm_stack_top_bound_ptr")) + || !(func_ctx->wasm_stack_top_bound = LLVMBuildLoad2( + comp_ctx->builder, INT8_PTR_TYPE, wasm_stack_top_bound_ptr, + "wasm_stack_top_bound"))) { + aot_set_last_error("load wasm_stack.top_boundary failed"); + return false; + } + + offset = I32_ELEVEN; + if (!(func_ctx->wasm_stack_top_ptr = LLVMBuildInBoundsGEP2( + comp_ctx->builder, OPQ_PTR_TYPE, func_ctx->exec_env, &offset, 1, + "wasm_stack_top_ptr"))) { + aot_set_last_error("llvm build inbounds gep failed"); + return false; + } + + return true; +} + static bool create_native_symbol(const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) { @@ -957,7 +1070,8 @@ create_local_variables(const AOTCompData *comp_data, const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, const AOTFunc *func) { - AOTFuncType *aot_func_type = comp_data->func_types[func->func_type_index]; + AOTFuncType *aot_func_type = + (AOTFuncType *)comp_data->types[func->func_type_index]; char local_name[32]; uint32 i, j = 1; @@ -982,14 +1096,14 @@ create_local_variables(const AOTCompData *comp_data, LLVMValueRef local_value = NULL; snprintf(local_name, sizeof(local_name), "l%d", aot_func_type->param_count + i); - local_type = TO_LLVM_TYPE(func->local_types[i]); + local_type = TO_LLVM_TYPE(func->local_types_wp[i]); func_ctx->locals[aot_func_type->param_count + i] = LLVMBuildAlloca(comp_ctx->builder, local_type, local_name); if (!func_ctx->locals[aot_func_type->param_count + i]) { aot_set_last_error("llvm build alloca failed."); return false; } - switch (func->local_types[i]) { + switch (func->local_types_wp[i]) { case VALUE_TYPE_I32: local_value = I32_ZERO; break; @@ -1007,8 +1121,33 @@ create_local_variables(const AOTCompData *comp_data, break; case VALUE_TYPE_FUNCREF: case VALUE_TYPE_EXTERNREF: - local_value = REF_NULL; + if (!comp_ctx->enable_gc) + local_value = REF_NULL; + else + local_value = GC_REF_NULL; break; +#if WASM_ENABLE_GC != 0 + case REF_TYPE_NULLFUNCREF: + case REF_TYPE_NULLEXTERNREF: + case REF_TYPE_NULLREF: + /* case REF_TYPE_FUNCREF: */ + /* case REF_TYPE_EXTERNREF: */ + case REF_TYPE_ANYREF: + case REF_TYPE_EQREF: + case REF_TYPE_HT_NULLABLE: + case REF_TYPE_HT_NON_NULLABLE: + case REF_TYPE_I31REF: + case REF_TYPE_STRUCTREF: + case REF_TYPE_ARRAYREF: +#if WASM_ENABLE_STRINGREF != 0 + case REF_TYPE_STRINGREF: + case REF_TYPE_STRINGVIEWWTF8: + case REF_TYPE_STRINGVIEWWTF16: + case REF_TYPE_STRINGVIEWITER: +#endif + local_value = GC_REF_NULL; + break; +#endif default: bh_assert(0); break; @@ -1541,7 +1680,8 @@ aot_create_func_context(const AOTCompData *comp_data, AOTCompContext *comp_ctx, AOTFunc *func, uint32 func_index) { AOTFuncContext *func_ctx; - AOTFuncType *aot_func_type = comp_data->func_types[func->func_type_index]; + AOTFuncType *aot_func_type = + (AOTFuncType *)comp_data->types[func->func_type_index]; WASMModule *module = comp_ctx->comp_data->wasm_module; WASMFunction *wasm_func = module->functions[func_index]; AOTBlock *aot_block; @@ -1599,6 +1739,11 @@ aot_create_func_context(const AOTCompData *comp_data, AOTCompContext *comp_ctx, goto fail; } + if (comp_ctx->enable_aux_stack_frame + && !create_aux_stack_frame(comp_ctx, func_ctx)) { + goto fail; + } + /* Create local variables */ if (!create_local_variables(comp_data, comp_ctx, func_ctx, func)) { goto fail; @@ -1636,13 +1781,14 @@ aot_create_func_context(const AOTCompData *comp_data, AOTCompContext *comp_ctx, fail: if (func_ctx->mem_info) wasm_runtime_free(func_ctx->mem_info); - aot_block_stack_destroy(&func_ctx->block_stack); + aot_block_stack_destroy(comp_ctx, &func_ctx->block_stack); wasm_runtime_free(func_ctx); return NULL; } static void -aot_destroy_func_contexts(AOTFuncContext **func_ctxes, uint32 count) +aot_destroy_func_contexts(AOTCompContext *comp_ctx, AOTFuncContext **func_ctxes, + uint32 count) { uint32 i; @@ -1650,7 +1796,7 @@ aot_destroy_func_contexts(AOTFuncContext **func_ctxes, uint32 count) if (func_ctxes[i]) { if (func_ctxes[i]->mem_info) wasm_runtime_free(func_ctxes[i]->mem_info); - aot_block_stack_destroy(&func_ctxes[i]->block_stack); + aot_block_stack_destroy(comp_ctx, &func_ctxes[i]->block_stack); aot_checked_addr_list_destroy(func_ctxes[i]); wasm_runtime_free(func_ctxes[i]); } @@ -1687,7 +1833,8 @@ aot_create_func_contexts(const AOTCompData *comp_data, AOTCompContext *comp_ctx) AOTFunc *func = comp_data->funcs[i]; if (!(func_ctxes[i] = aot_create_func_context(comp_data, comp_ctx, func, i))) { - aot_destroy_func_contexts(func_ctxes, comp_data->func_count); + aot_destroy_func_contexts(comp_ctx, func_ctxes, + comp_data->func_count); return NULL; } } @@ -1696,7 +1843,8 @@ aot_create_func_contexts(const AOTCompData *comp_data, AOTCompContext *comp_ctx) } static bool -aot_set_llvm_basic_types(AOTLLVMTypes *basic_types, LLVMContextRef context) +aot_set_llvm_basic_types(AOTLLVMTypes *basic_types, LLVMContextRef context, + int pointer_size) { basic_types->int1_type = LLVMInt1TypeInContext(context); basic_types->int8_type = LLVMInt8TypeInContext(context); @@ -1761,15 +1909,29 @@ aot_set_llvm_basic_types(AOTLLVMTypes *basic_types, LLVMContextRef context) basic_types->funcref_type = LLVMInt32TypeInContext(context); basic_types->externref_type = LLVMInt32TypeInContext(context); + if (pointer_size == 4) { + basic_types->intptr_t_type = basic_types->int32_type; + basic_types->intptr_t_ptr_type = basic_types->int32_ptr_type; + } + else { + basic_types->intptr_t_type = basic_types->int64_type; + basic_types->intptr_t_ptr_type = basic_types->int64_ptr_type; + } + + basic_types->gc_ref_type = LLVMPointerType(basic_types->void_type, 0); + basic_types->gc_ref_ptr_type = LLVMPointerType(basic_types->gc_ref_type, 0); + return (basic_types->int8_ptr_type && basic_types->int8_pptr_type && basic_types->int16_ptr_type && basic_types->int32_ptr_type - && basic_types->int64_ptr_type && basic_types->float32_ptr_type + && basic_types->int64_ptr_type && basic_types->intptr_t_type + && basic_types->intptr_t_ptr_type && basic_types->float32_ptr_type && basic_types->float64_ptr_type && basic_types->i8x16_vec_type && basic_types->i16x8_vec_type && basic_types->i32x4_vec_type && basic_types->i64x2_vec_type && basic_types->f32x4_vec_type && basic_types->f64x2_vec_type && basic_types->i1x2_vec_type && basic_types->meta_data_type && basic_types->funcref_type - && basic_types->externref_type) + && basic_types->externref_type && basic_types->gc_ref_type + && basic_types->gc_ref_ptr_type) ? true : false; } @@ -1789,6 +1951,9 @@ aot_create_llvm_consts(AOTLLVMConsts *consts, AOTCompContext *comp_ctx) if (!(consts->i8_zero = I8_CONST(0))) return false; + if (!(consts->i8_one = I8_CONST(1))) + return false; + if (!(consts->f32_zero = F32_CONST(0))) return false; @@ -1859,6 +2024,13 @@ aot_create_llvm_consts(AOTLLVMConsts *consts, AOTCompContext *comp_ctx) CREATE_VEC_ZERO_MASK(2) #undef CREATE_VEC_ZERO_MASK + if (!(consts->gc_ref_null = + LLVMConstNull(comp_ctx->basic_types.gc_ref_type))) + return false; + if (!(consts->i8_ptr_null = + LLVMConstNull(comp_ctx->basic_types.int8_ptr_type))) + return false; + return true; } @@ -2371,6 +2543,12 @@ aot_create_comp_context(const AOTCompData *comp_data, aot_comp_option_t option) if (option->enable_aux_stack_frame) comp_ctx->enable_aux_stack_frame = true; + if (option->enable_perf_profiling) + comp_ctx->enable_perf_profiling = true; + + if (option->enable_memory_profiling) + comp_ctx->enable_memory_profiling = true; + if (option->enable_aux_stack_check) comp_ctx->enable_aux_stack_check = true; @@ -2401,6 +2579,9 @@ aot_create_comp_context(const AOTCompData *comp_data, aot_comp_option_t option) if (option->builtin_intrinsics) comp_ctx->builtin_intrinsics = option->builtin_intrinsics; + if (option->enable_gc) + comp_ctx->enable_gc = true; + comp_ctx->opt_level = option->opt_level; comp_ctx->size_level = option->size_level; @@ -2887,6 +3068,29 @@ aot_create_comp_context(const AOTCompData *comp_data, aot_comp_option_t option) } LLVMDisposeMessage(triple); +#if WASM_ENABLE_WAMR_COMPILER != 0 + WASMModule *wasm_module = (WASMModule *)comp_data->wasm_module; + + /* Return error if SIMD is disabled by command line but SIMD instructions + * are used */ + if (!option->enable_simd && wasm_module->is_simd_used) { + aot_set_last_error("SIMD is disabled by --disable-simd but SIMD " + "instructions are used in this module"); + goto fail; + } + + /* Disable features when they are not actually used */ + if (!wasm_module->is_simd_used) { + option->enable_simd = comp_ctx->enable_simd = false; + } + if (!wasm_module->is_ref_types_used) { + option->enable_ref_types = comp_ctx->enable_ref_types = false; + } + if (!wasm_module->is_bulk_memory_used) { + option->enable_bulk_memory = comp_ctx->enable_bulk_memory = false; + } +#endif + if (option->enable_simd && strcmp(comp_ctx->target_arch, "x86_64") != 0 && strncmp(comp_ctx->target_arch, "aarch64", 7) != 0) { /* Disable simd if it isn't supported by target arch */ @@ -2937,7 +3141,8 @@ aot_create_comp_context(const AOTCompData *comp_data, aot_comp_option_t option) goto fail; } - if (!aot_set_llvm_basic_types(&comp_ctx->basic_types, comp_ctx->context)) { + if (!aot_set_llvm_basic_types(&comp_ctx->basic_types, comp_ctx->context, + comp_ctx->pointer_size)) { aot_set_last_error("create LLVM basic types failed."); goto fail; } @@ -3015,7 +3220,7 @@ aot_destroy_comp_context(AOTCompContext *comp_ctx) LLVMOrcDisposeLLLazyJIT(comp_ctx->orc_jit); if (comp_ctx->func_ctxes) - aot_destroy_func_contexts(comp_ctx->func_ctxes, + aot_destroy_func_contexts(comp_ctx, comp_ctx->func_ctxes, comp_ctx->func_ctx_count); if (bh_list_length(&comp_ctx->native_symbols) > 0) { @@ -3032,6 +3237,10 @@ aot_destroy_comp_context(AOTCompContext *comp_ctx) wasm_runtime_free(comp_ctx->target_cpu); } + if (comp_ctx->aot_frame) { + wasm_runtime_free(comp_ctx->aot_frame); + } + wasm_runtime_free(comp_ctx); } @@ -3110,7 +3319,8 @@ aot_get_native_symbol_index(AOTCompContext *comp_ctx, const char *symbol) } void -aot_value_stack_push(AOTValueStack *stack, AOTValue *value) +aot_value_stack_push(const AOTCompContext *comp_ctx, AOTValueStack *stack, + AOTValue *value) { if (!stack->value_list_head) stack->value_list_head = stack->value_list_end = value; @@ -3119,10 +3329,44 @@ aot_value_stack_push(AOTValueStack *stack, AOTValue *value) value->prev = stack->value_list_end; stack->value_list_end = value; } + + if (comp_ctx->aot_frame) { + switch (value->type) { + case VALUE_TYPE_I32: + case VALUE_TYPE_I1: + push_i32(comp_ctx->aot_frame, value); + break; + case VALUE_TYPE_I64: + push_i64(comp_ctx->aot_frame, value); + break; + case VALUE_TYPE_F32: + push_f32(comp_ctx->aot_frame, value); + break; + case VALUE_TYPE_F64: + push_f64(comp_ctx->aot_frame, value); + break; + case VALUE_TYPE_V128: + push_v128(comp_ctx->aot_frame, value); + break; + case VALUE_TYPE_FUNCREF: + case VALUE_TYPE_EXTERNREF: + push_ref(comp_ctx->aot_frame, value); + break; +#if WASM_ENABLE_GC != 0 + case VALUE_TYPE_GC_REF: + bh_assert(comp_ctx->enable_gc); + push_gc_ref(comp_ctx->aot_frame, value); + break; +#endif + default: + bh_assert(0); + break; + } + } } AOTValue * -aot_value_stack_pop(AOTValueStack *stack) +aot_value_stack_pop(const AOTCompContext *comp_ctx, AOTValueStack *stack) { AOTValue *value = stack->value_list_end; @@ -3136,11 +3380,49 @@ aot_value_stack_pop(AOTValueStack *stack) value->prev = NULL; } + if (comp_ctx->aot_frame) { + bh_assert(value); + bh_assert(value->value == (comp_ctx->aot_frame->sp - 1)->value); + bh_assert(value->type == (comp_ctx->aot_frame->sp - 1)->type); + + switch (value->type) { + case VALUE_TYPE_I32: + case VALUE_TYPE_I1: + pop_i32(comp_ctx->aot_frame); + break; + case VALUE_TYPE_I64: + pop_i64(comp_ctx->aot_frame); + break; + case VALUE_TYPE_F32: + pop_f32(comp_ctx->aot_frame); + break; + case VALUE_TYPE_F64: + pop_f64(comp_ctx->aot_frame); + break; + case VALUE_TYPE_V128: + pop_v128(comp_ctx->aot_frame); + break; + case VALUE_TYPE_FUNCREF: + case VALUE_TYPE_EXTERNREF: + pop_ref(comp_ctx->aot_frame); + break; +#if WASM_ENABLE_GC != 0 + case VALUE_TYPE_GC_REF: + bh_assert(comp_ctx->enable_gc); + pop_gc_ref(comp_ctx->aot_frame); + break; +#endif + default: + bh_assert(0); + break; + } + } + return value; } void -aot_value_stack_destroy(AOTValueStack *stack) +aot_value_stack_destroy(AOTCompContext *comp_ctx, AOTValueStack *stack) { AOTValue *value = stack->value_list_head, *p; @@ -3185,14 +3467,14 @@ aot_block_stack_pop(AOTBlockStack *stack) } void -aot_block_stack_destroy(AOTBlockStack *stack) +aot_block_stack_destroy(AOTCompContext *comp_ctx, AOTBlockStack *stack) { AOTBlock *block = stack->block_list_head, *p; while (block) { p = block->next; - aot_value_stack_destroy(&block->value_stack); - aot_block_destroy(block); + aot_value_stack_destroy(comp_ctx, &block->value_stack); + aot_block_destroy(comp_ctx, block); block = p; } @@ -3201,9 +3483,9 @@ aot_block_stack_destroy(AOTBlockStack *stack) } void -aot_block_destroy(AOTBlock *block) +aot_block_destroy(AOTCompContext *comp_ctx, AOTBlock *block) { - aot_value_stack_destroy(&block->value_stack); + aot_value_stack_destroy(comp_ctx, &block->value_stack); if (block->param_types) wasm_runtime_free(block->param_types); if (block->param_phis) @@ -3318,8 +3600,38 @@ aot_build_zero_function_ret(const AOTCompContext *comp_ctx, break; case VALUE_TYPE_FUNCREF: case VALUE_TYPE_EXTERNREF: - ret = LLVMBuildRet(comp_ctx->builder, REF_NULL); + if (comp_ctx->enable_ref_types) + ret = LLVMBuildRet(comp_ctx->builder, REF_NULL); +#if WASM_ENABLE_GC != 0 + else if (comp_ctx->enable_gc) + ret = LLVMBuildRet(comp_ctx->builder, GC_REF_NULL); +#endif + else + bh_assert(0); break; +#if WASM_ENABLE_GC != 0 + case REF_TYPE_NULLFUNCREF: + case REF_TYPE_NULLEXTERNREF: + case REF_TYPE_NULLREF: + /* case REF_TYPE_FUNCREF: */ + /* case REF_TYPE_EXTERNREF: */ + case REF_TYPE_ANYREF: + case REF_TYPE_EQREF: + case REF_TYPE_HT_NULLABLE: + case REF_TYPE_HT_NON_NULLABLE: + case REF_TYPE_I31REF: + case REF_TYPE_STRUCTREF: + case REF_TYPE_ARRAYREF: +#if WASM_ENABLE_STRINGREF != 0 + case REF_TYPE_STRINGREF: + case REF_TYPE_STRINGVIEWWTF8: + case REF_TYPE_STRINGVIEWWTF16: + case REF_TYPE_STRINGVIEWITER: +#endif + bh_assert(comp_ctx->enable_gc); + ret = LLVMBuildRet(comp_ctx->builder, GC_REF_NULL); + break; +#endif default: bh_assert(0); } diff --git a/core/iwasm/compilation/aot_llvm.h b/core/iwasm/compilation/aot_llvm.h index bb7534e5c..a47c054c9 100644 --- a/core/iwasm/compilation/aot_llvm.h +++ b/core/iwasm/compilation/aot_llvm.h @@ -35,6 +35,7 @@ #endif #include "aot_orc_extra.h" +#include "aot_comp_option.h" #ifdef __cplusplus extern "C" { @@ -64,6 +65,8 @@ extern "C" { #undef DUMP_MODULE #endif +struct AOTValueSlot; + /** * Value in the WASM operation stack, each stack element * is an LLVM value @@ -86,6 +89,53 @@ typedef struct AOTValueStack { AOTValue *value_list_end; } AOTValueStack; +/* Record information of a value slot of local variable or stack + during translation */ +typedef struct AOTValueSlot { + /* The LLVM value of this slot */ + LLVMValueRef value; + + /* The value type of this slot */ + uint8 type; + + /* The dirty bit of the value slot. It's set if the value in + register is newer than the value in memory. */ + uint32 dirty : 1; + + /* Whether the new value in register is a reference, which is valid + only when the dirty bit is set. */ + uint32 ref : 1; + + /* Committed reference flag: + 0: uncommitted, 1: not-reference, 2: reference */ + uint32 committed_ref : 2; +} AOTValueSlot; + +/* Frame information for translation */ +typedef struct AOTCompFrame { + /* The current compilation context */ + struct AOTCompContext *comp_ctx; + /* The current function context */ + struct AOTFuncContext *func_ctx; + /* The current instruction pointer which is being compiled */ + const uint8 *frame_ip; + + /* Max local slot number */ + uint32 max_local_cell_num; + + /* Max operand stack slot number */ + uint32 max_stack_cell_num; + + /* Size of current AOTFrame/WASMInterpFrame */ + uint32 cur_frame_size; + + /* Stack top pointer */ + AOTValueSlot *sp; + + /* Local variables + stack operands */ + AOTValueSlot lp[1]; +} AOTCompFrame; + typedef struct AOTBlock { struct AOTBlock *next; struct AOTBlock *prev; @@ -124,6 +174,12 @@ typedef struct AOTBlock { uint32 result_count; uint8 *result_types; LLVMValueRef *result_phis; + + /* The begin frame stack pointer of this block */ + AOTValueSlot *frame_sp_begin; + /* The max frame stack pointer that br/br_if/br_table/br_on_xxx + opcodes ever reached when they jumped to the end this block */ + AOTValueSlot *frame_sp_max_reached; } AOTBlock; /** @@ -176,12 +232,19 @@ typedef struct AOTFuncContext { LLVMValueRef cur_exception; + LLVMValueRef cur_frame; + LLVMValueRef cur_frame_ptr; + LLVMValueRef wasm_stack_top_bound; + LLVMValueRef wasm_stack_top_ptr; + bool mem_space_unchanged; AOTCheckedAddrList checked_addr_list; LLVMBasicBlockRef got_exception_block; LLVMBasicBlockRef func_return_block; LLVMValueRef exception_id_phi; + /* current ip when exception is thrown */ + LLVMValueRef exception_ip_phi; LLVMValueRef func_type_indexes; #if WASM_ENABLE_DEBUG_AOT != 0 LLVMMetadataRef debug_func; @@ -198,6 +261,7 @@ typedef struct AOTLLVMTypes { LLVMTypeRef int16_type; LLVMTypeRef int32_type; LLVMTypeRef int64_type; + LLVMTypeRef intptr_t_type; LLVMTypeRef float32_type; LLVMTypeRef float64_type; LLVMTypeRef void_type; @@ -207,6 +271,7 @@ typedef struct AOTLLVMTypes { LLVMTypeRef int16_ptr_type; LLVMTypeRef int32_ptr_type; LLVMTypeRef int64_ptr_type; + LLVMTypeRef intptr_t_ptr_type; LLVMTypeRef float32_ptr_type; LLVMTypeRef float64_ptr_type; @@ -233,12 +298,15 @@ typedef struct AOTLLVMTypes { LLVMTypeRef funcref_type; LLVMTypeRef externref_type; + LLVMTypeRef gc_ref_type; + LLVMTypeRef gc_ref_ptr_type; } AOTLLVMTypes; typedef struct AOTLLVMConsts { LLVMValueRef i1_zero; LLVMValueRef i1_one; LLVMValueRef i8_zero; + LLVMValueRef i8_one; LLVMValueRef i32_zero; LLVMValueRef i64_zero; LLVMValueRef f32_zero; @@ -282,6 +350,8 @@ typedef struct AOTLLVMConsts { LLVMValueRef i32x8_zero; LLVMValueRef i32x4_zero; LLVMValueRef i32x2_zero; + LLVMValueRef gc_ref_null; + LLVMValueRef i8_ptr_null; } AOTLLVMConsts; /** @@ -339,6 +409,12 @@ typedef struct AOTCompContext { /* Generate auxiliary stack frame */ bool enable_aux_stack_frame; + /* Function performance profiling */ + bool enable_perf_profiling; + + /* Memory usage profiling */ + bool enable_memory_profiling; + /* Thread Manager */ bool enable_thread_mgr; @@ -380,6 +456,11 @@ typedef struct AOTCompContext { /* Whether optimize the JITed code */ bool optimize; + bool emit_frame_pointer; + + /* Enable GC */ + bool enable_gc; + uint32 opt_level; uint32 size_level; @@ -403,7 +484,6 @@ typedef struct AOTCompContext { AOTLLVMConsts llvm_consts; /* Function contexts */ - /* TODO: */ AOTFuncContext **func_ctxes; uint32 func_ctx_count; char **custom_sections_wp; @@ -428,7 +508,8 @@ typedef struct AOTCompContext { const char *llvm_passes; const char *builtin_intrinsics; - bool emit_frame_pointer; + /* Current frame information for translation */ + AOTCompFrame *aot_frame; } AOTCompContext; enum { @@ -438,41 +519,6 @@ enum { AOT_LLVMIR_OPT_FILE, }; -/* always sync it with AOTCompOption in aot_export.h */ -typedef struct AOTCompOption { - bool is_jit_mode; - bool is_indirect_mode; - char *target_arch; - char *target_abi; - char *target_cpu; - char *cpu_features; - bool is_sgx_platform; - bool enable_bulk_memory; - bool enable_thread_mgr; - bool enable_tail_call; - bool enable_simd; - bool enable_ref_types; - bool enable_aux_stack_check; - bool enable_aux_stack_frame; - bool disable_llvm_intrinsics; - bool disable_llvm_lto; - bool enable_llvm_pgo; - bool enable_stack_estimation; - bool quick_invoke_c_api_import; - char *use_prof_file; - uint32 opt_level; - uint32 size_level; - uint32 output_format; - uint32 bounds_checks; - uint32 stack_bounds_checks; - uint32 segue_flags; - char **custom_sections; - uint32 custom_sections_count; - const char *stack_usage_file; - const char *llvm_passes; - const char *builtin_intrinsics; -} AOTCompOption, *aot_comp_option_t; - bool aot_compiler_init(void); @@ -498,13 +544,14 @@ void aot_destroy_elf_file(uint8 *elf_file); void -aot_value_stack_push(AOTValueStack *stack, AOTValue *value); +aot_value_stack_push(const AOTCompContext *comp_ctx, AOTValueStack *stack, + AOTValue *value); AOTValue * -aot_value_stack_pop(AOTValueStack *stack); +aot_value_stack_pop(const AOTCompContext *comp_ctx, AOTValueStack *stack); void -aot_value_stack_destroy(AOTValueStack *stack); +aot_value_stack_destroy(AOTCompContext *comp_ctx, AOTValueStack *stack); void aot_block_stack_push(AOTBlockStack *stack, AOTBlock *block); @@ -513,13 +560,14 @@ AOTBlock * aot_block_stack_pop(AOTBlockStack *stack); void -aot_block_stack_destroy(AOTBlockStack *stack); +aot_block_stack_destroy(AOTCompContext *comp_ctx, AOTBlockStack *stack); void -aot_block_destroy(AOTBlock *block); +aot_block_destroy(AOTCompContext *comp_ctx, AOTBlock *block); LLVMTypeRef -wasm_type_to_llvm_type(const AOTLLVMTypes *llvm_types, uint8 wasm_type); +wasm_type_to_llvm_type(const AOTCompContext *comp_ctx, + const AOTLLVMTypes *llvm_types, uint8 wasm_type); bool aot_checked_addr_list_add(AOTFuncContext *func_ctx, uint32 local_idx, diff --git a/core/iwasm/fast-jit/cg/x86-64/jit_codegen_x86_64.cpp b/core/iwasm/fast-jit/cg/x86-64/jit_codegen_x86_64.cpp index 65c4bb5e3..f5605b6f2 100644 --- a/core/iwasm/fast-jit/cg/x86-64/jit_codegen_x86_64.cpp +++ b/core/iwasm/fast-jit/cg/x86-64/jit_codegen_x86_64.cpp @@ -8461,7 +8461,7 @@ jit_codegen_compile_call_to_llvm_jit(const WASMType *func_type) /* r10 = outs_area->lp */ { x86::Mem m(regs_i64[hreg_info->exec_env_hreg_index], - (uint32)offsetof(WASMExecEnv, wasm_stack.s.top)); + (uint32)offsetof(WASMExecEnv, wasm_stack.top)); a.mov(reg_lp, m); a.add(reg_lp, (uint32)offsetof(WASMInterpFrame, lp)); } @@ -8701,15 +8701,15 @@ fast_jit_alloc_frame(WASMExecEnv *exec_env, uint32 param_cell_num, * frame to store the function results from jit function to call, * the second is the frame for the jit function */ - if ((uint8 *)exec_env->wasm_stack.s.top + size_frame1 + size_frame2 - > exec_env->wasm_stack.s.top_boundary) { + if ((uint8 *)exec_env->wasm_stack.top + size_frame1 + size_frame2 + > exec_env->wasm_stack.top_boundary) { wasm_set_exception(module_inst, "wasm operand stack overflow"); return NULL; } /* Allocate the frame */ - frame = (WASMInterpFrame *)exec_env->wasm_stack.s.top; - exec_env->wasm_stack.s.top += size_frame1; + frame = (WASMInterpFrame *)exec_env->wasm_stack.top; + exec_env->wasm_stack.top += size_frame1; frame->function = NULL; frame->ip = NULL; @@ -9073,9 +9073,9 @@ jit_codegen_compile_call_to_fast_jit(const WASMModule *module, uint32 func_idx) /* rdx = exec_env->cur_frame->prev_frame */ a.mov(x86::rdx, x86::ptr(x86::rsi, (uint32)offsetof(WASMInterpFrame, prev_frame))); - /* exec_env->wasm_stack.s.top = cur_frame */ + /* exec_env->wasm_stack.top = cur_frame */ { - x86::Mem m(x86::rdi, offsetof(WASMExecEnv, wasm_stack.s.top)); + x86::Mem m(x86::rdi, offsetof(WASMExecEnv, wasm_stack.top)); a.mov(m, x86::rsi); } /* exec_env->cur_frame = prev_frame */ diff --git a/core/iwasm/fast-jit/fe/jit_emit_control.c b/core/iwasm/fast-jit/fe/jit_emit_control.c index 47ab1d51e..9274e7217 100644 --- a/core/iwasm/fast-jit/fe/jit_emit_control.c +++ b/core/iwasm/fast-jit/fe/jit_emit_control.c @@ -396,8 +396,9 @@ handle_func_return(JitCompContext *cc, JitBlock *block) #endif #if WASM_ENABLE_PERF_PROFILING != 0 - /* time_end = os_time_get_boot_us() */ - if (!jit_emit_callnative(cc, os_time_get_boot_us, time_end, NULL, 0)) { + /* time_end = os_time_thread_cputime_us() */ + if (!jit_emit_callnative(cc, os_time_thread_cputime_us, time_end, NULL, + 0)) { return false; } /* time_start = cur_frame->time_started */ @@ -449,9 +450,9 @@ handle_func_return(JitCompContext *cc, JitBlock *block) } /* Free stack space of the current frame: - exec_env->wasm_stack.s.top = cur_frame */ + exec_env->wasm_stack.top = cur_frame */ GEN_INSN(STPTR, cc->fp_reg, cc->exec_env_reg, - NEW_CONST(I32, offsetof(WASMExecEnv, wasm_stack.s.top))); + NEW_CONST(I32, offsetof(WASMExecEnv, wasm_stack.top))); /* Set the prev_frame as the current frame: exec_env->cur_frame = prev_frame */ GEN_INSN(STPTR, prev_frame, cc->exec_env_reg, @@ -1101,7 +1102,7 @@ jit_compile_op_br_if(JitCompContext *cc, uint32 br_depth, } } - /* Only opy parameters or results when their count > 0 and + /* Only copy parameters or results when their count > 0 and the src/dst addr are different */ copy_arities = check_copy_arities(block_dst, jit_frame); diff --git a/core/iwasm/fast-jit/fe/jit_emit_function.c b/core/iwasm/fast-jit/fe/jit_emit_function.c index 43a71e26a..d1c71c309 100644 --- a/core/iwasm/fast-jit/fe/jit_emit_function.c +++ b/core/iwasm/fast-jit/fe/jit_emit_function.c @@ -499,7 +499,9 @@ jit_compile_op_call_indirect(JitCompContext *cc, uint32 type_idx, if (UINTPTR_MAX == UINT64_MAX) { offset_i32 = jit_cc_new_reg_I32(cc); offset = jit_cc_new_reg_I64(cc); - GEN_INSN(SHL, offset_i32, elem_idx, NEW_CONST(I32, 2)); + /* Calculate offset by pointer size (elem_idx * + * sizeof(table_elem_type_t)) */ + GEN_INSN(SHL, offset_i32, elem_idx, NEW_CONST(I32, 3)); GEN_INSN(I32TOI64, offset, offset_i32); } else { diff --git a/core/iwasm/fast-jit/fe/jit_emit_table.c b/core/iwasm/fast-jit/fe/jit_emit_table.c index 26bc35394..6da5b820f 100644 --- a/core/iwasm/fast-jit/fe/jit_emit_table.c +++ b/core/iwasm/fast-jit/fe/jit_emit_table.c @@ -46,7 +46,8 @@ jit_compile_op_table_get(JitCompContext *cc, uint32 tbl_idx) GEN_INSN(I32TOI64, elem_idx_long, elem_idx); offset = jit_cc_new_reg_I64(cc); - GEN_INSN(MUL, offset, elem_idx_long, NEW_CONST(I64, sizeof(uint32))); + GEN_INSN(MUL, offset, elem_idx_long, + NEW_CONST(I64, sizeof(table_elem_type_t))); res = jit_cc_new_reg_I32(cc); tbl_elems = get_table_elems_reg(cc->jit_frame, tbl_idx); @@ -77,7 +78,8 @@ jit_compile_op_table_set(JitCompContext *cc, uint32 tbl_idx) GEN_INSN(I32TOI64, elem_idx_long, elem_idx); offset = jit_cc_new_reg_I64(cc); - GEN_INSN(MUL, offset, elem_idx_long, NEW_CONST(I64, sizeof(uint32))); + GEN_INSN(MUL, offset, elem_idx_long, + NEW_CONST(I64, sizeof(table_elem_type_t))); tbl_elems = get_table_elems_reg(cc->jit_frame, tbl_idx); GEN_INSN(STI32, elem_val, tbl_elems, offset); @@ -92,14 +94,15 @@ wasm_init_table(WASMModuleInstance *inst, uint32 tbl_idx, uint32 seg_idx, uint32 dst_offset, uint32 len, uint32 src_offset) { WASMTableInstance *tbl; - uint32 tbl_sz; WASMTableSeg *tbl_seg = inst->module->table_segments + seg_idx; - uint32 *tbl_seg_elems = NULL, tbl_seg_len = 0; + InitializerExpression *tbl_seg_init_values = NULL, *init_values; + uint32 tbl_sz, tbl_seg_len = 0, i; + table_elem_type_t *addr; if (!bh_bitmap_get_bit(inst->e->common.elem_dropped, seg_idx)) { /* table segment isn't dropped */ - tbl_seg_elems = tbl_seg->func_indexes; - tbl_seg_len = tbl_seg->function_count; + tbl_seg_init_values = tbl_seg->init_values; + tbl_seg_len = tbl_seg->value_count; } if (offset_len_out_of_bounds(src_offset, len, tbl_seg_len)) @@ -113,10 +116,13 @@ wasm_init_table(WASMModuleInstance *inst, uint32 tbl_idx, uint32 seg_idx, if (!len) return 0; - bh_memcpy_s((uint8 *)tbl + offsetof(WASMTableInstance, elems) - + dst_offset * sizeof(uint32), - (uint32)((tbl_sz - dst_offset) * sizeof(uint32)), - tbl_seg_elems + src_offset, (uint32)(len * sizeof(uint32))); + addr = + (table_elem_type_t *)((uint8 *)tbl + offsetof(WASMTableInstance, elems) + + dst_offset * sizeof(table_elem_type_t)); + init_values = tbl_seg_init_values + src_offset; + for (i = 0; i < len; i++) { + addr[i] = (table_elem_type_t)(uintptr_t)init_values[+i].u.ref_index; + } return 0; out_of_bounds: @@ -175,12 +181,13 @@ wasm_copy_table(WASMModuleInstance *inst, uint32 src_tbl_idx, if (offset_len_out_of_bounds(src_offset, len, src_tbl_sz)) goto out_of_bounds; - bh_memmove_s((uint8 *)dst_tbl + offsetof(WASMTableInstance, elems) - + dst_offset * sizeof(uint32), - (uint32)((dst_tbl_sz - dst_offset) * sizeof(uint32)), - (uint8 *)src_tbl + offsetof(WASMTableInstance, elems) - + src_offset * sizeof(uint32), - (uint32)(len * sizeof(uint32))); + bh_memmove_s( + (uint8 *)dst_tbl + offsetof(WASMTableInstance, elems) + + dst_offset * sizeof(table_elem_type_t), + (uint32)((dst_tbl_sz - dst_offset) * sizeof(table_elem_type_t)), + (uint8 *)src_tbl + offsetof(WASMTableInstance, elems) + + src_offset * sizeof(table_elem_type_t), + (uint32)(len * sizeof(table_elem_type_t))); return 0; out_of_bounds: @@ -272,7 +279,7 @@ fail: static int wasm_fill_table(WASMModuleInstance *inst, uint32 tbl_idx, uint32 dst_offset, - uint32 val, uint32 len) + uintptr_t val, uint32 len) { WASMTableInstance *tbl; uint32 tbl_sz; diff --git a/core/iwasm/fast-jit/jit_compiler.c b/core/iwasm/fast-jit/jit_compiler.c index 958d0e987..2c686dd33 100644 --- a/core/iwasm/fast-jit/jit_compiler.c +++ b/core/iwasm/fast-jit/jit_compiler.c @@ -160,10 +160,10 @@ jit_compiler_compile(WASMModule *module, uint32 func_idx) #if WASM_ENABLE_CUSTOM_NAME_SECTION != 0 char *function_name = cc->cur_wasm_func->field_name; - os_printf("fast jit compilation failed: %s (function_name=%s)\n", + LOG_ERROR("fast jit compilation failed: %s (function_name=%s)\n", last_error ? last_error : "unknown error", function_name); #else - os_printf("fast jit compilation failed: %s\n", + LOG_ERROR("fast jit compilation failed: %s\n", last_error ? last_error : "unknown error"); #endif diff --git a/core/iwasm/fast-jit/jit_frontend.c b/core/iwasm/fast-jit/jit_frontend.c index e9d7a3ff3..f770b274c 100644 --- a/core/iwasm/fast-jit/jit_frontend.c +++ b/core/iwasm/fast-jit/jit_frontend.c @@ -97,9 +97,9 @@ jit_frontend_get_table_inst_offset(const WASMModule *module, uint32 tbl_idx) offset += (uint32)offsetof(WASMTableInstance, elems); #if WASM_ENABLE_MULTI_MODULE != 0 - offset += (uint32)sizeof(uint32) * table->max_size; + offset += (uint32)sizeof(table_elem_type_t) * table->max_size; #else - offset += (uint32)sizeof(uint32) + offset += (uint32)sizeof(table_elem_type_t) * (table->possible_grow ? table->max_size : table->init_size); #endif @@ -1093,7 +1093,7 @@ init_func_translation(JitCompContext *cc) || !(jit_frame = jit_calloc(offsetof(JitFrame, lp) + sizeof(*jit_frame->lp) * (max_locals + max_stacks)))) { - os_printf("allocate jit frame failed\n"); + LOG_ERROR("allocate jit frame failed\n"); return NULL; } @@ -1157,21 +1157,22 @@ init_func_translation(JitCompContext *cc) func_inst = jit_cc_new_reg_ptr(cc); #if WASM_ENABLE_PERF_PROFILING != 0 time_started = jit_cc_new_reg_I64(cc); - /* Call os_time_get_boot_us() to get time_started firstly + /* Call os_time_thread_cputime_us() to get time_started firstly as there is stack frame switching below, calling native in them may cause register spilling work inproperly */ - if (!jit_emit_callnative(cc, os_time_get_boot_us, time_started, NULL, 0)) { + if (!jit_emit_callnative(cc, os_time_thread_cputime_us, time_started, NULL, + 0)) { return NULL; } #endif #endif - /* top = exec_env->wasm_stack.s.top */ + /* top = exec_env->wasm_stack.top */ GEN_INSN(LDPTR, top, cc->exec_env_reg, - NEW_CONST(I32, offsetof(WASMExecEnv, wasm_stack.s.top))); - /* top_boundary = exec_env->wasm_stack.s.top_boundary */ + NEW_CONST(I32, offsetof(WASMExecEnv, wasm_stack.top))); + /* top_boundary = exec_env->wasm_stack.top_boundary */ GEN_INSN(LDPTR, top_boundary, cc->exec_env_reg, - NEW_CONST(I32, offsetof(WASMExecEnv, wasm_stack.s.top_boundary))); + NEW_CONST(I32, offsetof(WASMExecEnv, wasm_stack.top_boundary))); /* frame_boundary = top + frame_size + outs_size */ GEN_INSN(ADD, frame_boundary, top, NEW_CONST(PTR, frame_size + outs_size)); /* if frame_boundary > top_boundary, throw stack overflow exception */ @@ -1184,9 +1185,9 @@ init_func_translation(JitCompContext *cc) /* Add first and then sub to reduce one used register */ /* new_top = frame_boundary - outs_size = top + frame_size */ GEN_INSN(SUB, new_top, frame_boundary, NEW_CONST(PTR, outs_size)); - /* exec_env->wasm_stack.s.top = new_top */ + /* exec_env->wasm_stack.top = new_top */ GEN_INSN(STPTR, new_top, cc->exec_env_reg, - NEW_CONST(I32, offsetof(WASMExecEnv, wasm_stack.s.top))); + NEW_CONST(I32, offsetof(WASMExecEnv, wasm_stack.top))); /* frame_sp = frame->lp + local_size */ GEN_INSN(ADD, frame_sp, top, NEW_CONST(PTR, offsetof(WASMInterpFrame, lp) + local_size)); diff --git a/core/iwasm/include/aot_comp_option.h b/core/iwasm/include/aot_comp_option.h new file mode 100644 index 000000000..617b68f97 --- /dev/null +++ b/core/iwasm/include/aot_comp_option.h @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef __AOT_COMP_OPTION_H__ +#define __AOT_COMP_OPTION_H__ + +typedef struct AOTCompOption { + bool is_jit_mode; + bool is_indirect_mode; + char *target_arch; + char *target_abi; + char *target_cpu; + char *cpu_features; + bool is_sgx_platform; + bool enable_bulk_memory; + bool enable_thread_mgr; + bool enable_tail_call; + bool enable_simd; + bool enable_ref_types; + bool enable_gc; + bool enable_aux_stack_check; + bool enable_aux_stack_frame; + bool enable_perf_profiling; + bool enable_memory_profiling; + bool disable_llvm_intrinsics; + bool disable_llvm_lto; + bool enable_llvm_pgo; + bool enable_stack_estimation; + bool quick_invoke_c_api_import; + char *use_prof_file; + uint32_t opt_level; + uint32_t size_level; + uint32_t output_format; + uint32_t bounds_checks; + uint32_t stack_bounds_checks; + uint32_t segue_flags; + char **custom_sections; + uint32_t custom_sections_count; + const char *stack_usage_file; + const char *llvm_passes; + const char *builtin_intrinsics; +} AOTCompOption, *aot_comp_option_t; + +#endif diff --git a/core/iwasm/include/aot_export.h b/core/iwasm/include/aot_export.h index e1837e64f..c1a03d86c 100644 --- a/core/iwasm/include/aot_export.h +++ b/core/iwasm/include/aot_export.h @@ -9,6 +9,8 @@ #include #include +#include "aot_comp_option.h" + #ifdef __cplusplus extern "C" { #endif @@ -20,7 +22,8 @@ struct AOTCompContext; typedef struct AOTCompContext *aot_comp_context_t; aot_comp_data_t -aot_create_comp_data(void *wasm_module); +aot_create_comp_data(void *wasm_module, const char *target_arch, + bool gc_enabled); void aot_destroy_comp_data(aot_comp_data_t comp_data); @@ -38,41 +41,6 @@ enum { AOT_LLVMIR_OPT_FILE, }; -/* always sync it with AOTCompOption in compilation/aot_llvm.h */ -typedef struct AOTCompOption { - bool is_jit_mode; - bool is_indirect_mode; - char *target_arch; - char *target_abi; - char *target_cpu; - char *cpu_features; - bool is_sgx_platform; - bool enable_bulk_memory; - bool enable_thread_mgr; - bool enable_tail_call; - bool enable_simd; - bool enable_ref_types; - bool enable_aux_stack_check; - bool enable_aux_stack_frame; - bool disable_llvm_intrinsics; - bool disable_llvm_lto; - bool enable_llvm_pgo; - bool enable_stack_estimation; - bool quick_invoke_c_api_import; - char *use_prof_file; - uint32_t opt_level; - uint32_t size_level; - uint32_t output_format; - uint32_t bounds_checks; - uint32_t stack_bounds_checks; - uint32_t segue_flags; - char **custom_sections; - uint32_t custom_sections_count; - const char *stack_usage_file; - const char *llvm_passes; - const char *builtin_intrinsics; -} AOTCompOption, *aot_comp_option_t; - bool aot_compiler_init(void); diff --git a/core/iwasm/include/gc_export.h b/core/iwasm/include/gc_export.h new file mode 100644 index 000000000..8a1003194 --- /dev/null +++ b/core/iwasm/include/gc_export.h @@ -0,0 +1,954 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef _GC_EXPORT_H +#define _GC_EXPORT_H + +#include "wasm_export.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef uint8_t wasm_value_type_t; + +typedef enum wasm_value_type_enum { + VALUE_TYPE_I32 = 0x7F, + VALUE_TYPE_I64 = 0x7E, + VALUE_TYPE_F32 = 0x7D, + VALUE_TYPE_F64 = 0x7C, + VALUE_TYPE_V128 = 0x7B, + /* GC Types */ + VALUE_TYPE_I8 = 0x78, + VALUE_TYPE_I16 = 0x77, + VALUE_TYPE_NULLFUNCREF = 0x73, + VALUE_TYPE_NULLEXTERNREF = 0x72, + VALUE_TYPE_NULLREF = 0x71, + VALUE_TYPE_FUNCREF = 0x70, + VALUE_TYPE_EXTERNREF = 0x6F, + VALUE_TYPE_ANYREF = 0x6E, + VALUE_TYPE_EQREF = 0x6D, + VALUE_TYPE_I31REF = 0x6C, + VALUE_TYPE_STRUCTREF = 0x6B, + VALUE_TYPE_ARRAYREF = 0x6A, + VALUE_TYPE_HT_NON_NULLABLE_REF = 0x64, + VALUE_TYPE_HT_NULLABLE_REF = 0x63, + /* Stringref Types */ + VALUE_TYPE_STRINGREF = 0X67, + VALUE_TYPE_STRINGVIEWWTF8 = 0x66, + VALUE_TYPE_STRINGVIEWWTF16 = 0x62, + VALUE_TYPE_STRINGVIEWITER = 0x61 +} wasm_value_type_enum; + +typedef int32_t wasm_heap_type_t; + +typedef enum wasm_heap_type_enum { + HEAP_TYPE_FUNC = -0x10, + HEAP_TYPE_EXTERN = -0x11, + HEAP_TYPE_ANY = -0x12, + HEAP_TYPE_EQ = -0x13, + HEAP_TYPE_I31 = -0x16, + HEAP_TYPE_NOFUNC = -0x17, + HEAP_TYPE_NOEXTERN = -0x18, + HEAP_TYPE_STRUCT = -0x19, + HEAP_TYPE_ARRAY = -0x1A, + HEAP_TYPE_NONE = -0x1B +} wasm_heap_type_enum; + +struct WASMObject; +typedef struct WASMObject *wasm_obj_t; + +#ifndef WASM_VALUE_DEFINED +#define WASM_VALUE_DEFINED +typedef union V128 { + int8_t i8x16[16]; + int16_t i16x8[8]; + int32_t i32x8[4]; + int64_t i64x2[2]; + float f32x4[4]; + double f64x2[2]; +} V128; + +typedef union WASMValue { + int32_t i32; + uint32_t u32; + uint32_t global_index; + uint32_t ref_index; + int64_t i64; + uint64_t u64; + float f32; + double f64; + V128 v128; + wasm_obj_t gc_obj; + uint32_t type_index; + struct { + uint32_t type_index; + uint32_t length; + } array_new_default; + /* pointer to a memory space holding more data, current usage: + * struct.new init value: WASMStructNewInitValues * + * array.new init value: WASMArrayNewInitValues * + */ + void *data; +} WASMValue; +#endif /* end of WASM_VALUE_DEFINED */ + +typedef union WASMValue wasm_value_t; + +/* Reference type, the layout is same as WasmRefType in wasm.h + * use wasm_ref_type_set_type_idx to initialize as concrete ref type + * use wasm_ref_type_set_heap_type to initialize as abstract ref type + */ +typedef struct wasm_ref_type_t { + wasm_value_type_t value_type; + bool nullable; + int32_t heap_type; +} wasm_ref_type_t; + +/** + * Local object reference that can be traced when GC occurs. All + * native functions that need to hold WASM objects which may not be + * referenced from other elements of GC root set may be hold with + * this type of variable so that they can be traced when GC occurs. + * Before using such a variable, it must be pushed onto the stack + * (implemented as a chain) of such variables, and before leaving the + * frame of the variables, they must be popped from the stack. + */ +typedef struct WASMLocalObjectRef { + /* Previous local object reference variable on the stack */ + struct WASMLocalObjectRef *prev; + /* The reference of WASM object hold by this variable */ + wasm_obj_t val; +} WASMLocalObjectRef, wasm_local_obj_ref_t; + +struct WASMType; +struct WASMFuncType; +struct WASMStructType; +struct WASMArrayType; + +typedef struct WASMType *wasm_defined_type_t; +typedef struct WASMFuncType *wasm_func_type_t; +typedef struct WASMStructType *wasm_struct_type_t; +typedef struct WASMArrayType *wasm_array_type_t; + +struct WASMExternrefObject; +struct WASMAnyrefObject; +struct WASMStructObject; +struct WASMArrayObject; +struct WASMFuncObject; + +typedef struct WASMExternrefObject *wasm_externref_obj_t; +typedef struct WASMAnyrefObject *wasm_anyref_obj_t; +typedef struct WASMStructObject *wasm_struct_obj_t; +typedef struct WASMArrayObject *wasm_array_obj_t; +typedef struct WASMFuncObject *wasm_func_obj_t; +typedef struct WASMStringrefObject *wasm_stringref_obj_t; +typedef uintptr_t wasm_i31_obj_t; + +typedef void (*wasm_obj_finalizer_t)(const wasm_obj_t obj, void *data); + +/* Defined type related operations */ + +/** + * Get number of defined types in the given wasm module + * + * @param module the wasm module + * + * @return defined type count + */ +WASM_RUNTIME_API_EXTERN uint32_t +wasm_get_defined_type_count(const wasm_module_t module); + +/** + * Get defined type by type index + * + * @param module the wasm module + * @param index the type index + * + * @return defined type + */ +WASM_RUNTIME_API_EXTERN wasm_defined_type_t +wasm_get_defined_type(const wasm_module_t module, uint32_t index); + +/** + * Get defined type of the GC managed object, the object must be struct, + * array or func. + * + * @param obj the object + * + * @return defined type of the object. + */ +WASM_RUNTIME_API_EXTERN wasm_defined_type_t +wasm_obj_get_defined_type(const wasm_obj_t obj); + +/** + * Get defined type index of the GC managed object, the object must be struct, + * array or func. + * + * @param obj the object + * + * @return defined type index of the object. + */ +WASM_RUNTIME_API_EXTERN int32_t +wasm_obj_get_defined_type_idx(const wasm_module_t module, const wasm_obj_t obj); + +/** + * Check whether a defined type is a function type + * + * @param def_type the defined type to be checked + * + * @return true if the defined type is function type, false otherwise + */ +WASM_RUNTIME_API_EXTERN bool +wasm_defined_type_is_func_type(const wasm_defined_type_t def_type); + +/** + * Check whether a defined type is a struct type + * + * @param def_type the defined type to be checked + * + * @return true if the defined type is struct type, false otherwise + */ +WASM_RUNTIME_API_EXTERN bool +wasm_defined_type_is_struct_type(const wasm_defined_type_t def_type); + +/** + * Check whether a defined type is an array type + * + * @param def_type the defined type to be checked + * + * @return true if the defined type is array type, false otherwise + */ +WASM_RUNTIME_API_EXTERN bool +wasm_defined_type_is_array_type(const wasm_defined_type_t def_type); + +/** + * Get parameter count of a function type + * + * @param func_type the specified function type + * + * @return the param count of the specified function type + */ +WASM_RUNTIME_API_EXTERN uint32_t +wasm_func_type_get_param_count(const wasm_func_type_t func_type); + +/** + * Get type of a specified parameter of a function type + * + * @param func_type the specified function type + * @param param_idx the specified param index + * + * @return the param type at the specified param index of the specified func + * type + */ +WASM_RUNTIME_API_EXTERN wasm_ref_type_t +wasm_func_type_get_param_type(const wasm_func_type_t func_type, + uint32_t param_idx); + +/** + * Get result count of a function type + * + * @param func_type the specified function type + * + * @return the result count of the specified function type + */ +WASM_RUNTIME_API_EXTERN uint32_t +wasm_func_type_get_result_count(const wasm_func_type_t func_type); + +/** + * Get type of a specified result of a function type + * + * @param func_type the specified function type + * @param param_idx the specified result index + * + * @return the result type at the specified result index of the specified func + * type + */ +WASM_RUNTIME_API_EXTERN wasm_ref_type_t +wasm_func_type_get_result_type(const wasm_func_type_t func_type, + uint32_t result_idx); + +/** + * Get field count of a struct type + * + * @param struct_type the specified struct type + * + * @return the field count of the specified struct type + */ +WASM_RUNTIME_API_EXTERN uint32_t +wasm_struct_type_get_field_count(const wasm_struct_type_t struct_type); + +/** + * Get type of a specified field of a struct type + * + * @param struct_type the specified struct type + * @param field_idx index of the specified field + * @param p_is_mutable if not NULL, output the mutability of the field + * + * @return the result type at the specified field index of the specified struct + */ +WASM_RUNTIME_API_EXTERN wasm_ref_type_t +wasm_struct_type_get_field_type(const wasm_struct_type_t struct_type, + uint32_t field_idx, bool *p_is_mutable); + +/** + * Get element type of an array type + * + * @param array_type the specified array type + * @param p_is_mutable if not NULL, output the mutability of the element type + * + * @return the ref type of array's elem type + */ +WASM_RUNTIME_API_EXTERN wasm_ref_type_t +wasm_array_type_get_elem_type(const wasm_array_type_t array_type, + bool *p_is_mutable); + +/** + * Check whether two defined types are equal + * + * @param def_type1 the specified defined type1 + * @param def_type2 the specified defined type2 + * @param module current wasm module + * + * @return true if the defined type1 is equal to the defined type2, + * false otherwise + */ +WASM_RUNTIME_API_EXTERN bool +wasm_defined_type_equal(const wasm_defined_type_t def_type1, + const wasm_defined_type_t def_type2, + const wasm_module_t module); + +/** + * Check whether def_type1 is subtype of def_type2 + * + * @param def_type1 the specified defined type1 + * @param def_type2 the specified defined type2 + * @param module current wasm module + * + * @return true if the defined type1 is subtype of the defined type2, + * false otherwise + */ +WASM_RUNTIME_API_EXTERN bool +wasm_defined_type_is_subtype_of(const wasm_defined_type_t def_type1, + const wasm_defined_type_t def_type2, + const wasm_module_t module); + +/* ref type related operations */ + +/** + * Set the ref_type to be (ref null? type_idx) + * + * @param ref_type the ref_type to be set + * @param nullable whether the ref_type is nullable + * @param type_idx the type index + */ +WASM_RUNTIME_API_EXTERN void +wasm_ref_type_set_type_idx(wasm_ref_type_t *ref_type, bool nullable, + int32_t type_idx); + +/** + * Set the ref_type to be (ref null? func/extern/any/eq/i31/struct/array/..) + * + * @param ref_type the ref_type to be set + * @param nullable whether the ref_type is nullable + * @param heap_type the heap type + */ +WASM_RUNTIME_API_EXTERN void +wasm_ref_type_set_heap_type(wasm_ref_type_t *ref_type, bool nullable, + int32_t heap_type); + +/** + * Check whether two ref types are equal + * + * @param ref_type1 the specified ref type1 + * @param ref_type2 the specified ref type2 + * @param module current wasm module + * + * @return true if the ref type1 is equal to the ref type2, + * false otherwise + */ +WASM_RUNTIME_API_EXTERN bool +wasm_ref_type_equal(const wasm_ref_type_t *ref_type1, + const wasm_ref_type_t *ref_type2, + const wasm_module_t module); + +/** + * Check whether ref_type1 is subtype of ref_type2 + * + * @param ref_type1 the specified ref type1 + * @param ref_type2 the specified ref type2 + * @param module current wasm module + * + * @return true if the ref type1 is subtype of the ref type2, + * false otherwise + */ +WASM_RUNTIME_API_EXTERN bool +wasm_ref_type_is_subtype_of(const wasm_ref_type_t *ref_type1, + const wasm_ref_type_t *ref_type2, + const wasm_module_t module); + +/* wasm object related operations */ + +/** + * Create a struct object with the index of defined type + * + * @param exec_env the execution environment + * @param type_idx index of the struct type + * + * @return wasm_struct_obj_t if create success, NULL otherwise + */ +WASM_RUNTIME_API_EXTERN wasm_struct_obj_t +wasm_struct_obj_new_with_typeidx(wasm_exec_env_t exec_env, uint32_t type_idx); + +/** + * Create a struct object with the struct type + * + * @param exec_env the execution environment + * @param type defined struct type + * + * @return wasm_struct_obj_t if create success, NULL otherwise + */ +WASM_RUNTIME_API_EXTERN wasm_struct_obj_t +wasm_struct_obj_new_with_type(wasm_exec_env_t exec_env, + const wasm_struct_type_t type); + +/** + * Set the field value of a struct object + * + * @param obj the struct object to set field + * @param field_idx the specified field index + * @param value wasm value to be set + */ +WASM_RUNTIME_API_EXTERN void +wasm_struct_obj_set_field(wasm_struct_obj_t obj, uint32_t field_idx, + const wasm_value_t *value); + +/** + * Get the field value of a struct object + * + * @param obj the struct object to get field + * @param field_idx the specified field index + * @param sign_extend whether to sign extend for i8 and i16 element types + * @param value output the wasm value + */ +WASM_RUNTIME_API_EXTERN void +wasm_struct_obj_get_field(const wasm_struct_obj_t obj, uint32_t field_idx, + bool sign_extend, wasm_value_t *value); + +/** + * Create an array object with the index of defined type, the obj's length is + * length, init value is init_value + * + * @param exec_env the execution environment + * @param type_idx the index of the specified type + * @param length the array's length + * @param init_value the array's init value + * + * @return the created array object + */ +WASM_RUNTIME_API_EXTERN wasm_array_obj_t +wasm_array_obj_new_with_typeidx(wasm_exec_env_t exec_env, uint32_t type_idx, + uint32_t length, wasm_value_t *init_value); + +/** + * Create an array object with the array type, the obj's length is length, init + * value is init_value + * + * @param exec_env the execution environment + * @param type the array's specified type + * @param length the array's length + * @param init_value the array's init value + * + * @return the created array object + */ +WASM_RUNTIME_API_EXTERN wasm_array_obj_t +wasm_array_obj_new_with_type(wasm_exec_env_t exec_env, + const wasm_array_type_t type, uint32_t length, + wasm_value_t *init_value); + +/** + * Set the specified element's value of an array object + * + * @param array_obj the array object to set element value + * @param elem_idx the specified element index + * @param value wasm value to be set + */ +WASM_RUNTIME_API_EXTERN void +wasm_array_obj_set_elem(wasm_array_obj_t array_obj, uint32_t elem_idx, + const wasm_value_t *value); + +/** + * Get the specified element's value of an array object + * + * @param array_obj the array object to get element value + * @param elem_idx the specified element index + * @param sign_extend whether to sign extend for i8 and i16 element types + * @param value output the wasm value + */ +WASM_RUNTIME_API_EXTERN void +wasm_array_obj_get_elem(const wasm_array_obj_t array_obj, uint32_t elem_idx, + bool sign_extend, wasm_value_t *value); + +/** + * Copy elements from one array to another + * + * @param dst_obj destination array object + * @param dst_idx target index in destination + * @param src_obj source array object + * @param src_idx start index in source + * @param len length of elements to copy + */ +WASM_RUNTIME_API_EXTERN void +wasm_array_obj_copy(wasm_array_obj_t dst_obj, uint32_t dst_idx, + const wasm_array_obj_t src_obj, uint32_t src_idx, + uint32_t len); + +/** + * Return the length of an array object + * + * @param array_obj the array object to get length + * + * @return length of the array object + */ +WASM_RUNTIME_API_EXTERN uint32_t +wasm_array_obj_length(const wasm_array_obj_t array_obj); + +/** + * Get the address of the first element of an array object + * + * @param array_obj the array object to get element address + * + * @return address of the first element + */ +WASM_RUNTIME_API_EXTERN void * +wasm_array_obj_first_elem_addr(const wasm_array_obj_t array_obj); + +/** + * Get the address of the i-th element of an array object + * + * @param array_obj the array object to get element address + * @param elem_idx the specified element index + * + * @return address of the specified element + */ +WASM_RUNTIME_API_EXTERN void * +wasm_array_obj_elem_addr(const wasm_array_obj_t array_obj, uint32_t elem_idx); + +/** + * Create a function object with the index of defined type and the index of the + * function + * + * @param exec_env the execution environment + * @param type_idx the index of the specified type + * @param func_idx_bound the index of the function + * + * @return the created function object + */ +WASM_RUNTIME_API_EXTERN wasm_func_obj_t +wasm_func_obj_new_with_typeidx(wasm_exec_env_t exec_env, uint32_t type_idx, + uint32_t func_idx_bound); + +/** + * Create a function object with the function type and the index of the function + * + * @param exec_env the execution environment + * @param type the specified type + * @param func_idx_bound the index of the function + * + * @return the created function object + */ +WASM_RUNTIME_API_EXTERN wasm_func_obj_t +wasm_func_obj_new_with_type(wasm_exec_env_t exec_env, wasm_func_type_t type, + uint32_t func_idx_bound); + +/** + * Get the function index bound of a function object + * + * @param func_obj the function object + * + * @return the bound function index + */ +WASM_RUNTIME_API_EXTERN uint32_t +wasm_func_obj_get_func_idx_bound(const wasm_func_obj_t func_obj); + +/** + * Get the function type of a function object + * + * @param func_obj the function object + * + * @return defined function type + */ +WASM_RUNTIME_API_EXTERN wasm_func_type_t +wasm_func_obj_get_func_type(const wasm_func_obj_t func_obj); + +/** + * Call the given WASM function object with arguments (bytecode and AoT). + * + * @param exec_env the execution environment to call the function, + * which must be created from wasm_create_exec_env() + * @param func_obj the function object to call + * @param argc total cell number that the function parameters occupy, + * a cell is a slot of the uint32 array argv[], e.g. i32/f32 argument + * occupies one cell, i64/f64 argument occupies two cells, note that + * it might be different from the parameter number of the function + * @param argv the arguments. If the function has return value, + * the first (or first two in case 64-bit return value) element of + * argv stores the return value of the called WASM function after this + * function returns. + * + * @return true if success, false otherwise and exception will be thrown, + * the caller can call wasm_runtime_get_exception to get the exception + * info. + */ +WASM_RUNTIME_API_EXTERN bool +wasm_runtime_call_func_ref(wasm_exec_env_t exec_env, + const wasm_func_obj_t func_obj, uint32_t argc, + uint32_t argv[]); + +/** + * Call the given WASM function object with provided results space + * and arguments (bytecode and AoT). + * + * @param exec_env the execution environment to call the function, + * which must be created from wasm_create_exec_env() + * @param func_obj the function object to call + * @param num_results the number of results + * @param results the pre-alloced pointer to get the results + * @param num_args the number of arguments + * @param args the arguments + * + * @return true if success, false otherwise and exception will be thrown, + * the caller can call wasm_runtime_get_exception to get the exception + * info. + */ +WASM_RUNTIME_API_EXTERN bool +wasm_runtime_call_func_ref_a(wasm_exec_env_t exec_env, + const wasm_func_obj_t func_obj, + uint32_t num_results, wasm_val_t results[], + uint32_t num_args, wasm_val_t *args); + +/** + * Call the given WASM function object with provided results space and + * variant arguments (bytecode and AoT). + * + * @param exec_env the execution environment to call the function, + * which must be created from wasm_create_exec_env() + * @param func_obj the function object to call + * @param num_results the number of results + * @param results the pre-alloced pointer to get the results + * @param num_args the number of arguments + * @param ... the variant arguments + * + * @return true if success, false otherwise and exception will be thrown, + * the caller can call wasm_runtime_get_exception to get the exception + * info. + */ +WASM_RUNTIME_API_EXTERN bool +wasm_runtime_call_func_ref_v(wasm_exec_env_t exec_env, + const wasm_func_obj_t func_obj, + uint32_t num_results, wasm_val_t results[], + uint32_t num_args, ...); + +/** + * Create an externref object with host object + * + * @param exec_env the execution environment + * @param host_obj host object pointer + * + * @return wasm_externref_obj_t if success, NULL otherwise + */ +WASM_RUNTIME_API_EXTERN wasm_externref_obj_t +wasm_externref_obj_new(wasm_exec_env_t exec_env, const void *host_obj); + +/** + * Get the host value of an externref object + * + * @param externref_obj the externref object + * + * @return the stored host object pointer + */ +WASM_RUNTIME_API_EXTERN const void * +wasm_externref_obj_get_value(const wasm_externref_obj_t externref_obj); + +/** + * Create an anyref object with host object + * + * @param exec_env the execution environment + * @param host_obj host object pointer + * + * @return wasm_anyref_obj_t if success, NULL otherwise + */ +WASM_RUNTIME_API_EXTERN wasm_anyref_obj_t +wasm_anyref_obj_new(wasm_exec_env_t exec_env, const void *host_obj); + +/** + * Get the host object value of an anyref object + * + * @param anyref_obj the anyref object + * + * @return the stored host object pointer + */ +WASM_RUNTIME_API_EXTERN const void * +wasm_anyref_obj_get_value(const wasm_anyref_obj_t anyref_obj); + +/** + * Get the internal object inside the externref object, same as + * the operation of opcode extern.internalize + * + * @param externref_obj the externref object + * + * @return internalized wasm_obj_t + */ +WASM_RUNTIME_API_EXTERN wasm_obj_t +wasm_externref_obj_to_internal_obj(const wasm_externref_obj_t externref_obj); + +/** + * Create an externref object from an internal object, same as + * the operation of opcode extern.externalize + * + * @param exec_env the execution environment + * @param internal_obj the internal object + * + * @return wasm_externref_obj_t if create success, NULL othersise + */ +WASM_RUNTIME_API_EXTERN wasm_externref_obj_t +wasm_internal_obj_to_externref_obj(wasm_exec_env_t exec_env, + const wasm_obj_t internal_obj); + +/** + * Create an i31 object + * + * @param i31_value the scalar value + * + * @return wasm_i31_obj_t + */ +WASM_RUNTIME_API_EXTERN wasm_i31_obj_t +wasm_i31_obj_new(uint32_t i31_value); + +/** + * Get value from an i31 object + * + * @param i31_obj the i31 object + * @param sign_extend whether to sign extend the value + * + * @return wasm_i31_obj_t + */ +WASM_RUNTIME_API_EXTERN uint32_t +wasm_i31_obj_get_value(wasm_i31_obj_t i31_obj, bool sign_extend); + +/** + * Pin an object to make it traced during GC + * + * @param exec_env the execution environment + * @param obj the object to pin + * + * @return true if success, false otherwise + */ +WASM_RUNTIME_API_EXTERN bool +wasm_runtime_pin_object(wasm_exec_env_t exec_env, wasm_obj_t obj); + +/** + * Unpin an object + * + * @param exec_env the execution environment + * @param obj the object to unpin + * + * @return true if success, false otherwise + */ +WASM_RUNTIME_API_EXTERN bool +wasm_runtime_unpin_object(wasm_exec_env_t exec_env, wasm_obj_t obj); + +/** + * Check whether an object is a struct objectc + * + * @param obj the object to check + * + * @return true if the object is a struct, false otherwise + */ +WASM_RUNTIME_API_EXTERN bool +wasm_obj_is_struct_obj(const wasm_obj_t obj); + +/** + * Check whether an object is an array object + * + * @param obj the object to check + * + * @return true if the object is a array, false otherwise + */ +WASM_RUNTIME_API_EXTERN bool +wasm_obj_is_array_obj(const wasm_obj_t obj); + +/** + * Check whether an object is a function object + * + * @param obj the object to check + * + * @return true if the object is a function, false otherwise + */ +WASM_RUNTIME_API_EXTERN bool +wasm_obj_is_func_obj(const wasm_obj_t obj); + +/** + * Check whether an object is an i31 object + * + * @param obj the object to check + * + * @return true if the object is an i32, false otherwise + */ +WASM_RUNTIME_API_EXTERN bool +wasm_obj_is_i31_obj(const wasm_obj_t obj); + +/** + * Check whether an object is an externref object + * + * @param obj the object to check + * + * @return true if the object is an externref, false otherwise + */ +WASM_RUNTIME_API_EXTERN bool +wasm_obj_is_externref_obj(const wasm_obj_t obj); + +/** + * Check whether an object is an anyref object + * + * @param obj the object to check + * + * @return true if the object is an anyref, false otherwise + */ +WASM_RUNTIME_API_EXTERN bool +wasm_obj_is_anyref_obj(const wasm_obj_t obj); + +/** + * Check whether an object is a struct object, or, an i31/struct/array object + * + * @param obj the object to check + * + * @return true if the object is an internal object, false otherwise + */ +WASM_RUNTIME_API_EXTERN bool +wasm_obj_is_internal_obj(const wasm_obj_t obj); + +/** + * Check whether an object is an eq object + * + * @param obj the object to check + * + * @return true if the object is an eq object, false otherwise + */ +WASM_RUNTIME_API_EXTERN bool +wasm_obj_is_eq_obj(const wasm_obj_t obj); + +/** + * Check whether an object is an instance of a defined type + * + * @param obj the object to check + * @param defined_type the defined type + * @param module current wasm module + * + * @return true if the object is instance of the defined type, false otherwise + */ +WASM_RUNTIME_API_EXTERN bool +wasm_obj_is_instance_of_defined_type(const wasm_obj_t obj, + const wasm_defined_type_t defined_type, + const wasm_module_t module); + +/** + * Check whether an object is an instance of a defined type with + * index type_idx + * + * @param obj the object to check + * @param type_idx the type index + * @param module current wasm module + * + * @return true if the object is instance of the defined type specified by + * type_idx, false otherwise + */ +WASM_RUNTIME_API_EXTERN bool +wasm_obj_is_instance_of_type_idx(const wasm_obj_t obj, uint32_t type_idx, + const wasm_module_t module); + +/** + * Check whether an object is an instance of a ref type + * + * @param obj the object to check + * @param ref_type the ref type + * + * @return true if the object is instance of the ref type, false otherwise + */ +WASM_RUNTIME_API_EXTERN bool +wasm_obj_is_instance_of_ref_type(const wasm_obj_t obj, + const wasm_ref_type_t *ref_type); + +/** + * Push a local object ref into stack, note that we should set its value + * after pushing to retain it during GC, and should pop it from stack + * before returning from the current function + * + * @param exec_env the execution environment + * @param local_obj_ref the local object ref to push + */ +WASM_RUNTIME_API_EXTERN void +wasm_runtime_push_local_obj_ref(wasm_exec_env_t exec_env, + wasm_local_obj_ref_t *local_obj_ref); + +/** + * Pop a local object ref from stack + * + * @param exec_env the execution environment + * + * @return the popped wasm_local_obj_ref_t + */ +WASM_RUNTIME_API_EXTERN wasm_local_obj_ref_t * +wasm_runtime_pop_local_obj_ref(wasm_exec_env_t exec_env); + +/** + * Pop n local object refs from stack + * + * @param exec_env the execution environment + * @param n number to pop + */ +WASM_RUNTIME_API_EXTERN void +wasm_runtime_pop_local_obj_refs(wasm_exec_env_t exec_env, uint32_t n); + +/** + * Get current local object ref from stack + * + * @param exec_env the execution environment + * + * @return the wasm_local_obj_ref_t obj from the top of the stack, not change + * the state of the stack + */ +WASM_RUNTIME_API_EXTERN wasm_local_obj_ref_t * +wasm_runtime_get_cur_local_obj_ref(wasm_exec_env_t exec_env); + +/** + * Set finalizer to the given object, if another finalizer is set to the same + * object, the previous one will be cancelled + * + * @param exec_env the execution environment + * @param obj object to set finalizer + * @param cb finalizer function to be called before this object is freed + * @param data custom data to be passed to finalizer function + * + * @return true if success, false otherwise + */ +bool +wasm_obj_set_gc_finalizer(wasm_exec_env_t exec_env, const wasm_obj_t obj, + wasm_obj_finalizer_t cb, void *data); + +/** + * Unset finalizer to the given object + * + * @param exec_env the execution environment + * @param obj object to unset finalizer + */ +void +wasm_obj_unset_gc_finalizer(wasm_exec_env_t exec_env, void *obj); + +#ifdef __cplusplus +} +#endif + +#endif /* end of _GC_EXPORT_H */ diff --git a/core/iwasm/include/wasm_export.h b/core/iwasm/include/wasm_export.h index dda058d08..32114c490 100644 --- a/core/iwasm/include/wasm_export.h +++ b/core/iwasm/include/wasm_export.h @@ -161,6 +161,9 @@ typedef struct RuntimeInitArgs { /* Fast JIT code cache size */ uint32_t fast_jit_code_cache_size; + /* Default GC heap size */ + uint32_t gc_heap_size; + /* Default running mode of the runtime */ RunningMode running_mode; diff --git a/core/iwasm/interpreter/wasm.h b/core/iwasm/interpreter/wasm.h index 60e1238ad..d62351a27 100644 --- a/core/iwasm/interpreter/wasm.h +++ b/core/iwasm/interpreter/wasm.h @@ -9,12 +9,15 @@ #include "bh_platform.h" #include "bh_hashmap.h" #include "bh_assert.h" +#if WASM_ENABLE_GC != 0 +#include "gc_export.h" +#endif #ifdef __cplusplus extern "C" { #endif -/** Value Type */ +/* Value Type */ #define VALUE_TYPE_I32 0x7F #define VALUE_TYPE_I64 0X7E #define VALUE_TYPE_F32 0x7D @@ -23,29 +26,99 @@ extern "C" { #define VALUE_TYPE_FUNCREF 0x70 #define VALUE_TYPE_EXTERNREF 0x6F #define VALUE_TYPE_VOID 0x40 + +/* Packed Types */ +#define PACKED_TYPE_I8 0x78 +#define PACKED_TYPE_I16 0x77 + +/* Reference Types */ +#define REF_TYPE_NULLFUNCREF 0x73 +#define REF_TYPE_NULLEXTERNREF 0x72 +#define REF_TYPE_NULLREF 0x71 +#define REF_TYPE_FUNCREF VALUE_TYPE_FUNCREF /* 0x70 */ +#define REF_TYPE_EXTERNREF VALUE_TYPE_EXTERNREF /* 0x6F */ +#define REF_TYPE_ANYREF 0x6E +#define REF_TYPE_EQREF 0x6D +#define REF_TYPE_I31REF 0x6C +#define REF_TYPE_STRUCTREF 0x6B +#define REF_TYPE_ARRAYREF 0x6A +#define REF_TYPE_HT_NON_NULLABLE 0x64 +#define REF_TYPE_HT_NULLABLE 0x63 +#define REF_TYPE_STRINGREF VALUE_TYPE_STRINGREF /* 0x67 */ +#define REF_TYPE_STRINGVIEWWTF8 VALUE_TYPE_STRINGVIEWWTF8 /* 0x66 */ +#define REF_TYPE_STRINGVIEWWTF16 VALUE_TYPE_STRINGVIEWWTF16 /* 0x62 */ +#define REF_TYPE_STRINGVIEWITER VALUE_TYPE_STRINGVIEWITER /* 0x61 */ + +/* Heap Types */ +#define HEAP_TYPE_NOFUNC (-0x0D) +#define HEAP_TYPE_NOEXTERN (-0x0E) +#define HEAP_TYPE_NONE (-0x0F) +#define HEAP_TYPE_FUNC (-0x10) +#define HEAP_TYPE_EXTERN (-0x11) +#define HEAP_TYPE_ANY (-0x12) +#define HEAP_TYPE_EQ (-0x13) +#define HEAP_TYPE_I31 (-0x14) +#define HEAP_TYPE_STRUCT (-0x15) +#define HEAP_TYPE_ARRAY (-0x16) +#define HEAP_TYPE_STRINGREF (-0x19) +#define HEAP_TYPE_STRINGVIEWWTF8 (-0x1A) +#define HEAP_TYPE_STRINGVIEWWTF16 (-0x1E) +#define HEAP_TYPE_STRINGVIEWITER (-0x1F) + +/* Defined Types */ +#define DEFINED_TYPE_FUNC 0x60 +#define DEFINED_TYPE_STRUCT 0x5F +#define DEFINED_TYPE_ARRAY 0x5E +#define DEFINED_TYPE_SUB 0x50 +#define DEFINED_TYPE_SUB_FINAL 0x4F +#define DEFINED_TYPE_REC 0x4E + /* Used by AOT */ #define VALUE_TYPE_I1 0x41 -/* Used by loader to represent any type of i32/i64/f32/f64 */ +/** + * Used by loader to represent any type of i32/i64/f32/f64/v128 + * and ref types, including funcref, externref, anyref, eqref, + * (ref null $ht), (ref $ht), i31ref, structref, arrayref, + * nullfuncref, nullexternref, nullref and stringref + */ #define VALUE_TYPE_ANY 0x42 +/** + * Used by wamr compiler to represent object ref types, + * including func object ref, externref object ref, + * internal object ref, eq obect ref, i31 object ref, + * struct object ref, array obect ref + */ +#define VALUE_TYPE_GC_REF 0x43 #define DEFAULT_NUM_BYTES_PER_PAGE 65536 #define DEFAULT_MAX_PAGES 65536 +#if WASM_ENABLE_GC == 0 +typedef uintptr_t table_elem_type_t; #define NULL_REF (0xFFFFFFFF) +#else +typedef void *table_elem_type_t; +#define NULL_REF (NULL) +#define REF_CELL_NUM ((uint32)sizeof(uintptr_t) / sizeof(uint32)) +#endif -#define TABLE_MAX_SIZE (1024) - +#define INIT_EXPR_NONE 0x00 #define INIT_EXPR_TYPE_I32_CONST 0x41 #define INIT_EXPR_TYPE_I64_CONST 0x42 #define INIT_EXPR_TYPE_F32_CONST 0x43 #define INIT_EXPR_TYPE_F64_CONST 0x44 #define INIT_EXPR_TYPE_V128_CONST 0xFD -/* = WASM_OP_REF_FUNC */ -#define INIT_EXPR_TYPE_FUNCREF_CONST 0xD2 -/* = WASM_OP_REF_NULL */ -#define INIT_EXPR_TYPE_REFNULL_CONST 0xD0 #define INIT_EXPR_TYPE_GET_GLOBAL 0x23 -#define INIT_EXPR_TYPE_ERROR 0xff +#define INIT_EXPR_TYPE_REFNULL_CONST 0xD0 +#define INIT_EXPR_TYPE_FUNCREF_CONST 0xD2 +#define INIT_EXPR_TYPE_STRUCT_NEW 0xD3 +#define INIT_EXPR_TYPE_STRUCT_NEW_DEFAULT 0xD4 +#define INIT_EXPR_TYPE_ARRAY_NEW 0xD5 +#define INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT 0xD6 +#define INIT_EXPR_TYPE_ARRAY_NEW_FIXED 0xD7 +#define INIT_EXPR_TYPE_I31_NEW 0xD8 +#define INIT_EXPR_TYPE_ANY_CONVERT_EXTERN 0xD9 +#define INIT_EXPR_TYPE_EXTERN_CONVERT_ANY 0xDA #define WASM_MAGIC_NUMBER 0x6d736100 #define WASM_CURRENT_VERSION 1 @@ -68,6 +141,9 @@ extern "C" { #if WASM_ENABLE_TAGS != 0 #define SECTION_TYPE_TAG 13 #endif +#if WASM_ENABLE_STRINGREF != 0 +#define SECTION_TYPE_STRINGREF 14 +#endif #define SUB_SECTION_TYPE_MODULE 0 #define SUB_SECTION_TYPE_FUNC 1 @@ -99,6 +175,21 @@ extern "C" { #define LABEL_TYPE_CATCH_ALL 6 #endif +#define WASM_TYPE_FUNC 0 +#define WASM_TYPE_STRUCT 1 +#define WASM_TYPE_ARRAY 2 + +#if WASM_ENABLE_STRINGREF != 0 +#define WASM_TYPE_STRINGREF 3 +#define WASM_TYPE_STRINGVIEWWTF8 4 +#define WASM_TYPE_STRINGVIEWWTF16 5 +#define WASM_TYPE_STRINGVIEWITER 6 +#endif + +/* In WasmGC, a table can start with [0x40 0x00] to indicate it has an + * initializer */ +#define TABLE_INIT_EXPR_FLAG 0x40 + typedef struct WASMModule WASMModule; typedef struct WASMFunction WASMFunction; typedef struct WASMGlobal WASMGlobal; @@ -106,6 +197,8 @@ typedef struct WASMGlobal WASMGlobal; typedef struct WASMTag WASMTag; #endif +#ifndef WASM_VALUE_DEFINED +#define WASM_VALUE_DEFINED typedef union V128 { int8 i8x16[16]; int16 i16x8[8]; @@ -124,44 +217,268 @@ typedef union WASMValue { uint64 u64; float32 f32; float64 f64; - uintptr_t addr; V128 v128; +#if WASM_ENABLE_GC != 0 + wasm_obj_t gc_obj; + uint32 type_index; + struct { + uint32 type_index; + uint32 length; + } array_new_default; + /* pointer to a memory space holding more data, current usage: + * struct.new init value: WASMStructNewInitValues * + * array.new init value: WASMArrayNewInitValues * + */ + void *data; +#endif } WASMValue; +#endif /* end of WASM_VALUE_DEFINED */ + +typedef struct WASMStructNewInitValues { + uint8 type_idx; + uint32 count; + WASMValue fields[1]; +} WASMStructNewInitValues; + +typedef struct WASMArrayNewInitValues { + uint8 type_idx; + uint32 length; + WASMValue elem_data[1]; +} WASMArrayNewInitValues; typedef struct InitializerExpression { - /* type of INIT_EXPR_TYPE_XXX */ - /* it actually is instr, in some places, requires constant only */ + /* type of INIT_EXPR_TYPE_XXX, which is an instruction of + constant expression */ uint8 init_expr_type; WASMValue u; } InitializerExpression; +#if WASM_ENABLE_GC != 0 +/** + * Reference type of (ref null ht) or (ref ht), + * and heap type is defined type (type i), i >= 0 + */ +typedef struct RefHeapType_TypeIdx { + /* ref_type is REF_TYPE_HT_NULLABLE or + REF_TYPE_HT_NON_NULLABLE, (0x6C or 0x6B) */ + uint8 ref_type; + /* true if ref_type is REF_TYPE_HT_NULLABLE */ + bool nullable; + /* heap type is defined type: type_index >= 0 */ + int32 type_idx; +} RefHeapType_TypeIdx; + +/** + * Reference type of (ref null ht) or (ref ht), + * and heap type is non-defined type + */ +typedef struct RefHeapType_Common { + /* ref_type is REF_TYPE_HT_NULLABLE or + REF_TYPE_HT_NON_NULLABLE (0x6C or 0x6B) */ + uint8 ref_type; + /* true if ref_type is REF_TYPE_HT_NULLABLE */ + bool nullable; + /* Common heap type (not defined type): + -0x10 (func), -0x11 (extern), -0x12 (any), -0x13 (eq), + -0x16 (i31), -0x17 (nofunc), -0x18 (noextern), + -0x19 (struct), -0x20 (array), -0x21 (none) */ + int32 heap_type; +} RefHeapType_Common; + +/** + * Reference type + */ +typedef union WASMRefType { + uint8 ref_type; + RefHeapType_TypeIdx ref_ht_typeidx; + RefHeapType_Common ref_ht_common; +} WASMRefType; + +typedef struct WASMRefTypeMap { + /** + * The type index of a type array, which only stores + * the first byte of the type, e.g. WASMFuncType.types, + * WASMStructType.fields + */ + uint16 index; + /* The full type info if the type cannot be described + with one byte */ + WASMRefType *ref_type; +} WASMRefTypeMap; +#endif /* end of WASM_ENABLE_GC */ + +#if WASM_ENABLE_GC == 0 +typedef struct WASMFuncType WASMType; +typedef WASMType *WASMTypePtr; +#else +/** + * Common type, store the same fields of + * WASMFuncType, WASMStructType and WASMArrayType + */ typedef struct WASMType { + /** + * type_flag must be WASM_TYPE_FUNC/STRUCT/ARRAY to + * denote that it is a WASMFuncType, WASMStructType or + * WASMArrayType + */ + uint16 type_flag; + + bool is_sub_final; + /* The inheritance depth */ + uint32 inherit_depth; + /* The root type */ + struct WASMType *root_type; + /* The parent type */ + struct WASMType *parent_type; + uint32 parent_type_idx; + + /* number of internal types in the current rec group, if the type is not in + * a recursive group, rec_count = 0 */ + uint16 rec_count; + uint16 rec_idx; +} WASMType, *WASMTypePtr; +#endif /* end of WASM_ENABLE_GC */ + +/* Function type */ +typedef struct WASMFuncType { +#if WASM_ENABLE_GC != 0 + WASMType base_type; +#endif + uint16 param_count; uint16 result_count; uint16 param_cell_num; uint16 ret_cell_num; - uint16 ref_count; + #if WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 \ && WASM_ENABLE_LAZY_JIT != 0 /* Code block to call llvm jit functions of this kind of function type from fast jit jitted code */ void *call_to_llvm_jit_from_fast_jit; #endif + +#if WASM_ENABLE_GC != 0 + uint16 ref_type_map_count; + WASMRefTypeMap *ref_type_maps; + WASMRefTypeMap *result_ref_type_maps; + /* minimal type index of the type equal to this type, + used in type equal check in call_indirect opcode */ + uint32 min_type_idx_normalized; +#else + uint16 ref_count; +#endif + #if WASM_ENABLE_QUICK_AOT_ENTRY != 0 /* Quick AOT/JIT entry of this func type */ void *quick_aot_entry; #endif - /* types of params and results */ + + /* types of params and results, only store the first byte + * of the type, if it cannot be described with one byte, + * then the full type info is stored in ref_type_maps */ uint8 types[1]; -} WASMType; +} WASMFuncType; + +#if WASM_ENABLE_GC != 0 +typedef struct WASMStructFieldType { + uint16 field_flags; + uint8 field_type; + uint8 field_size; + uint32 field_offset; +#if WASM_ENABLE_WAMR_COMPILER != 0 || WASM_ENABLE_JIT != 0 + /* + * The field size and field offset of a wasm struct may vary + * in 32-bit target and 64-bit target, e.g., the size of a + * GC reference is 4 bytes in the former and 8 bytes in the + * latter, the AOT compiler needs to use the correct field + * offset according to the target info. + */ + uint8 field_size_64bit; + uint8 field_size_32bit; + uint32 field_offset_64bit; + uint32 field_offset_32bit; +#endif +} WASMStructFieldType; + +typedef struct WASMStructType { + WASMType base_type; + + /* total size of this struct object */ + uint32 total_size; + uint16 field_count; + + uint16 ref_type_map_count; + WASMRefTypeMap *ref_type_maps; + + /* Offsets of reference fields that need to be traced during GC. + The first element of the table is the number of such offsets. */ + uint16 *reference_table; + + /* Field info, note that fields[i]->field_type only stores + * the first byte of the field type, if it cannot be described + * with one byte, then the full field type info is stored in + * ref_type_maps */ + WASMStructFieldType fields[1]; +} WASMStructType; + +typedef struct WASMArrayType { + WASMType base_type; + + uint16 elem_flags; + uint8 elem_type; + /* The full elem type info if the elem type cannot be + described with one byte */ + WASMRefType *elem_ref_type; +} WASMArrayType; + +#if WASM_ENABLE_STRINGREF != 0 +/* stringref representation, we define it as a void * pointer here, the + * stringref implementation can use any structure */ +/* + WasmGC heap + +-----------------------+ + | | + | stringref | + | +----------+ | external string representation + | | host_ptr |--------o------+----->+------------+ + | +----------+ | | | | + | | | +------------+ + | stringview_wtf8/16 | | + | +----------+ | | + | | host_ptr |--------o------+ + | +----------+ | | + | | | + | stringview_iter | | + | +----------+ | | + | | host_ptr |--------o------+ + | +----------+ | + | | pos | | + | +----------+ | + | | + +-----------------------+ +*/ +typedef void *WASMString; + +#endif /* end of WASM_ENABLE_STRINGREF != 0 */ +#endif /* end of WASM_ENABLE_GC != 0 */ typedef struct WASMTable { uint8 elem_type; - uint32 flags; + /** + * 0: no max size and not shared + * 1: hax max size + * 2: shared + */ + uint8 flags; + bool possible_grow; uint32 init_size; /* specified if (flags & 1), else it is 0x10000 */ uint32 max_size; - bool possible_grow; +#if WASM_ENABLE_GC != 0 + WASMRefType *elem_ref_type; + /* init expr for the whole table */ + InitializerExpression init_expr; +#endif } WASMTable; typedef struct WASMMemory { @@ -174,12 +491,16 @@ typedef struct WASMMemory { typedef struct WASMTableImport { char *module_name; char *field_name; + /* 0: no max size, 1: has max size */ uint8 elem_type; - uint32 flags; + uint8 flags; + bool possible_grow; uint32 init_size; /* specified if (flags & 1), else it is 0x10000 */ uint32 max_size; - bool possible_grow; +#if WASM_ENABLE_GC != 0 + WASMRefType *elem_ref_type; +#endif #if WASM_ENABLE_MULTI_MODULE != 0 WASMModule *import_module; WASMTable *import_table_linked; @@ -203,19 +524,23 @@ typedef struct WASMFunctionImport { char *module_name; char *field_name; /* function type */ - WASMType *func_type; + WASMFuncType *func_type; /* native function pointer after linked */ void *func_ptr_linked; /* signature from registered native symbols */ const char *signature; /* attachment */ void *attachment; +#if WASM_ENABLE_GC != 0 + /* the type index of this function's func_type */ + uint32 type_idx; +#endif bool call_conv_raw; + bool call_conv_wasm_c_api; #if WASM_ENABLE_MULTI_MODULE != 0 WASMModule *import_module; WASMFunction *import_func_linked; #endif - bool call_conv_wasm_c_api; } WASMFunctionImport; #if WASM_ENABLE_TAGS != 0 @@ -241,9 +566,12 @@ typedef struct WASMGlobalImport { char *field_name; uint8 type; bool is_mutable; + bool is_linked; /* global data after linked */ WASMValue global_data_linked; - bool is_linked; +#if WASM_ENABLE_GC != 0 + WASMRefType *ref_type; +#endif #if WASM_ENABLE_MULTI_MODULE != 0 /* imported function pointer after linked */ /* TODO: remove if not needed */ @@ -278,9 +606,13 @@ struct WASMFunction { char *field_name; #endif /* the type of function */ - WASMType *func_type; + WASMFuncType *func_type; uint32 local_count; uint8 *local_types; +#if WASM_ENABLE_GC != 0 + uint16 local_ref_type_map_count; + WASMRefTypeMap *local_ref_type_maps; +#endif /* cell num of parameters */ uint16 param_cell_num; @@ -303,6 +635,11 @@ struct WASMFunction { uint32 const_cell_num; #endif +#if WASM_ENABLE_GC != 0 + /* the type index of this function's func_type */ + uint32 type_idx; +#endif + #if WASM_ENABLE_EXCE_HANDLING != 0 uint32 exception_handler_count; #endif @@ -347,6 +684,9 @@ struct WASMTag { struct WASMGlobal { uint8 type; bool is_mutable; +#if WASM_ENABLE_GC != 0 + WASMRefType *ref_type; +#endif InitializerExpression init_expr; #if WASM_ENABLE_FAST_JIT != 0 /* The data offset of current global in global data */ @@ -365,11 +705,14 @@ typedef struct WASMTableSeg { uint32 mode; /* funcref or externref, elemkind will be considered as funcref */ uint32 elem_type; +#if WASM_ENABLE_GC != 0 + WASMRefType *elem_ref_type; +#endif /* optional, only for active */ uint32 table_index; InitializerExpression base_offset; - uint32 function_count; - uint32 *func_indexes; + uint32 value_count; + InitializerExpression *init_values; } WASMTableSeg; typedef struct WASMDataSeg { @@ -481,6 +824,13 @@ struct WASMModule { #if WASM_ENABLE_BULK_MEMORY != 0 /* data count read from datacount section */ uint32 data_seg_count1; +#endif +#if WASM_ENABLE_GC != 0 +#if WASM_ENABLE_STRINGREF != 0 + uint32 string_literal_count; + uint32 *string_literal_lengths; + const uint8 **string_literal_ptrs; +#endif #endif uint32 import_function_count; @@ -564,13 +914,31 @@ struct WASMModule { bh_list import_module_list_head; bh_list *import_module_list; #endif + +#if WASM_ENABLE_GC != 0 + /* Ref types hash set */ + HashMap *ref_type_set; + struct WASMRttType **rtt_types; + korp_mutex rtt_type_lock; +#if WASM_ENABLE_STRINGREF != 0 + /* special rtts for stringref types + - stringref + - stringview_wtf8 + - stringview_wtf16 + - stringview_iter + */ + struct WASMRttType *stringref_rtts[4]; +#endif +#endif + #if WASM_ENABLE_DEBUG_INTERP != 0 || WASM_ENABLE_DEBUG_AOT != 0 bh_list fast_opcode_list; uint8 *buf_code; uint64 buf_code_size; #endif -#if WASM_ENABLE_DEBUG_INTERP != 0 || WASM_ENABLE_DEBUG_AOT != 0 \ - || WASM_ENABLE_FAST_JIT != 0 + +#if WASM_ENABLE_DEBUG_INTERP != 0 || WASM_ENABLE_FAST_JIT != 0 \ + || WASM_ENABLE_DUMP_CALL_STACK != 0 || WASM_ENABLE_JIT != 0 uint8 *load_addr; uint64 load_size; #endif @@ -671,6 +1039,12 @@ struct WASMModule { functions in that group */ uint32 fast_jit_ready_groups; #endif + +#if WASM_ENABLE_WAMR_COMPILER != 0 + bool is_simd_used; + bool is_ref_types_used; + bool is_bulk_memory_used; +#endif }; typedef struct BlockType { @@ -679,8 +1053,13 @@ typedef struct BlockType { * by a type index of module. */ union { - uint8 value_type; - WASMType *type; + struct { + uint8 type; +#if WASM_ENABLE_GC != 0 + WASMRefTypeMap ref_type_map; +#endif + } value_type; + WASMFuncType *type; } u; bool is_value_type; } BlockType; @@ -755,33 +1134,72 @@ wasm_string_equal(const char *s1, const char *s2) } /** - * Return the byte size of value type. + * Return the byte size of value type with specific pointer size. * + * Note: Please use wasm_value_type_size for interpreter, only aot compiler + * can use this API directly to calculate type size for different target + */ +inline static uint32 +wasm_value_type_size_internal(uint8 value_type, uint8 pointer_size) +{ + if (value_type == VALUE_TYPE_VOID) + return 0; + else if (value_type == VALUE_TYPE_I32 || value_type == VALUE_TYPE_F32 + || value_type == VALUE_TYPE_ANY) + return sizeof(int32); + else if (value_type == VALUE_TYPE_I64 || value_type == VALUE_TYPE_F64) + return sizeof(int64); +#if WASM_ENABLE_SIMD != 0 + else if (value_type == VALUE_TYPE_V128) + return sizeof(int64) * 2; +#endif +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 + else if (value_type == VALUE_TYPE_FUNCREF + || value_type == VALUE_TYPE_EXTERNREF) + return sizeof(uint32); +#elif WASM_ENABLE_GC != 0 + else if ((value_type >= (uint8)REF_TYPE_ARRAYREF /* 0x6A */ + && value_type <= (uint8)REF_TYPE_NULLFUNCREF) /* 0x73 */ + || (value_type >= (uint8)REF_TYPE_HT_NULLABLE /* 0x63 */ + && value_type <= (uint8)REF_TYPE_HT_NON_NULLABLE) /* 0x64 */ +#if WASM_ENABLE_STRINGREF != 0 + || (value_type >= (uint8)REF_TYPE_STRINGVIEWWTF8 /* 0x66 */ + && value_type <= (uint8)REF_TYPE_STRINGREF) /* 0x67 */ + || (value_type >= (uint8)REF_TYPE_STRINGVIEWITER /* 0x61 */ + && value_type <= (uint8)REF_TYPE_STRINGVIEWWTF16) /* 0x62 */ +#endif + ) + return pointer_size; + else if (value_type == PACKED_TYPE_I8) + return sizeof(int8); + else if (value_type == PACKED_TYPE_I16) + return sizeof(int16); +#endif + else { + bh_assert(0); + } + return 0; +} + +/** + * Return the cell num of value type with specific pointer size. + * + * Note: Please use wasm_value_type_cell_num for interpreter, only aot compiler + * can use this API directly to calculate type cell num for different target + */ +inline static uint16 +wasm_value_type_cell_num_internal(uint8 value_type, uint8 pointer_size) +{ + return wasm_value_type_size_internal(value_type, pointer_size) / 4; +} + +/** + * Return the byte size of value type. */ inline static uint32 wasm_value_type_size(uint8 value_type) { - switch (value_type) { - case VALUE_TYPE_I32: - case VALUE_TYPE_F32: -#if WASM_ENABLE_REF_TYPES != 0 - case VALUE_TYPE_FUNCREF: - case VALUE_TYPE_EXTERNREF: -#endif - return sizeof(int32); - case VALUE_TYPE_I64: - case VALUE_TYPE_F64: - return sizeof(int64); -#if WASM_ENABLE_SIMD != 0 - case VALUE_TYPE_V128: - return sizeof(int64) * 2; -#endif - case VALUE_TYPE_VOID: - return 0; - default: - bh_assert(0); - } - return 0; + return wasm_value_type_size_internal(value_type, sizeof(uintptr_t)); } inline static uint16 @@ -813,70 +1231,152 @@ wasm_value_type_cell_num_outside(uint8 value_type) } #endif +#if WASM_ENABLE_GC == 0 inline static bool -wasm_type_equal(const WASMType *type1, const WASMType *type2) +wasm_type_equal(const WASMType *type1, const WASMType *type2, + const WASMTypePtr *types, uint32 type_count) { + const WASMFuncType *func_type1 = (const WASMFuncType *)type1; + const WASMFuncType *func_type2 = (const WASMFuncType *)type2; + if (type1 == type2) { return true; } - return (type1->param_count == type2->param_count - && type1->result_count == type2->result_count - && memcmp(type1->types, type2->types, - (uint32)(type1->param_count + type1->result_count)) + + return (func_type1->param_count == func_type2->param_count + && func_type1->result_count == func_type2->result_count + && memcmp( + func_type1->types, func_type2->types, + (uint32)(func_type1->param_count + func_type1->result_count)) == 0) ? true : false; + (void)types; + (void)type_count; } +#else +/* implemented in gc_type.c */ +bool +wasm_type_equal(const WASMType *type1, const WASMType *type2, + const WASMTypePtr *types, uint32 type_count); +#endif inline static uint32 -wasm_get_smallest_type_idx(WASMType **types, uint32 type_count, +wasm_get_smallest_type_idx(const WASMTypePtr *types, uint32 type_count, uint32 cur_type_idx) { uint32 i; for (i = 0; i < cur_type_idx; i++) { - if (wasm_type_equal(types[cur_type_idx], types[i])) + if (wasm_type_equal(types[cur_type_idx], types[i], types, type_count)) return i; } - (void)type_count; return cur_type_idx; } +#if WASM_ENABLE_GC == 0 static inline uint32 block_type_get_param_types(BlockType *block_type, uint8 **p_param_types) +#else +static inline uint32 +block_type_get_param_types(BlockType *block_type, uint8 **p_param_types, + WASMRefTypeMap **p_param_reftype_maps, + uint32 *p_param_reftype_map_count) +#endif { uint32 param_count = 0; if (!block_type->is_value_type) { - WASMType *wasm_type = block_type->u.type; - *p_param_types = wasm_type->types; - param_count = wasm_type->param_count; + WASMFuncType *func_type = block_type->u.type; + *p_param_types = func_type->types; + param_count = func_type->param_count; +#if WASM_ENABLE_GC != 0 + *p_param_reftype_maps = func_type->ref_type_maps; + *p_param_reftype_map_count = + func_type->result_ref_type_maps - func_type->ref_type_maps; +#endif } else { *p_param_types = NULL; param_count = 0; +#if WASM_ENABLE_GC != 0 + *p_param_reftype_maps = NULL; + *p_param_reftype_map_count = 0; +#endif } return param_count; } +#if WASM_ENABLE_GC == 0 static inline uint32 block_type_get_result_types(BlockType *block_type, uint8 **p_result_types) +#else +static inline uint32 +block_type_get_result_types(BlockType *block_type, uint8 **p_result_types, + WASMRefTypeMap **p_result_reftype_maps, + uint32 *p_result_reftype_map_count) +#endif { uint32 result_count = 0; + uint8 *result_types = NULL; +#if WASM_ENABLE_GC != 0 + uint8 type; + uint32 result_reftype_map_count = 0; + WASMRefTypeMap *result_reftype_maps = NULL; +#endif + if (block_type->is_value_type) { - if (block_type->u.value_type != VALUE_TYPE_VOID) { - *p_result_types = &block_type->u.value_type; + if (block_type->u.value_type.type != VALUE_TYPE_VOID) { + result_types = &block_type->u.value_type.type; result_count = 1; +#if WASM_ENABLE_GC != 0 + type = block_type->u.value_type.type; + if (type == (uint8)REF_TYPE_HT_NULLABLE + || type == (uint8)REF_TYPE_HT_NON_NULLABLE) { + result_reftype_maps = &block_type->u.value_type.ref_type_map; + result_reftype_map_count = 1; + } +#endif } } else { - WASMType *wasm_type = block_type->u.type; - *p_result_types = wasm_type->types + wasm_type->param_count; - result_count = wasm_type->result_count; + WASMFuncType *func_type = block_type->u.type; + result_types = func_type->types + func_type->param_count; + result_count = func_type->result_count; +#if WASM_ENABLE_GC != 0 + result_reftype_maps = func_type->result_ref_type_maps; + result_reftype_map_count = (uint32)(func_type->ref_type_map_count + - (func_type->result_ref_type_maps + - func_type->ref_type_maps)); +#endif } + *p_result_types = result_types; +#if WASM_ENABLE_GC != 0 + *p_result_reftype_maps = result_reftype_maps; + *p_result_reftype_map_count = result_reftype_map_count; +#endif return result_count; } +static inline uint32 +block_type_get_arity(const BlockType *block_type, uint8 label_type) +{ + if (label_type == LABEL_TYPE_LOOP) { + if (block_type->is_value_type) + return 0; + else + return block_type->u.type->param_count; + } + else { + if (block_type->is_value_type) { + return block_type->u.value_type.type != VALUE_TYPE_VOID ? 1 : 0; + } + else + return block_type->u.type->result_count; + } + return 0; +} + #ifdef __cplusplus } /* end of extern "C" */ #endif diff --git a/core/iwasm/interpreter/wasm_interp.h b/core/iwasm/interpreter/wasm_interp.h index 2b5a51ea8..141640546 100644 --- a/core/iwasm/interpreter/wasm_interp.h +++ b/core/iwasm/interpreter/wasm_interp.h @@ -47,8 +47,11 @@ typedef struct WASMInterpFrame { the callee will put return values here continuously */ uint32 ret_offset; uint32 *lp; +#if WASM_ENABLE_GC != 0 + uint8 *frame_ref; +#endif uint32 operand[1]; -#else +#else /* else of WASM_ENABLE_FAST_INTERP != 0 */ /* Operand stack top pointer of the current frame. The bottom of the stack is the next cell after the last local variable. */ uint32 *sp_bottom; @@ -64,10 +67,12 @@ typedef struct WASMInterpFrame { * lp: parameters and local variables * sp_bottom to sp_boundary: wasm operand stack * csp_bottom to csp_boundary: wasm label stack + * frame ref flags: only available for GC + * whether each cell in local and stack area is a GC obj * jit spill cache: only available for fast jit */ uint32 lp[1]; -#endif +#endif /* end of WASM_ENABLE_FAST_INTERP != 0 */ } WASMInterpFrame; /** @@ -84,7 +89,12 @@ wasm_interp_interp_frame_size(unsigned all_cell_num) unsigned frame_size; #if WASM_ENABLE_FAST_INTERP == 0 +#if WASM_ENABLE_GC == 0 frame_size = (uint32)offsetof(WASMInterpFrame, lp) + all_cell_num * 4; +#else + frame_size = + (uint32)offsetof(WASMInterpFrame, lp) + align_uint(all_cell_num * 5, 4); +#endif #else frame_size = (uint32)offsetof(WASMInterpFrame, operand) + all_cell_num * 4; #endif @@ -97,6 +107,14 @@ wasm_interp_call_wasm(struct WASMModuleInstance *module_inst, struct WASMFunctionInstance *function, uint32 argc, uint32 argv[]); +#if WASM_ENABLE_GC != 0 +bool +wasm_interp_traverse_gc_rootset(struct WASMExecEnv *exec_env, void *heap); + +uint8 * +wasm_interp_get_frame_ref(WASMInterpFrame *frame); +#endif + #ifdef __cplusplus } #endif diff --git a/core/iwasm/interpreter/wasm_interp_classic.c b/core/iwasm/interpreter/wasm_interp_classic.c index e4da90b9c..16291b3f5 100644 --- a/core/iwasm/interpreter/wasm_interp_classic.c +++ b/core/iwasm/interpreter/wasm_interp_classic.c @@ -10,6 +10,13 @@ #include "wasm_loader.h" #include "wasm_memory.h" #include "../common/wasm_exec_env.h" +#if WASM_ENABLE_GC != 0 +#include "../common/gc/gc_object.h" +#include "mem_alloc.h" +#if WASM_ENABLE_STRINGREF != 0 +#include "string_object.h" +#endif +#endif #if WASM_ENABLE_SHARED_MEMORY != 0 #include "../common/wasm_shared_memory.h" #endif @@ -314,6 +321,98 @@ read_leb(const uint8 *buf, uint32 *p_offset, uint32 maxbits, bool sign) return result; } +#if WASM_ENABLE_GC != 0 +static uint8 * +get_frame_ref(WASMInterpFrame *frame) +{ + WASMFunctionInstance *cur_func = frame->function; + uint32 all_cell_num; + + if (!cur_func) { + /* it's a glue frame created in wasm_interp_call_wasm, + no GC object will be traversed */ + return (uint8 *)frame->lp; + } + else if (!frame->ip) { + /* it's a native method frame created in + wasm_interp_call_func_native */ + all_cell_num = + cur_func->param_cell_num > 2 ? cur_func->param_cell_num : 2; + return (uint8 *)(frame->lp + all_cell_num); + } + else { +#if WASM_ENABLE_JIT == 0 + /* it's a wasm bytecode function frame */ + return (uint8 *)frame->csp_boundary; +#else + return (uint8 *)(frame->lp + cur_func->param_cell_num + + cur_func->local_cell_num + + cur_func->u.func->max_stack_cell_num); +#endif + } +} + +static void +init_frame_refs(uint8 *frame_ref, uint32 cell_num, WASMFunctionInstance *func) +{ + uint32 i, j; + + memset(frame_ref, 0, cell_num); + + for (i = 0, j = 0; i < func->param_count; i++) { + if (wasm_is_type_reftype(func->param_types[i]) + && !wasm_is_reftype_i31ref(func->param_types[i])) { + frame_ref[j++] = 1; +#if UINTPTR_MAX == UINT64_MAX + frame_ref[j++] = 1; +#endif + } + else { + j += wasm_value_type_cell_num(func->param_types[i]); + } + } + + for (i = 0; i < func->local_count; i++) { + if (wasm_is_type_reftype(func->local_types[i]) + && !wasm_is_reftype_i31ref(func->local_types[i])) { + frame_ref[j++] = 1; +#if UINTPTR_MAX == UINT64_MAX + frame_ref[j++] = 1; +#endif + } + else { + j += wasm_value_type_cell_num(func->local_types[i]); + } + } +} + +uint8 * +wasm_interp_get_frame_ref(WASMInterpFrame *frame) +{ + return get_frame_ref(frame); +} + +/* Return the corresponding ref slot of the given address of local + variable or stack pointer. */ + +#define COMPUTE_FRAME_REF(ref, lp, p) (ref + (unsigned)((uint32 *)p - lp)) + +#define FRAME_REF(p) COMPUTE_FRAME_REF(frame_ref, frame_lp, p) + +#define FRAME_REF_FOR(frame, p) \ + COMPUTE_FRAME_REF(get_frame_ref(frame), frame->lp, p) + +#define CLEAR_FRAME_REF(p, n) \ + do { \ + int32 ref_i, ref_n = (int32)(n); \ + uint8 *ref = FRAME_REF(p); \ + for (ref_i = 0; ref_i < ref_n; ref_i++) \ + ref[ref_i] = 0; \ + } while (0) +#else +#define CLEAR_FRAME_REF(p, n) (void)0 +#endif /* end of WASM_ENABLE_GC != 0 */ + #define skip_leb(p) while (*p++ & 0x80) #define PUSH_I32(value) \ @@ -338,6 +437,34 @@ read_leb(const uint8 *buf, uint32 *p_offset, uint32 maxbits, bool sign) frame_sp += 2; \ } while (0) +#if UINTPTR_MAX == UINT64_MAX +#define PUSH_REF(value) \ + do { \ + PUT_REF_TO_ADDR(frame_sp, value); \ + frame_ref_tmp = FRAME_REF(frame_sp); \ + *frame_ref_tmp = *(frame_ref_tmp + 1) = 1; \ + frame_sp += 2; \ + } while (0) +#define PUSH_I31REF(value) \ + do { \ + PUT_REF_TO_ADDR(frame_sp, value); \ + frame_sp += 2; \ + } while (0) +#else +#define PUSH_REF(value) \ + do { \ + PUT_REF_TO_ADDR(frame_sp, value); \ + frame_ref_tmp = FRAME_REF(frame_sp); \ + *frame_ref_tmp = 1; \ + frame_sp++; \ + } while (0) +#define PUSH_I31REF(value) \ + do { \ + PUT_REF_TO_ADDR(frame_sp, value); \ + frame_sp++; \ + } while (0) +#endif + /* in exception handling, label_type needs to be stored to lookup exception * handlers */ @@ -366,6 +493,16 @@ read_leb(const uint8 *buf, uint32 *p_offset, uint32 maxbits, bool sign) #define POP_F64() (frame_sp -= 2, GET_F64_FROM_ADDR(frame_sp)) +#if UINTPTR_MAX == UINT64_MAX +#define POP_REF() \ + (frame_sp -= 2, frame_ref_tmp = FRAME_REF(frame_sp), \ + *frame_ref_tmp = *(frame_ref_tmp + 1) = 0, GET_REF_FROM_ADDR(frame_sp)) +#else +#define POP_REF() \ + (frame_sp--, frame_ref_tmp = FRAME_REF(frame_sp), *frame_ref_tmp = 0, \ + GET_REF_FROM_ADDR(frame_sp)) +#endif + #define POP_CSP_CHECK_OVERFLOW(n) \ do { \ bh_assert(frame_csp - n >= frame->csp_bottom); \ @@ -377,28 +514,33 @@ read_leb(const uint8 *buf, uint32 *p_offset, uint32 maxbits, bool sign) --frame_csp; \ } while (0) -#define POP_CSP_N(n) \ - do { \ - uint32 *frame_sp_old = frame_sp; \ - uint32 cell_num_to_copy; \ - POP_CSP_CHECK_OVERFLOW(n + 1); \ - frame_csp -= n; \ - frame_ip = (frame_csp - 1)->target_addr; \ - /* copy arity values of block */ \ - frame_sp = (frame_csp - 1)->frame_sp; \ - cell_num_to_copy = (frame_csp - 1)->cell_num; \ - if (cell_num_to_copy > 0) { \ - word_copy(frame_sp, frame_sp_old - cell_num_to_copy, \ - cell_num_to_copy); \ - } \ - frame_sp += cell_num_to_copy; \ +#define POP_CSP_N(n) \ + do { \ + uint32 *frame_sp_old = frame_sp; \ + uint32 cell_num_to_copy; \ + POP_CSP_CHECK_OVERFLOW(n + 1); \ + frame_csp -= n; \ + frame_ip = (frame_csp - 1)->target_addr; \ + /* copy arity values of block */ \ + frame_sp = (frame_csp - 1)->frame_sp; \ + cell_num_to_copy = (frame_csp - 1)->cell_num; \ + if (cell_num_to_copy > 0) { \ + word_copy(frame_sp, frame_sp_old - cell_num_to_copy, \ + cell_num_to_copy); \ + frame_ref_copy(FRAME_REF(frame_sp), \ + FRAME_REF(frame_sp_old - cell_num_to_copy), \ + cell_num_to_copy); \ + } \ + frame_sp += cell_num_to_copy; \ + CLEAR_FRAME_REF(frame_sp, frame_sp_old - frame_sp); \ } while (0) /* Pop the given number of elements from the given frame's stack. */ -#define POP(N) \ - do { \ - int n = (N); \ - frame_sp -= n; \ +#define POP(N) \ + do { \ + int n = (N); \ + frame_sp -= n; \ + CLEAR_FRAME_REF(frame_sp, n); \ } while (0) #if WASM_ENABLE_EXCE_HANDLING != 0 @@ -478,6 +620,12 @@ read_leb(const uint8 *buf, uint32 *p_offset, uint32 maxbits, bool sign) #define RECOVER_FRAME_IP_END() (void)0 #endif +#if WASM_ENABLE_GC != 0 +#define RECOVER_FRAME_REF() frame_ref = (uint8 *)frame->csp_boundary +#else +#define RECOVER_FRAME_REF() (void)0 +#endif + #define RECOVER_CONTEXT(new_frame) \ do { \ frame = (new_frame); \ @@ -488,6 +636,7 @@ read_leb(const uint8 *buf, uint32 *p_offset, uint32 maxbits, bool sign) frame_lp = frame->lp; \ frame_sp = frame->sp; \ frame_csp = frame->csp; \ + RECOVER_FRAME_REF(); \ } while (0) #if WASM_ENABLE_LABELS_AS_VALUES != 0 @@ -728,7 +877,7 @@ trunc_f64_to_int(WASMModuleInstance *module, uint32 *frame_sp, float64 src_min, addr = POP_I32(); \ \ if (opcode == WASM_OP_ATOMIC_RMW_I32_##OP_NAME##8_U) { \ - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 1, maddr); \ + CHECK_MEMORY_OVERFLOW(1); \ CHECK_ATOMIC_MEMORY_ACCESS(); \ \ shared_memory_lock(memory); \ @@ -737,7 +886,7 @@ trunc_f64_to_int(WASMModuleInstance *module, uint32 *frame_sp, float64 src_min, shared_memory_unlock(memory); \ } \ else if (opcode == WASM_OP_ATOMIC_RMW_I32_##OP_NAME##16_U) { \ - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 2, maddr); \ + CHECK_MEMORY_OVERFLOW(2); \ CHECK_ATOMIC_MEMORY_ACCESS(); \ \ shared_memory_lock(memory); \ @@ -746,7 +895,7 @@ trunc_f64_to_int(WASMModuleInstance *module, uint32 *frame_sp, float64 src_min, shared_memory_unlock(memory); \ } \ else { \ - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 4, maddr); \ + CHECK_MEMORY_OVERFLOW(4); \ CHECK_ATOMIC_MEMORY_ACCESS(); \ \ shared_memory_lock(memory); \ @@ -768,7 +917,7 @@ trunc_f64_to_int(WASMModuleInstance *module, uint32 *frame_sp, float64 src_min, addr = POP_I32(); \ \ if (opcode == WASM_OP_ATOMIC_RMW_I64_##OP_NAME##8_U) { \ - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 1, maddr); \ + CHECK_MEMORY_OVERFLOW(1); \ CHECK_ATOMIC_MEMORY_ACCESS(); \ \ shared_memory_lock(memory); \ @@ -777,7 +926,7 @@ trunc_f64_to_int(WASMModuleInstance *module, uint32 *frame_sp, float64 src_min, shared_memory_unlock(memory); \ } \ else if (opcode == WASM_OP_ATOMIC_RMW_I64_##OP_NAME##16_U) { \ - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 2, maddr); \ + CHECK_MEMORY_OVERFLOW(2); \ CHECK_ATOMIC_MEMORY_ACCESS(); \ \ shared_memory_lock(memory); \ @@ -786,7 +935,7 @@ trunc_f64_to_int(WASMModuleInstance *module, uint32 *frame_sp, float64 src_min, shared_memory_unlock(memory); \ } \ else if (opcode == WASM_OP_ATOMIC_RMW_I64_##OP_NAME##32_U) { \ - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 4, maddr); \ + CHECK_MEMORY_OVERFLOW(4); \ CHECK_ATOMIC_MEMORY_ACCESS(); \ \ shared_memory_lock(memory); \ @@ -796,7 +945,7 @@ trunc_f64_to_int(WASMModuleInstance *module, uint32 *frame_sp, float64 src_min, } \ else { \ uint64 op_result; \ - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 8, maddr); \ + CHECK_MEMORY_OVERFLOW(8); \ CHECK_ATOMIC_MEMORY_ACCESS(); \ \ shared_memory_lock(memory); \ @@ -863,6 +1012,18 @@ word_copy(uint32 *dest, uint32 *src, unsigned num) } } +#if WASM_ENABLE_GC != 0 +static inline void +frame_ref_copy(uint8 *frame_ref_dest, uint8 *frame_ref_src, unsigned num) +{ + if (frame_ref_dest != frame_ref_src) + for (; num > 0; num--) + *frame_ref_dest++ = *frame_ref_src++; +} +#else +#define frame_ref_copy(frame_ref_dst, frame_ref_src, num) (void)0 +#endif + static inline WASMInterpFrame * ALLOC_FRAME(WASMExecEnv *exec_env, uint32 size, WASMInterpFrame *prev_frame) { @@ -888,12 +1049,13 @@ FREE_FRAME(WASMExecEnv *exec_env, WASMInterpFrame *frame) #if WASM_ENABLE_PERF_PROFILING != 0 if (frame->function) { WASMInterpFrame *prev_frame = frame->prev_frame; - uint64 elapsed = os_time_thread_cputime_us() - frame->time_started; - frame->function->total_exec_time += elapsed; + uint64 time_elapsed = os_time_thread_cputime_us() - frame->time_started; + + frame->function->total_exec_time += time_elapsed; frame->function->total_exec_cnt++; if (prev_frame && prev_frame->function) - prev_frame->function->children_exec_time += elapsed; + prev_frame->function->children_exec_time += time_elapsed; } #endif wasm_exec_env_free_wasm_frame(exec_env, frame); @@ -907,21 +1069,37 @@ wasm_interp_call_func_native(WASMModuleInstance *module_inst, { WASMFunctionImport *func_import = cur_func->u.func_import; CApiFuncImport *c_api_func_import = NULL; - unsigned local_cell_num = 2; + unsigned local_cell_num = + cur_func->param_cell_num > 2 ? cur_func->param_cell_num : 2; + unsigned all_cell_num; WASMInterpFrame *frame; uint32 argv_ret[2], cur_func_index; void *native_func_pointer = NULL; char buf[128]; bool ret; +#if WASM_ENABLE_GC != 0 + WASMFuncType *func_type; + uint8 *frame_ref; +#endif - if (!(frame = ALLOC_FRAME(exec_env, - wasm_interp_interp_frame_size(local_cell_num), - prev_frame))) + all_cell_num = local_cell_num; +#if WASM_ENABLE_GC != 0 + all_cell_num += (local_cell_num + 3) / 4; +#endif + + if (!(frame = + ALLOC_FRAME(exec_env, wasm_interp_interp_frame_size(all_cell_num), + prev_frame))) return; frame->function = cur_func; frame->ip = NULL; frame->sp = frame->lp + local_cell_num; +#if WASM_ENABLE_GC != 0 + /* native function doesn't have operand stack and label stack */ + frame_ref = (uint8 *)frame->sp; + init_frame_refs(frame_ref, local_cell_num, cur_func); +#endif wasm_exec_env_set_cur_frame(exec_env, frame); @@ -970,6 +1148,22 @@ wasm_interp_call_func_native(WASMModuleInstance *module_inst, if (!ret) return; +#if WASM_ENABLE_GC != 0 + func_type = cur_func->u.func_import->func_type; + if (func_type->result_count + && wasm_is_type_reftype(func_type->types[cur_func->param_count])) { + frame_ref = (uint8 *)prev_frame->csp_boundary + + (unsigned)(uintptr_t)(prev_frame->sp - prev_frame->lp); + if (!wasm_is_reftype_i31ref(func_type->types[cur_func->param_count])) { +#if UINTPTR_MAX == UINT64_MAX + *frame_ref = *(frame_ref + 1) = 1; +#else + *frame_ref = 1; +#endif + } + } +#endif + if (cur_func->ret_cell_num == 1) { prev_frame->sp[0] = argv_ret[0]; prev_frame->sp++; @@ -1188,7 +1382,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, linear_mem_size = GET_LINEAR_MEMORY_SIZE(memory); #endif #endif - WASMType **wasm_types = module->module->types; + WASMFuncType **wasm_types = (WASMFuncType **)module->module->types; WASMGlobalInstance *globals = module->e->globals, *global; uint8 *global_data = module->global_data; uint8 opcode_IMPDEP = WASM_OP_IMPDEP; @@ -1198,6 +1392,10 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, register uint8 *frame_ip = &opcode_IMPDEP; /* cache of frame->ip */ register uint32 *frame_lp = NULL; /* cache of frame->lp */ register uint32 *frame_sp = NULL; /* cache of frame->sp */ +#if WASM_ENABLE_GC != 0 + register uint8 *frame_ref = NULL; /* cache of frame->ref */ + uint8 *frame_ref_tmp; +#endif WASMBranchBlock *frame_csp = NULL; BlockAddr *cache_items; uint8 *frame_ip_end = frame_ip + 1; @@ -1222,6 +1420,21 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, bool disable_bounds_checks = false; #endif #endif +#if WASM_ENABLE_GC != 0 + WASMObjectRef gc_obj; + WASMStructObjectRef struct_obj; + WASMArrayObjectRef array_obj; + WASMFuncObjectRef func_obj; + WASMI31ObjectRef i31_obj; + WASMExternrefObjectRef externref_obj; +#if WASM_ENABLE_STRINGREF != 0 + WASMString str_obj = NULL; + WASMStringrefObjectRef stringref_obj; + WASMStringviewWTF8ObjectRef stringview_wtf8_obj; + WASMStringviewWTF16ObjectRef stringview_wtf16_obj; + WASMStringviewIterObjectRef stringview_iter_obj; +#endif +#endif #if WASM_ENABLE_DEBUG_INTERP != 0 uint8 *frame_ip_orig = NULL; @@ -1255,7 +1468,6 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_NOP) { HANDLE_OP_END(); } #if WASM_ENABLE_EXCE_HANDLING != 0 - HANDLE_OP(WASM_OP_RETHROW) { int32_t relative_depth; @@ -1637,12 +1849,14 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, POP_CSP(); HANDLE_OP_END(); } -#endif +#endif /* end of WASM_ENABLE_EXCE_HANDLING != 0 */ HANDLE_OP(EXT_OP_BLOCK) { read_leb_uint32(frame_ip, frame_ip_end, type_index); - param_cell_num = wasm_types[type_index]->param_cell_num; - cell_num = wasm_types[type_index]->ret_cell_num; + param_cell_num = + ((WASMFuncType *)wasm_types[type_index])->param_cell_num; + cell_num = + ((WASMFuncType *)wasm_types[type_index])->ret_cell_num; goto handle_op_block; } @@ -1680,8 +1894,10 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(EXT_OP_LOOP) { read_leb_uint32(frame_ip, frame_ip_end, type_index); - param_cell_num = wasm_types[type_index]->param_cell_num; - cell_num = wasm_types[type_index]->param_cell_num; + param_cell_num = + ((WASMFuncType *)wasm_types[type_index])->param_cell_num; + cell_num = + ((WASMFuncType *)wasm_types[type_index])->param_cell_num; goto handle_op_loop; } @@ -1698,8 +1914,10 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(EXT_OP_IF) { read_leb_uint32(frame_ip, frame_ip_end, type_index); - param_cell_num = wasm_types[type_index]->param_cell_num; - cell_num = wasm_types[type_index]->ret_cell_num; + param_cell_num = + ((WASMFuncType *)wasm_types[type_index])->param_cell_num; + cell_num = + ((WASMFuncType *)wasm_types[type_index])->ret_cell_num; goto handle_op_if; } @@ -1763,6 +1981,14 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, else { /* end of function, treat as WASM_OP_RETURN */ frame_sp -= cur_func->ret_cell_num; for (i = 0; i < cur_func->ret_cell_num; i++) { +#if WASM_ENABLE_GC != 0 + if (prev_frame->ip) { + /* prev frame is not a glue frame and has + the frame ref area */ + *FRAME_REF_FOR(prev_frame, prev_frame->sp) = + *FRAME_REF(frame_sp + i); + } +#endif *prev_frame->sp++ = frame_sp[i]; } goto return_func; @@ -1845,6 +2071,14 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, { frame_sp -= cur_func->ret_cell_num; for (i = 0; i < cur_func->ret_cell_num; i++) { +#if WASM_ENABLE_GC != 0 + if (prev_frame->ip) { + /* prev frame is not a glue frame and has + the frame ref area */ + *FRAME_REF_FOR(prev_frame, prev_frame->sp) = + *FRAME_REF(frame_sp + i); + } +#endif *prev_frame->sp++ = frame_sp[i]; } goto return_func; @@ -1891,7 +2125,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_RETURN_CALL_INDIRECT) #endif { - WASMType *cur_type, *cur_func_type; + WASMFuncType *cur_type, *cur_func_type; WASMTableInstance *tbl_inst; uint32 tbl_idx; #if WASM_ENABLE_TAIL_CALL != 0 @@ -1922,11 +2156,22 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, goto got_exception; } + /* clang-format off */ +#if WASM_ENABLE_GC == 0 fidx = tbl_inst->elems[val]; - if (fidx == NULL_REF) { + if (fidx == (uint32)-1) { wasm_set_exception(module, "uninitialized element"); goto got_exception; } +#else + func_obj = (WASMFuncObjectRef)tbl_inst->elems[val]; + if (!func_obj) { + wasm_set_exception(module, "uninitialized element"); + goto got_exception; + } + fidx = wasm_func_obj_get_func_idx_bound(func_obj); +#endif + /* clang-format on */ /* * we might be using a table injected by host or @@ -1946,10 +2191,20 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, else cur_func_type = cur_func->u.func->func_type; + /* clang-format off */ +#if WASM_ENABLE_GC == 0 if (cur_type != cur_func_type) { wasm_set_exception(module, "indirect call type mismatch"); goto got_exception; } +#else + if (cur_type->min_type_idx_normalized + != cur_func_type->min_type_idx_normalized) { + wasm_set_exception(module, "indirect call type mismatch"); + goto got_exception; + } +#endif + /* clang-format on */ #if WASM_ENABLE_TAIL_CALL != 0 if (opcode == WASM_OP_RETURN_CALL_INDIRECT) @@ -1962,12 +2217,24 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_DROP) { frame_sp--; + +#if WASM_ENABLE_GC != 0 + frame_ref_tmp = FRAME_REF(frame_sp); + *frame_ref_tmp = 0; +#endif HANDLE_OP_END(); } HANDLE_OP(WASM_OP_DROP_64) { frame_sp -= 2; + +#if WASM_ENABLE_GC != 0 + frame_ref_tmp = FRAME_REF(frame_sp); + *frame_ref_tmp = 0; + *(frame_ref_tmp + 1) = 0; +#endif + HANDLE_OP_END(); } @@ -1991,7 +2258,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP_END(); } -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 HANDLE_OP(WASM_OP_SELECT_T) { uint32 vec_len; @@ -2001,7 +2268,11 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, type = *frame_ip++; cond = (uint32)POP_I32(); - if (type == VALUE_TYPE_I64 || type == VALUE_TYPE_F64) { + if (type == VALUE_TYPE_I64 || type == VALUE_TYPE_F64 +#if WASM_ENABLE_GC != 0 && UINTPTR_MAX == UINT64_MAX + || wasm_is_type_reftype(type) +#endif + ) { frame_sp -= 2; if (!cond) { *(frame_sp - 2) = *frame_sp; @@ -2014,9 +2285,17 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, *(frame_sp - 1) = *frame_sp; } +#if WASM_ENABLE_GC != 0 + frame_ref_tmp = FRAME_REF(frame_sp); + *frame_ref_tmp = 0; +#if UINTPTR_MAX == UINT64_MAX + *(frame_ref_tmp + 1) = 0; +#endif +#endif (void)vec_len; HANDLE_OP_END(); } + HANDLE_OP(WASM_OP_TABLE_GET) { uint32 tbl_idx, elem_idx; @@ -2033,21 +2312,30 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, goto got_exception; } +#if WASM_ENABLE_GC == 0 PUSH_I32(tbl_inst->elems[elem_idx]); +#else + PUSH_REF(tbl_inst->elems[elem_idx]); +#endif HANDLE_OP_END(); } HANDLE_OP(WASM_OP_TABLE_SET) { - uint32 tbl_idx, elem_idx, elem_val; WASMTableInstance *tbl_inst; + uint32 tbl_idx, elem_idx; + table_elem_type_t elem_val; read_leb_uint32(frame_ip, frame_ip_end, tbl_idx); bh_assert(tbl_idx < module->table_count); tbl_inst = wasm_get_table_inst(module, tbl_idx); +#if WASM_ENABLE_GC == 0 elem_val = POP_I32(); +#else + elem_val = POP_REF(); +#endif elem_idx = POP_I32(); if (elem_idx >= tbl_inst->cur_size) { wasm_set_exception(module, "out of bounds table access"); @@ -2062,15 +2350,24 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, { uint32 ref_type; read_leb_uint32(frame_ip, frame_ip_end, ref_type); +#if WASM_ENABLE_GC == 0 PUSH_I32(NULL_REF); +#else + PUSH_REF(NULL_REF); +#endif (void)ref_type; HANDLE_OP_END(); } HANDLE_OP(WASM_OP_REF_IS_NULL) { +#if WASM_ENABLE_GC == 0 uint32 ref_val; ref_val = POP_I32(); +#else + void *ref_val; + ref_val = POP_REF(); +#endif PUSH_I32(ref_val == NULL_REF ? 1 : 0); HANDLE_OP_END(); } @@ -2079,10 +2376,1512 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, { uint32 func_idx; read_leb_uint32(frame_ip, frame_ip_end, func_idx); +#if WASM_ENABLE_GC == 0 PUSH_I32(func_idx); +#else + SYNC_ALL_TO_FRAME(); + if (!(gc_obj = wasm_create_func_obj(module, func_idx, true, + NULL, 0))) { + goto got_exception; + } + PUSH_REF(gc_obj); +#endif HANDLE_OP_END(); } -#endif /* WASM_ENABLE_REF_TYPES */ +#endif /* end of WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */ + +#if WASM_ENABLE_GC != 0 + HANDLE_OP(WASM_OP_CALL_REF) + { +#if WASM_ENABLE_THREAD_MGR != 0 + CHECK_SUSPEND_FLAGS(); +#endif + read_leb_uint32(frame_ip, frame_ip_end, type_index); + func_obj = POP_REF(); + if (!func_obj) { + wasm_set_exception(module, "null function object"); + goto got_exception; + } + + fidx = wasm_func_obj_get_func_idx_bound(func_obj); + cur_func = module->e->functions + fidx; + goto call_func_from_interp; + } + + HANDLE_OP(WASM_OP_RETURN_CALL_REF) + { +#if WASM_ENABLE_THREAD_MGR != 0 + CHECK_SUSPEND_FLAGS(); +#endif + read_leb_uint32(frame_ip, frame_ip_end, type_index); + func_obj = POP_REF(); + if (!func_obj) { + wasm_set_exception(module, "null function object"); + goto got_exception; + } + + fidx = wasm_func_obj_get_func_idx_bound(func_obj); + cur_func = module->e->functions + fidx; + goto call_func_from_return_call; + } + + HANDLE_OP(WASM_OP_REF_EQ) + { + WASMObjectRef gc_obj1, gc_obj2; + gc_obj2 = POP_REF(); + gc_obj1 = POP_REF(); + val = wasm_obj_equal(gc_obj1, gc_obj2); + PUSH_I32(val); + HANDLE_OP_END(); + } + + HANDLE_OP(WASM_OP_REF_AS_NON_NULL) + { + gc_obj = POP_REF(); + if (gc_obj == NULL_REF) { + wasm_set_exception(module, "null reference"); + goto got_exception; + } + PUSH_REF(gc_obj); + HANDLE_OP_END(); + } + + HANDLE_OP(WASM_OP_BR_ON_NULL) + { +#if WASM_ENABLE_THREAD_MGR != 0 + CHECK_SUSPEND_FLAGS(); +#endif + read_leb_uint32(frame_ip, frame_ip_end, depth); + gc_obj = GET_REF_FROM_ADDR(frame_sp - REF_CELL_NUM); + if (gc_obj == NULL_REF) { + frame_sp -= REF_CELL_NUM; + CLEAR_FRAME_REF(frame_sp, REF_CELL_NUM); + goto label_pop_csp_n; + } + HANDLE_OP_END(); + } + + HANDLE_OP(WASM_OP_BR_ON_NON_NULL) + { +#if WASM_ENABLE_THREAD_MGR != 0 + CHECK_SUSPEND_FLAGS(); +#endif + read_leb_uint32(frame_ip, frame_ip_end, depth); + gc_obj = GET_REF_FROM_ADDR(frame_sp - REF_CELL_NUM); + if (gc_obj != NULL_REF) { + goto label_pop_csp_n; + } + else { + frame_sp -= REF_CELL_NUM; + CLEAR_FRAME_REF(frame_sp, REF_CELL_NUM); + } + HANDLE_OP_END(); + } + + HANDLE_OP(WASM_OP_GC_PREFIX) + { + uint32 opcode1; + + read_leb_uint32(frame_ip, frame_ip_end, opcode1); + /* opcode1 was checked in loader and is no larger than + UINT8_MAX */ + opcode = (uint8)opcode1; + + switch (opcode) { + case WASM_OP_STRUCT_NEW: + case WASM_OP_STRUCT_NEW_DEFAULT: + { + WASMModule *wasm_module = module->module; + WASMStructType *struct_type; + WASMRttType *rtt_type; + WASMValue field_value = { 0 }; + + read_leb_uint32(frame_ip, frame_ip_end, type_index); + struct_type = + (WASMStructType *)module->module->types[type_index]; + + if (!(rtt_type = wasm_rtt_type_new( + (WASMType *)struct_type, type_index, + wasm_module->rtt_types, + wasm_module->type_count, + &wasm_module->rtt_type_lock))) { + wasm_set_exception(module, + "create rtt type failed"); + goto got_exception; + } + + SYNC_ALL_TO_FRAME(); + struct_obj = wasm_struct_obj_new(exec_env, rtt_type); + if (!struct_obj) { + wasm_set_exception(module, + "create struct object failed"); + goto got_exception; + } + + if (opcode == WASM_OP_STRUCT_NEW) { + WASMStructFieldType *fields = struct_type->fields; + int32 field_count = (int32)struct_type->field_count; + int32 field_idx; + uint8 field_type; + + for (field_idx = field_count - 1; field_idx >= 0; + field_idx--) { + field_type = fields[field_idx].field_type; + if (wasm_is_type_reftype(field_type)) { + field_value.gc_obj = POP_REF(); + } + else if (field_type == VALUE_TYPE_I32 + || field_type == VALUE_TYPE_F32 + || field_type == PACKED_TYPE_I8 + || field_type == PACKED_TYPE_I16) { + field_value.i32 = POP_I32(); + } + else { + field_value.i64 = POP_I64(); + } + wasm_struct_obj_set_field(struct_obj, field_idx, + &field_value); + } + } + PUSH_REF(struct_obj); + HANDLE_OP_END(); + } + case WASM_OP_STRUCT_GET: + case WASM_OP_STRUCT_GET_S: + case WASM_OP_STRUCT_GET_U: + { + WASMStructType *struct_type; + WASMValue field_value = { 0 }; + uint32 field_idx; + uint8 field_type; + + read_leb_uint32(frame_ip, frame_ip_end, type_index); + read_leb_uint32(frame_ip, frame_ip_end, field_idx); + struct_type = + (WASMStructType *)module->module->types[type_index]; + + struct_obj = POP_REF(); + + if (!struct_obj) { + wasm_set_exception(module, "null structure object"); + goto got_exception; + } + + wasm_struct_obj_get_field( + struct_obj, field_idx, + opcode == WASM_OP_STRUCT_GET_S ? true : false, + &field_value); + + field_type = struct_type->fields[field_idx].field_type; + if (wasm_is_reftype_i31ref(field_type)) { + PUSH_I31REF(field_value.gc_obj); + } + else if (wasm_is_type_reftype(field_type)) { + PUSH_REF(field_value.gc_obj); + } + else if (field_type == VALUE_TYPE_I32 + || field_type == VALUE_TYPE_F32 + || field_type == PACKED_TYPE_I8 + || field_type == PACKED_TYPE_I16) { + PUSH_I32(field_value.i32); + } + else { + PUSH_I64(field_value.i64); + } + HANDLE_OP_END(); + } + case WASM_OP_STRUCT_SET: + { + WASMStructType *struct_type; + WASMValue field_value = { 0 }; + uint32 field_idx; + uint8 field_type; + + read_leb_uint32(frame_ip, frame_ip_end, type_index); + read_leb_uint32(frame_ip, frame_ip_end, field_idx); + + struct_type = + (WASMStructType *)module->module->types[type_index]; + field_type = struct_type->fields[field_idx].field_type; + + if (wasm_is_type_reftype(field_type)) { + field_value.gc_obj = POP_REF(); + } + else if (field_type == VALUE_TYPE_I32 + || field_type == VALUE_TYPE_F32 + || field_type == PACKED_TYPE_I8 + || field_type == PACKED_TYPE_I16) { + field_value.i32 = POP_I32(); + } + else { + field_value.i64 = POP_I64(); + } + + struct_obj = POP_REF(); + if (!struct_obj) { + wasm_set_exception(module, "null structure object"); + goto got_exception; + } + + wasm_struct_obj_set_field(struct_obj, field_idx, + &field_value); + HANDLE_OP_END(); + } + + case WASM_OP_ARRAY_NEW: + case WASM_OP_ARRAY_NEW_DEFAULT: + case WASM_OP_ARRAY_NEW_FIXED: + { + WASMModule *wasm_module = module->module; + WASMArrayType *array_type; + WASMRttType *rtt_type; + WASMValue array_elem = { 0 }; + uint32 array_len; + + read_leb_uint32(frame_ip, frame_ip_end, type_index); + array_type = + (WASMArrayType *)wasm_module->types[type_index]; + + if (!(rtt_type = wasm_rtt_type_new( + (WASMType *)array_type, type_index, + wasm_module->rtt_types, + wasm_module->type_count, + &wasm_module->rtt_type_lock))) { + wasm_set_exception(module, + "create rtt type failed"); + goto got_exception; + } + + if (opcode != WASM_OP_ARRAY_NEW_FIXED) + array_len = POP_I32(); + else + read_leb_uint32(frame_ip, frame_ip_end, array_len); + + if (opcode == WASM_OP_ARRAY_NEW) { + if (wasm_is_type_reftype(array_type->elem_type)) { + array_elem.gc_obj = POP_REF(); + } + else if (array_type->elem_type == VALUE_TYPE_I32 + || array_type->elem_type == VALUE_TYPE_F32 + || array_type->elem_type == PACKED_TYPE_I8 + || array_type->elem_type + == PACKED_TYPE_I16) { + array_elem.i32 = POP_I32(); + } + else { + array_elem.i64 = POP_I64(); + } + } + + SYNC_ALL_TO_FRAME(); + array_obj = wasm_array_obj_new(exec_env, rtt_type, + array_len, &array_elem); + if (!array_obj) { + wasm_set_exception(module, + "create array object failed"); + goto got_exception; + } + + if (opcode == WASM_OP_ARRAY_NEW_FIXED) { + for (i = 0; i < array_len; i++) { + if (wasm_is_type_reftype( + array_type->elem_type)) { + array_elem.gc_obj = POP_REF(); + } + else if (array_type->elem_type == VALUE_TYPE_I32 + || array_type->elem_type + == VALUE_TYPE_F32 + || array_type->elem_type + == PACKED_TYPE_I8 + || array_type->elem_type + == PACKED_TYPE_I16) { + array_elem.i32 = POP_I32(); + } + else { + array_elem.i64 = POP_I64(); + } + wasm_array_obj_set_elem( + array_obj, array_len - 1 - i, &array_elem); + } + } + + PUSH_REF(array_obj); + HANDLE_OP_END(); + } + case WASM_OP_ARRAY_NEW_DATA: + { + WASMModule *wasm_module = module->module; + WASMArrayType *array_type; + WASMRttType *rtt_type; + WASMValue array_elem = { 0 }; + WASMDataSeg *data_seg; + uint8 *array_elem_base; + uint32 array_len, data_seg_idx, data_seg_offset; + uint32 elem_size = 0; + uint64 total_size; + + read_leb_uint32(frame_ip, frame_ip_end, type_index); + read_leb_uint32(frame_ip, frame_ip_end, data_seg_idx); + data_seg = wasm_module->data_segments[data_seg_idx]; + + array_type = + (WASMArrayType *)wasm_module->types[type_index]; + + if (!(rtt_type = wasm_rtt_type_new( + (WASMType *)array_type, type_index, + wasm_module->rtt_types, + wasm_module->type_count, + &wasm_module->rtt_type_lock))) { + wasm_set_exception(module, + "create rtt type failed"); + goto got_exception; + } + + array_len = POP_I32(); + data_seg_offset = POP_I32(); + + switch (array_type->elem_type) { + case PACKED_TYPE_I8: + elem_size = 1; + break; + case PACKED_TYPE_I16: + elem_size = 2; + break; + case VALUE_TYPE_I32: + case VALUE_TYPE_F32: + elem_size = 4; + break; + case VALUE_TYPE_I64: + case VALUE_TYPE_F64: + elem_size = 8; + break; + default: + bh_assert(0); + } + + total_size = (uint64)elem_size * array_len; + if (data_seg_offset >= data_seg->data_length + || total_size + > data_seg->data_length - data_seg_offset) { + wasm_set_exception(module, + "data segment out of bounds"); + goto got_exception; + } + + SYNC_ALL_TO_FRAME(); + array_obj = wasm_array_obj_new(exec_env, rtt_type, + array_len, &array_elem); + if (!array_obj) { + wasm_set_exception(module, + "create array object failed"); + goto got_exception; + } + + array_elem_base = + (uint8 *)wasm_array_obj_first_elem_addr(array_obj); + bh_memcpy_s(array_elem_base, (uint32)total_size, + data_seg->data + data_seg_offset, + (uint32)total_size); + + PUSH_REF(array_obj); + HANDLE_OP_END(); + } + case WASM_OP_ARRAY_NEW_ELEM: + { + /* TODO */ + wasm_set_exception(module, "unsupported opcode"); + goto got_exception; + } + case WASM_OP_ARRAY_GET: + case WASM_OP_ARRAY_GET_S: + case WASM_OP_ARRAY_GET_U: + { + WASMArrayType *array_type; + WASMValue array_elem = { 0 }; + uint32 elem_idx, elem_size_log; + + read_leb_uint32(frame_ip, frame_ip_end, type_index); + array_type = + (WASMArrayType *)module->module->types[type_index]; + + elem_idx = POP_I32(); + array_obj = POP_REF(); + + if (!array_obj) { + wasm_set_exception(module, "null array reference"); + goto got_exception; + } + if (elem_idx >= wasm_array_obj_length(array_obj)) { + wasm_set_exception(module, + "out of bounds array access"); + goto got_exception; + } + + wasm_array_obj_get_elem( + array_obj, elem_idx, + opcode == WASM_OP_ARRAY_GET_S ? true : false, + &array_elem); + elem_size_log = wasm_array_obj_elem_size_log(array_obj); + + if (wasm_is_reftype_i31ref(array_type->elem_type)) { + PUSH_I31REF(array_elem.gc_obj); + } + else if (wasm_is_type_reftype(array_type->elem_type)) { + PUSH_REF(array_elem.gc_obj); + } + else if (elem_size_log < 3) { + PUSH_I32(array_elem.i32); + } + else { + PUSH_I64(array_elem.i64); + } + HANDLE_OP_END(); + } + case WASM_OP_ARRAY_SET: + { + WASMArrayType *array_type; + WASMValue array_elem = { 0 }; + uint32 elem_idx; + + read_leb_uint32(frame_ip, frame_ip_end, type_index); + array_type = + (WASMArrayType *)module->module->types[type_index]; + if (wasm_is_type_reftype(array_type->elem_type)) { + array_elem.gc_obj = POP_REF(); + } + else if (array_type->elem_type == VALUE_TYPE_I32 + || array_type->elem_type == VALUE_TYPE_F32 + || array_type->elem_type == PACKED_TYPE_I8 + || array_type->elem_type == PACKED_TYPE_I16) { + array_elem.i32 = POP_I32(); + } + else { + array_elem.i64 = POP_I64(); + } + + elem_idx = POP_I32(); + array_obj = POP_REF(); + + if (!array_obj) { + wasm_set_exception(module, "null array reference"); + goto got_exception; + } + if (elem_idx >= wasm_array_obj_length(array_obj)) { + wasm_set_exception(module, + "out of bounds array access"); + goto got_exception; + } + + wasm_array_obj_set_elem(array_obj, elem_idx, + &array_elem); + HANDLE_OP_END(); + } + case WASM_OP_ARRAY_LEN: + { + uint32 array_len; + + array_obj = POP_REF(); + if (!array_obj) { + wasm_set_exception(module, "null array reference"); + goto got_exception; + } + array_len = wasm_array_obj_length(array_obj); + PUSH_I32(array_len); + HANDLE_OP_END(); + } + case WASM_OP_ARRAY_FILL: + { + WASMArrayType *array_type; + WASMValue fill_value = { 0 }; + uint32 start_offset, len; + read_leb_uint32(frame_ip, frame_ip_end, type_index); + + array_type = + (WASMArrayType *)module->module->types[type_index]; + + len = POP_I32(); + if (wasm_is_type_reftype(array_type->elem_type)) { + fill_value.gc_obj = POP_REF(); + } + else if (array_type->elem_type == VALUE_TYPE_I32 + || array_type->elem_type == VALUE_TYPE_F32 + || array_type->elem_type == PACKED_TYPE_I8 + || array_type->elem_type == PACKED_TYPE_I16) { + fill_value.i32 = POP_I32(); + } + else { + fill_value.i64 = POP_I64(); + } + start_offset = POP_I32(); + array_obj = POP_REF(); + + if (!array_obj) { + wasm_set_exception(module, "null array reference"); + goto got_exception; + } + + if (len > 0) { + if ((uint64)start_offset + len + >= wasm_array_obj_length(array_obj)) { + wasm_set_exception( + module, "out of bounds array access"); + goto got_exception; + } + + wasm_array_obj_fill(array_obj, start_offset, len, + &fill_value); + } + + HANDLE_OP_END(); + } + case WASM_OP_ARRAY_COPY: + { + uint32 dst_offset, src_offset, len, src_type_index; + WASMArrayObjectRef src_obj, dst_obj; + + read_leb_uint32(frame_ip, frame_ip_end, type_index); + read_leb_uint32(frame_ip, frame_ip_end, src_type_index); + + len = POP_I32(); + src_offset = POP_I32(); + src_obj = POP_REF(); + dst_offset = POP_I32(); + dst_obj = POP_REF(); + + if (!src_obj || !dst_obj) { + wasm_set_exception(module, "null array reference"); + goto got_exception; + } + + if (len > 0) { + if ((dst_offset > UINT32_MAX - len) + || (dst_offset + len + > wasm_array_obj_length(dst_obj)) + || (src_offset > UINT32_MAX - len) + || (src_offset + len + > wasm_array_obj_length(src_obj))) { + wasm_set_exception( + module, "out of bounds array access"); + goto got_exception; + } + + wasm_array_obj_copy(dst_obj, dst_offset, src_obj, + src_offset, len); + } + + (void)src_type_index; + HANDLE_OP_END(); + } + + case WASM_OP_REF_I31: + { + uint32 i31_val; + + i31_val = POP_I32(); + i31_obj = wasm_i31_obj_new(i31_val); + PUSH_I31REF(i31_obj); + HANDLE_OP_END(); + } + case WASM_OP_I31_GET_S: + case WASM_OP_I31_GET_U: + { + uint32 i31_val; + + i31_obj = (WASMI31ObjectRef)POP_REF(); + if (!i31_obj) { + wasm_set_exception(module, "null i31 reference"); + goto got_exception; + } + i31_val = (uint32)(((uintptr_t)i31_obj) >> 1); + if (opcode == WASM_OP_I31_GET_S + && (i31_val & 0x40000000) /* bit 30 is 1 */) + /* set bit 31 to 1 */ + i31_val |= 0x80000000; + PUSH_I32(i31_val); + HANDLE_OP_END(); + } + + case WASM_OP_REF_TEST: + case WASM_OP_REF_CAST: + case WASM_OP_REF_TEST_NULLABLE: + case WASM_OP_REF_CAST_NULLABLE: + { + int32 heap_type; + + read_leb_int32(frame_ip, frame_ip_end, heap_type); + + gc_obj = GET_REF_FROM_ADDR(frame_sp - REF_CELL_NUM); + if (!gc_obj) { + if (opcode == WASM_OP_REF_TEST + || opcode == WASM_OP_REF_TEST_NULLABLE) { + (void)POP_REF(); + if (opcode == WASM_OP_REF_TEST) + PUSH_I32(0); + else + PUSH_I32(1); + } + else if (opcode == WASM_OP_REF_CAST) { + wasm_set_exception(module, "cast failure"); + goto got_exception; + } + else { + /* Do nothing for WASM_OP_REF_CAST_NULLABLE */ + } + } + else { + bool castable = false; + + if (heap_type >= 0) { + WASMModule *wasm_module = module->module; + castable = wasm_obj_is_instance_of( + gc_obj, (uint32)heap_type, + wasm_module->types, + wasm_module->type_count); + } + else { + castable = + wasm_obj_is_type_of(gc_obj, heap_type); + } + + if (opcode == WASM_OP_REF_TEST + || opcode == WASM_OP_REF_TEST_NULLABLE) { + (void)POP_REF(); + if (castable) + PUSH_I32(1); + else + PUSH_I32(0); + } + else if (!castable) { + wasm_set_exception(module, "cast failure"); + goto got_exception; + } + } + HANDLE_OP_END(); + } + + case WASM_OP_BR_ON_CAST: + case WASM_OP_BR_ON_CAST_FAIL: + { + int32 heap_type, heap_type_dst; + uint8 castflags; + +#if WASM_ENABLE_THREAD_MGR != 0 + CHECK_SUSPEND_FLAGS(); +#endif + castflags = *frame_ip++; + read_leb_uint32(frame_ip, frame_ip_end, depth); + read_leb_int32(frame_ip, frame_ip_end, heap_type); + read_leb_int32(frame_ip, frame_ip_end, heap_type_dst); + + gc_obj = GET_REF_FROM_ADDR(frame_sp - REF_CELL_NUM); + if (!gc_obj) { + /* + * castflags should be 0~3: + * 0: (non-null, non-null) + * 1: (null, non-null) + * 2: (non-null, null) + * 3: (null, null) + */ + if ( + /* op is BR_ON_CAST and dst reftype is nullable + */ + ((opcode1 == WASM_OP_BR_ON_CAST) + && ((castflags == 2) || (castflags == 3))) + /* op is BR_ON_CAST_FAIL and dst reftype is + non-nullable */ + || ((opcode1 == WASM_OP_BR_ON_CAST_FAIL) + && ((castflags == 0) || (castflags == 1)))) + goto label_pop_csp_n; + } + else { + bool castable = false; + + if (heap_type_dst >= 0) { + WASMModule *wasm_module = module->module; + castable = wasm_obj_is_instance_of( + gc_obj, (uint32)heap_type_dst, + wasm_module->types, + wasm_module->type_count); + } + else { + castable = + wasm_obj_is_type_of(gc_obj, heap_type_dst); + } + + if ((castable && (opcode == WASM_OP_BR_ON_CAST)) + || (!castable + && (opcode == WASM_OP_BR_ON_CAST_FAIL))) { + goto label_pop_csp_n; + } + } + + (void)heap_type; + HANDLE_OP_END(); + } + + case WASM_OP_ANY_CONVERT_EXTERN: + { + externref_obj = POP_REF(); + if (externref_obj == NULL_REF) + PUSH_REF(NULL_REF); + else { + gc_obj = wasm_externref_obj_to_internal_obj( + externref_obj); + PUSH_REF(gc_obj); + } + HANDLE_OP_END(); + } + case WASM_OP_EXTERN_CONVERT_ANY: + { + gc_obj = POP_REF(); + if (gc_obj == NULL_REF) + PUSH_REF(NULL_REF); + else { + if (!(externref_obj = + wasm_internal_obj_to_externref_obj( + exec_env, gc_obj))) { + wasm_set_exception( + module, "create externref object failed"); + goto got_exception; + } + PUSH_REF(externref_obj); + } + HANDLE_OP_END(); + } + +#if WASM_ENABLE_STRINGREF != 0 + case WASM_OP_STRING_NEW_UTF8: + case WASM_OP_STRING_NEW_WTF16: + case WASM_OP_STRING_NEW_LOSSY_UTF8: + case WASM_OP_STRING_NEW_WTF8: + { + uint32 mem_idx, addr, bytes_length, offset = 0; + EncodingFlag flag = WTF8; + + read_leb_uint32(frame_ip, frame_ip_end, mem_idx); + bytes_length = POP_I32(); + addr = POP_I32(); + + CHECK_MEMORY_OVERFLOW(bytes_length); + + if (opcode == WASM_OP_STRING_NEW_WTF16) { + flag = WTF16; + } + else if (opcode == WASM_OP_STRING_NEW_UTF8) { + flag = UTF8; + } + else if (opcode == WASM_OP_STRING_NEW_LOSSY_UTF8) { + flag = LOSSY_UTF8; + } + else if (opcode == WASM_OP_STRING_NEW_WTF8) { + flag = WTF8; + } + + str_obj = wasm_string_new_with_encoding( + maddr, bytes_length, flag); + if (!str_obj) { + wasm_set_exception(module, + "create string object failed"); + goto got_exception; + } + + SYNC_ALL_TO_FRAME(); + stringref_obj = + wasm_stringref_obj_new(exec_env, str_obj); + if (!stringref_obj) { + wasm_set_exception(module, + "create stringref failed"); + goto got_exception; + } + + PUSH_REF(stringref_obj); + + (void)mem_idx; + HANDLE_OP_END(); + } + case WASM_OP_STRING_CONST: + { + WASMModule *wasm_module = module->module; + uint32 contents; + + read_leb_uint32(frame_ip, frame_ip_end, contents); + + str_obj = wasm_string_new_const( + (const char *) + wasm_module->string_literal_ptrs[contents], + wasm_module->string_literal_lengths[contents]); + if (!str_obj) { + wasm_set_exception(module, + "create string object failed"); + goto got_exception; + } + + SYNC_ALL_TO_FRAME(); + stringref_obj = + wasm_stringref_obj_new(exec_env, str_obj); + if (!stringref_obj) { + wasm_set_exception(module, + "create stringref failed"); + goto got_exception; + } + + PUSH_REF(stringref_obj); + HANDLE_OP_END(); + } + case WASM_OP_STRING_MEASURE_UTF8: + case WASM_OP_STRING_MEASURE_WTF8: + case WASM_OP_STRING_MEASURE_WTF16: + { + int32 target_bytes_length; + EncodingFlag flag = WTF8; + + stringref_obj = POP_REF(); + + if (opcode == WASM_OP_STRING_MEASURE_WTF16) { + flag = WTF16; + } + else if (opcode == WASM_OP_STRING_MEASURE_UTF8) { + flag = UTF8; + } + else if (opcode == WASM_OP_STRING_MEASURE_WTF8) { + flag = LOSSY_UTF8; + } + target_bytes_length = wasm_string_measure( + (WASMString)wasm_stringref_obj_get_value( + stringref_obj), + flag); + + PUSH_I32(target_bytes_length); + HANDLE_OP_END(); + } + case WASM_OP_STRING_ENCODE_UTF8: + case WASM_OP_STRING_ENCODE_WTF16: + case WASM_OP_STRING_ENCODE_LOSSY_UTF8: + case WASM_OP_STRING_ENCODE_WTF8: + { + uint32 mem_idx, addr; + int32 target_bytes_length; + WASMMemoryInstance *memory_inst; + EncodingFlag flag = WTF8; + + read_leb_uint32(frame_ip, frame_ip_end, mem_idx); + addr = POP_I32(); + stringref_obj = POP_REF(); + + str_obj = (WASMString)wasm_stringref_obj_get_value( + stringref_obj); + + memory_inst = module->memories[mem_idx]; + maddr = memory_inst->memory_data + addr; + + if (opcode == WASM_OP_STRING_ENCODE_WTF16) { + flag = WTF16; + count = wasm_string_measure(str_obj, flag); + target_bytes_length = wasm_string_encode( + str_obj, 0, count, maddr, NULL, flag); + } + else { + if (opcode == WASM_OP_STRING_ENCODE_UTF8) { + flag = UTF8; + } + else if (opcode + == WASM_OP_STRING_ENCODE_LOSSY_UTF8) { + flag = LOSSY_UTF8; + } + else if (opcode == WASM_OP_STRING_ENCODE_WTF8) { + flag = WTF8; + } + count = wasm_string_measure(str_obj, flag); + target_bytes_length = wasm_string_encode( + str_obj, 0, count, maddr, NULL, flag); + + if (target_bytes_length == -1) { + wasm_set_exception( + module, "isolated surrogate is seen"); + goto got_exception; + } + } + if (target_bytes_length < 0) { + wasm_set_exception(module, + "stringref encode failed"); + goto got_exception; + } + + PUSH_I32(target_bytes_length); + HANDLE_OP_END(); + } + case WASM_OP_STRING_CONCAT: + { + WASMStringrefObjectRef stringref_obj1, stringref_obj2; + + stringref_obj2 = POP_REF(); + stringref_obj1 = POP_REF(); + + str_obj = wasm_string_concat( + (WASMString)wasm_stringref_obj_get_value( + stringref_obj1), + (WASMString)wasm_stringref_obj_get_value( + stringref_obj2)); + if (!str_obj) { + wasm_set_exception(module, + "create string object failed"); + goto got_exception; + } + + SYNC_ALL_TO_FRAME(); + stringref_obj = + wasm_stringref_obj_new(exec_env, str_obj); + if (!stringref_obj) { + wasm_set_exception(module, + "create stringref failed"); + goto got_exception; + } + + PUSH_REF(stringref_obj); + HANDLE_OP_END(); + } + case WASM_OP_STRING_EQ: + { + WASMStringrefObjectRef stringref_obj1, stringref_obj2; + int32 is_eq; + + stringref_obj2 = POP_REF(); + stringref_obj1 = POP_REF(); + + is_eq = wasm_string_eq( + (WASMString)wasm_stringref_obj_get_value( + stringref_obj1), + (WASMString)wasm_stringref_obj_get_value( + stringref_obj2)); + + PUSH_I32(is_eq); + HANDLE_OP_END(); + } + case WASM_OP_STRING_IS_USV_SEQUENCE: + { + int32 is_usv_sequence; + + stringref_obj = POP_REF(); + + is_usv_sequence = wasm_string_is_usv_sequence( + (WASMString)wasm_stringref_obj_get_value( + stringref_obj)); + + PUSH_I32(is_usv_sequence); + HANDLE_OP_END(); + } + case WASM_OP_STRING_AS_WTF8: + { + stringref_obj = POP_REF(); + + str_obj = wasm_string_create_view( + (WASMString)wasm_stringref_obj_get_value( + stringref_obj), + STRING_VIEW_WTF8); + if (!str_obj) { + wasm_set_exception(module, + "create string object failed"); + goto got_exception; + } + + SYNC_ALL_TO_FRAME(); + stringview_wtf8_obj = + wasm_stringview_wtf8_obj_new(exec_env, str_obj); + if (!stringview_wtf8_obj) { + wasm_set_exception(module, + "create stringview wtf8 failed"); + goto got_exception; + } + + PUSH_REF(stringview_wtf8_obj); + HANDLE_OP_END(); + } + case WASM_OP_STRINGVIEW_WTF8_ADVANCE: + { + uint32 next_pos, bytes, pos; + + bytes = POP_I32(); + pos = POP_I32(); + stringview_wtf8_obj = POP_REF(); + + next_pos = wasm_string_advance( + (WASMString)wasm_stringview_wtf8_obj_get_value( + stringview_wtf8_obj), + pos, bytes, NULL); + + PUSH_I32(next_pos); + HANDLE_OP_END(); + } + case WASM_OP_STRINGVIEW_WTF8_ENCODE_UTF8: + case WASM_OP_STRINGVIEW_WTF8_ENCODE_LOSSY_UTF8: + case WASM_OP_STRINGVIEW_WTF8_ENCODE_WTF8: + { + uint32 mem_idx, addr, pos, bytes, next_pos; + int32 bytes_written; + WASMMemoryInstance *memory_inst; + EncodingFlag flag = WTF8; + + if (opcode == WASM_OP_STRINGVIEW_WTF8_ENCODE_UTF8) { + flag = UTF8; + } + else if (opcode + == WASM_OP_STRINGVIEW_WTF8_ENCODE_LOSSY_UTF8) { + flag = LOSSY_UTF8; + } + else if (opcode + == WASM_OP_STRINGVIEW_WTF8_ENCODE_WTF8) { + flag = WTF8; + } + + read_leb_uint32(frame_ip, frame_ip_end, mem_idx); + bytes = POP_I32(); + pos = POP_I32(); + addr = POP_I32(); + stringview_wtf8_obj = POP_REF(); + + memory_inst = module->memories[mem_idx]; + maddr = memory_inst->memory_data + addr; + + bytes_written = wasm_string_encode( + (WASMString)wasm_stringview_wtf8_obj_get_value( + stringview_wtf8_obj), + pos, bytes, maddr, &next_pos, flag); + + if (bytes_written < 0) { + if (bytes_written == Isolated_Surrogate) { + wasm_set_exception( + module, "isolated surrogate is seen"); + } + else { + wasm_set_exception(module, "encode failed"); + } + + goto got_exception; + } + + PUSH_I32(next_pos); + PUSH_I32(bytes_written); + HANDLE_OP_END(); + } + case WASM_OP_STRINGVIEW_WTF8_SLICE: + { + uint32 start, end; + + end = POP_I32(); + start = POP_I32(); + stringview_wtf8_obj = POP_REF(); + + str_obj = wasm_string_slice( + (WASMString)wasm_stringview_wtf8_obj_get_value( + stringview_wtf8_obj), + start, end, STRING_VIEW_WTF8); + if (!str_obj) { + wasm_set_exception(module, + "create string object failed"); + goto got_exception; + } + + SYNC_ALL_TO_FRAME(); + stringref_obj = + wasm_stringref_obj_new(exec_env, str_obj); + if (!stringref_obj) { + wasm_set_exception(module, + "create stringref failed"); + goto got_exception; + } + + PUSH_REF(stringref_obj); + HANDLE_OP_END(); + } + case WASM_OP_STRING_AS_WTF16: + { + stringref_obj = POP_REF(); + + str_obj = wasm_string_create_view( + (WASMString)wasm_stringref_obj_get_value( + stringref_obj), + STRING_VIEW_WTF16); + if (!str_obj) { + wasm_set_exception(module, + "create string object failed"); + goto got_exception; + } + + SYNC_ALL_TO_FRAME(); + stringview_wtf16_obj = + wasm_stringview_wtf16_obj_new(exec_env, str_obj); + if (!stringview_wtf16_obj) { + wasm_set_exception( + module, "create stringview wtf16 failed"); + goto got_exception; + } + + PUSH_REF(stringview_wtf16_obj); + HANDLE_OP_END(); + } + case WASM_OP_STRINGVIEW_WTF16_LENGTH: + { + int32 code_units_length; + + stringview_wtf16_obj = POP_REF(); + + code_units_length = wasm_string_wtf16_get_length( + (WASMString)wasm_stringview_wtf16_obj_get_value( + stringview_wtf16_obj)); + + PUSH_I32(code_units_length); + HANDLE_OP_END(); + } + case WASM_OP_STRINGVIEW_WTF16_GET_CODEUNIT: + { + int32 pos; + uint32 code_unit; + + pos = POP_I32(); + stringview_wtf16_obj = POP_REF(); + + code_unit = (uint32)wasm_string_get_wtf16_codeunit( + (WASMString)wasm_stringview_wtf16_obj_get_value( + stringview_wtf16_obj), + pos); + + PUSH_I32(code_unit); + HANDLE_OP_END(); + } + case WASM_OP_STRINGVIEW_WTF16_ENCODE: + { + uint32 mem_idx, addr, pos, len, offset = 0; + int32 written_code_units = 0; + + read_leb_uint32(frame_ip, frame_ip_end, mem_idx); + len = POP_I32(); + pos = POP_I32(); + addr = POP_I32(); + stringview_wtf16_obj = POP_REF(); + + CHECK_MEMORY_OVERFLOW(len * sizeof(uint16)); + + /* check 2-byte alignment */ + if (((uintptr_t)maddr & (((uintptr_t)1 << 2) - 1)) + != 0) { + wasm_set_exception(module, + "unaligned memory access"); + goto got_exception; + } + + written_code_units = wasm_string_encode( + (WASMString)wasm_stringview_wtf16_obj_get_value( + stringview_wtf16_obj), + pos, len, maddr, NULL, WTF16); + if (written_code_units < 0) { + wasm_set_exception(module, "encode failed"); + goto got_exception; + } + + PUSH_I32(written_code_units); + (void)mem_idx; + HANDLE_OP_END(); + } + case WASM_OP_STRINGVIEW_WTF16_SLICE: + { + uint32 start, end; + + end = POP_I32(); + start = POP_I32(); + stringview_wtf16_obj = POP_REF(); + + str_obj = wasm_string_slice( + (WASMString)wasm_stringview_wtf16_obj_get_value( + stringview_wtf16_obj), + start, end, STRING_VIEW_WTF16); + if (!str_obj) { + wasm_set_exception(module, + "create string object failed"); + goto got_exception; + } + + SYNC_ALL_TO_FRAME(); + stringref_obj = + wasm_stringref_obj_new(exec_env, str_obj); + if (!stringref_obj) { + wasm_set_exception(module, + "create stringref failed"); + goto got_exception; + } + + PUSH_REF(stringref_obj); + HANDLE_OP_END(); + } + case WASM_OP_STRING_AS_ITER: + { + stringref_obj = POP_REF(); + + str_obj = wasm_string_create_view( + (WASMString)wasm_stringref_obj_get_value( + stringref_obj), + STRING_VIEW_ITER); + + if (!str_obj) { + wasm_set_exception(module, + "create string object failed"); + goto got_exception; + } + + SYNC_ALL_TO_FRAME(); + stringview_iter_obj = + wasm_stringview_iter_obj_new(exec_env, str_obj, 0); + if (!stringview_iter_obj) { + wasm_set_exception(module, + "create stringview iter failed"); + goto got_exception; + } + + PUSH_REF(stringview_iter_obj); + HANDLE_OP_END(); + } + case WASM_OP_STRINGVIEW_ITER_NEXT: + { + uint32 code_point; + + stringview_iter_obj = POP_REF(); + + code_point = wasm_string_next_codepoint( + (WASMString)wasm_stringview_iter_obj_get_value( + stringview_iter_obj), + wasm_stringview_iter_obj_get_pos( + stringview_iter_obj)); + + PUSH_I32(code_point); + HANDLE_OP_END(); + } + case WASM_OP_STRINGVIEW_ITER_ADVANCE: + case WASM_OP_STRINGVIEW_ITER_REWIND: + { + uint32 code_points_count, code_points_consumed = 0, + cur_pos, next_pos = 0; + + code_points_count = POP_I32(); + stringview_iter_obj = POP_REF(); + + str_obj = + (WASMString)wasm_stringview_iter_obj_get_value( + stringview_iter_obj); + cur_pos = wasm_stringview_iter_obj_get_pos( + stringview_iter_obj); + + if (opcode == WASM_OP_STRINGVIEW_ITER_ADVANCE) { + next_pos = wasm_string_advance( + str_obj, cur_pos, code_points_count, + &code_points_consumed); + } + else if (opcode == WASM_OP_STRINGVIEW_ITER_REWIND) { + next_pos = wasm_string_rewind( + str_obj, cur_pos, code_points_count, + &code_points_consumed); + } + + wasm_stringview_iter_obj_update_pos(stringview_iter_obj, + next_pos); + + PUSH_I32(code_points_consumed); + HANDLE_OP_END(); + } + case WASM_OP_STRINGVIEW_ITER_SLICE: + { + uint32 code_points_count, cur_pos; + + code_points_count = POP_I32(); + stringview_iter_obj = POP_REF(); + + cur_pos = wasm_stringview_iter_obj_get_pos( + stringview_iter_obj); + + str_obj = wasm_string_slice( + (WASMString)wasm_stringview_iter_obj_get_value( + stringview_iter_obj), + cur_pos, cur_pos + code_points_count, + STRING_VIEW_ITER); + if (!str_obj) { + wasm_set_exception(module, + "create string object failed"); + goto got_exception; + } + + SYNC_ALL_TO_FRAME(); + stringref_obj = + wasm_stringref_obj_new(exec_env, str_obj); + if (!stringref_obj) { + wasm_set_exception(module, + "create stringref failed"); + goto got_exception; + } + + PUSH_REF(stringref_obj); + HANDLE_OP_END(); + } + case WASM_OP_STRING_NEW_UTF8_ARRAY: + case WASM_OP_STRING_NEW_WTF16_ARRAY: + case WASM_OP_STRING_NEW_LOSSY_UTF8_ARRAY: + case WASM_OP_STRING_NEW_WTF8_ARRAY: + { + uint32 start, end, array_len; + EncodingFlag flag = WTF8; + WASMArrayType *array_type; + void *arr_start_addr; + + end = POP_I32(); + start = POP_I32(); + array_obj = POP_REF(); + + array_type = (WASMArrayType *)wasm_obj_get_defined_type( + (WASMObjectRef)array_obj); + arr_start_addr = + wasm_array_obj_elem_addr(array_obj, start); + array_len = wasm_array_obj_length(array_obj); + + if (start > end || end > array_len) { + wasm_set_exception(module, + "out of bounds array access"); + goto got_exception; + } + + if (opcode == WASM_OP_STRING_NEW_WTF16_ARRAY) { + if (array_type->elem_type != VALUE_TYPE_I16) { + wasm_set_exception(module, + "array type mismatch"); + goto got_exception; + } + flag = WTF16; + } + else { + if (array_type->elem_type != VALUE_TYPE_I8) { + wasm_set_exception(module, + "array type mismatch"); + goto got_exception; + } + if (opcode == WASM_OP_STRING_NEW_UTF8_ARRAY) { + flag = UTF8; + } + else if (opcode == WASM_OP_STRING_NEW_WTF8_ARRAY) { + flag = WTF8; + } + else if (opcode + == WASM_OP_STRING_NEW_LOSSY_UTF8_ARRAY) { + flag = LOSSY_UTF8; + } + } + + str_obj = wasm_string_new_with_encoding( + arr_start_addr, (end - start), flag); + if (!str_obj) { + wasm_set_exception(module, + "create string object failed"); + goto got_exception; + } + + SYNC_ALL_TO_FRAME(); + stringref_obj = + wasm_stringref_obj_new(exec_env, str_obj); + if (!stringref_obj) { + wasm_set_exception(module, + "create stringref failed"); + goto got_exception; + } + + PUSH_REF(stringref_obj); + HANDLE_OP_END(); + } + case WASM_OP_STRING_ENCODE_UTF8_ARRAY: + case WASM_OP_STRING_ENCODE_WTF16_ARRAY: + case WASM_OP_STRING_ENCODE_LOSSY_UTF8_ARRAY: + case WASM_OP_STRING_ENCODE_WTF8_ARRAY: + { + uint32 start, array_len, count; + int32 bytes_written; + EncodingFlag flag = WTF8; + WASMArrayType *array_type; + void *arr_start_addr; + + start = POP_I32(); + array_obj = POP_REF(); + stringref_obj = POP_REF(); + + str_obj = (WASMString)wasm_stringref_obj_get_value( + stringref_obj); + + array_type = (WASMArrayType *)wasm_obj_get_defined_type( + (WASMObjectRef)array_obj); + arr_start_addr = + wasm_array_obj_elem_addr(array_obj, start); + array_len = wasm_array_obj_length(array_obj); + + if (start > array_len) { + wasm_set_exception(module, + "out of bounds array access"); + goto got_exception; + } + + if (opcode == WASM_OP_STRING_ENCODE_WTF16_ARRAY) { + if (array_type->elem_type != VALUE_TYPE_I16) { + wasm_set_exception(module, + "array type mismatch"); + goto got_exception; + } + flag = WTF16; + } + else { + if (array_type->elem_type != VALUE_TYPE_I8) { + wasm_set_exception(module, + "array type mismatch"); + goto got_exception; + } + if (opcode == WASM_OP_STRING_ENCODE_UTF8_ARRAY) { + flag = UTF8; + } + else if (opcode + == WASM_OP_STRING_ENCODE_WTF8_ARRAY) { + flag = WTF8; + } + else if ( + opcode + == WASM_OP_STRING_ENCODE_LOSSY_UTF8_ARRAY) { + flag = LOSSY_UTF8; + } + } + + count = wasm_string_measure(str_obj, flag); + + bytes_written = wasm_string_encode( + str_obj, 0, count, arr_start_addr, NULL, flag); + + if (bytes_written < 0) { + if (bytes_written == Isolated_Surrogate) { + wasm_set_exception( + module, "isolated surrogate is seen"); + } + else if (bytes_written == Insufficient_Space) { + wasm_set_exception( + module, "array space is insufficient"); + } + else { + wasm_set_exception(module, "encode failed"); + } + + goto got_exception; + } + + PUSH_I32(bytes_written); + HANDLE_OP_END(); + } +#endif /* end of WASM_ENABLE_STRINGREF != 0 */ + default: + { + wasm_set_exception(module, "unsupported opcode"); + goto got_exception; + } + } + } +#endif /* end of WASM_ENABLE_GC != 0 */ /* variable instructions */ HANDLE_OP(WASM_OP_GET_LOCAL) @@ -2092,7 +3891,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, switch (local_type) { case VALUE_TYPE_I32: case VALUE_TYPE_F32: -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 && WASM_ENABLE_GC == 0 case VALUE_TYPE_FUNCREF: case VALUE_TYPE_EXTERNREF: #endif @@ -2103,8 +3902,23 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, PUSH_I64(GET_I64_FROM_ADDR(frame_lp + local_offset)); break; default: - wasm_set_exception(module, "invalid local type"); - goto got_exception; +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_reftype(local_type)) { + if (wasm_is_reftype_i31ref(local_type)) { + PUSH_I31REF( + GET_REF_FROM_ADDR(frame_lp + local_offset)); + } + else { + PUSH_REF( + GET_REF_FROM_ADDR(frame_lp + local_offset)); + } + } + else +#endif + { + wasm_set_exception(module, "invalid local type"); + goto got_exception; + } } HANDLE_OP_END(); @@ -2128,7 +3942,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, switch (local_type) { case VALUE_TYPE_I32: case VALUE_TYPE_F32: -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 && WASM_ENABLE_GC == 0 case VALUE_TYPE_FUNCREF: case VALUE_TYPE_EXTERNREF: #endif @@ -2140,8 +3954,16 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, POP_I64()); break; default: - wasm_set_exception(module, "invalid local type"); - goto got_exception; +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_reftype(local_type)) { + PUT_REF_TO_ADDR(frame_lp + local_offset, POP_REF()); + } + else +#endif + { + wasm_set_exception(module, "invalid local type"); + goto got_exception; + } } HANDLE_OP_END(); @@ -2166,7 +3988,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, switch (local_type) { case VALUE_TYPE_I32: case VALUE_TYPE_F32: -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 && WASM_ENABLE_GC == 0 case VALUE_TYPE_FUNCREF: case VALUE_TYPE_EXTERNREF: #endif @@ -2179,8 +4001,18 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, GET_I64_FROM_ADDR(frame_sp - 2)); break; default: - wasm_set_exception(module, "invalid local type"); - goto got_exception; +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_reftype(local_type)) { + PUT_REF_TO_ADDR( + frame_lp + local_offset, + GET_REF_FROM_ADDR(frame_sp - REF_CELL_NUM)); + } + else +#endif + { + wasm_set_exception(module, "invalid local type"); + goto got_exception; + } } HANDLE_OP_END(); @@ -2205,7 +4037,21 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, bh_assert(global_idx < module->e->global_count); global = globals + global_idx; global_addr = get_global_addr(global_data, global); + /* clang-format off */ +#if WASM_ENABLE_GC == 0 PUSH_I32(*(uint32 *)global_addr); +#else + if (!wasm_is_type_reftype(global->type)) { + PUSH_I32(*(uint32 *)global_addr); + } + else if (wasm_is_reftype_i31ref(global->type)) { + PUSH_I31REF(GET_REF_FROM_ADDR((uint32 *)global_addr)); + } + else { + PUSH_REF(GET_REF_FROM_ADDR((uint32 *)global_addr)); + } +#endif + /* clang-format on */ HANDLE_OP_END(); } @@ -2225,7 +4071,16 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, bh_assert(global_idx < module->e->global_count); global = globals + global_idx; global_addr = get_global_addr(global_data, global); + /* clang-format off */ +#if WASM_ENABLE_GC == 0 *(int32 *)global_addr = POP_I32(); +#else + if (!wasm_is_type_reftype(global->type)) + *(int32 *)global_addr = POP_I32(); + else + PUT_REF_TO_ADDR((uint32 *)global_addr, POP_REF()); +#endif + /* clang-format on */ HANDLE_OP_END(); } @@ -3665,13 +5520,16 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, break; } #endif /* WASM_ENABLE_BULK_MEMORY */ -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 case WASM_OP_TABLE_INIT: { uint32 tbl_idx, elem_idx; uint32 n, s, d; WASMTableInstance *tbl_inst; - uint32 *tbl_seg_elems = NULL, tbl_seg_len = 0; + table_elem_type_t *table_elems; + InitializerExpression *tbl_seg_init_values = NULL, + *init_values; + uint32 tbl_seg_len = 0; read_leb_uint32(frame_ip, frame_ip_end, elem_idx); bh_assert(elem_idx < module->module->table_seg_count); @@ -3688,12 +5546,12 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, if (!bh_bitmap_get_bit(module->e->common.elem_dropped, elem_idx)) { /* table segment isn't dropped */ - tbl_seg_elems = + tbl_seg_init_values = module->module->table_segments[elem_idx] - .func_indexes; + .init_values; tbl_seg_len = module->module->table_segments[elem_idx] - .function_count; + .value_count; } if (offset_len_out_of_bounds(s, n, tbl_seg_len) @@ -3708,13 +5566,34 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, break; } - bh_memcpy_s( - (uint8 *)tbl_inst - + offsetof(WASMTableInstance, elems) - + d * sizeof(uint32), - (uint32)((tbl_inst->cur_size - d) * sizeof(uint32)), - tbl_seg_elems + s, (uint32)(n * sizeof(uint32))); - + table_elems = tbl_inst->elems + d; + init_values = tbl_seg_init_values + s; +#if WASM_ENABLE_GC != 0 + SYNC_ALL_TO_FRAME(); +#endif + for (i = 0; i < n; i++) { + /* UINT32_MAX indicates that it is a null ref */ + bh_assert(init_values[i].init_expr_type + == INIT_EXPR_TYPE_REFNULL_CONST + || init_values[i].init_expr_type + == INIT_EXPR_TYPE_FUNCREF_CONST); +#if WASM_ENABLE_GC == 0 + table_elems[i] = + (table_elem_type_t)init_values[i].u.ref_index; +#else + if (init_values[i].u.ref_index != UINT32_MAX) { + if (!(func_obj = wasm_create_func_obj( + module, init_values[i].u.ref_index, + true, NULL, 0))) { + goto got_exception; + } + table_elems[i] = func_obj; + } + else { + table_elems[i] = NULL_REF; + } +#endif + } break; } case WASM_OP_ELEM_DROP: @@ -3761,19 +5640,20 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, /* merge all together */ bh_memmove_s((uint8 *)dst_tbl_inst + offsetof(WASMTableInstance, elems) - + d * sizeof(uint32), + + d * sizeof(table_elem_type_t), (uint32)((dst_tbl_inst->cur_size - d) - * sizeof(uint32)), + * sizeof(table_elem_type_t)), (uint8 *)src_tbl_inst + offsetof(WASMTableInstance, elems) - + s * sizeof(uint32), - (uint32)(n * sizeof(uint32))); + + s * sizeof(table_elem_type_t), + (uint32)(n * sizeof(table_elem_type_t))); break; } case WASM_OP_TABLE_GROW: { - uint32 tbl_idx, n, init_val, orig_tbl_sz; WASMTableInstance *tbl_inst; + uint32 tbl_idx, n, orig_tbl_sz; + table_elem_type_t init_val; read_leb_uint32(frame_ip, frame_ip_end, tbl_idx); bh_assert(tbl_idx < module->table_count); @@ -3783,7 +5663,11 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, orig_tbl_sz = tbl_inst->cur_size; n = POP_I32(); +#if WASM_ENABLE_GC == 0 init_val = POP_I32(); +#else + init_val = POP_REF(); +#endif if (!wasm_enlarge_table(module, tbl_idx, n, init_val)) { PUSH_I32(-1); @@ -3808,8 +5692,9 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, } case WASM_OP_TABLE_FILL: { - uint32 tbl_idx, n, fill_val; + uint32 tbl_idx, n; WASMTableInstance *tbl_inst; + table_elem_type_t fill_val; read_leb_uint32(frame_ip, frame_ip_end, tbl_idx); bh_assert(tbl_idx < module->table_count); @@ -3817,7 +5702,11 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, tbl_inst = wasm_get_table_inst(module, tbl_idx); n = POP_I32(); +#if WASM_ENABLE_GC == 0 fill_val = POP_I32(); +#else + fill_val = POP_REF(); +#endif i = POP_I32(); if (offset_len_out_of_bounds(i, n, @@ -3830,10 +5719,9 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, for (; n != 0; i++, n--) { tbl_inst->elems[i] = fill_val; } - break; } -#endif /* WASM_ENABLE_REF_TYPES */ +#endif /* end of WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */ default: wasm_set_exception(module, "unsupported opcode"); goto got_exception; @@ -3844,7 +5732,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, #if WASM_ENABLE_SHARED_MEMORY != 0 HANDLE_OP(WASM_OP_ATOMIC_PREFIX) { - uint32 offset = 0, align, addr; + uint32 offset = 0, align = 0, addr; uint32 opcode1; read_leb_uint32(frame_ip, frame_ip_end, opcode1); @@ -3864,7 +5752,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, notify_count = POP_I32(); addr = POP_I32(); - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 4, maddr); + CHECK_MEMORY_OVERFLOW(4); CHECK_ATOMIC_MEMORY_ACCESS(); ret = wasm_runtime_atomic_notify( @@ -3884,7 +5772,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, timeout = POP_I64(); expect = POP_I32(); addr = POP_I32(); - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 4, maddr); + CHECK_MEMORY_OVERFLOW(4); CHECK_ATOMIC_MEMORY_ACCESS(); ret = wasm_runtime_atomic_wait( @@ -3908,7 +5796,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, timeout = POP_I64(); expect = POP_I64(); addr = POP_I32(); - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 8, maddr); + CHECK_MEMORY_OVERFLOW(8); CHECK_ATOMIC_MEMORY_ACCESS(); ret = wasm_runtime_atomic_wait( @@ -3941,21 +5829,21 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, addr = POP_I32(); if (opcode == WASM_OP_ATOMIC_I32_LOAD8_U) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 1, maddr); + CHECK_MEMORY_OVERFLOW(1); CHECK_ATOMIC_MEMORY_ACCESS(); shared_memory_lock(memory); readv = (uint32)(*(uint8 *)maddr); shared_memory_unlock(memory); } else if (opcode == WASM_OP_ATOMIC_I32_LOAD16_U) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 2, maddr); + CHECK_MEMORY_OVERFLOW(2); CHECK_ATOMIC_MEMORY_ACCESS(); shared_memory_lock(memory); readv = (uint32)LOAD_U16(maddr); shared_memory_unlock(memory); } else { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 4, maddr); + CHECK_MEMORY_OVERFLOW(4); CHECK_ATOMIC_MEMORY_ACCESS(); shared_memory_lock(memory); readv = LOAD_I32(maddr); @@ -3976,28 +5864,28 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, addr = POP_I32(); if (opcode == WASM_OP_ATOMIC_I64_LOAD8_U) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 1, maddr); + CHECK_MEMORY_OVERFLOW(1); CHECK_ATOMIC_MEMORY_ACCESS(); shared_memory_lock(memory); readv = (uint64)(*(uint8 *)maddr); shared_memory_unlock(memory); } else if (opcode == WASM_OP_ATOMIC_I64_LOAD16_U) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 2, maddr); + CHECK_MEMORY_OVERFLOW(2); CHECK_ATOMIC_MEMORY_ACCESS(); shared_memory_lock(memory); readv = (uint64)LOAD_U16(maddr); shared_memory_unlock(memory); } else if (opcode == WASM_OP_ATOMIC_I64_LOAD32_U) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 4, maddr); + CHECK_MEMORY_OVERFLOW(4); CHECK_ATOMIC_MEMORY_ACCESS(); shared_memory_lock(memory); readv = (uint64)LOAD_U32(maddr); shared_memory_unlock(memory); } else { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 8, maddr); + CHECK_MEMORY_OVERFLOW(8); CHECK_ATOMIC_MEMORY_ACCESS(); shared_memory_lock(memory); readv = LOAD_I64(maddr); @@ -4018,21 +5906,21 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, addr = POP_I32(); if (opcode == WASM_OP_ATOMIC_I32_STORE8) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 1, maddr); + CHECK_MEMORY_OVERFLOW(1); CHECK_ATOMIC_MEMORY_ACCESS(); shared_memory_lock(memory); *(uint8 *)maddr = (uint8)sval; shared_memory_unlock(memory); } else if (opcode == WASM_OP_ATOMIC_I32_STORE16) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 2, maddr); + CHECK_MEMORY_OVERFLOW(2); CHECK_ATOMIC_MEMORY_ACCESS(); shared_memory_lock(memory); STORE_U16(maddr, (uint16)sval); shared_memory_unlock(memory); } else { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 4, maddr); + CHECK_MEMORY_OVERFLOW(4); CHECK_ATOMIC_MEMORY_ACCESS(); shared_memory_lock(memory); STORE_U32(maddr, sval); @@ -4052,28 +5940,28 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, addr = POP_I32(); if (opcode == WASM_OP_ATOMIC_I64_STORE8) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 1, maddr); + CHECK_MEMORY_OVERFLOW(1); CHECK_ATOMIC_MEMORY_ACCESS(); shared_memory_lock(memory); *(uint8 *)maddr = (uint8)sval; shared_memory_unlock(memory); } else if (opcode == WASM_OP_ATOMIC_I64_STORE16) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 2, maddr); + CHECK_MEMORY_OVERFLOW(2); CHECK_ATOMIC_MEMORY_ACCESS(); shared_memory_lock(memory); STORE_U16(maddr, (uint16)sval); shared_memory_unlock(memory); } else if (opcode == WASM_OP_ATOMIC_I64_STORE32) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 4, maddr); + CHECK_MEMORY_OVERFLOW(4); CHECK_ATOMIC_MEMORY_ACCESS(); shared_memory_lock(memory); STORE_U32(maddr, (uint32)sval); shared_memory_unlock(memory); } else { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 8, maddr); + CHECK_MEMORY_OVERFLOW(8); CHECK_ATOMIC_MEMORY_ACCESS(); shared_memory_lock(memory); PUT_I64_TO_ADDR((uint32 *)maddr, sval); @@ -4093,7 +5981,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, addr = POP_I32(); if (opcode == WASM_OP_ATOMIC_RMW_I32_CMPXCHG8_U) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 1, maddr); + CHECK_MEMORY_OVERFLOW(1); CHECK_ATOMIC_MEMORY_ACCESS(); expect = (uint8)expect; @@ -4104,7 +5992,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, shared_memory_unlock(memory); } else if (opcode == WASM_OP_ATOMIC_RMW_I32_CMPXCHG16_U) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 2, maddr); + CHECK_MEMORY_OVERFLOW(2); CHECK_ATOMIC_MEMORY_ACCESS(); expect = (uint16)expect; @@ -4115,7 +6003,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, shared_memory_unlock(memory); } else { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 4, maddr); + CHECK_MEMORY_OVERFLOW(4); CHECK_ATOMIC_MEMORY_ACCESS(); shared_memory_lock(memory); @@ -4139,7 +6027,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, addr = POP_I32(); if (opcode == WASM_OP_ATOMIC_RMW_I64_CMPXCHG8_U) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 1, maddr); + CHECK_MEMORY_OVERFLOW(1); CHECK_ATOMIC_MEMORY_ACCESS(); expect = (uint8)expect; @@ -4150,7 +6038,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, shared_memory_unlock(memory); } else if (opcode == WASM_OP_ATOMIC_RMW_I64_CMPXCHG16_U) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 2, maddr); + CHECK_MEMORY_OVERFLOW(2); CHECK_ATOMIC_MEMORY_ACCESS(); expect = (uint16)expect; @@ -4161,7 +6049,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, shared_memory_unlock(memory); } else if (opcode == WASM_OP_ATOMIC_RMW_I64_CMPXCHG32_U) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 4, maddr); + CHECK_MEMORY_OVERFLOW(4); CHECK_ATOMIC_MEMORY_ACCESS(); expect = (uint32)expect; @@ -4172,7 +6060,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, shared_memory_unlock(memory); } else { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 8, maddr); + CHECK_MEMORY_OVERFLOW(8); CHECK_ATOMIC_MEMORY_ACCESS(); shared_memory_lock(memory); @@ -4236,7 +6124,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, #if WASM_ENABLE_SHARED_MEMORY == 0 HANDLE_OP(WASM_OP_ATOMIC_PREFIX) #endif -#if WASM_ENABLE_REF_TYPES == 0 +#if WASM_ENABLE_REF_TYPES == 0 && WASM_ENABLE_GC == 0 HANDLE_OP(WASM_OP_SELECT_T) HANDLE_OP(WASM_OP_TABLE_GET) HANDLE_OP(WASM_OP_TABLE_SET) @@ -4244,6 +6132,15 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_REF_IS_NULL) HANDLE_OP(WASM_OP_REF_FUNC) #endif +#if WASM_ENABLE_GC == 0 + HANDLE_OP(WASM_OP_CALL_REF) + HANDLE_OP(WASM_OP_RETURN_CALL_REF) + HANDLE_OP(WASM_OP_REF_EQ) + HANDLE_OP(WASM_OP_REF_AS_NON_NULL) + HANDLE_OP(WASM_OP_BR_ON_NULL) + HANDLE_OP(WASM_OP_BR_ON_NON_NULL) + HANDLE_OP(WASM_OP_GC_PREFIX) +#endif #if WASM_ENABLE_EXCE_HANDLING == 0 HANDLE_OP(WASM_OP_TRY) HANDLE_OP(WASM_OP_CATCH) @@ -4259,8 +6156,6 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, trigger the SIMD opcode in interpreter */ HANDLE_OP(WASM_OP_SIMD_PREFIX) #endif - HANDLE_OP(WASM_OP_UNUSED_0x14) - HANDLE_OP(WASM_OP_UNUSED_0x15) HANDLE_OP(WASM_OP_UNUSED_0x16) HANDLE_OP(WASM_OP_UNUSED_0x17) HANDLE_OP(WASM_OP_UNUSED_0x27) @@ -4274,7 +6169,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, wasm_set_exception(module, "unsupported opcode"); goto got_exception; } -#endif +#endif /* end of WASM_ENABLE_LABELS_AS_VALUES != 0 */ #if WASM_ENABLE_LABELS_AS_VALUES == 0 continue; @@ -4282,7 +6177,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, FETCH_OPCODE_AND_DISPATCH(); #endif -#if WASM_ENABLE_TAIL_CALL != 0 +#if WASM_ENABLE_TAIL_CALL != 0 || WASM_ENABLE_GC != 0 call_func_from_return_call: { POP(cur_func->param_cell_num); @@ -4298,11 +6193,11 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, { /* Only do the copy when it's called from interpreter. */ WASMInterpFrame *outs_area = wasm_exec_env_wasm_stack_top(exec_env); - POP(cur_func->param_cell_num); - SYNC_ALL_TO_FRAME(); if (cur_func->param_cell_num > 0) { + POP(cur_func->param_cell_num); word_copy(outs_area->lp, frame_sp, cur_func->param_cell_num); } + SYNC_ALL_TO_FRAME(); prev_frame = frame; } @@ -4356,10 +6251,10 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, */ PUSH_I32(import_exception); } -#endif +#endif /* end of WASM_ENABLE_EXCE_HANDLING != 0 */ } else -#endif +#endif /* end of WASM_ENABLE_MULTI_MODULE != 0 */ { wasm_interp_call_func_native(module, exec_env, cur_func, prev_frame); @@ -4405,28 +6300,33 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, /* rethrow the exception into that frame */ goto find_a_catch_handler; } -#endif +#endif /* WASM_ENABLE_EXCE_HANDLING != 0 */ goto got_exception; } } else { WASMFunction *cur_wasm_func = cur_func->u.func; - WASMType *func_type; + WASMFuncType *func_type = cur_wasm_func->func_type; + uint32 max_stack_cell_num = cur_wasm_func->max_stack_cell_num; + uint32 cell_num_of_local_stack; #if WASM_ENABLE_EXCE_HANDLING != 0 - /* account for exception handlers */ - /* bundle them here */ + /* account for exception handlers, bundle them here */ uint32 eh_size = cur_wasm_func->exception_handler_count * sizeof(uint8 *); - cur_wasm_func->max_stack_cell_num += eh_size; + max_stack_cell_num += eh_size; #endif - func_type = cur_wasm_func->func_type; - - all_cell_num = cur_func->param_cell_num + cur_func->local_cell_num - + cur_wasm_func->max_stack_cell_num + cell_num_of_local_stack = cur_func->param_cell_num + + cur_func->local_cell_num + + max_stack_cell_num; + all_cell_num = cell_num_of_local_stack + cur_wasm_func->max_block_num * (uint32)sizeof(WASMBranchBlock) / 4; +#if WASM_ENABLE_GC != 0 + /* area of frame_ref */ + all_cell_num += (cell_num_of_local_stack + 3) / 4; +#endif /* param_cell_num, local_cell_num, max_stack_cell_num and max_block_num are all no larger than UINT16_MAX (checked @@ -4447,14 +6347,23 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, frame_sp = frame->sp_bottom = frame_lp + cur_func->param_cell_num + cur_func->local_cell_num; - frame->sp_boundary = - frame->sp_bottom + cur_wasm_func->max_stack_cell_num; + frame->sp_boundary = frame->sp_bottom + max_stack_cell_num; frame_csp = frame->csp_bottom = (WASMBranchBlock *)frame->sp_boundary; frame->csp_boundary = frame->csp_bottom + cur_wasm_func->max_block_num; +#if WASM_ENABLE_GC != 0 + /* frame->sp and frame->ip are used during GC root set enumeration, + * so we must initialized these fields here */ + frame->sp = frame_sp; + frame->ip = frame_ip; + frame_ref = (uint8 *)frame->csp_boundary; + init_frame_refs(frame_ref, (uint32)cell_num_of_local_stack, + cur_func); +#endif + /* Initialize the local variables */ memset(frame_lp + cur_func->param_cell_num, 0, (uint32)(cur_func->local_cell_num * 4)); @@ -4525,6 +6434,36 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, #endif } +#if WASM_ENABLE_GC != 0 +bool +wasm_interp_traverse_gc_rootset(WASMExecEnv *exec_env, void *heap) +{ + WASMInterpFrame *frame; + WASMObjectRef gc_obj; + int i; + + frame = wasm_exec_env_get_cur_frame(exec_env); + for (; frame; frame = frame->prev_frame) { + uint8 *frame_ref = get_frame_ref(frame); + for (i = 0; i < frame->sp - frame->lp; i++) { + if (frame_ref[i]) { + gc_obj = GET_REF_FROM_ADDR(frame->lp + i); + if (wasm_obj_is_created_from_heap(gc_obj)) { + if (mem_allocator_add_root((mem_allocator_t)heap, gc_obj)) { + return false; + } + } +#if UINTPTR_MAX == UINT64_MAX + bh_assert(frame_ref[i + 1]); + i++; +#endif + } + } + } + return true; +} +#endif + #if WASM_ENABLE_FAST_JIT != 0 /* * ASAN is not designed to work with custom stack unwind or other low-level @@ -4543,7 +6482,7 @@ fast_jit_call_func_bytecode(WASMModuleInstance *module_inst, JitGlobals *jit_globals = jit_compiler_get_jit_globals(); JitInterpSwitchInfo info; WASMModule *module = module_inst->module; - WASMType *func_type = function->u.func->func_type; + WASMFuncType *func_type = function->u.func->func_type; uint8 type = func_type->result_count ? func_type->types[func_type->param_count] : VALUE_TYPE_VOID; @@ -4607,19 +6546,260 @@ fast_jit_call_func_bytecode(WASMModuleInstance *module_inst, #endif /* end of WASM_ENABLE_FAST_JIT != 0 */ #if WASM_ENABLE_JIT != 0 +#if WASM_ENABLE_DUMP_CALL_STACK != 0 || WASM_ENABLE_PERF_PROFILING != 0 \ + || WASM_ENABLE_AOT_STACK_FRAME != 0 +#if WASM_ENABLE_GC == 0 +bool +llvm_jit_alloc_frame(WASMExecEnv *exec_env, uint32 func_index) +{ + WASMModuleInstance *module_inst = + (WASMModuleInstance *)exec_env->module_inst; + WASMInterpFrame *cur_frame, *frame; + uint32 size = (uint32)offsetof(WASMInterpFrame, lp); + + bh_assert(module_inst->module_type == Wasm_Module_Bytecode); + + cur_frame = exec_env->cur_frame; + if (!cur_frame) + frame = (WASMInterpFrame *)exec_env->wasm_stack.bottom; + else + frame = (WASMInterpFrame *)((uint8 *)cur_frame + size); + + if ((uint8 *)frame + size > exec_env->wasm_stack.top_boundary) { + wasm_set_exception(module_inst, "wasm operand stack overflow"); + return false; + } + + frame->function = module_inst->e->functions + func_index; + /* No need to initialize ip, it will be committed in jitted code + when needed */ + /* frame->ip = NULL; */ + frame->prev_frame = cur_frame; + +#if WASM_ENABLE_PERF_PROFILING != 0 + frame->time_started = os_time_thread_cputime_us(); +#endif +#if WASM_ENABLE_MEMORY_PROFILING != 0 + { + uint32 wasm_stack_used = + (uint8 *)frame + size - exec_env->wasm_stack.bottom; + if (wasm_stack_used > exec_env->max_wasm_stack_used) + exec_env->max_wasm_stack_used = wasm_stack_used; + } +#endif + + exec_env->cur_frame = frame; + + return true; +} + +static inline void +llvm_jit_free_frame_internal(WASMExecEnv *exec_env) +{ + WASMInterpFrame *frame = exec_env->cur_frame; + WASMInterpFrame *prev_frame = frame->prev_frame; + + bh_assert(exec_env->module_inst->module_type == Wasm_Module_Bytecode); + +#if WASM_ENABLE_PERF_PROFILING != 0 + if (frame->function) { + uint64 time_elapsed = os_time_thread_cputime_us() - frame->time_started; + + frame->function->total_exec_time += time_elapsed; + frame->function->total_exec_cnt++; + + /* parent function */ + if (prev_frame) + prev_frame->function->children_exec_time += time_elapsed; + } +#endif + exec_env->cur_frame = prev_frame; +} + +void +llvm_jit_free_frame(WASMExecEnv *exec_env) +{ + llvm_jit_free_frame_internal(exec_env); +} + +#else /* else of WASM_ENABLE_GC == 0 */ + +bool +llvm_jit_alloc_frame(WASMExecEnv *exec_env, uint32 func_index) +{ + WASMModuleInstance *module_inst; + WASMModule *module; + WASMInterpFrame *frame; + uint32 size, max_local_cell_num, max_stack_cell_num; + + bh_assert(exec_env->module_inst->module_type == Wasm_Module_Bytecode); + + module_inst = (WASMModuleInstance *)exec_env->module_inst; + module = module_inst->module; + + if (func_index >= func_index - module->import_function_count) { + WASMFunction *func = + module->functions[func_index - module->import_function_count]; + + max_local_cell_num = func->param_cell_num + func->local_cell_num; + max_stack_cell_num = func->max_stack_cell_num; + } + else { + WASMFunctionImport *func = + &((module->import_functions + func_index)->u.function); + + max_local_cell_num = func->func_type->param_cell_num > 2 + ? func->func_type->param_cell_num + : 2; + max_stack_cell_num = 0; + } + + size = + wasm_interp_interp_frame_size(max_local_cell_num + max_stack_cell_num); + + frame = wasm_exec_env_alloc_wasm_frame(exec_env, size); + if (!frame) { + wasm_set_exception(module_inst, "wasm operand stack overflow"); + return false; + } + + frame->function = module_inst->e->functions + func_index; +#if WASM_ENABLE_PERF_PROFILING != 0 + frame->time_started = os_time_thread_cputime_us(); +#endif + frame->prev_frame = wasm_exec_env_get_cur_frame(exec_env); + + /* No need to initialize ip, it will be committed in jitted code + when needed */ + /* frame->ip = NULL; */ + +#if WASM_ENABLE_GC != 0 + frame->sp = frame->lp + max_local_cell_num; + + /* Initialize frame ref flags for import function */ + if (func_index < module->import_function_count) { + WASMFunctionImport *func = + &((module->import_functions + func_index)->u.function); + WASMFuncType *func_type = func->func_type; + /* native function doesn't have operand stack and label stack */ + uint8 *frame_ref = (uint8 *)frame->sp; + uint32 i, j, k, value_type_cell_num; + + for (i = 0, j = 0; i < func_type->param_count; i++) { + if (wasm_is_type_reftype(func_type->types[i]) + && !wasm_is_reftype_i31ref(func_type->types[i])) { + frame_ref[j++] = 1; +#if UINTPTR_MAX == UINT64_MAX + frame_ref[j++] = 1; +#endif + } + else { + value_type_cell_num = + wasm_value_type_cell_num(func_type->types[i]); + for (k = 0; k < value_type_cell_num; k++) + frame_ref[j++] = 0; + } + } + } +#endif + + wasm_exec_env_set_cur_frame(exec_env, frame); + + return true; +} + +static inline void +llvm_jit_free_frame_internal(WASMExecEnv *exec_env) +{ + WASMInterpFrame *frame; + WASMInterpFrame *prev_frame; + + bh_assert(exec_env->module_inst->module_type == Wasm_Module_Bytecode); + + frame = wasm_exec_env_get_cur_frame(exec_env); + prev_frame = frame->prev_frame; + +#if WASM_ENABLE_PERF_PROFILING != 0 + if (frame->function) { + uint64 time_elapsed = os_time_thread_cputime_us() - frame->time_started; + + frame->function->total_exec_time += time_elapsed; + frame->function->total_exec_cnt++; + + /* parent function */ + if (prev_frame) + prev_frame->function->children_exec_time += time_elapsed; + } +#endif + wasm_exec_env_free_wasm_frame(exec_env, frame); + wasm_exec_env_set_cur_frame(exec_env, prev_frame); +} + +void +llvm_jit_free_frame(WASMExecEnv *exec_env) +{ + llvm_jit_free_frame_internal(exec_env); +} +#endif /* end of WASM_ENABLE_GC == 0 */ + +void +llvm_jit_frame_update_profile_info(WASMExecEnv *exec_env, bool alloc_frame) +{ +#if WASM_ENABLE_PERF_PROFILING != 0 + WASMInterpFrame *cur_frame = exec_env->cur_frame; + + if (alloc_frame) { + cur_frame->time_started = os_time_thread_cputime_us(); + } + else { + if (cur_frame->function) { + WASMInterpFrame *prev_frame = cur_frame->prev_frame; + uint64 time_elapsed = + os_time_thread_cputime_us() - cur_frame->time_started; + + cur_frame->function->total_exec_time += time_elapsed; + cur_frame->function->total_exec_cnt++; + + /* parent function */ + if (prev_frame) + prev_frame->function->children_exec_time += time_elapsed; + } + } +#endif + +#if WASM_ENABLE_MEMORY_PROFILING != 0 + if (alloc_frame) { +#if WASM_ENABLE_GC == 0 + uint32 wasm_stack_used = (uint8 *)exec_env->cur_frame + + (uint32)offsetof(WASMInterpFrame, lp) + - exec_env->wasm_stack.bottom; +#else + uint32 wasm_stack_used = + exec_env->wasm_stack.top - exec_env->wasm_stack.bottom; +#endif + if (wasm_stack_used > exec_env->max_wasm_stack_used) + exec_env->max_wasm_stack_used = wasm_stack_used; + } +#endif +} +#endif /* end of WASM_ENABLE_DUMP_CALL_STACK != 0 \ + || WASM_ENABLE_PERF_PROFILING != 0 \ + || WASM_ENABLE_AOT_STACK_FRAME != 0 */ + static bool llvm_jit_call_func_bytecode(WASMModuleInstance *module_inst, WASMExecEnv *exec_env, WASMFunctionInstance *function, uint32 argc, uint32 argv[]) { - WASMType *func_type = function->u.func->func_type; + WASMFuncType *func_type = function->u.func->func_type; uint32 result_count = func_type->result_count; uint32 ext_ret_count = result_count > 1 ? result_count - 1 : 0; uint32 func_idx = (uint32)(function - module_inst->e->functions); bool ret = false; -#if (WASM_ENABLE_DUMP_CALL_STACK != 0) || (WASM_ENABLE_PERF_PROFILING != 0) +#if (WASM_ENABLE_DUMP_CALL_STACK != 0) || (WASM_ENABLE_PERF_PROFILING != 0) \ + || (WASM_ENABLE_AOT_STACK_FRAME != 0) if (!llvm_jit_alloc_frame(exec_env, function - module_inst->e->functions)) { /* wasm operand stack overflow has been thrown, no need to throw again */ @@ -4731,8 +6911,9 @@ llvm_jit_call_func_bytecode(WASMModuleInstance *module_inst, fail: -#if (WASM_ENABLE_DUMP_CALL_STACK != 0) || (WASM_ENABLE_PERF_PROFILING != 0) - llvm_jit_free_frame(exec_env); +#if (WASM_ENABLE_DUMP_CALL_STACK != 0) || (WASM_ENABLE_PERF_PROFILING != 0) \ + || (WASM_ENABLE_AOT_STACK_FRAME != 0) + llvm_jit_free_frame_internal(exec_env); #endif return ret; @@ -4811,7 +6992,7 @@ wasm_interp_call_wasm(WASMModuleInstance *module_inst, WASMExecEnv *exec_env, frame->sp = frame->lp + 0; if ((uint8 *)(outs_area->lp + function->param_cell_num) - > exec_env->wasm_stack.s.top_boundary) { + > exec_env->wasm_stack.top_boundary) { wasm_set_exception(module_inst, "wasm operand stack overflow"); return; } diff --git a/core/iwasm/interpreter/wasm_interp_fast.c b/core/iwasm/interpreter/wasm_interp_fast.c index 335fefca0..a9e6af400 100644 --- a/core/iwasm/interpreter/wasm_interp_fast.c +++ b/core/iwasm/interpreter/wasm_interp_fast.c @@ -10,6 +10,13 @@ #include "wasm_loader.h" #include "wasm_memory.h" #include "../common/wasm_exec_env.h" +#if WASM_ENABLE_GC != 0 +#include "../common/gc/gc_object.h" +#include "mem_alloc.h" +#if WASM_ENABLE_STRINGREF != 0 +#include "string_object.h" +#endif +#endif #if WASM_ENABLE_SHARED_MEMORY != 0 #include "../common/wasm_shared_memory.h" #endif @@ -301,6 +308,78 @@ LOAD_PTR(void *addr) #endif /* end of UINTPTR_MAX */ #endif /* end of WASM_CPU_SUPPORTS_UNALIGNED_ADDR_ACCESS */ +#if WASM_ENABLE_GC != 0 +static void +init_frame_refs(uint8 *frame_ref, uint32 cell_num, WASMFunctionInstance *func) +{ + uint32 i, j; + + memset(frame_ref, 0, cell_num); + + for (i = 0, j = 0; i < func->param_count; i++) { + if (wasm_is_type_reftype(func->param_types[i]) + && !wasm_is_reftype_i31ref(func->param_types[i])) { + frame_ref[j++] = 1; +#if UINTPTR_MAX == UINT64_MAX + frame_ref[j++] = 1; +#endif + } + else { + j += wasm_value_type_cell_num(func->param_types[i]); + } + } + + for (i = 0; i < func->local_count; i++) { + if (wasm_is_type_reftype(func->local_types[i]) + && !wasm_is_reftype_i31ref(func->local_types[i])) { + frame_ref[j++] = 1; +#if UINTPTR_MAX == UINT64_MAX + frame_ref[j++] = 1; +#endif + } + else { + j += wasm_value_type_cell_num(func->local_types[i]); + } + } +} + +uint8 * +wasm_interp_get_frame_ref(WASMInterpFrame *frame) +{ + return frame->frame_ref; +} + +/* Return the corresponding ref slot of the given slot of local + variable or stack pointer. */ + +#define COMPUTE_FRAME_REF(ref, off) (ref + (unsigned)(off)) + +#define FRAME_REF(off) COMPUTE_FRAME_REF(frame_ref, off) + +#if UINTPTR_MAX == UINT64_MAX +#define SET_FRAME_REF(off) *FRAME_REF(off) = *FRAME_REF(off + 1) = 1 +#define CLEAR_FRAME_REF(off) \ + (unsigned)off >= local_cell_num \ + ? (*FRAME_REF(off) = *FRAME_REF(off + 1) = 0) \ + : (void)0 +#else +#define SET_FRAME_REF(off) *FRAME_REF(off) = 1 +#define CLEAR_FRAME_REF(off) \ + (unsigned)off >= local_cell_num ? (*FRAME_REF(off) = 0) : (void)0 +#endif + +#define FRAME_REF_FOR(frame, p) \ + COMPUTE_FRAME_REF(frame->frame_ref, p - frame->lp) + +#define CLEAR_FRAME_REF_FOR(p, n) \ + do { \ + int32 ref_i, ref_n = (int32)(n); \ + uint8 *ref = FRAME_REF(p - frame_lp); \ + for (ref_i = 0; ref_i < ref_n; ref_i++) \ + ref[ref_i] = 0; \ + } while (0) +#endif /* end of WASM_ENABLE_GC != 0 */ + #define read_uint32(p) \ (p += sizeof(uint32), LOAD_U32_WITH_2U16S(p - sizeof(uint32))) @@ -336,6 +415,14 @@ LOAD_PTR(void *addr) uint32 *addr_tmp = frame_lp + *(int16 *)(frame_ip + off); \ PUT_F64_TO_ADDR(addr_tmp, value); \ } while (0) +#define SET_OPERAND_REF(off, value) \ + do { \ + uint32 *addr_tmp; \ + opnd_off = *(int16 *)(frame_ip + off); \ + addr_tmp = frame_lp + opnd_off; \ + PUT_REF_TO_ADDR(addr_tmp, value); \ + SET_FRAME_REF(ond_off); \ + } while (0) #define SET_OPERAND(op_type, off, value) SET_OPERAND_##op_type(off, value) @@ -347,6 +434,8 @@ LOAD_PTR(void *addr) (type) GET_I64_FROM_ADDR(frame_lp + *(int16 *)(frame_ip + off)) #define GET_OPERAND_F64(type, off) \ (type) GET_F64_FROM_ADDR(frame_lp + *(int16 *)(frame_ip + off)) +#define GET_OPERAND_REF(type, off) \ + (type) GET_REF_FROM_ADDR(frame_lp + *(int16 *)(frame_ip + off)) #define GET_OPERAND(type, op_type, off) GET_OPERAND_##op_type(type, off) @@ -372,6 +461,23 @@ LOAD_PTR(void *addr) PUT_F64_TO_ADDR(addr_tmp, value); \ } while (0) +#define PUSH_REF(value) \ + do { \ + uint32 *addr_tmp; \ + opnd_off = GET_OFFSET(); \ + addr_tmp = frame_lp + opnd_off; \ + PUT_REF_TO_ADDR(addr_tmp, value); \ + SET_FRAME_REF(opnd_off); \ + } while (0) + +#define PUSH_I31REF(value) \ + do { \ + uint32 *addr_tmp; \ + opnd_off = GET_OFFSET(); \ + addr_tmp = frame_lp + opnd_off; \ + PUT_REF_TO_ADDR(addr_tmp, value); \ + } while (0) + #define POP_I32() (*(int32 *)(frame_lp + GET_OFFSET())) #define POP_F32() (*(float32 *)(frame_lp + GET_OFFSET())) @@ -380,14 +486,28 @@ LOAD_PTR(void *addr) #define POP_F64() (GET_F64_FROM_ADDR(frame_lp + GET_OFFSET())) +#define POP_REF() \ + (opnd_off = GET_OFFSET(), CLEAR_FRAME_REF((unsigned)(opnd_off)), \ + GET_REF_FROM_ADDR(frame_lp + opnd_off)) + +#if WASM_ENABLE_GC != 0 +#define SYNC_FRAME_REF() frame->frame_ref = frame_ref +#define UPDATE_FRAME_REF() frame_ref = frame->frame_ref +#else +#define SYNC_FRAME_REF() (void)0 +#define UPDATE_FRAME_REF() (void)0 +#endif + #define SYNC_ALL_TO_FRAME() \ do { \ frame->ip = frame_ip; \ + SYNC_FRAME_REF(); \ } while (0) #define UPDATE_ALL_FROM_FRAME() \ do { \ frame_ip = frame->ip; \ + UPDATE_FRAME_REF(); \ } while (0) #if WASM_ENABLE_LABELS_AS_VALUES != 0 @@ -396,6 +516,12 @@ LOAD_PTR(void *addr) #define UPDATE_FRAME_IP_END() frame_ip_end = wasm_get_func_code_end(cur_func) #endif +#if WASM_ENABLE_GC != 0 +#define RECOVER_FRAME_REF() frame_ref = frame->frame_ref +#else +#define RECOVER_FRAME_REF() (void)0 +#endif + #define RECOVER_CONTEXT(new_frame) \ do { \ frame = (new_frame); \ @@ -404,6 +530,7 @@ LOAD_PTR(void *addr) frame_ip = frame->ip; \ UPDATE_FRAME_IP_END(); \ frame_lp = frame->lp; \ + RECOVER_FRAME_REF(); \ } while (0) #if WASM_CPU_SUPPORTS_UNALIGNED_ADDR_ACCESS != 0 @@ -479,7 +606,7 @@ LOAD_PTR(void *addr) addr = POP_I32(); \ \ if (opcode == WASM_OP_ATOMIC_RMW_I32_##OP_NAME##8_U) { \ - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 1, maddr); \ + CHECK_MEMORY_OVERFLOW(1); \ CHECK_ATOMIC_MEMORY_ACCESS(1); \ \ shared_memory_lock(memory); \ @@ -488,7 +615,7 @@ LOAD_PTR(void *addr) shared_memory_unlock(memory); \ } \ else if (opcode == WASM_OP_ATOMIC_RMW_I32_##OP_NAME##16_U) { \ - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 2, maddr); \ + CHECK_MEMORY_OVERFLOW(2); \ CHECK_ATOMIC_MEMORY_ACCESS(2); \ \ shared_memory_lock(memory); \ @@ -497,7 +624,7 @@ LOAD_PTR(void *addr) shared_memory_unlock(memory); \ } \ else { \ - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 4, maddr); \ + CHECK_MEMORY_OVERFLOW(4); \ CHECK_ATOMIC_MEMORY_ACCESS(4); \ \ shared_memory_lock(memory); \ @@ -519,7 +646,7 @@ LOAD_PTR(void *addr) addr = POP_I32(); \ \ if (opcode == WASM_OP_ATOMIC_RMW_I64_##OP_NAME##8_U) { \ - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 1, maddr); \ + CHECK_MEMORY_OVERFLOW(1); \ CHECK_ATOMIC_MEMORY_ACCESS(1); \ \ shared_memory_lock(memory); \ @@ -528,7 +655,7 @@ LOAD_PTR(void *addr) shared_memory_unlock(memory); \ } \ else if (opcode == WASM_OP_ATOMIC_RMW_I64_##OP_NAME##16_U) { \ - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 2, maddr); \ + CHECK_MEMORY_OVERFLOW(2); \ CHECK_ATOMIC_MEMORY_ACCESS(2); \ \ shared_memory_lock(memory); \ @@ -537,7 +664,7 @@ LOAD_PTR(void *addr) shared_memory_unlock(memory); \ } \ else if (opcode == WASM_OP_ATOMIC_RMW_I64_##OP_NAME##32_U) { \ - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 4, maddr); \ + CHECK_MEMORY_OVERFLOW(4); \ CHECK_ATOMIC_MEMORY_ACCESS(4); \ \ shared_memory_lock(memory); \ @@ -547,7 +674,7 @@ LOAD_PTR(void *addr) } \ else { \ uint64 op_result; \ - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 8, maddr); \ + CHECK_MEMORY_OVERFLOW(8); \ CHECK_ATOMIC_MEMORY_ACCESS(8); \ \ shared_memory_lock(memory); \ @@ -711,6 +838,9 @@ trunc_f64_to_int(WASMModuleInstance *module, uint8 *frame_ip, uint32 *frame_lp, static bool copy_stack_values(WASMModuleInstance *module, uint32 *frame_lp, uint32 arity, +#if WASM_ENABLE_GC != 0 + uint8 *frame_ref, +#endif uint32 total_cell_num, const uint8 *cells, const int16 *src_offsets, const uint16 *dst_offsets) { @@ -718,11 +848,16 @@ copy_stack_values(WASMModuleInstance *module, uint32 *frame_lp, uint32 arity, * we use 2 steps to do the copy. First step, copy the src values * to a tmp buf. Second step, copy the values from tmp buf to dst. */ + bool ret = false; uint32 buf[16] = { 0 }, i; uint32 *tmp_buf = buf; uint8 cell; int16 src, buf_index = 0; uint16 dst; +#if WASM_ENABLE_GC != 0 + uint8 ref_buf[4]; + uint8 *tmp_ref_buf = ref_buf; +#endif /* Allocate memory if the buf is not large enough */ if (total_cell_num > sizeof(buf) / sizeof(uint32)) { @@ -730,19 +865,41 @@ copy_stack_values(WASMModuleInstance *module, uint32 *frame_lp, uint32 arity, if (total_size >= UINT32_MAX || !(tmp_buf = wasm_runtime_malloc((uint32)total_size))) { wasm_set_exception(module, "allocate memory failed"); - return false; + goto fail; } } +#if WASM_ENABLE_GC != 0 + if (total_cell_num > sizeof(ref_buf) / sizeof(uint8)) { + uint64 total_size = sizeof(uint8) * (uint64)total_cell_num; + if (total_size >= UINT32_MAX + || !(tmp_ref_buf = wasm_runtime_malloc((uint32)total_size))) { + wasm_set_exception(module, "allocate memory failed"); + goto fail; + } + } +#endif + /* 1) Copy values from src to tmp buf */ for (i = 0; i < arity; i++) { cell = cells[i * CELL_SIZE]; src = src_offsets[i]; - if (cell == 1) + if (cell == 1) { tmp_buf[buf_index] = frame_lp[src]; +#if WASM_ENABLE_GC != 0 + tmp_ref_buf[buf_index] = frame_ref[src]; + frame_ref[src] = 0; +#endif + } else { tmp_buf[buf_index] = frame_lp[src]; tmp_buf[buf_index + 1] = frame_lp[src + 1]; +#if WASM_ENABLE_GC != 0 + tmp_ref_buf[buf_index] = frame_ref[src]; + tmp_ref_buf[buf_index + 1] = frame_ref[src + 1]; + frame_ref[src] = 0; + frame_ref[src + 1] = 0; +#endif } buf_index += cell; } @@ -752,22 +909,93 @@ copy_stack_values(WASMModuleInstance *module, uint32 *frame_lp, uint32 arity, for (i = 0; i < arity; i++) { cell = cells[i * CELL_SIZE]; dst = dst_offsets[i]; - if (cell == 1) + if (cell == 1) { frame_lp[dst] = tmp_buf[buf_index]; +#if WASM_ENABLE_GC != 0 + frame_ref[dst] = tmp_ref_buf[buf_index]; +#endif + } else { frame_lp[dst] = tmp_buf[buf_index]; frame_lp[dst + 1] = tmp_buf[buf_index + 1]; +#if WASM_ENABLE_GC != 0 + frame_ref[dst] = tmp_ref_buf[buf_index]; + frame_ref[dst + 1] = tmp_ref_buf[buf_index + 1]; +#endif } buf_index += cell; } + ret = true; + +fail: if (tmp_buf != buf) { wasm_runtime_free(tmp_buf); } - return true; +#if WASM_ENABLE_GC != 0 + if (tmp_ref_buf != ref_buf) { + wasm_runtime_free(tmp_ref_buf); + } +#endif + + return ret; } +#if WASM_ENABLE_GC != 0 +#define RECOVER_BR_INFO() \ + do { \ + uint32 arity; \ + /* read arity */ \ + arity = read_uint32(frame_ip); \ + if (arity) { \ + uint32 total_cell; \ + uint16 *dst_offsets = NULL; \ + uint8 *cells; \ + int16 *src_offsets = NULL; \ + /* read total cell num */ \ + total_cell = read_uint32(frame_ip); \ + /* cells */ \ + cells = (uint8 *)frame_ip; \ + frame_ip += arity * CELL_SIZE; \ + /* src offsets */ \ + src_offsets = (int16 *)frame_ip; \ + frame_ip += arity * sizeof(int16); \ + /* dst offsets */ \ + dst_offsets = (uint16 *)frame_ip; \ + frame_ip += arity * sizeof(uint16); \ + if (arity == 1) { \ + if (cells[0] == 1) { \ + frame_lp[dst_offsets[0]] = frame_lp[src_offsets[0]]; \ + /* Ignore constants because they are not reference */ \ + if (src_offsets[0] >= 0) { \ + CLEAR_FRAME_REF((unsigned)(src_offsets[0])); \ + SET_FRAME_REF(dst_offsets[0]); \ + } \ + } \ + else if (cells[0] == 2) { \ + frame_lp[dst_offsets[0]] = frame_lp[src_offsets[0]]; \ + frame_lp[dst_offsets[0] + 1] = \ + frame_lp[src_offsets[0] + 1]; \ + /* Ignore constants because they are not reference */ \ + if (src_offsets[0] >= 0) { \ + CLEAR_FRAME_REF((unsigned)src_offsets[0]); \ + CLEAR_FRAME_REF((unsigned)(src_offsets[0] + 1)); \ + SET_FRAME_REF((unsigned)dst_offsets[0]); \ + SET_FRAME_REF((unsigned)(dst_offsets[0] + 1)); \ + } \ + } \ + } \ + else { \ + if (!copy_stack_values(module, frame_lp, arity, frame_ref, \ + total_cell, cells, src_offsets, \ + dst_offsets)) \ + goto got_exception; \ + } \ + } \ + frame_ip = (uint8 *)LOAD_PTR(frame_ip); \ + } while (0) +#else #define RECOVER_BR_INFO() \ do { \ uint32 arity; \ @@ -806,6 +1034,7 @@ copy_stack_values(WASMModuleInstance *module, uint32 *frame_lp, uint32 arity, } \ frame_ip = (uint8 *)LOAD_PTR(frame_ip); \ } while (0) +#endif #define SKIP_BR_INFO() \ do { \ @@ -901,12 +1130,14 @@ FREE_FRAME(WASMExecEnv *exec_env, WASMInterpFrame *frame) #if WASM_ENABLE_PERF_PROFILING != 0 if (frame->function) { WASMInterpFrame *prev_frame = frame->prev_frame; - uint64 elapsed = os_time_thread_cputime_us() - frame->time_started; - frame->function->total_exec_time += elapsed; + uint64 time_elapsed = os_time_thread_cputime_us() - frame->time_started; + + frame->function->total_exec_time += time_elapsed; frame->function->total_exec_cnt++; + /* parent function */ if (prev_frame && prev_frame->function) - prev_frame->function->children_exec_time += elapsed; + prev_frame->function->children_exec_time += time_elapsed; } #endif wasm_exec_env_free_wasm_frame(exec_env, frame); @@ -920,20 +1151,35 @@ wasm_interp_call_func_native(WASMModuleInstance *module_inst, { WASMFunctionImport *func_import = cur_func->u.func_import; CApiFuncImport *c_api_func_import = NULL; - unsigned local_cell_num = 2; + unsigned local_cell_num = + cur_func->param_cell_num > 2 ? cur_func->param_cell_num : 2; + unsigned all_cell_num; WASMInterpFrame *frame; uint32 argv_ret[2], cur_func_index; void *native_func_pointer = NULL; bool ret; +#if WASM_ENABLE_GC != 0 + WASMFuncType *func_type; + uint8 *frame_ref; +#endif - if (!(frame = ALLOC_FRAME(exec_env, - wasm_interp_interp_frame_size(local_cell_num), - prev_frame))) + all_cell_num = local_cell_num; +#if WASM_ENABLE_GC != 0 + all_cell_num += (local_cell_num + 3) / 4; +#endif + + if (!(frame = + ALLOC_FRAME(exec_env, wasm_interp_interp_frame_size(all_cell_num), + prev_frame))) return; frame->function = cur_func; frame->ip = NULL; frame->lp = frame->operand; +#if WASM_ENABLE_GC != 0 + frame->frame_ref = (uint8 *)(frame->lp + local_cell_num); + init_frame_refs(frame->frame_ref, local_cell_num, cur_func); +#endif wasm_exec_env_set_cur_frame(exec_env, frame); @@ -983,6 +1229,20 @@ wasm_interp_call_func_native(WASMModuleInstance *module_inst, if (!ret) return; +#if WASM_ENABLE_GC != 0 + func_type = cur_func->u.func_import->func_type; + if (func_type->result_count + && wasm_is_type_reftype(func_type->types[cur_func->param_count]) + && !wasm_is_reftype_i31ref(func_type->types[cur_func->param_count])) { + frame_ref = prev_frame->frame_ref + prev_frame->ret_offset; +#if UINTPTR_MAX == UINT64_MAX + *frame_ref = *(frame_ref + 1) = 1; +#else + *frame_ref = 1; +#endif + } +#endif + if (cur_func->ret_cell_num == 1) { prev_frame->lp[prev_frame->ret_offset] = argv_ret[0]; } @@ -1101,12 +1361,12 @@ wasm_interp_dump_op_count() for (i = 0; i < WASM_OP_IMPDEP; i++) total_count += opcode_table[i].count; - printf("total opcode count: %ld\n", total_count); + os_printf("total opcode count: %ld\n", total_count); for (i = 0; i < WASM_OP_IMPDEP; i++) if (opcode_table[i].count > 0) - printf("\t\t%s count:\t\t%ld,\t\t%.2f%%\n", opcode_table[i].name, - opcode_table[i].count, - opcode_table[i].count * 100.0f / total_count); + os_printf("\t\t%s count:\t\t%ld,\t\t%.2f%%\n", opcode_table[i].name, + opcode_table[i].count, + opcode_table[i].count * 100.0f / total_count); } #endif @@ -1206,6 +1466,11 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, /* cache of label base addr */ register uint8 *label_base = &&HANDLE_WASM_OP_UNREACHABLE; #endif +#endif +#if WASM_ENABLE_GC != 0 + register uint8 *frame_ref = NULL; /* cache of frame->ref */ + uint32 local_cell_num = 0; + int16 opnd_off; #endif uint8 *frame_ip_end = frame_ip + 1; uint32 cond, count, fidx, tidx, frame_size = 0; @@ -1214,7 +1479,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, int32 didx, val; uint8 *maddr = NULL; uint32 local_idx, local_offset, global_idx; - uint8 opcode, local_type, *global_addr; + uint8 opcode = 0, local_type, *global_addr; #if !defined(OS_ENABLE_HW_BOUND_CHECK) \ || WASM_CPU_SUPPORTS_UNALIGNED_ADDR_ACCESS == 0 #if WASM_CONFIGURABLE_BOUNDS_CHECKS != 0 @@ -1224,6 +1489,22 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, bool disable_bounds_checks = false; #endif #endif +#if WASM_ENABLE_GC != 0 + WASMObjectRef gc_obj; + WASMStructObjectRef struct_obj; + WASMArrayObjectRef array_obj; + WASMFuncObjectRef func_obj; + WASMI31ObjectRef i31_obj; + WASMExternrefObjectRef externref_obj; + uint32 type_idx; +#if WASM_ENABLE_STRINGREF != 0 + WASMString str_obj; + WASMStringrefObjectRef stringref_obj; + WASMStringviewWTF8ObjectRef stringview_wtf8_obj; + WASMStringviewWTF16ObjectRef stringview_wtf16_obj; + WASMStringviewIterObjectRef stringview_iter_obj; +#endif +#endif #if WASM_ENABLE_LABELS_AS_VALUES != 0 #define HANDLE_OPCODE(op) &&HANDLE_##op @@ -1338,7 +1619,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_RETURN) { uint32 ret_idx; - WASMType *func_type; + WASMFuncType *func_type; uint32 off, ret_offset; uint8 *ret_types; if (cur_func->is_import_func) @@ -1360,6 +1641,19 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, GET_OPERAND(uint64, I64, off)); ret_offset += 2; } +#if WASM_ENABLE_GC != 0 + else if (wasm_is_type_reftype(ret_types[ret_idx])) { + PUT_REF_TO_ADDR(prev_frame->lp + ret_offset, + GET_OPERAND(void *, REF, off)); + if (!wasm_is_reftype_i31ref(ret_types[ret_idx])) { + *(prev_frame->frame_ref + ret_offset) = 1; +#if UINTPTR_MAX == UINT64_MAX + *(prev_frame->frame_ref + ret_offset + 1) = 1; +#endif + } + ret_offset += REF_CELL_NUM; + } +#endif else { prev_frame->lp[ret_offset] = GET_OPERAND(uint32, I32, off); @@ -1374,7 +1668,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_RETURN_CALL_INDIRECT) #endif { - WASMType *cur_type, *cur_func_type; + WASMFuncType *cur_type, *cur_func_type; WASMTableInstance *tbl_inst; uint32 tbl_idx; @@ -1386,7 +1680,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, #endif tidx = read_uint32(frame_ip); - cur_type = module->module->types[tidx]; + cur_type = (WASMFuncType *)module->module->types[tidx]; tbl_idx = read_uint32(frame_ip); bh_assert(tbl_idx < module->table_count); @@ -1401,11 +1695,22 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, goto got_exception; } + /* clang-format off */ +#if WASM_ENABLE_GC == 0 fidx = tbl_inst->elems[val]; - if (fidx == NULL_REF) { + if (fidx == (uint32)-1) { wasm_set_exception(module, "uninitialized element"); goto got_exception; } +#else + func_obj = (WASMFuncObjectRef)tbl_inst->elems[val]; + if (!func_obj) { + wasm_set_exception(module, "uninitialized element"); + goto got_exception; + } + fidx = wasm_func_obj_get_func_idx_bound(func_obj); +#endif + /* clang-format on */ /* * we might be using a table injected by host or @@ -1425,10 +1730,20 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, else cur_func_type = cur_func->u.func->func_type; + /* clang-format off */ +#if WASM_ENABLE_GC == 0 if (cur_type != cur_func_type) { wasm_set_exception(module, "indirect call type mismatch"); goto got_exception; } +#else + if (cur_type->min_type_idx_normalized + != cur_func_type->min_type_idx_normalized) { + wasm_set_exception(module, "indirect call type mismatch"); + goto got_exception; + } +#endif + /* clang-format on */ #if WASM_ENABLE_TAIL_CALL != 0 if (opcode == WASM_OP_RETURN_CALL_INDIRECT) @@ -1490,7 +1805,44 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP_END(); } -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC != 0 + HANDLE_OP(WASM_OP_SELECT_T) + { + cond = frame_lp[GET_OFFSET()]; + addr1 = GET_OFFSET(); + addr2 = GET_OFFSET(); + addr_ret = GET_OFFSET(); + + if (!cond) { + if (addr_ret != addr1) + PUT_REF_TO_ADDR(frame_lp + addr_ret, + GET_REF_FROM_ADDR(frame_lp + addr1)); + } + else { + if (addr_ret != addr2) + PUT_REF_TO_ADDR(frame_lp + addr_ret, + GET_REF_FROM_ADDR(frame_lp + addr2)); + } + { + uint8 orig_ref = 0; + /* Ignore constants because they are not reference */ + if (addr1 >= 0) { + orig_ref = *FRAME_REF(addr1); + CLEAR_FRAME_REF(addr1); + } + if (addr2 >= 0) { + CLEAR_FRAME_REF(addr2); + } + if (orig_ref) { + SET_FRAME_REF(addr_ret); + } + } + + HANDLE_OP_END(); + } +#endif + +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 HANDLE_OP(WASM_OP_TABLE_GET) { uint32 tbl_idx, elem_idx; @@ -1507,21 +1859,30 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, goto got_exception; } +#if WASM_ENABLE_GC == 0 PUSH_I32(tbl_inst->elems[elem_idx]); +#else + PUSH_REF(tbl_inst->elems[elem_idx]); +#endif HANDLE_OP_END(); } HANDLE_OP(WASM_OP_TABLE_SET) { - uint32 tbl_idx, elem_idx, elem_val; + uint32 tbl_idx, elem_idx; WASMTableInstance *tbl_inst; + table_elem_type_t elem_val; tbl_idx = read_uint32(frame_ip); bh_assert(tbl_idx < module->table_count); tbl_inst = wasm_get_table_inst(module, tbl_idx); +#if WASM_ENABLE_GC == 0 elem_val = POP_I32(); +#else + elem_val = POP_REF(); +#endif elem_idx = POP_I32(); if (elem_idx >= tbl_inst->cur_size) { wasm_set_exception(module, "out of bounds table access"); @@ -1534,14 +1895,23 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_REF_NULL) { +#if WASM_ENABLE_GC == 0 PUSH_I32(NULL_REF); +#else + PUSH_REF(NULL_REF); +#endif HANDLE_OP_END(); } HANDLE_OP(WASM_OP_REF_IS_NULL) { +#if WASM_ENABLE_GC == 0 uint32 ref_val; ref_val = POP_I32(); +#else + void *ref_val; + ref_val = POP_REF(); +#endif PUSH_I32(ref_val == NULL_REF ? 1 : 0); HANDLE_OP_END(); } @@ -1549,23 +1919,1529 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_REF_FUNC) { uint32 func_idx = read_uint32(frame_ip); + +#if WASM_ENABLE_GC == 0 PUSH_I32(func_idx); +#else + SYNC_ALL_TO_FRAME(); + if (!(gc_obj = wasm_create_func_obj(module, func_idx, true, + NULL, 0))) { + goto got_exception; + } + PUSH_REF(gc_obj); +#endif HANDLE_OP_END(); } -#endif /* WASM_ENABLE_REF_TYPES */ +#endif /* end of WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */ + +#if WASM_ENABLE_GC != 0 + HANDLE_OP(WASM_OP_CALL_REF) + { +#if WASM_ENABLE_THREAD_MGR != 0 + CHECK_SUSPEND_FLAGS(); +#endif + func_obj = POP_REF(); + if (!func_obj) { + wasm_set_exception(module, "null function object"); + goto got_exception; + } + + fidx = wasm_func_obj_get_func_idx_bound(func_obj); + cur_func = module->e->functions + fidx; + goto call_func_from_interp; + } + HANDLE_OP(WASM_OP_RETURN_CALL_REF) + { +#if WASM_ENABLE_THREAD_MGR != 0 + CHECK_SUSPEND_FLAGS(); +#endif + func_obj = POP_REF(); + if (!func_obj) { + wasm_set_exception(module, "null function object"); + goto got_exception; + } + + fidx = wasm_func_obj_get_func_idx_bound(func_obj); + cur_func = module->e->functions + fidx; + goto call_func_from_return_call; + } + HANDLE_OP(WASM_OP_REF_AS_NON_NULL) + { + gc_obj = POP_REF(); + if (gc_obj == NULL_REF) { + wasm_set_exception(module, "null reference"); + goto got_exception; + } + PUSH_REF(gc_obj); + HANDLE_OP_END(); + } + HANDLE_OP(WASM_OP_REF_EQ) + { + WASMObjectRef gc_obj1, gc_obj2; + gc_obj2 = POP_REF(); + gc_obj1 = POP_REF(); + val = wasm_obj_equal(gc_obj1, gc_obj2); + PUSH_I32(val); + HANDLE_OP_END(); + } + HANDLE_OP(WASM_OP_BR_ON_NULL) + { +#if WASM_ENABLE_THREAD_MGR != 0 + CHECK_SUSPEND_FLAGS(); +#endif + opnd_off = GET_OFFSET(); + gc_obj = GET_REF_FROM_ADDR(frame_lp + opnd_off); + if (gc_obj == NULL_REF) { + CLEAR_FRAME_REF(opnd_off); + goto recover_br_info; + } + else { + SKIP_BR_INFO(); + } + HANDLE_OP_END(); + } + HANDLE_OP(WASM_OP_BR_ON_NON_NULL) + { +#if WASM_ENABLE_THREAD_MGR != 0 + CHECK_SUSPEND_FLAGS(); +#endif + opnd_off = GET_OFFSET(); + gc_obj = GET_REF_FROM_ADDR(frame_lp + opnd_off); + if (gc_obj != NULL_REF) { + goto recover_br_info; + } + else { + CLEAR_FRAME_REF(opnd_off); + SKIP_BR_INFO(); + } + HANDLE_OP_END(); + } + + HANDLE_OP(WASM_OP_GC_PREFIX) + { + GET_OPCODE(); + + switch (opcode) { + case WASM_OP_STRUCT_NEW: + case WASM_OP_STRUCT_NEW_DEFAULT: + { + WASMModule *wasm_module = module->module; + WASMStructType *struct_type; + WASMRttType *rtt_type; + WASMValue field_value = { 0 }; + + type_idx = read_uint32(frame_ip); + struct_type = + (WASMStructType *)module->module->types[type_idx]; + + if (!(rtt_type = wasm_rtt_type_new( + (WASMType *)struct_type, type_idx, + wasm_module->rtt_types, + wasm_module->type_count, + &wasm_module->rtt_type_lock))) { + wasm_set_exception(module, + "create rtt type failed"); + goto got_exception; + } + + SYNC_ALL_TO_FRAME(); + struct_obj = wasm_struct_obj_new(exec_env, rtt_type); + if (!struct_obj) { + wasm_set_exception(module, + "create struct object failed"); + goto got_exception; + } + + if (opcode == WASM_OP_STRUCT_NEW) { + WASMStructFieldType *fields = struct_type->fields; + int32 field_count = (int32)struct_type->field_count; + int32 field_idx; + uint8 field_type; + + for (field_idx = field_count - 1; field_idx >= 0; + field_idx--) { + field_type = fields[field_idx].field_type; + if (wasm_is_type_reftype(field_type)) { + field_value.gc_obj = POP_REF(); + } + else if (field_type == VALUE_TYPE_I32 + || field_type == VALUE_TYPE_F32 + || field_type == PACKED_TYPE_I8 + || field_type == PACKED_TYPE_I16) { + field_value.i32 = POP_I32(); + } + else { + field_value.i64 = POP_I64(); + } + wasm_struct_obj_set_field(struct_obj, field_idx, + &field_value); + } + } + PUSH_REF(struct_obj); + HANDLE_OP_END(); + } + case WASM_OP_STRUCT_GET: + case WASM_OP_STRUCT_GET_S: + case WASM_OP_STRUCT_GET_U: + { + WASMStructType *struct_type; + WASMValue field_value = { 0 }; + uint32 field_idx; + uint8 field_type; + + type_idx = read_uint32(frame_ip); + field_idx = read_uint32(frame_ip); + + struct_type = + (WASMStructType *)module->module->types[type_idx]; + + struct_obj = POP_REF(); + + if (!struct_obj) { + wasm_set_exception(module, "null structure object"); + goto got_exception; + } + + wasm_struct_obj_get_field( + struct_obj, field_idx, + opcode == WASM_OP_STRUCT_GET_S ? true : false, + &field_value); + + field_type = struct_type->fields[field_idx].field_type; + if (wasm_is_reftype_i31ref(field_type)) { + PUSH_I31REF(field_value.gc_obj); + } + else if (wasm_is_type_reftype(field_type)) { + PUSH_REF(field_value.gc_obj); + } + else if (field_type == VALUE_TYPE_I32 + || field_type == VALUE_TYPE_F32 + || field_type == PACKED_TYPE_I8 + || field_type == PACKED_TYPE_I16) { + PUSH_I32(field_value.i32); + } + else { + PUSH_I64(field_value.i64); + } + HANDLE_OP_END(); + } + case WASM_OP_STRUCT_SET: + { + WASMStructType *struct_type; + WASMValue field_value = { 0 }; + uint32 field_idx; + uint8 field_type; + + type_idx = read_uint32(frame_ip); + field_idx = read_uint32(frame_ip); + + struct_type = + (WASMStructType *)module->module->types[type_idx]; + field_type = struct_type->fields[field_idx].field_type; + + if (wasm_is_type_reftype(field_type)) { + field_value.gc_obj = POP_REF(); + } + else if (field_type == VALUE_TYPE_I32 + || field_type == VALUE_TYPE_F32 + || field_type == PACKED_TYPE_I8 + || field_type == PACKED_TYPE_I16) { + field_value.i32 = POP_I32(); + } + else { + field_value.i64 = POP_I64(); + } + + struct_obj = POP_REF(); + if (!struct_obj) { + wasm_set_exception(module, "null structure object"); + goto got_exception; + } + + wasm_struct_obj_set_field(struct_obj, field_idx, + &field_value); + HANDLE_OP_END(); + } + case WASM_OP_ARRAY_NEW: + case WASM_OP_ARRAY_NEW_DEFAULT: + case WASM_OP_ARRAY_NEW_FIXED: + { + WASMModule *wasm_module = module->module; + WASMArrayType *array_type; + WASMRttType *rtt_type; + WASMValue array_elem = { 0 }; + uint32 array_len, i; + + type_idx = read_uint32(frame_ip); + array_type = + (WASMArrayType *)wasm_module->types[type_idx]; + + if (!(rtt_type = wasm_rtt_type_new( + (WASMType *)array_type, type_idx, + wasm_module->rtt_types, + wasm_module->type_count, + &wasm_module->rtt_type_lock))) { + wasm_set_exception(module, + "create rtt type failed"); + goto got_exception; + } + + if (opcode != WASM_OP_ARRAY_NEW_FIXED) + array_len = POP_I32(); + else + array_len = read_uint32(frame_ip); + + if (opcode == WASM_OP_ARRAY_NEW) { + if (wasm_is_type_reftype(array_type->elem_type)) { + array_elem.gc_obj = POP_REF(); + } + else if (array_type->elem_type == VALUE_TYPE_I32 + || array_type->elem_type == VALUE_TYPE_F32 + || array_type->elem_type == PACKED_TYPE_I8 + || array_type->elem_type + == PACKED_TYPE_I16) { + array_elem.i32 = POP_I32(); + } + else { + array_elem.i64 = POP_I64(); + } + } + + SYNC_ALL_TO_FRAME(); + array_obj = wasm_array_obj_new(exec_env, rtt_type, + array_len, &array_elem); + if (!array_obj) { + wasm_set_exception(module, + "create array object failed"); + goto got_exception; + } + + if (opcode == WASM_OP_ARRAY_NEW_FIXED) { + for (i = 0; i < array_len; i++) { + if (wasm_is_type_reftype( + array_type->elem_type)) { + array_elem.gc_obj = POP_REF(); + } + else if (array_type->elem_type == VALUE_TYPE_I32 + || array_type->elem_type + == VALUE_TYPE_F32 + || array_type->elem_type + == PACKED_TYPE_I8 + || array_type->elem_type + == PACKED_TYPE_I16) { + array_elem.i32 = POP_I32(); + } + else { + array_elem.i64 = POP_I64(); + } + wasm_array_obj_set_elem( + array_obj, array_len - 1 - i, &array_elem); + } + } + + PUSH_REF(array_obj); + HANDLE_OP_END(); + } + case WASM_OP_ARRAY_NEW_DATA: + { + WASMModule *wasm_module = module->module; + WASMArrayType *array_type; + WASMRttType *rtt_type; + WASMValue array_elem = { 0 }; + WASMDataSeg *data_seg; + uint8 *array_elem_base; + uint32 array_len, data_seg_idx, data_seg_offset; + uint32 elem_size = 0; + uint64 total_size; + + type_idx = read_uint32(frame_ip); + data_seg_idx = read_uint32(frame_ip); + data_seg = wasm_module->data_segments[data_seg_idx]; + + array_type = + (WASMArrayType *)wasm_module->types[type_idx]; + + if (!(rtt_type = wasm_rtt_type_new( + (WASMType *)array_type, type_idx, + wasm_module->rtt_types, + wasm_module->type_count, + &wasm_module->rtt_type_lock))) { + wasm_set_exception(module, + "create rtt type failed"); + goto got_exception; + } + + array_len = POP_I32(); + data_seg_offset = POP_I32(); + + switch (array_type->elem_type) { + case PACKED_TYPE_I8: + elem_size = 1; + break; + case PACKED_TYPE_I16: + elem_size = 2; + break; + case VALUE_TYPE_I32: + case VALUE_TYPE_F32: + elem_size = 4; + break; + case VALUE_TYPE_I64: + case VALUE_TYPE_F64: + elem_size = 8; + break; + default: + bh_assert(0); + } + + total_size = (uint64)elem_size * array_len; + if (data_seg_offset >= data_seg->data_length + || total_size + > data_seg->data_length - data_seg_offset) { + wasm_set_exception(module, + "data segment out of bounds"); + goto got_exception; + } + + SYNC_ALL_TO_FRAME(); + array_obj = wasm_array_obj_new(exec_env, rtt_type, + array_len, &array_elem); + if (!array_obj) { + wasm_set_exception(module, + "create array object failed"); + goto got_exception; + } + + array_elem_base = + (uint8 *)wasm_array_obj_first_elem_addr(array_obj); + bh_memcpy_s(array_elem_base, (uint32)total_size, + data_seg->data + data_seg_offset, + (uint32)total_size); + + PUSH_REF(array_obj); + HANDLE_OP_END(); + } + case WASM_OP_ARRAY_NEW_ELEM: + { + /* TODO */ + wasm_set_exception(module, "unsupported opcode"); + goto got_exception; + } + case WASM_OP_ARRAY_GET: + case WASM_OP_ARRAY_GET_S: + case WASM_OP_ARRAY_GET_U: + { + WASMArrayType *array_type; + WASMValue array_elem = { 0 }; + uint32 elem_idx, elem_size_log; + + type_idx = read_uint32(frame_ip); + array_type = + (WASMArrayType *)module->module->types[type_idx]; + + elem_idx = POP_I32(); + array_obj = POP_REF(); + + if (!array_obj) { + wasm_set_exception(module, "null array reference"); + goto got_exception; + } + if (elem_idx >= wasm_array_obj_length(array_obj)) { + wasm_set_exception(module, + "out of bounds array access"); + goto got_exception; + } + + wasm_array_obj_get_elem( + array_obj, elem_idx, + opcode == WASM_OP_ARRAY_GET_S ? true : false, + &array_elem); + elem_size_log = wasm_array_obj_elem_size_log(array_obj); + + if (wasm_is_reftype_i31ref(array_type->elem_type)) { + PUSH_I31REF(array_elem.gc_obj); + } + else if (wasm_is_type_reftype(array_type->elem_type)) { + PUSH_REF(array_elem.gc_obj); + } + else if (elem_size_log < 3) { + PUSH_I32(array_elem.i32); + } + else { + PUSH_I64(array_elem.i64); + } + HANDLE_OP_END(); + } + case WASM_OP_ARRAY_SET: + { + WASMArrayType *array_type; + WASMValue array_elem = { 0 }; + uint32 elem_idx; + + type_idx = read_uint32(frame_ip); + array_type = + (WASMArrayType *)module->module->types[type_idx]; + if (wasm_is_type_reftype(array_type->elem_type)) { + array_elem.gc_obj = POP_REF(); + } + else if (array_type->elem_type == VALUE_TYPE_I32 + || array_type->elem_type == VALUE_TYPE_F32 + || array_type->elem_type == PACKED_TYPE_I8 + || array_type->elem_type == PACKED_TYPE_I16) { + array_elem.i32 = POP_I32(); + } + else { + array_elem.i64 = POP_I64(); + } + + elem_idx = POP_I32(); + array_obj = POP_REF(); + + if (!array_obj) { + wasm_set_exception(module, "null array reference"); + goto got_exception; + } + if (elem_idx >= wasm_array_obj_length(array_obj)) { + wasm_set_exception(module, + "out of bounds array access"); + goto got_exception; + } + + wasm_array_obj_set_elem(array_obj, elem_idx, + &array_elem); + HANDLE_OP_END(); + } + case WASM_OP_ARRAY_LEN: + { + uint32 array_len; + array_obj = POP_REF(); + if (!array_obj) { + wasm_set_exception(module, "null array reference"); + goto got_exception; + } + array_len = wasm_array_obj_length(array_obj); + PUSH_I32(array_len); + HANDLE_OP_END(); + } + case WASM_OP_ARRAY_FILL: + { + WASMArrayType *array_type; + WASMValue fill_value = { 0 }; + uint32 start_offset, len; + + type_idx = read_uint32(frame_ip); + + array_type = + (WASMArrayType *)module->module->types[type_idx]; + + len = POP_I32(); + if (wasm_is_type_reftype(array_type->elem_type)) { + fill_value.gc_obj = POP_REF(); + } + else if (array_type->elem_type == VALUE_TYPE_I32 + || array_type->elem_type == VALUE_TYPE_F32 + || array_type->elem_type == PACKED_TYPE_I8 + || array_type->elem_type == PACKED_TYPE_I16) { + fill_value.i32 = POP_I32(); + } + else { + fill_value.i64 = POP_I64(); + } + start_offset = POP_I32(); + array_obj = POP_REF(); + + if (!array_obj) { + wasm_set_exception(module, "null array reference"); + goto got_exception; + } + + if (len > 0) { + if ((uint64)start_offset + len + >= wasm_array_obj_length(array_obj)) { + wasm_set_exception( + module, "out of bounds array access"); + goto got_exception; + } + + wasm_array_obj_fill(array_obj, start_offset, len, + &fill_value); + } + + HANDLE_OP_END(); + } + case WASM_OP_ARRAY_COPY: + { + uint32 dst_offset, src_offset, len, src_type_index; + WASMArrayObjectRef src_obj, dst_obj; + + type_idx = read_uint32(frame_ip); + src_type_index = read_uint32(frame_ip); + + len = POP_I32(); + src_offset = POP_I32(); + src_obj = POP_REF(); + dst_offset = POP_I32(); + dst_obj = POP_REF(); + + if (!src_obj || !dst_obj) { + wasm_set_exception(module, "null array reference"); + goto got_exception; + } + + if (len > 0) { + if ((dst_offset > UINT32_MAX - len) + || (dst_offset + len + > wasm_array_obj_length(dst_obj)) + || (src_offset > UINT32_MAX - len) + || (src_offset + len + > wasm_array_obj_length(src_obj))) { + wasm_set_exception( + module, "out of bounds array access"); + goto got_exception; + } + + wasm_array_obj_copy(dst_obj, dst_offset, src_obj, + src_offset, len); + } + + (void)src_type_index; + HANDLE_OP_END(); + } + + case WASM_OP_REF_I31: + { + uint32 i31_val; + + i31_val = POP_I32(); + i31_obj = wasm_i31_obj_new(i31_val); + PUSH_I31REF(i31_obj); + HANDLE_OP_END(); + } + case WASM_OP_I31_GET_S: + case WASM_OP_I31_GET_U: + { + uint32 i31_val; + + i31_obj = (WASMI31ObjectRef)POP_REF(); + if (!i31_obj) { + wasm_set_exception(module, "null i31 reference"); + goto got_exception; + } + i31_val = (uint32)(((uintptr_t)i31_obj) >> 1); + if (opcode == WASM_OP_I31_GET_S + && (i31_val & 0x40000000) /* bit 30 is 1 */) + /* set bit 31 to 1 */ + i31_val |= 0x80000000; + PUSH_I32(i31_val); + HANDLE_OP_END(); + } + + case WASM_OP_REF_TEST: + case WASM_OP_REF_CAST: + case WASM_OP_REF_TEST_NULLABLE: + case WASM_OP_REF_CAST_NULLABLE: + { + int32 heap_type; + + heap_type = (int32)read_uint32(frame_ip); + + gc_obj = POP_REF(); + if (!gc_obj) { + if (opcode == WASM_OP_REF_TEST + || opcode == WASM_OP_REF_TEST_NULLABLE) { + if (opcode == WASM_OP_REF_TEST) + PUSH_I32(0); + else + PUSH_I32(1); + } + else if (opcode == WASM_OP_REF_CAST) { + wasm_set_exception(module, "cast failure"); + goto got_exception; + } + else { + PUSH_REF(gc_obj); + } + } + else { + bool castable = false; + + if (heap_type >= 0) { + WASMModule *wasm_module = module->module; + castable = wasm_obj_is_instance_of( + gc_obj, (uint32)heap_type, + wasm_module->types, + wasm_module->type_count); + } + else { + castable = + wasm_obj_is_type_of(gc_obj, heap_type); + } + + if (opcode == WASM_OP_REF_TEST + || opcode == WASM_OP_REF_TEST_NULLABLE) { + if (castable) + PUSH_I32(1); + else + PUSH_I32(0); + } + else if (!castable) { + wasm_set_exception(module, "cast failure"); + goto got_exception; + } + else { + PUSH_REF(gc_obj); + } + } + HANDLE_OP_END(); + } + + case WASM_OP_BR_ON_CAST: + case WASM_OP_BR_ON_CAST_FAIL: + { + int32 heap_type, heap_type_dst; + uint8 castflags; + uint16 opnd_off_br; + +#if WASM_ENABLE_THREAD_MGR != 0 + CHECK_SUSPEND_FLAGS(); +#endif + castflags = *frame_ip++; + heap_type = (int32)read_uint32(frame_ip); + heap_type_dst = (int32)read_uint32(frame_ip); + + opnd_off = GET_OFFSET(); + opnd_off_br = GET_OFFSET(); + gc_obj = GET_REF_FROM_ADDR(frame_lp + opnd_off); + PUT_REF_TO_ADDR(frame_lp + opnd_off_br, gc_obj); + + if (!gc_obj) { + /* + * castflags should be 0~3: + * 0: (non-null, non-null) + * 1: (null, non-null) + * 2: (non-null, null) + * 3: (null, null) + */ + if ( + /* op is BR_ON_CAST and dst reftype is nullable + */ + ((opcode == WASM_OP_BR_ON_CAST) + && ((castflags == 2) || (castflags == 3))) + /* op is BR_ON_CAST_FAIL and dst reftype is + non-nullable */ + || ((opcode == WASM_OP_BR_ON_CAST_FAIL) + && ((castflags == 0) + || (castflags == 1)))) { + CLEAR_FRAME_REF(opnd_off); + if (!wasm_is_reftype_i31ref(heap_type)) { + SET_FRAME_REF(opnd_off_br); + } + goto recover_br_info; + } + } + else { + bool castable = false; + + if (heap_type_dst >= 0) { + WASMModule *wasm_module = module->module; + castable = wasm_obj_is_instance_of( + gc_obj, (uint32)heap_type_dst, + wasm_module->types, + wasm_module->type_count); + } + else { + castable = + wasm_obj_is_type_of(gc_obj, heap_type_dst); + } + + if ((castable && (opcode == WASM_OP_BR_ON_CAST)) + || (!castable + && (opcode == WASM_OP_BR_ON_CAST_FAIL))) { + CLEAR_FRAME_REF(opnd_off); + if (!wasm_is_reftype_i31ref(heap_type)) { + SET_FRAME_REF(opnd_off_br); + } + goto recover_br_info; + } + } + SKIP_BR_INFO(); + + (void)heap_type_dst; + HANDLE_OP_END(); + } + + case WASM_OP_ANY_CONVERT_EXTERN: + { + externref_obj = POP_REF(); + if (externref_obj == NULL_REF) + PUSH_REF(NULL_REF); + else { + gc_obj = wasm_externref_obj_to_internal_obj( + externref_obj); + PUSH_REF(gc_obj); + } + HANDLE_OP_END(); + } + case WASM_OP_EXTERN_CONVERT_ANY: + { + gc_obj = POP_REF(); + if (gc_obj == NULL_REF) + PUSH_REF(NULL_REF); + else { + if (!(externref_obj = + wasm_internal_obj_to_externref_obj( + exec_env, gc_obj))) { + wasm_set_exception( + module, "create externref object failed"); + goto got_exception; + } + PUSH_REF(externref_obj); + } + HANDLE_OP_END(); + } + +#if WASM_ENABLE_STRINGREF != 0 + case WASM_OP_STRING_NEW_UTF8: + case WASM_OP_STRING_NEW_WTF16: + case WASM_OP_STRING_NEW_LOSSY_UTF8: + case WASM_OP_STRING_NEW_WTF8: + { + uint32 mem_idx, addr, bytes_length, offset = 0; + EncodingFlag flag = WTF8; + + mem_idx = (uint32)read_uint32(frame_ip); + bytes_length = POP_I32(); + addr = POP_I32(); + + CHECK_MEMORY_OVERFLOW(bytes_length); + + if (opcode == WASM_OP_STRING_NEW_WTF16) { + flag = WTF16; + } + else if (opcode == WASM_OP_STRING_NEW_UTF8) { + flag = UTF8; + } + else if (opcode == WASM_OP_STRING_NEW_LOSSY_UTF8) { + flag = LOSSY_UTF8; + } + else if (opcode == WASM_OP_STRING_NEW_WTF8) { + flag = WTF8; + } + + str_obj = wasm_string_new_with_encoding( + maddr, bytes_length, flag); + if (!str_obj) { + wasm_set_exception(module, + "create string object failed"); + goto got_exception; + } + + SYNC_ALL_TO_FRAME(); + stringref_obj = + wasm_stringref_obj_new(exec_env, str_obj); + if (!stringref_obj) { + wasm_set_exception(module, + "create stringref failed"); + goto got_exception; + } + + PUSH_REF(stringref_obj); + + (void)mem_idx; + HANDLE_OP_END(); + } + case WASM_OP_STRING_CONST: + { + WASMModule *wasm_module = module->module; + uint32 contents; + + contents = (uint32)read_uint32(frame_ip); + + str_obj = wasm_string_new_const( + (const char *) + wasm_module->string_literal_ptrs[contents], + wasm_module->string_literal_lengths[contents]); + if (!str_obj) { + wasm_set_exception(module, + "create string object failed"); + goto got_exception; + } + + SYNC_ALL_TO_FRAME(); + stringref_obj = + wasm_stringref_obj_new(exec_env, str_obj); + if (!str_obj) { + wasm_set_exception(module, + "create stringref failed"); + goto got_exception; + } + + PUSH_REF(stringref_obj); + HANDLE_OP_END(); + } + case WASM_OP_STRING_MEASURE_UTF8: + case WASM_OP_STRING_MEASURE_WTF8: + case WASM_OP_STRING_MEASURE_WTF16: + { + int32 target_bytes_length; + EncodingFlag flag = WTF8; + + stringref_obj = POP_REF(); + + if (opcode == WASM_OP_STRING_MEASURE_WTF16) { + flag = WTF16; + } + else if (opcode == WASM_OP_STRING_MEASURE_UTF8) { + flag = UTF8; + } + else if (opcode == WASM_OP_STRING_MEASURE_WTF8) { + flag = LOSSY_UTF8; + } + target_bytes_length = wasm_string_measure( + (WASMString)wasm_stringref_obj_get_value( + stringref_obj), + flag); + + PUSH_I32(target_bytes_length); + HANDLE_OP_END(); + } + case WASM_OP_STRING_ENCODE_UTF8: + case WASM_OP_STRING_ENCODE_WTF16: + case WASM_OP_STRING_ENCODE_LOSSY_UTF8: + case WASM_OP_STRING_ENCODE_WTF8: + { + uint32 mem_idx, addr; + int32 target_bytes_length; + WASMMemoryInstance *memory_inst; + EncodingFlag flag = WTF8; + + mem_idx = (uint32)read_uint32(frame_ip); + addr = POP_I32(); + stringref_obj = POP_REF(); + + str_obj = (WASMString)wasm_stringref_obj_get_value( + stringref_obj); + + memory_inst = module->memories[mem_idx]; + maddr = memory_inst->memory_data + addr; + + if (opcode == WASM_OP_STRING_ENCODE_WTF16) { + flag = WTF16; + count = wasm_string_measure(str_obj, flag); + target_bytes_length = wasm_string_encode( + str_obj, 0, count, maddr, NULL, flag); + } + else { + if (opcode == WASM_OP_STRING_ENCODE_UTF8) { + flag = UTF8; + } + else if (opcode + == WASM_OP_STRING_ENCODE_LOSSY_UTF8) { + flag = LOSSY_UTF8; + } + else if (opcode == WASM_OP_STRING_ENCODE_WTF8) { + flag = WTF8; + } + count = wasm_string_measure(str_obj, flag); + target_bytes_length = wasm_string_encode( + str_obj, 0, count, maddr, NULL, flag); + + if (target_bytes_length == -1) { + wasm_set_exception( + module, "isolated surrogate is seen"); + goto got_exception; + } + } + if (target_bytes_length < 0) { + wasm_set_exception(module, + "stringref encode failed"); + goto got_exception; + } + + PUSH_I32(target_bytes_length); + HANDLE_OP_END(); + } + case WASM_OP_STRING_CONCAT: + { + WASMStringrefObjectRef stringref_obj1, stringref_obj2; + + stringref_obj2 = POP_REF(); + stringref_obj1 = POP_REF(); + + str_obj = wasm_string_concat( + (WASMString)wasm_stringref_obj_get_value( + stringref_obj1), + (WASMString)wasm_stringref_obj_get_value( + stringref_obj2)); + if (!str_obj) { + wasm_set_exception(module, + "create string object failed"); + goto got_exception; + } + + SYNC_ALL_TO_FRAME(); + stringref_obj = + wasm_stringref_obj_new(exec_env, str_obj); + if (!stringref_obj) { + wasm_set_exception(module, + "create stringref failed"); + goto got_exception; + } + + PUSH_REF(stringref_obj); + HANDLE_OP_END(); + } + case WASM_OP_STRING_EQ: + { + WASMStringrefObjectRef stringref_obj1, stringref_obj2; + int32 is_eq; + + stringref_obj2 = POP_REF(); + stringref_obj1 = POP_REF(); + + is_eq = wasm_string_eq( + (WASMString)wasm_stringref_obj_get_value( + stringref_obj1), + (WASMString)wasm_stringref_obj_get_value( + stringref_obj2)); + + PUSH_I32(is_eq); + HANDLE_OP_END(); + } + case WASM_OP_STRING_IS_USV_SEQUENCE: + { + int32 is_usv_sequence; + + stringref_obj = POP_REF(); + + is_usv_sequence = wasm_string_is_usv_sequence( + (WASMString)wasm_stringref_obj_get_value( + stringref_obj)); + + PUSH_I32(is_usv_sequence); + HANDLE_OP_END(); + } + case WASM_OP_STRING_AS_WTF8: + { + stringref_obj = POP_REF(); + + str_obj = wasm_string_create_view( + (WASMString)wasm_stringref_obj_get_value( + stringref_obj), + STRING_VIEW_WTF8); + if (!str_obj) { + wasm_set_exception(module, + "create string object failed"); + goto got_exception; + } + + SYNC_ALL_TO_FRAME(); + stringview_wtf8_obj = + wasm_stringview_wtf8_obj_new(exec_env, str_obj); + if (!stringview_wtf8_obj) { + wasm_set_exception(module, + "create stringview wtf8 failed"); + goto got_exception; + } + + PUSH_REF(stringview_wtf8_obj); + HANDLE_OP_END(); + } + case WASM_OP_STRINGVIEW_WTF8_ADVANCE: + { + uint32 next_pos, bytes, pos; + + bytes = POP_I32(); + pos = POP_I32(); + stringview_wtf8_obj = POP_REF(); + + next_pos = wasm_string_advance( + (WASMString)wasm_stringview_wtf8_obj_get_value( + stringview_wtf8_obj), + pos, bytes, NULL); + + PUSH_I32(next_pos); + HANDLE_OP_END(); + } + case WASM_OP_STRINGVIEW_WTF8_ENCODE_UTF8: + case WASM_OP_STRINGVIEW_WTF8_ENCODE_LOSSY_UTF8: + case WASM_OP_STRINGVIEW_WTF8_ENCODE_WTF8: + { + uint32 mem_idx, addr, pos, bytes, next_pos; + int32 bytes_written; + WASMMemoryInstance *memory_inst; + EncodingFlag flag = WTF8; + + if (opcode == WASM_OP_STRINGVIEW_WTF8_ENCODE_UTF8) { + flag = UTF8; + } + else if (opcode + == WASM_OP_STRINGVIEW_WTF8_ENCODE_LOSSY_UTF8) { + flag = LOSSY_UTF8; + } + else if (opcode + == WASM_OP_STRINGVIEW_WTF8_ENCODE_WTF8) { + flag = WTF8; + } + + mem_idx = (uint32)read_uint32(frame_ip); + bytes = POP_I32(); + pos = POP_I32(); + addr = POP_I32(); + stringview_wtf8_obj = POP_REF(); + + memory_inst = module->memories[mem_idx]; + maddr = memory_inst->memory_data + addr; + + bytes_written = wasm_string_encode( + (WASMString)wasm_stringview_wtf8_obj_get_value( + stringview_wtf8_obj), + pos, bytes, maddr, &next_pos, flag); + + if (bytes_written < 0) { + if (bytes_written == Isolated_Surrogate) { + wasm_set_exception( + module, "isolated surrogate is seen"); + } + else { + wasm_set_exception(module, "encode failed"); + } + + goto got_exception; + } + + PUSH_I32(next_pos); + PUSH_I32(bytes_written); + HANDLE_OP_END(); + } + case WASM_OP_STRINGVIEW_WTF8_SLICE: + { + uint32 start, end; + + end = POP_I32(); + start = POP_I32(); + stringview_wtf8_obj = POP_REF(); + + str_obj = wasm_string_slice( + (WASMString)wasm_stringview_wtf8_obj_get_value( + stringview_wtf8_obj), + start, end, STRING_VIEW_WTF8); + if (!str_obj) { + wasm_set_exception(module, + "create string object failed"); + goto got_exception; + } + + SYNC_ALL_TO_FRAME(); + stringref_obj = + wasm_stringref_obj_new(exec_env, str_obj); + if (!stringref_obj) { + wasm_set_exception(module, + "create stringref failed"); + goto got_exception; + } + + PUSH_REF(stringref_obj); + HANDLE_OP_END(); + } + case WASM_OP_STRING_AS_WTF16: + { + stringref_obj = POP_REF(); + + str_obj = wasm_string_create_view( + (WASMString)wasm_stringref_obj_get_value( + stringref_obj), + STRING_VIEW_WTF16); + if (!str_obj) { + wasm_set_exception(module, + "create string object failed"); + goto got_exception; + } + + SYNC_ALL_TO_FRAME(); + stringview_wtf16_obj = + wasm_stringview_wtf16_obj_new(exec_env, str_obj); + if (!stringview_wtf16_obj) { + wasm_set_exception( + module, "create stringview wtf16 failed"); + goto got_exception; + } + + PUSH_REF(stringview_wtf16_obj); + HANDLE_OP_END(); + } + case WASM_OP_STRINGVIEW_WTF16_LENGTH: + { + int32 code_units_length; + + stringview_wtf16_obj = POP_REF(); + + code_units_length = wasm_string_wtf16_get_length( + (WASMString)wasm_stringview_wtf16_obj_get_value( + stringview_wtf16_obj)); + + PUSH_I32(code_units_length); + HANDLE_OP_END(); + } + case WASM_OP_STRINGVIEW_WTF16_GET_CODEUNIT: + { + int32 pos; + uint32 code_unit; + + pos = POP_I32(); + stringview_wtf16_obj = POP_REF(); + + code_unit = (uint32)wasm_string_get_wtf16_codeunit( + (WASMString)wasm_stringview_wtf16_obj_get_value( + stringview_wtf16_obj), + pos); + + PUSH_I32(code_unit); + HANDLE_OP_END(); + } + case WASM_OP_STRINGVIEW_WTF16_ENCODE: + { + uint32 mem_idx, addr, pos, len, offset = 0; + int32 written_code_units = 0; + + mem_idx = (uint32)read_uint32(frame_ip); + len = POP_I32(); + pos = POP_I32(); + addr = POP_I32(); + stringview_wtf16_obj = POP_REF(); + + CHECK_MEMORY_OVERFLOW(len * sizeof(uint16)); + + /* check 2-byte alignment */ + if (((uintptr_t)maddr & (((uintptr_t)1 << 2) - 1)) + != 0) { + wasm_set_exception(module, + "unaligned memory access"); + goto got_exception; + } + + written_code_units = wasm_string_encode( + (WASMString)wasm_stringview_wtf16_obj_get_value( + stringview_wtf16_obj), + pos, len, maddr, NULL, WTF16); + + PUSH_I32(written_code_units); + (void)mem_idx; + HANDLE_OP_END(); + } + case WASM_OP_STRINGVIEW_WTF16_SLICE: + { + uint32 start, end; + + end = POP_I32(); + start = POP_I32(); + stringview_wtf16_obj = POP_REF(); + + str_obj = wasm_string_slice( + (WASMString)wasm_stringview_wtf16_obj_get_value( + stringview_wtf16_obj), + start, end, STRING_VIEW_WTF16); + if (!str_obj) { + wasm_set_exception(module, + "create string object failed"); + goto got_exception; + } + + SYNC_ALL_TO_FRAME(); + stringref_obj = + wasm_stringref_obj_new(exec_env, str_obj); + if (!stringref_obj) { + wasm_set_exception(module, + "create stringref failed"); + goto got_exception; + } + + PUSH_REF(stringref_obj); + HANDLE_OP_END(); + } + case WASM_OP_STRING_AS_ITER: + { + stringref_obj = POP_REF(); + + str_obj = wasm_string_create_view( + (WASMString)wasm_stringref_obj_get_value( + stringref_obj), + STRING_VIEW_ITER); + + if (!str_obj) { + wasm_set_exception(module, + "create string object failed"); + goto got_exception; + } + + SYNC_ALL_TO_FRAME(); + stringview_iter_obj = + wasm_stringview_iter_obj_new(exec_env, str_obj, 0); + if (!stringview_iter_obj) { + wasm_set_exception(module, + "create stringview iter failed"); + goto got_exception; + } + + PUSH_REF(stringview_iter_obj); + HANDLE_OP_END(); + } + case WASM_OP_STRINGVIEW_ITER_NEXT: + { + uint32 code_point; + + stringview_iter_obj = POP_REF(); + + code_point = wasm_string_next_codepoint( + (WASMString)wasm_stringview_iter_obj_get_value( + stringview_iter_obj), + wasm_stringview_iter_obj_get_pos( + stringview_iter_obj)); + + PUSH_I32(code_point); + HANDLE_OP_END(); + } + case WASM_OP_STRINGVIEW_ITER_ADVANCE: + case WASM_OP_STRINGVIEW_ITER_REWIND: + { + uint32 code_points_count, code_points_consumed = 0, + cur_pos, next_pos = 0; + + code_points_count = POP_I32(); + stringview_iter_obj = POP_REF(); + + str_obj = + (WASMString)wasm_stringview_iter_obj_get_value( + stringview_iter_obj); + cur_pos = wasm_stringview_iter_obj_get_pos( + stringview_iter_obj); + + if (opcode == WASM_OP_STRINGVIEW_ITER_ADVANCE) { + next_pos = wasm_string_advance( + str_obj, cur_pos, code_points_count, + &code_points_consumed); + } + else if (opcode == WASM_OP_STRINGVIEW_ITER_REWIND) { + next_pos = wasm_string_rewind( + str_obj, cur_pos, code_points_count, + &code_points_consumed); + } + + wasm_stringview_iter_obj_update_pos(stringview_iter_obj, + next_pos); + + PUSH_I32(code_points_consumed); + HANDLE_OP_END(); + } + case WASM_OP_STRINGVIEW_ITER_SLICE: + { + uint32 code_points_count, cur_pos; + + code_points_count = POP_I32(); + stringview_iter_obj = POP_REF(); + + cur_pos = wasm_stringview_iter_obj_get_pos( + stringview_iter_obj); + + str_obj = wasm_string_slice( + (WASMString)wasm_stringview_iter_obj_get_value( + stringview_iter_obj), + cur_pos, cur_pos + code_points_count, + STRING_VIEW_ITER); + if (!str_obj) { + wasm_set_exception(module, + "create string object failed"); + goto got_exception; + } + + SYNC_ALL_TO_FRAME(); + stringref_obj = + wasm_stringref_obj_new(exec_env, str_obj); + if (!stringref_obj) { + wasm_set_exception(module, + "create stringref failed"); + goto got_exception; + } + + PUSH_REF(stringref_obj); + HANDLE_OP_END(); + } + case WASM_OP_STRING_NEW_UTF8_ARRAY: + case WASM_OP_STRING_NEW_WTF16_ARRAY: + case WASM_OP_STRING_NEW_LOSSY_UTF8_ARRAY: + case WASM_OP_STRING_NEW_WTF8_ARRAY: + { + uint32 start, end, array_len; + EncodingFlag flag = WTF8; + WASMArrayType *array_type; + void *arr_start_addr; + + end = POP_I32(); + start = POP_I32(); + array_obj = POP_REF(); + + array_type = (WASMArrayType *)wasm_obj_get_defined_type( + (WASMObjectRef)array_obj); + arr_start_addr = + wasm_array_obj_elem_addr(array_obj, start); + array_len = wasm_array_obj_length(array_obj); + + if (start > end || end > array_len) { + wasm_set_exception(module, + "out of bounds array access"); + goto got_exception; + } + + if (opcode == WASM_OP_STRING_NEW_WTF16_ARRAY) { + if (array_type->elem_type != VALUE_TYPE_I16) { + wasm_set_exception(module, + "array type mismatch"); + goto got_exception; + } + flag = WTF16; + } + else { + if (array_type->elem_type != VALUE_TYPE_I8) { + wasm_set_exception(module, + "array type mismatch"); + goto got_exception; + } + if (opcode == WASM_OP_STRING_NEW_UTF8_ARRAY) { + flag = UTF8; + } + else if (opcode == WASM_OP_STRING_NEW_WTF8_ARRAY) { + flag = WTF8; + } + else if (opcode + == WASM_OP_STRING_NEW_LOSSY_UTF8_ARRAY) { + flag = LOSSY_UTF8; + } + } + + str_obj = wasm_string_new_with_encoding( + arr_start_addr, (end - start), flag); + if (!str_obj) { + wasm_set_exception(module, + "create string object failed"); + goto got_exception; + } + + SYNC_ALL_TO_FRAME(); + stringref_obj = + wasm_stringref_obj_new(exec_env, str_obj); + if (!stringref_obj) { + wasm_set_exception(module, + "create stringref failed"); + goto got_exception; + } + + PUSH_REF(stringref_obj); + HANDLE_OP_END(); + } + case WASM_OP_STRING_ENCODE_UTF8_ARRAY: + case WASM_OP_STRING_ENCODE_WTF16_ARRAY: + case WASM_OP_STRING_ENCODE_LOSSY_UTF8_ARRAY: + case WASM_OP_STRING_ENCODE_WTF8_ARRAY: + { + uint32 start, array_len, count; + int32 bytes_written; + EncodingFlag flag = WTF8; + WASMArrayType *array_type; + void *arr_start_addr; + + start = POP_I32(); + array_obj = POP_REF(); + stringref_obj = POP_REF(); + + str_obj = (WASMString)wasm_stringref_obj_get_value( + stringref_obj); + + array_type = (WASMArrayType *)wasm_obj_get_defined_type( + (WASMObjectRef)array_obj); + arr_start_addr = + wasm_array_obj_elem_addr(array_obj, start); + array_len = wasm_array_obj_length(array_obj); + + if (start > array_len) { + wasm_set_exception(module, + "out of bounds array access"); + goto got_exception; + } + + if (opcode == WASM_OP_STRING_ENCODE_WTF16_ARRAY) { + if (array_type->elem_type != VALUE_TYPE_I16) { + wasm_set_exception(module, + "array type mismatch"); + goto got_exception; + } + flag = WTF16; + } + else { + if (array_type->elem_type != VALUE_TYPE_I8) { + wasm_set_exception(module, + "array type mismatch"); + goto got_exception; + } + if (opcode == WASM_OP_STRING_ENCODE_UTF8_ARRAY) { + flag = UTF8; + } + else if (opcode + == WASM_OP_STRING_ENCODE_WTF8_ARRAY) { + flag = WTF8; + } + else if ( + opcode + == WASM_OP_STRING_ENCODE_LOSSY_UTF8_ARRAY) { + flag = LOSSY_UTF8; + } + } + + count = wasm_string_measure(str_obj, flag); + + bytes_written = wasm_string_encode( + str_obj, 0, count, arr_start_addr, NULL, flag); + + if (bytes_written < 0) { + if (bytes_written == Isolated_Surrogate) { + wasm_set_exception( + module, "isolated surrogate is seen"); + } + else if (bytes_written == Insufficient_Space) { + wasm_set_exception( + module, "array space is insufficient"); + } + else { + wasm_set_exception(module, "encode failed"); + } + + goto got_exception; + } + + PUSH_I32(bytes_written); + HANDLE_OP_END(); + } +#endif /* end of WASM_ENABLE_STRINGREF != 0 */ + + default: + { + wasm_set_exception(module, "unsupported opcode"); + goto got_exception; + } + } + } +#endif /* end of WASM_ENABLE_GC != 0 */ /* variable instructions */ HANDLE_OP(EXT_OP_SET_LOCAL_FAST) HANDLE_OP(EXT_OP_TEE_LOCAL_FAST) { + /* clang-format off */ #if WASM_CPU_SUPPORTS_UNALIGNED_ADDR_ACCESS != 0 - local_offset = *frame_ip++; + local_offset = *frame_ip++; #else - /* clang-format off */ - local_offset = *frame_ip; - frame_ip += 2; - /* clang-format on */ + local_offset = *frame_ip; + frame_ip += 2; #endif + /* clang-format on */ *(uint32 *)(frame_lp + local_offset) = GET_OPERAND(uint32, I32, 0); frame_ip += 2; @@ -1575,14 +3451,14 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(EXT_OP_SET_LOCAL_FAST_I64) HANDLE_OP(EXT_OP_TEE_LOCAL_FAST_I64) { + /* clang-format off */ #if WASM_CPU_SUPPORTS_UNALIGNED_ADDR_ACCESS != 0 - local_offset = *frame_ip++; + local_offset = *frame_ip++; #else - /* clang-format off */ - local_offset = *frame_ip; - frame_ip += 2; - /* clang-format on */ + local_offset = *frame_ip; + frame_ip += 2; #endif + /* clang-format on */ PUT_I64_TO_ADDR((uint32 *)(frame_lp + local_offset), GET_OPERAND(uint64, I64, 0)); frame_ip += 2; @@ -1596,7 +3472,21 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, global = globals + global_idx; global_addr = get_global_addr(global_data, global); addr_ret = GET_OFFSET(); + /* clang-format off */ +#if WASM_ENABLE_GC == 0 frame_lp[addr_ret] = *(uint32 *)global_addr; +#else + if (!wasm_is_type_reftype(global->type)) + frame_lp[addr_ret] = *(uint32 *)global_addr; + else { + PUT_REF_TO_ADDR(frame_lp + addr_ret, + GET_REF_FROM_ADDR((uint32 *)global_addr)); + if (!wasm_is_reftype_i31ref(global->type)) { + SET_FRAME_REF(addr_ret); + } + } +#endif + /* clang-format on */ HANDLE_OP_END(); } @@ -1619,7 +3509,19 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, global = globals + global_idx; global_addr = get_global_addr(global_data, global); addr1 = GET_OFFSET(); + /* clang-format off */ +#if WASM_ENABLE_GC == 0 *(int32 *)global_addr = frame_lp[addr1]; +#else + if (!wasm_is_type_reftype(global->type)) + *(int32 *)global_addr = frame_lp[addr1]; + else { + PUT_REF_TO_ADDR((uint32 *)global_addr, + GET_REF_FROM_ADDR(frame_lp + addr1)); + CLEAR_FRAME_REF(addr1); + } +#endif + /* clang-format on */ HANDLE_OP_END(); } @@ -2874,6 +4776,17 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, addr1 = GET_OFFSET(); addr2 = GET_OFFSET(); frame_lp[addr2] = frame_lp[addr1]; + +#if WASM_ENABLE_GC != 0 + /* Ignore constants because they are not reference */ + if (addr1 >= 0) { + if (*FRAME_REF(addr1)) { + CLEAR_FRAME_REF(addr1); + SET_FRAME_REF(addr2); + } + } +#endif + HANDLE_OP_END(); } @@ -2881,8 +4794,20 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, { addr1 = GET_OFFSET(); addr2 = GET_OFFSET(); - frame_lp[addr2] = frame_lp[addr1]; - frame_lp[addr2 + 1] = frame_lp[addr1 + 1]; + + PUT_I64_TO_ADDR(frame_lp + addr2, + GET_I64_FROM_ADDR(frame_lp + addr1)); + +#if WASM_ENABLE_GC != 0 + /* Ignore constants because they are not reference */ + if (addr1 >= 0) { + if (*FRAME_REF(addr1)) { + CLEAR_FRAME_REF(addr1); + SET_FRAME_REF(addr2); + } + } +#endif + HANDLE_OP_END(); } @@ -2908,6 +4833,9 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, frame_ip += values_count * sizeof(uint16); if (!copy_stack_values(module, frame_lp, values_count, +#if WASM_ENABLE_GC != 0 + frame_ref, +#endif total_cell, cells, src_offsets, dst_offsets)) goto got_exception; @@ -2916,8 +4844,15 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, } HANDLE_OP(WASM_OP_SET_LOCAL) + { + opcode = WASM_OP_SET_LOCAL; + goto handle_op_set_tee_local; + } HANDLE_OP(WASM_OP_TEE_LOCAL) { + opcode = WASM_OP_TEE_LOCAL; + handle_op_set_tee_local: + GET_LOCAL_INDEX_TYPE_AND_OFFSET(); addr1 = GET_OFFSET(); @@ -2930,6 +4865,15 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, PUT_I64_TO_ADDR((uint32 *)(frame_lp + local_offset), GET_I64_FROM_ADDR(frame_lp + addr1)); } +#if WASM_ENABLE_GC != 0 + else if (wasm_is_type_reftype(local_type)) { + PUT_REF_TO_ADDR((uint32 *)(frame_lp + local_offset), + GET_REF_FROM_ADDR(frame_lp + addr1)); + if (opcode == WASM_OP_SET_LOCAL) { + CLEAR_FRAME_REF(addr1); + } + } +#endif else { wasm_set_exception(module, "invalid local type"); goto got_exception; @@ -3017,7 +4961,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, offset = (uint64)(uint32)POP_I32(); addr = POP_I32(); -#if WASM_ENABLE_THREAD_MGR +#if WASM_ENABLE_THREAD_MGR != 0 linear_mem_size = get_linear_mem_size(); #endif @@ -3065,7 +5009,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, src = POP_I32(); dst = POP_I32(); -#if WASM_ENABLE_THREAD_MGR +#if WASM_ENABLE_THREAD_MGR != 0 linear_mem_size = get_linear_mem_size(); #endif @@ -3095,7 +5039,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, fill_val = POP_I32(); dst = POP_I32(); -#if WASM_ENABLE_THREAD_MGR +#if WASM_ENABLE_THREAD_MGR != 0 linear_mem_size = get_linear_mem_size(); #endif @@ -3111,13 +5055,17 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, break; } #endif /* WASM_ENABLE_BULK_MEMORY */ -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 case WASM_OP_TABLE_INIT: { uint32 tbl_idx, elem_idx; uint32 n, s, d; WASMTableInstance *tbl_inst; - uint32 *tbl_seg_elems = NULL, tbl_seg_len = 0; + table_elem_type_t *table_elems; + InitializerExpression *tbl_seg_init_values = NULL, + *init_values; + uint64 i; + uint32 tbl_seg_len = 0; elem_idx = read_uint32(frame_ip); bh_assert(elem_idx < module->module->table_seg_count); @@ -3134,12 +5082,12 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, if (!bh_bitmap_get_bit(module->e->common.elem_dropped, elem_idx)) { /* table segment isn't dropped */ - tbl_seg_elems = + tbl_seg_init_values = module->module->table_segments[elem_idx] - .func_indexes; + .init_values; tbl_seg_len = module->module->table_segments[elem_idx] - .function_count; + .value_count; } if (offset_len_out_of_bounds(s, n, tbl_seg_len) @@ -3154,12 +5102,35 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, break; } - bh_memcpy_s( - (uint8 *)tbl_inst - + offsetof(WASMTableInstance, elems) - + d * sizeof(uint32), - (uint32)((tbl_inst->cur_size - d) * sizeof(uint32)), - tbl_seg_elems + s, (uint32)(n * sizeof(uint32))); + table_elems = tbl_inst->elems + d; + init_values = tbl_seg_init_values + s; +#if WASM_ENABLE_GC != 0 + SYNC_ALL_TO_FRAME(); +#endif + for (i = 0; i < n; i++) { + /* UINT32_MAX indicates that it is a null ref */ + bh_assert(init_values[i].init_expr_type + == INIT_EXPR_TYPE_REFNULL_CONST + || init_values[i].init_expr_type + == INIT_EXPR_TYPE_FUNCREF_CONST); +#if WASM_ENABLE_GC == 0 + table_elems[i] = + (table_elem_type_t)init_values[i].u.ref_index; +#else + if (init_values[i].u.ref_index != UINT32_MAX) { + if (!(func_obj = wasm_create_func_obj( + module, init_values[i].u.ref_index, + true, NULL, 0))) { + goto got_exception; + } + table_elems[i] = func_obj; + } + else { + table_elems[i] = NULL_REF; + } +#endif + } + break; } case WASM_OP_ELEM_DROP: @@ -3204,19 +5175,20 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, /* merge all together */ bh_memmove_s((uint8 *)dst_tbl_inst + offsetof(WASMTableInstance, elems) - + d * sizeof(uint32), + + d * sizeof(table_elem_type_t), (uint32)((dst_tbl_inst->cur_size - d) - * sizeof(uint32)), + * sizeof(table_elem_type_t)), (uint8 *)src_tbl_inst + offsetof(WASMTableInstance, elems) - + s * sizeof(uint32), - (uint32)(n * sizeof(uint32))); + + s * sizeof(table_elem_type_t), + (uint32)(n * sizeof(table_elem_type_t))); break; } case WASM_OP_TABLE_GROW: { - uint32 tbl_idx, n, init_val, orig_tbl_sz; + uint32 tbl_idx, n, orig_tbl_sz; WASMTableInstance *tbl_inst; + table_elem_type_t init_val; tbl_idx = read_uint32(frame_ip); bh_assert(tbl_idx < module->table_count); @@ -3226,7 +5198,11 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, orig_tbl_sz = tbl_inst->cur_size; n = POP_I32(); +#if WASM_ENABLE_GC == 0 init_val = POP_I32(); +#else + init_val = POP_REF(); +#endif if (!wasm_enlarge_table(module, tbl_idx, n, init_val)) { PUSH_I32(-1); @@ -3252,8 +5228,9 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, } case WASM_OP_TABLE_FILL: { - uint32 tbl_idx, n, fill_val, i; + uint32 tbl_idx, n, i; WASMTableInstance *tbl_inst; + table_elem_type_t fill_val; tbl_idx = read_uint32(frame_ip); bh_assert(tbl_idx < module->table_count); @@ -3261,7 +5238,11 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, tbl_inst = wasm_get_table_inst(module, tbl_idx); n = POP_I32(); +#if WASM_ENABLE_GC == 0 fill_val = POP_I32(); +#else + fill_val = POP_REF(); +#endif i = POP_I32(); if (offset_len_out_of_bounds(i, n, @@ -3303,7 +5284,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, notify_count = POP_I32(); addr = POP_I32(); - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 4, maddr); + CHECK_MEMORY_OVERFLOW(4); CHECK_ATOMIC_MEMORY_ACCESS(4); ret = wasm_runtime_atomic_notify( @@ -3323,7 +5304,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, timeout = POP_I64(); expect = POP_I32(); addr = POP_I32(); - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 4, maddr); + CHECK_MEMORY_OVERFLOW(4); CHECK_ATOMIC_MEMORY_ACCESS(4); ret = wasm_runtime_atomic_wait( @@ -3347,7 +5328,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, timeout = POP_I64(); expect = POP_I64(); addr = POP_I32(); - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 8, maddr); + CHECK_MEMORY_OVERFLOW(8); CHECK_ATOMIC_MEMORY_ACCESS(8); ret = wasm_runtime_atomic_wait( @@ -3378,21 +5359,21 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, addr = POP_I32(); if (opcode == WASM_OP_ATOMIC_I32_LOAD8_U) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 1, maddr); + CHECK_MEMORY_OVERFLOW(1); CHECK_ATOMIC_MEMORY_ACCESS(1); shared_memory_lock(memory); readv = (uint32)(*(uint8 *)maddr); shared_memory_unlock(memory); } else if (opcode == WASM_OP_ATOMIC_I32_LOAD16_U) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 2, maddr); + CHECK_MEMORY_OVERFLOW(2); CHECK_ATOMIC_MEMORY_ACCESS(2); shared_memory_lock(memory); readv = (uint32)LOAD_U16(maddr); shared_memory_unlock(memory); } else { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 4, maddr); + CHECK_MEMORY_OVERFLOW(4); CHECK_ATOMIC_MEMORY_ACCESS(4); shared_memory_lock(memory); readv = LOAD_I32(maddr); @@ -3413,28 +5394,28 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, addr = POP_I32(); if (opcode == WASM_OP_ATOMIC_I64_LOAD8_U) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 1, maddr); + CHECK_MEMORY_OVERFLOW(1); CHECK_ATOMIC_MEMORY_ACCESS(1); shared_memory_lock(memory); readv = (uint64)(*(uint8 *)maddr); shared_memory_unlock(memory); } else if (opcode == WASM_OP_ATOMIC_I64_LOAD16_U) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 2, maddr); + CHECK_MEMORY_OVERFLOW(2); CHECK_ATOMIC_MEMORY_ACCESS(2); shared_memory_lock(memory); readv = (uint64)LOAD_U16(maddr); shared_memory_unlock(memory); } else if (opcode == WASM_OP_ATOMIC_I64_LOAD32_U) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 4, maddr); + CHECK_MEMORY_OVERFLOW(4); CHECK_ATOMIC_MEMORY_ACCESS(4); shared_memory_lock(memory); readv = (uint64)LOAD_U32(maddr); shared_memory_unlock(memory); } else { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 8, maddr); + CHECK_MEMORY_OVERFLOW(8); CHECK_ATOMIC_MEMORY_ACCESS(8); shared_memory_lock(memory); readv = LOAD_I64(maddr); @@ -3454,21 +5435,21 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, addr = POP_I32(); if (opcode == WASM_OP_ATOMIC_I32_STORE8) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 1, maddr); + CHECK_MEMORY_OVERFLOW(1); CHECK_ATOMIC_MEMORY_ACCESS(1); shared_memory_lock(memory); *(uint8 *)maddr = (uint8)sval; shared_memory_unlock(memory); } else if (opcode == WASM_OP_ATOMIC_I32_STORE16) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 2, maddr); + CHECK_MEMORY_OVERFLOW(2); CHECK_ATOMIC_MEMORY_ACCESS(2); shared_memory_lock(memory); STORE_U16(maddr, (uint16)sval); shared_memory_unlock(memory); } else { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 4, maddr); + CHECK_MEMORY_OVERFLOW(4); CHECK_ATOMIC_MEMORY_ACCESS(4); shared_memory_lock(memory); STORE_U32(maddr, sval); @@ -3488,28 +5469,28 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, addr = POP_I32(); if (opcode == WASM_OP_ATOMIC_I64_STORE8) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 1, maddr); + CHECK_MEMORY_OVERFLOW(1); CHECK_ATOMIC_MEMORY_ACCESS(1); shared_memory_lock(memory); *(uint8 *)maddr = (uint8)sval; shared_memory_unlock(memory); } else if (opcode == WASM_OP_ATOMIC_I64_STORE16) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 2, maddr); + CHECK_MEMORY_OVERFLOW(2); CHECK_ATOMIC_MEMORY_ACCESS(2); shared_memory_lock(memory); STORE_U16(maddr, (uint16)sval); shared_memory_unlock(memory); } else if (opcode == WASM_OP_ATOMIC_I64_STORE32) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 4, maddr); + CHECK_MEMORY_OVERFLOW(4); CHECK_ATOMIC_MEMORY_ACCESS(4); shared_memory_lock(memory); STORE_U32(maddr, (uint32)sval); shared_memory_unlock(memory); } else { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 8, maddr); + CHECK_MEMORY_OVERFLOW(8); CHECK_ATOMIC_MEMORY_ACCESS(8); shared_memory_lock(memory); STORE_I64(maddr, sval); @@ -3529,7 +5510,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, addr = POP_I32(); if (opcode == WASM_OP_ATOMIC_RMW_I32_CMPXCHG8_U) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 1, maddr); + CHECK_MEMORY_OVERFLOW(1); CHECK_ATOMIC_MEMORY_ACCESS(1); expect = (uint8)expect; @@ -3540,7 +5521,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, shared_memory_unlock(memory); } else if (opcode == WASM_OP_ATOMIC_RMW_I32_CMPXCHG16_U) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 2, maddr); + CHECK_MEMORY_OVERFLOW(2); CHECK_ATOMIC_MEMORY_ACCESS(2); expect = (uint16)expect; @@ -3551,7 +5532,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, shared_memory_unlock(memory); } else { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 4, maddr); + CHECK_MEMORY_OVERFLOW(4); CHECK_ATOMIC_MEMORY_ACCESS(4); shared_memory_lock(memory); @@ -3575,7 +5556,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, addr = POP_I32(); if (opcode == WASM_OP_ATOMIC_RMW_I64_CMPXCHG8_U) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 1, maddr); + CHECK_MEMORY_OVERFLOW(1); CHECK_ATOMIC_MEMORY_ACCESS(1); expect = (uint8)expect; @@ -3586,7 +5567,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, shared_memory_unlock(memory); } else if (opcode == WASM_OP_ATOMIC_RMW_I64_CMPXCHG16_U) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 2, maddr); + CHECK_MEMORY_OVERFLOW(2); CHECK_ATOMIC_MEMORY_ACCESS(2); expect = (uint16)expect; @@ -3597,7 +5578,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, shared_memory_unlock(memory); } else if (opcode == WASM_OP_ATOMIC_RMW_I64_CMPXCHG32_U) { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 4, maddr); + CHECK_MEMORY_OVERFLOW(4); CHECK_ATOMIC_MEMORY_ACCESS(4); expect = (uint32)expect; @@ -3608,7 +5589,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, shared_memory_unlock(memory); } else { - CHECK_BULK_MEMORY_OVERFLOW(addr + offset, 8, maddr); + CHECK_MEMORY_OVERFLOW(8); CHECK_ATOMIC_MEMORY_ACCESS(8); shared_memory_lock(memory); @@ -3692,13 +5673,24 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, #if WASM_ENABLE_SHARED_MEMORY == 0 HANDLE_OP(WASM_OP_ATOMIC_PREFIX) #endif -#if WASM_ENABLE_REF_TYPES == 0 +#if WASM_ENABLE_REF_TYPES == 0 && WASM_ENABLE_GC == 0 HANDLE_OP(WASM_OP_TABLE_GET) HANDLE_OP(WASM_OP_TABLE_SET) HANDLE_OP(WASM_OP_REF_NULL) HANDLE_OP(WASM_OP_REF_IS_NULL) HANDLE_OP(WASM_OP_REF_FUNC) #endif +#if WASM_ENABLE_GC == 0 + /* SELECT_T is converted to SELECT or SELECT_64 */ + HANDLE_OP(WASM_OP_SELECT_T) + HANDLE_OP(WASM_OP_CALL_REF) + HANDLE_OP(WASM_OP_RETURN_CALL_REF) + HANDLE_OP(WASM_OP_REF_EQ) + HANDLE_OP(WASM_OP_REF_AS_NON_NULL) + HANDLE_OP(WASM_OP_BR_ON_NULL) + HANDLE_OP(WASM_OP_BR_ON_NON_NULL) + HANDLE_OP(WASM_OP_GC_PREFIX) +#endif #if WASM_ENABLE_EXCE_HANDLING == 0 /* if exception handling is disabled, these opcodes issue a trap */ HANDLE_OP(WASM_OP_TRY) @@ -3709,10 +5701,6 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_CATCH_ALL) HANDLE_OP(EXT_OP_TRY) #endif - /* SELECT_T is converted to SELECT or SELECT_64 */ - HANDLE_OP(WASM_OP_SELECT_T) - HANDLE_OP(WASM_OP_UNUSED_0x14) - HANDLE_OP(WASM_OP_UNUSED_0x15) HANDLE_OP(WASM_OP_UNUSED_0x16) HANDLE_OP(WASM_OP_UNUSED_0x17) HANDLE_OP(WASM_OP_UNUSED_0x27) @@ -3745,15 +5733,15 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, FETCH_OPCODE_AND_DISPATCH(); #endif -#if WASM_ENABLE_TAIL_CALL != 0 +#if WASM_ENABLE_TAIL_CALL != 0 || WASM_ENABLE_GC != 0 call_func_from_return_call: { - uint32 *lp_base; - uint32 *lp; + uint32 *lp_base = NULL, *lp = NULL; int i; - if (!(lp_base = lp = wasm_runtime_malloc(cur_func->param_cell_num - * sizeof(uint32)))) { + if (cur_func->param_cell_num > 0 + && !(lp_base = lp = wasm_runtime_malloc(cur_func->param_cell_num + * sizeof(uint32)))) { wasm_set_exception(module, "allocate memory failed"); goto got_exception; } @@ -3775,13 +5763,14 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, if (lp - lp_base > 0) { word_copy(frame->lp, lp_base, lp - lp_base); } - wasm_runtime_free(lp_base); + if (lp_base) + wasm_runtime_free(lp_base); FREE_FRAME(exec_env, frame); frame_ip += cur_func->param_count * sizeof(int16); wasm_exec_env_set_cur_frame(exec_env, (WASMRuntimeFrame *)prev_frame); goto call_func_from_entry; } -#endif /* WASM_ENABLE_TAIL_CALL */ +#endif /* WASM_ENABLE_TAIL_CALL != 0 || WASM_ENABLE_GC != 0 */ call_func_from_interp: { @@ -3803,7 +5792,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, } if ((uint8 *)(outs_area->lp + cur_func->param_cell_num) - > exec_env->wasm_stack.s.top_boundary) { + > exec_env->wasm_stack.top_boundary) { wasm_set_exception(module, "wasm operand stack overflow"); goto got_exception; } @@ -3817,6 +5806,18 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, 2 * (cur_func->param_count - i - 1))); outs_area->lp += 2; } +#if WASM_ENABLE_GC != 0 + else if (wasm_is_type_reftype(cur_func->param_types[i])) { + PUT_REF_TO_ADDR( + outs_area->lp, + GET_OPERAND(void *, REF, + 2 * (cur_func->param_count - i - 1))); + CLEAR_FRAME_REF( + *(uint16 *)(frame_ip + + (2 * (cur_func->param_count - i - 1)))); + outs_area->lp += REF_CELL_NUM; + } +#endif else { *outs_area->lp = GET_OPERAND( uint32, I32, (2 * (cur_func->param_count - i - 1))); @@ -3829,7 +5830,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, * all return values' offset so we must skip remain return * values' offsets. */ - WASMType *func_type; + WASMFuncType *func_type; if (cur_func->is_import_func) func_type = cur_func->u.func_import->func_type; else @@ -3873,10 +5874,20 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, } else { WASMFunction *cur_wasm_func = cur_func->u.func; + uint32 cell_num_of_local_stack; - all_cell_num = cur_func->param_cell_num + cur_func->local_cell_num - + cur_func->const_cell_num - + cur_wasm_func->max_stack_cell_num; + cell_num_of_local_stack = cur_func->param_cell_num + + cur_func->local_cell_num + + cur_wasm_func->max_stack_cell_num; + all_cell_num = cur_func->const_cell_num + cell_num_of_local_stack; +#if WASM_ENABLE_GC != 0 + /* area of frame_ref */ + all_cell_num += (cell_num_of_local_stack + 3) / 4; + /* cells occupied by locals, POP_REF should not clear frame_ref for + * these cells */ + local_cell_num = + cur_func->param_cell_num + cur_func->local_cell_num; +#endif /* param_cell_num, local_cell_num, const_cell_num and max_stack_cell_num are all no larger than UINT16_MAX (checked in loader), all_cell_num must be smaller than 1MB */ @@ -3906,6 +5917,16 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, memset(frame_lp + cur_func->param_cell_num, 0, (uint32)(cur_func->local_cell_num * 4)); +#if WASM_ENABLE_GC != 0 + /* frame->ip is used during GC root set enumeration, so we must + * initialized this field here */ + frame->ip = frame_ip; + frame_ref = frame->frame_ref = + (uint8 *)(frame->lp + (uint32)cell_num_of_local_stack); + init_frame_refs(frame_ref, (uint32)cell_num_of_local_stack, + cur_func); +#endif + wasm_exec_env_set_cur_frame(exec_env, (WASMRuntimeFrame *)frame); } #if WASM_ENABLE_THREAD_MGR != 0 @@ -3924,6 +5945,9 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, return; RECOVER_CONTEXT(prev_frame); +#if WASM_ENABLE_GC != 0 + local_cell_num = cur_func->param_cell_num + cur_func->local_cell_num; +#endif HANDLE_OP_END(); } @@ -3964,6 +5988,48 @@ wasm_interp_get_handle_table() } #endif +#if WASM_ENABLE_GC != 0 +bool +wasm_interp_traverse_gc_rootset(WASMExecEnv *exec_env, void *heap) +{ + WASMInterpFrame *frame; + WASMObjectRef gc_obj; + WASMFunctionInstance *cur_func; + uint8 *frame_ref; + uint32 local_cell_num, i; + + frame = wasm_exec_env_get_cur_frame(exec_env); + for (; frame; frame = frame->prev_frame) { + frame_ref = frame->frame_ref; + cur_func = frame->function; + + if (!cur_func) + continue; + + local_cell_num = cur_func->param_cell_num; + if (frame->ip) + local_cell_num += + cur_func->local_cell_num + cur_func->u.func->max_stack_cell_num; + + for (i = 0; i < local_cell_num; i++) { + if (frame_ref[i]) { + gc_obj = GET_REF_FROM_ADDR(frame->lp + i); + if (wasm_obj_is_created_from_heap(gc_obj)) { + if (mem_allocator_add_root((mem_allocator_t)heap, gc_obj)) { + return false; + } + } +#if UINTPTR_MAX == UINT64_MAX + bh_assert(frame_ref[i + 1]); + i++; +#endif + } + } + } + return true; +} +#endif + void wasm_interp_call_wasm(WASMModuleInstance *module_inst, WASMExecEnv *exec_env, WASMFunctionInstance *function, uint32 argc, @@ -3978,7 +6044,13 @@ wasm_interp_call_wasm(WASMModuleInstance *module_inst, WASMExecEnv *exec_env, i; /* This frame won't be used by JITed code, so only allocate interp frame here. */ - unsigned frame_size = wasm_interp_interp_frame_size(all_cell_num); + unsigned frame_size; + +#if WASM_ENABLE_GC != 0 + all_cell_num += (all_cell_num + 3) / 4; +#endif + + frame_size = wasm_interp_interp_frame_size(all_cell_num); if (argc < function->param_cell_num) { char buf[128]; @@ -4010,10 +6082,15 @@ wasm_interp_call_wasm(WASMModuleInstance *module_inst, WASMExecEnv *exec_env, frame->ip = NULL; /* There is no local variable. */ frame->lp = frame->operand + 0; +#if WASM_ENABLE_GC != 0 + frame->frame_ref = + (uint8 *)(frame->lp + + (function->ret_cell_num > 2 ? function->ret_cell_num : 2)); +#endif frame->ret_offset = 0; if ((uint8 *)(outs_area->operand + function->const_cell_num + argc) - > exec_env->wasm_stack.s.top_boundary) { + > exec_env->wasm_stack.top_boundary) { wasm_set_exception((WASMModuleInstance *)exec_env->module_inst, "wasm operand stack overflow"); return; diff --git a/core/iwasm/interpreter/wasm_loader.c b/core/iwasm/interpreter/wasm_loader.c index 8ca3796bc..1458c1bf6 100644 --- a/core/iwasm/interpreter/wasm_loader.c +++ b/core/iwasm/interpreter/wasm_loader.c @@ -11,6 +11,10 @@ #include "wasm_runtime.h" #include "../common/wasm_native.h" #include "../common/wasm_memory.h" +#if WASM_ENABLE_GC != 0 +#include "../common/gc/gc_type.h" +#include "../common/gc/gc_object.h" +#endif #if WASM_ENABLE_DEBUG_INTERP != 0 #include "../libraries/debug-engine/debug_engine.h" #endif @@ -22,6 +26,10 @@ #include "../compilation/aot_llvm.h" #endif +#ifndef TRACE_WASM_LOADER +#define TRACE_WASM_LOADER 0 +#endif + /* Read a value of given type from the address pointed to by the given pointer and increase the pointer to the position just after the value being read. */ @@ -205,9 +213,34 @@ static char * type2str(uint8 type) { char *type_str[] = { "v128", "f64", "f32", "i64", "i32" }; +#if WASM_ENABLE_GC != 0 + char *type_str_ref[] = { "stringview_iter", + "stringview_wtf16", + "(ref null ht)", + "(ref ht)", + "", /* reserved */ + "stringview_wtf8", + "stringref", + "", /* reserved */ + "", /* reserved */ + "arrayref", + "structref", + "i32ref", + "eqref", + "anyref", + "externref", + "funcref", + "nullref", + "nullexternref", + "nullfuncref" }; +#endif if (type >= VALUE_TYPE_V128 && type <= VALUE_TYPE_I32) return type_str[type - VALUE_TYPE_V128]; +#if WASM_ENABLE_GC != 0 + else if (wasm_is_type_reftype(type)) + return type_str_ref[type - REF_TYPE_STRINGVIEWITER]; +#endif else if (type == VALUE_TYPE_FUNCREF) return "funcref"; else if (type == VALUE_TYPE_EXTERNREF) @@ -220,7 +253,11 @@ static bool is_32bit_type(uint8 type) { if (type == VALUE_TYPE_I32 || type == VALUE_TYPE_F32 -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC != 0 + || (sizeof(uintptr_t) == 4 && wasm_is_type_reftype(type)) +#elif WASM_ENABLE_REF_TYPES != 0 + /* For reference types, we use uint32 index to represent + the funcref and externref */ || type == VALUE_TYPE_FUNCREF || type == VALUE_TYPE_EXTERNREF #endif ) @@ -231,33 +268,48 @@ is_32bit_type(uint8 type) static bool is_64bit_type(uint8 type) { - if (type == VALUE_TYPE_I64 || type == VALUE_TYPE_F64) - return true; - return false; -} - -static bool -is_value_type(uint8 type) -{ - if (type == VALUE_TYPE_I32 || type == VALUE_TYPE_I64 - || type == VALUE_TYPE_F32 || type == VALUE_TYPE_F64 -#if WASM_ENABLE_REF_TYPES != 0 - || type == VALUE_TYPE_FUNCREF || type == VALUE_TYPE_EXTERNREF -#endif -#if WASM_ENABLE_SIMD != 0 -#if (WASM_ENABLE_WAMR_COMPILER != 0) || (WASM_ENABLE_JIT != 0) - || type == VALUE_TYPE_V128 -#endif + if (type == VALUE_TYPE_I64 || type == VALUE_TYPE_F64 +#if WASM_ENABLE_GC != 0 + || (sizeof(uintptr_t) == 8 && wasm_is_type_reftype(type)) #endif ) return true; return false; } +static bool +is_value_type(uint8 type) +{ + if (/* I32/I64/F32/F64, 0x7C to 0x7F */ + (type >= VALUE_TYPE_F64 && type <= VALUE_TYPE_I32) +#if WASM_ENABLE_GC != 0 + /* reference types, 0x65 to 0x70 */ + || wasm_is_type_reftype(type) +#elif WASM_ENABLE_REF_TYPES != 0 + || (type == VALUE_TYPE_FUNCREF || type == VALUE_TYPE_EXTERNREF) +#endif +#if WASM_ENABLE_SIMD != 0 +#if (WASM_ENABLE_WAMR_COMPILER != 0) || (WASM_ENABLE_JIT != 0) + || type == VALUE_TYPE_V128 /* 0x7B */ +#endif +#endif + ) + return true; + return false; +} + +#if WASM_ENABLE_GC != 0 +static bool +is_packed_type(uint8 type) +{ + return (type == PACKED_TYPE_I8 || type == PACKED_TYPE_I16) ? true : false; +} +#endif + static bool is_byte_a_type(uint8 type) { - return is_value_type(type) || (type == VALUE_TYPE_VOID); + return (is_value_type(type) || (type == VALUE_TYPE_VOID)) ? true : false; } #if WASM_ENABLE_SIMD != 0 @@ -291,6 +343,29 @@ loader_malloc(uint64 size, char *error_buf, uint32 error_buf_size) return mem; } +static void * +memory_realloc(void *mem_old, uint32 size_old, uint32 size_new, char *error_buf, + uint32 error_buf_size) +{ + uint8 *mem_new; + bh_assert(size_new > size_old); + if ((mem_new = loader_malloc(size_new, error_buf, error_buf_size))) { + bh_memcpy_s(mem_new, size_new, mem_old, size_old); + memset(mem_new + size_old, 0, size_new - size_old); + wasm_runtime_free(mem_old); + } + return mem_new; +} + +#define MEM_REALLOC(mem, size_old, size_new) \ + do { \ + void *mem_new = memory_realloc(mem, size_old, size_new, error_buf, \ + error_buf_size); \ + if (!mem_new) \ + goto fail; \ + mem = mem_new; \ + } while (0) + static bool check_utf8_str(const uint8 *str, uint32 len) { @@ -423,6 +498,1401 @@ const_str_list_insert(const uint8 *str, uint32 len, WASMModule *module, return node->str; } +#if WASM_ENABLE_GC != 0 +static bool +check_type_index(const WASMModule *module, uint32 type_index, char *error_buf, + uint32 error_buf_size) +{ + if (type_index >= module->type_count) { + set_error_buf_v(error_buf, error_buf_size, "unknown type %d", + type_index); + return false; + } + return true; +} + +static bool +check_array_type(const WASMModule *module, uint32 type_index, char *error_buf, + uint32 error_buf_size) +{ + if (!check_type_index(module, type_index, error_buf, error_buf_size)) { + return false; + } + if (module->types[type_index]->type_flag != WASM_TYPE_ARRAY) { + set_error_buf(error_buf, error_buf_size, "unkown array type"); + return false; + } + + return true; +} +#endif + +static bool +check_function_index(const WASMModule *module, uint32 function_index, + char *error_buf, uint32 error_buf_size) +{ + if (function_index + >= module->import_function_count + module->function_count) { + set_error_buf_v(error_buf, error_buf_size, "unknown function %u", + function_index); + return false; + } + return true; +} + +typedef struct InitValue { + uint8 type; + uint8 flag; +#if WASM_ENABLE_GC != 0 + uint8 gc_opcode; + WASMRefType ref_type; +#endif + WASMValue value; +} InitValue; + +typedef struct ConstExprContext { + uint32 sp; + uint32 size; + WASMModule *module; + InitValue *stack; + InitValue data[WASM_CONST_EXPR_STACK_SIZE]; +} ConstExprContext; + +static void +init_const_expr_stack(ConstExprContext *ctx, WASMModule *module) +{ + ctx->sp = 0; + ctx->module = module; + ctx->stack = ctx->data; + ctx->size = WASM_CONST_EXPR_STACK_SIZE; +} + +static bool +push_const_expr_stack(ConstExprContext *ctx, uint8 flag, uint8 type, +#if WASM_ENABLE_GC != 0 + WASMRefType *ref_type, uint8 gc_opcode, +#endif + WASMValue *value, char *error_buf, uint32 error_buf_size) +{ + InitValue *cur_value; + + if (ctx->sp >= ctx->size) { + if (ctx->stack != ctx->data) { + MEM_REALLOC(ctx->stack, ctx->size * sizeof(InitValue), + (ctx->size + 4) * sizeof(InitValue)); + } + else { + if (!(ctx->stack = + loader_malloc((ctx->size + 4) * (uint64)sizeof(InitValue), + error_buf, error_buf_size))) { + goto fail; + } + } + ctx->size += 4; + } + + cur_value = &ctx->stack[ctx->sp++]; + cur_value->type = type; + cur_value->flag = flag; + cur_value->value = *value; + +#if WASM_ENABLE_GC != 0 + cur_value->gc_opcode = gc_opcode; + if (wasm_is_type_multi_byte_type(type)) { + bh_memcpy_s(&cur_value->ref_type, wasm_reftype_struct_size(ref_type), + ref_type, wasm_reftype_struct_size(ref_type)); + } +#endif + + return true; +fail: + return false; +} + +static bool +pop_const_expr_stack(ConstExprContext *ctx, uint8 *p_flag, uint8 type, +#if WASM_ENABLE_GC != 0 + WASMRefType *ref_type, uint8 *p_gc_opcode, +#endif + WASMValue *p_value, char *error_buf, uint32 error_buf_size) +{ + InitValue *cur_value; + + if (ctx->sp == 0) { + set_error_buf(error_buf, error_buf_size, + "type mismatch: const expr stack underflow"); + return false; + } + + cur_value = &ctx->stack[--ctx->sp]; + +#if WASM_ENABLE_GC == 0 + if (cur_value->type != type) { + set_error_buf(error_buf, error_buf_size, "type mismatch"); + return false; + } +#else + if (!wasm_reftype_is_subtype_of(cur_value->type, &cur_value->ref_type, type, + ref_type, ctx->module->types, + ctx->module->type_count)) { + set_error_buf_v(error_buf, error_buf_size, "%s%s%s", + "type mismatch: expect ", type2str(type), + " but got other"); + goto fail; + } + + if ((ctx->sp != 0) && (cur_value->flag == WASM_OP_GC_PREFIX) + && (cur_value->gc_opcode != WASM_OP_REF_I31)) { + /* To reduce complexity, we don't allow initialize struct fields/array + * element with references, so struct/array must be at the bottom of the + * init value stack */ + set_error_buf( + error_buf, error_buf_size, + "struct or array as field is not supported in constant expr"); + goto fail; + } +#endif + + if (p_flag) + *p_flag = cur_value->flag; + if (p_value) + *p_value = cur_value->value; +#if WASM_ENABLE_GC != 0 + if (p_gc_opcode) + *p_gc_opcode = cur_value->gc_opcode; +#endif + + return true; + +#if WASM_ENABLE_GC != 0 +fail: + if ((cur_value->flag == WASM_OP_GC_PREFIX) + && (cur_value->gc_opcode == WASM_OP_STRUCT_NEW + || cur_value->gc_opcode == WASM_OP_ARRAY_NEW + || cur_value->gc_opcode == WASM_OP_ARRAY_NEW_FIXED)) { + wasm_runtime_free(cur_value->value.data); + } + return false; +#endif +} + +static void +destroy_const_expr_stack(ConstExprContext *ctx) +{ +#if WASM_ENABLE_GC != 0 + uint32 i; + + for (i = 0; i < ctx->sp; i++) { + if ((ctx->stack[i].flag == WASM_OP_GC_PREFIX) + && (ctx->stack[i].gc_opcode == WASM_OP_STRUCT_NEW + || ctx->stack[i].gc_opcode == WASM_OP_ARRAY_NEW + || ctx->stack[i].gc_opcode == WASM_OP_ARRAY_NEW_FIXED)) { + wasm_runtime_free(ctx->stack[i].value.data); + } + } +#endif + + if (ctx->stack != ctx->data) { + wasm_runtime_free(ctx->stack); + } +} + +#if WASM_ENABLE_GC != 0 +static void +destroy_init_expr(InitializerExpression *expr) +{ + if (expr->init_expr_type == INIT_EXPR_TYPE_STRUCT_NEW + || expr->init_expr_type == INIT_EXPR_TYPE_ARRAY_NEW + || expr->init_expr_type == INIT_EXPR_TYPE_ARRAY_NEW_FIXED) { + wasm_runtime_free(expr->u.data); + } +} +#endif /* end of WASM_ENABLE_GC != 0 */ + +static bool +load_init_expr(WASMModule *module, const uint8 **p_buf, const uint8 *buf_end, + InitializerExpression *init_expr, uint8 type, void *ref_type, + char *error_buf, uint32 error_buf_size) +{ + const uint8 *p = *p_buf, *p_end = buf_end; + uint8 flag, *p_float; + uint32 i; + ConstExprContext const_expr_ctx = { 0 }; + WASMValue cur_value; +#if WASM_ENABLE_GC != 0 + uint32 opcode1, type_idx; + uint8 opcode; + WASMRefType cur_ref_type = { 0 }; +#endif + + init_const_expr_stack(&const_expr_ctx, module); + + CHECK_BUF(p, p_end, 1); + flag = read_uint8(p); + + while (flag != WASM_OP_END) { + switch (flag) { + /* i32.const */ + case INIT_EXPR_TYPE_I32_CONST: + read_leb_int32(p, p_end, cur_value.i32); + + if (!push_const_expr_stack( + &const_expr_ctx, flag, VALUE_TYPE_I32, +#if WASM_ENABLE_GC != 0 + NULL, 0, +#endif + &cur_value, error_buf, error_buf_size)) + goto fail; + break; + /* i64.const */ + case INIT_EXPR_TYPE_I64_CONST: + read_leb_int64(p, p_end, cur_value.i64); + + if (!push_const_expr_stack( + &const_expr_ctx, flag, VALUE_TYPE_I64, +#if WASM_ENABLE_GC != 0 + NULL, 0, +#endif + &cur_value, error_buf, error_buf_size)) + goto fail; + break; + /* f32.const */ + case INIT_EXPR_TYPE_F32_CONST: + CHECK_BUF(p, p_end, 4); + p_float = (uint8 *)&cur_value.f32; + for (i = 0; i < sizeof(float32); i++) + *p_float++ = *p++; + + if (!push_const_expr_stack( + &const_expr_ctx, flag, VALUE_TYPE_F32, +#if WASM_ENABLE_GC != 0 + NULL, 0, +#endif + &cur_value, error_buf, error_buf_size)) + goto fail; + break; + /* f64.const */ + case INIT_EXPR_TYPE_F64_CONST: + CHECK_BUF(p, p_end, 8); + p_float = (uint8 *)&cur_value.f64; + for (i = 0; i < sizeof(float64); i++) + *p_float++ = *p++; + + if (!push_const_expr_stack( + &const_expr_ctx, flag, VALUE_TYPE_F64, +#if WASM_ENABLE_GC != 0 + NULL, 0, +#endif + &cur_value, error_buf, error_buf_size)) + goto fail; + break; +#if WASM_ENABLE_SIMD != 0 +#if (WASM_ENABLE_WAMR_COMPILER != 0) || (WASM_ENABLE_JIT != 0) + /* v128.const */ + case INIT_EXPR_TYPE_V128_CONST: + { + uint64 high, low; + + CHECK_BUF(p, p_end, 1); + (void)read_uint8(p); + + CHECK_BUF(p, p_end, 16); + wasm_runtime_read_v128(p, &high, &low); + p += 16; + + cur_value.v128.i64x2[0] = high; + cur_value.v128.i64x2[1] = low; + + if (!push_const_expr_stack( + &const_expr_ctx, flag, VALUE_TYPE_V128, +#if WASM_ENABLE_GC != 0 + NULL, 0, +#endif + &cur_value, error_buf, error_buf_size)) + goto fail; +#if WASM_ENABLE_WAMR_COMPILER != 0 + /* If any init_expr is v128.const, mark SIMD used */ + module->is_simd_used = true; +#endif + break; + } +#endif /* end of (WASM_ENABLE_WAMR_COMPILER != 0) || (WASM_ENABLE_JIT != 0) */ +#endif /* end of WASM_ENABLE_SIMD */ + +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 + /* ref.func */ + case INIT_EXPR_TYPE_FUNCREF_CONST: + { + uint32 func_idx; + read_leb_uint32(p, p_end, func_idx); + cur_value.ref_index = func_idx; + if (!check_function_index(module, func_idx, error_buf, + error_buf_size)) { + goto fail; + } + +#if WASM_ENABLE_GC == 0 + if (!push_const_expr_stack(&const_expr_ctx, flag, + VALUE_TYPE_FUNCREF, &cur_value, + error_buf, error_buf_size)) + goto fail; +#else + if (func_idx < module->import_function_count) { + type_idx = + module->import_functions[func_idx].u.function.type_idx; + } + else { + type_idx = module + ->functions[func_idx + - module->import_function_count] + ->type_idx; + } + wasm_set_refheaptype_typeidx(&cur_ref_type.ref_ht_typeidx, + false, type_idx); + if (!push_const_expr_stack(&const_expr_ctx, flag, + cur_ref_type.ref_type, &cur_ref_type, + 0, &cur_value, error_buf, + error_buf_size)) + goto fail; +#endif +#if WASM_ENABLE_WAMR_COMPILER != 0 + module->is_ref_types_used = true; +#endif + break; + } + + /* ref.null */ + case INIT_EXPR_TYPE_REFNULL_CONST: + { + uint8 type1; + + CHECK_BUF(p, p_end, 1); + type1 = read_uint8(p); + +#if WASM_ENABLE_GC == 0 + cur_value.ref_index = NULL_REF; + if (!push_const_expr_stack(&const_expr_ctx, flag, type1, + &cur_value, error_buf, + error_buf_size)) + goto fail; +#else + cur_value.gc_obj = NULL_REF; + + if (!is_byte_a_type(type1)) { + p--; + read_leb_uint32(p, p_end, type_idx); + if (!check_type_index(module, type_idx, error_buf, + error_buf_size)) + goto fail; + + wasm_set_refheaptype_typeidx(&cur_ref_type.ref_ht_typeidx, + true, type_idx); + if (!push_const_expr_stack(&const_expr_ctx, flag, + cur_ref_type.ref_type, + &cur_ref_type, 0, &cur_value, + error_buf, error_buf_size)) + goto fail; + } + else { + if (!push_const_expr_stack(&const_expr_ctx, flag, type1, + NULL, 0, &cur_value, error_buf, + error_buf_size)) + goto fail; + } +#endif +#if WASM_ENABLE_WAMR_COMPILER != 0 + module->is_ref_types_used = true; +#endif + break; + } +#endif /* end of WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */ + + /* get_global */ + case INIT_EXPR_TYPE_GET_GLOBAL: + { + uint32 global_idx; + uint8 global_type; + + read_leb_uint32(p, p_end, cur_value.global_index); + global_idx = cur_value.global_index; + +#if WASM_ENABLE_GC == 0 + if (global_idx >= module->import_global_count) { + /** + * Currently, constant expressions occurring as initializers + * of globals are further constrained in that contained + * global.get instructions are + * only allowed to refer to imported globals. + */ + set_error_buf_v(error_buf, error_buf_size, + "unknown global %u", global_idx); + goto fail; + } + if (module->import_globals[global_idx].u.global.is_mutable) { + set_error_buf_v(error_buf, error_buf_size, + "constant expression required"); + goto fail; + } +#else + if (global_idx + >= module->import_global_count + module->global_count) { + set_error_buf_v(error_buf, error_buf_size, + "unknown global %u", global_idx); + goto fail; + } + if (global_idx < module->import_global_count + && module->import_globals[global_idx].u.global.is_mutable) { + set_error_buf_v(error_buf, error_buf_size, + "constant expression required"); + goto fail; + } +#endif + + if (global_idx < module->import_global_count) { + global_type = + module->import_globals[global_idx].u.global.type; +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_multi_byte_type(global_type)) { + WASMRefType *global_ref_type = + module->import_globals[global_idx] + .u.global.ref_type; + bh_memcpy_s(&cur_ref_type, + wasm_reftype_struct_size(global_ref_type), + global_ref_type, + wasm_reftype_struct_size(global_ref_type)); + } +#endif + } + else { + global_type = + module + ->globals[global_idx - module->import_global_count] + .type; +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_multi_byte_type(global_type)) { + WASMRefType *global_ref_type = + module + ->globals[global_idx + - module->import_global_count] + .ref_type; + bh_memcpy_s(&cur_ref_type, + wasm_reftype_struct_size(global_ref_type), + global_ref_type, + wasm_reftype_struct_size(global_ref_type)); + } +#endif + } + + if (!push_const_expr_stack(&const_expr_ctx, flag, global_type, +#if WASM_ENABLE_GC != 0 + &cur_ref_type, 0, +#endif + &cur_value, error_buf, + error_buf_size)) + goto fail; + + break; + } + +#if WASM_ENABLE_GC != 0 + /* struct.new and array.new */ + case WASM_OP_GC_PREFIX: + { + read_leb_uint32(p, p_end, opcode1); + + switch (opcode1) { + case WASM_OP_STRUCT_NEW: + { + WASMStructType *struct_type; + WASMStructNewInitValues *struct_init_values = NULL; + uint32 field_count; + read_leb_uint32(p, p_end, type_idx); + + if (!check_type_index(module, type_idx, error_buf, + error_buf_size)) { + goto fail; + } + + struct_type = (WASMStructType *)module->types[type_idx]; + if (struct_type->base_type.type_flag + != WASM_TYPE_STRUCT) { + set_error_buf(error_buf, error_buf_size, + "unkown struct type"); + goto fail; + } + field_count = struct_type->field_count; + + if (!(struct_init_values = loader_malloc( + offsetof(WASMStructNewInitValues, fields) + + (uint64)field_count * sizeof(WASMValue), + error_buf, error_buf_size))) { + goto fail; + } + struct_init_values->count = field_count; + + for (i = field_count; i > 0; i--) { + WASMRefType *field_ref_type = NULL; + uint32 field_idx = i - 1; + uint8 field_type = + struct_type->fields[field_idx].field_type; + if (wasm_is_type_multi_byte_type(field_type)) { + field_ref_type = wasm_reftype_map_find( + struct_type->ref_type_maps, + struct_type->ref_type_map_count, field_idx); + } + + if (is_packed_type(field_type)) { + field_type = VALUE_TYPE_I32; + } + + if (!pop_const_expr_stack( + &const_expr_ctx, NULL, field_type, + field_ref_type, NULL, + &struct_init_values->fields[field_idx], + error_buf, error_buf_size)) { + wasm_runtime_free(struct_init_values); + goto fail; + } + } + + cur_value.data = struct_init_values; + wasm_set_refheaptype_typeidx( + &cur_ref_type.ref_ht_typeidx, false, type_idx); + if (!push_const_expr_stack( + &const_expr_ctx, flag, cur_ref_type.ref_type, + &cur_ref_type, (uint8)opcode1, &cur_value, + error_buf, error_buf_size)) { + wasm_runtime_free(struct_init_values); + goto fail; + } + break; + } + case WASM_OP_STRUCT_NEW_DEFAULT: + { + read_leb_uint32(p, p_end, cur_value.type_index); + type_idx = cur_value.type_index; + + if (!check_type_index(module, type_idx, error_buf, + error_buf_size)) { + goto fail; + } + if (module->types[type_idx]->type_flag + != WASM_TYPE_STRUCT) { + set_error_buf(error_buf, error_buf_size, + "unkown struct type"); + goto fail; + } + + cur_value.type_index = type_idx; + wasm_set_refheaptype_typeidx( + &cur_ref_type.ref_ht_typeidx, false, type_idx); + if (!push_const_expr_stack( + &const_expr_ctx, flag, cur_ref_type.ref_type, + &cur_ref_type, (uint8)opcode1, &cur_value, + error_buf, error_buf_size)) { + goto fail; + } + break; + } + case WASM_OP_ARRAY_NEW: + case WASM_OP_ARRAY_NEW_DEFAULT: + case WASM_OP_ARRAY_NEW_FIXED: + { + WASMArrayNewInitValues *array_init_values = NULL; + WASMArrayType *array_type = NULL; + WASMRefType *elem_ref_type = NULL; + uint64 total_size; + uint8 elem_type; + + read_leb_uint32(p, p_end, cur_value.type_index); + type_idx = cur_value.type_index; + + if (!check_type_index(module, type_idx, error_buf, + error_buf_size)) { + goto fail; + } + + array_type = (WASMArrayType *)module->types[type_idx]; + if (array_type->base_type.type_flag + != WASM_TYPE_ARRAY) { + set_error_buf(error_buf, error_buf_size, + "unkown array type"); + goto fail; + } + + if (opcode1 != WASM_OP_ARRAY_NEW_DEFAULT) { + elem_type = array_type->elem_type; + if (wasm_is_type_multi_byte_type(elem_type)) { + elem_ref_type = array_type->elem_ref_type; + } + + if (is_packed_type(elem_type)) { + elem_type = VALUE_TYPE_I32; + } + + if (opcode1 == WASM_OP_ARRAY_NEW) { + WASMValue len_val; + + if (!(array_init_values = loader_malloc( + sizeof(WASMArrayNewInitValues), + error_buf, error_buf_size))) { + goto fail; + } + array_init_values->type_idx = type_idx; + + if (!pop_const_expr_stack( + &const_expr_ctx, NULL, VALUE_TYPE_I32, + NULL, NULL, &len_val, error_buf, + error_buf_size)) { + wasm_runtime_free(array_init_values); + goto fail; + } + array_init_values->length = len_val.i32; + + if (!pop_const_expr_stack( + &const_expr_ctx, NULL, elem_type, + elem_ref_type, NULL, + &array_init_values->elem_data[0], + error_buf, error_buf_size)) { + wasm_runtime_free(array_init_values); + goto fail; + } + + cur_value.data = array_init_values; + } + else { + /* WASM_OP_ARRAY_NEW_FIXED */ + uint32 len; + read_leb_uint32(p, p_end, len); + + total_size = + (uint64)offsetof(WASMArrayNewInitValues, + elem_data) + + (uint64)sizeof(WASMValue) * len; + if (!(array_init_values = + loader_malloc(total_size, error_buf, + error_buf_size))) { + goto fail; + } + + array_init_values->type_idx = type_idx; + array_init_values->length = len; + + for (i = len; i > 0; i--) { + if (!pop_const_expr_stack( + &const_expr_ctx, NULL, elem_type, + elem_ref_type, NULL, + &array_init_values + ->elem_data[i - 1], + error_buf, error_buf_size)) { + wasm_runtime_free(array_init_values); + goto fail; + } + } + + cur_value.data = array_init_values; + } + } + else { + /* WASM_OP_ARRAY_NEW_DEFAULT */ + WASMValue len_val; + uint32 len; + + /* POP(i32) */ + if (!pop_const_expr_stack(&const_expr_ctx, NULL, + VALUE_TYPE_I32, NULL, + NULL, &len_val, error_buf, + error_buf_size)) { + goto fail; + } + len = len_val.i32; + + cur_value.array_new_default.type_index = type_idx; + cur_value.array_new_default.length = len; + } + + wasm_set_refheaptype_typeidx( + &cur_ref_type.ref_ht_typeidx, false, type_idx); + if (!push_const_expr_stack( + &const_expr_ctx, flag, cur_ref_type.ref_type, + &cur_ref_type, (uint8)opcode1, &cur_value, + error_buf, error_buf_size)) { + if (array_init_values) { + wasm_runtime_free(array_init_values); + } + goto fail; + } + break; + } + case WASM_OP_ANY_CONVERT_EXTERN: + { + set_error_buf(error_buf, error_buf_size, + "unsuppoted constant expression of " + "extern.internalize"); + goto fail; + } + case WASM_OP_EXTERN_CONVERT_ANY: + { + set_error_buf(error_buf, error_buf_size, + "unsuppoted constant expression of " + "extern.externalize"); + goto fail; + } + case WASM_OP_REF_I31: + { + /* POP(i32) */ + if (!pop_const_expr_stack( + &const_expr_ctx, NULL, VALUE_TYPE_I32, NULL, + NULL, &cur_value, error_buf, error_buf_size)) { + goto fail; + } + + wasm_set_refheaptype_common(&cur_ref_type.ref_ht_common, + false, HEAP_TYPE_I31); + if (!push_const_expr_stack( + &const_expr_ctx, flag, cur_ref_type.ref_type, + &cur_ref_type, (uint8)opcode1, &cur_value, + error_buf, error_buf_size)) { + goto fail; + } + break; + } + default: + set_error_buf( + error_buf, error_buf_size, + "type mismatch or constant expression required"); + goto fail; + } + + break; + } +#endif /* end of WASM_ENABLE_GC != 0 */ + default: + { + set_error_buf(error_buf, error_buf_size, + "illegal opcode " + "or constant expression required " + "or type mismatch"); + goto fail; + } + } + + CHECK_BUF(p, p_end, 1); + flag = read_uint8(p); + } + + /* There should be only one value left on the init value stack */ + if (!pop_const_expr_stack(&const_expr_ctx, &flag, type, +#if WASM_ENABLE_GC != 0 + ref_type, &opcode, +#endif + &cur_value, error_buf, error_buf_size)) { + goto fail; + } + + if (const_expr_ctx.sp != 0) { + set_error_buf(error_buf, error_buf_size, + "type mismatch: illegal constant opcode sequence"); + goto fail; + } + + init_expr->init_expr_type = flag; + init_expr->u = cur_value; + +#if WASM_ENABLE_GC != 0 + if (init_expr->init_expr_type == WASM_OP_GC_PREFIX) { + switch (opcode) { + case WASM_OP_STRUCT_NEW: + init_expr->init_expr_type = INIT_EXPR_TYPE_STRUCT_NEW; + break; + case WASM_OP_STRUCT_NEW_DEFAULT: + init_expr->init_expr_type = INIT_EXPR_TYPE_STRUCT_NEW_DEFAULT; + break; + case WASM_OP_ARRAY_NEW: + init_expr->init_expr_type = INIT_EXPR_TYPE_ARRAY_NEW; + break; + case WASM_OP_ARRAY_NEW_DEFAULT: + init_expr->init_expr_type = INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT; + break; + case WASM_OP_ARRAY_NEW_FIXED: + init_expr->init_expr_type = INIT_EXPR_TYPE_ARRAY_NEW_FIXED; + break; + case WASM_OP_REF_I31: + init_expr->init_expr_type = INIT_EXPR_TYPE_I31_NEW; + break; + default: + bh_assert(0); + break; + } + } +#endif /* end of WASM_ENABLE_GC != 0 */ + + *p_buf = p; + destroy_const_expr_stack(&const_expr_ctx); + return true; + +fail: + destroy_const_expr_stack(&const_expr_ctx); + return false; +} + +static bool +check_mutability(uint8 mutable, char *error_buf, uint32 error_buf_size) +{ + if (mutable >= 2) { + set_error_buf(error_buf, error_buf_size, "invalid mutability"); + return false; + } + return true; +} + +#if WASM_ENABLE_GC != 0 +static void +destroy_func_type(WASMFuncType *type) +{ + /* Destroy the reference type hash set */ + if (type->ref_type_maps) + wasm_runtime_free(type->ref_type_maps); + +#if WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 \ + && WASM_ENABLE_LAZY_JIT != 0 + if (type->call_to_llvm_jit_from_fast_jit) + jit_code_cache_free(type->call_to_llvm_jit_from_fast_jit); +#endif + /* Free the type */ + wasm_runtime_free(type); +} + +static void +destroy_struct_type(WASMStructType *type) +{ + if (type->ref_type_maps) + wasm_runtime_free(type->ref_type_maps); + + wasm_runtime_free(type); +} + +static void +destroy_array_type(WASMArrayType *type) +{ + wasm_runtime_free(type); +} + +static void +destroy_wasm_type(WASMType *type) +{ + if (type->type_flag == WASM_TYPE_FUNC) + destroy_func_type((WASMFuncType *)type); + else if (type->type_flag == WASM_TYPE_STRUCT) + destroy_struct_type((WASMStructType *)type); + else if (type->type_flag == WASM_TYPE_ARRAY) + destroy_array_type((WASMArrayType *)type); + else { + bh_assert(0); + } +} + +/* Resolve (ref null ht) or (ref ht) */ +static bool +resolve_reftype_htref(const uint8 **p_buf, const uint8 *buf_end, + WASMModule *module, bool nullable, WASMRefType *ref_type, + char *error_buf, uint32 error_buf_size) +{ + const uint8 *p = *p_buf, *p_end = buf_end; + + ref_type->ref_type = + nullable ? REF_TYPE_HT_NULLABLE : REF_TYPE_HT_NON_NULLABLE; + ref_type->ref_ht_common.nullable = nullable; + read_leb_int32(p, p_end, ref_type->ref_ht_common.heap_type); + + if (wasm_is_refheaptype_typeidx(&ref_type->ref_ht_common)) { + /* heap type is (type i), i : typeidx, >= 0 */ + if (!check_type_index(module, ref_type->ref_ht_typeidx.type_idx, + error_buf, error_buf_size)) { + return false; + } + } + else if (!wasm_is_refheaptype_common(&ref_type->ref_ht_common)) { + /* heap type is func, extern, any, eq, i31 or data */ + set_error_buf(error_buf, error_buf_size, "unknown heap type"); + return false; + } + + *p_buf = p; + return true; +fail: + return false; +} + +static bool +resolve_value_type(const uint8 **p_buf, const uint8 *buf_end, + WASMModule *module, bool *p_need_ref_type_map, + WASMRefType *ref_type, bool allow_packed_type, + char *error_buf, uint32 error_buf_size) +{ + const uint8 *p = *p_buf, *p_end = buf_end; + uint8 type; + + memset(ref_type, 0, sizeof(WASMRefType)); + + CHECK_BUF(p, p_end, 1); + type = read_uint8(p); + + if (wasm_is_reftype_htref_nullable(type)) { + /* (ref null ht) */ + if (!resolve_reftype_htref(&p, p_end, module, true, ref_type, error_buf, + error_buf_size)) + return false; + if (!wasm_is_refheaptype_common(&ref_type->ref_ht_common)) + *p_need_ref_type_map = true; + else { + /* For (ref null func/extern/any/eq/i31/data), they are same as + funcref/externref/anyref/eqref/i31ref/dataref, we convert the + multi-byte type to one-byte type to reduce the footprint and + the complexity of type equal/subtype checking */ + ref_type->ref_type = + (uint8)((int32)0x80 + ref_type->ref_ht_common.heap_type); + *p_need_ref_type_map = false; + } + } + else if (wasm_is_reftype_htref_non_nullable(type)) { + /* (ref ht) */ + if (!resolve_reftype_htref(&p, p_end, module, false, ref_type, + error_buf, error_buf_size)) + return false; + *p_need_ref_type_map = true; +#if WASM_ENABLE_STRINGREF != 0 + /* covert (ref string) to stringref */ + if (wasm_is_refheaptype_stringrefs(&ref_type->ref_ht_common)) { + ref_type->ref_type = + (uint8)((int32)0x80 + ref_type->ref_ht_common.heap_type); + *p_need_ref_type_map = false; + } +#endif + } + else { + /* type which can be represented by one byte */ + if (!is_value_type(type) + && !(allow_packed_type && is_packed_type(type))) { + set_error_buf(error_buf, error_buf_size, "type mismatch"); + return false; + } + ref_type->ref_type = type; + *p_need_ref_type_map = false; +#if WASM_ENABLE_WAMR_COMPILER != 0 + /* If any value's type is v128, mark the module as SIMD used */ + if (type == VALUE_TYPE_V128) + module->is_simd_used = true; +#endif + } + + *p_buf = p; + return true; +fail: + return false; +} + +static WASMRefType * +reftype_set_insert(HashMap *ref_type_set, const WASMRefType *ref_type, + char *error_buf, uint32 error_buf_size) +{ + WASMRefType *ret = wasm_reftype_set_insert(ref_type_set, ref_type); + + if (!ret) { + set_error_buf(error_buf, error_buf_size, + "insert ref type to hash set failed"); + } + return ret; +} + +static bool +resolve_func_type(const uint8 **p_buf, const uint8 *buf_end, WASMModule *module, + uint32 type_idx, char *error_buf, uint32 error_buf_size) +{ + const uint8 *p = *p_buf, *p_end = buf_end, *p_org; + uint32 param_count, result_count, i, j = 0; + uint32 param_cell_num, ret_cell_num; + uint32 ref_type_map_count = 0, result_ref_type_map_count = 0; + uint64 total_size; + bool need_ref_type_map; + WASMRefType ref_type; + WASMFuncType *type = NULL; + + /* Parse first time to resolve param count, result count and + ref type map count */ + read_leb_uint32(p, p_end, param_count); + p_org = p; + for (i = 0; i < param_count; i++) { + if (!resolve_value_type(&p, p_end, module, &need_ref_type_map, + &ref_type, false, error_buf, error_buf_size)) { + return false; + } + if (need_ref_type_map) + ref_type_map_count++; + } + + read_leb_uint32(p, p_end, result_count); + for (i = 0; i < result_count; i++) { + if (!resolve_value_type(&p, p_end, module, &need_ref_type_map, + &ref_type, false, error_buf, error_buf_size)) { + return false; + } + if (need_ref_type_map) { + ref_type_map_count++; + result_ref_type_map_count++; + } + } + + LOG_VERBOSE("type %u: func, param count: %d, result count: %d, " + "ref type map count: %d", + type_idx, param_count, result_count, ref_type_map_count); + + /* Parse second time to resolve param types, result types and + ref type map info */ + p = p_org; + + total_size = offsetof(WASMFuncType, types) + + sizeof(uint8) * (uint64)(param_count + result_count); + if (!(type = loader_malloc(total_size, error_buf, error_buf_size))) { + return false; + } + if (ref_type_map_count > 0) { + total_size = sizeof(WASMRefTypeMap) * (uint64)ref_type_map_count; + if (!(type->ref_type_maps = + loader_malloc(total_size, error_buf, error_buf_size))) { + goto fail; + } + } + + type->base_type.type_flag = WASM_TYPE_FUNC; + type->param_count = param_count; + type->result_count = result_count; + type->ref_type_map_count = ref_type_map_count; + if (ref_type_map_count > 0) { + type->result_ref_type_maps = type->ref_type_maps + ref_type_map_count + - result_ref_type_map_count; + } + + for (i = 0; i < param_count; i++) { + if (!resolve_value_type(&p, p_end, module, &need_ref_type_map, + &ref_type, false, error_buf, error_buf_size)) { + goto fail; + } + type->types[i] = ref_type.ref_type; + if (need_ref_type_map) { + type->ref_type_maps[j].index = i; + if (!(type->ref_type_maps[j++].ref_type = + reftype_set_insert(module->ref_type_set, &ref_type, + error_buf, error_buf_size))) { + goto fail; + } + } + } + + read_leb_uint32(p, p_end, result_count); + for (i = 0; i < result_count; i++) { + if (!resolve_value_type(&p, p_end, module, &need_ref_type_map, + &ref_type, false, error_buf, error_buf_size)) { + goto fail; + } + type->types[param_count + i] = ref_type.ref_type; + if (need_ref_type_map) { + type->ref_type_maps[j].index = param_count + i; + if (!(type->ref_type_maps[j++].ref_type = + reftype_set_insert(module->ref_type_set, &ref_type, + error_buf, error_buf_size))) { + goto fail; + } + } + } + + bh_assert(j == type->ref_type_map_count); +#if TRACE_WASM_LOADER != 0 + os_printf("type %d = ", type_idx); + wasm_dump_func_type(type); +#endif + + param_cell_num = wasm_get_cell_num(type->types, param_count); + ret_cell_num = wasm_get_cell_num(type->types + param_count, result_count); + if (param_cell_num > UINT16_MAX || ret_cell_num > UINT16_MAX) { + set_error_buf(error_buf, error_buf_size, + "param count or result count too large"); + goto fail; + } + type->param_cell_num = (uint16)param_cell_num; + type->ret_cell_num = (uint16)ret_cell_num; + +#if WASM_ENABLE_QUICK_AOT_ENTRY != 0 + type->quick_aot_entry = wasm_native_lookup_quick_aot_entry(type); +#endif + +#if WASM_ENABLE_WAMR_COMPILER != 0 + for (i = 0; i < type->param_count + type->result_count; i++) { + if (type->types[i] == VALUE_TYPE_V128) + module->is_simd_used = true; + } +#endif + + /* Calculate the minimal type index of the type equal to this type */ + type->min_type_idx_normalized = type_idx; + for (i = 0; i < type_idx; i++) { + WASMFuncType *func_type = (WASMFuncType *)module->types[i]; + if (func_type->base_type.type_flag == WASM_TYPE_FUNC + && wasm_func_type_equal(type, func_type, module->types, + type_idx + 1)) { + type->min_type_idx_normalized = i; + break; + } + } + + *p_buf = p; + + module->types[type_idx] = (WASMType *)type; + return true; + +fail: + if (type) + destroy_func_type(type); + return false; +} + +static bool +resolve_struct_type(const uint8 **p_buf, const uint8 *buf_end, + WASMModule *module, uint32 type_idx, char *error_buf, + uint32 error_buf_size) +{ + const uint8 *p = *p_buf, *p_end = buf_end, *p_org; + uint32 field_count, ref_type_map_count = 0, ref_field_count = 0; + uint32 i, j = 0, offset; + uint16 *reference_table; + uint64 total_size; + uint8 mutable; + bool need_ref_type_map; + WASMRefType ref_type; + WASMStructType *type = NULL; + + /* Parse first time to resolve field count and ref type map count */ + read_leb_uint32(p, p_end, field_count); + p_org = p; + for (i = 0; i < field_count; i++) { + if (!resolve_value_type(&p, p_end, module, &need_ref_type_map, + &ref_type, true, error_buf, error_buf_size)) { + return false; + } + if (need_ref_type_map) + ref_type_map_count++; + + if (wasm_is_type_reftype(ref_type.ref_type)) + ref_field_count++; + + CHECK_BUF(p, p_end, 1); + mutable = read_uint8(p); + if (!check_mutability(mutable, error_buf, error_buf_size)) { + return false; + } + } + + LOG_VERBOSE("type %u: struct, field count: %d, ref type map count: %d", + type_idx, field_count, ref_type_map_count); + + /* Parse second time to resolve field types and ref type map info */ + p = p_org; + + total_size = offsetof(WASMStructType, fields) + + sizeof(WASMStructFieldType) * (uint64)field_count + + sizeof(uint16) * (uint64)(ref_field_count + 1); + if (!(type = loader_malloc(total_size, error_buf, error_buf_size))) { + return false; + } + if (ref_type_map_count > 0) { + total_size = sizeof(WASMRefTypeMap) * (uint64)ref_type_map_count; + if (!(type->ref_type_maps = + loader_malloc(total_size, error_buf, error_buf_size))) { + goto fail; + } + } + + type->reference_table = reference_table = + (uint16 *)((uint8 *)type + offsetof(WASMStructType, fields) + + sizeof(WASMStructFieldType) * field_count); + *reference_table++ = ref_field_count; + + type->base_type.type_flag = WASM_TYPE_STRUCT; + type->field_count = field_count; + type->ref_type_map_count = ref_type_map_count; + + offset = (uint32)offsetof(WASMStructObject, field_data); + for (i = 0; i < field_count; i++) { + if (!resolve_value_type(&p, p_end, module, &need_ref_type_map, + &ref_type, true, error_buf, error_buf_size)) { + goto fail; + } + type->fields[i].field_type = ref_type.ref_type; + if (need_ref_type_map) { + type->ref_type_maps[j].index = i; + if (!(type->ref_type_maps[j++].ref_type = + reftype_set_insert(module->ref_type_set, &ref_type, + error_buf, error_buf_size))) { + goto fail; + } + } + + CHECK_BUF(p, p_end, 1); + type->fields[i].field_flags = read_uint8(p); + type->fields[i].field_size = + (uint8)wasm_reftype_size(ref_type.ref_type); +#if !(defined(BUILD_TARGET_X86_64) || defined(BUILD_TARGET_AMD_64) \ + || defined(BUILD_TARGET_X86_32)) + if (type->fields[i].field_size == 2) + offset = align_uint(offset, 2); + else if (type->fields[i].field_size >= 4) /* field size is 4 or 8 */ + offset = align_uint(offset, 4); +#endif + type->fields[i].field_offset = offset; + if (wasm_is_type_reftype(ref_type.ref_type)) + *reference_table++ = offset; + offset += type->fields[i].field_size; + + LOG_VERBOSE(" field: %d, flags: %d, type: %d", i, + type->fields[i].field_flags, type->fields[i].field_type); + } + type->total_size = offset; + + bh_assert(j == type->ref_type_map_count); +#if TRACE_WASM_LOADER != 0 + os_printf("type %d = ", type_idx); + wasm_dump_struct_type(type); +#endif + + *p_buf = p; + + module->types[type_idx] = (WASMType *)type; + return true; + +fail: + if (type) + destroy_struct_type(type); + return false; +} + +static bool +resolve_array_type(const uint8 **p_buf, const uint8 *buf_end, + WASMModule *module, uint32 type_idx, char *error_buf, + uint32 error_buf_size) +{ + const uint8 *p = *p_buf, *p_end = buf_end; + uint8 mutable; + bool need_ref_type_map; + WASMRefType ref_type; + WASMArrayType *type = NULL; + + if (!resolve_value_type(&p, p_end, module, &need_ref_type_map, &ref_type, + true, error_buf, error_buf_size)) { + return false; + } + + CHECK_BUF(p, p_end, 1); + mutable = read_uint8(p); + if (!check_mutability(mutable, error_buf, error_buf_size)) { + return false; + } + + LOG_VERBOSE("type %u: array", type_idx); + + if (!(type = loader_malloc(sizeof(WASMArrayType), error_buf, + error_buf_size))) { + return false; + } + + type->base_type.type_flag = WASM_TYPE_ARRAY; + type->elem_flags = mutable; + type->elem_type = ref_type.ref_type; + if (need_ref_type_map) { + if (!(type->elem_ref_type = + reftype_set_insert(module->ref_type_set, &ref_type, error_buf, + error_buf_size))) { + goto fail; + } + } + +#if TRACE_WASM_LOADER != 0 + os_printf("type %d = ", type_idx); + wasm_dump_array_type(type); +#endif + + *p_buf = p; + + module->types[type_idx] = (WASMType *)type; + return true; + +fail: + if (type) + destroy_array_type(type); + return false; +} + +static bool +init_ref_type(WASMModule *module, WASMRefType *ref_type, bool nullable, + int32 heap_type, char *error_buf, uint32 error_buf_size) +{ + if (heap_type >= 0) { + if (!check_type_index(module, heap_type, error_buf, error_buf_size)) { + return false; + } + wasm_set_refheaptype_typeidx(&ref_type->ref_ht_typeidx, nullable, + heap_type); + } + else { + if (!wasm_is_valid_heap_type(heap_type)) { + set_error_buf(error_buf, error_buf_size, "unknown type"); + return false; + } + wasm_set_refheaptype_common(&ref_type->ref_ht_common, nullable, + heap_type); + if (nullable) { + /* For (ref null func/extern/any/eq/i31/data), + they are same as + funcref/externref/anyref/eqref/i31ref/dataref, + we convert the multi-byte type to one-byte + type to reduce the footprint and the + complexity of type equal/subtype checking */ + ref_type->ref_type = + (uint8)((int32)0x80 + ref_type->ref_ht_common.heap_type); + } + } + return true; +} + +static void +calculate_reftype_diff(WASMRefType *ref_type_diff, WASMRefType *ref_type1, + WASMRefType *ref_type2) +{ + /** + * The difference rt1 ∖ rt2 between two reference types is defined as + * follows: + * (ref null?1 ht1) ∖ (ref null ht2) = (ref ht1) (ref null?1 ht1) ∖ + * (ref ht2) = (ref null?1 ht1) + */ + if (wasm_is_type_multi_byte_type(ref_type1->ref_type)) { + bh_memcpy_s(ref_type_diff, wasm_reftype_struct_size(ref_type1), + ref_type1, wasm_reftype_struct_size(ref_type1)); + } + else { + ref_type_diff->ref_type = ref_type1->ref_type; + } + + if (ref_type2->ref_ht_common.nullable) { + if (wasm_is_type_reftype(ref_type_diff->ref_type) + && !(wasm_is_type_multi_byte_type(ref_type_diff->ref_type))) { + wasm_set_refheaptype_typeidx(&ref_type_diff->ref_ht_typeidx, false, + (int32)ref_type_diff->ref_type - 0x80); + } + else { + ref_type_diff->ref_ht_typeidx.nullable = false; + } + } +} +#else /* else of WASM_ENABLE_GC != 0 */ static void destroy_wasm_type(WASMType *type) { @@ -441,132 +1911,19 @@ destroy_wasm_type(WASMType *type) wasm_runtime_free(type); } - -static bool -load_init_expr(const uint8 **p_buf, const uint8 *buf_end, - InitializerExpression *init_expr, uint8 type, char *error_buf, - uint32 error_buf_size) -{ - const uint8 *p = *p_buf, *p_end = buf_end; - uint8 flag, end_byte, *p_float; - uint32 i; - - CHECK_BUF(p, p_end, 1); - init_expr->init_expr_type = read_uint8(p); - flag = init_expr->init_expr_type; - - switch (flag) { - /* i32.const */ - case INIT_EXPR_TYPE_I32_CONST: - if (type != VALUE_TYPE_I32) - goto fail_type_mismatch; - read_leb_int32(p, p_end, init_expr->u.i32); - break; - /* i64.const */ - case INIT_EXPR_TYPE_I64_CONST: - if (type != VALUE_TYPE_I64) - goto fail_type_mismatch; - read_leb_int64(p, p_end, init_expr->u.i64); - break; - /* f32.const */ - case INIT_EXPR_TYPE_F32_CONST: - if (type != VALUE_TYPE_F32) - goto fail_type_mismatch; - CHECK_BUF(p, p_end, 4); - p_float = (uint8 *)&init_expr->u.f32; - for (i = 0; i < sizeof(float32); i++) - *p_float++ = *p++; - break; - /* f64.const */ - case INIT_EXPR_TYPE_F64_CONST: - if (type != VALUE_TYPE_F64) - goto fail_type_mismatch; - CHECK_BUF(p, p_end, 8); - p_float = (uint8 *)&init_expr->u.f64; - for (i = 0; i < sizeof(float64); i++) - *p_float++ = *p++; - break; -#if WASM_ENABLE_SIMD != 0 -#if (WASM_ENABLE_WAMR_COMPILER != 0) || (WASM_ENABLE_JIT != 0) - case INIT_EXPR_TYPE_V128_CONST: - { - uint64 high, low; - - if (type != VALUE_TYPE_V128) - goto fail_type_mismatch; - - CHECK_BUF(p, p_end, 1); - flag = read_uint8(p); - (void)flag; - - CHECK_BUF(p, p_end, 16); - wasm_runtime_read_v128(p, &high, &low); - p += 16; - - init_expr->u.v128.i64x2[0] = high; - init_expr->u.v128.i64x2[1] = low; - break; - } -#endif /* end of (WASM_ENABLE_WAMR_COMPILER != 0) || (WASM_ENABLE_JIT != 0) */ -#endif /* end of WASM_ENABLE_SIMD */ -#if WASM_ENABLE_REF_TYPES != 0 - case INIT_EXPR_TYPE_FUNCREF_CONST: - { - if (type != VALUE_TYPE_FUNCREF) - goto fail_type_mismatch; - read_leb_uint32(p, p_end, init_expr->u.ref_index); - break; - } - case INIT_EXPR_TYPE_REFNULL_CONST: - { - uint8 reftype; - - CHECK_BUF(p, p_end, 1); - reftype = read_uint8(p); - if (reftype != type) - goto fail_type_mismatch; - - init_expr->u.ref_index = NULL_REF; - break; - } -#endif /* WASM_ENABLE_REF_TYPES != 0 */ - /* get_global */ - case INIT_EXPR_TYPE_GET_GLOBAL: - read_leb_uint32(p, p_end, init_expr->u.global_index); - break; - default: - { - set_error_buf(error_buf, error_buf_size, - "illegal opcode " - "or constant expression required " - "or type mismatch"); - goto fail; - } - } - CHECK_BUF(p, p_end, 1); - end_byte = read_uint8(p); - if (end_byte != 0x0b) - goto fail_type_mismatch; - *p_buf = p; - return true; - -fail_type_mismatch: - set_error_buf(error_buf, error_buf_size, - "type mismatch or constant expression required"); -fail: - return false; -} +#endif /* end of WASM_ENABLE_GC != 0 */ static bool load_type_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, char *error_buf, uint32 error_buf_size) { - const uint8 *p = buf, *p_end = buf_end, *p_org; - uint32 type_count, param_count, result_count, i, j; - uint32 param_cell_num, ret_cell_num; + const uint8 *p = buf, *p_end = buf_end; + uint32 type_count, i; uint64 total_size; uint8 flag; - WASMType *type; +#if WASM_ENABLE_GC != 0 + uint32 processed_type_count = 0; +#endif read_leb_uint32(p, p_end, type_count); @@ -578,7 +1935,13 @@ load_type_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, return false; } +#if WASM_ENABLE_GC == 0 for (i = 0; i < type_count; i++) { + WASMFuncType *type; + const uint8 *p_org; + uint32 param_count, result_count, j; + uint32 param_cell_num, ret_cell_num; + CHECK_BUF(p, p_end, 1); flag = read_uint8(p); if (flag != 0x60) { @@ -602,7 +1965,7 @@ load_type_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, return false; } - total_size = offsetof(WASMType, types) + total_size = offsetof(WASMFuncType, types) + sizeof(uint8) * (uint64)(param_count + result_count); if (!(type = module->types[i] = loader_malloc(total_size, error_buf, error_buf_size))) { @@ -645,9 +2008,19 @@ load_type_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, type->quick_aot_entry = wasm_native_lookup_quick_aot_entry(type); #endif +#if WASM_ENABLE_WAMR_COMPILER != 0 + for (j = 0; j < type->param_count + type->result_count; j++) { + if (type->types[j] == VALUE_TYPE_V128) + module->is_simd_used = true; + else if (type->types[j] == VALUE_TYPE_FUNCREF + || type->types[j] == VALUE_TYPE_EXTERNREF) + module->is_ref_types_used = true; + } +#endif + /* If there is already a same type created, use it instead */ for (j = 0; j < i; j++) { - if (wasm_type_equal(type, module->types[j])) { + if (wasm_type_equal(type, module->types[j], module->types, i)) { if (module->types[j]->ref_count == UINT16_MAX) { set_error_buf(error_buf, error_buf_size, "wasm type's ref count too large"); @@ -660,6 +2033,162 @@ load_type_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, } } } +#else /* else of WASM_ENABLE_GC == 0 */ + for (i = 0; i < type_count; i++) { + uint32 super_type_count = 0, parent_type_idx = (uint32)-1, + rec_count = 1, j; + bool is_sub_final = true; + + CHECK_BUF(p, p_end, 1); + flag = read_uint8(p); + + if (flag == DEFINED_TYPE_REC) { + read_leb_uint32(p, p_end, rec_count); + + if (rec_count > 1) { + uint64 new_total_size; + + module->type_count += rec_count - 1; + new_total_size = + sizeof(WASMFuncType *) * (uint64)module->type_count; + MEM_REALLOC(module->types, total_size, new_total_size); + total_size = new_total_size; + } + + LOG_VERBOSE("Processing rec group [%d-%d]", + processed_type_count, + processed_type_count + rec_count - 1); + } + else { + p--; + } + + for (j = 0; j < rec_count; j++) { + WASMType *cur_type = NULL; + + CHECK_BUF(p, p_end, 1); + flag = read_uint8(p); + + parent_type_idx = -1; + + if (flag == DEFINED_TYPE_SUB + || flag == DEFINED_TYPE_SUB_FINAL) { + read_leb_uint32(p, p_end, super_type_count); + if (super_type_count > 1) { + set_error_buf(error_buf, error_buf_size, + "super type count too large"); + return false; + } + + if (super_type_count > 0) { + read_leb_uint32(p, p_end, parent_type_idx); + if (parent_type_idx >= processed_type_count + j) { + set_error_buf_v(error_buf, error_buf_size, + "unknown type %d", parent_type_idx); + return false; + } + if (module->types[parent_type_idx]->is_sub_final) { + set_error_buf(error_buf, error_buf_size, + "sub type can not inherit from " + "a final super type"); + return false; + } + } + + if (flag == DEFINED_TYPE_SUB) + is_sub_final = false; + + CHECK_BUF(p, p_end, 1); + flag = read_uint8(p); + } + + if (flag == DEFINED_TYPE_FUNC) { + if (!resolve_func_type(&p, buf_end, module, + processed_type_count + j, error_buf, + error_buf_size)) { + return false; + } + } + else if (flag == DEFINED_TYPE_STRUCT) { + if (!resolve_struct_type(&p, buf_end, module, + processed_type_count + j, + error_buf, error_buf_size)) { + return false; + } + } + else if (flag == DEFINED_TYPE_ARRAY) { + if (!resolve_array_type(&p, buf_end, module, + processed_type_count + j, error_buf, + error_buf_size)) { + return false; + } + } + else { + set_error_buf(error_buf, error_buf_size, + "invalid type flag"); + return false; + } + + cur_type = module->types[processed_type_count + j]; + + cur_type->parent_type_idx = parent_type_idx; + cur_type->is_sub_final = is_sub_final; + + if (rec_count > 1) { + cur_type->rec_count = rec_count; + cur_type->rec_idx = j; + } + } + + /* resolve subtyping relationship in current rec group */ + for (j = 0; j < rec_count; j++) { + WASMType *cur_type = module->types[processed_type_count + j]; + + if (cur_type->parent_type_idx != (uint32)-1) { /* has parent */ + WASMType *parent_type = + module->types[cur_type->parent_type_idx]; + cur_type->parent_type = parent_type; + cur_type->root_type = parent_type->root_type; + cur_type->inherit_depth = parent_type->inherit_depth + 1; + } + else { + cur_type->parent_type = NULL; + cur_type->root_type = cur_type; + cur_type->inherit_depth = 0; + } + } + + for (j = 0; j < rec_count; j++) { + WASMType *cur_type = module->types[processed_type_count + j]; + + if (cur_type->parent_type_idx != (uint32)-1) { /* has parent */ + WASMType *parent_type = + module->types[cur_type->parent_type_idx]; + if (!wasm_type_is_subtype_of(cur_type, parent_type, + module->types, + module->type_count)) { + set_error_buf(error_buf, error_buf_size, + "sub type does not match super type"); + return false; + } + } + } + + if (rec_count > 1) { + LOG_VERBOSE("Finished processing rec group [%d-%d]", + processed_type_count, + processed_type_count + rec_count - 1); + } + + processed_type_count += rec_count; + } + + if (!(module->rtt_types = loader_malloc((uint64)sizeof(WASMRttType *) + * module->type_count, + error_buf, error_buf_size))) { + return false; + } +#endif /* end of WASM_ENABLE_GC == 0 */ } if (p != p_end) { @@ -676,8 +2205,9 @@ fail: static void adjust_table_max_size(uint32 init_size, uint32 max_size_flag, uint32 *max_size) { - uint32 default_max_size = - init_size * 2 > TABLE_MAX_SIZE ? init_size * 2 : TABLE_MAX_SIZE; + uint32 default_max_size = init_size * 2 > WASM_TABLE_MAX_SIZE + ? init_size * 2 + : WASM_TABLE_MAX_SIZE; if (max_size_flag) { /* module defines the table limitation */ @@ -714,14 +2244,14 @@ wasm_loader_find_export(const WASMModule *module, const char *module_name, #if WASM_ENABLE_MULTI_MODULE != 0 static WASMFunction * wasm_loader_resolve_function(const char *module_name, const char *function_name, - const WASMType *expected_function_type, + const WASMFuncType *expected_function_type, char *error_buf, uint32 error_buf_size) { WASMModuleCommon *module_reg; WASMFunction *function = NULL; WASMExport *export = NULL; WASMModule *module = NULL; - WASMType *target_function_type = NULL; + WASMFuncType *target_function_type = NULL; module_reg = wasm_runtime_find_module_registered(module_name); if (!module_reg || module_reg->module_type != Wasm_Module_Bytecode) { @@ -755,7 +2285,9 @@ wasm_loader_resolve_function(const char *module_name, const char *function_name, } /* check function type */ - if (!wasm_type_equal(expected_function_type, target_function_type)) { + if (!wasm_type_equal((WASMType *)expected_function_type, + (WASMType *)target_function_type, module->types, + module->type_count)) { LOG_DEBUG("%s.%s failed the type check", module_name, function_name); set_error_buf(error_buf, error_buf_size, "incompatible import type"); return NULL; @@ -948,7 +2480,7 @@ wasm_loader_resolve_tag(const char *module_name, const char *tag_name, return tag; } -#endif +#endif /* end of WASM_ENABLE_TAGS != 0 */ #endif /* end of WASM_ENABLE_MULTI_MODULE */ static bool @@ -960,7 +2492,7 @@ load_function_import(const uint8 **p_buf, const uint8 *buf_end, { const uint8 *p = *p_buf, *p_end = buf_end; uint32 declare_type_index = 0; - WASMType *declare_func_type = NULL; + WASMFuncType *declare_func_type = NULL; WASMFunction *linked_func = NULL; #if WASM_ENABLE_MULTI_MODULE != 0 WASMModule *sub_module = NULL; @@ -978,12 +2510,17 @@ load_function_import(const uint8 **p_buf, const uint8 *buf_end, return false; } +#if WASM_ENABLE_GC != 0 + function->type_idx = declare_type_index; +#endif + #if (WASM_ENABLE_WAMR_COMPILER != 0) || (WASM_ENABLE_JIT != 0) declare_type_index = wasm_get_smallest_type_idx( parent_module->types, parent_module->type_count, declare_type_index); #endif - declare_func_type = parent_module->types[declare_type_index]; + declare_func_type = + (WASMFuncType *)parent_module->types[declare_type_index]; /* lookup registered native symbols first */ linked_func = wasm_native_resolve_symbol( @@ -1050,7 +2587,12 @@ load_table_import(const uint8 **p_buf, const uint8 *buf_end, WASMModule *sub_module = NULL; WASMTable *linked_table = NULL; #endif +#if WASM_ENABLE_GC != 0 + WASMRefType ref_type; + bool need_ref_type_map; +#endif +#if WASM_ENABLE_GC == 0 CHECK_BUF(p, p_end, 1); /* 0x70 or 0x6F */ declare_elem_type = read_uint8(p); @@ -1062,6 +2604,29 @@ load_table_import(const uint8 **p_buf, const uint8 *buf_end, set_error_buf(error_buf, error_buf_size, "incompatible import type"); return false; } +#else /* else of WASM_ENABLE_GC == 0 */ + if (!resolve_value_type(&p, p_end, parent_module, &need_ref_type_map, + &ref_type, false, error_buf, error_buf_size)) { + return false; + } + if (wasm_is_reftype_htref_non_nullable(ref_type.ref_type)) { + set_error_buf(error_buf, error_buf_size, "type mismatch"); + return false; + } + declare_elem_type = ref_type.ref_type; + if (need_ref_type_map) { + if (!(table->elem_ref_type = + reftype_set_insert(parent_module->ref_type_set, &ref_type, + error_buf, error_buf_size))) { + return false; + } + } +#if TRACE_WASM_LOADER != 0 + os_printf("import table type: "); + wasm_dump_value_type(declare_elem_type, table->elem_ref_type); + os_printf("\n"); +#endif +#endif /* end of WASM_ENABLE_GC == 0 */ read_leb_uint32(p, p_end, declare_max_size_flag); if (declare_max_size_flag > 1) { @@ -1138,6 +2703,10 @@ load_table_import(const uint8 **p_buf, const uint8 *buf_end, table->flags = declare_max_size_flag; table->max_size = declare_max_size; +#if WASM_ENABLE_WAMR_COMPILER != 0 + if (table->elem_type == VALUE_TYPE_EXTERNREF) + parent_module->is_ref_types_used = true; +#endif (void)parent_module; return true; fail: @@ -1369,11 +2938,11 @@ load_tag_import(const uint8 **p_buf, const uint8 *buf_end, fail: return false; } -#endif +#endif /* end of WASM_ENABLE_TAGS != 0 */ static bool load_global_import(const uint8 **p_buf, const uint8 *buf_end, - const WASMModule *parent_module, char *sub_module_name, + WASMModule *parent_module, char *sub_module_name, char *global_name, WASMGlobalImport *global, char *error_buf, uint32 error_buf_size) { @@ -1383,16 +2952,42 @@ load_global_import(const uint8 **p_buf, const uint8 *buf_end, #if WASM_ENABLE_MULTI_MODULE != 0 WASMModule *sub_module = NULL; WASMGlobal *linked_global = NULL; +#endif +#if WASM_ENABLE_GC != 0 + WASMRefType ref_type; + bool need_ref_type_map; #endif bool ret = false; +#if WASM_ENABLE_GC == 0 CHECK_BUF(p, p_end, 2); declare_type = read_uint8(p); declare_mutable = read_uint8(p); +#else + if (!resolve_value_type(&p, p_end, parent_module, &need_ref_type_map, + &ref_type, false, error_buf, error_buf_size)) { + return false; + } + declare_type = ref_type.ref_type; + if (need_ref_type_map) { + if (!(global->ref_type = + reftype_set_insert(parent_module->ref_type_set, &ref_type, + error_buf, error_buf_size))) { + return false; + } + } +#if TRACE_WASM_LOADER != 0 + os_printf("import global type: "); + wasm_dump_value_type(declare_type, global->ref_type); + os_printf("\n"); +#endif + CHECK_BUF(p, p_end, 1); + declare_mutable = read_uint8(p); +#endif /* end of WASM_ENABLE_GC == 0 */ + *p_buf = p; - if (declare_mutable >= 2) { - set_error_buf(error_buf, error_buf_size, "invalid mutability"); + if (!check_mutability(declare_mutable, error_buf, error_buf_size)) { return false; } @@ -1436,6 +3031,12 @@ load_global_import(const uint8 **p_buf, const uint8 *buf_end, global->type = declare_type; global->is_mutable = (declare_mutable == 1); +#if WASM_ENABLE_WAMR_COMPILER != 0 + if (global->type == VALUE_TYPE_V128) + parent_module->is_simd_used = true; + else if (global->type == VALUE_TYPE_EXTERNREF) + parent_module->is_ref_types_used = true; +#endif (void)parent_module; (void)ret; return true; @@ -1444,11 +3045,16 @@ fail: } static bool -load_table(const uint8 **p_buf, const uint8 *buf_end, WASMTable *table, - char *error_buf, uint32 error_buf_size) +load_table(const uint8 **p_buf, const uint8 *buf_end, WASMModule *module, + WASMTable *table, char *error_buf, uint32 error_buf_size) { const uint8 *p = *p_buf, *p_end = buf_end, *p_org; +#if WASM_ENABLE_GC != 0 + WASMRefType ref_type; + bool need_ref_type_map; +#endif +#if WASM_ENABLE_GC == 0 CHECK_BUF(p, p_end, 1); /* 0x70 or 0x6F */ table->elem_type = read_uint8(p); @@ -1460,6 +3066,25 @@ load_table(const uint8 **p_buf, const uint8 *buf_end, WASMTable *table, set_error_buf(error_buf, error_buf_size, "incompatible import type"); return false; } +#else /* else of WASM_ENABLE_GC == 0 */ + if (!resolve_value_type(&p, p_end, module, &need_ref_type_map, &ref_type, + false, error_buf, error_buf_size)) { + return false; + } + table->elem_type = ref_type.ref_type; + if (need_ref_type_map) { + if (!(table->elem_ref_type = + reftype_set_insert(module->ref_type_set, &ref_type, error_buf, + error_buf_size))) { + return false; + } + } +#if TRACE_WASM_LOADER != 0 + os_printf("table type: "); + wasm_dump_value_type(table->elem_type, table->elem_ref_type); + os_printf("\n"); +#endif +#endif /* end of WASM_ENABLE_GC == 0 */ p_org = p; read_leb_uint32(p, p_end, table->flags); @@ -1499,6 +3124,11 @@ load_table(const uint8 **p_buf, const uint8 *buf_end, WASMTable *table, adjust_table_max_size(table->init_size, table->flags, &table->max_size); +#if WASM_ENABLE_WAMR_COMPILER != 0 + if (table->elem_type == VALUE_TYPE_EXTERNREF) + module->is_ref_types_used = true; +#endif + *p_buf = p; return true; fail: @@ -1596,7 +3226,7 @@ load_import_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, WASMImport *import_tags = NULL; #endif char *sub_module_name, *field_name; - uint8 u8, kind; + uint8 u8, kind, global_type; read_leb_uint32(p, p_end, import_count); @@ -1642,13 +3272,15 @@ load_import_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, read_leb_uint32(p, p_end, u32); module->import_table_count++; -#if WASM_ENABLE_REF_TYPES == 0 if (module->import_table_count > 1) { +#if WASM_ENABLE_REF_TYPES == 0 && WASM_ENABLE_GC == 0 set_error_buf(error_buf, error_buf_size, "multiple tables"); return false; - } +#elif WASM_ENABLE_WAMR_COMPILER != 0 + module->is_ref_types_used = true; #endif + } break; case IMPORT_KIND_MEMORY: /* import memory */ @@ -1675,8 +3307,25 @@ load_import_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, #endif case IMPORT_KIND_GLOBAL: /* import global */ +#if WASM_ENABLE_GC != 0 + /* valtype */ + CHECK_BUF(p, p_end, 1); + global_type = read_uint8(p); + if (wasm_is_type_multi_byte_type(global_type)) { + int32 heap_type; + read_leb_int32(p, p_end, heap_type); + (void)heap_type; + } + + /* mutability */ + CHECK_BUF(p, p_end, 1); + p += 1; +#else CHECK_BUF(p, p_end, 2); p += 2; +#endif + + (void)global_type; module->import_global_count++; break; @@ -1838,7 +3487,7 @@ static bool init_function_local_offsets(WASMFunction *func, char *error_buf, uint32 error_buf_size) { - WASMType *param_type = func->func_type; + WASMFuncType *param_type = func->func_type; uint32 param_count = param_type->param_count; uint8 *param_types = param_type->types; uint32 local_count = func->local_count; @@ -1885,6 +3534,11 @@ load_function_section(const uint8 *buf, const uint8 *buf_end, uint32 local_count, local_set_count, sub_local_count, local_cell_num; uint8 type; WASMFunction *func; +#if WASM_ENABLE_GC != 0 + bool need_ref_type_map; + WASMRefType ref_type; + uint32 ref_type_map_count = 0, t = 0, type_index_org; +#endif read_leb_uint32(p, p_end, func_count); @@ -1914,6 +3568,10 @@ load_function_section(const uint8 *buf, const uint8 *buf_end, return false; } +#if WASM_ENABLE_GC != 0 + type_index_org = type_index; +#endif + #if (WASM_ENABLE_WAMR_COMPILER != 0) || (WASM_ENABLE_JIT != 0) type_index = wasm_get_smallest_type_idx( module->types, module->type_count, type_index); @@ -1932,6 +3590,10 @@ load_function_section(const uint8 *buf, const uint8 *buf_end, read_leb_uint32(p_code, buf_code_end, local_set_count); p_code_save = p_code; +#if WASM_ENABLE_GC != 0 + ref_type_map_count = 0; +#endif + /* Calculate total local count */ for (j = 0; j < local_set_count; j++) { read_leb_uint32(p_code, buf_code_end, sub_local_count); @@ -1939,10 +3601,26 @@ load_function_section(const uint8 *buf, const uint8 *buf_end, set_error_buf(error_buf, error_buf_size, "too many locals"); return false; } +#if WASM_ENABLE_GC == 0 CHECK_BUF(p_code, buf_code_end, 1); /* 0x7F/0x7E/0x7D/0x7C */ type = read_uint8(p_code); local_count += sub_local_count; +#if WASM_ENABLE_WAMR_COMPILER != 0 + /* If any value's type is v128, mark the module as SIMD used */ + if (type == VALUE_TYPE_V128) + module->is_simd_used = true; +#endif +#else + if (!resolve_value_type(&p_code, buf_code_end, module, + &need_ref_type_map, &ref_type, false, + error_buf, error_buf_size)) { + return false; + } + local_count += sub_local_count; + if (need_ref_type_map) + ref_type_map_count += sub_local_count; +#endif } /* Alloc memory, layout: function structure + local types */ @@ -1953,9 +3631,20 @@ load_function_section(const uint8 *buf, const uint8 *buf_end, loader_malloc(total_size, error_buf, error_buf_size))) { return false; } +#if WASM_ENABLE_GC != 0 + if (ref_type_map_count > 0) { + total_size = + sizeof(WASMRefTypeMap) * (uint64)ref_type_map_count; + if (!(func->local_ref_type_maps = loader_malloc( + total_size, error_buf, error_buf_size))) { + return false; + } + func->local_ref_type_map_count = ref_type_map_count; + } +#endif /* Set function type, local count, code size and code body */ - func->func_type = module->types[type_index]; + func->func_type = (WASMFuncType *)module->types[type_index]; func->local_count = local_count; if (local_count > 0) func->local_types = (uint8 *)func + sizeof(WASMFunction); @@ -1971,6 +3660,13 @@ load_function_section(const uint8 *buf, const uint8 *buf_end, * func->code = code_body_cp; */ func->code = (uint8 *)p_code; +#if WASM_ENABLE_GC != 0 + func->type_idx = type_index_org; +#endif + +#if WASM_ENABLE_GC != 0 + t = 0; +#endif /* Load each local type */ p_code = p_code_save; @@ -1984,6 +3680,7 @@ load_function_section(const uint8 *buf, const uint8 *buf_end, "invalid local count"); return false; } +#if WASM_ENABLE_GC == 0 CHECK_BUF(p_code, buf_code_end, 1); /* 0x7F/0x7E/0x7D/0x7C */ type = read_uint8(p_code); @@ -2001,11 +3698,61 @@ load_function_section(const uint8 *buf, const uint8 *buf_end, "invalid local type 0x%02X", type); return false; } +#else + if (!resolve_value_type(&p_code, buf_code_end, module, + &need_ref_type_map, &ref_type, false, + error_buf, error_buf_size)) { + return false; + } + if (need_ref_type_map) { + WASMRefType *ref_type_tmp; + if (!(ref_type_tmp = reftype_set_insert( + module->ref_type_set, &ref_type, error_buf, + error_buf_size))) { + return false; + } + for (k = 0; k < sub_local_count; k++) { + func->local_ref_type_maps[t + k].ref_type = + ref_type_tmp; + func->local_ref_type_maps[t + k].index = + local_type_index + k; + } + t += sub_local_count; + } + type = ref_type.ref_type; +#endif for (k = 0; k < sub_local_count; k++) { func->local_types[local_type_index++] = type; } +#if WASM_ENABLE_WAMR_COMPILER != 0 + if (type == VALUE_TYPE_V128) + module->is_simd_used = true; + else if (type == VALUE_TYPE_FUNCREF + || type == VALUE_TYPE_EXTERNREF) + module->is_ref_types_used = true; +#endif } + bh_assert(local_type_index == func->local_count); +#if WASM_ENABLE_GC != 0 + bh_assert(t == func->local_ref_type_map_count); +#if TRACE_WASM_LOADER != 0 + os_printf("func %u, local types: [", i); + k = 0; + for (j = 0; j < func->local_count; j++) { + WASMRefType *ref_type_tmp = NULL; + if (wasm_is_type_multi_byte_type(func->local_types[j])) { + bh_assert(j == func->local_ref_type_maps[k].index); + ref_type_tmp = func->local_ref_type_maps[k++].ref_type; + } + wasm_dump_value_type(func->local_types[j], ref_type_tmp); + if (j < func->local_count - 1) + os_printf(" "); + } + os_printf("]\n"); +#endif +#endif + func->param_cell_num = func->func_type->param_cell_num; func->ret_cell_num = func->func_type->ret_cell_num; local_cell_num = @@ -2037,19 +3784,6 @@ fail: return false; } -static bool -check_function_index(const WASMModule *module, uint32 function_index, - char *error_buf, uint32 error_buf_size) -{ - if (function_index - >= module->import_function_count + module->function_count) { - set_error_buf_v(error_buf, error_buf_size, "unknown function %d", - function_index); - return false; - } - return true; -} - static bool load_table_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, char *error_buf, uint32 error_buf_size) @@ -2060,13 +3794,15 @@ load_table_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, WASMTable *table; read_leb_uint32(p, p_end, table_count); -#if WASM_ENABLE_REF_TYPES == 0 if (module->import_table_count + table_count > 1) { +#if WASM_ENABLE_REF_TYPES == 0 && WASM_ENABLE_GC == 0 /* a total of one table is allowed */ set_error_buf(error_buf, error_buf_size, "multiple tables"); return false; - } +#elif WASM_ENABLE_WAMR_COMPILER != 0 + module->is_ref_types_used = true; #endif + } if (table_count) { module->table_count = table_count; @@ -2078,9 +3814,64 @@ load_table_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, /* load each table */ table = module->tables; - for (i = 0; i < table_count; i++, table++) - if (!load_table(&p, p_end, table, error_buf, error_buf_size)) + for (i = 0; i < table_count; i++, table++) { +#if WASM_ENABLE_GC != 0 + uint8 flag; + bool has_init = false; + + CHECK_BUF(buf, buf_end, 1); + flag = read_uint8(p); + + if (flag == TABLE_INIT_EXPR_FLAG) { + CHECK_BUF(buf, buf_end, 1); + flag = read_uint8(p); + + if (flag != 0x00) { + set_error_buf(error_buf, error_buf_size, + "invalid leading bytes for table"); + return false; + } + has_init = true; + } + else { + p--; + } +#endif /* end of WASM_ENABLE_GC != 0 */ + + if (!load_table(&p, p_end, module, table, error_buf, + error_buf_size)) return false; + +#if WASM_ENABLE_GC != 0 + if (has_init) { + if (!load_init_expr(module, &p, p_end, &table->init_expr, + table->elem_type, table->elem_ref_type, + error_buf, error_buf_size)) + return false; + if (table->init_expr.init_expr_type >= INIT_EXPR_TYPE_STRUCT_NEW + && table->init_expr.init_expr_type + <= INIT_EXPR_TYPE_ARRAY_NEW_FIXED) { + set_error_buf( + error_buf, error_buf_size, + "unsupported initializer expression for table"); + return false; + } + } + else { + if (wasm_is_reftype_htref_non_nullable(table->elem_type)) { + set_error_buf( + error_buf, error_buf_size, + "type mismatch: non-nullable table without init expr"); + return false; + } + } +#endif /* end of WASM_ENABLE_GC != 0 */ + +#if WASM_ENABLE_WAMR_COMPILER != 0 + if (table->elem_type == VALUE_TYPE_EXTERNREF) + module->is_ref_types_used = true; +#endif + } } if (p != p_end) { @@ -2145,11 +3936,15 @@ load_global_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, uint64 total_size; WASMGlobal *global; uint8 mutable; +#if WASM_ENABLE_GC != 0 + bool need_ref_type_map; + WASMRefType ref_type; +#endif read_leb_uint32(p, p_end, global_count); + module->global_count = 0; if (global_count) { - module->global_count = global_count; total_size = sizeof(WASMGlobal) * (uint64)global_count; if (!(module->globals = loader_malloc(total_size, error_buf, error_buf_size))) { @@ -2159,41 +3954,97 @@ load_global_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, global = module->globals; for (i = 0; i < global_count; i++, global++) { +#if WASM_ENABLE_GC == 0 CHECK_BUF(p, p_end, 2); global->type = read_uint8(p); mutable = read_uint8(p); - if (mutable >= 2) { - set_error_buf(error_buf, error_buf_size, "invalid mutability"); +#else + if (!resolve_value_type(&p, p_end, module, &need_ref_type_map, + &ref_type, false, error_buf, + error_buf_size)) { + return false; + } + global->type = ref_type.ref_type; + CHECK_BUF(p, p_end, 1); + mutable = read_uint8(p); +#endif /* end of WASM_ENABLE_GC */ + +#if WASM_ENABLE_WAMR_COMPILER != 0 + if (global->type == VALUE_TYPE_V128) + module->is_simd_used = true; + else if (global->type == VALUE_TYPE_FUNCREF + || global->type == VALUE_TYPE_EXTERNREF) + module->is_ref_types_used = true; +#endif + + if (!check_mutability(mutable, error_buf, error_buf_size)) { return false; } global->is_mutable = mutable ? true : false; /* initialize expression */ - if (!load_init_expr(&p, p_end, &(global->init_expr), global->type, + if (!load_init_expr(module, &p, p_end, &(global->init_expr), + global->type, +#if WASM_ENABLE_GC == 0 + NULL, +#else + &ref_type, +#endif error_buf, error_buf_size)) return false; - if (INIT_EXPR_TYPE_GET_GLOBAL == global->init_expr.init_expr_type) { - /** - * Currently, constant expressions occurring as initializers - * of globals are further constrained in that contained - * global.get instructions are - * only allowed to refer to imported globals. - */ - uint32 target_global_index = global->init_expr.u.global_index; - if (target_global_index >= module->import_global_count) { +#if WASM_ENABLE_GC != 0 + if (global->init_expr.init_expr_type == INIT_EXPR_TYPE_GET_GLOBAL) { + uint8 global_type; + WASMRefType *global_ref_type; + uint32 global_idx = global->init_expr.u.global_index; + + if (global->init_expr.u.global_index + >= module->import_global_count + i) { set_error_buf(error_buf, error_buf_size, "unknown global"); return false; } - } - else if (INIT_EXPR_TYPE_FUNCREF_CONST - == global->init_expr.init_expr_type) { - if (!check_function_index(module, global->init_expr.u.ref_index, - error_buf, error_buf_size)) { + + if (global_idx < module->import_global_count) { + global_type = + module->import_globals[global_idx].u.global.type; + global_ref_type = + module->import_globals[global_idx].u.global.ref_type; + } + else { + global_type = + module + ->globals[global_idx - module->import_global_count] + .type; + global_ref_type = + module + ->globals[global_idx - module->import_global_count] + .ref_type; + } + if (!wasm_reftype_is_subtype_of( + global_type, global_ref_type, global->type, + global->ref_type, module->types, module->type_count)) { + set_error_buf(error_buf, error_buf_size, "type mismatch"); return false; } } + + if (need_ref_type_map) { + if (!(global->ref_type = + reftype_set_insert(module->ref_type_set, &ref_type, + error_buf, error_buf_size))) { + return false; + } + } +#if TRACE_WASM_LOADER != 0 + os_printf("global type: "); + wasm_dump_value_type(global->type, global->ref_type); + os_printf("\n"); +#endif +#endif + module->global_count++; } + bh_assert(module->global_count == global_count); } if (p != p_end) { @@ -2341,7 +4192,7 @@ static bool check_table_index(const WASMModule *module, uint32 table_index, char *error_buf, uint32 error_buf_size) { -#if WASM_ENABLE_REF_TYPES == 0 +#if WASM_ENABLE_REF_TYPES == 0 && WASM_ENABLE_GC == 0 if (table_index != 0) { set_error_buf(error_buf, error_buf_size, "zero byte expected"); return false; @@ -2375,78 +4226,103 @@ fail: return false; } -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 static bool -load_elem_type(const uint8 **p_buf, const uint8 *buf_end, uint32 *p_elem_type, +load_elem_type(WASMModule *module, const uint8 **p_buf, const uint8 *buf_end, + uint32 *p_elem_type, +#if WASM_ENABLE_GC != 0 + WASMRefType **p_elem_ref_type, +#endif bool elemkind_zero, char *error_buf, uint32 error_buf_size) { const uint8 *p = *p_buf, *p_end = buf_end; uint8 elem_type; +#if WASM_ENABLE_GC != 0 + WASMRefType elem_ref_type; + bool need_ref_type_map; +#endif CHECK_BUF(p, p_end, 1); elem_type = read_uint8(p); - if ((elemkind_zero && elem_type != 0) - || (!elemkind_zero && elem_type != VALUE_TYPE_FUNCREF - && elem_type != VALUE_TYPE_EXTERNREF)) { - set_error_buf(error_buf, error_buf_size, "invalid reference type"); - return false; + if (elemkind_zero) { + if (elem_type != 0) { + set_error_buf(error_buf, error_buf_size, + "invalid reference type or unknown type"); + return false; + } + else { + *p_elem_type = VALUE_TYPE_FUNCREF; + *p_buf = p; + return true; + } } - if (elemkind_zero) - *p_elem_type = VALUE_TYPE_FUNCREF; - else - *p_elem_type = elem_type; +#if WASM_ENABLE_GC == 0 + if (elem_type != VALUE_TYPE_FUNCREF && elem_type != VALUE_TYPE_EXTERNREF) { + set_error_buf(error_buf, error_buf_size, + "invalid reference type or unknown type"); + return false; + } + *p_elem_type = elem_type; +#else + p--; + if (!resolve_value_type((const uint8 **)&p, p_end, module, + &need_ref_type_map, &elem_ref_type, false, + error_buf, error_buf_size)) { + return false; + } + if (!wasm_is_type_reftype(elem_ref_type.ref_type)) { + set_error_buf(error_buf, error_buf_size, + "invalid reference type or unknown type"); + return false; + } + *p_elem_type = elem_ref_type.ref_type; + if (need_ref_type_map) { + if (!(*p_elem_ref_type = + reftype_set_insert(module->ref_type_set, &elem_ref_type, + error_buf, error_buf_size))) { + return false; + } + } +#endif + *p_buf = p; return true; fail: return false; } -#endif /* WASM_ENABLE_REF_TYPES != 0*/ +#endif /* end of WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */ static bool load_func_index_vec(const uint8 **p_buf, const uint8 *buf_end, WASMModule *module, WASMTableSeg *table_segment, - bool use_init_expr, char *error_buf, uint32 error_buf_size) + char *error_buf, uint32 error_buf_size) { const uint8 *p = *p_buf, *p_end = buf_end; uint32 function_count, function_index = 0, i; uint64 total_size; read_leb_uint32(p, p_end, function_count); - table_segment->function_count = function_count; - total_size = sizeof(uint32) * (uint64)function_count; + table_segment->value_count = function_count; + total_size = sizeof(InitializerExpression) * (uint64)function_count; if (total_size > 0 - && !(table_segment->func_indexes = (uint32 *)loader_malloc( - total_size, error_buf, error_buf_size))) { + && !(table_segment->init_values = + (InitializerExpression *)loader_malloc(total_size, error_buf, + error_buf_size))) { return false; } for (i = 0; i < function_count; i++) { - InitializerExpression init_expr = { 0 }; + InitializerExpression *init_expr = &table_segment->init_values[i]; -#if WASM_ENABLE_REF_TYPES != 0 - if (!use_init_expr) { - read_leb_uint32(p, p_end, function_index); - } - else { - if (!load_init_expr(&p, p_end, &init_expr, table_segment->elem_type, - error_buf, error_buf_size)) - return false; - - function_index = init_expr.u.ref_index; - } -#else read_leb_uint32(p, p_end, function_index); - (void)use_init_expr; -#endif - - /* since we are using -1 to indicate ref.null */ - if (init_expr.init_expr_type != INIT_EXPR_TYPE_REFNULL_CONST - && !check_function_index(module, function_index, error_buf, - error_buf_size)) { + if (!check_function_index(module, function_index, error_buf, + error_buf_size)) { return false; } - table_segment->func_indexes[i] = function_index; + + init_expr->init_expr_type = INIT_EXPR_TYPE_FUNCREF_CONST; + init_expr->u.ref_index = function_index; } *p_buf = p; @@ -2455,6 +4331,53 @@ fail: return false; } +#if (WASM_ENABLE_GC != 0) || (WASM_ENABLE_REF_TYPES != 0) +static bool +load_init_expr_vec(const uint8 **p_buf, const uint8 *buf_end, + WASMModule *module, WASMTableSeg *table_segment, + char *error_buf, uint32 error_buf_size) +{ + const uint8 *p = *p_buf, *p_end = buf_end; + uint32 ref_count, i; + uint64 total_size; + + read_leb_uint32(p, p_end, ref_count); + table_segment->value_count = ref_count; + total_size = sizeof(InitializerExpression) * (uint64)ref_count; + if (total_size > 0 + && !(table_segment->init_values = + (InitializerExpression *)loader_malloc(total_size, error_buf, + error_buf_size))) { + return false; + } + + for (i = 0; i < ref_count; i++) { + InitializerExpression *init_expr = &table_segment->init_values[i]; + + if (!load_init_expr(module, &p, p_end, init_expr, + table_segment->elem_type, +#if WASM_ENABLE_GC == 0 + NULL, +#else + table_segment->elem_ref_type, +#endif + error_buf, error_buf_size)) + return false; + + bh_assert((init_expr->init_expr_type == INIT_EXPR_TYPE_GET_GLOBAL) + || (init_expr->init_expr_type == INIT_EXPR_TYPE_REFNULL_CONST) + || (init_expr->init_expr_type >= INIT_EXPR_TYPE_FUNCREF_CONST + && init_expr->init_expr_type + <= INIT_EXPR_TYPE_ARRAY_NEW_FIXED)); + } + + *p_buf = p; + return true; +fail: + return false; +} +#endif /* end of (WASM_ENABLE_GC != 0) || (WASM_ENABLE_REF_TYPES != 0) */ + static bool load_table_segment_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, char *error_buf, @@ -2484,7 +4407,7 @@ load_table_segment_section(const uint8 *buf, const uint8 *buf_end, return false; } -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 read_leb_uint32(p, p_end, table_segment->mode); /* last three bits */ table_segment->mode = table_segment->mode & 0x07; @@ -2492,30 +4415,67 @@ load_table_segment_section(const uint8 *buf, const uint8 *buf_end, /* elemkind/elemtype + active */ case 0: case 4: + { +#if WASM_ENABLE_GC != 0 + if (table_segment->mode == 0) { + /* vec(funcidx), set elem type to (ref func) */ + WASMRefType elem_ref_type = { 0 }; + table_segment->elem_type = REF_TYPE_HT_NON_NULLABLE; + wasm_set_refheaptype_common( + &elem_ref_type.ref_ht_common, false, + HEAP_TYPE_FUNC); + if (!(table_segment->elem_ref_type = reftype_set_insert( + module->ref_type_set, &elem_ref_type, + error_buf, error_buf_size))) + return false; + } + else { + /* vec(expr), set elem type to funcref */ + table_segment->elem_type = VALUE_TYPE_FUNCREF; + } +#else table_segment->elem_type = VALUE_TYPE_FUNCREF; +#endif table_segment->table_index = 0; if (!check_table_index(module, table_segment->table_index, error_buf, error_buf_size)) return false; - if (!load_init_expr(&p, p_end, &table_segment->base_offset, - VALUE_TYPE_I32, error_buf, - error_buf_size)) - return false; - if (!load_func_index_vec(&p, p_end, module, table_segment, - table_segment->mode == 0 ? false - : true, - error_buf, error_buf_size)) + if (!load_init_expr( + module, &p, p_end, &table_segment->base_offset, + VALUE_TYPE_I32, NULL, error_buf, error_buf_size)) return false; + + if (table_segment->mode == 0) { + /* vec(funcidx) */ + if (!load_func_index_vec(&p, p_end, module, + table_segment, error_buf, + error_buf_size)) + return false; + } + else { + /* vec(expr) */ + if (!load_init_expr_vec(&p, p_end, module, + table_segment, error_buf, + error_buf_size)) + return false; + } + break; + } /* elemkind + passive/declarative */ case 1: case 3: - if (!load_elem_type(&p, p_end, &table_segment->elem_type, + if (!load_elem_type(module, &p, p_end, + &table_segment->elem_type, +#if WASM_ENABLE_GC != 0 + &table_segment->elem_ref_type, +#endif true, error_buf, error_buf_size)) return false; + /* vec(funcidx) */ if (!load_func_index_vec(&p, p_end, module, table_segment, - false, error_buf, error_buf_size)) + error_buf, error_buf_size)) return false; break; /* elemkind/elemtype + table_idx + active */ @@ -2525,27 +4485,46 @@ load_table_segment_section(const uint8 *buf, const uint8 *buf_end, &table_segment->table_index, error_buf, error_buf_size)) return false; - if (!load_init_expr(&p, p_end, &table_segment->base_offset, - VALUE_TYPE_I32, error_buf, - error_buf_size)) + if (!load_init_expr( + module, &p, p_end, &table_segment->base_offset, + VALUE_TYPE_I32, NULL, error_buf, error_buf_size)) return false; - if (!load_elem_type(&p, p_end, &table_segment->elem_type, + if (!load_elem_type(module, &p, p_end, + &table_segment->elem_type, +#if WASM_ENABLE_GC != 0 + &table_segment->elem_ref_type, +#endif table_segment->mode == 2 ? true : false, error_buf, error_buf_size)) return false; - if (!load_func_index_vec(&p, p_end, module, table_segment, - table_segment->mode == 2 ? false - : true, - error_buf, error_buf_size)) - return false; + + if (table_segment->mode == 2) { + /* vec(funcidx) */ + if (!load_func_index_vec(&p, p_end, module, + table_segment, error_buf, + error_buf_size)) + return false; + } + else { + /* vec(expr) */ + if (!load_init_expr_vec(&p, p_end, module, + table_segment, error_buf, + error_buf_size)) + return false; + } break; case 5: case 7: - if (!load_elem_type(&p, p_end, &table_segment->elem_type, + if (!load_elem_type(module, &p, p_end, + &table_segment->elem_type, +#if WASM_ENABLE_GC != 0 + &table_segment->elem_ref_type, +#endif false, error_buf, error_buf_size)) return false; - if (!load_func_index_vec(&p, p_end, module, table_segment, - true, error_buf, error_buf_size)) + /* vec(expr) */ + if (!load_init_expr_vec(&p, p_end, module, table_segment, + error_buf, error_buf_size)) return false; break; default: @@ -2562,13 +4541,19 @@ load_table_segment_section(const uint8 *buf, const uint8 *buf_end, &table_segment->table_index, error_buf, error_buf_size)) return false; - if (!load_init_expr(&p, p_end, &table_segment->base_offset, - VALUE_TYPE_I32, error_buf, error_buf_size)) + if (!load_init_expr(module, &p, p_end, &table_segment->base_offset, + VALUE_TYPE_I32, NULL, error_buf, + error_buf_size)) return false; - if (!load_func_index_vec(&p, p_end, module, table_segment, false, + if (!load_func_index_vec(&p, p_end, module, table_segment, error_buf, error_buf_size)) return false; #endif /* WASM_ENABLE_REF_TYPES != 0 */ + +#if WASM_ENABLE_WAMR_COMPILER != 0 + if (table_segment->elem_type == VALUE_TYPE_EXTERNREF) + module->is_ref_types_used = true; +#endif } } @@ -2625,6 +4610,9 @@ load_data_segment_section(const uint8 *buf, const uint8 *buf_end, switch (mem_flag) { case 0x01: is_passive = true; +#if WASM_ENABLE_WAMR_COMPILER != 0 + module->is_bulk_memory_used = true; +#endif break; case 0x00: /* no memory index, treat index as 0 */ @@ -2633,6 +4621,9 @@ load_data_segment_section(const uint8 *buf, const uint8 *buf_end, case 0x02: /* read following memory index */ read_leb_uint32(p, p_end, mem_index); +#if WASM_ENABLE_WAMR_COMPILER != 0 + module->is_bulk_memory_used = true; +#endif check_mem_index: if (mem_index >= module->import_memory_count + module->memory_count) { @@ -2659,8 +4650,9 @@ load_data_segment_section(const uint8 *buf, const uint8 *buf_end, #if WASM_ENABLE_BULK_MEMORY != 0 if (!is_passive) #endif - if (!load_init_expr(&p, p_end, &init_expr, VALUE_TYPE_I32, - error_buf, error_buf_size)) + if (!load_init_expr(module, &p, p_end, &init_expr, + VALUE_TYPE_I32, NULL, error_buf, + error_buf_size)) return false; read_leb_uint32(p, p_end, data_seg_len); @@ -2717,6 +4709,9 @@ load_datacount_section(const uint8 *buf, const uint8 *buf_end, return false; } +#if WASM_ENABLE_WAMR_COMPILER != 0 + module->is_bulk_memory_used = true; +#endif LOG_VERBOSE("Load datacount section success.\n"); return true; fail: @@ -2799,7 +4794,7 @@ load_tag_section(const uint8 *buf, const uint8 *buf_end, const uint8 *buf_code, fail: return false; } -#endif +#endif /* end of WASM_ENABLE_TAGS != 0 */ static bool load_code_section(const uint8 *buf, const uint8 *buf_end, const uint8 *buf_func, @@ -2835,7 +4830,7 @@ load_start_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, char *error_buf, uint32 error_buf_size) { const uint8 *p = buf, *p_end = buf_end; - WASMType *type; + WASMFuncType *type; uint32 start_function; read_leb_uint32(p, p_end, start_function); @@ -2869,6 +4864,61 @@ fail: return false; } +#if WASM_ENABLE_STRINGREF != 0 +static bool +load_stringref_section(const uint8 *buf, const uint8 *buf_end, + WASMModule *module, bool is_load_from_file_buf, + char *error_buf, uint32 error_buf_size) +{ + const uint8 *p = buf, *p_end = buf_end; + int32 deferred_count, immediate_count, string_length, i; + uint64 total_size; + + read_leb_uint32(p, p_end, deferred_count); + read_leb_uint32(p, p_end, immediate_count); + + /* proposal set deferred_count for future extension */ + if (deferred_count != 0) { + goto fail; + } + + if (immediate_count > 0) { + total_size = sizeof(char *) * (uint64)immediate_count; + if (!(module->string_literal_ptrs = + loader_malloc(total_size, error_buf, error_buf_size))) { + goto fail; + } + module->string_literal_count = immediate_count; + + total_size = sizeof(uint32) * (uint64)immediate_count; + if (!(module->string_literal_lengths = + loader_malloc(total_size, error_buf, error_buf_size))) { + goto fail; + } + + for (i = 0; i < immediate_count; i++) { + read_leb_uint32(p, p_end, string_length); + + CHECK_BUF(p, p_end, string_length); + module->string_literal_ptrs[i] = p; + module->string_literal_lengths[i] = string_length; + p += string_length; + } + } + + if (p != p_end) { + set_error_buf(error_buf, error_buf_size, "section size mismatch"); + goto fail; + } + + LOG_VERBOSE("Load stringref section success.\n"); + return true; + +fail: + return false; +} +#endif /* end of WASM_ENABLE_STRINGREF != 0 */ + #if WASM_ENABLE_CUSTOM_NAME_SECTION != 0 static bool handle_name_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, @@ -3120,6 +5170,11 @@ init_llvm_jit_functions_stage1(WASMModule *module, char *error_buf, AOTCompOption option = { 0 }; char *aot_last_error; uint64 size; +#if WASM_ENABLE_GC != 0 + bool gc_enabled = true; +#else + bool gc_enabled = false; +#endif if (module->function_count == 0) return true; @@ -3146,7 +5201,7 @@ init_llvm_jit_functions_stage1(WASMModule *module, char *error_buf, (bool *)((uint8 *)module->func_ptrs + sizeof(void *) * module->function_count); - module->comp_data = aot_create_comp_data(module); + module->comp_data = aot_create_comp_data(module, NULL, gc_enabled); if (!module->comp_data) { aot_last_error = aot_get_last_error(); bh_assert(aot_last_error != NULL); @@ -3174,14 +5229,21 @@ init_llvm_jit_functions_stage1(WASMModule *module, char *error_buf, #if WASM_ENABLE_SIMD != 0 option.enable_simd = true; #endif -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 option.enable_ref_types = true; +#elif WASM_ENABLE_GC != 0 + option.enable_gc = true; #endif option.enable_aux_stack_check = true; -#if (WASM_ENABLE_PERF_PROFILING != 0) || (WASM_ENABLE_DUMP_CALL_STACK != 0) +#if WASM_ENABLE_PERF_PROFILING != 0 || WASM_ENABLE_DUMP_CALL_STACK != 0 \ + || WASM_ENABLE_AOT_STACK_FRAME != 0 option.enable_aux_stack_frame = true; #endif +#if WASM_ENABLE_PERF_PROFILING != 0 + option.enable_perf_profiling = true; +#endif #if WASM_ENABLE_MEMORY_PROFILING != 0 + option.enable_memory_profiling = true; option.enable_stack_estimation = true; #endif @@ -3300,7 +5362,7 @@ orcjit_thread_callback(void *arg) /* Compile fast jit funcitons of this group */ for (i = group_idx; i < func_count; i += group_stride) { if (!jit_compiler_compile(module, i + module->import_function_count)) { - os_printf("failed to compile fast jit function %u\n", i); + LOG_ERROR("failed to compile fast jit function %u\n", i); break; } @@ -3327,7 +5389,7 @@ orcjit_thread_callback(void *arg) if (!jit_compiler_set_call_to_fast_jit( module, i + j * group_stride + module->import_function_count)) { - os_printf( + LOG_ERROR( "failed to compile call_to_fast_jit for func %u\n", i + j * group_stride + module->import_function_count); module->orcjit_stop_compiling = true; @@ -3377,7 +5439,7 @@ orcjit_thread_callback(void *arg) LLVMOrcLLLazyJITLookup(comp_ctx->orc_jit, &func_addr, func_name); if (error != LLVMErrorSuccess) { char *err_msg = LLVMGetErrorMessage(error); - os_printf("failed to compile llvm jit function %u: %s", i, err_msg); + LOG_ERROR("failed to compile llvm jit function %u: %s", i, err_msg); LLVMDisposeErrorMessage(err_msg); break; } @@ -3398,7 +5460,7 @@ orcjit_thread_callback(void *arg) func_name); if (error != LLVMErrorSuccess) { char *err_msg = LLVMGetErrorMessage(error); - os_printf("failed to compile llvm jit function %u: %s", i, + LOG_ERROR("failed to compile llvm jit function %u: %s", i, err_msg); LLVMDisposeErrorMessage(err_msg); /* Ignore current llvm jit func, as its func ptr is @@ -3539,7 +5601,7 @@ load_from_sections(WASMModule *module, WASMSection *sections, uint32 aux_stack_top = (uint32)-1, global_index, func_index, i; uint32 aux_data_end_global_index = (uint32)-1; uint32 aux_heap_base_global_index = (uint32)-1; - WASMType *func_type; + WASMFuncType *func_type; /* Find code and function sections if have */ while (section) { @@ -3641,6 +5703,14 @@ load_from_sections(WASMModule *module, WASMSection *sections, error_buf_size)) return false; break; +#endif +#if WASM_ENABLE_STRINGREF != 0 + case SECTION_TYPE_STRINGREF: + if (!load_stringref_section(buf, buf_end, module, + is_load_from_file_buf, error_buf, + error_buf_size)) + return false; + break; #endif default: set_error_buf(error_buf, error_buf_size, "invalid section id"); @@ -4005,19 +6075,45 @@ create_module(char *error_buf, uint32 error_buf_size) bh_assert(ret == BH_LIST_SUCCESS); #endif +#if WASM_ENABLE_GC != 0 + if (!(module->ref_type_set = + wasm_reftype_set_create(GC_REFTYPE_MAP_SIZE_DEFAULT))) { + set_error_buf(error_buf, error_buf_size, "create reftype map failed"); + goto fail1; + } + + if (os_mutex_init(&module->rtt_type_lock)) { + set_error_buf(error_buf, error_buf_size, "init rtt type lock failed"); + goto fail2; + } +#endif + #if WASM_ENABLE_DEBUG_INTERP != 0 \ || (WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 \ && WASM_ENABLE_LAZY_JIT != 0) if (os_mutex_init(&module->instance_list_lock) != 0) { set_error_buf(error_buf, error_buf_size, "init instance list lock failed"); - wasm_runtime_free(module); - return NULL; + goto fail3; } #endif (void)ret; return module; + +#if WASM_ENABLE_DEBUG_INTERP != 0 \ + || (WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT \ + && WASM_ENABLE_LAZY_JIT != 0) +fail3: +#endif +#if WASM_ENABLE_GC != 0 + os_mutex_destroy(&module->rtt_type_lock); +fail2: + bh_hash_map_destroy(module->ref_type_set); +fail1: +#endif + wasm_runtime_free(module); + return NULL; } #if WASM_ENABLE_DEBUG_INTERP != 0 @@ -4075,6 +6171,11 @@ static uint8 section_ids[] = { SECTION_TYPE_MEMORY, #if WASM_ENABLE_TAGS != 0 SECTION_TYPE_TAG, +#endif +#if WASM_ENABLE_STRINGREF != 0 + /* must immediately precede the global section, + or where the global section would be */ + SECTION_TYPE_STRINGREF, #endif SECTION_TYPE_GLOBAL, SECTION_TYPE_EXPORT, @@ -4267,14 +6368,22 @@ check_wasi_abi_compatibility(const WASMModule *module, /* clang-format on */ WASMExport *initialize = NULL, *memory = NULL, *start = NULL; + uint32 import_function_count = module->import_function_count; + WASMFuncType *func_type; /* (func (export "_start") (...) */ start = wasm_loader_find_export(module, "", "_start", EXPORT_KIND_FUNC, error_buf, error_buf_size); if (start) { - WASMType *func_type = - module->functions[start->index - module->import_function_count] - ->func_type; + if (start->index < import_function_count) { + set_error_buf( + error_buf, error_buf_size, + "the builtin _start function can not be an import function"); + return false; + } + + func_type = + module->functions[start->index - import_function_count]->func_type; if (func_type->param_count || func_type->result_count) { set_error_buf(error_buf, error_buf_size, "the signature of builtin _start function is wrong"); @@ -4286,11 +6395,17 @@ check_wasi_abi_compatibility(const WASMModule *module, initialize = wasm_loader_find_export(module, "", "_initialize", EXPORT_KIND_FUNC, error_buf, error_buf_size); + if (initialize) { - WASMType *func_type = - module - ->functions[initialize->index - - module->import_function_count] + if (initialize->index < import_function_count) { + set_error_buf(error_buf, error_buf_size, + "the builtin _initialize function can not be an " + "import function"); + return false; + } + + func_type = + module->functions[initialize->index - import_function_count] ->func_type; if (func_type->param_count || func_type->result_count) { set_error_buf( @@ -4369,7 +6484,8 @@ wasm_loader_load(uint8 *buf, uint32 size, return NULL; } -#if WASM_ENABLE_DEBUG_INTERP != 0 || WASM_ENABLE_FAST_JIT != 0 +#if WASM_ENABLE_DEBUG_INTERP != 0 || WASM_ENABLE_FAST_JIT != 0 \ + || WASM_ENABLE_DUMP_CALL_STACK != 0 || WASM_ENABLE_JIT != 0 module->load_addr = (uint8 *)buf; module->load_size = size; #endif @@ -4468,6 +6584,12 @@ wasm_loader_unload(WASMModule *module) module->functions[i]->call_to_fast_jit_from_llvm_jit); } #endif +#endif +#if WASM_ENABLE_GC != 0 + if (module->functions[i]->local_ref_type_maps) { + wasm_runtime_free( + module->functions[i]->local_ref_type_maps); + } #endif wasm_runtime_free(module->functions[i]); } @@ -4475,12 +6597,27 @@ wasm_loader_unload(WASMModule *module) wasm_runtime_free(module->functions); } - if (module->tables) + if (module->tables) { +#if WASM_ENABLE_GC != 0 + for (i = 0; i < module->table_count; i++) { + destroy_init_expr(&module->tables[i].init_expr); + } +#endif wasm_runtime_free(module->tables); + } if (module->memories) wasm_runtime_free(module->memories); + if (module->globals) { +#if WASM_ENABLE_GC != 0 + for (i = 0; i < module->global_count; i++) { + destroy_init_expr(&module->globals[i].init_expr); + } +#endif + wasm_runtime_free(module->globals); + } + #if WASM_ENABLE_TAGS != 0 if (module->tags) { for (i = 0; i < module->tag_count; i++) { @@ -4491,16 +6628,21 @@ wasm_loader_unload(WASMModule *module) } #endif - if (module->globals) - wasm_runtime_free(module->globals); - if (module->exports) wasm_runtime_free(module->exports); if (module->table_segments) { for (i = 0; i < module->table_seg_count; i++) { - if (module->table_segments[i].func_indexes) - wasm_runtime_free(module->table_segments[i].func_indexes); + if (module->table_segments[i].init_values) { +#if WASM_ENABLE_GC != 0 + uint32 j; + for (j = 0; j < module->table_segments[i].value_count; j++) { + destroy_init_expr( + &module->table_segments[i].init_values[j]); + } +#endif + wasm_runtime_free(module->table_segments[i].init_values); + } } wasm_runtime_free(module->table_segments); } @@ -4522,6 +6664,15 @@ wasm_loader_unload(WASMModule *module) } } +#if WASM_ENABLE_STRINGREF != 0 + if (module->string_literal_ptrs) { + wasm_runtime_free(module->string_literal_ptrs); + } + if (module->string_literal_lengths) { + wasm_runtime_free(module->string_literal_lengths); + } +#endif + #if WASM_ENABLE_FAST_INTERP == 0 if (module->br_table_cache_list) { BrTableCache *node = bh_list_first_elem(module->br_table_cache_list); @@ -4589,6 +6740,24 @@ wasm_loader_unload(WASMModule *module) } #endif +#if WASM_ENABLE_GC != 0 + os_mutex_destroy(&module->rtt_type_lock); + bh_hash_map_destroy(module->ref_type_set); + if (module->rtt_types) { + for (i = 0; i < module->type_count; i++) { + if (module->rtt_types[i]) + wasm_runtime_free(module->rtt_types[i]); + } + wasm_runtime_free(module->rtt_types); + } +#if WASM_ENABLE_STRINGREF != 0 + for (i = 0; i < WASM_TYPE_STRINGVIEWITER - WASM_TYPE_STRINGREF + 1; i++) { + if (module->stringref_rtts[i]) + wasm_runtime_free(module->stringref_rtts[i]); + } +#endif +#endif + wasm_runtime_free(module); } @@ -4688,13 +6857,26 @@ wasm_loader_find_block_addr(WASMExecEnv *exec_env, BlockAddr *block_addr_cache, (uint8 *)(p - 1); } break; -#endif +#endif /* end of WASM_ENABLE_EXCE_HANDLING != 0 */ case WASM_OP_BLOCK: case WASM_OP_LOOP: case WASM_OP_IF: + { /* block result type: 0x40/0x7F/0x7E/0x7D/0x7C */ u8 = read_uint8(p); + if (is_byte_a_type(u8)) { +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_multi_byte_type(u8)) { + /* the possible extra bytes of GC ref type have been + modified to OP_NOP, no need to resolve them again */ + } +#endif + } + else { + p--; + skip_leb_uint32(p, p_end); + } if (block_nested_depth < sizeof(block_stack) / sizeof(BlockAddr)) { block_stack[block_nested_depth].start_addr = p; @@ -4702,6 +6884,7 @@ wasm_loader_find_block_addr(WASMExecEnv *exec_env, BlockAddr *block_addr_cache, } block_nested_depth++; break; + } case EXT_OP_BLOCK: case EXT_OP_LOOP: @@ -4808,36 +6991,74 @@ wasm_loader_find_block_addr(WASMExecEnv *exec_env, BlockAddr *block_addr_cache, case WASM_OP_RETURN_CALL_INDIRECT: #endif skip_leb_uint32(p, p_end); /* typeidx */ - CHECK_BUF(p, p_end, 1); +#if WASM_ENABLE_REF_TYPES == 0 && WASM_ENABLE_GC == 0 u8 = read_uint8(p); /* 0x00 */ +#else + skip_leb_uint32(p, p_end); /* talbeidx */ +#endif break; +#if WASM_ENABLE_GC != 0 + case WASM_OP_CALL_REF: + case WASM_OP_RETURN_CALL_REF: + skip_leb_uint32(p, p_end); /* typeidx */ + break; +#endif + case WASM_OP_DROP: case WASM_OP_SELECT: case WASM_OP_DROP_64: case WASM_OP_SELECT_64: break; -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 case WASM_OP_SELECT_T: + { skip_leb_uint32(p, p_end); /* vec length */ - CHECK_BUF(p, p_end, 1); - u8 = read_uint8(p); /* typeidx */ + u8 = read_uint8(p); /* typeidx */ + /* the possible extra bytes of GC ref type have been + modified to OP_NOP, no need to resolve them again */ break; + } + case WASM_OP_TABLE_GET: case WASM_OP_TABLE_SET: skip_leb_uint32(p, p_end); /* table index */ break; case WASM_OP_REF_NULL: - CHECK_BUF(p, p_end, 1); + { u8 = read_uint8(p); /* type */ + if (is_byte_a_type(u8)) { +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_multi_byte_type(u8)) { + /* the possible extra bytes of GC ref type have been + modified to OP_NOP, no need to resolve them again */ + } +#endif + } + else { + p--; + skip_leb_uint32(p, p_end); + } break; + } case WASM_OP_REF_IS_NULL: break; case WASM_OP_REF_FUNC: skip_leb_uint32(p, p_end); /* func index */ break; -#endif /* WASM_ENABLE_REF_TYPES */ +#endif /* end of WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */ + +#if WASM_ENABLE_GC != 0 + case WASM_OP_REF_AS_NON_NULL: + case WASM_OP_REF_EQ: + break; + case WASM_OP_BR_ON_NULL: + case WASM_OP_BR_ON_NON_NULL: + skip_leb_uint32(p, p_end); /* label index */ + break; +#endif /* end of WASM_ENABLE_GC != 0 */ + case WASM_OP_GET_LOCAL: case WASM_OP_SET_LOCAL: case WASM_OP_TEE_LOCAL: @@ -5030,13 +7251,147 @@ wasm_loader_find_block_addr(WASMExecEnv *exec_env, BlockAddr *block_addr_cache, case WASM_OP_I64_EXTEND16_S: case WASM_OP_I64_EXTEND32_S: break; + +#if WASM_ENABLE_GC != 0 + case WASM_OP_GC_PREFIX: + { + uint32 opcode1; + + read_leb_uint32(p, p_end, opcode1); + /* opcode1 was checked in wasm_loader_prepare_bytecode and + is no larger than UINT8_MAX */ + opcode = (uint8)opcode1; + + switch (opcode) { + case WASM_OP_STRUCT_NEW: + case WASM_OP_STRUCT_NEW_DEFAULT: + skip_leb_uint32(p, p_end); /* typeidx */ + break; + case WASM_OP_STRUCT_GET: + case WASM_OP_STRUCT_GET_S: + case WASM_OP_STRUCT_GET_U: + case WASM_OP_STRUCT_SET: + skip_leb_uint32(p, p_end); /* typeidx */ + skip_leb_uint32(p, p_end); /* fieldidx */ + break; + + case WASM_OP_ARRAY_NEW: + case WASM_OP_ARRAY_NEW_DEFAULT: + case WASM_OP_ARRAY_GET: + case WASM_OP_ARRAY_GET_S: + case WASM_OP_ARRAY_GET_U: + case WASM_OP_ARRAY_SET: + case WASM_OP_ARRAY_FILL: + skip_leb_uint32(p, p_end); /* typeidx */ + break; + case WASM_OP_ARRAY_COPY: + skip_leb_uint32(p, p_end); /* typeidx1 */ + skip_leb_uint32(p, p_end); /* typeidx2 */ + break; + case WASM_OP_ARRAY_LEN: + break; + case WASM_OP_ARRAY_NEW_FIXED: + case WASM_OP_ARRAY_NEW_DATA: + case WASM_OP_ARRAY_NEW_ELEM: + skip_leb_uint32(p, p_end); /* typeidx */ + skip_leb_uint32(p, p_end); /* N/dataidx/elemidx */ + break; + + case WASM_OP_REF_I31: + case WASM_OP_I31_GET_S: + case WASM_OP_I31_GET_U: + break; + + case WASM_OP_REF_TEST: + case WASM_OP_REF_CAST: + case WASM_OP_REF_TEST_NULLABLE: + case WASM_OP_REF_CAST_NULLABLE: + skip_leb_int32(p, p_end); /* heaptype */ + break; + case WASM_OP_BR_ON_CAST: + case WASM_OP_BR_ON_CAST_FAIL: + p += sizeof(uint8); /* castflag */ + skip_leb_uint32(p, p_end); /* labelidx */ + skip_leb_int32(p, p_end); /* heaptype */ + skip_leb_int32(p, p_end); /* heaptype2 */ + break; + + case WASM_OP_ANY_CONVERT_EXTERN: + case WASM_OP_EXTERN_CONVERT_ANY: + break; + +#if WASM_ENABLE_STRINGREF != 0 + case WASM_OP_STRING_NEW_UTF8: + case WASM_OP_STRING_NEW_WTF16: + case WASM_OP_STRING_NEW_LOSSY_UTF8: + case WASM_OP_STRING_NEW_WTF8: + skip_leb_uint32(p, p_end); /* memory index 0x00 */ + break; + case WASM_OP_STRING_CONST: + skip_leb_int32(p, p_end); /* contents */ + break; + case WASM_OP_STRING_MEASURE_UTF8: + case WASM_OP_STRING_MEASURE_WTF8: + case WASM_OP_STRING_MEASURE_WTF16: + break; + case WASM_OP_STRING_ENCODE_UTF8: + case WASM_OP_STRING_ENCODE_WTF16: + case WASM_OP_STRING_ENCODE_LOSSY_UTF8: + case WASM_OP_STRING_ENCODE_WTF8: + skip_leb_uint32(p, p_end); /* memory index 0x00 */ + break; + case WASM_OP_STRING_CONCAT: + case WASM_OP_STRING_EQ: + case WASM_OP_STRING_IS_USV_SEQUENCE: + case WASM_OP_STRING_AS_WTF8: + case WASM_OP_STRINGVIEW_WTF8_ADVANCE: + break; + case WASM_OP_STRINGVIEW_WTF8_ENCODE_UTF8: + case WASM_OP_STRINGVIEW_WTF8_ENCODE_LOSSY_UTF8: + case WASM_OP_STRINGVIEW_WTF8_ENCODE_WTF8: + skip_leb_uint32(p, p_end); /* memory index 0x00 */ + break; + case WASM_OP_STRINGVIEW_WTF8_SLICE: + case WASM_OP_STRING_AS_WTF16: + case WASM_OP_STRINGVIEW_WTF16_LENGTH: + case WASM_OP_STRINGVIEW_WTF16_GET_CODEUNIT: + break; + case WASM_OP_STRINGVIEW_WTF16_ENCODE: + skip_leb_uint32(p, p_end); /* memory index 0x00 */ + break; + case WASM_OP_STRINGVIEW_WTF16_SLICE: + case WASM_OP_STRING_AS_ITER: + case WASM_OP_STRINGVIEW_ITER_NEXT: + case WASM_OP_STRINGVIEW_ITER_ADVANCE: + case WASM_OP_STRINGVIEW_ITER_REWIND: + case WASM_OP_STRINGVIEW_ITER_SLICE: + case WASM_OP_STRING_NEW_UTF8_ARRAY: + case WASM_OP_STRING_NEW_WTF16_ARRAY: + case WASM_OP_STRING_NEW_LOSSY_UTF8_ARRAY: + case WASM_OP_STRING_NEW_WTF8_ARRAY: + case WASM_OP_STRING_ENCODE_UTF8_ARRAY: + case WASM_OP_STRING_ENCODE_WTF16_ARRAY: + case WASM_OP_STRING_ENCODE_LOSSY_UTF8_ARRAY: + case WASM_OP_STRING_ENCODE_WTF8_ARRAY: + break; +#endif /* end of WASM_ENABLE_STRINGREF != 0 */ + default: + return false; + } + break; + } +#endif /* end of WASM_ENABLE_GC != 0 */ + case WASM_OP_MISC_PREFIX: { uint32 opcode1; read_leb_uint32(p, p_end, opcode1); + /* opcode1 was checked in wasm_loader_prepare_bytecode and + is no larger than UINT8_MAX */ + opcode = (uint8)opcode1; - switch (opcode1) { + switch (opcode) { case WASM_OP_I32_TRUNC_SAT_S_F32: case WASM_OP_I32_TRUNC_SAT_U_F32: case WASM_OP_I32_TRUNC_SAT_S_F64: @@ -5246,20 +7601,6 @@ fail: return false; } -#define REF_ANY VALUE_TYPE_ANY -#define REF_I32 VALUE_TYPE_I32 -#define REF_F32 VALUE_TYPE_F32 -#define REF_I64_1 VALUE_TYPE_I64 -#define REF_I64_2 VALUE_TYPE_I64 -#define REF_F64_1 VALUE_TYPE_F64 -#define REF_F64_2 VALUE_TYPE_F64 -#define REF_V128_1 VALUE_TYPE_V128 -#define REF_V128_2 VALUE_TYPE_V128 -#define REF_V128_3 VALUE_TYPE_V128 -#define REF_V128_4 VALUE_TYPE_V128 -#define REF_FUNCREF VALUE_TYPE_FUNCREF -#define REF_EXTERNREF VALUE_TYPE_EXTERNREF - #if WASM_ENABLE_FAST_INTERP != 0 #if WASM_DEBUG_PREPROCESSOR != 0 @@ -5284,6 +7625,13 @@ typedef struct BranchBlock { uint8 *else_addr; uint8 *end_addr; uint32 stack_cell_num; +#if WASM_ENABLE_GC != 0 + uint32 reftype_map_num; + /* Indicate which local is used inside current block, used to validate + * local.get with non-nullable ref types */ + uint8 *local_use_mask; + uint32 local_use_mask_size; +#endif #if WASM_ENABLE_FAST_INTERP != 0 uint16 dynamic_offset; uint8 *code_compiled; @@ -5312,6 +7660,23 @@ typedef struct WASMLoaderContext { uint32 stack_cell_num; uint32 max_stack_cell_num; +#if WASM_ENABLE_GC != 0 + /* frame reftype map stack */ + WASMRefTypeMap *frame_reftype_map; + WASMRefTypeMap *frame_reftype_map_bottom; + WASMRefTypeMap *frame_reftype_map_boundary; + uint32 frame_reftype_map_size; + uint32 reftype_map_num; + uint32 max_reftype_map_num; + /* Current module */ + WASMModule *module; + /* Current module's ref_type_set */ + HashMap *ref_type_set; + /* Always point to local variable ref_type of + wasm_loader_prepare_bytecode */ + WASMRefType *ref_type_tmp; +#endif + /* frame csp stack */ BranchBlock *frame_csp; BranchBlock *frame_csp_bottom; @@ -5356,29 +7721,6 @@ typedef struct Const { uint8 value_type; } Const; -static void * -memory_realloc(void *mem_old, uint32 size_old, uint32 size_new, char *error_buf, - uint32 error_buf_size) -{ - uint8 *mem_new; - bh_assert(size_new > size_old); - if ((mem_new = loader_malloc(size_new, error_buf, error_buf_size))) { - bh_memcpy_s(mem_new, size_new, mem_old, size_old); - memset(mem_new + size_old, 0, size_new - size_old); - wasm_runtime_free(mem_old); - } - return mem_new; -} - -#define MEM_REALLOC(mem, size_old, size_new) \ - do { \ - void *mem_new = memory_realloc(mem, size_old, size_new, error_buf, \ - error_buf_size); \ - if (!mem_new) \ - goto fail; \ - mem = mem_new; \ - } while (0) - #define CHECK_CSP_PUSH() \ do { \ if (ctx->frame_csp >= ctx->frame_csp_boundary) { \ @@ -5456,87 +7798,125 @@ free_all_label_patch_lists(BranchBlock *frame_csp, uint32 csp_num) #endif /* end of WASM_ENABLE_FAST_INTERP */ +#if WASM_ENABLE_GC != 0 static bool -check_stack_push(WASMLoaderContext *ctx, char *error_buf, uint32 error_buf_size) +wasm_loader_init_local_use_masks(WASMLoaderContext *ctx, uint32 local_count, + char *error_buf, uint32 error_buf_size) { - if (ctx->frame_ref >= ctx->frame_ref_boundary) { - MEM_REALLOC(ctx->frame_ref_bottom, ctx->frame_ref_size, - ctx->frame_ref_size + 16); - ctx->frame_ref_size += 16; - ctx->frame_ref_boundary = ctx->frame_ref_bottom + ctx->frame_ref_size; - ctx->frame_ref = ctx->frame_ref_bottom + ctx->stack_cell_num; - } - return true; -fail: - return false; -} + BranchBlock *current_csp = ctx->frame_csp - 1; + uint32 local_mask_size; -static bool -check_stack_top_values(uint8 *frame_ref, int32 stack_cell_num, uint8 type, - char *error_buf, uint32 error_buf_size) -{ - if ((is_32bit_type(type) && stack_cell_num < 1) - || (is_64bit_type(type) && stack_cell_num < 2) -#if WASM_ENABLE_SIMD != 0 -#if (WASM_ENABLE_WAMR_COMPILER != 0) || (WASM_ENABLE_JIT != 0) - || (type == VALUE_TYPE_V128 && stack_cell_num < 4) -#endif -#endif - ) { - set_error_buf(error_buf, error_buf_size, - "type mismatch: expect data but stack was empty"); - return false; - } - - if ((is_32bit_type(type) && *(frame_ref - 1) != type) - || (is_64bit_type(type) - && (*(frame_ref - 2) != type || *(frame_ref - 1) != type)) -#if WASM_ENABLE_SIMD != 0 -#if (WASM_ENABLE_WAMR_COMPILER != 0) || (WASM_ENABLE_JIT != 0) - || (type == VALUE_TYPE_V128 - && (*(frame_ref - 4) != REF_V128_1 || *(frame_ref - 3) != REF_V128_2 - || *(frame_ref - 2) != REF_V128_3 - || *(frame_ref - 1) != REF_V128_4)) -#endif -#endif - ) { - set_error_buf_v(error_buf, error_buf_size, "%s%s%s", - "type mismatch: expect ", type2str(type), - " but got other"); - return false; - } - - return true; -} - -static bool -check_stack_pop(WASMLoaderContext *ctx, uint8 type, char *error_buf, - uint32 error_buf_size) -{ - int32 block_stack_cell_num = - (int32)(ctx->stack_cell_num - (ctx->frame_csp - 1)->stack_cell_num); - - if (block_stack_cell_num > 0 && *(ctx->frame_ref - 1) == VALUE_TYPE_ANY) { - /* the stack top is a value of any type, return success */ + if (local_count == 0) { + current_csp->local_use_mask_size = 0; return true; } - if (!check_stack_top_values(ctx->frame_ref, block_stack_cell_num, type, - error_buf, error_buf_size)) - return false; + /* if current_csp->local_use_mask is not NULL, then it is re-init masks for + * else branch, we don't need to allocate memory again */ + if (!current_csp->local_use_mask) { + local_mask_size = (local_count + 7) / sizeof(uint8); + if (!(current_csp->local_use_mask = + loader_malloc(local_mask_size, error_buf, error_buf_size))) { + return false; + } + current_csp->local_use_mask_size = local_mask_size; + } + else { + local_mask_size = current_csp->local_use_mask_size; + bh_assert(current_csp->label_type == LABEL_TYPE_IF); + } + + if (current_csp->label_type != LABEL_TYPE_FUNCTION) { + /* For non-function blocks, inherit the use status from parent block */ + BranchBlock *parent_csp = current_csp - 1; + + bh_assert(parent_csp >= ctx->frame_csp_bottom); + bh_assert(parent_csp->local_use_mask); + + bh_memcpy_s(current_csp->local_use_mask, local_mask_size, + parent_csp->local_use_mask, local_mask_size); + } return true; } +static void +wasm_loader_destroy_curr_local_use_masks(WASMLoaderContext *ctx) +{ + BranchBlock *current_csp = ctx->frame_csp - 1; + + bh_assert(current_csp->local_use_mask + || current_csp->local_use_mask_size == 0); + + if (current_csp->local_use_mask) { + wasm_runtime_free(current_csp->local_use_mask); + } + + current_csp->local_use_mask = NULL; + current_csp->local_use_mask_size = 0; +} + +static void +wasm_loader_clean_all_local_use_masks(WASMLoaderContext *ctx) +{ + BranchBlock *tmp_csp = ctx->frame_csp_bottom; + uint32 i; + + for (i = 0; i < ctx->csp_num; i++) { + if (tmp_csp->local_use_mask) { + wasm_runtime_free(tmp_csp->local_use_mask); + tmp_csp->local_use_mask = NULL; + tmp_csp->local_use_mask_size = 0; + } + tmp_csp++; + } +} + +static void +wasm_loader_mask_local(WASMLoaderContext *ctx, uint32 index) +{ + BranchBlock *current_csp = ctx->frame_csp - 1; + uint32 byte_offset = index / sizeof(uint8); + uint32 bit_offset = index % sizeof(uint8); + + bh_assert(byte_offset < current_csp->local_use_mask_size); + bh_assert(current_csp->local_use_mask); + + current_csp->local_use_mask[byte_offset] |= (1 << bit_offset); +} + +static bool +wasm_loader_get_local_status(WASMLoaderContext *ctx, uint32 index) +{ + BranchBlock *current_csp = ctx->frame_csp - 1; + uint32 byte_offset = index / sizeof(uint8); + uint32 bit_offset = index % sizeof(uint8); + + bh_assert(byte_offset < current_csp->local_use_mask_size); + bh_assert(current_csp->local_use_mask); + + return (current_csp->local_use_mask[byte_offset] & (1 << bit_offset)) + ? true + : false; +} +#endif /* end of WASM_ENABLE_GC != 0 */ + static void wasm_loader_ctx_destroy(WASMLoaderContext *ctx) { if (ctx) { if (ctx->frame_ref_bottom) wasm_runtime_free(ctx->frame_ref_bottom); +#if WASM_ENABLE_GC != 0 + if (ctx->frame_reftype_map_bottom) + wasm_runtime_free(ctx->frame_reftype_map_bottom); +#endif if (ctx->frame_csp_bottom) { #if WASM_ENABLE_FAST_INTERP != 0 free_all_label_patch_lists(ctx->frame_csp_bottom, ctx->csp_num); +#endif +#if WASM_ENABLE_GC != 0 + wasm_loader_clean_all_local_use_masks(ctx); #endif wasm_runtime_free(ctx->frame_csp_bottom); } @@ -5564,6 +7944,16 @@ wasm_loader_ctx_init(WASMFunction *func, char *error_buf, uint32 error_buf_size) goto fail; loader_ctx->frame_ref_boundary = loader_ctx->frame_ref_bottom + 32; +#if WASM_ENABLE_GC != 0 + loader_ctx->frame_reftype_map_size = sizeof(WASMRefTypeMap) * 16; + if (!(loader_ctx->frame_reftype_map_bottom = loader_ctx->frame_reftype_map = + loader_malloc(loader_ctx->frame_reftype_map_size, error_buf, + error_buf_size))) + goto fail; + loader_ctx->frame_reftype_map_boundary = + loader_ctx->frame_reftype_map_bottom + 16; +#endif + loader_ctx->frame_csp_size = sizeof(BranchBlock) * 8; if (!(loader_ctx->frame_csp_bottom = loader_ctx->frame_csp = loader_malloc( loader_ctx->frame_csp_size, error_buf, error_buf_size))) @@ -5605,43 +7995,98 @@ fail: return NULL; } +static bool +check_stack_push(WASMLoaderContext *ctx, uint8 type, char *error_buf, + uint32 error_buf_size) +{ + uint32 cell_num_needed = wasm_value_type_cell_num(type); + + if (ctx->frame_ref + cell_num_needed > ctx->frame_ref_boundary) { + /* Increase the frame ref stack */ + MEM_REALLOC(ctx->frame_ref_bottom, ctx->frame_ref_size, + ctx->frame_ref_size + 16); + ctx->frame_ref_size += 16; + ctx->frame_ref_boundary = ctx->frame_ref_bottom + ctx->frame_ref_size; + ctx->frame_ref = ctx->frame_ref_bottom + ctx->stack_cell_num; + } + +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_multi_byte_type(type) + && ctx->frame_reftype_map >= ctx->frame_reftype_map_boundary) { + /* Increase the frame reftype map stack */ + bh_assert( + (uint32)((ctx->frame_reftype_map - ctx->frame_reftype_map_bottom) + * sizeof(WASMRefTypeMap)) + == ctx->frame_reftype_map_size); + MEM_REALLOC(ctx->frame_reftype_map_bottom, ctx->frame_reftype_map_size, + ctx->frame_reftype_map_size + + (uint32)sizeof(WASMRefTypeMap) * 8); + ctx->frame_reftype_map = + ctx->frame_reftype_map_bottom + + ctx->frame_reftype_map_size / ((uint32)sizeof(WASMRefTypeMap)); + ctx->frame_reftype_map_size += (uint32)sizeof(WASMRefTypeMap) * 8; + ctx->frame_reftype_map_boundary = + ctx->frame_reftype_map_bottom + + ctx->frame_reftype_map_size / ((uint32)sizeof(WASMRefTypeMap)); + } +#endif + return true; +fail: + return false; +} + static bool wasm_loader_push_frame_ref(WASMLoaderContext *ctx, uint8 type, char *error_buf, uint32 error_buf_size) { - if (type == VALUE_TYPE_VOID) - return true; + uint32 type_cell_num = wasm_value_type_cell_num(type); + uint32 i; - if (!check_stack_push(ctx, error_buf, error_buf_size)) + if (!check_stack_push(ctx, type, error_buf, error_buf_size)) return false; - *ctx->frame_ref++ = type; - ctx->stack_cell_num++; - if (is_32bit_type(type) || type == VALUE_TYPE_ANY) - goto check_stack_and_return; - - if (!check_stack_push(ctx, error_buf, error_buf_size)) - return false; - - *ctx->frame_ref++ = type; - ctx->stack_cell_num++; - -#if WASM_ENABLE_SIMD != 0 -#if (WASM_ENABLE_WAMR_COMPILER != 0) || (WASM_ENABLE_JIT != 0) - if (type == VALUE_TYPE_V128) { - if (!check_stack_push(ctx, error_buf, error_buf_size)) +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_multi_byte_type(type)) { + WASMRefType *ref_type; + if (!(ref_type = + reftype_set_insert(ctx->ref_type_set, ctx->ref_type_tmp, + error_buf, error_buf_size))) { return false; - *ctx->frame_ref++ = type; - ctx->stack_cell_num++; - if (!check_stack_push(ctx, error_buf, error_buf_size)) - return false; - *ctx->frame_ref++ = type; - ctx->stack_cell_num++; + } + + if (ctx->frame_reftype_map >= ctx->frame_reftype_map_boundary) { + /* Increase the frame reftype map stack */ + bh_assert((uint32)((ctx->frame_reftype_map + - ctx->frame_reftype_map_bottom) + * sizeof(WASMRefTypeMap)) + == ctx->frame_reftype_map_size); + MEM_REALLOC(ctx->frame_reftype_map_bottom, + ctx->frame_reftype_map_size, + ctx->frame_reftype_map_size + + (uint32)sizeof(WASMRefTypeMap) * 8); + ctx->frame_reftype_map = ctx->frame_reftype_map_bottom + + ctx->frame_reftype_map_size + / ((uint32)sizeof(WASMRefTypeMap)); + ctx->frame_reftype_map_size += (uint32)sizeof(WASMRefTypeMap) * 8; + ctx->frame_reftype_map_boundary = + ctx->frame_reftype_map_bottom + + ctx->frame_reftype_map_size + / ((uint32)sizeof(WASMRefTypeMap)); + } + + ctx->frame_reftype_map->index = ctx->stack_cell_num; + ctx->frame_reftype_map->ref_type = ref_type; + ctx->frame_reftype_map++; + ctx->reftype_map_num++; + if (ctx->reftype_map_num > ctx->max_reftype_map_num) + ctx->max_reftype_map_num = ctx->reftype_map_num; } #endif -#endif -check_stack_and_return: + for (i = 0; i < type_cell_num; i++) + *ctx->frame_ref++ = type; + ctx->stack_cell_num += type_cell_num; + if (ctx->stack_cell_num > ctx->max_stack_cell_num) { ctx->max_stack_cell_num = ctx->stack_cell_num; if (ctx->max_stack_cell_num > UINT16_MAX) { @@ -5650,6 +8095,124 @@ check_stack_and_return: return false; } } + return true; +#if WASM_ENABLE_GC != 0 +fail: + return false; +#endif +} + +static bool +check_stack_top_values(WASMLoaderContext *ctx, uint8 *frame_ref, + int32 stack_cell_num, +#if WASM_ENABLE_GC != 0 + WASMRefTypeMap *frame_reftype_map, int32 reftype_map_num, +#endif + uint8 type, +#if WASM_ENABLE_GC != 0 + WASMRefType *ref_type, +#endif + char *error_buf, uint32 error_buf_size) +{ + int32 type_cell_num = (int32)wasm_value_type_cell_num(type), i; +#if WASM_ENABLE_GC != 0 + WASMRefType *frame_reftype = NULL; +#endif + + if (stack_cell_num < type_cell_num) { + set_error_buf(error_buf, error_buf_size, + "type mismatch: expect data but stack was empty"); + return false; + } + +#if WASM_ENABLE_GC == 0 + for (i = 0; i < type_cell_num; i++) { + if (*(frame_ref - 1 - i) != type) { + set_error_buf_v(error_buf, error_buf_size, "%s%s%s", + "type mismatch: expect ", type2str(type), + " but got other"); + return false; + } + } +#else + if (wasm_is_type_multi_byte_type(*(frame_ref - 1))) { + bh_assert(reftype_map_num > 0); + frame_reftype = (frame_reftype_map - 1)->ref_type; + } + if (!wasm_reftype_is_subtype_of(*(frame_ref - 1), frame_reftype, type, + ref_type, ctx->module->types, + ctx->module->type_count)) { + set_error_buf_v(error_buf, error_buf_size, "%s%s%s", + "type mismatch: expect ", type2str(type), + " but got other"); + return false; + } + for (i = 0; i < type_cell_num - 1; i++) { + if (*(frame_ref - 2 - i) != *(frame_ref - 1)) { + set_error_buf_v(error_buf, error_buf_size, "%s%s%s", + "type mismatch: expect ", type2str(type), + " but got other"); + return false; + } + } +#endif + + return true; +} + +static bool +check_stack_pop(WASMLoaderContext *ctx, uint8 type, char *error_buf, + uint32 error_buf_size) +{ + int32 block_stack_cell_num = + (int32)(ctx->stack_cell_num - (ctx->frame_csp - 1)->stack_cell_num); +#if WASM_ENABLE_GC != 0 + int32 reftype_map_num = + (int32)(ctx->reftype_map_num - (ctx->frame_csp - 1)->reftype_map_num); +#endif + + if (block_stack_cell_num > 0) { + if (*(ctx->frame_ref - 1) == VALUE_TYPE_ANY) + /* the stack top is a value of any type, return success */ + return true; + } + +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_reftype(type) && block_stack_cell_num > 0) { + uint8 stack_top_type = *(ctx->frame_ref - 1); + WASMRefType *stack_top_ref_type = NULL; + + if (wasm_is_type_multi_byte_type(stack_top_type)) { + bh_assert(reftype_map_num > 0); + stack_top_ref_type = (*(ctx->frame_reftype_map - 1)).ref_type; + } + + if (wasm_reftype_is_subtype_of(stack_top_type, stack_top_ref_type, type, + ctx->ref_type_tmp, ctx->module->types, + ctx->module->type_count)) { + if (wasm_is_type_multi_byte_type(stack_top_type)) { + uint32 ref_type_struct_size = + wasm_reftype_struct_size(stack_top_ref_type); + bh_memcpy_s(ctx->ref_type_tmp, (uint32)sizeof(WASMRefType), + stack_top_ref_type, ref_type_struct_size); + } + return true; + } + } +#endif + + if (!check_stack_top_values(ctx, ctx->frame_ref, block_stack_cell_num, +#if WASM_ENABLE_GC != 0 + ctx->frame_reftype_map, reftype_map_num, +#endif + type, +#if WASM_ENABLE_GC != 0 + ctx->ref_type_tmp, +#endif + error_buf, error_buf_size)) { + return false; + } + return true; } @@ -5660,9 +8223,10 @@ wasm_loader_pop_frame_ref(WASMLoaderContext *ctx, uint8 type, char *error_buf, BranchBlock *cur_block = ctx->frame_csp - 1; int32 available_stack_cell = (int32)(ctx->stack_cell_num - cur_block->stack_cell_num); + uint32 cell_num_to_pop = wasm_value_type_cell_num(type); /* Directly return success if current block is in stack - * polymorphic state while stack is empty. */ + polymorphic state while stack is empty. */ if (available_stack_cell <= 0 && cur_block->is_stack_polymorphic) return true; @@ -5672,26 +8236,210 @@ wasm_loader_pop_frame_ref(WASMLoaderContext *ctx, uint8 type, char *error_buf, if (!check_stack_pop(ctx, type, error_buf, error_buf_size)) return false; - ctx->frame_ref--; - ctx->stack_cell_num--; + bh_assert(available_stack_cell > 0); + if (*(ctx->frame_ref - 1) == VALUE_TYPE_ANY) { + type = VALUE_TYPE_ANY; + cell_num_to_pop = 1; + } - if (is_32bit_type(type) || *ctx->frame_ref == VALUE_TYPE_ANY) - return true; - - ctx->frame_ref--; - ctx->stack_cell_num--; - -#if WASM_ENABLE_SIMD != 0 -#if (WASM_ENABLE_WAMR_COMPILER != 0) || (WASM_ENABLE_JIT != 0) - if (type == VALUE_TYPE_V128) { - ctx->frame_ref -= 2; - ctx->stack_cell_num -= 2; + ctx->frame_ref -= cell_num_to_pop; + ctx->stack_cell_num -= cell_num_to_pop; +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_multi_byte_type(*ctx->frame_ref)) { + ctx->frame_reftype_map--; + ctx->reftype_map_num--; } #endif -#endif + return true; } +#if WASM_ENABLE_GC != 0 +/* Get the stack top element of current block */ +static bool +wasm_loader_get_frame_ref_top(WASMLoaderContext *ctx, uint8 *p_type, + WASMRefType **p_ref_type, char *error_buf, + uint32 error_buf_size) +{ + BranchBlock *cur_block = ctx->frame_csp - 1; + int32 available_stack_cell = + (int32)(ctx->stack_cell_num - cur_block->stack_cell_num); + + if (available_stack_cell <= 0) { + /* Directly return success if current block is in stack + polymorphic state while stack is empty. */ + if (cur_block->is_stack_polymorphic) { + *p_type = VALUE_TYPE_ANY; + return true; + } + else { + set_error_buf( + error_buf, error_buf_size, + "type mismatch: expect data but block stack was empty"); + return false; + } + } + + *p_type = *(ctx->frame_ref - 1); + if (wasm_is_type_multi_byte_type(*p_type)) { + int32 available_reftype_map = + (int32)(ctx->reftype_map_num + - (ctx->frame_csp - 1)->reftype_map_num); + bh_assert(available_reftype_map > 0); + (void)available_reftype_map; + *p_ref_type = (ctx->frame_reftype_map - 1)->ref_type; + } + + return true; +} + +#if WASM_ENABLE_FAST_INTERP != 0 +static bool +wasm_loader_pop_frame_ref_offset(WASMLoaderContext *ctx, uint8 type, + char *error_buf, uint32 error_buf_size); +#endif + +/* Check whether the stack top elem is a heap object, and if yes, + pop and return it */ +static bool +wasm_loader_pop_heap_obj(WASMLoaderContext *ctx, uint8 *p_type, + WASMRefType *ref_ht_ret, char *error_buf, + uint32 error_buf_size) +{ + uint8 type = 0; + WASMRefType *ref_type = NULL; + + /* Get stack top element */ + if (!wasm_loader_get_frame_ref_top(ctx, &type, &ref_type, error_buf, + error_buf_size)) { + return false; + } + + if (type != VALUE_TYPE_ANY /* block isn't in stack polymorphic state */ + /* stack top isn't a ref type */ + && !wasm_is_type_reftype(type)) { + set_error_buf(error_buf, error_buf_size, + "type mismatch: expect heap object but got others"); + return false; + } + + /* POP stack top */ + if (wasm_is_type_multi_byte_type(type)) { + bh_assert(ref_type); + bh_memcpy_s(ctx->ref_type_tmp, sizeof(WASMRefType), ref_type, + wasm_reftype_struct_size(ref_type)); + } + +#if WASM_ENABLE_FAST_INTERP != 0 + if (!wasm_loader_pop_frame_ref_offset(ctx, type, error_buf, + error_buf_size)) { + return false; + } +#else + if (!wasm_loader_pop_frame_ref(ctx, type, error_buf, error_buf_size)) { + return false; + } +#endif + + if (p_type) + *p_type = type; + if (wasm_is_type_multi_byte_type(type) && ref_ht_ret) { + bh_memcpy_s(ref_ht_ret, sizeof(WASMRefType), ref_type, + wasm_reftype_struct_size(ref_type)); + } + return true; +} + +/* Check whether the stack top elem is subtype of (ref null ht), + and if yes, pop it and return the converted (ref ht) */ +static bool +wasm_loader_pop_nullable_ht(WASMLoaderContext *ctx, uint8 *p_type, + WASMRefType *ref_ht_ret, char *error_buf, + uint32 error_buf_size) +{ + uint8 type = 0; + WASMRefType ref_type = { 0 }; + + if (!wasm_loader_pop_heap_obj(ctx, &type, &ref_type, error_buf, + error_buf_size)) { + return false; + } + + /* Convert to related (ref ht) and return */ + if ((type >= REF_TYPE_EQREF && type <= REF_TYPE_FUNCREF) + || (type >= REF_TYPE_NULLREF && type <= REF_TYPE_I31REF)) { + /* Return (ref func/extern/any/eq/i31/nofunc/noextern/struct/array/none) + */ + wasm_set_refheaptype_common(&ref_ht_ret->ref_ht_common, false, + HEAP_TYPE_FUNC + (type - REF_TYPE_FUNCREF)); + type = ref_ht_ret->ref_type; + } + else if (wasm_is_reftype_htref_nullable(type) + || wasm_is_reftype_htref_non_nullable(type)) { + bh_memcpy_s(ref_ht_ret, (uint32)sizeof(WASMRefType), &ref_type, + wasm_reftype_struct_size(&ref_type)); + /* Convert to (ref ht) */ + ref_ht_ret->ref_ht_common.ref_type = REF_TYPE_HT_NON_NULLABLE; + ref_ht_ret->ref_ht_common.nullable = false; + type = ref_ht_ret->ref_type; + } + *p_type = type; + + return true; +} + +/* Check whether the stack top elem is (ref null $t) or (ref $t), + and if yes, pop it and return the type_idx */ +static bool +wasm_loader_pop_nullable_typeidx(WASMLoaderContext *ctx, uint8 *p_type, + uint32 *p_type_idx, char *error_buf, + uint32 error_buf_size) +{ + uint8 type = 0; + int32 type_idx = -1; + WASMRefType *ref_type = NULL; + + /* Get stack top element */ + if (!wasm_loader_get_frame_ref_top(ctx, &type, &ref_type, error_buf, + error_buf_size)) { + return false; + } + + if (type != VALUE_TYPE_ANY) { + /* stack top isn't (ref null $t) */ + if (!((wasm_is_reftype_htref_nullable(type) + || wasm_is_reftype_htref_non_nullable(type)) + && wasm_is_refheaptype_typeidx(&ref_type->ref_ht_common))) { + set_error_buf(error_buf, error_buf_size, + "type mismatch: expect (ref null $t) but got others"); + return false; + } + type_idx = ref_type->ref_ht_typeidx.type_idx; + + bh_memcpy_s(ctx->ref_type_tmp, sizeof(WASMRefType), ref_type, + wasm_reftype_struct_size(ref_type)); + } + + /* POP stack top */ +#if WASM_ENABLE_FAST_INTERP != 0 + if (!wasm_loader_pop_frame_ref_offset(ctx, type, error_buf, + error_buf_size)) { + return false; + } +#else + if (!wasm_loader_pop_frame_ref(ctx, type, error_buf, error_buf_size)) { + return false; + } +#endif + + /* Convert to type_idx and return */ + *p_type = type; + if (type != VALUE_TYPE_ANY) + *p_type_idx = (uint32)type_idx; + return true; +} +#endif /* WASM_ENABLE_GC != 0 */ + #if WASM_ENABLE_FAST_INTERP == 0 static bool wasm_loader_push_pop_frame_ref(WASMLoaderContext *ctx, uint8 pop_cnt, @@ -5720,6 +8468,9 @@ wasm_loader_push_frame_csp(WASMLoaderContext *ctx, uint8 label_type, ctx->frame_csp->block_type = block_type; ctx->frame_csp->start_addr = start_addr; ctx->frame_csp->stack_cell_num = ctx->stack_cell_num; +#if WASM_ENABLE_GC != 0 + ctx->frame_csp->reftype_map_num = ctx->reftype_map_num; +#endif #if WASM_ENABLE_FAST_INTERP != 0 ctx->frame_csp->dynamic_offset = ctx->dynamic_offset; ctx->frame_csp->patch_list = NULL; @@ -5925,6 +8676,13 @@ wasm_loader_ctx_reinit(WASMLoaderContext *ctx) ctx->frame_ref = ctx->frame_ref_bottom; ctx->stack_cell_num = 0; +#if WASM_ENABLE_GC != 0 + /* clean up reftype map */ + memset(ctx->frame_reftype_map_bottom, 0, ctx->frame_reftype_map_size); + ctx->frame_reftype_map = ctx->frame_reftype_map_bottom; + ctx->reftype_map_num = 0; +#endif + /* clean up frame csp */ memset(ctx->frame_csp_bottom, 0, ctx->frame_csp_size); ctx->frame_csp = ctx->frame_csp_bottom; @@ -6224,6 +8982,10 @@ wasm_loader_emit_br_info(WASMLoaderContext *ctx, BranchBlock *frame_csp, */ BlockType *block_type = &frame_csp->block_type; uint8 *types = NULL, cell; +#if WASM_ENABLE_GC != 0 + WASMRefTypeMap *reftype_maps; + uint32 reftype_map_count; +#endif uint32 arity = 0; int32 i; int16 *frame_offset = ctx->frame_offset; @@ -6232,10 +8994,19 @@ wasm_loader_emit_br_info(WASMLoaderContext *ctx, BranchBlock *frame_csp, /* Note: loop's arity is different from if and block. loop's arity is * its parameter count while if and block arity is result count. */ +#if WASM_ENABLE_GC == 0 if (frame_csp->label_type == LABEL_TYPE_LOOP) arity = block_type_get_param_types(block_type, &types); else arity = block_type_get_result_types(block_type, &types); +#else + if (frame_csp->label_type == LABEL_TYPE_LOOP) + arity = block_type_get_param_types(block_type, &types, &reftype_maps, + &reftype_map_count); + else + arity = block_type_get_result_types(block_type, &types, &reftype_maps, + &reftype_map_count); +#endif /* Part a */ emit_uint32(ctx, arity); @@ -6456,7 +9227,7 @@ wasm_loader_get_const_offset(WASMLoaderContext *ctx, uint8 type, void *value, if ((type == c->value_type) && ((type == VALUE_TYPE_I64 && *(int64 *)value == c->value.i64) || (type == VALUE_TYPE_I32 && *(int32 *)value == c->value.i32) -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 && WASM_ENABLE_GC == 0 || (type == VALUE_TYPE_FUNCREF && *(int32 *)value == c->value.i32) || (type == VALUE_TYPE_EXTERNREF @@ -6523,7 +9294,7 @@ wasm_loader_get_const_offset(WASMLoaderContext *ctx, uint8 type, void *value, c->value.i32 = *(int32 *)value; ctx->const_cell_num++; break; -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 && WASM_ENABLE_GC == 0 case VALUE_TYPE_EXTERNREF: case VALUE_TYPE_FUNCREF: c->value.i32 = *(int32 *)value; @@ -6571,6 +9342,14 @@ fail: goto fail; \ } while (0) +#define TEMPLATE_PUSH_REF(Type) \ + do { \ + if (!wasm_loader_push_frame_ref_offset(loader_ctx, Type, disable_emit, \ + operand_offset, error_buf, \ + error_buf_size)) \ + goto fail; \ + } while (0) + #define TEMPLATE_POP(Type) \ do { \ if (!wasm_loader_pop_frame_ref_offset(loader_ctx, VALUE_TYPE_##Type, \ @@ -6578,6 +9357,13 @@ fail: goto fail; \ } while (0) +#define TEMPLATE_POP_REF(Type) \ + do { \ + if (!wasm_loader_pop_frame_ref_offset(loader_ctx, Type, error_buf, \ + error_buf_size)) \ + goto fail; \ + } while (0) + #define PUSH_OFFSET_TYPE(type) \ do { \ if (!(wasm_loader_push_frame_offset(loader_ctx, type, disable_emit, \ @@ -6619,6 +9405,13 @@ fail: goto fail; \ } while (0) +#define TEMPLATE_PUSH_REF(Type) \ + do { \ + if (!(wasm_loader_push_frame_ref(loader_ctx, Type, error_buf, \ + error_buf_size))) \ + goto fail; \ + } while (0) + #define TEMPLATE_POP(Type) \ do { \ if (!(wasm_loader_pop_frame_ref(loader_ctx, VALUE_TYPE_##Type, \ @@ -6626,6 +9419,13 @@ fail: goto fail; \ } while (0) +#define TEMPLATE_POP_REF(Type) \ + do { \ + if (!(wasm_loader_pop_frame_ref(loader_ctx, Type, error_buf, \ + error_buf_size))) \ + goto fail; \ + } while (0) + #define POP_AND_PUSH(type_pop, type_push) \ do { \ if (!(wasm_loader_push_pop_frame_ref(loader_ctx, 1, type_push, \ @@ -6651,6 +9451,8 @@ fail: #define PUSH_V128() TEMPLATE_PUSH(V128) #define PUSH_FUNCREF() TEMPLATE_PUSH(FUNCREF) #define PUSH_EXTERNREF() TEMPLATE_PUSH(EXTERNREF) +#define PUSH_REF(Type) TEMPLATE_PUSH_REF(Type) +#define POP_REF(Type) TEMPLATE_POP_REF(Type) #define POP_I32() TEMPLATE_POP(I32) #define POP_F32() TEMPLATE_POP(F32) @@ -6659,6 +9461,7 @@ fail: #define POP_V128() TEMPLATE_POP(V128) #define POP_FUNCREF() TEMPLATE_POP(FUNCREF) #define POP_EXTERNREF() TEMPLATE_POP(EXTERNREF) +#define POP_STRINGREF() TEMPLATE_POP(STRINGREF) #if WASM_ENABLE_FAST_INTERP != 0 @@ -6671,12 +9474,21 @@ reserve_block_ret(WASMLoaderContext *loader_ctx, uint8 opcode, : loader_ctx->frame_csp; BlockType *block_type = &block->block_type; uint8 *return_types = NULL; +#if WASM_ENABLE_GC != 0 + WASMRefTypeMap *reftype_maps = NULL; + uint32 reftype_map_count; +#endif uint32 return_count = 0, value_count = 0, total_cel_num = 0; int32 i = 0; int16 dynamic_offset, dynamic_offset_org, *frame_offset = NULL, *frame_offset_org = NULL; +#if WASM_ENABLE_GC == 0 return_count = block_type_get_result_types(block_type, &return_types); +#else + return_count = block_type_get_result_types( + block_type, &return_types, &reftype_maps, &reftype_map_count); +#endif /* If there is only one return value, use EXT_OP_COPY_STACK_TOP/_I64 instead * of EXT_OP_COPY_STACK_VALUES for interpreter performance. */ @@ -6831,6 +9643,7 @@ fail: goto fail; \ } while (0) +#if WASM_ENABLE_GC == 0 #define PUSH_CSP(label_type, block_type, _start_addr) \ do { \ if (!wasm_loader_push_frame_csp(loader_ctx, label_type, block_type, \ @@ -6844,6 +9657,47 @@ fail: if (!wasm_loader_pop_frame_csp(loader_ctx, error_buf, error_buf_size)) \ goto fail; \ } while (0) +#else +#define PUSH_CSP(label_type, block_type, _start_addr) \ + do { \ + if (!wasm_loader_push_frame_csp(loader_ctx, label_type, block_type, \ + _start_addr, error_buf, \ + error_buf_size)) \ + goto fail; \ + if (!wasm_loader_init_local_use_masks(loader_ctx, local_count, \ + error_buf, error_buf_size)) { \ + goto fail; \ + } \ + } while (0) + +#define POP_CSP() \ + do { \ + wasm_loader_destroy_curr_local_use_masks(loader_ctx); \ + if (!wasm_loader_pop_frame_csp(loader_ctx, error_buf, error_buf_size)) \ + goto fail; \ + } while (0) +#endif /* end of WASM_ENABLE_GC == 0 */ + +#if WASM_ENABLE_GC == 0 +#define GET_LOCAL_REFTYPE() (void)0 +#else +#define GET_LOCAL_REFTYPE() \ + do { \ + if (wasm_is_type_multi_byte_type(local_type)) { \ + WASMRefType *_ref_type; \ + if (local_idx < param_count) \ + _ref_type = wasm_reftype_map_find( \ + param_reftype_maps, param_reftype_map_count, local_idx); \ + else \ + _ref_type = wasm_reftype_map_find(local_reftype_maps, \ + local_reftype_map_count, \ + local_idx - param_count); \ + bh_assert(_ref_type); \ + bh_memcpy_s(&wasm_ref_type, sizeof(WASMRefType), _ref_type, \ + wasm_reftype_struct_size(_ref_type)); \ + } \ + } while (0) +#endif /* end of WASM_ENABLE_GC == 0 */ #define GET_LOCAL_INDEX_TYPE_AND_OFFSET() \ do { \ @@ -6856,13 +9710,7 @@ fail: ? param_types[local_idx] \ : local_types[local_idx - param_count]; \ local_offset = local_offsets[local_idx]; \ - } while (0) - -#define CHECK_BR(depth) \ - do { \ - if (!wasm_loader_check_br(loader_ctx, depth, error_buf, \ - error_buf_size)) \ - goto fail; \ + GET_LOCAL_REFTYPE(); \ } while (0) static bool @@ -7048,16 +9896,46 @@ check_memory_align_equal(uint8 opcode, uint32 align, char *error_buf, static bool wasm_loader_check_br(WASMLoaderContext *loader_ctx, uint32 depth, - char *error_buf, uint32 error_buf_size) + bool is_br_table, char *error_buf, uint32 error_buf_size) { BranchBlock *target_block, *cur_block; BlockType *target_block_type; - uint8 *types = NULL, *frame_ref; + uint8 type, *types = NULL, *frame_ref; uint32 arity = 0; int32 i, available_stack_cell; uint16 cell_num; +#if WASM_ENABLE_GC != 0 + WASMRefTypeMap *frame_reftype_map; + WASMRefTypeMap *reftype_maps = NULL, *reftype_map = NULL; + WASMRefType *ref_type; + uint32 reftype_map_count = 0; + int32 available_reftype_map; + bool is_type_multi_byte; +#endif - if (loader_ctx->csp_num < depth + 1) { + uint8 *frame_ref_old = loader_ctx->frame_ref; + uint8 *frame_ref_after_popped = NULL; + uint8 frame_ref_tmp[4] = { 0 }; + uint8 *frame_ref_buf = frame_ref_tmp; + uint32 stack_cell_num_old = loader_ctx->stack_cell_num; +#if WASM_ENABLE_GC != 0 + WASMRefTypeMap *frame_reftype_map_old = loader_ctx->frame_reftype_map; + WASMRefTypeMap *frame_reftype_map_after_popped = NULL; + WASMRefTypeMap frame_reftype_map_tmp[4] = { 0 }; + WASMRefTypeMap *frame_reftype_map_buf = frame_reftype_map_tmp; + uint32 reftype_map_num_old = loader_ctx->reftype_map_num; +#endif +#if WASM_ENABLE_FAST_INTERP != 0 + int16 *frame_offset_old = loader_ctx->frame_offset; + int16 *frame_offset_after_popped = NULL; + int16 frame_offset_tmp[4] = { 0 }; + int16 *frame_offset_buf = frame_offset_tmp; + uint16 dynamic_offset_old = (loader_ctx->frame_csp - 1)->dynamic_offset; +#endif + bool ret = false; + + bh_assert(loader_ctx->csp_num > 0); + if (loader_ctx->csp_num - 1 < depth) { set_error_buf(error_buf, error_buf_size, "unknown label, " "unexpected end of section or function"); @@ -7068,26 +9946,108 @@ wasm_loader_check_br(WASMLoaderContext *loader_ctx, uint32 depth, target_block = loader_ctx->frame_csp - (depth + 1); target_block_type = &target_block->block_type; frame_ref = loader_ctx->frame_ref; +#if WASM_ENABLE_GC != 0 + frame_reftype_map = loader_ctx->frame_reftype_map; +#endif /* Note: loop's arity is different from if and block. loop's arity is * its parameter count while if and block arity is result count. */ +#if WASM_ENABLE_GC == 0 if (target_block->label_type == LABEL_TYPE_LOOP) arity = block_type_get_param_types(target_block_type, &types); else arity = block_type_get_result_types(target_block_type, &types); +#else + if (target_block->label_type == LABEL_TYPE_LOOP) + arity = block_type_get_param_types(target_block_type, &types, + &reftype_maps, &reftype_map_count); + else + arity = block_type_get_result_types(target_block_type, &types, + &reftype_maps, &reftype_map_count); +#endif /* If the stack is in polymorphic state, just clear the stack * and then re-push the values to make the stack top values * match block type. */ if (cur_block->is_stack_polymorphic) { +#if WASM_ENABLE_GC != 0 + int32 j = reftype_map_count - 1; +#endif for (i = (int32)arity - 1; i >= 0; i--) { +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_multi_byte_type(types[i])) { + bh_assert(reftype_maps[j].index == i); + bh_memcpy_s(loader_ctx->ref_type_tmp, sizeof(WASMRefType), + reftype_maps[j].ref_type, + wasm_reftype_struct_size(reftype_maps[j].ref_type)); + j--; + } +#endif #if WASM_ENABLE_FAST_INTERP != 0 POP_OFFSET_TYPE(types[i]); #endif POP_TYPE(types[i]); } + + /* Backup stack data since it may be changed in the below + push operations, and the stack data may be used when + checking other target blocks of opcode br_table */ + if (is_br_table) { + uint64 total_size; + + frame_ref_after_popped = loader_ctx->frame_ref; + total_size = (uint64)sizeof(uint8) + * (frame_ref_old - frame_ref_after_popped); + if (total_size > sizeof(frame_ref_tmp) + && !(frame_ref_buf = loader_malloc(total_size, error_buf, + error_buf_size))) { + goto fail; + } + bh_memcpy_s(frame_ref_buf, (uint32)total_size, + frame_ref_after_popped, (uint32)total_size); + +#if WASM_ENABLE_GC != 0 + frame_reftype_map_after_popped = loader_ctx->frame_reftype_map; + total_size = + (uint64)sizeof(WASMRefTypeMap) + * (frame_reftype_map_old - frame_reftype_map_after_popped); + if (total_size > sizeof(frame_reftype_map_tmp) + && !(frame_reftype_map_buf = loader_malloc( + total_size, error_buf, error_buf_size))) { + goto fail; + } + bh_memcpy_s(frame_reftype_map_buf, (uint32)total_size, + frame_reftype_map_after_popped, (uint32)total_size); +#endif + +#if WASM_ENABLE_FAST_INTERP != 0 + frame_offset_after_popped = loader_ctx->frame_offset; + total_size = (uint64)sizeof(int16) + * (frame_offset_old - frame_offset_after_popped); + if (total_size > sizeof(frame_offset_tmp) + && !(frame_offset_buf = loader_malloc(total_size, error_buf, + error_buf_size))) { + goto fail; + } + bh_memcpy_s(frame_offset_buf, (uint32)total_size, + frame_offset_after_popped, (uint32)total_size); +#endif + } + +#if WASM_ENABLE_GC != 0 + j = 0; +#endif for (i = 0; i < (int32)arity; i++) { +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_multi_byte_type(types[i])) { + bh_assert(reftype_maps[j].index == i); + bh_memcpy_s(loader_ctx->ref_type_tmp, sizeof(WASMRefType), + reftype_maps[j].ref_type, + wasm_reftype_struct_size(reftype_maps[j].ref_type)); + j++; + } +#endif #if WASM_ENABLE_FAST_INTERP != 0 bool disable_emit = true; int16 operand_offset = 0; @@ -7095,42 +10055,141 @@ wasm_loader_check_br(WASMLoaderContext *loader_ctx, uint32 depth, #endif PUSH_TYPE(types[i]); } - return true; + +#if WASM_ENABLE_FAST_INTERP != 0 + emit_br_info(target_block); +#endif + + /* Restore the stack data, note that frame_ref_bottom, + frame_reftype_map_bottom, frame_offset_bottom may be + re-allocated in the above push operations */ + if (is_br_table) { + uint32 total_size; + + /* The stack operand num should not be smaller than before + after pop and push operations */ + bh_assert(loader_ctx->stack_cell_num >= stack_cell_num_old); + loader_ctx->stack_cell_num = stack_cell_num_old; + loader_ctx->frame_ref = + loader_ctx->frame_ref_bottom + stack_cell_num_old; + total_size = (uint32)sizeof(uint8) + * (frame_ref_old - frame_ref_after_popped); + bh_memcpy_s((uint8 *)loader_ctx->frame_ref - total_size, total_size, + frame_ref_buf, total_size); + +#if WASM_ENABLE_GC != 0 + /* The stack operand num should not be smaller than before + after pop and push operations */ + bh_assert(loader_ctx->reftype_map_num >= reftype_map_num_old); + loader_ctx->reftype_map_num = reftype_map_num_old; + loader_ctx->frame_reftype_map = + loader_ctx->frame_reftype_map_bottom + reftype_map_num_old; + total_size = + (uint32)sizeof(WASMRefTypeMap) + * (frame_reftype_map_old - frame_reftype_map_after_popped); + bh_memcpy_s((uint8 *)loader_ctx->frame_reftype_map - total_size, + total_size, frame_reftype_map_buf, total_size); +#endif + +#if WASM_ENABLE_FAST_INTERP != 0 + loader_ctx->frame_offset = + loader_ctx->frame_offset_bottom + stack_cell_num_old; + total_size = (uint32)sizeof(int16) + * (frame_offset_old - frame_offset_after_popped); + bh_memcpy_s((uint8 *)loader_ctx->frame_offset - total_size, + total_size, frame_offset_buf, total_size); + (loader_ctx->frame_csp - 1)->dynamic_offset = dynamic_offset_old; +#endif + } + + ret = true; + goto cleanup_and_return; } available_stack_cell = (int32)(loader_ctx->stack_cell_num - cur_block->stack_cell_num); +#if WASM_ENABLE_GC != 0 + available_reftype_map = + (int32)(loader_ctx->reftype_map_num + - (loader_ctx->frame_csp - 1)->reftype_map_num); + reftype_map = reftype_maps ? reftype_maps + reftype_map_count - 1 : NULL; +#endif /* Check stack top values match target block type */ for (i = (int32)arity - 1; i >= 0; i--) { - if (!check_stack_top_values(frame_ref, available_stack_cell, types[i], - error_buf, error_buf_size)) - return false; + type = types[i]; +#if WASM_ENABLE_GC != 0 + ref_type = NULL; + is_type_multi_byte = wasm_is_type_multi_byte_type(type); + if (is_type_multi_byte) { + bh_assert(reftype_map); + ref_type = reftype_map->ref_type; + } +#endif + + if (available_stack_cell <= 0 && cur_block->is_stack_polymorphic) + break; + + if (!check_stack_top_values(loader_ctx, frame_ref, available_stack_cell, +#if WASM_ENABLE_GC != 0 + frame_reftype_map, available_reftype_map, +#endif + type, +#if WASM_ENABLE_GC != 0 + ref_type, +#endif + error_buf, error_buf_size)) { + goto fail; + } cell_num = wasm_value_type_cell_num(types[i]); frame_ref -= cell_num; available_stack_cell -= cell_num; +#if WASM_ENABLE_GC != 0 + if (is_type_multi_byte) { + frame_reftype_map--; + available_reftype_map--; + reftype_map--; + } +#endif } - return true; +#if WASM_ENABLE_FAST_INTERP != 0 + emit_br_info(target_block); +#endif + ret = true; + +cleanup_and_return: fail: - return false; + if (frame_ref_buf && frame_ref_buf != frame_ref_tmp) + wasm_runtime_free(frame_ref_buf); +#if WASM_ENABLE_GC != 0 + if (frame_reftype_map_buf && frame_reftype_map_buf != frame_reftype_map_tmp) + wasm_runtime_free(frame_reftype_map_buf); +#endif +#if WASM_ENABLE_FAST_INTERP != 0 + if (frame_offset_buf && frame_offset_buf != frame_offset_tmp) + wasm_runtime_free(frame_offset_tmp); +#endif + + return ret; } static BranchBlock * check_branch_block(WASMLoaderContext *loader_ctx, uint8 **p_buf, uint8 *buf_end, - char *error_buf, uint32 error_buf_size) + bool is_br_table, char *error_buf, uint32 error_buf_size) { uint8 *p = *p_buf, *p_end = buf_end; BranchBlock *frame_csp_tmp; uint32 depth; read_leb_uint32(p, p_end, depth); - CHECK_BR(depth); + if (!wasm_loader_check_br(loader_ctx, depth, is_br_table, error_buf, + error_buf_size)) { + goto fail; + } + frame_csp_tmp = loader_ctx->frame_csp - depth - 1; -#if WASM_ENABLE_FAST_INTERP != 0 - emit_br_info(frame_csp_tmp); -#endif *p_buf = p; return frame_csp_tmp; @@ -7157,7 +10216,11 @@ check_branch_block_for_delegate(WASMLoaderContext *loader_ctx, uint8 **p_buf, */ bh_assert(loader_ctx->csp_num > 0); if (loader_ctx->csp_num - 1 <= depth) { +#if WASM_ENABLE_SPEC_TEST == 0 set_error_buf(error_buf, error_buf_size, "unknown delegate label"); +#else + set_error_buf(error_buf, error_buf_size, "unknown label"); +#endif goto fail; } frame_csp_tmp = loader_ctx->frame_csp - depth - 2; @@ -7170,7 +10233,7 @@ check_branch_block_for_delegate(WASMLoaderContext *loader_ctx, uint8 **p_buf, fail: return NULL; } -#endif +#endif /* end of WASM_ENABLE_EXCE_HANDLING != 0 */ static bool check_block_stack(WASMLoaderContext *loader_ctx, BranchBlock *block, @@ -7181,11 +10244,28 @@ check_block_stack(WASMLoaderContext *loader_ctx, BranchBlock *block, uint32 return_count = 0; int32 available_stack_cell, return_cell_num, i; uint8 *frame_ref = NULL; +#if WASM_ENABLE_GC != 0 + WASMRefTypeMap *frame_reftype_map; + WASMRefTypeMap *return_reftype_maps = NULL, *return_reftype_map; + WASMRefType *ref_type; + uint32 param_count, return_reftype_map_count = 0; + int32 available_reftype_map = + (int32)(loader_ctx->reftype_map_num - block->reftype_map_num); +#endif available_stack_cell = (int32)(loader_ctx->stack_cell_num - block->stack_cell_num); +#if WASM_ENABLE_GC == 0 return_count = block_type_get_result_types(block_type, &return_types); +#else + return_count = block_type_get_result_types(block_type, &return_types, + &return_reftype_maps, + &return_reftype_map_count); + param_count = + block_type->is_value_type ? 0 : block_type->u.type->param_count; + (void)param_count; +#endif return_cell_num = return_count > 0 ? wasm_get_cell_num(return_types, return_count) : 0; @@ -7193,7 +10273,20 @@ check_block_stack(WASMLoaderContext *loader_ctx, BranchBlock *block, * and then re-push the values to make the stack top values * match block type. */ if (block->is_stack_polymorphic) { +#if WASM_ENABLE_GC != 0 + int32 j = return_reftype_map_count - 1; +#endif for (i = (int32)return_count - 1; i >= 0; i--) { +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_multi_byte_type(return_types[i])) { + bh_assert(return_reftype_maps[j].index == i + param_count); + bh_memcpy_s( + loader_ctx->ref_type_tmp, sizeof(WASMRefType), + return_reftype_maps[j].ref_type, + wasm_reftype_struct_size(return_reftype_maps[j].ref_type)); + j--; + } +#endif #if WASM_ENABLE_FAST_INTERP != 0 POP_OFFSET_TYPE(return_types[i]); #endif @@ -7208,7 +10301,20 @@ check_block_stack(WASMLoaderContext *loader_ctx, BranchBlock *block, goto fail; } +#if WASM_ENABLE_GC != 0 + j = 0; +#endif for (i = 0; i < (int32)return_count; i++) { +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_multi_byte_type(return_types[i])) { + bh_assert(return_reftype_maps[j].index == i + param_count); + bh_memcpy_s( + loader_ctx->ref_type_tmp, sizeof(WASMRefType), + return_reftype_maps[j].ref_type, + wasm_reftype_struct_size(return_reftype_maps[j].ref_type)); + j++; + } +#endif #if WASM_ENABLE_FAST_INTERP != 0 bool disable_emit = true; int16 operand_offset = 0; @@ -7243,12 +10349,42 @@ check_block_stack(WASMLoaderContext *loader_ctx, BranchBlock *block, /* Check stack values match return types */ frame_ref = loader_ctx->frame_ref; +#if WASM_ENABLE_GC != 0 + frame_reftype_map = loader_ctx->frame_reftype_map; + return_reftype_map = + return_reftype_map_count + ? return_reftype_maps + return_reftype_map_count - 1 + : NULL; +#endif for (i = (int32)return_count - 1; i >= 0; i--) { - if (!check_stack_top_values(frame_ref, available_stack_cell, - return_types[i], error_buf, error_buf_size)) + uint8 type = return_types[i]; +#if WASM_ENABLE_GC != 0 + bool is_type_multi_byte = wasm_is_type_multi_byte_type(type); + ref_type = NULL; + if (is_type_multi_byte) { + bh_assert(return_reftype_map); + ref_type = return_reftype_map->ref_type; + } +#endif + if (!check_stack_top_values(loader_ctx, frame_ref, available_stack_cell, +#if WASM_ENABLE_GC != 0 + frame_reftype_map, available_reftype_map, +#endif + type, +#if WASM_ENABLE_GC != 0 + ref_type, +#endif + error_buf, error_buf_size)) return false; frame_ref -= wasm_value_type_cell_num(return_types[i]); available_stack_cell -= wasm_value_type_cell_num(return_types[i]); +#if WASM_ENABLE_GC != 0 + if (is_type_multi_byte) { + frame_reftype_map--; + available_reftype_map--; + return_reftype_map--; + } +#endif } return true; @@ -7280,7 +10416,7 @@ copy_params_to_dynamic_space(WASMLoaderContext *loader_ctx, bool is_if_block, uint32 i; BranchBlock *block = loader_ctx->frame_csp - 1; BlockType *block_type = &block->block_type; - WASMType *wasm_type = block_type->u.type; + WASMFuncType *wasm_type = block_type->u.type; uint32 param_count = block_type->u.type->param_count; int16 condition_offset = 0; bool disable_emit = false; @@ -7353,6 +10489,18 @@ fail: } #endif +#if WASM_ENABLE_GC == 0 +#define RESET_REFTYPE_MAP_STACK() (void)0 +#else +#define RESET_REFTYPE_MAP_STACK() \ + do { \ + loader_ctx->reftype_map_num = \ + (loader_ctx->frame_csp - 1)->reftype_map_num; \ + loader_ctx->frame_reftype_map = loader_ctx->frame_reftype_map_bottom \ + + loader_ctx->reftype_map_num; \ + } while (0) +#endif + /* reset the stack to the state of before entering the last block */ #if WASM_ENABLE_FAST_INTERP != 0 #define RESET_STACK() \ @@ -7363,6 +10511,7 @@ fail: loader_ctx->frame_ref_bottom + loader_ctx->stack_cell_num; \ loader_ctx->frame_offset = \ loader_ctx->frame_offset_bottom + loader_ctx->stack_cell_num; \ + RESET_REFTYPE_MAP_STACK(); \ } while (0) #else #define RESET_STACK() \ @@ -7371,6 +10520,7 @@ fail: (loader_ctx->frame_csp - 1)->stack_cell_num; \ loader_ctx->frame_ref = \ loader_ctx->frame_ref_bottom + loader_ctx->stack_cell_num; \ + RESET_REFTYPE_MAP_STACK(); \ } while (0) #endif @@ -7392,30 +10542,44 @@ fail: } \ } while (0) -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 static bool get_table_elem_type(const WASMModule *module, uint32 table_idx, - uint8 *p_elem_type, char *error_buf, uint32 error_buf_size) + uint8 *p_elem_type, void **p_ref_type, char *error_buf, + uint32 error_buf_size) { if (!check_table_index(module, table_idx, error_buf, error_buf_size)) { return false; } - if (p_elem_type) { - if (table_idx < module->import_table_count) + if (table_idx < module->import_table_count) { + if (p_elem_type) *p_elem_type = module->import_tables[table_idx].u.table.elem_type; - else +#if WASM_ENABLE_GC != 0 + if (p_ref_type) + *((WASMRefType **)p_ref_type) = + module->import_tables[table_idx].u.table.elem_ref_type; +#endif + } + else { + if (p_elem_type) *p_elem_type = module->tables[module->import_table_count + table_idx] .elem_type; +#if WASM_ENABLE_GC != 0 + if (p_ref_type) + *((WASMRefType **)p_ref_type) = + module->tables[module->import_table_count + table_idx] + .elem_ref_type; +#endif } return true; } static bool get_table_seg_elem_type(const WASMModule *module, uint32 table_seg_idx, - uint8 *p_elem_type, char *error_buf, - uint32 error_buf_size) + uint8 *p_elem_type, void **p_elem_ref_type, + char *error_buf, uint32 error_buf_size) { if (table_seg_idx >= module->table_seg_count) { set_error_buf_v(error_buf, error_buf_size, "unknown elem segment %u", @@ -7426,6 +10590,11 @@ get_table_seg_elem_type(const WASMModule *module, uint32 table_seg_idx, if (p_elem_type) { *p_elem_type = module->table_segments[table_seg_idx].elem_type; } +#if WASM_ENABLE_GC != 0 + if (p_elem_ref_type) + *((WASMRefType **)p_elem_ref_type) = + module->table_segments[table_seg_idx].elem_ref_type; +#endif return true; } #endif @@ -7471,6 +10640,13 @@ wasm_loader_prepare_bytecode(WASMModule *module, WASMFunction *func, bool return_value = false; WASMLoaderContext *loader_ctx; BranchBlock *frame_csp_tmp; +#if WASM_ENABLE_GC != 0 + WASMRefTypeMap *param_reftype_maps, *local_reftype_maps; + uint32 param_reftype_map_count, local_reftype_map_count; + int32 heap_type; + WASMRefType wasm_ref_type = { 0 }; + bool need_ref_type_map; +#endif #if WASM_ENABLE_FAST_INTERP != 0 uint8 *func_const_end, *func_const = NULL; int16 operand_offset = 0; @@ -7495,9 +10671,21 @@ wasm_loader_prepare_bytecode(WASMModule *module, WASMFunction *func, local_types = func->local_types; local_offsets = func->local_offsets; +#if WASM_ENABLE_GC != 0 + param_reftype_maps = func->func_type->ref_type_maps; + param_reftype_map_count = func->func_type->ref_type_map_count; + local_reftype_maps = func->local_ref_type_maps; + local_reftype_map_count = func->local_ref_type_map_count; +#endif + if (!(loader_ctx = wasm_loader_ctx_init(func, error_buf, error_buf_size))) { goto fail; } +#if WASM_ENABLE_GC != 0 + loader_ctx->module = module; + loader_ctx->ref_type_set = module->ref_type_set; + loader_ctx->ref_type_tmp = &wasm_ref_type; +#endif #if WASM_ENABLE_FAST_INTERP != 0 /* For the first traverse, the initial value of preserved_local_offset has @@ -7531,7 +10719,6 @@ re_scan: disable_emit = false; emit_label(opcode); #endif - switch (opcode) { case WASM_OP_UNREACHABLE: RESET_STACK(); @@ -7560,7 +10747,9 @@ re_scan: PRESERVE_LOCAL_FOR_BLOCK(); #endif +#if WASM_ENABLE_GC == 0 POP_I32(); +#endif goto handle_op_block_and_loop; } case WASM_OP_BLOCK: @@ -7594,7 +10783,6 @@ re_scan: uint32 available_params = 0; #endif - p_org = p - 1; CHECK_BUF(p, p_end, 1); value_type = read_uint8(p); if (is_byte_a_type(value_type)) { @@ -7602,12 +10790,56 @@ re_scan: * 0x40/0x7F/0x7E/0x7D/0x7C, take it as the type of * the single return value. */ block_type.is_value_type = true; - block_type.u.value_type = value_type; + block_type.u.value_type.type = value_type; +#if WASM_ENABLE_WAMR_COMPILER != 0 + if (value_type == VALUE_TYPE_V128) + module->is_simd_used = true; + else if (value_type == VALUE_TYPE_FUNCREF + || value_type == VALUE_TYPE_EXTERNREF) + module->is_ref_types_used = true; +#endif +#if WASM_ENABLE_GC != 0 + if (value_type != VALUE_TYPE_VOID) { + p_org = p; + p--; + if (!resolve_value_type((const uint8 **)&p, p_end, + module, &need_ref_type_map, + &wasm_ref_type, false, + error_buf, error_buf_size)) { + goto fail; + } + if (need_ref_type_map) { + block_type.u.value_type.ref_type_map.index = 0; + if (!(block_type.u.value_type.ref_type_map + .ref_type = reftype_set_insert( + module->ref_type_set, &wasm_ref_type, + error_buf, error_buf_size))) { + goto fail; + } + } + /* Set again as the type might be changed, e.g. + (ref null any) to anyref */ + block_type.u.value_type.type = wasm_ref_type.ref_type; +#if WASM_ENABLE_FAST_INTERP == 0 + while (p_org < p) { +#if WASM_ENABLE_DEBUG_INTERP != 0 + if (!record_fast_op(module, p_org, *p_org, + error_buf, error_buf_size)) { + goto fail; + } +#endif + /* Ignore extra bytes for interpreter */ + *p_org++ = WASM_OP_NOP; + } +#endif + } +#endif /* end of WASM_ENABLE_GC != 0 */ } else { uint32 type_index; /* Resolve the leb128 encoded type index as block type */ p--; + p_org = p - 1; read_leb_uint32(p, p_end, type_index); if (type_index >= module->type_count) { set_error_buf(error_buf, error_buf_size, @@ -7615,7 +10847,8 @@ re_scan: goto fail; } block_type.is_value_type = false; - block_type.u.type = module->types[type_index]; + block_type.u.type = + (WASMFuncType *)module->types[type_index]; #if WASM_ENABLE_FAST_INTERP == 0 /* If block use type index as block type, change the opcode * to new extended opcode so that interpreter can resolve @@ -7631,9 +10864,15 @@ re_scan: #endif } +#if WASM_ENABLE_GC != 0 + if (opcode == WASM_OP_IF) { + POP_I32(); + } +#endif + /* Pop block parameters from stack */ if (BLOCK_HAS_PARAM(block_type)) { - WASMType *wasm_type = block_type.u.type; + WASMFuncType *wasm_type = block_type.u.type; BranchBlock *cur_block = loader_ctx->frame_csp - 1; #if WASM_ENABLE_FAST_INTERP != 0 @@ -7680,8 +10919,15 @@ re_scan: * Since the stack is already in polymorphic state, * the opcode will not be executed, so the dummy * offset won't cause any error */ - *loader_ctx->frame_offset++ = 0; - if (cell_num > 1) { + uint32 n; + + for (n = 0; n < cell_num; n++) { + if (loader_ctx->p_code_compiled == NULL) { + if (!check_offset_push(loader_ctx, + error_buf, + error_buf_size)) + goto fail; + } *loader_ctx->frame_offset++ = 0; } } @@ -7724,7 +10970,7 @@ re_scan: * (i32.const 1) * (i32.const 2) * (if (param i32 i32) (result i32 i32) (local.get 0) - * (then)) (i32.add) + * (then)) (i32.add) * ) * * So we should emit a copy instruction before the if. @@ -7823,9 +11069,9 @@ re_scan: uint8 *frame_ref = loader_ctx->frame_ref; for (int tti = (int32)tag_type->param_count - 1; tti >= 0; tti--) { - if (!check_stack_top_values(frame_ref, available_stack_cell, - tag_type->types[tti], error_buf, - error_buf_size)) { + if (!check_stack_top_values( + loader_ctx, frame_ref, available_stack_cell, + tag_type->types[tti], error_buf, error_buf_size)) { snprintf(error_buf, error_buf_size, "type mismatch: instruction requires [%s] but " "stack has [%s]", @@ -7854,8 +11100,9 @@ re_scan: SET_CUR_BLOCK_STACK_POLYMORPHIC_STATE(true); /* check the target catching block: LABEL_TYPE_CATCH */ - if (!(frame_csp_tmp = check_branch_block( - loader_ctx, &p, p_end, error_buf, error_buf_size))) + if (!(frame_csp_tmp = + check_branch_block(loader_ctx, &p, p_end, false, + error_buf, error_buf_size))) goto fail; if (frame_csp_tmp->label_type != LABEL_TYPE_CATCH @@ -7976,7 +11223,7 @@ re_scan: /* catch_all has no tagtype and therefore no parameters */ break; } -#endif +#endif /* end of WASM_ENABLE_EXCE_HANDLING != 0 */ case WASM_OP_ELSE: { BranchBlock *block = NULL; @@ -8000,6 +11247,13 @@ re_scan: block->else_addr = p - 1; block_type = block->block_type; +#if WASM_ENABLE_GC != 0 + if (!wasm_loader_init_local_use_masks( + loader_ctx, local_count, error_buf, error_buf_size)) { + goto fail; + } +#endif + #if WASM_ENABLE_FAST_INTERP != 0 /* if the result of if branch is in local or const area, add a * copy op */ @@ -8042,25 +11296,35 @@ re_scan: goto fail; /* if no else branch, and return types do not match param types, - * fail */ + report failure */ if (cur_block->label_type == LABEL_TYPE_IF && !cur_block->else_addr) { uint32 block_param_count = 0, block_ret_count = 0; uint8 *block_param_types = NULL, *block_ret_types = NULL; BlockType *cur_block_type = &cur_block->block_type; - if (cur_block_type->is_value_type) { - if (cur_block_type->u.value_type != VALUE_TYPE_VOID) { - block_ret_count = 1; - block_ret_types = &cur_block_type->u.value_type; - } - } - else { - block_param_count = cur_block_type->u.type->param_count; - block_ret_count = cur_block_type->u.type->result_count; - block_param_types = cur_block_type->u.type->types; - block_ret_types = - cur_block_type->u.type->types + block_param_count; - } +#if WASM_ENABLE_GC != 0 + uint32 block_param_reftype_map_count; + uint32 block_ret_reftype_map_count; + WASMRefTypeMap *block_param_reftype_maps; + WASMRefTypeMap *block_ret_reftype_maps; +#endif + + block_param_count = block_type_get_param_types( + cur_block_type, &block_param_types +#if WASM_ENABLE_GC != 0 + , + &block_param_reftype_maps, + &block_param_reftype_map_count +#endif + ); + block_ret_count = block_type_get_result_types( + cur_block_type, &block_ret_types +#if WASM_ENABLE_GC != 0 + , + &block_ret_reftype_maps, &block_ret_reftype_map_count +#endif + ); + if (block_param_count != block_ret_count || (block_param_count && memcmp(block_param_types, block_ret_types, @@ -8069,6 +11333,19 @@ re_scan: "type mismatch: else branch missing"); goto fail; } +#if WASM_ENABLE_GC != 0 + if (block_param_reftype_map_count + != block_ret_reftype_map_count + || (block_param_reftype_map_count + && memcmp(block_param_reftype_maps, + block_ret_reftype_maps, + sizeof(WASMRefTypeMap) + * block_param_reftype_map_count))) { + set_error_buf(error_buf, error_buf_size, + "type mismatch: else branch missing"); + goto fail; + } +#endif } POP_CSP(); @@ -8110,8 +11387,9 @@ re_scan: case WASM_OP_BR: { - if (!(frame_csp_tmp = check_branch_block( - loader_ctx, &p, p_end, error_buf, error_buf_size))) + if (!(frame_csp_tmp = + check_branch_block(loader_ctx, &p, p_end, false, + error_buf, error_buf_size))) goto fail; RESET_STACK(); @@ -8123,8 +11401,9 @@ re_scan: { POP_I32(); - if (!(frame_csp_tmp = check_branch_block( - loader_ctx, &p, p_end, error_buf, error_buf_size))) + if (!(frame_csp_tmp = + check_branch_block(loader_ctx, &p, p_end, false, + error_buf, error_buf_size))) goto fail; break; @@ -8132,14 +11411,13 @@ re_scan: case WASM_OP_BR_TABLE: { - uint8 *ret_types = NULL; - uint32 ret_count = 0; + uint32 depth, default_arity, arity = 0; + BranchBlock *target_block; + BlockType *target_block_type; #if WASM_ENABLE_FAST_INTERP == 0 - uint8 *p_depth_begin, *p_depth; - uint32 depth, j; BrTableCache *br_table_cache = NULL; - - p_org = p - 1; + uint8 *p_depth_begin, *p_depth, *p_opcode = p - 1; + uint32 j; #endif read_leb_uint32(p, p_end, count); @@ -8148,51 +11426,58 @@ re_scan: #endif POP_I32(); + /* Get the default depth and check it */ + p_org = p; + for (i = 0; i <= count; i++) { + read_leb_uint32(p, p_end, depth); + } + if (loader_ctx->csp_num < depth + 1) { + set_error_buf(error_buf, error_buf_size, + "unknown label, " + "unexpected end of section or function"); + goto fail; + } + p = p_org; + + /* Get the default block's arity */ + target_block = loader_ctx->frame_csp - (depth + 1); + target_block_type = &target_block->block_type; + default_arity = block_type_get_arity(target_block_type, + target_block->label_type); + #if WASM_ENABLE_FAST_INTERP == 0 p_depth_begin = p_depth = p; #endif for (i = 0; i <= count; i++) { - if (!(frame_csp_tmp = - check_branch_block(loader_ctx, &p, p_end, - error_buf, error_buf_size))) + p_org = p; + read_leb_uint32(p, p_end, depth); + if (loader_ctx->csp_num < depth + 1) { + set_error_buf(error_buf, error_buf_size, + "unknown label, " + "unexpected end of section or function"); goto fail; - - if (i == 0) { - if (frame_csp_tmp->label_type != LABEL_TYPE_LOOP) - ret_count = block_type_get_result_types( - &frame_csp_tmp->block_type, &ret_types); - else - ret_count = block_type_get_param_types( - &frame_csp_tmp->block_type, &ret_types); } - else { - uint8 *tmp_ret_types = NULL; - uint32 tmp_ret_count = 0; + p = p_org; - /* Check whether all table items have the same return - * type */ - if (frame_csp_tmp->label_type != LABEL_TYPE_LOOP) - tmp_ret_count = block_type_get_result_types( - &frame_csp_tmp->block_type, &tmp_ret_types); - else - tmp_ret_count = block_type_get_param_types( - &frame_csp_tmp->block_type, &tmp_ret_types); + /* Get the target block's arity and check it */ + target_block = loader_ctx->frame_csp - (depth + 1); + target_block_type = &target_block->block_type; + arity = block_type_get_arity(target_block_type, + target_block->label_type); + if (arity != default_arity) { + set_error_buf(error_buf, error_buf_size, + "type mismatch: br_table targets must " + "all use same result type"); + goto fail; + } - if (ret_count != tmp_ret_count - || (ret_count - && 0 - != memcmp(ret_types, tmp_ret_types, - ret_count))) { - set_error_buf( - error_buf, error_buf_size, - "type mismatch: br_table targets must " - "all use same result type"); - goto fail; - } + if (!(frame_csp_tmp = + check_branch_block(loader_ctx, &p, p_end, true, + error_buf, error_buf_size))) { + goto fail; } #if WASM_ENABLE_FAST_INTERP == 0 - depth = (uint32)(loader_ctx->frame_csp - 1 - frame_csp_tmp); if (br_table_cache) { br_table_cache->br_depths[i] = depth; } @@ -8201,7 +11486,7 @@ re_scan: /* The depth cannot be stored in one byte, create br_table cache to store each depth */ #if WASM_ENABLE_DEBUG_INTERP != 0 - if (!record_fast_op(module, p_org, *p_org, + if (!record_fast_op(module, p_opcode, *p_opcode, error_buf, error_buf_size)) { goto fail; } @@ -8213,8 +11498,8 @@ re_scan: error_buf, error_buf_size))) { goto fail; } - *p_org = EXT_OP_BR_TABLE_CACHE; - br_table_cache->br_table_op_addr = p_org; + *p_opcode = EXT_OP_BR_TABLE_CACHE; + br_table_cache->br_table_op_addr = p_opcode; br_table_cache->br_count = count; /* Copy previous depths which are one byte */ for (j = 0; j < i; j++) { @@ -8270,34 +11555,91 @@ re_scan: case WASM_OP_CALL: #if WASM_ENABLE_TAIL_CALL != 0 case WASM_OP_RETURN_CALL: +#endif +#if WASM_ENABLE_GC != 0 + case WASM_OP_CALL_REF: + case WASM_OP_RETURN_CALL_REF: #endif { - WASMType *func_type; + WASMFuncType *func_type; + uint8 type; int32 idx; - - read_leb_uint32(p, p_end, func_idx); -#if WASM_ENABLE_FAST_INTERP != 0 - /* we need to emit func_idx before arguments */ - emit_uint32(loader_ctx, func_idx); +#if WASM_ENABLE_GC != 0 + WASMRefType *ref_type; + uint32 type_idx1; + int32 j; #endif - if (!check_function_index(module, func_idx, error_buf, +#if WASM_ENABLE_GC != 0 + if (opcode == WASM_OP_CALL_REF + || opcode == WASM_OP_RETURN_CALL_REF) { + read_leb_uint32(p, p_end, type_idx1); + if (!wasm_loader_pop_nullable_typeidx(loader_ctx, &type, + &type_idx, error_buf, + error_buf_size)) { + goto fail; + } + if (type == VALUE_TYPE_ANY) { + type_idx = type_idx1; + } + if (!check_type_index(module, type_idx, error_buf, error_buf_size)) { - goto fail; + goto fail; + } + if (module->types[type_idx]->type_flag != WASM_TYPE_FUNC) { + set_error_buf(error_buf, error_buf_size, + "unkown function type"); + goto fail; + } + if (type_idx != type_idx1) { + set_error_buf(error_buf, error_buf_size, + "function type mismatch"); + goto fail; + } + func_type = (WASMFuncType *)module->types[type_idx]; + } + else +#endif + { + read_leb_uint32(p, p_end, func_idx); +#if WASM_ENABLE_FAST_INTERP != 0 + /* we need to emit func_idx before arguments */ + emit_uint32(loader_ctx, func_idx); +#endif + + if (!check_function_index(module, func_idx, error_buf, + error_buf_size)) { + goto fail; + } + + if (func_idx < module->import_function_count) + func_type = module->import_functions[func_idx] + .u.function.func_type; + else + func_type = + module + ->functions[func_idx + - module->import_function_count] + ->func_type; } - if (func_idx < module->import_function_count) - func_type = - module->import_functions[func_idx].u.function.func_type; - else - func_type = module - ->functions[func_idx - - module->import_function_count] - ->func_type; - if (func_type->param_count > 0) { +#if WASM_ENABLE_GC != 0 + j = (int32)(func_type->result_ref_type_maps + - func_type->ref_type_maps - 1); +#endif for (idx = (int32)(func_type->param_count - 1); idx >= 0; idx--) { +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_multi_byte_type( + func_type->types[idx])) { + ref_type = func_type->ref_type_maps[j].ref_type; + bh_memcpy_s(&wasm_ref_type, sizeof(WASMRefType), + ref_type, + wasm_reftype_struct_size(ref_type)); + j--; + } +#endif #if WASM_ENABLE_FAST_INTERP != 0 POP_OFFSET_TYPE(func_type->types[idx]); #endif @@ -8305,10 +11647,24 @@ re_scan: } } -#if WASM_ENABLE_TAIL_CALL != 0 - if (opcode == WASM_OP_CALL) { +#if WASM_ENABLE_TAIL_CALL != 0 || WASM_ENABLE_GC != 0 + if (opcode == WASM_OP_CALL || opcode == WASM_OP_CALL_REF) { +#endif +#if WASM_ENABLE_GC != 0 + j = (int32)(func_type->result_ref_type_maps + - func_type->ref_type_maps); #endif for (i = 0; i < func_type->result_count; i++) { +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_multi_byte_type( + func_type->types[func_type->param_count + i])) { + ref_type = func_type->ref_type_maps[j].ref_type; + bh_memcpy_s(&wasm_ref_type, sizeof(WASMRefType), + ref_type, + wasm_reftype_struct_size(ref_type)); + j++; + } +#endif PUSH_TYPE(func_type->types[func_type->param_count + i]); #if WASM_ENABLE_FAST_INTERP != 0 /* Here we emit each return value's dynamic_offset. But @@ -8319,10 +11675,10 @@ re_scan: func_type->types[func_type->param_count + i]); #endif } -#if WASM_ENABLE_TAIL_CALL != 0 +#if WASM_ENABLE_TAIL_CALL != 0 || WASM_ENABLE_GC != 0 } else { - uint8 type; +#if WASM_ENABLE_GC == 0 if (func_type->result_count != func->func_type->result_count) { set_error_buf_v(error_buf, error_buf_size, "%s%u%s", @@ -8342,14 +11698,26 @@ re_scan: goto fail; } } +#else + if (!wasm_func_type_result_is_subtype_of( + func_type, func->func_type, module->types, + module->type_count)) { + set_error_buf( + error_buf, error_buf_size, + "type mismatch: invalid func result types"); + goto fail; + } +#endif RESET_STACK(); SET_CUR_BLOCK_STACK_POLYMORPHIC_STATE(true); } #endif + #if WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0 \ || WASM_ENABLE_WAMR_COMPILER != 0 func->has_op_func_call = true; #endif + (void)type; break; } @@ -8363,10 +11731,10 @@ re_scan: #endif { int32 idx; - WASMType *func_type; + WASMFuncType *func_type; read_leb_uint32(p, p_end, type_idx); -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 read_leb_uint32(p, p_end, table_idx); #else CHECK_BUF(p, p_end, 1); @@ -8394,7 +11762,7 @@ re_scan: goto fail; } - func_type = module->types[type_idx]; + func_type = (WASMFuncType *)module->types[type_idx]; if (func_type->param_count > 0) { for (idx = (int32)(func_type->param_count - 1); idx >= 0; @@ -8469,6 +11837,16 @@ re_scan: } if (available_stack_cell > 0) { +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_multi_byte_type( + *(loader_ctx->frame_ref - 1))) { + bh_assert((int32)(loader_ctx->reftype_map_num + - cur_block->reftype_map_num) + > 0); + loader_ctx->frame_reftype_map--; + loader_ctx->reftype_map_num--; + } +#endif if (is_32bit_type(*(loader_ctx->frame_ref - 1)) || *(loader_ctx->frame_ref - 1) == VALUE_TYPE_ANY) { loader_ctx->frame_ref--; @@ -8501,7 +11879,7 @@ re_scan: } #if WASM_ENABLE_SIMD != 0 #if (WASM_ENABLE_WAMR_COMPILER != 0) || (WASM_ENABLE_JIT != 0) - else if (*(loader_ctx->frame_ref - 1) == REF_V128_1) { + else if (*(loader_ctx->frame_ref - 1) == VALUE_TYPE_V128) { loader_ctx->frame_ref -= 4; loader_ctx->stack_cell_num -= 4; } @@ -8546,11 +11924,11 @@ re_scan: if (available_stack_cell > 0) { switch (*(loader_ctx->frame_ref - 1)) { - case REF_I32: - case REF_F32: + case VALUE_TYPE_I32: + case VALUE_TYPE_F32: break; - case REF_I64_2: - case REF_F64_2: + case VALUE_TYPE_I64: + case VALUE_TYPE_F64: #if WASM_ENABLE_FAST_INTERP == 0 *(p - 1) = WASM_OP_SELECT_64; #endif @@ -8590,7 +11968,7 @@ re_scan: break; #if WASM_ENABLE_SIMD != 0 #if (WASM_ENABLE_WAMR_COMPILER != 0) || (WASM_ENABLE_JIT != 0) - case REF_V128_4: + case VALUE_TYPE_V128: break; #endif /* (WASM_ENABLE_WAMR_COMPILER != 0) || (WASM_ENABLE_JIT != 0) */ #endif /* WASM_ENABLE_SIMD != 0 */ @@ -8623,10 +12001,13 @@ re_scan: break; } -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 case WASM_OP_SELECT_T: { - uint8 vec_len, ref_type; + uint8 vec_len, type; +#if WASM_ENABLE_GC != 0 + WASMRefType *ref_type = NULL; +#endif #if WASM_ENABLE_FAST_INTERP != 0 uint8 *p_code_compiled_tmp = loader_ctx->p_code_compiled; #endif @@ -8639,13 +12020,42 @@ re_scan: goto fail; } +#if WASM_ENABLE_GC == 0 CHECK_BUF(p, p_end, 1); - ref_type = read_uint8(p); - if (!is_value_type(ref_type)) { + type = read_uint8(p); + if (!is_value_type(type)) { set_error_buf(error_buf, error_buf_size, "unknown value type"); goto fail; } +#else + p_org = p + 1; + if (!resolve_value_type((const uint8 **)&p, p_end, module, + &need_ref_type_map, &wasm_ref_type, + false, error_buf, error_buf_size)) { + goto fail; + } + type = wasm_ref_type.ref_type; + if (need_ref_type_map) { + if (!(ref_type = reftype_set_insert( + module->ref_type_set, &wasm_ref_type, error_buf, + error_buf_size))) { + goto fail; + } + } +#if WASM_ENABLE_FAST_INTERP == 0 + while (p_org < p) { +#if WASM_ENABLE_DEBUG_INTERP != 0 + if (!record_fast_op(module, p_org, *p_org, error_buf, + error_buf_size)) { + goto fail; + } +#endif + /* Ignore extra bytes for interpreter */ + *p_org++ = WASM_OP_NOP; + } +#endif +#endif /* end of WASM_ENABLE_GC == 0 */ POP_I32(); @@ -8653,7 +12063,7 @@ re_scan: if (loader_ctx->p_code_compiled) { uint8 opcode_tmp = WASM_OP_SELECT; - if (ref_type == VALUE_TYPE_V128) { + if (type == VALUE_TYPE_V128) { #if (WASM_ENABLE_SIMD == 0) \ || ((WASM_ENABLE_WAMR_COMPILER == 0) && (WASM_ENABLE_JIT == 0)) set_error_buf(error_buf, error_buf_size, @@ -8662,9 +12072,12 @@ re_scan: #endif } else { - if (ref_type == VALUE_TYPE_F64 - || ref_type == VALUE_TYPE_I64) + if (type == VALUE_TYPE_F64 || type == VALUE_TYPE_I64) opcode_tmp = WASM_OP_SELECT_64; +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_reftype(type)) + opcode_tmp = WASM_OP_SELECT_T; +#endif #if WASM_ENABLE_LABELS_AS_VALUES != 0 #if WASM_CPU_SUPPORTS_UNALIGNED_ADDR_ACCESS != 0 *(void **)(p_code_compiled_tmp - sizeof(void *)) = @@ -8693,17 +12106,27 @@ re_scan: } #endif /* WASM_ENABLE_FAST_INTERP != 0 */ -#if WASM_ENABLE_FAST_INTERP != 0 - POP_OFFSET_TYPE(ref_type); - POP_TYPE(ref_type); - POP_OFFSET_TYPE(ref_type); - POP_TYPE(ref_type); - PUSH_OFFSET_TYPE(ref_type); - PUSH_TYPE(ref_type); -#else - POP2_AND_PUSH(ref_type, ref_type); -#endif /* WASM_ENABLE_FAST_INTERP != 0 */ + POP_REF(type); +#if WASM_ENABLE_GC != 0 + if (need_ref_type_map) { + bh_memcpy_s(&wasm_ref_type, sizeof(WASMRefType), ref_type, + wasm_reftype_struct_size(ref_type)); + } +#endif + POP_REF(type); + +#if WASM_ENABLE_GC != 0 + if (need_ref_type_map) { + bh_memcpy_s(&wasm_ref_type, sizeof(WASMRefType), ref_type, + wasm_reftype_struct_size(ref_type)); + } +#endif + PUSH_REF(type); + +#if WASM_ENABLE_WAMR_COMPILER != 0 + module->is_ref_types_used = true; +#endif (void)vec_len; break; } @@ -8714,12 +12137,28 @@ re_scan: case WASM_OP_TABLE_SET: { uint8 decl_ref_type; +#if WASM_ENABLE_GC != 0 + WASMRefType *ref_type; +#endif read_leb_uint32(p, p_end, table_idx); if (!get_table_elem_type(module, table_idx, &decl_ref_type, +#if WASM_ENABLE_GC != 0 + (void **)&ref_type, +#else + NULL, +#endif error_buf, error_buf_size)) goto fail; +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_multi_byte_type(decl_ref_type)) { + bh_assert(ref_type); + bh_memcpy_s(&wasm_ref_type, (uint32)sizeof(WASMRefType), + ref_type, wasm_reftype_struct_size(ref_type)); + } +#endif + #if WASM_ENABLE_FAST_INTERP != 0 emit_uint32(loader_ctx, table_idx); #endif @@ -8738,28 +12177,59 @@ re_scan: POP_TYPE(decl_ref_type); POP_I32(); } + +#if WASM_ENABLE_WAMR_COMPILER != 0 + module->is_ref_types_used = true; +#endif break; } case WASM_OP_REF_NULL: { uint8 ref_type; +#if WASM_ENABLE_GC == 0 CHECK_BUF(p, p_end, 1); ref_type = read_uint8(p); + if (ref_type != VALUE_TYPE_FUNCREF && ref_type != VALUE_TYPE_EXTERNREF) { - set_error_buf(error_buf, error_buf_size, - "unknown value type"); + set_error_buf(error_buf, error_buf_size, "type mismatch"); goto fail; } +#else + read_leb_int32(p, p_end, heap_type); + if (heap_type >= 0) { + if (!check_type_index(module, heap_type, error_buf, + error_buf_size)) { + goto fail; + } + wasm_set_refheaptype_typeidx(&wasm_ref_type.ref_ht_typeidx, + true, heap_type); + ref_type = wasm_ref_type.ref_type; + } + else { + if (!wasm_is_valid_heap_type(heap_type)) { + set_error_buf(error_buf, error_buf_size, + "unknown type"); + goto fail; + } + ref_type = (uint8)((int32)0x80 + heap_type); + } +#endif /* end of WASM_ENABLE_GC == 0 */ + #if WASM_ENABLE_FAST_INTERP != 0 PUSH_OFFSET_TYPE(ref_type); #endif PUSH_TYPE(ref_type); + +#if WASM_ENABLE_WAMR_COMPILER != 0 + module->is_ref_types_used = true; +#endif break; } case WASM_OP_REF_IS_NULL: { +#if WASM_ENABLE_GC == 0 #if WASM_ENABLE_FAST_INTERP != 0 BranchBlock *cur_block = loader_ctx->frame_csp - 1; int32 block_stack_cell_num = @@ -8797,8 +12267,19 @@ re_scan: error_buf, error_buf_size)) { goto fail; } +#endif +#else /* else of WASM_ENABLE_GC == 0 */ + uint8 type; + if (!wasm_loader_pop_heap_obj(loader_ctx, &type, &wasm_ref_type, + error_buf, error_buf_size)) { + goto fail; + } #endif PUSH_I32(); + +#if WASM_ENABLE_WAMR_COMPILER != 0 + module->is_ref_types_used = true; +#endif break; } case WASM_OP_REF_FUNC: @@ -8821,8 +12302,9 @@ re_scan: is passive, active or declarative. */ for (i = 0; i < module->table_seg_count; i++, table_seg++) { if (table_seg->elem_type == VALUE_TYPE_FUNCREF) { - for (j = 0; j < table_seg->function_count; j++) { - if (table_seg->func_indexes[j] == func_idx) { + for (j = 0; j < table_seg->value_count; j++) { + if (table_seg->init_values[j].u.ref_index + == func_idx) { func_declared = true; break; } @@ -8850,10 +12332,112 @@ re_scan: #if WASM_ENABLE_FAST_INTERP != 0 emit_uint32(loader_ctx, func_idx); #endif +#if WASM_ENABLE_GC == 0 PUSH_FUNCREF(); +#else + if (func_idx < module->import_function_count) + type_idx = + module->import_functions[func_idx].u.function.type_idx; + else + type_idx = module + ->functions[func_idx + - module->import_function_count] + ->type_idx; + wasm_set_refheaptype_typeidx(&wasm_ref_type.ref_ht_typeidx, + false, type_idx); + PUSH_REF(wasm_ref_type.ref_type); +#endif + +#if WASM_ENABLE_WAMR_COMPILER != 0 + module->is_ref_types_used = true; +#endif break; } -#endif /* WASM_ENABLE_REF_TYPES */ +#endif /* end of WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */ + +#if WASM_ENABLE_GC != 0 + case WASM_OP_REF_AS_NON_NULL: + case WASM_OP_BR_ON_NULL: + { + uint8 type; + WASMRefType ref_type; + + /* POP (ref null ht) and get the converted (ref ht) */ + if (!wasm_loader_pop_nullable_ht(loader_ctx, &type, &ref_type, + error_buf, error_buf_size)) { + goto fail; + } + + if (opcode == WASM_OP_BR_ON_NULL) { + if (!(frame_csp_tmp = + check_branch_block(loader_ctx, &p, p_end, false, + error_buf, error_buf_size))) { + goto fail; + } +#if WASM_ENABLE_FAST_INTERP != 0 + disable_emit = true; +#endif + } + + /* PUSH the converted (ref ht) */ + if (type != VALUE_TYPE_ANY) { + bh_memcpy_s(&wasm_ref_type, sizeof(WASMRefType), &ref_type, + sizeof(WASMRefType)); + } + PUSH_REF(type); + break; + } + + case WASM_OP_BR_ON_NON_NULL: + { + uint8 type; + WASMRefType ref_type; + uint32 available_stack_cell = + loader_ctx->stack_cell_num + - (loader_ctx->frame_csp - 1)->stack_cell_num; + + /* POP (ref null ht) and get the converted (ref ht) */ + if (!wasm_loader_pop_nullable_ht(loader_ctx, &type, &ref_type, + error_buf, error_buf_size)) { + goto fail; + } + +#if WASM_ENABLE_FAST_INTERP != 0 + disable_emit = true; +#endif + + /* Temporarily PUSH back (ref ht), check brach block and + then POP it */ + if (available_stack_cell + > 0) { /* stack isn't in polymorphic state */ + if (type != VALUE_TYPE_ANY) { + bh_memcpy_s(&wasm_ref_type, sizeof(WASMRefType), + &ref_type, sizeof(WASMRefType)); + } + PUSH_REF(type); + } + if (!(frame_csp_tmp = + check_branch_block(loader_ctx, &p, p_end, false, + error_buf, error_buf_size))) { + goto fail; + } + if (available_stack_cell + > 0) { /* stack isn't in polymorphic state */ + POP_REF(type); +#if WASM_ENABLE_FAST_INTERP != 0 + /* Erase the opnd offset emitted by POP_REF() */ + wasm_loader_emit_backspace(loader_ctx, sizeof(uint16)); +#endif + } + break; + } + + case WASM_OP_REF_EQ: + POP_REF(REF_TYPE_EQREF); + POP_REF(REF_TYPE_EQREF); + PUSH_I32(); + break; +#endif /* end of WASM_ENABLE_GC != 0 */ case WASM_OP_GET_LOCAL: { @@ -8861,6 +12445,18 @@ re_scan: GET_LOCAL_INDEX_TYPE_AND_OFFSET(); PUSH_TYPE(local_type); +#if WASM_ENABLE_GC != 0 + /* Cannot get a non-nullable and unset local */ + if (local_idx >= param_count + && wasm_is_reftype_htref_non_nullable(local_type) + && !wasm_loader_get_local_status(loader_ctx, + local_idx - param_count)) { + set_error_buf(error_buf, error_buf_size, + "uninitialized local"); + goto fail; + } +#endif + #if WASM_ENABLE_FAST_INTERP != 0 /* Get Local is optimized out */ skip_label(); @@ -8870,7 +12466,11 @@ re_scan: #else #if (WASM_ENABLE_WAMR_COMPILER == 0) && (WASM_ENABLE_JIT == 0) \ && (WASM_ENABLE_FAST_JIT == 0) && (WASM_ENABLE_DEBUG_INTERP == 0) - if (local_offset < 0x80) { + if (local_offset < 0x80 +#if WASM_ENABLE_GC != 0 + && !wasm_is_type_reftype(local_type) +#endif + ) { *p_org++ = EXT_OP_GET_LOCAL_FAST; if (is_32bit_type(local_type)) { *p_org++ = (uint8)local_offset; @@ -8891,7 +12491,6 @@ re_scan: { p_org = p - 1; GET_LOCAL_INDEX_TYPE_AND_OFFSET(); - POP_TYPE(local_type); #if WASM_ENABLE_FAST_INTERP != 0 if (!(preserve_referenced_local( @@ -8899,7 +12498,11 @@ re_scan: &preserve_local, error_buf, error_buf_size))) goto fail; - if (local_offset < 256) { + if (local_offset < 256 +#if WASM_ENABLE_GC != 0 + && !wasm_is_type_reftype(local_type) +#endif + ) { skip_label(); if ((!preserve_local) && (LAST_OP_OUTPUT_I32())) { if (loader_ctx->p_code_compiled) @@ -8934,7 +12537,11 @@ re_scan: #else #if (WASM_ENABLE_WAMR_COMPILER == 0) && (WASM_ENABLE_JIT == 0) \ && (WASM_ENABLE_FAST_JIT == 0) && (WASM_ENABLE_DEBUG_INTERP == 0) - if (local_offset < 0x80) { + if (local_offset < 0x80 +#if WASM_ENABLE_GC != 0 + && !wasm_is_type_reftype(local_type) +#endif + ) { *p_org++ = EXT_OP_SET_LOCAL_FAST; if (is_32bit_type(local_type)) { *p_org++ = (uint8)local_offset; @@ -8948,6 +12555,14 @@ re_scan: } #endif #endif /* end of WASM_ENABLE_FAST_INTERP != 0 */ + +#if WASM_ENABLE_GC != 0 + if (local_idx >= param_count) { + wasm_loader_mask_local(loader_ctx, local_idx - param_count); + } +#endif + + POP_TYPE(local_type); break; } @@ -8974,7 +12589,11 @@ re_scan: &preserve_local, error_buf, error_buf_size))) goto fail; - if (local_offset < 256) { + if (local_offset < 256 +#if WASM_ENABLE_GC != 0 + && !wasm_is_type_reftype(local_type) +#endif + ) { skip_label(); if (is_32bit_type(local_type)) { emit_label(EXT_OP_TEE_LOCAL_FAST); @@ -8994,7 +12613,11 @@ re_scan: #else #if (WASM_ENABLE_WAMR_COMPILER == 0) && (WASM_ENABLE_JIT == 0) \ && (WASM_ENABLE_FAST_JIT == 0) && (WASM_ENABLE_DEBUG_INTERP == 0) - if (local_offset < 0x80) { + if (local_offset < 0x80 +#if WASM_ENABLE_GC != 0 + && !wasm_is_type_reftype(local_type) +#endif + ) { *p_org++ = EXT_OP_TEE_LOCAL_FAST; if (is_32bit_type(local_type)) { *p_org++ = (uint8)local_offset; @@ -9008,11 +12631,21 @@ re_scan: } #endif #endif /* end of WASM_ENABLE_FAST_INTERP != 0 */ + +#if WASM_ENABLE_GC != 0 + if (local_idx >= param_count) { + wasm_loader_mask_local(loader_ctx, local_idx - param_count); + } +#endif break; } case WASM_OP_GET_GLOBAL: { +#if WASM_ENABLE_GC != 0 + WASMRefType *ref_type; +#endif + p_org = p - 1; read_leb_uint32(p, p_end, global_idx); if (global_idx >= global_count) { @@ -9027,6 +12660,19 @@ re_scan: ->globals[global_idx - module->import_global_count] .type; +#if WASM_ENABLE_GC != 0 + ref_type = + global_idx < module->import_global_count + ? module->import_globals[global_idx].u.global.ref_type + : module + ->globals[global_idx + - module->import_global_count] + .ref_type; + if (wasm_is_type_multi_byte_type(global_type)) { + bh_memcpy_s(&wasm_ref_type, sizeof(WASMRefType), ref_type, + wasm_reftype_struct_size(ref_type)); + } +#endif PUSH_TYPE(global_type); @@ -9056,6 +12702,9 @@ re_scan: case WASM_OP_SET_GLOBAL: { bool is_mutable = false; +#if WASM_ENABLE_GC != 0 + WASMRefType *ref_type; +#endif p_org = p - 1; read_leb_uint32(p, p_end, global_idx); @@ -9072,8 +12721,13 @@ re_scan: - module->import_global_count] .is_mutable; if (!is_mutable) { +#if WASM_ENABLE_GC == 0 set_error_buf(error_buf, error_buf_size, "global is immutable"); +#else + set_error_buf(error_buf, error_buf_size, + "immutable global"); +#endif goto fail; } @@ -9084,6 +12738,19 @@ re_scan: ->globals[global_idx - module->import_global_count] .type; +#if WASM_ENABLE_GC != 0 + ref_type = + global_idx < module->import_global_count + ? module->import_globals[global_idx].u.global.ref_type + : module + ->globals[global_idx + - module->import_global_count] + .ref_type; + if (wasm_is_type_multi_byte_type(global_type)) { + bh_memcpy_s(&wasm_ref_type, sizeof(WASMRefType), ref_type, + wasm_reftype_struct_size(ref_type)); + } +#endif #if WASM_ENABLE_FAST_INTERP == 0 if (global_type == VALUE_TYPE_I64 @@ -9570,6 +13237,1009 @@ re_scan: POP_AND_PUSH(VALUE_TYPE_I64, VALUE_TYPE_I64); break; +#if WASM_ENABLE_GC != 0 + case WASM_OP_GC_PREFIX: + { + uint32 opcode1; + + read_leb_uint32(p, p_end, opcode1); +#if WASM_ENABLE_FAST_INTERP != 0 + emit_byte(loader_ctx, ((uint8)opcode1)); +#endif + + switch (opcode1) { + case WASM_OP_STRUCT_NEW: + case WASM_OP_STRUCT_NEW_DEFAULT: + { + read_leb_uint32(p, p_end, type_idx); +#if WASM_ENABLE_FAST_INTERP != 0 + emit_uint32(loader_ctx, type_idx); +#endif + if (!check_type_index(module, type_idx, error_buf, + error_buf_size)) { + goto fail; + } + if (module->types[type_idx]->type_flag + != WASM_TYPE_STRUCT) { + set_error_buf(error_buf, error_buf_size, + "unkown struct type"); + goto fail; + } + + if (opcode1 == WASM_OP_STRUCT_NEW) { + int32 j, k; + uint8 value_type; + uint32 ref_type_struct_size; + WASMStructType *struct_type = + (WASMStructType *)module->types[type_idx]; + + k = struct_type->ref_type_map_count - 1; + for (j = struct_type->field_count - 1; j >= 0; + j--) { + value_type = struct_type->fields[j].field_type; + if (wasm_is_type_reftype(value_type)) { + if (wasm_is_type_multi_byte_type( + value_type)) { + ref_type_struct_size = + wasm_reftype_struct_size( + struct_type->ref_type_maps[k] + .ref_type); + bh_memcpy_s( + &wasm_ref_type, + (uint32)sizeof(WASMRefType), + struct_type->ref_type_maps[k] + .ref_type, + ref_type_struct_size); + k--; + } + POP_REF(value_type); + } + else { + switch (value_type) { + case VALUE_TYPE_I32: + case PACKED_TYPE_I8: + case PACKED_TYPE_I16: + POP_I32(); + break; + case VALUE_TYPE_I64: + POP_I64(); + break; + case VALUE_TYPE_F32: + POP_F32(); + break; + case VALUE_TYPE_F64: + POP_F64(); + break; + default: + set_error_buf(error_buf, + error_buf_size, + "unknown type"); + goto fail; + } + } + } + } + + /* PUSH struct obj, (ref $t) */ + wasm_set_refheaptype_typeidx( + &wasm_ref_type.ref_ht_typeidx, false, type_idx); + PUSH_REF(wasm_ref_type.ref_type); + break; + } + + case WASM_OP_STRUCT_GET: + case WASM_OP_STRUCT_GET_S: + case WASM_OP_STRUCT_GET_U: + case WASM_OP_STRUCT_SET: + { + WASMStructType *struct_type; + WASMRefType *ref_type = NULL; + uint32 field_idx; + uint8 field_type; + + read_leb_uint32(p, p_end, type_idx); +#if WASM_ENABLE_FAST_INTERP != 0 + emit_uint32(loader_ctx, type_idx); +#endif + if (!check_type_index(module, type_idx, error_buf, + error_buf_size)) { + goto fail; + } + if (module->types[type_idx]->type_flag + != WASM_TYPE_STRUCT) { + set_error_buf(error_buf, error_buf_size, + "unknown struct type"); + goto fail; + } + struct_type = (WASMStructType *)module->types[type_idx]; + + read_leb_uint32(p, p_end, field_idx); +#if WASM_ENABLE_FAST_INTERP != 0 + emit_uint32(loader_ctx, field_idx); +#endif + if (field_idx >= struct_type->field_count) { + set_error_buf(error_buf, error_buf_size, + "unknown struct field"); + goto fail; + } + + if (opcode1 == WASM_OP_STRUCT_SET + && !(struct_type->fields[field_idx].field_flags + & 1)) { + set_error_buf(error_buf, error_buf_size, + "field is immutable"); + goto fail; + } + + field_type = struct_type->fields[field_idx].field_type; + if (is_packed_type(field_type)) { + if (opcode1 == WASM_OP_STRUCT_GET) { + set_error_buf(error_buf, error_buf_size, + "type mismatch"); + goto fail; + } + else { + field_type = VALUE_TYPE_I32; + } + } + if (wasm_is_type_multi_byte_type(field_type)) { + ref_type = wasm_reftype_map_find( + struct_type->ref_type_maps, + struct_type->ref_type_map_count, field_idx); + bh_assert(ref_type); + } + if (opcode1 == WASM_OP_STRUCT_SET) { + /* POP field */ + if (wasm_is_type_multi_byte_type(field_type)) { + bh_memcpy_s(&wasm_ref_type, + (uint32)sizeof(WASMRefType), + ref_type, + wasm_reftype_struct_size(ref_type)); + } + POP_REF(field_type); + /* POP struct obj, (ref null $t) */ + wasm_set_refheaptype_typeidx( + &wasm_ref_type.ref_ht_typeidx, true, type_idx); + POP_REF(wasm_ref_type.ref_type); + } + else { + /* POP struct obj, (ref null $t) */ + wasm_set_refheaptype_typeidx( + &wasm_ref_type.ref_ht_typeidx, true, type_idx); + POP_REF(wasm_ref_type.ref_type); + /* PUSH field */ + if (wasm_is_type_multi_byte_type(field_type)) { + bh_memcpy_s(&wasm_ref_type, + (uint32)sizeof(WASMRefType), + ref_type, + wasm_reftype_struct_size(ref_type)); + } + PUSH_REF(field_type); + } + break; + } + + case WASM_OP_ARRAY_NEW: + case WASM_OP_ARRAY_NEW_DEFAULT: + case WASM_OP_ARRAY_NEW_FIXED: + case WASM_OP_ARRAY_NEW_DATA: + case WASM_OP_ARRAY_NEW_ELEM: + { + WASMArrayType *array_type; + uint8 elem_type; + uint32 u32 = 0; + + read_leb_uint32(p, p_end, type_idx); +#if WASM_ENABLE_FAST_INTERP != 0 + emit_uint32(loader_ctx, type_idx); +#endif + if (opcode1 == WASM_OP_ARRAY_NEW_FIXED + || opcode1 == WASM_OP_ARRAY_NEW_DATA + || opcode1 == WASM_OP_ARRAY_NEW_ELEM) { + read_leb_uint32(p, p_end, u32); +#if WASM_ENABLE_FAST_INTERP != 0 + emit_uint32(loader_ctx, u32); +#endif + } + + if (!check_array_type(module, type_idx, error_buf, + error_buf_size)) { + goto fail; + } + + if (opcode1 != WASM_OP_ARRAY_NEW_FIXED) { + /* length */ + POP_I32(); + } + + array_type = (WASMArrayType *)module->types[type_idx]; + elem_type = array_type->elem_type; + + if (opcode1 == WASM_OP_ARRAY_NEW + || opcode1 == WASM_OP_ARRAY_NEW_FIXED) { + if (wasm_is_type_multi_byte_type(elem_type)) { + bh_memcpy_s(&wasm_ref_type, sizeof(WASMRefType), + array_type->elem_ref_type, + wasm_reftype_struct_size( + array_type->elem_ref_type)); + } + if (is_packed_type(elem_type)) { + elem_type = VALUE_TYPE_I32; + } + + if (opcode1 == WASM_OP_ARRAY_NEW_FIXED) { + uint32 N = u32; + for (i = 0; i < N; i++) { + if (wasm_is_type_multi_byte_type( + elem_type)) { + bh_memcpy_s( + &wasm_ref_type, sizeof(WASMRefType), + array_type->elem_ref_type, + wasm_reftype_struct_size( + array_type->elem_ref_type)); + } + POP_REF(elem_type); + } + } + else + POP_REF(elem_type); + } + else if (opcode1 == WASM_OP_ARRAY_NEW_DATA) { + /* offset of data segment */ + POP_I32(); + + if (u32 >= module->data_seg_count) { + set_error_buf(error_buf, error_buf_size, + "unknown data segement"); + goto fail; + } + + if (wasm_is_type_reftype(elem_type)) { + set_error_buf(error_buf, error_buf_size, + "array elem type mismatch"); + goto fail; + } + } + else if (opcode1 == WASM_OP_ARRAY_NEW_ELEM) { + WASMTableSeg *table_seg = + module->table_segments + u32; + + /* offset of element segment */ + POP_I32(); + + if (u32 >= module->table_seg_count) { + set_error_buf(error_buf, error_buf_size, + "unknown element segement"); + goto fail; + } + if (!wasm_reftype_is_subtype_of( + table_seg->elem_type, + table_seg->elem_ref_type, elem_type, + array_type->elem_ref_type, module->types, + module->type_count)) { + set_error_buf(error_buf, error_buf_size, + "array elem type mismatch"); + goto fail; + } + } + + /* PUSH array obj, (ref $t) */ + wasm_set_refheaptype_typeidx( + &wasm_ref_type.ref_ht_typeidx, false, type_idx); + PUSH_REF(wasm_ref_type.ref_type); + break; + } + + case WASM_OP_ARRAY_GET: + case WASM_OP_ARRAY_GET_S: + case WASM_OP_ARRAY_GET_U: + case WASM_OP_ARRAY_SET: + { + uint8 elem_type; + WASMArrayType *array_type; + WASMRefType *ref_type = NULL; + + read_leb_uint32(p, p_end, type_idx); +#if WASM_ENABLE_FAST_INTERP != 0 + emit_uint32(loader_ctx, type_idx); +#endif + if (!check_array_type(module, type_idx, error_buf, + error_buf_size)) { + goto fail; + } + array_type = (WASMArrayType *)module->types[type_idx]; + + if (opcode1 == WASM_OP_ARRAY_SET + && !(array_type->elem_flags & 1)) { + set_error_buf(error_buf, error_buf_size, + "array is immutable"); + goto fail; + } + + elem_type = array_type->elem_type; + if (is_packed_type(elem_type)) { + if (opcode1 != WASM_OP_ARRAY_GET_S + && opcode1 != WASM_OP_ARRAY_GET_U + && opcode1 != WASM_OP_ARRAY_SET) { + set_error_buf(error_buf, error_buf_size, + "type mismatch"); + goto fail; + } + else { + elem_type = VALUE_TYPE_I32; + } + } + ref_type = array_type->elem_ref_type; + + if (opcode1 == WASM_OP_ARRAY_SET) { + /* POP elem to set */ + if (wasm_is_type_multi_byte_type(elem_type)) { + bh_memcpy_s(&wasm_ref_type, sizeof(WASMRefType), + ref_type, + wasm_reftype_struct_size(ref_type)); + } + POP_REF(elem_type); + } + /* elem idx */ + POP_I32(); + /* POP array obj, (ref null $t) */ + wasm_set_refheaptype_typeidx( + &wasm_ref_type.ref_ht_typeidx, true, type_idx); + POP_REF(wasm_ref_type.ref_type); + if (opcode1 != WASM_OP_ARRAY_SET) { + /* PUSH elem */ + if (wasm_is_type_multi_byte_type(elem_type)) { + bh_memcpy_s(&wasm_ref_type, sizeof(WASMRefType), + ref_type, + wasm_reftype_struct_size(ref_type)); + } + PUSH_REF(elem_type); + } + break; + } + + case WASM_OP_ARRAY_LEN: + { + POP_REF(REF_TYPE_ARRAYREF); + /* length */ + PUSH_I32(); + break; + } + + case WASM_OP_ARRAY_FILL: + { + WASMArrayType *array_type; + uint8 elem_type; + /* typeidx */ + read_leb_uint32(p, p_end, type_idx); +#if WASM_ENABLE_FAST_INTERP != 0 + emit_uint32(loader_ctx, type_idx); +#endif + if (!check_array_type(module, type_idx, error_buf, + error_buf_size)) { + goto fail; + } + + array_type = (WASMArrayType *)module->types[type_idx]; + if (!(array_type->elem_flags & 1)) { + set_error_buf(error_buf, error_buf_size, + "array is immutable"); + goto fail; + } + + elem_type = array_type->elem_type; + if (is_packed_type(elem_type)) { + elem_type = VALUE_TYPE_I32; + } + + POP_I32(); /* length */ +#if WASM_ENABLE_FAST_INTERP != 0 + POP_OFFSET_TYPE(elem_type); +#endif + POP_TYPE(elem_type); + POP_I32(); /* start */ + /* POP array obj, (ref null $t) */ + wasm_set_refheaptype_typeidx( + &wasm_ref_type.ref_ht_typeidx, true, type_idx); + POP_REF(wasm_ref_type.ref_type); + + break; + } + + case WASM_OP_ARRAY_COPY: + { + uint32 src_type_idx; + uint8 src_elem_type, dst_elem_type; + WASMRefType src_ref_type = { 0 }, + *src_elem_ref_type = NULL; + WASMRefType dst_ref_type = { 0 }, + *dst_elem_ref_type = NULL; + WASMArrayType *array_type; + + /* typeidx1 */ + read_leb_uint32(p, p_end, type_idx); +#if WASM_ENABLE_FAST_INTERP != 0 + emit_uint32(loader_ctx, type_idx); +#endif + /* typeidx2 */ + read_leb_uint32(p, p_end, src_type_idx); +#if WASM_ENABLE_FAST_INTERP != 0 + emit_uint32(loader_ctx, src_type_idx); +#endif + if (!check_array_type(module, type_idx, error_buf, + error_buf_size)) { + goto fail; + } + + if (!check_array_type(module, src_type_idx, error_buf, + error_buf_size)) { + goto fail; + } + + POP_I32(); + POP_I32(); + /* POP array obj, (ref null $t) */ + wasm_set_refheaptype_typeidx( + &wasm_ref_type.ref_ht_typeidx, true, src_type_idx); + POP_REF(wasm_ref_type.ref_type); + bh_memcpy_s(&src_ref_type, (uint32)sizeof(WASMRefType), + &wasm_ref_type, + wasm_reftype_struct_size(&wasm_ref_type)); + POP_I32(); + /* POP array obj, (ref null $t) */ + wasm_set_refheaptype_typeidx( + &wasm_ref_type.ref_ht_typeidx, true, type_idx); + POP_REF(wasm_ref_type.ref_type); + bh_memcpy_s(&dst_ref_type, (uint32)sizeof(WASMRefType), + &wasm_ref_type, + wasm_reftype_struct_size(&wasm_ref_type)); + + array_type = (WASMArrayType *)module->types[type_idx]; + if (!(array_type->elem_flags & 1)) { + set_error_buf(error_buf, error_buf_size, + "destination array is immutable"); + goto fail; + } + + dst_elem_type = array_type->elem_type; + if (wasm_is_type_multi_byte_type(dst_elem_type)) { + dst_elem_ref_type = array_type->elem_ref_type; + } + + array_type = + (WASMArrayType *)module->types[src_type_idx]; + src_elem_type = array_type->elem_type; + if (wasm_is_type_multi_byte_type(src_elem_type)) { + src_elem_ref_type = array_type->elem_ref_type; + } + + if (!wasm_reftype_is_subtype_of( + src_elem_type, src_elem_ref_type, dst_elem_type, + dst_elem_ref_type, module->types, + module->type_count)) { + set_error_buf(error_buf, error_buf_size, + "array types do not match"); + goto fail; + } + + break; + } + + case WASM_OP_REF_I31: + { + POP_I32(); + wasm_set_refheaptype_common( + &wasm_ref_type.ref_ht_common, false, HEAP_TYPE_I31); + PUSH_REF(wasm_ref_type.ref_type); + break; + } + + case WASM_OP_I31_GET_S: + case WASM_OP_I31_GET_U: + { + POP_REF(REF_TYPE_I31REF); + PUSH_I32(); + break; + } + + case WASM_OP_REF_TEST: + case WASM_OP_REF_CAST: + case WASM_OP_REF_TEST_NULLABLE: + case WASM_OP_REF_CAST_NULLABLE: + { + uint8 type; + + read_leb_int32(p, p_end, heap_type); +#if WASM_ENABLE_FAST_INTERP != 0 + emit_uint32(loader_ctx, (uint32)heap_type); +#endif + if (heap_type >= 0) { + if (!check_type_index(module, heap_type, error_buf, + error_buf_size)) { + goto fail; + } + } + else { + if (!wasm_is_valid_heap_type(heap_type)) { + set_error_buf(error_buf, error_buf_size, + "unknown type"); + goto fail; + } + } + if (!wasm_loader_pop_heap_obj(loader_ctx, &type, + &wasm_ref_type, error_buf, + error_buf_size)) { + goto fail; + } + if (opcode1 == WASM_OP_REF_TEST + || opcode1 == WASM_OP_REF_TEST_NULLABLE) + PUSH_I32(); + else { + bool nullable = + (opcode1 == WASM_OP_REF_CAST_NULLABLE) ? true + : false; + if (heap_type >= 0 || !nullable) { + wasm_set_refheaptype_typeidx( + &wasm_ref_type.ref_ht_typeidx, nullable, + heap_type); + PUSH_REF(wasm_ref_type.ref_type); + } + else { + PUSH_REF((uint8)((int32)0x80 + heap_type)); + } + } + break; + } + + case WASM_OP_BR_ON_CAST: + case WASM_OP_BR_ON_CAST_FAIL: + { + WASMRefType ref_type_tmp = { 0 }, ref_type1 = { 0 }, + ref_type2 = { 0 }, ref_type_diff = { 0 }; + uint8 type_tmp, castflags; + uint32 depth; + int32 heap_type_dst; + bool src_nullable, dst_nullable; + + CHECK_BUF(p, p_end, 1); + castflags = read_uint8(p); +#if WASM_ENABLE_FAST_INTERP != 0 + /* Emit heap_type firstly */ + emit_byte(loader_ctx, castflags); +#endif + + p_org = p; + read_leb_uint32(p, p_end, depth); + read_leb_int32(p, p_end, heap_type); +#if WASM_ENABLE_FAST_INTERP != 0 + /* Emit heap_type firstly */ + emit_uint32(loader_ctx, (uint32)heap_type); +#endif + read_leb_int32(p, p_end, heap_type_dst); +#if WASM_ENABLE_FAST_INTERP != 0 + /* Emit heap_type firstly */ + emit_uint32(loader_ctx, (uint32)heap_type_dst); +#endif + (void)depth; + + /* + * castflags should be 0~3: + * 0: (non-null, non-null) + * 1: (null, non-null) + * 2: (non-null, null) + * 3: (null, null) + */ + if (castflags > 3) { + set_error_buf(error_buf, error_buf_size, + "invalid castflags"); + break; + } + src_nullable = + (castflags == 1) || (castflags == 3) ? true : false; + dst_nullable = + (castflags == 2) || (castflags == 3) ? true : false; + + /* Pop and backup the stack top's ref type */ + if (!wasm_loader_pop_heap_obj(loader_ctx, &type_tmp, + &ref_type_tmp, error_buf, + error_buf_size)) { + goto fail; + } + + /* The reference type rt1 must be valid */ + if (!init_ref_type(module, &ref_type1, src_nullable, + heap_type, error_buf, + error_buf_size)) { + goto fail; + } + + /* The reference type rt2 must be valid. */ + if (!init_ref_type(module, &ref_type2, dst_nullable, + heap_type_dst, error_buf, + error_buf_size)) { + goto fail; + } + + calculate_reftype_diff(&ref_type_diff, &ref_type1, + &ref_type2); + + /* The reference type rt2 must match rt1. */ + if (!wasm_reftype_is_subtype_of( + ref_type2.ref_type, &ref_type2, + ref_type1.ref_type, &ref_type1, module->types, + module->type_count)) { + set_error_buf(error_buf, error_buf_size, + "type mismatch"); + goto fail; + } + + p = p_org; + /* Push ref type casted for branch block check */ + if (opcode1 == WASM_OP_BR_ON_CAST) { + /* The reference type rt2 must match rt′. */ + type_tmp = ref_type2.ref_type; + if (wasm_is_type_multi_byte_type(type_tmp)) { + bh_memcpy_s( + &wasm_ref_type, + wasm_reftype_struct_size(&ref_type2), + &ref_type2, + wasm_reftype_struct_size(&ref_type2)); + } + } + else { + /* The reference type rt′1 must match rt′. */ + type_tmp = ref_type_diff.ref_type; + if (wasm_is_type_multi_byte_type(type_tmp)) { + bh_memcpy_s( + &wasm_ref_type, + wasm_reftype_struct_size(&ref_type_diff), + &ref_type_diff, + wasm_reftype_struct_size(&ref_type_diff)); + } + } + PUSH_REF(type_tmp); + if (!(frame_csp_tmp = check_branch_block( + loader_ctx, &p, p_end, false, error_buf, + error_buf_size))) { + goto fail; + } + /* Ignore heap_types */ + skip_leb_uint32(p, p_end); + skip_leb_uint32(p, p_end); + + /* Restore the original stack top's ref type */ + POP_REF(type_tmp); +#if WASM_ENABLE_FAST_INTERP != 0 + /* Erase the opnd offset emitted by POP_REF() */ + wasm_loader_emit_backspace(loader_ctx, sizeof(uint16)); +#endif + if (opcode1 == WASM_OP_BR_ON_CAST) { + type_tmp = ref_type_diff.ref_type; + if (wasm_is_type_multi_byte_type(type_tmp)) { + bh_memcpy_s( + &wasm_ref_type, + wasm_reftype_struct_size(&ref_type_diff), + &ref_type_diff, + wasm_reftype_struct_size(&ref_type_diff)); + } + } + else { + type_tmp = ref_type2.ref_type; + if (wasm_is_type_multi_byte_type(type_tmp)) { + bh_memcpy_s( + &wasm_ref_type, + wasm_reftype_struct_size(&ref_type2), + &ref_type2, + wasm_reftype_struct_size(&ref_type2)); + } + } + PUSH_REF(type_tmp); + +#if WASM_ENABLE_FAST_INTERP != 0 + /* Erase the opnd offset emitted by PUSH_REF() */ + wasm_loader_emit_backspace(loader_ctx, sizeof(uint16)); +#endif + break; + } + + case WASM_OP_ANY_CONVERT_EXTERN: + { + uint8 type; + + if (!wasm_loader_pop_heap_obj(loader_ctx, &type, + &wasm_ref_type, error_buf, + error_buf_size)) { + goto fail; + } + if (!(type == REF_TYPE_EXTERNREF + || (type == REF_TYPE_HT_NON_NULLABLE + && wasm_ref_type.ref_ht_common.heap_type + == HEAP_TYPE_EXTERN) + || type == VALUE_TYPE_ANY)) { + set_error_buf(error_buf, error_buf_size, + "type mismatch"); + goto fail; + } + + if (type == REF_TYPE_EXTERNREF) + type = REF_TYPE_ANYREF; + else { + wasm_ref_type.ref_ht_common.heap_type = + HEAP_TYPE_ANY; + } + PUSH_REF(type); + break; + } + + case WASM_OP_EXTERN_CONVERT_ANY: + { + uint8 type; + + if (!wasm_loader_pop_heap_obj(loader_ctx, &type, + &wasm_ref_type, error_buf, + error_buf_size)) { + goto fail; + } + if (type == REF_TYPE_EXTERNREF + || ((type == REF_TYPE_HT_NULLABLE + || type == REF_TYPE_HT_NON_NULLABLE) + && wasm_ref_type.ref_ht_common.heap_type + == HEAP_TYPE_EXTERN)) { + set_error_buf(error_buf, error_buf_size, + "type mismatch"); + goto fail; + } + + if (type != REF_TYPE_HT_NON_NULLABLE) { + /* push (ref null extern) */ + type = REF_TYPE_EXTERNREF; + } + else { + /* push (ref extern) */ + type = REF_TYPE_HT_NON_NULLABLE; + wasm_set_refheaptype_common( + &wasm_ref_type.ref_ht_common, false, + HEAP_TYPE_EXTERN); + } + PUSH_REF(type); + break; + } + +#if WASM_ENABLE_STRINGREF != 0 + case WASM_OP_STRING_NEW_UTF8: + case WASM_OP_STRING_NEW_WTF16: + case WASM_OP_STRING_NEW_LOSSY_UTF8: + case WASM_OP_STRING_NEW_WTF8: + { + uint32 memidx; + +#if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 + func->has_memory_operations = true; +#endif + + read_leb_uint32(p, p_end, memidx); +#if WASM_ENABLE_FAST_INTERP != 0 + emit_uint32(loader_ctx, (uint32)memidx); +#endif + POP_I32(); + POP_I32(); + PUSH_REF(REF_TYPE_STRINGREF); + (void)memidx; + break; + } + case WASM_OP_STRING_CONST: + { + uint32 contents; + + read_leb_uint32(p, p_end, contents); +#if WASM_ENABLE_FAST_INTERP != 0 + emit_uint32(loader_ctx, (uint32)contents); +#endif + PUSH_REF(REF_TYPE_STRINGREF); + (void)contents; + break; + } + case WASM_OP_STRING_MEASURE_UTF8: + case WASM_OP_STRING_MEASURE_WTF8: + case WASM_OP_STRING_MEASURE_WTF16: + { + POP_STRINGREF(); + PUSH_I32(); + break; + } + case WASM_OP_STRING_ENCODE_UTF8: + case WASM_OP_STRING_ENCODE_WTF16: + case WASM_OP_STRING_ENCODE_LOSSY_UTF8: + case WASM_OP_STRING_ENCODE_WTF8: + { + uint32 memidx; + +#if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 + func->has_memory_operations = true; +#endif + + read_leb_uint32(p, p_end, memidx); +#if WASM_ENABLE_FAST_INTERP != 0 + emit_uint32(loader_ctx, (uint32)memidx); +#endif + POP_I32(); + POP_STRINGREF(); + PUSH_I32(); + (void)memidx; + break; + } + case WASM_OP_STRING_CONCAT: + { + POP_STRINGREF(); + POP_STRINGREF(); + PUSH_REF(REF_TYPE_STRINGREF); + break; + } + case WASM_OP_STRING_EQ: + { + POP_STRINGREF(); + POP_STRINGREF(); + PUSH_I32(); + break; + } + case WASM_OP_STRING_IS_USV_SEQUENCE: + { + POP_STRINGREF(); + PUSH_I32(); + break; + } + case WASM_OP_STRING_AS_WTF8: + { + POP_STRINGREF(); + PUSH_REF(REF_TYPE_STRINGVIEWWTF8); + break; + } + case WASM_OP_STRINGVIEW_WTF8_ADVANCE: + { + POP_I32(); + POP_I32(); + POP_REF(REF_TYPE_STRINGVIEWWTF8); + PUSH_I32(); + break; + } + case WASM_OP_STRINGVIEW_WTF8_ENCODE_UTF8: + case WASM_OP_STRINGVIEW_WTF8_ENCODE_LOSSY_UTF8: + case WASM_OP_STRINGVIEW_WTF8_ENCODE_WTF8: + { + uint32 memidx; + +#if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 + func->has_memory_operations = true; +#endif + + read_leb_uint32(p, p_end, memidx); +#if WASM_ENABLE_FAST_INTERP != 0 + emit_uint32(loader_ctx, (uint32)memidx); +#endif + POP_I32(); + POP_I32(); + POP_I32(); + POP_REF(REF_TYPE_STRINGVIEWWTF8); + PUSH_I32(); + PUSH_I32(); + (void)memidx; + break; + } + case WASM_OP_STRINGVIEW_WTF8_SLICE: + { + POP_I32(); + POP_I32(); + POP_REF(REF_TYPE_STRINGVIEWWTF8); + PUSH_REF(REF_TYPE_STRINGREF); + break; + } + case WASM_OP_STRING_AS_WTF16: + { + POP_STRINGREF(); + PUSH_REF(REF_TYPE_STRINGVIEWWTF16); + break; + } + case WASM_OP_STRINGVIEW_WTF16_LENGTH: + { + POP_REF(REF_TYPE_STRINGVIEWWTF16); + PUSH_I32(); + break; + } + case WASM_OP_STRINGVIEW_WTF16_GET_CODEUNIT: + { + POP_I32(); + POP_REF(REF_TYPE_STRINGVIEWWTF16); + PUSH_I32(); + break; + } + case WASM_OP_STRINGVIEW_WTF16_ENCODE: + { + uint32 memidx; + +#if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 + func->has_memory_operations = true; +#endif + + read_leb_uint32(p, p_end, memidx); +#if WASM_ENABLE_FAST_INTERP != 0 + emit_uint32(loader_ctx, (uint32)memidx); +#endif + POP_I32(); + POP_I32(); + POP_I32(); + POP_REF(REF_TYPE_STRINGVIEWWTF16); + PUSH_I32(); + (void)memidx; + break; + } + case WASM_OP_STRINGVIEW_WTF16_SLICE: + { + POP_I32(); + POP_I32(); + POP_REF(REF_TYPE_STRINGVIEWWTF16); + PUSH_REF(REF_TYPE_STRINGREF); + break; + } + case WASM_OP_STRING_AS_ITER: + { + POP_STRINGREF(); + PUSH_REF(REF_TYPE_STRINGVIEWITER); + break; + } + case WASM_OP_STRINGVIEW_ITER_NEXT: + { + POP_REF(REF_TYPE_STRINGVIEWITER); + PUSH_I32(); + break; + } + case WASM_OP_STRINGVIEW_ITER_ADVANCE: + case WASM_OP_STRINGVIEW_ITER_REWIND: + { + POP_I32(); + POP_REF(REF_TYPE_STRINGVIEWITER); + PUSH_I32(); + break; + } + case WASM_OP_STRINGVIEW_ITER_SLICE: + { + POP_I32(); + POP_REF(REF_TYPE_STRINGVIEWITER); + PUSH_REF(REF_TYPE_STRINGREF); + break; + } + case WASM_OP_STRING_NEW_UTF8_ARRAY: + case WASM_OP_STRING_NEW_WTF16_ARRAY: + case WASM_OP_STRING_NEW_LOSSY_UTF8_ARRAY: + case WASM_OP_STRING_NEW_WTF8_ARRAY: + { + POP_I32(); + POP_I32(); + POP_REF(REF_TYPE_ARRAYREF); + PUSH_REF(REF_TYPE_STRINGREF); + break; + } + case WASM_OP_STRING_ENCODE_UTF8_ARRAY: + case WASM_OP_STRING_ENCODE_WTF16_ARRAY: + case WASM_OP_STRING_ENCODE_LOSSY_UTF8_ARRAY: + case WASM_OP_STRING_ENCODE_WTF8_ARRAY: + { + POP_I32(); + POP_REF(REF_TYPE_ARRAYREF); + POP_STRINGREF(); + PUSH_I32(); + break; + } +#endif /* end of WASM_ENABLE_STRINGREF != 0 */ + default: + set_error_buf_v(error_buf, error_buf_size, + "%s %02x %02x", "unsupported opcode", + 0xfb, opcode1); + goto fail; + } + break; + } +#endif /* end of WASM_ENABLE_GC != 0 */ + case WASM_OP_MISC_PREFIX: { uint32 opcode1; @@ -9624,6 +14294,9 @@ re_scan: POP_I32(); #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 func->has_memory_operations = true; +#endif +#if WASM_ENABLE_WAMR_COMPILER != 0 + module->is_bulk_memory_used = true; #endif break; } @@ -9644,6 +14317,9 @@ re_scan: #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 func->has_memory_operations = true; +#endif +#if WASM_ENABLE_WAMR_COMPILER != 0 + module->is_bulk_memory_used = true; #endif break; } @@ -9663,6 +14339,9 @@ re_scan: POP_I32(); #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 func->has_memory_operations = true; +#endif +#if WASM_ENABLE_WAMR_COMPILER != 0 + module->is_bulk_memory_used = true; #endif break; } @@ -9681,6 +14360,9 @@ re_scan: POP_I32(); #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 func->has_memory_operations = true; +#endif +#if WASM_ENABLE_WAMR_COMPILER != 0 + module->is_bulk_memory_used = true; #endif break; } @@ -9698,29 +14380,51 @@ re_scan: "data count section required"); goto fail; #endif /* WASM_ENABLE_BULK_MEMORY */ -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 case WASM_OP_TABLE_INIT: { - uint8 seg_ref_type = 0, tbl_ref_type = 0; + uint8 seg_type = 0, tbl_type = 0; +#if WASM_ENABLE_GC != 0 + WASMRefType *seg_ref_type = NULL, *tbl_ref_type = NULL; +#endif read_leb_uint32(p, p_end, table_seg_idx); read_leb_uint32(p, p_end, table_idx); - if (!get_table_elem_type(module, table_idx, - &tbl_ref_type, error_buf, - error_buf_size)) + if (!get_table_elem_type(module, table_idx, &tbl_type, +#if WASM_ENABLE_GC != 0 + (void **)&tbl_ref_type, +#else + NULL, +#endif + error_buf, error_buf_size)) goto fail; if (!get_table_seg_elem_type(module, table_seg_idx, - &seg_ref_type, error_buf, - error_buf_size)) + &seg_type, +#if WASM_ENABLE_GC != 0 + (void **)&seg_ref_type, +#else + NULL, +#endif + error_buf, error_buf_size)) goto fail; - if (seg_ref_type != tbl_ref_type) { +#if WASM_ENABLE_GC == 0 + if (seg_type != tbl_type) { set_error_buf(error_buf, error_buf_size, "type mismatch"); goto fail; } +#else + if (!wasm_reftype_is_subtype_of( + seg_type, seg_ref_type, tbl_type, tbl_ref_type, + module->types, module->type_count)) { + set_error_buf(error_buf, error_buf_size, + "type mismatch"); + goto fail; + } +#endif #if WASM_ENABLE_FAST_INTERP != 0 emit_uint32(loader_ctx, table_seg_idx); @@ -9729,50 +14433,83 @@ re_scan: POP_I32(); POP_I32(); POP_I32(); + +#if WASM_ENABLE_WAMR_COMPILER != 0 + module->is_ref_types_used = true; +#endif break; } case WASM_OP_ELEM_DROP: { read_leb_uint32(p, p_end, table_seg_idx); if (!get_table_seg_elem_type(module, table_seg_idx, - NULL, error_buf, + NULL, NULL, error_buf, error_buf_size)) goto fail; #if WASM_ENABLE_FAST_INTERP != 0 emit_uint32(loader_ctx, table_seg_idx); #endif + +#if WASM_ENABLE_WAMR_COMPILER != 0 + module->is_ref_types_used = true; +#endif break; } case WASM_OP_TABLE_COPY: { - uint8 src_ref_type, dst_ref_type; + uint8 src_type, dst_type; +#if WASM_ENABLE_GC != 0 + WASMRefType *src_ref_type = NULL, *dst_ref_type = NULL; +#endif uint32 src_tbl_idx, dst_tbl_idx; - read_leb_uint32(p, p_end, src_tbl_idx); - if (!get_table_elem_type(module, src_tbl_idx, - &src_ref_type, error_buf, - error_buf_size)) - goto fail; - read_leb_uint32(p, p_end, dst_tbl_idx); - if (!get_table_elem_type(module, dst_tbl_idx, - &dst_ref_type, error_buf, - error_buf_size)) + if (!get_table_elem_type(module, dst_tbl_idx, &dst_type, +#if WASM_ENABLE_GC != 0 + (void **)&dst_ref_type, +#else + NULL, +#endif + error_buf, error_buf_size)) goto fail; - if (src_ref_type != dst_ref_type) { + read_leb_uint32(p, p_end, src_tbl_idx); + if (!get_table_elem_type(module, src_tbl_idx, &src_type, +#if WASM_ENABLE_GC != 0 + (void **)&src_ref_type, +#else + NULL, +#endif + error_buf, error_buf_size)) + goto fail; + +#if WASM_ENABLE_GC == 0 + if (src_type != dst_type) { set_error_buf(error_buf, error_buf_size, "type mismatch"); goto fail; } +#else + if (!wasm_reftype_is_subtype_of( + src_type, src_ref_type, dst_type, dst_ref_type, + module->types, module->type_count)) { + set_error_buf(error_buf, error_buf_size, + "type mismatch"); + goto fail; + } +#endif #if WASM_ENABLE_FAST_INTERP != 0 - emit_uint32(loader_ctx, src_tbl_idx); emit_uint32(loader_ctx, dst_tbl_idx); + emit_uint32(loader_ctx, src_tbl_idx); #endif POP_I32(); POP_I32(); POP_I32(); + +#if WASM_ENABLE_WAMR_COMPILER != 0 + module->is_ref_types_used = true; +#endif break; } case WASM_OP_TABLE_SIZE: @@ -9780,7 +14517,7 @@ re_scan: read_leb_uint32(p, p_end, table_idx); /* TODO: shall we create a new function to check table idx instead of using below function? */ - if (!get_table_elem_type(module, table_idx, NULL, + if (!get_table_elem_type(module, table_idx, NULL, NULL, error_buf, error_buf_size)) goto fail; @@ -9789,18 +14526,36 @@ re_scan: #endif PUSH_I32(); + +#if WASM_ENABLE_WAMR_COMPILER != 0 + module->is_ref_types_used = true; +#endif break; } case WASM_OP_TABLE_GROW: case WASM_OP_TABLE_FILL: { - uint8 decl_ref_type; + uint8 decl_type; +#if WASM_ENABLE_GC != 0 + WASMRefType *ref_type = NULL; +#endif read_leb_uint32(p, p_end, table_idx); - if (!get_table_elem_type(module, table_idx, - &decl_ref_type, error_buf, - error_buf_size)) + if (!get_table_elem_type(module, table_idx, &decl_type, +#if WASM_ENABLE_GC != 0 + (void **)&ref_type, +#else + NULL, +#endif + error_buf, error_buf_size)) goto fail; +#if WASM_ENABLE_GC != 0 + if (wasm_is_type_multi_byte_type(decl_type)) { + bh_memcpy_s(&wasm_ref_type, sizeof(WASMRefType), + ref_type, + wasm_reftype_struct_size(ref_type)); + } +#endif if (opcode1 == WASM_OP_TABLE_GROW) { if (table_idx < module->import_table_count) { @@ -9821,16 +14576,20 @@ re_scan: POP_I32(); #if WASM_ENABLE_FAST_INTERP != 0 - POP_OFFSET_TYPE(decl_ref_type); + POP_OFFSET_TYPE(decl_type); #endif - POP_TYPE(decl_ref_type); + POP_TYPE(decl_type); if (opcode1 == WASM_OP_TABLE_GROW) PUSH_I32(); else POP_I32(); + +#if WASM_ENABLE_WAMR_COMPILER != 0 + module->is_ref_types_used = true; +#endif break; } -#endif /* WASM_ENABLE_REF_TYPES */ +#endif /* end of WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */ default: set_error_buf_v(error_buf, error_buf_size, "%s %02x %02x", "unsupported opcode", @@ -9846,6 +14605,11 @@ re_scan: { uint32 opcode1; +#if WASM_ENABLE_WAMR_COMPILER != 0 + /* Mark the SIMD instruction is used in this module */ + module->is_simd_used = true; +#endif + read_leb_uint32(p, p_end, opcode1); /* follow the order of enum WASMSimdEXTOpcode in wasm_opcode.h diff --git a/core/iwasm/interpreter/wasm_mini_loader.c b/core/iwasm/interpreter/wasm_mini_loader.c index ba2c37fc7..b8f74b8fe 100644 --- a/core/iwasm/interpreter/wasm_mini_loader.c +++ b/core/iwasm/interpreter/wasm_mini_loader.c @@ -194,6 +194,29 @@ loader_malloc(uint64 size, char *error_buf, uint32 error_buf_size) return mem; } +static void * +memory_realloc(void *mem_old, uint32 size_old, uint32 size_new, char *error_buf, + uint32 error_buf_size) +{ + uint8 *mem_new; + bh_assert(size_new > size_old); + if ((mem_new = loader_malloc(size_new, error_buf, error_buf_size))) { + bh_memcpy_s(mem_new, size_new, mem_old, size_old); + memset(mem_new + size_old, 0, size_new - size_old); + wasm_runtime_free(mem_old); + } + return mem_new; +} + +#define MEM_REALLOC(mem, size_old, size_new) \ + do { \ + void *mem_new = memory_realloc(mem, size_old, size_new, error_buf, \ + error_buf_size); \ + if (!mem_new) \ + goto fail; \ + mem = mem_new; \ + } while (0) + static char * const_str_list_insert(const uint8 *str, uint32 len, WASMModule *module, bool is_load_from_file_buf, char *error_buf, @@ -252,7 +275,7 @@ const_str_list_insert(const uint8 *str, uint32 len, WASMModule *module, } static void -destroy_wasm_type(WASMType *type) +destroy_wasm_type(WASMFuncType *type) { if (type->ref_count > 1) { /* The type is referenced by other types @@ -271,80 +294,256 @@ destroy_wasm_type(WASMType *type) } static bool -load_init_expr(const uint8 **p_buf, const uint8 *buf_end, +check_function_index(const WASMModule *module, uint32 function_index, + char *error_buf, uint32 error_buf_size) +{ + return (function_index + < module->import_function_count + module->function_count); +} + +typedef struct InitValue { + uint8 type; + uint8 flag; + WASMValue value; +} InitValue; + +typedef struct ConstExprContext { + uint32 sp; + uint32 size; + WASMModule *module; + InitValue *stack; + InitValue data[WASM_CONST_EXPR_STACK_SIZE]; +} ConstExprContext; + +static void +init_const_expr_stack(ConstExprContext *ctx, WASMModule *module) +{ + ctx->sp = 0; + ctx->module = module; + ctx->stack = ctx->data; + ctx->size = WASM_CONST_EXPR_STACK_SIZE; +} + +static bool +push_const_expr_stack(ConstExprContext *ctx, uint8 flag, uint8 type, + WASMValue *value, char *error_buf, uint32 error_buf_size) +{ + InitValue *cur_value; + + if (ctx->sp >= ctx->size) { + if (ctx->stack != ctx->data) { + MEM_REALLOC(ctx->stack, ctx->size * sizeof(InitValue), + (ctx->size + 4) * sizeof(InitValue)); + } + else { + if (!(ctx->stack = + loader_malloc((ctx->size + 4) * (uint64)sizeof(InitValue), + error_buf, error_buf_size))) { + return false; + } + } + ctx->size += 4; + } + + cur_value = &ctx->stack[ctx->sp++]; + cur_value->type = type; + cur_value->flag = flag; + cur_value->value = *value; + + return true; +fail: + return false; +} + +static bool +pop_const_expr_stack(ConstExprContext *ctx, uint8 *p_flag, uint8 type, + WASMValue *p_value, char *error_buf, uint32 error_buf_size) +{ + InitValue *cur_value; + + if (ctx->sp == 0) { + return false; + } + + cur_value = &ctx->stack[--ctx->sp]; + + if (cur_value->type != type) { + return false; + } + + if (p_flag) + *p_flag = cur_value->flag; + if (p_value) + *p_value = cur_value->value; + + return true; +} + +static void +destroy_const_expr_stack(ConstExprContext *ctx) +{ + if (ctx->stack != ctx->data) { + wasm_runtime_free(ctx->stack); + } +} + +static bool +load_init_expr(WASMModule *module, const uint8 **p_buf, const uint8 *buf_end, InitializerExpression *init_expr, uint8 type, char *error_buf, uint32 error_buf_size) { const uint8 *p = *p_buf, *p_end = buf_end; - uint8 flag, end_byte, *p_float; + uint8 flag, *p_float; uint32 i; + ConstExprContext const_expr_ctx = { 0 }; + WASMValue cur_value = { 0 }; + + init_const_expr_stack(&const_expr_ctx, module); CHECK_BUF(p, p_end, 1); - init_expr->init_expr_type = read_uint8(p); - flag = init_expr->init_expr_type; + flag = read_uint8(p); + + while (flag != WASM_OP_END) { + switch (flag) { + /* i32.const */ + case INIT_EXPR_TYPE_I32_CONST: + read_leb_int32(p, p_end, cur_value.i32); + + if (!push_const_expr_stack(&const_expr_ctx, flag, + VALUE_TYPE_I32, &cur_value, + error_buf, error_buf_size)) { + bh_assert(0); + } + break; + /* i64.const */ + case INIT_EXPR_TYPE_I64_CONST: + read_leb_int64(p, p_end, cur_value.i64); + + if (!push_const_expr_stack(&const_expr_ctx, flag, + VALUE_TYPE_I64, &cur_value, + error_buf, error_buf_size)) { + bh_assert(0); + } + break; + /* f32.const */ + case INIT_EXPR_TYPE_F32_CONST: + CHECK_BUF(p, p_end, 4); + p_float = (uint8 *)&cur_value.f32; + for (i = 0; i < sizeof(float32); i++) + *p_float++ = *p++; + + if (!push_const_expr_stack(&const_expr_ctx, flag, + VALUE_TYPE_F32, &cur_value, + error_buf, error_buf_size)) { + bh_assert(0); + } + break; + /* f64.const */ + case INIT_EXPR_TYPE_F64_CONST: + CHECK_BUF(p, p_end, 8); + p_float = (uint8 *)&cur_value.f64; + for (i = 0; i < sizeof(float64); i++) + *p_float++ = *p++; + + if (!push_const_expr_stack(&const_expr_ctx, flag, + VALUE_TYPE_F64, &cur_value, + error_buf, error_buf_size)) { + bh_assert(0); + } + break; - switch (flag) { - /* i32.const */ - case INIT_EXPR_TYPE_I32_CONST: - bh_assert(type == VALUE_TYPE_I32); - read_leb_int32(p, p_end, init_expr->u.i32); - break; - /* i64.const */ - case INIT_EXPR_TYPE_I64_CONST: - bh_assert(type == VALUE_TYPE_I64); - read_leb_int64(p, p_end, init_expr->u.i64); - break; - /* f32.const */ - case INIT_EXPR_TYPE_F32_CONST: - bh_assert(type == VALUE_TYPE_F32); - CHECK_BUF(p, p_end, 4); - p_float = (uint8 *)&init_expr->u.f32; - for (i = 0; i < sizeof(float32); i++) - *p_float++ = *p++; - break; - /* f64.const */ - case INIT_EXPR_TYPE_F64_CONST: - bh_assert(type == VALUE_TYPE_F64); - CHECK_BUF(p, p_end, 8); - p_float = (uint8 *)&init_expr->u.f64; - for (i = 0; i < sizeof(float64); i++) - *p_float++ = *p++; - break; #if WASM_ENABLE_REF_TYPES != 0 - case INIT_EXPR_TYPE_FUNCREF_CONST: - { - bh_assert(type == VALUE_TYPE_FUNCREF); - read_leb_uint32(p, p_end, init_expr->u.ref_index); - break; + /* ref.func */ + case INIT_EXPR_TYPE_FUNCREF_CONST: + { + uint32 func_idx; + read_leb_uint32(p, p_end, func_idx); + cur_value.ref_index = func_idx; + if (!check_function_index(module, func_idx, error_buf, + error_buf_size)) { + bh_assert(0); + } + + if (!push_const_expr_stack(&const_expr_ctx, flag, + VALUE_TYPE_FUNCREF, &cur_value, + error_buf, error_buf_size)) { + bh_assert(0); + } + break; + } + + /* ref.null */ + case INIT_EXPR_TYPE_REFNULL_CONST: + { + uint8 type1; + + CHECK_BUF(p, p_end, 1); + type1 = read_uint8(p); + + cur_value.ref_index = UINT32_MAX; + if (!push_const_expr_stack(&const_expr_ctx, flag, type1, + &cur_value, error_buf, + error_buf_size)) { + bh_assert(0); + } + break; + } +#endif /* end of WASM_ENABLE_REF_TYPES != 0 */ + + /* get_global */ + case INIT_EXPR_TYPE_GET_GLOBAL: + { + uint32 global_idx; + uint8 global_type; + + read_leb_uint32(p, p_end, cur_value.global_index); + global_idx = cur_value.global_index; + + bh_assert(global_idx < module->import_global_count); + bh_assert( + !module->import_globals[global_idx].u.global.is_mutable); + + if (global_idx < module->import_global_count) { + global_type = + module->import_globals[global_idx].u.global.type; + } + else { + global_type = + module + ->globals[global_idx - module->import_global_count] + .type; + } + + if (!push_const_expr_stack(&const_expr_ctx, flag, global_type, + &cur_value, error_buf, + error_buf_size)) + bh_assert(0); + + break; + } + default: + { + bh_assert(0); + } } - case INIT_EXPR_TYPE_REFNULL_CONST: - { - uint8 reftype; - CHECK_BUF(p, p_end, 1); - reftype = read_uint8(p); - - bh_assert(type == reftype); - - init_expr->u.ref_index = NULL_REF; - (void)reftype; - break; - } -#endif /* WASM_ENABLE_REF_TYPES != 0 */ - /* get_global */ - case INIT_EXPR_TYPE_GET_GLOBAL: - read_leb_uint32(p, p_end, init_expr->u.global_index); - break; - default: - bh_assert(0); - break; + CHECK_BUF(p, p_end, 1); + flag = read_uint8(p); } - CHECK_BUF(p, p_end, 1); - end_byte = read_uint8(p); - bh_assert(end_byte == 0x0b); - *p_buf = p; - (void)end_byte; + /* There should be only one value left on the init value stack */ + if (!pop_const_expr_stack(&const_expr_ctx, &flag, type, &cur_value, + error_buf, error_buf_size)) { + bh_assert(0); + } + + bh_assert(const_expr_ctx.sp == 0); + + init_expr->init_expr_type = flag; + init_expr->u = cur_value; + + *p_buf = p; + destroy_const_expr_stack(&const_expr_ctx); return true; } @@ -357,13 +556,13 @@ load_type_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, uint32 param_cell_num, ret_cell_num; uint64 total_size; uint8 flag; - WASMType *type; + WASMFuncType *type; read_leb_uint32(p, p_end, type_count); if (type_count) { module->type_count = type_count; - total_size = sizeof(WASMType *) * (uint64)type_count; + total_size = sizeof(WASMFuncType *) * (uint64)type_count; if (!(module->types = loader_malloc(total_size, error_buf, error_buf_size))) { return false; @@ -386,7 +585,7 @@ load_type_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, bh_assert(param_count <= UINT16_MAX && result_count <= UINT16_MAX); - total_size = offsetof(WASMType, types) + total_size = offsetof(WASMFuncType, types) + sizeof(uint8) * (uint64)(param_count + result_count); if (!(type = module->types[i] = loader_malloc(total_size, error_buf, error_buf_size))) { @@ -424,7 +623,7 @@ load_type_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, /* If there is already a same type created, use it instead */ for (j = 0; j < i; ++j) { - if (wasm_type_equal(type, module->types[j])) { + if (wasm_type_equal(type, module->types[j], module->types, i)) { bh_assert(module->types[j]->ref_count != UINT16_MAX); destroy_wasm_type(type); module->types[i] = module->types[j]; @@ -444,8 +643,9 @@ load_type_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, static void adjust_table_max_size(uint32 init_size, uint32 max_size_flag, uint32 *max_size) { - uint32 default_max_size = - init_size * 2 > TABLE_MAX_SIZE ? init_size * 2 : TABLE_MAX_SIZE; + uint32 default_max_size = init_size * 2 > WASM_TABLE_MAX_SIZE + ? init_size * 2 + : WASM_TABLE_MAX_SIZE; if (max_size_flag) { /* module defines the table limitation */ @@ -471,7 +671,7 @@ load_function_import(const uint8 **p_buf, const uint8 *buf_end, { const uint8 *p = *p_buf, *p_end = buf_end; uint32 declare_type_index = 0; - WASMType *declare_func_type = NULL; + WASMFuncType *declare_func_type = NULL; WASMFunction *linked_func = NULL; const char *linked_signature = NULL; void *linked_attachment = NULL; @@ -911,7 +1111,7 @@ static bool init_function_local_offsets(WASMFunction *func, char *error_buf, uint32 error_buf_size) { - WASMType *param_type = func->func_type; + WASMFuncType *param_type = func->func_type; uint32 param_count = param_type->param_count; uint8 *param_types = param_type->types; uint32 local_count = func->local_count; @@ -1065,14 +1265,6 @@ load_function_section(const uint8 *buf, const uint8 *buf_end, return true; } -static bool -check_function_index(const WASMModule *module, uint32 function_index, - char *error_buf, uint32 error_buf_size) -{ - return (function_index - < module->import_function_count + module->function_count); -} - static bool load_table_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, char *error_buf, uint32 error_buf_size) @@ -1151,8 +1343,8 @@ load_global_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, read_leb_uint32(p, p_end, global_count); + module->global_count = 0; if (global_count) { - module->global_count = global_count; total_size = sizeof(WASMGlobal) * (uint64)global_count; if (!(module->globals = loader_malloc(total_size, error_buf, error_buf_size))) { @@ -1169,8 +1361,8 @@ load_global_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, global->is_mutable = mutable ? true : false; /* initialize expression */ - if (!load_init_expr(&p, p_end, &(global->init_expr), global->type, - error_buf, error_buf_size)) + if (!load_init_expr(module, &p, p_end, &(global->init_expr), + global->type, error_buf, error_buf_size)) return false; if (INIT_EXPR_TYPE_GET_GLOBAL == global->init_expr.init_expr_type) { @@ -1190,7 +1382,10 @@ load_global_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, < module->import_function_count + module->function_count); } + + module->global_count++; } + bh_assert(module->global_count == global_count); } bh_assert(p == p_end); @@ -1341,52 +1536,78 @@ load_elem_type(const uint8 **p_buf, const uint8 *buf_end, uint32 *p_elem_type, static bool load_func_index_vec(const uint8 **p_buf, const uint8 *buf_end, WASMModule *module, WASMTableSeg *table_segment, - bool use_init_expr, char *error_buf, uint32 error_buf_size) + char *error_buf, uint32 error_buf_size) { const uint8 *p = *p_buf, *p_end = buf_end; uint32 function_count, function_index = 0, i; uint64 total_size; read_leb_uint32(p, p_end, function_count); - table_segment->function_count = function_count; - total_size = sizeof(uint32) * (uint64)function_count; + table_segment->value_count = function_count; + total_size = sizeof(InitializerExpression) * (uint64)function_count; if (total_size > 0 - && !(table_segment->func_indexes = (uint32 *)loader_malloc( - total_size, error_buf, error_buf_size))) { + && !(table_segment->init_values = + (InitializerExpression *)loader_malloc(total_size, error_buf, + error_buf_size))) { return false; } for (i = 0; i < function_count; i++) { - InitializerExpression init_expr = { 0 }; + InitializerExpression *init_expr = &table_segment->init_values[i]; -#if WASM_ENABLE_REF_TYPES != 0 - if (!use_init_expr) { - read_leb_uint32(p, p_end, function_index); - } - else { - if (!load_init_expr(&p, p_end, &init_expr, table_segment->elem_type, - error_buf, error_buf_size)) - return false; - - function_index = init_expr.u.ref_index; - } -#else read_leb_uint32(p, p_end, function_index); -#endif - - /* since we are using -1 to indicate ref.null */ - if (init_expr.init_expr_type != INIT_EXPR_TYPE_REFNULL_CONST - && !check_function_index(module, function_index, error_buf, - error_buf_size)) { + if (!check_function_index(module, function_index, error_buf, + error_buf_size)) { return false; } - table_segment->func_indexes[i] = function_index; + + init_expr->init_expr_type = INIT_EXPR_TYPE_FUNCREF_CONST; + init_expr->u.ref_index = function_index; } *p_buf = p; return true; } +#if WASM_ENABLE_REF_TYPES != 0 +static bool +load_init_expr_vec(const uint8 **p_buf, const uint8 *buf_end, + WASMModule *module, WASMTableSeg *table_segment, + char *error_buf, uint32 error_buf_size) +{ + const uint8 *p = *p_buf, *p_end = buf_end; + uint32 ref_count, i; + uint64 total_size; + + read_leb_uint32(p, p_end, ref_count); + table_segment->value_count = ref_count; + total_size = sizeof(InitializerExpression) * (uint64)ref_count; + if (total_size > 0 + && !(table_segment->init_values = + (InitializerExpression *)loader_malloc(total_size, error_buf, + error_buf_size))) { + return false; + } + + for (i = 0; i < ref_count; i++) { + InitializerExpression *init_expr = &table_segment->init_values[i]; + + if (!load_init_expr(module, &p, p_end, init_expr, + table_segment->elem_type, error_buf, + error_buf_size)) + return false; + + bh_assert( + (init_expr->init_expr_type == INIT_EXPR_TYPE_GET_GLOBAL) + || (init_expr->init_expr_type == INIT_EXPR_TYPE_REFNULL_CONST) + || (init_expr->init_expr_type == INIT_EXPR_TYPE_FUNCREF_CONST)); + } + + *p_buf = p; + return true; +} +#endif /* end of WASM_ENABLE_REF_TYPES != 0 */ + static bool load_table_segment_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, char *error_buf, @@ -1426,16 +1647,25 @@ load_table_segment_section(const uint8 *buf, const uint8 *buf_end, error_buf, error_buf_size)) return false; - if (!load_init_expr(&p, p_end, &table_segment->base_offset, - VALUE_TYPE_I32, error_buf, - error_buf_size)) + if (!load_init_expr( + module, &p, p_end, &table_segment->base_offset, + VALUE_TYPE_I32, error_buf, error_buf_size)) return false; - if (!load_func_index_vec(&p, p_end, module, table_segment, - table_segment->mode == 0 ? false - : true, - error_buf, error_buf_size)) - return false; + if (table_segment->mode == 0) { + /* vec(funcidx) */ + if (!load_func_index_vec(&p, p_end, module, + table_segment, error_buf, + error_buf_size)) + return false; + } + else { + /* vec(expr) */ + if (!load_init_expr_vec(&p, p_end, module, + table_segment, error_buf, + error_buf_size)) + return false; + } break; /* elemkind + passive/declarative */ case 1: @@ -1443,8 +1673,9 @@ load_table_segment_section(const uint8 *buf, const uint8 *buf_end, if (!load_elem_type(&p, p_end, &table_segment->elem_type, true, error_buf, error_buf_size)) return false; + /* vec(funcidx) */ if (!load_func_index_vec(&p, p_end, module, table_segment, - false, error_buf, error_buf_size)) + error_buf, error_buf_size)) return false; break; /* elemkind/elemtype + table_idx + active */ @@ -1454,27 +1685,37 @@ load_table_segment_section(const uint8 *buf, const uint8 *buf_end, &table_segment->table_index, error_buf, error_buf_size)) return false; - if (!load_init_expr(&p, p_end, &table_segment->base_offset, - VALUE_TYPE_I32, error_buf, - error_buf_size)) + if (!load_init_expr( + module, &p, p_end, &table_segment->base_offset, + VALUE_TYPE_I32, error_buf, error_buf_size)) return false; if (!load_elem_type(&p, p_end, &table_segment->elem_type, table_segment->mode == 2 ? true : false, error_buf, error_buf_size)) return false; - if (!load_func_index_vec(&p, p_end, module, table_segment, - table_segment->mode == 2 ? false - : true, - error_buf, error_buf_size)) - return false; + if (table_segment->mode == 2) { + /* vec(funcidx) */ + if (!load_func_index_vec(&p, p_end, module, + table_segment, error_buf, + error_buf_size)) + return false; + } + else { + /* vec(expr) */ + if (!load_init_expr_vec(&p, p_end, module, + table_segment, error_buf, + error_buf_size)) + return false; + } break; case 5: case 7: if (!load_elem_type(&p, p_end, &table_segment->elem_type, false, error_buf, error_buf_size)) return false; - if (!load_func_index_vec(&p, p_end, module, table_segment, - true, error_buf, error_buf_size)) + /* vec(expr) */ + if (!load_init_expr_vec(&p, p_end, module, table_segment, + error_buf, error_buf_size)) return false; break; default: @@ -1489,10 +1730,10 @@ load_table_segment_section(const uint8 *buf, const uint8 *buf_end, &table_segment->table_index, error_buf, error_buf_size)) return false; - if (!load_init_expr(&p, p_end, &table_segment->base_offset, + if (!load_init_expr(module, &p, p_end, &table_segment->base_offset, VALUE_TYPE_I32, error_buf, error_buf_size)) return false; - if (!load_func_index_vec(&p, p_end, module, table_segment, false, + if (!load_func_index_vec(&p, p_end, module, table_segment, error_buf, error_buf_size)) return false; #endif /* WASM_ENABLE_REF_TYPES != 0 */ @@ -1569,8 +1810,8 @@ load_data_segment_section(const uint8 *buf, const uint8 *buf_end, #if WASM_ENABLE_BULK_MEMORY != 0 if (!is_passive) #endif - if (!load_init_expr(&p, p_end, &init_expr, VALUE_TYPE_I32, - error_buf, error_buf_size)) + if (!load_init_expr(module, &p, p_end, &init_expr, + VALUE_TYPE_I32, error_buf, error_buf_size)) return false; read_leb_uint32(p, p_end, data_seg_len); @@ -1650,7 +1891,7 @@ load_start_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, char *error_buf, uint32 error_buf_size) { const uint8 *p = buf, *p_end = buf_end; - WASMType *type; + WASMFuncType *type; uint32 start_function; read_leb_uint32(p, p_end, start_function); @@ -1843,6 +2084,7 @@ init_llvm_jit_functions_stage1(WASMModule *module, char *error_buf, AOTCompOption option = { 0 }; char *aot_last_error; uint64 size; + bool gc_enabled = false; /* GC hasn't been enabled in mini loader */ if (module->function_count == 0) return true; @@ -1869,7 +2111,7 @@ init_llvm_jit_functions_stage1(WASMModule *module, char *error_buf, (bool *)((uint8 *)module->func_ptrs + sizeof(void *) * module->function_count); - module->comp_data = aot_create_comp_data(module); + module->comp_data = aot_create_comp_data(module, NULL, gc_enabled); if (!module->comp_data) { aot_last_error = aot_get_last_error(); bh_assert(aot_last_error != NULL); @@ -1900,10 +2142,15 @@ init_llvm_jit_functions_stage1(WASMModule *module, char *error_buf, option.enable_ref_types = true; #endif option.enable_aux_stack_check = true; -#if (WASM_ENABLE_PERF_PROFILING != 0) || (WASM_ENABLE_DUMP_CALL_STACK != 0) +#if WASM_ENABLE_PERF_PROFILING != 0 || WASM_ENABLE_DUMP_CALL_STACK != 0 \ + || WASM_ENABLE_AOT_STACK_FRAME != 0 option.enable_aux_stack_frame = true; #endif +#if WASM_ENABLE_PERF_PROFILING != 0 + option.enable_perf_profiling = true; +#endif #if WASM_ENABLE_MEMORY_PROFILING != 0 + option.enable_memory_profiling = true; option.enable_stack_estimation = true; #endif @@ -2024,7 +2271,7 @@ orcjit_thread_callback(void *arg) /* Compile fast jit funcitons of this group */ for (i = group_idx; i < func_count; i += group_stride) { if (!jit_compiler_compile(module, i + module->import_function_count)) { - os_printf("failed to compile fast jit function %u\n", i); + LOG_ERROR("failed to compile fast jit function %u\n", i); break; } @@ -2051,7 +2298,7 @@ orcjit_thread_callback(void *arg) if (!jit_compiler_set_call_to_fast_jit( module, i + j * group_stride + module->import_function_count)) { - os_printf( + LOG_ERROR( "failed to compile call_to_fast_jit for func %u\n", i + j * group_stride + module->import_function_count); module->orcjit_stop_compiling = true; @@ -2101,7 +2348,7 @@ orcjit_thread_callback(void *arg) LLVMOrcLLLazyJITLookup(comp_ctx->orc_jit, &func_addr, func_name); if (error != LLVMErrorSuccess) { char *err_msg = LLVMGetErrorMessage(error); - os_printf("failed to compile llvm jit function %u: %s", i, err_msg); + LOG_ERROR("failed to compile llvm jit function %u: %s", i, err_msg); LLVMDisposeErrorMessage(err_msg); break; } @@ -2122,7 +2369,7 @@ orcjit_thread_callback(void *arg) func_name); if (error != LLVMErrorSuccess) { char *err_msg = LLVMGetErrorMessage(error); - os_printf("failed to compile llvm jit function %u: %s", i, + LOG_ERROR("failed to compile llvm jit function %u: %s", i, err_msg); LLVMDisposeErrorMessage(err_msg); /* Ignore current llvm jit func, as its func ptr is @@ -2299,7 +2546,7 @@ load_from_sections(WASMModule *module, WASMSection *sections, uint32 aux_stack_top = (uint32)-1, global_index, func_index, i; uint32 aux_data_end_global_index = (uint32)-1; uint32 aux_heap_base_global_index = (uint32)-1; - WASMType *func_type; + WASMFuncType *func_type; /* Find code and function sections if have */ while (section) { @@ -2936,7 +3183,8 @@ wasm_loader_load(uint8 *buf, uint32 size, char *error_buf, return NULL; } -#if WASM_ENABLE_FAST_JIT != 0 +#if WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_DUMP_CALL_STACK != 0 \ + || WASM_ENABLE_JIT != 0 module->load_addr = (uint8 *)buf; module->load_size = size; #endif @@ -3045,8 +3293,8 @@ wasm_loader_unload(WASMModule *module) if (module->table_segments) { for (i = 0; i < module->table_seg_count; i++) { - if (module->table_segments[i].func_indexes) - wasm_runtime_free(module->table_segments[i].func_indexes); + if (module->table_segments[i].init_values) + wasm_runtime_free(module->table_segments[i].init_values); } wasm_runtime_free(module->table_segments); } @@ -3689,29 +3937,6 @@ typedef struct Const { uint8 value_type; } Const; -static void * -memory_realloc(void *mem_old, uint32 size_old, uint32 size_new, char *error_buf, - uint32 error_buf_size) -{ - uint8 *mem_new; - bh_assert(size_new > size_old); - if ((mem_new = loader_malloc(size_new, error_buf, error_buf_size))) { - bh_memcpy_s(mem_new, size_new, mem_old, size_old); - memset(mem_new + size_old, 0, size_new - size_old); - wasm_runtime_free(mem_old); - } - return mem_new; -} - -#define MEM_REALLOC(mem, size_old, size_new) \ - do { \ - void *mem_new = memory_realloc(mem, size_old, size_new, error_buf, \ - error_buf_size); \ - if (!mem_new) \ - goto fail; \ - mem = mem_new; \ - } while (0) - #define CHECK_CSP_PUSH() \ do { \ if (ctx->frame_csp >= ctx->frame_csp_boundary) { \ @@ -5203,13 +5428,6 @@ fail: local_offset = local_offsets[local_idx]; \ } while (0) -#define CHECK_BR(depth) \ - do { \ - if (!wasm_loader_check_br(loader_ctx, depth, error_buf, \ - error_buf_size)) \ - goto fail; \ - } while (0) - #define CHECK_MEMORY() \ do { \ bh_assert(module->import_memory_count + module->memory_count > 0); \ @@ -5217,7 +5435,7 @@ fail: static bool wasm_loader_check_br(WASMLoaderContext *loader_ctx, uint32 depth, - char *error_buf, uint32 error_buf_size) + bool is_br_table, char *error_buf, uint32 error_buf_size) { BranchBlock *target_block, *cur_block; BlockType *target_block_type; @@ -5226,7 +5444,22 @@ wasm_loader_check_br(WASMLoaderContext *loader_ctx, uint32 depth, int32 i, available_stack_cell; uint16 cell_num; - if (loader_ctx->csp_num < depth + 1) { + uint8 *frame_ref_old = loader_ctx->frame_ref; + uint8 *frame_ref_after_popped = NULL; + uint8 frame_ref_tmp[4] = { 0 }; + uint8 *frame_ref_buf = frame_ref_tmp; + uint32 stack_cell_num_old = loader_ctx->stack_cell_num; +#if WASM_ENABLE_FAST_INTERP != 0 + int16 *frame_offset_old = loader_ctx->frame_offset; + int16 *frame_offset_after_popped = NULL; + int16 frame_offset_tmp[4] = { 0 }; + int16 *frame_offset_buf = frame_offset_tmp; + uint16 dynamic_offset_old = (loader_ctx->frame_csp - 1)->dynamic_offset; +#endif + bool ret = false; + + bh_assert(loader_ctx->csp_num > 0); + if (loader_ctx->csp_num - 1 < depth) { set_error_buf(error_buf, error_buf_size, "unknown label, " "unexpected end of section or function"); @@ -5256,6 +5489,38 @@ wasm_loader_check_br(WASMLoaderContext *loader_ctx, uint32 depth, #endif POP_TYPE(types[i]); } + + /* Backup stack data since it may be changed in the below + push operations, and the stack data may be used when + checking other target blocks of opcode br_table */ + if (is_br_table) { + uint64 total_size; + + frame_ref_after_popped = loader_ctx->frame_ref; + total_size = (uint64)sizeof(uint8) + * (frame_ref_old - frame_ref_after_popped); + if (total_size > sizeof(frame_ref_tmp) + && !(frame_ref_buf = loader_malloc(total_size, error_buf, + error_buf_size))) { + goto fail; + } + bh_memcpy_s(frame_ref_buf, (uint32)total_size, + frame_ref_after_popped, (uint32)total_size); + +#if WASM_ENABLE_FAST_INTERP != 0 + frame_offset_after_popped = loader_ctx->frame_offset; + total_size = (uint64)sizeof(int16) + * (frame_offset_old - frame_offset_after_popped); + if (total_size > sizeof(frame_offset_tmp) + && !(frame_offset_buf = loader_malloc(total_size, error_buf, + error_buf_size))) { + goto fail; + } + bh_memcpy_s(frame_offset_buf, (uint32)total_size, + frame_offset_after_popped, (uint32)total_size); +#endif + } + for (i = 0; i < (int32)arity; i++) { #if WASM_ENABLE_FAST_INTERP != 0 bool disable_emit = true; @@ -5264,7 +5529,44 @@ wasm_loader_check_br(WASMLoaderContext *loader_ctx, uint32 depth, #endif PUSH_TYPE(types[i]); } - return true; + +#if WASM_ENABLE_FAST_INTERP != 0 + emit_br_info(target_block); +#endif + + /* Restore the stack data, note that frame_ref_bottom, + frame_reftype_map_bottom, frame_offset_bottom may be + re-allocated in the above push operations */ + if (is_br_table) { + uint32 total_size; + + /* The stack operand num should not be smaller than before + after pop and push operations */ + bh_assert(loader_ctx->stack_cell_num >= stack_cell_num_old); + loader_ctx->stack_cell_num = stack_cell_num_old; + loader_ctx->frame_ref = + loader_ctx->frame_ref_bottom + stack_cell_num_old; + total_size = (uint32)sizeof(uint8) + * (frame_ref_old - frame_ref_after_popped); + bh_memcpy_s((uint8 *)loader_ctx->frame_ref - total_size, total_size, + frame_ref_buf, total_size); + +#if WASM_ENABLE_FAST_INTERP != 0 + /* The stack operand num should not be smaller than before + after pop and push operations */ + bh_assert(loader_ctx->reftype_map_num >= reftype_map_num_old); + loader_ctx->frame_offset = + loader_ctx->frame_offset_bottom + stack_cell_num_old; + total_size = (uint32)sizeof(int16) + * (frame_offset_old - frame_offset_after_popped); + bh_memcpy_s((uint8 *)loader_ctx->frame_offset - total_size, + total_size, frame_offset_buf, total_size); + (loader_ctx->frame_csp - 1)->dynamic_offset = dynamic_offset_old; +#endif + } + + ret = true; + goto cleanup_and_return; } available_stack_cell = @@ -5273,33 +5575,47 @@ wasm_loader_check_br(WASMLoaderContext *loader_ctx, uint32 depth, /* Check stack top values match target block type */ for (i = (int32)arity - 1; i >= 0; i--) { if (!check_stack_top_values(frame_ref, available_stack_cell, types[i], - error_buf, error_buf_size)) - return false; + error_buf, error_buf_size)) { + goto fail; + } cell_num = wasm_value_type_cell_num(types[i]); frame_ref -= cell_num; available_stack_cell -= cell_num; } - return true; +#if WASM_ENABLE_FAST_INTERP != 0 + emit_br_info(target_block); +#endif + ret = true; + +cleanup_and_return: fail: - return false; + if (frame_ref_buf && frame_ref_buf != frame_ref_tmp) + wasm_runtime_free(frame_ref_buf); +#if WASM_ENABLE_FAST_INTERP != 0 + if (frame_offset_buf && frame_offset_buf != frame_offset_tmp) + wasm_runtime_free(frame_offset_tmp); +#endif + + return ret; } static BranchBlock * check_branch_block(WASMLoaderContext *loader_ctx, uint8 **p_buf, uint8 *buf_end, - char *error_buf, uint32 error_buf_size) + bool is_br_table, char *error_buf, uint32 error_buf_size) { uint8 *p = *p_buf, *p_end = buf_end; BranchBlock *frame_csp_tmp; uint32 depth; read_leb_uint32(p, p_end, depth); - CHECK_BR(depth); + if (!wasm_loader_check_br(loader_ctx, depth, is_br_table, error_buf, + error_buf_size)) { + goto fail; + } + frame_csp_tmp = loader_ctx->frame_csp - depth - 1; -#if WASM_ENABLE_FAST_INTERP != 0 - emit_br_info(frame_csp_tmp); -#endif *p_buf = p; return frame_csp_tmp; @@ -5392,7 +5708,7 @@ copy_params_to_dynamic_space(WASMLoaderContext *loader_ctx, bool is_if_block, uint32 i; BranchBlock *block = loader_ctx->frame_csp - 1; BlockType *block_type = &block->block_type; - WASMType *wasm_type = block_type->u.type; + WASMFuncType *wasm_type = block_type->u.type; uint32 param_count = block_type->u.type->param_count; int16 condition_offset = 0; bool disable_emit = false; @@ -5636,7 +5952,7 @@ re_scan: * 0x40/0x7F/0x7E/0x7D/0x7C, take it as the type of * the single return value. */ block_type.is_value_type = true; - block_type.u.value_type = value_type; + block_type.u.value_type.type = value_type; } else { uint32 type_index; @@ -5657,7 +5973,7 @@ re_scan: /* Pop block parameters from stack */ if (BLOCK_HAS_PARAM(block_type)) { - WASMType *wasm_type = block_type.u.type; + WASMFuncType *wasm_type = block_type.u.type; BranchBlock *cur_block = loader_ctx->frame_csp - 1; #if WASM_ENABLE_FAST_INTERP != 0 @@ -5705,8 +6021,15 @@ re_scan: * Since the stack is already in polymorphic state, * the opcode will not be executed, so the dummy * offset won't cause any error */ - *loader_ctx->frame_offset++ = 0; - if (cell_num > 1) { + uint32 n; + + for (n = 0; n < cell_num; n++) { + if (loader_ctx->p_code_compiled == NULL) { + if (!check_offset_push(loader_ctx, + error_buf, + error_buf_size)) + goto fail; + } *loader_ctx->frame_offset++ = 0; } } @@ -5860,19 +6183,11 @@ re_scan: uint32 block_param_count = 0, block_ret_count = 0; uint8 *block_param_types = NULL, *block_ret_types = NULL; BlockType *cur_block_type = &cur_block->block_type; - if (cur_block_type->is_value_type) { - if (cur_block_type->u.value_type != VALUE_TYPE_VOID) { - block_ret_count = 1; - block_ret_types = &cur_block_type->u.value_type; - } - } - else { - block_param_count = cur_block_type->u.type->param_count; - block_ret_count = cur_block_type->u.type->result_count; - block_param_types = cur_block_type->u.type->types; - block_ret_types = - cur_block_type->u.type->types + block_param_count; - } + + block_param_count = block_type_get_param_types( + cur_block_type, &block_param_types); + block_ret_count = block_type_get_result_types( + cur_block_type, &block_ret_types); bh_assert(block_param_count == block_ret_count && (!block_param_count || !memcmp(block_param_types, block_ret_types, @@ -5880,6 +6195,7 @@ re_scan: (void)block_ret_types; (void)block_ret_count; (void)block_param_types; + (void)block_param_count; } POP_CSP(); @@ -5917,8 +6233,9 @@ re_scan: case WASM_OP_BR: { - if (!(frame_csp_tmp = check_branch_block( - loader_ctx, &p, p_end, error_buf, error_buf_size))) + if (!(frame_csp_tmp = + check_branch_block(loader_ctx, &p, p_end, false, + error_buf, error_buf_size))) goto fail; RESET_STACK(); @@ -5930,8 +6247,9 @@ re_scan: { POP_I32(); - if (!(frame_csp_tmp = check_branch_block( - loader_ctx, &p, p_end, error_buf, error_buf_size))) + if (!(frame_csp_tmp = + check_branch_block(loader_ctx, &p, p_end, false, + error_buf, error_buf_size))) goto fail; break; @@ -5960,7 +6278,7 @@ re_scan: #endif for (i = 0; i <= count; i++) { if (!(frame_csp_tmp = - check_branch_block(loader_ctx, &p, p_end, + check_branch_block(loader_ctx, &p, p_end, true, error_buf, error_buf_size))) goto fail; @@ -6042,7 +6360,7 @@ re_scan: case WASM_OP_RETURN_CALL: #endif { - WASMType *func_type; + WASMFuncType *func_type; uint32 func_idx; int32 idx; @@ -6114,7 +6432,7 @@ re_scan: #endif { int32 idx; - WASMType *func_type; + WASMFuncType *func_type; uint32 type_idx, table_idx; bh_assert(module->import_table_count + module->table_count > 0); @@ -6530,8 +6848,9 @@ re_scan: is passive, active or declarative. */ for (i = 0; i < module->table_seg_count; i++, table_seg++) { if (table_seg->elem_type == VALUE_TYPE_FUNCREF) { - for (j = 0; j < table_seg->function_count; j++) { - if (table_seg->func_indexes[j] == func_idx) { + for (j = 0; j < table_seg->value_count; j++) { + if (table_seg->init_values[j].u.ref_index + == func_idx) { func_declared = true; break; } @@ -6593,7 +6912,6 @@ re_scan: { p_org = p - 1; GET_LOCAL_INDEX_TYPE_AND_OFFSET(); - POP_TYPE(local_type); #if WASM_ENABLE_FAST_INTERP != 0 if (!(preserve_referenced_local( @@ -6647,6 +6965,7 @@ re_scan: } #endif #endif + POP_TYPE(local_type); break; } diff --git a/core/iwasm/interpreter/wasm_opcode.h b/core/iwasm/interpreter/wasm_opcode.h index 4f8a6a695..98e5b1325 100644 --- a/core/iwasm/interpreter/wasm_opcode.h +++ b/core/iwasm/interpreter/wasm_opcode.h @@ -35,9 +35,9 @@ typedef enum WASMOpcode { WASM_OP_CALL_INDIRECT = 0x11, /* call_indirect */ WASM_OP_RETURN_CALL = 0x12, /* return_call */ WASM_OP_RETURN_CALL_INDIRECT = 0x13, /* return_call_indirect */ + WASM_OP_CALL_REF = 0x14, /* call_ref */ + WASM_OP_RETURN_CALL_REF = 0x15, /* return_call_ref */ - WASM_OP_UNUSED_0x14 = 0x14, - WASM_OP_UNUSED_0x15 = 0x15, WASM_OP_UNUSED_0x16 = 0x16, WASM_OP_UNUSED_0x17 = 0x17, @@ -259,27 +259,124 @@ typedef enum WASMOpcode { WASM_OP_IMPDEP = 0xcf, - WASM_OP_REF_NULL = 0xd0, /* ref.null */ - WASM_OP_REF_IS_NULL = 0xd1, /* ref.is_null */ - WASM_OP_REF_FUNC = 0xd2, /* ref.func */ + WASM_OP_REF_NULL = 0xd0, /* ref.null */ + WASM_OP_REF_IS_NULL = 0xd1, /* ref.is_null */ + WASM_OP_REF_FUNC = 0xd2, /* ref.func */ + WASM_OP_REF_EQ = 0xd3, /* ref.eq */ + WASM_OP_REF_AS_NON_NULL = 0xd4, /* ref.as_non_null */ + WASM_OP_BR_ON_NULL = 0xd5, /* br_on_null */ + WASM_OP_BR_ON_NON_NULL = 0xd6, /* br_on_non_null */ - EXT_OP_BLOCK = 0xd3, /* block with blocktype */ - EXT_OP_LOOP = 0xd4, /* loop with blocktype */ - EXT_OP_IF = 0xd5, /* if with blocktype */ - EXT_OP_BR_TABLE_CACHE = 0xd6, /* br_table from cache */ + EXT_OP_BLOCK = 0xd7, /* block with blocktype */ + EXT_OP_LOOP = 0xd8, /* loop with blocktype */ + EXT_OP_IF = 0xd9, /* if with blocktype */ + EXT_OP_BR_TABLE_CACHE = 0xda, /* br_table from cache */ - EXT_OP_TRY = 0xd7, /* try block with blocktype */ + EXT_OP_TRY = 0xdb, /* try block with blocktype */ #if WASM_ENABLE_DEBUG_INTERP != 0 - DEBUG_OP_BREAK = 0xd8, /* debug break point */ + DEBUG_OP_BREAK = 0xdc, /* debug break point */ #endif /* Post-MVP extend op prefix */ + WASM_OP_GC_PREFIX = 0xfb, WASM_OP_MISC_PREFIX = 0xfc, WASM_OP_SIMD_PREFIX = 0xfd, WASM_OP_ATOMIC_PREFIX = 0xfe, } WASMOpcode; +typedef enum WASMGCEXTOpcode { + WASM_OP_STRUCT_NEW = 0x00, /* struct.new */ + WASM_OP_STRUCT_NEW_DEFAULT = 0x01, /* struct.new_default */ + WASM_OP_STRUCT_GET = 0x02, /* struct.get */ + WASM_OP_STRUCT_GET_S = 0x03, /* struct.get_s */ + WASM_OP_STRUCT_GET_U = 0x04, /* struct.get_u */ + WASM_OP_STRUCT_SET = 0x05, /* struct.set */ + + WASM_OP_ARRAY_NEW = 0x06, /* array.new */ + WASM_OP_ARRAY_NEW_DEFAULT = 0x07, /* array.new_default */ + WASM_OP_ARRAY_NEW_FIXED = 0x08, /* array.new_fixed */ + WASM_OP_ARRAY_NEW_DATA = 0x09, /* array.new_data */ + WASM_OP_ARRAY_NEW_ELEM = 0x0A, /* array.new_elem */ + WASM_OP_ARRAY_GET = 0x0B, /* array.get */ + WASM_OP_ARRAY_GET_S = 0x0C, /* array.get_s */ + WASM_OP_ARRAY_GET_U = 0x0D, /* array.get_u */ + WASM_OP_ARRAY_SET = 0x0E, /* array.set */ + WASM_OP_ARRAY_LEN = 0x0F, /* array.len */ + WASM_OP_ARRAY_FILL = 0x10, /* array.fill */ + WASM_OP_ARRAY_COPY = 0x11, /* array.copy */ + WASM_OP_ARRAY_INIT_DATA = 0x12, + /* array.init_data */ /* TODO */ + WASM_OP_ARRAY_INIT_ELEM = 0x13, + /* array.init_elem */ /* TODO */ + + WASM_OP_REF_TEST = 0x14, /* ref.test */ + WASM_OP_REF_TEST_NULLABLE = 0x15, /* ref.test_nullable */ + WASM_OP_REF_CAST = 0x16, /* ref.cast */ + WASM_OP_REF_CAST_NULLABLE = 0x17, /* ref.cast_nullable */ + + WASM_OP_BR_ON_CAST = 0x18, /* br_on_cast */ + WASM_OP_BR_ON_CAST_FAIL = 0x19, /* br_on_cast_fail */ + + WASM_OP_ANY_CONVERT_EXTERN = 0x1A, /* any.convert_extern */ + WASM_OP_EXTERN_CONVERT_ANY = 0x1B, /* extern.covert_any */ + + WASM_OP_REF_I31 = 0x1C, /* ref.i31 */ + WASM_OP_I31_GET_S = 0x1D, /* i31.get_s */ + WASM_OP_I31_GET_U = 0x1E, /* i31.get_u */ + + /* stringref related opcoded */ + WASM_OP_STRING_NEW_UTF8 = 0x80, /* string.new_utf8 */ + WASM_OP_STRING_NEW_WTF16 = 0x81, /* string.new_wtf16 */ + WASM_OP_STRING_CONST = 0x82, /* string.const */ + WASM_OP_STRING_MEASURE_UTF8 = 0x83, /* string.measure_utf8 */ + WASM_OP_STRING_MEASURE_WTF8 = 0x84, /* string.measure_wtf8 */ + WASM_OP_STRING_MEASURE_WTF16 = 0x85, /* string.measure_wtf16 */ + WASM_OP_STRING_ENCODE_UTF8 = 0x86, /* string.encode_utf8 */ + WASM_OP_STRING_ENCODE_WTF16 = 0x87, /* string.encode_wtf16 */ + WASM_OP_STRING_CONCAT = 0x88, /* string.concat */ + WASM_OP_STRING_EQ = 0x89, /* string.eq */ + WASM_OP_STRING_IS_USV_SEQUENCE = 0x8a, /* string.is_usv_sequence */ + WASM_OP_STRING_NEW_LOSSY_UTF8 = 0x8b, /* string.new_lossy_utf8 */ + WASM_OP_STRING_NEW_WTF8 = 0x8c, /* string.new_wtf8 */ + WASM_OP_STRING_ENCODE_LOSSY_UTF8 = 0x8d, /* string.encode_lossy_utf8 */ + WASM_OP_STRING_ENCODE_WTF8 = 0x8e, /* string.encode_wtf8 */ + + WASM_OP_STRING_AS_WTF8 = 0x90, /* string.as_wtf8 */ + WASM_OP_STRINGVIEW_WTF8_ADVANCE = 0x91, /* stringview_wtf8.advance */ + WASM_OP_STRINGVIEW_WTF8_ENCODE_UTF8 = + 0x92, /* stringview_wtf8.encode_utf8 */ + WASM_OP_STRINGVIEW_WTF8_SLICE = 0x93, /* stringview_wtf8.slice */ + WASM_OP_STRINGVIEW_WTF8_ENCODE_LOSSY_UTF8 = + 0x94, /* stringview_wtf8.encode_lossy_utf8 */ + WASM_OP_STRINGVIEW_WTF8_ENCODE_WTF8 = + 0x95, /* stringview_wtf8.encode_wtf8 */ + + WASM_OP_STRING_AS_WTF16 = 0x98, /* string.as_wtf16 */ + WASM_OP_STRINGVIEW_WTF16_LENGTH = 0x99, /* stringview_wtf16.length */ + WASM_OP_STRINGVIEW_WTF16_GET_CODEUNIT = + 0x9a, /* stringview_wtf16.get_codeunit */ + WASM_OP_STRINGVIEW_WTF16_ENCODE = 0x9b, /* stringview_wtf16.encode */ + WASM_OP_STRINGVIEW_WTF16_SLICE = 0x9c, /* stringview_wtf16.slice */ + + WASM_OP_STRING_AS_ITER = 0xa0, /* string.as_iter */ + WASM_OP_STRINGVIEW_ITER_NEXT = 0xa1, /* stringview_iter.next */ + WASM_OP_STRINGVIEW_ITER_ADVANCE = 0xa2, /* stringview_iter.advance */ + WASM_OP_STRINGVIEW_ITER_REWIND = 0xa3, /* stringview_iter.rewind */ + WASM_OP_STRINGVIEW_ITER_SLICE = 0xa4, /* stringview_iter.slice */ + + WASM_OP_STRING_NEW_UTF8_ARRAY = 0xb0, /* string.new_utf8_array */ + WASM_OP_STRING_NEW_WTF16_ARRAY = 0xb1, /* string.new_wtf16_array */ + WASM_OP_STRING_ENCODE_UTF8_ARRAY = 0xb2, /* string.encode_utf8_array */ + WASM_OP_STRING_ENCODE_WTF16_ARRAY = 0xb3, /* string.encode_wtf16_array */ + WASM_OP_STRING_NEW_LOSSY_UTF8_ARRAY = + 0xb4, /* string.new_lossy_utf8_array */ + WASM_OP_STRING_NEW_WTF8_ARRAY = 0xb5, /* string.new_wtf8_array */ + WASM_OP_STRING_ENCODE_LOSSY_UTF8_ARRAY = + 0xb6, /* string.encode_lossy_utf8_array */ + WASM_OP_STRING_ENCODE_WTF8_ARRAY = 0xb7, /* string.encode_wtf8_array */ +} WASMGCEXTOpcode; + typedef enum WASMMiscEXTOpcode { WASM_OP_I32_TRUNC_SAT_S_F32 = 0x00, WASM_OP_I32_TRUNC_SAT_U_F32 = 0x01, @@ -678,7 +775,7 @@ typedef enum WASMAtomicEXTOpcode { #if WASM_ENABLE_DEBUG_INTERP != 0 #define DEF_DEBUG_BREAK_HANDLE() \ - [DEBUG_OP_BREAK] = HANDLE_OPCODE(DEBUG_OP_BREAK), /* 0xd7 */ + [DEBUG_OP_BREAK] = HANDLE_OPCODE(DEBUG_OP_BREAK), /* 0xdb */ #else #define DEF_DEBUG_BREAK_HANDLE() #endif @@ -719,8 +816,8 @@ typedef enum WASMAtomicEXTOpcode { HANDLE_OPCODE(WASM_OP_CALL_INDIRECT), /* 0x11 */ \ HANDLE_OPCODE(WASM_OP_RETURN_CALL), /* 0x12 */ \ HANDLE_OPCODE(WASM_OP_RETURN_CALL_INDIRECT), /* 0x13 */ \ - HANDLE_OPCODE(WASM_OP_UNUSED_0x14), /* 0x14 */ \ - HANDLE_OPCODE(WASM_OP_UNUSED_0x15), /* 0x15 */ \ + HANDLE_OPCODE(WASM_OP_CALL_REF), /* 0x14 */ \ + HANDLE_OPCODE(WASM_OP_RETURN_CALL_REF), /* 0x15 */ \ HANDLE_OPCODE(WASM_OP_UNUSED_0x16), /* 0x16 */ \ HANDLE_OPCODE(WASM_OP_UNUSED_0x17), /* 0x17 */ \ HANDLE_OPCODE(WASM_OP_DELEGATE), /* 0x18 */ \ @@ -910,11 +1007,16 @@ typedef enum WASMAtomicEXTOpcode { HANDLE_OPCODE(WASM_OP_REF_NULL), /* 0xd0 */ \ HANDLE_OPCODE(WASM_OP_REF_IS_NULL), /* 0xd1 */ \ HANDLE_OPCODE(WASM_OP_REF_FUNC), /* 0xd2 */ \ - HANDLE_OPCODE(EXT_OP_BLOCK), /* 0xd3 */ \ - HANDLE_OPCODE(EXT_OP_LOOP), /* 0xd4 */ \ - HANDLE_OPCODE(EXT_OP_IF), /* 0xd5 */ \ - HANDLE_OPCODE(EXT_OP_BR_TABLE_CACHE), /* 0xd6 */ \ - HANDLE_OPCODE(EXT_OP_TRY), /* 0xd7 */ \ + HANDLE_OPCODE(WASM_OP_REF_EQ), /* 0xd3 */ \ + HANDLE_OPCODE(WASM_OP_REF_AS_NON_NULL), /* 0xd4 */ \ + HANDLE_OPCODE(WASM_OP_BR_ON_NULL), /* 0xd5 */ \ + HANDLE_OPCODE(WASM_OP_BR_ON_NON_NULL), /* 0xd6 */ \ + HANDLE_OPCODE(EXT_OP_BLOCK), /* 0xd7 */ \ + HANDLE_OPCODE(EXT_OP_LOOP), /* 0xd8 */ \ + HANDLE_OPCODE(EXT_OP_IF), /* 0xd9 */ \ + HANDLE_OPCODE(EXT_OP_BR_TABLE_CACHE), /* 0xda */ \ + HANDLE_OPCODE(EXT_OP_TRY), /* 0xdb */ \ + SET_GOTO_TABLE_ELEM(WASM_OP_GC_PREFIX), /* 0xfb */ \ SET_GOTO_TABLE_ELEM(WASM_OP_MISC_PREFIX), /* 0xfc */ \ SET_GOTO_TABLE_SIMD_PREFIX_ELEM() /* 0xfd */ \ SET_GOTO_TABLE_ELEM(WASM_OP_ATOMIC_PREFIX), /* 0xfe */ \ diff --git a/core/iwasm/interpreter/wasm_runtime.c b/core/iwasm/interpreter/wasm_runtime.c index 003ceb1f5..a75a204bb 100644 --- a/core/iwasm/interpreter/wasm_runtime.c +++ b/core/iwasm/interpreter/wasm_runtime.c @@ -4,6 +4,7 @@ */ #include "wasm_runtime.h" +#include "wasm.h" #include "wasm_loader.h" #include "wasm_interp.h" #include "bh_common.h" @@ -11,6 +12,9 @@ #include "mem_alloc.h" #include "../common/wasm_runtime_common.h" #include "../common/wasm_memory.h" +#if WASM_ENABLE_GC != 0 +#include "../common/gc/gc_object.h" +#endif #if WASM_ENABLE_SHARED_MEMORY != 0 #include "../common/wasm_shared_memory.h" #endif @@ -115,9 +119,6 @@ static void memories_deinstantiate(WASMModuleInstance *module_inst, WASMMemoryInstance **memories, uint32 count) { -#ifdef WASM_LINEAR_MEMORY_MMAP - uint64 map_size; -#endif uint32 i; if (memories) { for (i = 0; i < count; i++) { @@ -144,23 +145,7 @@ memories_deinstantiate(WASMModuleInstance *module_inst, memories[i]->heap_handle = NULL; } if (memories[i]->memory_data) { -#ifndef OS_ENABLE_HW_BOUND_CHECK -#ifdef WASM_LINEAR_MEMORY_MMAP - if (shared_memory_is_shared(memories[i])) { - map_size = (uint64)memories[i]->num_bytes_per_page - * memories[i]->max_page_count; - wasm_munmap_linear_memory(memories[i]->memory_data, - map_size, map_size); - } - else -#endif - wasm_runtime_free(memories[i]->memory_data); -#else - map_size = (uint64)memories[i]->num_bytes_per_page - * memories[i]->cur_page_count; - wasm_munmap_linear_memory(memories[i]->memory_data, - map_size, 8 * (uint64)BH_GB); -#endif + wasm_deallocate_linear_memory(memories[i]); } } } @@ -182,13 +167,10 @@ memory_instantiate(WASMModuleInstance *module_inst, WASMModuleInstance *parent, uint32 inc_page_count, aux_heap_base, global_idx; uint32 bytes_of_last_page, bytes_to_page_end; uint8 *global_addr; -#ifdef WASM_LINEAR_MEMORY_MMAP - uint8 *mapped_mem = NULL; - uint64 map_size; -#endif + bool is_shared_memory = false; #if WASM_ENABLE_SHARED_MEMORY != 0 - bool is_shared_memory = flags & 0x02 ? true : false; + is_shared_memory = flags & 0x02 ? true : false; /* shared memory */ if (is_shared_memory && parent != NULL) { @@ -197,6 +179,10 @@ memory_instantiate(WASMModuleInstance *module_inst, WASMModuleInstance *parent, shared_memory_inc_reference(memory); return memory; } +#else + (void)parent; + (void)memory_idx; + (void)flags; #endif /* end of WASM_ENABLE_SHARED_MEMORY */ if (heap_size > 0 && module_inst->module->malloc_function != (uint32)-1 @@ -296,57 +282,20 @@ memory_instantiate(WASMModuleInstance *module_inst, WASMModuleInstance *parent, num_bytes_per_page, init_page_count, max_page_count); LOG_VERBOSE(" heap offset: %u, heap size: %d\n", heap_offset, heap_size); - memory_data_size = (uint64)num_bytes_per_page * init_page_count; max_memory_data_size = (uint64)num_bytes_per_page * max_page_count; - bh_assert(memory_data_size <= UINT32_MAX); bh_assert(max_memory_data_size <= 4 * (uint64)BH_GB); (void)max_memory_data_size; bh_assert(memory != NULL); -#ifndef OS_ENABLE_HW_BOUND_CHECK -#if WASM_ENABLE_SHARED_MEMORY != 0 - if (is_shared_memory) { - /* Allocate maximum memory size when memory is shared */ -#if WASM_ENABLE_SHARED_MEMORY_MMAP != 0 - map_size = max_memory_data_size; - if (max_memory_data_size > 0 - && !(memory->memory_data = mapped_mem = - wasm_mmap_linear_memory(map_size, &max_memory_data_size, - error_buf, error_buf_size))) { - goto fail1; - } -#else - if (max_memory_data_size > 0 - && !(memory->memory_data = runtime_malloc( - max_memory_data_size, error_buf, error_buf_size))) { - goto fail1; - } -#endif + if (wasm_allocate_linear_memory(&memory->memory_data, is_shared_memory, + num_bytes_per_page, init_page_count, + max_page_count, &memory_data_size) + != BHT_OK) { + set_error_buf(error_buf, error_buf_size, + "allocate linear memory failed"); + return NULL; } - else -#endif /* end of WASM_ENABLE_SHARED_MEMORY != 0 */ - { - /* Allocate initial memory size when memory is not shared */ - if (memory_data_size > 0 - && !(memory->memory_data = runtime_malloc( - memory_data_size, error_buf, error_buf_size))) { - goto fail1; - } - } -#else /* else of OS_ENABLE_HW_BOUND_CHECK */ - /* Totally 8G is mapped, the opcode load/store address range is 0 to 8G: - * ea = i + memarg.offset - * both i and memarg.offset are u32 in range 0 to 4G - * so the range of ea is 0 to 8G - */ - map_size = 8 * (uint64)BH_GB; - if (!(memory->memory_data = mapped_mem = wasm_mmap_linear_memory( - map_size, &memory_data_size, error_buf, error_buf_size))) { - set_error_buf(error_buf, error_buf_size, "mmap memory failed"); - goto fail1; - } -#endif /* end of OS_ENABLE_HW_BOUND_CHECK */ memory->module_type = Wasm_Module_Bytecode; memory->num_bytes_per_page = num_bytes_per_page; @@ -364,13 +313,13 @@ memory_instantiate(WASMModuleInstance *module_inst, WASMModuleInstance *parent, if (!(memory->heap_handle = runtime_malloc( (uint64)heap_struct_size, error_buf, error_buf_size))) { - goto fail2; + goto fail1; } if (!mem_allocator_create_with_struct_and_pool( memory->heap_handle, heap_struct_size, memory->heap_data, heap_size)) { set_error_buf(error_buf, error_buf_size, "init app heap failed"); - goto fail3; + goto fail2; } } @@ -388,20 +337,13 @@ memory_instantiate(WASMModuleInstance *module_inst, WASMModuleInstance *parent, LOG_VERBOSE("Memory instantiate success."); return memory; -fail3: +fail2: if (heap_size > 0) wasm_runtime_free(memory->heap_handle); -fail2: -#ifdef WASM_LINEAR_MEMORY_MMAP - if (mapped_mem) - wasm_munmap_linear_memory(mapped_mem, memory_data_size, map_size); - else -#endif - { - if (memory->memory_data) - wasm_runtime_free(memory->memory_data); - } fail1: + if (memory->memory_data) + wasm_deallocate_linear_memory(memory); + return NULL; } @@ -567,23 +509,37 @@ tables_instantiate(const WASMModule *module, WASMModuleInstance *module_inst, /* it is a built-in table, every module has its own */ total_size = offsetof(WASMTableInstance, elems); - total_size += (uint64)max_size_fixed * sizeof(uint32); + /* store function indexes for non-gc, object pointers for gc */ + total_size += (uint64)sizeof(table_elem_type_t) * max_size_fixed; } tables[table_index++] = table; +#if WASM_ENABLE_GC == 0 /* Set all elements to -1 to mark them as uninitialized elements */ memset(table, -1, (uint32)total_size); +#else + /* For GC, all elements have already been set to NULL_REF (0) as + uninitialized elements */ +#endif #if WASM_ENABLE_MULTI_MODULE != 0 *table_linked = table_inst_linked; if (table_inst_linked != NULL) { +#if WASM_ENABLE_GC != 0 + table->elem_type = table_inst_linked->elem_type; + table->elem_ref_type = table_inst_linked->elem_ref_type; +#endif table->cur_size = table_inst_linked->cur_size; table->max_size = table_inst_linked->max_size; } else #endif { +#if WASM_ENABLE_GC != 0 + table->elem_type = import->u.table.elem_type; + table->elem_ref_type.elem_ref_type = import->u.table.elem_ref_type; +#endif table->cur_size = import->u.table.init_size; table->max_size = max_size_fixed; } @@ -607,12 +563,27 @@ tables_instantiate(const WASMModule *module, WASMModuleInstance *module_inst, ? module->tables[i].max_size : module->tables[i].init_size; #endif - total_size += sizeof(uint32) * (uint64)max_size_fixed; +#if WASM_ENABLE_GC == 0 + /* Store function indexes */ + total_size += sizeof(uintptr_t) * (uint64)max_size_fixed; +#else + /* Store object pointers */ + total_size += sizeof(uintptr_t) * (uint64)max_size_fixed; +#endif tables[table_index++] = table; +#if WASM_ENABLE_GC == 0 /* Set all elements to -1 to mark them as uninitialized elements */ memset(table, -1, (uint32)total_size); +#else + /* For GC, all elements have already been set to NULL_REF (0) as + uninitialized elements */ +#endif +#if WASM_ENABLE_GC != 0 + table->elem_type = module->tables[i].elem_type; + table->elem_ref_type.elem_ref_type = module->tables[i].elem_ref_type; +#endif table->cur_size = module->tables[i].init_size; table->max_size = max_size_fixed; @@ -633,7 +604,7 @@ fail: * Destroy function instances. */ static void -functions_deinstantiate(WASMFunctionInstance *functions, uint32 count) +functions_deinstantiate(WASMFunctionInstance *functions) { if (functions) { wasm_runtime_free(functions); @@ -825,7 +796,7 @@ fail: return NULL; #endif } -#endif +#endif /* end of WASM_ENABLE_TAGS != 0 */ /** * Destroy global instances. @@ -847,6 +818,7 @@ check_global_init_expr(const WASMModule *module, uint32 global_index, return false; } +#if WASM_ENABLE_GC == 0 /** * Currently, constant expressions occurring as initializers of * globals are further constrained in that contained global.get @@ -860,6 +832,7 @@ check_global_init_expr(const WASMModule *module, uint32 global_index, "constant expression required"); return false; } +#endif return true; } @@ -868,7 +841,7 @@ check_global_init_expr(const WASMModule *module, uint32 global_index, * Instantiate globals in a module. */ static WASMGlobalInstance * -globals_instantiate(const WASMModule *module, WASMModuleInstance *module_inst, +globals_instantiate(WASMModule *module, WASMModuleInstance *module_inst, char *error_buf, uint32 error_buf_size) { WASMImport *import; @@ -888,6 +861,9 @@ globals_instantiate(const WASMModule *module, WASMModuleInstance *module_inst, WASMGlobalImport *global_import = &import->u.global; global->type = global_import->type; global->is_mutable = global_import->is_mutable; +#if WASM_ENABLE_GC != 0 + global->ref_type = global_import->ref_type; +#endif #if WASM_ENABLE_MULTI_MODULE != 0 if (global_import->import_module) { if (!(global->import_module_inst = get_sub_module_inst( @@ -928,6 +904,7 @@ globals_instantiate(const WASMModule *module, WASMModuleInstance *module_inst, /* instantiate globals from global section */ for (i = 0; i < module->global_count; i++) { InitializerExpression *init_expr = &(module->globals[i].init_expr); + uint8 flag = init_expr->init_expr_type; global->type = module->globals[i].type; global->is_mutable = module->globals[i].is_mutable; @@ -936,27 +913,148 @@ globals_instantiate(const WASMModule *module, WASMModuleInstance *module_inst, #endif global->data_offset = global_data_offset; global_data_offset += wasm_value_type_size(global->type); - - if (init_expr->init_expr_type == INIT_EXPR_TYPE_GET_GLOBAL) { - if (!check_global_init_expr(module, init_expr->u.global_index, - error_buf, error_buf_size)) { - goto fail; - } - - bh_memcpy_s( - &(global->initial_value), sizeof(WASMValue), - &(globals[init_expr->u.global_index].initial_value), - sizeof(globals[init_expr->u.global_index].initial_value)); - } -#if WASM_ENABLE_REF_TYPES != 0 - else if (init_expr->init_expr_type == INIT_EXPR_TYPE_REFNULL_CONST) { - global->initial_value.u32 = (uint32)NULL_REF; - } +#if WASM_ENABLE_GC != 0 + global->ref_type = module->globals[i].ref_type; #endif - else { - bh_memcpy_s(&(global->initial_value), sizeof(WASMValue), - &(init_expr->u), sizeof(init_expr->u)); + + switch (flag) { + case INIT_EXPR_TYPE_GET_GLOBAL: + { + if (!check_global_init_expr(module, init_expr->u.global_index, + error_buf, error_buf_size)) { + goto fail; + } + + bh_memcpy_s( + &(global->initial_value), sizeof(WASMValue), + &(globals[init_expr->u.global_index].initial_value), + sizeof(globals[init_expr->u.global_index].initial_value)); + break; + } +#if WASM_ENABLE_GC != 0 + case INIT_EXPR_TYPE_STRUCT_NEW: + case INIT_EXPR_TYPE_STRUCT_NEW_DEFAULT: + { + WASMRttType *rtt_type; + WASMStructObjectRef struct_obj; + WASMStructType *struct_type; + WASMStructNewInitValues *init_values = NULL; + uint32 type_idx; + + if (flag == INIT_EXPR_TYPE_STRUCT_NEW) { + init_values = (WASMStructNewInitValues *)init_expr->u.data; + type_idx = init_values->type_idx; + } + else { + type_idx = init_expr->u.type_index; + } + + struct_type = (WASMStructType *)module->types[type_idx]; + + if (!(rtt_type = wasm_rtt_type_new( + (WASMType *)struct_type, type_idx, module->rtt_types, + module->type_count, &module->rtt_type_lock))) { + set_error_buf(error_buf, error_buf_size, + "create rtt object failed"); + goto fail; + } + + if (!(struct_obj = wasm_struct_obj_new_internal( + module_inst->e->common.gc_heap_handle, rtt_type))) { + set_error_buf(error_buf, error_buf_size, + "create struct object failed"); + goto fail; + } + + if (flag == INIT_EXPR_TYPE_STRUCT_NEW) { + uint32 field_idx; + + bh_assert(init_values->count == struct_type->field_count); + + for (field_idx = 0; field_idx < init_values->count; + field_idx++) { + wasm_struct_obj_set_field( + struct_obj, field_idx, + &init_values->fields[field_idx]); + } + } + + global->initial_value.gc_obj = (void *)struct_obj; + break; + } + case INIT_EXPR_TYPE_ARRAY_NEW: + case INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT: + case INIT_EXPR_TYPE_ARRAY_NEW_FIXED: + { + WASMRttType *rtt_type; + WASMArrayObjectRef array_obj; + WASMArrayType *array_type; + WASMArrayNewInitValues *init_values = NULL; + WASMValue *arr_init_val = NULL, empty_val = { 0 }; + uint32 type_idx, len; + + if (flag == INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT) { + type_idx = init_expr->u.array_new_default.type_index; + len = init_expr->u.array_new_default.length; + arr_init_val = &empty_val; + } + else { + init_values = (WASMArrayNewInitValues *)init_expr->u.data; + type_idx = init_values->type_idx; + len = init_values->length; + + if (flag == INIT_EXPR_TYPE_ARRAY_NEW) { + arr_init_val = init_values->elem_data; + } + } + + array_type = (WASMArrayType *)module->types[type_idx]; + + if (!(rtt_type = wasm_rtt_type_new( + (WASMType *)array_type, type_idx, module->rtt_types, + module->type_count, &module->rtt_type_lock))) { + set_error_buf(error_buf, error_buf_size, + "create rtt object failed"); + goto fail; + } + + if (!(array_obj = wasm_array_obj_new_internal( + module_inst->e->common.gc_heap_handle, rtt_type, len, + arr_init_val))) { + set_error_buf(error_buf, error_buf_size, + "create array object failed"); + goto fail; + } + + if (flag == INIT_EXPR_TYPE_ARRAY_NEW_FIXED) { + uint32 elem_idx; + + bh_assert(init_values); + + for (elem_idx = 0; elem_idx < len; elem_idx++) { + wasm_array_obj_set_elem( + array_obj, elem_idx, + &init_values->elem_data[elem_idx]); + } + } + + global->initial_value.gc_obj = (void *)array_obj; + + break; + } + case INIT_EXPR_TYPE_I31_NEW: + { + global->initial_value.gc_obj = + (wasm_obj_t)wasm_i31_obj_new(init_expr->u.i32); + break; + } +#endif /* end of WASM_ENABLE_GC != 0 */ + default: + bh_memcpy_s(&(global->initial_value), sizeof(WASMValue), + &(init_expr->u), sizeof(init_expr->u)); + break; } + global++; } @@ -1070,7 +1168,7 @@ export_tags_instantiate(const WASMModule *module, bh_assert((uint32)(export_tag - export_tags) == export_tag_count); return export_tags; } -#endif +#endif /* end of WASM_ENABLE_TAGS != 0 */ #if WASM_ENABLE_MULTI_MODULE != 0 static void @@ -1114,7 +1212,7 @@ lookup_post_instantiate_func(WASMModuleInstance *module_inst, const char *func_name) { WASMFunctionInstance *func; - WASMType *func_type; + WASMFuncType *func_type; if (!(func = wasm_lookup_function(module_inst, func_name, NULL))) /* Not found */ @@ -1495,12 +1593,12 @@ init_func_ptrs(WASMModuleInstance *module_inst, WASMModule *module, #if WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0 static uint32 -get_smallest_type_idx(WASMModule *module, WASMType *func_type) +get_smallest_type_idx(WASMModule *module, WASMFuncType *func_type) { uint32 i; for (i = 0; i < module->type_count; i++) { - if (func_type == module->types[i]) + if (func_type == (WASMFuncType *)module->types[i]) return i; } @@ -1523,9 +1621,9 @@ init_func_type_indexes(WASMModuleInstance *module_inst, char *error_buf, for (i = 0; i < module_inst->e->function_count; i++) { WASMFunctionInstance *func_inst = module_inst->e->functions + i; - WASMType *func_type = func_inst->is_import_func - ? func_inst->u.func_import->func_type - : func_inst->u.func->func_type; + WASMFuncType *func_type = func_inst->is_import_func + ? func_inst->u.func_import->func_type + : func_inst->u.func->func_type; module_inst->func_type_indexes[i] = get_smallest_type_idx(module_inst->module, func_type); } @@ -1534,6 +1632,134 @@ init_func_type_indexes(WASMModuleInstance *module_inst, char *error_buf, } #endif /* end of WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0 */ +#if WASM_ENABLE_GC != 0 +void * +wasm_create_func_obj(WASMModuleInstance *module_inst, uint32 func_idx, + bool throw_exce, char *error_buf, uint32 error_buf_size) +{ + WASMModule *module = module_inst->module; + WASMRttTypeRef rtt_type; + WASMFuncObjectRef func_obj; + WASMFunctionInstance *func_inst; + WASMFuncType *func_type; + uint32 type_idx; + + if (throw_exce) { + error_buf = module_inst->cur_exception; + error_buf_size = sizeof(module_inst->cur_exception); + } + + if (func_idx >= module_inst->e->function_count) { + set_error_buf_v(error_buf, error_buf_size, "unknown function %d", + func_idx); + return NULL; + } + + func_inst = &module_inst->e->functions[func_idx]; + func_type = func_inst->is_import_func ? func_inst->u.func_import->func_type + : func_inst->u.func->func_type; + type_idx = func_inst->is_import_func ? func_inst->u.func_import->type_idx + : func_inst->u.func->type_idx; + + if (!(rtt_type = wasm_rtt_type_new((WASMType *)func_type, type_idx, + module->rtt_types, module->type_count, + &module->rtt_type_lock))) { + set_error_buf(error_buf, error_buf_size, "create rtt object failed"); + return NULL; + } + + if (!(func_obj = wasm_func_obj_new_internal( + module_inst->e->common.gc_heap_handle, rtt_type, func_idx))) { + set_error_buf(error_buf, error_buf_size, "create func object failed"); + return NULL; + } + + return func_obj; +} + +static bool +wasm_global_traverse_gc_rootset(WASMModuleInstance *module_inst, void *heap) +{ + WASMGlobalInstance *global = module_inst->e->globals; + WASMGlobalInstance *global_end = global + module_inst->e->global_count; + uint8 *global_data = module_inst->global_data; + WASMObjectRef gc_obj; + + while (global < global_end) { + if (wasm_is_type_reftype(global->type)) { + gc_obj = GET_REF_FROM_ADDR( + (uint32 *)(global_data + global->data_offset)); + if (wasm_obj_is_created_from_heap(gc_obj)) { + if (0 != mem_allocator_add_root((mem_allocator_t)heap, gc_obj)) + return false; + } + } + global++; + } + return true; +} + +static bool +wasm_table_traverse_gc_rootset(WASMModuleInstance *module_inst, void *heap) +{ + WASMTableInstance **tables = module_inst->tables, *table; + uint32 table_count = module_inst->table_count, i, j; + WASMObjectRef gc_obj, *table_elems; + + for (i = 0; i < table_count; i++) { + table = tables[i]; + table_elems = (WASMObjectRef *)table->elems; + for (j = 0; j < table->cur_size; j++) { + gc_obj = table_elems[j]; + if (wasm_obj_is_created_from_heap(gc_obj)) { + if (0 != mem_allocator_add_root((mem_allocator_t)heap, gc_obj)) + return false; + } + } + } + + return true; +} + +static bool +local_object_refs_traverse_gc_rootset(WASMExecEnv *exec_env, void *heap) +{ + WASMLocalObjectRef *r; + WASMObjectRef gc_obj; + + for (r = exec_env->cur_local_object_ref; r; r = r->prev) { + gc_obj = r->val; + if (wasm_obj_is_created_from_heap(gc_obj)) { + if (0 != mem_allocator_add_root((mem_allocator_t)heap, gc_obj)) + return false; + } + } + return true; +} + +bool +wasm_traverse_gc_rootset(WASMExecEnv *exec_env, void *heap) +{ + WASMModuleInstance *module_inst = + (WASMModuleInstance *)exec_env->module_inst; + bool ret; + + ret = wasm_global_traverse_gc_rootset(module_inst, heap); + if (!ret) + return ret; + + ret = wasm_table_traverse_gc_rootset(module_inst, heap); + if (!ret) + return ret; + + ret = local_object_refs_traverse_gc_rootset(exec_env, heap); + if (!ret) + return ret; + + return wasm_interp_traverse_gc_rootset(exec_env, heap); +} +#endif /* end of WASM_ENABLE_GC != 0 */ + static bool set_running_mode(WASMModuleInstance *module_inst, RunningMode running_mode, bool first_time_set) @@ -1561,6 +1787,7 @@ set_running_mode(WASMModuleInstance *module_inst, RunningMode running_mode, #if !(WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 \ && WASM_ENABLE_LAZY_JIT != 0) /* No possible multi-tier JIT */ + (void)first_time_set; module_inst->e->running_mode = running_mode; if (running_mode == Mode_Interp) { @@ -1752,9 +1979,10 @@ wasm_instantiate(WASMModule *module, WASMModuleInstance *parent, WASMTableImport *import_table = &module->import_tables[i].u.table; table_size += offsetof(WASMTableInstance, elems); #if WASM_ENABLE_MULTI_MODULE != 0 - table_size += (uint64)sizeof(uint32) * import_table->max_size; + table_size += + (uint64)sizeof(table_elem_type_t) * import_table->max_size; #else - table_size += (uint64)sizeof(uint32) + table_size += (uint64)sizeof(table_elem_type_t) * (import_table->possible_grow ? import_table->max_size : import_table->init_size); #endif @@ -1763,10 +1991,10 @@ wasm_instantiate(WASMModule *module, WASMModuleInstance *parent, WASMTable *table = module->tables + i; table_size += offsetof(WASMTableInstance, elems); #if WASM_ENABLE_MULTI_MODULE != 0 - table_size += (uint64)sizeof(uint32) * table->max_size; + table_size += (uint64)sizeof(table_elem_type_t) * table->max_size; #else table_size += - (uint64)sizeof(uint32) + (uint64)sizeof(table_elem_type_t) * (table->possible_grow ? table->max_size : table->init_size); #endif } @@ -1834,6 +2062,27 @@ wasm_instantiate(WASMModule *module, WASMModuleInstance *parent, } #endif +#if WASM_ENABLE_GC != 0 + if (!is_sub_inst) { + uint32 gc_heap_size = wasm_runtime_get_gc_heap_size_default(); + + if (gc_heap_size < GC_HEAP_SIZE_MIN) + gc_heap_size = GC_HEAP_SIZE_MIN; + if (gc_heap_size > GC_HEAP_SIZE_MAX) + gc_heap_size = GC_HEAP_SIZE_MAX; + + module_inst->e->common.gc_heap_pool = + runtime_malloc(gc_heap_size, error_buf, error_buf_size); + if (!module_inst->e->common.gc_heap_pool) + goto fail; + + module_inst->e->common.gc_heap_handle = mem_allocator_create( + module_inst->e->common.gc_heap_pool, gc_heap_size); + if (!module_inst->e->common.gc_heap_handle) + goto fail; + } +#endif + #if WASM_ENABLE_DUMP_CALL_STACK != 0 if (!(module_inst->frames = runtime_malloc((uint64)sizeof(Vector), error_buf, error_buf_size))) { @@ -1931,7 +2180,7 @@ wasm_instantiate(WASMModule *module, WASMModuleInstance *parent, switch (global->type) { case VALUE_TYPE_I32: case VALUE_TYPE_F32: -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 case VALUE_TYPE_FUNCREF: case VALUE_TYPE_EXTERNREF: #endif @@ -1951,9 +2200,70 @@ wasm_instantiate(WASMModule *module, WASMModuleInstance *parent, &global->initial_value.v128, sizeof(V128)); global_data += sizeof(V128); break; +#endif +#if WASM_ENABLE_GC != 0 + case VALUE_TYPE_EXTERNREF: + /* the initial value should be a null reference */ + bh_assert(global->initial_value.gc_obj == NULL_REF); + STORE_PTR((void **)global_data, NULL_REF); + global_data += sizeof(void *); + break; #endif default: + { +#if WASM_ENABLE_GC != 0 + InitializerExpression *global_init = NULL; + bh_assert(wasm_is_type_reftype(global->type)); + + if (i >= module->import_global_count) { + global_init = + &module->globals[i - module->import_global_count] + .init_expr; + } + + if (global->type == REF_TYPE_NULLFUNCREF + || global->type == REF_TYPE_NULLEXTERNREF + || global->type == REF_TYPE_NULLREF) { + STORE_PTR((void **)global_data, NULL_REF); + global_data += sizeof(void *); + break; + } + + /* We can't create funcref obj during global instantiation + * since the functions are not instantiated yet, so we need + * to defer the initialization here */ + if (global_init + && (global_init->init_expr_type + == INIT_EXPR_TYPE_FUNCREF_CONST) + && wasm_reftype_is_subtype_of( + global->type, global->ref_type, REF_TYPE_FUNCREF, + NULL, module_inst->module->types, + module_inst->module->type_count)) { + WASMFuncObjectRef func_obj = NULL; + /* UINT32_MAX indicates that it is a null reference */ + if ((uint32)global->initial_value.i32 != UINT32_MAX) { + if (!(func_obj = wasm_create_func_obj( + module_inst, global->initial_value.i32, + false, error_buf, error_buf_size))) + goto fail; + } + STORE_PTR((void **)global_data, func_obj); + global_data += sizeof(void *); + /* Also update the inital_value since other globals may + * refer to this */ + global->initial_value.gc_obj = (wasm_obj_t)func_obj; + break; + } + else { + STORE_PTR((void **)global_data, + global->initial_value.gc_obj); + global_data += sizeof(void *); + break; + } +#endif bh_assert(0); + break; + } } } bh_assert(global_data == global_data_end); @@ -2019,7 +2329,7 @@ wasm_instantiate(WASMModule *module, WASMModuleInstance *parent, if (base_offset > memory_size) { LOG_DEBUG("base_offset(%d) > memory_size(%d)", base_offset, memory_size); -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 set_error_buf(error_buf, error_buf_size, "out of bounds memory access"); #else @@ -2034,7 +2344,7 @@ wasm_instantiate(WASMModule *module, WASMModuleInstance *parent, if ((uint64)base_offset + length > memory_size) { LOG_DEBUG("base_offset(%d) + length(%d) > memory_size(%d)", base_offset, length, memory_size); -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 set_error_buf(error_buf, error_buf_size, "out of bounds memory access"); #else @@ -2051,33 +2361,109 @@ wasm_instantiate(WASMModule *module, WASMModuleInstance *parent, } } +#if WASM_ENABLE_GC != 0 + /* Initialize the table data with init expr */ + for (i = 0; i < module->table_count; i++) { + WASMTable *table = module->tables + i; + WASMTableInstance *table_inst = module_inst->tables[i]; + table_elem_type_t *table_data; + uint32 j; + + if (table->init_expr.init_expr_type == 0) { + /* No table initializer */ + continue; + } + + table_data = table_inst->elems; + + bh_assert( + table->init_expr.init_expr_type == INIT_EXPR_TYPE_GET_GLOBAL + || table->init_expr.init_expr_type == INIT_EXPR_TYPE_FUNCREF_CONST + || table->init_expr.init_expr_type == INIT_EXPR_TYPE_REFNULL_CONST); + + if (table->init_expr.init_expr_type == INIT_EXPR_TYPE_GET_GLOBAL) { + if (!check_global_init_expr(module, table->init_expr.u.global_index, + error_buf, error_buf_size)) { + goto fail; + } + + table->init_expr.u.gc_obj = + globals[table->init_expr.u.global_index].initial_value.gc_obj; + } + else if (table->init_expr.init_expr_type + == INIT_EXPR_TYPE_FUNCREF_CONST) { + uint32 func_idx = table->init_expr.u.ref_index; + if (func_idx != UINT32_MAX) { + if (!(table->init_expr.u.gc_obj = + wasm_create_func_obj(module_inst, func_idx, false, + error_buf, error_buf_size))) + goto fail; + } + else { + table->init_expr.u.gc_obj = NULL_REF; + } + } + else if (table->init_expr.init_expr_type + == INIT_EXPR_TYPE_REFNULL_CONST) { + table->init_expr.u.gc_obj = NULL_REF; + } + + LOG_DEBUG("Init table [%d] elements from [%d] to [%d] as: %p", i, 0, + table_inst->cur_size, (void *)table->init_expr.u.gc_obj); + for (j = 0; j < table_inst->cur_size; j++) { + *(table_data + j) = table->init_expr.u.gc_obj; + } + } +#endif /* end of WASM_ENABLE_GC != 0 */ + /* Initialize the table data with table segment section */ for (i = 0; module_inst->table_count > 0 && i < module->table_seg_count; i++) { WASMTableSeg *table_seg = module->table_segments + i; /* has check it in loader */ WASMTableInstance *table = module_inst->tables[table_seg->table_index]; - uint32 *table_data; -#if WASM_ENABLE_REF_TYPES != 0 + table_elem_type_t *table_data; + uint32 j; +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 uint8 tbl_elem_type; uint32 tbl_init_size, tbl_max_size; #endif +#if WASM_ENABLE_GC != 0 + WASMRefType *tbl_elem_ref_type; +#endif bh_assert(table); -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 (void)wasm_runtime_get_table_inst_elem_type( (WASMModuleInstanceCommon *)module_inst, table_seg->table_index, - &tbl_elem_type, &tbl_init_size, &tbl_max_size); + &tbl_elem_type, +#if WASM_ENABLE_GC != 0 + &tbl_elem_ref_type, +#endif + &tbl_init_size, &tbl_max_size); + +#if WASM_ENABLE_GC == 0 if (tbl_elem_type != VALUE_TYPE_FUNCREF && tbl_elem_type != VALUE_TYPE_EXTERNREF) { set_error_buf(error_buf, error_buf_size, - "elements segment does not fit"); + "type mismatch: elements segment does not fit"); goto fail; } +#elif WASM_ENABLE_GC != 0 + if (!wasm_elem_is_declarative(table_seg->mode) + && !wasm_reftype_is_subtype_of( + table_seg->elem_type, table_seg->elem_ref_type, + table->elem_type, table->elem_ref_type.elem_ref_type, + module->types, module->type_count)) { + set_error_buf(error_buf, error_buf_size, + "type mismatch: elements segment does not fit"); + goto fail; + } +#endif (void)tbl_init_size; (void)tbl_max_size; -#endif +#endif /* end of WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */ table_data = table->elems; #if WASM_ENABLE_MULTI_MODULE != 0 @@ -2090,12 +2476,12 @@ wasm_instantiate(WASMModule *module, WASMModuleInstance *parent, #endif bh_assert(table_data); -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 if (!wasm_elem_is_active(table_seg->mode)) continue; #endif -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 bh_assert(table_seg->base_offset.init_expr_type == INIT_EXPR_TYPE_I32_CONST || table_seg->base_offset.init_expr_type @@ -2124,7 +2510,7 @@ wasm_instantiate(WASMModule *module, WASMModuleInstance *parent, || globals[table_seg->base_offset.u.global_index].type != VALUE_TYPE_I32) { set_error_buf(error_buf, error_buf_size, - "elements segment does not fit"); + "type mismatch: elements segment does not fit"); goto fail; } @@ -2137,49 +2523,223 @@ wasm_instantiate(WASMModule *module, WASMModuleInstance *parent, if ((uint32)table_seg->base_offset.u.i32 > table->cur_size) { LOG_DEBUG("base_offset(%d) > table->cur_size(%d)", table_seg->base_offset.u.i32, table->cur_size); -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 set_error_buf(error_buf, error_buf_size, "out of bounds table access"); #else set_error_buf(error_buf, error_buf_size, - "elements segment does not fit"); + "type mismatch: elements segment does not fit"); #endif goto fail; } /* check offset + length(could be zero) */ - length = table_seg->function_count; + length = table_seg->value_count; if ((uint32)table_seg->base_offset.u.i32 + length > table->cur_size) { LOG_DEBUG("base_offset(%d) + length(%d)> table->cur_size(%d)", table_seg->base_offset.u.i32, length, table->cur_size); -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 set_error_buf(error_buf, error_buf_size, "out of bounds table access"); #else set_error_buf(error_buf, error_buf_size, - "elements segment does not fit"); + "type mismatch: elements segment does not fit"); #endif goto fail; } - /** - * Check function index in the current module inst for now. - * will check the linked table inst owner in future. - * so loader check is enough - */ - bh_memcpy_s( - table_data + table_seg->base_offset.u.i32, - (uint32)((table->cur_size - (uint32)table_seg->base_offset.u.i32) - * sizeof(uint32)), - table_seg->func_indexes, (uint32)(length * sizeof(uint32))); + for (j = 0; j < length; j++) { + InitializerExpression *init_expr = &table_seg->init_values[j]; + uint8 flag = init_expr->init_expr_type; + void *ref = NULL; + + /* const and get global init values should be resolved during + * loading */ + bh_assert((flag == INIT_EXPR_TYPE_GET_GLOBAL) + || (flag == INIT_EXPR_TYPE_REFNULL_CONST) + || ((flag >= INIT_EXPR_TYPE_FUNCREF_CONST) + && (flag <= INIT_EXPR_TYPE_EXTERN_CONVERT_ANY))); + + switch (flag) { + case INIT_EXPR_TYPE_REFNULL_CONST: + ref = NULL; + break; + case INIT_EXPR_TYPE_FUNCREF_CONST: + { +#if WASM_ENABLE_GC == 0 + ref = (void *)(uintptr_t)init_expr->u.ref_index; +#else + WASMFuncObjectRef func_obj; + uint32 func_idx = init_expr->u.ref_index; + /* UINT32_MAX indicates that it is a null reference */ + if (func_idx != UINT32_MAX) { + if (!(func_obj = wasm_create_func_obj( + module_inst, func_idx, false, error_buf, + error_buf_size))) { + goto fail; + } + ref = func_obj; + } + else { + ref = NULL_REF; + } +#endif /* end of WASM_ENABLE_GC != 0 */ + break; + } +#if WASM_ENABLE_GC != 0 + case INIT_EXPR_TYPE_GET_GLOBAL: + { + if (!check_global_init_expr(module, + init_expr->u.global_index, + error_buf, error_buf_size)) { + goto fail; + } + + ref = + globals[init_expr->u.global_index].initial_value.gc_obj; + break; + } + case INIT_EXPR_TYPE_STRUCT_NEW: + case INIT_EXPR_TYPE_STRUCT_NEW_DEFAULT: + { + WASMRttType *rtt_type; + WASMStructObjectRef struct_obj; + WASMStructType *struct_type; + WASMStructNewInitValues *init_values = NULL; + uint32 type_idx; + + if (flag == INIT_EXPR_TYPE_STRUCT_NEW) { + init_values = + (WASMStructNewInitValues *)init_expr->u.data; + type_idx = init_values->type_idx; + } + else { + type_idx = init_expr->u.type_index; + } + + struct_type = (WASMStructType *)module->types[type_idx]; + + if (!(rtt_type = wasm_rtt_type_new( + (WASMType *)struct_type, type_idx, + module->rtt_types, module->type_count, + &module->rtt_type_lock))) { + set_error_buf(error_buf, error_buf_size, + "create rtt object failed"); + goto fail; + } + + if (!(struct_obj = wasm_struct_obj_new_internal( + module_inst->e->common.gc_heap_handle, + rtt_type))) { + set_error_buf(error_buf, error_buf_size, + "create struct object failed"); + goto fail; + } + + if (flag == INIT_EXPR_TYPE_STRUCT_NEW) { + uint32 field_idx; + + bh_assert(init_values->count + == struct_type->field_count); + + for (field_idx = 0; field_idx < init_values->count; + field_idx++) { + wasm_struct_obj_set_field( + struct_obj, field_idx, + &init_values->fields[field_idx]); + } + } + + ref = struct_obj; + break; + } + case INIT_EXPR_TYPE_ARRAY_NEW: + case INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT: + case INIT_EXPR_TYPE_ARRAY_NEW_FIXED: + { + WASMRttType *rtt_type; + WASMArrayObjectRef array_obj; + WASMArrayType *array_type; + WASMArrayNewInitValues *init_values = NULL; + WASMValue *arr_init_val = NULL, empty_val = { 0 }; + uint32 type_idx, len; + + if (flag == INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT) { + type_idx = init_expr->u.array_new_default.type_index; + len = init_expr->u.array_new_default.length; + arr_init_val = &empty_val; + } + else { + init_values = + (WASMArrayNewInitValues *)init_expr->u.data; + type_idx = init_values->type_idx; + len = init_values->length; + + if (flag == INIT_EXPR_TYPE_ARRAY_NEW_FIXED) { + arr_init_val = init_values->elem_data; + } + } + + array_type = (WASMArrayType *)module->types[type_idx]; + + if (!(rtt_type = wasm_rtt_type_new( + (WASMType *)array_type, type_idx, + module->rtt_types, module->type_count, + &module->rtt_type_lock))) { + set_error_buf(error_buf, error_buf_size, + "create rtt object failed"); + goto fail; + } + + if (!(array_obj = wasm_array_obj_new_internal( + module_inst->e->common.gc_heap_handle, rtt_type, + len, arr_init_val))) { + set_error_buf(error_buf, error_buf_size, + "create array object failed"); + goto fail; + } + + if (flag == INIT_EXPR_TYPE_ARRAY_NEW_FIXED) { + uint32 elem_idx; + + bh_assert(init_values); + + for (elem_idx = 0; elem_idx < len; elem_idx++) { + wasm_array_obj_set_elem( + array_obj, elem_idx, + &init_values->elem_data[elem_idx]); + } + } + + ref = array_obj; + + break; + } + case INIT_EXPR_TYPE_I31_NEW: + { + ref = (wasm_obj_t)wasm_i31_obj_new(init_expr->u.i32); + break; + } +#endif /* end of WASM_ENABLE_GC != 0 */ + } + + *(table_data + table_seg->base_offset.u.i32 + j) = + (table_elem_type_t)ref; + } } /* Initialize the thread related data */ if (stack_size == 0) stack_size = DEFAULT_WASM_STACK_SIZE; #if WASM_ENABLE_SPEC_TEST != 0 +#if WASM_ENABLE_TAIL_CALL == 0 if (stack_size < 128 * 1024) stack_size = 128 * 1024; +#else + /* Some tail-call cases require large operand stack */ + if (stack_size < 10 * 1024 * 1024) + stack_size = 10 * 1024 * 1024; +#endif #endif module_inst->default_wasm_stack_size = stack_size; @@ -2266,6 +2826,29 @@ fail: return NULL; } +#if WASM_ENABLE_DUMP_CALL_STACK != 0 +static void +destroy_c_api_frames(Vector *frames) +{ + WASMCApiFrame frame = { 0 }; + uint32 i, total_frames, ret; + + total_frames = (uint32)bh_vector_size(frames); + + for (i = 0; i < total_frames; i++) { + ret = bh_vector_get(frames, i, &frame); + bh_assert(ret); + + if (frame.lp) + wasm_runtime_free(frame.lp); + } + + ret = bh_vector_destroy(frames); + bh_assert(ret); + (void)ret; +} +#endif + void wasm_deinstantiate(WASMModuleInstance *module_inst, bool is_sub_inst) { @@ -2342,12 +2925,10 @@ wasm_deinstantiate(WASMModuleInstance *module_inst, bool is_sub_inst) } tables_deinstantiate(module_inst); - functions_deinstantiate(module_inst->e->functions, - module_inst->e->function_count); + functions_deinstantiate(module_inst->e->functions); #if WASM_ENABLE_TAGS != 0 tags_deinstantiate(module_inst->e->tags, module_inst->e->import_tag_ptrs); #endif - globals_deinstantiate(module_inst->e->globals); export_functions_deinstantiate(module_inst->export_functions); #if WASM_ENABLE_TAGS != 0 @@ -2358,13 +2939,22 @@ wasm_deinstantiate(WASMModuleInstance *module_inst, bool is_sub_inst) export_globals_deinstantiate(module_inst->export_globals); #endif -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 wasm_externref_cleanup((WASMModuleInstanceCommon *)module_inst); #endif +#if WASM_ENABLE_GC != 0 + if (!is_sub_inst) { + if (module_inst->e->common.gc_heap_handle) + mem_allocator_destroy(module_inst->e->common.gc_heap_handle); + if (module_inst->e->common.gc_heap_pool) + wasm_runtime_free(module_inst->e->common.gc_heap_pool); + } +#endif + #if WASM_ENABLE_DUMP_CALL_STACK != 0 if (module_inst->frames) { - bh_vector_destroy(module_inst->frames); + destroy_c_api_frames(module_inst->frames); wasm_runtime_free(module_inst->frames); module_inst->frames = NULL; } @@ -2463,7 +3053,7 @@ call_wasm_with_hw_bound_check(WASMModuleInstance *module_inst, uint32 page_size = os_getpagesize(); uint32 guard_page_count = STACK_OVERFLOW_CHECK_GUARD_PAGE_COUNT; WASMRuntimeFrame *prev_frame = wasm_exec_env_get_cur_frame(exec_env); - uint8 *prev_top = exec_env->wasm_stack.s.top; + uint8 *prev_top = exec_env->wasm_stack.top; #ifdef BH_PLATFORM_WINDOWS int result; bool has_exception; @@ -2538,7 +3128,7 @@ call_wasm_with_hw_bound_check(WASMModuleInstance *module_inst, #endif /* Restore operand frames */ wasm_exec_env_set_cur_frame(exec_env, prev_frame); - exec_env->wasm_stack.s.top = prev_top; + exec_env->wasm_stack.top = prev_top; } jmpbuf_node_pop = wasm_exec_env_pop_jmpbuf(exec_env); @@ -2828,12 +3418,13 @@ wasm_module_dup_data(WASMModuleInstance *module_inst, const char *src, return buffer_offset; } -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 bool wasm_enlarge_table(WASMModuleInstance *module_inst, uint32 table_idx, - uint32 inc_size, uint32 init_val) + uint32 inc_size, table_elem_type_t init_val) { - uint32 total_size, *new_table_data_start, i; + uint32 total_size, i; + table_elem_type_t *new_table_data_start; WASMTableInstance *table_inst; if (!inc_size) { @@ -2864,14 +3455,15 @@ wasm_enlarge_table(WASMModuleInstance *module_inst, uint32 table_idx, table_inst->cur_size = total_size; return true; } -#endif /* WASM_ENABLE_REF_TYPES != 0 */ +#endif /* end of WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */ static bool -call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 elem_idx, +call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 tbl_elem_idx, uint32 argc, uint32 argv[], bool check_type_idx, uint32 type_idx) { WASMModuleInstance *module_inst = NULL; WASMTableInstance *table_inst = NULL; + table_elem_type_t tbl_elem_val = NULL_REF; uint32 func_idx = 0; WASMFunctionInstance *func_inst = NULL; @@ -2884,17 +3476,24 @@ call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 elem_idx, goto got_exception; } - if (elem_idx >= table_inst->cur_size) { + if (tbl_elem_idx >= table_inst->cur_size) { wasm_set_exception(module_inst, "undefined element"); goto got_exception; } - func_idx = table_inst->elems[elem_idx]; - if (func_idx == NULL_REF) { + tbl_elem_val = ((table_elem_type_t *)table_inst->elems)[tbl_elem_idx]; + if (tbl_elem_val == NULL_REF) { wasm_set_exception(module_inst, "uninitialized element"); goto got_exception; } +#if WASM_ENABLE_GC == 0 + func_idx = tbl_elem_val; +#else + func_idx = + wasm_func_obj_get_func_idx_bound((WASMFuncObjectRef)tbl_elem_val); +#endif + /** * we insist to call functions owned by the module itself **/ @@ -2910,9 +3509,9 @@ call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 elem_idx, WASMType *cur_func_type; if (func_inst->is_import_func) - cur_func_type = func_inst->u.func_import->func_type; + cur_func_type = (WASMType *)func_inst->u.func_import->func_type; else - cur_func_type = func_inst->u.func->func_type; + cur_func_type = (WASMType *)func_inst->u.func->func_type; if (cur_type != cur_func_type) { wasm_set_exception(module_inst, "indirect call type mismatch"); @@ -3003,10 +3602,10 @@ wasm_get_module_mem_consumption(const WASMModule *module, mem_conspn->module_struct_size = sizeof(WASMModule); - mem_conspn->types_size = sizeof(WASMType *) * module->type_count; + mem_conspn->types_size = sizeof(WASMFuncType *) * module->type_count; for (i = 0; i < module->type_count; i++) { - WASMType *type = module->types[i]; - size = offsetof(WASMType, types) + WASMFuncType *type = module->types[i]; + size = offsetof(WASMFuncType, types) + sizeof(uint8) * (type->param_count + type->result_count); mem_conspn->types_size += size; } @@ -3017,7 +3616,7 @@ wasm_get_module_mem_consumption(const WASMModule *module, sizeof(WASMFunction *) * module->function_count; for (i = 0; i < module->function_count; i++) { WASMFunction *func = module->functions[i]; - WASMType *type = func->func_type; + WASMFuncType *type = func->func_type; size = sizeof(WASMFunction) + func->local_count + sizeof(uint16) * (type->param_count + func->local_count); #if WASM_ENABLE_FAST_INTERP != 0 @@ -3036,7 +3635,8 @@ wasm_get_module_mem_consumption(const WASMModule *module, sizeof(WASMTableSeg) * module->table_seg_count; for (i = 0; i < module->table_seg_count; i++) { WASMTableSeg *table_seg = &module->table_segments[i]; - mem_conspn->tables_size += sizeof(uint32) * table_seg->function_count; + mem_conspn->tables_size += + sizeof(InitializerExpression *) * table_seg->value_count; } mem_conspn->data_segs_size = sizeof(WASMDataSeg *) * module->data_seg_count; @@ -3123,6 +3723,7 @@ wasm_interp_create_call_stack(struct WASMExecEnv *exec_env) { WASMModuleInstance *module_inst = (WASMModuleInstance *)wasm_exec_env_get_module_inst(exec_env); + WASMModule *module = module_inst->module; WASMInterpFrame *first_frame, *cur_frame = wasm_exec_env_get_cur_frame(exec_env); uint32 n = 0; @@ -3137,9 +3738,8 @@ wasm_interp_create_call_stack(struct WASMExecEnv *exec_env) } /* release previous stack frames and create new ones */ - if (!bh_vector_destroy(module_inst->frames) - || !bh_vector_init(module_inst->frames, n, sizeof(WASMCApiFrame), - false)) { + destroy_c_api_frames(module_inst->frames); + if (!bh_vector_init(module_inst->frames, n, sizeof(WASMCApiFrame), false)) { return false; } @@ -3151,6 +3751,8 @@ wasm_interp_create_call_stack(struct WASMExecEnv *exec_env) WASMFunctionInstance *func_inst = cur_frame->function; const char *func_name = NULL; const uint8 *func_code_base = NULL; + uint32 max_local_cell_num, max_stack_cell_num; + uint32 all_cell_num, lp_size; if (!func_inst) { cur_frame = cur_frame->prev_frame; @@ -3167,14 +3769,67 @@ wasm_interp_create_call_stack(struct WASMExecEnv *exec_env) frame.func_offset = 0; } else { +#if WASM_ENABLE_FAST_INTERP == 0 + frame.func_offset = (uint32)(cur_frame->ip - module->load_addr); +#else frame.func_offset = (uint32)(cur_frame->ip - func_code_base); +#endif } func_name = get_func_name_from_index(module_inst, frame.func_index); frame.func_name_wp = func_name; + if (frame.func_index >= module->import_function_count) { + uint32 wasm_func_idx = + frame.func_index - module->import_function_count; + max_local_cell_num = + module->functions[wasm_func_idx]->param_cell_num + + module->functions[wasm_func_idx]->local_cell_num; + max_stack_cell_num = + module->functions[wasm_func_idx]->max_stack_cell_num; + all_cell_num = max_local_cell_num + max_stack_cell_num; +#if WASM_ENABLE_FAST_INTERP != 0 + all_cell_num += module->functions[wasm_func_idx]->const_cell_num; +#endif + } + else { + WASMFuncType *func_type = + module->import_functions[frame.func_index].u.function.func_type; + max_local_cell_num = + func_type->param_cell_num > 2 ? func_type->param_cell_num : 2; + max_stack_cell_num = 0; + all_cell_num = max_local_cell_num + max_stack_cell_num; + } + +#if WASM_ENABLE_GC == 0 + lp_size = all_cell_num * 4; +#else + lp_size = align_uint(all_cell_num * 5, 4); +#endif + if (lp_size > 0) { + if (!(frame.lp = wasm_runtime_malloc(lp_size))) { + destroy_c_api_frames(module_inst->frames); + return false; + } + bh_memcpy_s(frame.lp, lp_size, cur_frame->lp, lp_size); + +#if WASM_ENABLE_GC != 0 +#if WASM_ENABLE_FAST_INTERP == 0 + frame.sp = frame.lp + (cur_frame->sp - cur_frame->lp); +#else + /* for fast-interp, let frame sp point to the end of the frame */ + frame.sp = frame.lp + all_cell_num; +#endif + frame.frame_ref = (uint8 *)frame.lp + + (wasm_interp_get_frame_ref(cur_frame) + - (uint8 *)cur_frame->lp); +#endif + } + if (!bh_vector_append(module_inst->frames, &frame)) { - bh_vector_destroy(module_inst->frames); + if (frame.lp) + wasm_runtime_free(frame.lp); + destroy_c_api_frames(module_inst->frames); return false; } @@ -3228,16 +3883,37 @@ wasm_interp_dump_call_stack(struct WASMExecEnv *exec_env, bool print, char *buf, return 0; } - /* function name not exported, print number instead */ - if (frame.func_name_wp == NULL) { - line_length = - snprintf(line_buf, sizeof(line_buf), - "#%02" PRIu32 " $f%" PRIu32 "\n", n, frame.func_index); +#if WASM_ENABLE_FAST_JIT != 0 + /* Fast JIT doesn't support committing ip (instruction pointer) yet */ + if (module_inst->e->running_mode == Mode_Fast_JIT + || module_inst->e->running_mode == Mode_Multi_Tier_JIT) { + /* function name not exported, print number instead */ + if (frame.func_name_wp == NULL) { + line_length = snprintf(line_buf, sizeof(line_buf), + "#%02" PRIu32 " $f%" PRIu32 "\n", n, + frame.func_index); + } + else { + line_length = + snprintf(line_buf, sizeof(line_buf), "#%02" PRIu32 " %s\n", + n, frame.func_name_wp); + } } - else { - line_length = - snprintf(line_buf, sizeof(line_buf), "#%02" PRIu32 " %s\n", n, - frame.func_name_wp); + else +#endif + { + /* function name not exported, print number instead */ + if (frame.func_name_wp == NULL) { + line_length = + snprintf(line_buf, sizeof(line_buf), + "#%02" PRIu32 ": 0x%04x - $f%" PRIu32 "\n", n, + frame.func_offset, frame.func_index); + } + else { + line_length = snprintf(line_buf, sizeof(line_buf), + "#%02" PRIu32 ": 0x%04x - %s\n", n, + frame.func_offset, frame.func_name_wp); + } } if (line_length >= sizeof(line_buf)) { @@ -3327,7 +4003,7 @@ llvm_jit_invoke_native(WASMExecEnv *exec_env, uint32 func_idx, uint32 argc, WASMModule *module; uint32 *func_type_indexes; uint32 func_type_idx; - WASMType *func_type; + WASMFuncType *func_type; void *func_ptr; WASMFunctionImport *import_func; CApiFuncImport *c_api_func_import = NULL; @@ -3342,7 +4018,7 @@ llvm_jit_invoke_native(WASMExecEnv *exec_env, uint32 func_idx, uint32 argc, module = module_inst->module; func_type_indexes = module_inst->func_type_indexes; func_type_idx = func_type_indexes[func_idx]; - func_type = module->types[func_type_idx]; + func_type = (WASMFuncType *)module->types[func_type_idx]; func_ptr = module_inst->func_ptrs[func_idx]; bh_assert(func_idx < module->import_function_count); @@ -3450,7 +4126,7 @@ llvm_jit_data_drop(WASMModuleInstance *module_inst, uint32 seg_index) } #endif /* end of WASM_ENABLE_BULK_MEMORY != 0 */ -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 void llvm_jit_drop_table_seg(WASMModuleInstance *module_inst, uint32 tbl_seg_idx) { @@ -3465,7 +4141,12 @@ llvm_jit_table_init(WASMModuleInstance *module_inst, uint32 tbl_idx, { WASMTableInstance *tbl_inst; WASMTableSeg *tbl_seg; - uint32 *tbl_seg_elems = NULL, tbl_seg_len = 0; + table_elem_type_t *table_elems; + InitializerExpression *tbl_seg_init_values = NULL, *init_values; + uint32 i, tbl_seg_len = 0; +#if WASM_ENABLE_GC != 0 + void *func_obj; +#endif bh_assert(module_inst->module_type == Wasm_Module_Bytecode); @@ -3477,8 +4158,8 @@ llvm_jit_table_init(WASMModuleInstance *module_inst, uint32 tbl_idx, if (!bh_bitmap_get_bit(module_inst->e->common.elem_dropped, tbl_seg_idx)) { /* table segment isn't dropped */ - tbl_seg_elems = tbl_seg->func_indexes; - tbl_seg_len = tbl_seg->function_count; + tbl_seg_init_values = tbl_seg->init_values; + tbl_seg_len = tbl_seg->value_count; } if (offset_len_out_of_bounds(src_offset, length, tbl_seg_len) @@ -3491,10 +4172,28 @@ llvm_jit_table_init(WASMModuleInstance *module_inst, uint32 tbl_idx, return; } - bh_memcpy_s((uint8 *)tbl_inst + offsetof(WASMTableInstance, elems) - + dst_offset * sizeof(uint32), - (uint32)sizeof(uint32) * (tbl_inst->cur_size - dst_offset), - tbl_seg_elems + src_offset, (uint32)(length * sizeof(uint32))); + table_elems = tbl_inst->elems + dst_offset; + init_values = tbl_seg_init_values + src_offset; + + for (i = 0; i < length; i++) { +#if WASM_ENABLE_GC != 0 + /* UINT32_MAX indicates that it is a null ref */ + if (init_values[i].u.ref_index != UINT32_MAX) { + if (!(func_obj = wasm_create_func_obj(module_inst, + init_values[i].u.ref_index, + true, NULL, 0))) { + wasm_set_exception(module_inst, "null function object"); + return; + } + table_elems[i] = func_obj; + } + else { + table_elems[i] = NULL_REF; + } +#else + table_elems[i] = init_values[i].u.ref_index; +#endif + } } void @@ -3523,16 +4222,17 @@ llvm_jit_table_copy(WASMModuleInstance *module_inst, uint32 src_tbl_idx, /* if src_offset < dst_offset, copy from back to front */ /* merge all together */ bh_memmove_s((uint8 *)dst_tbl_inst + offsetof(WASMTableInstance, elems) - + sizeof(uint32) * dst_offset, - (uint32)sizeof(uint32) * (dst_tbl_inst->cur_size - dst_offset), + + sizeof(table_elem_type_t) * dst_offset, + (uint32)sizeof(table_elem_type_t) + * (dst_tbl_inst->cur_size - dst_offset), (uint8 *)src_tbl_inst + offsetof(WASMTableInstance, elems) - + sizeof(uint32) * src_offset, - (uint32)sizeof(uint32) * length); + + sizeof(table_elem_type_t) * src_offset, + (uint32)sizeof(table_elem_type_t) * length); } void llvm_jit_table_fill(WASMModuleInstance *module_inst, uint32 tbl_idx, - uint32 length, uint32 val, uint32 data_offset) + uint32 length, uintptr_t val, uint32 data_offset) { WASMTableInstance *tbl_inst; @@ -3547,13 +4247,13 @@ llvm_jit_table_fill(WASMModuleInstance *module_inst, uint32 tbl_idx, } for (; length != 0; data_offset++, length--) { - tbl_inst->elems[data_offset] = val; + tbl_inst->elems[data_offset] = (table_elem_type_t)val; } } uint32 llvm_jit_table_grow(WASMModuleInstance *module_inst, uint32 tbl_idx, - uint32 inc_size, uint32 init_val) + uint32 inc_size, uintptr_t init_val) { WASMTableInstance *tbl_inst; uint32 i, orig_size, total_size; @@ -3582,72 +4282,76 @@ llvm_jit_table_grow(WASMModuleInstance *module_inst, uint32 tbl_idx, /* fill in */ for (i = 0; i < inc_size; ++i) { - tbl_inst->elems[tbl_inst->cur_size + i] = init_val; + tbl_inst->elems[tbl_inst->cur_size + i] = (table_elem_type_t)init_val; } tbl_inst->cur_size = total_size; return orig_size; } -#endif /* end of WASM_ENABLE_REF_TYPES != 0 */ +#endif /* end of WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */ -#if WASM_ENABLE_DUMP_CALL_STACK != 0 || WASM_ENABLE_PERF_PROFILING != 0 -bool -llvm_jit_alloc_frame(WASMExecEnv *exec_env, uint32 func_index) +#if WASM_ENABLE_GC != 0 +void * +llvm_jit_create_func_obj(WASMModuleInstance *module_inst, uint32 func_idx, + bool throw_exce, char *error_buf, + uint32 error_buf_size) { - WASMModuleInstance *module_inst; - WASMInterpFrame *frame; - uint32 size; + bh_assert(module_inst->module_type == Wasm_Module_Bytecode); - bh_assert(exec_env->module_inst->module_type == Wasm_Module_Bytecode); + return wasm_create_func_obj(module_inst, func_idx, throw_exce, error_buf, + error_buf_size); +} - module_inst = (WASMModuleInstance *)exec_env->module_inst; - size = wasm_interp_interp_frame_size(0); +bool +llvm_jit_obj_is_instance_of(WASMModuleInstance *module_inst, + WASMObjectRef gc_obj, uint32 type_index) +{ + WASMModule *module = module_inst->module; + WASMType **types = module->types; + uint32 type_count = module->type_count; - frame = wasm_exec_env_alloc_wasm_frame(exec_env, size); - if (!frame) { - wasm_set_exception(module_inst, "wasm operand stack overflow"); + return wasm_obj_is_instance_of(gc_obj, type_index, types, type_count); +} + +WASMRttTypeRef +llvm_jit_rtt_type_new(WASMModuleInstance *module_inst, uint32 type_index) +{ + WASMModule *module = module_inst->module; + WASMType *defined_type = module->types[type_index]; + WASMRttType **rtt_types = module->rtt_types; + uint32 rtt_type_count = module->type_count; + korp_mutex *rtt_type_lock = &module->rtt_type_lock; + + return wasm_rtt_type_new(defined_type, type_index, rtt_types, + rtt_type_count, rtt_type_lock); +} + +bool +llvm_array_init_with_data(WASMModuleInstance *module_inst, uint32 seg_index, + uint32 data_seg_offset, WASMArrayObjectRef array_obj, + uint32 elem_size, uint32 array_len) +{ + WASMModule *wasm_module = module_inst->module; + WASMDataSeg *data_seg; + uint8 *array_elem_base; + uint64 total_size; + + data_seg = wasm_module->data_segments[seg_index]; + total_size = (int64)elem_size * array_len; + + if (data_seg_offset >= data_seg->data_length + || total_size > data_seg->data_length - data_seg_offset) { + wasm_set_exception(module_inst, "out of bounds memory access"); return false; } - frame->function = module_inst->e->functions + func_index; - frame->ip = NULL; - frame->sp = frame->lp; -#if WASM_ENABLE_PERF_PROFILING != 0 - frame->time_started = os_time_thread_cputime_us(); -#endif - frame->prev_frame = wasm_exec_env_get_cur_frame(exec_env); - wasm_exec_env_set_cur_frame(exec_env, frame); + array_elem_base = (uint8 *)wasm_array_obj_first_elem_addr(array_obj); + bh_memcpy_s(array_elem_base, (uint32)total_size, + data_seg->data + data_seg_offset, (uint32)total_size); return true; } - -void -llvm_jit_free_frame(WASMExecEnv *exec_env) -{ - WASMInterpFrame *frame; - WASMInterpFrame *prev_frame; - - bh_assert(exec_env->module_inst->module_type == Wasm_Module_Bytecode); - - frame = wasm_exec_env_get_cur_frame(exec_env); - prev_frame = frame->prev_frame; - -#if WASM_ENABLE_PERF_PROFILING != 0 - if (frame->function) { - uint64 elapsed = os_time_thread_cputime_us() - frame->time_started; - frame->function->total_exec_time += elapsed; - frame->function->total_exec_cnt++; - - /* parent function */ - if (prev_frame) - prev_frame->function->children_exec_time += elapsed; - } -#endif - wasm_exec_env_free_wasm_frame(exec_env, frame); - wasm_exec_env_set_cur_frame(exec_env, prev_frame); -} -#endif /* end of WASM_ENABLE_DUMP_CALL_STACK != 0 \ - || WASM_ENABLE_PERF_PROFILING != 0 */ +#endif /* end of WASM_ENABLE_GC != 0 */ #endif /* end of WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 */ diff --git a/core/iwasm/interpreter/wasm_runtime.h b/core/iwasm/interpreter/wasm_runtime.h index b1224863e..1007dc27c 100644 --- a/core/iwasm/interpreter/wasm_runtime.h +++ b/core/iwasm/interpreter/wasm_runtime.h @@ -71,6 +71,22 @@ typedef enum WASMExceptionID { EXCE_OUT_OF_BOUNDS_TABLE_ACCESS, EXCE_OPERAND_STACK_OVERFLOW, EXCE_FAILED_TO_COMPILE_FAST_JIT_FUNC, + /* GC related exceptions */ + EXCE_NULL_FUNC_OBJ, + EXCE_NULL_STRUCT_OBJ, + EXCE_NULL_ARRAY_OBJ, + EXCE_NULL_I31_OBJ, + EXCE_NULL_REFERENCE, + EXCE_FAILED_TO_CREATE_RTT_TYPE, + EXCE_FAILED_TO_CREATE_STRUCT_OBJ, + EXCE_FAILED_TO_CREATE_ARRAY_OBJ, + EXCE_FAILED_TO_CREATE_EXTERNREF_OBJ, + EXCE_CAST_FAILURE, + EXCE_ARRAY_IDX_OOB, + EXCE_FAILED_TO_CREATE_STRING, + EXCE_FAILED_TO_CREATE_STRINGREF, + EXCE_FAILED_TO_CREATE_STRINGVIEW, + EXCE_FAILED_TO_ENCODE_STRING, EXCE_ALREADY_THROWN, EXCE_NUM, } WASMExceptionID; @@ -129,13 +145,29 @@ struct WASMMemoryInstance { #endif }; +/* WASMTableInstance is used to represent table instance in + * runtime, to compute the table element address with index + * we need to know the element type and the element ref type. + * For pointer type, it's 32-bit or 64-bit, align up to 8 bytes + * to simplify the computation. + * And each struct member should be 4-byte or 8-byte aligned. + */ struct WASMTableInstance { + /* The element type */ + uint8 elem_type; + uint8 __padding__[7]; + union { +#if WASM_ENABLE_GC != 0 + WASMRefType *elem_ref_type; +#endif + uint64 __padding__; + } elem_ref_type; /* Current size */ uint32 cur_size; /* Maximum size */ uint32 max_size; /* Table elements */ - uint32 elems[1]; + table_elem_type_t elems[1]; }; struct WASMGlobalInstance { @@ -147,6 +179,9 @@ struct WASMGlobalInstance { uint32 data_offset; /* initial value */ WASMValue initial_value; +#if WASM_ENABLE_GC != 0 + WASMRefType *ref_type; +#endif #if WASM_ENABLE_MULTI_MODULE != 0 /* just for import, keep the reference here */ WASMModuleInstance *import_module_inst; @@ -271,6 +306,13 @@ typedef struct WASMModuleInstanceExtraCommon { #if WASM_ENABLE_REF_TYPES != 0 bh_bitmap *elem_dropped; #endif + +#if WASM_ENABLE_GC != 0 + /* The gc heap memory pool */ + uint8 *gc_heap_pool; + /* The gc heap created */ + void *gc_heap_handle; +#endif } WASMModuleInstanceExtraCommon; /* Extra info of WASM module instance for interpreter/jit mode */ @@ -598,7 +640,7 @@ void wasm_get_module_inst_mem_consumption(const WASMModuleInstance *module, WASMModuleInstMemConsumption *mem_conspn); -#if WASM_ENABLE_REF_TYPES != 0 +#if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 static inline bool wasm_elem_is_active(uint32 mode) { @@ -619,8 +661,18 @@ wasm_elem_is_declarative(uint32 mode) bool wasm_enlarge_table(WASMModuleInstance *module_inst, uint32 table_idx, - uint32 inc_entries, uint32 init_val); -#endif /* WASM_ENABLE_REF_TYPES != 0 */ + uint32 inc_entries, table_elem_type_t init_val); +#endif /* WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */ + +#if WASM_ENABLE_GC != 0 +void * +wasm_create_func_obj(WASMModuleInstance *module_inst, uint32 func_idx, + bool throw_exce, char *error_buf, uint32 error_buf_size); + +bool +wasm_traverse_gc_rootset(WASMExecEnv *exec_env, void *heap); + +#endif static inline WASMTableInstance * wasm_get_table_inst(const WASMModuleInstance *module_inst, uint32 tbl_idx) @@ -723,19 +775,42 @@ llvm_jit_table_copy(WASMModuleInstance *module_inst, uint32 src_tbl_idx, void llvm_jit_table_fill(WASMModuleInstance *module_inst, uint32 tbl_idx, - uint32 length, uint32 val, uint32 data_offset); + uint32 length, uintptr_t val, uint32 data_offset); uint32 llvm_jit_table_grow(WASMModuleInstance *module_inst, uint32 tbl_idx, - uint32 inc_entries, uint32 init_val); + uint32 inc_entries, uintptr_t init_val); #endif -#if WASM_ENABLE_DUMP_CALL_STACK != 0 || WASM_ENABLE_PERF_PROFILING != 0 +#if WASM_ENABLE_DUMP_CALL_STACK != 0 || WASM_ENABLE_PERF_PROFILING != 0 \ + || WASM_ENABLE_AOT_STACK_FRAME != 0 bool llvm_jit_alloc_frame(WASMExecEnv *exec_env, uint32 func_index); void llvm_jit_free_frame(WASMExecEnv *exec_env); + +void +llvm_jit_frame_update_profile_info(WASMExecEnv *exec_env, bool alloc_frame); +#endif + +#if WASM_ENABLE_GC != 0 +void * +llvm_jit_create_func_obj(WASMModuleInstance *module_inst, uint32 func_idx, + bool throw_exce, char *error_buf, + uint32 error_buf_size); + +bool +llvm_jit_obj_is_instance_of(WASMModuleInstance *module_inst, + WASMObjectRef gc_obj, uint32 type_index); + +WASMRttTypeRef +llvm_jit_rtt_type_new(WASMModuleInstance *module_inst, uint32 type_index); + +bool +llvm_array_init_with_data(WASMModuleInstance *module_inst, uint32 seg_index, + uint32 data_seg_offset, WASMArrayObjectRef array_obj, + uint32 elem_size, uint32 array_len); #endif #endif /* end of WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 */ diff --git a/core/iwasm/libraries/lib-rats/lib_rats_common.h b/core/iwasm/libraries/lib-rats/lib_rats_common.h index 929e105f0..434c2abfd 100644 --- a/core/iwasm/libraries/lib-rats/lib_rats_common.h +++ b/core/iwasm/libraries/lib-rats/lib_rats_common.h @@ -15,6 +15,22 @@ extern "C" { #endif +/* Enclave Flags Bit Masks */ +/* If set, then the enclave is initialized */ +#define SGX_FLAGS_INITTED 0x001ULL +/* If set, then the enclave is debug */ +#define SGX_FLAGS_DEBUG 0x002ULL +/* If set, then the enclave is 64 bit */ +#define SGX_FLAGS_MODE64BIT 0x004ULL +/* If set, then the enclave has access to provision key */ +#define SGX_FLAGS_PROVISION_KEY 0x010ULL +/* If set, then the enclave has access to EINITTOKEN key */ +#define SGX_FLAGS_EINITTOKEN_KEY 0x020ULL +/* If set, then the enclave uses KSS */ +#define SGX_FLAGS_KSS 0x080ULL +/* If set, then the enclave enables AEX Notify */ +#define SGX_FLAGS_AEX_NOTIFY 0x400ULL + #define SGX_QUOTE_MAX_SIZE 8192 #define SGX_USER_DATA_SIZE 64 #define SGX_MEASUREMENT_SIZE 32 diff --git a/core/iwasm/libraries/libc-builtin/libc_builtin_wrapper.c b/core/iwasm/libraries/libc-builtin/libc_builtin_wrapper.c index 8e6a65a4a..d19e1bbbb 100644 --- a/core/iwasm/libraries/libc-builtin/libc_builtin_wrapper.c +++ b/core/iwasm/libraries/libc-builtin/libc_builtin_wrapper.c @@ -1136,6 +1136,10 @@ static WASMNativeGlobalDef native_global_defs[] = { { "test", "global-f32", VALUE_TYPE_F32, false, .value.f32 = 0 }, { "test", "global-mut-i32", VALUE_TYPE_I32, true, .value.i32 = 0 }, { "test", "global-mut-i64", VALUE_TYPE_I64, true, .value.i64 = 0 }, +#if WASM_ENABLE_GC != 0 + { "G", "g", VALUE_TYPE_I32, false, .value.i32 = 4 }, + { "M", "g", REF_TYPE_HT_NON_NULLABLE, false, .value.gc_obj = 0 }, +#endif #endif { "global", "NaN", VALUE_TYPE_F64, .value.u64 = 0x7FF8000000000000LL }, { "global", "Infinity", VALUE_TYPE_F64, .value.u64 = 0x7FF0000000000000LL } diff --git a/core/iwasm/libraries/libc-emcc/libc_emcc_wrapper.c b/core/iwasm/libraries/libc-emcc/libc_emcc_wrapper.c index 23c02aad3..c21b96261 100644 --- a/core/iwasm/libraries/libc-emcc/libc_emcc_wrapper.c +++ b/core/iwasm/libraries/libc-emcc/libc_emcc_wrapper.c @@ -269,14 +269,14 @@ getentropy_wrapper(wasm_exec_env_t exec_env, void *buffer, uint32 length) static int setjmp_wrapper(wasm_exec_env_t exec_env, void *jmp_buf) { - os_printf("setjmp() called\n"); + LOG_DEBUG("setjmp() called\n"); return 0; } static void longjmp_wrapper(wasm_exec_env_t exec_env, void *jmp_buf, int val) { - os_printf("longjmp() called\n"); + LOG_DEBUG("longjmp() called\n"); } #if !defined(BH_PLATFORM_LINUX_SGX) diff --git a/core/shared/mem-alloc/ems/ems_alloc.c b/core/shared/mem-alloc/ems/ems_alloc.c index 0e2c4da7c..b667fbe9f 100644 --- a/core/shared/mem-alloc/ems/ems_alloc.c +++ b/core/shared/mem-alloc/ems/ems_alloc.c @@ -5,6 +5,27 @@ #include "ems_gc_internal.h" +#if WASM_ENABLE_GC != 0 +#define LOCK_HEAP(heap) \ + do { \ + if (!heap->is_doing_reclaim) \ + /* If the heap is doing reclaim, it must have been locked, \ + we should not lock the heap again. */ \ + os_mutex_lock(&heap->lock); \ + } while (0) +#define UNLOCK_HEAP(heap) \ + do { \ + if (!heap->is_doing_reclaim) \ + /* If the heap is doing reclaim, it must have been locked, \ + and will be unlocked after reclaim, we should not \ + unlock the heap again. */ \ + os_mutex_unlock(&heap->lock); \ + } while (0) +#else +#define LOCK_HEAP(heap) os_mutex_lock(&heap->lock) +#define UNLOCK_HEAP(heap) os_mutex_unlock(&heap->lock) +#endif + static inline bool hmu_is_in_heap(void *hmu, gc_uint8 *heap_base_addr, gc_uint8 *heap_end_addr) { @@ -199,7 +220,7 @@ unlink_hmu(gc_heap_t *heap, hmu_t *hmu) } if (!node) { - os_printf("[GC_ERROR]couldn't find the node in the normal list\n"); + LOG_ERROR("[GC_ERROR]couldn't find the node in the normal list\n"); } } else { @@ -332,6 +353,11 @@ alloc_hmu(gc_heap_t *heap, gc_size_t size) bh_assert(gci_is_heap_valid(heap)); bh_assert(size > 0 && !(size & 7)); +#if WASM_ENABLE_GC != 0 + /* In doing reclaim, gc must not alloc memory again. */ + bh_assert(!heap->is_doing_reclaim); +#endif + base_addr = heap->base_addr; end_addr = base_addr + heap->current_size; @@ -454,6 +480,34 @@ alloc_hmu(gc_heap_t *heap, gc_size_t size) return NULL; } +#if WASM_ENABLE_GC != 0 +static int +do_gc_heap(gc_heap_t *heap) +{ + int ret = GC_SUCCESS; +#if WASM_ENABLE_GC_PERF_PROFILING != 0 + uint64 start = 0, end = 0, time = 0; + + start = os_time_get_boot_microsecond(); +#endif + if (heap->is_reclaim_enabled) { + UNLOCK_HEAP(heap); + ret = gci_gc_heap(heap); + LOCK_HEAP(heap); + } +#if WASM_ENABLE_GC_PERF_PROFILING != 0 + end = os_time_get_boot_microsecond(); + time = end - start; + heap->total_gc_time += time; + if (time > heap->max_gc_time) { + heap->max_gc_time = time; + } + heap->total_gc_count += 1; +#endif + return ret; +} +#endif + /** * Find a proper HMU with given size * @@ -475,12 +529,29 @@ alloc_hmu_ex(gc_heap_t *heap, gc_size_t size) bh_assert(gci_is_heap_valid(heap)); bh_assert(size > 0 && !(size & 7)); +#if WASM_ENABLE_GC != 0 +#if GC_IN_EVERY_ALLOCATION != 0 + if (GC_SUCCESS != do_gc_heap(heap)) + return NULL; +#else + if (heap->total_free_size < heap->gc_threshold) { + if (GC_SUCCESS != do_gc_heap(heap)) + return NULL; + } + else { + hmu_t *ret = NULL; + if ((ret = alloc_hmu(heap, size))) { + return ret; + } + if (GC_SUCCESS != do_gc_heap(heap)) + return NULL; + } +#endif +#endif + return alloc_hmu(heap, size); } -static unsigned long g_total_malloc = 0; -static unsigned long g_total_free = 0; - #if BH_ENABLE_GC_VERIFY == 0 gc_object_t gc_alloc_vo(void *vheap, gc_size_t size) @@ -504,12 +575,12 @@ gc_alloc_vo_internal(void *vheap, gc_size_t size, const char *file, int line) #if BH_ENABLE_GC_CORRUPTION_CHECK != 0 if (heap->is_heap_corrupted) { - os_printf("[GC_ERROR]Heap is corrupted, allocate memory failed.\n"); + LOG_ERROR("[GC_ERROR]Heap is corrupted, allocate memory failed.\n"); return NULL; } #endif - os_mutex_lock(&heap->lock); + LOCK_HEAP(heap); hmu = alloc_hmu_ex(heap, tot_size); if (!hmu) @@ -520,7 +591,9 @@ gc_alloc_vo_internal(void *vheap, gc_size_t size, const char *file, int line) the required size, reset it here */ tot_size = hmu_get_size(hmu); - g_total_malloc += tot_size; +#if GC_STAT_DATA != 0 + heap->total_size_allocated += tot_size; +#endif hmu_set_ut(hmu, HMU_VO); hmu_unfree_vo(hmu); @@ -535,7 +608,7 @@ gc_alloc_vo_internal(void *vheap, gc_size_t size, const char *file, int line) memset((uint8 *)ret + size, 0, tot_size - tot_size_unaligned); finish: - os_mutex_unlock(&heap->lock); + UNLOCK_HEAP(heap); return ret; } @@ -566,7 +639,7 @@ gc_realloc_vo_internal(void *vheap, void *ptr, gc_size_t size, const char *file, #if BH_ENABLE_GC_CORRUPTION_CHECK != 0 if (heap->is_heap_corrupted) { - os_printf("[GC_ERROR]Heap is corrupted, allocate memory failed.\n"); + LOG_ERROR("[GC_ERROR]Heap is corrupted, allocate memory failed.\n"); return NULL; } #endif @@ -582,7 +655,7 @@ gc_realloc_vo_internal(void *vheap, void *ptr, gc_size_t size, const char *file, base_addr = heap->base_addr; end_addr = base_addr + heap->current_size; - os_mutex_lock(&heap->lock); + LOCK_HEAP(heap); if (hmu_old) { hmu_next = (hmu_t *)((char *)hmu_old + tot_size_old); @@ -592,7 +665,7 @@ gc_realloc_vo_internal(void *vheap, void *ptr, gc_size_t size, const char *file, if (ut == HMU_FC && tot_size <= tot_size_old + tot_size_next) { /* current node and next node meets requirement */ if (!unlink_hmu(heap, hmu_next)) { - os_mutex_unlock(&heap->lock); + UNLOCK_HEAP(heap); return NULL; } hmu_set_size(hmu_old, tot_size); @@ -605,12 +678,12 @@ gc_realloc_vo_internal(void *vheap, void *ptr, gc_size_t size, const char *file, hmu_next = (hmu_t *)((char *)hmu_old + tot_size); tot_size_next = tot_size_old + tot_size_next - tot_size; if (!gci_add_fc(heap, hmu_next, tot_size_next)) { - os_mutex_unlock(&heap->lock); + UNLOCK_HEAP(heap); return NULL; } hmu_mark_pinuse(hmu_next); } - os_mutex_unlock(&heap->lock); + UNLOCK_HEAP(heap); return obj_old; } } @@ -624,7 +697,10 @@ gc_realloc_vo_internal(void *vheap, void *ptr, gc_size_t size, const char *file, /* the total size allocated may be larger than the required size, reset it here */ tot_size = hmu_get_size(hmu); - g_total_malloc += tot_size; + +#if GC_STAT_DATA != 0 + heap->total_size_allocated += tot_size; +#endif hmu_set_ut(hmu, HMU_VO); hmu_unfree_vo(hmu); @@ -647,7 +723,7 @@ finish: } } - os_mutex_unlock(&heap->lock); + UNLOCK_HEAP(heap); if (ret && obj_old) gc_free_vo(vheap, obj_old); @@ -655,6 +731,93 @@ finish: return ret; } +#if GC_MANUALLY != 0 +void +gc_free_wo(void *vheap, void *ptr) +{ + gc_heap_t *heap = (gc_heap_t *)vheap; + gc_object_t *obj = (gc_object_t *)ptr; + hmu_t *hmu = obj_to_hmu(obj); + + bh_assert(gci_is_heap_valid(heap)); + bh_assert(obj); + bh_assert((gc_uint8 *)hmu >= heap->base_addr + && (gc_uint8 *)hmu < heap->base_addr + heap->current_size); + bh_assert(hmu_get_ut(hmu) == HMU_WO); + + hmu_unmark_wo(hmu); + (void)heap; +} +#endif + +/* see ems_gc.h for description*/ +#if BH_ENABLE_GC_VERIFY == 0 +gc_object_t +gc_alloc_wo(void *vheap, gc_size_t size) +#else +gc_object_t +gc_alloc_wo_internal(void *vheap, gc_size_t size, const char *file, int line) +#endif +{ + gc_heap_t *heap = (gc_heap_t *)vheap; + hmu_t *hmu = NULL; + gc_object_t ret = (gc_object_t)NULL; + gc_size_t tot_size = 0, tot_size_unaligned; + + /* hmu header + prefix + obj + suffix */ + tot_size_unaligned = HMU_SIZE + OBJ_PREFIX_SIZE + size + OBJ_SUFFIX_SIZE; + /* aligned size*/ + tot_size = GC_ALIGN_8(tot_size_unaligned); + if (tot_size < size) + /* integer overflow */ + return NULL; + +#if BH_ENABLE_GC_CORRUPTION_CHECK != 0 + if (heap->is_heap_corrupted) { + os_printf("[GC_ERROR]Heap is corrupted, allocate memory failed.\n"); + return NULL; + } +#endif + + LOCK_HEAP(heap); + + hmu = alloc_hmu_ex(heap, tot_size); + if (!hmu) + goto finish; + + /* Do we need to memset the memory to 0? */ + /* memset((char *)hmu + sizeof(*hmu), 0, tot_size - sizeof(*hmu)); */ + + bh_assert(hmu_get_size(hmu) >= tot_size); + /* the total size allocated may be larger than + the required size, reset it here */ + tot_size = hmu_get_size(hmu); + +#if GC_STAT_DATA != 0 + heap->total_size_allocated += tot_size; +#endif + + hmu_set_ut(hmu, HMU_WO); +#if GC_MANUALLY != 0 + hmu_mark_wo(hmu); +#else + hmu_unmark_wo(hmu); +#endif + +#if BH_ENABLE_GC_VERIFY != 0 + hmu_init_prefix_and_suffix(hmu, tot_size, file, line); +#endif + + ret = hmu_to_obj(hmu); + if (tot_size > tot_size_unaligned) + /* clear buffer appended by GC_ALIGN_8() */ + memset((uint8 *)ret + size, 0, tot_size - tot_size_unaligned); + +finish: + UNLOCK_HEAP(heap); + return ret; +} + /** * Do some checking to see if given pointer is a possible valid heap * @return GC_TRUE if all checking passed, GC_FALSE otherwise @@ -693,7 +856,7 @@ gc_free_vo_internal(void *vheap, gc_object_t obj, const char *file, int line) #if BH_ENABLE_GC_CORRUPTION_CHECK != 0 if (heap->is_heap_corrupted) { - os_printf("[GC_ERROR]Heap is corrupted, free memory failed.\n"); + LOG_ERROR("[GC_ERROR]Heap is corrupted, free memory failed.\n"); return GC_ERROR; } #endif @@ -703,7 +866,7 @@ gc_free_vo_internal(void *vheap, gc_object_t obj, const char *file, int line) base_addr = heap->base_addr; end_addr = base_addr + heap->current_size; - os_mutex_lock(&heap->lock); + LOCK_HEAP(heap); if (hmu_is_in_heap(hmu, base_addr, end_addr)) { #if BH_ENABLE_GC_VERIFY != 0 @@ -719,10 +882,12 @@ gc_free_vo_internal(void *vheap, gc_object_t obj, const char *file, int line) size = hmu_get_size(hmu); - g_total_free += size; - heap->total_free_size += size; +#if GC_STAT_DATA != 0 + heap->total_size_freed += size; +#endif + if (!hmu_get_pinuse(hmu)) { prev = (hmu_t *)((char *)hmu - *((int *)hmu - 1)); @@ -767,7 +932,7 @@ gc_free_vo_internal(void *vheap, gc_object_t obj, const char *file, int line) } out: - os_mutex_unlock(&heap->lock); + UNLOCK_HEAP(heap); return ret; } @@ -778,8 +943,12 @@ gc_dump_heap_stats(gc_heap_t *heap) os_printf("total free: %" PRIu32 ", current: %" PRIu32 ", highmark: %" PRIu32 "\n", heap->total_free_size, heap->current_size, heap->highmark_size); - os_printf("g_total_malloc=%lu, g_total_free=%lu, occupied=%lu\n", - g_total_malloc, g_total_free, g_total_malloc - g_total_free); +#if GC_STAT_DATA != 0 + os_printf("total size allocated: %" PRIu64 ", total size freed: %" PRIu64 + ", total occupied: %" PRIu64 "\n", + heap->total_size_allocated, heap->total_size_freed, + heap->total_size_allocated - heap->total_size_freed); +#endif } uint32 @@ -804,18 +973,18 @@ gci_dump(gc_heap_t *heap) ut = hmu_get_ut(cur); size = hmu_get_size(cur); p = hmu_get_pinuse(cur); - mark = hmu_is_jo_marked(cur); + mark = hmu_is_wo_marked(cur); if (ut == HMU_VO) inuse = 'V'; - else if (ut == HMU_JO) - inuse = hmu_is_jo_marked(cur) ? 'J' : 'j'; + else if (ut == HMU_WO) + inuse = hmu_is_wo_marked(cur) ? 'W' : 'w'; else if (ut == HMU_FC) inuse = 'F'; #if BH_ENABLE_GC_CORRUPTION_CHECK != 0 if (size == 0 || size > (uint32)((uint8 *)end - (uint8 *)cur)) { - os_printf("[GC_ERROR]Heap is corrupted, heap dump failed.\n"); + LOG_ERROR("[GC_ERROR]Heap is corrupted, heap dump failed.\n"); heap->is_heap_corrupted = true; return; } @@ -838,10 +1007,163 @@ gci_dump(gc_heap_t *heap) #if BH_ENABLE_GC_CORRUPTION_CHECK != 0 if (cur != end) { - os_printf("[GC_ERROR]Heap is corrupted, heap dump failed.\n"); + LOG_ERROR("[GC_ERROR]Heap is corrupted, heap dump failed.\n"); heap->is_heap_corrupted = true; } #else bh_assert(cur == end); #endif } + +#if WASM_ENABLE_GC != 0 +extra_info_node_t * +gc_search_extra_info_node(gc_handle_t handle, gc_object_t obj, + gc_size_t *p_index) +{ + gc_heap_t *vheap = (gc_heap_t *)handle; + int32 low = 0, high = vheap->extra_info_node_cnt - 1; + int32 mid; + extra_info_node_t *node; + + if (!vheap->extra_info_nodes) + return NULL; + + while (low <= high) { + mid = (low + high) / 2; + node = vheap->extra_info_nodes[mid]; + + if (obj == node->obj) { + if (p_index) { + *p_index = mid; + } + return node; + } + else if (obj < node->obj) { + high = mid - 1; + } + else { + low = mid + 1; + } + } + + if (p_index) { + *p_index = low; + } + return NULL; +} + +static bool +insert_extra_info_node(gc_heap_t *vheap, extra_info_node_t *node) +{ + gc_size_t index; + extra_info_node_t *orig_node; + + if (!vheap->extra_info_nodes) { + vheap->extra_info_nodes = vheap->extra_info_normal_nodes; + vheap->extra_info_node_capacity = sizeof(vheap->extra_info_normal_nodes) + / sizeof(extra_info_node_t *); + vheap->extra_info_nodes[0] = node; + vheap->extra_info_node_cnt = 1; + return true; + } + + /* extend array */ + if (vheap->extra_info_node_cnt == vheap->extra_info_node_capacity) { + extra_info_node_t **new_nodes = NULL; + gc_size_t new_capacity = vheap->extra_info_node_capacity * 3 / 2; + gc_size_t total_size = sizeof(extra_info_node_t *) * new_capacity; + + new_nodes = (extra_info_node_t **)BH_MALLOC(total_size); + if (!new_nodes) { + LOG_ERROR("alloc extra info nodes failed"); + return false; + } + + bh_memcpy_s(new_nodes, total_size, vheap->extra_info_nodes, + sizeof(extra_info_node_t *) * vheap->extra_info_node_cnt); + if (vheap->extra_info_nodes != vheap->extra_info_normal_nodes) { + BH_FREE(vheap->extra_info_nodes); + } + + vheap->extra_info_nodes = new_nodes; + vheap->extra_info_node_capacity = new_capacity; + } + + orig_node = gc_search_extra_info_node(vheap, node->obj, &index); + if (orig_node) { + /* replace the old node */ + vheap->extra_info_nodes[index] = node; + BH_FREE(orig_node); + } + else { + bh_memmove_s(vheap->extra_info_nodes + index + 1, + (vheap->extra_info_node_capacity - index - 1) + * sizeof(extra_info_node_t *), + vheap->extra_info_nodes + index, + (vheap->extra_info_node_cnt - index) + * sizeof(extra_info_node_t *)); + vheap->extra_info_nodes[index] = node; + vheap->extra_info_node_cnt += 1; + } + + return true; +} + +bool +gc_set_finalizer(gc_handle_t handle, gc_object_t obj, gc_finalizer_t cb, + void *data) +{ + extra_info_node_t *node = NULL; + gc_heap_t *vheap = (gc_heap_t *)handle; + + node = (extra_info_node_t *)BH_MALLOC(sizeof(extra_info_node_t)); + + if (!node) { + LOG_ERROR("alloc a new extra info node failed"); + return GC_FALSE; + } + memset(node, 0, sizeof(extra_info_node_t)); + + node->finalizer = cb; + node->obj = obj; + node->data = data; + + LOCK_HEAP(vheap); + if (!insert_extra_info_node(vheap, node)) { + BH_FREE(node); + UNLOCK_HEAP(vheap); + return GC_FALSE; + } + UNLOCK_HEAP(vheap); + + gct_vm_set_extra_info_flag(obj, true); + return GC_TRUE; +} + +void +gc_unset_finalizer(gc_handle_t handle, gc_object_t obj) +{ + gc_size_t index; + gc_heap_t *vheap = (gc_heap_t *)handle; + extra_info_node_t *node; + + LOCK_HEAP(vheap); + node = gc_search_extra_info_node(vheap, obj, &index); + + if (!node) { + UNLOCK_HEAP(vheap); + return; + } + + BH_FREE(node); + bh_memmove_s( + vheap->extra_info_nodes + index, + (vheap->extra_info_node_capacity - index) * sizeof(extra_info_node_t *), + vheap->extra_info_nodes + index + 1, + (vheap->extra_info_node_cnt - index - 1) * sizeof(extra_info_node_t *)); + vheap->extra_info_node_cnt -= 1; + UNLOCK_HEAP(vheap); + + gct_vm_set_extra_info_flag(obj, false); +} +#endif diff --git a/core/shared/mem-alloc/ems/ems_gc.c b/core/shared/mem-alloc/ems/ems_gc.c new file mode 100644 index 000000000..b0f14772b --- /dev/null +++ b/core/shared/mem-alloc/ems/ems_gc.c @@ -0,0 +1,493 @@ +/* + * Copyright (C) 2022 Tencent Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include "ems_gc.h" +#include "ems_gc_internal.h" + +#define GB (1 << 30UL) + +#define MARK_NODE_OBJ_CNT 256 + +#if WASM_ENABLE_GC != 0 + +/* mark node is used for gc marker*/ +typedef struct mark_node_struct { + /* number of to-expand objects can be saved in this node */ + gc_size_t cnt; + + /* the first unused index */ + uint32 idx; + + /* next node on the node list */ + struct mark_node_struct *next; + + /* the actual to-expand objects list */ + gc_object_t set[MARK_NODE_OBJ_CNT]; +} mark_node_t; + +/** + * Alloc a mark node from the native heap + * + * @return a valid mark node if success, NULL otherwise + */ +static mark_node_t * +alloc_mark_node(void) +{ + mark_node_t *ret = (mark_node_t *)BH_MALLOC(sizeof(mark_node_t)); + + if (!ret) { + LOG_ERROR("alloc a new mark node failed"); + return NULL; + } + ret->cnt = sizeof(ret->set) / sizeof(ret->set[0]); + ret->idx = 0; + ret->next = NULL; + return ret; +} + +/* Free a mark node to the native heap + * + * @param node the mark node to free, should not be NULL + */ +static void +free_mark_node(mark_node_t *node) +{ + bh_assert(node); + BH_FREE((gc_object_t)node); +} + +/** + * Sweep phase of mark_sweep algorithm + * @param heap the heap to sweep, should be a valid instance heap + * which has already been marked + */ +static void +sweep_instance_heap(gc_heap_t *heap) +{ + hmu_t *cur = NULL, *end = NULL, *last = NULL; + hmu_type_t ut; + gc_size_t size; + int i, lsize; + gc_size_t tot_free = 0; + + bh_assert(gci_is_heap_valid(heap)); + + cur = (hmu_t *)heap->base_addr; + last = NULL; + end = (hmu_t *)((char *)heap->base_addr + heap->current_size); + + /* reset KFC */ + lsize = + (int)(sizeof(heap->kfc_normal_list) / sizeof(heap->kfc_normal_list[0])); + for (i = 0; i < lsize; i++) { + heap->kfc_normal_list[i].next = NULL; + } + heap->kfc_tree_root->right = NULL; + heap->root_set = NULL; + + while (cur < end) { + ut = hmu_get_ut(cur); + size = hmu_get_size(cur); + bh_assert(size > 0); + + if (ut == HMU_FC || ut == HMU_FM + || (ut == HMU_VO && hmu_is_vo_freed(cur)) + || (ut == HMU_WO && !hmu_is_wo_marked(cur))) { + /* merge previous free areas with current one */ + if (!last) + last = cur; + + if (ut == HMU_WO) { + /* Invoke registered finalizer */ + gc_object_t cur_obj = hmu_to_obj(cur); + if (gct_vm_get_extra_info_flag(cur_obj)) { + extra_info_node_t *node = gc_search_extra_info_node( + (gc_handle_t)heap, cur_obj, NULL); + bh_assert(node); + node->finalizer(node->obj, node->data); + gc_unset_finalizer((gc_handle_t)heap, cur_obj); + } + } + } + else { + /* current block is still live */ + if (last) { + tot_free += (char *)cur - (char *)last; + gci_add_fc(heap, last, (char *)cur - (char *)last); + hmu_mark_pinuse(last); + last = NULL; + } + + if (ut == HMU_WO) { + /* unmark it */ + hmu_unmark_wo(cur); + } + } + + cur = (hmu_t *)((char *)cur + size); + } + + bh_assert(cur == end); + + if (last) { + tot_free += (char *)cur - (char *)last; + gci_add_fc(heap, last, (char *)cur - (char *)last); + hmu_mark_pinuse(last); + } + + heap->total_free_size = tot_free; + +#if GC_STAT_DATA != 0 + heap->total_gc_count++; + if ((heap->current_size - tot_free) > heap->highmark_size) + heap->highmark_size = heap->current_size - tot_free; + +#endif + gc_update_threshold(heap); +} + +/** + * Add a to-expand node to the to-expand list + * + * @param heap should be a valid instance heap + * @param obj should be a valid wo inside @heap + * + * @return GC_ERROR if there is no more resource for marking, + * GC_SUCCESS if success + */ +static int +add_wo_to_expand(gc_heap_t *heap, gc_object_t obj) +{ + mark_node_t *mark_node = NULL, *new_node = NULL; + hmu_t *hmu = NULL; + + bh_assert(obj); + + hmu = obj_to_hmu(obj); + + bh_assert(gci_is_heap_valid(heap)); + bh_assert((gc_uint8 *)hmu >= heap->base_addr + && (gc_uint8 *)hmu < heap->base_addr + heap->current_size); + bh_assert(hmu_get_ut(hmu) == HMU_WO); + + if (hmu_is_wo_marked(hmu)) + return GC_SUCCESS; /* already marked*/ + + mark_node = (mark_node_t *)heap->root_set; + if (!mark_node || mark_node->idx == mark_node->cnt) { + new_node = alloc_mark_node(); + if (!new_node) { + LOG_ERROR("can not add obj to mark node because of mark node " + "allocation failed"); + return GC_ERROR; + } + new_node->next = mark_node; + heap->root_set = new_node; + mark_node = new_node; + } + + mark_node->set[mark_node->idx++] = obj; + hmu_mark_wo(hmu); + return GC_SUCCESS; +} + +/* Check ems_gc.h for description*/ +int +gc_add_root(void *heap_p, gc_object_t obj) +{ + gc_heap_t *heap = (gc_heap_t *)heap_p; + hmu_t *hmu = NULL; + + if (!obj) { + LOG_ERROR("gc_add_root with NULL obj"); + return GC_ERROR; + } + + hmu = obj_to_hmu(obj); + + if (!gci_is_heap_valid(heap)) { + LOG_ERROR("vm_get_gc_handle_for_current_instance returns invalid heap"); + return GC_ERROR; + } + + if (!((gc_uint8 *)hmu >= heap->base_addr + && (gc_uint8 *)hmu < heap->base_addr + heap->current_size)) { + LOG_ERROR("Obj is not a object in current instance heap"); + return GC_ERROR; + } + + if (hmu_get_ut(hmu) != HMU_WO) { + LOG_ERROR("Given object is not wo"); + return GC_ERROR; + } + + if (add_wo_to_expand(heap, obj) != GC_SUCCESS) { + heap->is_fast_marking_failed = 1; + return GC_ERROR; + } + + return GC_SUCCESS; +} + +/** + * Unmark all marked objects to do rollback + * + * @param heap the heap to do rollback, should be a valid instance heap + */ +static void +rollback_mark(gc_heap_t *heap) +{ + mark_node_t *mark_node = NULL, *next_mark_node = NULL; + hmu_t *cur = NULL, *end = NULL; + hmu_type_t ut; + gc_size_t size; + + bh_assert(gci_is_heap_valid(heap)); + + /* roll back*/ + mark_node = (mark_node_t *)heap->root_set; + while (mark_node) { + next_mark_node = mark_node->next; + free_mark_node(mark_node); + mark_node = next_mark_node; + } + + heap->root_set = NULL; + + /* then traverse the heap to unmark all marked wos*/ + + cur = (hmu_t *)heap->base_addr; + end = (hmu_t *)((char *)heap->base_addr + heap->current_size); + + while (cur < end) { + ut = hmu_get_ut(cur); + size = hmu_get_size(cur); + + if (ut == HMU_WO && hmu_is_wo_marked(cur)) { + hmu_unmark_wo(cur); + } + + cur = (hmu_t *)((char *)cur + size); + } + + bh_assert(cur == end); +} + +/** + * Reclaim GC instance heap + * + * @param heap the heap to reclaim, should be a valid instance heap + * + * @return GC_SUCCESS if success, GC_ERROR otherwise + */ +static int +reclaim_instance_heap(gc_heap_t *heap) +{ + mark_node_t *mark_node = NULL; + int idx = 0, j = 0; + bool ret, is_compact_mode = false; + gc_object_t obj = NULL, ref = NULL; + hmu_t *hmu = NULL; + gc_uint32 ref_num = 0, ref_start_offset = 0, size = 0, offset = 0; + gc_uint16 *ref_list = NULL; + + bh_assert(gci_is_heap_valid(heap)); + + heap->root_set = NULL; + +#if WASM_ENABLE_THREAD_MGR == 0 + if (!heap->exec_env) + return GC_SUCCESS; + ret = gct_vm_begin_rootset_enumeration(heap->exec_env, heap); +#else + if (!heap->cluster) + return GC_SUCCESS; + ret = gct_vm_begin_rootset_enumeration(heap->cluster, heap); +#endif + if (!ret) + return GC_ERROR; + +#if BH_ENABLE_GC_VERIFY != 0 + /* no matter whether the enumeration is successful or not, the data + collected should be checked at first */ + mark_node = (mark_node_t *)heap->root_set; + while (mark_node) { + /* all nodes except first should be full filled */ + bh_assert(mark_node == (mark_node_t *)heap->root_set + || mark_node->idx == mark_node->cnt); + + /* all nodes should be non-empty */ + bh_assert(mark_node->idx > 0); + + for (idx = 0; idx < (int)mark_node->idx; idx++) { + obj = mark_node->set[idx]; + hmu = obj_to_hmu(obj); + bh_assert(hmu_is_wo_marked(hmu)); + bh_assert((gc_uint8 *)hmu >= heap->base_addr + && (gc_uint8 *)hmu + < heap->base_addr + heap->current_size); + } + + mark_node = mark_node->next; + } +#endif + + /* TODO: when fast marking failed, we can still do slow + marking, currently just simply roll it back. */ + if (heap->is_fast_marking_failed) { + LOG_ERROR("enumerate rootset failed"); + LOG_ERROR("all marked wos will be unmarked to keep heap consistency"); + + rollback_mark(heap); + heap->is_fast_marking_failed = 0; + return GC_ERROR; + } + + /* the algorithm we use to mark all objects */ + /* 1. mark rootset and organize them into a mark_node list (last marked + * roots at list header, i.e. stack top) */ + /* 2. in every iteration, we use the top node to expand*/ + /* 3. execute step 2 till no expanding */ + /* this is a BFS & DFS mixed algorithm, but more like DFS */ + mark_node = (mark_node_t *)heap->root_set; + while (mark_node) { + heap->root_set = mark_node->next; + + /* note that mark_node->idx may change in each loop */ + for (idx = 0; idx < (int)mark_node->idx; idx++) { + obj = mark_node->set[idx]; + hmu = obj_to_hmu(obj); + size = hmu_get_size(hmu); + + if (!gct_vm_get_wasm_object_ref_list(obj, &is_compact_mode, + &ref_num, &ref_list, + &ref_start_offset)) { + LOG_ERROR("mark process failed because failed " + "vm_get_wasm_object_ref_list"); + break; + } + + if (ref_num >= 2U * GB) { + LOG_ERROR("Invalid ref_num returned"); + break; + } + + if (is_compact_mode) { + for (j = 0; j < (int)ref_num; j++) { + offset = ref_start_offset + j * sizeof(void *); + bh_assert(offset + sizeof(void *) < size); + ref = *(gc_object_t *)(((gc_uint8 *)obj) + offset); + if (ref == NULL_REF || ((uintptr_t)ref & 1)) + continue; /* null object or i31 object */ + if (add_wo_to_expand(heap, ref) == GC_ERROR) { + LOG_ERROR("add_wo_to_expand failed"); + break; + } + } + if (j < (int)ref_num) + break; + } + else { + for (j = 0; j < (int)ref_num; j++) { + offset = ref_list[j]; + bh_assert(offset + sizeof(void *) < size); + + ref = *(gc_object_t *)(((gc_uint8 *)obj) + offset); + if (ref == NULL_REF || ((uintptr_t)ref & 1)) + continue; /* null object or i31 object */ + if (add_wo_to_expand(heap, ref) == GC_ERROR) { + LOG_ERROR("mark process failed"); + break; + } + } + if (j < (int)ref_num) + break; + } + } + if (idx < (int)mark_node->idx) + break; /* not yet done */ + + /* obj's in mark_node are all expanded */ + free_mark_node(mark_node); + mark_node = heap->root_set; + } + + if (mark_node) { + LOG_ERROR("mark process is not successfully finished"); + + free_mark_node(mark_node); + /* roll back is required */ + rollback_mark(heap); + + return GC_ERROR; + } + + /* now sweep */ + sweep_instance_heap(heap); + + (void)size; + + return GC_SUCCESS; +} + +/** + * Do GC on given heap + * + * @param the heap to do GC, should be a valid heap + * + * @return GC_SUCCESS if success, GC_ERROR otherwise + */ +int +gci_gc_heap(void *h) +{ + int ret = GC_ERROR; + gc_heap_t *heap = (gc_heap_t *)h; + + bh_assert(gci_is_heap_valid(heap)); + + LOG_VERBOSE("#reclaim instance heap %p", heap); + + gct_vm_gc_prepare(); + + gct_vm_mutex_lock(&heap->lock); + heap->is_doing_reclaim = 1; + + ret = reclaim_instance_heap(heap); + + heap->is_doing_reclaim = 0; + gct_vm_mutex_unlock(&heap->lock); + + gct_vm_gc_finished(); + + LOG_VERBOSE("#reclaim instance heap %p done", heap); + +#if BH_ENABLE_GC_VERIFY != 0 + gci_verify_heap(heap); +#endif + +#if GC_STAT_SHOW != 0 + gc_show_stat(heap); + gc_show_fragment(heap); +#endif + + return ret; +} + +int +gc_is_dead_object(void *obj) +{ + return !hmu_is_wo_marked(obj_to_hmu(obj)); +} + +#else + +int +gci_gc_heap(void *h) +{ + (void)h; + return GC_ERROR; +} + +#endif /* end of WASM_ENABLE_GC != 0 */ diff --git a/core/shared/mem-alloc/ems/ems_gc.h b/core/shared/mem-alloc/ems/ems_gc.h index 9a74d0046..293ad18e8 100644 --- a/core/shared/mem-alloc/ems/ems_gc.h +++ b/core/shared/mem-alloc/ems/ems_gc.h @@ -19,9 +19,27 @@ extern "C" { #endif +#ifndef GC_STAT_DATA +#define GC_STAT_DATA 0 +#endif + +#ifndef GC_STAT_SHOW +#define GC_STAT_SHOW 0 +#endif + +#ifndef GC_IN_EVERY_ALLOCATION +#define GC_IN_EVERY_ALLOCATION 0 +#endif + +#ifndef GC_MANUALLY +#define GC_MANUALLY 0 +#endif + #define GC_HEAD_PADDING 4 +#ifndef NULL_REF #define NULL_REF ((gc_object_t)NULL) +#endif #define GC_SUCCESS (0) #define GC_ERROR (-1) @@ -33,6 +51,7 @@ extern "C" { typedef void *gc_handle_t; typedef void *gc_object_t; +typedef uint64 gc_uint64; typedef int64 gc_int64; typedef uint32 gc_uint32; typedef int32 gc_int32; @@ -46,8 +65,24 @@ typedef enum { GC_STAT_TOTAL = 0, GC_STAT_FREE, GC_STAT_HIGHMARK, + GC_STAT_COUNT, + GC_STAT_TIME, + GC_STAT_MAX } GC_STAT_INDEX; +typedef void (*gc_finalizer_t)(void *obj, void *data); + +#ifndef EXTRA_INFO_NORMAL_NODE_CNT +#define EXTRA_INFO_NORMAL_NODE_CNT 32 +#endif + +/* extra information attached to specific object */ +typedef struct extra_info_node { + gc_object_t obj; + gc_finalizer_t finalizer; + void *data; +} extra_info_node_t; + /** * GC initialization from a buffer, which is separated into * two parts: the beginning of the buffer is used to create @@ -87,6 +122,28 @@ gc_init_with_struct_and_pool(char *struct_buf, gc_size_t struct_buf_size, int gc_destroy_with_pool(gc_handle_t handle); +#if WASM_ENABLE_GC != 0 +/** + * Enable or disable GC reclaim for a heap + * + * @param handle handle of the heap + * @param exec_env the exec_env of current module instance + */ +#if WASM_ENABLE_THREAD_MGR == 0 +void +gc_enable_gc_reclaim(gc_handle_t handle, void *exec_env); +#else +/** + * Enable or disable GC reclaim for a heap + * + * @param handle handle of the heap + * @param cluster the tread cluster of current module instance + */ +void +gc_enable_gc_reclaim(gc_handle_t handle, void *cluster); +#endif +#endif + /** * Return heap struct size */ @@ -136,6 +193,14 @@ gc_realloc_vo(void *heap, void *ptr, gc_size_t size); int gc_free_vo(void *heap, gc_object_t obj); +#if WASM_ENABLE_GC != 0 +gc_object_t +gc_alloc_wo(void *heap, gc_size_t size); + +void +gc_free_wo(void *vheap, void *ptr); +#endif + #else /* else of BH_ENABLE_GC_VERIFY */ gc_object_t @@ -148,6 +213,14 @@ gc_realloc_vo_internal(void *heap, void *ptr, gc_size_t size, const char *file, int gc_free_vo_internal(void *heap, gc_object_t obj, const char *file, int line); +#if WASM_ENABLE_GC != 0 +gc_object_t +gc_alloc_wo_internal(void *heap, gc_size_t size, const char *file, int line); + +void +gc_free_wo_internal(void *vheap, void *ptr, const char *file, int line); +#endif + /* clang-format off */ #define gc_alloc_vo(heap, size) \ gc_alloc_vo_internal(heap, size, __FILE__, __LINE__) @@ -157,10 +230,116 @@ gc_free_vo_internal(void *heap, gc_object_t obj, const char *file, int line); #define gc_free_vo(heap, obj) \ gc_free_vo_internal(heap, obj, __FILE__, __LINE__) + +#if WASM_ENABLE_GC != 0 +#define gc_alloc_wo(heap, size) \ + gc_alloc_wo_internal(heap, size, __FILE__, __LINE__) + +#define gc_free_wo(heap, obj) \ + gc_free_wo_internal(heap, obj, __FILE__, __LINE__) +#endif /* clang-format on */ #endif /* end of BH_ENABLE_GC_VERIFY */ +#if WASM_ENABLE_GC != 0 +/** + * Add gc object ref to the rootset of a gc heap. + * + * @param heap the heap to add the gc object to its rootset + * @param obj pointer to a valid WASM object managed by the gc heap. + * + * @return GC_SUCCESS if success, GC_ERROR otherwise + */ +int +gc_add_root(void *heap, gc_object_t obj); + +int +gci_gc_heap(void *heap); + +extra_info_node_t * +gc_search_extra_info_node(gc_handle_t handle, gc_object_t obj, + gc_size_t *p_index); + +/** + * Set finalizer to the given object, if another finalizer is set to the same + * object, the previous one will be cancelled + * + * @param handle handle of the heap + * @param obj object to set finalizer + * @param cb finalizer function to be called before this object is freed + * @param data custom data to be passed to finalizer function + * + * @return true if success, false otherwise + */ +bool +gc_set_finalizer(gc_handle_t handle, gc_object_t obj, gc_finalizer_t cb, + void *data); + +/** + * Unset finalizer to the given object + * + * @param handle handle of the heap + * @param obj object to unset finalizer + */ +void +gc_unset_finalizer(gc_handle_t handle, gc_object_t obj); + +#if WASM_ENABLE_THREAD_MGR == 0 +bool +wasm_runtime_traverse_gc_rootset(void *exec_env, void *heap); +#else +bool +wasm_runtime_traverse_gc_rootset(void *cluster, void *heap); +#endif + +bool +wasm_runtime_get_wasm_object_ref_list(gc_object_t obj, bool *p_is_compact_mode, + gc_uint32 *p_ref_num, + gc_uint16 **p_ref_list, + gc_uint32 *p_ref_start_offset); + +bool +wasm_runtime_get_wasm_object_extra_info_flag(gc_object_t obj); + +void +wasm_runtime_set_wasm_object_extra_info_flag(gc_object_t obj, bool set); + +void +wasm_runtime_gc_prepare(); + +void +wasm_runtime_gc_finalize(); +#endif /* end of WASM_ENABLE_GC != 0 */ + +#define GC_HEAP_STAT_SIZE (128 / 4) + +typedef struct { + int usage; + int usage_block; + int vo_usage; + int wo_usage; + int free; + int free_block; + int vo_free; + int wo_free; + int usage_sizes[GC_HEAP_STAT_SIZE]; + int free_sizes[GC_HEAP_STAT_SIZE]; +} gc_stat_t; + +void +gc_show_stat(gc_handle_t handle); + +#if WASM_ENABLE_GC != 0 +void +gc_show_fragment(gc_handle_t handle); + +#if WASM_ENABLE_GC_PERF_PROFILING != 0 +void +gc_dump_perf_profiling(gc_handle_t *handle); +#endif +#endif + #ifdef __cplusplus } #endif diff --git a/core/shared/mem-alloc/ems/ems_gc_internal.h b/core/shared/mem-alloc/ems/ems_gc_internal.h index 6abe2b12a..c902d5711 100644 --- a/core/shared/mem-alloc/ems/ems_gc_internal.h +++ b/core/shared/mem-alloc/ems/ems_gc_internal.h @@ -17,8 +17,8 @@ extern "C" { typedef enum hmu_type_enum { HMU_TYPE_MIN = 0, HMU_TYPE_MAX = 3, - HMU_JO = 3, - HMU_VO = 2, + HMU_WO = 3, /* WASM Object */ + HMU_VO = 2, /* VM Object */ HMU_FC = 1, HMU_FM = 0 } hmu_type_t; @@ -135,13 +135,13 @@ hmu_verify(void *vheap, hmu_t *hmu); #define hmu_unmark_pinuse(hmu) CLRBIT((hmu)->header, HMU_P_OFFSET) #define hmu_get_pinuse(hmu) GETBIT((hmu)->header, HMU_P_OFFSET) -#define HMU_JO_VT_SIZE 27 -#define HMU_JO_VT_OFFSET 0 -#define HMU_JO_MB_OFFSET 28 +#define HMU_WO_VT_SIZE 27 +#define HMU_WO_VT_OFFSET 0 +#define HMU_WO_MB_OFFSET 28 -#define hmu_mark_jo(hmu) SETBIT((hmu)->header, HMU_JO_MB_OFFSET) -#define hmu_unmark_jo(hmu) CLRBIT((hmu)->header, HMU_JO_MB_OFFSET) -#define hmu_is_jo_marked(hmu) GETBIT((hmu)->header, HMU_JO_MB_OFFSET) +#define hmu_mark_wo(hmu) SETBIT((hmu)->header, HMU_WO_MB_OFFSET) +#define hmu_unmark_wo(hmu) CLRBIT((hmu)->header, HMU_WO_MB_OFFSET) +#define hmu_is_wo_marked(hmu) GETBIT((hmu)->header, HMU_WO_MB_OFFSET) /** * The hmu size is divisible by 8, its lowest 3 bits are 0, so we only @@ -271,6 +271,33 @@ typedef struct gc_heap_struct { size[left] <= size[cur] < size[right] */ hmu_tree_node_t *kfc_tree_root; +#if WASM_ENABLE_GC != 0 + /* for rootset enumeration of private heap*/ + void *root_set; + +#if WASM_ENABLE_THREAD_MGR == 0 + /* exec_env of current wasm module instance */ + void *exec_env; +#else + /* thread cluster of current module instances */ + void *cluster; +#endif + + /* whether the fast mode of marking process that requires + additional memory fails. When the fast mode fails, the + marking process can still be done in the slow mode, which + doesn't need additional memory (by walking through all + blocks and marking sucessors of marked nodes until no new + node is marked). TODO: slow mode is not implemented. */ + unsigned is_fast_marking_failed : 1; + + /* whether the heap is doing reclaim */ + unsigned is_doing_reclaim : 1; + + /* Whether the heap can do reclaim */ + unsigned is_reclaim_enabled : 1; +#endif + #if BH_ENABLE_GC_CORRUPTION_CHECK != 0 /* whether heap is corrupted, e.g. the hmu nodes are modified by user */ @@ -280,8 +307,54 @@ typedef struct gc_heap_struct { gc_size_t init_size; gc_size_t highmark_size; gc_size_t total_free_size; + +#if WASM_ENABLE_GC != 0 + gc_size_t gc_threshold; + gc_size_t gc_threshold_factor; + gc_size_t total_gc_count; + gc_size_t total_gc_time; + gc_size_t max_gc_time; + /* Usually there won't be too many extra info node, so we try to use a fixed + * array to store them, if the fixed array don't have enough space to store + * the nodes, a new space will be allocated from heap */ + extra_info_node_t *extra_info_normal_nodes[EXTRA_INFO_NORMAL_NODE_CNT]; + /* Used to store extra information such as finalizer for specified nodes, we + * introduce a seperate space to store these information so only nodes who + * really require extra information will occupy additional memory spaces. */ + extra_info_node_t **extra_info_nodes; + gc_size_t extra_info_node_cnt; + gc_size_t extra_info_node_capacity; +#endif +#if GC_STAT_DATA != 0 + gc_uint64 total_size_allocated; + gc_uint64 total_size_freed; +#endif } gc_heap_t; +#if WASM_ENABLE_GC != 0 + +#define GC_DEFAULT_THRESHOLD_FACTOR 300 + +static inline void +gc_update_threshold(gc_heap_t *heap) +{ + heap->gc_threshold = + heap->total_free_size * heap->gc_threshold_factor / 1000; +} + +#define gct_vm_mutex_init os_mutex_init +#define gct_vm_mutex_destroy os_mutex_destroy +#define gct_vm_mutex_lock os_mutex_lock +#define gct_vm_mutex_unlock os_mutex_unlock +#define gct_vm_gc_prepare wasm_runtime_gc_prepare +#define gct_vm_gc_finished wasm_runtime_gc_finalize +#define gct_vm_begin_rootset_enumeration wasm_runtime_traverse_gc_rootset +#define gct_vm_get_wasm_object_ref_list wasm_runtime_get_wasm_object_ref_list +#define gct_vm_get_extra_info_flag wasm_runtime_get_wasm_object_extra_info_flag +#define gct_vm_set_extra_info_flag wasm_runtime_set_wasm_object_extra_info_flag + +#endif /* end of WAMS_ENABLE_GC != 0 */ + /** * MISC internal used APIs */ diff --git a/core/shared/mem-alloc/ems/ems_hmu.c b/core/shared/mem-alloc/ems/ems_hmu.c index f9d7c0f4a..e4c79e339 100644 --- a/core/shared/mem-alloc/ems/ems_hmu.c +++ b/core/shared/mem-alloc/ems/ems_hmu.c @@ -24,7 +24,7 @@ hmu_init_prefix_and_suffix(hmu_t *hmu, gc_size_t tot_size, gc_uint32 i = 0; bh_assert(hmu); - bh_assert(hmu_get_ut(hmu) == HMU_JO || hmu_get_ut(hmu) == HMU_VO); + bh_assert(hmu_get_ut(hmu) == HMU_WO || hmu_get_ut(hmu) == HMU_VO); bh_assert(tot_size >= OBJ_EXTRA_SIZE); bh_assert(!(tot_size & 7)); bh_assert(hmu_get_ut(hmu) != HMU_VO || hmu_get_size(hmu) >= tot_size); @@ -48,7 +48,9 @@ hmu_init_prefix_and_suffix(hmu_t *hmu, gc_size_t tot_size, void hmu_verify(void *vheap, hmu_t *hmu) { +#if BH_ENABLE_GC_CORRUPTION_CHECK != 0 gc_heap_t *heap = (gc_heap_t *)vheap; +#endif gc_object_prefix_t *prefix = NULL; gc_object_suffix_t *suffix = NULL; gc_uint32 i = 0; @@ -64,7 +66,7 @@ hmu_verify(void *vheap, hmu_t *hmu) size = prefix->size; suffix = (gc_object_suffix_t *)((gc_uint8 *)hmu + size - OBJ_SUFFIX_SIZE); - if (ut == HMU_VO || ut == HMU_JO) { + if (ut == HMU_VO || ut == HMU_WO) { /* check padding*/ for (i = 0; i < GC_OBJECT_PREFIX_PADDING_CNT; i++) { if (prefix->padding[i] != GC_OBJECT_PADDING_VALUE) { @@ -80,7 +82,7 @@ hmu_verify(void *vheap, hmu_t *hmu) } if (!is_padding_ok) { - os_printf("Invalid padding for object created at %s:%d\n", + LOG_ERROR("Invalid padding for object created at %s:%d\n", (prefix->file_name ? prefix->file_name : ""), prefix->line_no); #if BH_ENABLE_GC_CORRUPTION_CHECK != 0 diff --git a/core/shared/mem-alloc/ems/ems_kfc.c b/core/shared/mem-alloc/ems/ems_kfc.c index 1dda3ae03..8ab2df545 100644 --- a/core/shared/mem-alloc/ems/ems_kfc.c +++ b/core/shared/mem-alloc/ems/ems_kfc.c @@ -12,10 +12,11 @@ gc_init_internal(gc_heap_t *heap, char *base_addr, gc_size_t heap_max_size) int ret; memset(heap, 0, sizeof *heap); + memset(base_addr, 0, heap_max_size); ret = os_mutex_init(&heap->lock); if (ret != BHT_OK) { - os_printf("[GC_ERROR]failed to init lock\n"); + LOG_ERROR("[GC_ERROR]failed to init lock\n"); return NULL; } @@ -26,6 +27,10 @@ gc_init_internal(gc_heap_t *heap, char *base_addr, gc_size_t heap_max_size) heap->total_free_size = heap->current_size; heap->highmark_size = 0; +#if WASM_ENABLE_GC != 0 + heap->gc_threshold_factor = GC_DEFAULT_THRESHOLD_FACTOR; + gc_update_threshold(heap); +#endif root = heap->kfc_tree_root = (hmu_tree_node_t *)heap->kfc_tree_root_buf; memset(root, 0, sizeof *root); @@ -61,7 +66,7 @@ gc_init_with_pool(char *buf, gc_size_t buf_size) gc_size_t heap_max_size; if (buf_size < APP_HEAP_SIZE_MIN) { - os_printf("[GC_ERROR]heap init buf size (%" PRIu32 ") < %" PRIu32 "\n", + LOG_ERROR("[GC_ERROR]heap init buf size (%" PRIu32 ") < %" PRIu32 "\n", buf_size, (uint32)APP_HEAP_SIZE_MIN); return NULL; } @@ -90,23 +95,23 @@ gc_init_with_struct_and_pool(char *struct_buf, gc_size_t struct_buf_size, gc_size_t heap_max_size; if ((((uintptr_t)struct_buf) & 7) != 0) { - os_printf("[GC_ERROR]heap init struct buf not 8-byte aligned\n"); + LOG_ERROR("[GC_ERROR]heap init struct buf not 8-byte aligned\n"); return NULL; } if (struct_buf_size < sizeof(gc_handle_t)) { - os_printf("[GC_ERROR]heap init struct buf size (%" PRIu32 ") < %zu\n", + LOG_ERROR("[GC_ERROR]heap init struct buf size (%" PRIu32 ") < %zu\n", struct_buf_size, sizeof(gc_handle_t)); return NULL; } if ((((uintptr_t)pool_buf) & 7) != 0) { - os_printf("[GC_ERROR]heap init pool buf not 8-byte aligned\n"); + LOG_ERROR("[GC_ERROR]heap init pool buf not 8-byte aligned\n"); return NULL; } if (pool_buf_size < APP_HEAP_SIZE_MIN) { - os_printf("[GC_ERROR]heap init buf size (%" PRIu32 ") < %u\n", + LOG_ERROR("[GC_ERROR]heap init buf size (%" PRIu32 ") < %u\n", pool_buf_size, APP_HEAP_SIZE_MIN); return NULL; } @@ -129,6 +134,28 @@ gc_destroy_with_pool(gc_handle_t handle) gc_heap_t *heap = (gc_heap_t *)handle; int ret = GC_SUCCESS; +#if WASM_ENABLE_GC != 0 + gc_size_t i = 0; + + if (heap->extra_info_node_cnt > 0) { + for (i = 0; i < heap->extra_info_node_cnt; i++) { + extra_info_node_t *node = heap->extra_info_nodes[i]; +#if BH_ENABLE_GC_VERIFY != 0 + os_printf("Memory leak detected: gc object [%p] not claimed\n", + node->obj); +#endif + bh_assert(heap->is_reclaim_enabled); + node->finalizer(node->obj, node->data); + + BH_FREE(heap->extra_info_nodes[i]); + } + + if (heap->extra_info_nodes != heap->extra_info_normal_nodes) { + BH_FREE(heap->extra_info_nodes); + } + } +#endif + #if BH_ENABLE_GC_VERIFY != 0 hmu_t *cur = (hmu_t *)heap->base_addr; hmu_t *end = (hmu_t *)((char *)heap->base_addr + heap->current_size); @@ -138,17 +165,40 @@ gc_destroy_with_pool(gc_handle_t handle) !heap->is_heap_corrupted && #endif (hmu_t *)((char *)cur + hmu_get_size(cur)) != end) { - os_printf("Memory leak detected:\n"); + LOG_WARNING("Memory leak detected:\n"); gci_dump(heap); ret = GC_ERROR; } #endif os_mutex_destroy(&heap->lock); + memset(heap->base_addr, 0, heap->current_size); memset(heap, 0, sizeof(gc_heap_t)); return ret; } +#if WASM_ENABLE_GC != 0 +#if WASM_ENABLE_THREAD_MGR == 0 +void +gc_enable_gc_reclaim(gc_handle_t handle, void *exec_env) +{ + gc_heap_t *heap = (gc_heap_t *)handle; + + heap->is_reclaim_enabled = 1; + heap->exec_env = exec_env; +} +#else +void +gc_enable_gc_reclaim(gc_handle_t handle, void *cluster) +{ + gc_heap_t *heap = (gc_heap_t *)handle; + + heap->is_reclaim_enabled = 1; + heap->cluster = cluster; +} +#endif +#endif + uint32 gc_get_heap_struct_size() { @@ -175,14 +225,14 @@ gc_migrate(gc_handle_t handle, char *pool_buf_new, gc_size_t pool_buf_size) gc_size_t heap_max_size, size; if ((((uintptr_t)pool_buf_new) & 7) != 0) { - os_printf("[GC_ERROR]heap migrate pool buf not 8-byte aligned\n"); + LOG_ERROR("[GC_ERROR]heap migrate pool buf not 8-byte aligned\n"); return GC_ERROR; } heap_max_size = (uint32)(pool_buf_end - base_addr_new) & (uint32)~7; if (pool_buf_end < base_addr_new || heap_max_size < heap->current_size) { - os_printf("[GC_ERROR]heap migrate invlaid pool buf size\n"); + LOG_ERROR("[GC_ERROR]heap migrate invlaid pool buf size\n"); return GC_ERROR; } @@ -191,7 +241,7 @@ gc_migrate(gc_handle_t handle, char *pool_buf_new, gc_size_t pool_buf_size) #if BH_ENABLE_GC_CORRUPTION_CHECK != 0 if (heap->is_heap_corrupted) { - os_printf("[GC_ERROR]Heap is corrupted, heap migrate failed.\n"); + LOG_ERROR("[GC_ERROR]Heap is corrupted, heap migrate failed.\n"); return GC_ERROR; } #endif @@ -218,7 +268,7 @@ gc_migrate(gc_handle_t handle, char *pool_buf_new, gc_size_t pool_buf_size) #if BH_ENABLE_GC_CORRUPTION_CHECK != 0 if (size <= 0 || size > (uint32)((uint8 *)end - (uint8 *)cur)) { - os_printf("[GC_ERROR]Heap is corrupted, heap migrate failed.\n"); + LOG_ERROR("[GC_ERROR]Heap is corrupted, heap migrate failed.\n"); heap->is_heap_corrupted = true; return GC_ERROR; } @@ -247,7 +297,7 @@ gc_migrate(gc_handle_t handle, char *pool_buf_new, gc_size_t pool_buf_size) #if BH_ENABLE_GC_CORRUPTION_CHECK != 0 if (cur != end) { - os_printf("[GC_ERROR]Heap is corrupted, heap migrate failed.\n"); + LOG_ERROR("[GC_ERROR]Heap is corrupted, heap migrate failed.\n"); heap->is_heap_corrupted = true; return GC_ERROR; } @@ -287,12 +337,103 @@ gci_verify_heap(gc_heap_t *heap) } #endif +void +gc_heap_stat(void *heap_ptr, gc_stat_t *stat) +{ + hmu_t *cur = NULL, *end = NULL; + hmu_type_t ut; + gc_size_t size; + gc_heap_t *heap = (gc_heap_t *)heap_ptr; + + memset(stat, 0, sizeof(gc_stat_t)); + cur = (hmu_t *)heap->base_addr; + end = (hmu_t *)((char *)heap->base_addr + heap->current_size); + + while (cur < end) { + ut = hmu_get_ut(cur); + size = hmu_get_size(cur); + bh_assert(size > 0); + + if (ut == HMU_FC || ut == HMU_FM + || (ut == HMU_VO && hmu_is_vo_freed(cur)) + || (ut == HMU_WO && !hmu_is_wo_marked(cur))) { + if (ut == HMU_VO) + stat->vo_free += size; + if (ut == HMU_WO) + stat->wo_free += size; + stat->free += size; + stat->free_block++; + if (size / sizeof(int) < GC_HEAP_STAT_SIZE - 1) + stat->free_sizes[size / sizeof(int)] += 1; + else + stat->free_sizes[GC_HEAP_STAT_SIZE - 1] += 1; + } + else { + if (ut == HMU_VO) + stat->vo_usage += size; + if (ut == HMU_WO) + stat->wo_usage += size; + stat->usage += size; + stat->usage_block++; + if (size / sizeof(int) < GC_HEAP_STAT_SIZE - 1) + stat->usage_sizes[size / sizeof(int)] += 1; + else + stat->usage_sizes[GC_HEAP_STAT_SIZE - 1] += 1; + } + + cur = (hmu_t *)((char *)cur + size); + } +} + +void +gc_print_stat(void *heap_ptr, int verbose) +{ + gc_stat_t stat; + int i; + + bh_assert(heap_ptr != NULL); + gc_heap_t *heap = (gc_heap_t *)(heap_ptr); + + gc_heap_stat(heap, &stat); + + os_printf("# stat %s %p use %d free %d \n", "instance", heap, stat.usage, + stat.free); + os_printf("# stat %s %p wo_usage %d vo_usage %d \n", "instance", heap, + stat.wo_usage, stat.vo_usage); + os_printf("# stat %s %p wo_free %d vo_free %d \n", "instance", heap, + stat.wo_free, stat.vo_free); +#if WASM_ENABLE_GC == 0 + os_printf("# stat free size %" PRIu32 " high %" PRIu32 "\n", + heap->total_free_size, heap->highmark_size); +#else + os_printf("# stat gc %" PRIu32 " free size %" PRIu32 " high %" PRIu32 "\n", + heap->total_gc_count, heap->total_free_size, heap->highmark_size); +#endif + if (verbose) { + os_printf("usage sizes: \n"); + for (i = 0; i < GC_HEAP_STAT_SIZE; i++) + if (stat.usage_sizes[i]) + os_printf(" %d: %d; ", i * 4, stat.usage_sizes[i]); + os_printf(" \n"); + os_printf("free sizes: \n"); + for (i = 0; i < GC_HEAP_STAT_SIZE; i++) + if (stat.free_sizes[i]) + os_printf(" %d: %d; ", i * 4, stat.free_sizes[i]); + } +} + void * gc_heap_stats(void *heap_arg, uint32 *stats, int size) { int i; gc_heap_t *heap = (gc_heap_t *)heap_arg; + if (!gci_is_heap_valid(heap)) { + for (i = 0; i < size; i++) + stats[i] = 0; + return NULL; + } + for (i = 0; i < size; i++) { switch (i) { case GC_STAT_TOTAL: @@ -304,9 +445,83 @@ gc_heap_stats(void *heap_arg, uint32 *stats, int size) case GC_STAT_HIGHMARK: stats[i] = heap->highmark_size; break; +#if WASM_ENABLE_GC != 0 + case GC_STAT_COUNT: + stats[i] = heap->total_gc_count; + break; + case GC_STAT_TIME: + stats[i] = heap->total_gc_time; + break; +#endif default: break; } } + return heap; } + +void +gc_traverse_tree(hmu_tree_node_t *node, gc_size_t *stats, int *n) +{ + if (!node) + return; + + if (*n > 0) + gc_traverse_tree(node->right, stats, n); + + if (*n > 0) { + (*n)--; + stats[*n] = node->size; + } + + if (*n > 0) + gc_traverse_tree(node->left, stats, n); +} + +void +gc_show_stat(void *heap) +{ + + uint32 stats[GC_STAT_MAX]; + + heap = gc_heap_stats(heap, stats, GC_STAT_MAX); + + os_printf("\n[GC stats %p] %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 + " %" PRIu32 "\n", + heap, stats[0], stats[1], stats[2], stats[3], stats[4]); +} + +#if WASM_ENABLE_GC != 0 +void +gc_show_fragment(void *heap_arg) +{ + uint32 stats[3]; + int n = 3; + gc_heap_t *heap = (gc_heap_t *)heap_arg; + + memset(stats, 0, n * sizeof(int)); + gct_vm_mutex_lock(&heap->lock); + gc_traverse_tree(heap->kfc_tree_root, (gc_size_t *)stats, &n); + gct_vm_mutex_unlock(&heap->lock); + os_printf("\n[GC %p top sizes] %" PRIu32 " %" PRIu32 " %" PRIu32 "\n", heap, + stats[0], stats[1], stats[2]); +} + +#if WASM_ENABLE_GC_PERF_PROFILING != 0 +void +gc_dump_perf_profiling(gc_handle_t *handle) +{ + gc_heap_t *gc_heap_handle = (void *)handle; + if (gc_heap_handle) { + os_printf("\nGC performance summary\n"); + os_printf(" Total GC time (ms): %u\n", + gc_heap_handle->total_gc_time); + os_printf(" Max GC time (ms): %u\n", gc_heap_handle->max_gc_time); + } + else { + os_printf("Failed to dump GC performance\n"); + } +} +#endif +#endif diff --git a/core/shared/mem-alloc/mem_alloc.c b/core/shared/mem-alloc/mem_alloc.c index f952c1858..1f9e03d5a 100644 --- a/core/shared/mem-alloc/mem_alloc.c +++ b/core/shared/mem-alloc/mem_alloc.c @@ -4,6 +4,7 @@ */ #include "mem_alloc.h" +#include #if DEFAULT_MEM_ALLOCATOR == MEM_ALLOCATOR_EMS @@ -56,6 +57,43 @@ mem_allocator_free(mem_allocator_t allocator, void *ptr) gc_free_vo((gc_handle_t)allocator, ptr); } +#if WASM_ENABLE_GC != 0 +void * +mem_allocator_malloc_with_gc(mem_allocator_t allocator, uint32_t size) +{ + return gc_alloc_wo((gc_handle_t)allocator, size); +} + +#if WASM_GC_MANUALLY != 0 +void +mem_allocator_free_with_gc(mem_allocator_t allocator, void *ptr) +{ + if (ptr) + gc_free_wo((gc_handle_t)allocator, ptr); +} +#endif + +#if WASM_ENABLE_THREAD_MGR == 0 +void +mem_allocator_enable_gc_reclaim(mem_allocator_t allocator, void *exec_env) +{ + return gc_enable_gc_reclaim((gc_handle_t)allocator, exec_env); +} +#else +void +mem_allocator_enable_gc_reclaim(mem_allocator_t allocator, void *cluster) +{ + return gc_enable_gc_reclaim((gc_handle_t)allocator, cluster); +} +#endif + +int +mem_allocator_add_root(mem_allocator_t allocator, WASMObjectRef obj) +{ + return gc_add_root((gc_handle_t)allocator, (gc_object_t)obj); +} +#endif + int mem_allocator_migrate(mem_allocator_t allocator, char *pool_buf_new, uint32 pool_buf_size) @@ -76,6 +114,30 @@ mem_allocator_get_alloc_info(mem_allocator_t allocator, void *mem_alloc_info) return true; } +#if WASM_ENABLE_GC != 0 +bool +mem_allocator_set_gc_finalizer(mem_allocator_t allocator, void *obj, + gc_finalizer_t cb, void *data) +{ + return gc_set_finalizer((gc_handle_t)allocator, (gc_object_t)obj, cb, data); +} + +void +mem_allocator_unset_gc_finalizer(mem_allocator_t allocator, void *obj) +{ + gc_unset_finalizer((gc_handle_t)allocator, (gc_object_t)obj); +} + +#if WASM_ENABLE_GC_PERF_PROFILING != 0 +void +mem_allocator_dump_perf_profiling(mem_allocator_t allocator) +{ + gc_dump_perf_profiling((gc_handle_t)allocator); +} +#endif + +#endif + #else /* else of DEFAULT_MEM_ALLOCATOR */ #include "tlsf/tlsf.h" diff --git a/core/shared/mem-alloc/mem_alloc.cmake b/core/shared/mem-alloc/mem_alloc.cmake index 1754a1aca..5f47cce13 100644 --- a/core/shared/mem-alloc/mem_alloc.cmake +++ b/core/shared/mem-alloc/mem_alloc.cmake @@ -11,7 +11,13 @@ if (WAMR_BUILD_GC_VERIFY EQUAL 1) endif () if (NOT DEFINED WAMR_BUILD_GC_CORRUPTION_CHECK) - set (WAMR_BUILD_GC_CORRUPTION_CHECK 1) + # Disable memory allocator heap corruption check + # when GC is enabled + if (WAMR_BUILD_GC EQUAL 1) + set (WAMR_BUILD_GC_CORRUPTION_CHECK 0) + else () + set (WAMR_BUILD_GC_CORRUPTION_CHECK 1) + endif () endif () if (WAMR_BUILD_GC_CORRUPTION_CHECK EQUAL 0) diff --git a/core/shared/mem-alloc/mem_alloc.h b/core/shared/mem-alloc/mem_alloc.h index 1f35b2792..ca683d1e3 100644 --- a/core/shared/mem-alloc/mem_alloc.h +++ b/core/shared/mem-alloc/mem_alloc.h @@ -7,6 +7,9 @@ #define __MEM_ALLOC_H #include "bh_platform.h" +#if WASM_ENABLE_GC != 0 +#include "../../common/gc/gc_object.h" +#endif #ifdef __cplusplus extern "C" { @@ -14,6 +17,8 @@ extern "C" { typedef void *mem_allocator_t; +typedef void (*gc_finalizer_t)(void *obj, void *data); + mem_allocator_t mem_allocator_create(void *mem, uint32_t size); @@ -45,6 +50,39 @@ mem_allocator_migrate(mem_allocator_t allocator, char *pool_buf_new, bool mem_allocator_is_heap_corrupted(mem_allocator_t allocator); +#if WASM_ENABLE_GC != 0 +void * +mem_allocator_malloc_with_gc(mem_allocator_t allocator, uint32_t size); + +#if WASM_GC_MANUALLY != 0 +void +mem_allocator_free_with_gc(mem_allocator_t allocator, void *ptr); +#endif + +#if WASM_ENABLE_THREAD_MGR == 0 +void +mem_allocator_enable_gc_reclaim(mem_allocator_t allocator, void *exec_env); +#else +void +mem_allocator_enable_gc_reclaim(mem_allocator_t allocator, void *cluster); +#endif + +int +mem_allocator_add_root(mem_allocator_t allocator, WASMObjectRef obj); + +bool +mem_allocator_set_gc_finalizer(mem_allocator_t allocator, void *obj, + gc_finalizer_t cb, void *data); + +void +mem_allocator_unset_gc_finalizer(mem_allocator_t allocator, void *obj); + +#if WASM_ENABLE_GC_PERF_PROFILING != 0 +void +mem_allocator_dump_perf_profiling(mem_allocator_t allocator); +#endif +#endif /* end of WASM_ENABLE_GC != 0 */ + bool mem_allocator_get_alloc_info(mem_allocator_t allocator, void *mem_alloc_info); diff --git a/core/shared/platform/android/platform_init.c b/core/shared/platform/android/platform_init.c index 1e7cf4447..ad206af0e 100644 --- a/core/shared/platform/android/platform_init.c +++ b/core/shared/platform/android/platform_init.c @@ -24,11 +24,15 @@ bh_platform_destroy() int os_printf(const char *fmt, ...) { - int ret; + int ret = 0; va_list ap; va_start(ap, fmt); - ret = __android_log_vprint(ANDROID_LOG_INFO, "wasm_runtime::", fmt, ap); +#ifndef BH_VPRINTF + ret += __android_log_vprint(ANDROID_LOG_INFO, "wasm_runtime::", fmt, ap); +#else + ret += BH_VPRINTF(fmt, ap); +#endif va_end(ap); return ret; @@ -37,7 +41,11 @@ os_printf(const char *fmt, ...) int os_vprintf(const char *fmt, va_list ap) { +#ifndef BH_VPRINTF return __android_log_vprint(ANDROID_LOG_INFO, "wasm_runtime::", fmt, ap); +#else + return BH_VPRINTF(fmt, ap); +#endif } #if __ANDROID_API__ < 19 diff --git a/core/shared/platform/common/memory/mremap.c b/core/shared/platform/common/memory/mremap.c new file mode 100644 index 000000000..dca10a342 --- /dev/null +++ b/core/shared/platform/common/memory/mremap.c @@ -0,0 +1,12 @@ +/* + * Copyright (C) 2024 Amazon Inc. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include "platform_api_vmcore.h" + +void * +os_mremap(void *old_addr, size_t old_size, size_t new_size) +{ + return os_mremap_slow(old_addr, old_size, new_size); +} diff --git a/core/shared/platform/common/memory/platform_api_memory.cmake b/core/shared/platform/common/memory/platform_api_memory.cmake new file mode 100644 index 000000000..9f06c1391 --- /dev/null +++ b/core/shared/platform/common/memory/platform_api_memory.cmake @@ -0,0 +1,4 @@ +# Copyright (C) 2024 Amazon Inc. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +file (GLOB_RECURSE PLATFORM_COMMON_MEMORY_SOURCE ${CMAKE_CURRENT_LIST_DIR}/*.c) diff --git a/core/shared/platform/common/posix/platform_api_posix.cmake b/core/shared/platform/common/posix/platform_api_posix.cmake index 2bf9fab4a..15d6daf3f 100644 --- a/core/shared/platform/common/posix/platform_api_posix.cmake +++ b/core/shared/platform/common/posix/platform_api_posix.cmake @@ -16,4 +16,20 @@ else() set(source_all ${source_all} ${PLATFORM_COMMON_LIBC_UTIL_SOURCE}) endif() +# This is to support old CMake version. Newer version of CMake could use +# list APPEND/POP_BACK methods. +include(CheckSymbolExists) +set (CMAKE_REQUIRED_DEFINITIONS -D_GNU_SOURCE ${CMAKE_REQUIRED_DEFINITIONS}) +check_symbol_exists (mremap "sys/mman.h" MREMAP_EXISTS) +list (REMOVE_AT CMAKE_REQUIRED_DEFINITIONS 0) + +if(MREMAP_EXISTS) + add_definitions (-DWASM_HAVE_MREMAP=1) + add_definitions (-D_GNU_SOURCE) +else() + add_definitions (-DWASM_HAVE_MREMAP=0) + include (${CMAKE_CURRENT_LIST_DIR}/../memory/platform_api_memory.cmake) + set (source_all ${source_all} ${PLATFORM_COMMON_MEMORY_SOURCE}) +endif() + set (PLATFORM_COMMON_POSIX_SOURCE ${source_all} ) diff --git a/core/shared/platform/common/posix/posix_memmap.c b/core/shared/platform/common/posix/posix_memmap.c index 2baf5aeb7..72c8d70e6 100644 --- a/core/shared/platform/common/posix/posix_memmap.c +++ b/core/shared/platform/common/posix/posix_memmap.c @@ -236,6 +236,23 @@ os_munmap(void *addr, size_t size) } } +#if WASM_HAVE_MREMAP != 0 +void * +os_mremap(void *old_addr, size_t old_size, size_t new_size) +{ + void *ptr = mremap(old_addr, old_size, new_size, MREMAP_MAYMOVE); + + if (ptr == MAP_FAILED) { +#if BH_ENABLE_TRACE_MMAP != 0 + os_printf("mremap failed: %d\n", errno); +#endif + return os_mremap_slow(old_addr, old_size, new_size); + } + + return ptr; +} +#endif + int os_mprotect(void *addr, size_t size, int prot) { diff --git a/core/shared/platform/darwin/shared_platform.cmake b/core/shared/platform/darwin/shared_platform.cmake index 5eecd65c7..3680f3d3a 100644 --- a/core/shared/platform/darwin/shared_platform.cmake +++ b/core/shared/platform/darwin/shared_platform.cmake @@ -12,6 +12,9 @@ include (${CMAKE_CURRENT_LIST_DIR}/../common/posix/platform_api_posix.cmake) file (GLOB_RECURSE source_all ${PLATFORM_SHARED_DIR}/*.c) +include (${CMAKE_CURRENT_LIST_DIR}/../common/memory/platform_api_memory.cmake) +set (source_all ${source_all} ${PLATFORM_COMMON_MEMORY_SOURCE}) + set (PLATFORM_SHARED_SOURCE ${source_all} ${PLATFORM_COMMON_POSIX_SOURCE}) file (GLOB header ${PLATFORM_SHARED_DIR}/../include/*.h) diff --git a/core/shared/platform/esp-idf/espidf_platform.c b/core/shared/platform/esp-idf/espidf_platform.c index 0a1dd3c9d..8d3a9b87c 100644 --- a/core/shared/platform/esp-idf/espidf_platform.c +++ b/core/shared/platform/esp-idf/espidf_platform.c @@ -23,7 +23,11 @@ os_printf(const char *format, ...) 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; @@ -32,7 +36,11 @@ os_printf(const char *format, ...) int os_vprintf(const char *format, va_list ap) { +#ifndef BH_VPRINTF return vprintf(format, ap); +#else + return BH_VPRINTF(format, ap); +#endif } uint64 diff --git a/core/shared/platform/include/platform_api_vmcore.h b/core/shared/platform/include/platform_api_vmcore.h index 4a9d29cc0..1fa524f9e 100644 --- a/core/shared/platform/include/platform_api_vmcore.h +++ b/core/shared/platform/include/platform_api_vmcore.h @@ -132,7 +132,7 @@ enum { MMAP_MAP_32BIT = 1, /* Don't interpret addr as a hint: place the mapping at exactly that address. */ - MMAP_MAP_FIXED = 2 + MMAP_MAP_FIXED = 2, }; void * @@ -142,6 +142,29 @@ os_munmap(void *addr, size_t size); int os_mprotect(void *addr, size_t size, int prot); +static inline void * +os_mremap_slow(void *old_addr, size_t old_size, size_t new_size) +{ + void *new_memory = os_mmap(NULL, new_size, MMAP_PROT_WRITE | MMAP_PROT_READ, + 0, os_get_invalid_handle()); + if (!new_memory) { + return NULL; + } + /* + * bh_memcpy_s can't be used as it doesn't support values bigger than + * UINT32_MAX + */ + memcpy(new_memory, old_addr, new_size < old_size ? new_size : old_size); + os_munmap(old_addr, old_size); + + return new_memory; +} + +/* Doesn't guarantee that protection flags will be preserved. + os_mprotect() must be called after remapping. */ +void * +os_mremap(void *old_addr, size_t old_size, size_t new_size); + #if (WASM_MEM_DUAL_BUS_MIRROR != 0) void * os_get_dbus_mirror(void *ibus); diff --git a/core/shared/platform/linux-sgx/platform_internal.h b/core/shared/platform/linux-sgx/platform_internal.h index c96768e32..2cc34dfca 100644 --- a/core/shared/platform/linux-sgx/platform_internal.h +++ b/core/shared/platform/linux-sgx/platform_internal.h @@ -79,6 +79,8 @@ os_get_invalid_handle() return -1; } +#define os_getpagesize getpagesize + #ifdef __cplusplus } #endif diff --git a/core/shared/platform/linux-sgx/shared_platform.cmake b/core/shared/platform/linux-sgx/shared_platform.cmake index e8e167005..9cd765be4 100644 --- a/core/shared/platform/linux-sgx/shared_platform.cmake +++ b/core/shared/platform/linux-sgx/shared_platform.cmake @@ -37,6 +37,9 @@ else() set(source_all ${source_all} ${PLATFORM_COMMON_LIBC_UTIL_SOURCE}) endif() +include (${CMAKE_CURRENT_LIST_DIR}/../common/memory/platform_api_memory.cmake) +set (source_all ${source_all} ${PLATFORM_COMMON_MEMORY_SOURCE}) + file (GLOB source_all_untrusted ${PLATFORM_SHARED_DIR}/untrusted/*.c) set (PLATFORM_SHARED_SOURCE ${source_all}) diff --git a/core/shared/platform/nuttx/nuttx_platform.c b/core/shared/platform/nuttx/nuttx_platform.c index d105924ae..0077c9e02 100644 --- a/core/shared/platform/nuttx/nuttx_platform.c +++ b/core/shared/platform/nuttx/nuttx_platform.c @@ -94,7 +94,11 @@ os_mmap(void *hint, size_t size, int prot, int flags, os_file_handle file) #if defined(CONFIG_ARCH_USE_TEXT_HEAP) if ((prot & MMAP_PROT_EXEC) != 0) { - return up_textheap_memalign(sizeof(void *), size); + p = up_textheap_memalign(sizeof(void *), size); + if (p) { + memset(p, 0, size); + } + return p; } #endif @@ -108,7 +112,11 @@ os_mmap(void *hint, size_t size, int prot, int flags, os_file_handle file) return NULL; } i_addr = (void *)((uint8 *)d_addr + MEM_DUAL_BUS_OFFSET); - return in_ibus_ext(i_addr) ? i_addr : d_addr; + p = in_ibus_ext(i_addr) ? i_addr : d_addr; + if (p) { + memset(p, 0, size); + } + return p; } #endif /* Note: aot_loader.c assumes that os_mmap provides large enough @@ -125,6 +133,10 @@ os_mmap(void *hint, size_t size, int prot, int flags, os_file_handle file) if (posix_memalign(&p, 32, size)) { return NULL; } + + /* Zero the memory which is required by os_mmap */ + memset(p, 0, size); + return p; } diff --git a/core/shared/platform/nuttx/platform_internal.h b/core/shared/platform/nuttx/platform_internal.h index 2fb80a6e3..0b54d85a9 100644 --- a/core/shared/platform/nuttx/platform_internal.h +++ b/core/shared/platform/nuttx/platform_internal.h @@ -44,6 +44,8 @@ typedef pthread_t korp_thread; typedef pthread_rwlock_t korp_rwlock; typedef sem_t korp_sem; +#define os_getpagesize getpagesize + #define OS_THREAD_MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER #define BH_APPLET_PRESERVED_STACK_SIZE (2 * BH_KB) diff --git a/core/shared/platform/nuttx/shared_platform.cmake b/core/shared/platform/nuttx/shared_platform.cmake index 1cbe2218b..ff70cc031 100644 --- a/core/shared/platform/nuttx/shared_platform.cmake +++ b/core/shared/platform/nuttx/shared_platform.cmake @@ -16,5 +16,6 @@ if (WAMR_BUILD_LIBC_WASI EQUAL 1) set(source_all ${source_all} ${PLATFORM_COMMON_LIBC_UTIL_SOURCE}) endif () -set (PLATFORM_SHARED_SOURCE ${source_all} ${PLATFORM_COMMON_MATH_SOURCE}) +include (${CMAKE_CURRENT_LIST_DIR}/../common/memory/platform_api_memory.cmake) +set (PLATFORM_SHARED_SOURCE ${source_all} ${PLATFORM_COMMON_MATH_SOURCE} ${PLATFORM_COMMON_MEMORY_SOURCE}) diff --git a/core/shared/platform/windows/shared_platform.cmake b/core/shared/platform/windows/shared_platform.cmake index 3c531c17c..502a8a2ed 100644 --- a/core/shared/platform/windows/shared_platform.cmake +++ b/core/shared/platform/windows/shared_platform.cmake @@ -20,6 +20,9 @@ else() set(source_all ${source_all} ${PLATFORM_COMMON_LIBC_UTIL_SOURCE}) endif() +include (${CMAKE_CURRENT_LIST_DIR}/../common/memory/platform_api_memory.cmake) +set (source_all ${source_all} ${PLATFORM_COMMON_MEMORY_SOURCE}) + set (PLATFORM_SHARED_SOURCE ${source_all}) file (GLOB header ${PLATFORM_SHARED_DIR}/../include/*.h) diff --git a/core/shared/platform/zephyr/platform_internal.h b/core/shared/platform/zephyr/platform_internal.h index a5d563a6c..00bb49567 100644 --- a/core/shared/platform/zephyr/platform_internal.h +++ b/core/shared/platform/zephyr/platform_internal.h @@ -50,6 +50,12 @@ #include #endif /* end of KERNEL_VERSION_NUMBER < 0x030200 */ +#if KERNEL_VERSION_NUMBER >= 0x030300 /* version 3.3.0 */ +#if defined(CONFIG_CPU_CORTEX_M7) && defined(CONFIG_ARM_MPU) +#include +#endif +#endif /* end of KERNEL_VERSION_NUMBER > 0x030300 */ + #ifdef CONFIG_ARM_MPU #if KERNEL_VERSION_NUMBER < 0x030200 /* version 3.2.0 */ #include @@ -96,7 +102,8 @@ void abort(void); size_t strspn(const char *s, const char *accept); size_t strcspn(const char *s, const char *reject); -/* math functions which are not provided by os */ +/* math functions which are not provided by os with minimal libc */ +#if defined(CONFIG_MINIMAL_LIBC) double atan(double x); double atan2(double y, double x); double sqrt(double x); @@ -123,6 +130,10 @@ double scalbn(double x, int n); unsigned long long int strtoull(const char *nptr, char **endptr, int base); double strtod(const char *nptr, char **endptr); float strtof(const char *nptr, char **endptr); +#else +#include +#endif /* CONFIG_MINIMAL_LIBC */ + /* clang-format on */ #if KERNEL_VERSION_NUMBER >= 0x030100 /* version 3.1.0 */ diff --git a/core/shared/platform/zephyr/shared_platform.cmake b/core/shared/platform/zephyr/shared_platform.cmake index 9b043b52f..dfd45a406 100644 --- a/core/shared/platform/zephyr/shared_platform.cmake +++ b/core/shared/platform/zephyr/shared_platform.cmake @@ -8,7 +8,9 @@ add_definitions(-DBH_PLATFORM_ZEPHYR) include_directories(${PLATFORM_SHARED_DIR}) include_directories(${PLATFORM_SHARED_DIR}/../include) -include (${CMAKE_CURRENT_LIST_DIR}/../common/math/platform_api_math.cmake) +if(${CONFIG_MINIMAL_LIBC}) + include (${CMAKE_CURRENT_LIST_DIR}/../common/math/platform_api_math.cmake) +endif() file (GLOB_RECURSE source_all ${PLATFORM_SHARED_DIR}/*.c) diff --git a/core/shared/platform/zephyr/zephyr_platform.c b/core/shared/platform/zephyr/zephyr_platform.c index 1a5b6621d..e91a42300 100644 --- a/core/shared/platform/zephyr/zephyr_platform.c +++ b/core/shared/platform/zephyr/zephyr_platform.c @@ -202,10 +202,14 @@ void os_dcache_flush() { #if defined(CONFIG_CPU_CORTEX_M7) && defined(CONFIG_ARM_MPU) +#if KERNEL_VERSION_NUMBER < 0x030300 /* version 3.3.0 */ uint32 key; key = irq_lock(); SCB_CleanDCache(); irq_unlock(key); +#else + sys_cache_data_flush_all(); +#endif #elif defined(CONFIG_SOC_CVF_EM7D) && defined(CONFIG_ARC_MPU) \ && defined(CONFIG_CACHE_FLUSHING) __asm__ __volatile__("sync"); @@ -216,7 +220,11 @@ os_dcache_flush() void os_icache_flush(void *start, size_t len) -{} +{ +#if KERNEL_VERSION_NUMBER >= 0x030300 /* version 3.3.0 */ + sys_cache_instr_flush_range(start, len); +#endif +} void set_exec_mem_alloc_func(exec_mem_alloc_func_t alloc_func, diff --git a/core/shared/utils/bh_assert.c b/core/shared/utils/bh_assert.c index 246c55d1b..5e62baaf3 100644 --- a/core/shared/utils/bh_assert.c +++ b/core/shared/utils/bh_assert.c @@ -18,7 +18,7 @@ bh_assert_internal(int64 v, const char *file_name, int line_number, if (!expr_string) expr_string = "NULL EXPR_STRING"; - os_printf("\nASSERTION FAILED: %s, at file %s, line %d\n", expr_string, + LOG_ERROR("\nASSERTION FAILED: %s, at file %s, line %d\n", expr_string, file_name, line_number); abort(); diff --git a/doc/build_wamr.md b/doc/build_wamr.md index 6857478a9..1331f9601 100644 --- a/doc/build_wamr.md +++ b/doc/build_wamr.md @@ -130,6 +130,10 @@ cmake -DWAMR_BUILD_PLATFORM=linux -DWAMR_BUILD_TARGET=ARM - **WAMR_BUILD_CUSTOM_NAME_SECTION**=1/0, load the function name from custom name section, default to disable if not set +#### **Enable AOT stack frame feature** +- **WAMR_BUILD_AOT_STACK_FRAME**=1/0, default to disable if not set +> Note: if it is enabled, the AOT or JIT stack frames (like stack frame of classic interpreter but only necessary data is committed) will be created for AOT or JIT mode in function calls. And please add `--enable-dump-call-stack` option to wamrc during compiling AOT module. + #### **Enable dump call stack feature** - **WAMR_BUILD_DUMP_CALL_STACK**=1/0, default to disable if not set @@ -153,7 +157,6 @@ Currently we only profile the memory consumption of module, module_instance and > Also refer to [Tune the performance of running wasm/aot file](./perf_tune.md). - #### **Enable the global heap** - **WAMR_BUILD_GLOBAL_HEAP_POOL**=1/0, default to disable if not set for all *iwasm* applications, except for the platforms Alios and Zephyr. @@ -171,8 +174,9 @@ Currently we only profile the memory consumption of module, module_instance and - **WAMR_APP_THREAD_STACK_SIZE_MAX**=n, default to 8 MB (8388608) if not set > Note: the AOT boundary check with hardware trap mechanism might consume large stack since the OS may lazily grow the stack mapping as a guard page is hit, we may use this configuration to reduce the total stack usage, e.g. -DWAMR_APP_THREAD_STACK_SIZE_MAX=131072 (128 KB). -#### **WAMR_BH_VPRINTF**=, default to disable if not set -> Note: if the vprintf_callback function is provided by developer, the os_printf() and os_vprintf() in Linux, Darwin, Windows and VxWorks platforms, besides WASI Libc output will call the callback function instead of libc vprintf() function to redirect the stdout output. For example, developer can define the callback function like below outside runtime lib: +#### **Set vprintf callback** +- **WAMR_BH_VPRINTF**=, default to disable if not set +> Note: if the vprintf_callback function is provided by developer, the os_printf() and os_vprintf() in Linux, Darwin, Windows, VxWorks, Android and esp-idf platforms, besides WASI Libc output will call the callback function instead of libc vprintf() function to redirect the stdout output. For example, developer can define the callback function like below outside runtime lib: > > ```C > int my_vprintf(const char *format, va_list ap) @@ -224,25 +228,25 @@ Currently we only profile the memory consumption of module, module_instance and > For AoT file, must use `--emit-custom-sections` to specify which sections need to be emitted into AoT file, otherwise all custom sections will be ignored. -### **Stack guard size** +#### **Stack guard size** - **WAMR_BUILD_STACK_GUARD_SIZE**=n, default to N/A if not set. > Note: By default, the stack guard size is 1K (1024) or 24K (if uvwasi enabled). -### **Disable the writing linear memory base address to x86 GS segment register** +#### **Disable writing the linear memory base address to x86 GS segment register** - **WAMR_DISABLE_WRITE_GS_BASE**=1/0, default to enable if not set and supported by platform > Note: by default only platform [linux x86-64](https://github.com/bytecodealliance/wasm-micro-runtime/blob/5fb5119239220b0803e7045ca49b0a29fe65e70e/core/shared/platform/linux/platform_internal.h#L67) will enable this feature, for 32-bit platforms it's automatically disabled even when the flag is set to 0. In linux x86-64, writing the linear memory base address to x86 GS segment register may be used to speedup the linear memory access for LLVM AOT/JIT, when `--enable-segue=[]` option is added for `wamrc` or `iwasm`. > See [Enable segue optimization for wamrc when generating the aot file](./perf_tune.md#3-enable-segue-optimization-for-wamrc-when-generating-the-aot-file) for more details. -### **Enable running PGO(Profile-Guided Optimization) instrumented AOT file** +#### **Enable running PGO(Profile-Guided Optimization) instrumented AOT file** - **WAMR_BUILD_STATIC_PGO**=1/0, default to disable if not set > Note: See [Use the AOT static PGO method](./perf_tune.md#5-use-the-aot-static-pgo-method) for more details. -### **Enable linux perf support** +#### **Enable linux perf support** - **WAMR_BUILD_LINUX_PERF**=1/0, enable linux perf support to generate the flamegraph to analyze the performance of a wasm application, default to disable if not set > Note: See [Use linux-perf](./perf_tune.md#7-use-linux-perf) for more details. -### **Enable module instance context APIs** +#### **Enable module instance context APIs** - **WAMR_BUILD_MODULE_INST_CONTEXT**=1/0, enable module instance context APIs which can set one or more contexts created by the embedder for a wasm module instance, default to enable if not set: ```C wasm_runtime_create_context_key @@ -253,10 +257,25 @@ Currently we only profile the memory consumption of module, module_instance and ``` > Note: See [wasm_export.h](../core/iwasm/include/wasm_export.h) for more details. -### **Enable quick AOT/JTI entries** +#### **Enable quick AOT/JTI entries** - **WAMR_BUILD_QUICK_AOT_ENTRY**=1/0, enable registering quick call entries to speedup the aot/jit func call process, default to enable if not set > Note: See [Refine callings to AOT/JIT functions from host native](./perf_tune.md#83-refine-callings-to-aotjit-functions-from-host-native) for more details. +#### **Configurale memory access boundary check** +- **WAMR_CONFIGUABLE_BOUNDS_CHECKS**=1/0, default to disable if not set +> Note: If it is enabled, allow to run `iwasm --disable-bounds-checks` to disable the memory access boundary checks for interpreter mode. + +#### **Module instance context APIs** +- **WAMR_BUILD_MODULE_INST_CONTEXT**=1/0, default to disable if not set +> Note: If it is enabled, allow to set one or more contexts created by embedder for a module instance, the below APIs are provided: +```C + wasm_runtime_create_context_key + wasm_runtime_destroy_context_key + wasm_runtime_set_context + wasm_runtime_set_context_spread + wasm_runtime_get_context +``` + **Combination of configurations:** We can combine the configurations. For example, if we want to disable interpreter, enable AOT and WASI, we can run command: diff --git a/doc/export_native_api.md b/doc/export_native_api.md index ed7385539..a4123d12c 100644 --- a/doc/export_native_api.md +++ b/doc/export_native_api.md @@ -211,17 +211,17 @@ API that way unless necessary because it needs extra carefulness. We must do data serialization for passing structured data or class objects between the two worlds of WASM and native. There are two serialization methods available in WASM as below, and yet you can introduce more like json, cbor etc. -- [attributes container](../core/app-framework/app-native-shared/attr_container.c) -- [restful request/response](../core/app-framework/app-native-shared/restful_utils.c) +- [attributes container](https://github.com/bytecodealliance/wamr-app-framework/blob/main/app-framework/app-native-shared/attr_container.c) +- [restful request/response](https://github.com/bytecodealliance/wamr-app-framework/blob/main/app-framework/app-native-shared/restful_utils.c) -Note the serialization library is separately compiled into WASM and runtime. And the source files are located in the folder "[core/app-framework/app-native-shared](../core/app-framework/app-native-shared)“ where all source files will be compiled into both worlds. +Note the serialization library is separately compiled into WASM and runtime. And the source files are located in the folder "[wamr-app-framework/app-framework/app-native-shared](https://github.com/bytecodealliance/wamr-app-framework/blob/main/app-framework/app-native-shared)“ where all source files will be compiled into both worlds. The following sample code demonstrates WASM app packs a response structure to buffer, then pass the buffer pointer to the native: ```c -/*** file name: core/app-framework/base/app/request.c ***/ +/*** file name: https://github.com/bytecodealliance/wamr-app-framework/blob/main/app-framework/base/app/request.c ***/ void api_response_send(response_t *response) { @@ -240,7 +240,7 @@ void api_response_send(response_t *response) The following code demonstrates the native API unpack the WASM buffer to local native data structure: ```c -/*** file name: core/app-framework/base/native/request_response.c ***/ +/*** file name: https://github.com/bytecodealliance/wamr-app-framework/blob/main/app-framework/base/native/request_response.c ***/ bool wasm_response_send(wasm_exec_env_t exec_env, char *buffer, int size) diff --git a/doc/memory_usage.md b/doc/memory_usage.md index ec0624c6f..88b792f0c 100644 --- a/doc/memory_usage.md +++ b/doc/memory_usage.md @@ -51,14 +51,9 @@ They are in the number of WASM pages, each of which is of 65536 bytes. The `max` is optional for non-shared memory. When omitted, it effectivily means unlimited. -If `OS_ENABLE_HW_BOUND_CHECK` is enabled, the memory is allocated via -`os_mmap` and `os_mem_commit`/`os_mprotect`. -Otherwise, it's allocated from the global heap. +The linear memory is allocated via `os_mmap` and `os_mem_commit`/`os_mprotect`. -If the memory is shared and `OS_ENABLE_HW_BOUND_CHECK` is not enabled, -the `max` size of memory is allocated on instantiation. - -Otherwise, the `min` size of memory is allocated on instantiation. +The `min` size of memory is allocated on instantiation. It can later grow up to the `max` size via the `memory.grow` instruction. Libc heap diff --git a/doc/wamr_api.md b/doc/wamr_api.md deleted file mode 100644 index 3eff86927..000000000 --- a/doc/wamr_api.md +++ /dev/null @@ -1,351 +0,0 @@ - -WAMR application framework -======================== - -## Application system callbacks -The `on_init` and `on_destroy` functions are wamr application system callbacks which must be implemented in the wasm application if you want to use the APP framework. -``` C -void on_init() -{ - /* - Your init functions here, for example: - * platform initialization - * timer registration - * service / event registration - * ...... - */ -} - -void on_destroy() -{ - /* - your destroy functions here - */ -} -``` - -## Base App library - -The base library of application framework supports the essential API for WASM applications, such as inter-app communication, timers, etc. Other application framework components rely on the base library. - -When building the WAMR SDK, once application framework is enabled, the base library will automatically enabled. - -### Timer -The *timer* API's can be used to create some `soft timers` with single-shot mode or periodic mode. Here is a reference of how to use timer API's to execute a function every one second. -``` C -/* User global variable */ -static int num = 0; - -/* Timer callback */ -void timer1_update(user_timer_t timer) -{ - printf("Timer update %d\n", num++); -} - -void on_init() -{ - user_timer_t timer; - - /* set up a timer */ - timer = api_timer_create(1000, true, false, timer1_update); - api_timer_restart(timer, 1000); -} - -void on_destroy() -{ - -} -``` - -### Micro-service model (request/response) -The microservice model is also known as request and response model. One WASM application acts as the server which provides a specific service. Other WASM applications or host/cloud applications request that service and get the response. - -
- -Below is the reference implementation of the server application. It provides room temperature measurement service. - -``` C -void on_init() -{ - api_register_resource_handler("/room_temp", room_temp_handler); -} - -void on_destroy() -{ -} - -void room_temp_handler(request_t *request) -{ - response_t response[1]; - attr_container_t *payload; - payload = attr_container_create("room_temp payload"); - if (payload == NULL) - return; - - attr_container_set_string(&payload, "temp unit", "centigrade"); - attr_container_set_int(&payload, "value", 26); - - make_response_for_request(request, response); - set_response(response, - CONTENT_2_05, - FMT_ATTR_CONTAINER, - payload, - attr_container_get_serialize_length(payload)); - - api_response_send(response); - attr_container_destroy(payload); -} -``` - - -### Pub/sub model -One WASM application acts as the event publisher. It publishes events to notify WASM applications or host/cloud applications which subscribe to the events. - -
- -Below is the reference implementation of the pub application. It utilizes a timer to repeatedly publish an overheat alert event to the subscriber applications. Then the subscriber applications receive the events immediately. - -``` C -/* Timer callback */ -void timer_update(user_timer_t timer) -{ - attr_container_t *event; - - event = attr_container_create("event"); - attr_container_set_string(&event, - "warning", - "temperature is over high"); - - api_publish_event("alert/overheat", - FMT_ATTR_CONTAINER, - event, - attr_container_get_serialize_length(event)); - - attr_container_destroy(event); -} - -void on_init() -{ - user_timer_t timer; - timer = api_timer_create(1000, true, true, timer_update); -} - -void on_destroy() -{ -} -``` - -Below is the reference implementation of the sub application. -``` C -void overheat_handler(request_t *event) -{ - printf("Event: %s\n", event->url); - - if (event->payload != NULL && event->fmt == FMT_ATTR_CONTAINER) - attr_container_dump((attr_container_t *) event->payload); -} - -void on_init( -{ - api_subscribe_event ("alert/overheat", overheat_handler); -} - -void on_destroy() -{ -} -``` -**Note:** You can also subscribe this event from host side by using host tool. Please refer `samples/simple` project for detail usage. - - -## Sensor API - -The API set is defined in the header file ```core/app-framework/sensor/app/wa-inc/sensor.h```. - -Here is a reference of how to use sensor API's: - -``` C -static sensor_t sensor = NULL; - -/* Sensor event callback*/ -void sensor_event_handler(sensor_t sensor, attr_container_t *event, - void *user_data) -{ - printf("### app get sensor event\n"); - attr_container_dump(event); -} - -void on_init() -{ - char *user_data; - attr_container_t *config; - - printf("### app on_init 1\n"); - /* open a sensor */ - user_data = malloc(100); - printf("### app on_init 2\n"); - sensor = sensor_open("sensor_test", 0, sensor_event_handler, user_data); - printf("### app on_init 3\n"); - - /* config the sensor */ - sensor_config(sensor, 1000, 0, 0); - printf("### app on_init 4\n"); -} - -void on_destroy() -{ - if (NULL != sensor) { - sensor_config(sensor, 0, 0, 0); - } -} -``` - -## Connection API: - -The API set is defined in the header file `core/app-framework/connection/app/wa-inc/connection.h` - -Here is a reference of how to use connection API's: -``` C -/* User global variable */ -static int num = 0; -static user_timer_t g_timer; -static connection_t *g_conn = NULL; - -void on_data1(connection_t *conn, - conn_event_type_t type, - const char *data, - uint32 len, - void *user_data) -{ - if (type == CONN_EVENT_TYPE_DATA) { - char message[64] = {0}; - memcpy(message, data, len); - printf("Client got a message from server -> %s\n", message); - } else if (type == CONN_EVENT_TYPE_DISCONNECT) { - printf("connection is close by server!\n"); - } else { - printf("error: got unknown event type!!!\n"); - } -} - -/* Timer callback */ -void timer1_update(user_timer_t timer) -{ - char message[64] = {0}; - /* Reply to server */ - snprintf(message, sizeof(message), "Hello %d", num++); - api_send_on_connection(g_conn, message, strlen(message)); -} - -void my_close_handler(request_t * request) -{ - response_t response[1]; - - if (g_conn != NULL) { - api_timer_cancel(g_timer); - api_close_connection(g_conn); - } - - make_response_for_request(request, response); - set_response(response, DELETED_2_02, 0, NULL, 0); - api_response_send(response); -} - -void on_init() -{ - user_timer_t timer; - attr_container_t *args; - char *str = "this is client!"; - - api_register_resource_handler("/close", my_close_handler); - - args = attr_container_create(""); - attr_container_set_string(&args, "address", "127.0.0.1"); - attr_container_set_uint16(&args, "port", 7777); - - g_conn = api_open_connection("TCP", args, on_data1, NULL); - if (g_conn == NULL) { - printf("connect to server fail!\n"); - return; - } - - printf("connect to server success! handle: %p\n", g_conn); - - /* set up a timer */ - timer = api_timer_create(1000, true, false, timer1_update); - api_timer_restart(timer, 1000); -} - -void on_destroy() -{ - -} -``` - -## GUI API - -The API's is listed in header file ```core/app-framework/wgl/app/wa-inc/wgl.h``` which is implemented based on open source 2D graphic library [LVGL](https://docs.lvgl.io/master/index.html). - -``` C -static void btn_event_cb(wgl_obj_t btn, wgl_event_t event); - -uint32_t count = 0; -char count_str[11] = { 0 }; -wgl_obj_t hello_world_label; -wgl_obj_t count_label; -wgl_obj_t btn1; -wgl_obj_t label_count1; -int label_count1_value = 0; -char label_count1_str[11] = { 0 }; - -void timer1_update(user_timer_t timer1) -{ - if ((count % 100) == 0) { - snprintf(count_str, sizeof(count_str), "%d", count / 100); - wgl_label_set_text(count_label, count_str); - } - ++count; -} - -void on_init() -{ - hello_world_label = wgl_label_create((wgl_obj_t)NULL, (wgl_obj_t)NULL); - wgl_label_set_text(hello_world_label, "Hello world!"); - wgl_obj_align(hello_world_label, (wgl_obj_t)NULL, WGL_ALIGN_IN_TOP_LEFT, 0, 0); - - count_label = wgl_label_create((wgl_obj_t)NULL, (wgl_obj_t)NULL); - wgl_obj_align(count_label, (wgl_obj_t)NULL, WGL_ALIGN_IN_TOP_MID, 0, 0); - - btn1 = wgl_btn_create((wgl_obj_t)NULL, (wgl_obj_t)NULL); /*Create a button on the currently loaded screen*/ - wgl_obj_set_event_cb(btn1, btn_event_cb); /*Set function to be called when the button is released*/ - wgl_obj_align(btn1, (wgl_obj_t)NULL, WGL_ALIGN_CENTER, 0, 0); /*Align below the label*/ - - /*Create a label on the button*/ - wgl_obj_t btn_label = wgl_label_create(btn1, (wgl_obj_t)NULL); - wgl_label_set_text(btn_label, "Click ++"); - - label_count1 = wgl_label_create((wgl_obj_t)NULL, (wgl_obj_t)NULL); - wgl_label_set_text(label_count1, "0"); - wgl_obj_align(label_count1, (wgl_obj_t)NULL, WGL_ALIGN_IN_BOTTOM_MID, 0, 0); - - /* set up a timer */ - user_timer_t timer; - timer = api_timer_create(10, true, false, timer1_update); - if (timer) - api_timer_restart(timer, 10); - else - printf("Fail to create timer.\n"); -} - -static void btn_event_cb(wgl_obj_t btn, wgl_event_t event) -{ - if(event == WGL_EVENT_RELEASED) { - label_count1_value++; - snprintf(label_count1_str, sizeof(label_count1_str), - "%d", label_count1_value); - wgl_label_set_text(label_count1, label_count1_str); - } -} - -``` - -Currently supported widgets include button, label, list and check box and more widgets would be provided in future. diff --git a/product-mini/README.md b/product-mini/README.md index 4a8275618..8d7e799a4 100644 --- a/product-mini/README.md +++ b/product-mini/README.md @@ -10,7 +10,7 @@ cmake .. -DCMAKE_TOOLCHAIN_FILE=$TOOL_CHAIN_FILE \ -DWAMR_BUILD_TARGET=ARM ``` -Refer to toolchain sample file [`samples/simple/profiles/arm-interp/toolchain.cmake`](../samples/simple/profiles/arm-interp/toolchain.cmake) for how to build mini product for ARM target architecture. +Refer to toolchain sample file [`wamr-app-framework/samples/simple/profiles/arm-interp/toolchain.cmake`](https://github.com/bytecodealliance/wamr-app-framework/blob/main/samples/simple/profiles/arm-interp/toolchain.cmake) for how to build mini product for ARM target architecture. If you compile for ESP-IDF, make sure to set the right toolchain file for the chip you're using (e.g. `$IDF_PATH/tools/cmake/toolchain-esp32c3.cmake`). Note that all ESP-IDF toolchain files live under `$IDF_PATH/tools/cmake/`. @@ -250,7 +250,6 @@ Note: WAMR provides some features which can be easily configured by passing options to cmake, please see [WAMR vmcore cmake building configurations](../doc/build_wamr.md#wamr-vmcore-cmake-building-configurations) for details. Currently in VxWorks, interpreter and builtin libc are enabled by default. ## Zephyr - Please refer to this [README](./platforms/zephyr/simple/README.md) under the Zephyr sample directory for details. Note: diff --git a/product-mini/platforms/linux-sgx/CMakeLists.txt b/product-mini/platforms/linux-sgx/CMakeLists.txt index 0b2b4afec..20b3fdfac 100644 --- a/product-mini/platforms/linux-sgx/CMakeLists.txt +++ b/product-mini/platforms/linux-sgx/CMakeLists.txt @@ -16,6 +16,10 @@ if (NOT DEFINED WAMR_BUILD_TARGET) if (CMAKE_SIZEOF_VOID_P EQUAL 8) # Build as X86_64 by default in 64-bit platform set (WAMR_BUILD_TARGET "X86_64") + if (NOT DEFINED WAMR_BUILD_SIMD) + # Enable SIMD by default in 64-bit platform + set (WAMR_BUILD_SIMD 1) + endif () elseif (CMAKE_SIZEOF_VOID_P EQUAL 4) # Build as X86_32 by default in 32-bit platform set (WAMR_BUILD_TARGET "X86_32") @@ -176,3 +180,10 @@ else() OUTPUT_VARIABLE cmdOutput ) endif() + +if (WAMR_BUILD_SPEC_TEST EQUAL 1) + execute_process( + COMMAND bash -c "sed -i -E 's/0x1000000<\\/ReservedMemMaxSize>/0x8000000<\\/ReservedMemMaxSize>/g' ${CMAKE_CURRENT_SOURCE_DIR}/enclave-sample/Enclave/Enclave.config.xml" + OUTPUT_VARIABLE cmdOutput + ) +endif() diff --git a/product-mini/platforms/linux/CMakeLists.txt b/product-mini/platforms/linux/CMakeLists.txt index ecd08655c..df156b3a0 100644 --- a/product-mini/platforms/linux/CMakeLists.txt +++ b/product-mini/platforms/linux/CMakeLists.txt @@ -24,11 +24,17 @@ set (CMAKE_CXX_STANDARD 17) if (NOT DEFINED WAMR_BUILD_TARGET) if (CMAKE_SYSTEM_PROCESSOR MATCHES "^(arm64|aarch64)") set (WAMR_BUILD_TARGET "AARCH64") + if (NOT DEFINED WAMR_BUILD_SIMD) + set (WAMR_BUILD_SIMD 1) + endif () 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") + if (NOT DEFINED WAMR_BUILD_SIMD) + set (WAMR_BUILD_SIMD 1) + endif () elseif (CMAKE_SIZEOF_VOID_P EQUAL 4) # Build as X86_32 by default in 32-bit platform set (WAMR_BUILD_TARGET "X86_32") @@ -91,7 +97,6 @@ if (NOT DEFINED WAMR_BUILD_LIB_WASI_THREADS) set (WAMR_BUILD_LIB_WASI_THREADS 0) endif() - if (NOT DEFINED WAMR_BUILD_MINI_LOADER) # Disable wasm mini loader by default set (WAMR_BUILD_MINI_LOADER 0) diff --git a/product-mini/platforms/nuttx/wamr.mk b/product-mini/platforms/nuttx/wamr.mk index 748fb6a87..e414a7cda 100644 --- a/product-mini/platforms/nuttx/wamr.mk +++ b/product-mini/platforms/nuttx/wamr.mk @@ -215,12 +215,25 @@ else CFLAGS += -DWASM_ENABLE_BULK_MEMORY=0 endif +ifeq ($(CONFIG_INTERPRETERS_WAMR_AOT_STACK_FRAME), y) +CFLAGS += -DWASM_ENABLE_AOT_STACK_FRAME=1 +else +CFLAGS += -DWASM_ENABLE_AOT_STACK_FRAME=0 +endif + ifeq ($(CONFIG_INTERPRETERS_WAMR_PERF_PROFILING),y) CFLAGS += -DWASM_ENABLE_PERF_PROFILING=1 +CFLAGS += -DWASM_ENABLE_AOT_STACK_FRAME=1 else CFLAGS += -DWASM_ENABLE_PERF_PROFILING=0 endif +ifeq ($(CONFIG_INTERPRETERS_WAMR_GC_PERF_PROFILING),y) +CFLAGS += -DWASM_ENABLE_GC_PERF_PROFILING=1 +else +CFLAGS += -DWASM_ENABLE_GC_PERF_PROFILING=0 +endif + ifeq ($(CONFIG_INTERPRETERS_WAMR_MEMORY_PROFILING),y) CFLAGS += -DWASM_ENABLE_MEMORY_PROFILING=1 else @@ -235,6 +248,7 @@ endif ifeq ($(CONFIG_INTERPRETERS_WAMR_DUMP_CALL_STACK),y) CFLAGS += -DWASM_ENABLE_DUMP_CALL_STACK=1 +CFLAGS += -DWASM_ENABLE_AOT_STACK_FRAME=1 else CFLAGS += -DWASM_ENABLE_DUMP_CALL_STACK=0 endif @@ -304,6 +318,20 @@ else CFLAGS += -DWASM_ENABLE_LIB_WASI_THREADS=0 endif +ifeq ($(CONFIG_INTERPRETERS_WAMR_GC),y) +CFLAGS += -DWASM_ENABLE_GC=1 +CSRCS += gc_common.c gc_type.c gc_object.c +VPATH += $(IWASM_ROOT)/common/gc +else +CFLAGS += -DWASM_ENABLE_GC=0 +endif + +ifeq ($(CONFIG_INTERPRETERS_WAMR_GC_MANUALLY),y) +CFLAGS += -DWASM_GC_MANUALLY=1 +else +CFLAGS += -DWASM_GC_MANUALLY=0 +endif + ifeq ($(CONFIG_INTERPRETERS_WAMR_LIB_PTHREAD),y) CFLAGS += -DWASM_ENABLE_LIB_PTHREAD=1 CSRCS += lib_pthread_wrapper.c @@ -359,6 +387,12 @@ else CFLAGS += -DWASM_ENABLE_REF_TYPES=0 endif +ifeq ($(CONFIG_INTERPRETERS_WAMR_TAIL_CALL),y) +CFLAGS += -DWASM_ENABLE_TAIL_CALL=1 +else +CFLAGS += -DWASM_ENABLE_TAIL_CALL=0 +endif + ifeq ($(CONFIG_INTERPRETERS_WAMR_ENABLE_EXCE_HANDLING),y) CFLAGS += -DWASM_ENABLE_EXCE_HANDLING=1 CFLAGS += -DWASM_ENABLE_TAGS=1 @@ -391,10 +425,12 @@ CSRCS += nuttx_platform.c \ posix_thread.c \ posix_time.c \ posix_sleep.c \ + mremap.c \ mem_alloc.c \ ems_kfc.c \ ems_alloc.c \ ems_hmu.c \ + ems_gc.c \ bh_assert.c \ bh_bitmap.c \ bh_common.c \ @@ -416,6 +452,7 @@ CSRCS += nuttx_platform.c \ ASRCS += $(INVOKE_NATIVE) VPATH += $(SHARED_ROOT)/platform/nuttx +VPATH += $(SHARED_ROOT)/platform/common/memory VPATH += $(SHARED_ROOT)/platform/common/posix VPATH += $(SHARED_ROOT)/platform/common/libc-util VPATH += $(SHARED_ROOT)/mem-alloc diff --git a/product-mini/platforms/posix/main.c b/product-mini/platforms/posix/main.c index 89aef5f91..37ee0cb87 100644 --- a/product-mini/platforms/posix/main.c +++ b/product-mini/platforms/posix/main.c @@ -55,6 +55,10 @@ print_help() printf(" --jit-codecache-size=n Set fast jit maximum code cache size in bytes,\n"); printf(" default is %u KB\n", FAST_JIT_DEFAULT_CODE_CACHE_SIZE / 1024); #endif +#if WASM_ENABLE_GC != 0 + printf(" --gc-heap-size=n Set maximum gc heap size in bytes,\n"); + printf(" default is %u KB\n", GC_HEAP_SIZE_DEFAULT / 1024); +#endif #if WASM_ENABLE_JIT != 0 printf(" --llvm-jit-size-level=n Set LLVM JIT size level, default is 3\n"); printf(" --llvm-jit-opt-level=n Set LLVM JIT optimization level, default is 3\n"); @@ -559,6 +563,9 @@ main(int argc, char *argv[]) #if WASM_ENABLE_FAST_JIT != 0 uint32 jit_code_cache_size = FAST_JIT_DEFAULT_CODE_CACHE_SIZE; #endif +#if WASM_ENABLE_GC != 0 + uint32 gc_heap_size = GC_HEAP_SIZE_DEFAULT; +#endif #if WASM_ENABLE_JIT != 0 uint32 llvm_jit_size_level = 3; uint32 llvm_jit_opt_level = 3; @@ -666,6 +673,13 @@ main(int argc, char *argv[]) jit_code_cache_size = atoi(argv[0] + 21); } #endif +#if WASM_ENABLE_GC != 0 + else if (!strncmp(argv[0], "--gc-heap-size=", 15)) { + if (argv[0][21] == '\0') + return print_help(); + gc_heap_size = atoi(argv[0] + 15); + } +#endif #if WASM_ENABLE_JIT != 0 else if (!strncmp(argv[0], "--llvm-jit-size-level=", 22)) { if (argv[0][22] == '\0') @@ -821,6 +835,10 @@ main(int argc, char *argv[]) init_args.fast_jit_code_cache_size = jit_code_cache_size; #endif +#if WASM_ENABLE_GC != 0 + init_args.gc_heap_size = gc_heap_size; +#endif + #if WASM_ENABLE_JIT != 0 init_args.llvm_jit_size_level = llvm_jit_size_level; init_args.llvm_jit_opt_level = llvm_jit_opt_level; diff --git a/samples/README.md b/samples/README.md index 21a735268..4113fcad1 100644 --- a/samples/README.md +++ b/samples/README.md @@ -1,10 +1,7 @@ # Samples - [**basic**](./basic): Demonstrating how to use runtime exposed API's to call WASM functions, how to register native functions and call them, and how to call WASM function from native function. -- **[simple](./simple/README.md)**: The runtime is integrated with most of the WAMR APP libraries, and a few WASM applications are provided for testing the WAMR APP API set. It uses **built-in libc** and executes apps in **interpreter** mode by default. - **[file](./file/README.md)**: Demonstrating the supported file interaction API of WASI. This sample can also demonstrate the SGX IPFS (Intel Protected File System), enabling an enclave to seal and unseal data at rest. -- **[littlevgl](./littlevgl/README.md)**: Demonstrating the graphic user interface application usage on WAMR. The whole [LVGL](https://github.com/lvgl/lvgl) 2D user graphic library and the UI application are built into WASM application. It uses **WASI libc** and executes apps in **AOT mode** by default. -- **[gui](./gui/README.md)**: Move the [LVGL](https://github.com/lvgl/lvgl) library into the runtime and define a WASM application interface by wrapping the littlevgl API. It uses **WASI libc** and executes apps in **interpreter** mode by default. - **[multi-thread](./multi-thread/)**: Demonstrating how to run wasm application which creates multiple threads to execute wasm functions concurrently, and uses mutex/cond by calling pthread related API's. - **[spawn-thread](./spawn-thread)**: Demonstrating how to execute wasm functions of the same wasm application concurrently, in threads created by host embedder or runtime, but not the wasm application itself. - **[wasi-threads](./wasi-threads/README.md)**: Demonstrating how to run wasm application which creates multiple threads to execute wasm functions concurrently based on lib wasi-threads. diff --git a/samples/file/src/CMakeLists.txt b/samples/file/src/CMakeLists.txt index 1f7a2435f..19775a08e 100644 --- a/samples/file/src/CMakeLists.txt +++ b/samples/file/src/CMakeLists.txt @@ -50,6 +50,7 @@ set (WAMR_BUILD_INTERP 1) set (WAMR_BUILD_AOT 1) set (WAMR_BUILD_JIT 0) set (WAMR_BUILD_LIBC_BUILTIN 1) +set (WAMR_BUILD_REF_TYPES 1) if (NOT MSVC) set (WAMR_BUILD_LIBC_WASI 1) diff --git a/samples/gui/README.md b/samples/gui/README.md deleted file mode 100644 index d79453c3e..000000000 --- a/samples/gui/README.md +++ /dev/null @@ -1,138 +0,0 @@ -"gui" sample introduction -============== -This sample demonstrates that a graphic user interface application in WebAssembly programming with WAMR graphic library(WGL) which is part of WAMR app-framework. - -Compared with the [littlevgl](../littlevgl) sample, WGL compiles LittlevGL source code into the WAMR runtime and defines a set of wrapper API's for exporting to Webassembly application. - -Below picture shows the WASM application is running on an STM board with an LCD touch panel. - -![WAMR UI SAMPLE](../../doc/pics/vgl_demo2.png "WAMR UI DEMO") - - When user clicks the blue button, the WASM application increases the counter, and the latest counter value is displayed on the top banner of the touch panel. The number on top will plus one each second, and the number on the bottom will plus one when clicked. - -# Test on Linux - -Install required SDK and libraries --------------- -- 32 bit SDL(simple directmedia layer) (Note: only necessary when `WAMR_BUILD_TARGET` is set to `X86_32` when building WAMR runtime) -Use apt-get: - ```bash - sudo apt-get install libsdl2-dev:i386 - ``` -Or download source from www.libsdl.org: - ```bash - ./configure C_FLAGS=-m32 CXX_FLAGS=-m32 LD_FLAGS=-m32 - make - sudo make install - ``` -- 64 bit SDL(simple directmedia layer) (Note: only necessary when `WAMR_BUILD_TARGET` is set to `X86_64` when building WAMR runtime) -Use apt-get: - - ```bash - sudo apt-get install libsdl2-dev - ``` - Or download source from www.libsdl.org: - ```bash - ./configure - make - sudo make install - ``` - -Build and Run --------------- - -- Build - ```bash - ./build.sh - ``` - All binaries are in "out", which contains "host_tool", "ui_decrease.wasm", "ui_increase.wasm" and "wasm_runtime_wgl". - -- Run WASM VM Linux applicaton & install WASM APP - First start wasm_runtime_wgl in server mode. - ```bash - ./wasm_runtime_wgl -s - ``` - Then install wasm APP by using host tool. - ```bash - ./host_tool -i inc -f ui_increase.wasm - # or - ./host_tool -i dec -f ui_decrease.wasm - ``` - -Test on Zephyr -================================ - -We can use a STM32 NUCLEO_F767ZI board with ILI9341 display and XPT2046 touch screen to run the test. Then use host_tool to remotely install wasm app into STM32. -- Build WASM VM into Zephyr system - a. clone zephyr source code -Refer to [Zephyr getting started](https://docs.zephyrproject.org/latest/getting_started/index.html). - - ```bash - west init zephyrproject - cd zephyrproject/zephyr - git checkout zephyr-v2.3.0 - cd .. - west update - ``` - b. copy samples - ```bash - cd zephyr/samples - cp -a /samples/gui/wasm-runtime-wgl wasm-runtime-wgl - cd wasm-runtime-wgl/zephyr_build - ``` - c. create a link to wamr root dir - ```bash - ln -s wamr - ``` - d. build source code - ```bash - mkdir build && cd build - source ../../../../zephyr-env.sh - cmake -GNinja -DBOARD=nucleo_f767zi .. - ninja flash - ``` - -- Hardware Connections - -``` -+-------------------+-+------------------+ -|NUCLEO-F767ZI | ILI9341 Display | -+-------------------+-+------------------+ -| CN7.10 | CLK | -+-------------------+-+------------------+ -| CN7.12 | MISO | -+-------------------+-+------------------+ -| CN7.14 | MOSI | -+-------------------+-+------------------+ -| CN11.1 | CS1 for ILI9341 | -+-------------------+-+------------------+ -| CN11.2 | D/C | -+-------------------+-+------------------+ -| CN11.3 | RESET | -+-------------------+-+------------------+ -| CN9.25 | PEN interrupt | -+-------------------+-+------------------+ -| CN9.27 | CS2 for XPT2046 | -+-------------------+-+------------------+ -| CN10.14 | PC UART RX | -+-------------------+-+------------------+ -| CN11.16 | PC UART RX | -+-------------------+-+------------------+ -``` - -- Install WASM application to Zephyr using host_tool -First, connect PC and STM32 with UART. Then install to use host_tool. - ```bash - sudo ./host_tool -D /dev/ttyUSBXXX -i inc -f ui_increase.wasm - # /dev/ttyUSBXXX is the UART device, e.g. /dev/ttyUSB0 - ``` - -- Install AOT version WASM application - ```bash - wamrc --target=thumbv7 --target-abi=eabi --cpu=cortex-m7 -o ui_app.aot ui_increase.wasm - ./host_tool -D /dev/ttyUSBXXX -i inc -f ui_app.aot - ``` - -The graphic user interface demo photo: - -![WAMR samples diagram](../../doc/pics/vgl_demo.png "WAMR samples diagram") diff --git a/samples/gui/build.sh b/samples/gui/build.sh deleted file mode 100755 index f910f450b..000000000 --- a/samples/gui/build.sh +++ /dev/null @@ -1,75 +0,0 @@ -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -#!/bin/bash - -PROJECT_DIR=$PWD -WAMR_DIR=${PWD}/../.. -OUT_DIR=${PWD}/out -BUILD_DIR=${PWD}/build -WAMR_RUNTIME_CFG=${PROJECT_DIR}/wamr_config_gui.cmake -LV_CFG_PATH=${PROJECT_DIR}/lv_config - -if [ -z $KW_BUILD ] || [ -z $KW_OUT_FILE ];then - echo "Local Build Env" - cmakewrap="cmake" - makewrap="make" -else - echo "Klocwork Build Env" - cmakewrap="cmake -DCMAKE_BUILD_TYPE=Debug" - makewrap="kwinject -o $KW_OUT_FILE make" -fi - -if [ ! -d $BUILD_DIR ]; then - mkdir ${BUILD_DIR} -fi - -rm -rf ${OUT_DIR} -mkdir ${OUT_DIR} - - -echo -e "\n\n" -echo "##################### 1. build wamr-sdk gui start#####################" -cd ${WAMR_DIR}/wamr-sdk -./build_sdk.sh -n gui -x ${WAMR_RUNTIME_CFG} -e ${LV_CFG_PATH} -[ $? -eq 0 ] || exit $? - -echo "#####################build wamr-sdk success" - - - -echo "##################### 2. build wasm runtime start#####################" -cd $BUILD_DIR -mkdir -p wasm-runtime-wgl -cd wasm-runtime-wgl -$cmakewrap ${PROJECT_DIR}/wasm-runtime-wgl/linux-build -DWAMR_BUILD_SDK_PROFILE=gui -[ $? -eq 0 ] || exit $? -$makewrap -[ $? -eq 0 ] || exit $? -cp wasm_runtime_wgl ${OUT_DIR}/ - -echo "##################### build littlevgl wasm runtime end#####################" -echo -e "\n\n" - - -echo "#####################build host-tool" -cd $BUILD_DIR -mkdir -p host-tool -cd host-tool -$cmakewrap ${WAMR_DIR}/test-tools/host-tool -$makewrap -if [ $? != 0 ];then - echo "BUILD_FAIL host tool exit as $?\n" - exit 2 -fi -cp host_tool ${OUT_DIR} -echo "#####################build host-tool success" -echo -e "\n\n" - -echo "##################### 3. build wasm ui app start#####################" -cd ${PROJECT_DIR}/wasm-apps -export OUT_DIR=${OUT_DIR} -./build_apps.sh - diff --git a/samples/gui/lv_config/lv_conf.h b/samples/gui/lv_config/lv_conf.h deleted file mode 100644 index 2f9fc77a7..000000000 --- a/samples/gui/lv_config/lv_conf.h +++ /dev/null @@ -1,498 +0,0 @@ -/** - * @file lv_conf.h - * - */ - -/* - * COPY THIS FILE AS `lv_conf.h` NEXT TO the `lvgl` FOLDER - */ - -#if 1 /*Set it to "1" to enable content*/ - -#ifndef LV_CONF_H -#define LV_CONF_H -/* clang-format off */ - -#include - -/*==================== - Graphical settings - *====================*/ - -/* Maximal horizontal and vertical resolution to support by the library.*/ -#define LV_HOR_RES_MAX (320) -#define LV_VER_RES_MAX (240) - -/* Color depth: - * - 1: 1 byte per pixel - * - 8: RGB233 - * - 16: RGB565 - * - 32: ARGB8888 - */ -#define LV_COLOR_DEPTH 32 - -/* Swap the 2 bytes of RGB565 color. - * Useful if the display has a 8 bit interface (e.g. SPI)*/ -#define LV_COLOR_16_SWAP 0 - -/* 1: Enable screen transparency. - * Useful for OSD or other overlapping GUIs. - * Requires `LV_COLOR_DEPTH = 32` colors and the screen's style should be modified: `style.body.opa = ...`*/ -#define LV_COLOR_SCREEN_TRANSP 0 - -/*Images pixels with this color will not be drawn (with chroma keying)*/ -#define LV_COLOR_TRANSP LV_COLOR_LIME /*LV_COLOR_LIME: pure green*/ - -/* Enable anti-aliasing (lines, and radiuses will be smoothed) */ -#define LV_ANTIALIAS 1 - -/* Default display refresh period. - * Can be changed in the display driver (`lv_disp_drv_t`).*/ -#define LV_DISP_DEF_REFR_PERIOD 30 /*[ms]*/ - -/* Dot Per Inch: used to initialize default sizes. - * E.g. a button with width = LV_DPI / 2 -> half inch wide - * (Not so important, you can adjust it to modify default sizes and spaces)*/ -#define LV_DPI 100 /*[px]*/ - -/* Type of coordinates. Should be `int16_t` (or `int32_t` for extreme cases) */ -typedef int16_t lv_coord_t; - -/*========================= - Memory manager settings - *=========================*/ - -/* LittelvGL's internal memory manager's settings. - * The graphical objects and other related data are stored here. */ - -/* 1: use custom malloc/free, 0: use the built-in `lv_mem_alloc` and `lv_mem_free` */ -#ifndef LV_MEM_CUSTOM -#define LV_MEM_CUSTOM 0 -#endif - -#if LV_MEM_CUSTOM == 0 -/* Size of the memory used by `lv_mem_alloc` in bytes (>= 2kB)*/ -# define LV_MEM_SIZE (128U * 1024U) - -/* Complier prefix for a big array declaration */ -# define LV_MEM_ATTR - -/* Set an address for the memory pool instead of allocating it as an array. - * Can be in external SRAM too. */ -# define LV_MEM_ADR 0 - -/* Automatically defrag. on free. Defrag. means joining the adjacent free cells. */ -# define LV_MEM_AUTO_DEFRAG 1 -#else /*LV_MEM_CUSTOM*/ -# define LV_MEM_CUSTOM_INCLUDE "bh_platform.h" /*Header for the dynamic memory function*/ -# define LV_MEM_CUSTOM_ALLOC BH_MALLOC /*Wrapper to malloc*/ -# define LV_MEM_CUSTOM_FREE BH_FREE /*Wrapper to free*/ -#endif /*LV_MEM_CUSTOM*/ - -/* Garbage Collector settings - * Used if lvgl is binded to higher level language and the memory is managed by that language */ -#define LV_ENABLE_GC 0 -#if LV_ENABLE_GC != 0 -# define LV_GC_INCLUDE "gc.h" /*Include Garbage Collector related things*/ -# define LV_MEM_CUSTOM_REALLOC your_realloc /*Wrapper to realloc*/ -# define LV_MEM_CUSTOM_GET_SIZE your_mem_get_size /*Wrapper to lv_mem_get_size*/ -#endif /* LV_ENABLE_GC */ - -/*======================= - Input device settings - *=======================*/ - -/* Input device default settings. - * Can be changed in the Input device driver (`lv_indev_drv_t`)*/ - -/* Input device read period in milliseconds */ -#define LV_INDEV_DEF_READ_PERIOD 30 - -/* Drag threshold in pixels */ -#define LV_INDEV_DEF_DRAG_LIMIT 10 - -/* Drag throw slow-down in [%]. Greater value -> faster slow-down */ -#define LV_INDEV_DEF_DRAG_THROW 20 - -/* Long press time in milliseconds. - * Time to send `LV_EVENT_LONG_PRESSSED`) */ -#define LV_INDEV_DEF_LONG_PRESS_TIME 400 - -/* Repeated trigger period in long press [ms] - * Time between `LV_EVENT_LONG_PRESSED_REPEAT */ -#define LV_INDEV_DEF_LONG_PRESS_REP_TIME 100 - -/*================== - * Feature usage - *==================*/ - -/*1: Enable the Animations */ -#define LV_USE_ANIMATION 1 -#if LV_USE_ANIMATION - -/*Declare the type of the user data of animations (can be e.g. `void *`, `int`, `struct`)*/ -typedef void * lv_anim_user_data_t; - -#endif - -/* 1: Enable shadow drawing*/ -#define LV_USE_SHADOW 1 - -/* 1: Enable object groups (for keyboard/encoder navigation) */ -#define LV_USE_GROUP 1 -#if LV_USE_GROUP -typedef void * lv_group_user_data_t; -#endif /*LV_USE_GROUP*/ - -/* 1: Enable GPU interface*/ -#define LV_USE_GPU 1 - -/* 1: Enable file system (might be required for images */ -#define LV_USE_FILESYSTEM 1 -#if LV_USE_FILESYSTEM -/*Declare the type of the user data of file system drivers (can be e.g. `void *`, `int`, `struct`)*/ -typedef void * lv_fs_drv_user_data_t; -#endif - -/*1: Add a `user_data` to drivers and objects*/ -#define LV_USE_USER_DATA 1 - -/*======================== - * Image decoder and cache - *========================*/ - -/* 1: Enable indexed (palette) images */ -#define LV_IMG_CF_INDEXED 1 - -/* 1: Enable alpha indexed images */ -#define LV_IMG_CF_ALPHA 1 - -/* Default image cache size. Image caching keeps the images opened. - * If only the built-in image formats are used there is no real advantage of caching. - * (I.e. no new image decoder is added) - * With complex image decoders (e.g. PNG or JPG) caching can save the continuous open/decode of images. - * However the opened images might consume additional RAM. - * LV_IMG_CACHE_DEF_SIZE must be >= 1 */ -#define LV_IMG_CACHE_DEF_SIZE 1 - -/*Declare the type of the user data of image decoder (can be e.g. `void *`, `int`, `struct`)*/ -typedef void * lv_img_decoder_user_data_t; - -/*===================== - * Compiler settings - *====================*/ -/* Define a custom attribute to `lv_tick_inc` function */ -#define LV_ATTRIBUTE_TICK_INC - -/* Define a custom attribute to `lv_task_handler` function */ -#define LV_ATTRIBUTE_TASK_HANDLER - -/* With size optimization (-Os) the compiler might not align data to - * 4 or 8 byte boundary. This alignment will be explicitly applied where needed. - * E.g. __attribute__((aligned(4))) */ -#define LV_ATTRIBUTE_MEM_ALIGN - -/* Attribute to mark large constant arrays for example - * font's bitmaps */ -#define LV_ATTRIBUTE_LARGE_CONST - -/*=================== - * HAL settings - *==================*/ - -/* 1: use a custom tick source. - * It removes the need to manually update the tick with `lv_tick_inc`) */ -#define LV_TICK_CUSTOM 1 -#if LV_TICK_CUSTOM == 1 -#define LV_TICK_CUSTOM_INCLUDE "system_header.h" /*Header for the sys time function*/ -#define LV_TICK_CUSTOM_SYS_TIME_EXPR (time_get_ms()) /*Expression evaluating to current systime in ms*/ -#endif /*LV_TICK_CUSTOM*/ - -typedef void * lv_disp_drv_user_data_t; /*Type of user data in the display driver*/ -typedef void * lv_indev_drv_user_data_t; /*Type of user data in the input device driver*/ - -/*================ - * Log settings - *===============*/ - -/*1: Enable the log module*/ -#define LV_USE_LOG 1 -#if LV_USE_LOG -/* How important log should be added: - * LV_LOG_LEVEL_TRACE A lot of logs to give detailed information - * LV_LOG_LEVEL_INFO Log important events - * LV_LOG_LEVEL_WARN Log if something unwanted happened but didn't cause a problem - * LV_LOG_LEVEL_ERROR Only critical issue, when the system may fail - * LV_LOG_LEVEL_NONE Do not log anything - */ -# define LV_LOG_LEVEL LV_LOG_LEVEL_WARN - -/* 1: Print the log with 'printf'; - * 0: user need to register a callback with `lv_log_register_print`*/ -# define LV_LOG_PRINTF 1 -#endif /*LV_USE_LOG*/ - -/*================ - * THEME USAGE - *================*/ -#define LV_THEME_LIVE_UPDATE 1 /*1: Allow theme switching at run time. Uses 8..10 kB of RAM*/ - -#define LV_USE_THEME_TEMPL 1 /*Just for test*/ -#define LV_USE_THEME_DEFAULT 1 /*Built mainly from the built-in styles. Consumes very few RAM*/ -#define LV_USE_THEME_ALIEN 1 /*Dark futuristic theme*/ -#define LV_USE_THEME_NIGHT 1 /*Dark elegant theme*/ -#define LV_USE_THEME_MONO 1 /*Mono color theme for monochrome displays*/ -#define LV_USE_THEME_MATERIAL 1 /*Flat theme with bold colors and light shadows*/ -#define LV_USE_THEME_ZEN 1 /*Peaceful, mainly light theme */ -#define LV_USE_THEME_NEMO 1 /*Water-like theme based on the movie "Finding Nemo"*/ - -/*================== - * FONT USAGE - *===================*/ - -/* The built-in fonts contains the ASCII range and some Symbols with 4 bit-per-pixel. - * The symbols are available via `LV_SYMBOL_...` defines - * More info about fonts: https://docs.littlevgl.com/#Fonts - * To create a new font go to: https://littlevgl.com/ttf-font-to-c-array - */ - -/* Robot fonts with bpp = 4 - * https://fonts.google.com/specimen/Roboto */ -#define LV_FONT_ROBOTO_12 1 -#define LV_FONT_ROBOTO_16 1 -#define LV_FONT_ROBOTO_22 1 -#define LV_FONT_ROBOTO_28 1 - -/*Pixel perfect monospace font - * http://pelulamu.net/unscii/ */ -#define LV_FONT_UNSCII_8 1 - -/* Optionally declare your custom fonts here. - * You can use these fonts as default font too - * and they will be available globally. E.g. - * #define LV_FONT_CUSTOM_DECLARE LV_FONT_DECLARE(my_font_1) \ - * LV_FONT_DECLARE(my_font_2) - */ -#define LV_FONT_CUSTOM_DECLARE - -/*Always set a default font from the built-in fonts*/ -#define LV_FONT_DEFAULT &lv_font_roboto_16 - -/* Enable it if you have fonts with a lot of characters. - * The limit depends on the font size, font face and bpp - * but with > 10,000 characters if you see issues probably you need to enable it.*/ -#define LV_FONT_FMT_TXT_LARGE 1 - -/*Declare the type of the user data of fonts (can be e.g. `void *`, `int`, `struct`)*/ -typedef void * lv_font_user_data_t; - -/*================= - * Text settings - *=================*/ - -/* Select a character encoding for strings. - * Your IDE or editor should have the same character encoding - * - LV_TXT_ENC_UTF8 - * - LV_TXT_ENC_ASCII - * */ -#define LV_TXT_ENC LV_TXT_ENC_UTF8 - - /*Can break (wrap) texts on these chars*/ -#define LV_TXT_BREAK_CHARS " ,.;:-_" - -/*=================== - * LV_OBJ SETTINGS - *==================*/ - -/*Declare the type of the user data of object (can be e.g. `void *`, `int`, `struct`)*/ -typedef void * lv_obj_user_data_t; - -/*1: enable `lv_obj_realaign()` based on `lv_obj_align()` parameters*/ -#define LV_USE_OBJ_REALIGN 1 - -/* Enable to make the object clickable on a larger area. - * LV_EXT_CLICK_AREA_OFF or 0: Disable this feature - * LV_EXT_CLICK_AREA_TINY: The extra area can be adjusted horizontally and vertically (0..255 px) - * LV_EXT_CLICK_AREA_FULL: The extra area can be adjusted in all 4 directions (-32k..+32k px) - */ -#define LV_USE_EXT_CLICK_AREA LV_EXT_CLICK_AREA_FULL - -/*================== - * LV OBJ X USAGE - *================*/ -/* - * Documentation of the object types: https://docs.littlevgl.com/#Object-types - */ - -/*Arc (dependencies: -)*/ -#define LV_USE_ARC 1 - -/*Bar (dependencies: -)*/ -#define LV_USE_BAR 1 - -/*Button (dependencies: lv_cont*/ -#define LV_USE_BTN 1 -#if LV_USE_BTN != 0 -/*Enable button-state animations - draw a circle on click (dependencies: LV_USE_ANIMATION)*/ -# define LV_BTN_INK_EFFECT 1 -#endif - -/*Button matrix (dependencies: -)*/ -#define LV_USE_BTNM 1 - -/*Calendar (dependencies: -)*/ -#define LV_USE_CALENDAR 1 - -/*Canvas (dependencies: lv_img)*/ -#define LV_USE_CANVAS 1 - -/*Check box (dependencies: lv_btn, lv_label)*/ -#define LV_USE_CB 1 - -/*Chart (dependencies: -)*/ -#define LV_USE_CHART 1 -#if LV_USE_CHART -# define LV_CHART_AXIS_TICK_LABEL_MAX_LEN 20 -#endif - -/*Container (dependencies: -*/ -#define LV_USE_CONT 1 - -/*Drop down list (dependencies: lv_page, lv_label, lv_symbol_def.h)*/ -#define LV_USE_DDLIST 1 -#if LV_USE_DDLIST != 0 -/*Open and close default animation time [ms] (0: no animation)*/ -# define LV_DDLIST_DEF_ANIM_TIME 200 -#endif - -/*Gauge (dependencies:lv_bar, lv_lmeter)*/ -#define LV_USE_GAUGE 1 - -/*Image (dependencies: lv_label*/ -#define LV_USE_IMG 1 - -/*Image Button (dependencies: lv_btn*/ -#define LV_USE_IMGBTN 1 -#if LV_USE_IMGBTN -/*1: The imgbtn requires left, mid and right parts and the width can be set freely*/ -# define LV_IMGBTN_TILED 0 -#endif - -/*Keyboard (dependencies: lv_btnm)*/ -#define LV_USE_KB 1 - -/*Label (dependencies: -*/ -#define LV_USE_LABEL 1 -#if LV_USE_LABEL != 0 -/*Hor, or ver. scroll speed [px/sec] in 'LV_LABEL_LONG_ROLL/ROLL_CIRC' mode*/ -# define LV_LABEL_DEF_SCROLL_SPEED 25 - -/* Waiting period at beginning/end of animation cycle */ -# define LV_LABEL_WAIT_CHAR_COUNT 3 - -/*Enable selecting text of the label */ -# define LV_LABEL_TEXT_SEL 1 - -/*Store extra some info in labels (12 bytes) to speed up drawing of very long texts*/ -# define LV_LABEL_LONG_TXT_HINT 0 -#endif - -/*LED (dependencies: -)*/ -#define LV_USE_LED 1 - -/*Line (dependencies: -*/ -#define LV_USE_LINE 1 - -/*List (dependencies: lv_page, lv_btn, lv_label, (lv_img optionally for icons ))*/ -#define LV_USE_LIST 1 -#if LV_USE_LIST != 0 -/*Default animation time of focusing to a list element [ms] (0: no animation) */ -# define LV_LIST_DEF_ANIM_TIME 100 -#endif - -/*Line meter (dependencies: *;)*/ -#define LV_USE_LMETER 1 - -/*Message box (dependencies: lv_rect, lv_btnm, lv_label)*/ -#define LV_USE_MBOX 1 - -/*Page (dependencies: lv_cont)*/ -#define LV_USE_PAGE 1 -#if LV_USE_PAGE != 0 -/*Focus default animation time [ms] (0: no animation)*/ -# define LV_PAGE_DEF_ANIM_TIME 400 -#endif - -/*Preload (dependencies: lv_arc, lv_anim)*/ -#define LV_USE_PRELOAD 1 -#if LV_USE_PRELOAD != 0 -# define LV_PRELOAD_DEF_ARC_LENGTH 60 /*[deg]*/ -# define LV_PRELOAD_DEF_SPIN_TIME 1000 /*[ms]*/ -# define LV_PRELOAD_DEF_ANIM LV_PRELOAD_TYPE_SPINNING_ARC -#endif - -/*Roller (dependencies: lv_ddlist)*/ -#define LV_USE_ROLLER 1 -#if LV_USE_ROLLER != 0 -/*Focus animation time [ms] (0: no animation)*/ -# define LV_ROLLER_DEF_ANIM_TIME 200 - -/*Number of extra "pages" when the roller is infinite*/ -# define LV_ROLLER_INF_PAGES 7 -#endif - -/*Slider (dependencies: lv_bar)*/ -#define LV_USE_SLIDER 1 - -/*Spinbox (dependencies: lv_ta)*/ -#define LV_USE_SPINBOX 1 - -/*Switch (dependencies: lv_slider)*/ -#define LV_USE_SW 1 - -/*Text area (dependencies: lv_label, lv_page)*/ -#define LV_USE_TA 1 -#if LV_USE_TA != 0 -# define LV_TA_DEF_CURSOR_BLINK_TIME 400 /*ms*/ -# define LV_TA_DEF_PWD_SHOW_TIME 1500 /*ms*/ -#endif - -/*Table (dependencies: lv_label)*/ -#define LV_USE_TABLE 1 -#if LV_USE_TABLE -# define LV_TABLE_COL_MAX 12 -#endif - -/*Tab (dependencies: lv_page, lv_btnm)*/ -#define LV_USE_TABVIEW 1 -# if LV_USE_TABVIEW != 0 -/*Time of slide animation [ms] (0: no animation)*/ -# define LV_TABVIEW_DEF_ANIM_TIME 300 -#endif - -/*Tileview (dependencies: lv_page) */ -#define LV_USE_TILEVIEW 1 -#if LV_USE_TILEVIEW -/*Time of slide animation [ms] (0: no animation)*/ -# define LV_TILEVIEW_DEF_ANIM_TIME 300 -#endif - -/*Window (dependencies: lv_cont, lv_btn, lv_label, lv_img, lv_page)*/ -#define LV_USE_WIN 1 - -/*================== - * Non-user section - *==================*/ - -#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) /* Disable warnings for Visual Studio*/ -# define _CRT_SECURE_NO_WARNINGS -#endif - -/*--END OF LV_CONF_H--*/ - -/*Be sure every define has a default value*/ -#include "lvgl/src/lv_conf_checker.h" - -#endif /*LV_CONF_H*/ - -#endif /*End of "Content enable"*/ diff --git a/samples/gui/lv_config/lv_drv_conf.h b/samples/gui/lv_config/lv_drv_conf.h deleted file mode 100644 index d216a3e90..000000000 --- a/samples/gui/lv_config/lv_drv_conf.h +++ /dev/null @@ -1,310 +0,0 @@ -/** - * @file lv_drv_conf.h - * - */ - -/* - * COPY THIS FILE AS lv_drv_conf.h - */ - -#if 1 /*Set it to "1" to enable the content*/ - -#ifndef LV_DRV_CONF_H -#define LV_DRV_CONF_H - -#include "lv_conf.h" - -/********************* - * DELAY INTERFACE - *********************/ -#define LV_DRV_DELAY_INCLUDE /*Dummy include by default*/ -#define LV_DRV_DELAY_US(us) /*delay_us(us)*/ /*Delay the given number of microseconds*/ -#define LV_DRV_DELAY_MS(ms) /*delay_ms(ms)*/ /*Delay the given number of milliseconds*/ - -/********************* - * DISPLAY INTERFACE - *********************/ - -/*------------ - * Common - *------------*/ -#define LV_DRV_DISP_INCLUDE /*Dummy include by default*/ -#define LV_DRV_DISP_CMD_DATA(val) /*pin_x_set(val)*/ /*Set the command/data pin to 'val'*/ -#define LV_DRV_DISP_RST(val) /*pin_x_set(val)*/ /*Set the reset pin to 'val'*/ - -/*--------- - * SPI - *---------*/ -#define LV_DRV_DISP_SPI_CS(val) /*spi_cs_set(val)*/ /*Set the SPI's Chip select to 'val'*/ -#define LV_DRV_DISP_SPI_WR_BYTE(data) /*spi_wr(data)*/ /*Write a byte the SPI bus*/ -#define LV_DRV_DISP_SPI_WR_ARRAY(adr, n) /*spi_wr_mem(adr, n)*/ /*Write 'n' bytes to SPI bus from 'adr'*/ - -/*------------------ - * Parallel port - *-----------------*/ -#define LV_DRV_DISP_PAR_CS(val) /*par_cs_set(val)*/ /*Set the Parallel port's Chip select to 'val'*/ -#define LV_DRV_DISP_PAR_SLOW /*par_slow()*/ /*Set low speed on the parallel port*/ -#define LV_DRV_DISP_PAR_FAST /*par_fast()*/ /*Set high speed on the parallel port*/ -#define LV_DRV_DISP_PAR_WR_WORD(data) /*par_wr(data)*/ /*Write a word to the parallel port*/ -#define LV_DRV_DISP_PAR_WR_ARRAY(adr, n) /*par_wr_mem(adr,n)*/ /*Write 'n' bytes to Parallel ports from 'adr'*/ - -/*************************** - * INPUT DEVICE INTERFACE - ***************************/ - -/*---------- - * Common - *----------*/ -#define LV_DRV_INDEV_INCLUDE /*Dummy include by default*/ -#define LV_DRV_INDEV_RST(val) /*pin_x_set(val)*/ /*Set the reset pin to 'val'*/ -#define LV_DRV_INDEV_IRQ_READ 0 /*pn_x_read()*/ /*Read the IRQ pin*/ - -/*--------- - * SPI - *---------*/ -#define LV_DRV_INDEV_SPI_CS(val) /*spi_cs_set(val)*/ /*Set the SPI's Chip select to 'val'*/ -#define LV_DRV_INDEV_SPI_XCHG_BYTE(data) 0 /*spi_xchg(val)*/ /*Write 'val' to SPI and give the read value*/ - -/*--------- - * I2C - *---------*/ -#define LV_DRV_INDEV_I2C_START /*i2c_start()*/ /*Make an I2C start*/ -#define LV_DRV_INDEV_I2C_STOP /*i2c_stop()*/ /*Make an I2C stop*/ -#define LV_DRV_INDEV_I2C_RESTART /*i2c_restart()*/ /*Make an I2C restart*/ -#define LV_DRV_INDEV_I2C_WR(data) /*i2c_wr(data)*/ /*Write a byte to the I1C bus*/ -#define LV_DRV_INDEV_I2C_READ(last_read) 0 /*i2c_rd()*/ /*Read a byte from the I2C bud*/ - - -/********************* - * DISPLAY DRIVERS - *********************/ - -/*------------------- - * Monitor of PC - *-------------------*/ -#ifndef USE_MONITOR -# define USE_MONITOR 1 -#endif - -#if USE_MONITOR -# define MONITOR_HOR_RES LV_HOR_RES_MAX -# define MONITOR_VER_RES LV_VER_RES_MAX - -/* Scale window by this factor (useful when simulating small screens) */ -# define MONITOR_ZOOM 1 - -/* Used to test true double buffering with only address changing. - * Set LV_VDB_SIZE = (LV_HOR_RES * LV_VER_RES) and LV_VDB_DOUBLE = 1 and LV_COLOR_DEPTH = 32" */ -# define MONITOR_DOUBLE_BUFFERED 0 - -/*Eclipse: Visual Studio: */ -# define MONITOR_SDL_INCLUDE_PATH - -/*Different rendering might be used if running in a Virtual machine*/ -# define MONITOR_VIRTUAL_MACHINE 0 - -/*Open two windows to test multi display support*/ -# define MONITOR_DUAL 0 -#endif - -/*----------------------------------- - * Native Windows (including mouse) - *----------------------------------*/ -#ifndef USE_WINDOWS -# define USE_WINDOWS 0 -#endif - -#define USE_WINDOWS 0 -#if USE_WINDOWS -# define WINDOW_HOR_RES 480 -# define WINDOW_VER_RES 320 -#endif - -/*---------------- - * SSD1963 - *--------------*/ -#ifndef USE_SSD1963 -# define USE_SSD1963 0 -#endif - -#if USE_SSD1963 -# define SSD1963_HOR_RES LV_HOR_RES -# define SSD1963_VER_RES LV_VER_RES -# define SSD1963_HT 531 -# define SSD1963_HPS 43 -# define SSD1963_LPS 8 -# define SSD1963_HPW 10 -# define SSD1963_VT 288 -# define SSD1963_VPS 12 -# define SSD1963_FPS 4 -# define SSD1963_VPW 10 -# define SSD1963_HS_NEG 0 /*Negative hsync*/ -# define SSD1963_VS_NEG 0 /*Negative vsync*/ -# define SSD1963_ORI 0 /*0, 90, 180, 270*/ -# define SSD1963_COLOR_DEPTH 16 -#endif - -/*---------------- - * R61581 - *--------------*/ -#ifndef USE_R61581 -# define USE_R61581 0 -#endif - -#if USE_R61581 -# define R61581_HOR_RES LV_HOR_RES -# define R61581_VER_RES LV_VER_RES -# define R61581_HSPL 0 /*HSYNC signal polarity*/ -# define R61581_HSL 10 /*HSYNC length (Not Implemented)*/ -# define R61581_HFP 10 /*Horitontal Front poarch (Not Implemented)*/ -# define R61581_HBP 10 /*Horitontal Back poarch (Not Implemented */ -# define R61581_VSPL 0 /*VSYNC signal polarity*/ -# define R61581_VSL 10 /*VSYNC length (Not Implemented)*/ -# define R61581_VFP 8 /*Vertical Front poarch*/ -# define R61581_VBP 8 /*Vertical Back poarch */ -# define R61581_DPL 0 /*DCLK signal polarity*/ -# define R61581_EPL 1 /*ENABLE signal polarity*/ -# define R61581_ORI 0 /*0, 180*/ -# define R61581_LV_COLOR_DEPTH 16 /*Fix 16 bit*/ -#endif - -/*------------------------------ - * ST7565 (Monochrome, low res.) - *-----------------------------*/ -#ifndef USE_ST7565 -# define USE_ST7565 0 -#endif - -#if USE_ST7565 -/*No settings*/ -#endif /*USE_ST7565*/ - -/*----------------------------------------- - * Linux frame buffer device (/dev/fbx) - *-----------------------------------------*/ -#ifndef USE_FBDEV -# define USE_FBDEV 1 -#endif - -#if USE_FBDEV -# define FBDEV_PATH "/dev/fb0" -#endif - -/********************* - * INPUT DEVICES - *********************/ - -/*-------------- - * XPT2046 - *--------------*/ -#ifndef USE_XPT2046 -# define USE_XPT2046 0 -#endif - -#if USE_XPT2046 -# define XPT2046_HOR_RES 480 -# define XPT2046_VER_RES 320 -# define XPT2046_X_MIN 200 -# define XPT2046_Y_MIN 200 -# define XPT2046_X_MAX 3800 -# define XPT2046_Y_MAX 3800 -# define XPT2046_AVG 4 -# define XPT2046_INV 0 -#endif - -/*----------------- - * FT5406EE8 - *-----------------*/ -#ifndef USE_FT5406EE8 -# define USE_FT5406EE8 0 -#endif - -#if USE_FT5406EE8 -# define FT5406EE8_I2C_ADR 0x38 /*7 bit address*/ -#endif - -/*--------------- - * AD TOUCH - *--------------*/ -#ifndef USE_AD_TOUCH -# define USE_AD_TOUCH 0 -#endif - -#if USE_AD_TOUCH -/*No settings*/ -#endif - - -/*--------------------------------------- - * Mouse or touchpad on PC (using SDL) - *-------------------------------------*/ -#ifndef USE_MOUSE -# define USE_MOUSE 1 -#endif - -#if USE_MOUSE -/*No settings*/ -#endif - -/*------------------------------------------- - * Mousewheel as encoder on PC (using SDL) - *------------------------------------------*/ -#ifndef USE_MOUSEWHEEL -# define USE_MOUSEWHEEL 1 -#endif - -#if USE_MOUSEWHEEL -/*No settings*/ -#endif - -/*------------------------------------------------- - * Touchscreen as libinput interface (for Linux based systems) - *------------------------------------------------*/ -#ifndef USE_LIBINPUT -# define USE_LIBINPUT 0 -#endif - -#if USE_LIBINPUT -# define LIBINPUT_NAME "/dev/input/event0" /*You can use the "evtest" Linux tool to get the list of devices and test them*/ -#endif /*USE_LIBINPUT*/ - -/*------------------------------------------------- - * Mouse or touchpad as evdev interface (for Linux based systems) - *------------------------------------------------*/ -#ifndef USE_EVDEV -# define USE_EVDEV 0 -#endif - -#if USE_EVDEV -# define EVDEV_NAME "/dev/input/event0" /*You can use the "evtest" Linux tool to get the list of devices and test them*/ -# define EVDEV_SWAP_AXES 0 /*Swap the x and y axes of the touchscreen*/ - -# define EVDEV_SCALE 0 /* Scale input, e.g. if touchscreen resolution does not match display resolution */ -# if EVDEV_SCALE -# define EVDEV_SCALE_HOR_RES (4096) /* Horizontal resolution of touchscreen */ -# define EVDEV_SCALE_VER_RES (4096) /* Vertical resolution of touchscreen */ -# endif /*EVDEV_SCALE*/ - -# define EVDEV_CALIBRATE 0 /*Scale and offset the touchscreen coordinates by using maximum and minimum values for each axis*/ -# if EVDEV_CALIBRATE -# define EVDEV_HOR_MIN 3800 /*If EVDEV_XXX_MIN > EVDEV_XXX_MAX the XXX axis is automatically inverted*/ -# define EVDEV_HOR_MAX 200 -# define EVDEV_VER_MIN 200 -# define EVDEV_VER_MAX 3800 -# endif /*EVDEV_SCALE*/ -#endif /*USE_EVDEV*/ - -/*------------------------------- - * Keyboard of a PC (using SDL) - *------------------------------*/ -#ifndef USE_KEYBOARD -# define USE_KEYBOARD 1 -#endif - -#if USE_KEYBOARD -/*No settings*/ -#endif - -#endif /*LV_DRV_CONF_H*/ - -#endif /*End of "Content enable"*/ diff --git a/samples/gui/lv_config/system_header.h b/samples/gui/lv_config/system_header.h deleted file mode 100644 index a0d790c8e..000000000 --- a/samples/gui/lv_config/system_header.h +++ /dev/null @@ -1,9 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include - -int -time_get_ms(); diff --git a/samples/gui/wamr_config_gui.cmake b/samples/gui/wamr_config_gui.cmake deleted file mode 100644 index 3b33d33b2..000000000 --- a/samples/gui/wamr_config_gui.cmake +++ /dev/null @@ -1,9 +0,0 @@ -set (WAMR_BUILD_PLATFORM "linux") -set (WAMR_BUILD_TARGET "X86_64") -set (WAMR_BUILD_INTERP 1) -set (WAMR_BUILD_AOT 1) -set (WAMR_BUILD_JIT 0) -set (WAMR_BUILD_LIBC_BUILTIN 1) -set (WAMR_BUILD_LIBC_WASI 0) -set (WAMR_BUILD_APP_FRAMEWORK 1) -set (WAMR_BUILD_APP_LIST WAMR_APP_BUILD_ALL) diff --git a/samples/gui/wasm-apps/build_apps.sh b/samples/gui/wasm-apps/build_apps.sh deleted file mode 100755 index 18c76caf4..000000000 --- a/samples/gui/wasm-apps/build_apps.sh +++ /dev/null @@ -1,45 +0,0 @@ -#!/bin/bash - -APPS_ROOT=$(cd "$(dirname "$0")/" && pwd) -cd ${APPS_ROOT} - -echo "OUT_DIR: ${OUT_DIR}" - -if [ -z ${OUT_DIR} ]; then - OUT_DIR=${APPS_ROOT}/out - echo "set the wasm app folder: ${OUT_DIR}" - - if [ -d ${OUT_DIR} ]; then - rm -rf ${OUT_DIR} - echo "removed the present output folder: ${OUT_DIR}" - fi - mkdir ${OUT_DIR} - -fi - -if [ -z ${WAMR_DIR} ]; then - WAMR_DIR=${APPS_ROOT}/../../.. -fi - - -cd ${APPS_ROOT}/increase - -rm -rf build -mkdir build && cd build -cmake .. -DCMAKE_TOOLCHAIN_FILE=${WAMR_DIR}/wamr-sdk/out/gui/app-sdk/wamr_toolchain.cmake \ - -DWASI_SDK_DIR=/opt/wasi-sdk -make -[ $? -eq 0 ] || exit $? -mv ui_increase.wasm ${OUT_DIR}/ - -# $makewrap -# mv ui_app.wasm ${OUT_DIR}/ - -cd ${APPS_ROOT}/decrease -make -[ $? -eq 0 ] || exit $? -mv ui_decrease.wasm ${OUT_DIR}/ - -echo "WASM files generated in folder ${OUT_DIR}" - -echo "##################### build WASM APPs finished #####################" diff --git a/samples/gui/wasm-apps/decrease/Makefile b/samples/gui/wasm-apps/decrease/Makefile deleted file mode 100644 index d99008beb..000000000 --- a/samples/gui/wasm-apps/decrease/Makefile +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -CC = /opt/wasi-sdk/bin/clang -APP_DIR = ${shell pwd} -IWASM_DIR = $(APP_DIR)/../../../../core/iwasm -SDK_DIR = $(APP_DIR)/../../../../wamr-sdk/out/gui/app-sdk -APP_FRAMEWORK_DIR = $(APP_DIR)/../../../../wamr-sdk/out/gui/app-sdk/wamr-app-framework -DEPS_DIR = $(APP_DIR)/../../../../core/deps - -CFLAGS += -O3 \ - -Wno-int-conversion \ - -I$(APP_DIR)/src \ - -I$(APP_FRAMEWORK_DIR)/include \ - -I${DEPS_DIR} - -SRCS += $(APP_DIR)/src/main.c - -all: - @$(CC) $(CFLAGS) $(SRCS) \ - --target=wasm32 -O3 -z stack-size=2048 -Wl,--initial-memory=65536 \ - --sysroot=$(SDK_DIR)/libc-builtin-sysroot \ - -L$(APP_FRAMEWORK_DIR)/lib -lapp_framework \ - -Wl,--allow-undefined-file=$(SDK_DIR)/libc-builtin-sysroot/share/defined-symbols.txt \ - -Wl,--strip-all,--no-entry -nostdlib \ - -Wl,--export=on_init -Wl,--export=on_timer_callback \ - -Wl,--export=on_widget_event \ - -Wl,--export=__heap_base,--export=__data_end \ - -o ui_decrease.wasm diff --git a/samples/gui/wasm-apps/increase/CMakeLists.txt b/samples/gui/wasm-apps/increase/CMakeLists.txt deleted file mode 100644 index ce55fb1e6..000000000 --- a/samples/gui/wasm-apps/increase/CMakeLists.txt +++ /dev/null @@ -1,20 +0,0 @@ -cmake_minimum_required(VERSION 2.8) - -project(wgl) - -set (WAMR_ROOT_DIR ${CMAKE_CURRENT_LIST_DIR}/../../../../) - -include_directories( - ${WAMR_ROOT_DIR}/wamr-sdk/out/gui/app-sdk/wamr-app-framework/include - ${WAMR_ROOT_DIR}/core/deps -) - -set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS},-L${WAMR_ROOT_DIR}/wamr-sdk/out/gui/app-sdk/wamr-app-framework/lib") -set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS},--export=on_init,--export=on_timer_callback,--export=on_widget_event,--export=__heap_base,--export=__data_end") -set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O3 -Wno-unused-command-line-argument") - -add_executable(ui_increase.wasm - ${CMAKE_CURRENT_LIST_DIR}/src/main.c -) - -target_link_libraries(ui_increase.wasm app_framework) diff --git a/samples/gui/wasm-apps/increase/Makefile b/samples/gui/wasm-apps/increase/Makefile deleted file mode 100644 index 5f250d6ef..000000000 --- a/samples/gui/wasm-apps/increase/Makefile +++ /dev/null @@ -1,34 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -CC = /opt/wasi-sdk/bin/clang -APP_DIR = ${shell pwd} -IWASM_DIR = ../../../../core/iwasm -APP_FRAMEWORK_DIR = ../../../../core/app-framework -DEPS_DIR = ../../../../core/deps - -CFLAGS += -O3 \ - -Wno-int-conversion \ - -I$(APP_DIR)/src \ - -I$(APP_FRAMEWORK_DIR)/base/app \ - -I$(APP_FRAMEWORK_DIR)/app-native-shared \ - -I$(APP_FRAMEWORK_DIR)/sensor/app \ - -I$(APP_FRAMEWORK_DIR)/wgl/app \ - -I$(APP_FRAMEWORK_DIR)/connection/app \ - -I${DEPS_DIR} - -SRCS += $(APP_DIR)/src/main.c - -# For app size consideration, not all but necessary app libs are included -SRCS += $(APP_FRAMEWORK_DIR)/base/app/timer.c -SRCS += $(APP_FRAMEWORK_DIR)/wgl/app/src/*.c - -all: - @$(CC) $(CFLAGS) $(SRCS) \ - --target=wasm32-wasi -O3 -z stack-size=2048 -Wl,--initial-memory=65536 \ - -nostdlib -Wl,--allow-undefined \ - -Wl,--strip-all,--no-entry \ - -Wl,--export=on_init -Wl,--export=on_timer_callback \ - -Wl,--export=on_widget_event \ - -Wl,--export=__heap_base,--export=__data_end \ - -o ui_app.wasm diff --git a/samples/gui/wasm-runtime-wgl/linux-build/CMakeLists.txt b/samples/gui/wasm-runtime-wgl/linux-build/CMakeLists.txt deleted file mode 100644 index a2c9c0465..000000000 --- a/samples/gui/wasm-runtime-wgl/linux-build/CMakeLists.txt +++ /dev/null @@ -1,54 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -cmake_minimum_required (VERSION 2.9) - -project (wasm_runtime_wgl) - -set (WAMR_BUILD_PLATFORM "linux") - -# Reset default linker flags -set (CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "") -set (CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS "") - -################ wamr runtime settings ################ - -set (WAMR_ROOT_DIR ${CMAKE_CURRENT_LIST_DIR}/../../../..) -set (DEPS_DIR ${WAMR_ROOT_DIR}/core/deps) - - -add_definitions(-DLV_CONF_INCLUDE_SIMPLE) - -## use library and headers in the SDK -link_directories(${WAMR_ROOT_DIR}/wamr-sdk/out/gui/runtime-sdk/lib) -include_directories( - ${WAMR_ROOT_DIR}/wamr-sdk/out/gui/runtime-sdk/include - ${WAMR_ROOT_DIR}/wamr-sdk/out/gui/runtime-sdk/include/bi-inc/deps - ${WAMR_ROOT_DIR}/core/shared/utils - ${WAMR_ROOT_DIR}/core/shared/platform/${WAMR_BUILD_PLATFORM} -) - -################ application related ################ - -set (LV_DRIVERS_DIR ${WAMR_ROOT_DIR}/core/deps/lv_drivers) -file (GLOB_RECURSE LV_DRIVERS_SOURCES "${LV_DRIVERS_DIR}/*.c") - -set (PROJECT_SRC_DIR ${CMAKE_CURRENT_LIST_DIR}/../src/platform/${WAMR_BUILD_PLATFORM}) -include_directories( - ${PROJECT_SRC_DIR} - ${DEPS_DIR} - ${DEPS_DIR}/lvgl - ${DEPS_DIR}/lvgl/src -) - -set (SOURCES - ${PROJECT_SRC_DIR}/main.c - ${PROJECT_SRC_DIR}/iwasm_main.c - ${LV_DRIVERS_SOURCES} - ) - -add_executable (wasm_runtime_wgl ${SOURCES}) - -target_link_libraries (wasm_runtime_wgl vmlib -lm -ldl -lpthread -lSDL2) -#target_link_libraries(wasm_runtime_wgl PRIVATE SDL2 ) - diff --git a/samples/gui/wasm-runtime-wgl/src/platform/linux/iwasm_main.c b/samples/gui/wasm-runtime-wgl/src/platform/linux/iwasm_main.c deleted file mode 100644 index 61c7bb39d..000000000 --- a/samples/gui/wasm-runtime-wgl/src/platform/linux/iwasm_main.c +++ /dev/null @@ -1,564 +0,0 @@ - -#ifndef CONNECTION_UART -#include -#include -#include -#include -#else -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "runtime_lib.h" -#include "runtime_timer.h" -#include "native_interface.h" -#include "app_manager_export.h" -#include "bh_platform.h" -#include "runtime_sensor.h" -#include "bi-inc/attr_container.h" -#include "module_wasm_app.h" -#include "wasm_export.h" -#include "wgl.h" - -#include "lv_drivers/display/monitor.h" -#include "lv_drivers/indev/mouse.h" - -#define MAX 2048 - -#ifndef CONNECTION_UART -#define SA struct sockaddr -static char *host_address = "127.0.0.1"; -static int port = 8888; -#else -static char *uart_device = "/dev/ttyS2"; -static int baudrate = B115200; -#endif - -extern bool -init_sensor_framework(); -extern void -exit_sensor_framework(); -extern void -exit_connection_framework(); -extern int -aee_host_msg_callback(void *msg, uint32_t msg_len); -extern bool -init_connection_framework(); - -#ifndef CONNECTION_UART -int listenfd = -1; -int sockfd = -1; -static pthread_mutex_t sock_lock = PTHREAD_MUTEX_INITIALIZER; -#else -int uartfd = -1; -#endif - -#ifndef CONNECTION_UART -static bool server_mode = false; - -// Function designed for chat between client and server. -void * -func(void *arg) -{ - char buff[MAX]; - int n; - struct sockaddr_in servaddr; - - while (1) { - if (sockfd != -1) - close(sockfd); - // socket create and verification - sockfd = socket(AF_INET, SOCK_STREAM, 0); - if (sockfd == -1) { - printf("socket creation failed...\n"); - return NULL; - } - else - printf("Socket successfully created..\n"); - bzero(&servaddr, sizeof(servaddr)); - // assign IP, PORT - servaddr.sin_family = AF_INET; - servaddr.sin_addr.s_addr = inet_addr(host_address); - servaddr.sin_port = htons(port); - - // connect the client socket to server socket - if (connect(sockfd, (SA *)&servaddr, sizeof(servaddr)) != 0) { - printf("connection with the server failed...\n"); - sleep(10); - continue; - } - else { - printf("connected to the server..\n"); - } - - // infinite loop for chat - for (;;) { - bzero(buff, MAX); - - // read the message from client and copy it in buffer - n = read(sockfd, buff, sizeof(buff)); - // print buffer which contains the client contents - // fprintf(stderr, "recieved %d bytes from host: %s", n, buff); - - // socket disconnected - if (n <= 0) - break; - - aee_host_msg_callback(buff, n); - } - } - - // After chatting close the socket - close(sockfd); -} - -static bool -host_init() -{ - return true; -} - -int -host_send(void *ctx, const char *buf, int size) -{ - int ret; - - if (pthread_mutex_trylock(&sock_lock) == 0) { - if (sockfd == -1) { - pthread_mutex_unlock(&sock_lock); - return 0; - } - - ret = write(sockfd, buf, size); - - pthread_mutex_unlock(&sock_lock); - return ret; - } - - return -1; -} - -void -host_destroy() -{ - if (server_mode) - close(listenfd); - - pthread_mutex_lock(&sock_lock); - close(sockfd); - pthread_mutex_unlock(&sock_lock); -} - -/* clang-format off */ -host_interface interface = { - .init = host_init, - .send = host_send, - .destroy = host_destroy -}; -/* clang-format on */ - -void * -func_server_mode(void *arg) -{ - int clilent; - struct sockaddr_in serv_addr, cli_addr; - int n; - char buff[MAX]; - struct sigaction sa; - - sa.sa_handler = SIG_IGN; - sa.sa_flags = 0; - sigemptyset(&sa.sa_mask); - sigaction(SIGPIPE, &sa, 0); - - /* First call to socket() function */ - listenfd = socket(AF_INET, SOCK_STREAM, 0); - - if (listenfd < 0) { - perror("ERROR opening socket"); - exit(1); - } - - /* Initialize socket structure */ - bzero((char *)&serv_addr, sizeof(serv_addr)); - - serv_addr.sin_family = AF_INET; - serv_addr.sin_addr.s_addr = INADDR_ANY; - serv_addr.sin_port = htons(port); - - /* Now bind the host address using bind() call.*/ - if (bind(listenfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { - perror("ERROR on binding"); - exit(1); - } - - listen(listenfd, 5); - clilent = sizeof(cli_addr); - - while (1) { - pthread_mutex_lock(&sock_lock); - - sockfd = accept(listenfd, (struct sockaddr *)&cli_addr, &clilent); - - pthread_mutex_unlock(&sock_lock); - - if (sockfd < 0) { - perror("ERROR on accept"); - exit(1); - } - - printf("connection established!\n"); - - for (;;) { - bzero(buff, MAX); - - // read the message from client and copy it in buffer - n = read(sockfd, buff, sizeof(buff)); - - // socket disconnected - if (n <= 0) { - pthread_mutex_lock(&sock_lock); - close(sockfd); - sockfd = -1; - pthread_mutex_unlock(&sock_lock); - - sleep(2); - break; - } - - aee_host_msg_callback(buff, n); - } - } -} - -#else -static int -parse_baudrate(int baud) -{ - switch (baud) { - case 9600: - return B9600; - case 19200: - return B19200; - case 38400: - return B38400; - case 57600: - return B57600; - case 115200: - return B115200; - case 230400: - return B230400; - case 460800: - return B460800; - case 500000: - return B500000; - case 576000: - return B576000; - case 921600: - return B921600; - case 1000000: - return B1000000; - case 1152000: - return B1152000; - case 1500000: - return B1500000; - case 2000000: - return B2000000; - case 2500000: - return B2500000; - case 3000000: - return B3000000; - case 3500000: - return B3500000; - case 4000000: - return B4000000; - default: - return -1; - } -} -static bool -uart_init(const char *device, int baudrate, int *fd) -{ - int uart_fd; - struct termios uart_term; - - uart_fd = open(device, O_RDWR | O_NOCTTY); - - if (uart_fd <= 0) - return false; - - memset(&uart_term, 0, sizeof(uart_term)); - uart_term.c_cflag = baudrate | CS8 | CLOCAL | CREAD; - uart_term.c_iflag = IGNPAR; - uart_term.c_oflag = 0; - - /* set noncanonical mode */ - uart_term.c_lflag = 0; - uart_term.c_cc[VTIME] = 30; - uart_term.c_cc[VMIN] = 1; - tcflush(uart_fd, TCIFLUSH); - - if (tcsetattr(uart_fd, TCSANOW, &uart_term) != 0) { - close(uart_fd); - return false; - } - - *fd = uart_fd; - - return true; -} - -static void * -func_uart_mode(void *arg) -{ - int n; - char buff[MAX]; - - if (!uart_init(uart_device, baudrate, &uartfd)) { - printf("open uart fail! %s\n", uart_device); - return NULL; - } - - for (;;) { - bzero(buff, MAX); - - n = read(uartfd, buff, sizeof(buff)); - - if (n <= 0) { - close(uartfd); - uartfd = -1; - break; - } - - aee_host_msg_callback(buff, n); - } - - return NULL; -} - -static int -uart_send(void *ctx, const char *buf, int size) -{ - int ret; - - ret = write(uartfd, buf, size); - - return ret; -} - -static void -uart_destroy() -{ - close(uartfd); -} - -/* clang-format off */ -static host_interface interface = { - .send = uart_send, - .destroy = uart_destroy -}; -/* clang-format on */ - -#endif - -static char global_heap_buf[270 * 1024] = { 0 }; - -/* clang-format off */ -static void showUsage() -{ -#ifndef CONNECTION_UART - printf("Usage:\n"); - printf("\nWork as TCP server mode:\n"); - printf("\tvgl_wasm_runtime -s|--server_mode -p|--port \n"); - printf("where\n"); - printf("\t represents the port that would be listened on and the default is 8888\n"); - printf("\nWork as TCP client mode:\n"); - printf("\tvgl_wasm_runtime -a|--host_address -p|--port \n"); - printf("where\n"); - printf("\t represents the network address of host and the default is 127.0.0.1\n"); - printf("\t represents the listen port of host and the default is 8888\n"); -#else - printf("Usage:\n"); - printf("\tvgl_wasm_runtime -u -b \n\n"); - printf("where\n"); - printf("\t represents the UART device name and the default is /dev/ttyS2\n"); - printf("\t represents the UART device baudrate and the default is 115200\n"); -#endif -} -/* clang-format on */ - -static bool -parse_args(int argc, char *argv[]) -{ - int c; - - while (1) { - int optIndex = 0; - static struct option longOpts[] = { -#ifndef CONNECTION_UART - { "server_mode", no_argument, NULL, 's' }, - { "host_address", required_argument, NULL, 'a' }, - { "port", required_argument, NULL, 'p' }, -#else - { "uart", required_argument, NULL, 'u' }, - { "baudrate", required_argument, NULL, 'b' }, -#endif - { "help", required_argument, NULL, 'h' }, - { 0, 0, 0, 0 } - }; - - c = getopt_long(argc, argv, "sa:p:u:b:h", longOpts, &optIndex); - if (c == -1) - break; - - switch (c) { -#ifndef CONNECTION_UART - case 's': - server_mode = true; - break; - case 'a': - host_address = optarg; - printf("host address: %s\n", host_address); - break; - case 'p': - port = atoi(optarg); - printf("port: %d\n", port); - break; -#else - case 'u': - uart_device = optarg; - printf("uart device: %s\n", uart_device); - break; - case 'b': - baudrate = parse_baudrate(atoi(optarg)); - printf("uart baudrate: %s\n", optarg); - break; -#endif - case 'h': - showUsage(); - return false; - default: - showUsage(); - return false; - } - } - - return true; -} - -/** - * Initialize the Hardware Abstraction Layer (HAL) for the Littlev graphics - * library - */ -static void -hal_init(void) -{ - /* Use the 'monitor' driver which creates window on PC's monitor to simulate - * a display*/ - monitor_init(); - - /*Create a display buffer*/ - static lv_disp_buf_t disp_buf1; - static lv_color_t buf1_1[480 * 10]; - lv_disp_buf_init(&disp_buf1, buf1_1, NULL, 480 * 10); - - /*Create a display*/ - lv_disp_drv_t disp_drv; - - /*Basic initialization*/ - memset(&disp_drv, 0, sizeof(disp_drv)); - lv_disp_drv_init(&disp_drv); - disp_drv.buffer = &disp_buf1; - disp_drv.flush_cb = monitor_flush; - // disp_drv.hor_res = 200; - // disp_drv.ver_res = 100; - lv_disp_drv_register(&disp_drv); - - /* Add the mouse as input device - * Use the 'mouse' driver which reads the PC's mouse*/ - mouse_init(); - lv_indev_drv_t indev_drv; - lv_indev_drv_init(&indev_drv); /*Basic initialization*/ - indev_drv.type = LV_INDEV_TYPE_POINTER; - indev_drv.read_cb = - mouse_read; /*This function will be called periodically (by the library) - to get the mouse position and state*/ - lv_indev_drv_register(&indev_drv); -} - -// Driver function -int -iwasm_main(int argc, char *argv[]) -{ - RuntimeInitArgs init_args; - korp_tid tid; - - if (!parse_args(argc, argv)) - return -1; - - memset(&init_args, 0, sizeof(RuntimeInitArgs)); - - init_args.mem_alloc_type = Alloc_With_Pool; - init_args.mem_alloc_option.pool.heap_buf = global_heap_buf; - init_args.mem_alloc_option.pool.heap_size = sizeof(global_heap_buf); - - /* initialize runtime environment */ - if (!wasm_runtime_full_init(&init_args)) { - printf("Init runtime environment failed.\n"); - return -1; - } - - if (!init_connection_framework()) { - goto fail1; - } - - wgl_init(); - - hal_init(); - - if (!init_sensor_framework()) { - goto fail2; - } - - /* timer manager */ - if (!init_wasm_timer()) { - goto fail3; - } - -#ifndef CONNECTION_UART - if (server_mode) - os_thread_create(&tid, func_server_mode, NULL, - BH_APPLET_PRESERVED_STACK_SIZE); - else - os_thread_create(&tid, func, NULL, BH_APPLET_PRESERVED_STACK_SIZE); -#else - os_thread_create(&tid, func_uart_mode, NULL, - BH_APPLET_PRESERVED_STACK_SIZE); -#endif - - app_manager_startup(&interface); - - exit_wasm_timer(); - -fail3: - exit_sensor_framework(); - -fail2: - wgl_exit(); - exit_connection_framework(); - -fail1: - wasm_runtime_destroy(); - return -1; -} diff --git a/samples/gui/wasm-runtime-wgl/src/platform/linux/lv_drv_conf.h b/samples/gui/wasm-runtime-wgl/src/platform/linux/lv_drv_conf.h deleted file mode 100644 index d216a3e90..000000000 --- a/samples/gui/wasm-runtime-wgl/src/platform/linux/lv_drv_conf.h +++ /dev/null @@ -1,310 +0,0 @@ -/** - * @file lv_drv_conf.h - * - */ - -/* - * COPY THIS FILE AS lv_drv_conf.h - */ - -#if 1 /*Set it to "1" to enable the content*/ - -#ifndef LV_DRV_CONF_H -#define LV_DRV_CONF_H - -#include "lv_conf.h" - -/********************* - * DELAY INTERFACE - *********************/ -#define LV_DRV_DELAY_INCLUDE /*Dummy include by default*/ -#define LV_DRV_DELAY_US(us) /*delay_us(us)*/ /*Delay the given number of microseconds*/ -#define LV_DRV_DELAY_MS(ms) /*delay_ms(ms)*/ /*Delay the given number of milliseconds*/ - -/********************* - * DISPLAY INTERFACE - *********************/ - -/*------------ - * Common - *------------*/ -#define LV_DRV_DISP_INCLUDE /*Dummy include by default*/ -#define LV_DRV_DISP_CMD_DATA(val) /*pin_x_set(val)*/ /*Set the command/data pin to 'val'*/ -#define LV_DRV_DISP_RST(val) /*pin_x_set(val)*/ /*Set the reset pin to 'val'*/ - -/*--------- - * SPI - *---------*/ -#define LV_DRV_DISP_SPI_CS(val) /*spi_cs_set(val)*/ /*Set the SPI's Chip select to 'val'*/ -#define LV_DRV_DISP_SPI_WR_BYTE(data) /*spi_wr(data)*/ /*Write a byte the SPI bus*/ -#define LV_DRV_DISP_SPI_WR_ARRAY(adr, n) /*spi_wr_mem(adr, n)*/ /*Write 'n' bytes to SPI bus from 'adr'*/ - -/*------------------ - * Parallel port - *-----------------*/ -#define LV_DRV_DISP_PAR_CS(val) /*par_cs_set(val)*/ /*Set the Parallel port's Chip select to 'val'*/ -#define LV_DRV_DISP_PAR_SLOW /*par_slow()*/ /*Set low speed on the parallel port*/ -#define LV_DRV_DISP_PAR_FAST /*par_fast()*/ /*Set high speed on the parallel port*/ -#define LV_DRV_DISP_PAR_WR_WORD(data) /*par_wr(data)*/ /*Write a word to the parallel port*/ -#define LV_DRV_DISP_PAR_WR_ARRAY(adr, n) /*par_wr_mem(adr,n)*/ /*Write 'n' bytes to Parallel ports from 'adr'*/ - -/*************************** - * INPUT DEVICE INTERFACE - ***************************/ - -/*---------- - * Common - *----------*/ -#define LV_DRV_INDEV_INCLUDE /*Dummy include by default*/ -#define LV_DRV_INDEV_RST(val) /*pin_x_set(val)*/ /*Set the reset pin to 'val'*/ -#define LV_DRV_INDEV_IRQ_READ 0 /*pn_x_read()*/ /*Read the IRQ pin*/ - -/*--------- - * SPI - *---------*/ -#define LV_DRV_INDEV_SPI_CS(val) /*spi_cs_set(val)*/ /*Set the SPI's Chip select to 'val'*/ -#define LV_DRV_INDEV_SPI_XCHG_BYTE(data) 0 /*spi_xchg(val)*/ /*Write 'val' to SPI and give the read value*/ - -/*--------- - * I2C - *---------*/ -#define LV_DRV_INDEV_I2C_START /*i2c_start()*/ /*Make an I2C start*/ -#define LV_DRV_INDEV_I2C_STOP /*i2c_stop()*/ /*Make an I2C stop*/ -#define LV_DRV_INDEV_I2C_RESTART /*i2c_restart()*/ /*Make an I2C restart*/ -#define LV_DRV_INDEV_I2C_WR(data) /*i2c_wr(data)*/ /*Write a byte to the I1C bus*/ -#define LV_DRV_INDEV_I2C_READ(last_read) 0 /*i2c_rd()*/ /*Read a byte from the I2C bud*/ - - -/********************* - * DISPLAY DRIVERS - *********************/ - -/*------------------- - * Monitor of PC - *-------------------*/ -#ifndef USE_MONITOR -# define USE_MONITOR 1 -#endif - -#if USE_MONITOR -# define MONITOR_HOR_RES LV_HOR_RES_MAX -# define MONITOR_VER_RES LV_VER_RES_MAX - -/* Scale window by this factor (useful when simulating small screens) */ -# define MONITOR_ZOOM 1 - -/* Used to test true double buffering with only address changing. - * Set LV_VDB_SIZE = (LV_HOR_RES * LV_VER_RES) and LV_VDB_DOUBLE = 1 and LV_COLOR_DEPTH = 32" */ -# define MONITOR_DOUBLE_BUFFERED 0 - -/*Eclipse: Visual Studio: */ -# define MONITOR_SDL_INCLUDE_PATH - -/*Different rendering might be used if running in a Virtual machine*/ -# define MONITOR_VIRTUAL_MACHINE 0 - -/*Open two windows to test multi display support*/ -# define MONITOR_DUAL 0 -#endif - -/*----------------------------------- - * Native Windows (including mouse) - *----------------------------------*/ -#ifndef USE_WINDOWS -# define USE_WINDOWS 0 -#endif - -#define USE_WINDOWS 0 -#if USE_WINDOWS -# define WINDOW_HOR_RES 480 -# define WINDOW_VER_RES 320 -#endif - -/*---------------- - * SSD1963 - *--------------*/ -#ifndef USE_SSD1963 -# define USE_SSD1963 0 -#endif - -#if USE_SSD1963 -# define SSD1963_HOR_RES LV_HOR_RES -# define SSD1963_VER_RES LV_VER_RES -# define SSD1963_HT 531 -# define SSD1963_HPS 43 -# define SSD1963_LPS 8 -# define SSD1963_HPW 10 -# define SSD1963_VT 288 -# define SSD1963_VPS 12 -# define SSD1963_FPS 4 -# define SSD1963_VPW 10 -# define SSD1963_HS_NEG 0 /*Negative hsync*/ -# define SSD1963_VS_NEG 0 /*Negative vsync*/ -# define SSD1963_ORI 0 /*0, 90, 180, 270*/ -# define SSD1963_COLOR_DEPTH 16 -#endif - -/*---------------- - * R61581 - *--------------*/ -#ifndef USE_R61581 -# define USE_R61581 0 -#endif - -#if USE_R61581 -# define R61581_HOR_RES LV_HOR_RES -# define R61581_VER_RES LV_VER_RES -# define R61581_HSPL 0 /*HSYNC signal polarity*/ -# define R61581_HSL 10 /*HSYNC length (Not Implemented)*/ -# define R61581_HFP 10 /*Horitontal Front poarch (Not Implemented)*/ -# define R61581_HBP 10 /*Horitontal Back poarch (Not Implemented */ -# define R61581_VSPL 0 /*VSYNC signal polarity*/ -# define R61581_VSL 10 /*VSYNC length (Not Implemented)*/ -# define R61581_VFP 8 /*Vertical Front poarch*/ -# define R61581_VBP 8 /*Vertical Back poarch */ -# define R61581_DPL 0 /*DCLK signal polarity*/ -# define R61581_EPL 1 /*ENABLE signal polarity*/ -# define R61581_ORI 0 /*0, 180*/ -# define R61581_LV_COLOR_DEPTH 16 /*Fix 16 bit*/ -#endif - -/*------------------------------ - * ST7565 (Monochrome, low res.) - *-----------------------------*/ -#ifndef USE_ST7565 -# define USE_ST7565 0 -#endif - -#if USE_ST7565 -/*No settings*/ -#endif /*USE_ST7565*/ - -/*----------------------------------------- - * Linux frame buffer device (/dev/fbx) - *-----------------------------------------*/ -#ifndef USE_FBDEV -# define USE_FBDEV 1 -#endif - -#if USE_FBDEV -# define FBDEV_PATH "/dev/fb0" -#endif - -/********************* - * INPUT DEVICES - *********************/ - -/*-------------- - * XPT2046 - *--------------*/ -#ifndef USE_XPT2046 -# define USE_XPT2046 0 -#endif - -#if USE_XPT2046 -# define XPT2046_HOR_RES 480 -# define XPT2046_VER_RES 320 -# define XPT2046_X_MIN 200 -# define XPT2046_Y_MIN 200 -# define XPT2046_X_MAX 3800 -# define XPT2046_Y_MAX 3800 -# define XPT2046_AVG 4 -# define XPT2046_INV 0 -#endif - -/*----------------- - * FT5406EE8 - *-----------------*/ -#ifndef USE_FT5406EE8 -# define USE_FT5406EE8 0 -#endif - -#if USE_FT5406EE8 -# define FT5406EE8_I2C_ADR 0x38 /*7 bit address*/ -#endif - -/*--------------- - * AD TOUCH - *--------------*/ -#ifndef USE_AD_TOUCH -# define USE_AD_TOUCH 0 -#endif - -#if USE_AD_TOUCH -/*No settings*/ -#endif - - -/*--------------------------------------- - * Mouse or touchpad on PC (using SDL) - *-------------------------------------*/ -#ifndef USE_MOUSE -# define USE_MOUSE 1 -#endif - -#if USE_MOUSE -/*No settings*/ -#endif - -/*------------------------------------------- - * Mousewheel as encoder on PC (using SDL) - *------------------------------------------*/ -#ifndef USE_MOUSEWHEEL -# define USE_MOUSEWHEEL 1 -#endif - -#if USE_MOUSEWHEEL -/*No settings*/ -#endif - -/*------------------------------------------------- - * Touchscreen as libinput interface (for Linux based systems) - *------------------------------------------------*/ -#ifndef USE_LIBINPUT -# define USE_LIBINPUT 0 -#endif - -#if USE_LIBINPUT -# define LIBINPUT_NAME "/dev/input/event0" /*You can use the "evtest" Linux tool to get the list of devices and test them*/ -#endif /*USE_LIBINPUT*/ - -/*------------------------------------------------- - * Mouse or touchpad as evdev interface (for Linux based systems) - *------------------------------------------------*/ -#ifndef USE_EVDEV -# define USE_EVDEV 0 -#endif - -#if USE_EVDEV -# define EVDEV_NAME "/dev/input/event0" /*You can use the "evtest" Linux tool to get the list of devices and test them*/ -# define EVDEV_SWAP_AXES 0 /*Swap the x and y axes of the touchscreen*/ - -# define EVDEV_SCALE 0 /* Scale input, e.g. if touchscreen resolution does not match display resolution */ -# if EVDEV_SCALE -# define EVDEV_SCALE_HOR_RES (4096) /* Horizontal resolution of touchscreen */ -# define EVDEV_SCALE_VER_RES (4096) /* Vertical resolution of touchscreen */ -# endif /*EVDEV_SCALE*/ - -# define EVDEV_CALIBRATE 0 /*Scale and offset the touchscreen coordinates by using maximum and minimum values for each axis*/ -# if EVDEV_CALIBRATE -# define EVDEV_HOR_MIN 3800 /*If EVDEV_XXX_MIN > EVDEV_XXX_MAX the XXX axis is automatically inverted*/ -# define EVDEV_HOR_MAX 200 -# define EVDEV_VER_MIN 200 -# define EVDEV_VER_MAX 3800 -# endif /*EVDEV_SCALE*/ -#endif /*USE_EVDEV*/ - -/*------------------------------- - * Keyboard of a PC (using SDL) - *------------------------------*/ -#ifndef USE_KEYBOARD -# define USE_KEYBOARD 1 -#endif - -#if USE_KEYBOARD -/*No settings*/ -#endif - -#endif /*LV_DRV_CONF_H*/ - -#endif /*End of "Content enable"*/ diff --git a/samples/gui/wasm-runtime-wgl/src/platform/linux/main.c b/samples/gui/wasm-runtime-wgl/src/platform/linux/main.c deleted file mode 100644 index 741e54fd8..000000000 --- a/samples/gui/wasm-runtime-wgl/src/platform/linux/main.c +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ -#include -#include - -extern int -iwasm_main(int argc, char *argv[]); - -int -main(int argc, char *argv[]) -{ - return iwasm_main(argc, argv); -} - -int -time_get_ms() -{ - static struct timeval tv; - gettimeofday(&tv, NULL); - long long time_in_mill = (tv.tv_sec) * 1000 + (tv.tv_usec) / 1000; - - return (int)time_in_mill; -} diff --git a/samples/gui/wasm-runtime-wgl/src/platform/zephyr/LICENSE b/samples/gui/wasm-runtime-wgl/src/platform/zephyr/LICENSE deleted file mode 100644 index 8f71f43fe..000000000 --- a/samples/gui/wasm-runtime-wgl/src/platform/zephyr/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - diff --git a/samples/gui/wasm-runtime-wgl/src/platform/zephyr/XPT2046.h b/samples/gui/wasm-runtime-wgl/src/platform/zephyr/XPT2046.h deleted file mode 100644 index 228321dcc..000000000 --- a/samples/gui/wasm-runtime-wgl/src/platform/zephyr/XPT2046.h +++ /dev/null @@ -1,65 +0,0 @@ -/** - * @file XPT2046.h - * - */ - -#ifndef XPT2046_H -#define XPT2046_H - -#define USE_XPT2046 1 - -#define XPT2046_HOR_RES 320 -#define XPT2046_VER_RES 240 -#define XPT2046_X_MIN 200 -#define XPT2046_Y_MIN 200 -#define XPT2046_X_MAX 3800 -#define XPT2046_Y_MAX 3800 -#define XPT2046_AVG 4 -#define XPT2046_INV 0 - -#define CMD_X_READ 0b10010000 -#define CMD_Y_READ 0b11010000 - -#ifdef __cplusplus -extern "C" { -#endif - -/********************* - * INCLUDES - *********************/ - -#if USE_XPT2046 -#include -#include -#include -#include "lv_hal/lv_hal_indev.h" -#include "device.h" -#include "drivers/gpio.h" - -/********************* - * DEFINES - *********************/ - -/********************** - * TYPEDEFS - **********************/ - -/********************** - * GLOBAL PROTOTYPES - **********************/ -void -xpt2046_init(void); -bool -xpt2046_read(lv_indev_data_t *data); - -/********************** - * MACROS - **********************/ - -#endif /* USE_XPT2046 */ - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* XPT2046_H */ diff --git a/samples/gui/wasm-runtime-wgl/src/platform/zephyr/board_config.h b/samples/gui/wasm-runtime-wgl/src/platform/zephyr/board_config.h deleted file mode 100644 index d7ea279a9..000000000 --- a/samples/gui/wasm-runtime-wgl/src/platform/zephyr/board_config.h +++ /dev/null @@ -1,9 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ -#ifndef __BOARD_CONFIG_H__ -#define __BOARD_CONFIG_H__ -#include "pin_config_stm32.h" - -#endif /* __BOARD_CONFIG_H__ */ diff --git a/samples/gui/wasm-runtime-wgl/src/platform/zephyr/display.h b/samples/gui/wasm-runtime-wgl/src/platform/zephyr/display.h deleted file mode 100644 index 8354ca378..000000000 --- a/samples/gui/wasm-runtime-wgl/src/platform/zephyr/display.h +++ /dev/null @@ -1,418 +0,0 @@ -/* - * Copyright (c) 2017 Jan Van Winkel - * - * SPDX-License-Identifier: Apache-2.0 - */ - -/** - * @file - * @brief Public API for display drivers and applications - */ - -#ifndef ZEPHYR_INCLUDE_DISPLAY_H_ -#define ZEPHYR_INCLUDE_DISPLAY_H_ - -/** - * @brief Display Interface - * @defgroup display_interface Display Interface - * @ingroup display_interfaces - * @{ - */ - -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -enum display_pixel_format { - PIXEL_FORMAT_RGB_888 = BIT(0), - PIXEL_FORMAT_MONO01 = BIT(1), /* 0=Black 1=White */ - PIXEL_FORMAT_MONO10 = BIT(2), /* 1=Black 0=White */ - PIXEL_FORMAT_ARGB_8888 = BIT(3), - PIXEL_FORMAT_RGB_565 = BIT(4), -}; - -enum display_screen_info { - /** - * If selected, one octet represents 8 pixels ordered vertically, - * otherwise ordered horizontally. - */ - SCREEN_INFO_MONO_VTILED = BIT(0), - /** - * If selected, the MSB represents the first pixel, - * otherwise MSB represents the last pixel. - */ - SCREEN_INFO_MONO_MSB_FIRST = BIT(1), - /** - * Electrophoretic Display. - */ - SCREEN_INFO_EPD = BIT(2), - /** - * Screen has two alternating ram buffers - */ - SCREEN_INFO_DOUBLE_BUFFER = BIT(3), -}; - -/** - * @enum display_orientation - * @brief Enumeration with possible display orientation - * - */ -enum display_orientation { - DISPLAY_ORIENTATION_NORMAL, - DISPLAY_ORIENTATION_ROTATED_90, - DISPLAY_ORIENTATION_ROTATED_180, - DISPLAY_ORIENTATION_ROTATED_270, -}; - -/** - * @struct display_capabilities - * @brief Structure holding display capabilities - * - * @var u16_t display_capabilities::x_resolution - * Display resolution in the X direction - * - * @var u16_t display_capabilities::y_resolution - * Display resolution in the Y direction - * - * @var u32_t display_capabilities::supported_pixel_formats - * Bitwise or of pixel formats supported by the display - * - * @var u32_t display_capabilities::screen_info - * Information about display panel - * - * @var enum display_pixel_format display_capabilities::current_pixel_format - * Currently active pixel format for the display - * - * @var enum display_orientation display_capabilities::current_orientation - * Current display orientation - * - */ -struct display_capabilities { - u16_t x_resolution; - u16_t y_resolution; - u32_t supported_pixel_formats; - u32_t screen_info; - enum display_pixel_format current_pixel_format; - enum display_orientation current_orientation; -}; - -/** - * @struct display_buffer_descriptor - * @brief Structure to describe display data buffer layout - * - * @var u32_t display_buffer_descriptor::buf_size - * Data buffer size in bytes - * - * @var u16_t display_buffer_descriptor::width - * Data buffer row width in pixels - * - * @var u16_t display_buffer_descriptor::height - * Data buffer column height in pixels - * - * @var u16_t display_buffer_descriptor::pitch - * Number of pixels between consecutive rows in the data buffer - * - */ -struct display_buffer_descriptor { - u32_t buf_size; - u16_t width; - u16_t height; - u16_t pitch; -}; - -/** - * @typedef display_blanking_on_api - * @brief Callback API to turn on display blanking - * See display_blanking_on() for argument description - */ -typedef int (*display_blanking_on_api)(const struct device *dev); - -/** - * @typedef display_blanking_off_api - * @brief Callback API to turn off display blanking - * See display_blanking_off() for argument description - */ -typedef int (*display_blanking_off_api)(const struct device *dev); - -/** - * @typedef display_write_api - * @brief Callback API for writing data to the display - * See display_write() for argument description - */ -typedef int (*display_write_api)(const struct device *dev, const u16_t x, - const u16_t y, - const struct display_buffer_descriptor *desc, - const void *buf); - -/** - * @typedef display_read_api - * @brief Callback API for reading data from the display - * See display_read() for argument description - */ -typedef int (*display_read_api)(const struct device *dev, const u16_t x, - const u16_t y, - const struct display_buffer_descriptor *desc, - void *buf); - -/** - * @typedef display_get_framebuffer_api - * @brief Callback API to get framebuffer pointer - * See display_get_framebuffer() for argument description - */ -typedef void *(*display_get_framebuffer_api)(const struct device *dev); - -/** - * @typedef display_set_brightness_api - * @brief Callback API to set display brightness - * See display_set_brightness() for argument description - */ -typedef int (*display_set_brightness_api)(const struct device *dev, - const u8_t brightness); - -/** - * @typedef display_set_contrast_api - * @brief Callback API to set display contrast - * See display_set_contrast() for argument description - */ -typedef int (*display_set_contrast_api)(const struct device *dev, - const u8_t contrast); - -/** - * @typedef display_get_capabilities_api - * @brief Callback API to get display capabilities - * See display_get_capabilities() for argument description - */ -typedef void (*display_get_capabilities_api)( - const struct device *dev, struct display_capabilities *capabilities); - -/** - * @typedef display_set_pixel_format_api - * @brief Callback API to set pixel format used by the display - * See display_set_pixel_format() for argument description - */ -typedef int (*display_set_pixel_format_api)( - const struct device *dev, const enum display_pixel_format pixel_format); - -/** - * @typedef display_set_orientation_api - * @brief Callback API to set orientation used by the display - * See display_set_orientation() for argument description - */ -typedef int (*display_set_orientation_api)( - const struct device *dev, const enum display_orientation orientation); - -/** - * @brief Display driver API - * API which a display driver should expose - */ -struct display_driver_api { - display_blanking_on_api blanking_on; - display_blanking_off_api blanking_off; - display_write_api write; - display_read_api read; - display_get_framebuffer_api get_framebuffer; - display_set_brightness_api set_brightness; - display_set_contrast_api set_contrast; - display_get_capabilities_api get_capabilities; - display_set_pixel_format_api set_pixel_format; - display_set_orientation_api set_orientation; -}; -extern struct ili9340_data ili9340_data1; -extern struct display_driver_api ili9340_api1; -/** - * @brief Write data to display - * - * @param dev Pointer to device structure - * @param x x Coordinate of the upper left corner where to write the buffer - * @param y y Coordinate of the upper left corner where to write the buffer - * @param desc Pointer to a structure describing the buffer layout - * @param buf Pointer to buffer array - * - * @retval 0 on success else negative errno code. - */ -static inline int -display_write(const struct device *dev, const u16_t x, const u16_t y, - const struct display_buffer_descriptor *desc, const void *buf) -{ - struct display_driver_api *api = &ili9340_api1; - //(struct display_driver_api *)dev->driver_api; - - return api->write(dev, x, y, desc, buf); -} - -/** - * @brief Read data from display - * - * @param dev Pointer to device structure - * @param x x Coordinate of the upper left corner where to read from - * @param y y Coordinate of the upper left corner where to read from - * @param desc Pointer to a structure describing the buffer layout - * @param buf Pointer to buffer array - * - * @retval 0 on success else negative errno code. - */ -static inline int -display_read(const struct device *dev, const u16_t x, const u16_t y, - const struct display_buffer_descriptor *desc, void *buf) -{ - struct display_driver_api *api = &ili9340_api1; - //(struct display_driver_api *)dev->driver_api; - - return api->read(dev, x, y, desc, buf); -} - -/** - * @brief Get pointer to framebuffer for direct access - * - * @param dev Pointer to device structure - * - * @retval Pointer to frame buffer or NULL if direct framebuffer access - * is not supported - * - */ -static inline void * -display_get_framebuffer(const struct device *dev) -{ - struct display_driver_api *api = &ili9340_api1; - //(struct display_driver_api *)dev->driver_api; - - return api->get_framebuffer(dev); -} - -/** - * @brief Turn display blanking on - * - * @param dev Pointer to device structure - * - * @retval 0 on success else negative errno code. - */ -static inline int -display_blanking_on(const struct device *dev) -{ - struct display_driver_api *api = &ili9340_api1; - //(struct display_driver_api *)dev->driver_api; - - return api->blanking_on(dev); -} - -/** - * @brief Turn display blanking off - * - * @param dev Pointer to device structure - * - * @retval 0 on success else negative errno code. - */ -static inline int -display_blanking_off(const struct device *dev) -{ - struct display_driver_api *api = &ili9340_api1; - //(struct display_driver_api *)dev->driver_api; - - return api->blanking_off(dev); -} - -/** - * @brief Set the brightness of the display - * - * Set the brightness of the display in steps of 1/256, where 255 is full - * brightness and 0 is minimal. - * - * @param dev Pointer to device structure - * @param brightness Brightness in steps of 1/256 - * - * @retval 0 on success else negative errno code. - */ -static inline int -display_set_brightness(const struct device *dev, u8_t brightness) -{ - struct display_driver_api *api = &ili9340_api1; - //(struct display_driver_api *)dev->driver_api; - - return api->set_brightness(dev, brightness); -} - -/** - * @brief Set the contrast of the display - * - * Set the contrast of the display in steps of 1/256, where 255 is maximum - * difference and 0 is minimal. - * - * @param dev Pointer to device structure - * @param contrast Contrast in steps of 1/256 - * - * @retval 0 on success else negative errno code. - */ -static inline int -display_set_contrast(const struct device *dev, u8_t contrast) -{ - struct display_driver_api *api = &ili9340_api1; - //(struct display_driver_api *)dev->driver_api; - - return api->set_contrast(dev, contrast); -} - -/** - * @brief Get display capabilities - * - * @param dev Pointer to device structure - * @param capabilities Pointer to capabilities structure to populate - */ -static inline void -display_get_capabilities(const struct device *dev, - struct display_capabilities *capabilities) -{ - struct display_driver_api *api = &ili9340_api1; - //(struct display_driver_api *)dev->driver_api; - - api->get_capabilities(dev, capabilities); -} - -/** - * @brief Set pixel format used by the display - * - * @param dev Pointer to device structure - * @param pixel_format Pixel format to be used by display - * - * @retval 0 on success else negative errno code. - */ -static inline int -display_set_pixel_format(const struct device *dev, - const enum display_pixel_format pixel_format) -{ - struct display_driver_api *api = &ili9340_api1; - //(struct display_driver_api *)dev->driver_api; - - return api->set_pixel_format(dev, pixel_format); -} - -/** - * @brief Set display orientation - * - * @param dev Pointer to device structure - * @param orientation Orientation to be used by display - * - * @retval 0 on success else negative errno code. - */ -static inline int -display_set_orientation(const struct device *dev, - const enum display_orientation orientation) -{ - struct display_driver_api *api = &ili9340_api1; - //(struct display_driver_api *)dev->driver_api; - - return api->set_orientation(dev, orientation); -} - -#ifdef __cplusplus -} -#endif - -/** - * @} - */ - -#endif /* ZEPHYR_INCLUDE_DISPLAY_H_*/ diff --git a/samples/gui/wasm-runtime-wgl/src/platform/zephyr/display_ili9340.c b/samples/gui/wasm-runtime-wgl/src/platform/zephyr/display_ili9340.c deleted file mode 100644 index 6dd8a330a..000000000 --- a/samples/gui/wasm-runtime-wgl/src/platform/zephyr/display_ili9340.c +++ /dev/null @@ -1,283 +0,0 @@ -/* - * Copyright (c) 2017 Jan Van Winkel - * - * SPDX-License-Identifier: Apache-2.0 - */ - -#include "display_ili9340.h" -#include - -//#define LOG_LEVEL CONFIG_DISPLAY_LOG_LEVEL -//#include -// LOG_MODULE_REGISTER(display_ili9340); -#define LOG_ERR printf -#define LOG_DBG printf -#define LOG_WRN printf - -#include -#include -#include -#include -#include - -struct ili9340_data { - struct device *reset_gpio; - struct device *command_data_gpio; - struct device *spi_dev; - struct spi_config spi_config; -#ifdef DT_ILITEK_ILI9340_0_CS_GPIO_CONTROLLER - struct spi_cs_control cs_ctrl; -#endif -}; - -struct ili9340_data ili9340_data1; - -#define ILI9340_CMD_DATA_PIN_COMMAND 0 -#define ILI9340_CMD_DATA_PIN_DATA 1 - -static void -ili9340_exit_sleep(struct ili9340_data *data) -{ - ili9340_transmit(data, ILI9340_CMD_EXIT_SLEEP, NULL, 0); - // k_sleep(Z_TIMEOUT_MS(120)); -} - -int -ili9340_init() -{ - struct ili9340_data *data = &ili9340_data1; - printf("Initializing display driver\n"); - data->spi_dev = device_get_binding(DT_ILITEK_ILI9340_0_BUS_NAME); - if (data->spi_dev == NULL) { - return -EPERM; - } - data->spi_config.frequency = DT_ILITEK_ILI9340_0_SPI_MAX_FREQUENCY; - data->spi_config.operation = - SPI_OP_MODE_MASTER - | SPI_WORD_SET(8); // SPI_OP_MODE_MASTER | SPI_WORD_SET(8); - data->spi_config.slave = DT_ILITEK_ILI9340_0_BASE_ADDRESS; - -#ifdef DT_ILITEK_ILI9340_0_CS_GPIO_CONTROLLER - data->cs_ctrl.gpio_dev = - device_get_binding(DT_ILITEK_ILI9340_0_CS_GPIO_CONTROLLER); - data->cs_ctrl.gpio_pin = DT_ILITEK_ILI9340_0_CS_GPIO_PIN; - data->cs_ctrl.delay = 0; - data->spi_config.cs = &(data->cs_ctrl); -#else - data->spi_config.cs = NULL; -#endif - data->reset_gpio = - device_get_binding(DT_ILITEK_ILI9340_0_RESET_GPIOS_CONTROLLER); - if (data->reset_gpio == NULL) { - return -EPERM; - } - - gpio_pin_configure(data->reset_gpio, DT_ILITEK_ILI9340_0_RESET_GPIOS_PIN, - GPIO_OUTPUT); - - data->command_data_gpio = - device_get_binding(DT_ILITEK_ILI9340_0_CMD_DATA_GPIOS_CONTROLLER); - if (data->command_data_gpio == NULL) { - return -EPERM; - } - - gpio_pin_configure(data->command_data_gpio, - DT_ILITEK_ILI9340_0_CMD_DATA_GPIOS_PIN, GPIO_OUTPUT); - - LOG_DBG("Resetting display driver\n"); - gpio_pin_set(data->reset_gpio, DT_ILITEK_ILI9340_0_RESET_GPIOS_PIN, 1); - k_sleep(Z_TIMEOUT_MS(1)); - gpio_pin_set(data->reset_gpio, DT_ILITEK_ILI9340_0_RESET_GPIOS_PIN, 0); - k_sleep(Z_TIMEOUT_MS(1)); - gpio_pin_set(data->reset_gpio, DT_ILITEK_ILI9340_0_RESET_GPIOS_PIN, 1); - k_sleep(Z_TIMEOUT_MS(5)); - - LOG_DBG("Initializing LCD\n"); - ili9340_lcd_init(data); - - LOG_DBG("Exiting sleep mode\n"); - ili9340_exit_sleep(data); - - return 0; -} - -static void -ili9340_set_mem_area(struct ili9340_data *data, const u16_t x, const u16_t y, - const u16_t w, const u16_t h) -{ - u16_t spi_data[2]; - - spi_data[0] = sys_cpu_to_be16(x); - spi_data[1] = sys_cpu_to_be16(x + w - 1); - ili9340_transmit(data, ILI9340_CMD_COLUMN_ADDR, &spi_data[0], 4); - - spi_data[0] = sys_cpu_to_be16(y); - spi_data[1] = sys_cpu_to_be16(y + h - 1); - ili9340_transmit(data, ILI9340_CMD_PAGE_ADDR, &spi_data[0], 4); -} - -static int -ili9340_write(const struct device *dev, const u16_t x, const u16_t y, - const struct display_buffer_descriptor *desc, const void *buf) -{ - struct ili9340_data *data = (struct ili9340_data *)&ili9340_data1; - const u8_t *write_data_start = (u8_t *)buf; - struct spi_buf tx_buf; - struct spi_buf_set tx_bufs; - u16_t write_cnt; - u16_t nbr_of_writes; - u16_t write_h; - - __ASSERT(desc->width <= desc->pitch, "Pitch is smaller then width"); - __ASSERT((3 * desc->pitch * desc->height) <= desc->buf_size, - "Input buffer to small"); - ili9340_set_mem_area(data, x, y, desc->width, desc->height); - - if (desc->pitch > desc->width) { - write_h = 1U; - nbr_of_writes = desc->height; - } - else { - write_h = desc->height; - nbr_of_writes = 1U; - } - ili9340_transmit(data, ILI9340_CMD_MEM_WRITE, (void *)write_data_start, - 3 * desc->width * write_h); - - tx_bufs.buffers = &tx_buf; - tx_bufs.count = 1; - - write_data_start += (3 * desc->pitch); - for (write_cnt = 1U; write_cnt < nbr_of_writes; ++write_cnt) { - tx_buf.buf = (void *)write_data_start; - tx_buf.len = 3 * desc->width * write_h; - spi_transceive(data->spi_dev, &data->spi_config, &tx_bufs, NULL); - write_data_start += (3 * desc->pitch); - } - - return 0; -} - -static int -ili9340_read(const struct device *dev, const u16_t x, const u16_t y, - const struct display_buffer_descriptor *desc, void *buf) -{ - LOG_ERR("Reading not supported\n"); - return -ENOTSUP; -} - -static void * -ili9340_get_framebuffer(const struct device *dev) -{ - LOG_ERR("Direct framebuffer access not supported\n"); - return NULL; -} - -static int -ili9340_display_blanking_off(const struct device *dev) -{ - struct ili9340_data *data = (struct ili9340_data *)dev->driver_data; - - LOG_DBG("Turning display blanking off\n"); - ili9340_transmit(data, ILI9340_CMD_DISPLAY_ON, NULL, 0); - return 0; -} - -static int -ili9340_display_blanking_on(const struct device *dev) -{ - struct ili9340_data *data = (struct ili9340_data *)dev->driver_data; - - LOG_DBG("Turning display blanking on\n"); - ili9340_transmit(data, ILI9340_CMD_DISPLAY_OFF, NULL, 0); - return 0; -} - -static int -ili9340_set_brightness(const struct device *dev, const u8_t brightness) -{ - LOG_WRN("Set brightness not implemented\n"); - return -ENOTSUP; -} - -static int -ili9340_set_contrast(const struct device *dev, const u8_t contrast) -{ - LOG_ERR("Set contrast not supported\n"); - return -ENOTSUP; -} - -static int -ili9340_set_pixel_format(const struct device *dev, - const enum display_pixel_format pixel_format) -{ - if (pixel_format == PIXEL_FORMAT_RGB_888) { - return 0; - } - LOG_ERR("Pixel format change not implemented\n"); - return -ENOTSUP; -} - -static int -ili9340_set_orientation(const struct device *dev, - const enum display_orientation orientation) -{ - if (orientation == DISPLAY_ORIENTATION_NORMAL) { - return 0; - } - LOG_ERR("Changing display orientation not implemented\n"); - return -ENOTSUP; -} - -static void -ili9340_get_capabilities(const struct device *dev, - struct display_capabilities *capabilities) -{ - memset(capabilities, 0, sizeof(struct display_capabilities)); - capabilities->x_resolution = 320; - capabilities->y_resolution = 240; - capabilities->supported_pixel_formats = PIXEL_FORMAT_RGB_888; - capabilities->current_pixel_format = PIXEL_FORMAT_RGB_888; - capabilities->current_orientation = DISPLAY_ORIENTATION_NORMAL; -} - -void -ili9340_transmit(struct ili9340_data *data, u8_t cmd, void *tx_data, - size_t tx_len) -{ - data = (struct ili9340_data *)&ili9340_data1; - struct spi_buf tx_buf = { .buf = &cmd, .len = 1 }; - struct spi_buf_set tx_bufs = { .buffers = &tx_buf, .count = 1 }; - - gpio_pin_set(data->command_data_gpio, - DT_ILITEK_ILI9340_0_CMD_DATA_GPIOS_PIN, - ILI9340_CMD_DATA_PIN_COMMAND); - spi_transceive(data->spi_dev, &data->spi_config, &tx_bufs, NULL); - if (tx_data != NULL) { - tx_buf.buf = tx_data; - tx_buf.len = tx_len; - gpio_pin_set(data->command_data_gpio, - DT_ILITEK_ILI9340_0_CMD_DATA_GPIOS_PIN, - ILI9340_CMD_DATA_PIN_DATA); - spi_transceive(data->spi_dev, &data->spi_config, &tx_bufs, NULL); - } -} - -struct display_driver_api ili9340_api1 = { - .blanking_on = ili9340_display_blanking_on, - .blanking_off = ili9340_display_blanking_off, - .write = ili9340_write, - .read = ili9340_read, - .get_framebuffer = ili9340_get_framebuffer, - .set_brightness = ili9340_set_brightness, - .set_contrast = ili9340_set_contrast, - .get_capabilities = ili9340_get_capabilities, - .set_pixel_format = ili9340_set_pixel_format, - .set_orientation = ili9340_set_orientation -}; - -/* - DEVICE_AND_API_INIT(ili9340, DT_ILITEK_ILI9340_0_LABEL, &ili9340_init, - &ili9340_data, NULL, APPLICATION, - CONFIG_APPLICATION_INIT_PRIORITY, &ili9340_api); - */ diff --git a/samples/gui/wasm-runtime-wgl/src/platform/zephyr/display_ili9340_adafruit_1480.c b/samples/gui/wasm-runtime-wgl/src/platform/zephyr/display_ili9340_adafruit_1480.c deleted file mode 100644 index 1077a87f1..000000000 --- a/samples/gui/wasm-runtime-wgl/src/platform/zephyr/display_ili9340_adafruit_1480.c +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2017 Jan Van Winkel - * - * SPDX-License-Identifier: Apache-2.0 - */ - -#include "display_ili9340.h" - -void -ili9340_lcd_init(struct ili9340_data *data) -{ - u8_t tx_data[15]; - - tx_data[0] = 0x23; - ili9340_transmit(data, ILI9340_CMD_POWER_CTRL_1, tx_data, 1); - - tx_data[0] = 0x10; - ili9340_transmit(data, ILI9340_CMD_POWER_CTRL_2, tx_data, 1); - - tx_data[0] = 0x3e; - tx_data[1] = 0x28; - ili9340_transmit(data, ILI9340_CMD_VCOM_CTRL_1, tx_data, 2); - - tx_data[0] = 0x86; - ili9340_transmit(data, ILI9340_CMD_VCOM_CTRL_2, tx_data, 1); - - tx_data[0] = - ILI9340_DATA_MEM_ACCESS_CTRL_MV | ILI9340_DATA_MEM_ACCESS_CTRL_BGR; - ili9340_transmit(data, ILI9340_CMD_MEM_ACCESS_CTRL, tx_data, 1); - - tx_data[0] = ILI9340_DATA_PIXEL_FORMAT_MCU_18_BIT - | ILI9340_DATA_PIXEL_FORMAT_RGB_18_BIT; - ili9340_transmit(data, ILI9340_CMD_PIXEL_FORMAT_SET, tx_data, 1); - - tx_data[0] = 0x00; - tx_data[1] = 0x18; - ili9340_transmit(data, ILI9340_CMD_FRAME_CTRL_NORMAL_MODE, tx_data, 2); - - tx_data[0] = 0x08; - tx_data[1] = 0x82; - tx_data[2] = 0x27; - ili9340_transmit(data, ILI9340_CMD_DISPLAY_FUNCTION_CTRL, tx_data, 3); - - tx_data[0] = 0x01; - ili9340_transmit(data, ILI9340_CMD_GAMMA_SET, tx_data, 1); - - tx_data[0] = 0x0F; - tx_data[1] = 0x31; - tx_data[2] = 0x2B; - tx_data[3] = 0x0C; - tx_data[4] = 0x0E; - tx_data[5] = 0x08; - tx_data[6] = 0x4E; - tx_data[7] = 0xF1; - tx_data[8] = 0x37; - tx_data[9] = 0x07; - tx_data[10] = 0x10; - tx_data[11] = 0x03; - tx_data[12] = 0x0E; - tx_data[13] = 0x09; - tx_data[14] = 0x00; - ili9340_transmit(data, ILI9340_CMD_POSITVE_GAMMA_CORRECTION, tx_data, 15); - - tx_data[0] = 0x00; - tx_data[1] = 0x0E; - tx_data[2] = 0x14; - tx_data[3] = 0x03; - tx_data[4] = 0x11; - tx_data[5] = 0x07; - tx_data[6] = 0x31; - tx_data[7] = 0xC1; - tx_data[8] = 0x48; - tx_data[9] = 0x08; - tx_data[10] = 0x0F; - tx_data[11] = 0x0C; - tx_data[12] = 0x31; - tx_data[13] = 0x36; - tx_data[14] = 0x0F; - ili9340_transmit(data, ILI9340_CMD_NEGATIVE_GAMMA_CORRECTION, tx_data, 15); -} diff --git a/samples/gui/wasm-runtime-wgl/src/platform/zephyr/main.c b/samples/gui/wasm-runtime-wgl/src/platform/zephyr/main.c deleted file mode 100644 index e6254e5b9..000000000 --- a/samples/gui/wasm-runtime-wgl/src/platform/zephyr/main.c +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include -#include -#include "bh_platform.h" -#include "bh_assert.h" -#include "bh_log.h" -#include "wasm_export.h" - -extern int -iwasm_main(); - -void -main(void) -{ - iwasm_main(); - for (;;) { - k_sleep(Z_TIMEOUT_MS(1000)); - } -} - -int -time_get_ms() -{ - return k_uptime_get_32(); -} diff --git a/samples/gui/wasm-runtime-wgl/src/platform/zephyr/pin_config_jlf.h b/samples/gui/wasm-runtime-wgl/src/platform/zephyr/pin_config_jlf.h deleted file mode 100644 index bb20ecbb8..000000000 --- a/samples/gui/wasm-runtime-wgl/src/platform/zephyr/pin_config_jlf.h +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ -#ifndef __PIN_CONFIG_JLF_H__ -#define __PIN_CONFIG_JLF_H__ - -#define DT_ILITEK_ILI9340_0_BUS_NAME "SPI_2" -#define DT_ILITEK_ILI9340_0_SPI_MAX_FREQUENCY 10 * 1000 - -#define DT_ILITEK_ILI9340_0_BASE_ADDRESS 1 -#define DT_ILITEK_ILI9340_0_RESET_GPIOS_CONTROLLER "GPIO_0" -#define DT_ILITEK_ILI9340_0_RESET_GPIOS_PIN 5 -#define DT_ILITEK_ILI9340_0_CMD_DATA_GPIOS_CONTROLLER "GPIO_0" -#define DT_ILITEK_ILI9340_0_CMD_DATA_GPIOS_PIN 4 - -#define XPT2046_SPI_DEVICE_NAME "SPI_2" -#define XPT2046_SPI_MAX_FREQUENCY 10 * 1000 -#define XPT2046_CS_GPIO_CONTROLLER "GPIO_0" -#define XPT2046_CS_GPIO_PIN 6 - -#define XPT2046_PEN_GPIO_CONTROLLER "GPIO_0" -#define XPT2046_PEN_GPIO_PIN 7 - -#define HOST_DEVICE_COMM_UART_NAME "UART_1" -#endif /* __PIN_CONFIG_JLF_H__ */ diff --git a/samples/gui/wasm-runtime-wgl/src/platform/zephyr/pin_config_stm32.h b/samples/gui/wasm-runtime-wgl/src/platform/zephyr/pin_config_stm32.h deleted file mode 100644 index 523ce2308..000000000 --- a/samples/gui/wasm-runtime-wgl/src/platform/zephyr/pin_config_stm32.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ -#ifndef __PIN_CONFIG_STM32_H__ -#define __PIN_CONFIG_STM32_H__ - -#define DT_ILITEK_ILI9340_0_BUS_NAME "SPI_1" -#define DT_ILITEK_ILI9340_0_SPI_MAX_FREQUENCY 24 * 1000 * 1000 - -#define DT_ILITEK_ILI9340_0_BASE_ADDRESS 1 -#define DT_ILITEK_ILI9340_0_RESET_GPIOS_CONTROLLER "GPIOC" -#define DT_ILITEK_ILI9340_0_RESET_GPIOS_PIN 12 -#define DT_ILITEK_ILI9340_0_CMD_DATA_GPIOS_CONTROLLER "GPIOC" -#define DT_ILITEK_ILI9340_0_CMD_DATA_GPIOS_PIN 11 - -#define DT_ILITEK_ILI9340_0_CS_GPIO_CONTROLLER "GPIOC" -#define DT_ILITEK_ILI9340_0_CS_GPIO_PIN 10 - -#define XPT2046_SPI_DEVICE_NAME "SPI_1" -#define XPT2046_SPI_MAX_FREQUENCY 12 * 1000 * 1000 -#define XPT2046_CS_GPIO_CONTROLLER "GPIOD" -#define XPT2046_CS_GPIO_PIN 0 - -#define XPT2046_PEN_GPIO_CONTROLLER "GPIOD" -#define XPT2046_PEN_GPIO_PIN 1 - -#define HOST_DEVICE_COMM_UART_NAME "UART_6" - -#endif /* __PIN_CONFIG_STM32_H__ */ diff --git a/samples/gui/wasm-runtime-wgl/zephyr-build/CMakeLists.txt b/samples/gui/wasm-runtime-wgl/zephyr-build/CMakeLists.txt deleted file mode 100644 index 005358c72..000000000 --- a/samples/gui/wasm-runtime-wgl/zephyr-build/CMakeLists.txt +++ /dev/null @@ -1,78 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -cmake_minimum_required(VERSION 3.8.2) - -include($ENV{ZEPHYR_BASE}/cmake/app/boilerplate.cmake NO_POLICY_SCOPE) -project(NONE) - -set (WAMR_BUILD_PLATFORM "zephyr") - -enable_language (ASM) - -add_definitions(-DWA_MALLOC=wasm_runtime_malloc) -add_definitions(-DWA_FREE=wasm_runtime_free) - -# Build as THUMB by default -# change to "ARM[sub]", "THUMB[sub]", "X86_32", "MIPS" or "XTENSA" -# if we want to support arm_32, x86, mips or xtensa -if (NOT DEFINED WAMR_BUILD_TARGET) - set (WAMR_BUILD_TARGET "THUMBV7") -endif () - -if (NOT DEFINED WAMR_BUILD_INTERP) - # Enable Interpreter by default - set (WAMR_BUILD_INTERP 1) -endif () - -if (NOT DEFINED WAMR_BUILD_AOT) - 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_LIBC_BUILTIN) - # Enable libc builtin support by default - set (WAMR_BUILD_LIBC_BUILTIN 1) -endif () - -if (NOT DEFINED WAMR_BUILD_LIBC_WASI) - # Disable libc wasi support by default - set (WAMR_BUILD_LIBC_WASI 0) -endif () - -if (NOT DEFINED WAMR_BUILD_APP_FRAMEWORK) - set (WAMR_BUILD_APP_FRAMEWORK 1) -endif () - -if (NOT DEFINED WAMR_BUILD_APP_LIST) - set (WAMR_BUILD_APP_LIST WAMR_APP_BUILD_ALL) -endif () - -################ wamr runtime settings ################ -set (WAMR_ROOT_DIR ${CMAKE_CURRENT_SOURCE_DIR}/wamr) -include (${WAMR_ROOT_DIR}/build-scripts/runtime_lib.cmake) - -################ sample project related ################ -add_definitions(-DLV_CONF_INCLUDE_SIMPLE) -add_definitions(-DLV_MEM_CUSTOM=1) - -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../src) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../src/platform/zephyr) -include_directories(${WAMR_ROOT_DIR}/samples/gui/lv_config) - -set (LVGL_DRV_SRCS - ${CMAKE_CURRENT_SOURCE_DIR}/../src/platform/zephyr/display_ili9340_adafruit_1480.c - ${CMAKE_CURRENT_SOURCE_DIR}/../src/platform/zephyr/display_ili9340.c - ${CMAKE_CURRENT_SOURCE_DIR}/../src/platform/zephyr/XPT2046.c - ) - -target_sources(app PRIVATE - ${WAMR_RUNTIME_LIB_SOURCE} - ${LVGL_DRV_SRCS} - ${CMAKE_CURRENT_SOURCE_DIR}/../src/platform/zephyr/main.c - ${CMAKE_CURRENT_SOURCE_DIR}/../src/platform/zephyr/iwasm_main.c - ) diff --git a/samples/gui/wasm-runtime-wgl/zephyr-build/prj.conf b/samples/gui/wasm-runtime-wgl/zephyr-build/prj.conf deleted file mode 100644 index f9f13f9a7..000000000 --- a/samples/gui/wasm-runtime-wgl/zephyr-build/prj.conf +++ /dev/null @@ -1,10 +0,0 @@ -CONFIG_SPI=y -CONFIG_SPI_STM32=y -CONFIG_SPI_1=y -CONFIG_PRINTK=y -CONFIG_LOG=y -#CONFIG_UART_2=y -CONFIG_UART_INTERRUPT_DRIVEN=y -CONFIG_STACK_SENTINEL=y -CONFIG_MAIN_STACK_SIZE=2048 -CONFIG_ARM_MPU=y diff --git a/samples/littlevgl/LICENCE.txt b/samples/littlevgl/LICENCE.txt deleted file mode 100644 index beaef1d26..000000000 --- a/samples/littlevgl/LICENCE.txt +++ /dev/null @@ -1,8 +0,0 @@ -MIT licence -Copyright (c) 2016 Gábor Kiss-Vámosi - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/samples/littlevgl/README.md b/samples/littlevgl/README.md deleted file mode 100644 index 87fd2bd42..000000000 --- a/samples/littlevgl/README.md +++ /dev/null @@ -1,174 +0,0 @@ -"littlevgl" sample introduction -============== -This sample demonstrates that a graphic user interface application in WebAssembly by compiling the LittlevGL v5.3, an open-source embedded 2d graphic library into the WASM bytecode. - -In this sample, the whole LittlevGL v5.3 source code is built into the WebAssembly code with the user application. The platform interfaces defined by LittlevGL is implemented in the runtime and registered for WASM application through calling wasm_runtime_full_init(). - -```C -static NativeSymbol native_symbols[] = { - EXPORT_WASM_API_WITH_SIG(display_input_read, "(*)i"), - EXPORT_WASM_API_WITH_SIG(display_flush, "(iiii*)"), - EXPORT_WASM_API_WITH_SIG(display_fill, "(iiii*)"), - EXPORT_WASM_API_WITH_SIG(display_vdb_write, "(*iii*i)"), - EXPORT_WASM_API_WITH_SIG(display_map, "(iiii*)"), - EXPORT_WASM_API_WITH_SIG(time_get_ms, "()i") -}; -``` - -The runtime component supports building target for Linux and Zephyr/STM Nucleo board. The beauty of this sample is the WebAssembly application can have identical display and behavior when running from both runtime environments. That implies we can do majority of application validation from desktop environment as long as two runtime distributions support the same set of application interface. - - -Below pictures show the WASM application is running on an STM board with an LCD touch panel. - -![WAMR UI SAMPLE](../../doc/pics/vgl_demo2.png "WAMR UI DEMO STM32") - -![WAMR UI SAMPLE](../../doc/pics/vgl_demo_linux.png "WAMR UI DEMO LINUX") - - -The number on top will plus one each second, and the number on the bottom will plus one when clicked. When users click the blue button, the WASM application increases the counter, and the latest counter value is displayed on the top banner of the touch panel. - -The sample also provides the native Linux version of application without the runtime under folder "vgl-native-ui-app". It can help to check differences between the implementations in native and WebAssembly. - -Test on Linux -================================ - -Install required SDK and libraries --------------- -- 32 bit SDL(simple directmedia layer) (Note: only necessary when `WAMR_BUILD_TARGET` is set to `X86_32` when building WAMR runtime) -Use apt-get: - ```bash - sudo apt-get install libsdl2-dev:i386 - ``` -Or download source from www.libsdl.org: - ```bash - ./configure C_FLAGS=-m32 CXX_FLAGS=-m32 LD_FLAGS=-m32 - make - sudo make install - ``` -- 64 bit SDL(simple directmedia layer) (Note: only necessary when `WAMR_BUILD_TARGET` is set to `X86_64` when building WAMR runtime) -Use apt-get: - ```bash - sudo apt-get install libsdl2-dev - ``` -Or download source from www.libsdl.org: - ```bash - ./configure - make - sudo make install - ``` - -Build and Run --------------- - -- Build - ```bash - ./build.sh - ``` - All binaries are in "out", which contains "host_tool", "vgl_native_ui_app", "ui_app.wasm" "ui_app_no_wasi.wasm "and "vgl_wasm_runtime". -- Run the native Linux build of the lvgl sample (no wasm) - ```bash - ./vgl_native_ui_app - ``` - -- Run WASM VM Linux applicaton & install WASM APP - First start vgl_wasm_runtime in server mode. - ```bash - ./vgl_wasm_runtime -s - ``` - Then install and uninstall wasm APPs by using host tool. - ```bash - ./host_tool -i ui_wasi -f ui_app_wasi.wasm - ./host_tool -q - ./host_tool -u ui_wasi - ./host_tool -i ui_no_wasi -f ui_app_builtin_libc.wasm - ./host_tool -q - ./host_tool -u ui_no_wasi - ``` - -Test on Zephyr -================================ -We can use a STM32 NUCLEO_F767ZI board with ILI9341 display and XPT2046 touch screen to run the test. Then use host_tool to remotely install wasm app into STM32. -- Build WASM VM into Zephyr system - a. clone zephyr source code - Refer to [Zephyr getting started](https://docs.zephyrproject.org/latest/getting_started/index.html). - - ```bash - west init zephyrproject - cd zephyrproject/zephyr - git checkout zephyr-v2.3.0 - cd .. - west update - ``` - - b. copy samples - ```bash - cd zephyr/samples/ - cp -a /samples/littlevgl/vgl-wasm-runtime vgl-wasm-runtime - cd vgl-wasm-runtime/zephyr_build - ``` - c. create a link to wamr root dir - ```bash - ln -s wamr - ``` - -d. build source code - Since ui_app incorporated LittlevGL source code, so it needs more RAM on the device to install the application. It is recommended that RAM SIZE not less than 380KB. In our test use nucleo_f767zi, which is supported by Zephyr. Since the littlevgl wasm app is quite big (~100KB in wasm format and ~200KB in AOT format ), there isn't enough SRAM to build interpreter and AOT together. You can only choose one of them: - - - Interpreter - ```bash - mkdir build && cd build - source ../../../../zephyr-env.sh - cmake -GNinja -DBOARD=nucleo_f767zi -DWAMR_BUILD_INTERP=1 -DWAMR_BUILD_AOT=0 .. - ninja flash - ``` - - - AOT - ```bash - mkdir build && cd build - source ../../../../zephyr-env.sh - cmake -GNinja -DBOARD=nucleo_f767zi -DWAMR_BUILD_INTERP=0 -DWAMR_BUILD_AOT=1 .. - ninja flash - ``` - -- Hardware Connections - -``` -+-------------------+-+------------------+ -|NUCLEO-F767ZI | ILI9341 Display | -+-------------------+-+------------------+ -| CN7.10 | CLK | -+-------------------+-+------------------+ -| CN7.12 | MISO | -+-------------------+-+------------------+ -| CN7.14 | MOSI | -+-------------------+-+------------------+ -| CN11.1 | CS1 for ILI9341 | -+-------------------+-+------------------+ -| CN11.2 | D/C | -+-------------------+-+------------------+ -| CN11.3 | RESET | -+-------------------+-+------------------+ -| CN9.25 | PEN interrupt | -+-------------------+-+------------------+ -| CN9.27 | CS2 for XPT2046 | -+-------------------+-+------------------+ -| CN10.14 | PC UART RX | -+-------------------+-+------------------+ -| CN11.16 | PC UART RX | -+-------------------+-+------------------+ -``` - -- Install WASM application to Zephyr using host_tool -First, connect PC and STM32 with UART. Then install to use host_tool. - ```bash - sudo ./host_tool -D /dev/ttyUSBXXX -i ui_app -f ui_app_builtin_libc.wasm - # /dev/ttyUSBXXX is the UART device, e.g. /dev/ttyUSB0 - ``` -**Note**: WASI is unavailable on zephyr currently, so you have to use the ui_app_builtin_libc.wasm which doesn't depend on WASI. - -- Install AOT version WASM application - ```bash - wamrc --target=thumbv7 --target-abi=eabi --cpu=cortex-m7 -o ui_app_no_wasi.aot ui_app_builtin_libc.wasm - ./host_tool -D /dev/ttyUSBXXX -i ui_app -f ui_app_no_wasi.aot - ``` - diff --git a/samples/littlevgl/build.sh b/samples/littlevgl/build.sh deleted file mode 100755 index 81f2e67f4..000000000 --- a/samples/littlevgl/build.sh +++ /dev/null @@ -1,102 +0,0 @@ -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -#!/bin/bash - -PROJECT_DIR=$PWD -WAMR_DIR=${PWD}/../.. -OUT_DIR=${PWD}/out -BUILD_DIR=${PWD}/build -LV_CFG_PATH=${PROJECT_DIR}/lv_config - - - -if [ -z $KW_BUILD ] || [ -z $KW_OUT_FILE ];then - echo "Local Build Env" - cmakewrap="cmake" - makewrap="make" -else - echo "Klocwork Build Env" - cmakewrap="cmake -DCMAKE_BUILD_TYPE=Debug" - makewrap="kwinject -o $KW_OUT_FILE make" -fi - -if [ ! -d $BUILD_DIR ]; then - mkdir ${BUILD_DIR} -fi - -rm -rf ${OUT_DIR} -mkdir ${OUT_DIR} - - -cd ${BUILD_DIR} -if [ ! -d "lvgl" ]; then - echo "starting download lvgl for v5.3 ..." - git clone https://github.com/lvgl/lvgl.git --branch v5.3 - if [ $? != 0 ];then - echo "download lvgl repo failed: $?\n" - exit 2 - fi -fi - -echo "##################### 0. build wamr-sdk littlevgl start#####################" -cd ${WAMR_DIR}/wamr-sdk -./build_sdk.sh -n littlevgl -x ${PROJECT_DIR}/wamr_config_littlevgl.cmake -e ${LV_CFG_PATH} -c -[ $? -eq 0 ] || exit $? -echo "#####################build wamr-sdk littlevgl success" - -echo -e "\n\n" -echo "##################### 1. build native-ui-app start#####################" -cd $BUILD_DIR -mkdir -p vgl-native-ui-app -cd vgl-native-ui-app -$cmakewrap ${PROJECT_DIR}/vgl-native-ui-app -$makewrap -if [ $? != 0 ];then - echo "BUILD_FAIL native-ui-app $?\n" - exit 2 -fi -echo $PWD -cp vgl_native_ui_app ${OUT_DIR} -echo "#####################build native-ui-app success" - -echo -e "\n\n" -echo "##################### 2. build littlevgl wasm runtime start#####################" -cd $BUILD_DIR -mkdir -p vgl-wasm-runtime -cd vgl-wasm-runtime -$cmakewrap ${PROJECT_DIR}/vgl-wasm-runtime -$makewrap -[ $? -eq 0 ] || exit $? -cp vgl_wasm_runtime ${OUT_DIR}/ - -echo "##################### build littlevgl wasm runtime end#####################" - -echo -e "\n\n" -echo "#####################build host-tool" -cd $BUILD_DIR -mkdir -p host-tool -cd host-tool -$cmakewrap ${WAMR_DIR}/test-tools/host-tool -$makewrap -if [ $? != 0 ];then - echo "BUILD_FAIL host tool exit as $?\n" - exit 2 -fi -cp host_tool ${OUT_DIR} -echo "#####################build host-tool success" - -echo -e "\n\n" -echo "##################### 3. build wasm ui app start#####################" -cd ${PROJECT_DIR}/wasm-apps -if [ ! -d "${PROJECT_DIR}/wasm-apps/lvgl" ]; then - if [ -d "$BUILD_DIR/vgl-native-ui-app/lvgl" ]; then - cp -fr $BUILD_DIR/vgl-native-ui-app/lvgl ${PROJECT_DIR}/wasm-apps - fi -fi -./build_wasm_app.sh -mv *.wasm ${OUT_DIR}/ - -echo "##################### build wasm ui app end#####################" diff --git a/samples/littlevgl/lv_config/lv_conf.h b/samples/littlevgl/lv_config/lv_conf.h deleted file mode 100644 index 76533a8e1..000000000 --- a/samples/littlevgl/lv_config/lv_conf.h +++ /dev/null @@ -1,389 +0,0 @@ -/** - * @file lv_conf.h - * - */ - -#if 1 /*Set it to "1" to enable content*/ - -#ifndef LV_CONF_H -#define LV_CONF_H -/*=================== - Dynamic memory - *===================*/ - -/* Memory size which will be used by the library - * to store the graphical objects and other data */ -#define LV_MEM_CUSTOM 1 /*1: use custom malloc/free, 0: use the built-in lv_mem_alloc/lv_mem_free*/ -#if LV_MEM_CUSTOM == 0 -# define LV_MEM_SIZE (64U * 1024U) /*Size memory used by `lv_mem_alloc` in bytes (>= 2kB)*/ -# define LV_MEM_ATTR /*Complier prefix for big array declaration*/ -# define LV_MEM_ADR 0 /*Set an address for memory pool instead of allocation it as an array. Can be in external SRAM too.*/ -# define LV_MEM_AUTO_DEFRAG 1 /*Automatically defrag on free*/ -#else /*LV_MEM_CUSTOM*/ -# define LV_MEM_CUSTOM_INCLUDE /*Header for the dynamic memory function*/ -# define LV_MEM_CUSTOM_ALLOC malloc /*Wrapper to malloc*/ -# define LV_MEM_CUSTOM_FREE free /*Wrapper to free*/ -#endif /*LV_MEM_CUSTOM*/ - -/* Garbage Collector settings - * Used if lvgl is binded to higher language and the memory is managed by that language */ -#define LV_ENABLE_GC 0 -#if LV_ENABLE_GC != 0 -# define LV_MEM_CUSTOM_REALLOC your_realloc /*Wrapper to realloc*/ -# define LV_MEM_CUSTOM_GET_SIZE your_mem_get_size /*Wrapper to lv_mem_get_size*/ -# define LV_GC_INCLUDE "gc.h" /*Include Garbage Collector related things*/ -#endif /* LV_ENABLE_GC */ - -/*=================== - Graphical settings - *===================*/ - -/* Horizontal and vertical resolution of the library.*/ -#define LV_HOR_RES (320) -#define LV_VER_RES (240) - -/* Dot Per Inch: used to initialize default sizes. E.g. a button with width = LV_DPI / 2 -> half inch wide - * (Not so important, you can adjust it to modify default sizes and spaces)*/ -#define LV_DPI 100 - -/* Enable anti-aliasing (lines, and radiuses will be smoothed) */ -#define LV_ANTIALIAS 0 /*1: Enable anti-aliasing*/ - -/*Screen refresh period in milliseconds*/ -#define LV_REFR_PERIOD 30 - -/*----------------- - * VDB settings - *----------------*/ - -/* VDB (Virtual Display Buffer) is an internal graphics buffer. - * The GUI will be drawn into this buffer first and then - * the buffer will be passed to your `disp_drv.disp_flush` function to - * copy it to your frame buffer. - * VDB is required for: buffered drawing, opacity, anti-aliasing and shadows - * Learn more: https://docs.littlevgl.com/#Drawing*/ - -/* Size of the VDB in pixels. Typical size: ~1/10 screen. Must be >= LV_HOR_RES - * Setting it to 0 will disable VDB and `disp_drv.disp_fill` and `disp_drv.disp_map` functions - * will be called to draw to the frame buffer directly*/ -#define LV_VDB_SIZE ((LV_VER_RES * LV_HOR_RES) / 10) - -/* Bit-per-pixel of VDB. Useful for monochrome or non-standard color format displays. - * Special formats are handled with `disp_drv.vdb_wr`)*/ -#define LV_VDB_PX_BPP LV_COLOR_SIZE /*LV_COLOR_SIZE comes from LV_COLOR_DEPTH below to set 8, 16 or 32 bit pixel size automatically */ - -/* Place VDB to a specific address (e.g. in external RAM) - * 0: allocate automatically into RAM - * LV_VDB_ADR_INV: to replace it later with `lv_vdb_set_adr()`*/ -#define LV_VDB_ADR 0 - -/* Use two Virtual Display buffers (VDB) to parallelize rendering and flushing - * The flushing should use DMA to write the frame buffer in the background */ -#define LV_VDB_DOUBLE 0 - -/* Place VDB2 to a specific address (e.g. in external RAM) - * 0: allocate automatically into RAM - * LV_VDB_ADR_INV: to replace it later with `lv_vdb_set_adr()`*/ -#define LV_VDB2_ADR 0 - -/* Using true double buffering in `disp_drv.disp_flush` you will always get the image of the whole screen. - * Your only task is to set the rendered image (`color_p` parameter) as frame buffer address or send it to your display. - * The best if you do in the blank period of you display to avoid tearing effect. - * Requires: - * - LV_VDB_SIZE = LV_HOR_RES * LV_VER_RES - * - LV_VDB_DOUBLE = 1 - */ -#define LV_VDB_TRUE_DOUBLE_BUFFERED 0 - -/*================= - Misc. setting - *=================*/ - -/*Input device settings*/ -#define LV_INDEV_READ_PERIOD 50 /*Input device read period in milliseconds*/ -#define LV_INDEV_POINT_MARKER 0 /*Mark the pressed points (required: USE_LV_REAL_DRAW = 1)*/ -#define LV_INDEV_DRAG_LIMIT 10 /*Drag threshold in pixels */ -#define LV_INDEV_DRAG_THROW 20 /*Drag throw slow-down in [%]. Greater value means faster slow-down */ -#define LV_INDEV_LONG_PRESS_TIME 400 /*Long press time in milliseconds*/ -#define LV_INDEV_LONG_PRESS_REP_TIME 100 /*Repeated trigger period in long press [ms] */ - -/*Color settings*/ -#define LV_COLOR_DEPTH 32 /*Color depth: 1/8/16/32*/ -#define LV_COLOR_16_SWAP 0 /*Swap the 2 bytes of RGB565 color. Useful if the display has a 8 bit interface (e.g. SPI)*/ -#define LV_COLOR_SCREEN_TRANSP 0 /*1: Enable screen transparency. Useful for OSD or other overlapping GUIs. Requires ARGB8888 colors*/ -#define LV_COLOR_TRANSP LV_COLOR_LIME /*Images pixels with this color will not be drawn (with chroma keying)*/ - -/*Text settings*/ -#define LV_TXT_UTF8 1 /*Enable UTF-8 coded Unicode character usage */ -#define LV_TXT_BREAK_CHARS " ,.;:-_" /*Can break texts on these chars*/ -#define LV_TXT_LINE_BREAK_LONG_LEN 12 /* If a character is at least this long, will break wherever "prettiest" */ -#define LV_TXT_LINE_BREAK_LONG_PRE_MIN_LEN 3 /* Minimum number of characters of a word to put on a line before a break */ -#define LV_TXT_LINE_BREAK_LONG_POST_MIN_LEN 1 /* Minimum number of characters of a word to put on a line after a break */ - -/*Feature usage*/ -#define USE_LV_ANIMATION 1 /*1: Enable all animations*/ -#define USE_LV_SHADOW 1 /*1: Enable shadows*/ -#define USE_LV_GROUP 1 /*1: Enable object groups (for keyboards)*/ -#define USE_LV_GPU 0 /*1: Enable GPU interface*/ -#define USE_LV_REAL_DRAW 1 /*1: Enable function which draw directly to the frame buffer instead of VDB (required if LV_VDB_SIZE = 0)*/ -#define USE_LV_FILESYSTEM 0 /*1: Enable file system (might be required for images*/ -#define USE_LV_MULTI_LANG 0 /* Number of languages for labels to store (0: to disable this feature)*/ - -/*Compiler settings*/ -#define LV_ATTRIBUTE_TICK_INC /* Define a custom attribute to `lv_tick_inc` function */ -#define LV_ATTRIBUTE_TASK_HANDLER /* Define a custom attribute to `lv_task_handler` function */ -#define LV_COMPILER_VLA_SUPPORTED 1 /* 1: Variable length array is supported*/ -#define LV_COMPILER_NON_CONST_INIT_SUPPORTED 1 /* 1: Initialization with non constant values are supported */ - -/*HAL settings*/ -#define LV_TICK_CUSTOM 1 /*1: use a custom tick source (removing the need to manually update the tick with `lv_tick_inc`) */ -#if LV_TICK_CUSTOM == 1 -#define LV_TICK_CUSTOM_INCLUDE "system_header.h" /*Header for the sys time function*/ -#define LV_TICK_CUSTOM_SYS_TIME_EXPR (time_get_ms()) /*Expression evaluating to current systime in ms*/ -#endif /*LV_TICK_CUSTOM*/ - -/*Log settings*/ -#define USE_LV_LOG 1 /*Enable/disable the log module*/ -#if USE_LV_LOG -/* How important log should be added: - * LV_LOG_LEVEL_TRACE A lot of logs to give detailed information - * LV_LOG_LEVEL_INFO Log important events - * LV_LOG_LEVEL_WARN Log if something unwanted happened but didn't caused problem - * LV_LOG_LEVEL_ERROR Only critical issue, when the system may fail - */ -# define LV_LOG_LEVEL LV_LOG_LEVEL_WARN -/* 1: Print the log with 'printf'; 0: user need to register a callback*/ - -# define LV_LOG_PRINTF 0 -#endif /*USE_LV_LOG*/ - -/*================ - * THEME USAGE - *================*/ -#define LV_THEME_LIVE_UPDATE 1 /*1: Allow theme switching at run time. Uses 8..10 kB of RAM*/ - -#define USE_LV_THEME_TEMPL 0 /*Just for test*/ -#define USE_LV_THEME_DEFAULT 1 /*Built mainly from the built-in styles. Consumes very few RAM*/ -#define USE_LV_THEME_ALIEN 0 /*Dark futuristic theme*/ -#define USE_LV_THEME_NIGHT 0 /*Dark elegant theme*/ -#define USE_LV_THEME_MONO 0 /*Mono color theme for monochrome displays*/ -#define USE_LV_THEME_MATERIAL 0 /*Flat theme with bold colors and light shadows*/ -#define USE_LV_THEME_ZEN 0 /*Peaceful, mainly light theme */ -#define USE_LV_THEME_NEMO 0 /*Water-like theme based on the movie "Finding Nemo"*/ - -/*================== - * FONT USAGE - *===================*/ - -/* More info about fonts: https://docs.littlevgl.com/#Fonts - * To enable a built-in font use 1,2,4 or 8 values - * which will determine the bit-per-pixel. Higher value means smoother fonts */ -#define USE_LV_FONT_DEJAVU_10 0 -#define USE_LV_FONT_DEJAVU_10_LATIN_SUP 0 -#define USE_LV_FONT_DEJAVU_10_CYRILLIC 0 -#define USE_LV_FONT_SYMBOL_10 0 - -#define USE_LV_FONT_DEJAVU_20 4 -#define USE_LV_FONT_DEJAVU_20_LATIN_SUP 0 -#define USE_LV_FONT_DEJAVU_20_CYRILLIC 0 -#define USE_LV_FONT_SYMBOL_20 0 - -#define USE_LV_FONT_DEJAVU_30 0 -#define USE_LV_FONT_DEJAVU_30_LATIN_SUP 0 -#define USE_LV_FONT_DEJAVU_30_CYRILLIC 0 -#define USE_LV_FONT_SYMBOL_30 0 - -#define USE_LV_FONT_DEJAVU_40 0 -#define USE_LV_FONT_DEJAVU_40_LATIN_SUP 0 -#define USE_LV_FONT_DEJAVU_40_CYRILLIC 0 -#define USE_LV_FONT_SYMBOL_40 0 - -#define USE_LV_FONT_MONOSPACE_8 1 - -/* Optionally declare your custom fonts here. - * You can use these fonts as default font too - * and they will be available globally. E.g. - * #define LV_FONT_CUSTOM_DECLARE LV_FONT_DECLARE(my_font_1) \ - * LV_FONT_DECLARE(my_font_2) \ - */ -#define LV_FONT_CUSTOM_DECLARE - -#define LV_FONT_DEFAULT &lv_font_dejavu_20 /*Always set a default font from the built-in fonts*/ - -/*=================== - * LV_OBJ SETTINGS - *==================*/ -#define LV_OBJ_FREE_NUM_TYPE uint32_t /*Type of free number attribute (comment out disable free number)*/ -#define LV_OBJ_FREE_PTR 1 /*Enable the free pointer attribute*/ -#define LV_OBJ_REALIGN 1 /*Enable `lv_obj_realaign()` based on `lv_obj_align()` parameters*/ - -/*================== - * LV OBJ X USAGE - *================*/ -/* - * Documentation of the object types: https://docs.littlevgl.com/#Object-types - */ - -/***************** - * Simple object - *****************/ - -/*Label (dependencies: -*/ -#define USE_LV_LABEL 1 -#if USE_LV_LABEL != 0 -# define LV_LABEL_SCROLL_SPEED 25 /*Hor, or ver. scroll speed [px/sec] in 'LV_LABEL_LONG_SCROLL/ROLL' mode*/ -#endif - -/*Image (dependencies: lv_label*/ -#define USE_LV_IMG 1 -#if USE_LV_IMG != 0 -# define LV_IMG_CF_INDEXED 1 /*Enable indexed (palette) images*/ -# define LV_IMG_CF_ALPHA 1 /*Enable alpha indexed images*/ -#endif - -/*Line (dependencies: -*/ -#define USE_LV_LINE 1 - -/*Arc (dependencies: -)*/ -#define USE_LV_ARC 1 - -/******************* - * Container objects - *******************/ - -/*Container (dependencies: -*/ -#define USE_LV_CONT 1 - -/*Page (dependencies: lv_cont)*/ -#define USE_LV_PAGE 1 - -/*Window (dependencies: lv_cont, lv_btn, lv_label, lv_img, lv_page)*/ -#define USE_LV_WIN 1 - -/*Tab (dependencies: lv_page, lv_btnm)*/ -#define USE_LV_TABVIEW 1 -# if USE_LV_TABVIEW != 0 -# define LV_TABVIEW_ANIM_TIME 300 /*Time of slide animation [ms] (0: no animation)*/ -#endif - -/*Tileview (dependencies: lv_page) */ -#define USE_LV_TILEVIEW 1 -#if USE_LV_TILEVIEW -# define LV_TILEVIEW_ANIM_TIME 300 /*Time of slide animation [ms] (0: no animation)*/ -#endif - -/************************* - * Data visualizer objects - *************************/ - -/*Bar (dependencies: -)*/ -#define USE_LV_BAR 1 - -/*Line meter (dependencies: *;)*/ -#define USE_LV_LMETER 1 - -/*Gauge (dependencies:lv_bar, lv_lmeter)*/ -#define USE_LV_GAUGE 1 - -/*Chart (dependencies: -)*/ -#define USE_LV_CHART 1 - -/*Table (dependencies: lv_label)*/ -#define USE_LV_TABLE 1 -#if USE_LV_TABLE -# define LV_TABLE_COL_MAX 12 -#endif - -/*LED (dependencies: -)*/ -#define USE_LV_LED 1 - -/*Message box (dependencies: lv_rect, lv_btnm, lv_label)*/ -#define USE_LV_MBOX 1 - -/*Text area (dependencies: lv_label, lv_page)*/ -#define USE_LV_TA 1 -#if USE_LV_TA != 0 -# define LV_TA_CURSOR_BLINK_TIME 400 /*ms*/ -# define LV_TA_PWD_SHOW_TIME 1500 /*ms*/ -#endif - -/*Spinbox (dependencies: lv_ta)*/ -#define USE_LV_SPINBOX 1 - -/*Calendar (dependencies: -)*/ -#define USE_LV_CALENDAR 1 - -/*Preload (dependencies: lv_arc)*/ -#define USE_LV_PRELOAD 1 -#if USE_LV_PRELOAD != 0 -# define LV_PRELOAD_DEF_ARC_LENGTH 60 /*[deg]*/ -# define LV_PRELOAD_DEF_SPIN_TIME 1000 /*[ms]*/ -# define LV_PRELOAD_DEF_ANIM LV_PRELOAD_TYPE_SPINNING_ARC -#endif - -/*Canvas (dependencies: lv_img)*/ -#define USE_LV_CANVAS 1 -/************************* - * User input objects - *************************/ - -/*Button (dependencies: lv_cont*/ -#define USE_LV_BTN 1 -#if USE_LV_BTN != 0 -# define LV_BTN_INK_EFFECT 1 /*Enable button-state animations - draw a circle on click (dependencies: USE_LV_ANIMATION)*/ -#endif - -/*Image Button (dependencies: lv_btn*/ -#define USE_LV_IMGBTN 1 -#if USE_LV_IMGBTN -# define LV_IMGBTN_TILED 0 /*1: The imgbtn requires left, mid and right parts and the width can be set freely*/ -#endif - -/*Button matrix (dependencies: -)*/ -#define USE_LV_BTNM 1 - -/*Keyboard (dependencies: lv_btnm)*/ -#define USE_LV_KB 1 - -/*Check box (dependencies: lv_btn, lv_label)*/ -#define USE_LV_CB 1 - -/*List (dependencies: lv_page, lv_btn, lv_label, (lv_img optionally for icons ))*/ -#define USE_LV_LIST 1 -#if USE_LV_LIST != 0 -# define LV_LIST_FOCUS_TIME 100 /*Default animation time of focusing to a list element [ms] (0: no animation) */ -#endif - -/*Drop down list (dependencies: lv_page, lv_label, lv_symbol_def.h)*/ -#define USE_LV_DDLIST 1 -#if USE_LV_DDLIST != 0 -# define LV_DDLIST_ANIM_TIME 200 /*Open and close default animation time [ms] (0: no animation)*/ -#endif - -/*Roller (dependencies: lv_ddlist)*/ -#define USE_LV_ROLLER 1 -#if USE_LV_ROLLER != 0 -# define LV_ROLLER_ANIM_TIME 200 /*Focus animation time [ms] (0: no animation)*/ -#endif - -/*Slider (dependencies: lv_bar)*/ -#define USE_LV_SLIDER 1 - -/*Switch (dependencies: lv_slider)*/ -#define USE_LV_SW 1 - -/************************* - * Non-user section - *************************/ -#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) /* Disable warnings for Visual Studio*/ -# define _CRT_SECURE_NO_WARNINGS -#endif - -/*--END OF LV_CONF_H--*/ - -/*Be sure every define has a default value*/ -#include "lvgl/lv_conf_checker.h" - -#endif /*LV_CONF_H*/ - -#endif /*End of "Content enable"*/ diff --git a/samples/littlevgl/lv_config/lv_drv_conf.h b/samples/littlevgl/lv_config/lv_drv_conf.h deleted file mode 100644 index d216a3e90..000000000 --- a/samples/littlevgl/lv_config/lv_drv_conf.h +++ /dev/null @@ -1,310 +0,0 @@ -/** - * @file lv_drv_conf.h - * - */ - -/* - * COPY THIS FILE AS lv_drv_conf.h - */ - -#if 1 /*Set it to "1" to enable the content*/ - -#ifndef LV_DRV_CONF_H -#define LV_DRV_CONF_H - -#include "lv_conf.h" - -/********************* - * DELAY INTERFACE - *********************/ -#define LV_DRV_DELAY_INCLUDE /*Dummy include by default*/ -#define LV_DRV_DELAY_US(us) /*delay_us(us)*/ /*Delay the given number of microseconds*/ -#define LV_DRV_DELAY_MS(ms) /*delay_ms(ms)*/ /*Delay the given number of milliseconds*/ - -/********************* - * DISPLAY INTERFACE - *********************/ - -/*------------ - * Common - *------------*/ -#define LV_DRV_DISP_INCLUDE /*Dummy include by default*/ -#define LV_DRV_DISP_CMD_DATA(val) /*pin_x_set(val)*/ /*Set the command/data pin to 'val'*/ -#define LV_DRV_DISP_RST(val) /*pin_x_set(val)*/ /*Set the reset pin to 'val'*/ - -/*--------- - * SPI - *---------*/ -#define LV_DRV_DISP_SPI_CS(val) /*spi_cs_set(val)*/ /*Set the SPI's Chip select to 'val'*/ -#define LV_DRV_DISP_SPI_WR_BYTE(data) /*spi_wr(data)*/ /*Write a byte the SPI bus*/ -#define LV_DRV_DISP_SPI_WR_ARRAY(adr, n) /*spi_wr_mem(adr, n)*/ /*Write 'n' bytes to SPI bus from 'adr'*/ - -/*------------------ - * Parallel port - *-----------------*/ -#define LV_DRV_DISP_PAR_CS(val) /*par_cs_set(val)*/ /*Set the Parallel port's Chip select to 'val'*/ -#define LV_DRV_DISP_PAR_SLOW /*par_slow()*/ /*Set low speed on the parallel port*/ -#define LV_DRV_DISP_PAR_FAST /*par_fast()*/ /*Set high speed on the parallel port*/ -#define LV_DRV_DISP_PAR_WR_WORD(data) /*par_wr(data)*/ /*Write a word to the parallel port*/ -#define LV_DRV_DISP_PAR_WR_ARRAY(adr, n) /*par_wr_mem(adr,n)*/ /*Write 'n' bytes to Parallel ports from 'adr'*/ - -/*************************** - * INPUT DEVICE INTERFACE - ***************************/ - -/*---------- - * Common - *----------*/ -#define LV_DRV_INDEV_INCLUDE /*Dummy include by default*/ -#define LV_DRV_INDEV_RST(val) /*pin_x_set(val)*/ /*Set the reset pin to 'val'*/ -#define LV_DRV_INDEV_IRQ_READ 0 /*pn_x_read()*/ /*Read the IRQ pin*/ - -/*--------- - * SPI - *---------*/ -#define LV_DRV_INDEV_SPI_CS(val) /*spi_cs_set(val)*/ /*Set the SPI's Chip select to 'val'*/ -#define LV_DRV_INDEV_SPI_XCHG_BYTE(data) 0 /*spi_xchg(val)*/ /*Write 'val' to SPI and give the read value*/ - -/*--------- - * I2C - *---------*/ -#define LV_DRV_INDEV_I2C_START /*i2c_start()*/ /*Make an I2C start*/ -#define LV_DRV_INDEV_I2C_STOP /*i2c_stop()*/ /*Make an I2C stop*/ -#define LV_DRV_INDEV_I2C_RESTART /*i2c_restart()*/ /*Make an I2C restart*/ -#define LV_DRV_INDEV_I2C_WR(data) /*i2c_wr(data)*/ /*Write a byte to the I1C bus*/ -#define LV_DRV_INDEV_I2C_READ(last_read) 0 /*i2c_rd()*/ /*Read a byte from the I2C bud*/ - - -/********************* - * DISPLAY DRIVERS - *********************/ - -/*------------------- - * Monitor of PC - *-------------------*/ -#ifndef USE_MONITOR -# define USE_MONITOR 1 -#endif - -#if USE_MONITOR -# define MONITOR_HOR_RES LV_HOR_RES_MAX -# define MONITOR_VER_RES LV_VER_RES_MAX - -/* Scale window by this factor (useful when simulating small screens) */ -# define MONITOR_ZOOM 1 - -/* Used to test true double buffering with only address changing. - * Set LV_VDB_SIZE = (LV_HOR_RES * LV_VER_RES) and LV_VDB_DOUBLE = 1 and LV_COLOR_DEPTH = 32" */ -# define MONITOR_DOUBLE_BUFFERED 0 - -/*Eclipse: Visual Studio: */ -# define MONITOR_SDL_INCLUDE_PATH - -/*Different rendering might be used if running in a Virtual machine*/ -# define MONITOR_VIRTUAL_MACHINE 0 - -/*Open two windows to test multi display support*/ -# define MONITOR_DUAL 0 -#endif - -/*----------------------------------- - * Native Windows (including mouse) - *----------------------------------*/ -#ifndef USE_WINDOWS -# define USE_WINDOWS 0 -#endif - -#define USE_WINDOWS 0 -#if USE_WINDOWS -# define WINDOW_HOR_RES 480 -# define WINDOW_VER_RES 320 -#endif - -/*---------------- - * SSD1963 - *--------------*/ -#ifndef USE_SSD1963 -# define USE_SSD1963 0 -#endif - -#if USE_SSD1963 -# define SSD1963_HOR_RES LV_HOR_RES -# define SSD1963_VER_RES LV_VER_RES -# define SSD1963_HT 531 -# define SSD1963_HPS 43 -# define SSD1963_LPS 8 -# define SSD1963_HPW 10 -# define SSD1963_VT 288 -# define SSD1963_VPS 12 -# define SSD1963_FPS 4 -# define SSD1963_VPW 10 -# define SSD1963_HS_NEG 0 /*Negative hsync*/ -# define SSD1963_VS_NEG 0 /*Negative vsync*/ -# define SSD1963_ORI 0 /*0, 90, 180, 270*/ -# define SSD1963_COLOR_DEPTH 16 -#endif - -/*---------------- - * R61581 - *--------------*/ -#ifndef USE_R61581 -# define USE_R61581 0 -#endif - -#if USE_R61581 -# define R61581_HOR_RES LV_HOR_RES -# define R61581_VER_RES LV_VER_RES -# define R61581_HSPL 0 /*HSYNC signal polarity*/ -# define R61581_HSL 10 /*HSYNC length (Not Implemented)*/ -# define R61581_HFP 10 /*Horitontal Front poarch (Not Implemented)*/ -# define R61581_HBP 10 /*Horitontal Back poarch (Not Implemented */ -# define R61581_VSPL 0 /*VSYNC signal polarity*/ -# define R61581_VSL 10 /*VSYNC length (Not Implemented)*/ -# define R61581_VFP 8 /*Vertical Front poarch*/ -# define R61581_VBP 8 /*Vertical Back poarch */ -# define R61581_DPL 0 /*DCLK signal polarity*/ -# define R61581_EPL 1 /*ENABLE signal polarity*/ -# define R61581_ORI 0 /*0, 180*/ -# define R61581_LV_COLOR_DEPTH 16 /*Fix 16 bit*/ -#endif - -/*------------------------------ - * ST7565 (Monochrome, low res.) - *-----------------------------*/ -#ifndef USE_ST7565 -# define USE_ST7565 0 -#endif - -#if USE_ST7565 -/*No settings*/ -#endif /*USE_ST7565*/ - -/*----------------------------------------- - * Linux frame buffer device (/dev/fbx) - *-----------------------------------------*/ -#ifndef USE_FBDEV -# define USE_FBDEV 1 -#endif - -#if USE_FBDEV -# define FBDEV_PATH "/dev/fb0" -#endif - -/********************* - * INPUT DEVICES - *********************/ - -/*-------------- - * XPT2046 - *--------------*/ -#ifndef USE_XPT2046 -# define USE_XPT2046 0 -#endif - -#if USE_XPT2046 -# define XPT2046_HOR_RES 480 -# define XPT2046_VER_RES 320 -# define XPT2046_X_MIN 200 -# define XPT2046_Y_MIN 200 -# define XPT2046_X_MAX 3800 -# define XPT2046_Y_MAX 3800 -# define XPT2046_AVG 4 -# define XPT2046_INV 0 -#endif - -/*----------------- - * FT5406EE8 - *-----------------*/ -#ifndef USE_FT5406EE8 -# define USE_FT5406EE8 0 -#endif - -#if USE_FT5406EE8 -# define FT5406EE8_I2C_ADR 0x38 /*7 bit address*/ -#endif - -/*--------------- - * AD TOUCH - *--------------*/ -#ifndef USE_AD_TOUCH -# define USE_AD_TOUCH 0 -#endif - -#if USE_AD_TOUCH -/*No settings*/ -#endif - - -/*--------------------------------------- - * Mouse or touchpad on PC (using SDL) - *-------------------------------------*/ -#ifndef USE_MOUSE -# define USE_MOUSE 1 -#endif - -#if USE_MOUSE -/*No settings*/ -#endif - -/*------------------------------------------- - * Mousewheel as encoder on PC (using SDL) - *------------------------------------------*/ -#ifndef USE_MOUSEWHEEL -# define USE_MOUSEWHEEL 1 -#endif - -#if USE_MOUSEWHEEL -/*No settings*/ -#endif - -/*------------------------------------------------- - * Touchscreen as libinput interface (for Linux based systems) - *------------------------------------------------*/ -#ifndef USE_LIBINPUT -# define USE_LIBINPUT 0 -#endif - -#if USE_LIBINPUT -# define LIBINPUT_NAME "/dev/input/event0" /*You can use the "evtest" Linux tool to get the list of devices and test them*/ -#endif /*USE_LIBINPUT*/ - -/*------------------------------------------------- - * Mouse or touchpad as evdev interface (for Linux based systems) - *------------------------------------------------*/ -#ifndef USE_EVDEV -# define USE_EVDEV 0 -#endif - -#if USE_EVDEV -# define EVDEV_NAME "/dev/input/event0" /*You can use the "evtest" Linux tool to get the list of devices and test them*/ -# define EVDEV_SWAP_AXES 0 /*Swap the x and y axes of the touchscreen*/ - -# define EVDEV_SCALE 0 /* Scale input, e.g. if touchscreen resolution does not match display resolution */ -# if EVDEV_SCALE -# define EVDEV_SCALE_HOR_RES (4096) /* Horizontal resolution of touchscreen */ -# define EVDEV_SCALE_VER_RES (4096) /* Vertical resolution of touchscreen */ -# endif /*EVDEV_SCALE*/ - -# define EVDEV_CALIBRATE 0 /*Scale and offset the touchscreen coordinates by using maximum and minimum values for each axis*/ -# if EVDEV_CALIBRATE -# define EVDEV_HOR_MIN 3800 /*If EVDEV_XXX_MIN > EVDEV_XXX_MAX the XXX axis is automatically inverted*/ -# define EVDEV_HOR_MAX 200 -# define EVDEV_VER_MIN 200 -# define EVDEV_VER_MAX 3800 -# endif /*EVDEV_SCALE*/ -#endif /*USE_EVDEV*/ - -/*------------------------------- - * Keyboard of a PC (using SDL) - *------------------------------*/ -#ifndef USE_KEYBOARD -# define USE_KEYBOARD 1 -#endif - -#if USE_KEYBOARD -/*No settings*/ -#endif - -#endif /*LV_DRV_CONF_H*/ - -#endif /*End of "Content enable"*/ diff --git a/samples/littlevgl/vgl-native-ui-app/CMakeLists.txt b/samples/littlevgl/vgl-native-ui-app/CMakeLists.txt deleted file mode 100644 index 9778e821b..000000000 --- a/samples/littlevgl/vgl-native-ui-app/CMakeLists.txt +++ /dev/null @@ -1,137 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -cmake_minimum_required (VERSION 2.9) -message ("vgl_native_ui_app...") -project (vgl_native_ui_app) - - -SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DPLATFORM_NATIVE_LINUX -DUSE_MONITOR -DUSE_MOUSE=1") - -# Currently build as 64-bit by default. Set to "NO" to build 32-bit binaries. -set (BUILD_AS_64BIT_SUPPORT "YES") - -if (CMAKE_SIZEOF_VOID_P EQUAL 8) - if (${BUILD_AS_64BIT_SUPPORT} STREQUAL "YES") - # Add -fPIC flag if build as 64-bit - set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fPIC") - set (CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "${CMAKE_SHARED_LIBRARY_LINK_C_FLAGS} -fPIC") - else () - add_definitions (-m32) - set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -m32") - set (CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -m32") - endif () -endif () - -set(lv_name lvgl) -set(LVGL_SOURCE_DIR ${CMAKE_CURRENT_LIST_DIR}/../build/lvgl) -set(LVGL_DRIVER_DIR ${CMAKE_CURRENT_LIST_DIR}/lv-drivers) - -message(${LVGL_SOURCE_DIR}) -include( ExternalProject ) - -add_definitions(-DLV_CONF_INCLUDE_SIMPLE) - -SET (LVGL_SOURCES - ${LVGL_SOURCE_DIR}/lv_core/lv_group.c - ${LVGL_SOURCE_DIR}/lv_core/lv_indev.c - ${LVGL_SOURCE_DIR}/lv_core/lv_lang.c - ${LVGL_SOURCE_DIR}/lv_core/lv_obj.c - ${LVGL_SOURCE_DIR}/lv_core/lv_refr.c - ${LVGL_SOURCE_DIR}/lv_core/lv_style.c - ${LVGL_SOURCE_DIR}/lv_core/lv_vdb.c - - ${LVGL_SOURCE_DIR}/lv_draw/lv_draw.c - ${LVGL_SOURCE_DIR}/lv_draw/lv_draw_arc.c - ${LVGL_SOURCE_DIR}/lv_draw/lv_draw_img.c - ${LVGL_SOURCE_DIR}/lv_draw/lv_draw_label.c - ${LVGL_SOURCE_DIR}/lv_draw/lv_draw_line.c - ${LVGL_SOURCE_DIR}/lv_draw/lv_draw_rbasic.c - ${LVGL_SOURCE_DIR}/lv_draw/lv_draw_rect.c - ${LVGL_SOURCE_DIR}/lv_draw/lv_draw_triangle.c - ${LVGL_SOURCE_DIR}/lv_draw/lv_draw_vbasic.c - - ${LVGL_SOURCE_DIR}/lv_hal/lv_hal_disp.c - ${LVGL_SOURCE_DIR}/lv_hal/lv_hal_indev.c - ${LVGL_SOURCE_DIR}/lv_hal/lv_hal_tick.c - - ${LVGL_SOURCE_DIR}/lv_misc/lv_anim.c - ${LVGL_SOURCE_DIR}/lv_misc/lv_area.c - ${LVGL_SOURCE_DIR}/lv_misc/lv_circ.c - ${LVGL_SOURCE_DIR}/lv_misc/lv_color.c - ${LVGL_SOURCE_DIR}/lv_misc/lv_font.c - ${LVGL_SOURCE_DIR}/lv_misc/lv_fs.c - ${LVGL_SOURCE_DIR}/lv_misc/lv_gc.c - ${LVGL_SOURCE_DIR}/lv_misc/lv_ll.c - ${LVGL_SOURCE_DIR}/lv_misc/lv_log.c - ${LVGL_SOURCE_DIR}/lv_misc/lv_math.c - ${LVGL_SOURCE_DIR}/lv_misc/lv_mem.c - ${LVGL_SOURCE_DIR}/lv_misc/lv_task.c - ${LVGL_SOURCE_DIR}/lv_misc/lv_templ.c - ${LVGL_SOURCE_DIR}/lv_misc/lv_txt.c - - ${LVGL_SOURCE_DIR}/lv_objx/lv_arc.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_bar.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_btn.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_btnm.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_calendar.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_canvas.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_cb.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_chart.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_cont.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_ddlist.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_gauge.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_img.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_imgbtn.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_kb.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_label.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_led.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_line.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_list.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_lmeter.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_mbox.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_objx_templ.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_page.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_preload.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_roller.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_slider.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_spinbox.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_sw.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_ta.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_table.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_tabview.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_tileview.c - ${LVGL_SOURCE_DIR}/lv_objx/lv_win.c - - ${LVGL_SOURCE_DIR}/lv_themes/lv_theme.c - ${LVGL_SOURCE_DIR}/lv_themes/lv_theme_alien.c - ${LVGL_SOURCE_DIR}/lv_themes/lv_theme_default.c - ${LVGL_SOURCE_DIR}/lv_themes/lv_theme_material.c - ${LVGL_SOURCE_DIR}/lv_themes/lv_theme_mono.c - ${LVGL_SOURCE_DIR}/lv_themes/lv_theme_nemo.c - ${LVGL_SOURCE_DIR}/lv_themes/lv_theme_night.c - ${LVGL_SOURCE_DIR}/lv_themes/lv_theme_templ.c - ${LVGL_SOURCE_DIR}/lv_themes/lv_theme_zen.c - - ${LVGL_SOURCE_DIR}/lv_fonts/lv_font_builtin.c - ${LVGL_SOURCE_DIR}/lv_fonts/lv_font_dejavu_20.c - ${LVGL_DRIVER_DIR}/linux_display_indev.c - ${LVGL_DRIVER_DIR}/indev/mouse.c - -) -SET(SOURCES - ${LVGL_SOURCES} - ${CMAKE_CURRENT_LIST_DIR}/main.c - ) -include_directories( - ${LVGL_DRIVER_DIR} - ${LVGL_DRIVER_DIR}/display - ${LVGL_DRIVER_DIR}/indev - ${LVGL_SOURCE_DIR} - ${LVGL_SOURCE_DIR}/.. - ${CMAKE_CURRENT_BINARY_DIR} - ${CMAKE_CURRENT_LIST_DIR} - ${CMAKE_CURRENT_LIST_DIR}/../lv_config -) -add_executable(vgl_native_ui_app ${SOURCES} ) -target_link_libraries( vgl_native_ui_app -lSDL2) diff --git a/samples/littlevgl/vgl-native-ui-app/CMakeLists.txt.in b/samples/littlevgl/vgl-native-ui-app/CMakeLists.txt.in deleted file mode 100644 index 25f4db955..000000000 --- a/samples/littlevgl/vgl-native-ui-app/CMakeLists.txt.in +++ /dev/null @@ -1,18 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -cmake_minimum_required(VERSION 2.8.2) - -project(lvgl_download NONE) - -include(ExternalProject) -ExternalProject_Add(${lv_name} - GIT_REPOSITORY https://github.com/lvgl/lvgl.git - GIT_TAG v5.3 - BINARY_DIR "" - SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/../build/lvgl" - CONFIGURE_COMMAND "" - BUILD_COMMAND "" - INSTALL_COMMAND "" - TEST_COMMAND "" - ) diff --git a/samples/littlevgl/vgl-native-ui-app/lv-drivers/.gitignore b/samples/littlevgl/vgl-native-ui-app/lv-drivers/.gitignore deleted file mode 100644 index 2372cca06..000000000 --- a/samples/littlevgl/vgl-native-ui-app/lv-drivers/.gitignore +++ /dev/null @@ -1 +0,0 @@ -**/*.o \ No newline at end of file diff --git a/samples/littlevgl/vgl-native-ui-app/lv-drivers/display_indev.h b/samples/littlevgl/vgl-native-ui-app/lv-drivers/display_indev.h deleted file mode 100644 index 95136e285..000000000 --- a/samples/littlevgl/vgl-native-ui-app/lv-drivers/display_indev.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef DISPLAY_INDEV_H_ -#define DISPLAY_INDEV_H_ -#include -#include -#include "mouse.h" -#include "lvgl/lv_misc/lv_color.h" -#include "lvgl/lv_hal/lv_hal_indev.h" -extern void -display_init(void); -extern void -display_flush(int32_t x1, int32_t y1, int32_t x2, int32_t y2, - const lv_color_t *color_p); -extern bool -display_input_read(lv_indev_data_t *data); -extern void -display_deinit(void); -extern void -display_vdb_write(void *buf, lv_coord_t buf_w, lv_coord_t x, lv_coord_t y, - lv_color_t *color, lv_opa_t opa); -extern int -time_get_ms(); - -#endif diff --git a/samples/littlevgl/vgl-native-ui-app/lv-drivers/indev/mouse.c b/samples/littlevgl/vgl-native-ui-app/lv-drivers/indev/mouse.c deleted file mode 100644 index 848b2eca2..000000000 --- a/samples/littlevgl/vgl-native-ui-app/lv-drivers/indev/mouse.c +++ /dev/null @@ -1,96 +0,0 @@ -/** - * @file mouse.c - * - */ - -/********************* - * INCLUDES - *********************/ -#include "mouse.h" -#if USE_MOUSE != 0 - -/********************* - * DEFINES - *********************/ -#ifndef MONITOR_ZOOM -#define MONITOR_ZOOM 1 -#endif - -/********************** - * TYPEDEFS - **********************/ - -/********************** - * STATIC PROTOTYPES - **********************/ - -/********************** - * STATIC VARIABLES - **********************/ -static bool left_button_down = false; -static int16_t last_x = 0; -static int16_t last_y = 0; - -/********************** - * MACROS - **********************/ - -/********************** - * GLOBAL FUNCTIONS - **********************/ - -/** - * Initialize the mouse - */ -void -mouse_init(void) -{} - -/** - * Get the current position and state of the mouse - * @param data store the mouse data here - * @return false: because the points are not buffered, so no more data to be - * read - */ -bool -mouse_read(lv_indev_data_t *data) -{ - /*Store the collected data*/ - data->point.x = last_x; - data->point.y = last_y; - data->state = left_button_down ? LV_INDEV_STATE_PR : LV_INDEV_STATE_REL; - - return false; -} - -/** - * It will be called from the main SDL thread - */ -void -mouse_handler(SDL_Event *event) -{ - switch (event->type) { - case SDL_MOUSEBUTTONUP: - if (event->button.button == SDL_BUTTON_LEFT) - left_button_down = false; - break; - case SDL_MOUSEBUTTONDOWN: - if (event->button.button == SDL_BUTTON_LEFT) { - left_button_down = true; - last_x = event->motion.x / MONITOR_ZOOM; - last_y = event->motion.y / MONITOR_ZOOM; - } - break; - case SDL_MOUSEMOTION: - last_x = event->motion.x / MONITOR_ZOOM; - last_y = event->motion.y / MONITOR_ZOOM; - - break; - } -} - -/********************** - * STATIC FUNCTIONS - **********************/ - -#endif diff --git a/samples/littlevgl/vgl-native-ui-app/lv-drivers/indev/mouse.h b/samples/littlevgl/vgl-native-ui-app/lv-drivers/indev/mouse.h deleted file mode 100644 index 07e492f96..000000000 --- a/samples/littlevgl/vgl-native-ui-app/lv-drivers/indev/mouse.h +++ /dev/null @@ -1,73 +0,0 @@ -/** - * @file mouse.h - * - */ - -#ifndef MOUSE_H -#define MOUSE_H - -#ifdef __cplusplus -extern "C" { -#endif - -/********************* - * INCLUDES - *********************/ - -#include "lv_drv_conf.h" - -#if USE_MOUSE - -#include -#include -#include "lvgl/lv_hal/lv_hal_indev.h" - -#ifndef MONITOR_SDL_INCLUDE_PATH -#define MONITOR_SDL_INCLUDE_PATH -#endif - -#include MONITOR_SDL_INCLUDE_PATH - -/********************* - * DEFINES - *********************/ - -/********************** - * TYPEDEFS - **********************/ - -/********************** - * GLOBAL PROTOTYPES - **********************/ - -/** - * Initialize the mouse - */ -void -mouse_init(void); -/** - * Get the current position and state of the mouse - * @param data store the mouse data here - * @return false: because the points are not buffered, so no more data to be - * read - */ -bool -mouse_read(lv_indev_data_t *data); - -/** - * It will be called from the main SDL thread - */ -void -mouse_handler(SDL_Event *event); - -/********************** - * MACROS - **********************/ - -#endif /* USE_MOUSE */ - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* MOUSE_H */ diff --git a/samples/littlevgl/vgl-native-ui-app/lv-drivers/linux_display_indev.c b/samples/littlevgl/vgl-native-ui-app/lv-drivers/linux_display_indev.c deleted file mode 100644 index bd5071067..000000000 --- a/samples/littlevgl/vgl-native-ui-app/lv-drivers/linux_display_indev.c +++ /dev/null @@ -1,319 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include -#include -#include "display_indev.h" -#include "sys/time.h" -#include "SDL2/SDL.h" -#define MONITOR_HOR_RES 320 -#define MONITOR_VER_RES 240 -#ifndef MONITOR_ZOOM -#define MONITOR_ZOOM 1 -#endif -#define SDL_REFR_PERIOD 50 -void -monitor_sdl_init(void); -void -monitor_sdl_refr_core(void); -void -monitor_sdl_clean_up(void); -static uint32_t tft_fb[MONITOR_HOR_RES * MONITOR_VER_RES]; - -void -display_vdb_write(void *buf, lv_coord_t buf_w, lv_coord_t x, lv_coord_t y, - lv_color_t *color, lv_opa_t opa) -{ - unsigned char *buf_xy = buf + 4 * x + 4 * y * buf_w; - lv_color_t *temp = (lv_color_t *)buf_xy; - *temp = *color; - /* - if (opa != LV_OPA_COVER) { - lv_color_t mix_color; - - mix_color.red = *buf_xy; - mix_color.green = *(buf_xy+1); - mix_color.blue = *(buf_xy+2); - color = lv_color_mix(color, mix_color, opa); - } - */ -} -int -time_get_ms() -{ - static struct timeval tv; - gettimeofday(&tv, NULL); - long long time_in_mill = (tv.tv_sec) * 1000 + (tv.tv_usec) / 1000; - - return (int)time_in_mill; -} - -SDL_Window *window; -SDL_Renderer *renderer; -SDL_Texture *texture; -static volatile bool sdl_inited = false; -static volatile bool sdl_refr_qry = false; -static volatile bool sdl_quit_qry = false; - -void -monitor_flush(int32_t x1, int32_t y1, int32_t x2, int32_t y2, - const lv_color_t *color_p) -{ - /*Return if the area is out the screen*/ - if (x2 < 0 || y2 < 0 || x1 > MONITOR_HOR_RES - 1 - || y1 > MONITOR_VER_RES - 1) { - return; - } - - int32_t y; - uint32_t w = x2 - x1 + 1; - for (y = y1; y <= y2; y++) { - memcpy(&tft_fb[y * MONITOR_HOR_RES + x1], color_p, - w * sizeof(lv_color_t)); - - color_p += w; - } - sdl_refr_qry = true; - - /*IMPORTANT! It must be called to tell the system the flush is ready*/ -} - -/** - * Fill out the marked area with a color - * @param x1 left coordinate - * @param y1 top coordinate - * @param x2 right coordinate - * @param y2 bottom coordinate - * @param color fill color - */ -void -monitor_fill(int32_t x1, int32_t y1, int32_t x2, int32_t y2, lv_color_t color) -{ - /*Return if the area is out the screen*/ - if (x2 < 0) - return; - if (y2 < 0) - return; - if (x1 > MONITOR_HOR_RES - 1) - return; - if (y1 > MONITOR_VER_RES - 1) - return; - - /*Truncate the area to the screen*/ - int32_t act_x1 = x1 < 0 ? 0 : x1; - int32_t act_y1 = y1 < 0 ? 0 : y1; - int32_t act_x2 = x2 > MONITOR_HOR_RES - 1 ? MONITOR_HOR_RES - 1 : x2; - int32_t act_y2 = y2 > MONITOR_VER_RES - 1 ? MONITOR_VER_RES - 1 : y2; - - int32_t x; - int32_t y; - uint32_t color32 = color.full; // lv_color_to32(color); - - for (x = act_x1; x <= act_x2; x++) { - for (y = act_y1; y <= act_y2; y++) { - tft_fb[y * MONITOR_HOR_RES + x] = color32; - } - } - - sdl_refr_qry = true; -} - -/** - * Put a color map to the marked area - * @param x1 left coordinate - * @param y1 top coordinate - * @param x2 right coordinate - * @param y2 bottom coordinate - * @param color_p an array of colors - */ -void -monitor_map(int32_t x1, int32_t y1, int32_t x2, int32_t y2, - const lv_color_t *color_p) -{ - /*Return if the area is out the screen*/ - if (x2 < 0) - return; - if (y2 < 0) - return; - if (x1 > MONITOR_HOR_RES - 1) - return; - if (y1 > MONITOR_VER_RES - 1) - return; - - /*Truncate the area to the screen*/ - int32_t act_x1 = x1 < 0 ? 0 : x1; - int32_t act_y1 = y1 < 0 ? 0 : y1; - int32_t act_x2 = x2 > MONITOR_HOR_RES - 1 ? MONITOR_HOR_RES - 1 : x2; - int32_t act_y2 = y2 > MONITOR_VER_RES - 1 ? MONITOR_VER_RES - 1 : y2; - - int32_t x; - int32_t y; - - for (y = act_y1; y <= act_y2; y++) { - for (x = act_x1; x <= act_x2; x++) { - tft_fb[y * MONITOR_HOR_RES + x] = - color_p->full; // lv_color_to32(*color_p); - color_p++; - } - - color_p += x2 - act_x2; - } - - sdl_refr_qry = true; -} - -void -display_init(void) -{} - -void -display_flush(int32_t x1, int32_t y1, int32_t x2, int32_t y2, - const lv_color_t *color_p) -{ - monitor_flush(x1, y1, x2, y2, color_p); -} -void -display_fill(int32_t x1, int32_t y1, int32_t x2, int32_t y2, lv_color_t color_p) -{ - monitor_fill(x1, y1, x2, y2, color_p); -} -void -display_map(int32_t x1, int32_t y1, int32_t x2, int32_t y2, - const lv_color_t *color_p) -{ - monitor_map(x1, y1, x2, y2, color_p); -} - -bool -display_input_read(lv_indev_data_t *data) -{ - return mouse_read(data); -} - -void -display_deinit(void) -{} - -int -monitor_sdl_refr_thread(void *param) -{ - (void)param; - - /*If not OSX initialize SDL in the Thread*/ - monitor_sdl_init(); - /*Run until quit event not arrives*/ - while (sdl_quit_qry == false) { - /*Refresh handling*/ - monitor_sdl_refr_core(); - } - - monitor_sdl_clean_up(); - exit(0); - - return 0; -} - -void -monitor_sdl_refr_core(void) -{ - if (sdl_refr_qry != false) { - sdl_refr_qry = false; - - SDL_UpdateTexture(texture, NULL, tft_fb, - MONITOR_HOR_RES * sizeof(uint32_t)); - SDL_RenderClear(renderer); - /*Test: Draw a background to test transparent screens - * (LV_COLOR_SCREEN_TRANSP)*/ - // SDL_SetRenderDrawColor(renderer, 0xff, 0, 0, 0xff); - // SDL_Rect r; - // r.x = 0; r.y = 0; r.w = MONITOR_HOR_RES; r.w = - // MONITOR_VER_RES; SDL_RenderDrawRect(renderer, &r); - /*Update the renderer with the texture containing the rendered image*/ - SDL_RenderCopy(renderer, texture, NULL, NULL); - SDL_RenderPresent(renderer); - } - - SDL_Event event; - while (SDL_PollEvent(&event)) { -#if USE_MOUSE != 0 - mouse_handler(&event); -#endif - if ((&event)->type == SDL_WINDOWEVENT) { - switch ((&event)->window.event) { -#if SDL_VERSION_ATLEAST(2, 0, 5) - case SDL_WINDOWEVENT_TAKE_FOCUS: -#endif - case SDL_WINDOWEVENT_EXPOSED: - - SDL_UpdateTexture(texture, NULL, tft_fb, - MONITOR_HOR_RES * sizeof(uint32_t)); - SDL_RenderClear(renderer); - SDL_RenderCopy(renderer, texture, NULL, NULL); - SDL_RenderPresent(renderer); - break; - default: - break; - } - } - } - - /*Sleep some time*/ - SDL_Delay(SDL_REFR_PERIOD); -} -int -quit_filter(void *userdata, SDL_Event *event) -{ - (void)userdata; - - if (event->type == SDL_QUIT) { - sdl_quit_qry = true; - } - - return 1; -} - -void -monitor_sdl_clean_up(void) -{ - SDL_DestroyTexture(texture); - SDL_DestroyRenderer(renderer); - SDL_DestroyWindow(window); - SDL_Quit(); -} - -void -monitor_sdl_init(void) -{ - /*Initialize the SDL*/ - SDL_Init(SDL_INIT_VIDEO); - - SDL_SetEventFilter(quit_filter, NULL); - - window = SDL_CreateWindow( - "TFT Simulator", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, - MONITOR_HOR_RES * MONITOR_ZOOM, MONITOR_VER_RES * MONITOR_ZOOM, - 0); /*last param. SDL_WINDOW_BORDERLESS to hide borders*/ - - renderer = SDL_CreateRenderer(window, -1, 0); - texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, - SDL_TEXTUREACCESS_STATIC, MONITOR_HOR_RES, - MONITOR_VER_RES); - SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND); - - /*Initialize the frame buffer to gray (77 is an empirical value) */ - memset(tft_fb, 0x44, MONITOR_HOR_RES * MONITOR_VER_RES * sizeof(uint32_t)); - SDL_UpdateTexture(texture, NULL, tft_fb, - MONITOR_HOR_RES * sizeof(uint32_t)); - sdl_refr_qry = true; - sdl_inited = true; -} - -void -display_SDL_init() -{ - SDL_CreateThread(monitor_sdl_refr_thread, "sdl_refr", NULL); - while (sdl_inited == false) - ; /*Wait until 'sdl_refr' initializes the SDL*/ -} diff --git a/samples/littlevgl/vgl-native-ui-app/lv-drivers/system_header.h b/samples/littlevgl/vgl-native-ui-app/lv-drivers/system_header.h deleted file mode 100644 index a0d790c8e..000000000 --- a/samples/littlevgl/vgl-native-ui-app/lv-drivers/system_header.h +++ /dev/null @@ -1,9 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include - -int -time_get_ms(); diff --git a/samples/littlevgl/vgl-native-ui-app/main.c b/samples/littlevgl/vgl-native-ui-app/main.c deleted file mode 100644 index e67847c6c..000000000 --- a/samples/littlevgl/vgl-native-ui-app/main.c +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -/** - * @file main - * - */ - -/********************* - * INCLUDES - *********************/ -#include -#include -#include "lvgl/lvgl.h" -#include "display_indev.h" -#include - -/********************* - * DEFINES - *********************/ - -/********************** - * TYPEDEFS - **********************/ - -/********************** - * STATIC PROTOTYPES - **********************/ -static void -hal_init(void); -// static int tick_thread(void * data); -// static void memory_monitor(void * param); - -/********************** - * STATIC VARIABLES - **********************/ - -/********************** - * MACROS - **********************/ - -/********************** - * GLOBAL FUNCTIONS - **********************/ -uint32_t count = 0; -char count_str[11] = { 0 }; -lv_obj_t *hello_world_label; -lv_obj_t *count_label; -lv_obj_t *btn1; - -lv_obj_t *label_count1; -int label_count1_value = 0; -char label_count1_str[11] = { 0 }; -static lv_res_t -btn_rel_action(lv_obj_t *btn) -{ - label_count1_value++; - snprintf(label_count1_str, sizeof(label_count1_str), "%d", - label_count1_value); - lv_label_set_text(label_count1, label_count1_str); - return LV_RES_OK; -} - -int -main() -{ - void display_SDL_init(); - display_SDL_init(); - - /*Initialize LittlevGL*/ - lv_init(); - - /*Initialize the HAL (display, input devices, tick) for LittlevGL*/ - hal_init(); - - hello_world_label = lv_label_create(lv_scr_act(), NULL); - lv_label_set_text(hello_world_label, "Hello world!"); - lv_obj_align(hello_world_label, NULL, LV_ALIGN_IN_TOP_LEFT, 0, 0); - - count_label = lv_label_create(lv_scr_act(), NULL); - lv_obj_align(count_label, NULL, LV_ALIGN_IN_TOP_MID, 0, 0); - - btn1 = lv_btn_create( - lv_scr_act(), NULL); /*Create a button on the currently loaded screen*/ - lv_btn_set_action(btn1, LV_BTN_ACTION_CLICK, - btn_rel_action); /*Set function to be called when the - button is released*/ - lv_obj_align(btn1, NULL, LV_ALIGN_CENTER, 0, 20); /*Align below the label*/ - - /*Create a label on the button*/ - lv_obj_t *btn_label = lv_label_create(btn1, NULL); - lv_label_set_text(btn_label, "Click ++"); - - label_count1 = lv_label_create(lv_scr_act(), NULL); - lv_label_set_text(label_count1, "0"); - lv_obj_align(label_count1, NULL, LV_ALIGN_IN_BOTTOM_MID, 0, 0); - - while (1) { - /* Periodically call the lv_task handler. - * It could be done in a timer interrupt or an OS task too.*/ - if ((count % 100) == 0) { - snprintf(count_str, sizeof(count_str), "%d", count / 100); - lv_label_set_text(count_label, count_str); - } - lv_task_handler(); - ++count; - usleep(10 * 1000); /*Just to let the system breath*/ - } - - return 0; -} - -/********************** - * STATIC FUNCTIONS - **********************/ - -/** - * Initialize the Hardware Abstraction Layer (HAL) for the Littlev graphics - * library - */ -void -display_flush_wrapper(int32_t x1, int32_t y1, int32_t x2, int32_t y2, - const lv_color_t *color_p) -{ - display_flush(x1, y1, x2, y2, color_p); - lv_flush_ready(); -} -void -display_vdb_write_wrapper(uint8_t *buf, lv_coord_t buf_w, lv_coord_t x, - lv_coord_t y, lv_color_t color, lv_opa_t opa) -{ - display_vdb_write(buf, buf_w, x, y, &color, opa); -} -extern void -display_fill(int32_t x1, int32_t y1, int32_t x2, int32_t y2, - lv_color_t color_p); -extern void -display_map(int32_t x1, int32_t y1, int32_t x2, int32_t y2, - const lv_color_t *color_p); -static void -hal_init(void) -{ - /* Add a display*/ - lv_disp_drv_t disp_drv; - lv_disp_drv_init(&disp_drv); /*Basic initialization*/ - disp_drv.disp_flush = - display_flush_wrapper; /*Used when `LV_VDB_SIZE != 0` in lv_conf.h - (buffered drawing)*/ - disp_drv.disp_fill = display_fill; /*Used when `LV_VDB_SIZE == 0` in - lv_conf.h (unbuffered drawing)*/ - disp_drv.disp_map = display_map; /*Used when `LV_VDB_SIZE == 0` in lv_conf.h - (unbuffered drawing)*/ -#if LV_VDB_SIZE != 0 - disp_drv.vdb_wr = display_vdb_write_wrapper; -#endif - lv_disp_drv_register(&disp_drv); - - /* Add the mouse as input device - * Use the 'mouse' driver which reads the PC's mouse*/ - // mouse_init(); - lv_indev_drv_t indev_drv; - lv_indev_drv_init(&indev_drv); /*Basic initialization*/ - indev_drv.type = LV_INDEV_TYPE_POINTER; - indev_drv.read = - display_input_read; /*This function will be called periodically (by the - library) to get the mouse position and state*/ - lv_indev_t *mouse_indev = lv_indev_drv_register(&indev_drv); -} diff --git a/samples/littlevgl/vgl-wasm-runtime/CMakeLists.txt b/samples/littlevgl/vgl-wasm-runtime/CMakeLists.txt deleted file mode 100644 index a99959ad5..000000000 --- a/samples/littlevgl/vgl-wasm-runtime/CMakeLists.txt +++ /dev/null @@ -1,36 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -cmake_minimum_required (VERSION 2.9) - -project (vgl_wasm_runtime) - -set (WAMR_BUILD_PLATFORM "linux") - -# Reset default linker flags -set (CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "") -set (CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS "") - -################ wamr runtime settings ################ - -set (WAMR_ROOT_DIR ${CMAKE_CURRENT_LIST_DIR}/../../..) - -## use library and headers in the SDK -link_directories(${WAMR_ROOT_DIR}/wamr-sdk/out/littlevgl/runtime-sdk/lib) -include_directories( - ${WAMR_ROOT_DIR}/wamr-sdk/out/littlevgl/runtime-sdk/include - ${WAMR_ROOT_DIR}/wamr-sdk/out/littlevgl/runtime-sdk/include/bi-inc/deps - ${WAMR_ROOT_DIR}/core/shared/utils - ${WAMR_ROOT_DIR}/core/shared/platform/${WAMR_BUILD_PLATFORM} -) - -############### application related ############### -include_directories(${CMAKE_CURRENT_LIST_DIR}/src) - -add_executable (vgl_wasm_runtime src/platform/${WAMR_BUILD_PLATFORM}/main.c - src/platform/${WAMR_BUILD_PLATFORM}/iwasm_main.c - src/platform/${WAMR_BUILD_PLATFORM}/display_indev.c - src/platform/${WAMR_BUILD_PLATFORM}/mouse.c) - -target_link_libraries (vgl_wasm_runtime vmlib -lm -ldl -lpthread -lSDL2) - diff --git a/samples/littlevgl/vgl-wasm-runtime/src/display_indev.h b/samples/littlevgl/vgl-wasm-runtime/src/display_indev.h deleted file mode 100644 index 273d0ad03..000000000 --- a/samples/littlevgl/vgl-wasm-runtime/src/display_indev.h +++ /dev/null @@ -1,96 +0,0 @@ -#ifndef DISPLAY_INDEV_H_ -#define DISPLAY_INDEV_H_ -#include -#include -#include -#include "bh_platform.h" -#include "wasm_export.h" - -#define USE_MOUSE 1 -typedef union { - struct { - uint8_t blue; - uint8_t green; - uint8_t red; - uint8_t alpha; - }; - uint32_t full; -} lv_color32_t; - -typedef lv_color32_t lv_color_t; -typedef uint8_t lv_indev_state_t; -typedef int16_t lv_coord_t; -typedef uint8_t lv_opa_t; -typedef struct { - lv_coord_t x; - lv_coord_t y; -} lv_point_t; - -typedef struct { - union { - lv_point_t - point; /*For LV_INDEV_TYPE_POINTER the currently pressed point*/ - uint32_t key; /*For LV_INDEV_TYPE_KEYPAD the currently pressed key*/ - uint32_t btn; /*For LV_INDEV_TYPE_BUTTON the currently pressed button*/ - int16_t enc_diff; /*For LV_INDEV_TYPE_ENCODER number of steps since the - previous read*/ - }; - void *user_data; /*'lv_indev_drv_t.priv' for this driver*/ - lv_indev_state_t state; /*LV_INDEV_STATE_REL or LV_INDEV_STATE_PR*/ -} lv_indev_data_t; - -enum { LV_INDEV_STATE_REL = 0, LV_INDEV_STATE_PR }; -enum { - LV_OPA_TRANSP = 0, - LV_OPA_0 = 0, - LV_OPA_10 = 25, - LV_OPA_20 = 51, - LV_OPA_30 = 76, - LV_OPA_40 = 102, - LV_OPA_50 = 127, - LV_OPA_60 = 153, - LV_OPA_70 = 178, - LV_OPA_80 = 204, - LV_OPA_90 = 229, - LV_OPA_100 = 255, - LV_OPA_COVER = 255, -}; - -extern void -xpt2046_init(void); - -extern bool -touchscreen_read(lv_indev_data_t *data); - -extern bool -mouse_read(lv_indev_data_t *data); - -extern void -display_init(void); - -extern void -display_deinit(wasm_exec_env_t exec_env); - -extern int -time_get_ms(wasm_exec_env_t exec_env); - -extern void -display_flush(wasm_exec_env_t exec_env, int32_t x1, int32_t y1, int32_t x2, - int32_t y2, lv_color_t *color); - -extern void -display_fill(wasm_exec_env_t exec_env, int32_t x1, int32_t y1, int32_t x2, - int32_t y2, lv_color_t *color); - -extern void -display_map(wasm_exec_env_t exec_env, int32_t x1, int32_t y1, int32_t x2, - int32_t y2, const lv_color_t *color); - -extern bool -display_input_read(wasm_exec_env_t exec_env, void *data); - -void -display_vdb_write(wasm_exec_env_t exec_env, void *buf, lv_coord_t buf_w, - lv_coord_t x, lv_coord_t y, lv_color_t *color, lv_opa_t opa); - -#endif diff --git a/samples/littlevgl/vgl-wasm-runtime/src/platform/linux/display_indev.c b/samples/littlevgl/vgl-wasm-runtime/src/platform/linux/display_indev.c deleted file mode 100644 index 2b3b00067..000000000 --- a/samples/littlevgl/vgl-wasm-runtime/src/platform/linux/display_indev.c +++ /dev/null @@ -1,347 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include -#include -#include "display_indev.h" -#include "SDL2/SDL.h" -#include "sys/time.h" -#include "wasm_export.h" -#include "app_manager_export.h" - -#define MONITOR_HOR_RES 320 -#define MONITOR_VER_RES 240 -#ifndef MONITOR_ZOOM -#define MONITOR_ZOOM 1 -#endif -#define SDL_REFR_PERIOD 50 -void -monitor_sdl_init(void); -void -monitor_sdl_refr_core(void); -void -monitor_sdl_clean_up(void); - -static uint32_t tft_fb[MONITOR_HOR_RES * MONITOR_VER_RES]; - -int -time_get_ms(wasm_exec_env_t exec_env) -{ - static struct timeval tv; - gettimeofday(&tv, NULL); - long long time_in_mill = (tv.tv_sec) * 1000 + (tv.tv_usec) / 1000; - - return (int)time_in_mill; -} - -SDL_Window *window; -SDL_Renderer *renderer; -SDL_Texture *texture; -static volatile bool sdl_inited = false; -static volatile bool sdl_refr_qry = false; -static volatile bool sdl_quit_qry = false; - -void -monitor_flush(int32_t x1, int32_t y1, int32_t x2, int32_t y2, - const lv_color_t *color) -{ - /*Return if the area is out the screen*/ - if (x2 < 0 || y2 < 0 || x1 > MONITOR_HOR_RES - 1 - || y1 > MONITOR_VER_RES - 1) { - return; - } - - int32_t y; - uint32_t w = x2 - x1 + 1; - - for (y = y1; y <= y2; y++) { - memcpy(&tft_fb[y * MONITOR_HOR_RES + x1], color, - w * sizeof(lv_color_t)); - - color += w; - } - sdl_refr_qry = true; - - /*IMPORTANT! It must be called to tell the system the flush is ready*/ -} - -/** - * Fill out the marked area with a color - * @param x1 left coordinate - * @param y1 top coordinate - * @param x2 right coordinate - * @param y2 bottom coordinate - * @param color fill color - */ -void -monitor_fill(int32_t x1, int32_t y1, int32_t x2, int32_t y2, lv_color_t *color) -{ - /*Return if the area is out the screen*/ - if (x2 < 0) - return; - if (y2 < 0) - return; - if (x1 > MONITOR_HOR_RES - 1) - return; - if (y1 > MONITOR_VER_RES - 1) - return; - - /*Truncate the area to the screen*/ - int32_t act_x1 = x1 < 0 ? 0 : x1; - int32_t act_y1 = y1 < 0 ? 0 : y1; - int32_t act_x2 = x2 > MONITOR_HOR_RES - 1 ? MONITOR_HOR_RES - 1 : x2; - int32_t act_y2 = y2 > MONITOR_VER_RES - 1 ? MONITOR_VER_RES - 1 : y2; - - int32_t x; - int32_t y; - uint32_t color32 = color->full; // lv_color_to32(color); - - for (x = act_x1; x <= act_x2; x++) { - for (y = act_y1; y <= act_y2; y++) { - tft_fb[y * MONITOR_HOR_RES + x] = color32; - } - } - - sdl_refr_qry = true; -} - -/** - * Put a color map to the marked area - * @param x1 left coordinate - * @param y1 top coordinate - * @param x2 right coordinate - * @param y2 bottom coordinate - * @param color an array of colors - */ -void -monitor_map(int32_t x1, int32_t y1, int32_t x2, int32_t y2, - const lv_color_t *color) -{ - /*Return if the area is out the screen*/ - if (x2 < 0) - return; - if (y2 < 0) - return; - if (x1 > MONITOR_HOR_RES - 1) - return; - if (y1 > MONITOR_VER_RES - 1) - return; - - /*Truncate the area to the screen*/ - int32_t act_x1 = x1 < 0 ? 0 : x1; - int32_t act_y1 = y1 < 0 ? 0 : y1; - int32_t act_x2 = x2 > MONITOR_HOR_RES - 1 ? MONITOR_HOR_RES - 1 : x2; - int32_t act_y2 = y2 > MONITOR_VER_RES - 1 ? MONITOR_VER_RES - 1 : y2; - - int32_t x; - int32_t y; - - for (y = act_y1; y <= act_y2; y++) { - for (x = act_x1; x <= act_x2; x++) { - tft_fb[y * MONITOR_HOR_RES + x] = - color->full; // lv_color_to32(*color); - color++; - } - - color += x2 - act_x2; - } - - sdl_refr_qry = true; -} - -void -display_init(void) -{} - -void -display_flush(wasm_exec_env_t exec_env, int32_t x1, int32_t y1, int32_t x2, - int32_t y2, lv_color_t *color) -{ - wasm_module_inst_t module_inst = get_module_inst(exec_env); - - if (!wasm_runtime_validate_native_addr(module_inst, color, - sizeof(lv_color_t))) - return; - - monitor_flush(x1, y1, x2, y2, color); -} - -void -display_fill(wasm_exec_env_t exec_env, int32_t x1, int32_t y1, int32_t x2, - int32_t y2, lv_color_t *color) -{ - monitor_fill(x1, y1, x2, y2, color); -} - -void -display_map(wasm_exec_env_t exec_env, int32_t x1, int32_t y1, int32_t x2, - int32_t y2, const lv_color_t *color) -{ - monitor_map(x1, y1, x2, y2, color); -} - -typedef struct display_input_data { - lv_point_t point; - uint32 user_data_offset; - uint8 state; -} display_input_data; - -bool -display_input_read(wasm_exec_env_t exec_env, void *input_data_app) -{ - wasm_module_inst_t module_inst = get_module_inst(exec_env); - display_input_data *data_app = (display_input_data *)input_data_app; - bool ret; - - if (!wasm_runtime_validate_native_addr(module_inst, data_app, - sizeof(display_input_data))) - return false; - - lv_indev_data_t data = { 0 }; - - ret = mouse_read(&data); - - data_app->point = data.point; - data_app->user_data_offset = - wasm_runtime_addr_native_to_app(module_inst, data.user_data); - data_app->state = data.state; - - return ret; -} - -void -display_deinit(wasm_exec_env_t exec_env) -{} - -void -display_vdb_write(wasm_exec_env_t exec_env, void *buf, lv_coord_t buf_w, - lv_coord_t x, lv_coord_t y, lv_color_t *color, lv_opa_t opa) -{ - wasm_module_inst_t module_inst = get_module_inst(exec_env); - unsigned char *buf_xy = (unsigned char *)buf + 4 * x + 4 * y * buf_w; - - if (!wasm_runtime_validate_native_addr(module_inst, color, - sizeof(lv_color_t))) - return; - - *(lv_color_t *)buf_xy = *color; -} - -int -monitor_sdl_refr_thread(void *param) -{ - (void)param; - - /*If not OSX initialize SDL in the Thread*/ - monitor_sdl_init(); - /*Run until quit event not arrives*/ - while (sdl_quit_qry == false) { - /*Refresh handling*/ - monitor_sdl_refr_core(); - } - - monitor_sdl_clean_up(); - exit(0); - - return 0; -} -extern void -mouse_handler(SDL_Event *event); -void -monitor_sdl_refr_core(void) -{ - if (sdl_refr_qry != false) { - sdl_refr_qry = false; - - SDL_UpdateTexture(texture, NULL, tft_fb, - MONITOR_HOR_RES * sizeof(uint32_t)); - SDL_RenderClear(renderer); - /*Update the renderer with the texture containing the rendered image*/ - SDL_RenderCopy(renderer, texture, NULL, NULL); - SDL_RenderPresent(renderer); - } - - SDL_Event event; - while (SDL_PollEvent(&event)) { - - mouse_handler(&event); - - if ((&event)->type == SDL_WINDOWEVENT) { - switch ((&event)->window.event) { -#if SDL_VERSION_ATLEAST(2, 0, 5) - case SDL_WINDOWEVENT_TAKE_FOCUS: -#endif - case SDL_WINDOWEVENT_EXPOSED: - - SDL_UpdateTexture(texture, NULL, tft_fb, - MONITOR_HOR_RES * sizeof(uint32_t)); - SDL_RenderClear(renderer); - SDL_RenderCopy(renderer, texture, NULL, NULL); - SDL_RenderPresent(renderer); - break; - default: - break; - } - } - } - - /*Sleep some time*/ - SDL_Delay(SDL_REFR_PERIOD); -} -int -quit_filter(void *userdata, SDL_Event *event) -{ - (void)userdata; - - if (event->type == SDL_QUIT) { - sdl_quit_qry = true; - } - - return 1; -} - -void -monitor_sdl_clean_up(void) -{ - SDL_DestroyTexture(texture); - SDL_DestroyRenderer(renderer); - SDL_DestroyWindow(window); - SDL_Quit(); -} - -void -monitor_sdl_init(void) -{ - /*Initialize the SDL*/ - SDL_Init(SDL_INIT_VIDEO); - - SDL_SetEventFilter(quit_filter, NULL); - - window = SDL_CreateWindow( - "TFT Simulator", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, - MONITOR_HOR_RES * MONITOR_ZOOM, MONITOR_VER_RES * MONITOR_ZOOM, - 0); /*last param. SDL_WINDOW_BORDERLESS to hide borders*/ - - renderer = SDL_CreateRenderer(window, -1, 0); - texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, - SDL_TEXTUREACCESS_STATIC, MONITOR_HOR_RES, - MONITOR_VER_RES); - SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND); - - /*Initialize the frame buffer to gray (77 is an empirical value) */ - memset(tft_fb, 0x44, MONITOR_HOR_RES * MONITOR_VER_RES * sizeof(uint32_t)); - SDL_UpdateTexture(texture, NULL, tft_fb, - MONITOR_HOR_RES * sizeof(uint32_t)); - sdl_refr_qry = true; - sdl_inited = true; -} - -void -display_SDL_init() -{ - SDL_CreateThread(monitor_sdl_refr_thread, "sdl_refr", NULL); - while (sdl_inited == false) - ; /*Wait until 'sdl_refr' initializes the SDL*/ -} diff --git a/samples/littlevgl/vgl-wasm-runtime/src/platform/linux/iwasm_main.c b/samples/littlevgl/vgl-wasm-runtime/src/platform/linux/iwasm_main.c deleted file mode 100644 index e2253bb5e..000000000 --- a/samples/littlevgl/vgl-wasm-runtime/src/platform/linux/iwasm_main.c +++ /dev/null @@ -1,544 +0,0 @@ - -#ifndef CONNECTION_UART -#include -#include -#include -#include -#else -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "runtime_lib.h" -#include "runtime_timer.h" -#include "native_interface.h" -#include "app_manager_export.h" -#include "bh_platform.h" -#include "bi-inc/attr_container.h" -#include "module_wasm_app.h" -#include "wasm_export.h" -#include "sensor_native_api.h" -#include "connection_native_api.h" -#include "display_indev.h" - -#define MAX 2048 - -#ifndef CONNECTION_UART -#define SA struct sockaddr -static char *host_address = "127.0.0.1"; -static int port = 8888; -#else -static char *uart_device = "/dev/ttyS2"; -static int baudrate = B115200; -#endif - -extern bool -init_sensor_framework(); -extern void -exit_sensor_framework(); -extern void -exit_connection_framework(); -extern int -aee_host_msg_callback(void *msg, uint32_t msg_len); -extern bool -init_connection_framework(); - -#ifndef CONNECTION_UART -int listenfd = -1; -int sockfd = -1; -static pthread_mutex_t sock_lock = PTHREAD_MUTEX_INITIALIZER; -#else -int uartfd = -1; -#endif - -#ifndef CONNECTION_UART -static bool server_mode = false; - -// Function designed for chat between client and server. -void * -func(void *arg) -{ - char buff[MAX]; - int n; - struct sockaddr_in servaddr; - - while (1) { - if (sockfd != -1) - close(sockfd); - // socket create and verification - sockfd = socket(AF_INET, SOCK_STREAM, 0); - if (sockfd == -1) { - printf("socket creation failed...\n"); - return NULL; - } - else - printf("Socket successfully created..\n"); - bzero(&servaddr, sizeof(servaddr)); - // assign IP, PORT - servaddr.sin_family = AF_INET; - servaddr.sin_addr.s_addr = inet_addr(host_address); - servaddr.sin_port = htons(port); - - // connect the client socket to server socket - if (connect(sockfd, (SA *)&servaddr, sizeof(servaddr)) != 0) { - printf("connection with the server failed...\n"); - sleep(10); - continue; - } - else { - printf("connected to the server..\n"); - } - - // infinite loop for chat - for (;;) { - bzero(buff, MAX); - - // read the message from client and copy it in buffer - n = read(sockfd, buff, sizeof(buff)); - // print buffer which contains the client contents - // fprintf(stderr, "recieved %d bytes from host: %s", n, buff); - - // socket disconnected - if (n <= 0) - break; - - aee_host_msg_callback(buff, n); - } - } - - // After chatting close the socket - close(sockfd); -} - -static bool -host_init() -{ - return true; -} - -int -host_send(void *ctx, const char *buf, int size) -{ - int ret; - - if (pthread_mutex_trylock(&sock_lock) == 0) { - if (sockfd == -1) { - pthread_mutex_unlock(&sock_lock); - return 0; - } - - ret = write(sockfd, buf, size); - - pthread_mutex_unlock(&sock_lock); - return ret; - } - - return -1; -} - -void -host_destroy() -{ - if (server_mode) - close(listenfd); - - pthread_mutex_lock(&sock_lock); - close(sockfd); - pthread_mutex_unlock(&sock_lock); -} - -host_interface interface = { .init = host_init, - .send = host_send, - .destroy = host_destroy }; - -void * -func_server_mode(void *arg) -{ - int clilent; - struct sockaddr_in serv_addr, cli_addr; - int n; - char buff[MAX]; - struct sigaction sa; - - sa.sa_handler = SIG_IGN; - sa.sa_flags = 0; - sigemptyset(&sa.sa_mask); - sigaction(SIGPIPE, &sa, 0); - - /* First call to socket() function */ - listenfd = socket(AF_INET, SOCK_STREAM, 0); - - if (listenfd < 0) { - perror("ERROR opening socket"); - exit(1); - } - - /* Initialize socket structure */ - bzero((char *)&serv_addr, sizeof(serv_addr)); - - serv_addr.sin_family = AF_INET; - serv_addr.sin_addr.s_addr = INADDR_ANY; - serv_addr.sin_port = htons(port); - - /* Now bind the host address using bind() call.*/ - if (bind(listenfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { - perror("ERROR on binding"); - exit(1); - } - - listen(listenfd, 5); - clilent = sizeof(cli_addr); - - while (1) { - pthread_mutex_lock(&sock_lock); - - sockfd = accept(listenfd, (struct sockaddr *)&cli_addr, &clilent); - - pthread_mutex_unlock(&sock_lock); - - if (sockfd < 0) { - perror("ERROR on accept"); - exit(1); - } - - printf("connection established!\n"); - - for (;;) { - bzero(buff, MAX); - - // read the message from client and copy it in buffer - n = read(sockfd, buff, sizeof(buff)); - - // socket disconnected - if (n <= 0) { - pthread_mutex_lock(&sock_lock); - close(sockfd); - sockfd = -1; - pthread_mutex_unlock(&sock_lock); - - sleep(2); - break; - } - - aee_host_msg_callback(buff, n); - } - } -} - -#else -static int -parse_baudrate(int baud) -{ - switch (baud) { - case 9600: - return B9600; - case 19200: - return B19200; - case 38400: - return B38400; - case 57600: - return B57600; - case 115200: - return B115200; - case 230400: - return B230400; - case 460800: - return B460800; - case 500000: - return B500000; - case 576000: - return B576000; - case 921600: - return B921600; - case 1000000: - return B1000000; - case 1152000: - return B1152000; - case 1500000: - return B1500000; - case 2000000: - return B2000000; - case 2500000: - return B2500000; - case 3000000: - return B3000000; - case 3500000: - return B3500000; - case 4000000: - return B4000000; - default: - return -1; - } -} -static bool -uart_init(const char *device, int baudrate, int *fd) -{ - int uart_fd; - struct termios uart_term; - - uart_fd = open(device, O_RDWR | O_NOCTTY); - - if (uart_fd <= 0) - return false; - - memset(&uart_term, 0, sizeof(uart_term)); - uart_term.c_cflag = baudrate | CS8 | CLOCAL | CREAD; - uart_term.c_iflag = IGNPAR; - uart_term.c_oflag = 0; - - /* set noncanonical mode */ - uart_term.c_lflag = 0; - uart_term.c_cc[VTIME] = 30; - uart_term.c_cc[VMIN] = 1; - tcflush(uart_fd, TCIFLUSH); - - if (tcsetattr(uart_fd, TCSANOW, &uart_term) != 0) { - close(uart_fd); - return false; - } - - *fd = uart_fd; - - return true; -} - -static void * -func_uart_mode(void *arg) -{ - int n; - char buff[MAX]; - - if (!uart_init(uart_device, baudrate, &uartfd)) { - printf("open uart fail! %s\n", uart_device); - return NULL; - } - - for (;;) { - bzero(buff, MAX); - - n = read(uartfd, buff, sizeof(buff)); - - if (n <= 0) { - close(uartfd); - uartfd = -1; - break; - } - - aee_host_msg_callback(buff, n); - } - - return NULL; -} - -static int -uart_send(void *ctx, const char *buf, int size) -{ - int ret; - - ret = write(uartfd, buf, size); - - return ret; -} - -static void -uart_destroy() -{ - close(uartfd); -} - -static host_interface interface = { .send = uart_send, - .destroy = uart_destroy }; - -#endif - -#ifdef __x86_64__ -static char global_heap_buf[400 * 1024] = { 0 }; -#else -static char global_heap_buf[270 * 1024] = { 0 }; -#endif - -/* clang-format off */ -static void showUsage() -{ -#ifndef CONNECTION_UART - printf("Usage:\n"); - printf("\nWork as TCP server mode:\n"); - printf("\tvgl_wasm_runtime -s|--server_mode -p|--port \n"); - printf("where\n"); - printf("\t represents the port that would be listened on and the default is 8888\n"); - printf("\nWork as TCP client mode:\n"); - printf("\tvgl_wasm_runtime -a|--host_address -p|--port \n"); - printf("where\n"); - printf("\t represents the network address of host and the default is 127.0.0.1\n"); - printf("\t represents the listen port of host and the default is 8888\n"); -#else - printf("Usage:\n"); - printf("\tvgl_wasm_runtime -u -b \n\n"); - printf("where\n"); - printf("\t represents the UART device name and the default is /dev/ttyS2\n"); - printf("\t represents the UART device baudrate and the default is 115200\n"); -#endif - printf("\nNote:\n"); - printf("\tUse -w|--wasi_root to specify the root dir (default to '.') of WASI wasm modules. \n"); -} -/* clang-format on */ - -static bool -parse_args(int argc, char *argv[]) -{ - int c; - - while (1) { - int optIndex = 0; - static struct option longOpts[] = { -#ifndef CONNECTION_UART - { "server_mode", no_argument, NULL, 's' }, - { "host_address", required_argument, NULL, 'a' }, - { "port", required_argument, NULL, 'p' }, -#else - { "uart", required_argument, NULL, 'u' }, - { "baudrate", required_argument, NULL, 'b' }, -#endif -#if WASM_ENABLE_LIBC_WASI != 0 - { "wasi_root", required_argument, NULL, 'w' }, -#endif - { "help", required_argument, NULL, 'h' }, - { 0, 0, 0, 0 } - }; - - c = getopt_long(argc, argv, "sa:p:u:b:w:h", longOpts, &optIndex); - if (c == -1) - break; - - switch (c) { -#ifndef CONNECTION_UART - case 's': - server_mode = true; - break; - case 'a': - host_address = optarg; - printf("host address: %s\n", host_address); - break; - case 'p': - port = atoi(optarg); - printf("port: %d\n", port); - break; -#else - case 'u': - uart_device = optarg; - printf("uart device: %s\n", uart_device); - break; - case 'b': - baudrate = parse_baudrate(atoi(optarg)); - printf("uart baudrate: %s\n", optarg); - break; -#endif -#if WASM_ENABLE_LIBC_WASI != 0 - case 'w': - if (!wasm_set_wasi_root_dir(optarg)) { - printf("Fail to set wasi root dir: %s\n", optarg); - return false; - } - break; -#endif - case 'h': - showUsage(); - return false; - default: - showUsage(); - return false; - } - } - - return true; -} - -static NativeSymbol native_symbols[] = { - EXPORT_WASM_API_WITH_SIG(display_input_read, "(*)i"), - EXPORT_WASM_API_WITH_SIG(display_flush, "(iiii*)"), - EXPORT_WASM_API_WITH_SIG(display_fill, "(iiii*)"), - EXPORT_WASM_API_WITH_SIG(display_vdb_write, "(*iii*i)"), - EXPORT_WASM_API_WITH_SIG(display_map, "(iiii*)"), - EXPORT_WASM_API_WITH_SIG(time_get_ms, "()i") -}; - -// Driver function -int -iwasm_main(int argc, char *argv[]) -{ - RuntimeInitArgs init_args; - korp_tid tid; - uint32 n_native_symbols; - - if (!parse_args(argc, argv)) - return -1; - - memset(&init_args, 0, sizeof(RuntimeInitArgs)); - - init_args.mem_alloc_type = Alloc_With_Pool; - init_args.mem_alloc_option.pool.heap_buf = global_heap_buf; - init_args.mem_alloc_option.pool.heap_size = sizeof(global_heap_buf); - - init_args.native_module_name = "env"; - init_args.n_native_symbols = sizeof(native_symbols) / sizeof(NativeSymbol); - init_args.native_symbols = native_symbols; - - /* initialize runtime environment */ - if (!wasm_runtime_full_init(&init_args)) { - printf("Init runtime environment failed.\n"); - return -1; - } - - if (!init_connection_framework()) { - goto fail1; - } - - extern void display_SDL_init(); - display_SDL_init(); - - if (!init_sensor_framework()) { - goto fail2; - } - - /* timer manager */ - if (!init_wasm_timer()) { - goto fail3; - } - -#ifndef CONNECTION_UART - if (server_mode) - os_thread_create(&tid, func_server_mode, NULL, - BH_APPLET_PRESERVED_STACK_SIZE); - else - os_thread_create(&tid, func, NULL, BH_APPLET_PRESERVED_STACK_SIZE); -#else - os_thread_create(&tid, func_uart_mode, NULL, - BH_APPLET_PRESERVED_STACK_SIZE); -#endif - - app_manager_startup(&interface); - - exit_wasm_timer(); - -fail3: - exit_sensor_framework(); - -fail2: - exit_connection_framework(); - -fail1: - wasm_runtime_destroy(); - - return -1; -} diff --git a/samples/littlevgl/vgl-wasm-runtime/src/platform/linux/main.c b/samples/littlevgl/vgl-wasm-runtime/src/platform/linux/main.c deleted file mode 100644 index 63e24f11d..000000000 --- a/samples/littlevgl/vgl-wasm-runtime/src/platform/linux/main.c +++ /dev/null @@ -1,11 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ -extern int -iwasm_main(int argc, char *argv[]); -int -main(int argc, char *argv[]) -{ - return iwasm_main(argc, argv); -} diff --git a/samples/littlevgl/vgl-wasm-runtime/src/platform/linux/mouse.c b/samples/littlevgl/vgl-wasm-runtime/src/platform/linux/mouse.c deleted file mode 100644 index 45eb8cfe5..000000000 --- a/samples/littlevgl/vgl-wasm-runtime/src/platform/linux/mouse.c +++ /dev/null @@ -1,97 +0,0 @@ -/** - * @file mouse.c - * - */ - -/********************* - * INCLUDES - *********************/ -#include "display_indev.h" -#include "SDL2/SDL.h" -#if USE_MOUSE != 0 - -/********************* - * DEFINES - *********************/ -#ifndef MONITOR_ZOOM -#define MONITOR_ZOOM 1 -#endif - -/********************** - * TYPEDEFS - **********************/ - -/********************** - * STATIC PROTOTYPES - **********************/ - -/********************** - * STATIC VARIABLES - **********************/ -static bool left_button_down = false; -static int16_t last_x = 0; -static int16_t last_y = 0; - -/********************** - * MACROS - **********************/ - -/********************** - * GLOBAL FUNCTIONS - **********************/ - -/** - * Initialize the mouse - */ -void -mouse_init(void) -{} - -/** - * Get the current position and state of the mouse - * @param data store the mouse data here - * @return false: because the points are not buffered, so no more data to be - * read - */ -bool -mouse_read(lv_indev_data_t *data) -{ - /*Store the collected data*/ - data->point.x = last_x; - data->point.y = last_y; - data->state = left_button_down ? LV_INDEV_STATE_PR : LV_INDEV_STATE_REL; - - return false; -} - -/** - * It will be called from the main SDL thread - */ -void -mouse_handler(SDL_Event *event) -{ - switch (event->type) { - case SDL_MOUSEBUTTONUP: - if (event->button.button == SDL_BUTTON_LEFT) - left_button_down = false; - break; - case SDL_MOUSEBUTTONDOWN: - if (event->button.button == SDL_BUTTON_LEFT) { - left_button_down = true; - last_x = event->motion.x / MONITOR_ZOOM; - last_y = event->motion.y / MONITOR_ZOOM; - } - break; - case SDL_MOUSEMOTION: - last_x = event->motion.x / MONITOR_ZOOM; - last_y = event->motion.y / MONITOR_ZOOM; - - break; - } -} - -/********************** - * STATIC FUNCTIONS - **********************/ - -#endif diff --git a/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/LICENSE b/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/LICENSE deleted file mode 100644 index 8f71f43fe..000000000 --- a/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - diff --git a/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/XPT2046.h b/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/XPT2046.h deleted file mode 100644 index 3cd3a571d..000000000 --- a/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/XPT2046.h +++ /dev/null @@ -1,87 +0,0 @@ -/** - * @file XPT2046.h - * - */ - -#ifndef XPT2046_H -#define XPT2046_H - -#define USE_XPT2046 1 - -#define XPT2046_HOR_RES 320 -#define XPT2046_VER_RES 240 -#define XPT2046_X_MIN 200 -#define XPT2046_Y_MIN 200 -#define XPT2046_X_MAX 3800 -#define XPT2046_Y_MAX 3800 -#define XPT2046_AVG 4 -#define XPT2046_INV 0 - -#define CMD_X_READ 0b10010000 -#define CMD_Y_READ 0b11010000 - -#ifdef __cplusplus -extern "C" { -#endif - -/********************* - * INCLUDES - *********************/ - -#if USE_XPT2046 -#include -#include -#include -//#include "lvgl/lv_hal/lv_hal_indev.h" -#include "device.h" -#include "drivers/gpio.h" -#if 1 -enum { LV_INDEV_STATE_REL = 0, LV_INDEV_STATE_PR }; -typedef uint8_t lv_indev_state_t; -typedef int16_t lv_coord_t; -typedef struct { - lv_coord_t x; - lv_coord_t y; -} lv_point_t; - -typedef struct { - union { - lv_point_t - point; /*For LV_INDEV_TYPE_POINTER the currently pressed point*/ - uint32_t key; /*For LV_INDEV_TYPE_KEYPAD the currently pressed key*/ - uint32_t btn; /*For LV_INDEV_TYPE_BUTTON the currently pressed button*/ - int16_t enc_diff; /*For LV_INDEV_TYPE_ENCODER number of steps since the - previous read*/ - }; - void *user_data; /*'lv_indev_drv_t.priv' for this driver*/ - lv_indev_state_t state; /*LV_INDEV_STATE_REL or LV_INDEV_STATE_PR*/ -} lv_indev_data_t; -#endif - -/********************* - * DEFINES - *********************/ - -/********************** - * TYPEDEFS - **********************/ - -/********************** - * GLOBAL PROTOTYPES - **********************/ -void -xpt2046_init(void); -bool -xpt2046_read(lv_indev_data_t *data); - -/********************** - * MACROS - **********************/ - -#endif /* USE_XPT2046 */ - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* XPT2046_H */ diff --git a/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/board_config.h b/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/board_config.h deleted file mode 100644 index d7ea279a9..000000000 --- a/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/board_config.h +++ /dev/null @@ -1,9 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ -#ifndef __BOARD_CONFIG_H__ -#define __BOARD_CONFIG_H__ -#include "pin_config_stm32.h" - -#endif /* __BOARD_CONFIG_H__ */ diff --git a/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/display.h b/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/display.h deleted file mode 100644 index c6657a40a..000000000 --- a/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/display.h +++ /dev/null @@ -1,418 +0,0 @@ -/* - * Copyright (c) 2017 Jan Van Winkel - * - * SPDX-License-Identifier: Apache-2.0 - */ - -/** - * @file - * @brief Public API for display drivers and applications - */ - -#ifndef ZEPHYR_INCLUDE_DISPLAY_H_ -#define ZEPHYR_INCLUDE_DISPLAY_H_ - -/** - * @brief Display Interface - * @defgroup display_interface Display Interface - * @ingroup display_interfaces - * @{ - */ - -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -enum display_pixel_format { - PIXEL_FORMAT_RGB_888 = BIT(0), - PIXEL_FORMAT_MONO01 = BIT(1), /* 0=Black 1=White */ - PIXEL_FORMAT_MONO10 = BIT(2), /* 1=Black 0=White */ - PIXEL_FORMAT_ARGB_8888 = BIT(3), - PIXEL_FORMAT_RGB_565 = BIT(4), -}; - -enum display_screen_info { - /** - * If selected, one octet represents 8 pixels ordered vertically, - * otherwise ordered horizontally. - */ - SCREEN_INFO_MONO_VTILED = BIT(0), - /** - * If selected, the MSB represents the first pixel, - * otherwise MSB represents the last pixel. - */ - SCREEN_INFO_MONO_MSB_FIRST = BIT(1), - /** - * Electrophoretic Display. - */ - SCREEN_INFO_EPD = BIT(2), - /** - * Screen has two alternating ram buffers - */ - SCREEN_INFO_DOUBLE_BUFFER = BIT(3), -}; - -/** - * @enum display_orientation - * @brief Enumeration with possible display orientation - * - */ -enum display_orientation { - DISPLAY_ORIENTATION_NORMAL, - DISPLAY_ORIENTATION_ROTATED_90, - DISPLAY_ORIENTATION_ROTATED_180, - DISPLAY_ORIENTATION_ROTATED_270, -}; - -/** - * @struct display_capabilities - * @brief Structure holding display capabilities - * - * @var u16_t display_capabilities::x_resolution - * Display resolution in the X direction - * - * @var u16_t display_capabilities::y_resolution - * Display resolution in the Y direction - * - * @var u32_t display_capabilities::supported_pixel_formats - * Bitwise or of pixel formats supported by the display - * - * @var u32_t display_capabilities::screen_info - * Information about display panel - * - * @var enum display_pixel_format display_capabilities::current_pixel_format - * Currently active pixel format for the display - * - * @var enum display_orientation display_capabilities::current_orientation - * Current display orientation - * - */ -struct display_capabilities { - uint16_t x_resolution; - uint16_t y_resolution; - uint32_t supported_pixel_formats; - uint32_t screen_info; - enum display_pixel_format current_pixel_format; - enum display_orientation current_orientation; -}; - -/** - * @struct display_buffer_descriptor - * @brief Structure to describe display data buffer layout - * - * @var u32_t display_buffer_descriptor::buf_size - * Data buffer size in bytes - * - * @var u16_t display_buffer_descriptor::width - * Data buffer row width in pixels - * - * @var u16_t display_buffer_descriptor::height - * Data buffer column height in pixels - * - * @var u16_t display_buffer_descriptor::pitch - * Number of pixels between consecutive rows in the data buffer - * - */ -struct display_buffer_descriptor { - uint32_t buf_size; - uint16_t width; - uint16_t height; - uint16_t pitch; -}; - -/** - * @typedef display_blanking_on_api - * @brief Callback API to turn on display blanking - * See display_blanking_on() for argument description - */ -typedef int (*display_blanking_on_api)(const struct device *dev); - -/** - * @typedef display_blanking_off_api - * @brief Callback API to turn off display blanking - * See display_blanking_off() for argument description - */ -typedef int (*display_blanking_off_api)(const struct device *dev); - -/** - * @typedef display_write_api - * @brief Callback API for writing data to the display - * See display_write() for argument description - */ -typedef int (*display_write_api)(const struct device *dev, const uint16_t x, - const uint16_t y, - const struct display_buffer_descriptor *desc, - const void *buf); - -/** - * @typedef display_read_api - * @brief Callback API for reading data from the display - * See display_read() for argument description - */ -typedef int (*display_read_api)(const struct device *dev, const uint16_t x, - const uint16_t y, - const struct display_buffer_descriptor *desc, - void *buf); - -/** - * @typedef display_get_framebuffer_api - * @brief Callback API to get framebuffer pointer - * See display_get_framebuffer() for argument description - */ -typedef void *(*display_get_framebuffer_api)(const struct device *dev); - -/** - * @typedef display_set_brightness_api - * @brief Callback API to set display brightness - * See display_set_brightness() for argument description - */ -typedef int (*display_set_brightness_api)(const struct device *dev, - const uint8_t brightness); - -/** - * @typedef display_set_contrast_api - * @brief Callback API to set display contrast - * See display_set_contrast() for argument description - */ -typedef int (*display_set_contrast_api)(const struct device *dev, - const uint8_t contrast); - -/** - * @typedef display_get_capabilities_api - * @brief Callback API to get display capabilities - * See display_get_capabilities() for argument description - */ -typedef void (*display_get_capabilities_api)( - const struct device *dev, struct display_capabilities *capabilities); - -/** - * @typedef display_set_pixel_format_api - * @brief Callback API to set pixel format used by the display - * See display_set_pixel_format() for argument description - */ -typedef int (*display_set_pixel_format_api)( - const struct device *dev, const enum display_pixel_format pixel_format); - -/** - * @typedef display_set_orientation_api - * @brief Callback API to set orientation used by the display - * See display_set_orientation() for argument description - */ -typedef int (*display_set_orientation_api)( - const struct device *dev, const enum display_orientation orientation); - -/** - * @brief Display driver API - * API which a display driver should expose - */ -struct display_driver_api { - display_blanking_on_api blanking_on; - display_blanking_off_api blanking_off; - display_write_api write; - display_read_api read; - display_get_framebuffer_api get_framebuffer; - display_set_brightness_api set_brightness; - display_set_contrast_api set_contrast; - display_get_capabilities_api get_capabilities; - display_set_pixel_format_api set_pixel_format; - display_set_orientation_api set_orientation; -}; -extern struct ili9340_data ili9340_data1; -extern struct display_driver_api ili9340_api1; -/** - * @brief Write data to display - * - * @param dev Pointer to device structure - * @param x x Coordinate of the upper left corner where to write the buffer - * @param y y Coordinate of the upper left corner where to write the buffer - * @param desc Pointer to a structure describing the buffer layout - * @param buf Pointer to buffer array - * - * @retval 0 on success else negative errno code. - */ -static inline int -display_write(const struct device *dev, const uint16_t x, const uint16_t y, - const struct display_buffer_descriptor *desc, const void *buf) -{ - struct display_driver_api *api = &ili9340_api1; - //(struct display_driver_api *)dev->driver_api; - - return api->write(dev, x, y, desc, buf); -} - -/** - * @brief Read data from display - * - * @param dev Pointer to device structure - * @param x x Coordinate of the upper left corner where to read from - * @param y y Coordinate of the upper left corner where to read from - * @param desc Pointer to a structure describing the buffer layout - * @param buf Pointer to buffer array - * - * @retval 0 on success else negative errno code. - */ -static inline int -display_read(const struct device *dev, const uint16_t x, const uint16_t y, - const struct display_buffer_descriptor *desc, void *buf) -{ - struct display_driver_api *api = &ili9340_api1; - //(struct display_driver_api *)dev->driver_api; - - return api->read(dev, x, y, desc, buf); -} - -/** - * @brief Get pointer to framebuffer for direct access - * - * @param dev Pointer to device structure - * - * @retval Pointer to frame buffer or NULL if direct framebuffer access - * is not supported - * - */ -static inline void * -display_get_framebuffer(const struct device *dev) -{ - struct display_driver_api *api = &ili9340_api1; - //(struct display_driver_api *)dev->driver_api; - - return api->get_framebuffer(dev); -} - -/** - * @brief Turn display blanking on - * - * @param dev Pointer to device structure - * - * @retval 0 on success else negative errno code. - */ -static inline int -display_blanking_on(const struct device *dev) -{ - struct display_driver_api *api = &ili9340_api1; - //(struct display_driver_api *)dev->driver_api; - - return api->blanking_on(dev); -} - -/** - * @brief Turn display blanking off - * - * @param dev Pointer to device structure - * - * @retval 0 on success else negative errno code. - */ -static inline int -display_blanking_off(const struct device *dev) -{ - struct display_driver_api *api = &ili9340_api1; - //(struct display_driver_api *)dev->driver_api; - - return api->blanking_off(dev); -} - -/** - * @brief Set the brightness of the display - * - * Set the brightness of the display in steps of 1/256, where 255 is full - * brightness and 0 is minimal. - * - * @param dev Pointer to device structure - * @param brightness Brightness in steps of 1/256 - * - * @retval 0 on success else negative errno code. - */ -static inline int -display_set_brightness(const struct device *dev, uint8_t brightness) -{ - struct display_driver_api *api = &ili9340_api1; - //(struct display_driver_api *)dev->driver_api; - - return api->set_brightness(dev, brightness); -} - -/** - * @brief Set the contrast of the display - * - * Set the contrast of the display in steps of 1/256, where 255 is maximum - * difference and 0 is minimal. - * - * @param dev Pointer to device structure - * @param contrast Contrast in steps of 1/256 - * - * @retval 0 on success else negative errno code. - */ -static inline int -display_set_contrast(const struct device *dev, uint8_t contrast) -{ - struct display_driver_api *api = &ili9340_api1; - //(struct display_driver_api *)dev->driver_api; - - return api->set_contrast(dev, contrast); -} - -/** - * @brief Get display capabilities - * - * @param dev Pointer to device structure - * @param capabilities Pointer to capabilities structure to populate - */ -static inline void -display_get_capabilities(const struct device *dev, - struct display_capabilities *capabilities) -{ - struct display_driver_api *api = &ili9340_api1; - //(struct display_driver_api *)dev->driver_api; - - api->get_capabilities(dev, capabilities); -} - -/** - * @brief Set pixel format used by the display - * - * @param dev Pointer to device structure - * @param pixel_format Pixel format to be used by display - * - * @retval 0 on success else negative errno code. - */ -static inline int -display_set_pixel_format(const struct device *dev, - const enum display_pixel_format pixel_format) -{ - struct display_driver_api *api = &ili9340_api1; - //(struct display_driver_api *)dev->driver_api; - - return api->set_pixel_format(dev, pixel_format); -} - -/** - * @brief Set display orientation - * - * @param dev Pointer to device structure - * @param orientation Orientation to be used by display - * - * @retval 0 on success else negative errno code. - */ -static inline int -display_set_orientation(const struct device *dev, - const enum display_orientation orientation) -{ - struct display_driver_api *api = &ili9340_api1; - //(struct display_driver_api *)dev->driver_api; - - return api->set_orientation(dev, orientation); -} - -#ifdef __cplusplus -} -#endif - -/** - * @} - */ - -#endif /* ZEPHYR_INCLUDE_DISPLAY_H_*/ diff --git a/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/display_ili9340.c b/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/display_ili9340.c deleted file mode 100644 index e5b0d771a..000000000 --- a/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/display_ili9340.c +++ /dev/null @@ -1,284 +0,0 @@ -/* - * Copyright (c) 2017 Jan Van Winkel - * - * SPDX-License-Identifier: Apache-2.0 - */ - -#include "display_ili9340.h" -#include - -//#define LOG_LEVEL CONFIG_DISPLAY_LOG_LEVEL -//#include -// LOG_MODULE_REGISTER(display_ili9340); -#define LOG_ERR printf -#define LOG_DBG printf -#define LOG_WRN printf - -#include -#include -#include -#include -#include - -struct ili9340_data { - struct device *reset_gpio; - struct device *command_data_gpio; - struct device *spi_dev; - struct spi_config spi_config; -#ifdef DT_ILITEK_ILI9340_0_CS_GPIO_CONTROLLER - struct spi_cs_control cs_ctrl; -#endif -}; - -struct ili9340_data ili9340_data1; - -#define ILI9340_CMD_DATA_PIN_COMMAND 0 -#define ILI9340_CMD_DATA_PIN_DATA 1 - -static void -ili9340_exit_sleep(struct ili9340_data *data) -{ - ili9340_transmit(data, ILI9340_CMD_EXIT_SLEEP, NULL, 0); - // k_sleep(Z_TIMEOUT_MS(120)); -} - -int -ili9340_init() -{ - struct ili9340_data *data = &ili9340_data1; - - printf("Initializing display driver\n"); - data->spi_dev = device_get_binding(DT_ILITEK_ILI9340_0_BUS_NAME); - if (data->spi_dev == NULL) { - return -EPERM; - } - data->spi_config.frequency = DT_ILITEK_ILI9340_0_SPI_MAX_FREQUENCY; - data->spi_config.operation = - SPI_OP_MODE_MASTER - | SPI_WORD_SET(8); // SPI_OP_MODE_MASTER | SPI_WORD_SET(8); - data->spi_config.slave = DT_ILITEK_ILI9340_0_BASE_ADDRESS; - -#ifdef DT_ILITEK_ILI9340_0_CS_GPIO_CONTROLLER - data->cs_ctrl.gpio_dev = - device_get_binding(DT_ILITEK_ILI9340_0_CS_GPIO_CONTROLLER); - data->cs_ctrl.gpio_pin = DT_ILITEK_ILI9340_0_CS_GPIO_PIN; - data->cs_ctrl.delay = 0; - data->spi_config.cs = &(data->cs_ctrl); -#else - data->spi_config.cs = NULL; -#endif - data->reset_gpio = - device_get_binding(DT_ILITEK_ILI9340_0_RESET_GPIOS_CONTROLLER); - if (data->reset_gpio == NULL) { - return -EPERM; - } - - gpio_pin_configure(data->reset_gpio, DT_ILITEK_ILI9340_0_RESET_GPIOS_PIN, - GPIO_OUTPUT); - - data->command_data_gpio = - device_get_binding(DT_ILITEK_ILI9340_0_CMD_DATA_GPIOS_CONTROLLER); - if (data->command_data_gpio == NULL) { - return -EPERM; - } - - gpio_pin_configure(data->command_data_gpio, - DT_ILITEK_ILI9340_0_CMD_DATA_GPIOS_PIN, GPIO_OUTPUT); - - LOG_DBG("Resetting display driver\n"); - gpio_pin_set(data->reset_gpio, DT_ILITEK_ILI9340_0_RESET_GPIOS_PIN, 1); - k_sleep(Z_TIMEOUT_MS(1)); - gpio_pin_set(data->reset_gpio, DT_ILITEK_ILI9340_0_RESET_GPIOS_PIN, 0); - k_sleep(Z_TIMEOUT_MS(1)); - gpio_pin_set(data->reset_gpio, DT_ILITEK_ILI9340_0_RESET_GPIOS_PIN, 1); - k_sleep(Z_TIMEOUT_MS(5)); - - LOG_DBG("Initializing LCD\n"); - ili9340_lcd_init(data); - - LOG_DBG("Exiting sleep mode\n"); - ili9340_exit_sleep(data); - - return 0; -} - -static void -ili9340_set_mem_area(struct ili9340_data *data, const uint16_t x, - const uint16_t y, const uint16_t w, const uint16_t h) -{ - uint16_t spi_data[2]; - - spi_data[0] = sys_cpu_to_be16(x); - spi_data[1] = sys_cpu_to_be16(x + w - 1); - ili9340_transmit(data, ILI9340_CMD_COLUMN_ADDR, &spi_data[0], 4); - - spi_data[0] = sys_cpu_to_be16(y); - spi_data[1] = sys_cpu_to_be16(y + h - 1); - ili9340_transmit(data, ILI9340_CMD_PAGE_ADDR, &spi_data[0], 4); -} - -static int -ili9340_write(const struct device *dev, const uint16_t x, const uint16_t y, - const struct display_buffer_descriptor *desc, const void *buf) -{ - struct ili9340_data *data = (struct ili9340_data *)&ili9340_data1; - const uint8_t *write_data_start = (uint8_t *)buf; - struct spi_buf tx_buf; - struct spi_buf_set tx_bufs; - uint16_t write_cnt; - uint16_t nbr_of_writes; - uint16_t write_h; - - __ASSERT(desc->width <= desc->pitch, "Pitch is smaller then width"); - __ASSERT((3 * desc->pitch * desc->height) <= desc->buf_size, - "Input buffer to small"); - ili9340_set_mem_area(data, x, y, desc->width, desc->height); - - if (desc->pitch > desc->width) { - write_h = 1U; - nbr_of_writes = desc->height; - } - else { - write_h = desc->height; - nbr_of_writes = 1U; - } - ili9340_transmit(data, ILI9340_CMD_MEM_WRITE, (void *)write_data_start, - 3 * desc->width * write_h); - - tx_bufs.buffers = &tx_buf; - tx_bufs.count = 1; - - write_data_start += (3 * desc->pitch); - for (write_cnt = 1U; write_cnt < nbr_of_writes; ++write_cnt) { - tx_buf.buf = (void *)write_data_start; - tx_buf.len = 3 * desc->width * write_h; - spi_transceive(data->spi_dev, &data->spi_config, &tx_bufs, NULL); - write_data_start += (3 * desc->pitch); - } - - return 0; -} - -static int -ili9340_read(const struct device *dev, const uint16_t x, const uint16_t y, - const struct display_buffer_descriptor *desc, void *buf) -{ - LOG_ERR("Reading not supported\n"); - return -ENOTSUP; -} - -static void * -ili9340_get_framebuffer(const struct device *dev) -{ - LOG_ERR("Direct framebuffer access not supported\n"); - return NULL; -} - -static int -ili9340_display_blanking_off(const struct device *dev) -{ - struct ili9340_data *data = (struct ili9340_data *)dev->driver_data; - - LOG_DBG("Turning display blanking off\n"); - ili9340_transmit(data, ILI9340_CMD_DISPLAY_ON, NULL, 0); - return 0; -} - -static int -ili9340_display_blanking_on(const struct device *dev) -{ - struct ili9340_data *data = (struct ili9340_data *)dev->driver_data; - - LOG_DBG("Turning display blanking on\n"); - ili9340_transmit(data, ILI9340_CMD_DISPLAY_OFF, NULL, 0); - return 0; -} - -static int -ili9340_set_brightness(const struct device *dev, const uint8_t brightness) -{ - LOG_WRN("Set brightness not implemented\n"); - return -ENOTSUP; -} - -static int -ili9340_set_contrast(const struct device *dev, const uint8_t contrast) -{ - LOG_ERR("Set contrast not supported\n"); - return -ENOTSUP; -} - -static int -ili9340_set_pixel_format(const struct device *dev, - const enum display_pixel_format pixel_format) -{ - if (pixel_format == PIXEL_FORMAT_RGB_888) { - return 0; - } - LOG_ERR("Pixel format change not implemented\n"); - return -ENOTSUP; -} - -static int -ili9340_set_orientation(const struct device *dev, - const enum display_orientation orientation) -{ - if (orientation == DISPLAY_ORIENTATION_NORMAL) { - return 0; - } - LOG_ERR("Changing display orientation not implemented\n"); - return -ENOTSUP; -} - -static void -ili9340_get_capabilities(const struct device *dev, - struct display_capabilities *capabilities) -{ - memset(capabilities, 0, sizeof(struct display_capabilities)); - capabilities->x_resolution = 320; - capabilities->y_resolution = 240; - capabilities->supported_pixel_formats = PIXEL_FORMAT_RGB_888; - capabilities->current_pixel_format = PIXEL_FORMAT_RGB_888; - capabilities->current_orientation = DISPLAY_ORIENTATION_NORMAL; -} - -void -ili9340_transmit(struct ili9340_data *data, uint8_t cmd, void *tx_data, - size_t tx_len) -{ - struct spi_buf tx_buf = { .buf = &cmd, .len = 1 }; - struct spi_buf_set tx_bufs = { .buffers = &tx_buf, .count = 1 }; - - data = (struct ili9340_data *)&ili9340_data1; - gpio_pin_set(data->command_data_gpio, - DT_ILITEK_ILI9340_0_CMD_DATA_GPIOS_PIN, - ILI9340_CMD_DATA_PIN_COMMAND); - spi_transceive(data->spi_dev, &data->spi_config, &tx_bufs, NULL); - if (tx_data != NULL) { - tx_buf.buf = tx_data; - tx_buf.len = tx_len; - gpio_pin_set(data->command_data_gpio, - DT_ILITEK_ILI9340_0_CMD_DATA_GPIOS_PIN, - ILI9340_CMD_DATA_PIN_DATA); - spi_transceive(data->spi_dev, &data->spi_config, &tx_bufs, NULL); - } -} - -struct display_driver_api ili9340_api1 = { - .blanking_on = ili9340_display_blanking_on, - .blanking_off = ili9340_display_blanking_off, - .write = ili9340_write, - .read = ili9340_read, - .get_framebuffer = ili9340_get_framebuffer, - .set_brightness = ili9340_set_brightness, - .set_contrast = ili9340_set_contrast, - .get_capabilities = ili9340_get_capabilities, - .set_pixel_format = ili9340_set_pixel_format, - .set_orientation = ili9340_set_orientation -}; - -/* -DEVICE_AND_API_INIT(ili9340, DT_ILITEK_ILI9340_0_LABEL, &ili9340_init, - &ili9340_data, NULL, APPLICATION, - CONFIG_APPLICATION_INIT_PRIORITY, &ili9340_api); -*/ diff --git a/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/display_ili9340_adafruit_1480.c b/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/display_ili9340_adafruit_1480.c deleted file mode 100644 index 65aa618b5..000000000 --- a/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/display_ili9340_adafruit_1480.c +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2017 Jan Van Winkel - * - * SPDX-License-Identifier: Apache-2.0 - */ - -#include "display_ili9340.h" - -void -ili9340_lcd_init(struct ili9340_data *data) -{ - uint8_t tx_data[15]; - - tx_data[0] = 0x23; - ili9340_transmit(data, ILI9340_CMD_POWER_CTRL_1, tx_data, 1); - - tx_data[0] = 0x10; - ili9340_transmit(data, ILI9340_CMD_POWER_CTRL_2, tx_data, 1); - - tx_data[0] = 0x3e; - tx_data[1] = 0x28; - ili9340_transmit(data, ILI9340_CMD_VCOM_CTRL_1, tx_data, 2); - - tx_data[0] = 0x86; - ili9340_transmit(data, ILI9340_CMD_VCOM_CTRL_2, tx_data, 1); - - tx_data[0] = - ILI9340_DATA_MEM_ACCESS_CTRL_MV | ILI9340_DATA_MEM_ACCESS_CTRL_BGR; - ili9340_transmit(data, ILI9340_CMD_MEM_ACCESS_CTRL, tx_data, 1); - - tx_data[0] = ILI9340_DATA_PIXEL_FORMAT_MCU_18_BIT - | ILI9340_DATA_PIXEL_FORMAT_RGB_18_BIT; - ili9340_transmit(data, ILI9340_CMD_PIXEL_FORMAT_SET, tx_data, 1); - - tx_data[0] = 0x00; - tx_data[1] = 0x18; - ili9340_transmit(data, ILI9340_CMD_FRAME_CTRL_NORMAL_MODE, tx_data, 2); - - tx_data[0] = 0x08; - tx_data[1] = 0x82; - tx_data[2] = 0x27; - ili9340_transmit(data, ILI9340_CMD_DISPLAY_FUNCTION_CTRL, tx_data, 3); - - tx_data[0] = 0x01; - ili9340_transmit(data, ILI9340_CMD_GAMMA_SET, tx_data, 1); - - tx_data[0] = 0x0F; - tx_data[1] = 0x31; - tx_data[2] = 0x2B; - tx_data[3] = 0x0C; - tx_data[4] = 0x0E; - tx_data[5] = 0x08; - tx_data[6] = 0x4E; - tx_data[7] = 0xF1; - tx_data[8] = 0x37; - tx_data[9] = 0x07; - tx_data[10] = 0x10; - tx_data[11] = 0x03; - tx_data[12] = 0x0E; - tx_data[13] = 0x09; - tx_data[14] = 0x00; - ili9340_transmit(data, ILI9340_CMD_POSITVE_GAMMA_CORRECTION, tx_data, 15); - - tx_data[0] = 0x00; - tx_data[1] = 0x0E; - tx_data[2] = 0x14; - tx_data[3] = 0x03; - tx_data[4] = 0x11; - tx_data[5] = 0x07; - tx_data[6] = 0x31; - tx_data[7] = 0xC1; - tx_data[8] = 0x48; - tx_data[9] = 0x08; - tx_data[10] = 0x0F; - tx_data[11] = 0x0C; - tx_data[12] = 0x31; - tx_data[13] = 0x36; - tx_data[14] = 0x0F; - ili9340_transmit(data, ILI9340_CMD_NEGATIVE_GAMMA_CORRECTION, tx_data, 15); -} diff --git a/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/display_indev.c b/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/display_indev.c deleted file mode 100644 index b2f9f8e52..000000000 --- a/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/display_indev.c +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ -#include -#include -#include "display_indev.h" -#include "display.h" -#include "wasm_export.h" -#include "app_manager_export.h" - -#define MONITOR_HOR_RES 320 -#define MONITOR_VER_RES 240 -#ifndef MONITOR_ZOOM -#define MONITOR_ZOOM 1 -#endif - -extern int -ili9340_init(); - -static int lcd_initialized = 0; - -void -display_init(void) -{ - if (lcd_initialized != 0) { - return; - } - lcd_initialized = 1; - xpt2046_init(); - ili9340_init(); - display_blanking_off(NULL); -} - -void -display_flush(wasm_exec_env_t exec_env, int32_t x1, int32_t y1, int32_t x2, - int32_t y2, lv_color_t *color) -{ - wasm_module_inst_t module_inst = get_module_inst(exec_env); - struct display_buffer_descriptor desc; - - if (!wasm_runtime_validate_native_addr(module_inst, color, - sizeof(lv_color_t))) - return; - - uint16_t w = x2 - x1 + 1; - uint16_t h = y2 - y1 + 1; - - desc.buf_size = 3 * w * h; - desc.width = w; - desc.pitch = w; - desc.height = h; - display_write(NULL, x1, y1, &desc, (void *)color); - - /*lv_flush_ready();*/ -} - -void -display_fill(wasm_exec_env_t exec_env, int32_t x1, int32_t y1, int32_t x2, - int32_t y2, lv_color_t *color) -{} - -void -display_map(wasm_exec_env_t exec_env, int32_t x1, int32_t y1, int32_t x2, - int32_t y2, const lv_color_t *color) -{} - -bool -display_input_read(wasm_exec_env_t exec_env, void *data) -{ - wasm_module_inst_t module_inst = get_module_inst(exec_env); - lv_indev_data_t *lv_data = (lv_indev_data_t *)data; - - if (!wasm_runtime_validate_native_addr(module_inst, lv_data, - sizeof(lv_indev_data_t))) - return false; - - return touchscreen_read(lv_data); -} - -void -display_deinit(wasm_exec_env_t exec_env) -{} - -void -display_vdb_write(wasm_exec_env_t exec_env, void *buf, lv_coord_t buf_w, - lv_coord_t x, lv_coord_t y, lv_color_t *color, lv_opa_t opa) -{ - wasm_module_inst_t module_inst = get_module_inst(exec_env); - uint8_t *buf_xy = (uint8_t *)buf + 3 * x + 3 * y * buf_w; - - if (!wasm_runtime_validate_native_addr(module_inst, color, - sizeof(lv_color_t))) - return; - - *buf_xy = color->red; - *(buf_xy + 1) = color->green; - *(buf_xy + 2) = color->blue; -} - -int -time_get_ms(wasm_exec_env_t exec_env) -{ - return k_uptime_get_32(); -} diff --git a/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/main.c b/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/main.c deleted file mode 100644 index c331306ed..000000000 --- a/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/main.c +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include -#include -#include "bh_platform.h" -#include "bh_assert.h" -#include "bh_log.h" -#include "wasm_export.h" - -extern void -display_init(void); -extern int -iwasm_main(); - -void -main(void) -{ - display_init(); - iwasm_main(); - for (;;) { - k_sleep(Z_TIMEOUT_MS(1000)); - } -} diff --git a/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/pin_config_jlf.h b/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/pin_config_jlf.h deleted file mode 100644 index bb20ecbb8..000000000 --- a/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/pin_config_jlf.h +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ -#ifndef __PIN_CONFIG_JLF_H__ -#define __PIN_CONFIG_JLF_H__ - -#define DT_ILITEK_ILI9340_0_BUS_NAME "SPI_2" -#define DT_ILITEK_ILI9340_0_SPI_MAX_FREQUENCY 10 * 1000 - -#define DT_ILITEK_ILI9340_0_BASE_ADDRESS 1 -#define DT_ILITEK_ILI9340_0_RESET_GPIOS_CONTROLLER "GPIO_0" -#define DT_ILITEK_ILI9340_0_RESET_GPIOS_PIN 5 -#define DT_ILITEK_ILI9340_0_CMD_DATA_GPIOS_CONTROLLER "GPIO_0" -#define DT_ILITEK_ILI9340_0_CMD_DATA_GPIOS_PIN 4 - -#define XPT2046_SPI_DEVICE_NAME "SPI_2" -#define XPT2046_SPI_MAX_FREQUENCY 10 * 1000 -#define XPT2046_CS_GPIO_CONTROLLER "GPIO_0" -#define XPT2046_CS_GPIO_PIN 6 - -#define XPT2046_PEN_GPIO_CONTROLLER "GPIO_0" -#define XPT2046_PEN_GPIO_PIN 7 - -#define HOST_DEVICE_COMM_UART_NAME "UART_1" -#endif /* __PIN_CONFIG_JLF_H__ */ diff --git a/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/pin_config_stm32.h b/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/pin_config_stm32.h deleted file mode 100644 index 523ce2308..000000000 --- a/samples/littlevgl/vgl-wasm-runtime/src/platform/zephyr/pin_config_stm32.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ -#ifndef __PIN_CONFIG_STM32_H__ -#define __PIN_CONFIG_STM32_H__ - -#define DT_ILITEK_ILI9340_0_BUS_NAME "SPI_1" -#define DT_ILITEK_ILI9340_0_SPI_MAX_FREQUENCY 24 * 1000 * 1000 - -#define DT_ILITEK_ILI9340_0_BASE_ADDRESS 1 -#define DT_ILITEK_ILI9340_0_RESET_GPIOS_CONTROLLER "GPIOC" -#define DT_ILITEK_ILI9340_0_RESET_GPIOS_PIN 12 -#define DT_ILITEK_ILI9340_0_CMD_DATA_GPIOS_CONTROLLER "GPIOC" -#define DT_ILITEK_ILI9340_0_CMD_DATA_GPIOS_PIN 11 - -#define DT_ILITEK_ILI9340_0_CS_GPIO_CONTROLLER "GPIOC" -#define DT_ILITEK_ILI9340_0_CS_GPIO_PIN 10 - -#define XPT2046_SPI_DEVICE_NAME "SPI_1" -#define XPT2046_SPI_MAX_FREQUENCY 12 * 1000 * 1000 -#define XPT2046_CS_GPIO_CONTROLLER "GPIOD" -#define XPT2046_CS_GPIO_PIN 0 - -#define XPT2046_PEN_GPIO_CONTROLLER "GPIOD" -#define XPT2046_PEN_GPIO_PIN 1 - -#define HOST_DEVICE_COMM_UART_NAME "UART_6" - -#endif /* __PIN_CONFIG_STM32_H__ */ diff --git a/samples/littlevgl/vgl-wasm-runtime/zephyr-build/CMakeLists.txt b/samples/littlevgl/vgl-wasm-runtime/zephyr-build/CMakeLists.txt deleted file mode 100644 index 723ff8fa9..000000000 --- a/samples/littlevgl/vgl-wasm-runtime/zephyr-build/CMakeLists.txt +++ /dev/null @@ -1,71 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -cmake_minimum_required(VERSION 3.8.2) - -include($ENV{ZEPHYR_BASE}/cmake/app/boilerplate.cmake NO_POLICY_SCOPE) -project(NONE) - -set (WAMR_BUILD_PLATFORM "zephyr") - -enable_language (ASM) - -add_definitions(-DWA_MALLOC=wasm_runtime_malloc) -add_definitions(-DWA_FREE=wasm_runtime_free) - -# Build as THUMB by default -# change to "ARM[sub]", "THUMB[sub]", "X86_32", "MIPS_32" or "XTENSA_32" -# if we want to support arm_32, x86, mips or xtensa -if (NOT DEFINED WAMR_BUILD_TARGET) - set (WAMR_BUILD_TARGET "THUMBV7") -endif () - -if (NOT DEFINED WAMR_BUILD_INTERP) - # Enable Interpreter by default - set (WAMR_BUILD_INTERP 1) -endif () - -if (NOT DEFINED WAMR_BUILD_AOT) - 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_LIBC_BUILTIN) - set (WAMR_BUILD_LIBC_BUILTIN 1) -endif () - -if (NOT DEFINED WAMR_BUILD_LIBC_WASI) - set (WAMR_BUILD_LIBC_WASI 0) -endif () - -if (NOT DEFINED WAMR_BUILD_APP_FRAMEWORK) - set (WAMR_BUILD_APP_FRAMEWORK 1) -endif () - -if (NOT DEFINED WAMR_BUILD_APP_LIST) - set (WAMR_BUILD_APP_LIST WAMR_APP_BUILD_BASE WAMR_APP_BUILD_SENSOR WAMR_APP_BUILD_CONNECTION) -endif () - -set (WAMR_ROOT_DIR ${CMAKE_CURRENT_SOURCE_DIR}/wamr) -include (${WAMR_ROOT_DIR}/build-scripts/runtime_lib.cmake) - -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../src) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../src/platform/zephyr) - -set (LVGL_DRV_SRCS - ${CMAKE_CURRENT_SOURCE_DIR}/../src/platform/zephyr/display_ili9340_adafruit_1480.c - ${CMAKE_CURRENT_SOURCE_DIR}/../src/platform/zephyr/display_ili9340.c - ${CMAKE_CURRENT_SOURCE_DIR}/../src/platform/zephyr/display_indev.c - ${CMAKE_CURRENT_SOURCE_DIR}/../src/platform/zephyr/XPT2046.c - ) - -target_sources(app PRIVATE - ${WAMR_RUNTIME_LIB_SOURCE} - ${LVGL_DRV_SRCS} - ${CMAKE_CURRENT_SOURCE_DIR}/../src/platform/zephyr/main.c - ${CMAKE_CURRENT_SOURCE_DIR}/../src/platform/zephyr/iwasm_main.c - ) diff --git a/samples/littlevgl/vgl-wasm-runtime/zephyr-build/prj.conf b/samples/littlevgl/vgl-wasm-runtime/zephyr-build/prj.conf deleted file mode 100644 index 6ca7f4426..000000000 --- a/samples/littlevgl/vgl-wasm-runtime/zephyr-build/prj.conf +++ /dev/null @@ -1,9 +0,0 @@ -CONFIG_SPI=y -CONFIG_SPI_STM32=y -CONFIG_PRINTK=y -CONFIG_LOG=y -#CONFIG_UART_2=y -CONFIG_UART_INTERRUPT_DRIVEN=y -CONFIG_STACK_SENTINEL=y -CONFIG_MAIN_STACK_SIZE=2048 -CONFIG_ARM_MPU=y diff --git a/samples/littlevgl/wamr_config_littlevgl.cmake b/samples/littlevgl/wamr_config_littlevgl.cmake deleted file mode 100644 index 7a9065ab5..000000000 --- a/samples/littlevgl/wamr_config_littlevgl.cmake +++ /dev/null @@ -1,9 +0,0 @@ -set (WAMR_BUILD_PLATFORM "linux") -set (WAMR_BUILD_TARGET X86_64) -set (WAMR_BUILD_INTERP 1) -set (WAMR_BUILD_AOT 1) -set (WAMR_BUILD_JIT 0) -set (WAMR_BUILD_LIBC_BUILTIN 1) -set (WAMR_BUILD_LIBC_WASI 1) -set (WAMR_BUILD_APP_FRAMEWORK 1) -set (WAMR_BUILD_APP_LIST WAMR_APP_BUILD_BASE WAMR_APP_BUILD_SENSOR WAMR_APP_BUILD_CONNECTION) diff --git a/samples/littlevgl/wasm-apps/Makefile_wasm_app b/samples/littlevgl/wasm-apps/Makefile_wasm_app deleted file mode 100644 index 8c053cc6d..000000000 --- a/samples/littlevgl/wasm-apps/Makefile_wasm_app +++ /dev/null @@ -1,57 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -CC = /opt/wasi-sdk/bin/clang -LVGL_DIR = ${shell pwd} -SDK_DIR = $(LVGL_DIR)/../../../wamr-sdk/out/littlevgl/app-sdk -APP_FRAMEWORK_DIR = $(SDK_DIR)/wamr-app-framework -LVGL_REPO_PATH=../build/lvgl - -CFLAGS += -O3 \ - -I$(LVGL_DIR) \ - -I$(LVGL_DIR)/../build \ - -I$(LVGL_DIR)/lv_drivers \ - -I$(LVGL_DIR)/src \ - -I$(LVGL_DIR)/../lv_config \ - -I$(APP_FRAMEWORK_DIR)/include - -SRCS += ${LVGL_REPO_PATH}/lv_draw/lv_draw_line.c ${LVGL_REPO_PATH}/lv_draw/lv_draw_rbasic.c -SRCS += ${LVGL_REPO_PATH}/lv_draw/lv_draw_img.c ${LVGL_REPO_PATH}/lv_draw/lv_draw_arc.c -SRCS += ${LVGL_REPO_PATH}/lv_draw/lv_draw_rect.c ${LVGL_REPO_PATH}/lv_draw/lv_draw_triangle.c -SRCS += ${LVGL_REPO_PATH}/lv_draw/lv_draw.c ${LVGL_REPO_PATH}/lv_draw/lv_draw_label.c -SRCS += ${LVGL_REPO_PATH}/lv_draw/lv_draw_vbasic.c ${LVGL_REPO_PATH}/lv_fonts/lv_font_builtin.c -SRCS += ${LVGL_REPO_PATH}/lv_fonts/lv_font_dejavu_20.c -SRCS += ${LVGL_REPO_PATH}/lv_objx/lv_img.c -SRCS += ${LVGL_REPO_PATH}/lv_objx/lv_roller.c ${LVGL_REPO_PATH}/lv_objx/lv_cb.c ${LVGL_REPO_PATH}/lv_objx/lv_led.c ${LVGL_REPO_PATH}/lv_objx/lv_cont.c -SRCS += ${LVGL_REPO_PATH}/lv_objx/lv_calendar.c ${LVGL_REPO_PATH}/lv_objx/lv_gauge.c ${LVGL_REPO_PATH}/lv_objx/lv_page.c -SRCS += ${LVGL_REPO_PATH}/lv_objx/lv_list.c ${LVGL_REPO_PATH}/lv_objx/lv_bar.c ${LVGL_REPO_PATH}/lv_objx/lv_tabview.c -SRCS += ${LVGL_REPO_PATH}/lv_objx/lv_mbox.c ${LVGL_REPO_PATH}/lv_objx/lv_objx_templ.c ${LVGL_REPO_PATH}/lv_objx/lv_sw.c -SRCS += ${LVGL_REPO_PATH}/lv_objx/lv_label.c ${LVGL_REPO_PATH}/lv_objx/lv_slider.c ${LVGL_REPO_PATH}/lv_objx/lv_ddlist.c -SRCS += ${LVGL_REPO_PATH}/lv_objx/lv_imgbtn.c ${LVGL_REPO_PATH}/lv_objx/lv_line.c ${LVGL_REPO_PATH}/lv_objx/lv_chart.c -SRCS += ${LVGL_REPO_PATH}/lv_objx/lv_btnm.c ${LVGL_REPO_PATH}/lv_objx/lv_arc.c ${LVGL_REPO_PATH}/lv_objx/lv_preload.c -SRCS += ${LVGL_REPO_PATH}/lv_objx/lv_win.c ${LVGL_REPO_PATH}/lv_objx/lv_lmeter.c ${LVGL_REPO_PATH}/lv_objx/lv_btn.c -SRCS += ${LVGL_REPO_PATH}/lv_objx/lv_ta.c ${LVGL_REPO_PATH}/lv_misc/lv_log.c ${LVGL_REPO_PATH}/lv_misc/lv_fs.c -SRCS += ${LVGL_REPO_PATH}/lv_misc/lv_task.c ${LVGL_REPO_PATH}/lv_misc/lv_circ.c ${LVGL_REPO_PATH}/lv_misc/lv_anim.c -SRCS += ${LVGL_REPO_PATH}/lv_misc/lv_color.c ${LVGL_REPO_PATH}/lv_misc/lv_txt.c ${LVGL_REPO_PATH}/lv_misc/lv_math.c -SRCS += ${LVGL_REPO_PATH}/lv_misc/lv_mem.c ${LVGL_REPO_PATH}/lv_misc/lv_font.c ${LVGL_REPO_PATH}/lv_misc/lv_ll.c -SRCS += ${LVGL_REPO_PATH}/lv_misc/lv_area.c ${LVGL_REPO_PATH}/lv_misc/lv_templ.c ${LVGL_REPO_PATH}/lv_misc/lv_ufs.c -SRCS += ${LVGL_REPO_PATH}/lv_misc/lv_gc.c -SRCS += ${LVGL_REPO_PATH}/lv_hal/lv_hal_tick.c ${LVGL_REPO_PATH}/lv_hal/lv_hal_indev.c ${LVGL_REPO_PATH}/lv_hal/lv_hal_disp.c -SRCS += ${LVGL_REPO_PATH}/lv_themes/lv_theme_mono.c ${LVGL_REPO_PATH}/lv_themes/lv_theme_templ.c -SRCS += ${LVGL_REPO_PATH}/lv_themes/lv_theme_material.c ${LVGL_REPO_PATH}/lv_themes/lv_theme.c -SRCS += ${LVGL_REPO_PATH}/lv_themes/lv_theme_night.c ${LVGL_REPO_PATH}/lv_themes/lv_theme_zen.c ${LVGL_REPO_PATH}/lv_themes/lv_theme_nemo.c -SRCS += ${LVGL_REPO_PATH}/lv_themes/lv_theme_alien.c ${LVGL_REPO_PATH}/lv_themes/lv_theme_default.c -SRCS += ${LVGL_REPO_PATH}/lv_core/lv_group.c ${LVGL_REPO_PATH}/lv_core/lv_style.c ${LVGL_REPO_PATH}/lv_core/lv_indev.c -SRCS += ${LVGL_REPO_PATH}/lv_core/lv_vdb.c ${LVGL_REPO_PATH}/lv_core/lv_obj.c ${LVGL_REPO_PATH}/lv_core/lv_refr.c -SRCS += $(LVGL_DIR)/src/main.c - -all: - @$(CC) $(CFLAGS) $(SRCS) \ - -O3 -z stack-size=2048 -Wl,--initial-memory=65536 \ - -DLV_CONF_INCLUDE_SIMPLE \ - -L$(APP_FRAMEWORK_DIR)/lib -lapp_framework \ - -Wl,--allow-undefined \ - -Wl,--strip-all,--no-entry \ - -Wl,--export=on_init -Wl,--export=on_timer_callback \ - -Wl,--export=__heap_base,--export=__data_end \ - -o ui_app_wasi.wasm diff --git a/samples/littlevgl/wasm-apps/Makefile_wasm_app_no_wasi b/samples/littlevgl/wasm-apps/Makefile_wasm_app_no_wasi deleted file mode 100644 index d18c0a222..000000000 --- a/samples/littlevgl/wasm-apps/Makefile_wasm_app_no_wasi +++ /dev/null @@ -1,59 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -CC = /opt/wasi-sdk/bin/clang -LVGL_DIR = ${shell pwd} -WAMR_DIR = ${LVGL_DIR}/../../.. -SDK_DIR = $(LVGL_DIR)/../../../wamr-sdk/out/littlevgl/app-sdk -APP_FRAMEWORK_DIR = $(SDK_DIR)/wamr-app-framework -LVGL_REPO_PATH=../build/lvgl - -CFLAGS += -O3 \ - -I$(LVGL_DIR) \ - -I$(LVGL_DIR)/../build \ - -I$(LVGL_DIR)/lv_drivers \ - -I$(LVGL_DIR)/src \ - -I$(LVGL_DIR)/../lv_config \ - -I$(APP_FRAMEWORK_DIR)/include - -SRCS += $(LVGL_REPO_PATH)/lv_draw/lv_draw_line.c $(LVGL_REPO_PATH)/lv_draw/lv_draw_rbasic.c -SRCS += $(LVGL_REPO_PATH)/lv_draw/lv_draw_img.c $(LVGL_REPO_PATH)/lv_draw/lv_draw_arc.c -SRCS += $(LVGL_REPO_PATH)/lv_draw/lv_draw_rect.c $(LVGL_REPO_PATH)/lv_draw/lv_draw_triangle.c -SRCS += $(LVGL_REPO_PATH)/lv_draw/lv_draw.c $(LVGL_REPO_PATH)/lv_draw/lv_draw_label.c -SRCS += $(LVGL_REPO_PATH)/lv_draw/lv_draw_vbasic.c $(LVGL_REPO_PATH)/lv_fonts/lv_font_builtin.c -SRCS += $(LVGL_REPO_PATH)/lv_fonts/lv_font_dejavu_20.c -SRCS += $(LVGL_REPO_PATH)/lv_objx/lv_img.c -SRCS += $(LVGL_REPO_PATH)/lv_objx/lv_roller.c $(LVGL_REPO_PATH)/lv_objx/lv_cb.c $(LVGL_REPO_PATH)/lv_objx/lv_led.c $(LVGL_REPO_PATH)/lv_objx/lv_cont.c -SRCS += $(LVGL_REPO_PATH)/lv_objx/lv_calendar.c $(LVGL_REPO_PATH)/lv_objx/lv_gauge.c $(LVGL_REPO_PATH)/lv_objx/lv_page.c -SRCS += $(LVGL_REPO_PATH)/lv_objx/lv_list.c $(LVGL_REPO_PATH)/lv_objx/lv_bar.c $(LVGL_REPO_PATH)/lv_objx/lv_tabview.c -SRCS += $(LVGL_REPO_PATH)/lv_objx/lv_mbox.c $(LVGL_REPO_PATH)/lv_objx/lv_objx_templ.c $(LVGL_REPO_PATH)/lv_objx/lv_sw.c -SRCS += $(LVGL_REPO_PATH)/lv_objx/lv_label.c $(LVGL_REPO_PATH)/lv_objx/lv_slider.c $(LVGL_REPO_PATH)/lv_objx/lv_ddlist.c -SRCS += $(LVGL_REPO_PATH)/lv_objx/lv_imgbtn.c $(LVGL_REPO_PATH)/lv_objx/lv_line.c $(LVGL_REPO_PATH)/lv_objx/lv_chart.c -SRCS += $(LVGL_REPO_PATH)/lv_objx/lv_btnm.c $(LVGL_REPO_PATH)/lv_objx/lv_arc.c $(LVGL_REPO_PATH)/lv_objx/lv_preload.c -SRCS += $(LVGL_REPO_PATH)/lv_objx/lv_win.c $(LVGL_REPO_PATH)/lv_objx/lv_lmeter.c $(LVGL_REPO_PATH)/lv_objx/lv_btn.c -SRCS += $(LVGL_REPO_PATH)/lv_objx/lv_ta.c $(LVGL_REPO_PATH)/lv_misc/lv_log.c $(LVGL_REPO_PATH)/lv_misc/lv_fs.c -SRCS += $(LVGL_REPO_PATH)/lv_misc/lv_task.c $(LVGL_REPO_PATH)/lv_misc/lv_circ.c $(LVGL_REPO_PATH)/lv_misc/lv_anim.c -SRCS += $(LVGL_REPO_PATH)/lv_misc/lv_color.c $(LVGL_REPO_PATH)/lv_misc/lv_txt.c $(LVGL_REPO_PATH)/lv_misc/lv_math.c -SRCS += $(LVGL_REPO_PATH)/lv_misc/lv_mem.c $(LVGL_REPO_PATH)/lv_misc/lv_font.c $(LVGL_REPO_PATH)/lv_misc/lv_ll.c -SRCS += $(LVGL_REPO_PATH)/lv_misc/lv_area.c $(LVGL_REPO_PATH)/lv_misc/lv_templ.c $(LVGL_REPO_PATH)/lv_misc/lv_ufs.c -SRCS += $(LVGL_REPO_PATH)/lv_misc/lv_gc.c -SRCS += $(LVGL_REPO_PATH)/lv_hal/lv_hal_tick.c $(LVGL_REPO_PATH)/lv_hal/lv_hal_indev.c $(LVGL_REPO_PATH)/lv_hal/lv_hal_disp.c -SRCS += $(LVGL_REPO_PATH)/lv_themes/lv_theme_mono.c $(LVGL_REPO_PATH)/lv_themes/lv_theme_templ.c -SRCS += $(LVGL_REPO_PATH)/lv_themes/lv_theme_material.c $(LVGL_REPO_PATH)/lv_themes/lv_theme.c -SRCS += $(LVGL_REPO_PATH)/lv_themes/lv_theme_night.c $(LVGL_REPO_PATH)/lv_themes/lv_theme_zen.c $(LVGL_REPO_PATH)/lv_themes/lv_theme_nemo.c -SRCS += $(LVGL_REPO_PATH)/lv_themes/lv_theme_alien.c $(LVGL_REPO_PATH)/lv_themes/lv_theme_default.c -SRCS += $(LVGL_REPO_PATH)/lv_core/lv_group.c $(LVGL_REPO_PATH)/lv_core/lv_style.c $(LVGL_REPO_PATH)/lv_core/lv_indev.c -SRCS += $(LVGL_REPO_PATH)/lv_core/lv_vdb.c $(LVGL_REPO_PATH)/lv_core/lv_obj.c $(LVGL_REPO_PATH)/lv_core/lv_refr.c -SRCS += $(LVGL_DIR)/src/main.c - -all: - @$(CC) $(CFLAGS) $(SRCS) \ - --target=wasm32 -Wl,--allow-undefined \ - --sysroot=$(WAMR_DIR)/wamr-sdk/app/libc-builtin-sysroot \ - -O3 -z stack-size=2048 -Wl,--initial-memory=65536 \ - -DLV_CONF_INCLUDE_SIMPLE \ - -L$(APP_FRAMEWORK_DIR)/lib -lapp_framework \ - -Wl,--allow-undefined \ - -Wl,--strip-all,--no-entry -nostdlib \ - -Wl,--export=on_init -Wl,--export=on_timer_callback \ - -o ui_app_builtin_libc.wasm diff --git a/samples/littlevgl/wasm-apps/build_wasm_app.sh b/samples/littlevgl/wasm-apps/build_wasm_app.sh deleted file mode 100755 index a86784e2a..000000000 --- a/samples/littlevgl/wasm-apps/build_wasm_app.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/bin/sh - -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -WAMR_DIR=${PWD}/../../.. - -if [ -z $KW_BUILD ] || [ -z $KW_OUT_FILE ];then - echo "Local Build Env" - makewrap="make" -else - echo "Klocwork Build Env" - makewrap="kwinject -o $KW_OUT_FILE make" -fi - -echo "make Makefile_wasm_app" -$makewrap -f Makefile_wasm_app - -echo "make Makefile_wasm_app_no_wasi" -$makewrap -f Makefile_wasm_app_no_wasi - -echo "completed." \ No newline at end of file diff --git a/samples/littlevgl/wasm-apps/src/display_indev.h b/samples/littlevgl/wasm-apps/src/display_indev.h deleted file mode 100644 index 9285699b6..000000000 --- a/samples/littlevgl/wasm-apps/src/display_indev.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef DISPLAY_INDEV_H_ -#define DISPLAY_INDEV_H_ -#include -#include - -#include "lvgl/lv_misc/lv_color.h" -#include "lvgl/lv_hal/lv_hal_indev.h" - -extern void -display_init(void); - -extern void -display_deinit(void); - -extern void -display_flush(int32_t x1, int32_t y1, int32_t x2, int32_t y2, - const lv_color_t *color); - -extern bool -display_input_read(lv_indev_data_t *data); - -extern void -display_vdb_write(void *buf, lv_coord_t buf_w, lv_coord_t x, lv_coord_t y, - lv_color_t *color, lv_opa_t opa); - -void -display_fill(int32_t x1, int32_t y1, int32_t x2, int32_t y2, - const lv_color_t *color); - -void -display_map(int32_t x1, int32_t y1, int32_t x2, int32_t y2, - const lv_color_t *color); - -extern uint32_t -time_get_ms(void); - -#endif diff --git a/samples/littlevgl/wasm-apps/src/main.c b/samples/littlevgl/wasm-apps/src/main.c deleted file mode 100644 index 8676d41b5..000000000 --- a/samples/littlevgl/wasm-apps/src/main.c +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -/** - * @file main - * - */ - -/********************* - * INCLUDES - *********************/ -#include -//#include -#include -#include "lvgl/lvgl.h" -#include "display_indev.h" -#include "wasm_app.h" -#include "wa-inc/timer_wasm_app.h" -/********************* - * DEFINES - *********************/ - -/********************** - * TYPEDEFS - **********************/ - -/********************** - * STATIC PROTOTYPES - **********************/ -static void -hal_init(void); -// static int tick_thread(void * data); -// static void memory_monitor(void * param); - -/********************** - * STATIC VARIABLES - **********************/ - -/********************** - * MACROS - **********************/ - -/********************** - * GLOBAL FUNCTIONS - **********************/ -uint32_t count = 0; -char count_str[11] = { 0 }; -lv_obj_t *hello_world_label; -lv_obj_t *count_label; -lv_obj_t *btn1; - -lv_obj_t *label_count1; -int label_count1_value = 0; -char label_count1_str[11] = { 0 }; - -void -timer1_update(user_timer_t timer1) -{ - if ((count % 100) == 0) { - snprintf(count_str, sizeof(count_str), "%d", count / 100); - lv_label_set_text(count_label, count_str); - } - lv_task_handler(); - ++count; -} - -static lv_res_t -btn_rel_action(lv_obj_t *btn) -{ - label_count1_value++; - snprintf(label_count1_str, sizeof(label_count1_str), "%d", - label_count1_value); - lv_label_set_text(label_count1, label_count1_str); - return LV_RES_OK; -} - -void -on_init() -{ - /* Initialize LittlevGL */ - lv_init(); - - /* Initialize the HAL (display, input devices, tick) for LittlevGL */ - hal_init(); - - hello_world_label = lv_label_create(lv_scr_act(), NULL); - lv_label_set_text(hello_world_label, "Hello world!"); - lv_obj_align(hello_world_label, NULL, LV_ALIGN_IN_TOP_LEFT, 0, 0); - - count_label = lv_label_create(lv_scr_act(), NULL); - lv_obj_align(count_label, NULL, LV_ALIGN_IN_TOP_MID, 0, 0); - - btn1 = lv_btn_create( - lv_scr_act(), - NULL); /* Create a button on the currently loaded screen */ - lv_btn_set_action(btn1, LV_BTN_ACTION_CLICK, - btn_rel_action); /* Set function to be called when the - button is released */ - lv_obj_align(btn1, NULL, LV_ALIGN_CENTER, 0, - 20); /* Align below the label */ - - /* Create a label on the button */ - lv_obj_t *btn_label = lv_label_create(btn1, NULL); - lv_label_set_text(btn_label, "Click ++"); - - label_count1 = lv_label_create(lv_scr_act(), NULL); - lv_label_set_text(label_count1, "0"); - lv_obj_align(label_count1, NULL, LV_ALIGN_IN_BOTTOM_MID, 0, 0); - - /* set up a timer */ - user_timer_t timer; - timer = api_timer_create(10, true, false, timer1_update); - if (timer) - api_timer_restart(timer, 10); - else - printf("Fail to create timer.\n"); -} - -/********************** - * STATIC FUNCTIONS - **********************/ - -/** - * Initialize the Hardware Abstraction Layer (HAL) for the Littlev graphics - * library - */ -void -display_flush_wrapper(int32_t x1, int32_t y1, int32_t x2, int32_t y2, - const lv_color_t *color_p) -{ - display_flush(x1, y1, x2, y2, color_p); - lv_flush_ready(); -} - -void -display_vdb_write_wrapper(uint8_t *buf, lv_coord_t buf_w, lv_coord_t x, - lv_coord_t y, lv_color_t color, lv_opa_t opa) -{ - display_vdb_write(buf, buf_w, x, y, &color, opa); -} - -void -display_fill_wrapper(int32_t x1, int32_t y1, int32_t x2, int32_t y2, - lv_color_t color) -{ - display_fill(x1, y1, x2, y2, &color); -} - -static void -hal_init(void) -{ - /* Add a display */ - lv_disp_drv_t disp_drv; - lv_disp_drv_init(&disp_drv); /* Basic initialization */ - disp_drv.disp_flush = - display_flush_wrapper; /* Used when `LV_VDB_SIZE != 0` in lv_conf.h - (buffered drawing) */ - disp_drv.disp_fill = - display_fill_wrapper; /* Used when `LV_VDB_SIZE == 0` in lv_conf.h - (unbuffered drawing) */ - disp_drv.disp_map = display_map; /* Used when `LV_VDB_SIZE == 0` in - lv_conf.h (unbuffered drawing) */ -#if LV_VDB_SIZE != 0 - disp_drv.vdb_wr = display_vdb_write_wrapper; -#endif - lv_disp_drv_register(&disp_drv); - - /* Add the mouse as input device - * Use the 'mouse' driver which reads the PC's mouse */ - // mouse_init(); - lv_indev_drv_t indev_drv; - lv_indev_drv_init(&indev_drv); /* Basic initialization */ - indev_drv.type = LV_INDEV_TYPE_POINTER; - indev_drv.read = - display_input_read; /* This function will be called periodically (by the - library) to get the mouse position and state */ - lv_indev_t *mouse_indev = lv_indev_drv_register(&indev_drv); -} - -/* Implement empry main function as wasi start function calls it */ -int -main(int argc, char **argv) -{ - (void)argc; - (void)argv; - return 0; -} diff --git a/samples/littlevgl/wasm-apps/src/system_header.h b/samples/littlevgl/wasm-apps/src/system_header.h deleted file mode 100644 index 59fd59aeb..000000000 --- a/samples/littlevgl/wasm-apps/src/system_header.h +++ /dev/null @@ -1,9 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include - -uint32_t -time_get_ms(void); diff --git a/samples/multi-module/CMakeLists.txt b/samples/multi-module/CMakeLists.txt index 17f4e1bcc..7b3fdb852 100644 --- a/samples/multi-module/CMakeLists.txt +++ b/samples/multi-module/CMakeLists.txt @@ -49,6 +49,8 @@ endif () if (NOT DEFINED WAMR_BUILD_JIT) set(WAMR_BUILD_JIT 0) endif () +set(WAMR_BUILD_SIMD 1) +set(WAMR_BUILD_REF_TYPES 1) set(WAMR_BUILD_LIBC_BUILTIN 1) set(WAMR_BUILD_LIBC_WASI 1) set(WAMR_BUILD_MULTI_MODULE 1) diff --git a/samples/sgx-ra/README.md b/samples/sgx-ra/README.md index 9270c96f1..179a074b8 100644 --- a/samples/sgx-ra/README.md +++ b/samples/sgx-ra/README.md @@ -18,6 +18,7 @@ The following commands are an example of the SGX environment installation on Ubu # https://download.01.org/intel-sgx/latest/linux-latest/distro $ cd $HOME $ OS_PLATFORM=ubuntu20.04 +$ OS_CODE_NAME=`lsb_release -sc` $ SGX_PLATFORM=$OS_PLATFORM-server $ SGX_RELEASE_VERSION=1.17 $ SGX_DRIVER_VERSION=1.41 @@ -39,7 +40,7 @@ $ chmod +x sgx_linux_x64_sdk_$SGX_SDK_VERSION.bin $ sudo ./sgx_linux_x64_sdk_$SGX_SDK_VERSION.bin --prefix /opt/intel # install SGX DCAP Library -$ echo 'deb [arch=amd64] https://download.01.org/intel-sgx/sgx_repo/ubuntu focal main' | sudo tee /etc/apt/sources.list.d/intel-sgx.list +$ echo "deb [arch=amd64] https://download.01.org/intel-sgx/sgx_repo/ubuntu $OS_CODE_NAME main" | sudo tee /etc/apt/sources.list.d/intel-sgx.list $ wget -O - https://download.01.org/intel-sgx/sgx_repo/ubuntu/intel-sgx-deb.key | sudo apt-key add $ sudo apt-get update $ sudo apt-get install -y libsgx-epid libsgx-quote-ex libsgx-dcap-ql libsgx-enclave-common-dev libsgx-dcap-ql-dev libsgx-dcap-default-qpl-dev libsgx-dcap-quote-verify-dev @@ -86,9 +87,9 @@ Intel provides an implementation of the cache mechanism. The following commands set up Intel PCCS. ```shell # install Node.js +$ sudo apt install -y curl cracklib-runtime $ curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - && sudo apt-get install -y nodejs # install PCCS software -$ sudo apt-get install -y cracklib-runtime $ sudo apt-get install -y sgx-dcap-pccs ``` @@ -140,7 +141,7 @@ Do you want to generate insecure HTTPS key and cert for PCCS service? [Y] (Y/N) Answer "Y" to this question. -### Provisioning a system into Intel PCCS +### Provisioning the current system's Intel SGX collateral into the PCCS Now that the PCCS is up and running, it's time to provision an Intel SGX-enabled platform. We use the tool `PCKIDRetrievalTool` to get the attestation collateral of the current machine. @@ -195,8 +196,75 @@ $ ./iwasm wasm-app/test.wasm The sample will print the evidence in JSON and the message: *Evidence is trusted.* +In case of validation issues expressed as a value of `0xeXXX`, the corresponding error reason is explained in [this header file](https://github.com/intel/SGXDataCenterAttestationPrimitives/blob/master/QuoteGeneration/quote_wrapper/common/inc/sgx_ql_lib_common.h). + +## Validate quotes on non-SGX platforms +Quotes created on an Intel SGX platform can also be verified on systems that do not support SGX (e.g., a different CPU architecture). +This scenario typically arises when deploying trusted applications in a cloud environment, which provides confidential computing. + +For that purpose, we are required to install a subset of Intel SGX libraries to support quote validation. +The steps below highlight how to set up such an environment. + + +### Intel SGX dependencies +```shell +$ OS_CODE_NAME=`lsb_release -sc` +# install SGX DCAP Library +$ echo "deb [arch=amd64] https://download.01.org/intel-sgx/sgx_repo/ubuntu $OS_CODE_NAME main" | sudo tee /etc/apt/sources.list.d/intel-sgx.list +$ wget -O - https://download.01.org/intel-sgx/sgx_repo/ubuntu/intel-sgx-deb.key | sudo apt-key add +$ sudo apt-get update +$ sudo apt-get install -y libsgx-quote-ex libsgx-dcap-ql libsgx-dcap-quote-verify libsgx-dcap-default-qpl +``` + +### Set up the Intel Provisioning Certification Caching Service (Intel PCCS) +Follow the steps described in the section _Set up the Intel Provisioning Certification Caching Service (Intel PCCS)_. + +### Runtime configuration +Follow the steps described in the section _Runtime configuration_. + +### Provisioning all the Intel SGX collateral into the PCCS +We must finally fetch and configure the SGX collaterals into the PCCS for all the SGX-enabled CPUs. + +```shell +# Set up the Intel PCCS administration tool +$ git clone https://github.com/intel/SGXDataCenterAttestationPrimitives.git +$ cd SGXDataCenterAttestationPrimitives/tools/PccsAdminTool +$ sudo apt-get install -y python3 python3-pip +$ pip3 install -r requirements.txt + +# Configuring the Intel PCCS. Input the PCS/PCCS password as requested. +# 1. Get registration data from PCCS service +./pccsadmin.py get +# 2. Fetch platform collateral data from Intel PCS based on the registration data +./pccsadmin.py fetch +# 3. Put platform collateral data or appraisal policy files to PCCS cache db +./pccsadmin.py put +# 4. Request PCCS to refresh certificates or collateral in cache database +./pccsadmin.py refresh +``` + +### Validation of the quotes +The Wasm application can then be modified to validate precomputed quotes using the exposed function `librats_verify`. + +Alternatively, the underlying library `librats` may be directly used if the non-SGX platforms do not execute WebAssembly code (without WAMR). +Examples are provided in the directory [non-sgx-verify/](non-sgx-verify/). + +### Claims validation +Once the runtime has validated the signature of the quote, the application must also check the other claims embedded in the quote to ensure they match their expected value. + +The documentation _Data Center Attestation Primitives: Library API_ describes in Section _3.8 Enclave Identity Checking_ defines the claims for the user to check. +Here is a summary of them: + +- **Enclave Identity Checking**: either check the hash _MRENCLAVE_ (the enclave identity) or _MRSIGNER_ and the _product id_ (the software provider identity). +- **Verify Attributes**: production enclaves should not have the _Debug_ flag set to 1. +- **Verify SSA Frame extended feature set** +- **Verify the ISV_SVN level of the enclave**: whenever there is a security update to an enclave, the ISV_SVN value should be increased to reflect the higher security level. +- **Verify that the ReportData contains the expected value**: This can be used to provide specific data from the enclave or it can be used to hold a hash of a larger block of data which is provided with the quote. Note that the verification of the quote signature confirms the integrity of the report data (and the rest of the REPORT body). + + ## Further readings - [Intel SGX Software Installation Guide For Linux OS](https://download.01.org/intel-sgx/latest/dcap-latest/linux/docs/Intel_SGX_SW_Installation_Guide_for_Linux.pdf) -- [Intel Software Guard Extensions (Intel® SGX) Data Center Attestation Primitives: Library API ](https://download.01.org/intel-sgx/latest/dcap-latest/linux/docs/Intel_SGX_ECDSA_QuoteLibReference_DCAP_API.pdf) +- [Intel Software Guard Extensions (Intel® SGX) Data Center Attestation Primitives: Library API](https://download.01.org/intel-sgx/latest/dcap-latest/linux/docs/Intel_SGX_ECDSA_QuoteLibReference_DCAP_API.pdf) - [Remote Attestation for Multi-Package Platforms using Intel SGX Datacenter Attestation Primitives (DCAP)](https://download.01.org/intel-sgx/latest/dcap-latest/linux/docs/Intel_SGX_DCAP_Multipackage_SW.pdf) +- [Documentation of the PCCS administration tool](https://github.com/intel/SGXDataCenterAttestationPrimitives/blob/master/tools/PccsAdminTool/README.txt) diff --git a/samples/sgx-ra/non-sgx-verify/README.md b/samples/sgx-ra/non-sgx-verify/README.md new file mode 100644 index 000000000..e4e9d87d4 --- /dev/null +++ b/samples/sgx-ra/non-sgx-verify/README.md @@ -0,0 +1,5 @@ +# Examples of evidence verification without Intel SGX +Intel SGX evidence generated using WAMR can be validated on trusted plaforms without Intel SGX, or an Intel processors. + +## Using C# +The sample [csharp/](csharp/) demonstrates such validation using C# as a managed language. diff --git a/samples/sgx-ra/non-sgx-verify/csharp/.gitignore b/samples/sgx-ra/non-sgx-verify/csharp/.gitignore new file mode 100644 index 000000000..27e48df5a --- /dev/null +++ b/samples/sgx-ra/non-sgx-verify/csharp/.gitignore @@ -0,0 +1,3 @@ +.idea/ +bin/ +obj/ diff --git a/samples/sgx-ra/non-sgx-verify/csharp/Program.cs b/samples/sgx-ra/non-sgx-verify/csharp/Program.cs new file mode 100644 index 000000000..6d7753a1b --- /dev/null +++ b/samples/sgx-ra/non-sgx-verify/csharp/Program.cs @@ -0,0 +1,108 @@ +/* + * Copyright (C) 2024 Intel Corporation. + * Copyright (C) 2024 University of Neuchatel, Switzerland. + * + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; + +// Set the reference values below +byte[] mrEnclaveReference = +{ + 0xDA, 0xE0, 0xDA, 0x2F, 0x8A, 0x53, 0xA0, 0xB4, 0x8F, 0x92, 0x6A, 0x3B, 0xC0, 0x48, 0xD6, 0xA9, + 0x67, 0xD4, 0x7C, 0x86, 0x19, 0x86, 0x76, 0x6F, 0x8F, 0x5A, 0xB1, 0xC0, 0xA8, 0xD8, 0x8E, 0x44 +}; +byte[] mrSignerReference = +{ + 0x83, 0xD7, 0x19, 0xE7, 0x7D, 0xEA, 0xCA, 0x14, 0x70, 0xF6, 0xBA, 0xF6, 0x2A, 0x4D, 0x77, 0x43, + 0x03, 0xC8, 0x99, 0xDB, 0x69, 0x02, 0x0F, 0x9C, 0x70, 0xEE, 0x1D, 0xFC, 0x08, 0xC7, 0xCE, 0x9E +}; +const ushort securityVersionReference = 0; +const ushort productIdReference = 0; +string nonce = "This is a sample.\0"; // Notice the \0 at the end, which is mandatory as C-strings are terminated with this char +string evidenceAsString = """{"type":"sgx_ecdsa","report_base64":"[..]","report_len":[..]}"""; +string wasmFilePath = "../build/wasm-app/test.wasm"; + +// Parse and compute the claims +EvidenceJson? evidenceAsJson = JsonSerializer.Deserialize(evidenceAsString, new JsonSerializerOptions +{ + PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower +}); +Debug.Assert(evidenceAsJson != null, "The evidence cannot be parsed."); + +byte[] wasmFileContent = await File.ReadAllBytesAsync(wasmFilePath); +byte[] nonceAsBytes = Encoding.UTF8.GetBytes(nonce); +byte[] computedUserData = await ComputeUserData(wasmFileContent, nonceAsBytes); +byte[] evidenceAsBytes = Convert.FromBase64String(evidenceAsJson.ReportBase64); +Evidence evidence = new(evidenceAsBytes); +int libRatsReturnValue = LibRats.VerifyEvidenceFromJson(evidenceAsString, await ComputeUserData(wasmFileContent, nonceAsBytes)); + +// Compare and display the results +Console.WriteLine($"User data, evidence: {BitConverter.ToString(evidence.UserData)}"); +Console.WriteLine($"User Data, computed: {BitConverter.ToString(computedUserData)}"); +Console.WriteLine($"Do the two user data match? {evidence.UserData.SequenceEqual(computedUserData)}"); +Console.WriteLine($"MrEnclave: {BitConverter.ToString(evidence.MrEnclave)}"); +Console.WriteLine($"Do the MrEnclave match? {mrEnclaveReference.SequenceEqual(evidence.MrEnclave)}"); +Console.WriteLine($"MrSigner: {BitConverter.ToString(evidence.MrSigner)}"); +Console.WriteLine($"Do the MrSigner match? {mrSignerReference.SequenceEqual(evidence.MrSigner)}"); +Console.WriteLine($"Security Version: {evidence.SecurityVersion}, expected: {securityVersionReference}"); +Console.WriteLine($"Product ID: {evidence.ProductId}, expected: {productIdReference}"); +Console.WriteLine($"VerifyJsonUsingLibrats returned: {libRatsReturnValue:X}"); + +// Compute the user data as computed by WAMR +static async ValueTask ComputeUserData(byte[] wasmFileContent, byte[] nonce) +{ + using var sha256 = SHA256.Create(); + var wasmFileContentHash = sha256.ComputeHash(wasmFileContent); + + using MemoryStream stream = new(); + await stream.WriteAsync(wasmFileContentHash); + await stream.WriteAsync(nonce); + stream.Position = 0; + + byte[] computedUserData = await sha256.ComputeHashAsync(stream); + return computedUserData; +} + +/// +/// The layout of the JSON is given by librats. +/// +class EvidenceJson +{ + public required string Type { get; init; } + public required string ReportBase64 { get; init; } + public required int ReportLen { get; init; } +} + +/// +/// The start of the _report_body_t struct from Intel SGX is at offset 0x30. +/// +/// +/// _report_body_t struct: https://github.com/intel/linux-sgx/blob/a1eeccba5a72b3b9b342569d2cc469ece106d3e9/common/inc/sgx_report.h#L93-L111 +/// Attestation flow: https://www.intel.com/content/www/us/en/developer/articles/code-sample/software-guard-extensions-remote-attestation-end-to-end-example.html +/// +class Evidence(byte[] evidenceAsBytes) +{ + public byte[] MrEnclave => evidenceAsBytes[0x70..0x90]; + public byte[] MrSigner => evidenceAsBytes[0xB0..0xD0]; + public ushort ProductId => BitConverter.ToUInt16(evidenceAsBytes.AsSpan(0x130, 2)); + public ushort SecurityVersion => BitConverter.ToUInt16(evidenceAsBytes.AsSpan(0x132, 2)); + public byte[] UserData => evidenceAsBytes[0x170..0x190]; +} + +static class LibRats +{ + /// + /// Verifies the evidence using librats native function. + /// + /// + /// Original signature: int librats_verify_evidence_from_json(const char *json_string, const uint8_t *hash); + /// + [DllImport("/usr/local/lib/librats/librats_lib.so", EntryPoint = "librats_verify_evidence_from_json")] + public static extern int VerifyEvidenceFromJson(string json, byte[] hash); +} diff --git a/samples/sgx-ra/non-sgx-verify/csharp/README.md b/samples/sgx-ra/non-sgx-verify/csharp/README.md new file mode 100644 index 000000000..689c8da08 --- /dev/null +++ b/samples/sgx-ra/non-sgx-verify/csharp/README.md @@ -0,0 +1,18 @@ +# Examples of evidence verification without Intel SGX using C# +This sample demonstrates how to validate WAMR-generated evidence without using an Intel SGX-enabled platform. +A typical use case is a Web service hosted on trusted premises. + +## Prerequisites + - [dotnet-sdk](https://learn.microsoft.com/en-us/dotnet/core/install/linux) (8+) + - [librats](https://github.com/inclavare-containers/librats) + - Intel infrastructure for validating evidence, [see here](../../README.md#validate-quotes-on-non-sgx-platforms) + +This sample has been tested on Linux Ubuntu 20.04+. +Any other Linux platforms should be supported. +This sample should also work on other OS, provided librats can be compiled on those other OS. + +## How to use + - Supply the reference values to consider trustworthy in [Program.cs](Program.cs#L15-L27). + - Generate a valid JSON evidence using WAMR on an Intel SGX-enabled platform. + - Fill in the JSON evidence in [Program.cs](Program.cs#L28). + - Run the command `dotnet run` in this directory. diff --git a/samples/sgx-ra/non-sgx-verify/csharp/VerifyEvidence.csproj b/samples/sgx-ra/non-sgx-verify/csharp/VerifyEvidence.csproj new file mode 100644 index 000000000..206b89a9a --- /dev/null +++ b/samples/sgx-ra/non-sgx-verify/csharp/VerifyEvidence.csproj @@ -0,0 +1,10 @@ + + + + Exe + net8.0 + enable + enable + + + diff --git a/samples/sgx-ra/wasm-app/main.c b/samples/sgx-ra/wasm-app/main.c index 6f506e06a..ab615056e 100644 --- a/samples/sgx-ra/wasm-app/main.c +++ b/samples/sgx-ra/wasm-app/main.c @@ -90,10 +90,24 @@ main(int argc, char **argv) hex_dump("User Data", evidence->user_data, SGX_USER_DATA_SIZE, 32); hex_dump("MRENCLAVE", evidence->mr_enclave, SGX_MEASUREMENT_SIZE, 32); hex_dump("MRSIGNER", evidence->mr_signer, SGX_MEASUREMENT_SIZE, 32); - printf("\n\tProduct ID:\t\t%u\n", evidence->product_id); - printf("\tSecurity Version:\t%u\n", evidence->security_version); - printf("\tAttributes.flags:\t%llu\n", evidence->att_flags); - printf("\tAttribute.xfrm:\t\t%llu\n", evidence->att_xfrm); + printf("\n\tProduct ID:\t\t\t\t%u\n", evidence->product_id); + printf("\tSecurity Version:\t\t\t%u\n", evidence->security_version); + printf("\tAttributes.flags:\t\t\t%llu\n", evidence->att_flags); + printf("\tAttributes.flags[INITTED]:\t\t%d\n", + (evidence->att_flags & SGX_FLAGS_INITTED) != 0); + printf("\tAttributes.flags[DEBUG]:\t\t%d\n", + (evidence->att_flags & SGX_FLAGS_DEBUG) != 0); + printf("\tAttributes.flags[MODE64BIT]:\t\t%d\n", + (evidence->att_flags & SGX_FLAGS_MODE64BIT) != 0); + printf("\tAttributes.flags[PROVISION_KEY]:\t%d\n", + (evidence->att_flags & SGX_FLAGS_PROVISION_KEY) != 0); + printf("\tAttributes.flags[EINITTOKEN_KEY]:\t%d\n", + (evidence->att_flags & SGX_FLAGS_EINITTOKEN_KEY) != 0); + printf("\tAttributes.flags[KSS]:\t\t\t%d\n", + (evidence->att_flags & SGX_FLAGS_KSS) != 0); + printf("\tAttributes.flags[AEX_NOTIFY]:\t\t%d\n", + (evidence->att_flags & SGX_FLAGS_AEX_NOTIFY) != 0); + printf("\tAttribute.xfrm:\t\t\t\t%llu\n", evidence->att_xfrm); rats_err = librats_verify((const char *)evidence_json, evidence->user_data); if (rats_err != 0) { diff --git a/samples/simple/.gitignore b/samples/simple/.gitignore deleted file mode 100644 index e2e7327cd..000000000 --- a/samples/simple/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/out diff --git a/samples/simple/CMakeLists.txt b/samples/simple/CMakeLists.txt deleted file mode 100644 index f3a0848fe..000000000 --- a/samples/simple/CMakeLists.txt +++ /dev/null @@ -1,40 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -cmake_minimum_required (VERSION 2.9) - -project (simple) - -################ wamr runtime settings ################ -message(STATUS "WAMR_BUILD_SDK_PROFILE=${WAMR_BUILD_SDK_PROFILE}") - -# Reset default linker flags -set (CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "") -set (CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS "") - -if ("$ENV{COLLECT_CODE_COVERAGE}" STREQUAL "1" OR COLLECT_CODE_COVERAGE EQUAL 1) - set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fprofile-arcs -ftest-coverage") - set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fprofile-arcs -ftest-coverage") -endif () - -set (WAMR_ROOT_DIR ${CMAKE_CURRENT_LIST_DIR}/../..) - -## use library and headers in the SDK -link_directories(${WAMR_ROOT_DIR}/wamr-sdk/out/${WAMR_BUILD_SDK_PROFILE}/runtime-sdk/lib) -include_directories( - ${WAMR_ROOT_DIR}/wamr-sdk/out/${WAMR_BUILD_SDK_PROFILE}/runtime-sdk/include - ${WAMR_ROOT_DIR}/core/shared/utils - ${WAMR_ROOT_DIR}/core/shared/platform/linux -) - -################ application related ################ - -include_directories(${CMAKE_CURRENT_LIST_DIR}/src) - -#Note: uncomment below line to use UART mode -#add_definitions (-DCONNECTION_UART) - -add_executable (simple src/main.c src/iwasm_main.c) -target_link_libraries (simple vmlib -lm -ldl -lpthread -lrt) - - diff --git a/samples/simple/README.md b/samples/simple/README.md deleted file mode 100644 index 5625212f9..000000000 --- a/samples/simple/README.md +++ /dev/null @@ -1,342 +0,0 @@ - - -"simple" sample introduction -============== - -This sample demonstrates following scenarios: - -- Use tool "host_tool" to remotely install/uninstall wasm applications from the WAMR runtime over either TCP socket or UART cable -- Inter-app communication programming models -- Communication between WASM applications and the remote app host_tool -- A number of WASM applications built on top of WAMR application framework API sets - - - -Directory structure ------------------------------- -``` -simple/ -├── build.sh -├── CMakeLists.txt -├── README.md -├── src -│   ├── ext_lib_export.c -│   ├── iwasm_main.c -│   └── main.c -└── wasm-apps - ├── connection.c - ├── event_publisher.c - ├── event_subscriber.c - ├── request_handler.c - ├── request_sender.c - ├── sensor.c - └── timer.c -``` - -- src/ext_lib_export.c
- This file is used to export native APIs. See the `The mechanism of exporting Native API to WASM application` section in WAMR README.md for detail. -- src/iwam_main.c
- This file is the implementation by platform integrator. It implements the interfaces that enable the application manager communicating with the host side. See `{WAMR_ROOT}/core/app-mgr/app-mgr-shared/app_manager_export.h` for the definition of the host interface. -## Set physical communication between device and remote - - - -``` -/* Interfaces of host communication */ -typedef struct host_interface { - host_init_func init; - host_send_fun send; - host_destroy_fun destroy; -} host_interface; - -``` -The `host_init_func` is called when the application manager starts up. And `host_send_fun` is called by the application manager to send data to the host. - -Define a global variable "interface" of the data structure: - -``` - -host_interface interface = { - .init = host_init, - .send = host_send, - .destroy = host_destroy -}; -``` -This interface is passed to application manager during the runtime startup: -``` -app_manager_startup(&interface); -``` - -> - -**Note:** The connection between simple and host_tool is TCP by default. The simple application works as a server and the host_tool works as a client. You can also use UART connection. To achieve this you have to uncomment the below line in CMakeLists.txt and rebuild. - -``` -#add_definitions (-DCONNECTION_UART)` -``` - -To run the UART based test, you have to set up a UART hardware connection between host_tool and the simple application. See the help of host_tool for how to specify UART device parameters. - - -Build the sample -============== -Execute the build.sh script then all binaries including wasm application files would be generated in 'out' directory. - -``` -$ ./build.sh -Enter build target profile (default=host-interp) --> -arm-interp -host-aot -host-interp -\>: - -``` - -Enter the profile name for starting your build. "host-***" profiles build the sample for executing on your development machine, and "arm-interp" profile will do cross building for ARM target platform. If "arm-interp" is entered, please ensure the ARM cross compiler toolchain is already installed in your development machine. Your should set *ARM_A7_COMPILER_DIR* and *ARM_A7_SDKTARGETSYSROOT* environment variable in your ~/.bashrc correctly. refer to the file [profiles/arm-interp/toolchain.cmake](./profiles/arm-interp/toolchain.cmake). - -``` -~/.bashrc: -export ARM_A7_COMPILER_DIR="/home/beihai/cross-toolchains/gcc-linaro-arm-linux-gnueabihf-4.7-2013.03-20130313_linux/bin" -export ARM_A7_SDKTARGETSYSROOT="/home/beihai/cross-toolchains/gcc-linaro-arm-linux-gnueabihf-4.7-2013.03-20130313_linux/arm-linux-gnueabihf/libc" - -notes: please set the value to the actual path of your cross toolchain. -``` - -If you need to create additional profile for customizing your runtime, application framework or the target platforms, a new subfolder can be created under the *profiles* folder, and place your own version of "toolchain.cmake" and "wamr_config_simple.cmake" in it. - -``` -$wamr-root/samples/simple/profiles$ ls -arm-interp host-aot host-interp -$wamr-root/samples/simple/profiles$ ls arm-interp/ -toolchain.cmake wamr_config_simple.cmake - -``` - - - - - -**Out directory structure** - -``` -out/ -├── host_tool -├── simple -└── wasm-apps - ├── connection.wasm - ├── event_publisher.wasm - ├── event_subscriber.wasm - ├── request_handler.wasm - ├── request_sender.wasm - ├── sensor.wasm - └── timer.wasm -``` - -- host_tool: - A small testing tool to interact with WAMR. See the usage of this tool by executing "./host_tool -h". - `./host_tool -h` - -- simple: - A simple testing tool running on the host side that interact with WAMR. It is used to install, uninstall and query WASM applications in WAMR, and send request or subscribe event, etc. See the usage of this application by executing "./simple -h". - `./simple -h` -> - -Run the sample -========================== -- Enter the out directory -``` -$ cd ./out/ -``` - -- Startup the 'simple' process works in TCP server mode and you would see "App Manager started." is printed. -``` -$ ./simple -s -App Manager started. -``` - -- Query all installed applications -``` -$ ./host_tool -q - -response status 69 -{ - "num": 0 -} -``` - -The `69` stands for response code SUCCESS. The payload is printed with JSON format where the `num` stands for application installations number and value `0` means currently no application is installed yet. - -- Install the request handler wasm application
-``` -$ ./host_tool -i request_handler -f ./wasm-apps/request_handler.wasm - -response status 65 -``` -Now the request handler application is running and waiting for host or other wasm application to send a request. - -- Query again -``` -$ ./host_tool -q - -response status 69 -{ - "num": 1, - "applet1": "request_handler", - "heap1": 49152 -} -``` -In the payload, we can see `num` is 1 which means 1 application is installed. `applet1`stands for the name of the 1st application. `heap1` stands for the heap size of the 1st application. - -- Send request from host to specific wasm application -``` -$ ./host_tool -r /app/request_handler/url1 -A GET - -response status 69 -{ - "key1": "value1", - "key2": "value2" -} -``` - -We can see a response with status `69` and a payload is received. - -Output of simple application: -``` -connection established! -Send request to applet: request_handler -Send request to app request_handler success. -App request_handler got request, url url1, action 1 -[resp] ### user resource 1 handler called -sent 150 bytes to host -Wasm app process request success. -``` - -- Send a general request from host (not specify target application name)
-``` -$ ./host_tool -r /url1 -A GET - -response status 69 -{ - "key1": "value1", - "key2": "value2" -} -``` - -Output of simple application: -``` -connection established! -Send request to app request_handler success. -App request_handler got request, url /url1, action 1 -[resp] ### user resource 1 handler called -sent 150 bytes to host -Wasm app process request success. -``` - -- Install the event publisher wasm application -``` -$ ./host_tool -i pub -f ./wasm-apps/event_publisher.wasm - -response status 65 -``` - -- Subscribe event by host_tool
-``` -$ ./host_tool -s /alert/overheat -a 3000 - -response status 69 - -received an event alert/overheat -{ - "warning": "temperature is over high" -} -received an event alert/overheat -{ - "warning": "temperature is over high" -} -received an event alert/overheat -{ - "warning": "temperature is over high" -} -received an event alert/overheat -{ - "warning": "temperature is over high" -} -``` -We can see 4 `alert/overheat` events are received in 3 seconds which is published by the `pub` application. - -Output of simple -``` -connection established! -am_register_event adding url:(alert/overheat) -client: -3 registered event (alert/overheat) -sent 16 bytes to host -sent 142 bytes to host -sent 142 bytes to host -sent 142 bytes to host -sent 142 bytes to host -``` -- Install the event subscriber wasm application
-``` -$ ./host_tool -i sub -f ./wasm-apps/event_subscriber.wasm - -response status 65 -``` -The `sub` application is installed. - -Output of simple -``` -connection established! -Install WASM app success! -WASM app 'sub' started -am_register_event adding url:(alert/overheat) -client: 3 registered event (alert/overheat) -sent 16 bytes to host -Send request to app sub success. -App sub got request, url alert/overheat, action 6 -### user over heat event handler called -Attribute container dump: -Tag: -Attribute list: - key: warning, type: string, value: temperature is over high - -Wasm app process request success. -``` - -We can see the `sub` application receives the `alert/overheat` event and dumps it out.
-At device side, the event is represented by an attribute container which contains key-value pairs like below: -``` -Attribute container dump: -Tag: -Attribute list: - key: warning, type: string, value: temperature is over high -``` -`warning` is the key's name. `string` means this is a string value and `temperature is over high` is the value. - -- Uninstall the wasm application
-``` -$ ./host_tool -u request_handler - -response status 66 - -$ ./host_tool -u pub - -response status 66 - -$ ./host_tool -u sub - -response status 66 -``` - -- Query again
-``` -$ ./host_tool -q - -response status 69 -{ - "num": 0 -} -``` - - >**Note:** Here we only installed part of the sample WASM applications. You can try others by yourself. - - >**Note:** You have to manually kill the simple process by Ctrl+C after use. diff --git a/samples/simple/build.sh b/samples/simple/build.sh deleted file mode 100755 index 9d9d1874d..000000000 --- a/samples/simple/build.sh +++ /dev/null @@ -1,166 +0,0 @@ -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -#!/bin/bash - -CURR_DIR=$PWD -WAMR_DIR=${PWD}/../.. -OUT_DIR=${PWD}/out -BUILD_DIR=${PWD}/build - -IWASM_ROOT=${PWD}/../../core/iwasm -APP_FRAMEWORK_DIR=${PWD}/../../core/app-framework -NATIVE_LIBS=${APP_FRAMEWORK_DIR}/app-native-shared -APP_LIB_SRC="${APP_FRAMEWORK_DIR}/base/app/*.c ${APP_FRAMEWORK_DIR}/sensor/app/*.c \ - ${APP_FRAMEWORK_DIR}/connection/app/*.c ${NATIVE_LIBS}/*.c" -WASM_APPS=${PWD}/wasm-apps -CLEAN= -CM_BUILD_TYPE="-DCMAKE_BUILD_TYPE=Debug" -CM_TOOLCHAIN="" - -usage () -{ - echo "build.sh [options]" - echo " -p [profile]" - echo " -d [target]" - echo " -c, rebuild SDK" - exit 1 -} - - -while getopts "p:dch" opt -do - case $opt in - p) - PROFILE=$OPTARG - ;; - d) - CM_BUILD_TYPE="-DCMAKE_BUILD_TYPE=Debug" - ;; - c) - CLEAN="TRUE" - ;; - h) - usage - exit 1; - ;; - ?) - echo "Unknown arg: $arg" - usage - exit 1 - ;; - esac -done - - -if [ "$CLEAN" = "TRUE" ]; then - rm -rf $CURR_DIR/cmake-build -fi - - -while [ ! -n "$PROFILE" ] -do - support_profiles=`ls -l "profiles/" |grep '^d' | awk '{print $9}'` - read -p "Enter build target profile (default=host-interp) --> -$support_profiles -\>:" read_platform - if [ ! -n "$read_platform" ]; then - PROFILE="host-interp" - else - PROFILE=$read_platform - fi -done - -ARG_TOOLCHAIN="" -TOOL_CHAIN_FILE=$CURR_DIR/profiles/$PROFILE/toolchain.cmake -if [ -f $TOOL_CHAIN_FILE ]; then - CM_TOOLCHAIN="-DCMAKE_TOOLCHAIN_FILE=$TOOL_CHAIN_FILE" - ARG_TOOLCHAIN="-t $TOOL_CHAIN_FILE" - echo "toolchain file: $TOOL_CHAIN_FILE" -fi - - -SDK_CONFIG_FILE=$CURR_DIR/profiles/$PROFILE/wamr_config_simple.cmake -if [ ! -f $SDK_CONFIG_FILE ]; then - echo "SDK config file [$SDK_CONFIG_FILE] doesn't exit. quit.." - exit 1 -fi - - - -rm -rf ${OUT_DIR} -mkdir ${OUT_DIR} -mkdir ${OUT_DIR}/wasm-apps - -cd ${WAMR_DIR}/core/shared/mem-alloc - -PROFILE="simple-$PROFILE" - - -echo "#####################build wamr sdk" -cd ${WAMR_DIR}/wamr-sdk -./build_sdk.sh -n $PROFILE -x $SDK_CONFIG_FILE $ARG_TOOLCHAIN -[ $? -eq 0 ] || exit $? - - -echo "#####################build simple project" -cd ${CURR_DIR} -mkdir -p cmake-build/$PROFILE -cd cmake-build/$PROFILE -cmake ../.. -DWAMR_BUILD_SDK_PROFILE=$PROFILE $CM_TOOLCHAIN $CM_BUILD_TYPE -make -if [ $? != 0 ];then - echo "BUILD_FAIL simple exit as $?\n" - exit 2 -fi -cp -a simple ${OUT_DIR} -echo "#####################build simple project success" - -echo -e "\n\n" -echo "#####################build host-tool" -cd ${WAMR_DIR}/test-tools/host-tool -mkdir -p bin -cd bin -cmake .. $CM_TOOLCHAIN $CM_BUILD_TYPE -make -if [ $? != 0 ];then - echo "BUILD_FAIL host tool exit as $?\n" - exit 2 -fi -cp host_tool ${OUT_DIR} -echo "#####################build host-tool success" - -echo -e "\n\n" -echo "#####################build wasm apps" - -cd ${WASM_APPS} - -for i in `ls *.c` -do -APP_SRC="$i" -OUT_FILE=${i%.*}.wasm - -/opt/wasi-sdk/bin/clang \ - -I${WAMR_DIR}/wamr-sdk/out/$PROFILE/app-sdk/wamr-app-framework/include \ - -L${WAMR_DIR}/wamr-sdk/out/$PROFILE/app-sdk/wamr-app-framework/lib \ - -lapp_framework \ - --target=wasm32 -O3 -z stack-size=4096 -Wl,--initial-memory=65536 \ - --sysroot=${WAMR_DIR}/wamr-sdk/out/$PROFILE/app-sdk/libc-builtin-sysroot \ - -Wl,--allow-undefined-file=${WAMR_DIR}/wamr-sdk/out/$PROFILE/app-sdk/libc-builtin-sysroot/share/defined-symbols.txt \ - -Wl,--strip-all,--no-entry -nostdlib \ - -Wl,--export=on_init -Wl,--export=on_destroy \ - -Wl,--export=on_request -Wl,--export=on_response \ - -Wl,--export=on_sensor_event -Wl,--export=on_timer_callback \ - -Wl,--export=on_connection_data \ - -Wl,--export=__heap_base -Wl,--export=__data_end \ - -o ${OUT_DIR}/wasm-apps/${OUT_FILE} ${APP_SRC} -if [ -f ${OUT_DIR}/wasm-apps/${OUT_FILE} ]; then - echo "build ${OUT_FILE} success" -else - echo "build ${OUT_FILE} fail" -fi -done - -echo "#####################build wasm apps done" diff --git a/samples/simple/profiles/arm-interp/toolchain.cmake b/samples/simple/profiles/arm-interp/toolchain.cmake deleted file mode 100644 index 604141d0a..000000000 --- a/samples/simple/profiles/arm-interp/toolchain.cmake +++ /dev/null @@ -1,40 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -INCLUDE(CMakeForceCompiler) - -SET(CMAKE_SYSTEM_NAME Linux) # this one is important -SET(CMAKE_SYSTEM_VERSION 1) # this one not so much - -message(STATUS "*** ARM A7 toolchain file ***") -set(CMAKE_VERBOSE_MAKEFILE ON) - -set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D_GNU_SOURCE") -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D_GNU_SOURCE") - - -if (NOT $ENV{ARM_A7_COMPILER_DIR} STREQUAL "") - SET (toolchain_sdk_dir $ENV{ARM_A7_COMPILER_DIR}/) -endif () - -if (NOT $ENV{ARM_A7_SDKTARGETSYSROOT} STREQUAL "") - SET(SDKTARGETSYSROOT $ENV{ARM_A7_SDKTARGETSYSROOT}) - #SET(CMAKE_SYSROOT SDKTARGETSYSROOT) -endif () - -message(STATUS "SDKTARGETSYSROOT=${SDKTARGETSYSROOT}") -message(STATUS "toolchain_sdk_dir=${toolchain_sdk_dir}") - -SET(CMAKE_C_COMPILER ${toolchain_sdk_dir}arm-linux-gnueabihf-gcc) -SET(CMAKE_CXX_COMPILER ${toolchain_sdk_dir}arm-linux-gnueabihf-g++) - - -# this is the file system root of the target -SET(CMAKE_FIND_ROOT_PATH ${SDKTARGETSYSROOT}) - -# search for programs in the build host directories -SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) - -# for libraries and headers in the target directories -SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) -SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) - diff --git a/samples/simple/profiles/arm-interp/wamr_config_simple.cmake b/samples/simple/profiles/arm-interp/wamr_config_simple.cmake deleted file mode 100644 index 90bb2f8d1..000000000 --- a/samples/simple/profiles/arm-interp/wamr_config_simple.cmake +++ /dev/null @@ -1,11 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -set (WAMR_BUILD_PLATFORM "linux") -set (WAMR_BUILD_TARGET ARM) -set (WAMR_BUILD_INTERP 1) -set (WAMR_BUILD_AOT 0) -set (WAMR_BUILD_JIT 0) -set (WAMR_BUILD_LIBC_BUILTIN 1) -set (WAMR_BUILD_LIBC_WASI 0) -set (WAMR_BUILD_APP_FRAMEWORK 1) -set (WAMR_BUILD_APP_LIST WAMR_APP_BUILD_BASE WAMR_APP_BUILD_CONNECTION WAMR_APP_BUILD_SENSOR) diff --git a/samples/simple/profiles/arm64-aot/toolchain.cmake b/samples/simple/profiles/arm64-aot/toolchain.cmake deleted file mode 100644 index 182504fea..000000000 --- a/samples/simple/profiles/arm64-aot/toolchain.cmake +++ /dev/null @@ -1,38 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -INCLUDE(CMakeForceCompiler) - -SET(CMAKE_SYSTEM_NAME Linux) # this one is important -SET(CMAKE_SYSTEM_VERSION 1) # this one not so much - -message(STATUS "*** ARM A7 toolchain file ***") -set(CMAKE_VERBOSE_MAKEFILE ON) - -set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D_GNU_SOURCE") -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D_GNU_SOURCE") - - -if (NOT $ENV{ARM_A7_COMPILER_DIR} STREQUAL "") - SET (toolchain_sdk_dir $ENV{ARM_A7_COMPILER_DIR}/) -endif () - -if (NOT $ENV{ARM_A7_SDKTARGETSYSROOT} STREQUAL "") - SET(SDKTARGETSYSROOT $ENV{ARM_A7_SDKTARGETSYSROOT}) -endif () - -message(STATUS "SDKTARGETSYSROOT=${SDKTARGETSYSROOT}") -message(STATUS "toolchain_sdk_dir=${toolchain_sdk_dir}") - -SET(CMAKE_C_COMPILER ${toolchain_sdk_dir}aarch64-linux-gnu-gcc) -SET(CMAKE_CXX_COMPILER ${toolchain_sdk_dir}aarch64-linux-gnu-g++) - - -# this is the file system root of the target -SET(CMAKE_FIND_ROOT_PATH ${SDKTARGETSYSROOT}) - -# search for programs in the build host directories -SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) - -# for libraries and headers in the target directories -SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) -SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) diff --git a/samples/simple/profiles/arm64-aot/wamr_config_simple.cmake b/samples/simple/profiles/arm64-aot/wamr_config_simple.cmake deleted file mode 100644 index 7e6604885..000000000 --- a/samples/simple/profiles/arm64-aot/wamr_config_simple.cmake +++ /dev/null @@ -1,12 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -set (WAMR_BUILD_PLATFORM "linux") -set (WAMR_BUILD_TARGET AARCH64) -set (WAMR_BUILD_INTERP 1) -set (WAMR_BUILD_AOT 1) -set (WAMR_BUILD_JIT 0) -set (WAMR_BUILD_SIMD 0) -set (WAMR_BUILD_LIBC_BUILTIN 1) -set (WAMR_BUILD_LIBC_WASI 0) -set (WAMR_BUILD_APP_FRAMEWORK 1) -set (WAMR_BUILD_APP_LIST WAMR_APP_BUILD_BASE WAMR_APP_BUILD_CONNECTION WAMR_APP_BUILD_SENSOR) diff --git a/samples/simple/profiles/arm64-interp/toolchain.cmake b/samples/simple/profiles/arm64-interp/toolchain.cmake deleted file mode 100644 index 182504fea..000000000 --- a/samples/simple/profiles/arm64-interp/toolchain.cmake +++ /dev/null @@ -1,38 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -INCLUDE(CMakeForceCompiler) - -SET(CMAKE_SYSTEM_NAME Linux) # this one is important -SET(CMAKE_SYSTEM_VERSION 1) # this one not so much - -message(STATUS "*** ARM A7 toolchain file ***") -set(CMAKE_VERBOSE_MAKEFILE ON) - -set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D_GNU_SOURCE") -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D_GNU_SOURCE") - - -if (NOT $ENV{ARM_A7_COMPILER_DIR} STREQUAL "") - SET (toolchain_sdk_dir $ENV{ARM_A7_COMPILER_DIR}/) -endif () - -if (NOT $ENV{ARM_A7_SDKTARGETSYSROOT} STREQUAL "") - SET(SDKTARGETSYSROOT $ENV{ARM_A7_SDKTARGETSYSROOT}) -endif () - -message(STATUS "SDKTARGETSYSROOT=${SDKTARGETSYSROOT}") -message(STATUS "toolchain_sdk_dir=${toolchain_sdk_dir}") - -SET(CMAKE_C_COMPILER ${toolchain_sdk_dir}aarch64-linux-gnu-gcc) -SET(CMAKE_CXX_COMPILER ${toolchain_sdk_dir}aarch64-linux-gnu-g++) - - -# this is the file system root of the target -SET(CMAKE_FIND_ROOT_PATH ${SDKTARGETSYSROOT}) - -# search for programs in the build host directories -SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) - -# for libraries and headers in the target directories -SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) -SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) diff --git a/samples/simple/profiles/arm64-interp/wamr_config_simple.cmake b/samples/simple/profiles/arm64-interp/wamr_config_simple.cmake deleted file mode 100644 index 13fb9ac13..000000000 --- a/samples/simple/profiles/arm64-interp/wamr_config_simple.cmake +++ /dev/null @@ -1,12 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -set (WAMR_BUILD_PLATFORM "linux") -set (WAMR_BUILD_TARGET AARCH64) -set (WAMR_BUILD_INTERP 1) -set (WAMR_BUILD_AOT 0) -set (WAMR_BUILD_JIT 0) -set (WAMR_BUILD_SIMD 0) -set (WAMR_BUILD_LIBC_BUILTIN 1) -set (WAMR_BUILD_LIBC_WASI 0) -set (WAMR_BUILD_APP_FRAMEWORK 1) -set (WAMR_BUILD_APP_LIST WAMR_APP_BUILD_BASE WAMR_APP_BUILD_CONNECTION WAMR_APP_BUILD_SENSOR) diff --git a/samples/simple/profiles/host-aot/wamr_config_simple.cmake b/samples/simple/profiles/host-aot/wamr_config_simple.cmake deleted file mode 100644 index 1f8cf9f8f..000000000 --- a/samples/simple/profiles/host-aot/wamr_config_simple.cmake +++ /dev/null @@ -1,11 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -set (WAMR_BUILD_PLATFORM "linux") -set (WAMR_BUILD_TARGET X86_64) -set (WAMR_BUILD_INTERP 1) -set (WAMR_BUILD_AOT 1) -set (WAMR_BUILD_JIT 0) -set (WAMR_BUILD_LIBC_BUILTIN 1) -set (WAMR_BUILD_LIBC_WASI 0) -set (WAMR_BUILD_APP_FRAMEWORK 1) -set (WAMR_BUILD_APP_LIST WAMR_APP_BUILD_BASE WAMR_APP_BUILD_CONNECTION WAMR_APP_BUILD_SENSOR) diff --git a/samples/simple/profiles/host-interp/wamr_config_simple.cmake b/samples/simple/profiles/host-interp/wamr_config_simple.cmake deleted file mode 100644 index 1f8cf9f8f..000000000 --- a/samples/simple/profiles/host-interp/wamr_config_simple.cmake +++ /dev/null @@ -1,11 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -set (WAMR_BUILD_PLATFORM "linux") -set (WAMR_BUILD_TARGET X86_64) -set (WAMR_BUILD_INTERP 1) -set (WAMR_BUILD_AOT 1) -set (WAMR_BUILD_JIT 0) -set (WAMR_BUILD_LIBC_BUILTIN 1) -set (WAMR_BUILD_LIBC_WASI 0) -set (WAMR_BUILD_APP_FRAMEWORK 1) -set (WAMR_BUILD_APP_LIST WAMR_APP_BUILD_BASE WAMR_APP_BUILD_CONNECTION WAMR_APP_BUILD_SENSOR) diff --git a/samples/simple/profiles/macos-interp/wamr_config_simple.cmake b/samples/simple/profiles/macos-interp/wamr_config_simple.cmake deleted file mode 100644 index d13c06d97..000000000 --- a/samples/simple/profiles/macos-interp/wamr_config_simple.cmake +++ /dev/null @@ -1,11 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -set (WAMR_BUILD_PLATFORM "darwin") -set (WAMR_BUILD_TARGET X86_64) -set (WAMR_BUILD_INTERP 1) -set (WAMR_BUILD_AOT 1) -set (WAMR_BUILD_JIT 0) -set (WAMR_BUILD_LIBC_BUILTIN 1) -set (WAMR_BUILD_LIBC_WASI 0) -set (WAMR_BUILD_APP_FRAMEWORK 1) -set (WAMR_BUILD_APP_LIST WAMR_APP_BUILD_BASE WAMR_APP_BUILD_CONNECTION WAMR_APP_BUILD_SENSOR) diff --git a/samples/simple/sample_test_run.py b/samples/simple/sample_test_run.py deleted file mode 100755 index 09c36db5e..000000000 --- a/samples/simple/sample_test_run.py +++ /dev/null @@ -1,224 +0,0 @@ -#!/usr/bin/env python3 -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -import argparse -import shlex -import subprocess -import sys -import time -import traceback -import glob - -WAMRC_CMD = "../../wamr-compiler/build/wamrc" - -def compile_wasm_files_to_aot(wasm_apps_dir): - wasm_files = glob.glob(wasm_apps_dir + "/*.wasm") - print("Compile wasm app into aot files") - for wasm_file in wasm_files: - aot_file = wasm_file[0 : len(wasm_file) - 5] + ".aot"; - cmd = [ WAMRC_CMD, "-o", aot_file, wasm_file ] - subprocess.check_call(cmd) - -def start_server(cwd): - """ - Startup the 'simple' process works in TCP server mode - """ - app_server = subprocess.Popen(shlex.split("./simple -s "), cwd=cwd) - return app_server - - -def query_installed_application(cwd): - """ - Query all installed applications - """ - qry_prc = subprocess.run( - shlex.split("./host_tool -q"), cwd=cwd, check=False, capture_output=True - ) - assert qry_prc.returncode == 69 - return qry_prc.returncode, qry_prc.stdout - - -def install_wasm_application(wasm_name, wasm_file, cwd): - """ - Install a wasm application - """ - inst_prc = subprocess.run( - shlex.split(f"./host_tool -i {wasm_name} -f {wasm_file}"), - cwd=cwd, - check=False, - capture_output=True, - ) - assert inst_prc.returncode == 65 - return inst_prc.returncode, inst_prc.stdout - - -def uninstall_wasm_application(wasm_name, cwd): - """ - Uninstall a wasm application - """ - - unst_prc = subprocess.run( - shlex.split(f"./host_tool -u {wasm_name}"), - cwd=cwd, - check=False, - capture_output=True, - ) - assert unst_prc.returncode == 66 - return unst_prc.returncode, unst_prc.stdout - - -def send_get_to_wasm_application(wasm_name, url, cwd): - """ - send a request (GET) from host to an applicaton - """ - qry_prc = subprocess.run( - shlex.split(f"./host_tool -r /app/{wasm_name}{url} -A GET"), - cwd=cwd, - check=False, - capture_output=True, - ) - assert qry_prc.returncode == 69 - return qry_prc.returncode, qry_prc.stdout - - -def main(): - """ - GO!GO!!GO!!! - """ - parser = argparse.ArgumentParser(description="run the sample and examine outputs") - parser.add_argument("working_directory", type=str) - parser.add_argument("--aot", action='store_true', help="Test with AOT") - args = parser.parse_args() - - test_aot = False - suffix = ".wasm" - if not args.aot: - print("Test with interpreter mode") - else: - print("Test with AOT mode") - test_aot = True - suffix = ".aot" - wasm_apps_dir = args.working_directory + "/wasm-apps" - compile_wasm_files_to_aot(wasm_apps_dir) - - ret = 1 - app_server = None - try: - app_server = start_server(args.working_directory) - - # wait for a second - time.sleep(1) - - print("--> Install timer" + suffix + "...") - install_wasm_application( - "timer", "./wasm-apps/timer" + suffix, args.working_directory - ) - - # wait for a second - time.sleep(3) - - print("--> Query all installed applications...") - query_installed_application(args.working_directory) - - print("--> Install event_publisher" + suffix + "...") - install_wasm_application( - "event_publisher", - "./wasm-apps/event_publisher" + suffix, - args.working_directory, - ) - - print("--> Install event_subscriber" + suffix + "...") - install_wasm_application( - "event_subscriber", - "./wasm-apps/event_subscriber" + suffix, - args.working_directory, - ) - - print("--> Query all installed applications...") - query_installed_application(args.working_directory) - - print("--> Uninstall timer" + suffix + "...") - uninstall_wasm_application("timer", args.working_directory) - - print("--> Query all installed applications...") - query_installed_application(args.working_directory) - - print("--> Uninstall event_publisher" + suffix + "...") - uninstall_wasm_application( - "event_publisher", - args.working_directory, - ) - - print("--> Uninstall event_subscriber" + suffix + "...") - uninstall_wasm_application( - "event_subscriber", - args.working_directory, - ) - - print("--> Query all installed applications...") - query_installed_application(args.working_directory) - - print("--> Install request_handler" + suffix + "...") - install_wasm_application( - "request_handler", - "./wasm-apps/request_handler" + suffix, - args.working_directory, - ) - - print("--> Query again...") - query_installed_application(args.working_directory) - - print("--> Install request_sender" + suffix + "...") - install_wasm_application( - "request_sender", - "./wasm-apps/request_sender" + suffix, - args.working_directory, - ) - - print("--> Send GET to the Wasm application named request_handler...") - send_get_to_wasm_application("request_handler", "/url1", args.working_directory) - - print("--> Uninstall request_handler" + suffix + "...") - uninstall_wasm_application( - "request_handler", - args.working_directory, - ) - - print("--> Uninstall request_sender" + suffix + "...") - uninstall_wasm_application( - "request_sender", - args.working_directory, - ) - - # Install a wasm app named "__exit_app_manager__" just to make app manager exit - # while the wasm app is uninstalled, so as to collect the code coverage data. - # Only available when collecting code coverage is enabled. - print("--> Install timer" + suffix + "...") - install_wasm_application( - "__exit_app_manager__", "./wasm-apps/timer" + suffix, args.working_directory - ) - - print("--> Uninstall timer" + suffix + "...") - uninstall_wasm_application( - "__exit_app_manager__", - args.working_directory, - ) - - # wait for a second - time.sleep(1) - - print("--> All pass") - ret = 0 - except AssertionError: - traceback.print_exc() - finally: - app_server.kill() - - return ret - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/samples/simple/src/iwasm_main.c b/samples/simple/src/iwasm_main.c deleted file mode 100644 index 36fb35b12..000000000 --- a/samples/simple/src/iwasm_main.c +++ /dev/null @@ -1,568 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef CONNECTION_UART -#include -#include -#include -#include -#else -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "runtime_lib.h" -#include "runtime_timer.h" -#include "native_interface.h" -#include "app_manager_export.h" -#include "bh_platform.h" -#include "runtime_sensor.h" -#include "bi-inc/attr_container.h" -#include "module_wasm_app.h" -#include "wasm_export.h" - -#define MAX 2048 - -#ifndef CONNECTION_UART -#define SA struct sockaddr -static char *host_address = "127.0.0.1"; -static int port = 8888; -#else -static char *uart_device = "/dev/ttyS2"; -static int baudrate = B115200; -#endif - -extern bool -init_sensor_framework(); -extern void -exit_sensor_framework(); -extern void -exit_connection_framework(); -extern int -aee_host_msg_callback(void *msg, uint32_t msg_len); -extern bool -init_connection_framework(); - -#ifndef CONNECTION_UART -int listenfd = -1; -int sockfd = -1; -static pthread_mutex_t sock_lock = PTHREAD_MUTEX_INITIALIZER; -#else -int uartfd = -1; -#endif - -#ifndef CONNECTION_UART -static bool server_mode = false; - -// Function designed for chat between client and server. -void * -func(void *arg) -{ - char buff[MAX]; - int n; - struct sockaddr_in servaddr; - - while (1) { - if (sockfd != -1) - close(sockfd); - // socket create and verification - sockfd = socket(AF_INET, SOCK_STREAM, 0); - if (sockfd == -1) { - printf("socket creation failed...\n"); - return NULL; - } - else - printf("Socket successfully created..\n"); - bzero(&servaddr, sizeof(servaddr)); - // assign IP, PORT - servaddr.sin_family = AF_INET; - servaddr.sin_addr.s_addr = inet_addr(host_address); - servaddr.sin_port = htons(port); - - // connect the client socket to server socket - if (connect(sockfd, (SA *)&servaddr, sizeof(servaddr)) != 0) { - printf("connection with the server failed...\n"); - sleep(10); - continue; - } - else { - printf("connected to the server..\n"); - } - - // infinite loop for chat - for (;;) { - bzero(buff, MAX); - - // read the message from client and copy it in buffer - n = read(sockfd, buff, sizeof(buff)); - // print buffer which contains the client contents - // fprintf(stderr, "recieved %d bytes from host: %s", n, buff); - - // socket disconnected - if (n <= 0) - break; - - aee_host_msg_callback(buff, n); - } - } - - // After chatting close the socket - close(sockfd); -} - -static bool -host_init() -{ - return true; -} - -int -host_send(void *ctx, const char *buf, int size) -{ - int ret; - - if (pthread_mutex_trylock(&sock_lock) == 0) { - if (sockfd == -1) { - pthread_mutex_unlock(&sock_lock); - return 0; - } - - ret = write(sockfd, buf, size); - - pthread_mutex_unlock(&sock_lock); - return ret; - } - - return -1; -} - -void -host_destroy() -{ - if (server_mode) - close(listenfd); - - pthread_mutex_lock(&sock_lock); - close(sockfd); - pthread_mutex_unlock(&sock_lock); -} - -/* clang-format off */ -host_interface interface = { - .init = host_init, - .send = host_send, - .destroy = host_destroy -}; -/* clang-format on */ - -/* Change it to 1 when fuzzing test */ -#define WASM_ENABLE_FUZZ_TEST 0 - -void * -func_server_mode(void *arg) -{ - int clilent; - struct sockaddr_in serv_addr, cli_addr; - int n; - char buff[MAX]; - struct sigaction sa; - - sa.sa_handler = SIG_IGN; - sa.sa_flags = 0; - sigemptyset(&sa.sa_mask); - sigaction(SIGPIPE, &sa, 0); - - /* First call to socket() function */ - listenfd = socket(AF_INET, SOCK_STREAM, 0); - - if (listenfd < 0) { - perror("ERROR opening socket"); - exit(1); - } - - /* Initialize socket structure */ - bzero((char *)&serv_addr, sizeof(serv_addr)); - - serv_addr.sin_family = AF_INET; - serv_addr.sin_addr.s_addr = INADDR_ANY; - serv_addr.sin_port = htons(port); - - /* Now bind the host address using bind() call.*/ - if (bind(listenfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { - perror("ERROR on binding"); - exit(1); - } - - listen(listenfd, 5); - clilent = sizeof(cli_addr); - - while (1) { - pthread_mutex_lock(&sock_lock); - - sockfd = accept(listenfd, (struct sockaddr *)&cli_addr, &clilent); - - pthread_mutex_unlock(&sock_lock); - - if (sockfd < 0) { - perror("ERROR on accept"); - exit(1); - } - - printf("connection established!\n"); - - for (;;) { - bzero(buff, MAX); - - // read the message from client and copy it in buffer - n = read(sockfd, buff, sizeof(buff)); - - // socket disconnected - if (n <= 0) { - pthread_mutex_lock(&sock_lock); - close(sockfd); - sockfd = -1; - pthread_mutex_unlock(&sock_lock); - - sleep(1); - break; - } - - aee_host_msg_callback(buff, n); - } -#if WASM_ENABLE_FUZZ_TEST != 0 - /* Exit the process when host disconnect. - This is helpful for reproducing failure case. */ - close(sockfd); - exit(1); -#endif - } -} - -#else -static int -parse_baudrate(int baud) -{ - switch (baud) { - case 9600: - return B9600; - case 19200: - return B19200; - case 38400: - return B38400; - case 57600: - return B57600; - case 115200: - return B115200; - case 230400: - return B230400; - case 460800: - return B460800; - case 500000: - return B500000; - case 576000: - return B576000; - case 921600: - return B921600; - case 1000000: - return B1000000; - case 1152000: - return B1152000; - case 1500000: - return B1500000; - case 2000000: - return B2000000; - case 2500000: - return B2500000; - case 3000000: - return B3000000; - case 3500000: - return B3500000; - case 4000000: - return B4000000; - default: - return -1; - } -} -static bool -uart_init(const char *device, int baudrate, int *fd) -{ - int uart_fd; - struct termios uart_term; - - uart_fd = open(device, O_RDWR | O_NOCTTY); - - if (uart_fd <= 0) - return false; - - memset(&uart_term, 0, sizeof(uart_term)); - uart_term.c_cflag = baudrate | CS8 | CLOCAL | CREAD; - uart_term.c_iflag = IGNPAR; - uart_term.c_oflag = 0; - - /* set noncanonical mode */ - uart_term.c_lflag = 0; - uart_term.c_cc[VTIME] = 30; - uart_term.c_cc[VMIN] = 1; - tcflush(uart_fd, TCIFLUSH); - - if (tcsetattr(uart_fd, TCSANOW, &uart_term) != 0) { - close(uart_fd); - return false; - } - - *fd = uart_fd; - - return true; -} - -static void * -func_uart_mode(void *arg) -{ - int n; - char buff[MAX]; - - if (!uart_init(uart_device, baudrate, &uartfd)) { - printf("open uart fail! %s\n", uart_device); - return NULL; - } - - for (;;) { - bzero(buff, MAX); - - n = read(uartfd, buff, sizeof(buff)); - - if (n <= 0) { - close(uartfd); - uartfd = -1; - break; - } - - aee_host_msg_callback(buff, n); - } - - return NULL; -} - -static int -uart_send(void *ctx, const char *buf, int size) -{ - int ret; - - ret = write(uartfd, buf, size); - - return ret; -} - -static void -uart_destroy() -{ - close(uartfd); -} - -/* clang-format off */ -static host_interface interface = { - .send = uart_send, - .destroy = uart_destroy -}; -/* clang-format on */ - -#endif - -static attr_container_t * -read_test_sensor(void *sensor) -{ - attr_container_t *attr_obj = attr_container_create("read test sensor data"); - if (attr_obj) { - bool ret = - attr_container_set_string(&attr_obj, "name", "read test sensor"); - if (!ret) { - attr_container_destroy(attr_obj); - return NULL; - } - return attr_obj; - } - return NULL; -} - -static bool -config_test_sensor(void *s, void *config) -{ - return false; -} - -static char global_heap_buf[1024 * 1024] = { 0 }; - -/* clang-format off */ -static void -showUsage() -{ -#ifndef CONNECTION_UART - printf("Usage:\n"); - printf("\nWork as TCP server mode:\n"); - printf("\tsimple -s|--server_mode -p|--port \n"); - printf("where\n"); - printf("\t represents the port that would be listened on and the default is 8888\n"); - printf("\nWork as TCP client mode:\n"); - printf("\tsimple -a|--host_address -p|--port \n"); - printf("where\n"); - printf("\t represents the network address of host and the default is 127.0.0.1\n"); - printf("\t represents the listen port of host and the default is 8888\n"); -#else - printf("Usage:\n"); - printf("\tsimple -u -b \n\n"); - printf("where\n"); - printf("\t represents the UART device name and the default is /dev/ttyS2\n"); - printf("\t represents the UART device baudrate and the default is 115200\n"); -#endif -} -/* clang-format on */ - -static bool -parse_args(int argc, char *argv[]) -{ - int c; - - while (1) { - int optIndex = 0; - static struct option longOpts[] = { -#ifndef CONNECTION_UART - { "server_mode", no_argument, NULL, 's' }, - { "host_address", required_argument, NULL, 'a' }, - { "port", required_argument, NULL, 'p' }, -#else - { "uart", required_argument, NULL, 'u' }, - { "baudrate", required_argument, NULL, 'b' }, -#endif - { "help", required_argument, NULL, 'h' }, - { 0, 0, 0, 0 } - }; - - c = getopt_long(argc, argv, "sa:p:u:b:w:h", longOpts, &optIndex); - if (c == -1) - break; - - switch (c) { -#ifndef CONNECTION_UART - case 's': - server_mode = true; - break; - case 'a': - host_address = optarg; - printf("host address: %s\n", host_address); - break; - case 'p': - port = atoi(optarg); - printf("port: %d\n", port); - break; -#else - case 'u': - uart_device = optarg; - printf("uart device: %s\n", uart_device); - break; - case 'b': - baudrate = parse_baudrate(atoi(optarg)); - printf("uart baudrate: %s\n", optarg); - break; -#endif - case 'h': - showUsage(); - return false; - default: - showUsage(); - return false; - } - } - - return true; -} - -// Driver function -int -iwasm_main(int argc, char *argv[]) -{ - RuntimeInitArgs init_args; - korp_tid tid; - - if (!parse_args(argc, argv)) - return -1; - - memset(&init_args, 0, sizeof(RuntimeInitArgs)); - -#if USE_GLOBAL_HEAP_BUF != 0 - init_args.mem_alloc_type = Alloc_With_Pool; - init_args.mem_alloc_option.pool.heap_buf = global_heap_buf; - init_args.mem_alloc_option.pool.heap_size = sizeof(global_heap_buf); -#else - init_args.mem_alloc_type = Alloc_With_Allocator; - init_args.mem_alloc_option.allocator.malloc_func = malloc; - init_args.mem_alloc_option.allocator.realloc_func = realloc; - init_args.mem_alloc_option.allocator.free_func = free; -#endif - - /* initialize runtime environment */ - if (!wasm_runtime_full_init(&init_args)) { - printf("Init runtime environment failed.\n"); - return -1; - } - - /* connection framework */ - if (!init_connection_framework()) { - goto fail1; - } - - /* sensor framework */ - if (!init_sensor_framework()) { - goto fail2; - } - - /* timer manager */ - if (!init_wasm_timer()) { - goto fail3; - } - - /* add the sys sensor objects */ - add_sys_sensor("sensor_test1", "This is a sensor for test", 0, 1000, - read_test_sensor, config_test_sensor); - add_sys_sensor("sensor_test2", "This is a sensor for test", 0, 1000, - read_test_sensor, config_test_sensor); - start_sensor_framework(); - -#ifndef CONNECTION_UART - if (server_mode) - os_thread_create(&tid, func_server_mode, NULL, - BH_APPLET_PRESERVED_STACK_SIZE); - else - os_thread_create(&tid, func, NULL, BH_APPLET_PRESERVED_STACK_SIZE); -#else - os_thread_create(&tid, func_uart_mode, NULL, - BH_APPLET_PRESERVED_STACK_SIZE); -#endif - - app_manager_startup(&interface); - - exit_wasm_timer(); - -fail3: - exit_sensor_framework(); - -fail2: - exit_connection_framework(); - -fail1: - wasm_runtime_destroy(); - - return -1; -} diff --git a/samples/simple/src/main.c b/samples/simple/src/main.c deleted file mode 100644 index e603420ee..000000000 --- a/samples/simple/src/main.c +++ /dev/null @@ -1,14 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -extern void -iwasm_main(); - -int -main(int argc, char *argv[]) -{ - iwasm_main(argc, argv); - return 0; -} diff --git a/samples/simple/wasm-apps/connection.c b/samples/simple/wasm-apps/connection.c deleted file mode 100644 index d8efefdcf..000000000 --- a/samples/simple/wasm-apps/connection.c +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "wasm_app.h" -#include "wa-inc/connection.h" -#include "wa-inc/timer_wasm_app.h" -#include "wa-inc/request.h" - -/* User global variable */ -static int num = 0; -static user_timer_t g_timer; -static connection_t *g_conn = NULL; - -void -on_data1(connection_t *conn, conn_event_type_t type, const char *data, - uint32 len, void *user_data) -{ - if (type == CONN_EVENT_TYPE_DATA) { - char message[64] = { 0 }; - memcpy(message, data, len); - printf("Client got a message from server -> %s\n", message); - } - else if (type == CONN_EVENT_TYPE_DISCONNECT) { - printf("connection is close by server!\n"); - } - else { - printf("error: got unknown event type!!!\n"); - } -} - -/* Timer callback */ -void -timer1_update(user_timer_t timer) -{ - char message[64] = { 0 }; - /* Reply to server */ - snprintf(message, sizeof(message), "Hello %d", num++); - api_send_on_connection(g_conn, message, strlen(message)); -} - -void -my_close_handler(request_t *request) -{ - response_t response[1]; - - if (g_conn != NULL) { - api_timer_cancel(g_timer); - api_close_connection(g_conn); - } - - make_response_for_request(request, response); - set_response(response, DELETED_2_02, 0, NULL, 0); - api_response_send(response); -} - -void -on_init() -{ - user_timer_t timer; - attr_container_t *args; - char *str = "this is client!"; - - api_register_resource_handler("/close", my_close_handler); - - args = attr_container_create(""); - attr_container_set_string(&args, "address", "127.0.0.1"); - attr_container_set_uint16(&args, "port", 7777); - - g_conn = api_open_connection("TCP", args, on_data1, NULL); - if (g_conn == NULL) { - printf("connect to server fail!\n"); - return; - } - - printf("connect to server success! handle: %p\n", g_conn); - - /* set up a timer */ - timer = api_timer_create(1000, true, false, timer1_update); - api_timer_restart(timer, 1000); -} - -void -on_destroy() -{ - /* real destroy work including killing timer and closing sensor is - accomplished in wasm app library version of on_destroy() */ -} diff --git a/samples/simple/wasm-apps/event_publisher.c b/samples/simple/wasm-apps/event_publisher.c deleted file mode 100644 index 2fa4418ca..000000000 --- a/samples/simple/wasm-apps/event_publisher.c +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "wasm_app.h" -#include "wa-inc/request.h" -#include "wa-inc/timer_wasm_app.h" - -int num = 0; - -void -publish_overheat_event() -{ - attr_container_t *event; - - event = attr_container_create("event"); - attr_container_set_string(&event, "warning", "temperature is over high"); - - api_publish_event("alert/overheat", FMT_ATTR_CONTAINER, event, - attr_container_get_serialize_length(event)); - - attr_container_destroy(event); -} - -/* Timer callback */ -void -timer1_update(user_timer_t timer) -{ - publish_overheat_event(); -} - -void -start_timer() -{ - user_timer_t timer; - - /* set up a timer */ - timer = api_timer_create(1000, true, false, timer1_update); - api_timer_restart(timer, 1000); -} - -void -on_init() -{ - start_timer(); -} - -void -on_destroy() -{ - /* real destroy work including killing timer and closing sensor is - accomplished in wasm app library version of on_destroy() */ -} diff --git a/samples/simple/wasm-apps/event_subscriber.c b/samples/simple/wasm-apps/event_subscriber.c deleted file mode 100644 index 7ebd309e7..000000000 --- a/samples/simple/wasm-apps/event_subscriber.c +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "wasm_app.h" -#include "wa-inc/request.h" - -void -over_heat_event_handler(request_t *request) -{ - printf("### user over heat event handler called\n"); - - if (request->payload != NULL && request->fmt == FMT_ATTR_CONTAINER) - attr_container_dump((attr_container_t *)request->payload); -} - -void -on_init() -{ - api_subscribe_event("alert/overheat", over_heat_event_handler); -} - -void -on_destroy() -{ - /* real destroy work including killing timer and closing sensor is - accomplished in wasm app library version of on_destroy() */ -} diff --git a/samples/simple/wasm-apps/request_handler.c b/samples/simple/wasm-apps/request_handler.c deleted file mode 100644 index be6c56030..000000000 --- a/samples/simple/wasm-apps/request_handler.c +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "wasm_app.h" -#include "wa-inc/request.h" - -static void -url1_request_handler(request_t *request) -{ - response_t response[1]; - attr_container_t *payload; - - printf("[resp] ### user resource 1 handler called\n"); - - if (request->payload != NULL && request->fmt == FMT_ATTR_CONTAINER) - attr_container_dump((attr_container_t *)request->payload); - - payload = attr_container_create("wasm app response payload"); - if (payload == NULL) - return; - - attr_container_set_string(&payload, "key1", "value1"); - attr_container_set_string(&payload, "key2", "value2"); - - make_response_for_request(request, response); - set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, (void *)payload, - attr_container_get_serialize_length(payload)); - api_response_send(response); - - attr_container_destroy(payload); -} - -static void -url2_request_handler(request_t *request) -{ - response_t response[1]; - make_response_for_request(request, response); - set_response(response, DELETED_2_02, 0, NULL, 0); - api_response_send(response); - - printf("### user resource 2 handler called\n"); -} - -void -on_init() -{ - /* register resource uri */ - api_register_resource_handler("/url1", url1_request_handler); - api_register_resource_handler("/url2", url2_request_handler); -} - -void -on_destroy() -{ - /* real destroy work including killing timer and closing sensor is - accomplished in wasm app library version of on_destroy() */ -} diff --git a/samples/simple/wasm-apps/request_sender.c b/samples/simple/wasm-apps/request_sender.c deleted file mode 100644 index 823f7f62c..000000000 --- a/samples/simple/wasm-apps/request_sender.c +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "wasm_app.h" -#include "wa-inc/request.h" - -static void -my_response_handler(response_t *response, void *user_data) -{ - char *tag = (char *)user_data; - - if (response == NULL) { - printf("[req] request timeout!\n"); - return; - } - - printf("[req] response handler called mid:%d, status:%d, fmt:%d, " - "payload:%p, len:%d, tag:%s\n", - response->mid, response->status, response->fmt, response->payload, - response->payload_len, tag); - - if (response->payload != NULL && response->payload_len > 0 - && response->fmt == FMT_ATTR_CONTAINER) { - printf("[req] dump the response payload:\n"); - attr_container_dump((attr_container_t *)response->payload); - } -} - -static void -test_send_request(char *url, char *tag) -{ - request_t request[1]; - - init_request(request, url, COAP_PUT, 0, NULL, 0); - api_send_request(request, my_response_handler, tag); -} - -void -on_init() -{ - test_send_request("/app/request_handler/url1", "a request to target app"); - test_send_request("url1", "a general request"); -} - -void -on_destroy() -{ - /* real destroy work including killing timer and closing sensor is - accomplished in wasm app library version of on_destroy() */ -} diff --git a/samples/simple/wasm-apps/sensor.c b/samples/simple/wasm-apps/sensor.c deleted file mode 100644 index c45ff67d9..000000000 --- a/samples/simple/wasm-apps/sensor.c +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "wasm_app.h" -#include "wa-inc/sensor.h" - -static sensor_t sensor1 = NULL; -static sensor_t sensor2 = NULL; -static char *user_data = NULL; - -/* Sensor event callback*/ -void -sensor_event_handler(sensor_t sensor, attr_container_t *event, void *user_data) -{ - if (sensor == sensor1) { - printf("### app get sensor event from sensor1\n"); - attr_container_dump(event); - } - else { - printf("### app get sensor event from sensor2\n"); - attr_container_dump(event); - } -} - -void -on_init() -{ - attr_container_t *config; - - printf("### app on_init 1\n"); - /* open a sensor */ - user_data = malloc(100); - if (!user_data) { - printf("allocate memory failed\n"); - return; - } - - printf("### app on_init 2\n"); - sensor1 = sensor_open("sensor_test1", 0, sensor_event_handler, user_data); - if (!sensor1) { - printf("open sensor1 failed\n"); - return; - } - /* config the sensor */ - sensor_config(sensor1, 1000, 0, 0); - - printf("### app on_init 3\n"); - sensor2 = sensor_open("sensor_test2", 0, sensor_event_handler, user_data); - if (!sensor2) { - printf("open sensor2 failed\n"); - return; - } - /* config the sensor */ - sensor_config(sensor2, 5000, 0, 0); - - printf("### app on_init 4\n"); - /* - config = attr_container_create("sensor config"); - sensor_config(sensor, config); - attr_container_destroy(config); - */ -} - -void -on_destroy() -{ - if (NULL != sensor1) { - sensor_config(sensor1, 0, 0, 0); - } - - if (NULL != sensor2) { - sensor_config(sensor2, 0, 0, 0); - } - - if (NULL != user_data) { - free(user_data); - } - - /* real destroy work including killing timer and closing sensor is - accomplished in wasm app library version of on_destroy() */ -} diff --git a/samples/simple/wasm-apps/timer.c b/samples/simple/wasm-apps/timer.c deleted file mode 100644 index 5bf0822cd..000000000 --- a/samples/simple/wasm-apps/timer.c +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "wasm_app.h" -#include "wa-inc/timer_wasm_app.h" - -/* User global variable */ -static int num = 0; - -/* Timer callback */ -void -timer1_update(user_timer_t timer) -{ - printf("Timer update %d\n", num++); -} - -void -on_init() -{ - user_timer_t timer; - - /* set up a timer */ - timer = api_timer_create(1000, true, false, timer1_update); - api_timer_restart(timer, 1000); -} - -void -on_destroy() -{ - /* real destroy work including killing timer and closing sensor is - accomplished in wasm app library version of on_destroy() */ -} diff --git a/samples/wasm-c-api/CMakeLists.txt b/samples/wasm-c-api/CMakeLists.txt index 4189f7280..b8783f4ae 100644 --- a/samples/wasm-c-api/CMakeLists.txt +++ b/samples/wasm-c-api/CMakeLists.txt @@ -35,11 +35,17 @@ set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS "") if (NOT DEFINED WAMR_BUILD_TARGET) if (CMAKE_SYSTEM_PROCESSOR MATCHES "^(arm64|aarch64)") set (WAMR_BUILD_TARGET "AARCH64") + if (NOT DEFINED WAMR_BUILD_SIMD) + set (WAMR_BUILD_SIMD 1) + endif () 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") + if (NOT DEFINED WAMR_BUILD_SIMD) + set (WAMR_BUILD_SIMD 1) + endif () elseif (CMAKE_SIZEOF_VOID_P EQUAL 4) # Build as X86_32 by default in 32-bit platform set (WAMR_BUILD_TARGET "X86_32") @@ -66,6 +72,11 @@ set(WAMR_BUILD_MULTI_MODULE 1) set(WAMR_BUILD_DUMP_CALL_STACK 1) set(WAMR_BUILD_REF_TYPES 1) +# If not defined WAMR_BUILD_GC, set it to 0 +if(NOT DEFINED WAMRC_BUILD_WITH_GC) + set(WAMRC_BUILD_WITH_GC 0) +endif() + if(NOT DEFINED WAMR_BUILD_FAST_INTERP) set(WAMR_BUILD_FAST_INTERP 1) endif() @@ -172,8 +183,13 @@ foreach(EX ${EXAMPLES}) # generate .aot file if(${WAMR_BUILD_AOT} EQUAL 1) + if(${WAMRC_BUILD_WITH_GC} EQUAL 1) + set(WAMRC_GC_FLAGS "--enable-gc") + else() + set(WAMRC_GC_FLAGS "") + endif() add_custom_target(${EX}_AOT - COMMAND ${WAMRC} -o ${PROJECT_BINARY_DIR}/${EX}.aot + COMMAND ${WAMRC} ${WAMRC_GC_FLAGS} -o ${PROJECT_BINARY_DIR}/${EX}.aot ${PROJECT_BINARY_DIR}/${EX}.wasm DEPENDS ${EX}_WASM BYPRODUCTS ${PROJECT_BINARY_DIR}/${EX}.aot diff --git a/test-tools/IoT-APP-Store-Demo/README.md b/test-tools/IoT-APP-Store-Demo/README.md deleted file mode 100644 index 266255c0c..000000000 --- a/test-tools/IoT-APP-Store-Demo/README.md +++ /dev/null @@ -1,50 +0,0 @@ -# IoT Application Store -Wasm application management portal for WAMR - -## Start the server - -### Using docker -1. install docker and docker-compose - ``` bash - sudo apt install docker.io docker-compose - ``` - -2. start - ``` bash - docker-compose up - ``` -### Using commands -> Note: must use python3.5. If you don't have python3.5 on your machine, had better using docker -1. install the required package - ``` bash - pip3 install django - ``` - -2. Start device server - ``` bash - cd wasm_django/server - python3 wasm_server.py - ``` - -3. Start IoT application management web portal - ``` bash - cd wasm_django - python3 manage.py runserver 0.0.0.0:80 - ``` - -## Start the runtime -1. Download WAMR runtime from [help](http://localhost/help/) page - > NOTE: You need to start the server before accessing this link! - -2. Start a WAMR runtime from localhost - ``` bash - chmod +x simple - ./simple - ``` - or from other computers - ``` bash - ./simple -a [your.server.ip.address] - ``` - -## Online demo - http://82.156.57.236/ diff --git a/test-tools/IoT-APP-Store-Demo/docker-compose.yml b/test-tools/IoT-APP-Store-Demo/docker-compose.yml deleted file mode 100644 index 331d064cd..000000000 --- a/test-tools/IoT-APP-Store-Demo/docker-compose.yml +++ /dev/null @@ -1,22 +0,0 @@ -version: '2.0' - -services: - web_portal: - build: ./wasm_django - network_mode: "host" - depends_on: - - 'device_server' - restart: always - volumes: - - store:/app/static/upload/ - device_server: - build: - context: ./wasm_django - dockerfile: ./server/Dockerfile - network_mode: "host" - restart: always - volumes: - - store:/app/static/upload/ - -volumes: - store: \ No newline at end of file diff --git a/test-tools/IoT-APP-Store-Demo/wasm_django/Dockerfile b/test-tools/IoT-APP-Store-Demo/wasm_django/Dockerfile deleted file mode 100644 index a796725fa..000000000 --- a/test-tools/IoT-APP-Store-Demo/wasm_django/Dockerfile +++ /dev/null @@ -1,9 +0,0 @@ -FROM python:3.5 - -WORKDIR /app -COPY . /app - -# hadolint ignore=DL3013 -RUN pip install django --no-cache-dir - -ENTRYPOINT ["python", "manage.py", "runserver", "0.0.0.0:80"] diff --git a/test-tools/IoT-APP-Store-Demo/wasm_django/db.sqlite3 b/test-tools/IoT-APP-Store-Demo/wasm_django/db.sqlite3 deleted file mode 100755 index 211576ca3..000000000 Binary files a/test-tools/IoT-APP-Store-Demo/wasm_django/db.sqlite3 and /dev/null differ diff --git a/test-tools/IoT-APP-Store-Demo/wasm_django/devices/__init__.py b/test-tools/IoT-APP-Store-Demo/wasm_django/devices/__init__.py deleted file mode 100755 index e69de29bb..000000000 diff --git a/test-tools/IoT-APP-Store-Demo/wasm_django/devices/admin.py b/test-tools/IoT-APP-Store-Demo/wasm_django/devices/admin.py deleted file mode 100755 index 8c38f3f3d..000000000 --- a/test-tools/IoT-APP-Store-Demo/wasm_django/devices/admin.py +++ /dev/null @@ -1,3 +0,0 @@ -from django.contrib import admin - -# Register your models here. diff --git a/test-tools/IoT-APP-Store-Demo/wasm_django/devices/apps.py b/test-tools/IoT-APP-Store-Demo/wasm_django/devices/apps.py deleted file mode 100755 index d43cc4b66..000000000 --- a/test-tools/IoT-APP-Store-Demo/wasm_django/devices/apps.py +++ /dev/null @@ -1,5 +0,0 @@ -from django.apps import AppConfig - - -class DevicesConfig(AppConfig): - name = 'devices' diff --git a/test-tools/IoT-APP-Store-Demo/wasm_django/devices/migrations/__init__.py b/test-tools/IoT-APP-Store-Demo/wasm_django/devices/migrations/__init__.py deleted file mode 100755 index e69de29bb..000000000 diff --git a/test-tools/IoT-APP-Store-Demo/wasm_django/devices/models.py b/test-tools/IoT-APP-Store-Demo/wasm_django/devices/models.py deleted file mode 100755 index 71a836239..000000000 --- a/test-tools/IoT-APP-Store-Demo/wasm_django/devices/models.py +++ /dev/null @@ -1,3 +0,0 @@ -from django.db import models - -# Create your models here. diff --git a/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/application.html b/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/application.html deleted file mode 100644 index 0b2ea7faf..000000000 --- a/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/application.html +++ /dev/null @@ -1,141 +0,0 @@ - - -{% load static %} - - - - - - - Wasm-Micro-Runtime - - - - - - - - - - -
-
- -
-
-

WebAssembly Micro Runtime - APP Store Demo

-
-
- - - -
-
-
-
-

- -

-
-
IP :
-
Port :
-
Installed apps :
-
-
-
- - - - - -
-

app is downloading now

-
-
-
-
- - -
-
-
×
-
HOT Applications
- -
-
- -

Product Name:

-

Current Version:

- -
-
-
-
- - -
-

List of Installed Apps:

- -
- - -
-
- -
Product Name:
-
Staus:
-
Current Version:
-
-
-
- -
Copyright© intel.com
- - - - - - - - - - - diff --git a/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/appstore.html b/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/appstore.html deleted file mode 100644 index 46ecedf15..000000000 --- a/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/appstore.html +++ /dev/null @@ -1,98 +0,0 @@ - - -{% load static %} - - - - - - - - Wasm-Micro-Runtime - - - - - - - - - - -
-
- -
-
-

WebAssembly Micro Runtime - APP Store Demo

-
-
- - - - - -
-
-
-
The products
-
Application List
-
-
- {%csrf_token%} -
- - Choose File -
-
- -
-
-
-
-
-
-
-

Product Name:

-

Product Version:

-

Preloaded Apps

- -
-
-
-
-
- - -
- Copyright© intel.com -
- - - - - - - - - diff --git a/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/empty.html b/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/empty.html deleted file mode 100644 index 5610a2d84..000000000 --- a/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/empty.html +++ /dev/null @@ -1,125 +0,0 @@ - - - - - -wasm-micro-runtime - - - - - - - - - - -
-

404

-

Server Not Found

-

Github

-
- - - - - - - - - - diff --git a/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/help.html b/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/help.html deleted file mode 100755 index 4ad7427ba..000000000 --- a/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/help.html +++ /dev/null @@ -1,102 +0,0 @@ - - -{% load static %} - - - - - - - Wasm-Micro-Runtime - - - - - - - - - - - - -
-
-
-
-

- How to use? -

-

- 1. Download a simple runtime (build for ubuntu 20.04 64 bits, other platforms please build - from the source code) -

-

- 2. In the terminal: cd ~/Download && ./simple -a 82.156.57.236 -

-
-
- -
- Notes: -
We also have a UI-enabled runtime, please download here and enjoy. It may require - a few more setups. -

Before running the UI-enabled runtime, please install some required softwares:

-

sudo apt-get install libsdl2-2.0-0:i386

-

For more details please refer to this guide -

-

cd ~/Download && ./wasm_runtime_wgl -a 82.156.57.236

-
-
-

- 3. Return to device page, find your device according to the IP address and click it, you - will enter application installation page -

-

- 4. In the application installation page, click the Install Application button, and chose an - app to install. (The "ui_app" is only for UI_enabled_runtimes, simple runtime can't install - this app) -

-

- 5. If you want to upload a new application, go to App Store page, choose a file and click - upload -

-

- Go Back - Download - simple_runtime - Download - UI_enabled_runtime -

-
-
-
-
-

Like this project?

-

Join us and build a powerful and interesting world for embedded - devices!

- - -

- View - on GitHub -

-
-
-
-
-
-
- - - diff --git a/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/mysite.html b/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/mysite.html deleted file mode 100644 index 3832791d1..000000000 --- a/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/mysite.html +++ /dev/null @@ -1,91 +0,0 @@ - - -{% load static %} - - - - - - - Wasm-Micro-Runtime - - - - - - - - - - -
-
- -
-
-

WebAssembly Micro Runtime - APP Store Demo

-
-
- -
-
-
-
-

- -

-
-

The devices

-
-
- -
- - -
-
-
-
-

- -

-
-
IP :
-
Port :
-
Installed apps :
-
-
-

- -

-
-
-
- - - - -
- Copyright© intel.com -
- - - - - - - - diff --git a/test-tools/IoT-APP-Store-Demo/wasm_django/devices/tests.py b/test-tools/IoT-APP-Store-Demo/wasm_django/devices/tests.py deleted file mode 100755 index 7ce503c2d..000000000 --- a/test-tools/IoT-APP-Store-Demo/wasm_django/devices/tests.py +++ /dev/null @@ -1,3 +0,0 @@ -from django.test import TestCase - -# Create your tests here. diff --git a/test-tools/IoT-APP-Store-Demo/wasm_django/devices/views.py b/test-tools/IoT-APP-Store-Demo/wasm_django/devices/views.py deleted file mode 100755 index 1afa1f954..000000000 --- a/test-tools/IoT-APP-Store-Demo/wasm_django/devices/views.py +++ /dev/null @@ -1,273 +0,0 @@ -''' - /* Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ -''' - -# _*_ -from django.shortcuts import render, render_to_response -from django.http import HttpResponse, HttpResponseRedirect, HttpResponseNotFound -import json -import socket -import os - -# Create your views here. - - -avaliable_list = [ - {'ID': 'timer', 'Version': '1.0'}, - {'ID': 'connection', 'Version': '1.0'}, - {'ID': 'event_publisher', 'Version': '3.0'}, - {'ID': 'event_subscriber', 'Version': '1.0'}, - {'ID': 'request_handler', 'Version': '1.0'}, - {'ID': 'sensor', 'Version': '1.0'}, - {'ID': 'ui_app', 'Version': '1.0'} -] - -# Help -def help(req): -# return "Help" page - return render(req, "help.html") - -# View -def index(req): - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - - host = '127.0.0.1' - port = 8889 - msg = "" - err = "" - - try: - s.connect((host, port)) - s.send(bytes("query:all", encoding='utf8')) - s.settimeout(10) - msg = s.recv(1024) - except socket.timeout as e: - err = "empty" - print("no client connected") - except socket.error as e: - err = "refused" - print("server not started") - - s.close() - - device_list = [] - if msg != "": - devices = msg.decode('utf-8').split("*") - for dev in devices: - dev_info = eval(dev) - addr = dev_info['addr'] - port = dev_info['port'] - apps = dev_info['num'] - device_list.append({'IP': addr, 'Port': port, 'apps': apps}) - else: - if err == "refused": - return render(req, "empty.html") - - dlist = device_list - - return render(req, 'mysite.html', {'dlist': json.dumps(dlist)}) - - -def apps(req): - open_status = '' - search_node = [] - if req.method == "POST": - dev_search = req.POST['mykey'] - dev_addr = req.POST['voip'] - dev_port = req.POST['voport'] - open_status = 'open' - for i in avaliable_list: - if i['ID'] == dev_search: - search_node = [{'ID':dev_search, 'Version': '1.0'}] - print("search_node:",search_node) - break - else: - search_node = ["Nothing find"] - print( "final:",search_node) - else: - dev_addr = req.GET['ip'] - dev_port = req.GET['port'] - open_status = 'close' - - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - host = '127.0.0.1' - port = 8889 - msg = "" - err = "" - - try: - s.connect((host, port)) - s.send(bytes("query:"+dev_addr+":"+str(dev_port), encoding='utf8')) - msg = s.recv(1024) - except socket.error as e: - print("unable to connect to server") - msg = b"fail" - s.close() - - app_list = [] - - if msg != "": - if msg.decode() == "fail": - return render(req, "empty.html") - else: - dic = eval(msg.decode(encoding='utf8')) - app_num = dic["num"] - for i in range(app_num): - app_list.append( - {'pname': dic["applet"+str(i+1)], 'status': 'Installed', 'current_version': '1.0'}) - - alist = app_list - device_info = [] - device_info.append( - {'IP': dev_addr, 'Port': str(dev_port), 'apps': app_num}) - - print(device_info) - return render(req, 'application.html', {'alist': json.dumps(alist), 'dlist': json.dumps(device_info), 'llist': json.dumps(avaliable_list), - "open_status":json.dumps(open_status),"search_node": json.dumps(search_node),}) - - -def appDownload(req): - dev_addr = req.GET['ip'] - dev_port = req.GET['port'] - app_name = req.GET['name'] - - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - - host = '127.0.0.1' - port = 8889 - msg = "" - - app_path = os.path.abspath(os.path.join(os.getcwd(), "static", "upload")) - if app_path[-1] != '/': - app_path += '/' - - try: - s.connect((host, port)) - s.send(bytes("install:"+dev_addr+":"+str(dev_port)+":"+app_name + - ":"+app_path + app_name + ".wasm", encoding='utf8')) - msg = s.recv(1024) - except socket.error as e: - print("unable to connect to server") - s.close() - - success = "ok" - fail = "Fail!" - status = [success, fail] - print(msg) - if msg == b"fail": - return HttpResponse(json.dumps({ - "status": fail - })) - elif msg == b"success": - return HttpResponse(json.dumps({ - "status": success - })) - else: - return HttpResponse(json.dumps({ - "status": eval(msg.decode())["error message"].split(':')[1] - })) - - -def appDelete(req): - dev_addr = req.GET['ip'] - dev_port = req.GET['port'] - app_name = req.GET['name'] - - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - - host = '127.0.0.1' - port = 8889 - s.connect((host, port)) - s.send(bytes("uninstall:"+dev_addr+":" + - str(dev_port)+":"+app_name, encoding='utf8')) - msg = s.recv(1024) - s.close() - r = HttpResponse("ok") - return r - -static_list = [{'ID': 'timer', 'Version': '1.0'}, {'ID': 'connection', 'Version': '1.0'}, {'ID': 'event_publisher', 'Version': '3.0'}, { - 'ID': 'event_subscriber', 'Version': '1.0'}, {'ID': 'reuqest_handler', 'Version': '1.0'}, {'ID': 'sensor', 'Version': '1.0'}, {'ID': 'ui_app', 'Version': '1.0'}] - -def store(req): - - store_path = os.path.join('static', 'upload') - status = [] - - print(user_file_list) - return render(req, 'appstore.html', {'staticlist': json.dumps(static_list), 'flist': json.dumps(user_file_list),'ulist':json.dumps(status)}) - -user_file_list = [] -files_list = [] -def uploadapps(req): - status = [] - local_list = ['timer','connection','event_publisher','event_subscriber','reuqest_handler','sensor'] - req.encoding = 'utf-8' - if req.method == 'POST': - myfile = req.FILES.get("myfile", None) - obj = req.FILES.get('myfile') - store_path = os.path.join('static', 'upload') - file_path = os.path.join('static', 'upload', obj.name) - - if not os.path.exists(store_path): - os.makedirs(store_path) - - file_name = obj.name.split(".")[0] - file_prefix = obj.name.split(".")[-1] - - - if file_prefix != "wasm": - status = ["Not a wasm file"] - elif file_name in local_list: - status = ["This App is preloaded"] - elif file_name in files_list: - status = ["This App is already uploaded"] - else: - status = [] - avaliable_list.append({'ID': file_name, 'Version': '1.0'}) - user_file_list.append({'ID': file_name, 'Version': '1.0'}) - files_list.append(file_name) - - print(user_file_list) - f = open(file_path, 'wb') - for chunk in obj.chunks(): - f.write(chunk) - f.close() - return render(req, 'appstore.html', {'staticlist': json.dumps(static_list), 'flist': json.dumps(user_file_list),'ulist':json.dumps(status)}) - -appname_list = [] - -def addapps(request): - types = '' - print("enter addapps") - request.encoding = 'utf-8' - app_dic = {'ID': '', 'Version': ''} - - # if request.method == 'get': - if "NAME" in request.GET: - a_name = request.GET['NAME'] - if a_name != "" and a_name not in appname_list: - appname_list.append(a_name) - message = request.GET['NAME'] + request.GET['Version'] - app_dic['ID'] = request.GET['NAME'] - app_dic['Version'] = request.GET['Version'] - avaliable_list.append(app_dic) - else: - types = "Exist" - print(avaliable_list) - return render(request, 'appstore.html', {'alist': json.dumps(avaliable_list)}) - -def removeapps(req): - app_name = req.GET['name'] - app_version = req.GET['version'] - remove_app = {'ID': app_name, 'Version': app_version} - avaliable_list.remove(remove_app) - user_file_list.remove(remove_app) - files_list.remove(app_name) - return render(req, 'appstore.html', {'alist': json.dumps(avaliable_list),'flist': json.dumps(user_file_list)}) - -# Test -# if __name__ == "__main__": -# print(device_list[0]['IP']) -# print(device['IP']) diff --git a/test-tools/IoT-APP-Store-Demo/wasm_django/manage.py b/test-tools/IoT-APP-Store-Demo/wasm_django/manage.py deleted file mode 100755 index 341863cf6..000000000 --- a/test-tools/IoT-APP-Store-Demo/wasm_django/manage.py +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/env python -"""Django's command-line utility for administrative tasks.""" -import os -import sys - - -def main(): - os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') - try: - from django.core.management import execute_from_command_line - except ImportError as exc: - raise ImportError( - "Couldn't import Django. Are you sure it's installed and " - "available on your PYTHONPATH environment variable? Did you " - "forget to activate a virtual environment?" - ) from exc - execute_from_command_line(sys.argv) - - -if __name__ == '__main__': - main() diff --git a/test-tools/IoT-APP-Store-Demo/wasm_django/mysite/__init__.py b/test-tools/IoT-APP-Store-Demo/wasm_django/mysite/__init__.py deleted file mode 100755 index e69de29bb..000000000 diff --git a/test-tools/IoT-APP-Store-Demo/wasm_django/mysite/settings.py b/test-tools/IoT-APP-Store-Demo/wasm_django/mysite/settings.py deleted file mode 100755 index 7eb3685c4..000000000 --- a/test-tools/IoT-APP-Store-Demo/wasm_django/mysite/settings.py +++ /dev/null @@ -1,136 +0,0 @@ -""" -Django settings for mysite project. - -Generated by 'django-admin startproject' using Django 2.2.2. - -For more information on this file, see -https://docs.djangoproject.com/en/2.2/topics/settings/ - -For the full list of settings and their values, see -https://docs.djangoproject.com/en/2.2/ref/settings/ -""" - -import os -from django.conf.global_settings import STATIC_ROOT - -# Build paths inside the project like this: os.path.join(BASE_DIR, ...) -BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - - -# Quick-start development settings - unsuitable for production -# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ - -# SECURITY WARNING: keep the secret key used in production secret! -SECRET_KEY = '8m05#6yx5wcygj*a+v6+=-y(#o+(z58-3!epq$u@5)64!mmu8q' - -# SECURITY WARNING: don't run with debug turned on in production! -DEBUG = True - -ALLOWED_HOSTS = ['*'] - - -# Application definition - -INSTALLED_APPS = [ - 'django.contrib.admin', - 'django.contrib.auth', - 'django.contrib.contenttypes', - 'django.contrib.sessions', - 'django.contrib.messages', - 'django.contrib.staticfiles', - - - 'devices', -] - -MIDDLEWARE = [ - 'django.middleware.security.SecurityMiddleware', - 'django.contrib.sessions.middleware.SessionMiddleware', - 'django.middleware.common.CommonMiddleware', - 'django.middleware.csrf.CsrfViewMiddleware', - 'django.contrib.auth.middleware.AuthenticationMiddleware', - 'django.contrib.messages.middleware.MessageMiddleware', - 'django.middleware.clickjacking.XFrameOptionsMiddleware', -] - -ROOT_URLCONF = 'mysite.urls' - -TEMPLATES = [ - { - 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [], - 'APP_DIRS': True, - 'OPTIONS': { - 'context_processors': [ - 'django.template.context_processors.debug', - 'django.template.context_processors.request', - 'django.contrib.auth.context_processors.auth', - 'django.contrib.messages.context_processors.messages', - ], - }, - }, -] - -WSGI_APPLICATION = 'mysite.wsgi.application' - - -# Database -# https://docs.djangoproject.com/en/2.2/ref/settings/#databases - -DATABASES = { - 'default': { - 'ENGINE': 'django.db.backends.sqlite3', - 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), - } -} - - -# Password validation -# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators - -AUTH_PASSWORD_VALIDATORS = [ - { - 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', - }, - { - 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', - }, - { - 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', - }, - { - 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', - }, -] - - -# Internationalization -# https://docs.djangoproject.com/en/2.2/topics/i18n/ - -LANGUAGE_CODE = 'en-us' - -TIME_ZONE = 'UTC' - -USE_I18N = True - -USE_L10N = True - -USE_TZ = True - -APPEND_SLASH = False - - -# Static files (CSS, JavaScript, Images) -# https://docs.djangoproject.com/en/2.2/howto/static-files/ - -STATIC_URL = '/static/' -HERE = os.path.dirname(os.path.abspath(__file__)) -HERE = os.path.join(HERE,'../') -STATICFILES_DIRS = (os.path.join(HERE,'static/'),) -#STATICFILES_DIRS = (os.path.join(BASE_DIR,'static'),) -#STATIC_ROOT = (os.path.join(os.path.dirname(_file_),'static') -#templates -TEMPLATE_DIRS=[ - '/home/xujun/mysite/templates', -] - diff --git a/test-tools/IoT-APP-Store-Demo/wasm_django/mysite/urls.py b/test-tools/IoT-APP-Store-Demo/wasm_django/mysite/urls.py deleted file mode 100755 index 8a74b5509..000000000 --- a/test-tools/IoT-APP-Store-Demo/wasm_django/mysite/urls.py +++ /dev/null @@ -1,41 +0,0 @@ -#config:utf-8 - -"""mysite URL Configuration - -The `urlpatterns` list routes URLs to views. For more information please see: - https://docs.djangoproject.com/en/2.2/topics/http/urls/ -Examples: -Function views - 1. Add an import: from my_app import views - 2. Add a URL to urlpatterns: path('', views.home, name='home') -Class-based views - 1. Add an import: from other_app.views import Home - 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') -Including another URLconf - 1. Import the include() function: from django.urls import include, path - 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) -""" -from django.contrib import admin -#from django.conf.urls import include,url -from django.urls import path,include -from devices import views as devices_views -#from login import views as login_views - - -urlpatterns = [ - - path('admin/', admin.site.urls), - path('',devices_views.index), - path('apps/',devices_views.apps), - path('appDownload/', devices_views.appDownload), - path('appDelete/', devices_views.appDelete), - path('appstore/',devices_views.store), -## path('apps/appstore/',devices_views.storeofdevic), -## path('search/',devices_views.search), - path('upload',devices_views.uploadapps), - path('removeapps/',devices_views.removeapps), - path('help/',devices_views.help), - -] - - diff --git a/test-tools/IoT-APP-Store-Demo/wasm_django/mysite/wsgi.py b/test-tools/IoT-APP-Store-Demo/wasm_django/mysite/wsgi.py deleted file mode 100755 index 45e28c9a1..000000000 --- a/test-tools/IoT-APP-Store-Demo/wasm_django/mysite/wsgi.py +++ /dev/null @@ -1,16 +0,0 @@ -""" -WSGI config for mysite project. - -It exposes the WSGI callable as a module-level variable named ``application``. - -For more information on this file, see -https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ -""" - -import os - -from django.core.wsgi import get_wsgi_application - -os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') - -application = get_wsgi_application() diff --git a/test-tools/IoT-APP-Store-Demo/wasm_django/server/Dockerfile b/test-tools/IoT-APP-Store-Demo/wasm_django/server/Dockerfile deleted file mode 100644 index 371fa45b0..000000000 --- a/test-tools/IoT-APP-Store-Demo/wasm_django/server/Dockerfile +++ /dev/null @@ -1,6 +0,0 @@ -FROM python:3.5 - -WORKDIR /app -COPY server/wasm_server.py /app/server/ - -ENTRYPOINT ["python", "server/wasm_server.py"] diff --git a/test-tools/IoT-APP-Store-Demo/wasm_django/server/wasm_server.py b/test-tools/IoT-APP-Store-Demo/wasm_django/server/wasm_server.py deleted file mode 100755 index 970ec6f60..000000000 --- a/test-tools/IoT-APP-Store-Demo/wasm_django/server/wasm_server.py +++ /dev/null @@ -1,621 +0,0 @@ -''' - /* Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ -''' -import select -import socket -import queue -from time import sleep -import struct -import threading -import time -from ctypes import * -import json -import logging -import os - -attr_type_list = [ - "ATTR_TYPE_BYTE", # = ATTR_TYPE_INT8 - "ATTR_TYPE_SHORT",# = ATTR_TYPE_INT16 - "ATTR_TYPE_INT", # = ATTR_TYPE_INT32 - "ATTR_TYPE_INT64", - "ATTR_TYPE_UINT8", - "ATTR_TYPE_UINT16", - "ATTR_TYPE_UINT32", - "ATTR_TYPE_UINT64", - "ATTR_TYPE_FLOAT", - "ATTR_TYPE_DOUBLE", - "ATTR_NONE", - "ATTR_NONE", - "ATTR_TYPE_BOOLEAN", - "ATTR_TYPE_STRING", - "ATTR_TYPE_BYTEARRAY" -] - - -Phase_Non_Start = 0 -Phase_Leading = 1 -Phase_Type = 2 -Phase_Size = 3 -Phase_Payload = 4 - - - -class imrt_link_message(object): - def __init__(self): - self.leading = bytes([0x12, 0x34]) - self.phase = Phase_Non_Start - self.size_in_phase = 0 - self.message_type = bytes() - self.message_size = bytes() - self.payload = bytes() - self.msg = bytes() - - def set_recv_phase(self, phase): - self.phase = phase - - def on_imrt_link_byte_arrive(self, ch): - self.msg += ch - if self.phase == Phase_Non_Start: - if ch == b'\x12': - self.set_recv_phase(Phase_Leading) - else: - return -1 - elif self.phase == Phase_Leading: - if ch == b'\x34': - self.set_recv_phase(Phase_Type) - else: - self.set_recv_phase(Phase_Non_Start) - return -1 - elif self.phase == Phase_Type: - self.message_type += ch - self.size_in_phase += 1 - - if self.size_in_phase == 2: - (self.message_type, ) = struct.unpack('!H', self.message_type) - self.size_in_phase = 0 - self.set_recv_phase(Phase_Size) - elif self.phase == Phase_Size: - self.message_size += ch - self.size_in_phase += 1 - - if self.size_in_phase == 4: - (self.message_size, ) = struct.unpack('!I', self.message_size) - self.size_in_phase = 0 - self.set_recv_phase(Phase_Payload) - - if self.message_size == b'\x00': - self.set_recv_phase(Phase_Non_Start) - return 0 - - self.set_recv_phase(Phase_Payload) - - elif self.phase == Phase_Payload: - self.payload += ch - self.size_in_phase += 1 - - if self.size_in_phase == self.message_size: - self.set_recv_phase(Phase_Non_Start) - return 0 - - return 2 - - return 1 - - - -def read_file_to_buffer(file_name): - file_object = open(file_name, 'rb') - buffer = None - - if not os.path.exists(file_name): - logging.error("file {} not found.".format(file_name)) - return "file not found" - - try: - buffer = file_object.read() - finally: - file_object.close() - - return buffer - -def decode_attr_container(msg): - - attr_dict = {} - - buf = msg[26 : ] - (total_len, tag_len) = struct.unpack('@IH', buf[0 : 6]) - tag_name = buf[6 : 6 + tag_len].decode() - buf = buf[6 + tag_len : ] - (attr_num, ) = struct.unpack('@H', buf[0 : 2]) - buf = buf[2 : ] - - logging.info("parsed attr:") - logging.info("total_len:{}, tag_len:{}, tag_name:{}, attr_num:{}" - .format(str(total_len), str(tag_len), str(tag_name), str(attr_num))) - - for i in range(attr_num): - (key_len, ) = struct.unpack('@H', buf[0 : 2]) - key_name = buf[2 : 2 + key_len - 1].decode() - buf = buf[2 + key_len : ] - (type_index, ) = struct.unpack('@c', buf[0 : 1]) - - attr_type = attr_type_list[int(type_index[0])] - buf = buf[1 : ] - - if attr_type == "ATTR_TYPE_BYTE": # = ATTR_TYPE_INT8 - (attr_value, ) = struct.unpack('@c', buf[0 : 1]) - buf = buf[1 : ] - # continue - elif attr_type == "ATTR_TYPE_SHORT": # = ATTR_TYPE_INT16 - (attr_value, ) = struct.unpack('@h', buf[0 : 2]) - buf = buf[2 : ] - # continue - elif attr_type == "ATTR_TYPE_INT": # = ATTR_TYPE_INT32 - (attr_value, ) = struct.unpack('@i', buf[0 : 4]) - buf = buf[4 : ] - # continue - elif attr_type == "ATTR_TYPE_INT64": - (attr_value, ) = struct.unpack('@q', buf[0 : 8]) - buf = buf[8 : ] - # continue - elif attr_type == "ATTR_TYPE_UINT8": - (attr_value, ) = struct.unpack('@B', buf[0 : 1]) - buf = buf[1 : ] - # continue - elif attr_type == "ATTR_TYPE_UINT16": - (attr_value, ) = struct.unpack('@H', buf[0 : 2]) - buf = buf[2 : ] - # continue - elif attr_type == "ATTR_TYPE_UINT32": - (attr_value, ) = struct.unpack('@I', buf[0 : 4]) - buf = buf[4 : ] - # continue - elif attr_type == "ATTR_TYPE_UINT64": - (attr_value, ) = struct.unpack('@Q', buf[0 : 8]) - buf = buf[8 : ] - # continue - elif attr_type == "ATTR_TYPE_FLOAT": - (attr_value, ) = struct.unpack('@f', buf[0 : 4]) - buf = buf[4 : ] - # continue - elif attr_type == "ATTR_TYPE_DOUBLE": - (attr_value, ) = struct.unpack('@d', buf[0 : 8]) - buf = buf[8 : ] - # continue - elif attr_type == "ATTR_TYPE_BOOLEAN": - (attr_value, ) = struct.unpack('@?', buf[0 : 1]) - buf = buf[1 : ] - # continue - elif attr_type == "ATTR_TYPE_STRING": - (str_len, ) = struct.unpack('@H', buf[0 : 2]) - attr_value = buf[2 : 2 + str_len - 1].decode() - buf = buf[2 + str_len : ] - # continue - elif attr_type == "ATTR_TYPE_BYTEARRAY": - (byte_len, ) = struct.unpack('@I', buf[0 : 4]) - attr_value = buf[4 : 4 + byte_len] - buf = buf[4 + byte_len : ] - # continue - - attr_dict[key_name] = attr_value - - logging.info(str(attr_dict)) - return attr_dict - -class Request(): - mid = 0 - url = "" - action = 0 - fmt = 0 - payload = "" - payload_len = 0 - sender = 0 - - def __init__(self, url, action, fmt, payload, payload_len): - self.url = url - self.action = action - self.fmt = fmt - # if type(payload) == bytes: - # self.payload = bytes(payload, encoding = "utf8") - # else: - self.payload_len = payload_len - if self.payload_len > 0: - self.payload = payload - - - def pack_request(self): - url_len = len(self.url) + 1 - buffer_len = url_len + self.payload_len - - req_buffer = struct.pack('!2BH2IHI',1, self.action, self.fmt, self.mid, self.sender, url_len, self.payload_len) - for i in range(url_len - 1): - req_buffer += struct.pack('!c', bytes(self.url[i], encoding = "utf8")) - req_buffer += bytes([0]) - for i in range(self.payload_len): - req_buffer += struct.pack('!B', self.payload[i]) - - return req_buffer, len(req_buffer) - - - def send(self, conn, is_install): - leading = struct.pack('!2B', 0x12, 0x34) - - if not is_install: - msg_type = struct.pack('!H', 0x0002) - else: - msg_type = struct.pack('!H', 0x0004) - buff, buff_len = self.pack_request() - lenth = struct.pack('!I', buff_len) - - try: - conn.send(leading) - conn.send(msg_type) - conn.send(lenth) - conn.send(buff) - except socket.error as e: - logging.error("device closed") - for dev in tcpserver.devices: - if dev.conn == conn: - tcpserver.devices.remove(dev) - return -1 - - -def query(conn): - req = Request("/applet", 1, 0, "", 0) - if req.send(conn, False) == -1: - return "fail" - time.sleep(0.05) - try: - receive_context = imrt_link_message() - start = time.time() - while True: - if receive_context.on_imrt_link_byte_arrive(conn.recv(1)) == 0: - break - elif time.time() - start >= 5.0: - return "fail" - query_resp = receive_context.msg - print(query_resp) - except OSError as e: - logging.error("OSError exception occur") - return "fail" - - res = decode_attr_container(query_resp) - - logging.info('Query device infomation success') - return res - -def install(conn, app_name, wasm_file): - wasm = read_file_to_buffer(wasm_file) - if wasm == "file not found": - return "failed to install: file not found" - - print("wasm file len:") - print(len(wasm)) - req = Request("/applet?name=" + app_name, 3, 98, wasm, len(wasm)) - if req.send(conn, True) == -1: - return "fail" - time.sleep(0.05) - try: - receive_context = imrt_link_message() - start = time.time() - while True: - if receive_context.on_imrt_link_byte_arrive(conn.recv(1)) == 0: - break - elif time.time() - start >= 5.0: - return "fail" - msg = receive_context.msg - except OSError as e: - logging.error("OSError exception occur") - # TODO: check return message - - if len(msg) == 24 and msg[8 + 1] == 65: - logging.info('Install application success') - return "success" - else: - res = decode_attr_container(msg) - logging.warning('Install application failed: %s' % (str(res))) - print(str(res)) - - return str(res) - - -def uninstall(conn, app_name): - req = Request("/applet?name=" + app_name, 4, 99, "", 0) - if req.send(conn, False) == -1: - return "fail" - time.sleep(0.05) - try: - receive_context = imrt_link_message() - start = time.time() - while True: - if receive_context.on_imrt_link_byte_arrive(conn.recv(1)) == 0: - break - elif time.time() - start >= 5.0: - return "fail" - msg = receive_context.msg - except OSError as e: - logging.error("OSError exception occur") - # TODO: check return message - - if len(msg) == 24 and msg[8 + 1] == 66: - logging.info('Uninstall application success') - return "success" - else: - res = decode_attr_container(msg) - logging.warning('Uninstall application failed: %s' % (str(res))) - print(str(res)) - - return str(res) - -class Device: - def __init__(self, conn, addr, port): - self.conn = conn - self.addr = addr - self.port = port - self.app_num = 0 - self.apps = [] - -cmd = [] - -class TCPServer: - def __init__(self, server, server_address, inputs, outputs, message_queues): - # Create a TCP/IP - self.server = server - self.server.setblocking(False) - - # Bind the socket to the port - self.server_address = server_address - print('starting up on %s port %s' % self.server_address) - self.server.bind(self.server_address) - - # Listen for incoming connections - self.server.listen(10) - - self.cmd_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.cmd_sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) - - self.cmd_sock.bind(('127.0.0.1', 8889)) - self.cmd_sock.listen(5) - - - # Sockets from which we expect to read - self.inputs = inputs - self.inputs.append(self.cmd_sock) - - # Sockets to which we expect to write - # 处理要发送的消息 - self.outputs = outputs - # Outgoing message queues (socket: Queue) - self.message_queues = message_queues - - self.devices = [] - self.conn_dict = {} - - def handler_recever(self, readable): - # Handle inputs - for s in readable: - if s is self.server: - # A "readable" socket is ready to accept a connection - connection, client_address = s.accept() - self.client_address = client_address - print('connection from', client_address) - # this is connection not server - # connection.setblocking(0) - self.inputs.append(connection) - - # Give the connection a queue for data we want to send - # self.message_queues[connection] = queue.Queue() - - res = query(connection) - - if res != "fail": - dev = Device(connection, client_address[0], client_address[1]) - self.devices.append(dev) - self.conn_dict[client_address] = connection - - dev_info = {} - dev_info['addr'] = dev.addr - dev_info['port'] = dev.port - dev_info['apps'] = 0 - - logging.info('A new client connected from ("%s":"%s")' % (dev.conn, dev.port)) - - elif s is self.cmd_sock: - connection, client_address = s.accept() - print("web server socket connected") - logging.info("Django server connected") - self.inputs.append(connection) - self.message_queues[connection] = queue.Queue() - - else: - data = s.recv(1024) - if data != b'': - # A readable client socket has data - logging.info('received "%s" from %s' % (data, s.getpeername())) - - # self.message_queues[s].put(data) - # # Add output channel for response - - # if s not in self.outputs: - # self.outputs.append(s) - - if(data.decode().split(':')[0] == "query"): - if data.decode().split(':')[1] == "all": - resp = [] - print('start query all devices') - for dev in self.devices: - dev_info = query(dev.conn) - if dev_info == "fail": - continue - dev_info["addr"] = dev.addr - dev_info["port"] = dev.port - resp.append(str(dev_info)) - - print(resp) - - if self.message_queues[s] is not None: - # '*' is used in web server to sperate the string - self.message_queues[s].put(bytes("*".join(resp), encoding = 'utf8')) - if s not in self.outputs: - self.outputs.append(s) - else: - client_addr = (data.decode().split(':')[1],int(data.decode().split(':')[2])) - - if client_addr in self.conn_dict.keys(): - print('start query device from (%s:%s)' % (client_addr[0], client_addr[1])) - resp = query(self.conn_dict[client_addr]) - print(resp) - - if self.message_queues[s] is not None: - self.message_queues[s].put(bytes(str(resp), encoding = 'utf8')) - if s not in self.outputs: - self.outputs.append(s) - else: # no connection - if self.message_queues[s] is not None: - self.message_queues[s].put(bytes(str("fail"), encoding = 'utf8')) - if s not in self.outputs: - self.outputs.append(s) - elif(data.decode().split(':')[0] == "install"): - client_addr = (data.decode().split(':')[1],int(data.decode().split(':')[2])) - app_name = data.decode().split(':')[3] - app_file = data.decode().split(':')[4] - - if client_addr in self.conn_dict.keys(): - print('start install application %s to ("%s":"%s")' % (app_name, client_addr[0], client_addr[1])) - res = install(self.conn_dict[client_addr], app_name, app_file) - if self.message_queues[s] is not None: - logging.info("response {} to cmd server".format(res)) - self.message_queues[s].put(bytes(res, encoding = 'utf8')) - if s not in self.outputs: - self.outputs.append(s) - elif(data.decode().split(':')[0] == "uninstall"): - client_addr = (data.decode().split(':')[1],int(data.decode().split(':')[2])) - app_name = data.decode().split(':')[3] - - if client_addr in self.conn_dict.keys(): - print("start uninstall") - res = uninstall(self.conn_dict[client_addr], app_name) - if self.message_queues[s] is not None: - logging.info("response {} to cmd server".format(res)) - self.message_queues[s].put(bytes(res, encoding = 'utf8')) - if s not in self.outputs: - self.outputs.append(s) - - - # if self.message_queues[s] is not None: - # self.message_queues[s].put(data) - # if s not in self.outputs: - # self.outputs.append(s) - else: - logging.warning(data) - - # Interpret empty result as closed connection - try: - for dev in self.devices: - if s == dev.conn: - self.devices.remove(dev) - # Stop listening for input on the connection - if s in self.outputs: - self.outputs.remove(s) - self.inputs.remove(s) - - # Remove message queue - if s in self.message_queues.keys(): - del self.message_queues[s] - s.close() - except OSError as e: - logging.error("OSError raised, unknown connection") - return "got it" - - def handler_send(self, writable): - # Handle outputs - for s in writable: - try: - message_queue = self.message_queues.get(s) - send_data = '' - if message_queue is not None: - send_data = message_queue.get_nowait() - except queue.Empty: - self.outputs.remove(s) - else: - # print "sending %s to %s " % (send_data, s.getpeername) - # print "send something" - if message_queue is not None: - s.send(send_data) - else: - print("client has closed") - # del message_queues[s] - # writable.remove(s) - # print "Client %s disconnected" % (client_address) - return "got it" - - def handler_exception(self, exceptional): - # # Handle "exceptional conditions" - for s in exceptional: - print('exception condition on', s.getpeername()) - # Stop listening for input on the connection - self.inputs.remove(s) - if s in self.outputs: - self.outputs.remove(s) - s.close() - - # Remove message queue - del self.message_queues[s] - return "got it" - - -def event_loop(tcpserver, inputs, outputs): - while inputs: - # Wait for at least one of the sockets to be ready for processing - print('waiting for the next event') - readable, writable, exceptional = select.select(inputs, outputs, inputs) - if readable is not None: - tcp_recever = tcpserver.handler_recever(readable) - if tcp_recever == 'got it': - print("server have received") - if writable is not None: - tcp_send = tcpserver.handler_send(writable) - if tcp_send == 'got it': - print("server have send") - if exceptional is not None: - tcp_exception = tcpserver.handler_exception(exceptional) - if tcp_exception == 'got it': - print("server have exception") - - - sleep(0.1) - -def run_wasm_server(): - server_address = ('localhost', 8888) - server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) - inputs = [server] - outputs = [] - message_queues = {} - tcpserver = TCPServer(server, server_address, inputs, outputs, message_queues) - - task = threading.Thread(target=event_loop,args=(tcpserver,inputs,outputs)) - task.start() - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG, - filename='wasm_server.log', - filemode='a', - format= - '%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s' - ) - server_address = ('0.0.0.0', 8888) - server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) - inputs = [server] - outputs = [] - message_queues = {} - tcpserver = TCPServer(server, server_address, inputs, outputs, message_queues) - logging.info("TCP Server start at {}:{}".format(server_address[0], "8888")) - - task = threading.Thread(target=event_loop,args=(tcpserver,inputs,outputs)) - task.start() - - # event_loop(tcpserver, inputs, outputs) \ No newline at end of file diff --git a/test-tools/IoT-APP-Store-Demo/wasm_django/static/css/application.css b/test-tools/IoT-APP-Store-Demo/wasm_django/static/css/application.css deleted file mode 100644 index 220d4b618..000000000 --- a/test-tools/IoT-APP-Store-Demo/wasm_django/static/css/application.css +++ /dev/null @@ -1,400 +0,0 @@ -/* Copyright (C) 2019 Intel Corporation. All rights reserved. -* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -*/ - -{% load static %} - diff --git a/test-tools/IoT-APP-Store-Demo/wasm_django/static/js/application.js b/test-tools/IoT-APP-Store-Demo/wasm_django/static/js/application.js deleted file mode 100644 index 0510fb901..000000000 --- a/test-tools/IoT-APP-Store-Demo/wasm_django/static/js/application.js +++ /dev/null @@ -1,217 +0,0 @@ -/* Copyright (C) 2019 Intel Corporation. All rights reserved. -* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -*/ - -/* - * Dom Location - * - */ - - function setDivCenter(divname) -// make qn element center aligned - { - var Top =($(window).height()-$(divname).height())/2; - var Left = ($(window).width()-$(divname).width())/2; - var scrollTop = $(document).scrollTop(); - var scrollLeft = $(document).scrollLeft(); - $(divname).css({posisiton:'absolute','top':Top+scrollTop,'left':Left+scrollLeft}); - -}; - -setDivCenter(".middlebox"); -setDivCenter(".deletebox"); - -function setmain(divname){ -// Set the pop-up window of apps for download at the right place - var x = $('#btn').offset().top; - var Top = x + $('#btn').height()+15; - var y = $('#btn').offset().left; - var Left = y + ($('#btn').width()/2)-($(divname).width()/2); - console.log(Top,Left) - $(divname).css({'top':Top,'left':Left}); -} -setmain(".main") - -/* - * download apps - * - */ - -function getthis(val) -//Telling background which app to be loaded from appstore_list and to be installed in the current device. -{ - - /* Get the ip adress and the port of a device, as well as the application ID to be downloaded on this device*/ - var ip,port,name,version; - var ipArr=$("#IPs").text().split(":"); - ip=ipArr[1]; - var portArr=$("#ports").text().split(":"); - port=portArr[1]; - name = $(val).parent().find("#appsinfo1").text().split(":")[1]; - version = $(val).parent().find("#appsinfo2").text().split(":")[1]; - $(".main").fadeOut(); - - for (num in alist){ - if (alist[num]['pname'].trim() == name.trim()) - {alert("This app has been downloaded."); - return;}}; - $("#loading").fadeIn(); - var sNode = document.getElementById("APPS"); - var tempNode= sNode.cloneNode(true); - sNode.parentNode.appendChild(tempNode); - $("#appinfo1").html("Product Name : "+ name); - $("#appinfo2").html("Status : "+"Installing"); - $("#appinfo3").html("Current_Version : "+ version); - - $.get("/appDownload/",{'ip':ip.trim(),'port':port.trim(),'name':name.trim(),},function (ret) { - var status = $.trim(ret.split(":")[1].split("}")[0]); - $(".loadapp").html(name+" is downloading now"); - var msg = JSON.parse(status) - console.log(msg) - if (JSON.parse(status)=="ok"){ - $(".middlebox").fadeIn(); - $(".sourceapp").fadeOut(); - $("#loading").fadeOut(); - $(".findapp").html("Download "+name +" successfully"); - $(".surebtn").click(function (){ - $(".middlebox").fadeOut(); - window.location.reload(); - })} - else if (JSON.parse(status)=="Fail!"){ - alert("Download failed!"); - $("#loading").fadeOut(); - sNode.remove(); - } - else { - alert("Install app failed:" + msg) - $("#loading").fadeOut(); - sNode.remove(); - } - }) -}; - -window.onload = function clone() -//Add & Delete apps to the device. -{ - /*Install Apps*/ - var sourceNode = document.getElementById("APPS"); - if (alist.length != 0) - { - $("#appinfo1").html("Product Name : "+ alist[0]['pname']); - $("#appinfo2").html("Status : "+ alist[0]['status']); - $("#appinfo3").html("Current_Version : "+ alist[0]['current_version']); - $("#delete").attr('class','delet0'); - $("#APPS").attr('class','app0'); - - for (var i=1; i=3){ - alert("Install app failed: exceed max app installations.") - } - $(".main").fadeOut(); - getthis(".mybtn2"); - var newurl = "?"+"ip="+ip+"&port="+port; - window.location.href= newurl; - }); - - } -} -givevalue(); - -function popbox(){ -/*Open and close the "install apps" window*/ - $(".btn").click(function(){ - $(".main").fadeIn(); - }); - $(".close").click(function(){ - $(".main").fadeOut(); - }); -}; -popbox(); diff --git a/test-tools/IoT-APP-Store-Demo/wasm_django/static/js/appstore.js b/test-tools/IoT-APP-Store-Demo/wasm_django/static/js/appstore.js deleted file mode 100644 index 71d029efa..000000000 --- a/test-tools/IoT-APP-Store-Demo/wasm_django/static/js/appstore.js +++ /dev/null @@ -1,125 +0,0 @@ -/* Copyright (C) 2019 Intel Corporation. All rights reserved. -* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -*/ - -function setDivCenter(divname) -//Center a dom -{ - var Top =($(window).height()-$(divname).height())/2; - var Left = ($(window).width()-$(divname).width())/2; - var scrollTop = $(document).scrollTop(); - var scrollLeft = $(document).scrollLeft(); - $(divname).css({posisiton:'absolute','top':Top+scrollTop,'left':Left+scrollLeft}); - -}; -setDivCenter(".deletebox"); - -function setDivheight(divname) -//set the height of "appbook" to contain all its child elements. -{ - var leng = elist.length + flist.length; - var heig = 51 * leng; - $(divname).css({height:'heig'}); -}; -setDivheight(".appbook"); - -function setfooterposition(divname) -//Locate footer on the right place -{ - var Top = flist.length* $("#devices").height()+300; - var scrollTop = $(document).scrollTop(); - if (flist.length >=4){ - $(divname).css({posisiton:'absolute','top':Top+scrollTop}); - } -} -setfooterposition(".footer"); - -function deleteClick (obj) -//Remove an app from apppstore if clicks the "OK" button -{ - var indexapp = $(obj).attr('class').match(/\d+\b/); - var removeitem = $(".applic"+indexapp); - var name=removeitem.find('#appinfo1').text().split(":")[1].trim(); - var version=removeitem.find('#appinfo2').text().split(":")[1].trim(); - - if (flist.length >= 1){ - $(".deletebox").fadeIn(); - $(".findapp").html("Are you sure to delete "+name); - $(".suresbtn").click(function (){ - removeitem.remove(); - $.get("/removeapps/",{'name':name,'version':version},function (ret) { - console.log(ret);}); - $(".deletebox").fadeOut(); - window.location.href="/appstore/"; - }) - $(".delsbtn").click(function (){ - $(".deletebox").fadeOut(); })} -}; - -function upload_file() -//Make sure the uploading file is eligible -{ - var type = ulist[0]; - console.log(type); - if (type == "Not a wasm file"){ - alert(type); - window.location.href="/appstore/"; - } - if (type == "This App is preloaded"){ - alert(type); - window.location.href="/appstore/"; - } - if (type == "This App is already uploaded"){ - alert(type); - window.location.href="/appstore/"; - } -}; -upload_file(); - - -function clone() -//Render a interface that shows all the apps for installing in appstore, -//including preloaded ones and locally uploaded ones. -{ - - var sourceNode = document.getElementById("applications"); - $("#appinfo1").html("product name : "+ elist[0]['ID']); - $("#appinfo2").html("product Version : "+ elist[0]['Version']); - $("#delbutton").attr('class','del0'); - $("#applications").attr('class','applic0'); - - - for (var i=1; i=4){ - $(divname).css({posisiton:'absolute','top':Top+scrollTop}); - } -} -setfooterposition(".footer"); - -window.onload = function clone() -//Show the list of connected devices -{ - var sourceNode = document.getElementById("devices"); - $("#IPs").html("IP : "+ dlist[0]['IP']); - $("#ports").html("Port : "+ dlist[0]['Port']); - $("#installs").html("Installed Apps : "+ dlist[0]['apps']); - $("#devices").attr('class','devic0'); - $("#dbutton").attr('class','bt0'); - $("#choose").attr('class','chos0'); - - for (var i=1; i in order to generate the call-stack dump, you can use the following command: `$ cmake -DWAMR_BUILD_DUMP_CALL_STACK=1 ...` + +When a wasm file is compiled with debug info, it is possible to transfer the address to line info. + +For example, there is a call-stack dump: + +``` +#00: 0x0a04 - $f18 +#01: 0x08e4 - $f11 +#02: 0x096f - $f12 +#03: 0x01aa - _start +``` + +- store the call-stack dump into a file, e.g. call_stack.txt +- run the following command to transfer the address to line info: + ``` + $ cd test-tools/addr2line + $ python3 addr2line.py --wasi-sdk --wabt --wasm-file call_stack.txt + ``` +- the script will use *wasm-objdump* in wabt to transform address, then use *llvm-dwarfdump* to lookup the line info for each address + in the call-stack dump. +- the output will be: + ``` + #00: 0x0a04 - $f18 + #01: 0x08e4 - $f11 (FILE:quicksort.c LINE: 176 COLUMN: 11 FUNC:Quick) + #02: 0x096f - $f12 (FILE:quicksort.c LINE: 182 COLUMN: 3 FUNC:main) + #03: 0x01aa - _start + ``` + +""" + + +def get_code_section_start(wasm_objdump: Path, wasm_file: Path) -> int: + """ + Find the start offset of Code section in a wasm file. + + if the code section header likes: + Code start=0x0000017c end=0x00004382 (size=0x00004206) count: 47 + + the start offset is 0x0000017c + """ + cmd = f"{wasm_objdump} -h {wasm_file}" + p = subprocess.run( + shlex.split(cmd), + check=True, + capture_output=True, + text=True, + universal_newlines=True, + ) + outputs = p.stdout.split(os.linesep) + + # if there is no .debug section, return -1 + for line in outputs: + line = line.strip() + if ".debug_info" in line: + break + else: + print(f"No .debug_info section found {wasm_file}") + return -1 + + for line in outputs: + line = line.strip() + if "Code" in line: + return int(line.split()[1].split("=")[1], 16) + + return -1 + + +def get_line_info(dwarf_dump: Path, wasm_file: Path, offset: int) -> str: + """ + Find the location info of a given offset in a wasm file. + """ + cmd = f"{dwarf_dump} --lookup={offset} {wasm_file}" + p = subprocess.run( + shlex.split(cmd), + check=False, + capture_output=True, + text=True, + universal_newlines=True, + ) + outputs = p.stdout.split(os.linesep) + + capture_name = False + for line in outputs: + line = line.strip() + + if "DW_TAG_subprogram" in line: + capture_name = True + continue + + if "DW_AT_name" in line and capture_name: + PATTERN = r"DW_AT_name\s+\(\"(\S+)\"\)" + m = re.match(PATTERN, line) + assert m is not None + + function_name = m.groups()[0] + + if line.startswith("Line info"): + location = line + return (function_name, location) + + return () + + +def parse_line_info(line_info: str) -> (): + """ + line_info -> [file, line, column] + """ + PATTERN = r"Line info: file \'(.+)\', line ([0-9]+), column ([0-9]+)" + m = re.search(PATTERN, line_info) + assert m is not None + + file, line, column = m.groups() + return (file, int(line), int(column)) + + +def parse_call_stack_line(line: str) -> (): + """ + #00: 0x0a04 - $f18 => (00, 0x0a04, $f18) + """ + PATTERN = r"#([0-9]+): 0x([0-9a-f]+) - (\S+)" + m = re.match(PATTERN, line) + return m.groups() if m else None + + +def main(): + parser = argparse.ArgumentParser(description="addr2line for wasm") + parser.add_argument("--wasi-sdk", type=Path, help="path to wasi-sdk") + parser.add_argument("--wabt", type=Path, help="path to wabt") + parser.add_argument("--wasm-file", type=Path, help="path to wasm file") + parser.add_argument("call_stack_file", type=Path, help="path to a call stack file") + args = parser.parse_args() + + wasm_objdump = args.wabt.joinpath("bin/wasm-objdump") + assert wasm_objdump.exists() + + llvm_dwarf_dump = args.wasi_sdk.joinpath("bin/llvm-dwarfdump") + assert llvm_dwarf_dump.exists() + + code_section_start = get_code_section_start(wasm_objdump, args.wasm_file) + if code_section_start == -1: + return -1 + + assert args.call_stack_file.exists() + with open(args.call_stack_file, "rt", encoding="ascii") as f: + for line in f: + line = line.strip() + + if not line: + continue + + splitted = parse_call_stack_line(line) + if splitted is None: + print(line) + continue + + _, offset, _ = splitted + + offset = int(offset, 16) + offset = offset - code_section_start + line_info = get_line_info(llvm_dwarf_dump, args.wasm_file, offset) + if not line_info: + print(line) + continue + + function_name, line_info = line_info + src_file, src_line, src_column = parse_line_info(line_info) + print( + f"{line} (FILE:{src_file} LINE:{src_line:5} COLUMN:{src_column:3} FUNC:{function_name})" + ) + + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/test-tools/component-test/README.md b/test-tools/component-test/README.md deleted file mode 100644 index c72d0fcb8..000000000 --- a/test-tools/component-test/README.md +++ /dev/null @@ -1,56 +0,0 @@ -# Component Test - -The purpose of this test suite is to verify the basic components of WAMR work well in combination. It is highly recommended to run pass all suites before each commitment. - -Prerequisites -============== -- clang is available to build wasm application. -- python is installed to run test script. - - -Run the test -============= -``` -start.py [-h] [-s SUITE_ID [SUITE_ID ...]] [-t CASE_ID [CASE_ID ...]] - [-n REPEAT_TIME] [--shuffle_all] - [--cases_list CASES_LIST_FILE_PATH] [--skip_proc] - [-b BINARIES] [-d] [--rebuild] -``` -It builds out the simple project binary including WAMR runtime binary ```simple``` and the testing tool ```host_tool``` before running the test suites. - -Test output is like: -``` -Test Execution Summary: - Success: 8 - Cases fails: 0 - Setup fails: 0 - Case load fails: 0 - - ------------------------------------------------------------- -The run folder is [run-03-23-16-29] -that's all. bye -kill to quit.. -Killed -``` - -The detailed report and log is generated in ```run``` folder. The binaries copy is also put in that folder. - -Usage samples -============== - -Run default test suite: -
-```python start.py``` - -Rebuild all test apps and then run default test suite: -
-```python start.py --rebuild``` - -Run a specified test suite: -
-```python start.py -s 01-life-cycle``` - -Run a specified test case: -
-```python start.py -t 01-install``` \ No newline at end of file diff --git a/test-tools/component-test/__init__.py b/test-tools/component-test/__init__.py deleted file mode 100644 index fd734d561..000000000 --- a/test-tools/component-test/__init__.py +++ /dev/null @@ -1,11 +0,0 @@ -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# -__all__ = [ - "net_manager", "wifi_daemon_utils" -] - -__author__ = "" -__package__ = "model" -__version__ = "1.0" diff --git a/test-tools/component-test/framework/__init__.py b/test-tools/component-test/framework/__init__.py deleted file mode 100644 index fd734d561..000000000 --- a/test-tools/component-test/framework/__init__.py +++ /dev/null @@ -1,11 +0,0 @@ -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# -__all__ = [ - "net_manager", "wifi_daemon_utils" -] - -__author__ = "" -__package__ = "model" -__version__ = "1.0" diff --git a/test-tools/component-test/framework/case_base.py b/test-tools/component-test/framework/case_base.py deleted file mode 100644 index 311de5eaa..000000000 --- a/test-tools/component-test/framework/case_base.py +++ /dev/null @@ -1,29 +0,0 @@ -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -import os -import json -from test.test_support import _run_suite - -class CTestCaseBase(object): - def __init__(self, suite): - self.m_suite = suite - return - def on_get_case_description(self): - return "Undefined" - - def on_setup_case(self): - return True, '' - - def on_cleanup_case(self): - return True, '' - - # called by the framework - def on_run_case(self): - return True, '' - - def get_suite(self): - return self.m_suite - diff --git a/test-tools/component-test/framework/engine.py b/test-tools/component-test/framework/engine.py deleted file mode 100644 index 6c68a1eb1..000000000 --- a/test-tools/component-test/framework/engine.py +++ /dev/null @@ -1,39 +0,0 @@ -from __future__ import print_function -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -import datetime -import os -import pprint -import random -import re -import shlex -import subprocess -import signal -import sys -import time - -from .test_utils import * -from .test_api import * - - - - -def read_cases_from_file(file_path): - if not os.path.exists(file_path): - return False, None - - with open(file_path, 'r') as f: - content = f.readlines() - - content = [x.strip() for x in content] - print(content) - if len(content) == 0: - return False, None - - return True, content - - - diff --git a/test-tools/component-test/framework/framework.py b/test-tools/component-test/framework/framework.py deleted file mode 100644 index 99f0b0772..000000000 --- a/test-tools/component-test/framework/framework.py +++ /dev/null @@ -1,288 +0,0 @@ -from __future__ import print_function -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -import datetime -import os -import pprint -import random -import re -import shlex -import subprocess -import signal -import sys -import time -import shutil - -from .test_api import * -import this - - -''' -The run evironment dir structure: - - run/ - run{date-time}/ - suites/ - {suite name}/ - -- target/ (the target software being tested) - -- tools/ (the tools for testing the target software) -''' - - -framework=None - -def get_framework(): - global framework - return framework - -def my_import(name): - mod = __import__(name) - components = name.split('.') - for comp in components[1:]: - mod = getattr(mod, comp) - return mod - - -# we maintain a root path apart from framework location -# so the suites can be located in anywhere -class CTestFramework(object): - - def __init__(self, path): - self.running_case = '' - self.running_suite = '' - self.target_suites = {} - self.target_cases = {} - self.root_path = path - self.running_folder='' - self.report = None - self.sucess_cases = 0 - self.failed_cases = 0 - self.setup_fails = 0 - self.load_fails = 0; - global framework - framework = self - - api_set_root_path(path) - - print("root_path is " + self.root_path) - - def gen_execution_stats(self): - return '\nTest Execution Summary: ' \ - '\n\tSuccess: {}' \ - '\n\tCases fails: {}' \ - '\n\tSetup fails: {}' \ - '\n\tCase load fails: {}'.format( - self.sucess_cases, self.failed_cases, self.setup_fails, self.load_fails) - - def report_result(self, success, message, case_description): - if self.report is None: - return - - case_pass = "pass" - if not success: - case_pass = "fail" - - self.report.write(case_pass + ": [" + self.running_case + "]\n\treason: " + \ - message + "\n\tcase: " + case_description + "\n") - return - - def get_running_path(self): - return self.root_path + "/run/" + self.running_folder - - def load_suites(self): - self.target_suites = os.listdir(self.root_path + "/suites") - return - - def run_case(self, suite_instance, case): - # load the test case module - case_description = '' - suite = suite_instance.m_name - api_log("\n>>start run [" + case + "] >>") - module_name = 'suites.' + suite + ".cases." + case + ".case" - try: - module = my_import(module_name) - except Exception as e: - report_fail("load case fail: " + str(e)) - api_log_error("load case fail: " + str(e)) - self.load_fails = self.load_fails +1 - print(traceback.format_exc()) - return False - - try: - case = module.CTestCase(suite_instance) - except Exception as e: - report_fail("initialize case fail: " + str(e)) - api_log_error("initialize case fail: " + str(e)) - self.load_fails = self.load_fails +1 - return False - - # call the case on setup callback - try: - case_description = case.on_get_case_description() - result, message = case.on_setup_case() - except Exception as e: - result = False - message = str(e); - if not result: - api_log_error(message) - report_fail (message, case_description) - self.failed_cases = self.failed_cases+1 - return False - - # call the case execution callaback - try: - result, message = case.on_run_case() - except Exception as e: - result = False - message = str(e); - if not result: - report_fail (message, case_description) - api_log_error(message) - self.failed_cases = self.failed_cases+1 - else: - report_success(case_description) - self.sucess_cases = self.sucess_cases +1 - - # call the case cleanup callback - try: - clean_result, message = case.on_cleanup_case() - except Exception as e: - clean_result = False - message = str(e) - - if not clean_result: - api_log(message) - - return result - - def run_suite(self, suite, cases): - # suite setup - message = '' - api_log("\n>>> Suite [" + suite + "] starting >>>") - running_folder = self.get_running_path()+ "/suites/" + suite; - - module_name = 'suites.' + suite + ".suite_setup" - try: - module = my_import(module_name) - except Exception as e: - report_fail("load suite [" + suite +"] fail: " + str(e)) - self.load_fails = self.load_fails +1 - return False - - try: - suite_instance = module.CTestSuite(suite, \ - self.root_path + '/suites/' + suite, running_folder) - except Exception as e: - report_fail("initialize suite fail: " + str(e)) - self.load_fails = self.load_fails +1 - return False - - result, message = suite_instance.load_settings() - if not result: - report_fail("load settings fail: " + str(e)) - self.load_fails = self.load_fails +1 - return False - - try: - result, message = suite_instance.on_suite_setup() - except Exception as e: - result = False - message = str(e); - if not result: - api_log_error(message) - report_fail (message) - self.setup_fails = self.setup_fails + 1 - return False - - self.running_suite = suite - - cases.sort() - - # run cases - for case in cases: - if not os.path.isdir(self.root_path + '/suites/' + suite + '/cases/' + case): - continue - - self.running_case = case - self.run_case(suite_instance, case) - self.running_case = '' - - # suites cleanup - self.running_suite = '' - try: - result, message = suite_instance.on_suite_cleanup() - except Exception as e: - result = False - message = str(e); - if not result: - api_log_error(message) - report_fail (message) - self.setup_fails = self.setup_fails + 1 - return - - def start_run(self): - if self.target_suites is None: - print("\n\nstart run: no target suites, exit..") - return - - cur_time = time.localtime() - time_prefix = "{:02}-{:02}-{:02}-{:02}".format( - cur_time.tm_mon, cur_time.tm_mday, cur_time.tm_hour, cur_time.tm_min) - - debug = api_get_value('debug', False) - if debug: - self.running_folder = 'debug' - else: - self.running_folder = 'run-' + time_prefix - - folder = self.root_path + "/run/" +self.running_folder; - - if os.path.exists(folder): - shutil.rmtree(folder, ignore_errors=True) - - if not os.path.exists(folder): - os.makedirs(folder ) - os.makedirs(folder + "/suites") - - api_init_log(folder + "/test.log") - - self.report = open(folder + "/report.txt", 'a') - - self.target_suites.sort() - - for suite in self.target_suites: - if not os.path.isdir(self.root_path + '/suites/' + suite): - continue - self.report.write("suite " + suite + " cases:\n") - if self.target_cases is None: - cases = os.listdir(self.root_path + "/suites/" + suite + "/cases") - self.run_suite(suite, cases) - else: - self.run_suite(suite, self.target_cases) - self.report.write("\n") - - self.report.write("\n\n") - summary = self.gen_execution_stats() - self.report.write(summary); - self.report.flush() - self.report.close() - print(summary) - - -def report_fail(message, case_description=''): - global framework - if framework is not None: - framework.report_result(False, message, case_description) - - api_log_error(message) - - return - -def report_success(case_description=''): - global framework - if framework is not None: - framework.report_result(True , "OK", case_description) - return diff --git a/test-tools/component-test/framework/suite.py b/test-tools/component-test/framework/suite.py deleted file mode 100644 index 2b690b08f..000000000 --- a/test-tools/component-test/framework/suite.py +++ /dev/null @@ -1,40 +0,0 @@ -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -import os -import json - -class CTestSuiteBase(object): - def __init__(self, name, suite_path, run_path): - self.suite_path=suite_path - self.run_path=run_path - self.m_name = name - self.settings = {} - - def get_settings_item(self, item): - if item in self.settings: - return self.settings[item] - else: - return None - - def load_settings(self): - path = self.suite_path + "/settings.cfg" - if os.path.isfile(path): - try: - fp = open(path, 'r') - self.settings = json.load(fp) - fp.close() - except Exception, e: - return False, 'Load settings fail: ' + e.message - return True, 'OK' - else: - return True, 'No file' - - def on_suite_setup(self): - return True, 'OK' - - def on_suite_cleanup(self): - return True, 'OK' - diff --git a/test-tools/component-test/framework/test_api.py b/test-tools/component-test/framework/test_api.py deleted file mode 100644 index 82a7e6dd0..000000000 --- a/test-tools/component-test/framework/test_api.py +++ /dev/null @@ -1,99 +0,0 @@ -from __future__ import print_function -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -import logging -import threading -from .test_utils import * - -global logger -logger = None - -def api_init_log(log_path): - global logger - print("api_init_log: " + log_path) - logger = logging.getLogger(__name__) - - logger.setLevel(level = logging.INFO) - handler = logging.FileHandler(log_path) - handler.setLevel(logging.INFO) - formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') - handler.setFormatter(formatter) - - console = logging.StreamHandler() - console.setLevel(logging.INFO) - - logger.addHandler(handler) - logger.addHandler(console) - - return - -def api_log(message): - global logger - if logger is None: - print(message) - else: - logger.info (message) - return - -def api_log_error(message): - global logger - if logger is None: - print(message) - else: - logger.error (message) - return - -def api_logv(message): - global logger - if logger is None: - print(message) - else: - logger.info(message) - return - -#####################################3 -global g_case_runner_event -def api_wait_case_event(timeout): - global g_case_runner_event - g_case_runner_event.clear() - g_case_runner_event.wait(timeout) - -def api_notify_case_runner(): - global g_case_runner_event - g_case_runner_event.set() - -def api_create_case_event(): - global g_case_runner_event - g_case_runner_event = threading.Event() - -####################################### - -def api_init_globals(): - global _global_dict - _global_dict = {} - -def api_set_value(name, value): - _global_dict[name] = value - -def api_get_value(name, defValue=None): - try: - return _global_dict[name] - except KeyError: - return defValue - - -######################################### -global root_path -def api_set_root_path(root): - global root_path - root_path = root - -def api_get_root_path(): - global root_path - return root_path; - - - diff --git a/test-tools/component-test/framework/test_utils.py b/test-tools/component-test/framework/test_utils.py deleted file mode 100644 index e3eb645ae..000000000 --- a/test-tools/component-test/framework/test_utils.py +++ /dev/null @@ -1,71 +0,0 @@ -from __future__ import print_function -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -import datetime -import os -import random -import re -import shlex -import subprocess -import sys -import time -import shutil -from subprocess import check_output, CalledProcessError - -def t_getPIDs(process): - try: - pidlist = map(int, check_output(["pidof", process]).split()) - except CalledProcessError: - pidlist = [] - #print process + ':list of PIDs = ' + ', '.join(str(e) for e in pidlist) - return pidlist - - -def t_kill_process_by_name(p_keywords): - pid_list = [] - ps_info = subprocess.check_output(shlex.split("ps aux")).split("\n") - for p in ps_info: - if p_keywords in p: - tmp = p.split(" ") - tmp = [x for x in tmp if len(x) > 0] - pid_list.append(tmp[1]) - - for pid in pid_list: - cmd = "kill -9 {}".format(pid) - subprocess.call(shlex.split(cmd)) - - return pid_list - - - -#proc -> name of the process -#kill = 1 -> search for pid for kill -#kill = 0 -> search for name (default) - -def t_process_exists(proc, kill = 0): - ret = False - processes = t_getPIDs(proc) - - for pid in processes: - if kill == 0: - return True - else: - print("kill [" + proc + "], pid=" + str(pid)) - os.kill((pid), 9) - ret = True - return ret - -def t_copy_files(source_dir, pattern, dest_dir): - files = os.listdir(source_dir) - for file in files: - if file in ('/', '.', '..'): - continue - - if pattern in ('*', '') or files.endswith(pattern): - shutil.copy(source_dir+"/"+ file, dest_dir) - - - diff --git a/test-tools/component-test/harness/__init__.py b/test-tools/component-test/harness/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/test-tools/component-test/harness/harness_api.py b/test-tools/component-test/harness/harness_api.py deleted file mode 100644 index e35aa6b4c..000000000 --- a/test-tools/component-test/harness/harness_api.py +++ /dev/null @@ -1,150 +0,0 @@ -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -import os -import shutil -import subprocess -import json -import time - -from framework import test_api -from framework.test_utils import * - -output = "output.txt" - -def start_env(): - os.system("./start.sh") - -def stop_env(): - os.system("./stop.sh") - time.sleep(0.5) - os.chdir("../") #reset path for other cases in the same suite - -def check_is_timeout(): - line_num = 0 - ft = open(output, 'r') - lines = ft.readlines() - - for line in reversed(lines): - if (line[0:36] == "--------one operation begin.--------"): - break - line_num = line_num + 1 - - ft.close() - if (lines[-(line_num)] == "operation timeout"): - return True - else: - return False - -def parse_ret(file): - ft = open(file, 'a') - ft.writelines("\n") - ft.writelines("--------one operation finish.--------") - ft.writelines("\n") - ft.close() - - ft = open(file, 'r') - for line in reversed(ft.readlines()): - if (line[0:16] == "response status "): - ret = line[16:] - ft.close() - return int(ret) - -def run_host_tool(cmd, file): - ft = open(file, 'a') - ft.writelines("--------one operation begin.--------") - ft.writelines("\n") - ft.close() - os.system(cmd + " -o" + file) - if (check_is_timeout() == True): - return -1 - return parse_ret(file) - -def install_app(app_name, file_name): - return run_host_tool("./host_tool -i " + app_name + " -f ../test-app/" + file_name, output) - -def uninstall_app(app_name): - return run_host_tool("./host_tool -u " + app_name, output) - -def query_app(): - return run_host_tool("./host_tool -q ", output) - -def send_request(url, action, payload): - if (payload is None): - return run_host_tool("./host_tool -r " + url + " -A " + action, output) - else: - return run_host_tool("./host_tool -r " + url + " -A " + action + " -p " + payload, output) - -def register(url, timeout, alive_time): - return run_host_tool("./host_tool -s " + url + " -t " + str(timeout) + " -a " + str(alive_time), output) - -def deregister(url): - return run_host_tool("./host_tool -d " + url, output) - -def get_response_payload(): - line_num = 0 - ft = open(output, 'r') - lines = ft.readlines() - - for line in reversed(lines): - if (line[0:16] == "response status "): - break - line_num = line_num + 1 - - payload_lines = lines[-(line_num):-1] - ft.close() - - return payload_lines - -def check_query_apps(expected_app_list): - if (check_is_timeout() == True): - return False - json_lines = get_response_payload() - json_str = " ".join(json_lines) - json_dict = json.loads(json_str) - app_list = [] - - for key, value in json_dict.items(): - if key[0:6] == "applet": - app_list.append(value) - - if (sorted(app_list) == sorted(expected_app_list)): - return True - else: - return False - -def check_response_payload(expected_payload): - if (check_is_timeout() == True): - return False - json_lines = get_response_payload() - json_str = " ".join(json_lines) - - if (json_str.strip() != ""): - json_dict = json.loads(json_str) - else: - json_dict = {} - - if (json_dict == expected_payload): - return True - else: - return False - -def check_get_event(): - line_num = 0 - ft = open(output, 'r') - lines = ft.readlines() - - for line in reversed(lines): - if (line[0:16] == "response status "): - break - line_num = line_num + 1 - - payload_lines = lines[-(line_num):-1] - ft.close() - - if (payload_lines[1][0:17] == "received an event"): - return True - else: - return False diff --git a/test-tools/component-test/host-clients/src/host_app_sample.c b/test-tools/component-test/host-clients/src/host_app_sample.c deleted file mode 100644 index c4010de6a..000000000 --- a/test-tools/component-test/host-clients/src/host_app_sample.c +++ /dev/null @@ -1,301 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include -#include -#include -#include -#include "host_api.h" -#include "bi-inc/attr_container.h" -#include "er-coap-constants.h" - -static char * -read_file_to_buffer(const char *filename, int *ret_size); -int send_request_to_applet_success = 0; -const char *label_for_request = "request1"; -int event_listener_counter = 0; -char *applet_buf[1024 * 1024]; -const char *host_agent_ip = "127.0.0.1"; -void -f_aee_response_handler(void *usr_ctx, aee_response_t *response) -{ - if (response == NULL) { - printf("########## request timeout!!! \n"); - } - else { - char *str = (char *)usr_ctx; - printf("#### dump response ####\n"); - printf("#### user data: %s \n", str); - printf("#### status: %d \n", response->status); - if (response->payload != NULL) - attr_container_dump((attr_container_t *)response->payload); - } -} - -void -f_aee_event_listener(const char *url, void *event, int fmt) -{ - printf("######## event is received. url: %s, fmt:%d ############\n", url, - fmt); - - attr_container_t *attr_obj = (attr_container_t *)event; - - attr_container_dump(attr_obj); - /* - if (0 == strcmp(url, "alert/overheat")) - { - event_listener_counter++; - printf("event :%d \n", event_listener_counter); - } - */ -} - -static int -print_menu_and_select(void) -{ - char s[256]; - int choice; - do { - printf("\n"); - printf("1. Install TestApplet1\n"); - printf("2. Install TestApplet2\n"); - printf("3. Install TestApplet3\n"); - printf("4. Uninstall TestApplet1\n"); - printf("5. Uninstall TestApplet2\n"); - printf("6. Uninstall TestApplet3\n"); - printf("7. Send Request to TestApplet1\n"); - printf("8. Register Event to TestApplet1\n"); - printf("9. UnRegister Event to TestApplet1\n"); - printf("a. Query Applets\n"); - printf("t. Auto Test\n"); - printf("q. Exit\n"); - printf("Please Select: "); - - if (fgets(s, sizeof(s), stdin)) { - if (!strncmp(s, "q", 1)) - return 0; - if (!strncmp(s, "a", 1)) - return 10; - if (!strncmp(s, "t", 1)) - return 20; - choice = atoi(s); - if (choice >= 1 && choice <= 9) - return choice; - } - } while (1); - return 0; -} - -static void -install_applet(int index) -{ - char applet_name[64]; - char applet_file_name[64]; - char *buf; - int size; - int ret; - - printf("Installing TestApplet%d...\n", index); - snprintf(applet_name, sizeof(applet_name), "TestApplet%d", index); - snprintf(applet_file_name, sizeof(applet_file_name), "./TestApplet%d.wasm", - index); - buf = read_file_to_buffer(applet_file_name, &size); - if (!buf) { - printf("Install Applet failed: read file %s error.\n", - applet_file_name); - return; - } - - // step2. install applet - ret = aee_applet_install(buf, "wasm", size, applet_name, 5000); - if (ret) { - printf("%s install success\n", applet_name); - } - free(buf); -} - -static void -uninstall_applet(int index) -{ - int ret; - char applet_name[64]; - snprintf(applet_name, sizeof(applet_name), "TestApplet%d", index); - ret = aee_applet_uninstall(applet_name, "wasm", 5000); - if (ret) { - printf("uninstall %s success\n", applet_name); - } - else { - printf("uninstall %s failed\n", applet_name); - } -} - -static void -send_request(int index) -{ - char url[64]; - int ret; - aee_request_t req; - const char *user_context = "label for request"; - attr_container_t *attr_obj = - attr_container_create("Send Request to Applet"); - attr_container_set_string(&attr_obj, "String key", "Hello"); - attr_container_set_int(&attr_obj, "Int key", 1000); - attr_container_set_int64(&attr_obj, "Int64 key", 0x77BBCCDD11223344LL); - - // specify the target wasm app - snprintf(url, sizeof(url), "/app/TestApplet%d/url1", index); - - // not specify the target wasm app - // snprintf(url, sizeof(url), "url1"); - aee_request_init(&req, url, COAP_PUT); - aee_request_set_payload(&req, attr_obj, - attr_container_get_serialize_length(attr_obj), - PAYLOAD_FORMAT_ATTRIBUTE_OBJECT); - ret = aee_request_send(&req, f_aee_response_handler, (void *)user_context, - 10000); - - if (ret) { - printf("send request to TestApplet1 success\n"); - } -} - -static void -register_event(const char *event_path) -{ - hostclient_register_event(event_path, f_aee_event_listener); -} - -static void -unregister_event(const char *event_path) -{ - hostclient_unregister_event(event_path); -} - -static void -query_applets() -{ - aee_applet_list_t applet_lst; - aee_applet_list_init(&applet_lst); - aee_applet_list(5000, &applet_lst); - aee_applet_list_clean(&applet_lst); -} - -static char * -read_file_to_buffer(const char *filename, int *ret_size) -{ - FILE *fl = NULL; - char *buffer = NULL; - int file_size = 0; - if (!(fl = fopen(filename, "rb"))) { - printf("file open failed\n"); - return NULL; - } - - fseek(fl, 0, SEEK_END); - file_size = ftell(fl); - - if (file_size == 0) { - printf("file length 0\n"); - return NULL; - } - - if (!(buffer = (char *)malloc(file_size))) { - fclose(fl); - return NULL; - } - - fseek(fl, 0, SEEK_SET); - - if (!fread(buffer, 1, file_size, fl)) { - printf("file read failed\n"); - return NULL; - } - - fclose(fl); - *ret_size = file_size; - return buffer; -} - -static void -auto_test() -{ - int i; - int interval = 1000; /* ms */ - while (1) { - uninstall_applet(1); - uninstall_applet(2); - uninstall_applet(3); - install_applet(1); - install_applet(2); - install_applet(3); - - for (i = 0; i < 60 * 1000 / interval; i++) { - query_applets(); - send_request(1); - send_request(2); - send_request(3); - usleep(interval * 1000); - } - } -} - -void -exit_program() -{ - hostclient_shutdown(); - exit(0); -} - -int - -main() -{ - bool ret; - - // step1. host client init - ret = hostclient_initialize(host_agent_ip, 3456); - - if (!ret) { - printf("host client initialize failed\n"); - return -1; - } - - do { - int choice = print_menu_and_select(); - printf("\n"); - - if (choice == 0) - exit_program(); - if (choice <= 3) - install_applet(choice); - else if (choice <= 6) - uninstall_applet(choice - 3); - else if (choice <= 7) - send_request(1); - else if (choice <= 8) - register_event("alert/overheat"); - else if (choice <= 9) - unregister_event("alert/overheat"); - else if (choice == 10) - query_applets(); - else if (choice == 20) - auto_test(); - } while (1); - - return 0; -} - -// Run program: Ctrl + F5 or Debug > Start Without Debugging menu -// Debug program: F5 or Debug > Start Debugging menu - -// Tips for Getting Started: -// 1. Use the Solution Explorer window to add/manage files -// 2. Use the Team Explorer window to connect to source control -// 3. Use the Output window to see build output and other messages -// 4. Use the Error List window to view errors -// 5. Go to Project > Add New Item to create new code files, or -// Project > Add Existing Item to add existing code files to the project -// 6. In the future, to open this project again, go to File > Open > Project -// and select the .sln file diff --git a/test-tools/component-test/host-clients/src/makefile b/test-tools/component-test/host-clients/src/makefile deleted file mode 100644 index 763a60c38..000000000 --- a/test-tools/component-test/host-clients/src/makefile +++ /dev/null @@ -1,44 +0,0 @@ -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -CC = gcc -CFLAGS := -Wall -g - -# Add this to make compiler happy -CFLAGS += -DWASM_ENABLE_INTERP=1 - -host_api_c=../../../../host-agent/host-api-c -attr_container_dir=../../../../wamr/core/app-framework/app-native-shared -coap_dir=../../../../host-agent/coap -shared_dir=../../../../wamr/core/shared - -# core -INCLUDE_PATH = -I$(host_api_c)/src -I$(attr_container_dir)/ \ - -I$(coap_dir)/er-coap -I$(coap_dir)/er-coap/extension \ - -I$(shared_dir)/include \ - -I$(shared_dir)/utils \ - -I$(shared_dir)/platform/include/ \ - -I$(shared_dir)/platform/linux/ - -LIB := $(host_api_c)/src/libhostapi.a -EXE := ./hostapp - -App_C_Files := host_app_sample.c - -OBJS := $(App_C_Files:.c=.o) - -all: $(EXE) - -%.o: %.c - @$(CC) $(CFLAGS) -c $< -o $@ $(INCLUDE_PATH) - -$(EXE): $(OBJS) - @rm -f $(EXE) - @$(CC) $(OBJS) -o $(EXE) $(LIB) -lpthread -lrt - @rm -f $(OBJS) - -.PHONY: clean -clean: - rm -f $(OBJS) $(EXE) diff --git a/test-tools/component-test/set_dev_env.sh b/test-tools/component-test/set_dev_env.sh deleted file mode 100755 index 1abe23b80..000000000 --- a/test-tools/component-test/set_dev_env.sh +++ /dev/null @@ -1,7 +0,0 @@ -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -#!/bin/sh - diff --git a/test-tools/component-test/start.py b/test-tools/component-test/start.py deleted file mode 100755 index 2cbc4fe63..000000000 --- a/test-tools/component-test/start.py +++ /dev/null @@ -1,152 +0,0 @@ -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -#!/usr/bin/env python - -# -*- coding: utf-8 -*- -""" -It is the entrance of the iagent test framework. - -""" -from __future__ import print_function - -import argparse -import datetime -import os -import pprint -import random -import re -import shlex -import subprocess -import signal -import sys -import time - -sys.path.append('../../../app-sdk/python') -from framework.test_utils import * -from framework.framework import * - - -def signal_handler(signal, frame): - print('Pressed Ctrl+C!') - sys.exit(0) - -def Register_signal_handler(): - signal.signal(signal.SIGINT, signal_handler) -# signal.pause() - - -def flatten_args_list(l): - if l is None: - return None - - return [x for y in l for x in y] - - - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description = "to run specific case(s) "\ - "in specific suite(s) with FC test framework") - parser.add_argument('-s', dest = 'suite_id', action = 'append', - nargs = '+', - help = 'one or multiple suite ids, which are also setup ids.'\ - 'by default if it isn\'t passed from argument, all '\ - 'suites are going to be run.') - parser.add_argument('-t', dest = 'case_id', action = 'append', - nargs = '+', - help = 'one or multiple cases ids.'\ - 'by default if it isn\'t passed from argument, all '\ - 'cases in specific suites are going to be run.') - parser.add_argument('-n', dest = 'repeat_time', action = 'store', - default = 1, - help = 'how many times do you want to run. there is 40s '\ - 'break time between two rounds. each round includs '\ - 'init_setup, run_test_case and deinit_setup.') - parser.add_argument('--shuffle_all', dest = 'shuffle_all', - default = False, action = 'store_true', - help = 'shuffle_all test cases in per test suite '\ - 'by default, all cases under per suite should '\ - 'be executed by input order.') - parser.add_argument('--cases_list', dest='cases_list_file_path', - default=None, - action='store', - help="read cases list from a flie ") - parser.add_argument('--skip_proc', dest='skip_proc', - default = False, action = 'store_true', - help='do not start the test process.'\ - 'sometimes the gw_broker process will be started in eclipse for debug purpose') - parser.add_argument('-b', dest = 'binaries', action = 'store', - help = 'The path of target folder ') - parser.add_argument('-d', dest = 'debug', action = 'store_true', - help = 'wait user to attach the target process after launch processes ') - parser.add_argument('--rebuild', dest = 'rebuild', action = 'store_true', - help = 'rebuild all test binaries') - args = parser.parse_args() - - print("------------------------------------------------------------") - print("parsing arguments ... ...") - print(args) - - ''' - logger = logging.getLogger('coapthon.server.coap') - logger.setLevel(logging.DEBUG) - console = logging.StreamHandler() - console.setLevel(logging.DEBUG) - logger.addHandler(console) - ''' - print("------------------------------------------------------------") - print("preparing wamr binary and test tools ... ...") - os.system("cd ../../samples/simple/ && bash build.sh -p host-interp") - - Register_signal_handler() - - api_init_globals(); - - api_create_case_event(); - - suites_list = flatten_args_list(args.suite_id) - cases_list = flatten_args_list(args.case_id) - - dirname, filename = os.path.split(os.path.abspath(sys.argv[0])) - api_set_root_path(dirname); - - framework = CTestFramework(dirname); - framework.repeat_time = int(args.repeat_time) - framework.shuffle_all = args.shuffle_all - framework.skip_proc=args.skip_proc - - api_set_value('keep_env', args.skip_proc) - api_set_value('debug', args.debug) - api_set_value('rebuild', args.rebuild) - - binary_path = args.binaries - if binary_path is None: - binary_path = os.path.abspath(dirname + '/../..') - - print("checking execution binary path: " + binary_path) - if not os.path.exists(binary_path): - print("The execution binary path was not available. quit...") - os._exit(0) - api_set_value('binary_path', binary_path) - - if suites_list is not None: - framework.target_suites = suites_list - else: - framework.load_suites() - - framework.target_cases = cases_list - framework.start_run() - - print("\n\n------------------------------------------------------------") - print("The run folder is [" + framework.running_folder +"]") - print("that's all. bye") - - print("kill to quit..") - t_kill_process_by_name("start.py") - - sys.exit(0) - os._exit() - - diff --git a/test-tools/component-test/suites/01-life-cycle/__init__.py b/test-tools/component-test/suites/01-life-cycle/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/test-tools/component-test/suites/01-life-cycle/cases/01-install/__init__.py b/test-tools/component-test/suites/01-life-cycle/cases/01-install/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/test-tools/component-test/suites/01-life-cycle/cases/01-install/case.py b/test-tools/component-test/suites/01-life-cycle/cases/01-install/case.py deleted file mode 100644 index b8d2c38b8..000000000 --- a/test-tools/component-test/suites/01-life-cycle/cases/01-install/case.py +++ /dev/null @@ -1,94 +0,0 @@ -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -import sys -import time -import random -import logging -import json - -from framework.case_base import * -from framework.test_api import * -from harness.harness_api import * - -class CTestCase(CTestCaseBase): - def __init__(self, suite): - CTestCaseBase.__init__(self, suite) - - def get_case_name(self): - case_path = os.path.dirname(os.path.abspath( __file__ )) - return os.path.split(case_path)[1] - - def on_get_case_description(self): - return "startup the executables" - - def on_setup_case(self): - os.chdir(self.get_case_name()) - start_env() - api_log_error("on_setup_case OK") - return True, '' - - def on_cleanup_case(self): - stop_env() - api_log_error("on_cleanup_case OK") - return True, '' - - # called by the framework - def on_run_case(self): - time.sleep(0.5) - - #uninstall inexistent App1 - ret = uninstall_app("App1") - if (ret != 160): - return False, '' - - #query Apps - ret = query_app() - if (ret != 69): - return False, '' - ret = check_query_apps([]) - if (ret == False): - return False, '' - - #install App1 - ret = install_app("App1", "01_install.wasm") - if (ret != 65): - return False, '' - - #query Apps - ret = query_app() - if (ret != 69): - return False, '' - ret = check_query_apps(["App1"]) - if (ret == False): - return False, '' - - #install App2 - ret = install_app("App2", "01_install.wasm") - if (ret != 65): - return False, '' - - #query Apps - ret = query_app() - if (ret != 69): - return False, '' - ret = check_query_apps(["App1","App2"]) - if (ret == False): - return False, '' - - #uninstall App2 - ret = uninstall_app("App2") - if (ret != 66): - return False, '' - - #query Apps - ret = query_app() - if (ret != 69): - return False, '' - ret = check_query_apps(["App1"]) - if (ret == False): - return False, '' - - return True, '' diff --git a/test-tools/component-test/suites/01-life-cycle/cases/02-request/__init__.py b/test-tools/component-test/suites/01-life-cycle/cases/02-request/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/test-tools/component-test/suites/01-life-cycle/cases/02-request/case.py b/test-tools/component-test/suites/01-life-cycle/cases/02-request/case.py deleted file mode 100644 index e2192d5fa..000000000 --- a/test-tools/component-test/suites/01-life-cycle/cases/02-request/case.py +++ /dev/null @@ -1,73 +0,0 @@ -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -import sys -import time -import random -import logging -import json - -from framework.case_base import * -from framework.test_api import * -from harness.harness_api import * - -class CTestCase(CTestCaseBase): - def __init__(self, suite): - CTestCaseBase.__init__(self, suite) - - def get_case_name(self): - case_path = os.path.dirname(os.path.abspath( __file__ )) - return os.path.split(case_path)[1] - - def on_get_case_description(self): - return "startup the executables" - - def on_setup_case(self): - os.chdir(self.get_case_name()) - start_env() - api_log_error("on_setup_case OK") - return True, '' - - def on_cleanup_case(self): - stop_env() - api_log_error("on_cleanup_case OK") - return True, '' - - # called by the framework - def on_run_case(self): - time.sleep(0.5) - - #install App1 - ret = install_app("App1", "02_request.wasm") - if (ret != 65): - return False, '' - - #query Apps - ret = query_app() - if (ret != 69): - return False, '' - ret = check_query_apps(["App1"]) - if (ret == False): - return False, '' - - #send request to App1 - ret = send_request("/res1", "GET", None) - if (ret != 69): - return False, '' - expect_response_payload = {"key1":"value1","key2":"value2"} - ret = check_response_payload(expect_response_payload) - if (ret == False): - return False, '' - - #send request to App1 - ret = send_request("/res2", "DELETE", None) - if (ret != 66): - return False, '' - expect_response_payload = {} - ret = check_response_payload(expect_response_payload) - if (ret == False): - return False, '' - - return True, '' diff --git a/test-tools/component-test/suites/01-life-cycle/cases/03-event/__init__.py b/test-tools/component-test/suites/01-life-cycle/cases/03-event/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/test-tools/component-test/suites/01-life-cycle/cases/03-event/case.py b/test-tools/component-test/suites/01-life-cycle/cases/03-event/case.py deleted file mode 100644 index 3886cb820..000000000 --- a/test-tools/component-test/suites/01-life-cycle/cases/03-event/case.py +++ /dev/null @@ -1,67 +0,0 @@ -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# -import sys -import time -import random -import logging -import json - -from framework.case_base import * -from framework.test_api import * -from harness.harness_api import * - -class CTestCase(CTestCaseBase): - def __init__(self, suite): - CTestCaseBase.__init__(self, suite) - - def get_case_name(self): - case_path = os.path.dirname(os.path.abspath( __file__ )) - return os.path.split(case_path)[1] - - def on_get_case_description(self): - return "startup the executables" - - def on_setup_case(self): - os.chdir(self.get_case_name()) - start_env() - api_log_error("on_setup_case OK") - return True, '' - - def on_cleanup_case(self): - stop_env() - api_log_error("on_cleanup_case OK") - return True, '' - - # called by the framework - def on_run_case(self): - time.sleep(0.5) - - #install App1 - ret = install_app("App1", "03_event.wasm") - if (ret != 65): - return False, '' - - #query Apps - ret = query_app() - if (ret != 69): - return False, '' - ret = check_query_apps(["App1"]) - if (ret == False): - return False, '' - - #register event - ret = register("/alert/overheat", 2000, 5000) - if (ret != 69): - return False, '' - ret = check_get_event() - if (ret == False): - return False, '' - - #deregister event - ret = deregister("/alert/overheat") - if (ret != 69): - return False, '' - - return True, '' diff --git a/test-tools/component-test/suites/01-life-cycle/cases/04-request-internal/__init__.py b/test-tools/component-test/suites/01-life-cycle/cases/04-request-internal/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/test-tools/component-test/suites/01-life-cycle/cases/04-request-internal/case.py b/test-tools/component-test/suites/01-life-cycle/cases/04-request-internal/case.py deleted file mode 100644 index bf395f58b..000000000 --- a/test-tools/component-test/suites/01-life-cycle/cases/04-request-internal/case.py +++ /dev/null @@ -1,80 +0,0 @@ -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -import sys -import time -import random -import logging -import json - -from framework.case_base import * -from framework.test_api import * -from harness.harness_api import * - -class CTestCase(CTestCaseBase): - def __init__(self, suite): - CTestCaseBase.__init__(self, suite) - - def get_case_name(self): - case_path = os.path.dirname(os.path.abspath( __file__ )) - return os.path.split(case_path)[1] - - def on_get_case_description(self): - return "startup the executables" - - def on_setup_case(self): - os.chdir(self.get_case_name()) - start_env() - api_log_error("on_setup_case OK") - return True, '' - - def on_cleanup_case(self): - stop_env() - api_log_error("on_cleanup_case OK") - return True, '' - - # called by the framework - def on_run_case(self): - time.sleep(0.5) - - #install App1 - ret = install_app("App1", "04_request_internal_resp.wasm") - if (ret != 65): - return False, '' - - #install App2 - ret = install_app("App2", "04_request_internal_req.wasm") - if (ret != 65): - return False, '' - - #query Apps - ret = query_app() - if (ret != 69): - return False, '' - ret = check_query_apps(["App1","App2"]) - if (ret == False): - return False, '' - - #send request to App2 - ret = send_request("/res1", "GET", None) - if (ret != 69): - return False, '' - time.sleep(2) - expect_response_payload = {"key1":"value1","key2":"value2"} - ret = check_response_payload(expect_response_payload) - if (ret == False): - return False, '' - - #send request to App2 - ret = send_request("/res2", "GET", None) - if (ret != 69): - return False, '' - time.sleep(2) - expect_response_payload = {"key1":"value1","key2":"value2"} - ret = check_response_payload(expect_response_payload) - if (ret == False): - return False, '' - - return True, '' diff --git a/test-tools/component-test/suites/01-life-cycle/cases/05-event-internal/__init__.py b/test-tools/component-test/suites/01-life-cycle/cases/05-event-internal/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/test-tools/component-test/suites/01-life-cycle/cases/05-event-internal/case.py b/test-tools/component-test/suites/01-life-cycle/cases/05-event-internal/case.py deleted file mode 100644 index 79c328749..000000000 --- a/test-tools/component-test/suites/01-life-cycle/cases/05-event-internal/case.py +++ /dev/null @@ -1,70 +0,0 @@ -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -import sys -import time -import random -import logging -import json - -from framework.case_base import * -from framework.test_api import * -from harness.harness_api import * - -class CTestCase(CTestCaseBase): - def __init__(self, suite): - CTestCaseBase.__init__(self, suite) - - def get_case_name(self): - case_path = os.path.dirname(os.path.abspath( __file__ )) - return os.path.split(case_path)[1] - - def on_get_case_description(self): - return "startup the executables" - - def on_setup_case(self): - os.chdir(self.get_case_name()) - start_env() - api_log_error("on_setup_case OK") - return True, '' - - def on_cleanup_case(self): - stop_env() - api_log_error("on_cleanup_case OK") - return True, '' - - # called by the framework - def on_run_case(self): - time.sleep(0.5) - - #install App1 - ret = install_app("App1", "05_event_internal_provider.wasm") - if (ret != 65): - return False, '' - - #install App2 - ret = install_app("App2", "05_event_internal_subscriber.wasm") - if (ret != 65): - return False, '' - - #query Apps - ret = query_app() - if (ret != 69): - return False, '' - ret = check_query_apps(["App1","App2"]) - if (ret == False): - return False, '' - - #send request to App2 - ret = send_request("/res1", "GET", None) - if (ret != 69): - return False, '' - time.sleep(2) - expect_response_payload = {"key1":"value1","key2":"value2"} - ret = check_response_payload(expect_response_payload) - if (ret == False): - return False, '' - - return True, '' diff --git a/test-tools/component-test/suites/01-life-cycle/cases/06-timer/__init__.py b/test-tools/component-test/suites/01-life-cycle/cases/06-timer/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/test-tools/component-test/suites/01-life-cycle/cases/06-timer/case.py b/test-tools/component-test/suites/01-life-cycle/cases/06-timer/case.py deleted file mode 100644 index 90af4d5d9..000000000 --- a/test-tools/component-test/suites/01-life-cycle/cases/06-timer/case.py +++ /dev/null @@ -1,70 +0,0 @@ -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -import sys -import time -import random -import logging -import json - -from framework.case_base import * -from framework.test_api import * -from harness.harness_api import * - -class CTestCase(CTestCaseBase): - def __init__(self, suite): - CTestCaseBase.__init__(self, suite) - - def get_case_name(self): - case_path = os.path.dirname(os.path.abspath( __file__ )) - return os.path.split(case_path)[1] - - def on_get_case_description(self): - return "startup the executables" - - def on_setup_case(self): - os.chdir(self.get_case_name()) - start_env() - api_log_error("on_setup_case OK") - return True, '' - - def on_cleanup_case(self): - stop_env() - api_log_error("on_cleanup_case OK") - return True, '' - - # called by the framework - def on_run_case(self): - time.sleep(0.5) - - #install App1 - ret = install_app("App1", "06_timer.wasm") - if (ret != 65): - return False, '' - - #query Apps - ret = query_app() - if (ret != 69): - return False, '' - ret = check_query_apps(["App1"]) - if (ret == False): - return False, '' - - #send request to App1 - ret = send_request("/res1", "GET", None) - if (ret != 69): - return False, '' - - time.sleep(3) - - ret = send_request("/check_timer", "GET", None) - if (ret != 69): - return False, '' - expect_response_payload = {"num":2} - ret = check_response_payload(expect_response_payload) - if (ret == False): - return False, '' - - return True, '' diff --git a/test-tools/component-test/suites/01-life-cycle/cases/07-sensor/__init__.py b/test-tools/component-test/suites/01-life-cycle/cases/07-sensor/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/test-tools/component-test/suites/01-life-cycle/cases/07-sensor/case.py b/test-tools/component-test/suites/01-life-cycle/cases/07-sensor/case.py deleted file mode 100644 index 2bb756203..000000000 --- a/test-tools/component-test/suites/01-life-cycle/cases/07-sensor/case.py +++ /dev/null @@ -1,65 +0,0 @@ -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -import sys -import time -import random -import logging -import json - -from framework.case_base import * -from framework.test_api import * -from harness.harness_api import * - -class CTestCase(CTestCaseBase): - def __init__(self, suite): - CTestCaseBase.__init__(self, suite) - - def get_case_name(self): - case_path = os.path.dirname(os.path.abspath( __file__ )) - return os.path.split(case_path)[1] - - def on_get_case_description(self): - return "startup the executables" - - def on_setup_case(self): - os.chdir(self.get_case_name()) - start_env() - api_log_error("on_setup_case OK") - return True, '' - - def on_cleanup_case(self): - stop_env() - api_log_error("on_cleanup_case OK") - return True, '' - - # called by the framework - def on_run_case(self): - time.sleep(0.5) - - #install App1 - ret = install_app("App1", "07_sensor.wasm") - if (ret != 65): - return False, '' - - #query Apps - ret = query_app() - if (ret != 69): - return False, '' - ret = check_query_apps(["App1"]) - if (ret == False): - return False, '' - - #send request to App1 - ret = send_request("/res1", "GET", None) - if (ret != 69): - return False, '' - time.sleep(2) - expect_response_payload = {"key1":"value1","key2":"value2"} - ret = check_response_payload(expect_response_payload) - if (ret == False): - return False, '' - - return True, '' diff --git a/test-tools/component-test/suites/01-life-cycle/cases/08-on-destroy/__init__.py b/test-tools/component-test/suites/01-life-cycle/cases/08-on-destroy/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/test-tools/component-test/suites/01-life-cycle/cases/08-on-destroy/case.py b/test-tools/component-test/suites/01-life-cycle/cases/08-on-destroy/case.py deleted file mode 100644 index 99a4512ee..000000000 --- a/test-tools/component-test/suites/01-life-cycle/cases/08-on-destroy/case.py +++ /dev/null @@ -1,78 +0,0 @@ -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -import sys -import time -import random -import logging -import json - -from framework.case_base import * -from framework.test_api import * -from harness.harness_api import * - -class CTestCase(CTestCaseBase): - def __init__(self, suite): - CTestCaseBase.__init__(self, suite) - - def get_case_name(self): - case_path = os.path.dirname(os.path.abspath( __file__ )) - return os.path.split(case_path)[1] - - def on_get_case_description(self): - return "startup the executables" - - def on_setup_case(self): - os.chdir(self.get_case_name()) - start_env() - api_log_error("on_setup_case OK") - return True, '' - - def on_cleanup_case(self): - stop_env() - api_log_error("on_cleanup_case OK") - return True, '' - - # called by the framework - def on_run_case(self): - time.sleep(0.5) - - #install App1 - ret = install_app("App1", "08_on_destroy.wasm") - if (ret != 65): - return False, '' - - #query Apps - ret = query_app() - if (ret != 69): - return False, '' - ret = check_query_apps(["App1"]) - if (ret == False): - return False, '' - - #send request to App1 - ret = send_request("/res1", "GET", None) - if (ret != 69): - return False, '' - time.sleep(2) - expect_response_payload = {"key1":"value1"} - ret = check_response_payload(expect_response_payload) - if (ret == False): - return False, '' - - #uninstall App1 - ret = uninstall_app("App1") - if (ret != 66): - return False, '' - - #query Apps - ret = query_app() - if (ret != 69): - return False, '' - ret = check_query_apps([]) - if (ret == False): - return False, '' - - return True, '' diff --git a/test-tools/component-test/suites/01-life-cycle/cases/__init__.py b/test-tools/component-test/suites/01-life-cycle/cases/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/test-tools/component-test/suites/01-life-cycle/suite_setup.py b/test-tools/component-test/suites/01-life-cycle/suite_setup.py deleted file mode 100644 index 2307186f7..000000000 --- a/test-tools/component-test/suites/01-life-cycle/suite_setup.py +++ /dev/null @@ -1,56 +0,0 @@ -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -import os -import shutil -import types -import time -import glob - -from framework.test_api import * -from framework.test_utils import * -from harness.harness_api import * -from framework.suite import * - -class CTestSuite(CTestSuiteBase): - setup_path = "" - def __init__(self, name, suite_path, run_path): - CTestSuiteBase.__init__(self, name, suite_path, run_path) - - def on_suite_setup(self): - global setup_path - setup_path = os.getcwd() - cases = os.listdir(self.suite_path + "/cases/") - cases.sort() - - if api_get_value("rebuild", False): - path_tmp = os.getcwd() - os.chdir(self.suite_path + "/test-app") - os.system(self.suite_path + "/test-app" + "/build.sh") - os.chdir(path_tmp) - - os.makedirs(self.run_path + "/test-app") - - for case in cases: - if case != "__init__.pyc" and case != "__init__.py": - os.makedirs(self.run_path + "/" + case) - #copy each case's host_tool, simple, wasm files, start/stop scripts to the run directory, - shutil.copy(setup_path + "/../../samples/simple/out/simple", self.run_path + "/" + case) - shutil.copy(setup_path + "/../../samples/simple/out/host_tool", self.run_path + "/" + case) - for file in glob.glob(self.suite_path + "/test-app/" + "/*.wasm"): - shutil.copy(file, self.run_path + "/test-app") - shutil.copy(self.suite_path + "/tools/product/start.sh", self.run_path + "/" + case) - shutil.copy(self.suite_path + "/tools/product/stop.sh", self.run_path + "/" + case) - - os.chdir(self.run_path) - - return True, 'OK' - - def on_suite_cleanup(self): - global setup_path - os.chdir(setup_path) - api_log("stopping env..") - - return True, 'OK' diff --git a/test-tools/component-test/suites/01-life-cycle/test-app/01_install.c b/test-tools/component-test/suites/01-life-cycle/test-app/01_install.c deleted file mode 100644 index 5c7153588..000000000 --- a/test-tools/component-test/suites/01-life-cycle/test-app/01_install.c +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "wasm_app.h" - -void -on_init() -{ - printf("Hello, I was installed.\n"); -} - -void -on_destroy() -{ - /* real destroy work including killing timer and closing sensor is - * accomplished in wasm app library version of on_destroy() */ -} diff --git a/test-tools/component-test/suites/01-life-cycle/test-app/02_request.c b/test-tools/component-test/suites/01-life-cycle/test-app/02_request.c deleted file mode 100644 index 251de6ff4..000000000 --- a/test-tools/component-test/suites/01-life-cycle/test-app/02_request.c +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "wasm_app.h" -#include "wa-inc/request.h" - -void -res1_handler(request_t *request) -{ - response_t response[1]; - attr_container_t *payload; - - printf("### user resource 1 handler called\n"); - - printf("###### dump request ######\n"); - printf("sender: %lu\n", request->sender); - printf("url: %s\n", request->url); - printf("action: %d\n", request->action); - printf("payload:\n"); - if (request->payload != NULL && request->payload_len > 0 - && request->fmt == FMT_ATTR_CONTAINER) - attr_container_dump((attr_container_t *)request->payload); - printf("#### dump request end ###\n"); - - payload = attr_container_create("wasm app response payload"); - if (payload == NULL) - return; - - attr_container_set_string(&payload, "key1", "value1"); - attr_container_set_string(&payload, "key2", "value2"); - - make_response_for_request(request, response); - set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, - (const char *)payload, - attr_container_get_serialize_length(payload)); - printf("reciver: %lu, mid:%d\n", response->reciever, response->mid); - api_response_send(response); - - attr_container_destroy(payload); -} - -void -res2_handler(request_t *request) -{ - response_t response[1]; - make_response_for_request(request, response); - set_response(response, DELETED_2_02, 0, NULL, 0); - api_response_send(response); - - printf("### user resource 2 handler called\n"); -} - -void -on_init() -{ - /* register resource uri */ - api_register_resource_handler("/res1", res1_handler); - api_register_resource_handler("/res2", res2_handler); -} - -void -on_destroy() -{ - /* real destroy work including killing timer and closing sensor is - * accomplished in wasm app library version of on_destroy() */ -} diff --git a/test-tools/component-test/suites/01-life-cycle/test-app/03_event.c b/test-tools/component-test/suites/01-life-cycle/test-app/03_event.c deleted file mode 100644 index 59cfd0097..000000000 --- a/test-tools/component-test/suites/01-life-cycle/test-app/03_event.c +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "wasm_app.h" -#include "wa-inc/timer_wasm_app.h" -#include "wa-inc/request.h" - -int num = 0; - -void -publish_overheat_event() -{ - attr_container_t *event; - - event = attr_container_create("event"); - attr_container_set_string(&event, "warning", "temperature is over high"); - - printf("###app publish event begin ###\n"); - - api_publish_event("alert/overheat", FMT_ATTR_CONTAINER, event, - attr_container_get_serialize_length(event)); - - printf("###app publish event end ###\n"); - - attr_container_destroy(event); -} - -/* Timer callback */ -void -timer1_update(user_timer_t timer) -{ - printf("Timer update %d\n", num++); - publish_overheat_event(); -} - -void -start_timer() -{ - user_timer_t timer; - - /* set up a timer */ - timer = api_timer_create(1000, true, false, timer1_update); - api_timer_restart(timer, 1000); -} - -void -on_init() -{ - start_timer(); -} - -void -on_destroy() -{ - /* real destroy work including killing timer and closing sensor is - * accomplished in wasm app library version of on_destroy() */ -} diff --git a/test-tools/component-test/suites/01-life-cycle/test-app/04_request_internal_req.c b/test-tools/component-test/suites/01-life-cycle/test-app/04_request_internal_req.c deleted file mode 100644 index 99bab9704..000000000 --- a/test-tools/component-test/suites/01-life-cycle/test-app/04_request_internal_req.c +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "wasm_app.h" -#include "wa-inc/request.h" - -uint32 mid; -unsigned long sender; - -void -my_response_handler(response_t *response, void *user_data) -{ - attr_container_t *payload; - printf("### user resource 1 handler called\n"); - - payload = attr_container_create("wasm app response payload"); - if (payload == NULL) - return; - - attr_container_set_string(&payload, "key1", "value1"); - attr_container_set_string(&payload, "key2", "value2"); - - response->mid = mid; - response->reciever = sender; - set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, - (const char *)payload, - attr_container_get_serialize_length(payload)); - printf("reciver: %lu, mid:%d\n", response->reciever, response->mid); - api_response_send(response); - - attr_container_destroy(payload); -} - -static void -test_send_request(const char *url, const char *tag) -{ - request_t request[1]; - - init_request(request, (char *)url, COAP_PUT, 0, NULL, 0); - api_send_request(request, my_response_handler, (void *)tag); -} - -void -res1_handler(request_t *request) -{ - mid = request->mid; - sender = request->sender; - test_send_request("url1", "a general request"); -} - -void -res2_handler(request_t *request) -{ - mid = request->mid; - sender = request->sender; - test_send_request("/app/App1/url1", "a general request"); -} - -void -on_init() -{ - /* register resource uri */ - api_register_resource_handler("/res1", res1_handler); - api_register_resource_handler("/res2", res2_handler); -} - -void -on_destroy() -{ - /* real destroy work including killing timer and closing sensor is - * accomplished in wasm app library version of on_destroy() */ -} diff --git a/test-tools/component-test/suites/01-life-cycle/test-app/04_request_internal_resp.c b/test-tools/component-test/suites/01-life-cycle/test-app/04_request_internal_resp.c deleted file mode 100644 index 13aecb43a..000000000 --- a/test-tools/component-test/suites/01-life-cycle/test-app/04_request_internal_resp.c +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "wasm_app.h" -#include "wa-inc/request.h" - -void -res1_handler(request_t *request) -{ - response_t response[1]; - attr_container_t *payload; - - printf("[resp] ### user resource 1 handler called\n"); - - printf("[resp] ###### dump request ######\n"); - printf("[resp] sender: %lu\n", request->sender); - printf("[resp] url: %s\n", request->url); - printf("[resp] action: %d\n", request->action); - printf("[resp] payload:\n"); - if (request->payload != NULL && request->fmt == FMT_ATTR_CONTAINER) - attr_container_dump((attr_container_t *)request->payload); - printf("[resp] #### dump request end ###\n"); - - payload = attr_container_create("wasm app response payload"); - if (payload == NULL) - return; - - attr_container_set_string(&payload, "key1", "value1"); - attr_container_set_string(&payload, "key2", "value2"); - - make_response_for_request(request, response); - set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, - (const char *)payload, - attr_container_get_serialize_length(payload)); - printf("[resp] response payload len %d\n", - attr_container_get_serialize_length(payload)); - printf("[resp] reciver: %lu, mid:%d\n", response->reciever, response->mid); - api_response_send(response); - - attr_container_destroy(payload); -} - -void -on_init() -{ - /* register resource uri */ - api_register_resource_handler("/url1", res1_handler); -} - -void -on_destroy() -{ - /* real destroy work including killing timer and closing sensor is - * accomplished in wasm app library version of on_destroy() */ -} diff --git a/test-tools/component-test/suites/01-life-cycle/test-app/05_event_internal_provider.c b/test-tools/component-test/suites/01-life-cycle/test-app/05_event_internal_provider.c deleted file mode 100644 index 59cfd0097..000000000 --- a/test-tools/component-test/suites/01-life-cycle/test-app/05_event_internal_provider.c +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "wasm_app.h" -#include "wa-inc/timer_wasm_app.h" -#include "wa-inc/request.h" - -int num = 0; - -void -publish_overheat_event() -{ - attr_container_t *event; - - event = attr_container_create("event"); - attr_container_set_string(&event, "warning", "temperature is over high"); - - printf("###app publish event begin ###\n"); - - api_publish_event("alert/overheat", FMT_ATTR_CONTAINER, event, - attr_container_get_serialize_length(event)); - - printf("###app publish event end ###\n"); - - attr_container_destroy(event); -} - -/* Timer callback */ -void -timer1_update(user_timer_t timer) -{ - printf("Timer update %d\n", num++); - publish_overheat_event(); -} - -void -start_timer() -{ - user_timer_t timer; - - /* set up a timer */ - timer = api_timer_create(1000, true, false, timer1_update); - api_timer_restart(timer, 1000); -} - -void -on_init() -{ - start_timer(); -} - -void -on_destroy() -{ - /* real destroy work including killing timer and closing sensor is - * accomplished in wasm app library version of on_destroy() */ -} diff --git a/test-tools/component-test/suites/01-life-cycle/test-app/05_event_internal_subscriber.c b/test-tools/component-test/suites/01-life-cycle/test-app/05_event_internal_subscriber.c deleted file mode 100644 index 00e451369..000000000 --- a/test-tools/component-test/suites/01-life-cycle/test-app/05_event_internal_subscriber.c +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "wasm_app.h" -#include "wa-inc/request.h" - -uint32 mid; -unsigned long sender; - -void -over_heat_event_handler(request_t *request) -{ - response_t response[1]; - attr_container_t *payload; - - payload = attr_container_create("wasm app response payload"); - if (payload == NULL) - return; - - attr_container_set_string(&payload, "key1", "value1"); - attr_container_set_string(&payload, "key2", "value2"); - - response->mid = mid; - response->reciever = sender; - set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, - (const char *)payload, - attr_container_get_serialize_length(payload)); - printf("reciver: %lu, mid:%d\n", response->reciever, response->mid); - api_response_send(response); - - attr_container_destroy(payload); -} - -void -res1_handler(request_t *request) -{ - mid = request->mid; - sender = request->sender; - api_subscribe_event("alert/overheat", over_heat_event_handler); -} - -void -on_init() -{ - /* register resource uri */ - api_register_resource_handler("/res1", res1_handler); -} - -void -on_destroy() -{ - /* real destroy work including killing timer and closing sensor is - * accomplished in wasm app library version of on_destroy() */ -} diff --git a/test-tools/component-test/suites/01-life-cycle/test-app/06_timer.c b/test-tools/component-test/suites/01-life-cycle/test-app/06_timer.c deleted file mode 100644 index 6aa107d5c..000000000 --- a/test-tools/component-test/suites/01-life-cycle/test-app/06_timer.c +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "wasm_app.h" -#include "wa-inc/request.h" -#include "wa-inc/timer_wasm_app.h" - -/* User global variable */ -int num = 0; - -/* Timer callback */ -void -timer1_update(user_timer_t timer) -{ - if (num < 2) - num++; -} - -void -res1_handler(request_t *request) -{ - user_timer_t timer; - - /* set up a timer */ - timer = api_timer_create(1000, true, false, timer1_update); - api_timer_restart(timer, 1000); - - response_t response[1]; - - make_response_for_request(request, response); - - set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, NULL, 0); - - api_response_send(response); -} - -void -res2_handler(request_t *request) -{ - response_t response[1]; - attr_container_t *payload; - - if (num == 2) { - attr_container_t *payload; - printf("### user resource 1 handler called\n"); - - payload = attr_container_create("wasm app response payload"); - if (payload == NULL) - return; - - attr_container_set_int(&payload, "num", num); - - make_response_for_request(request, response); - - set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, - (const char *)payload, - attr_container_get_serialize_length(payload)); - printf("reciver: %lu, mid:%d\n", response->reciever, response->mid); - api_response_send(response); - - attr_container_destroy(payload); - } -} - -void -on_init() -{ - /* register resource uri */ - api_register_resource_handler("/res1", res1_handler); - api_register_resource_handler("/check_timer", res2_handler); -} - -void -on_destroy() -{ - /* real destroy work including killing timer and closing sensor is - * accomplished in wasm app library version of on_destroy() */ -} diff --git a/test-tools/component-test/suites/01-life-cycle/test-app/07_sensor.c b/test-tools/component-test/suites/01-life-cycle/test-app/07_sensor.c deleted file mode 100644 index a6c24a8bc..000000000 --- a/test-tools/component-test/suites/01-life-cycle/test-app/07_sensor.c +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "wasm_app.h" -#include "wa-inc/request.h" -#include "wa-inc/sensor.h" - -uint32 mid; -unsigned long sender; - -/* Sensor event callback*/ -void -sensor_event_handler(sensor_t sensor, attr_container_t *event, void *user_data) -{ - printf("### app get sensor event\n"); - - response_t response[1]; - attr_container_t *payload; - - payload = attr_container_create("wasm app response payload"); - if (payload == NULL) - return; - - attr_container_set_string(&payload, "key1", "value1"); - attr_container_set_string(&payload, "key2", "value2"); - - response->mid = mid; - response->reciever = sender; - set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, - (const char *)payload, - attr_container_get_serialize_length(payload)); - printf("reciver: %lu, mid:%d\n", response->reciever, response->mid); - api_response_send(response); - - attr_container_destroy(payload); -} - -void -res1_handler(request_t *request) -{ - mid = request->mid; - sender = request->sender; - - sensor_t sensor; - char *user_data; - attr_container_t *config; - - printf("### app on_init 1\n"); - /* open a sensor */ - user_data = malloc(100); - printf("### app on_init 2\n"); - sensor = sensor_open("sensor_test", 0, sensor_event_handler, user_data); - printf("### app on_init 3\n"); - - /* config the sensor */ - sensor_config(sensor, 2000, 0, 0); - printf("### app on_init 4\n"); -} - -void -on_init() -{ - /* register resource uri */ - api_register_resource_handler("/res1", res1_handler); -} - -void -on_destroy() -{ - /* real destroy work including killing timer and closing sensor is - * accomplished in wasm app library version of on_destroy() */ -} diff --git a/test-tools/component-test/suites/01-life-cycle/test-app/08_on_destroy.c b/test-tools/component-test/suites/01-life-cycle/test-app/08_on_destroy.c deleted file mode 100644 index ac05a77da..000000000 --- a/test-tools/component-test/suites/01-life-cycle/test-app/08_on_destroy.c +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "wasm_app.h" -#include "wa-inc/request.h" -#include "wa-inc/sensor.h" - -uint32 mid; -unsigned long sender; -sensor_t sensor; - -/* Sensor event callback*/ -void -sensor_event_handler(sensor_t sensor, attr_container_t *event, void *user_data) -{ - printf("### app get sensor event\n"); - - response_t response[1]; - attr_container_t *payload; - - payload = attr_container_create("wasm app response payload"); - if (payload == NULL) - return; - - attr_container_set_string(&payload, "key1", "value1"); - - response->mid = mid; - response->reciever = sender; - set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, - (const char *)payload, - attr_container_get_serialize_length(payload)); - printf("reciver: %lu, mid:%d\n", response->reciever, response->mid); - api_response_send(response); - - attr_container_destroy(payload); -} - -void -res1_handler(request_t *request) -{ - mid = request->mid; - sender = request->sender; - - char *user_data; - attr_container_t *config; - - printf("### app on_init 1\n"); - /* open a sensor */ - user_data = malloc(100); - printf("### app on_init 2\n"); - sensor = sensor_open("sensor_test", 0, sensor_event_handler, user_data); - printf("### app on_init 3\n"); -} - -void -on_init() -{ - /* register resource uri */ - api_register_resource_handler("/res1", res1_handler); -} - -void -on_destroy() -{ - if (NULL != sensor) { - sensor_close(sensor); - } -} diff --git a/test-tools/component-test/suites/01-life-cycle/test-app/build.sh b/test-tools/component-test/suites/01-life-cycle/test-app/build.sh deleted file mode 100755 index 4b5428051..000000000 --- a/test-tools/component-test/suites/01-life-cycle/test-app/build.sh +++ /dev/null @@ -1,39 +0,0 @@ -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -. ../../../set_dev_env.sh - -CC=/opt/wasi-sdk/bin/clang -APP_DIR=$PWD -WAMR_DIR=${APP_DIR}/../../../../../ -SDK_DIR=${WAMR_DIR}/wamr-sdk/out/simple-host-interp -APP_FRAMEWORK_DIR=${SDK_DIR}/app-sdk/wamr-app-framework -DEPS_DIR=${WAMR_DIR}/core/deps - -for i in `ls *.c` -do -APP_SRC="$i" -OUT_FILE=${i%.*}.wasm -/opt/wasi-sdk/bin/clang -O3 \ - -Wno-int-conversion \ - -I${APP_FRAMEWORK_DIR}/include \ - -I${DEPS_DIR} \ - -O3 -z stack-size=4096 -Wl,--initial-memory=65536 \ - --sysroot=${SDK_DIR}/app-sdk/libc-builtin-sysroot \ - -L${APP_FRAMEWORK_DIR}/lib -lapp_framework \ - -Wl,--allow-undefined-file=${SDK_DIR}/app-sdk/libc-builtin-sysroot/share/defined-symbols.txt \ - -Wl,--strip-all,--no-entry -nostdlib \ - -Wl,--export=on_init -Wl,--export=on_destroy \ - -Wl,--export=on_request -Wl,--export=on_response \ - -Wl,--export=on_sensor_event -Wl,--export=on_timer_callback \ - -Wl,--export=on_connection_data \ - -o ${OUT_FILE} \ - ${APP_SRC} -if [ -f ${OUT_FILE} ]; then - echo "build ${OUT_FILE} success" -else - echo "build ${OUT_FILE} fail" -fi -done diff --git a/test-tools/component-test/suites/01-life-cycle/tools/product/start.sh b/test-tools/component-test/suites/01-life-cycle/tools/product/start.sh deleted file mode 100755 index f83e39356..000000000 --- a/test-tools/component-test/suites/01-life-cycle/tools/product/start.sh +++ /dev/null @@ -1,10 +0,0 @@ -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -#!/bin/bash - -cd $(dirname "$0") - -./simple -s > /dev/null 2>&1 & diff --git a/test-tools/component-test/suites/01-life-cycle/tools/product/stop.sh b/test-tools/component-test/suites/01-life-cycle/tools/product/stop.sh deleted file mode 100755 index b7bc2c8d2..000000000 --- a/test-tools/component-test/suites/01-life-cycle/tools/product/stop.sh +++ /dev/null @@ -1,9 +0,0 @@ -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -#!/bin/bash - -ps aux | grep -ie host_tool | awk '{print $2}' | xargs kill -9 & -ps aux | grep -ie simple | awk '{print $2}' | xargs kill -9 & diff --git a/test-tools/component-test/suites/__init__.py b/test-tools/component-test/suites/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/test-tools/component-test/suites/readme.txt b/test-tools/component-test/suites/readme.txt deleted file mode 100644 index 1e8792f5b..000000000 --- a/test-tools/component-test/suites/readme.txt +++ /dev/null @@ -1,19 +0,0 @@ -The description of each case in the test suites, should add descriptions in this file when new cases created in the future. - -suite 01-life-cycle: -case 01-install: - install or uninstall apps for times and query apps to see if the app list is expected. -case 02-request: - send request to an app, the app will respond specific attribute objects, host side should get them. -case 03-event: - register event to an app, the app will send event back periodically, host side should get some payload. -case 04-request_internal: - install 2 apps, host sends request to app2, then app2 sends request to app1, finally app1 respond specific payload to host, host side will check it. -case 05-event_internal: - install 2 apps, host sends request to app2, then app2 subscribe app1's event, finally app1 respond specific payload to host, host side will check it. -case 06-timer: - host send request to an app, the app then start a timer, when time goes by 2 seconds, app will respond specific payload to host, host side will check it. -case 07-sensor: - open sensor in app and then config the sensor in on_init, finally app will respond specific payload to host, host side will check it. -case 08-on_destroy: - open sensor in app in on_init, and close the sensor in on_destroy, host should install and uninstall the app successfully. diff --git a/test-tools/host-tool/CMakeLists.txt b/test-tools/host-tool/CMakeLists.txt deleted file mode 100644 index 932cf73bd..000000000 --- a/test-tools/host-tool/CMakeLists.txt +++ /dev/null @@ -1,56 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# - -cmake_minimum_required (VERSION 2.9) -project (host-agent) - -if (NOT CMAKE_BUILD_TYPE) - SET(CMAKE_BUILD_TYPE Debug) -endif (NOT CMAKE_BUILD_TYPE) - -if (NOT WAMR_BUILD_PLATFORM) - set (WAMR_BUILD_PLATFORM "linux") -endif (NOT WAMR_BUILD_PLATFORM) - -message ("WAMR_BUILD_PLATFORM = " ${WAMR_BUILD_PLATFORM}) - -add_definitions(-DWA_MALLOC=malloc) -add_definitions(-DWA_FREE=free) - -set (REPO_ROOT_DIR ${CMAKE_CURRENT_LIST_DIR}/../..) -set (IWASM_DIR ${REPO_ROOT_DIR}/core/iwasm) -set (APP_MGR_DIR ${REPO_ROOT_DIR}/core/app-mgr) -set (SHARED_DIR ${REPO_ROOT_DIR}/core/shared) -set (APP_FRAMEWORK_DIR ${REPO_ROOT_DIR}/core/app-framework) -#TODO: use soft-plc/tools/iec-runtime/external/cJSON instead -set (CJSON_DIR ${CMAKE_CURRENT_LIST_DIR}/external/cJSON) - -include (${APP_FRAMEWORK_DIR}/app-native-shared/native_interface.cmake) -include (${APP_MGR_DIR}/app-mgr-shared/app_mgr_shared.cmake) -include (${SHARED_DIR}/platform/${WAMR_BUILD_PLATFORM}/shared_platform.cmake) -include (${SHARED_DIR}/utils/shared_utils.cmake) -include (${SHARED_DIR}/mem-alloc/mem_alloc.cmake) -include (${CJSON_DIR}/cjson.cmake) -include (${SHARED_DIR}/coap/lib_coap.cmake) - -add_definitions(-Wall -Wno-pointer-sign) - -include_directories( - ${CMAKE_CURRENT_LIST_DIR}/src - ${IWASM_DIR}/include -) - -file (GLOB_RECURSE HOST_TOOL_SRC src/*.c) - -SET(SOURCES - ${HOST_TOOL_SRC} - ${PLATFORM_SHARED_SOURCE} - ${UTILS_SHARED_SOURCE} - ${NATIVE_INTERFACE_SOURCE} - ${CJSON_SOURCE} - ${LIB_HOST_AGENT_SOURCE} - ) - -add_executable(host_tool ${SOURCES}) -target_link_libraries(host_tool pthread) diff --git a/test-tools/host-tool/external/cJSON/LICENSE b/test-tools/host-tool/external/cJSON/LICENSE deleted file mode 100644 index 78deb0406..000000000 --- a/test-tools/host-tool/external/cJSON/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2009-2017 Dave Gamble and cJSON contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - diff --git a/test-tools/host-tool/external/cJSON/cJSON.c b/test-tools/host-tool/external/cJSON/cJSON.c deleted file mode 100644 index 830d2a346..000000000 --- a/test-tools/host-tool/external/cJSON/cJSON.c +++ /dev/null @@ -1,2991 +0,0 @@ -/* - Copyright (c) 2009-2017 Dave Gamble and cJSON contributors - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -/* cJSON */ -/* JSON parser in C. */ - -/* disable warnings about old C89 functions in MSVC */ -#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) -#define _CRT_SECURE_NO_DEPRECATE -#endif - -#ifdef __GNUC__ -#pragma GCC visibility push(default) -#endif -#if defined(_MSC_VER) -#pragma warning(push) -/* disable warning about single line comments in system headers */ -#pragma warning(disable : 4001) -#endif - -#include -#include -#include -#include -#include -#include -#include - -#ifdef ENABLE_LOCALES -#include -#endif - -#if defined(_MSC_VER) -#pragma warning(pop) -#endif -#ifdef __GNUC__ -#pragma GCC visibility pop -#endif - -#include "cJSON.h" - -/* define our own boolean type */ -#ifdef true -#undef true -#endif -#define true ((cJSON_bool)1) - -#ifdef false -#undef false -#endif -#define false ((cJSON_bool)0) - -/* define isnan and isinf for ANSI C, if in C99 or above, isnan and isinf has - * been defined in math.h */ -#ifndef isinf -#define isinf(d) (isnan((d - d)) && !isnan(d)) -#endif -#ifndef isnan -#define isnan(d) (d != d) -#endif - -#ifndef NAN -#ifdef _WIN32 -#define NAN sqrt(-1.0) -#else -#define NAN 0.0 / 0.0 -#endif -#endif - -typedef struct { - const unsigned char *json; - size_t position; -} error; -static error global_error = { NULL, 0 }; - -CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void) -{ - return (const char *)(global_error.json + global_error.position); -} - -CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON *const item) -{ - if (!cJSON_IsString(item)) { - return NULL; - } - - return item->valuestring; -} - -CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON *const item) -{ - if (!cJSON_IsNumber(item)) { - return (double)NAN; - } - - return item->valuedouble; -} - -/* This is a safeguard to prevent copy-pasters from using incompatible C and - * header files */ -#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) \ - || (CJSON_VERSION_PATCH != 16) -#error cJSON.h and cJSON.c have different versions. Make sure that both have the same. -#endif - -CJSON_PUBLIC(const char *) cJSON_Version(void) -{ - static char version[15]; - sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, - CJSON_VERSION_PATCH); - - return version; -} - -/* Case insensitive string comparison, doesn't consider two NULL pointers equal - * though */ -static int -case_insensitive_strcmp(const unsigned char *string1, - const unsigned char *string2) -{ - if ((string1 == NULL) || (string2 == NULL)) { - return 1; - } - - if (string1 == string2) { - return 0; - } - - for (; tolower(*string1) == tolower(*string2); (void)string1++, string2++) { - if (*string1 == '\0') { - return 0; - } - } - - return tolower(*string1) - tolower(*string2); -} - -typedef struct internal_hooks { - void *(CJSON_CDECL *allocate)(size_t size); - void(CJSON_CDECL *deallocate)(void *pointer); - void *(CJSON_CDECL *reallocate)(void *pointer, size_t size); -} internal_hooks; - -#if defined(_MSC_VER) -/* work around MSVC error C2322: '...' address of dllimport '...' is not static - */ -static void *CJSON_CDECL -internal_malloc(size_t size) -{ - return malloc(size); -} -static void CJSON_CDECL -internal_free(void *pointer) -{ - free(pointer); -} -static void *CJSON_CDECL -internal_realloc(void *pointer, size_t size) -{ - return realloc(pointer, size); -} -#else -#define internal_malloc malloc -#define internal_free free -#define internal_realloc realloc -#endif - -/* strlen of character literals resolved at compile time */ -#define static_strlen(string_literal) (sizeof(string_literal) - sizeof("")) - -static internal_hooks global_hooks = { internal_malloc, internal_free, - internal_realloc }; - -static unsigned char * -cJSON_strdup(const unsigned char *string, const internal_hooks *const hooks) -{ - size_t length = 0; - unsigned char *copy = NULL; - - if (string == NULL) { - return NULL; - } - - length = strlen((const char *)string) + sizeof(""); - copy = (unsigned char *)hooks->allocate(length); - if (copy == NULL) { - return NULL; - } - memcpy(copy, string, length); - - return copy; -} - -CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks *hooks) -{ - if (hooks == NULL) { - /* Reset hooks */ - global_hooks.allocate = malloc; - global_hooks.deallocate = free; - global_hooks.reallocate = realloc; - return; - } - - global_hooks.allocate = malloc; - if (hooks->malloc_fn != NULL) { - global_hooks.allocate = hooks->malloc_fn; - } - - global_hooks.deallocate = free; - if (hooks->free_fn != NULL) { - global_hooks.deallocate = hooks->free_fn; - } - - /* use realloc only if both free and malloc are used */ - global_hooks.reallocate = NULL; - if ((global_hooks.allocate == malloc) - && (global_hooks.deallocate == free)) { - global_hooks.reallocate = realloc; - } -} - -/* Internal constructor. */ -static cJSON * -cJSON_New_Item(const internal_hooks *const hooks) -{ - cJSON *node = (cJSON *)hooks->allocate(sizeof(cJSON)); - if (node) { - memset(node, '\0', sizeof(cJSON)); - } - - return node; -} - -/* Delete a cJSON structure. */ -CJSON_PUBLIC(void) cJSON_Delete(cJSON *item) -{ - cJSON *next = NULL; - while (item != NULL) { - next = item->next; - if (!(item->type & cJSON_IsReference) && (item->child != NULL)) { - cJSON_Delete(item->child); - } - if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL)) { - global_hooks.deallocate(item->valuestring); - } - if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) { - global_hooks.deallocate(item->string); - } - global_hooks.deallocate(item); - item = next; - } -} - -/* get the decimal point character of the current locale */ -static unsigned char -get_decimal_point(void) -{ -#ifdef ENABLE_LOCALES - struct lconv *lconv = localeconv(); - return (unsigned char)lconv->decimal_point[0]; -#else - return '.'; -#endif -} - -typedef struct { - const unsigned char *content; - size_t length; - size_t offset; - size_t depth; /* How deeply nested (in arrays/objects) is the input at the - current offset. */ - internal_hooks hooks; -} parse_buffer; - -/* check if the given size is left to read in a given parse buffer (starting - * with 1) */ -#define can_read(buffer, size) \ - ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length)) -/* check if the buffer can be accessed at the given index (starting with 0) */ -#define can_access_at_index(buffer, index) \ - ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length)) -#define cannot_access_at_index(buffer, index) \ - (!can_access_at_index(buffer, index)) -/* get a pointer to the buffer at the position */ -#define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset) - -/* Parse the input text to generate a number, and populate the result into item. - */ -static cJSON_bool -parse_number(cJSON *const item, parse_buffer *const input_buffer) -{ - double number = 0; - unsigned char *after_end = NULL; - unsigned char number_c_string[64]; - unsigned char decimal_point = get_decimal_point(); - size_t i = 0; - - if ((input_buffer == NULL) || (input_buffer->content == NULL)) { - return false; - } - - /* copy the number into a temporary buffer and replace '.' with the decimal - * point of the current locale (for strtod) This also takes care of '\0' not - * necessarily being available for marking the end of the input */ - for (i = 0; (i < (sizeof(number_c_string) - 1)) - && can_access_at_index(input_buffer, i); - i++) { - switch (buffer_at_offset(input_buffer)[i]) { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - case '+': - case '-': - case 'e': - case 'E': - number_c_string[i] = buffer_at_offset(input_buffer)[i]; - break; - - case '.': - number_c_string[i] = decimal_point; - break; - - default: - goto loop_end; - } - } -loop_end: - number_c_string[i] = '\0'; - - number = strtod((const char *)number_c_string, (char **)&after_end); - if (number_c_string == after_end) { - return false; /* parse_error */ - } - - item->valuedouble = number; - - /* use saturation in case of overflow */ - if (number >= INT_MAX) { - item->valueint = INT_MAX; - } - else if (number <= (double)INT_MIN) { - item->valueint = INT_MIN; - } - else { - item->valueint = (int)number; - } - - item->type = cJSON_Number; - - input_buffer->offset += (size_t)(after_end - number_c_string); - return true; -} - -/* don't ask me, but the original cJSON_SetNumberValue returns an integer or - * double */ -CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number) -{ - if (number >= INT_MAX) { - object->valueint = INT_MAX; - } - else if (number <= (double)INT_MIN) { - object->valueint = INT_MIN; - } - else { - object->valueint = (int)number; - } - - return object->valuedouble = number; -} - -CJSON_PUBLIC(char *) -cJSON_SetValuestring(cJSON *object, const char *valuestring) -{ - char *copy = NULL; - /* if object's type is not cJSON_String or is cJSON_IsReference, it should - * not set valuestring */ - if (!(object->type & cJSON_String) || (object->type & cJSON_IsReference)) { - return NULL; - } - if (strlen(valuestring) <= strlen(object->valuestring)) { - strcpy(object->valuestring, valuestring); - return object->valuestring; - } - copy = - (char *)cJSON_strdup((const unsigned char *)valuestring, &global_hooks); - if (copy == NULL) { - return NULL; - } - if (object->valuestring != NULL) { - cJSON_free(object->valuestring); - } - object->valuestring = copy; - - return copy; -} - -typedef struct { - unsigned char *buffer; - size_t length; - size_t offset; - size_t depth; /* current nesting depth (for formatted printing) */ - cJSON_bool noalloc; - cJSON_bool format; /* is this print a formatted print */ - internal_hooks hooks; -} printbuffer; - -/* realloc printbuffer if necessary to have at least "needed" bytes more */ -static unsigned char * -ensure(printbuffer *const p, size_t needed) -{ - unsigned char *newbuffer = NULL; - size_t newsize = 0; - - if ((p == NULL) || (p->buffer == NULL)) { - return NULL; - } - - if ((p->length > 0) && (p->offset >= p->length)) { - /* make sure that offset is valid */ - return NULL; - } - - if (needed > INT_MAX) { - /* sizes bigger than INT_MAX are currently not supported */ - return NULL; - } - - needed += p->offset + 1; - if (needed <= p->length) { - return p->buffer + p->offset; - } - - if (p->noalloc) { - return NULL; - } - - /* calculate new buffer size */ - if (needed > (INT_MAX / 2)) { - /* overflow of int, use INT_MAX if possible */ - if (needed <= INT_MAX) { - newsize = INT_MAX; - } - else { - return NULL; - } - } - else { - newsize = needed * 2; - } - - if (p->hooks.reallocate != NULL) { - /* reallocate with realloc if available */ - newbuffer = (unsigned char *)p->hooks.reallocate(p->buffer, newsize); - if (newbuffer == NULL) { - p->hooks.deallocate(p->buffer); - p->length = 0; - p->buffer = NULL; - - return NULL; - } - } - else { - /* otherwise reallocate manually */ - newbuffer = (unsigned char *)p->hooks.allocate(newsize); - if (!newbuffer) { - p->hooks.deallocate(p->buffer); - p->length = 0; - p->buffer = NULL; - - return NULL; - } - - memcpy(newbuffer, p->buffer, p->offset + 1); - p->hooks.deallocate(p->buffer); - } - p->length = newsize; - p->buffer = newbuffer; - - return newbuffer + p->offset; -} - -/* calculate the new length of the string in a printbuffer and update the offset - */ -static void -update_offset(printbuffer *const buffer) -{ - const unsigned char *buffer_pointer = NULL; - if ((buffer == NULL) || (buffer->buffer == NULL)) { - return; - } - buffer_pointer = buffer->buffer + buffer->offset; - - buffer->offset += strlen((const char *)buffer_pointer); -} - -/* securely comparison of floating-point variables */ -static cJSON_bool -compare_double(double a, double b) -{ - double maxVal = fabs(a) > fabs(b) ? fabs(a) : fabs(b); - return (fabs(a - b) <= maxVal * DBL_EPSILON); -} - -/* Render the number nicely from the given item into a string. */ -static cJSON_bool -print_number(const cJSON *const item, printbuffer *const output_buffer) -{ - unsigned char *output_pointer = NULL; - double d = item->valuedouble; - int length = 0; - size_t i = 0; - unsigned char number_buffer[26] = { - 0 - }; /* temporary buffer to print the number into */ - unsigned char decimal_point = get_decimal_point(); - double test = 0.0; - - if (output_buffer == NULL) { - return false; - } - - /* This checks for NaN and Infinity */ - if (isnan(d) || isinf(d)) { - length = sprintf((char *)number_buffer, "null"); - } - else if (d == (double)item->valueint) { - length = sprintf((char *)number_buffer, "%d", item->valueint); - } - else { - /* Try 15 decimal places of precision to avoid nonsignificant nonzero - * digits */ - length = sprintf((char *)number_buffer, "%1.15g", d); - - /* Check whether the original double can be recovered */ - if ((sscanf((char *)number_buffer, "%lg", &test) != 1) - || !compare_double((double)test, d)) { - /* If not, print with 17 decimal places of precision */ - length = sprintf((char *)number_buffer, "%1.17g", d); - } - } - - /* sprintf failed or buffer overrun occurred */ - if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1))) { - return false; - } - - /* reserve appropriate space in the output */ - output_pointer = ensure(output_buffer, (size_t)length + sizeof("")); - if (output_pointer == NULL) { - return false; - } - - /* copy the printed number to the output and replace locale - * dependent decimal point with '.' */ - for (i = 0; i < ((size_t)length); i++) { - if (number_buffer[i] == decimal_point) { - output_pointer[i] = '.'; - continue; - } - - output_pointer[i] = number_buffer[i]; - } - output_pointer[i] = '\0'; - - output_buffer->offset += (size_t)length; - - return true; -} - -/* parse 4 digit hexadecimal number */ -static unsigned -parse_hex4(const unsigned char *const input) -{ - unsigned int h = 0; - size_t i = 0; - - for (i = 0; i < 4; i++) { - /* parse digit */ - if ((input[i] >= '0') && (input[i] <= '9')) { - h += (unsigned int)input[i] - '0'; - } - else if ((input[i] >= 'A') && (input[i] <= 'F')) { - h += (unsigned int)10 + input[i] - 'A'; - } - else if ((input[i] >= 'a') && (input[i] <= 'f')) { - h += (unsigned int)10 + input[i] - 'a'; - } - else /* invalid */ - { - return 0; - } - - if (i < 3) { - /* shift left to make place for the next nibble */ - h = h << 4; - } - } - - return h; -} - -/* converts a UTF-16 literal to UTF-8 - * A literal can be one or two sequences of the form \uXXXX */ -static unsigned char -utf16_literal_to_utf8(const unsigned char *const input_pointer, - const unsigned char *const input_end, - unsigned char **output_pointer) -{ - long unsigned int codepoint = 0; - unsigned int first_code = 0; - const unsigned char *first_sequence = input_pointer; - unsigned char utf8_length = 0; - unsigned char utf8_position = 0; - unsigned char sequence_length = 0; - unsigned char first_byte_mark = 0; - - if ((input_end - first_sequence) < 6) { - /* input ends unexpectedly */ - goto fail; - } - - /* get the first utf16 sequence */ - first_code = parse_hex4(first_sequence + 2); - - /* check that the code is valid */ - if (((first_code >= 0xDC00) && (first_code <= 0xDFFF))) { - goto fail; - } - - /* UTF16 surrogate pair */ - if ((first_code >= 0xD800) && (first_code <= 0xDBFF)) { - const unsigned char *second_sequence = first_sequence + 6; - unsigned int second_code = 0; - sequence_length = 12; /* \uXXXX\uXXXX */ - - if ((input_end - second_sequence) < 6) { - /* input ends unexpectedly */ - goto fail; - } - - if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u')) { - /* missing second half of the surrogate pair */ - goto fail; - } - - /* get the second utf16 sequence */ - second_code = parse_hex4(second_sequence + 2); - /* check that the code is valid */ - if ((second_code < 0xDC00) || (second_code > 0xDFFF)) { - /* invalid second half of the surrogate pair */ - goto fail; - } - - /* calculate the unicode codepoint from the surrogate pair */ - codepoint = - 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF)); - } - else { - sequence_length = 6; /* \uXXXX */ - codepoint = first_code; - } - - /* encode as UTF-8 - * takes at maximum 4 bytes to encode: - * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ - if (codepoint < 0x80) { - /* normal ascii, encoding 0xxxxxxx */ - utf8_length = 1; - } - else if (codepoint < 0x800) { - /* two bytes, encoding 110xxxxx 10xxxxxx */ - utf8_length = 2; - first_byte_mark = 0xC0; /* 11000000 */ - } - else if (codepoint < 0x10000) { - /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */ - utf8_length = 3; - first_byte_mark = 0xE0; /* 11100000 */ - } - else if (codepoint <= 0x10FFFF) { - /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */ - utf8_length = 4; - first_byte_mark = 0xF0; /* 11110000 */ - } - else { - /* invalid unicode codepoint */ - goto fail; - } - - /* encode as utf8 */ - for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; - utf8_position--) { - /* 10xxxxxx */ - (*output_pointer)[utf8_position] = - (unsigned char)((codepoint | 0x80) & 0xBF); - codepoint >>= 6; - } - /* encode first byte */ - if (utf8_length > 1) { - (*output_pointer)[0] = - (unsigned char)((codepoint | first_byte_mark) & 0xFF); - } - else { - (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F); - } - - *output_pointer += utf8_length; - - return sequence_length; - -fail: - return 0; -} - -/* Parse the input text into an unescaped cinput, and populate item. */ -static cJSON_bool -parse_string(cJSON *const item, parse_buffer *const input_buffer) -{ - const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1; - const unsigned char *input_end = buffer_at_offset(input_buffer) + 1; - unsigned char *output_pointer = NULL; - unsigned char *output = NULL; - - /* not a string */ - if (buffer_at_offset(input_buffer)[0] != '\"') { - goto fail; - } - - { - /* calculate approximate size of the output (overestimate) */ - size_t allocation_length = 0; - size_t skipped_bytes = 0; - while ( - ((size_t)(input_end - input_buffer->content) < input_buffer->length) - && (*input_end != '\"')) { - /* is escape sequence */ - if (input_end[0] == '\\') { - if ((size_t)(input_end + 1 - input_buffer->content) - >= input_buffer->length) { - /* prevent buffer overflow when last input character is a - * backslash */ - goto fail; - } - skipped_bytes++; - input_end++; - } - input_end++; - } - if (((size_t)(input_end - input_buffer->content) - >= input_buffer->length) - || (*input_end != '\"')) { - goto fail; /* string ended unexpectedly */ - } - - /* This is at most how much we need for the output */ - allocation_length = (size_t)(input_end - buffer_at_offset(input_buffer)) - - skipped_bytes; - output = (unsigned char *)input_buffer->hooks.allocate(allocation_length - + sizeof("")); - if (output == NULL) { - goto fail; /* allocation failure */ - } - } - - output_pointer = output; - /* loop through the string literal */ - while (input_pointer < input_end) { - if (*input_pointer != '\\') { - *output_pointer++ = *input_pointer++; - } - /* escape sequence */ - else { - unsigned char sequence_length = 2; - if ((input_end - input_pointer) < 1) { - goto fail; - } - - switch (input_pointer[1]) { - case 'b': - *output_pointer++ = '\b'; - break; - case 'f': - *output_pointer++ = '\f'; - break; - case 'n': - *output_pointer++ = '\n'; - break; - case 'r': - *output_pointer++ = '\r'; - break; - case 't': - *output_pointer++ = '\t'; - break; - case '\"': - case '\\': - case '/': - *output_pointer++ = input_pointer[1]; - break; - - /* UTF-16 literal */ - case 'u': - sequence_length = utf16_literal_to_utf8( - input_pointer, input_end, &output_pointer); - if (sequence_length == 0) { - /* failed to convert UTF16-literal to UTF-8 */ - goto fail; - } - break; - - default: - goto fail; - } - input_pointer += sequence_length; - } - } - - /* zero terminate the output */ - *output_pointer = '\0'; - - item->type = cJSON_String; - item->valuestring = (char *)output; - - input_buffer->offset = (size_t)(input_end - input_buffer->content); - input_buffer->offset++; - - return true; - -fail: - if (output != NULL) { - input_buffer->hooks.deallocate(output); - } - - if (input_pointer != NULL) { - input_buffer->offset = (size_t)(input_pointer - input_buffer->content); - } - - return false; -} - -/* Render the cstring provided to an escaped version that can be printed. */ -static cJSON_bool -print_string_ptr(const unsigned char *const input, - printbuffer *const output_buffer) -{ - const unsigned char *input_pointer = NULL; - unsigned char *output = NULL; - unsigned char *output_pointer = NULL; - size_t output_length = 0; - /* numbers of additional characters needed for escaping */ - size_t escape_characters = 0; - - if (output_buffer == NULL) { - return false; - } - - /* empty string */ - if (input == NULL) { - output = ensure(output_buffer, sizeof("\"\"")); - if (output == NULL) { - return false; - } - strcpy((char *)output, "\"\""); - - return true; - } - - /* set "flag" to 1 if something needs to be escaped */ - for (input_pointer = input; *input_pointer; input_pointer++) { - switch (*input_pointer) { - case '\"': - case '\\': - case '\b': - case '\f': - case '\n': - case '\r': - case '\t': - /* one character escape sequence */ - escape_characters++; - break; - default: - if (*input_pointer < 32) { - /* UTF-16 escape sequence uXXXX */ - escape_characters += 5; - } - break; - } - } - output_length = (size_t)(input_pointer - input) + escape_characters; - - output = ensure(output_buffer, output_length + sizeof("\"\"")); - if (output == NULL) { - return false; - } - - /* no characters have to be escaped */ - if (escape_characters == 0) { - output[0] = '\"'; - memcpy(output + 1, input, output_length); - output[output_length + 1] = '\"'; - output[output_length + 2] = '\0'; - - return true; - } - - output[0] = '\"'; - output_pointer = output + 1; - /* copy the string */ - for (input_pointer = input; *input_pointer != '\0'; - (void)input_pointer++, output_pointer++) { - if ((*input_pointer > 31) && (*input_pointer != '\"') - && (*input_pointer != '\\')) { - /* normal character, copy */ - *output_pointer = *input_pointer; - } - else { - /* character needs to be escaped */ - *output_pointer++ = '\\'; - switch (*input_pointer) { - case '\\': - *output_pointer = '\\'; - break; - case '\"': - *output_pointer = '\"'; - break; - case '\b': - *output_pointer = 'b'; - break; - case '\f': - *output_pointer = 'f'; - break; - case '\n': - *output_pointer = 'n'; - break; - case '\r': - *output_pointer = 'r'; - break; - case '\t': - *output_pointer = 't'; - break; - default: - /* escape and print as unicode codepoint */ - sprintf((char *)output_pointer, "u%04x", *input_pointer); - output_pointer += 4; - break; - } - } - } - output[output_length + 1] = '\"'; - output[output_length + 2] = '\0'; - - return true; -} - -/* Invoke print_string_ptr (which is useful) on an item. */ -static cJSON_bool -print_string(const cJSON *const item, printbuffer *const p) -{ - return print_string_ptr((unsigned char *)item->valuestring, p); -} - -/* Predeclare these prototypes. */ -static cJSON_bool -parse_value(cJSON *const item, parse_buffer *const input_buffer); -static cJSON_bool -print_value(const cJSON *const item, printbuffer *const output_buffer); -static cJSON_bool -parse_array(cJSON *const item, parse_buffer *const input_buffer); -static cJSON_bool -print_array(const cJSON *const item, printbuffer *const output_buffer); -static cJSON_bool -parse_object(cJSON *const item, parse_buffer *const input_buffer); -static cJSON_bool -print_object(const cJSON *const item, printbuffer *const output_buffer); - -/* Utility to jump whitespace and cr/lf */ -static parse_buffer * -buffer_skip_whitespace(parse_buffer *const buffer) -{ - if ((buffer == NULL) || (buffer->content == NULL)) { - return NULL; - } - - if (cannot_access_at_index(buffer, 0)) { - return buffer; - } - - while (can_access_at_index(buffer, 0) - && (buffer_at_offset(buffer)[0] <= 32)) { - buffer->offset++; - } - - if (buffer->offset == buffer->length) { - buffer->offset--; - } - - return buffer; -} - -/* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */ -static parse_buffer * -skip_utf8_bom(parse_buffer *const buffer) -{ - if ((buffer == NULL) || (buffer->content == NULL) - || (buffer->offset != 0)) { - return NULL; - } - - if (can_access_at_index(buffer, 4) - && (strncmp((const char *)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) - == 0)) { - buffer->offset += 3; - } - - return buffer; -} - -CJSON_PUBLIC(cJSON *) -cJSON_ParseWithOpts(const char *value, const char **return_parse_end, - cJSON_bool require_null_terminated) -{ - size_t buffer_length; - - if (NULL == value) { - return NULL; - } - - /* Adding null character size due to require_null_terminated. */ - buffer_length = strlen(value) + sizeof(""); - - return cJSON_ParseWithLengthOpts(value, buffer_length, return_parse_end, - require_null_terminated); -} - -/* Parse an object - create a new root, and populate. */ -CJSON_PUBLIC(cJSON *) -cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, - const char **return_parse_end, - cJSON_bool require_null_terminated) -{ - parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } }; - cJSON *item = NULL; - - /* reset error position */ - global_error.json = NULL; - global_error.position = 0; - - if (value == NULL || 0 == buffer_length) { - goto fail; - } - - buffer.content = (const unsigned char *)value; - buffer.length = buffer_length; - buffer.offset = 0; - buffer.hooks = global_hooks; - - item = cJSON_New_Item(&global_hooks); - if (item == NULL) /* memory fail */ - { - goto fail; - } - - if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer)))) { - /* parse failure. ep is set. */ - goto fail; - } - - /* if we require null-terminated JSON without appended garbage, skip and - * then check for a null terminator */ - if (require_null_terminated) { - buffer_skip_whitespace(&buffer); - if ((buffer.offset >= buffer.length) - || buffer_at_offset(&buffer)[0] != '\0') { - goto fail; - } - } - if (return_parse_end) { - *return_parse_end = (const char *)buffer_at_offset(&buffer); - } - - return item; - -fail: - if (item != NULL) { - cJSON_Delete(item); - } - - if (value != NULL) { - error local_error; - local_error.json = (const unsigned char *)value; - local_error.position = 0; - - if (buffer.offset < buffer.length) { - local_error.position = buffer.offset; - } - else if (buffer.length > 0) { - local_error.position = buffer.length - 1; - } - - if (return_parse_end != NULL) { - *return_parse_end = - (const char *)local_error.json + local_error.position; - } - - global_error = local_error; - } - - return NULL; -} - -/* Default options for cJSON_Parse */ -CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value) -{ - return cJSON_ParseWithOpts(value, 0, 0); -} - -CJSON_PUBLIC(cJSON *) -cJSON_ParseWithLength(const char *value, size_t buffer_length) -{ - return cJSON_ParseWithLengthOpts(value, buffer_length, 0, 0); -} - -#define cjson_min(a, b) (((a) < (b)) ? (a) : (b)) - -static unsigned char * -print(const cJSON *const item, cJSON_bool format, - const internal_hooks *const hooks) -{ - static const size_t default_buffer_size = 256; - printbuffer buffer[1]; - unsigned char *printed = NULL; - - memset(buffer, 0, sizeof(buffer)); - - /* create buffer */ - buffer->buffer = (unsigned char *)hooks->allocate(default_buffer_size); - buffer->length = default_buffer_size; - buffer->format = format; - buffer->hooks = *hooks; - if (buffer->buffer == NULL) { - goto fail; - } - - /* print the value */ - if (!print_value(item, buffer)) { - goto fail; - } - update_offset(buffer); - - /* check if reallocate is available */ - if (hooks->reallocate != NULL) { - printed = (unsigned char *)hooks->reallocate(buffer->buffer, - buffer->offset + 1); - if (printed == NULL) { - goto fail; - } - buffer->buffer = NULL; - } - else /* otherwise copy the JSON over to a new buffer */ - { - printed = (unsigned char *)hooks->allocate(buffer->offset + 1); - if (printed == NULL) { - goto fail; - } - memcpy(printed, buffer->buffer, - cjson_min(buffer->length, buffer->offset + 1)); - printed[buffer->offset] = '\0'; /* just to be sure */ - - /* free the buffer */ - hooks->deallocate(buffer->buffer); - } - - return printed; - -fail: - if (buffer->buffer != NULL) { - hooks->deallocate(buffer->buffer); - } - - if (printed != NULL) { - hooks->deallocate(printed); - } - - return NULL; -} - -/* Render a cJSON item/entity/structure to text. */ -CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item) -{ - return (char *)print(item, true, &global_hooks); -} - -CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item) -{ - return (char *)print(item, false, &global_hooks); -} - -CJSON_PUBLIC(char *) -cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt) -{ - printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; - - if (prebuffer < 0) { - return NULL; - } - - p.buffer = (unsigned char *)global_hooks.allocate((size_t)prebuffer); - if (!p.buffer) { - return NULL; - } - - p.length = (size_t)prebuffer; - p.offset = 0; - p.noalloc = false; - p.format = fmt; - p.hooks = global_hooks; - - if (!print_value(item, &p)) { - global_hooks.deallocate(p.buffer); - return NULL; - } - - return (char *)p.buffer; -} - -CJSON_PUBLIC(cJSON_bool) -cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, - const cJSON_bool format) -{ - printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; - - if ((length < 0) || (buffer == NULL)) { - return false; - } - - p.buffer = (unsigned char *)buffer; - p.length = (size_t)length; - p.offset = 0; - p.noalloc = true; - p.format = format; - p.hooks = global_hooks; - - return print_value(item, &p); -} - -/* Parser core - when encountering text, process appropriately. */ -static cJSON_bool -parse_value(cJSON *const item, parse_buffer *const input_buffer) -{ - if ((input_buffer == NULL) || (input_buffer->content == NULL)) { - return false; /* no input */ - } - - /* parse the different types of values */ - /* null */ - if (can_read(input_buffer, 4) - && (strncmp((const char *)buffer_at_offset(input_buffer), "null", 4) - == 0)) { - item->type = cJSON_NULL; - input_buffer->offset += 4; - return true; - } - /* false */ - if (can_read(input_buffer, 5) - && (strncmp((const char *)buffer_at_offset(input_buffer), "false", 5) - == 0)) { - item->type = cJSON_False; - input_buffer->offset += 5; - return true; - } - /* true */ - if (can_read(input_buffer, 4) - && (strncmp((const char *)buffer_at_offset(input_buffer), "true", 4) - == 0)) { - item->type = cJSON_True; - item->valueint = 1; - input_buffer->offset += 4; - return true; - } - /* string */ - if (can_access_at_index(input_buffer, 0) - && (buffer_at_offset(input_buffer)[0] == '\"')) { - return parse_string(item, input_buffer); - } - /* number */ - if (can_access_at_index(input_buffer, 0) - && ((buffer_at_offset(input_buffer)[0] == '-') - || ((buffer_at_offset(input_buffer)[0] >= '0') - && (buffer_at_offset(input_buffer)[0] <= '9')))) { - return parse_number(item, input_buffer); - } - /* array */ - if (can_access_at_index(input_buffer, 0) - && (buffer_at_offset(input_buffer)[0] == '[')) { - return parse_array(item, input_buffer); - } - /* object */ - if (can_access_at_index(input_buffer, 0) - && (buffer_at_offset(input_buffer)[0] == '{')) { - return parse_object(item, input_buffer); - } - - return false; -} - -/* Render a value to text. */ -static cJSON_bool -print_value(const cJSON *const item, printbuffer *const output_buffer) -{ - unsigned char *output = NULL; - - if ((item == NULL) || (output_buffer == NULL)) { - return false; - } - - switch ((item->type) & 0xFF) { - case cJSON_NULL: - output = ensure(output_buffer, 5); - if (output == NULL) { - return false; - } - strcpy((char *)output, "null"); - return true; - - case cJSON_False: - output = ensure(output_buffer, 6); - if (output == NULL) { - return false; - } - strcpy((char *)output, "false"); - return true; - - case cJSON_True: - output = ensure(output_buffer, 5); - if (output == NULL) { - return false; - } - strcpy((char *)output, "true"); - return true; - - case cJSON_Number: - return print_number(item, output_buffer); - - case cJSON_Raw: - { - size_t raw_length = 0; - if (item->valuestring == NULL) { - return false; - } - - raw_length = strlen(item->valuestring) + sizeof(""); - output = ensure(output_buffer, raw_length); - if (output == NULL) { - return false; - } - memcpy(output, item->valuestring, raw_length); - return true; - } - - case cJSON_String: - return print_string(item, output_buffer); - - case cJSON_Array: - return print_array(item, output_buffer); - - case cJSON_Object: - return print_object(item, output_buffer); - - default: - return false; - } -} - -/* Build an array from input text. */ -static cJSON_bool -parse_array(cJSON *const item, parse_buffer *const input_buffer) -{ - cJSON *head = NULL; /* head of the linked list */ - cJSON *current_item = NULL; - - if (input_buffer->depth >= CJSON_NESTING_LIMIT) { - return false; /* to deeply nested */ - } - input_buffer->depth++; - - if (buffer_at_offset(input_buffer)[0] != '[') { - /* not an array */ - goto fail; - } - - input_buffer->offset++; - buffer_skip_whitespace(input_buffer); - if (can_access_at_index(input_buffer, 0) - && (buffer_at_offset(input_buffer)[0] == ']')) { - /* empty array */ - goto success; - } - - /* check if we skipped to the end of the buffer */ - if (cannot_access_at_index(input_buffer, 0)) { - input_buffer->offset--; - goto fail; - } - - /* step back to character in front of the first element */ - input_buffer->offset--; - /* loop through the comma separated array elements */ - do { - /* allocate next item */ - cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); - if (new_item == NULL) { - goto fail; /* allocation failure */ - } - - /* attach next item to list */ - if (head == NULL) { - /* start the linked list */ - current_item = head = new_item; - } - else { - /* add to the end and advance */ - current_item->next = new_item; - new_item->prev = current_item; - current_item = new_item; - } - - /* parse next value */ - input_buffer->offset++; - buffer_skip_whitespace(input_buffer); - if (!parse_value(current_item, input_buffer)) { - goto fail; /* failed to parse value */ - } - buffer_skip_whitespace(input_buffer); - } while (can_access_at_index(input_buffer, 0) - && (buffer_at_offset(input_buffer)[0] == ',')); - - if (cannot_access_at_index(input_buffer, 0) - || buffer_at_offset(input_buffer)[0] != ']') { - goto fail; /* expected end of array */ - } - -success: - input_buffer->depth--; - - if (head != NULL) { - head->prev = current_item; - } - - item->type = cJSON_Array; - item->child = head; - - input_buffer->offset++; - - return true; - -fail: - if (head != NULL) { - cJSON_Delete(head); - } - - return false; -} - -/* Render an array to text */ -static cJSON_bool -print_array(const cJSON *const item, printbuffer *const output_buffer) -{ - unsigned char *output_pointer = NULL; - size_t length = 0; - cJSON *current_element = item->child; - - if (output_buffer == NULL) { - return false; - } - - /* Compose the output array. */ - /* opening square bracket */ - output_pointer = ensure(output_buffer, 1); - if (output_pointer == NULL) { - return false; - } - - *output_pointer = '['; - output_buffer->offset++; - output_buffer->depth++; - - while (current_element != NULL) { - if (!print_value(current_element, output_buffer)) { - return false; - } - update_offset(output_buffer); - if (current_element->next) { - length = (size_t)(output_buffer->format ? 2 : 1); - output_pointer = ensure(output_buffer, length + 1); - if (output_pointer == NULL) { - return false; - } - *output_pointer++ = ','; - if (output_buffer->format) { - *output_pointer++ = ' '; - } - *output_pointer = '\0'; - output_buffer->offset += length; - } - current_element = current_element->next; - } - - output_pointer = ensure(output_buffer, 2); - if (output_pointer == NULL) { - return false; - } - *output_pointer++ = ']'; - *output_pointer = '\0'; - output_buffer->depth--; - - return true; -} - -/* Build an object from the text. */ -static cJSON_bool -parse_object(cJSON *const item, parse_buffer *const input_buffer) -{ - cJSON *head = NULL; /* linked list head */ - cJSON *current_item = NULL; - - if (input_buffer->depth >= CJSON_NESTING_LIMIT) { - return false; /* to deeply nested */ - } - input_buffer->depth++; - - if (cannot_access_at_index(input_buffer, 0) - || (buffer_at_offset(input_buffer)[0] != '{')) { - goto fail; /* not an object */ - } - - input_buffer->offset++; - buffer_skip_whitespace(input_buffer); - if (can_access_at_index(input_buffer, 0) - && (buffer_at_offset(input_buffer)[0] == '}')) { - goto success; /* empty object */ - } - - /* check if we skipped to the end of the buffer */ - if (cannot_access_at_index(input_buffer, 0)) { - input_buffer->offset--; - goto fail; - } - - /* step back to character in front of the first element */ - input_buffer->offset--; - /* loop through the comma separated array elements */ - do { - /* allocate next item */ - cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); - if (new_item == NULL) { - goto fail; /* allocation failure */ - } - - /* attach next item to list */ - if (head == NULL) { - /* start the linked list */ - current_item = head = new_item; - } - else { - /* add to the end and advance */ - current_item->next = new_item; - new_item->prev = current_item; - current_item = new_item; - } - - /* parse the name of the child */ - input_buffer->offset++; - buffer_skip_whitespace(input_buffer); - if (!parse_string(current_item, input_buffer)) { - goto fail; /* failed to parse name */ - } - buffer_skip_whitespace(input_buffer); - - /* swap valuestring and string, because we parsed the name */ - current_item->string = current_item->valuestring; - current_item->valuestring = NULL; - - if (cannot_access_at_index(input_buffer, 0) - || (buffer_at_offset(input_buffer)[0] != ':')) { - goto fail; /* invalid object */ - } - - /* parse the value */ - input_buffer->offset++; - buffer_skip_whitespace(input_buffer); - if (!parse_value(current_item, input_buffer)) { - goto fail; /* failed to parse value */ - } - buffer_skip_whitespace(input_buffer); - } while (can_access_at_index(input_buffer, 0) - && (buffer_at_offset(input_buffer)[0] == ',')); - - if (cannot_access_at_index(input_buffer, 0) - || (buffer_at_offset(input_buffer)[0] != '}')) { - goto fail; /* expected end of object */ - } - -success: - input_buffer->depth--; - - if (head != NULL) { - head->prev = current_item; - } - - item->type = cJSON_Object; - item->child = head; - - input_buffer->offset++; - return true; - -fail: - if (head != NULL) { - cJSON_Delete(head); - } - - return false; -} - -/* Render an object to text. */ -static cJSON_bool -print_object(const cJSON *const item, printbuffer *const output_buffer) -{ - unsigned char *output_pointer = NULL; - size_t length = 0; - cJSON *current_item = item->child; - - if (output_buffer == NULL) { - return false; - } - - /* Compose the output: */ - length = (size_t)(output_buffer->format ? 2 : 1); /* fmt: {\n */ - output_pointer = ensure(output_buffer, length + 1); - if (output_pointer == NULL) { - return false; - } - - *output_pointer++ = '{'; - output_buffer->depth++; - if (output_buffer->format) { - *output_pointer++ = '\n'; - } - output_buffer->offset += length; - - while (current_item) { - if (output_buffer->format) { - size_t i; - output_pointer = ensure(output_buffer, output_buffer->depth); - if (output_pointer == NULL) { - return false; - } - for (i = 0; i < output_buffer->depth; i++) { - *output_pointer++ = '\t'; - } - output_buffer->offset += output_buffer->depth; - } - - /* print key */ - if (!print_string_ptr((unsigned char *)current_item->string, - output_buffer)) { - return false; - } - update_offset(output_buffer); - - length = (size_t)(output_buffer->format ? 2 : 1); - output_pointer = ensure(output_buffer, length); - if (output_pointer == NULL) { - return false; - } - *output_pointer++ = ':'; - if (output_buffer->format) { - *output_pointer++ = '\t'; - } - output_buffer->offset += length; - - /* print value */ - if (!print_value(current_item, output_buffer)) { - return false; - } - update_offset(output_buffer); - - /* print comma if not last */ - length = ((size_t)(output_buffer->format ? 1 : 0) - + (size_t)(current_item->next ? 1 : 0)); - output_pointer = ensure(output_buffer, length + 1); - if (output_pointer == NULL) { - return false; - } - if (current_item->next) { - *output_pointer++ = ','; - } - - if (output_buffer->format) { - *output_pointer++ = '\n'; - } - *output_pointer = '\0'; - output_buffer->offset += length; - - current_item = current_item->next; - } - - output_pointer = ensure( - output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2); - if (output_pointer == NULL) { - return false; - } - if (output_buffer->format) { - size_t i; - for (i = 0; i < (output_buffer->depth - 1); i++) { - *output_pointer++ = '\t'; - } - } - *output_pointer++ = '}'; - *output_pointer = '\0'; - output_buffer->depth--; - - return true; -} - -/* Get Array size/item / object item. */ -CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array) -{ - cJSON *child = NULL; - size_t size = 0; - - if (array == NULL) { - return 0; - } - - child = array->child; - - while (child != NULL) { - size++; - child = child->next; - } - - /* FIXME: Can overflow here. Cannot be fixed without breaking the API */ - - return (int)size; -} - -static cJSON * -get_array_item(const cJSON *array, size_t index) -{ - cJSON *current_child = NULL; - - if (array == NULL) { - return NULL; - } - - current_child = array->child; - while ((current_child != NULL) && (index > 0)) { - index--; - current_child = current_child->next; - } - - return current_child; -} - -CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index) -{ - if (index < 0) { - return NULL; - } - - return get_array_item(array, (size_t)index); -} - -static cJSON * -get_object_item(const cJSON *const object, const char *const name, - const cJSON_bool case_sensitive) -{ - cJSON *current_element = NULL; - - if ((object == NULL) || (name == NULL)) { - return NULL; - } - - current_element = object->child; - if (case_sensitive) { - while ((current_element != NULL) && (current_element->string != NULL) - && (strcmp(name, current_element->string) != 0)) { - current_element = current_element->next; - } - } - else { - while ((current_element != NULL) - && (case_insensitive_strcmp( - (const unsigned char *)name, - (const unsigned char *)(current_element->string)) - != 0)) { - current_element = current_element->next; - } - } - - if ((current_element == NULL) || (current_element->string == NULL)) { - return NULL; - } - - return current_element; -} - -CJSON_PUBLIC(cJSON *) -cJSON_GetObjectItem(const cJSON *const object, const char *const string) -{ - return get_object_item(object, string, false); -} - -CJSON_PUBLIC(cJSON *) -cJSON_GetObjectItemCaseSensitive(const cJSON *const object, - const char *const string) -{ - return get_object_item(object, string, true); -} - -CJSON_PUBLIC(cJSON_bool) -cJSON_HasObjectItem(const cJSON *object, const char *string) -{ - return cJSON_GetObjectItem(object, string) ? 1 : 0; -} - -/* Utility for array list handling. */ -static void -suffix_object(cJSON *prev, cJSON *item) -{ - prev->next = item; - item->prev = prev; -} - -/* Utility for handling references. */ -static cJSON * -create_reference(const cJSON *item, const internal_hooks *const hooks) -{ - cJSON *reference = NULL; - if (item == NULL) { - return NULL; - } - - reference = cJSON_New_Item(hooks); - if (reference == NULL) { - return NULL; - } - - memcpy(reference, item, sizeof(cJSON)); - reference->string = NULL; - reference->type |= cJSON_IsReference; - reference->next = reference->prev = NULL; - return reference; -} - -static cJSON_bool -add_item_to_array(cJSON *array, cJSON *item) -{ - cJSON *child = NULL; - - if ((item == NULL) || (array == NULL) || (array == item)) { - return false; - } - - child = array->child; - /* - * To find the last item in array quickly, we use prev in array - */ - if (child == NULL) { - /* list is empty, start new one */ - array->child = item; - item->prev = item; - item->next = NULL; - } - else { - /* append to the end */ - if (child->prev) { - suffix_object(child->prev, item); - array->child->prev = item; - } - } - - return true; -} - -/* Add item to array/object. */ -CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item) -{ - return add_item_to_array(array, item); -} - -#if defined(__clang__) \ - || (defined(__GNUC__) \ - && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) -#pragma GCC diagnostic push -#endif -#ifdef __GNUC__ -#pragma GCC diagnostic ignored "-Wcast-qual" -#endif -/* helper function to cast away const */ -static void * -cast_away_const(const void *string) -{ - return (void *)string; -} -#if defined(__clang__) \ - || (defined(__GNUC__) \ - && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) -#pragma GCC diagnostic pop -#endif - -static cJSON_bool -add_item_to_object(cJSON *const object, const char *const string, - cJSON *const item, const internal_hooks *const hooks, - const cJSON_bool constant_key) -{ - char *new_key = NULL; - int new_type = cJSON_Invalid; - - if ((object == NULL) || (string == NULL) || (item == NULL) - || (object == item)) { - return false; - } - - if (constant_key) { - new_key = (char *)cast_away_const(string); - new_type = item->type | cJSON_StringIsConst; - } - else { - new_key = (char *)cJSON_strdup((const unsigned char *)string, hooks); - if (new_key == NULL) { - return false; - } - - new_type = item->type & ~cJSON_StringIsConst; - } - - if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) { - hooks->deallocate(item->string); - } - - item->string = new_key; - item->type = new_type; - - return add_item_to_array(object, item); -} - -CJSON_PUBLIC(cJSON_bool) -cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item) -{ - return add_item_to_object(object, string, item, &global_hooks, false); -} - -/* Add an item to an object with constant string as key */ -CJSON_PUBLIC(cJSON_bool) -cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item) -{ - return add_item_to_object(object, string, item, &global_hooks, true); -} - -CJSON_PUBLIC(cJSON_bool) -cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) -{ - if (array == NULL) { - return false; - } - - return add_item_to_array(array, create_reference(item, &global_hooks)); -} - -CJSON_PUBLIC(cJSON_bool) -cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item) -{ - if ((object == NULL) || (string == NULL)) { - return false; - } - - return add_item_to_object(object, string, - create_reference(item, &global_hooks), - &global_hooks, false); -} - -CJSON_PUBLIC(cJSON *) -cJSON_AddNullToObject(cJSON *const object, const char *const name) -{ - cJSON *null = cJSON_CreateNull(); - if (add_item_to_object(object, name, null, &global_hooks, false)) { - return null; - } - - cJSON_Delete(null); - return NULL; -} - -CJSON_PUBLIC(cJSON *) -cJSON_AddTrueToObject(cJSON *const object, const char *const name) -{ - cJSON *true_item = cJSON_CreateTrue(); - if (add_item_to_object(object, name, true_item, &global_hooks, false)) { - return true_item; - } - - cJSON_Delete(true_item); - return NULL; -} - -CJSON_PUBLIC(cJSON *) -cJSON_AddFalseToObject(cJSON *const object, const char *const name) -{ - cJSON *false_item = cJSON_CreateFalse(); - if (add_item_to_object(object, name, false_item, &global_hooks, false)) { - return false_item; - } - - cJSON_Delete(false_item); - return NULL; -} - -CJSON_PUBLIC(cJSON *) -cJSON_AddBoolToObject(cJSON *const object, const char *const name, - const cJSON_bool boolean) -{ - cJSON *bool_item = cJSON_CreateBool(boolean); - if (add_item_to_object(object, name, bool_item, &global_hooks, false)) { - return bool_item; - } - - cJSON_Delete(bool_item); - return NULL; -} - -CJSON_PUBLIC(cJSON *) -cJSON_AddNumberToObject(cJSON *const object, const char *const name, - const double number) -{ - cJSON *number_item = cJSON_CreateNumber(number); - if (add_item_to_object(object, name, number_item, &global_hooks, false)) { - return number_item; - } - - cJSON_Delete(number_item); - return NULL; -} - -CJSON_PUBLIC(cJSON *) -cJSON_AddStringToObject(cJSON *const object, const char *const name, - const char *const string) -{ - cJSON *string_item = cJSON_CreateString(string); - if (add_item_to_object(object, name, string_item, &global_hooks, false)) { - return string_item; - } - - cJSON_Delete(string_item); - return NULL; -} - -CJSON_PUBLIC(cJSON *) -cJSON_AddRawToObject(cJSON *const object, const char *const name, - const char *const raw) -{ - cJSON *raw_item = cJSON_CreateRaw(raw); - if (add_item_to_object(object, name, raw_item, &global_hooks, false)) { - return raw_item; - } - - cJSON_Delete(raw_item); - return NULL; -} - -CJSON_PUBLIC(cJSON *) -cJSON_AddObjectToObject(cJSON *const object, const char *const name) -{ - cJSON *object_item = cJSON_CreateObject(); - if (add_item_to_object(object, name, object_item, &global_hooks, false)) { - return object_item; - } - - cJSON_Delete(object_item); - return NULL; -} - -CJSON_PUBLIC(cJSON *) -cJSON_AddArrayToObject(cJSON *const object, const char *const name) -{ - cJSON *array = cJSON_CreateArray(); - if (add_item_to_object(object, name, array, &global_hooks, false)) { - return array; - } - - cJSON_Delete(array); - return NULL; -} - -CJSON_PUBLIC(cJSON *) -cJSON_DetachItemViaPointer(cJSON *parent, cJSON *const item) -{ - if ((parent == NULL) || (item == NULL)) { - return NULL; - } - - if (item != parent->child) { - /* not the first element */ - item->prev->next = item->next; - } - if (item->next != NULL) { - /* not the last element */ - item->next->prev = item->prev; - } - - if (item == parent->child) { - /* first element */ - parent->child = item->next; - } - else if (item->next == NULL) { - /* last element */ - parent->child->prev = item->prev; - } - - /* make sure the detached item doesn't point anywhere anymore */ - item->prev = NULL; - item->next = NULL; - - return item; -} - -CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which) -{ - if (which < 0) { - return NULL; - } - - return cJSON_DetachItemViaPointer(array, - get_array_item(array, (size_t)which)); -} - -CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which) -{ - cJSON_Delete(cJSON_DetachItemFromArray(array, which)); -} - -CJSON_PUBLIC(cJSON *) -cJSON_DetachItemFromObject(cJSON *object, const char *string) -{ - cJSON *to_detach = cJSON_GetObjectItem(object, string); - - return cJSON_DetachItemViaPointer(object, to_detach); -} - -CJSON_PUBLIC(cJSON *) -cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string) -{ - cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string); - - return cJSON_DetachItemViaPointer(object, to_detach); -} - -CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string) -{ - cJSON_Delete(cJSON_DetachItemFromObject(object, string)); -} - -CJSON_PUBLIC(void) -cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string) -{ - cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string)); -} - -/* Replace array/object items with new ones. */ -CJSON_PUBLIC(cJSON_bool) -cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem) -{ - cJSON *after_inserted = NULL; - - if (which < 0) { - return false; - } - - after_inserted = get_array_item(array, (size_t)which); - if (after_inserted == NULL) { - return add_item_to_array(array, newitem); - } - - newitem->next = after_inserted; - newitem->prev = after_inserted->prev; - after_inserted->prev = newitem; - if (after_inserted == array->child) { - array->child = newitem; - } - else { - newitem->prev->next = newitem; - } - return true; -} - -CJSON_PUBLIC(cJSON_bool) -cJSON_ReplaceItemViaPointer(cJSON *const parent, cJSON *const item, - cJSON *replacement) -{ - if ((parent == NULL) || (parent->child == NULL) || (replacement == NULL) - || (item == NULL)) { - return false; - } - - if (replacement == item) { - return true; - } - - replacement->next = item->next; - replacement->prev = item->prev; - - if (replacement->next != NULL) { - replacement->next->prev = replacement; - } - if (parent->child == item) { - if (parent->child->prev == parent->child) { - replacement->prev = replacement; - } - parent->child = replacement; - } - else { /* - * To find the last item in array quickly, we use prev in array. - * We can't modify the last item's next pointer where this item was - * the parent's child - */ - if (replacement->prev != NULL) { - replacement->prev->next = replacement; - } - if (replacement->next == NULL) { - parent->child->prev = replacement; - } - } - - item->next = NULL; - item->prev = NULL; - cJSON_Delete(item); - - return true; -} - -CJSON_PUBLIC(cJSON_bool) -cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem) -{ - if (which < 0) { - return false; - } - - return cJSON_ReplaceItemViaPointer( - array, get_array_item(array, (size_t)which), newitem); -} - -static cJSON_bool -replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, - cJSON_bool case_sensitive) -{ - if ((replacement == NULL) || (string == NULL)) { - return false; - } - - /* replace the name in the replacement */ - if (!(replacement->type & cJSON_StringIsConst) - && (replacement->string != NULL)) { - cJSON_free(replacement->string); - } - replacement->string = - (char *)cJSON_strdup((const unsigned char *)string, &global_hooks); - if (replacement->string == NULL) { - return false; - } - - replacement->type &= ~cJSON_StringIsConst; - - return cJSON_ReplaceItemViaPointer( - object, get_object_item(object, string, case_sensitive), replacement); -} - -CJSON_PUBLIC(cJSON_bool) -cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem) -{ - return replace_item_in_object(object, string, newitem, false); -} - -CJSON_PUBLIC(cJSON_bool) -cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, - cJSON *newitem) -{ - return replace_item_in_object(object, string, newitem, true); -} - -/* Create basic types: */ -CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if (item) { - item->type = cJSON_NULL; - } - - return item; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if (item) { - item->type = cJSON_True; - } - - return item; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if (item) { - item->type = cJSON_False; - } - - return item; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if (item) { - item->type = boolean ? cJSON_True : cJSON_False; - } - - return item; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if (item) { - item->type = cJSON_Number; - item->valuedouble = num; - - /* use saturation in case of overflow */ - if (num >= INT_MAX) { - item->valueint = INT_MAX; - } - else if (num <= (double)INT_MIN) { - item->valueint = INT_MIN; - } - else { - item->valueint = (int)num; - } - } - - return item; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if (item) { - item->type = cJSON_String; - item->valuestring = - (char *)cJSON_strdup((const unsigned char *)string, &global_hooks); - if (!item->valuestring) { - cJSON_Delete(item); - return NULL; - } - } - - return item; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if (item != NULL) { - item->type = cJSON_String | cJSON_IsReference; - item->valuestring = (char *)cast_away_const(string); - } - - return item; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if (item != NULL) { - item->type = cJSON_Object | cJSON_IsReference; - item->child = (cJSON *)cast_away_const(child); - } - - return item; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if (item != NULL) { - item->type = cJSON_Array | cJSON_IsReference; - item->child = (cJSON *)cast_away_const(child); - } - - return item; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if (item) { - item->type = cJSON_Raw; - item->valuestring = - (char *)cJSON_strdup((const unsigned char *)raw, &global_hooks); - if (!item->valuestring) { - cJSON_Delete(item); - return NULL; - } - } - - return item; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if (item) { - item->type = cJSON_Array; - } - - return item; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if (item) { - item->type = cJSON_Object; - } - - return item; -} - -/* Create Arrays: */ -CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count) -{ - size_t i = 0; - cJSON *n = NULL; - cJSON *p = NULL; - cJSON *a = NULL; - - if ((count < 0) || (numbers == NULL)) { - return NULL; - } - - a = cJSON_CreateArray(); - - for (i = 0; a && (i < (size_t)count); i++) { - n = cJSON_CreateNumber(numbers[i]); - if (!n) { - cJSON_Delete(a); - return NULL; - } - if (!i) { - a->child = n; - } - else { - suffix_object(p, n); - } - p = n; - } - - if (a && a->child) { - a->child->prev = n; - } - - return a; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count) -{ - size_t i = 0; - cJSON *n = NULL; - cJSON *p = NULL; - cJSON *a = NULL; - - if ((count < 0) || (numbers == NULL)) { - return NULL; - } - - a = cJSON_CreateArray(); - - for (i = 0; a && (i < (size_t)count); i++) { - n = cJSON_CreateNumber((double)numbers[i]); - if (!n) { - cJSON_Delete(a); - return NULL; - } - if (!i) { - a->child = n; - } - else { - suffix_object(p, n); - } - p = n; - } - - if (a && a->child) { - a->child->prev = n; - } - - return a; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count) -{ - size_t i = 0; - cJSON *n = NULL; - cJSON *p = NULL; - cJSON *a = NULL; - - if ((count < 0) || (numbers == NULL)) { - return NULL; - } - - a = cJSON_CreateArray(); - - for (i = 0; a && (i < (size_t)count); i++) { - n = cJSON_CreateNumber(numbers[i]); - if (!n) { - cJSON_Delete(a); - return NULL; - } - if (!i) { - a->child = n; - } - else { - suffix_object(p, n); - } - p = n; - } - - if (a && a->child) { - a->child->prev = n; - } - - return a; -} - -CJSON_PUBLIC(cJSON *) -cJSON_CreateStringArray(const char *const *strings, int count) -{ - size_t i = 0; - cJSON *n = NULL; - cJSON *p = NULL; - cJSON *a = NULL; - - if ((count < 0) || (strings == NULL)) { - return NULL; - } - - a = cJSON_CreateArray(); - - for (i = 0; a && (i < (size_t)count); i++) { - n = cJSON_CreateString(strings[i]); - if (!n) { - cJSON_Delete(a); - return NULL; - } - if (!i) { - a->child = n; - } - else { - suffix_object(p, n); - } - p = n; - } - - if (a && a->child) { - a->child->prev = n; - } - - return a; -} - -/* Duplication */ -CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse) -{ - cJSON *newitem = NULL; - cJSON *child = NULL; - cJSON *next = NULL; - cJSON *newchild = NULL; - - /* Bail on bad ptr */ - if (!item) { - goto fail; - } - /* Create new item */ - newitem = cJSON_New_Item(&global_hooks); - if (!newitem) { - goto fail; - } - /* Copy over all vars */ - newitem->type = item->type & (~cJSON_IsReference); - newitem->valueint = item->valueint; - newitem->valuedouble = item->valuedouble; - if (item->valuestring) { - newitem->valuestring = (char *)cJSON_strdup( - (unsigned char *)item->valuestring, &global_hooks); - if (!newitem->valuestring) { - goto fail; - } - } - if (item->string) { - newitem->string = (item->type & cJSON_StringIsConst) - ? item->string - : (char *)cJSON_strdup( - (unsigned char *)item->string, &global_hooks); - if (!newitem->string) { - goto fail; - } - } - /* If non-recursive, then we're done! */ - if (!recurse) { - return newitem; - } - /* Walk the ->next chain for the child. */ - child = item->child; - while (child != NULL) { - newchild = cJSON_Duplicate( - child, - true); /* Duplicate (with recurse) each item in the ->next chain */ - if (!newchild) { - goto fail; - } - if (next != NULL) { - /* If newitem->child already set, then crosswire ->prev and ->next - * and move on */ - next->next = newchild; - newchild->prev = next; - next = newchild; - } - else { - /* Set newitem->child and move to it */ - newitem->child = newchild; - next = newchild; - } - child = child->next; - } - if (newitem && newitem->child) { - newitem->child->prev = newchild; - } - - return newitem; - -fail: - if (newitem != NULL) { - cJSON_Delete(newitem); - } - - return NULL; -} - -static void -skip_oneline_comment(char **input) -{ - *input += static_strlen("//"); - - for (; (*input)[0] != '\0'; ++(*input)) { - if ((*input)[0] == '\n') { - *input += static_strlen("\n"); - return; - } - } -} - -static void -skip_multiline_comment(char **input) -{ - *input += static_strlen("/*"); - - for (; (*input)[0] != '\0'; ++(*input)) { - if (((*input)[0] == '*') && ((*input)[1] == '/')) { - *input += static_strlen("*/"); - return; - } - } -} - -static void -minify_string(char **input, char **output) -{ - (*output)[0] = (*input)[0]; - *input += static_strlen("\""); - *output += static_strlen("\""); - - for (; (*input)[0] != '\0'; (void)++(*input), ++(*output)) { - (*output)[0] = (*input)[0]; - - if ((*input)[0] == '\"') { - (*output)[0] = '\"'; - *input += static_strlen("\""); - *output += static_strlen("\""); - return; - } - else if (((*input)[0] == '\\') && ((*input)[1] == '\"')) { - (*output)[1] = (*input)[1]; - *input += static_strlen("\""); - *output += static_strlen("\""); - } - } -} - -CJSON_PUBLIC(void) cJSON_Minify(char *json) -{ - char *into = json; - - if (json == NULL) { - return; - } - - while (json[0] != '\0') { - switch (json[0]) { - case ' ': - case '\t': - case '\r': - case '\n': - json++; - break; - - case '/': - if (json[1] == '/') { - skip_oneline_comment(&json); - } - else if (json[1] == '*') { - skip_multiline_comment(&json); - } - else { - json++; - } - break; - - case '\"': - minify_string(&json, (char **)&into); - break; - - default: - into[0] = json[0]; - json++; - into++; - } - } - - /* and null-terminate. */ - *into = '\0'; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON *const item) -{ - if (item == NULL) { - return false; - } - - return (item->type & 0xFF) == cJSON_Invalid; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON *const item) -{ - if (item == NULL) { - return false; - } - - return (item->type & 0xFF) == cJSON_False; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON *const item) -{ - if (item == NULL) { - return false; - } - - return (item->type & 0xff) == cJSON_True; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON *const item) -{ - if (item == NULL) { - return false; - } - - return (item->type & (cJSON_True | cJSON_False)) != 0; -} -CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON *const item) -{ - if (item == NULL) { - return false; - } - - return (item->type & 0xFF) == cJSON_NULL; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON *const item) -{ - if (item == NULL) { - return false; - } - - return (item->type & 0xFF) == cJSON_Number; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON *const item) -{ - if (item == NULL) { - return false; - } - - return (item->type & 0xFF) == cJSON_String; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON *const item) -{ - if (item == NULL) { - return false; - } - - return (item->type & 0xFF) == cJSON_Array; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON *const item) -{ - if (item == NULL) { - return false; - } - - return (item->type & 0xFF) == cJSON_Object; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON *const item) -{ - if (item == NULL) { - return false; - } - - return (item->type & 0xFF) == cJSON_Raw; -} - -CJSON_PUBLIC(cJSON_bool) -cJSON_Compare(const cJSON *const a, const cJSON *const b, - const cJSON_bool case_sensitive) -{ - if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF))) { - return false; - } - - /* check if type is valid */ - switch (a->type & 0xFF) { - case cJSON_False: - case cJSON_True: - case cJSON_NULL: - case cJSON_Number: - case cJSON_String: - case cJSON_Raw: - case cJSON_Array: - case cJSON_Object: - break; - - default: - return false; - } - - /* identical objects are equal */ - if (a == b) { - return true; - } - - switch (a->type & 0xFF) { - /* in these cases and equal type is enough */ - case cJSON_False: - case cJSON_True: - case cJSON_NULL: - return true; - - case cJSON_Number: - if (compare_double(a->valuedouble, b->valuedouble)) { - return true; - } - return false; - - case cJSON_String: - case cJSON_Raw: - if ((a->valuestring == NULL) || (b->valuestring == NULL)) { - return false; - } - if (strcmp(a->valuestring, b->valuestring) == 0) { - return true; - } - - return false; - - case cJSON_Array: - { - cJSON *a_element = a->child; - cJSON *b_element = b->child; - - for (; (a_element != NULL) && (b_element != NULL);) { - if (!cJSON_Compare(a_element, b_element, case_sensitive)) { - return false; - } - - a_element = a_element->next; - b_element = b_element->next; - } - - /* one of the arrays is longer than the other */ - if (a_element != b_element) { - return false; - } - - return true; - } - - case cJSON_Object: - { - cJSON *a_element = NULL; - cJSON *b_element = NULL; - cJSON_ArrayForEach(a_element, a) - { - /* TODO This has O(n^2) runtime, which is horrible! */ - b_element = - get_object_item(b, a_element->string, case_sensitive); - if (b_element == NULL) { - return false; - } - - if (!cJSON_Compare(a_element, b_element, case_sensitive)) { - return false; - } - } - - /* doing this twice, once on a and b to prevent true comparison if a - * subset of b - * TODO: Do this the proper way, this is just a fix for now */ - cJSON_ArrayForEach(b_element, b) - { - a_element = - get_object_item(a, b_element->string, case_sensitive); - if (a_element == NULL) { - return false; - } - - if (!cJSON_Compare(b_element, a_element, case_sensitive)) { - return false; - } - } - - return true; - } - - default: - return false; - } -} - -CJSON_PUBLIC(void *) cJSON_malloc(size_t size) -{ - return global_hooks.allocate(size); -} - -CJSON_PUBLIC(void) cJSON_free(void *object) -{ - global_hooks.deallocate(object); -} diff --git a/test-tools/host-tool/external/cJSON/cJSON.h b/test-tools/host-tool/external/cJSON/cJSON.h deleted file mode 100644 index 2cafdcf59..000000000 --- a/test-tools/host-tool/external/cJSON/cJSON.h +++ /dev/null @@ -1,392 +0,0 @@ -/* - Copyright (c) 2009-2017 Dave Gamble and cJSON contributors - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -#ifndef cJSON__h -#define cJSON__h - -#ifdef __cplusplus -extern "C" { -#endif - -#if !defined(__WINDOWS__) \ - && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) \ - || defined(_WIN32)) -#define __WINDOWS__ -#endif - -#ifdef __WINDOWS__ - -/* When compiling for windows, we specify a specific calling convention to avoid -issues where we are being called from a project with a different default calling -convention. For windows you have 3 define options: - -CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever -dllexport symbols CJSON_EXPORT_SYMBOLS - Define this on library build when you -want to dllexport symbols (default) CJSON_IMPORT_SYMBOLS - Define this if you -want to dllimport symbol - -For *nix builds that support visibility attribute, you can define similar -behavior by - -setting default visibility to hidden by adding --fvisibility=hidden (for gcc) -or --xldscope=hidden (for sun cc) -to CFLAGS - -then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way -CJSON_EXPORT_SYMBOLS does - -*/ - -#define CJSON_CDECL __cdecl -#define CJSON_STDCALL __stdcall - -/* export symbols by default, this is necessary for copy pasting the C and - * header file */ -#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) \ - && !defined(CJSON_EXPORT_SYMBOLS) -#define CJSON_EXPORT_SYMBOLS -#endif - -#if defined(CJSON_HIDE_SYMBOLS) -#define CJSON_PUBLIC(type) type CJSON_STDCALL -#elif defined(CJSON_EXPORT_SYMBOLS) -#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL -#elif defined(CJSON_IMPORT_SYMBOLS) -#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL -#endif -#else /* !__WINDOWS__ */ -#define CJSON_CDECL -#define CJSON_STDCALL - -#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined(__SUNPRO_C)) \ - && defined(CJSON_API_VISIBILITY) -#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type -#else -#define CJSON_PUBLIC(type) type -#endif -#endif - -/* project version */ -#define CJSON_VERSION_MAJOR 1 -#define CJSON_VERSION_MINOR 7 -#define CJSON_VERSION_PATCH 16 - -#include - -/* cJSON Types: */ -#define cJSON_Invalid (0) -#define cJSON_False (1 << 0) -#define cJSON_True (1 << 1) -#define cJSON_NULL (1 << 2) -#define cJSON_Number (1 << 3) -#define cJSON_String (1 << 4) -#define cJSON_Array (1 << 5) -#define cJSON_Object (1 << 6) -#define cJSON_Raw (1 << 7) /* raw json */ - -#define cJSON_IsReference 256 -#define cJSON_StringIsConst 512 - -/* The cJSON structure: */ -typedef struct cJSON { - /* next/prev allow you to walk array/object chains. Alternatively, use - * GetArraySize/GetArrayItem/GetObjectItem */ - struct cJSON *next; - struct cJSON *prev; - /* An array or object item will have a child pointer pointing to a chain of - * the items in the array/object. */ - struct cJSON *child; - - /* The type of the item, as above. */ - int type; - - /* The item's string, if type==cJSON_String and type == cJSON_Raw */ - char *valuestring; - /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */ - int valueint; - /* The item's number, if type==cJSON_Number */ - double valuedouble; - - /* The item's name string, if this item is the child of, or is in the list - * of subitems of an object. */ - char *string; -} cJSON; - -typedef struct cJSON_Hooks { - /* malloc/free are CDECL on Windows regardless of the default calling - * convention of the compiler, so ensure the hooks allow passing those - * functions directly. */ - void *(CJSON_CDECL *malloc_fn)(size_t sz); - void(CJSON_CDECL *free_fn)(void *ptr); -} cJSON_Hooks; - -typedef int cJSON_bool; - -/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse - * them. This is to prevent stack overflows. */ -#ifndef CJSON_NESTING_LIMIT -#define CJSON_NESTING_LIMIT 1000 -#endif - -/* returns the version of cJSON as a string */ -CJSON_PUBLIC(const char *) cJSON_Version(void); - -/* Supply malloc, realloc and free functions to cJSON */ -CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks *hooks); - -/* Memory Management: the caller is always responsible to free the results from - * all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib - * free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is - * cJSON_PrintPreallocated, where the caller has full responsibility of the - * buffer. */ -/* Supply a block of JSON, and this returns a cJSON object you can interrogate. - */ -CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); -CJSON_PUBLIC(cJSON *) -cJSON_ParseWithLength(const char *value, size_t buffer_length); -/* ParseWithOpts allows you to require (and check) that the JSON is null - * terminated, and to retrieve the pointer to the final byte parsed. */ -/* If you supply a ptr in return_parse_end and parsing fails, then - * return_parse_end will contain a pointer to the error so will match - * cJSON_GetErrorPtr(). */ -CJSON_PUBLIC(cJSON *) -cJSON_ParseWithOpts(const char *value, const char **return_parse_end, - cJSON_bool require_null_terminated); -CJSON_PUBLIC(cJSON *) -cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, - const char **return_parse_end, - cJSON_bool require_null_terminated); - -/* Render a cJSON entity to text for transfer/storage. */ -CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item); -/* Render a cJSON entity to text for transfer/storage without any formatting. */ -CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item); -/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess - * at the final size. guessing well reduces reallocation. fmt=0 gives - * unformatted, =1 gives formatted */ -CJSON_PUBLIC(char *) -cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt); -/* Render a cJSON entity to text using a buffer already allocated in memory with - * given length. Returns 1 on success and 0 on failure. */ -/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will - * use, so to be safe allocate 5 bytes more than you actually need */ -CJSON_PUBLIC(cJSON_bool) -cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, - const cJSON_bool format); -/* Delete a cJSON entity and all subentities. */ -CJSON_PUBLIC(void) cJSON_Delete(cJSON *item); - -/* Returns the number of items in an array (or object). */ -CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array); -/* Retrieve item number "index" from array "array". Returns NULL if - * unsuccessful. */ -CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index); -/* Get item "string" from object. Case insensitive. */ -CJSON_PUBLIC(cJSON *) -cJSON_GetObjectItem(const cJSON *const object, const char *const string); -CJSON_PUBLIC(cJSON *) -cJSON_GetObjectItemCaseSensitive(const cJSON *const object, - const char *const string); -CJSON_PUBLIC(cJSON_bool) -cJSON_HasObjectItem(const cJSON *object, const char *string); -/* For analysing failed parses. This returns a pointer to the parse error. - * You'll probably need to look a few chars back to make sense of it. Defined - * when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ -CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void); - -/* Check item type and return its value */ -CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON *const item); -CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON *const item); - -/* These functions check the type of an item */ -CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON *const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON *const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON *const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON *const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON *const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON *const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON *const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON *const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON *const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON *const item); - -/* These calls create a cJSON item of the appropriate type. */ -CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void); -CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void); -CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void); -CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean); -CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num); -CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string); -/* raw json */ -CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw); -CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void); -CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void); - -/* Create a string where valuestring references a string so - * it will not be freed by cJSON_Delete */ -CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string); -/* Create an object/array that only references it's elements so - * they will not be freed by cJSON_Delete */ -CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child); -CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child); - -/* These utilities create an Array of count items. - * The parameter count cannot be greater than the number of elements in the - * number array, otherwise array access will be out of bounds.*/ -CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count); -CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count); -CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count); -CJSON_PUBLIC(cJSON *) -cJSON_CreateStringArray(const char *const *strings, int count); - -/* Append item to the specified array/object. */ -CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item); -CJSON_PUBLIC(cJSON_bool) -cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item); -/* Use this when string is definitely const (i.e. a literal, or as good as), and - * will definitely survive the cJSON object. WARNING: When this function was - * used, make sure to always check that (item->type & cJSON_StringIsConst) is - * zero before writing to `item->string` */ -CJSON_PUBLIC(cJSON_bool) -cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item); -/* Append reference to item to the specified array/object. Use this when you - * want to add an existing cJSON to a new cJSON, but don't want to corrupt your - * existing cJSON. */ -CJSON_PUBLIC(cJSON_bool) -cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); -CJSON_PUBLIC(cJSON_bool) -cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item); - -/* Remove/Detach items from Arrays/Objects. */ -CJSON_PUBLIC(cJSON *) -cJSON_DetachItemViaPointer(cJSON *parent, cJSON *const item); -CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which); -CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which); -CJSON_PUBLIC(cJSON *) -cJSON_DetachItemFromObject(cJSON *object, const char *string); -CJSON_PUBLIC(cJSON *) -cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string); -CJSON_PUBLIC(void) -cJSON_DeleteItemFromObject(cJSON *object, const char *string); -CJSON_PUBLIC(void) -cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string); - -/* Update array items. */ -CJSON_PUBLIC(cJSON_bool) -cJSON_InsertItemInArray( - cJSON *array, int which, - cJSON *newitem); /* Shifts pre-existing items to the right. */ -CJSON_PUBLIC(cJSON_bool) -cJSON_ReplaceItemViaPointer(cJSON *const parent, cJSON *const item, - cJSON *replacement); -CJSON_PUBLIC(cJSON_bool) -cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem); -CJSON_PUBLIC(cJSON_bool) -cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem); -CJSON_PUBLIC(cJSON_bool) -cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, - cJSON *newitem); - -/* Duplicate a cJSON item */ -CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse); -/* Duplicate will create a new, identical cJSON item to the one you pass, in new - * memory that will need to be released. With recurse!=0, it will duplicate any - * children connected to the item. The item->next and ->prev pointers are always - * zero on return from Duplicate. */ -/* Recursively compare two cJSON items for equality. If either a or b is NULL or - * invalid, they will be considered unequal. case_sensitive determines if object - * keys are treated case sensitive (1) or case insensitive (0) */ -CJSON_PUBLIC(cJSON_bool) -cJSON_Compare(const cJSON *const a, const cJSON *const b, - const cJSON_bool case_sensitive); - -/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from - * strings. The input pointer json cannot point to a read-only address area, - * such as a string constant, but should point to a readable and writable - * address area. */ -CJSON_PUBLIC(void) cJSON_Minify(char *json); - -/* Helper functions for creating and adding items to an object at the same time. - * They return the added item or NULL on failure. */ -CJSON_PUBLIC(cJSON *) -cJSON_AddNullToObject(cJSON *const object, const char *const name); -CJSON_PUBLIC(cJSON *) -cJSON_AddTrueToObject(cJSON *const object, const char *const name); -CJSON_PUBLIC(cJSON *) -cJSON_AddFalseToObject(cJSON *const object, const char *const name); -CJSON_PUBLIC(cJSON *) -cJSON_AddBoolToObject(cJSON *const object, const char *const name, - const cJSON_bool boolean); -CJSON_PUBLIC(cJSON *) -cJSON_AddNumberToObject(cJSON *const object, const char *const name, - const double number); -CJSON_PUBLIC(cJSON *) -cJSON_AddStringToObject(cJSON *const object, const char *const name, - const char *const string); -CJSON_PUBLIC(cJSON *) -cJSON_AddRawToObject(cJSON *const object, const char *const name, - const char *const raw); -CJSON_PUBLIC(cJSON *) -cJSON_AddObjectToObject(cJSON *const object, const char *const name); -CJSON_PUBLIC(cJSON *) -cJSON_AddArrayToObject(cJSON *const object, const char *const name); - -/* When assigning an integer value, it needs to be propagated to valuedouble - * too. */ -#define cJSON_SetIntValue(object, number) \ - ((object) ? (object)->valueint = (object)->valuedouble = (number) \ - : (number)) -/* helper for the cJSON_SetNumberValue macro */ -CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number); -#define cJSON_SetNumberValue(object, number) \ - ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) \ - : (number)) -/* Change the valuestring of a cJSON_String object, only takes effect when type - * of object is cJSON_String */ -CJSON_PUBLIC(char *) -cJSON_SetValuestring(cJSON *object, const char *valuestring); - -/* If the object is not a boolean type this does nothing and returns - * cJSON_Invalid else it returns the new type*/ -#define cJSON_SetBoolValue(object, boolValue) \ - ((object != NULL && ((object)->type & (cJSON_False | cJSON_True))) \ - ? (object)->type = ((object)->type & (~(cJSON_False | cJSON_True))) \ - | ((boolValue) ? cJSON_True : cJSON_False) \ - : cJSON_Invalid) - -/* Macro for iterating over an array or object */ -#define cJSON_ArrayForEach(element, array) \ - for (element = (array != NULL) ? (array)->child : NULL; element != NULL; \ - element = element->next) - -/* malloc/free objects using the malloc/free functions that have been set with - * cJSON_InitHooks */ -CJSON_PUBLIC(void *) cJSON_malloc(size_t size); -CJSON_PUBLIC(void) cJSON_free(void *object); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/test-tools/host-tool/external/cJSON/cjson.cmake b/test-tools/host-tool/external/cJSON/cjson.cmake deleted file mode 100644 index af1a9d8a1..000000000 --- a/test-tools/host-tool/external/cJSON/cjson.cmake +++ /dev/null @@ -1,10 +0,0 @@ - -set (CJSON_DIR ${CMAKE_CURRENT_LIST_DIR}) - -include_directories(${CJSON_DIR}) - - -file (GLOB_RECURSE source_all ${CJSON_DIR}/*.c) - -set (CJSON_SOURCE ${source_all}) - diff --git a/test-tools/host-tool/src/host_tool_utils.c b/test-tools/host-tool/src/host_tool_utils.c deleted file mode 100644 index 9ea3d6ca9..000000000 --- a/test-tools/host-tool/src/host_tool_utils.c +++ /dev/null @@ -1,336 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "host_tool_utils.h" -#include "bi-inc/shared_utils.h" -#include "bh_platform.h" - -#include -#include -#include -#include -#include - -typedef union jvalue { - bool z; - int8_t i8; - uint8_t u8; - int16_t i16; - uint16_t u16; - int32_t i32; - uint32_t u32; - int64_t i64; - uint64_t u64; - float f; - double d; -} jvalue; - -static inline int16_t -get_int16(const char *buf) -{ - int16_t ret; - bh_memcpy_s(&ret, sizeof(int16_t), buf, sizeof(int16_t)); - return ret; -} - -static inline uint16_t -get_uint16(const char *buf) -{ - return get_int16(buf); -} - -static inline int32_t -get_int32(const char *buf) -{ - int32_t ret; - bh_memcpy_s(&ret, sizeof(int32_t), buf, sizeof(int32_t)); - return ret; -} - -static inline uint32_t -get_uint32(const char *buf) -{ - return get_int32(buf); -} - -char * -attr_container_get_attr_begin(const attr_container_t *attr_cont, - uint32_t *p_total_length, uint16_t *p_attr_num); - -cJSON * -attr2json(const attr_container_t *attr_cont) -{ - uint32_t total_length; - uint16_t attr_num, i, j, type; - const char *p, *tag, *key; - jvalue value; - cJSON *root; - - if (!attr_cont) - return NULL; - - root = cJSON_CreateObject(); - if (!root) - return NULL; - - /* TODO: how to convert the tag? */ - tag = attr_container_get_tag(attr_cont); - if (!tag) - goto fail; - - p = attr_container_get_attr_begin(attr_cont, &total_length, &attr_num); - if (!p) - goto fail; - - for (i = 0; i < attr_num; i++) { - cJSON *obj; - - key = p + 2; - /* Skip key len and key */ - p += 2 + get_uint16(p); - type = *p++; - - switch (type) { - case ATTR_TYPE_BYTE: /* = ATTR_TYPE_INT8 */ - bh_memcpy_s(&value.i8, 1, p, 1); - if (NULL == (obj = cJSON_CreateNumber(value.i8))) - goto fail; - cJSON_AddItemToObject(root, key, obj); - p++; - break; - case ATTR_TYPE_SHORT: /* = ATTR_TYPE_INT16 */ - bh_memcpy_s(&value.i16, sizeof(int16_t), p, sizeof(int16_t)); - if (NULL == (obj = cJSON_CreateNumber(value.i16))) - goto fail; - cJSON_AddItemToObject(root, key, obj); - /* another approach: cJSON_AddNumberToObject(root, key, value.s) - */ - p += 2; - break; - case ATTR_TYPE_INT: /* = ATTR_TYPE_INT32 */ - bh_memcpy_s(&value.i32, sizeof(int32_t), p, sizeof(int32_t)); - if (NULL == (obj = cJSON_CreateNumber(value.i32))) - goto fail; - cJSON_AddItemToObject(root, key, obj); - p += 4; - break; - case ATTR_TYPE_INT64: - bh_memcpy_s(&value.i64, sizeof(int64_t), p, sizeof(int64_t)); - if (NULL == (obj = cJSON_CreateNumber(value.i64))) - goto fail; - cJSON_AddItemToObject(root, key, obj); - p += 8; - break; - case ATTR_TYPE_UINT8: - bh_memcpy_s(&value.u8, 1, p, 1); - if (NULL == (obj = cJSON_CreateNumber(value.u8))) - goto fail; - cJSON_AddItemToObject(root, key, obj); - p++; - break; - case ATTR_TYPE_UINT16: - bh_memcpy_s(&value.u16, sizeof(uint16_t), p, sizeof(uint16_t)); - if (NULL == (obj = cJSON_CreateNumber(value.u16))) - goto fail; - cJSON_AddItemToObject(root, key, obj); - p += 2; - break; - case ATTR_TYPE_UINT32: - bh_memcpy_s(&value.u32, sizeof(uint32_t), p, sizeof(uint32_t)); - if (NULL == (obj = cJSON_CreateNumber(value.u32))) - goto fail; - cJSON_AddItemToObject(root, key, obj); - p += 4; - break; - case ATTR_TYPE_UINT64: - bh_memcpy_s(&value.u64, sizeof(uint64_t), p, sizeof(uint64_t)); - if (NULL == (obj = cJSON_CreateNumber(value.u64))) - goto fail; - cJSON_AddItemToObject(root, key, obj); - p += 8; - break; - case ATTR_TYPE_FLOAT: - bh_memcpy_s(&value.f, sizeof(float), p, sizeof(float)); - if (NULL == (obj = cJSON_CreateNumber(value.f))) - goto fail; - cJSON_AddItemToObject(root, key, obj); - p += 4; - break; - case ATTR_TYPE_DOUBLE: - bh_memcpy_s(&value.d, sizeof(double), p, sizeof(double)); - if (NULL == (obj = cJSON_CreateNumber(value.d))) - goto fail; - cJSON_AddItemToObject(root, key, obj); - p += 8; - break; - case ATTR_TYPE_BOOLEAN: - bh_memcpy_s(&value.z, 1, p, 1); - if (NULL == (obj = cJSON_CreateBool(value.z))) - goto fail; - cJSON_AddItemToObject(root, key, obj); - p++; - break; - case ATTR_TYPE_STRING: - if (NULL == (obj = cJSON_CreateString(p + sizeof(uint16_t)))) - goto fail; - cJSON_AddItemToObject(root, key, obj); - p += sizeof(uint16_t) + get_uint16(p); - break; - case ATTR_TYPE_BYTEARRAY: - if (NULL == (obj = cJSON_CreateArray())) - goto fail; - cJSON_AddItemToObject(root, key, obj); - for (j = 0; j < get_uint32(p); j++) { - cJSON *item = - cJSON_CreateNumber(*(p + sizeof(uint32_t) + j)); - if (item == NULL) - goto fail; - cJSON_AddItemToArray(obj, item); - } - p += sizeof(uint32_t) + get_uint32(p); - break; - } - } - - return root; - -fail: - cJSON_Delete(root); - return NULL; -} - -attr_container_t * -json2attr(const cJSON *json_obj) -{ - attr_container_t *attr_cont; - cJSON *item; - - if (NULL == (attr_cont = attr_container_create(""))) - return NULL; - - if (!cJSON_IsObject(json_obj)) - goto fail; - - cJSON_ArrayForEach(item, json_obj) - { - - if (cJSON_IsNumber(item)) { - attr_container_set_double(&attr_cont, item->string, - item->valuedouble); - } - else if (cJSON_IsTrue(item)) { - attr_container_set_bool(&attr_cont, item->string, true); - } - else if (cJSON_IsFalse(item)) { - attr_container_set_bool(&attr_cont, item->string, false); - } - else if (cJSON_IsString(item)) { - attr_container_set_string(&attr_cont, item->string, - item->valuestring); - } - else if (cJSON_IsArray(item)) { - int8_t *array; - int i = 0, len = sizeof(int8_t) * cJSON_GetArraySize(item); - cJSON *array_item; - - if (0 == len || NULL == (array = (int8_t *)malloc(len))) - goto fail; - memset(array, 0, len); - - cJSON_ArrayForEach(array_item, item) - { - /* must be number array */ - if (!cJSON_IsNumber(array_item)) - break; - /* TODO: if array_item->valuedouble > 127 or < -128 */ - array[i++] = (int8_t)array_item->valuedouble; - } - if (i > 0) - attr_container_set_bytearray(&attr_cont, item->string, array, - i); - free(array); - } - } - - return attr_cont; - -fail: - attr_container_destroy(attr_cont); - return NULL; -} - -int g_mid = 0; - -int -gen_random_id() -{ - static bool init = false; - int r; - - if (!init) { - srand(time(NULL)); - init = true; - } - - r = rand(); - g_mid = r; - - return r; -} - -char * -read_file_to_buffer(const char *filename, int *ret_size) -{ - char *buffer; - int file; - int file_size, read_size; - struct stat stat_buf; - - if (!filename || !ret_size) { - return NULL; - } - - if ((file = open(filename, O_RDONLY, 0)) == -1) { - return NULL; - } - - if (fstat(file, &stat_buf) != 0) { - close(file); - return NULL; - } - - file_size = stat_buf.st_size; - - if (!(buffer = malloc(file_size))) { - close(file); - return NULL; - } - - read_size = read(file, buffer, file_size); - close(file); - - if (read_size < file_size) { - free(buffer); - return NULL; - } - - *ret_size = file_size; - return buffer; -} - -int -wirte_buffer_to_file(const char *filename, const char *buffer, int size) -{ - int file, ret; - - if ((file = open(filename, O_RDWR | O_CREAT | O_APPEND, 0644)) == -1) - return -1; - - ret = write(file, buffer, size); - - close(file); - - return ret; -} diff --git a/test-tools/host-tool/src/host_tool_utils.h b/test-tools/host-tool/src/host_tool_utils.h deleted file mode 100644 index 9b30b41ab..000000000 --- a/test-tools/host-tool/src/host_tool_utils.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _HOST_TOOL_UTILS_H_ -#define _HOST_TOOL_UTILS_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "bi-inc/attr_container.h" -#include "cJSON.h" - -/** - * @brief Convert attribute container object to cJSON object. - * - * @param attr the attribute container object to be converted - * - * @return the created cJSON object if not NULL, NULL means fail - * - * @warning the return object should be deleted with cJSON_Delete by caller - */ -cJSON * -attr2json(const attr_container_t *attr); - -/** - * @brief Convert cJSON object to attribute container object. - * - * @param json the cJSON object to be converted - * - * @return the created attribute container object if not NULL, NULL means fail - * - * @warning the return object should be deleted with attr_container_destroy - */ -attr_container_t * -json2attr(const cJSON *json); - -/** - * @brief Generate a random 32 bit integer. - * - * @return the generated random integer - */ -int -gen_random_id(); - -/** - * @brief Read file content to buffer. - * - * @param filename the file name to read - * @param ret_size pointer of integer to save file size once return success - * - * @return the created buffer which contains file content if not NULL, NULL - * means fail - * - * @warning the return buffer should be deleted with free by caller - */ -char * -read_file_to_buffer(const char *filename, int *ret_size); - -/** - * @brief Write buffer content to file. - * - * @param filename name the file name to be written - * @param buffer the buffer - * @param size size of the buffer to be written - * - * @return < 0 means fail, > 0 means the number of bytes actually written - */ -int -wirte_buffer_to_file(const char *filename, const char *buffer, int size); - -#ifdef __cplusplus -} /* end of extern "C" */ -#endif - -#endif diff --git a/test-tools/host-tool/src/main.c b/test-tools/host-tool/src/main.c deleted file mode 100644 index dbddbf81b..000000000 --- a/test-tools/host-tool/src/main.c +++ /dev/null @@ -1,887 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include -#include -#include -#include -#include -#include -#include - -#include "host_tool_utils.h" -#include "bi-inc/shared_utils.h" -#include "bi-inc/attr_container.h" -#include "coap_ext.h" -#include "cJSON.h" -#include "app_manager_export.h" /* for Module_WASM_App */ -#include "host_link.h" /* for REQUEST_PACKET */ -#include "transport.h" - -#define BUF_SIZE 1024 -#define TIMEOUT_EXIT_CODE 2 -#define URL_MAX_LEN 256 -#define DEFAULT_TIMEOUT_MS 5000 -#define DEFAULT_ALIVE_TIME_MS 0 - -#define CONNECTION_MODE_TCP 1 -#define CONNECTION_MODE_UART 2 - -typedef enum { - INSTALL, - UNINSTALL, - QUERY, - REQUEST, - REGISTER, - UNREGISTER -} op_type; - -typedef struct { - const char *file; - const char *name; - const char *module_type; - int heap_size; - /* max timers number */ - int timers; - int watchdog_interval; -} inst_info; - -typedef struct { - const char *name; - const char *module_type; -} uninst_info; - -typedef struct { - const char *name; -} query_info; - -typedef struct { - const char *url; - int action; - const char *json_payload_file; -} req_info; - -typedef struct { - const char *urls; -} reg_info; - -typedef struct { - const char *urls; -} unreg_info; - -typedef union operation_info { - inst_info inst; - uninst_info uinst; - query_info query; - req_info req; - reg_info reg; - unreg_info unreg; -} operation_info; - -typedef struct { - op_type type; - operation_info info; -} operation; - -typedef enum REPLY_PACKET_TYPE { - REPLY_TYPE_EVENT = 0, - REPLY_TYPE_RESPONSE = 1 -} REPLY_PACKET_TYPE; - -static uint32_t g_timeout_ms = DEFAULT_TIMEOUT_MS; -static uint32_t g_alive_time_ms = DEFAULT_ALIVE_TIME_MS; -static char *g_redirect_file_name = NULL; -static int g_redirect_udp_port = -1; -static int g_conn_fd; /* may be tcp or uart */ -static char *g_server_addr = "127.0.0.1"; -static int g_server_port = 8888; -static char *g_uart_dev = "/dev/ttyS2"; -static int g_baudrate = B115200; -static int g_connection_mode = CONNECTION_MODE_TCP; - -extern int g_mid; -extern unsigned char leading[2]; - -/* -1 fail, 0 success */ -static int -send_request(request_t *request, uint16_t msg_type) -{ - char *req_p; - int req_size, req_size_n, ret = -1; - - if ((req_p = pack_request(request, &req_size)) == NULL) - return -1; - - /* leading bytes */ - if (!host_tool_send_data(g_conn_fd, leading, sizeof(leading))) - goto ret; - - /* message type */ - msg_type = htons(msg_type); - if (!host_tool_send_data(g_conn_fd, (char *)&msg_type, sizeof(msg_type))) - goto ret; - - /* payload length */ - req_size_n = htonl(req_size); - if (!host_tool_send_data(g_conn_fd, (char *)&req_size_n, - sizeof(req_size_n))) - goto ret; - - /* payload */ - if (!host_tool_send_data(g_conn_fd, req_p, req_size)) - goto ret; - - ret = 0; - -ret: - free_req_resp_packet(req_p); - return ret; -} - -#define url_remain_space (sizeof(url) - strlen(url)) - -/** - * return: 0: success, others: fail - */ -static int -install(inst_info *info) -{ - request_t request[1] = { 0 }; - char *app_file_buf; - char url[URL_MAX_LEN] = { 0 }; - int ret = -1, app_size; - - snprintf(url, sizeof(url) - 1, "/applet?name=%s", info->name); - - if (info->module_type != NULL && url_remain_space > 0) - snprintf(url + strlen(url), url_remain_space, "&type=%s", - info->module_type); - - if (info->heap_size > 0 && url_remain_space > 0) - snprintf(url + strlen(url), url_remain_space, "&heap=%d", - info->heap_size); - - if (info->timers > 0 && url_remain_space > 0) - snprintf(url + strlen(url), url_remain_space, "&timers=%d", - info->timers); - - if (info->watchdog_interval > 0 && url_remain_space > 0) - snprintf(url + strlen(url), url_remain_space, "&wd=%d", - info->watchdog_interval); - - if ((app_file_buf = read_file_to_buffer(info->file, &app_size)) == NULL) - return -1; - - init_request(request, url, COAP_PUT, FMT_APP_RAW_BINARY, app_file_buf, - app_size); - request->mid = gen_random_id(); - - if (info->module_type == NULL || strcmp(info->module_type, "wasm") == 0) - ret = send_request(request, INSTALL_WASM_APP); - else - ret = send_request(request, REQUEST_PACKET); - - free(app_file_buf); - - return ret; -} - -static int -uninstall(uninst_info *info) -{ - request_t request[1] = { 0 }; - char url[URL_MAX_LEN] = { 0 }; - - snprintf(url, sizeof(url) - 1, "/applet?name=%s", info->name); - - if (info->module_type != NULL && url_remain_space > 0) - snprintf(url + strlen(url), url_remain_space, "&type=%s", - info->module_type); - - init_request(request, url, COAP_DELETE, FMT_ATTR_CONTAINER, NULL, 0); - request->mid = gen_random_id(); - - return send_request(request, REQUEST_PACKET); -} - -static int -query(query_info *info) -{ - request_t request[1] = { 0 }; - char url[URL_MAX_LEN] = { 0 }; - - if (info->name != NULL) - snprintf(url, sizeof(url) - 1, "/applet?name=%s", info->name); - else - snprintf(url, sizeof(url) - 1, "/applet"); - - init_request(request, url, COAP_GET, FMT_ATTR_CONTAINER, NULL, 0); - request->mid = gen_random_id(); - - return send_request(request, REQUEST_PACKET); -} - -static int -request(req_info *info) -{ - request_t request[1] = { 0 }; - attr_container_t *payload = NULL; - int ret = -1, payload_len = 0; - - if (info->json_payload_file != NULL) { - char *payload_file; - cJSON *json; - int payload_file_size; - - if ((payload_file = read_file_to_buffer(info->json_payload_file, - &payload_file_size)) - == NULL) - return -1; - - if (NULL == (json = cJSON_Parse(payload_file))) { - free(payload_file); - goto fail; - } - - if (NULL == (payload = json2attr(json))) { - cJSON_Delete(json); - free(payload_file); - goto fail; - } - payload_len = attr_container_get_serialize_length(payload); - - cJSON_Delete(json); - free(payload_file); - } - - init_request(request, (char *)info->url, info->action, FMT_ATTR_CONTAINER, - payload, payload_len); - request->mid = gen_random_id(); - - ret = send_request(request, REQUEST_PACKET); - - if (info->json_payload_file != NULL && payload != NULL) - attr_container_destroy(payload); - -fail: - return ret; -} - -/** - * TODO: currently only support 1 url. - * how to handle multiple responses and set process's exit code? - */ -static int -subscribe(reg_info *info) -{ - request_t request[1] = { 0 }; - int ret = -1; -#if 0 - char *p; - - p = strtok(info->urls, ","); - while(p != NULL) { - char url[URL_MAX_LEN] = {0}; - snprintf(url, URL_MAX_LEN, "%s%s", "/event/", p); - init_request(request, - url, - COAP_PUT, - FMT_ATTR_CONTAINER, - NULL, - 0); - request->mid = gen_random_id(); - ret = send_request(request, false); - p = strtok (NULL, ","); - } -#else - char url[URL_MAX_LEN] = { 0 }; - char *prefix = info->urls[0] == '/' ? "/event" : "/event/"; - snprintf(url, URL_MAX_LEN, "%s%s", prefix, info->urls); - init_request(request, url, COAP_PUT, FMT_ATTR_CONTAINER, NULL, 0); - request->mid = gen_random_id(); - ret = send_request(request, REQUEST_PACKET); -#endif - return ret; -} - -static int -unsubscribe(unreg_info *info) -{ - request_t request[1] = { 0 }; - int ret = -1; -#if 0 - char *p; - - p = strtok(info->urls, ","); - while(p != NULL) { - char url[URL_MAX_LEN] = {0}; - snprintf(url, URL_MAX_LEN, "%s%s", "/event/", p); - init_request(request, - url, - COAP_DELETE, - FMT_ATTR_CONTAINER, - NULL, - 0); - request->mid = gen_random_id(); - ret = send_request(request, false); - p = strtok (NULL, ","); - } -#else - char url[URL_MAX_LEN] = { 0 }; - snprintf(url, URL_MAX_LEN, "%s%s", "/event/", info->urls); - init_request(request, url, COAP_DELETE, FMT_ATTR_CONTAINER, NULL, 0); - request->mid = gen_random_id(); - ret = send_request(request, REQUEST_PACKET); -#endif - return ret; -} - -static int -init() -{ - if (g_connection_mode == CONNECTION_MODE_TCP) { - int fd; - if (!tcp_init(g_server_addr, g_server_port, &fd)) - return -1; - g_conn_fd = fd; - return 0; - } - else if (g_connection_mode == CONNECTION_MODE_UART) { - int fd; - if (!uart_init(g_uart_dev, g_baudrate, &fd)) - return -1; - g_conn_fd = fd; - return 0; - } - - return -1; -} - -static void -deinit() -{ - close(g_conn_fd); -} - -static int -parse_action(const char *str) -{ - if (strcasecmp(str, "PUT") == 0) - return COAP_PUT; - if (strcasecmp(str, "GET") == 0) - return COAP_GET; - if (strcasecmp(str, "DELETE") == 0) - return COAP_DELETE; - if (strcasecmp(str, "POST") == 0) - return COAP_POST; - return -1; -} - -/* clang-format off */ -static void showUsage() -{ - printf("Usages:\n"); - printf(" host_tool -i|-u|-q|-r|-s|-d ...\n"); - printf(" host_tool -i -f \n" - " [--type=]\n" - " [--heap=]\n" - " [--timers=]\n" - " [--watchdog=]\n" - " [ ...] \n"); - printf(" host_tool -u [ ...]\n"); - printf(" host_tool -q[] [ ...]\n"); - printf(" host_tool -r -A [-p ] [ ...]\n"); - printf(" host_tool -s [ ...]\n"); - printf(" host_tool -d [ ...]\n"); - - printf("\nGeneral Options:\n"); - printf(" -i, --install Install an application\n"); - printf(" -u, --uninstall Uninstall an application\n"); - printf(" -q, --query Query all applications\n"); - printf(" -r, --request Send a request\n"); - printf(" -s, --register Register event(s)\n"); - printf(" -d, --deregister De-register event(s)\n"); - printf(" -f, --file Specify app binary file path\n"); - printf(" -A, --action Specify action of the request\n"); - printf(" -p, --payload Specify payload of the request\n"); - - printf("\nControl Options:\n"); - printf(" -S
|--address=
Set server address, default to 127.0.0.1\n"); - printf(" -P |--port= Set server port, default to 8888\n"); - printf(" -D |--uart= Set uart device, default to /dev/ttyS2\n"); - printf(" -B |--baudrate= Set uart device baudrate, default to 115200\n"); - printf(" -t |--timeout= Operation timeout in ms, default to 5000\n"); - printf(" -a |--alive= Alive time in ms after last operation done, default to 0\n"); - printf(" -o |--output= Redirect the output to output a file\n"); - printf(" -U |--udp= Redirect the output to an UDP port in local machine\n"); - - printf("\nNotes:\n"); - printf(" =name of the application\n"); - printf(" =path of the application binary file in wasm format\n"); - printf(" =resource descriptor, such as /app//res1 or /res1\n"); - printf(" =event url list separated by ',', such as /event1,/event2,/event3\n"); - printf(" =action of the request, can be PUT, GET, DELETE or POST (case insensitive)\n"); - printf(" =path of the payload file in json format\n"); - printf(" =Type of app. Can be 'wasm'(default) or 'jeff'\n"); - printf(" =Heap size of app.\n"); - printf(" =Max timers number app can use.\n"); - printf(" =Watchdog interval in ms.\n"); -} - -#define CHECK_DUPLICATE_OPERATION do { \ - if (operation_parsed) { \ - showUsage(); \ - return false; \ - } \ -} while(0) - -#define ERROR_RETURN do { \ - showUsage(); \ - return false; \ -} while(0) - -#define CHECK_ARGS_UNMATCH_OPERATION(op_type) do { \ - if (!operation_parsed || op->type != op_type) { \ - showUsage(); \ - return false; \ - } \ -} while(0) - -static bool parse_args(int argc, char *argv[], operation *op) -{ - int c; - bool operation_parsed = false; - bool conn_mode_parsed = false; - - while (1) { - int optIndex = 0; - static struct option longOpts[] = { - { "install", required_argument, NULL, 'i' }, - { "uninstall", required_argument, NULL, 'u' }, - { "query", optional_argument, NULL, 'q' }, - { "request", required_argument, NULL, 'r' }, - { "register", required_argument, NULL, 's' }, - { "deregister", required_argument, NULL, 'd' }, - { "timeout", required_argument, NULL, 't' }, - { "alive", required_argument, NULL, 'a' }, - { "output", required_argument, NULL, 'o' }, - { "udp", required_argument, NULL, 'U' }, - { "action", required_argument, NULL, 'A' }, - { "file", required_argument, NULL, 'f' }, - { "payload", required_argument, NULL, 'p' }, - { "type", required_argument, NULL, 0 }, - { "heap", required_argument, NULL, 1 }, - { "timers", required_argument, NULL, 2 }, - { "watchdog", required_argument, NULL, 3 }, - { "address", required_argument, NULL, 'S' }, - { "port", required_argument, NULL, 'P' }, - { "uart_device",required_argument, NULL, 'D' }, - { "baudrate", required_argument, NULL, 'B' }, - { "help", required_argument, NULL, 'h' }, - { 0, 0, 0, 0 } - }; - - c = getopt_long(argc, argv, "i:u:q::r:s:d:t:a:o:U:A:f:p:S:P:D:B:h", - longOpts, &optIndex); - if (c == -1) - break; - - switch (c) { - case 'i': - CHECK_DUPLICATE_OPERATION; - op->type = INSTALL; - op->info.inst.name = optarg; - operation_parsed = true; - break; - case 'u': - CHECK_DUPLICATE_OPERATION; - op->type = UNINSTALL; - op->info.uinst.name = optarg; - operation_parsed = true; - break; - case 'q': - CHECK_DUPLICATE_OPERATION; - op->type = QUERY; - op->info.query.name = optarg; - break; - case 'r': - CHECK_DUPLICATE_OPERATION; - op->type = REQUEST; - op->info.req.url = optarg; - operation_parsed = true; - break; - case 's': - CHECK_DUPLICATE_OPERATION; - op->type = REGISTER; - op->info.reg.urls = optarg; - operation_parsed = true; - break; - case 'd': - CHECK_DUPLICATE_OPERATION; - op->type = UNREGISTER; - op->info.unreg.urls = optarg; - operation_parsed = true; - break; - case 't': - g_timeout_ms = atoi(optarg); - break; - case 'a': - g_alive_time_ms = atoi(optarg); - break; - case 'o': - g_redirect_file_name = optarg; - break; - case 'U': - g_redirect_udp_port = atoi(optarg); - break; - case 'A': - CHECK_ARGS_UNMATCH_OPERATION(REQUEST); - op->info.req.action = parse_action(optarg); - break; - case 'f': - CHECK_ARGS_UNMATCH_OPERATION(INSTALL); - op->info.inst.file = optarg; - break; - case 'p': - CHECK_ARGS_UNMATCH_OPERATION(REQUEST); - op->info.req.json_payload_file = optarg; - break; - /* module type */ - case 0: - /* TODO: use bit mask */ - /* CHECK_ARGS_UNMATCH_OPERATION(INSTALL | UNINSTALL); */ - if (op->type == INSTALL) - op->info.inst.module_type = optarg; - else if (op->type == UNINSTALL) - op->info.uinst.module_type = optarg; - break; - /* heap */ - case 1: - CHECK_ARGS_UNMATCH_OPERATION(INSTALL); - op->info.inst.heap_size = atoi(optarg); - break; - /* timers */ - case 2: - CHECK_ARGS_UNMATCH_OPERATION(INSTALL); - op->info.inst.timers = atoi(optarg); - break; - /* watchdog */ - case 3: - CHECK_ARGS_UNMATCH_OPERATION(INSTALL); - op->info.inst.watchdog_interval = atoi(optarg); - break; - case 'S': - if (conn_mode_parsed) { - showUsage(); - return false; - } - g_connection_mode = CONNECTION_MODE_TCP; - g_server_addr = optarg; - conn_mode_parsed = true; - break; - case 'P': - g_server_port = atoi(optarg); - break; - case 'D': - if (conn_mode_parsed) { - showUsage(); - return false; - } - g_connection_mode = CONNECTION_MODE_UART; - g_uart_dev = optarg; - conn_mode_parsed = true; - break; - case 'B': - g_baudrate = parse_baudrate(atoi(optarg)); - break; - case 'h': - showUsage(); - return false; - default: - showUsage(); - return false; - } - } - - /* check mandatory options for the operation */ - switch (op->type) { - case INSTALL: - if (NULL == op->info.inst.file || NULL == op->info.inst.name) - ERROR_RETURN; - break; - case UNINSTALL: - if (NULL == op->info.uinst.name) - ERROR_RETURN; - break; - case QUERY: - break; - case REQUEST: - if (NULL == op->info.req.url || op->info.req.action <= 0) - ERROR_RETURN; - break; - case REGISTER: - if (NULL == op->info.reg.urls) - ERROR_RETURN; - break; - case UNREGISTER: - if (NULL == op->info.unreg.urls) - ERROR_RETURN; - break; - default: - return false; - } - - return true; -} - -/** - * return value: < 0: not complete message - * REPLY_TYPE_EVENT: event(request) - * REPLY_TYPE_RESPONSE: response - */ -static int process_reply_data(const char *buf, int len, - imrt_link_recv_context_t *ctx) -{ - int result = -1; - const char *pos = buf; - -#if DEBUG - int i = 0; - for (; i < len; i++) { - printf(" 0x%02x", buf[i]); - } - printf("\n"); -#endif - - while (len-- > 0) { - result = on_imrt_link_byte_arrive((unsigned char) *pos++, ctx); - switch (result) { - case 0: { - imrt_link_message_t *message = &ctx->message; - if (message->message_type == RESPONSE_PACKET) - return REPLY_TYPE_RESPONSE; - if (message->message_type == REQUEST_PACKET) - return REPLY_TYPE_EVENT; - break; - } - default: - break; - } - } - - return -1; -} - -static response_t * -parse_response_from_imrtlink(imrt_link_message_t *message, response_t *response) -{ - if (!unpack_response(message->payload, message->payload_size, response)) - return NULL; - - return response; -} - -static request_t * -parse_event_from_imrtlink(imrt_link_message_t *message, request_t *request) -{ - if (!unpack_request(message->payload, message->payload_size, request)) - return NULL; - - return request; -} - -static void output(const char *header, attr_container_t *payload, - int foramt, int payload_len) -{ - cJSON *json = NULL; - char *json_str = NULL; - - /* output the header */ - printf("%s", header); - if (g_redirect_file_name != NULL) - wirte_buffer_to_file(g_redirect_file_name, header, strlen(header)); - if (g_redirect_udp_port > 0 && g_redirect_udp_port < 65535) - udp_send("127.0.0.1", g_redirect_udp_port, header, strlen(header)); - - if (foramt != FMT_ATTR_CONTAINER || payload == NULL || payload_len <= 0) - return; - - if ((json = attr2json(payload)) == NULL) - return; - - if ((json_str = cJSON_Print(json)) == NULL) { - cJSON_Delete(json); - return; - } - - /* output the payload as json format */ - printf("%s", json_str); - if (g_redirect_file_name != NULL) - wirte_buffer_to_file(g_redirect_file_name, json_str, strlen(json_str)); - if (g_redirect_udp_port > 0 && g_redirect_udp_port < 65535) - udp_send("127.0.0.1", g_redirect_udp_port, json_str, strlen(json_str)); - - free(json_str); - cJSON_Delete(json); -} - -static void output_response(response_t *obj) -{ - char header[32] = { 0 }; - snprintf(header, sizeof(header), "\nresponse status %d\n", obj->status); - output(header, obj->payload, obj->fmt, obj->payload_len); -} - -static void output_event(request_t *obj) -{ - char header[256] = { 0 }; - snprintf(header, sizeof(header), "\nreceived an event %s\n", obj->url); - output(header, obj->payload, obj->fmt, obj->payload_len); -} - -int main(int argc, char *argv[]) -{ - int ret = -1; - imrt_link_recv_context_t recv_ctx = { 0 }; - char buffer[BUF_SIZE] = { 0 }; - uint32_t last_check = 0, total_elpased_ms = 0; - bool is_responsed = false; - operation op; - - memset(&op, 0, sizeof(op)); - - if (!parse_args(argc, argv, &op)) - return -1; - - /* TODO: reconnect 3 times */ - if (init() != 0) - return -1; - - switch (op.type) { - case INSTALL: - ret = install((inst_info *) &op.info.inst); - break; - case UNINSTALL: - ret = uninstall((uninst_info *) &op.info.uinst); - break; - case QUERY: - ret = query((query_info *) &op.info.query); - break; - case REQUEST: - ret = request((req_info *) &op.info.req); - break; - case REGISTER: - ret = subscribe((reg_info *) &op.info.reg); - break; - case UNREGISTER: - ret = unsubscribe((unreg_info *) &op.info.unreg); - break; - default: - goto ret; - } - - if (ret != 0) - goto ret; - - bh_get_elpased_ms(&last_check); - - while (1) { - int result = 0; - fd_set readfds; - struct timeval tv; - - total_elpased_ms += bh_get_elpased_ms(&last_check); - - if (!is_responsed) { - if (total_elpased_ms >= g_timeout_ms) { - output("operation timeout\n", NULL, 0, 0); - ret = TIMEOUT_EXIT_CODE; - goto ret; - } - } else { - if (total_elpased_ms >= g_alive_time_ms) { - /*ret = 0;*/ - goto ret; - } - } - - if (g_conn_fd == -1) { - if ((init() != 0) - || (g_conn_fd == -1)) { - sleep(1); - continue; - } - } - - FD_ZERO(&readfds); - FD_SET(g_conn_fd, &readfds); - - tv.tv_sec = 1; - tv.tv_usec = 0; - - result = select(FD_SETSIZE, &readfds, NULL, NULL, &tv); - - if (result < 0) { - if (errno != EINTR) { - printf("Error in select, errno: 0x%x\n", errno); - ret = -1; - goto ret; - } - } - else if (result == 0) { /* select timeout */ - } - else if (result > 0) { - int n; - if (FD_ISSET(g_conn_fd, &readfds)) { - int reply_type = -1; - - n = read(g_conn_fd, buffer, BUF_SIZE); - if (n <= 0) { - g_conn_fd = -1; - continue; - } - - reply_type = process_reply_data((char *) buffer, n, &recv_ctx); - - if (reply_type == REPLY_TYPE_RESPONSE) { - response_t response[1] = { 0 }; - - parse_response_from_imrtlink(&recv_ctx.message, response); - - if (response->mid != g_mid) { - /* ignore invalid response */ - continue; - } - - is_responsed = true; - ret = response->status; - output_response(response); - - if (op.type == REGISTER || op.type == UNREGISTER) { - /* alive time start */ - total_elpased_ms = 0; - bh_get_elpased_ms(&last_check); - } - } - else if (reply_type == REPLY_TYPE_EVENT) { - request_t event[1] = { 0 }; - - parse_event_from_imrtlink(&recv_ctx.message, event); - - if (op.type == REGISTER || op.type == UNREGISTER) { - output_event(event); - } - } - } - } - } /* end of while(1) */ - -ret: - if (recv_ctx.message.payload != NULL) - free(recv_ctx.message.payload); - - deinit(); - return ret; -} diff --git a/test-tools/host-tool/src/transport.c b/test-tools/host-tool/src/transport.c deleted file mode 100644 index d4edf4f1d..000000000 --- a/test-tools/host-tool/src/transport.c +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "transport.h" - -#define SA struct sockaddr - -unsigned char leading[2] = { 0x12, 0x34 }; - -bool -tcp_init(const char *address, uint16_t port, int *fd) -{ - int sock; - struct sockaddr_in servaddr; - - if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) - return false; - - bzero(&servaddr, sizeof(servaddr)); - servaddr.sin_family = AF_INET; - servaddr.sin_addr.s_addr = inet_addr(address); - servaddr.sin_port = htons(port); - - if (connect(sock, (SA *)&servaddr, sizeof(servaddr)) != 0) { - close(sock); - return false; - } - - *fd = sock; - return true; -} - -int -parse_baudrate(int baud) -{ - switch (baud) { - case 9600: - return B9600; - case 19200: - return B19200; - case 38400: - return B38400; - case 57600: - return B57600; - case 115200: - return B115200; - case 230400: - return B230400; - case 460800: - return B460800; - case 500000: - return B500000; - case 576000: - return B576000; - case 921600: - return B921600; - case 1000000: - return B1000000; - case 1152000: - return B1152000; - case 1500000: - return B1500000; - case 2000000: - return B2000000; - case 2500000: - return B2500000; - case 3000000: - return B3000000; - case 3500000: - return B3500000; - case 4000000: - return B4000000; - default: - return -1; - } -} - -bool -uart_init(const char *device, int baudrate, int *fd) -{ - int uart_fd; - struct termios uart_term; - - uart_fd = open(device, O_RDWR | O_NOCTTY); - - if (uart_fd < 0) - return false; - - memset(&uart_term, 0, sizeof(uart_term)); - uart_term.c_cflag = baudrate | CS8 | CLOCAL | CREAD; - uart_term.c_iflag = IGNPAR; - uart_term.c_oflag = 0; - - /* set noncanonical mode */ - uart_term.c_lflag = 0; - uart_term.c_cc[VTIME] = 30; - uart_term.c_cc[VMIN] = 1; - tcflush(uart_fd, TCIFLUSH); - - if (tcsetattr(uart_fd, TCSANOW, &uart_term) != 0) { - close(uart_fd); - return false; - } - - *fd = uart_fd; - return true; -} - -bool -udp_send(const char *address, int port, const char *buf, int len) -{ - int sockfd; - ssize_t size_sent; - struct sockaddr_in servaddr; - - if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) - return false; - - memset(&servaddr, 0, sizeof(servaddr)); - - servaddr.sin_family = AF_INET; - servaddr.sin_port = htons(port); - servaddr.sin_addr.s_addr = INADDR_ANY; - - size_sent = sendto(sockfd, buf, len, MSG_CONFIRM, - (const struct sockaddr *)&servaddr, sizeof(servaddr)); - - close(sockfd); - return (size_sent != -1) ? true : false; -} - -bool -host_tool_send_data(int fd, const char *buf, unsigned int len) -{ - int cnt = 0; - ssize_t ret; - - if (fd == -1 || buf == NULL || len <= 0) { - return false; - } - -resend: - ret = write(fd, buf, len); - - if (ret == -1) { - if (errno == ECONNRESET) { - close(fd); - } - - // repeat sending if the outbuffer is full - if (errno == EAGAIN || errno == EWOULDBLOCK) { - if (++cnt > 10) { - close(fd); - return false; - } - sleep(1); - goto resend; - } - } - - return (ret == len); -} - -#define SET_RECV_PHASE(ctx, new_phase) \ - do { \ - ctx->phase = new_phase; \ - ctx->size_in_phase = 0; \ - } while (0) - -/* - * input: 1 byte from remote - * output: parse result - * return: -1 invalid sync byte - * 1 byte added to buffer, waiting more for complete packet - * 0 completed packet - * 2 in receiving payload - */ -int -on_imrt_link_byte_arrive(unsigned char ch, imrt_link_recv_context_t *ctx) -{ - if (ctx->phase == Phase_Non_Start) { - if (ctx->message.payload) { - free(ctx->message.payload); - ctx->message.payload = NULL; - ctx->message.payload_size = 0; - } - - if (leading[0] == ch) { - ctx->phase = Phase_Leading; - } - else { - return -1; - } - } - else if (ctx->phase == Phase_Leading) { - if (leading[1] == ch) { - SET_RECV_PHASE(ctx, Phase_Type); - } - else { - ctx->phase = Phase_Non_Start; - return -1; - } - } - else if (ctx->phase == Phase_Type) { - unsigned char *p = (unsigned char *)&ctx->message.message_type; - p[ctx->size_in_phase++] = ch; - - if (ctx->size_in_phase == sizeof(ctx->message.message_type)) { - ctx->message.message_type = ntohs(ctx->message.message_type); - SET_RECV_PHASE(ctx, Phase_Size); - } - } - else if (ctx->phase == Phase_Size) { - unsigned char *p = (unsigned char *)&ctx->message.payload_size; - p[ctx->size_in_phase++] = ch; - - if (ctx->size_in_phase == sizeof(ctx->message.payload_size)) { - ctx->message.payload_size = ntohl(ctx->message.payload_size); - SET_RECV_PHASE(ctx, Phase_Payload); - - if (ctx->message.payload) { - free(ctx->message.payload); - ctx->message.payload = NULL; - } - - /* no payload */ - if (ctx->message.payload_size == 0) { - SET_RECV_PHASE(ctx, Phase_Non_Start); - return 0; - } - - ctx->message.payload = (char *)malloc(ctx->message.payload_size); - SET_RECV_PHASE(ctx, Phase_Payload); - } - } - else if (ctx->phase == Phase_Payload) { - ctx->message.payload[ctx->size_in_phase++] = ch; - - if (ctx->size_in_phase == ctx->message.payload_size) { - SET_RECV_PHASE(ctx, Phase_Non_Start); - return 0; - } - - return 2; - } - - return 1; -} diff --git a/test-tools/host-tool/src/transport.h b/test-tools/host-tool/src/transport.h deleted file mode 100644 index 449f438f8..000000000 --- a/test-tools/host-tool/src/transport.h +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef DEPS_APP_MGR_HOST_TOOL_SRC_TRANSPORT_H_ -#define DEPS_APP_MGR_HOST_TOOL_SRC_TRANSPORT_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -/* IMRT link message between host and WAMR */ -typedef struct { - unsigned short message_type; - unsigned int payload_size; - char *payload; -} imrt_link_message_t; - -/* The receive phase of IMRT link message */ -typedef enum { - Phase_Non_Start, - Phase_Leading, - Phase_Type, - Phase_Size, - Phase_Payload -} recv_phase_t; - -/* The receive context of IMRT link message */ -typedef struct { - recv_phase_t phase; - int size_in_phase; - imrt_link_message_t message; -} imrt_link_recv_context_t; - -/** - * @brief Send data to WAMR. - * - * @param fd the connection fd to WAMR - * @param buf the buffer that contains content to be sent - * @param len size of the buffer to be sent - * - * @return true if success, false if fail - */ -bool -host_tool_send_data(int fd, const char *buf, unsigned int len); - -/** - * @brief Handle one byte of IMRT link message - * - * @param ch the one byte from WAMR to be handled - * @param ctx the receive context - * - * @return -1 invalid sync byte - * 1 byte added to buffer, waiting more for complete packet - * 0 completed packet - * 2 in receiving payload - */ -int -on_imrt_link_byte_arrive(unsigned char ch, imrt_link_recv_context_t *ctx); - -/** - * @brief Initialize TCP connection with remote server. - * - * @param address the network address of peer - * @param port the network port of peer - * @param fd pointer of integer to save the socket fd once return success - * - * @return true if success, false if fail - */ -bool -tcp_init(const char *address, uint16_t port, int *fd); - -/** - * @brief Initialize UART connection with remote. - * - * @param device name of the UART device - * @param baudrate baudrate of the device - * @param fd pointer of integer to save the uart fd once return success - * - * @return true if success, false if fail - */ -bool -uart_init(const char *device, int baudrate, int *fd); - -/** - * @brief Parse UART baudrate from an integer - * - * @param the baudrate interger to be parsed - * - * @return true if success, false if fail - * - * @par - * @code - * int baudrate = parse_baudrate(9600); - * ... - * uart_term.c_cflag = baudrate; - * ... - * @endcode - */ -int -parse_baudrate(int baud); - -/** - * @brief Send data over UDP. - * - * @param address network address of the remote - * @param port network port of the remote - * @param buf the buffer that contains content to be sent - * @param len size of the buffer to be sent - * - * @return true if success, false if fail - */ -bool -udp_send(const char *address, int port, const char *buf, int len); - -#ifdef __cplusplus -} /* end of extern "C" */ -#endif - -#endif /* DEPS_APP_MGR_HOST_TOOL_SRC_TRANSPORT_H_ */ diff --git a/test-tools/wamr-ide/Media/Config_building_target.png b/test-tools/wamr-ide/Media/Config_building_target.png index a1270007f..18db0c836 100644 Binary files a/test-tools/wamr-ide/Media/Config_building_target.png and b/test-tools/wamr-ide/Media/Config_building_target.png differ diff --git a/test-tools/wamr-ide/Media/compilation_config.png b/test-tools/wamr-ide/Media/compilation_config.png index 43c60a21f..346244d6c 100644 Binary files a/test-tools/wamr-ide/Media/compilation_config.png and b/test-tools/wamr-ide/Media/compilation_config.png differ diff --git a/test-tools/wamr-ide/Media/compilation_config_2.png b/test-tools/wamr-ide/Media/compilation_config_2.png index c16bb09ec..7bf46b2aa 100644 Binary files a/test-tools/wamr-ide/Media/compilation_config_2.png and b/test-tools/wamr-ide/Media/compilation_config_2.png differ diff --git a/test-tools/wamr-ide/README.md b/test-tools/wamr-ide/README.md index 8a6e1509f..778892220 100644 --- a/test-tools/wamr-ide/README.md +++ b/test-tools/wamr-ide/README.md @@ -14,7 +14,11 @@ The WAMR-IDE is an Integrated Development Environment to develop WebAssembly app ## How to setup WAMR IDE -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). +Now, the most straightforward way to install the WAMR IDE extension is by searching for WAMR-IDE in the VS Code extension marketplace and installing it directly. So, if you simply want to use WAMR debugging features in VS Code, this is the ideal (and effortless) way. And you are ready to [use WAMR IDE](#how-to-use-wamr-ide). + +> It is only recommended to download versions after 1.3.2 from the marketplace. + +Also, we have same version tagged docker images, lldb binaries and VS Code installation file(.vsix file) packed for each GitHub release. You can following the tutorial in [this section](#21-download-wamr-vs-code-extension-from-the-github-releaserecommended-approach). 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). @@ -93,19 +97,19 @@ We have 2 docker images which should be built or loaded on your host, `wasm-tool Windows (powershell): ```batch -$ cd .\WASM-Toolchain\Docker -$ .\build_docker_image.bat -$ cd .\WASM-Debug-Server\Docker -$ .\build_docker_image.bat +cd .\WASM-Toolchain\Docker +.\build_docker_image.bat +cd .\WASM-Debug-Server\Docker +.\build_docker_image.bat ``` Linux: ```shell -$ cd ./WASM-Toolchain/Docker -$ ./build_docker_image.sh -$ cd ./WASM-Debug-Server/Docker -$ ./build_docker_image.sh +cd ./WASM-Toolchain/Docker +./build_docker_image.sh +cd ./WASM-Debug-Server/Docker +./build_docker_image.sh ``` ##### 2.2.2 After building, you can find `wasm-toolchain` and `wasm-debug-server` docker images on your local @@ -145,11 +149,11 @@ $ docker build --no-cache --build-arg http_proxy=http://proxy.example.com:1234 `wamride-1.0.0.vsix` can be packaged by [`npm vsce`](https://code.visualstudio.com/api/working-with-extensions/publishing-extension). ```shell -$ npm install -g vsce -$ cd VSCode-Extension -$ rm -rf node_modules -$ npm install -$ vsce package +npm install -g vsce +cd VSCode-Extension +rm -rf node_modules +npm install +vsce package ``` ##### 2.2.7 Enable VS Code debugging feature @@ -171,7 +175,6 @@ $ cp inst/* /home/{usrname}/.vscode-server/extensions/wamr.wamride-1.0.0/resourc 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.** ##### 2.2.7 Install extension from vsix @@ -184,7 +187,7 @@ select `wamride-1.0.0.vsix` which you have packed on your host. ## How to use `wamr-ide` -#### `WAMR-IDE` extension contains 2 components as following picture showing. `WAMR IDE` for workspace and project management and `Current Project` for project's execution. +#### `WAMR-IDE` extension contains 2 components as following picture showing. `WAMR IDE` for workspace and project management and `Current Project` for project's execution ![wamr_ide_main_menu](./Media/wamr_ide_main_menu.png "wamr-ide main menu") @@ -254,7 +257,7 @@ Click `Change workspace` button, a dialog will show as following. You can select At the same time, all added `include path` and `exclude files` will be saved in `.wamr/compilation_config.json` as json array. - ![compilation config](./Media/compilation_config_2.png "compilation config") + ![compilation config](./Media/compilation_config.png "compilation config") > `Toggle state of path including` just shows when selecting `folder` and hides with other resources. > @@ -268,13 +271,22 @@ Click `Configuration` button, a new page will be shown as following. You can con ![config building target](./Media/Config_building_target.png "config building target") +Short Explanation of the Fields Above: + +- Output file name: The compiled wasm file name of your program. +- Initial linear memory size, Max linear memory size, Stack size: The wasi-sdk clang compile options. +- Exported symbols: The symbols your wasm program wants to export. **Multiple symbols are separated by commas without spaces**. +- Host managed heap size: The running configuration for the host managed heap size of iwasm. In most cases, the default size would be fine, but in some scenarios, let's say you want to allocate more memory using `malloc`, you should increase it here accordingly. + +> Note that due to the current implementation limitation, after changing the `Output file name` or `Host managed heap size`, you need to close and reopen VSCode (to reactivate the extension) so that the running config will be correctly updated. + Then click `Modify` button to confirm, if configurations are modified successfully and following message will pop. Click `OK`, the page will be auto closed. ![save configuration](./Media/save_configuration.png "save configuration") And all configuration will be saved in `.wamr/compilation_config.json`. -![configuration file](./Media/compilation_config.png "configuration file") +![configuration file](./Media/compilation_config_2.png "configuration file") #### 2. `Build` diff --git a/test-tools/wamr-ide/VSCode-Extension/package.json b/test-tools/wamr-ide/VSCode-Extension/package.json index d7cc20595..77f96537c 100644 --- a/test-tools/wamr-ide/VSCode-Extension/package.json +++ b/test-tools/wamr-ide/VSCode-Extension/package.json @@ -6,7 +6,7 @@ }, "displayName": "WAMR-IDE", "description": "An Integrated Development Environment for WASM", - "version": "1.2.2", + "version": "1.3.2", "engines": { "vscode": "^1.59.0", "node": ">=16.0.0" diff --git a/test-tools/wamr-ide/VSCode-Extension/resource/scripts/boot_debugger_server.bat b/test-tools/wamr-ide/VSCode-Extension/resource/scripts/boot_debugger_server.bat index 7fd1f024a..4d3a2c3ec 100644 --- a/test-tools/wamr-ide/VSCode-Extension/resource/scripts/boot_debugger_server.bat +++ b/test-tools/wamr-ide/VSCode-Extension/resource/scripts/boot_debugger_server.bat @@ -7,4 +7,4 @@ docker run --rm -it --name=wasm-debug-server-ctr ^ -v "%cd%":/mnt ^ -p 1234:1234 ^ wasm-debug-server:%2 ^ - /bin/bash -c "./debug.sh %1" + /bin/bash -c "./debug.sh %1 %3" diff --git a/test-tools/wamr-ide/VSCode-Extension/resource/scripts/boot_debugger_server.sh b/test-tools/wamr-ide/VSCode-Extension/resource/scripts/boot_debugger_server.sh index 169fb7e5f..e06586593 100755 --- a/test-tools/wamr-ide/VSCode-Extension/resource/scripts/boot_debugger_server.sh +++ b/test-tools/wamr-ide/VSCode-Extension/resource/scripts/boot_debugger_server.sh @@ -9,4 +9,4 @@ docker run --rm -it --name=wasm-debug-server-ctr \ -v "$(pwd)":/mnt \ -p 1234:1234 \ wasm-debug-server:$2 \ - /bin/bash -c "./debug.sh $1" + /bin/bash -c "./debug.sh $1 $3" diff --git a/test-tools/wamr-ide/VSCode-Extension/resource/scripts/run.bat b/test-tools/wamr-ide/VSCode-Extension/resource/scripts/run.bat index af47f35ba..387a8e629 100644 --- a/test-tools/wamr-ide/VSCode-Extension/resource/scripts/run.bat +++ b/test-tools/wamr-ide/VSCode-Extension/resource/scripts/run.bat @@ -6,4 +6,4 @@ docker run --rm -it --name=wasm-debug-server-ctr ^ -v "%cd%":/mnt ^ wasm-debug-server:%2 ^ - /bin/bash -c "./run.sh %1" + /bin/bash -c "./run.sh %1 %3" diff --git a/test-tools/wamr-ide/VSCode-Extension/resource/scripts/run.sh b/test-tools/wamr-ide/VSCode-Extension/resource/scripts/run.sh index 670e57c1e..2526b9546 100755 --- a/test-tools/wamr-ide/VSCode-Extension/resource/scripts/run.sh +++ b/test-tools/wamr-ide/VSCode-Extension/resource/scripts/run.sh @@ -8,4 +8,4 @@ set -e docker run --rm -it --name=wasm-debug-server-ctr \ -v "$(pwd)":/mnt \ wasm-debug-server:$2 \ - /bin/bash -c "./run.sh $1" + /bin/bash -c "./run.sh $1 $3" diff --git a/test-tools/wamr-ide/VSCode-Extension/resource/webview/js/configbuildtarget.js b/test-tools/wamr-ide/VSCode-Extension/resource/webview/js/configbuildtarget.js index 837f384bc..1c146d933 100644 --- a/test-tools/wamr-ide/VSCode-Extension/resource/webview/js/configbuildtarget.js +++ b/test-tools/wamr-ide/VSCode-Extension/resource/webview/js/configbuildtarget.js @@ -15,6 +15,7 @@ function submitFunc() { let maxMemSize = document.getElementById('max_mem_size').value; let stackSize = document.getElementById('stack_size').value; let exportedSymbols = document.getElementById('exported_symbols').value; + let hostManagedHeapSize = document.getElementById('host_managed_heap_size').value; vscode.postMessage({ command: 'config_build_target', @@ -23,5 +24,6 @@ function submitFunc() { maxMemSize: maxMemSize, stackSize: stackSize, exportedSymbols: exportedSymbols, + hostManagedHeapSize: hostManagedHeapSize, }); } diff --git a/test-tools/wamr-ide/VSCode-Extension/resource/webview/page/configBuildTarget.html b/test-tools/wamr-ide/VSCode-Extension/resource/webview/page/configBuildTarget.html index b4c431511..877356a42 100644 --- a/test-tools/wamr-ide/VSCode-Extension/resource/webview/page/configBuildTarget.html +++ b/test-tools/wamr-ide/VSCode-Extension/resource/webview/page/configBuildTarget.html @@ -41,12 +41,30 @@
- +
+
+
+

Config iwasm running option

+ +
+
+ +
+
+
+ + +
+
+
+
diff --git a/test-tools/wamr-ide/VSCode-Extension/src/debugConfigurationProvider.ts b/test-tools/wamr-ide/VSCode-Extension/src/debugConfigurationProvider.ts index 657cf59c7..d24abe6a2 100644 --- a/test-tools/wamr-ide/VSCode-Extension/src/debugConfigurationProvider.ts +++ b/test-tools/wamr-ide/VSCode-Extension/src/debugConfigurationProvider.ts @@ -8,23 +8,24 @@ import * as os from 'os'; /* see https://github.com/llvm/llvm-project/tree/main/lldb/tools/lldb-vscode#attaching-settings */ export interface WasmDebugConfig { - type: string, - name: string, - request: string, - program? : string, - pid?: string, - stopOnEntry?: boolean, - waitFor?: boolean, - initCommands?: string[], - preRunCommands?: string[], - stopCommands?: string[], - exitCommands?: string[], - terminateCommands?: string[], - attachCommands?: string[] + type: string; + name: string; + request: string; + program?: string; + pid?: string; + stopOnEntry?: boolean; + waitFor?: boolean; + initCommands?: string[]; + preRunCommands?: string[]; + stopCommands?: string[]; + exitCommands?: string[]; + terminateCommands?: string[]; + attachCommands?: string[]; } export class WasmDebugConfigurationProvider - implements vscode.DebugConfigurationProvider { + implements vscode.DebugConfigurationProvider +{ private wasmDebugConfig: WasmDebugConfig = { type: 'wamr-debug', name: 'Attach', @@ -33,28 +34,29 @@ export class WasmDebugConfigurationProvider attachCommands: [ /* default port 1234 */ 'process connect -p wasm connect://127.0.0.1:1234', - ] + ], }; constructor(extensionPath: string) { this.wasmDebugConfig.initCommands = [ /* Add rust formatters -> https://lldb.llvm.org/use/variable.html */ - `command script import ${extensionPath}/formatters/rust.py` + `command script import ${extensionPath}/formatters/rust.py`, ]; if (os.platform() === 'win32' || os.platform() === 'darwin') { - this.wasmDebugConfig.initCommands.push('platform select remote-linux'); + this.wasmDebugConfig.initCommands.push( + 'platform select remote-linux' + ); } } public resolveDebugConfiguration( _: vscode.WorkspaceFolder | undefined, - debugConfiguration: vscode.DebugConfiguration, + debugConfiguration: vscode.DebugConfiguration ): vscode.ProviderResult { - this.wasmDebugConfig = { ...this.wasmDebugConfig, - ...debugConfiguration + ...debugConfiguration, }; return this.wasmDebugConfig; diff --git a/test-tools/wamr-ide/VSCode-Extension/src/extension.ts b/test-tools/wamr-ide/VSCode-Extension/src/extension.ts index 419f730c8..ab549fc2d 100644 --- a/test-tools/wamr-ide/VSCode-Extension/src/extension.ts +++ b/test-tools/wamr-ide/VSCode-Extension/src/extension.ts @@ -170,7 +170,9 @@ export async function activate(context: vscode.ExtensionContext) { } /* register debug configuration */ - wasmDebugConfigProvider = new WasmDebugConfigurationProvider(context.extensionPath); + wasmDebugConfigProvider = new WasmDebugConfigurationProvider( + context.extensionPath + ); vscode.debug.registerDebugConfigurationProvider( 'wamr-debug', @@ -811,6 +813,7 @@ interface BuildArgs { maxMemorySize: string; stackSize: string; exportedSymbols: string; + hostManagedHeapSize: string; } /** diff --git a/test-tools/wamr-ide/VSCode-Extension/src/taskProvider.ts b/test-tools/wamr-ide/VSCode-Extension/src/taskProvider.ts index 9b9b75f9a..ee8ba5d1d 100644 --- a/test-tools/wamr-ide/VSCode-Extension/src/taskProvider.ts +++ b/test-tools/wamr-ide/VSCode-Extension/src/taskProvider.ts @@ -31,6 +31,7 @@ export class WasmTaskProvider implements vscode.TaskProvider { /* target name is used for generated aot target */ const targetName = TargetConfigPanel.buildArgs.outputFileName.split('.')[0]; + const heapSize = TargetConfigPanel.buildArgs.hostManagedHeapSize; if ( os.platform() === 'linux' || @@ -57,7 +58,7 @@ export class WasmTaskProvider implements vscode.TaskProvider { : (this._script.get('debugScript') as string), options: { executable: this._script.get('debugScript'), - shellArgs: [targetName, this._wamrVersion], + shellArgs: [targetName, this._wamrVersion, heapSize], }, }; @@ -69,7 +70,7 @@ export class WasmTaskProvider implements vscode.TaskProvider { : (this._script.get('runScript') as string), options: { executable: this._script.get('runScript'), - shellArgs: [targetName, this._wamrVersion], + shellArgs: [targetName, this._wamrVersion, heapSize], }, }; diff --git a/test-tools/wamr-ide/VSCode-Extension/src/test/runTest.ts b/test-tools/wamr-ide/VSCode-Extension/src/test/runTest.ts index ae81a539b..635e02ede 100644 --- a/test-tools/wamr-ide/VSCode-Extension/src/test/runTest.ts +++ b/test-tools/wamr-ide/VSCode-Extension/src/test/runTest.ts @@ -9,25 +9,25 @@ import * as os from 'os'; import { runTests } from '@vscode/test-electron'; async function main() { - try { - // The folder containing the Extension Manifest package.json - // Passed to `--extensionDevelopmentPath` - const extensionDevelopmentPath = path.resolve(__dirname, '../../'); + try { + // The folder containing the Extension Manifest package.json + // Passed to `--extensionDevelopmentPath` + const extensionDevelopmentPath = path.resolve(__dirname, '../../'); - // The path to the extension test script - // Passed to --extensionTestsPath - const extensionTestsPath = path.resolve(__dirname, './suite/index'); + // The path to the extension test script + // Passed to --extensionTestsPath + const extensionTestsPath = path.resolve(__dirname, './suite/index'); - // Download VS Code, unzip it and run the integration test - await runTests({ - extensionDevelopmentPath, - extensionTestsPath, - launchArgs: ['--user-data-dir', `${os.tmpdir()}`] - }); - } catch (err) { - console.error('Failed to run tests'); - process.exit(1); - } + // Download VS Code, unzip it and run the integration test + await runTests({ + extensionDevelopmentPath, + extensionTestsPath, + launchArgs: ['--user-data-dir', `${os.tmpdir()}`], + }); + } catch (err) { + console.error('Failed to run tests'); + process.exit(1); + } } main(); diff --git a/test-tools/wamr-ide/VSCode-Extension/src/test/suite/extension.test.ts b/test-tools/wamr-ide/VSCode-Extension/src/test/suite/extension.test.ts index 5bd717b28..d1420dfa5 100644 --- a/test-tools/wamr-ide/VSCode-Extension/src/test/suite/extension.test.ts +++ b/test-tools/wamr-ide/VSCode-Extension/src/test/suite/extension.test.ts @@ -3,57 +3,65 @@ * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ -import {DebugProtocol} from '@vscode/debugprotocol'; -import {after, before, test, suite} from 'mocha'; -import {assert} from 'chai'; +import { DebugProtocol } from '@vscode/debugprotocol'; +import { after, before, test, suite } from 'mocha'; +import { assert } from 'chai'; import * as vscode from 'vscode'; import * as cp from 'child_process'; -import * as path from "path"; +import * as path from 'path'; import * as os from 'os'; -import {WasmDebugConfig, WasmDebugConfigurationProvider} from "../../debugConfigurationProvider"; -import {EXTENSION_PATH, clearAllBp, setBpAtMarker, compileRustToWasm} from "./utils"; -import {downloadLldb, isLLDBInstalled} from '../../utilities/lldbUtilities'; +import { + WasmDebugConfig, + WasmDebugConfigurationProvider, +} from '../../debugConfigurationProvider'; +import { + EXTENSION_PATH, + clearAllBp, + setBpAtMarker, + compileRustToWasm, +} from './utils'; +import { downloadLldb, isLLDBInstalled } from '../../utilities/lldbUtilities'; suite('Unit Tests', function () { test('DebugConfigurationProvider init commands', function () { - const testExtensionPath = "/test/path/"; + const testExtensionPath = '/test/path/'; const provider = new WasmDebugConfigurationProvider(testExtensionPath); assert.includeMembers( // eslint-disable-next-line @typescript-eslint/no-non-null-assertion provider.getDebugConfig().initCommands!, [`command script import ${testExtensionPath}/formatters/rust.py`], - "Debugger init commands did not contain " + 'Debugger init commands did not contain ' ); }); test('DebugConfigurationProvider resolve configuration', function () { - const testExtensionPath = "/test/path/"; + const testExtensionPath = '/test/path/'; const provider = new WasmDebugConfigurationProvider(testExtensionPath); const actual = provider.resolveDebugConfiguration(undefined, { - type: "wamr-debug", - name: "Attach", - request: "attach", + type: 'wamr-debug', + name: 'Attach', + request: 'attach', initCommands: [], attachCommands: [ 'process connect -p wasm connect://123.456.789.1:1237', - ] + ], }); assert.deepEqual( actual, { - type: "wamr-debug", - name: "Attach", - request: "attach", + type: 'wamr-debug', + name: 'Attach', + request: 'attach', stopOnEntry: true, initCommands: [], attachCommands: [ 'process connect -p wasm connect://123.456.789.1:1237', - ] + ], }, - "Configuration did not match the expected configuration after calling resolveDebugConfiguration()" + 'Configuration did not match the expected configuration after calling resolveDebugConfiguration()' ); }); }); @@ -69,16 +77,24 @@ suite('Inegration Tests', function () { // Download LLDB if necessary. Should be available in the CI. Only for local execution. if (!isLLDBInstalled(EXTENSION_PATH)) { this.timeout(downloadTimeout); - console.log("Downloading LLDB. This might take a moment..."); + console.log('Downloading LLDB. This might take a moment...'); await downloadLldb(EXTENSION_PATH); - assert.isTrue(isLLDBInstalled(EXTENSION_PATH), "LLDB was not installed correctly"); + assert.isTrue( + isLLDBInstalled(EXTENSION_PATH), + 'LLDB was not installed correctly' + ); } compileRustToWasm(); const platform = os.platform(); - assert.isTrue(platform === "darwin" || platform === "linux", `Tests do not support your platform: ${platform}`); - const iWasmPath = path.resolve(`${EXTENSION_PATH}/../../../product-mini/platforms/${platform}/build/iwasm`); + assert.isTrue( + platform === 'darwin' || platform === 'linux', + `Tests do not support your platform: ${platform}` + ); + const iWasmPath = path.resolve( + `${EXTENSION_PATH}/../../../product-mini/platforms/${platform}/build/iwasm` + ); const testWasmFilePath = `${EXTENSION_PATH}/resource/test/test.wasm`; debuggerProcess = cp.spawn( @@ -87,7 +103,7 @@ suite('Inegration Tests', function () { {} ); - debuggerProcess.stderr.on('data', (data) => { + debuggerProcess.stderr.on('data', data => { console.log(`Error from debugger process: ${data}`); }); }); @@ -101,44 +117,54 @@ suite('Inegration Tests', function () { // timeout of 1 minutes this.timeout(60 * 1000); clearAllBp(); - setBpAtMarker(`${EXTENSION_PATH}/resource/test/test.rs`, "BP_MARKER_1"); + setBpAtMarker(`${EXTENSION_PATH}/resource/test/test.rs`, 'BP_MARKER_1'); - const getVariables = new Promise((resolve, reject) => { - vscode.debug.registerDebugAdapterTrackerFactory("wamr-debug", { - createDebugAdapterTracker: function () { - return { - // The debug adapter has sent a Debug Adapter Protocol message to the editor. - onDidSendMessage: (message: DebugProtocol.ProtocolMessage) => { - if (message.type === "response") { - const m = message as DebugProtocol.Response; - if (m.command === "variables") { - const res = m as DebugProtocol.VariablesResponse; - resolve(res.body.variables); + const getVariables = new Promise( + (resolve, reject) => { + vscode.debug.registerDebugAdapterTrackerFactory('wamr-debug', { + createDebugAdapterTracker: function () { + return { + // The debug adapter has sent a Debug Adapter Protocol message to the editor. + onDidSendMessage: ( + message: DebugProtocol.ProtocolMessage + ) => { + if (message.type === 'response') { + const m = message as DebugProtocol.Response; + if (m.command === 'variables') { + const res = + m as DebugProtocol.VariablesResponse; + resolve(res.body.variables); + } } - } - }, - onError: (error: Error) => { - reject("An error occurred before vscode reached the breakpoint: " + error); - }, - onExit: (code: number | undefined) => { - reject(`Debugger exited before vscode reached the breakpoint with code: ${code}`); - }, - }; - } - }); - }); + }, + onError: (error: Error) => { + reject( + 'An error occurred before vscode reached the breakpoint: ' + + error + ); + }, + onExit: (code: number | undefined) => { + reject( + `Debugger exited before vscode reached the breakpoint with code: ${code}` + ); + }, + }; + }, + }); + } + ); const config: WasmDebugConfig = { - type: "wamr-debug", - request: "attach", - name: "Attach Debugger", + type: 'wamr-debug', + request: 'attach', + name: 'Attach Debugger', stopOnEntry: false, initCommands: [ - `command script import ${EXTENSION_PATH}/formatters/rust.py` + `command script import ${EXTENSION_PATH}/formatters/rust.py`, ], attachCommands: [ - `process connect -p wasm connect://127.0.0.1:${port}` - ] + `process connect -p wasm connect://127.0.0.1:${port}`, + ], }; if (os.platform() === 'win32' || os.platform() === 'darwin') { @@ -148,36 +174,70 @@ suite('Inegration Tests', function () { try { await vscode.debug.startDebugging(undefined, config); } catch (e) { - assert.fail("Could not connect to debug adapter"); + assert.fail('Could not connect to debug adapter'); } // wait until vs code has reached breakpoint and has requested the variables. const variables = await getVariables; - const namesToVariables = variables.reduce((acc: { [name: string]: DebugProtocol.Variable }, c) => { - if (c.evaluateName) { - acc[c.evaluateName] = c; - } - return acc; - }, {}); + const namesToVariables = variables.reduce( + (acc: { [name: string]: DebugProtocol.Variable }, c) => { + if (c.evaluateName) { + acc[c.evaluateName] = c; + } + return acc; + }, + {} + ); - assert.includeMembers(Object.keys(namesToVariables), ["vector", "map", "string", "slice", "deque", "ref_cell"], "The Debugger did not return all expected debugger variables."); + assert.includeMembers( + Object.keys(namesToVariables), + ['vector', 'map', 'string', 'slice', 'deque', 'ref_cell'], + 'The Debugger did not return all expected debugger variables.' + ); // Vector - assert.equal(namesToVariables["vector"].value, " (5) vec![1, 2, 3, 4, 12]", "The Vector summary string looks different than expected"); + assert.equal( + namesToVariables['vector'].value, + ' (5) vec![1, 2, 3, 4, 12]', + 'The Vector summary string looks different than expected' + ); // Map - assert.equal(namesToVariables["map"].value, " size=5, capacity=8", "The Map summary string looks different than expected"); + assert.equal( + namesToVariables['map'].value, + ' size=5, capacity=8', + 'The Map summary string looks different than expected' + ); // String - assert.equal(namesToVariables["string"].value, " \"this is a string\"", "The String summary string looks different than expected"); + assert.equal( + namesToVariables['string'].value, + ' "this is a string"', + 'The String summary string looks different than expected' + ); // Slice - assert.equal(namesToVariables["slice"].value, " \"ello\"", "The Slice summary string looks different than expected"); + assert.equal( + namesToVariables['slice'].value, + ' "ello"', + 'The Slice summary string looks different than expected' + ); // Deque - assert.equal(namesToVariables["deque"].value, " (5) VecDeque[1, 2, 3, 4, 5]", "The Deque summary string looks different than expected"); + // TODO: The deque format conversion have some problem now + // -alloc::collections::vec_deque::VecDeque @ 0xfff1c + // + (5) VecDeque[1, 2, 3, 4, 5] + // assert.equal( + // namesToVariables['deque'].value, + // ' (5) VecDeque[1, 2, 3, 4, 5]', + // 'The Deque summary string looks different than expected' + // ); // RefCell - assert.equal(namesToVariables["ref_cell"].value, " 5", "The RefCell summary string looks different than expected"); + assert.equal( + namesToVariables['ref_cell'].value, + ' 5', + 'The RefCell summary string looks different than expected' + ); }); }); diff --git a/test-tools/wamr-ide/VSCode-Extension/src/test/suite/index.ts b/test-tools/wamr-ide/VSCode-Extension/src/test/suite/index.ts index 9b56c6ffe..3b7d271b1 100644 --- a/test-tools/wamr-ide/VSCode-Extension/src/test/suite/index.ts +++ b/test-tools/wamr-ide/VSCode-Extension/src/test/suite/index.ts @@ -8,35 +8,35 @@ import * as Mocha from 'mocha'; import * as glob from 'glob'; export function run(): Promise { - // Create the mocha test - const mocha = new Mocha({ - ui: 'tdd' - }); - - const testsRoot = path.resolve(__dirname, '..'); + // Create the mocha test + const mocha = new Mocha({ + ui: 'tdd', + }); - return new Promise((c, e) => { - glob('**/**.test.js', { cwd: testsRoot }, (err, files) => { - if (err) { - return e(err); - } + const testsRoot = path.resolve(__dirname, '..'); - // Add files to the test suite - files.forEach(f => mocha.addFile(path.resolve(testsRoot, f))); + return new Promise((c, e) => { + glob('**/**.test.js', { cwd: testsRoot }, (err, files) => { + if (err) { + return e(err); + } - try { - // Run the mocha test - mocha.run(failures => { - if (failures > 0) { - e(new Error(`${failures} tests failed.`)); - } else { - c(); - } - }); - } catch (err) { - console.error(err); - e(err); - } - }); - }); + // Add files to the test suite + files.forEach(f => mocha.addFile(path.resolve(testsRoot, f))); + + try { + // Run the mocha test + mocha.run(failures => { + if (failures > 0) { + e(new Error(`${failures} tests failed.`)); + } else { + c(); + } + }); + } catch (err) { + console.error(err); + e(err); + } + }); + }); } diff --git a/test-tools/wamr-ide/VSCode-Extension/src/test/suite/utils.ts b/test-tools/wamr-ide/VSCode-Extension/src/test/suite/utils.ts index 87cb04b3b..3f40596c3 100644 --- a/test-tools/wamr-ide/VSCode-Extension/src/test/suite/utils.ts +++ b/test-tools/wamr-ide/VSCode-Extension/src/test/suite/utils.ts @@ -3,10 +3,10 @@ * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ -import {assert} from 'chai'; +import { assert } from 'chai'; import * as vscode from 'vscode'; -import {Range, SourceBreakpoint} from "vscode"; -import * as fs from "fs"; +import { Range, SourceBreakpoint } from 'vscode'; +import * as fs from 'fs'; import path = require('path'); import * as cp from 'child_process'; @@ -20,11 +20,18 @@ export function clearAllBp(): void { // Inserts a breakpoint in a file at the first occurrence of bpMarker export function setBpAtMarker(file: string, bpMarker: string): void { const uri = vscode.Uri.file(file); - const data = fs.readFileSync(uri.path, "utf8"); - const line = data.split("\n").findIndex(line => line.includes(bpMarker)); - assert.notStrictEqual(line, -1, "Could not find breakpoint marker in source file"); + const data = fs.readFileSync(uri.path, 'utf8'); + const line = data.split('\n').findIndex(line => line.includes(bpMarker)); + assert.notStrictEqual( + line, + -1, + 'Could not find breakpoint marker in source file' + ); const position = new vscode.Position(line, 0); - const bp = new SourceBreakpoint(new vscode.Location(uri, new Range(position, position)), true); + const bp = new SourceBreakpoint( + new vscode.Location(uri, new Range(position, position)), + true + ); vscode.debug.addBreakpoints([bp]); } @@ -35,9 +42,12 @@ export function compileRustToWasm(): void { const cmd = `rustc --target wasm32-wasi ${testResourceFolder}/test.rs -g -C opt-level=0 -o ${testResourceFolder}/test.wasm`; try { - cp.execSync(cmd, {stdio: [null, null, process.stderr]}); + cp.execSync(cmd, { stdio: [null, null, process.stderr] }); } catch (e) { assert.fail(`Compilation of example rust file failed with error: ${e}`); } - assert.isTrue(fs.existsSync(`${testResourceFolder}/test.wasm`), "Could not find wasm file WASM file to run debugger on."); + assert.isTrue( + fs.existsSync(`${testResourceFolder}/test.wasm`), + 'Could not find wasm file WASM file to run debugger on.' + ); } diff --git a/test-tools/wamr-ide/VSCode-Extension/src/utilities/lldbUtilities.ts b/test-tools/wamr-ide/VSCode-Extension/src/utilities/lldbUtilities.ts index b6553acbc..954476666 100644 --- a/test-tools/wamr-ide/VSCode-Extension/src/utilities/lldbUtilities.ts +++ b/test-tools/wamr-ide/VSCode-Extension/src/utilities/lldbUtilities.ts @@ -35,9 +35,7 @@ function getLLDBUnzipFilePath(destinationFolder: string, filename: string) { return path.join(destinationFolder, ...dirs); } -export function getWAMRExtensionVersion( - extensionPath: string -): string { +export function getWAMRExtensionVersion(extensionPath: string): string { // eslint-disable-next-line @typescript-eslint/no-var-requires return require(path.join(extensionPath, 'package.json')).version; } @@ -68,7 +66,6 @@ export function isLLDBInstalled(extensionPath: string): boolean { export async function promptInstallLLDB( extensionPath: string ): Promise { - const response = await vscode.window.showWarningMessage( 'No LLDB instance found. Setup now?', SelectionOfPrompt.setUp, @@ -84,9 +81,7 @@ export async function promptInstallLLDB( return SelectionOfPrompt.setUp; } -export async function downloadLldb( - extensionPath: string -): Promise { +export async function downloadLldb(extensionPath: string): Promise { const downloadUrl = getLLDBDownloadUrl(extensionPath); const destinationDir = os.platform(); diff --git a/test-tools/wamr-ide/VSCode-Extension/src/view/TargetConfigPanel.ts b/test-tools/wamr-ide/VSCode-Extension/src/view/TargetConfigPanel.ts index f2e1343a5..8efa2455c 100644 --- a/test-tools/wamr-ide/VSCode-Extension/src/view/TargetConfigPanel.ts +++ b/test-tools/wamr-ide/VSCode-Extension/src/view/TargetConfigPanel.ts @@ -20,6 +20,7 @@ export class TargetConfigPanel { maxMemorySize: '131072', stackSize: '4096', exportedSymbols: 'main', + hostManagedHeapSize: '4096', }; private static readonly userInputError: number = -2; @@ -74,14 +75,16 @@ export class TargetConfigPanel { initMemSize: string, maxMemSize: string, stackSize: string, - exportedSymbols: string + exportedSymbols: string, + hostManagedHeapSize: string ): number { if ( outputFileName === '' || initMemSize === '' || maxMemSize === '' || stackSize === '' || - exportedSymbols === '' + exportedSymbols === '' || + hostManagedHeapSize === '' ) { return TargetConfigPanel.userInputError; } @@ -95,6 +98,7 @@ export class TargetConfigPanel { maxMemorySize: maxMemSize, stackSize: stackSize, exportedSymbols: exportedSymbols, + hostManagedHeapSize: hostManagedHeapSize, }; const configStr = readFromConfigFile(); @@ -174,6 +178,10 @@ export class TargetConfigPanel { .replace( /(\${exported_symbols_val})/, TargetConfigPanel.buildArgs.exportedSymbols + ) + .replace( + /(\${host_managed_heap_size_val})/, + TargetConfigPanel.buildArgs.hostManagedHeapSize ); return html; @@ -189,7 +197,8 @@ export class TargetConfigPanel { message.initMemSize === '' || message.maxMemSize === '' || message.stackSize === '' || - message.exportedSymbols === '' + message.exportedSymbols === '' || + message.hostManagedHeapSize === '' ) { vscode.window.showErrorMessage( 'Please fill chart before your submit!' @@ -201,7 +210,8 @@ export class TargetConfigPanel { message.initMemSize, message.maxMemSize, message.stackSize, - message.exportedSymbols + message.exportedSymbols, + message.hostManagedHeapSize ) === TargetConfigPanel.executionSuccess ) { vscode.window diff --git a/test-tools/wamr-ide/WASM-Debug-Server/Docker/resource/debug.sh b/test-tools/wamr-ide/WASM-Debug-Server/Docker/resource/debug.sh index 48458870f..33cdb5844 100755 --- a/test-tools/wamr-ide/WASM-Debug-Server/Docker/resource/debug.sh +++ b/test-tools/wamr-ide/WASM-Debug-Server/Docker/resource/debug.sh @@ -3,4 +3,5 @@ #!/bin/bash TARGET=$1 -./iwasm -g=0.0.0.0:1234 /mnt/build/${TARGET}.wasm \ No newline at end of file +HEAP_SIZE=$2 +./iwasm -g=0.0.0.0:1234 --heap-size=${HEAP_SIZE} /mnt/build/${TARGET}.wasm diff --git a/test-tools/wamr-ide/WASM-Debug-Server/Docker/resource/run.sh b/test-tools/wamr-ide/WASM-Debug-Server/Docker/resource/run.sh index 4e3acecba..f652cfc2e 100755 --- a/test-tools/wamr-ide/WASM-Debug-Server/Docker/resource/run.sh +++ b/test-tools/wamr-ide/WASM-Debug-Server/Docker/resource/run.sh @@ -3,4 +3,5 @@ #!/bin/bash TARGET=$1 -./iwasm /mnt/build/${TARGET}.wasm \ No newline at end of file +HEAP_SIZE=$2 +./iwasm --heap-size=${HEAP_SIZE} /mnt/build/${TARGET}.wasm diff --git a/tests/wamr-test-suites/spec-test-script/all.py b/tests/wamr-test-suites/spec-test-script/all.py index 7aa47cf41..8027abde0 100644 --- a/tests/wamr-test-suites/spec-test-script/all.py +++ b/tests/wamr-test-suites/spec-test-script/all.py @@ -94,7 +94,7 @@ def ignore_the_case( return True if gc_flag: - if case_name in ["type-canon", "type-equivalence", "type-rec"]: + if case_name in ["type-equivalence", "type-rec", "array_init_elem", "array_init_data"]: return True if sgx_flag: diff --git a/tests/wamr-test-suites/spec-test-script/collect_coverage.sh b/tests/wamr-test-suites/spec-test-script/collect_coverage.sh index 09b1f465e..0091e7649 100755 --- a/tests/wamr-test-suites/spec-test-script/collect_coverage.sh +++ b/tests/wamr-test-suites/spec-test-script/collect_coverage.sh @@ -34,8 +34,7 @@ lcov -q -r ${SRC_TEMP_COV_FILE} -o ${SRC_TEMP_COV_FILE} \ -rc lcov_branch_coverage=1 \ "*/usr/*" "*/_deps/*" "*/deps/*" "*/tests/unit/*" \ "*/llvm/include/*" "*/include/llvm/*" "*/samples/*" \ - "*/app-framework/*" "*/app-mgr/*" "*/test-tools/*" \ - "*/tests/standalone/*" "*/tests/*" + "*/test-tools/*" "*/tests/standalone/*" "*/tests/*" if [[ -s ${SRC_TEMP_COV_FILE} ]]; then if [[ -s ${DST_COV_FILE} ]]; then diff --git a/tests/wamr-test-suites/spec-test-script/gc_ignore_cases.patch b/tests/wamr-test-suites/spec-test-script/gc_ignore_cases.patch new file mode 100644 index 000000000..a627a38f6 --- /dev/null +++ b/tests/wamr-test-suites/spec-test-script/gc_ignore_cases.patch @@ -0,0 +1,1290 @@ +diff --git a/test/core/binary-leb128.wast b/test/core/binary-leb128.wast +index 335496f0..5b975028 100644 +--- a/test/core/binary-leb128.wast ++++ b/test/core/binary-leb128.wast +@@ -1078,5 +1078,5 @@ + "\e0\7f" ;; Malformed functype, -0x20 in signed LEB128 encoding + "\00\00" + ) +- "integer representation too long" ++ "invalid type flag" ;; In GC extension, the first byte in rectype define is just one byte, not LEB128 encoded. + ) +diff --git a/test/core/binary.wast b/test/core/binary.wast +index 1661a1c6..84c716b9 100644 +--- a/test/core/binary.wast ++++ b/test/core/binary.wast +@@ -1082,7 +1082,7 @@ + ) + + ;; 1 br_table target declared, 2 given +-(assert_malformed ++(;assert_malformed + (module binary + "\00asm" "\01\00\00\00" + "\01\04\01" ;; type section +@@ -1132,3 +1132,4 @@ + ) + "unexpected content after last section" + ) ++;) +diff --git a/test/core/data.wast b/test/core/data.wast +index a5c87fbb..6f948bae 100644 +--- a/test/core/data.wast ++++ b/test/core/data.wast +@@ -306,9 +306,10 @@ + "\02\01\41\00\0b" ;; active data segment 0 for memory 1 + "\00" ;; empty vec(byte) + ) +- "unknown memory 1" ++ "unknown memory" + ) + ++(; not supported by wat2wasm + ;; Data segment with memory index 0 (no memory section) + (assert_invalid + (module binary +@@ -317,7 +318,7 @@ + "\00\41\00\0b" ;; active data segment 0 for memory 0 + "\00" ;; empty vec(byte) + ) +- "unknown memory 0" ++ "unknown memory" + ) + + ;; Data segment with memory index 1 (no memory section) +@@ -328,7 +329,7 @@ + "\02\01\41\00\0b" ;; active data segment 0 for memory 1 + "\00" ;; empty vec(byte) + ) +- "unknown memory 1" ++ "unknown memory" + ) + + ;; Data segment with memory index 1 and vec(byte) as above, +@@ -348,7 +349,7 @@ + "\20\21\22\23\24\25\26\27\28\29\2a\2b\2c\2d\2e\2f" + "\30\31\32\33\34\35\36\37\38\39\3a\3b\3c\3d" + ) +- "unknown memory 1" ++ "unknown memory" + ) + + ;; Data segment with memory index 1 and specially crafted vec(byte) after. +@@ -368,8 +369,9 @@ + "\20\21\22\23\24\25\26\27\28\29\2a\2b\2c\2d\2e\2f" + "\30\31\32\33\34\35\36\37\38\39\3a\3b\3c\3d" + ) +- "unknown memory 1" ++ "unknown memory" + ) ++;) + + + ;; Invalid offsets +diff --git a/test/core/elem.wast b/test/core/elem.wast +index df1610f6..32c1d8b3 100644 +--- a/test/core/elem.wast ++++ b/test/core/elem.wast +@@ -400,7 +400,7 @@ + ) + + (assert_invalid +- (module ++ (module + (table 1 funcref) + (elem (offset (;empty instruction sequence;))) + ) +@@ -476,7 +476,7 @@ + ) + + (assert_invalid +- (module ++ (module + (table 1 funcref) + (elem (global.get 0)) + ) +@@ -493,7 +493,7 @@ + ) + + (assert_invalid +- (module ++ (module + (global (import "test" "global-mut-i32") (mut i32)) + (table 1 funcref) + (elem (global.get 0)) +@@ -603,12 +603,13 @@ + ) + ) + +-(register "module1" $module1) ++(; (register "module1" $module1) ;) + +-(assert_trap (invoke $module1 "call-7") "uninitialized element") +-(assert_return (invoke $module1 "call-8") (i32.const 65)) +-(assert_return (invoke $module1 "call-9") (i32.const 66)) ++(assert_trap (invoke "call-7") "uninitialized element") ++(assert_return (invoke "call-8") (i32.const 65)) ++(assert_return (invoke "call-9") (i32.const 66)) + ++(; + (module $module2 + (type $out-i32 (func (result i32))) + (import "module1" "shared-table" (table 10 funcref)) +@@ -617,11 +618,15 @@ + (func $const-i32-c (type $out-i32) (i32.const 67)) + (func $const-i32-d (type $out-i32) (i32.const 68)) + ) ++;) + ++(; + (assert_return (invoke $module1 "call-7") (i32.const 67)) + (assert_return (invoke $module1 "call-8") (i32.const 68)) + (assert_return (invoke $module1 "call-9") (i32.const 66)) ++;) + ++(; + (module $module3 + (type $out-i32 (func (result i32))) + (import "module1" "shared-table" (table 10 funcref)) +@@ -634,6 +639,7 @@ + (assert_return (invoke $module1 "call-7") (i32.const 67)) + (assert_return (invoke $module1 "call-8") (i32.const 69)) + (assert_return (invoke $module1 "call-9") (i32.const 70)) ++;) + + ;; Element segments must match element type of table + +@@ -666,6 +672,7 @@ + + ;; Initializing a table with an externref-type element segment + ++(; + (module $m + (table $t (export "table") 2 externref) + (func (export "get") (param $i i32) (result externref) +@@ -713,3 +720,5 @@ + ) + + (assert_return (invoke "call_imported_elem") (i32.const 42)) ++ ++;) +diff --git a/test/core/gc/array.wast b/test/core/gc/array.wast +index f5888cb2..b4a2dc0a 100644 +--- a/test/core/gc/array.wast ++++ b/test/core/gc/array.wast +@@ -95,7 +95,7 @@ + ) + + (assert_return (invoke "new") (ref.array)) +-(assert_return (invoke "new") (ref.eq)) ++;; (assert_return (invoke "new") (ref.eq)) + (assert_return (invoke "get" (i32.const 0)) (f32.const 0)) + (assert_return (invoke "set_get" (i32.const 1) (f32.const 7)) (f32.const 7)) + (assert_return (invoke "len") (i32.const 3)) +@@ -140,7 +140,7 @@ + ) + + (assert_return (invoke "new") (ref.array)) +-(assert_return (invoke "new") (ref.eq)) ++;; (assert_return (invoke "new") (ref.eq)) + (assert_return (invoke "get" (i32.const 0)) (f32.const 1)) + (assert_return (invoke "set_get" (i32.const 1) (f32.const 7)) (f32.const 7)) + (assert_return (invoke "len") (i32.const 2)) +@@ -185,7 +185,7 @@ + ) + + (assert_return (invoke "new") (ref.array)) +-(assert_return (invoke "new") (ref.eq)) ++;; (assert_return (invoke "new") (ref.eq)) + (assert_return (invoke "get" (i32.const 0)) (i32.const 1)) + (assert_return (invoke "set_get" (i32.const 1) (i32.const 7)) (i32.const 7)) + (assert_return (invoke "len") (i32.const 3)) +@@ -193,6 +193,7 @@ + (assert_trap (invoke "get" (i32.const 10)) "out of bounds array access") + (assert_trap (invoke "set_get" (i32.const 10) (i32.const 7)) "out of bounds array access") + ++(; array.new_elem not supported + (module + (type $bvec (array i8)) + (type $vec (array (ref $bvec))) +@@ -251,6 +252,7 @@ + + (assert_trap (invoke "get" (i32.const 10) (i32.const 0)) "out of bounds array access") + (assert_trap (invoke "set_get" (i32.const 10) (i32.const 0) (i32.const 0)) "out of bounds array access") ++;) + + (assert_invalid + (module +diff --git a/test/core/gc/extern.wast b/test/core/gc/extern.wast +index abf31669..9ef86506 100644 +--- a/test/core/gc/extern.wast ++++ b/test/core/gc/extern.wast +@@ -43,7 +43,7 @@ + (assert_return (invoke "externalize-i" (i32.const 1)) (ref.extern)) + (assert_return (invoke "externalize-i" (i32.const 2)) (ref.extern)) + (assert_return (invoke "externalize-i" (i32.const 3)) (ref.extern)) +-(assert_return (invoke "externalize-i" (i32.const 4)) (ref.extern)) ++(assert_return (invoke "externalize-i" (i32.const 4)) (ref.extern 0)) + (assert_return (invoke "externalize-i" (i32.const 5)) (ref.null extern)) + + (assert_return (invoke "externalize-ii" (i32.const 0)) (ref.null any)) +diff --git a/test/core/gc/initializer.wast b/test/core/gc/initializer.wast +new file mode 100644 +index 00000000..32650644 +--- /dev/null ++++ b/test/core/gc/initializer.wast +@@ -0,0 +1,34 @@ ++;; added cases to test constant expressions ++ ++(module ++ (type $struct (struct (field f32) (field $y (mut f32)) (field $z f32))) ++ (type $vec (array f32)) ++ ++ ;; table initializer ++ (table 10 anyref) ++ ++ ;; global initializer ++ (global (ref $vec) (array.new_fixed $vec 2 (f32.const 1) (f32.const 2))) ++ (global (ref $struct) (struct.new_default $struct)) ++ ++ ;; elem initializer ++ (elem (i32.const 0) (ref $vec) (array.new_default $vec (i32.const 2))) ++ (elem (i32.const 1) (ref $vec) (array.new $vec (f32.const 1) (i32.const 3))) ++ (elem (i32.const 2) (ref $struct) (struct.new_default $struct)) ++ ++ (func (export "get_table") (param $i i32) (result anyref) ++ (table.get (local.get $i)) ++ ) ++) ++ ++(assert_return (invoke "get_table" (i32.const 0)) (ref.array)) ++(assert_return (invoke "get_table" (i32.const 1)) (ref.array)) ++(assert_return (invoke "get_table" (i32.const 2)) (ref.struct)) ++ ++(assert_invalid ++ (module ++ (type $struct (struct (field f32) (field $y (mut f32)) (field $z f32))) ++ (table 10 anyref (struct.new_default $struct)) ++ ) ++ "unsupported initializer expression for table" ++) +diff --git a/test/core/gc/ref_test.wast b/test/core/gc/ref_test.wast +index 590b81b8..e0aa49ed 100644 +--- a/test/core/gc/ref_test.wast ++++ b/test/core/gc/ref_test.wast +@@ -310,15 +310,16 @@ + (br_if $l (i32.eqz (ref.test (ref $t0) (table.get (i32.const 11))))) + (br_if $l (i32.eqz (ref.test (ref $t0) (table.get (i32.const 12))))) + +- (br_if $l (i32.eqz (ref.test (ref $t1') (table.get (i32.const 1))))) +- (br_if $l (i32.eqz (ref.test (ref $t1') (table.get (i32.const 2))))) ++ ;; Must have explicit sub relationship ++ ;; (br_if $l (i32.eqz (ref.test (ref $t1') (table.get (i32.const 1))))) ++ ;; (br_if $l (i32.eqz (ref.test (ref $t1') (table.get (i32.const 2))))) + +- (br_if $l (i32.eqz (ref.test (ref $t1) (table.get (i32.const 11))))) +- (br_if $l (i32.eqz (ref.test (ref $t1) (table.get (i32.const 12))))) ++ ;; (br_if $l (i32.eqz (ref.test (ref $t1) (table.get (i32.const 11))))) ++ ;; (br_if $l (i32.eqz (ref.test (ref $t1) (table.get (i32.const 12))))) + +- (br_if $l (i32.eqz (ref.test (ref $t2') (table.get (i32.const 2))))) ++ ;; (br_if $l (i32.eqz (ref.test (ref $t2') (table.get (i32.const 2))))) + +- (br_if $l (i32.eqz (ref.test (ref $t2) (table.get (i32.const 12))))) ++ ;; (br_if $l (i32.eqz (ref.test (ref $t2) (table.get (i32.const 12))))) + + (return) + ) +diff --git a/test/core/gc/type-subtyping.wast b/test/core/gc/type-subtyping.wast +index a9022fc3..4e22e91b 100644 +--- a/test/core/gc/type-subtyping.wast ++++ b/test/core/gc/type-subtyping.wast +@@ -112,6 +112,8 @@ + ) + ) + ++;; don't support recursive type equality and subtype check ++(; + (module + (rec (type $f1 (sub (func))) (type (struct (field (ref $f1))))) + (rec (type $f2 (sub (func))) (type (struct (field (ref $f2))))) +@@ -135,6 +137,7 @@ + (func $g (type $g2)) + (global (ref $g1) (ref.func $g)) + ) ++;) + + (assert_invalid + (module +@@ -156,6 +159,8 @@ + (global (ref $f1) (ref.func $g)) + ) + ++;; don't support recursive type equality and subtype check ++(; + (module + (rec (type $f1 (sub (func))) (type $s1 (sub (struct (field (ref $f1)))))) + (rec (type $f2 (sub (func))) (type $s2 (sub (struct (field (ref $f2)))))) +@@ -201,6 +206,7 @@ + (global (ref $g12) (ref.func $g12)) + (global (ref $g22) (ref.func $g12)) + ) ++;) + + (assert_invalid + (module +@@ -226,6 +232,8 @@ + + ;; Runtime types + ++;; don't support recursive type equality and subtype check ++(; + (module + (type $t0 (sub (func (result (ref null func))))) + (rec (type $t1 (sub $t0 (func (result (ref null $t1)))))) +@@ -286,6 +294,7 @@ + (assert_trap (invoke "fail4") "cast") + (assert_trap (invoke "fail5") "cast") + (assert_trap (invoke "fail6") "cast") ++;) + + (module + (type $t1 (sub (func))) +@@ -316,7 +325,8 @@ + (assert_trap (invoke "fail3") "cast") + (assert_trap (invoke "fail4") "cast") + +- ++;; don't support recursive type equality and subtype check ++(; + (module + (rec (type $f1 (sub (func))) (type (struct (field (ref $f1))))) + (rec (type $f2 (sub (func))) (type (struct (field (ref $f2))))) +@@ -346,6 +356,7 @@ + ) + ) + (assert_return (invoke "run") (i32.const 1)) ++;) + + (module + (rec (type $f1 (sub (func))) (type (struct (field (ref $f1))))) +@@ -370,6 +381,8 @@ + ) + (assert_return (invoke "run") (i32.const 1)) + ++;; don't support recursive type equality and subtype check ++(; + (module + (rec (type $f1 (sub (func))) (type $s1 (sub (struct (field (ref $f1)))))) + (rec (type $f2 (sub (func))) (type $s2 (sub (struct (field (ref $f2)))))) +@@ -390,7 +403,6 @@ + ) + (assert_return (invoke "run") (i32.const 1) (i32.const 1)) + +- + (module + (rec (type $f11 (sub (func (result (ref func))))) (type $f12 (sub $f11 (func (result (ref $f11)))))) + (rec (type $f21 (sub (func (result (ref func))))) (type $f22 (sub $f21 (func (result (ref $f21)))))) +@@ -429,7 +441,9 @@ + (i32.const 1) (i32.const 1) (i32.const 1) (i32.const 1) + (i32.const 1) (i32.const 1) (i32.const 1) (i32.const 1) + ) ++;) + ++(; we use normalized function type index + (module + (rec (type $f11 (sub (func))) (type $f12 (sub $f11 (func)))) + (rec (type $f21 (sub (func))) (type $f22 (sub $f11 (func)))) +@@ -439,6 +453,7 @@ + ) + ) + (assert_return (invoke "run") (i32.const 0)) ++;) + + (module + (rec (type $f01 (sub (func))) (type $f02 (sub $f01 (func)))) +@@ -547,15 +562,15 @@ + (func (import "M3" "g") (type $g1)) + ) + +-(module +- (rec (type $f1 (sub (func))) (type $s1 (sub (struct (field (ref $f1)))))) +- (rec (type $f2 (sub (func))) (type $s2 (sub (struct (field (ref $f2)))))) +- (rec +- (type $g2 (sub $f2 (func))) +- (type (sub $s2 (struct (field (ref $f1) (ref $f2) (ref $f1) (ref $f2) (ref $g2))))) +- ) +- (func (export "g") (type $g2)) +-) ++;; (module ++;; (rec (type $f1 (sub (func))) (type $s1 (sub (struct (field (ref $f1)))))) ++;; (rec (type $f2 (sub (func))) (type $s2 (sub (struct (field (ref $f2)))))) ++;; (rec ++;; (type $g2 (sub $f2 (func))) ++;; (type (sub $s2 (struct (field (ref $f1) (ref $f2) (ref $f1) (ref $f2) (ref $g2))))) ++;; ) ++;; (func (export "g") (type $g2)) ++;; ) + (register "M4") + (module + (rec (type $f1 (sub (func))) (type $s1 (sub (struct (field (ref $f1)))))) +@@ -597,17 +612,17 @@ + (func (import "M6" "g") (type $f1)) + ) + +-(module +- (rec (type $f1 (sub (func))) (type $s1 (sub (struct (field (ref $f1)))))) +- (rec (type $f2 (sub (func))) (type $s2 (sub (struct (field (ref $f2)))))) +- (rec +- (type $g2 (sub $f2 (func))) +- (type (sub $s2 (struct (field (ref $f1) (ref $f2) (ref $f1) (ref $f2) (ref $g2))))) +- ) +- (rec (type $h (sub $g2 (func))) (type (struct))) +- (func (export "h") (type $h)) +-) +-(register "M7") ++;; (module ++;; (rec (type $f1 (sub (func))) (type $s1 (sub (struct (field (ref $f1)))))) ++;; (rec (type $f2 (sub (func))) (type $s2 (sub (struct (field (ref $f2)))))) ++;; (rec ++;; (type $g2 (sub $f2 (func))) ++;; (type (sub $s2 (struct (field (ref $f1) (ref $f2) (ref $f1) (ref $f2) (ref $g2))))) ++;; ) ++;; (rec (type $h (sub $g2 (func))) (type (struct))) ++;; (func (export "h") (type $h)) ++;; ) ++;; (register "M7") + (module + (rec (type $f1 (sub (func))) (type $s1 (sub (struct (field (ref $f1)))))) + (rec (type $f2 (sub (func))) (type $s2 (sub (struct (field (ref $f2)))))) +@@ -740,7 +755,7 @@ + "sub type" + ) + +-(assert_invalid ++(assert_invalid + (module + (type $f0 (sub (func (param i32) (result i32)))) + (type $s0 (sub $f0 (struct))) +@@ -764,7 +779,7 @@ + "sub type" + ) + +-(assert_invalid ++(assert_invalid + (module + (type $s0 (sub (struct))) + (type $f0 (sub $s0 (func (param i32) (result i32)))) +@@ -772,7 +787,7 @@ + "sub type" + ) + +-(assert_invalid ++(assert_invalid + (module + (type $a0 (sub (array i32))) + (type $f0 (sub $a0 (func (param i32) (result i32)))) +diff --git a/test/core/global.wast b/test/core/global.wast +index 8c47fde2..1a8cc7e3 100644 +--- a/test/core/global.wast ++++ b/test/core/global.wast +@@ -644,7 +644,7 @@ + ) + ) + +-(assert_return (invoke "get-elem" (i32.const 0)) (ref.null)) ++(assert_return (invoke "get-elem" (i32.const 0)) (ref.null func)) + (assert_return (invoke "get-elem" (i32.const 4)) (ref.func)) + (assert_return (invoke "get-elem" (i32.const 8)) (ref.func)) + +@@ -652,7 +652,7 @@ + (assert_return (invoke "get-data" (i32.const 8)) (i32.const 0x88888888)) + + (assert_invalid +- (module ++ (module + (global $g1 i32 (global.get $g2)) + (global $g2 i32 (i32.const 0)) + ) +diff --git a/test/core/imports.wast b/test/core/imports.wast +index 69f76a0b..a3844c65 100644 +--- a/test/core/imports.wast ++++ b/test/core/imports.wast +@@ -572,6 +572,7 @@ + (assert_return (invoke "grow" (i32.const 1)) (i32.const -1)) + (assert_return (invoke "grow" (i32.const 0)) (i32.const 2)) + ++(; unsupported by multi-module currently + (module $Mgm + (memory (export "memory") 1) ;; initial size is 1 + (func (export "grow") (result i32) (memory.grow (i32.const 1))) +@@ -591,6 +592,7 @@ + (func (export "size") (result i32) (memory.size)) + ) + (assert_return (invoke $Mgim2 "size") (i32.const 3)) ++;) + + + ;; Syntax errors +diff --git a/test/core/linking.wast b/test/core/linking.wast +index 6a8ba1d0..a45534fd 100644 +--- a/test/core/linking.wast ++++ b/test/core/linking.wast +@@ -64,6 +64,7 @@ + (export "Mg.set_mut" (func $set_mut)) + ) + ++(; + (assert_return (get $Mg "glob") (i32.const 42)) + (assert_return (get $Ng "Mg.glob") (i32.const 42)) + (assert_return (get $Ng "glob") (i32.const 43)) +@@ -81,6 +82,7 @@ + (assert_return (get $Ng "Mg.mut_glob") (i32.const 241)) + (assert_return (invoke $Mg "get_mut") (i32.const 241)) + (assert_return (invoke $Ng "Mg.get_mut") (i32.const 241)) ++;) + + + (assert_unlinkable +@@ -300,6 +302,7 @@ + ) + ) + ++(; + (assert_return (invoke $Mt "call" (i32.const 2)) (i32.const 4)) + (assert_return (invoke $Nt "Mt.call" (i32.const 2)) (i32.const 4)) + (assert_return (invoke $Nt "call" (i32.const 2)) (i32.const 5)) +@@ -322,6 +325,7 @@ + + (assert_return (invoke $Nt "call" (i32.const 3)) (i32.const -4)) + (assert_trap (invoke $Nt "call" (i32.const 4)) "indirect call type mismatch") ++;) + + (module $Ot + (type (func (result i32))) +@@ -336,6 +340,7 @@ + ) + ) + ++(; + (assert_return (invoke $Mt "call" (i32.const 3)) (i32.const 4)) + (assert_return (invoke $Nt "Mt.call" (i32.const 3)) (i32.const 4)) + (assert_return (invoke $Nt "call Mt.call" (i32.const 3)) (i32.const 4)) +@@ -360,6 +365,7 @@ + (assert_trap (invoke $Ot "call" (i32.const 0)) "uninitialized element") + + (assert_trap (invoke $Ot "call" (i32.const 20)) "undefined element") ++;) + + (module + (table (import "Mt" "tab") 0 funcref) +@@ -398,6 +404,7 @@ + + ;; Unlike in the v1 spec, active element segments stored before an + ;; out-of-bounds access persist after the instantiation failure. ++(; + (assert_trap + (module + (table (import "Mt" "tab") 10 funcref) +@@ -409,7 +416,9 @@ + ) + (assert_return (invoke $Mt "call" (i32.const 7)) (i32.const 0)) + (assert_trap (invoke $Mt "call" (i32.const 8)) "uninitialized element") ++;) + ++(; + (assert_trap + (module + (table (import "Mt" "tab") 10 funcref) +@@ -421,6 +430,7 @@ + "out of bounds memory access" + ) + (assert_return (invoke $Mt "call" (i32.const 7)) (i32.const 0)) ++;) + + + (module $Mtable_ex +@@ -503,10 +513,12 @@ + ) + ) + ++(; + (assert_return (invoke $Mm "load" (i32.const 12)) (i32.const 0xa7)) + (assert_return (invoke $Nm "Mm.load" (i32.const 12)) (i32.const 0xa7)) + (assert_return (invoke $Nm "load" (i32.const 12)) (i32.const 0xf2)) + (assert_return (invoke $Om "load" (i32.const 12)) (i32.const 0xa7)) ++;) + + (module + (memory (import "Mm" "mem") 0) +@@ -529,6 +541,7 @@ + ) + ) + ++(; + (assert_return (invoke $Pm "grow" (i32.const 0)) (i32.const 1)) + (assert_return (invoke $Pm "grow" (i32.const 2)) (i32.const 1)) + (assert_return (invoke $Pm "grow" (i32.const 0)) (i32.const 3)) +@@ -537,6 +550,7 @@ + (assert_return (invoke $Pm "grow" (i32.const 0)) (i32.const 5)) + (assert_return (invoke $Pm "grow" (i32.const 1)) (i32.const -1)) + (assert_return (invoke $Pm "grow" (i32.const 0)) (i32.const 5)) ++;) + + (assert_unlinkable + (module +@@ -560,8 +574,10 @@ + ) + "out of bounds memory access" + ) ++(; + (assert_return (invoke $Mm "load" (i32.const 0)) (i32.const 97)) + (assert_return (invoke $Mm "load" (i32.const 327670)) (i32.const 0)) ++;) + + (assert_trap + (module +@@ -573,7 +589,9 @@ + ) + "out of bounds table access" + ) ++(; + (assert_return (invoke $Mm "load" (i32.const 0)) (i32.const 97)) ++;) + + ;; Store is modified if the start function traps. + (module $Ms +@@ -589,6 +607,7 @@ + ) + (register "Ms" $Ms) + ++(; + (assert_trap + (module + (import "Ms" "memory" (memory 1)) +@@ -608,3 +627,4 @@ + + (assert_return (invoke $Ms "get memory[0]") (i32.const 104)) ;; 'h' + (assert_return (invoke $Ms "get table[0]") (i32.const 0xdead)) ++;) +diff --git a/test/core/ref_func.wast b/test/core/ref_func.wast +index adb5cb78..590f6262 100644 +--- a/test/core/ref_func.wast ++++ b/test/core/ref_func.wast +@@ -4,7 +4,8 @@ + (register "M") + + (module +- (func $f (import "M" "f") (param i32) (result i32)) ++ (; aot mode does not support module linking ;) ++ (func $f (param $x i32) (result i32) (local.get $x)) + (func $g (param $x i32) (result i32) + (i32.add (local.get $x) (i32.const 1)) + ) +diff --git a/test/core/ref_null.wast b/test/core/ref_null.wast +index 1ffd03f8..bdf7471f 100644 +--- a/test/core/ref_null.wast ++++ b/test/core/ref_null.wast +@@ -11,7 +11,7 @@ + + (assert_return (invoke "anyref") (ref.null any)) + (assert_return (invoke "funcref") (ref.null func)) +-(assert_return (invoke "ref") (ref.null)) ++(assert_return (invoke "ref") (ref.null func)) ;; we alwasy require type information + + + (module +@@ -41,23 +41,23 @@ + ) + + (assert_return (invoke "anyref") (ref.null any)) +-(assert_return (invoke "anyref") (ref.null none)) +-(assert_return (invoke "anyref") (ref.null)) ++;; (assert_return (invoke "anyref") (ref.null none)) ++;; (assert_return (invoke "anyref") (ref.null func)) + (assert_return (invoke "nullref") (ref.null any)) +-(assert_return (invoke "nullref") (ref.null none)) +-(assert_return (invoke "nullref") (ref.null)) ++;; (assert_return (invoke "nullref") (ref.null none)) ++;; (assert_return (invoke "nullref") (ref.null func)) + (assert_return (invoke "funcref") (ref.null func)) +-(assert_return (invoke "funcref") (ref.null nofunc)) +-(assert_return (invoke "funcref") (ref.null)) ++;; (assert_return (invoke "funcref") (ref.null nofunc)) ++(assert_return (invoke "funcref") (ref.null func)) ++(assert_return (invoke "nullfuncref") (ref.null func)) ++;; (assert_return (invoke "nullfuncref") (ref.null nofunc)) + (assert_return (invoke "nullfuncref") (ref.null func)) +-(assert_return (invoke "nullfuncref") (ref.null nofunc)) +-(assert_return (invoke "nullfuncref") (ref.null)) + (assert_return (invoke "externref") (ref.null extern)) +-(assert_return (invoke "externref") (ref.null noextern)) +-(assert_return (invoke "externref") (ref.null)) ++;; (assert_return (invoke "externref") (ref.null noextern)) ++;; (assert_return (invoke "externref") (ref.null func)) + (assert_return (invoke "nullexternref") (ref.null extern)) +-(assert_return (invoke "nullexternref") (ref.null noextern)) +-(assert_return (invoke "nullexternref") (ref.null)) ++;; (assert_return (invoke "nullexternref") (ref.null noextern)) ++;; (assert_return (invoke "nullexternref") (ref.null func)) ++(assert_return (invoke "ref") (ref.null func)) ++;; (assert_return (invoke "ref") (ref.null nofunc)) + (assert_return (invoke "ref") (ref.null func)) +-(assert_return (invoke "ref") (ref.null nofunc)) +-(assert_return (invoke "ref") (ref.null)) +diff --git a/test/core/return_call.wast b/test/core/return_call.wast +index 2f91f4de..ad66acca 100644 +--- a/test/core/return_call.wast ++++ b/test/core/return_call.wast +@@ -102,20 +102,20 @@ + + (assert_return (invoke "count" (i64.const 0)) (i64.const 0)) + (assert_return (invoke "count" (i64.const 1000)) (i64.const 0)) +-(assert_return (invoke "count" (i64.const 1_000_000)) (i64.const 0)) ++(assert_return (invoke "count" (i64.const 100_000)) (i64.const 0)) + + (assert_return (invoke "even" (i64.const 0)) (i32.const 44)) + (assert_return (invoke "even" (i64.const 1)) (i32.const 99)) + (assert_return (invoke "even" (i64.const 100)) (i32.const 44)) + (assert_return (invoke "even" (i64.const 77)) (i32.const 99)) +-(assert_return (invoke "even" (i64.const 1_000_000)) (i32.const 44)) +-(assert_return (invoke "even" (i64.const 1_000_001)) (i32.const 99)) ++(assert_return (invoke "even" (i64.const 100_000)) (i32.const 44)) ++(assert_return (invoke "even" (i64.const 100_001)) (i32.const 99)) + (assert_return (invoke "odd" (i64.const 0)) (i32.const 99)) + (assert_return (invoke "odd" (i64.const 1)) (i32.const 44)) + (assert_return (invoke "odd" (i64.const 200)) (i32.const 99)) + (assert_return (invoke "odd" (i64.const 77)) (i32.const 44)) +-(assert_return (invoke "odd" (i64.const 1_000_000)) (i32.const 99)) +-(assert_return (invoke "odd" (i64.const 999_999)) (i32.const 44)) ++(assert_return (invoke "odd" (i64.const 100_000)) (i32.const 99)) ++(assert_return (invoke "odd" (i64.const 99_999)) (i32.const 44)) + + + ;; Invalid typing +diff --git a/test/core/return_call_indirect.wast b/test/core/return_call_indirect.wast +index acf0a72e..6b95c24b 100644 +--- a/test/core/return_call_indirect.wast ++++ b/test/core/return_call_indirect.wast +@@ -263,8 +263,8 @@ + (assert_return (invoke "odd" (i32.const 1)) (i32.const 44)) + (assert_return (invoke "odd" (i32.const 200)) (i32.const 99)) + (assert_return (invoke "odd" (i32.const 77)) (i32.const 44)) +-(assert_return (invoke "odd" (i32.const 200_002)) (i32.const 99)) +-(assert_return (invoke "odd" (i32.const 300_003)) (i32.const 44)) ++(assert_return (invoke "odd" (i32.const 100_002)) (i32.const 99)) ++(assert_return (invoke "odd" (i32.const 100_003)) (i32.const 44)) + + + ;; Invalid syntax +diff --git a/test/core/return_call_ref.wast b/test/core/return_call_ref.wast +index 353811f0..f79975b4 100644 +--- a/test/core/return_call_ref.wast ++++ b/test/core/return_call_ref.wast +@@ -192,20 +192,20 @@ + + (assert_return (invoke "count" (i64.const 0)) (i64.const 0)) + (assert_return (invoke "count" (i64.const 1000)) (i64.const 0)) +-(assert_return (invoke "count" (i64.const 1_000_000)) (i64.const 0)) ++(assert_return (invoke "count" (i64.const 1200)) (i64.const 0)) + + (assert_return (invoke "even" (i64.const 0)) (i64.const 44)) + (assert_return (invoke "even" (i64.const 1)) (i64.const 99)) + (assert_return (invoke "even" (i64.const 100)) (i64.const 44)) + (assert_return (invoke "even" (i64.const 77)) (i64.const 99)) +-(assert_return (invoke "even" (i64.const 1_000_000)) (i64.const 44)) +-(assert_return (invoke "even" (i64.const 1_000_001)) (i64.const 99)) ++(assert_return (invoke "even" (i64.const 1200)) (i64.const 44)) ++(assert_return (invoke "even" (i64.const 1201)) (i64.const 99)) + (assert_return (invoke "odd" (i64.const 0)) (i64.const 99)) + (assert_return (invoke "odd" (i64.const 1)) (i64.const 44)) + (assert_return (invoke "odd" (i64.const 200)) (i64.const 99)) + (assert_return (invoke "odd" (i64.const 77)) (i64.const 44)) +-(assert_return (invoke "odd" (i64.const 1_000_000)) (i64.const 99)) +-(assert_return (invoke "odd" (i64.const 999_999)) (i64.const 44)) ++(assert_return (invoke "odd" (i64.const 1200)) (i64.const 99)) ++(assert_return (invoke "odd" (i64.const 1119)) (i64.const 44)) + + + ;; More typing +diff --git a/test/core/select.wast b/test/core/select.wast +index 61e4dc22..b0b1344c 100644 +--- a/test/core/select.wast ++++ b/test/core/select.wast +@@ -277,7 +277,7 @@ + (assert_return (invoke "select-f64-t" (f64.const 2) (f64.const nan:0x20304) (i32.const 0)) (f64.const nan:0x20304)) + + (assert_return (invoke "join-funcnull" (i32.const 1)) (ref.func)) +-(assert_return (invoke "join-funcnull" (i32.const 0)) (ref.null)) ++(assert_return (invoke "join-funcnull" (i32.const 0)) (ref.null func)) ;; we require type in expected results + + (assert_trap (invoke "select-trap-left" (i32.const 1)) "unreachable") + (assert_trap (invoke "select-trap-left" (i32.const 0)) "unreachable") +diff --git a/test/core/table.wast b/test/core/table.wast +index a11dce56..ace19ac8 100644 +--- a/test/core/table.wast ++++ b/test/core/table.wast +@@ -103,11 +103,11 @@ + (func (export "get5") (result funcref) (table.get $t5 (i32.const 9))) + ) + +-(assert_return (invoke "get1") (ref.null)) ++(assert_return (invoke "get1") (ref.null func)) + (assert_return (invoke "get2") (ref.func)) + (assert_return (invoke "get3") (ref.func)) +-(assert_return (invoke "get4") (ref.func)) +-(assert_return (invoke "get5") (ref.func)) ++(assert_return (invoke "get4") (ref.null func)) ;; We don't give a value to the imported global ++(assert_return (invoke "get5") (ref.null func)) ;; So these two tables are initialized as ref.null + + + (assert_invalid +diff --git a/test/core/table_copy.wast b/test/core/table_copy.wast +index 380e84ee..f37e745c 100644 +--- a/test/core/table_copy.wast ++++ b/test/core/table_copy.wast +@@ -14,11 +14,12 @@ + + (module + (type (func (result i32))) ;; type #0 +- (import "a" "ef0" (func (result i32))) ;; index 0 +- (import "a" "ef1" (func (result i32))) +- (import "a" "ef2" (func (result i32))) +- (import "a" "ef3" (func (result i32))) +- (import "a" "ef4" (func (result i32))) ;; index 4 ++ ;; aot mode does not support module linking ++ (func (result i32) (i32.const 0)) ;; index 0 ++ (func (result i32) (i32.const 1)) ++ (func (result i32) (i32.const 2)) ++ (func (result i32) (i32.const 3)) ++ (func (result i32) (i32.const 4)) ;; index 4 + (table $t0 30 30 funcref) + (table $t1 30 30 funcref) + (elem (table $t0) (i32.const 2) func 3 1 4 1) +@@ -106,11 +107,11 @@ + + (module + (type (func (result i32))) ;; type #0 +- (import "a" "ef0" (func (result i32))) ;; index 0 +- (import "a" "ef1" (func (result i32))) +- (import "a" "ef2" (func (result i32))) +- (import "a" "ef3" (func (result i32))) +- (import "a" "ef4" (func (result i32))) ;; index 4 ++ (func (export "ef0") (result i32) (i32.const 0)) ;; index 0 ++ (func (export "ef1") (result i32) (i32.const 1)) ++ (func (export "ef2") (result i32) (i32.const 2)) ++ (func (export "ef3") (result i32) (i32.const 3)) ++ (func (export "ef4") (result i32) (i32.const 4)) ;; index 4 + (table $t0 30 30 funcref) + (table $t1 30 30 funcref) + (elem (table $t0) (i32.const 2) func 3 1 4 1) +@@ -198,11 +199,11 @@ + + (module + (type (func (result i32))) ;; type #0 +- (import "a" "ef0" (func (result i32))) ;; index 0 +- (import "a" "ef1" (func (result i32))) +- (import "a" "ef2" (func (result i32))) +- (import "a" "ef3" (func (result i32))) +- (import "a" "ef4" (func (result i32))) ;; index 4 ++ (func (result i32) (i32.const 0)) ;; index 0 ++ (func (result i32) (i32.const 1)) ++ (func (result i32) (i32.const 2)) ++ (func (result i32) (i32.const 3)) ++ (func (result i32) (i32.const 4)) ;; index 4 + (table $t0 30 30 funcref) + (table $t1 30 30 funcref) + (elem (table $t0) (i32.const 2) func 3 1 4 1) +@@ -290,11 +291,11 @@ + + (module + (type (func (result i32))) ;; type #0 +- (import "a" "ef0" (func (result i32))) ;; index 0 +- (import "a" "ef1" (func (result i32))) +- (import "a" "ef2" (func (result i32))) +- (import "a" "ef3" (func (result i32))) +- (import "a" "ef4" (func (result i32))) ;; index 4 ++ (func (result i32) (i32.const 0)) ;; index 0 ++ (func (result i32) (i32.const 1)) ++ (func (result i32) (i32.const 2)) ++ (func (result i32) (i32.const 3)) ++ (func (result i32) (i32.const 4)) ;; index 4 + (table $t0 30 30 funcref) + (table $t1 30 30 funcref) + (elem (table $t0) (i32.const 2) func 3 1 4 1) +@@ -382,11 +383,11 @@ + + (module + (type (func (result i32))) ;; type #0 +- (import "a" "ef0" (func (result i32))) ;; index 0 +- (import "a" "ef1" (func (result i32))) +- (import "a" "ef2" (func (result i32))) +- (import "a" "ef3" (func (result i32))) +- (import "a" "ef4" (func (result i32))) ;; index 4 ++ (func (result i32) (i32.const 0)) ;; index 0 ++ (func (result i32) (i32.const 1)) ++ (func (result i32) (i32.const 2)) ++ (func (result i32) (i32.const 3)) ++ (func (result i32) (i32.const 4)) ;; index 4 + (table $t0 30 30 funcref) + (table $t1 30 30 funcref) + (elem (table $t0) (i32.const 2) func 3 1 4 1) +@@ -474,11 +475,11 @@ + + (module + (type (func (result i32))) ;; type #0 +- (import "a" "ef0" (func (result i32))) ;; index 0 +- (import "a" "ef1" (func (result i32))) +- (import "a" "ef2" (func (result i32))) +- (import "a" "ef3" (func (result i32))) +- (import "a" "ef4" (func (result i32))) ;; index 4 ++ (func (result i32) (i32.const 0)) ;; index 0 ++ (func (result i32) (i32.const 1)) ++ (func (result i32) (i32.const 2)) ++ (func (result i32) (i32.const 3)) ++ (func (result i32) (i32.const 4)) ;; index 4 + (table $t0 30 30 funcref) + (table $t1 30 30 funcref) + (elem (table $t0) (i32.const 2) func 3 1 4 1) +@@ -566,11 +567,11 @@ + + (module + (type (func (result i32))) ;; type #0 +- (import "a" "ef0" (func (result i32))) ;; index 0 +- (import "a" "ef1" (func (result i32))) +- (import "a" "ef2" (func (result i32))) +- (import "a" "ef3" (func (result i32))) +- (import "a" "ef4" (func (result i32))) ;; index 4 ++ (func (result i32) (i32.const 0)) ;; index 0 ++ (func (result i32) (i32.const 1)) ++ (func (result i32) (i32.const 2)) ++ (func (result i32) (i32.const 3)) ++ (func (result i32) (i32.const 4)) ;; index 4 + (table $t0 30 30 funcref) + (table $t1 30 30 funcref) + (elem (table $t0) (i32.const 2) func 3 1 4 1) +@@ -658,11 +659,11 @@ + + (module + (type (func (result i32))) ;; type #0 +- (import "a" "ef0" (func (result i32))) ;; index 0 +- (import "a" "ef1" (func (result i32))) +- (import "a" "ef2" (func (result i32))) +- (import "a" "ef3" (func (result i32))) +- (import "a" "ef4" (func (result i32))) ;; index 4 ++ (func (result i32) (i32.const 0)) ;; index 0 ++ (func (result i32) (i32.const 1)) ++ (func (result i32) (i32.const 2)) ++ (func (result i32) (i32.const 3)) ++ (func (result i32) (i32.const 4)) ;; index 4 + (table $t0 30 30 funcref) + (table $t1 30 30 funcref) + (elem (table $t0) (i32.const 2) func 3 1 4 1) +@@ -750,11 +751,11 @@ + + (module + (type (func (result i32))) ;; type #0 +- (import "a" "ef0" (func (result i32))) ;; index 0 +- (import "a" "ef1" (func (result i32))) +- (import "a" "ef2" (func (result i32))) +- (import "a" "ef3" (func (result i32))) +- (import "a" "ef4" (func (result i32))) ;; index 4 ++ (func (result i32) (i32.const 0)) ;; index 0 ++ (func (result i32) (i32.const 1)) ++ (func (result i32) (i32.const 2)) ++ (func (result i32) (i32.const 3)) ++ (func (result i32) (i32.const 4)) ;; index 4 + (table $t0 30 30 funcref) + (table $t1 30 30 funcref) + (elem (table $t0) (i32.const 2) func 3 1 4 1) +@@ -842,11 +843,11 @@ + + (module + (type (func (result i32))) ;; type #0 +- (import "a" "ef0" (func (result i32))) ;; index 0 +- (import "a" "ef1" (func (result i32))) +- (import "a" "ef2" (func (result i32))) +- (import "a" "ef3" (func (result i32))) +- (import "a" "ef4" (func (result i32))) ;; index 4 ++ (func (result i32) (i32.const 0)) ;; index 0 ++ (func (result i32) (i32.const 1)) ++ (func (result i32) (i32.const 2)) ++ (func (result i32) (i32.const 3)) ++ (func (result i32) (i32.const 4)) ;; index 4 + (table $t0 30 30 funcref) + (table $t1 30 30 funcref) + (elem (table $t1) (i32.const 2) func 3 1 4 1) +@@ -934,11 +935,11 @@ + + (module + (type (func (result i32))) ;; type #0 +- (import "a" "ef0" (func (result i32))) ;; index 0 +- (import "a" "ef1" (func (result i32))) +- (import "a" "ef2" (func (result i32))) +- (import "a" "ef3" (func (result i32))) +- (import "a" "ef4" (func (result i32))) ;; index 4 ++ (func (result i32) (i32.const 0)) ;; index 0 ++ (func (result i32) (i32.const 1)) ++ (func (result i32) (i32.const 2)) ++ (func (result i32) (i32.const 3)) ++ (func (result i32) (i32.const 4)) ;; index 4 + (table $t0 30 30 funcref) + (table $t1 30 30 funcref) + (elem (table $t1) (i32.const 2) func 3 1 4 1) +@@ -1026,11 +1027,11 @@ + + (module + (type (func (result i32))) ;; type #0 +- (import "a" "ef0" (func (result i32))) ;; index 0 +- (import "a" "ef1" (func (result i32))) +- (import "a" "ef2" (func (result i32))) +- (import "a" "ef3" (func (result i32))) +- (import "a" "ef4" (func (result i32))) ;; index 4 ++ (func (result i32) (i32.const 0)) ;; index 0 ++ (func (result i32) (i32.const 1)) ++ (func (result i32) (i32.const 2)) ++ (func (result i32) (i32.const 3)) ++ (func (result i32) (i32.const 4)) ;; index 4 + (table $t0 30 30 funcref) + (table $t1 30 30 funcref) + (elem (table $t1) (i32.const 2) func 3 1 4 1) +@@ -1118,11 +1119,11 @@ + + (module + (type (func (result i32))) ;; type #0 +- (import "a" "ef0" (func (result i32))) ;; index 0 +- (import "a" "ef1" (func (result i32))) +- (import "a" "ef2" (func (result i32))) +- (import "a" "ef3" (func (result i32))) +- (import "a" "ef4" (func (result i32))) ;; index 4 ++ (func (result i32) (i32.const 0)) ;; index 0 ++ (func (result i32) (i32.const 1)) ++ (func (result i32) (i32.const 2)) ++ (func (result i32) (i32.const 3)) ++ (func (result i32) (i32.const 4)) ;; index 4 + (table $t0 30 30 funcref) + (table $t1 30 30 funcref) + (elem (table $t1) (i32.const 2) func 3 1 4 1) +@@ -1210,11 +1211,11 @@ + + (module + (type (func (result i32))) ;; type #0 +- (import "a" "ef0" (func (result i32))) ;; index 0 +- (import "a" "ef1" (func (result i32))) +- (import "a" "ef2" (func (result i32))) +- (import "a" "ef3" (func (result i32))) +- (import "a" "ef4" (func (result i32))) ;; index 4 ++ (func (result i32) (i32.const 0)) ;; index 0 ++ (func (result i32) (i32.const 1)) ++ (func (result i32) (i32.const 2)) ++ (func (result i32) (i32.const 3)) ++ (func (result i32) (i32.const 4)) ;; index 4 + (table $t0 30 30 funcref) + (table $t1 30 30 funcref) + (elem (table $t1) (i32.const 2) func 3 1 4 1) +@@ -1302,11 +1303,11 @@ + + (module + (type (func (result i32))) ;; type #0 +- (import "a" "ef0" (func (result i32))) ;; index 0 +- (import "a" "ef1" (func (result i32))) +- (import "a" "ef2" (func (result i32))) +- (import "a" "ef3" (func (result i32))) +- (import "a" "ef4" (func (result i32))) ;; index 4 ++ (func (result i32) (i32.const 0)) ;; index 0 ++ (func (result i32) (i32.const 1)) ++ (func (result i32) (i32.const 2)) ++ (func (result i32) (i32.const 3)) ++ (func (result i32) (i32.const 4)) ;; index 4 + (table $t0 30 30 funcref) + (table $t1 30 30 funcref) + (elem (table $t1) (i32.const 2) func 3 1 4 1) +@@ -1394,11 +1395,11 @@ + + (module + (type (func (result i32))) ;; type #0 +- (import "a" "ef0" (func (result i32))) ;; index 0 +- (import "a" "ef1" (func (result i32))) +- (import "a" "ef2" (func (result i32))) +- (import "a" "ef3" (func (result i32))) +- (import "a" "ef4" (func (result i32))) ;; index 4 ++ (func (result i32) (i32.const 0)) ;; index 0 ++ (func (result i32) (i32.const 1)) ++ (func (result i32) (i32.const 2)) ++ (func (result i32) (i32.const 3)) ++ (func (result i32) (i32.const 4)) ;; index 4 + (table $t0 30 30 funcref) + (table $t1 30 30 funcref) + (elem (table $t1) (i32.const 2) func 3 1 4 1) +@@ -1486,11 +1487,11 @@ + + (module + (type (func (result i32))) ;; type #0 +- (import "a" "ef0" (func (result i32))) ;; index 0 +- (import "a" "ef1" (func (result i32))) +- (import "a" "ef2" (func (result i32))) +- (import "a" "ef3" (func (result i32))) +- (import "a" "ef4" (func (result i32))) ;; index 4 ++ (func (result i32) (i32.const 0)) ;; index 0 ++ (func (result i32) (i32.const 1)) ++ (func (result i32) (i32.const 2)) ++ (func (result i32) (i32.const 3)) ++ (func (result i32) (i32.const 4)) ;; index 4 + (table $t0 30 30 funcref) + (table $t1 30 30 funcref) + (elem (table $t1) (i32.const 2) func 3 1 4 1) +@@ -1578,11 +1579,11 @@ + + (module + (type (func (result i32))) ;; type #0 +- (import "a" "ef0" (func (result i32))) ;; index 0 +- (import "a" "ef1" (func (result i32))) +- (import "a" "ef2" (func (result i32))) +- (import "a" "ef3" (func (result i32))) +- (import "a" "ef4" (func (result i32))) ;; index 4 ++ (func (result i32) (i32.const 0)) ;; index 0 ++ (func (result i32) (i32.const 1)) ++ (func (result i32) (i32.const 2)) ++ (func (result i32) (i32.const 3)) ++ (func (result i32) (i32.const 4)) ;; index 4 + (table $t0 30 30 funcref) + (table $t1 30 30 funcref) + (elem (table $t1) (i32.const 2) func 3 1 4 1) +diff --git a/test/core/table_init.wast b/test/core/table_init.wast +index 0b2d26f7..bdab6a01 100644 +--- a/test/core/table_init.wast ++++ b/test/core/table_init.wast +@@ -14,11 +14,12 @@ + + (module + (type (func (result i32))) ;; type #0 +- (import "a" "ef0" (func (result i32))) ;; index 0 +- (import "a" "ef1" (func (result i32))) +- (import "a" "ef2" (func (result i32))) +- (import "a" "ef3" (func (result i32))) +- (import "a" "ef4" (func (result i32))) ;; index 4 ++ ;; aot mode does not support module linking ++ (func (result i32) (i32.const 0)) ;; index 0 ++ (func (result i32) (i32.const 1)) ++ (func (result i32) (i32.const 2)) ++ (func (result i32) (i32.const 3)) ++ (func (result i32) (i32.const 4)) ;; index 4 + (table $t0 30 30 funcref) + (table $t1 30 30 funcref) + (elem (table $t0) (i32.const 2) func 3 1 4 1) +@@ -72,11 +73,12 @@ + + (module + (type (func (result i32))) ;; type #0 +- (import "a" "ef0" (func (result i32))) ;; index 0 +- (import "a" "ef1" (func (result i32))) +- (import "a" "ef2" (func (result i32))) +- (import "a" "ef3" (func (result i32))) +- (import "a" "ef4" (func (result i32))) ;; index 4 ++ ;; aot mode does not support module linking ++ (func (result i32) (i32.const 0)) ;; index 0 ++ (func (result i32) (i32.const 1)) ++ (func (result i32) (i32.const 2)) ++ (func (result i32) (i32.const 3)) ++ (func (result i32) (i32.const 4)) ;; index 4 + (table $t0 30 30 funcref) + (table $t1 30 30 funcref) + (elem (table $t0) (i32.const 2) func 3 1 4 1) +@@ -130,11 +132,12 @@ + + (module + (type (func (result i32))) ;; type #0 +- (import "a" "ef0" (func (result i32))) ;; index 0 +- (import "a" "ef1" (func (result i32))) +- (import "a" "ef2" (func (result i32))) +- (import "a" "ef3" (func (result i32))) +- (import "a" "ef4" (func (result i32))) ;; index 4 ++ ;; aot mode does not support module linking ++ (func (result i32) (i32.const 0)) ;; index 0 ++ (func (result i32) (i32.const 1)) ++ (func (result i32) (i32.const 2)) ++ (func (result i32) (i32.const 3)) ++ (func (result i32) (i32.const 4)) ;; index 4 + (table $t0 30 30 funcref) + (table $t1 30 30 funcref) + (elem (table $t0) (i32.const 2) func 3 1 4 1) +@@ -196,11 +199,12 @@ + + (module + (type (func (result i32))) ;; type #0 +- (import "a" "ef0" (func (result i32))) ;; index 0 +- (import "a" "ef1" (func (result i32))) +- (import "a" "ef2" (func (result i32))) +- (import "a" "ef3" (func (result i32))) +- (import "a" "ef4" (func (result i32))) ;; index 4 ++ ;; aot mode does not support module linking ++ (func (result i32) (i32.const 0)) ;; index 0 ++ (func (result i32) (i32.const 1)) ++ (func (result i32) (i32.const 2)) ++ (func (result i32) (i32.const 3)) ++ (func (result i32) (i32.const 4)) ;; index 4 + (table $t0 30 30 funcref) + (table $t1 30 30 funcref) + (elem (table $t1) (i32.const 2) func 3 1 4 1) +@@ -254,11 +258,12 @@ + + (module + (type (func (result i32))) ;; type #0 +- (import "a" "ef0" (func (result i32))) ;; index 0 +- (import "a" "ef1" (func (result i32))) +- (import "a" "ef2" (func (result i32))) +- (import "a" "ef3" (func (result i32))) +- (import "a" "ef4" (func (result i32))) ;; index 4 ++ ;; aot mode does not support module linking ++ (func (result i32) (i32.const 0)) ;; index 0 ++ (func (result i32) (i32.const 1)) ++ (func (result i32) (i32.const 2)) ++ (func (result i32) (i32.const 3)) ++ (func (result i32) (i32.const 4)) ;; index 4 + (table $t0 30 30 funcref) + (table $t1 30 30 funcref) + (elem (table $t1) (i32.const 2) func 3 1 4 1) +@@ -312,11 +317,12 @@ + + (module + (type (func (result i32))) ;; type #0 +- (import "a" "ef0" (func (result i32))) ;; index 0 +- (import "a" "ef1" (func (result i32))) +- (import "a" "ef2" (func (result i32))) +- (import "a" "ef3" (func (result i32))) +- (import "a" "ef4" (func (result i32))) ;; index 4 ++ ;; aot mode does not support module linking ++ (func (result i32) (i32.const 0)) ;; index 0 ++ (func (result i32) (i32.const 1)) ++ (func (result i32) (i32.const 2)) ++ (func (result i32) (i32.const 3)) ++ (func (result i32) (i32.const 4)) ;; index 4 + (table $t0 30 30 funcref) + (table $t1 30 30 funcref) + (elem (table $t1) (i32.const 2) func 3 1 4 1) +diff --git a/test/core/unreached-valid.wast b/test/core/unreached-valid.wast +index f3feb0f3..d8ef8743 100644 +--- a/test/core/unreached-valid.wast ++++ b/test/core/unreached-valid.wast +@@ -60,7 +60,7 @@ + + ;; Validation after unreachable + +-(module ++(;module + (func (export "meet-bottom") + (block (result f64) + (block (result f32) +@@ -76,7 +76,6 @@ + + (assert_trap (invoke "meet-bottom") "unreachable") + +- + ;; Bottom heap type + + (module +@@ -106,3 +105,4 @@ + (unreachable) + ) + ) ++;) diff --git a/tests/wamr-test-suites/spec-test-script/gc_nuttx_tail_call.patch b/tests/wamr-test-suites/spec-test-script/gc_nuttx_tail_call.patch new file mode 100644 index 000000000..efbd9e178 --- /dev/null +++ b/tests/wamr-test-suites/spec-test-script/gc_nuttx_tail_call.patch @@ -0,0 +1,53 @@ +diff --git a/test/core/return_call.wast b/test/core/return_call.wast +index ad66acca..b27af19b 100644 +--- a/test/core/return_call.wast ++++ b/test/core/return_call.wast +@@ -102,20 +102,20 @@ + + (assert_return (invoke "count" (i64.const 0)) (i64.const 0)) + (assert_return (invoke "count" (i64.const 1000)) (i64.const 0)) +-(assert_return (invoke "count" (i64.const 100_000)) (i64.const 0)) ++(assert_return (invoke "count" (i64.const 1001)) (i64.const 0)) + + (assert_return (invoke "even" (i64.const 0)) (i32.const 44)) + (assert_return (invoke "even" (i64.const 1)) (i32.const 99)) + (assert_return (invoke "even" (i64.const 100)) (i32.const 44)) + (assert_return (invoke "even" (i64.const 77)) (i32.const 99)) +-(assert_return (invoke "even" (i64.const 100_000)) (i32.const 44)) +-(assert_return (invoke "even" (i64.const 100_001)) (i32.const 99)) ++(assert_return (invoke "even" (i64.const 1000)) (i32.const 44)) ++(assert_return (invoke "even" (i64.const 1001)) (i32.const 99)) + (assert_return (invoke "odd" (i64.const 0)) (i32.const 99)) + (assert_return (invoke "odd" (i64.const 1)) (i32.const 44)) + (assert_return (invoke "odd" (i64.const 200)) (i32.const 99)) + (assert_return (invoke "odd" (i64.const 77)) (i32.const 44)) +-(assert_return (invoke "odd" (i64.const 100_000)) (i32.const 99)) +-(assert_return (invoke "odd" (i64.const 99_999)) (i32.const 44)) ++(assert_return (invoke "odd" (i64.const 1000)) (i32.const 99)) ++(assert_return (invoke "odd" (i64.const 999)) (i32.const 44)) + + + ;; Invalid typing +diff --git a/test/core/return_call_indirect.wast b/test/core/return_call_indirect.wast +index 6b95c24b..a9e86d42 100644 +--- a/test/core/return_call_indirect.wast ++++ b/test/core/return_call_indirect.wast +@@ -257,14 +257,14 @@ + (assert_return (invoke "even" (i32.const 1)) (i32.const 99)) + (assert_return (invoke "even" (i32.const 100)) (i32.const 44)) + (assert_return (invoke "even" (i32.const 77)) (i32.const 99)) +-(assert_return (invoke "even" (i32.const 100_000)) (i32.const 44)) +-(assert_return (invoke "even" (i32.const 111_111)) (i32.const 99)) ++(assert_return (invoke "even" (i32.const 1000)) (i32.const 44)) ++(assert_return (invoke "even" (i32.const 1111)) (i32.const 99)) + (assert_return (invoke "odd" (i32.const 0)) (i32.const 99)) + (assert_return (invoke "odd" (i32.const 1)) (i32.const 44)) + (assert_return (invoke "odd" (i32.const 200)) (i32.const 99)) + (assert_return (invoke "odd" (i32.const 77)) (i32.const 44)) +-(assert_return (invoke "odd" (i32.const 100_002)) (i32.const 99)) +-(assert_return (invoke "odd" (i32.const 100_003)) (i32.const 44)) ++(assert_return (invoke "odd" (i32.const 1002)) (i32.const 99)) ++(assert_return (invoke "odd" (i32.const 1003)) (i32.const 44)) + + + ;; Invalid syntax diff --git a/tests/wamr-test-suites/spec-test-script/runtest.py b/tests/wamr-test-suites/spec-test-script/runtest.py index 60d4607e9..344e4fd44 100755 --- a/tests/wamr-test-suites/spec-test-script/runtest.py +++ b/tests/wamr-test-suites/spec-test-script/runtest.py @@ -626,7 +626,7 @@ def vector_value_comparison(out, expected): int(expected_val[1]) if not "0x" in expected_val[1] else int(expected_val[1], 16)) if lane_type in ["i8x16", "i16x8", "i32x4", "i64x2"]: - return out_packed == expected_packed; + return out_packed == expected_packed else: assert(lane_type in ["f32x4", "f64x2"]), "unexpected lane_type" @@ -817,7 +817,7 @@ def test_assert_return(r, opts, form): n = re.search('^\(assert_return\s+\(invoke\s+\$((?:[^\s])*)\s+"([^"]*)"*()()\)\s*\)\s*$', form, re.S) if not m and not n: if re.search('^\(assert_return\s+\(get.*\).*\)$', form, re.S): - log("ignoring assert_return get"); + log("ignoring assert_return get") return else: raise Exception("unparsed assert_return: '%s'" % form) @@ -898,6 +898,7 @@ def test_assert_return(r, opts, form): except: _, exc, _ = sys.exc_info() log("Run wamrc failed:\n got: '%s'" % r.buf) + ret_code = 1 sys.exit(1) r = run_wasm_with_repl(module+".wasm", module+".aot" if test_aot else module, opts, r) # Wait for the initial prompt @@ -963,6 +964,7 @@ def test_assert_trap(r, opts, form): except: _, exc, _ = sys.exc_info() log("Run wamrc failed:\n got: '%s'" % r.buf) + ret_code = 1 sys.exit(1) r = run_wasm_with_repl(module+".wasm", module+".aot" if test_aot else module, opts, r) # Wait for the initial prompt @@ -1091,7 +1093,7 @@ def compile_wast_to_wasm(form, wast_tempfile, wasm_tempfile, opts): return True def compile_wasm_to_aot(wasm_tempfile, aot_tempfile, runner, opts, r, output = 'default'): - log("Compiling AOT to '%s'" % aot_tempfile) + log("Compiling '%s' to '%s'" % (wasm_tempfile, aot_tempfile)) cmd = [opts.aot_compiler] if test_target in aot_target_options_map: @@ -1110,6 +1112,10 @@ def compile_wasm_to_aot(wasm_tempfile, aot_tempfile, runner, opts, r, output = ' if opts.multi_thread: cmd.append("--enable-multi-thread") + if opts.gc: + cmd.append("--enable-gc") + cmd.append("--enable-tail-call") + if output == 'object': cmd.append("--format=object") elif output == 'ir': @@ -1223,6 +1229,7 @@ def test_assert_with_exception(form, wast_tempfile, wasm_tempfile, aot_tempfile, else: log("Run wamrc failed:\n expected: '%s'\n got: '%s'" % \ (expected, r.buf)) + ret_code = 1 sys.exit(1) r = run_wasm_with_repl(wasm_tempfile, aot_tempfile if test_aot else None, opts, r) @@ -1319,26 +1326,47 @@ if __name__ == "__main__": log("Out exception includes expected one, pass:") log(" Expected: %s" % error_msg) log(" Got: %s" % r.buf) + continue + # one case in binary.wast + elif (error_msg == "unexpected end of section or function" + and r.buf.find("unexpected end")): + continue + # one case in binary.wast + elif (error_msg == "invalid value type" + and r.buf.find("unexpected end")): + continue + # one case in binary.wast + elif (error_msg == "integer too large" + and r.buf.find("tables cannot be shared")): + continue + # one case in binary.wast + elif (error_msg == "zero byte expected" + and r.buf.find("unknown table")): + continue + # one case in binary.wast + elif (error_msg == "invalid section id" + and r.buf.find("unexpected end of section or function")): + continue + # one case in binary.wast + elif (error_msg == "illegal opcode" + and r.buf.find("unexpected end of section or function")): + continue + # one case in custom.wast + elif (error_msg == "length out of bounds" + and r.buf.find("unexpected end")): + continue + # several cases in binary-leb128.wast + elif (error_msg == "integer representation too long" + and r.buf.find("invalid section id")): + continue else: log("Run wamrc failed:\n expected: '%s'\n got: '%s'" % \ (error_msg, r.buf)) - continue + ret_code = 1 + sys.exit(1) r = run_wasm_with_repl(wasm_tempfile, aot_tempfile if test_aot else None, opts, r) - if (error_msg == "unexpected end of section or function"): - # one case in binary.wast - assert_prompt(r, ["unexpected end", error_msg], opts.start_timeout, True) - elif (error_msg == "invalid value type"): - # one case in binary.wast - assert_prompt(r, ["unexpected end", error_msg], opts.start_timeout, True) - elif (error_msg == "length out of bounds"): - # one case in custom.wast - assert_prompt(r, ["unexpected end", error_msg], opts.start_timeout, True) - elif (error_msg == "integer representation too long"): - # several cases in binary-leb128.wast - assert_prompt(r, ["invalid section id", error_msg], opts.start_timeout, True) - elif re.match("^\(assert_malformed\s*\(module quote", form): log("ignoring assert_malformed module quote") else: @@ -1371,6 +1399,7 @@ if __name__ == "__main__": except: _, exc, _ = sys.exc_info() log("Run wamrc failed:\n got: '%s'" % r.buf) + ret_code = 1 sys.exit(1) temp_module_table[module_name] = temp_files[1] r = run_wasm_with_repl(temp_files[1], temp_files[2] if test_aot else None, opts, r) @@ -1385,6 +1414,7 @@ if __name__ == "__main__": except: _, exc, _ = sys.exc_info() log("Run wamrc failed:\n got: '%s'" % r.buf) + ret_code = 1 sys.exit(1) r = run_wasm_with_repl(wasm_tempfile, aot_tempfile if test_aot else None, opts, r) @@ -1468,4 +1498,3 @@ if __name__ == "__main__": log("Leaving tempfiles: %s" % ([wast_tempfile, wasm_tempfile])) sys.exit(ret_code) - \ No newline at end of file diff --git a/tests/wamr-test-suites/spec-test-script/tail-call/return_call.wast b/tests/wamr-test-suites/spec-test-script/tail-call/return_call.wast deleted file mode 100644 index df75df403..000000000 --- a/tests/wamr-test-suites/spec-test-script/tail-call/return_call.wast +++ /dev/null @@ -1,202 +0,0 @@ -;; Test `return_call` operator - -(module - ;; Auxiliary definitions - (func $const-i32 (result i32) (i32.const 0x132)) - (func $const-i64 (result i64) (i64.const 0x164)) - (func $const-f32 (result f32) (f32.const 0xf32)) - (func $const-f64 (result f64) (f64.const 0xf64)) - - (func $id-i32 (param i32) (result i32) (get_local 0)) - (func $id-i64 (param i64) (result i64) (get_local 0)) - (func $id-f32 (param f32) (result f32) (get_local 0)) - (func $id-f64 (param f64) (result f64) (get_local 0)) - - (func $f32-i32 (param f32 i32) (result i32) (get_local 1)) - (func $i32-i64 (param i32 i64) (result i64) (get_local 1)) - (func $f64-f32 (param f64 f32) (result f32) (get_local 1)) - (func $i64-f64 (param i64 f64) (result f64) (get_local 1)) - - ;; Typing - - (func (export "type-i32") (result i32) (return_call $const-i32)) - (func (export "type-i64") (result i64) (return_call $const-i64)) - (func (export "type-f32") (result f32) (return_call $const-f32)) - (func (export "type-f64") (result f64) (return_call $const-f64)) - - (func (export "type-first-i32") (result i32) (return_call $id-i32 (i32.const 32))) - (func (export "type-first-i64") (result i64) (return_call $id-i64 (i64.const 64))) - (func (export "type-first-f32") (result f32) (return_call $id-f32 (f32.const 1.32))) - (func (export "type-first-f64") (result f64) (return_call $id-f64 (f64.const 1.64))) - - (func (export "type-second-i32") (result i32) - (return_call $f32-i32 (f32.const 32.1) (i32.const 32)) - ) - (func (export "type-second-i64") (result i64) - (return_call $i32-i64 (i32.const 32) (i64.const 64)) - ) - (func (export "type-second-f32") (result f32) - (return_call $f64-f32 (f64.const 64) (f32.const 32)) - ) - (func (export "type-second-f64") (result f64) - (return_call $i64-f64 (i64.const 64) (f64.const 64.1)) - ) - - ;; Recursion - - (func $fac-acc (export "fac-acc") (param i64 i64) (result i64) - (if (result i64) (i64.eqz (get_local 0)) - (then (get_local 1)) - (else - (return_call $fac-acc - (i64.sub (get_local 0) (i64.const 1)) - (i64.mul (get_local 0) (get_local 1)) - ) - ) - ) - ) - - (func $count (export "count") (param i64) (result i64) - (if (result i64) (i64.eqz (get_local 0)) - (then (get_local 0)) - (else (return_call $count (i64.sub (get_local 0) (i64.const 1)))) - ) - ) - - (func $even (export "even") (param i64) (result i32) - (if (result i32) (i64.eqz (get_local 0)) - (then (i32.const 44)) - (else (return_call $odd (i64.sub (get_local 0) (i64.const 1)))) - ) - ) - (func $odd (export "odd") (param i64) (result i32) - (if (result i32) (i64.eqz (get_local 0)) - (then (i32.const 99)) - (else (return_call $even (i64.sub (get_local 0) (i64.const 1)))) - ) - ) -) - -(assert_return (invoke "type-i32") (i32.const 0x132)) -(assert_return (invoke "type-i64") (i64.const 0x164)) -(assert_return (invoke "type-f32") (f32.const 0xf32)) -(assert_return (invoke "type-f64") (f64.const 0xf64)) - -(assert_return (invoke "type-first-i32") (i32.const 32)) -(assert_return (invoke "type-first-i64") (i64.const 64)) -(assert_return (invoke "type-first-f32") (f32.const 1.32)) -(assert_return (invoke "type-first-f64") (f64.const 1.64)) - -(assert_return (invoke "type-second-i32") (i32.const 32)) -(assert_return (invoke "type-second-i64") (i64.const 64)) -(assert_return (invoke "type-second-f32") (f32.const 32)) -(assert_return (invoke "type-second-f64") (f64.const 64.1)) - -(assert_return (invoke "fac-acc" (i64.const 0) (i64.const 1)) (i64.const 1)) -(assert_return (invoke "fac-acc" (i64.const 1) (i64.const 1)) (i64.const 1)) -(assert_return (invoke "fac-acc" (i64.const 5) (i64.const 1)) (i64.const 120)) -(assert_return - (invoke "fac-acc" (i64.const 25) (i64.const 1)) - (i64.const 7034535277573963776) -) - -(assert_return (invoke "count" (i64.const 0)) (i64.const 0)) -(assert_return (invoke "count" (i64.const 1000)) (i64.const 0)) -(assert_return (invoke "count" (i64.const 1_000_000)) (i64.const 0)) - -(assert_return (invoke "even" (i64.const 0)) (i32.const 44)) -(assert_return (invoke "even" (i64.const 1)) (i32.const 99)) -(assert_return (invoke "even" (i64.const 100)) (i32.const 44)) -(assert_return (invoke "even" (i64.const 77)) (i32.const 99)) -(assert_return (invoke "even" (i64.const 1_000_000)) (i32.const 44)) -(assert_return (invoke "even" (i64.const 1_000_001)) (i32.const 99)) -(assert_return (invoke "odd" (i64.const 0)) (i32.const 99)) -(assert_return (invoke "odd" (i64.const 1)) (i32.const 44)) -(assert_return (invoke "odd" (i64.const 200)) (i32.const 99)) -(assert_return (invoke "odd" (i64.const 77)) (i32.const 44)) -(assert_return (invoke "odd" (i64.const 1_000_000)) (i32.const 99)) -(assert_return (invoke "odd" (i64.const 999_999)) (i32.const 44)) - - -;; Invalid typing - -(assert_invalid - (module - (func $type-void-vs-num (result i32) (return_call 1) (i32.const 0)) - (func) - ) - "type mismatch" -) -(assert_invalid - (module - (func $type-num-vs-num (result i32) (return_call 1) (i32.const 0)) - (func (result i64) (i64.const 1)) - ) - "type mismatch" -) - -(assert_invalid - (module - (func $arity-0-vs-1 (return_call 1)) - (func (param i32)) - ) - "type mismatch" -) -(assert_invalid - (module - (func $arity-0-vs-2 (return_call 1)) - (func (param f64 i32)) - ) - "type mismatch" -) - -(module - (func $arity-1-vs-0 (i32.const 1) (return_call 1)) - (func) -) - -(module - (func $arity-2-vs-0 (f64.const 2) (i32.const 1) (return_call 1)) - (func) -) - -(assert_invalid - (module - (func $type-first-void-vs-num (return_call 1 (nop) (i32.const 1))) - (func (param i32 i32)) - ) - "type mismatch" -) -(assert_invalid - (module - (func $type-second-void-vs-num (return_call 1 (i32.const 1) (nop))) - (func (param i32 i32)) - ) - "type mismatch" -) -(assert_invalid - (module - (func $type-first-num-vs-num (return_call 1 (f64.const 1) (i32.const 1))) - (func (param i32 f64)) - ) - "type mismatch" -) -(assert_invalid - (module - (func $type-second-num-vs-num (return_call 1 (i32.const 1) (f64.const 1))) - (func (param f64 i32)) - ) - "type mismatch" -) - - -;; Unbound function - -(assert_invalid - (module (func $unbound-func (return_call 1))) - "unknown function" -) -(assert_invalid - (module (func $large-func (return_call 1012321300))) - "unknown function" -) diff --git a/tests/wamr-test-suites/spec-test-script/tail-call/return_call_indirect.wast b/tests/wamr-test-suites/spec-test-script/tail-call/return_call_indirect.wast deleted file mode 100644 index 515f15d5d..000000000 --- a/tests/wamr-test-suites/spec-test-script/tail-call/return_call_indirect.wast +++ /dev/null @@ -1,511 +0,0 @@ -;; Test `return_call_indirect` operator - -(module - ;; Auxiliary definitions - (type $proc (func)) - (type $out-i32 (func (result i32))) - (type $out-i64 (func (result i64))) - (type $out-f32 (func (result f32))) - (type $out-f64 (func (result f64))) - (type $over-i32 (func (param i32) (result i32))) - (type $over-i64 (func (param i64) (result i64))) - (type $over-f32 (func (param f32) (result f32))) - (type $over-f64 (func (param f64) (result f64))) - (type $f32-i32 (func (param f32 i32) (result i32))) - (type $i32-i64 (func (param i32 i64) (result i64))) - (type $f64-f32 (func (param f64 f32) (result f32))) - (type $i64-f64 (func (param i64 f64) (result f64))) - (type $over-i32-duplicate (func (param i32) (result i32))) - (type $over-i64-duplicate (func (param i64) (result i64))) - (type $over-f32-duplicate (func (param f32) (result f32))) - (type $over-f64-duplicate (func (param f64) (result f64))) - - (func $const-i32 (type $out-i32) (i32.const 0x132)) - (func $const-i64 (type $out-i64) (i64.const 0x164)) - (func $const-f32 (type $out-f32) (f32.const 0xf32)) - (func $const-f64 (type $out-f64) (f64.const 0xf64)) - - (func $id-i32 (type $over-i32) (get_local 0)) - (func $id-i64 (type $over-i64) (get_local 0)) - (func $id-f32 (type $over-f32) (get_local 0)) - (func $id-f64 (type $over-f64) (get_local 0)) - - (func $i32-i64 (type $i32-i64) (get_local 1)) - (func $i64-f64 (type $i64-f64) (get_local 1)) - (func $f32-i32 (type $f32-i32) (get_local 1)) - (func $f64-f32 (type $f64-f32) (get_local 1)) - - (func $over-i32-duplicate (type $over-i32-duplicate) (get_local 0)) - (func $over-i64-duplicate (type $over-i64-duplicate) (get_local 0)) - (func $over-f32-duplicate (type $over-f32-duplicate) (get_local 0)) - (func $over-f64-duplicate (type $over-f64-duplicate) (get_local 0)) - - (table anyfunc - (elem - $const-i32 $const-i64 $const-f32 $const-f64 - $id-i32 $id-i64 $id-f32 $id-f64 - $f32-i32 $i32-i64 $f64-f32 $i64-f64 - $fac $fac-acc $even $odd - $over-i32-duplicate $over-i64-duplicate - $over-f32-duplicate $over-f64-duplicate - ) - ) - - ;; Syntax - - (func - (return_call_indirect (i32.const 0)) - (return_call_indirect (param i64) (i64.const 0) (i32.const 0)) - (return_call_indirect (param i64) (param) (param f64 i32 i64) - (i64.const 0) (f64.const 0) (i32.const 0) (i64.const 0) (i32.const 0) - ) - (return_call_indirect (result) (i32.const 0)) - ) - - (func (result i32) - (return_call_indirect (result i32) (i32.const 0)) - (return_call_indirect (result i32) (result) (i32.const 0)) - (return_call_indirect (param i64) (result i32) (i64.const 0) (i32.const 0)) - (return_call_indirect - (param) (param i64) (param) (param f64 i32 i64) (param) (param) - (result) (result i32) (result) (result) - (i64.const 0) (f64.const 0) (i32.const 0) (i64.const 0) (i32.const 0) - ) - ) - - (func (result i64) - (return_call_indirect (type $over-i64) (param i64) (result i64) - (i64.const 0) (i32.const 0) - ) - ) - - ;; Typing - - (func (export "type-i32") (result i32) - (return_call_indirect (type $out-i32) (i32.const 0)) - ) - (func (export "type-i64") (result i64) - (return_call_indirect (type $out-i64) (i32.const 1)) - ) - (func (export "type-f32") (result f32) - (return_call_indirect (type $out-f32) (i32.const 2)) - ) - (func (export "type-f64") (result f64) - (return_call_indirect (type $out-f64) (i32.const 3)) - ) - - (func (export "type-index") (result i64) - (return_call_indirect (type $over-i64) (i64.const 100) (i32.const 5)) - ) - - (func (export "type-first-i32") (result i32) - (return_call_indirect (type $over-i32) (i32.const 32) (i32.const 4)) - ) - (func (export "type-first-i64") (result i64) - (return_call_indirect (type $over-i64) (i64.const 64) (i32.const 5)) - ) - (func (export "type-first-f32") (result f32) - (return_call_indirect (type $over-f32) (f32.const 1.32) (i32.const 6)) - ) - (func (export "type-first-f64") (result f64) - (return_call_indirect (type $over-f64) (f64.const 1.64) (i32.const 7)) - ) - - (func (export "type-second-i32") (result i32) - (return_call_indirect (type $f32-i32) - (f32.const 32.1) (i32.const 32) (i32.const 8) - ) - ) - (func (export "type-second-i64") (result i64) - (return_call_indirect (type $i32-i64) - (i32.const 32) (i64.const 64) (i32.const 9) - ) - ) - (func (export "type-second-f32") (result f32) - (return_call_indirect (type $f64-f32) - (f64.const 64) (f32.const 32) (i32.const 10) - ) - ) - (func (export "type-second-f64") (result f64) - (return_call_indirect (type $i64-f64) - (i64.const 64) (f64.const 64.1) (i32.const 11) - ) - ) - - ;; Dispatch - - (func (export "dispatch") (param i32 i64) (result i64) - (return_call_indirect (type $over-i64) (get_local 1) (get_local 0)) - ) - - (func (export "dispatch-structural") (param i32) (result i64) - (return_call_indirect (type $over-i64-duplicate) - (i64.const 9) (get_local 0) - ) - ) - - ;; Recursion - - (func $fac (export "fac") (type $over-i64) - (return_call_indirect (param i64 i64) (result i64) - (get_local 0) (i64.const 1) (i32.const 13) - ) - ) - - (func $fac-acc (param i64 i64) (result i64) - (if (result i64) (i64.eqz (get_local 0)) - (then (get_local 1)) - (else - (return_call_indirect (param i64 i64) (result i64) - (i64.sub (get_local 0) (i64.const 1)) - (i64.mul (get_local 0) (get_local 1)) - (i32.const 13) - ) - ) - ) - ) - - (func $even (export "even") (param i32) (result i32) - (if (result i32) (i32.eqz (get_local 0)) - (then (i32.const 44)) - (else - (return_call_indirect (type $over-i32) - (i32.sub (get_local 0) (i32.const 1)) - (i32.const 15) - ) - ) - ) - ) - (func $odd (export "odd") (param i32) (result i32) - (if (result i32) (i32.eqz (get_local 0)) - (then (i32.const 99)) - (else - (return_call_indirect (type $over-i32) - (i32.sub (get_local 0) (i32.const 1)) - (i32.const 14) - ) - ) - ) - ) -) - -(assert_return (invoke "type-i32") (i32.const 0x132)) -(assert_return (invoke "type-i64") (i64.const 0x164)) -(assert_return (invoke "type-f32") (f32.const 0xf32)) -(assert_return (invoke "type-f64") (f64.const 0xf64)) - -(assert_return (invoke "type-index") (i64.const 100)) - -(assert_return (invoke "type-first-i32") (i32.const 32)) -(assert_return (invoke "type-first-i64") (i64.const 64)) -(assert_return (invoke "type-first-f32") (f32.const 1.32)) -(assert_return (invoke "type-first-f64") (f64.const 1.64)) - -(assert_return (invoke "type-second-i32") (i32.const 32)) -(assert_return (invoke "type-second-i64") (i64.const 64)) -(assert_return (invoke "type-second-f32") (f32.const 32)) -(assert_return (invoke "type-second-f64") (f64.const 64.1)) - -(assert_return (invoke "dispatch" (i32.const 5) (i64.const 2)) (i64.const 2)) -(assert_return (invoke "dispatch" (i32.const 5) (i64.const 5)) (i64.const 5)) -(assert_return (invoke "dispatch" (i32.const 12) (i64.const 5)) (i64.const 120)) -(assert_return (invoke "dispatch" (i32.const 17) (i64.const 2)) (i64.const 2)) -(assert_trap (invoke "dispatch" (i32.const 0) (i64.const 2)) "indirect call type mismatch") -(assert_trap (invoke "dispatch" (i32.const 15) (i64.const 2)) "indirect call type mismatch") -(assert_trap (invoke "dispatch" (i32.const 20) (i64.const 2)) "undefined element") -(assert_trap (invoke "dispatch" (i32.const -1) (i64.const 2)) "undefined element") -(assert_trap (invoke "dispatch" (i32.const 1213432423) (i64.const 2)) "undefined element") - -(assert_return (invoke "dispatch-structural" (i32.const 5)) (i64.const 9)) -(assert_return (invoke "dispatch-structural" (i32.const 5)) (i64.const 9)) -(assert_return (invoke "dispatch-structural" (i32.const 12)) (i64.const 362880)) -(assert_return (invoke "dispatch-structural" (i32.const 17)) (i64.const 9)) -(assert_trap (invoke "dispatch-structural" (i32.const 11)) "indirect call type mismatch") -(assert_trap (invoke "dispatch-structural" (i32.const 16)) "indirect call type mismatch") - -(assert_return (invoke "fac" (i64.const 0)) (i64.const 1)) -(assert_return (invoke "fac" (i64.const 1)) (i64.const 1)) -(assert_return (invoke "fac" (i64.const 5)) (i64.const 120)) -(assert_return (invoke "fac" (i64.const 25)) (i64.const 7034535277573963776)) - -(assert_return (invoke "even" (i32.const 0)) (i32.const 44)) -(assert_return (invoke "even" (i32.const 1)) (i32.const 99)) -(assert_return (invoke "even" (i32.const 100)) (i32.const 44)) -(assert_return (invoke "even" (i32.const 77)) (i32.const 99)) -(assert_return (invoke "even" (i32.const 100_000)) (i32.const 44)) -(assert_return (invoke "even" (i32.const 111_111)) (i32.const 99)) -(assert_return (invoke "odd" (i32.const 0)) (i32.const 99)) -(assert_return (invoke "odd" (i32.const 1)) (i32.const 44)) -(assert_return (invoke "odd" (i32.const 200)) (i32.const 99)) -(assert_return (invoke "odd" (i32.const 77)) (i32.const 44)) -(assert_return (invoke "odd" (i32.const 200_002)) (i32.const 99)) -(assert_return (invoke "odd" (i32.const 300_003)) (i32.const 44)) - - -;; Invalid syntax - -(assert_malformed - (module quote - "(type $sig (func (param i32) (result i32)))" - "(table 0 anyfunc)" - "(func (result i32)" - " (return_call_indirect (type $sig) (result i32) (param i32)" - " (i32.const 0) (i32.const 0)" - " )" - ")" - ) - "unexpected token" -) -(assert_malformed - (module quote - "(type $sig (func (param i32) (result i32)))" - "(table 0 anyfunc)" - "(func (result i32)" - " (return_call_indirect (param i32) (type $sig) (result i32)" - " (i32.const 0) (i32.const 0)" - " )" - ")" - ) - "unexpected token" -) -(assert_malformed - (module quote - "(type $sig (func (param i32) (result i32)))" - "(table 0 anyfunc)" - "(func (result i32)" - " (return_call_indirect (param i32) (result i32) (type $sig)" - " (i32.const 0) (i32.const 0)" - " )" - ")" - ) - "unexpected token" -) -(assert_malformed - (module quote - "(type $sig (func (param i32) (result i32)))" - "(table 0 anyfunc)" - "(func (result i32)" - " (return_call_indirect (result i32) (type $sig) (param i32)" - " (i32.const 0) (i32.const 0)" - " )" - ")" - ) - "unexpected token" -) -(assert_malformed - (module quote - "(type $sig (func (param i32) (result i32)))" - "(table 0 anyfunc)" - "(func (result i32)" - " (return_call_indirect (result i32) (param i32) (type $sig)" - " (i32.const 0) (i32.const 0)" - " )" - ")" - ) - "unexpected token" -) -(assert_malformed - (module quote - "(table 0 anyfunc)" - "(func (result i32)" - " (return_call_indirect (result i32) (param i32)" - " (i32.const 0) (i32.const 0)" - " )" - ")" - ) - "unexpected token" -) - -(assert_malformed - (module quote - "(table 0 anyfunc)" - "(func (return_call_indirect (param $x i32) (i32.const 0) (i32.const 0)))" - ) - "unexpected token" -) -(assert_malformed - (module quote - "(type $sig (func))" - "(table 0 anyfunc)" - "(func (result i32)" - " (return_call_indirect (type $sig) (result i32) (i32.const 0))" - ")" - ) - "inline function type" -) -(assert_malformed - (module quote - "(type $sig (func (param i32) (result i32)))" - "(table 0 anyfunc)" - "(func (result i32)" - " (return_call_indirect (type $sig) (result i32) (i32.const 0))" - ")" - ) - "inline function type" -) -(assert_malformed - (module quote - "(type $sig (func (param i32) (result i32)))" - "(table 0 anyfunc)" - "(func" - " (return_call_indirect (type $sig) (param i32)" - " (i32.const 0) (i32.const 0)" - " )" - ")" - ) - "inline function type" -) -(assert_malformed - (module quote - "(type $sig (func (param i32 i32) (result i32)))" - "(table 0 anyfunc)" - "(func (result i32)" - " (return_call_indirect (type $sig) (param i32) (result i32)" - " (i32.const 0) (i32.const 0)" - " )" - ")" - ) - "inline function type" -) - -;; Invalid typing - -(assert_invalid - (module - (type (func)) - (func $no-table (return_call_indirect (type 0) (i32.const 0))) - ) - "unknown table" -) - -(assert_invalid - (module - (type (func)) - (table 0 anyfunc) - (func $type-void-vs-num (i32.eqz (return_call_indirect (type 0) (i32.const 0)))) - ) - "type mismatch" -) -(assert_invalid - (module - (type (func (result i64))) - (table 0 anyfunc) - (func $type-num-vs-num (i32.eqz (return_call_indirect (type 0) (i32.const 0)))) - ) - "type mismatch" -) - -(assert_invalid - (module - (type (func (param i32))) - (table 0 anyfunc) - (func $arity-0-vs-1 (return_call_indirect (type 0) (i32.const 0))) - ) - "type mismatch" -) -(assert_invalid - (module - (type (func (param f64 i32))) - (table 0 anyfunc) - (func $arity-0-vs-2 (return_call_indirect (type 0) (i32.const 0))) - ) - "type mismatch" -) - -(module - (type (func)) - (table 0 anyfunc) - (func $arity-1-vs-0 (return_call_indirect (type 0) (i32.const 1) (i32.const 0))) -) - -(module - (type (func)) - (table 0 anyfunc) - (func $arity-2-vs-0 - (return_call_indirect (type 0) (f64.const 2) (i32.const 1) (i32.const 0)) - ) -) - -(assert_invalid - (module - (type (func (param i32))) - (table 0 anyfunc) - (func $type-func-void-vs-i32 (return_call_indirect (type 0) (i32.const 1) (nop))) - ) - "type mismatch" -) -(assert_invalid - (module - (type (func (param i32))) - (table 0 anyfunc) - (func $type-func-num-vs-i32 (return_call_indirect (type 0) (i32.const 0) (i64.const 1))) - ) - "type mismatch" -) - -(assert_invalid - (module - (type (func (param i32 i32))) - (table 0 anyfunc) - (func $type-first-void-vs-num - (return_call_indirect (type 0) (nop) (i32.const 1) (i32.const 0)) - ) - ) - "type mismatch" -) -(assert_invalid - (module - (type (func (param i32 i32))) - (table 0 anyfunc) - (func $type-second-void-vs-num - (return_call_indirect (type 0) (i32.const 1) (nop) (i32.const 0)) - ) - ) - "type mismatch" -) -(assert_invalid - (module - (type (func (param i32 f64))) - (table 0 anyfunc) - (func $type-first-num-vs-num - (return_call_indirect (type 0) (f64.const 1) (i32.const 1) (i32.const 0)) - ) - ) - "type mismatch" -) -(assert_invalid - (module - (type (func (param f64 i32))) - (table 0 anyfunc) - (func $type-second-num-vs-num - (return_call_indirect (type 0) (i32.const 1) (f64.const 1) (i32.const 0)) - ) - ) - "type mismatch" -) - - -;; Unbound type - -(assert_invalid - (module - (table 0 anyfunc) - (func $unbound-type (return_call_indirect (type 1) (i32.const 0))) - ) - "unknown type" -) -(assert_invalid - (module - (table 0 anyfunc) - (func $large-type (return_call_indirect (type 1012321300) (i32.const 0))) - ) - "unknown type" -) - - -;; Unbound function in table - -(assert_invalid - (module (table anyfunc (elem 0 0))) - "unknown function" -) diff --git a/tests/wamr-test-suites/spec-test-script/thread_proposal_ignore_cases.patch b/tests/wamr-test-suites/spec-test-script/thread_proposal_ignore_cases.patch index c411d89c1..b2f4ab38a 100644 --- a/tests/wamr-test-suites/spec-test-script/thread_proposal_ignore_cases.patch +++ b/tests/wamr-test-suites/spec-test-script/thread_proposal_ignore_cases.patch @@ -211,6 +211,21 @@ index 1ea2b06..8eded37 100644 (assert_return (invoke $module1 "call-8") (i32.const 69)) (assert_return (invoke $module1 "call-9") (i32.const 70)) +;) +diff --git a/test/core/table.wast b/test/core/table.wast +index 0bc43ca6..ee5209ec 100644 +--- a/test/core/table.wast ++++ b/test/core/table.wast +@@ -8,8 +8,8 @@ + (module (table 0 65536 funcref)) + (module (table 0 0xffff_ffff funcref)) + +-(assert_invalid (module (table 0 funcref) (table 0 funcref)) "multiple tables") +-(assert_invalid (module (table (import "spectest" "table") 0 funcref) (table 0 funcref)) "multiple tables") ++(module (table 0 funcref) (table 0 funcref)) ++(module (table (import "spectest" "table") 0 funcref) (table 0 funcref)) + + (assert_invalid (module (elem (i32.const 0))) "unknown table") + (assert_invalid (module (elem (i32.const 0) $f) (func $f)) "unknown table") diff --git a/test/core/thread.wast b/test/core/thread.wast index c3456a6..83fc281 100644 --- a/test/core/thread.wast @@ -228,3 +243,23 @@ index c3456a6..83fc281 100644 (wait $T1) (wait $T2) +;) +diff --git a/test/core/unreached-invalid.wast b/test/core/unreached-invalid.wast +index 6ef4ac55..9a2387a3 100644 +--- a/test/core/unreached-invalid.wast ++++ b/test/core/unreached-invalid.wast +@@ -535,6 +535,7 @@ + )) + "type mismatch" + ) ++(; invalid case, the module is fine for the latest spec interpreter + (assert_invalid + (module (func $type-br_table-label-num-vs-label-num-after-unreachable + (block (result f64) +@@ -549,6 +550,7 @@ + )) + "type mismatch" + ) ++;) + + (assert_invalid + (module (func $type-block-value-nested-unreachable-num-vs-void diff --git a/tests/wamr-test-suites/test_wamr.sh b/tests/wamr-test-suites/test_wamr.sh index 7f41fc43d..933583816 100755 --- a/tests/wamr-test-suites/test_wamr.sh +++ b/tests/wamr-test-suites/test_wamr.sh @@ -462,13 +462,19 @@ function spec_test() pushd spec git restore . && git clean -ffd . - # Sync constant expression descriptions - git reset --hard 62beb94ddd41987517781732f17f213d8b866dcc + # Reset to commit: "[test] Unify the error message." + git reset --hard 0caaadc65b5e1910512d8ae228502edcf9d60390 git apply ../../spec-test-script/gc_ignore_cases.patch + if [[ ${ENABLE_QEMU} == 1 ]]; then + # Decrease the recursive count for tail call cases as nuttx qemu's + # native stack size is much smaller + git apply ../../spec-test-script/gc_nuttx_tail_call.patch + fi + echo "compile the reference intepreter" pushd interpreter - make opt + make popd fi @@ -819,6 +825,7 @@ function trigger() local EXTRA_COMPILE_FLAGS="" # default enabled features EXTRA_COMPILE_FLAGS+=" -DWAMR_BUILD_BULK_MEMORY=1" + EXTRA_COMPILE_FLAGS+=" -DWAMR_BUILD_REF_TYPES=1" if [[ ${ENABLE_MULTI_MODULE} == 1 ]];then EXTRA_COMPILE_FLAGS+=" -DWAMR_BUILD_MULTI_MODULE=1" @@ -828,9 +835,6 @@ function trigger() if [[ ${ENABLE_MULTI_THREAD} == 1 ]];then EXTRA_COMPILE_FLAGS+=" -DWAMR_BUILD_LIB_PTHREAD=1" - EXTRA_COMPILE_FLAGS+=" -DWAMR_BUILD_REF_TYPES=0" - else - EXTRA_COMPILE_FLAGS+=" -DWAMR_BUILD_REF_TYPES=1" fi if [[ ${ENABLE_SIMD} == 1 ]]; then @@ -841,8 +845,8 @@ function trigger() if [[ ${ENABLE_GC} == 1 ]]; then EXTRA_COMPILE_FLAGS+=" -DWAMR_BUILD_GC=1" - EXTRA_COMPILE_FLAGS+=" -DWAMR_BUILD_REF_TYPES=1" EXTRA_COMPILE_FLAGS+=" -DWAMR_BUILD_BULK_MEMORY=1" + EXTRA_COMPILE_FLAGS+=" -DWAMR_BUILD_TAIL_CALL=1" fi if [[ ${ENABLE_DEBUG_VERSION} == 1 ]]; then diff --git a/wamr-compiler/CMakeLists.txt b/wamr-compiler/CMakeLists.txt index 84e8b524c..6a3f97521 100644 --- a/wamr-compiler/CMakeLists.txt +++ b/wamr-compiler/CMakeLists.txt @@ -41,11 +41,17 @@ add_definitions(-DWASM_ENABLE_TAIL_CALL=1) add_definitions(-DWASM_ENABLE_SIMD=1) add_definitions(-DWASM_ENABLE_REF_TYPES=1) add_definitions(-DWASM_ENABLE_CUSTOM_NAME_SECTION=1) +add_definitions(-DWASM_ENABLE_AOT_STACK_FRAME=1) add_definitions(-DWASM_ENABLE_DUMP_CALL_STACK=1) add_definitions(-DWASM_ENABLE_PERF_PROFILING=1) add_definitions(-DWASM_ENABLE_LOAD_CUSTOM_SECTION=1) add_definitions(-DWASM_ENABLE_MODULE_INST_CONTEXT=1) +add_definitions(-DWASM_ENABLE_GC=1) + +set (WAMR_BUILD_STRINGREF 1) +set (WAMR_STRINGREF_IMPL_SOURCE "STUB") + if (WAMR_BUILD_LLVM_LEGACY_PM EQUAL 1) add_definitions(-DWASM_ENABLE_LLVM_LEGACY_PM=1) endif () @@ -208,7 +214,6 @@ endif() set (SHARED_DIR ../core/shared) set (IWASM_DIR ../core/iwasm) -set (APP_FRAMEWORK_DIR ../core/app-framework) include_directories (${SHARED_DIR}/include ${IWASM_DIR}/include) @@ -283,6 +288,7 @@ include (${SHARED_DIR}/utils/shared_utils.cmake) include (${SHARED_DIR}/utils/uncommon/shared_uncommon.cmake) include (${IWASM_DIR}/libraries/thread-mgr/thread_mgr.cmake) include (${IWASM_DIR}/common/iwasm_common.cmake) +include (${IWASM_DIR}/common/gc/iwasm_gc.cmake) include (${IWASM_DIR}/interpreter/iwasm_interp.cmake) include (${IWASM_DIR}/aot/iwasm_aot.cmake) include (${IWASM_DIR}/compilation/iwasm_compl.cmake) @@ -359,7 +365,8 @@ add_library (vmlib ${LIB_WASI_THREADS_SOURCE} ${IWASM_COMMON_SOURCE} ${IWASM_INTERP_SOURCE} - ${IWASM_AOT_SOURCE}) + ${IWASM_AOT_SOURCE} + ${IWASM_GC_SOURCE}) add_library (aotclib ${IWASM_COMPL_SOURCE}) diff --git a/wamr-compiler/main.c b/wamr-compiler/main.c index 17c19143c..909752523 100644 --- a/wamr-compiler/main.c +++ b/wamr-compiler/main.c @@ -154,13 +154,15 @@ print_help() printf(" --disable-simd Disable the post-MVP 128-bit SIMD feature:\n"); printf(" currently 128-bit SIMD is supported for x86-64 and aarch64 targets,\n"); printf(" and by default it is enabled in them and disabled in other targets\n"); - printf(" --disable-ref-types Disable the MVP reference types feature\n"); + printf(" --disable-ref-types Disable the MVP reference types feature, it will be disabled forcibly if\n"); + printf(" GC is enabled\n"); printf(" --disable-aux-stack-check Disable auxiliary stack overflow/underflow check\n"); printf(" --enable-dump-call-stack Enable stack trace feature\n"); printf(" --enable-perf-profiling Enable function performance profiling\n"); printf(" --enable-memory-profiling Enable memory usage profiling\n"); - printf(" --xip A shorthand of --enable-indirect-mode --disable-llvm-intrinsics\n"); - printf(" --enable-indirect-mode Enable call function through symbol table but not direct call\n"); + printf(" --xip A shorthand of --enalbe-indirect-mode --disable-llvm-intrinsics\n"); + printf(" --enable-indirect-mode Enalbe call function through symbol table but not direct call\n"); + printf(" --enable-gc Enalbe GC (Garbage Collection) feature\n"); printf(" --disable-llvm-intrinsics Disable the LLVM built-in intrinsics\n"); printf(" --enable-builtin-intrinsics=\n"); printf(" Enable the specified built-in intrinsics, it will override the default\n"); @@ -345,6 +347,7 @@ main(int argc, char *argv[]) option.enable_aux_stack_check = true; option.enable_bulk_memory = true; option.enable_ref_types = true; + option.enable_gc = false; /* Process options */ for (argc--, argv++; argc > 0 && argv[0][0] == '-'; argc--, argv++) { @@ -440,7 +443,6 @@ main(int argc, char *argv[]) else if (!strcmp(argv[0], "--enable-multi-thread")) { option.enable_bulk_memory = true; option.enable_thread_mgr = true; - option.enable_ref_types = false; } else if (!strcmp(argv[0], "--enable-tail-call")) { option.enable_tail_call = true; @@ -463,8 +465,10 @@ main(int argc, char *argv[]) } else if (!strcmp(argv[0], "--enable-perf-profiling")) { option.enable_aux_stack_frame = true; + option.enable_perf_profiling = true; } else if (!strcmp(argv[0], "--enable-memory-profiling")) { + option.enable_memory_profiling = true; option.enable_stack_estimation = true; } else if (!strcmp(argv[0], "--xip")) { @@ -474,6 +478,10 @@ main(int argc, char *argv[]) else if (!strcmp(argv[0], "--enable-indirect-mode")) { option.is_indirect_mode = true; } + else if (!strcmp(argv[0], "--enable-gc")) { + option.enable_aux_stack_frame = true; + option.enable_gc = true; + } else if (!strcmp(argv[0], "--disable-llvm-intrinsics")) { option.disable_llvm_intrinsics = true; } @@ -580,6 +588,10 @@ main(int argc, char *argv[]) option.is_sgx_platform = true; } + if (option.enable_gc) { + option.enable_ref_types = false; + } + if (!use_dummy_wasm) { wasm_file_name = argv[0]; @@ -641,7 +653,8 @@ main(int argc, char *argv[]) goto fail2; } - if (!(comp_data = aot_create_comp_data(wasm_module))) { + if (!(comp_data = aot_create_comp_data(wasm_module, option.target_arch, + option.enable_gc))) { printf("%s\n", aot_get_last_error()); goto fail3; } diff --git a/wamr-sdk/Kconfig b/wamr-sdk/Kconfig deleted file mode 100644 index 96c23a83c..000000000 --- a/wamr-sdk/Kconfig +++ /dev/null @@ -1,84 +0,0 @@ -mainmenu "WebAssembly Micro Runtime Configuration" - -choice - prompt "select a build target" - - config TARGET_X86_64 - bool "X86_64" - - config TARGET_X86_32 - bool "X86_32" - -endchoice - -choice - prompt "select a target platform" - - config PLATFORM_LINUX - bool "Linux" - -endchoice - -menu "select execution mode" - comment "At least one execution mode must be selected" - config EXEC_AOT - bool "AOT" - depends on PLATFORM_LINUX - - config EXEC_JIT - bool "JIT" - depends on PLATFORM_LINUX - select BUILD_LLVM - - config BUILD_LLVM - bool "build llvm (this may take a long time)" - depends on EXEC_JIT - help - llvm library is required by JIT mode. - - config EXEC_INTERP - bool "INTERPRETER" - default y -endmenu - -choice - prompt "libc support" - - config LIBC_BUILTIN - bool "builtin libc" - help - use builtin libc, this is a minimal subset of libc. - - config LIBC_WASI - bool "WebAssembly System Interface [WASI]" - depends on PLATFORM_LINUX - help - enable WebAssembly System Interface - -endchoice - -choice - prompt "application framework" - config APP_FRAMEWORK_DISABLE - bool "Disable app framework" - help - Disable wamr app framework - - config APP_FRAMEWORK_DEFAULT - bool "Default components" - help - Default components - - config APP_FRAMEWORK_ALL - bool "All components" - - config APP_FRAMEWORK_CUSTOM - bool "customized module config" - - menu "modules:" - depends on APP_FRAMEWORK_CUSTOM - - source ".wamr_modules" - - endmenu -endchoice diff --git a/wamr-sdk/Makefile b/wamr-sdk/Makefile deleted file mode 100644 index a0824aeab..000000000 --- a/wamr-sdk/Makefile +++ /dev/null @@ -1,10 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -# # This will generate SDK for both runtime and wasm application -config: - ./build_sdk.sh -i - -menuconfig: - ./menuconfig.sh - diff --git a/wamr-sdk/README.md b/wamr-sdk/README.md index fd926af86..ef0cfd2ff 100644 --- a/wamr-sdk/README.md +++ b/wamr-sdk/README.md @@ -1,133 +1,3 @@ -# WebAssembly Micro Runtime SDK - -Usually there are two tasks for integrating the WAMR into a particular project: - -- Select what WAMR components (vmcore, libc, app-mgr, app-framework components) to be integrated, and get the associated source files added into the project building configuration -- Generate the APP SDK for developing the WASM apps on the selected libc and framework components - -The **[WAMR SDK](./wamr-sdk)** tools is helpful to finish the two tasks quickly. It supports menu configuration for selecting WAMR components and builds the WAMR to a SDK package that includes **runtime SDK** and **APP SDK**. The runtime SDK is used for building the native application and the APP SDK should be shipped to WASM application developers. - - -**Note**: [WASI-SDK](https://github.com/WebAssembly/wasi-sdk/releases) version 7 and above should be installed before building the WAMR SDK. - - - -### SDK profile and configuration file - -A SDK profile presents a configuration of build parameters for the selection of CPU architecture, software platforms, execution mode, libc and application framework components. The profile configurations are saved in a cmake file that will be included by the WAMR SDK building tool `build_sdk.sh`. - -Here is the default configuration file [wamr-sdk/wamr_config_default.cmake](./wamr_config_default.cmake): - -``` -set (WAMR_BUILD_PLATFORM "linux") -set (WAMR_BUILD_TARGET X86_64) -set (WAMR_BUILD_INTERP 1) -set (WAMR_BUILD_AOT 1) -set (WAMR_BUILD_JIT 0) -set (WAMR_BUILD_LIBC_BUILTIN 1) -set (WAMR_BUILD_LIBC_WASI 0) -set (WAMR_BUILD_APP_FRAMEWORK 1) -set (WAMR_BUILD_APP_LIST WAMR_APP_BUILD_BASE) -``` - - - -Execute following command to build the WAMR SDK for a configuration profile: - -``` -cd wamr-sdk -./build_sdk.sh -n [profile name] -x [config file path] -``` - -The output directory structure of a SDK package with profile name "simple": - -``` -simple/ -├── app-sdk -│   ├── libc-builtin-sysroot -│   │   ├── include -│   │   └── share -│   └── wamr-app-framework -│   ├── include -│   │   ├── bi-inc -│   │   └── wa-inc -│   ├── lib -│   └── share -└── runtime-sdk - ├── include - │   └── bi-inc - └── lib -``` - - - -Like the WAMR samples, a project probably has its own pre-defined SDK configuration file. The project building script can call the `build_sdk.sh` by passing the configuration file name to the build_sdk.sh to generate its own WAMR SDK package. - - - -### Menu configuration for building SDK - -Menu configuration is supported for easy integration of runtime components and application libraries for the target architecture and platform. Run following command to start the menu config. - -``` -cd wamr-sdk -./build_sdk.sh -i -n [profile name] -``` - - The argument "-i" will make the command enter menu config mode as depicted below. - -wamr build menu configuration - -After the menu configuration is finished, the profile config file is saved and the building process is automatically started. When the building gets successful, the SDK package is generated under folder $wamr-sdk/out/{profile}, and the header files of configured components were copied into the SDK package. - - - -### Build WASM applications with APP-SDK - -The folder “**app-sdk**” under the profile output directory contains all the header files and WASM library for developing the WASM application. For C/C++ based WASM applications, the developers can use conventional cross-compilation procedure to build the WASM application. According to the profile selection of libc, following cmake toolchain files under folder [wamr-sdk/app](./app) are available for cross compiling WASM application: - -- ` wamr_toolchain.cmake` -- `wasi_toolchain.cmake` - - - -Refer to [build WASM applications](../doc/build_wasm_app.md) for the details. - - - -### Use Runtime SDK to build native application - -The output folder "**runtime-sdk**" contains all the header files and library files for integration with project native code. - -You can link the pre-built library: -``` cmake -link_directories(${SDK_DIR}/runtime-sdk/lib) -include_directories(${SDK_DIR}/runtime-sdk/include) -# ...... -target_link_libraries (your_target vmlib -lm -ldl -lpthread) -``` - -This method can also be used when you don't use cmake - -You can refer to this sample: [CMakeLists.txt](../samples/simple/CMakeLists.txt). - -> NOTE: If you are familiar with how to configure WAMR by cmake and don't want to build the SDK, you can set the related settings on the top of your `CMakeLists.txt`, then the `runtime_lib.cmake` will not load settings from the SDK. - - - -### Integrate WAMR without pre-built WAMR library - -Use the provided `runtime_lib.cmake` file: - -You can include `${WAMR_ROOT}/cmake/runtime_lib.cmake` in your project's `CMakeLists.txt` file: - -``` cmake -include (${WAMR_ROOT}/cmake/runtime_lib.cmake) -add_library (vmlib ${WAMR_RUNTIME_LIB_SOURCE}) -# ...... -target_link_libraries (your_target vmlib -lm -ldl -lpthread) -``` - -You can refer to to product-mini building for Linux: [`product-mini/platforms/linux/CMakeLists.txt`](../product-mini/platforms/linux/CMakeLists.txt). - -> +# Notice +`wamr-sdk` has been migrated to **[wamr-app-framework/wamr-sdk](https://github.com/bytecodealliance/wamr-app-framework/tree/main/wamr-sdk)**. +Only some necessary files that wasm app will use are retained here diff --git a/wamr-sdk/app/CMakeLists.txt b/wamr-sdk/app/CMakeLists.txt deleted file mode 100644 index 2e115cf4c..000000000 --- a/wamr-sdk/app/CMakeLists.txt +++ /dev/null @@ -1,98 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -cmake_minimum_required(VERSION 2.8) -project(app-framework) - -SET (CMAKE_C_FLAGS "-O3") - -if (NOT DEFINED WAMR_BUILD_SDK_PROFILE) - set (WAMR_BUILD_SDK_PROFILE "default") -endif () - -if (NOT DEFINED CONFIG_PATH) - set (CONFIG_PATH ${CMAKE_CURRENT_LIST_DIR}/../wamr_config_default.cmake) - message(STATUS "CONFIG_PATH set to ${CONFIG_PATH} ") -endif () - -if (NOT EXISTS "${CONFIG_PATH}") - message (FATAL_ERROR "${CONFIG_PATH} not exist") -endif () - -include(${CONFIG_PATH}) - -if (NOT DEFINED OUT_DIR) - set (OUT_DIR "${CMAKE_CURRENT_LIST_DIR}/../out/${WAMR_BUILD_SDK_PROFILE}") -endif () -set (APP_SDK_DIR "${OUT_DIR}/app-sdk") - -if (DEFINED EXTRA_SDK_INCLUDE_PATH) - message(STATUS, "EXTRA_SDK_INCLUDE_PATH = ${EXTRA_SDK_INCLUDE_PATH} ") - include_directories ( - ${EXTRA_SDK_INCLUDE_PATH} - ) -endif () - -if (WAMR_BUILD_LIBC_BUILTIN EQUAL 1) - set (SYSROOT_DIR "${APP_SDK_DIR}/libc-builtin-sysroot") - execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory ${SYSROOT_DIR}/include) - execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory ${SYSROOT_DIR}/share) - execute_process(COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_LIST_DIR}/libc-builtin-sysroot/share/defined-symbols.txt ${SYSROOT_DIR}/share) - execute_process(COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_LIST_DIR}/wamr_toolchain.cmake ${APP_SDK_DIR}) - execute_process( - COMMAND ${CMAKE_COMMAND} - -E copy_directory ${CMAKE_CURRENT_LIST_DIR}/libc-builtin-sysroot/include ${SYSROOT_DIR}/include - ) -else() - if (WAMR_BUILD_LIBC_WASI EQUAL 1) - set (SYSROOT_DIR "${APP_SDK_DIR}/wasi-sysroot") - message("sysroot: ${SYSROOT_DIR}") - execute_process(COMMAND ln -s ${WASI_SDK_DIR}/share/wasi-sysroot ${SYSROOT_DIR}) - execute_process(COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_LIST_DIR}/wasi_toolchain.cmake ${APP_SDK_DIR}/wamr_toolchain.cmake) - endif () -endif() - -if (WAMR_BUILD_APP_FRAMEWORK EQUAL 1) - message(WAMR_BUILD_APP_FRAMEWORK) - set (APP_FRAMEWORK_INCLUDE_TYPE "APP") - set (WAMR_APP_OUT_DIR "${APP_SDK_DIR}/wamr-app-framework") - - include(${CMAKE_CURRENT_LIST_DIR}/../../core/app-framework/app_framework.cmake) - - add_library(app_framework - ${WASM_APP_SOURCE_ALL} - ) - - add_custom_command( - TARGET app_framework POST_BUILD - - COMMAND ${CMAKE_COMMAND} -E make_directory ${WAMR_APP_OUT_DIR}/lib - COMMAND ${CMAKE_COMMAND} -E make_directory ${WAMR_APP_OUT_DIR}/include/wa-inc - COMMAND ${CMAKE_COMMAND} -E make_directory ${WAMR_APP_OUT_DIR}/share - COMMAND ${CMAKE_COMMAND} -E copy_directory ${WASM_APP_BI_INC_DIR} ${WAMR_APP_OUT_DIR}/include/bi-inc - COMMAND ${CMAKE_COMMAND} -E copy ${WASM_APP_BASE_DIR}/bh_platform.h ${WAMR_APP_OUT_DIR}/include - COMMAND ${CMAKE_COMMAND} -E copy ${WASM_APP_BASE_DIR}/wasm_app.h ${WAMR_APP_OUT_DIR}/include - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/*.a ${WAMR_APP_OUT_DIR}/lib - - # bi-inc folder should also copy into runtime-sdk - COMMAND ${CMAKE_COMMAND} -E make_directory ${OUT_DIR}/runtime-sdk/include - COMMAND ${CMAKE_COMMAND} -E copy_directory ${WASM_APP_BI_INC_DIR} ${OUT_DIR}/runtime-sdk/include/bi-inc - ) - - # If app-framework is enabled, add the undefined-symbol list to the toolchain file - if (WAMR_BUILD_LIBC_WASI EQUAL 1) - file (APPEND - ${APP_SDK_DIR}/wamr_toolchain.cmake - "SET (CMAKE_EXE_LINKER_FLAGS \"\${CMAKE_EXE_LINKER_FLAGS},--allow-undefined-file=\${CMAKE_CURRENT_LIST_DIR}/wamr-app-framework/share/defined-symbols.txt\" CACHE INTERNAL \"\")" - ) - endif () - - FOREACH (dir IN LISTS WASM_APP_WA_INC_DIR_LIST) - file (COPY ${dir} DESTINATION ${WAMR_APP_OUT_DIR}/include/) - ENDFOREACH (dir) - - if (DEFINED EXTRA_SDK_INCLUDE_PATH) - execute_process(COMMAND ${CMAKE_COMMAND} -E copy_directory ${EXTRA_SDK_INCLUDE_PATH} ${WAMR_APP_OUT_DIR}/include) - endif () - -endif() diff --git a/wamr-sdk/build_sdk.sh b/wamr-sdk/build_sdk.sh deleted file mode 100755 index 954584f69..000000000 --- a/wamr-sdk/build_sdk.sh +++ /dev/null @@ -1,254 +0,0 @@ -#!/bin/bash - -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -sdk_root=$(cd "$(dirname "$0")/" && pwd) -wamr_root_dir=${sdk_root}/.. -out_dir=${sdk_root}/out -profile_path=${out_dir}/profile.cmake -wamr_config_cmake_file="" -wasi_sdk_home="/opt/wasi-sdk" -# libc support, default builtin-libc -LIBC_SUPPORT="BUILTIN" -CM_DEXTRA_SDK_INCLUDE_PATH="" -CM_BUILD_TYPE="-DCMAKE_BUILD_TYPE=Release" -CM_TOOLCHAIN="" - -# menuconfig will pass options to this script -MENUCONFIG="" - -usage () -{ - echo "build.sh [options]" - echo " -n [profile name]" - echo " -x [config file path name]" - echo " -t [cmake toolchain file]" - echo " -e [extra include path], files under this path will be copied into SDK package" - echo " -c, clean" - echo " -d, debug mode" - echo " -i, enter menu config settings" - echo " -w [wasi-sdk installation path] it will be '/opt/wasi-sdk' if not set" - exit 1 -} - - -while getopts "e:x:n:t:icdw:" opt -do - case $opt in - n) - PROFILE=$OPTARG - ;; - t) - CM_TOOLCHAIN="-DCMAKE_TOOLCHAIN_FILE=$OPTARG" - ;; - x) - wamr_config_cmake_file=$OPTARG - ;; - e) - CM_DEXTRA_SDK_INCLUDE_PATH="-DEXTRA_SDK_INCLUDE_PATH=${OPTARG}" - ;; - c) - CLEAN="TRUE" - ;; - d) - CM_BUILD_TYPE="-DCMAKE_BUILD_TYPE=Debug" - ;; - i) - MENUCONFIG="TRUE" - ;; - w) - if [[ -n "${OPTARG}" ]]; then - wasi_sdk_home=$(realpath "${OPTARG}") - fi - ;; - ?) - echo "Unknown arg: $arg" - usage - exit 1 - ;; - esac -done - - -if [ ! -f "${wasi_sdk_home}/bin/clang" ]; then - echo "Can not find clang under \"${wasi_sdk_home}/bin\"." - exit 1 -else - echo "Found WASI_SDK HOME ${wasi_sdk_home}" -fi - - -echo "download dependent external repositories.." -${wamr_root_dir}/core/deps/download.sh -[ $? -eq 0 ] || exit $? - - - -if [ -z "$PROFILE" ]; then - PROFILE="default" - echo "PROFILE argument not set, using DEFAULT" - if [[ -z "$wamr_config_cmake_file" ]]; then - wamr_config_cmake_file=${sdk_root}/wamr_config_default.cmake - echo "use default config file: [$wamr_config_cmake_file]" - fi -fi - - -if [ ! -d "${out_dir}" ]; then - mkdir -p ${out_dir} -fi - -curr_profile_dir=${out_dir}/${PROFILE} -wamr_app_out_dir=${curr_profile_dir}/app-sdk/wamr-app-framework -sysroot_dir=${curr_profile_dir}/app-sdk/libc-builtin-sysroot - - -echo "CM_DEXTRA_SDK_INCLUDE_PATH=${CM_DEXTRA_SDK_INCLUDE_PATH}" - - -if [[ "$CLEAN" = "TRUE" ]]; then - rm -rf ${curr_profile_dir} -fi - - - -# cmake config file for wamr runtime: -# 1. use the users provided the config cmake file path. -# 2. if user set MENU CONFIG, enter menu config to generate -# menu_config.cmake in the profile output folder -# 3. If the menu_config.cmake is already in the profile folder, use it -# 4. Use the default config cmake file -# -if [[ -n "$wamr_config_cmake_file" ]]; then - if [[ ! -f $wamr_config_cmake_file ]]; then - echo "user given file not exist: ${wamr_config_cmake_file}" - exit 1 - fi - - echo "User config file: [${wamr_config_cmake_file}]" - -else - wamr_config_cmake_file=${out_dir}/wamr_config_${PROFILE}.cmake - # always rebuilt the sdk if user is not giving the config file - if [ -d ${curr_profile_dir} ]; then - rm -rf ${curr_profile_dir} - fi - - if [[ "$MENUCONFIG" = "TRUE" ]] || [[ ! -f $wamr_config_cmake_file ]]; then - echo "MENUCONFIG: [${wamr_config_cmake_file}]" - ./menuconfig.sh -x ${wamr_config_cmake_file} - [ $? -eq 0 ] || exit $? - else - echo "use existing config file: [$wamr_config_cmake_file]" - fi -fi - - -mkdir -p ${curr_profile_dir} -mkdir -p ${curr_profile_dir}/app-sdk -mkdir -p ${curr_profile_dir}/runtime-sdk - - -if [ "${BUILD_LLVM}" = "TRUE" ]; then - if [ ! -d "${wamr_root_dir}/core/deps/llvm" ]; then - echo -e "\n" - echo "###### build llvm (this will take a long time) #######" - echo "" - cd ${wamr_root_dir}/wamr-compiler - ./build_llvm.sh - fi -fi - -echo -e "\n\n" -echo "############## Start to build wasm app sdk ###############" - -# If wgl module is selected, check if the extra SDK include dir is passed by the args, prompt user to input if not. -app_all_selected=`cat ${wamr_config_cmake_file} | grep WAMR_APP_BUILD_ALL` -app_wgl_selected=`cat ${wamr_config_cmake_file} | grep WAMR_APP_BUILD_WGL` - -if [[ -n "${app_wgl_selected}" ]] || [[ -n "${app_all_selected}" ]]; then - if [ -z "${CM_DEXTRA_SDK_INCLUDE_PATH}" ]; then - echo -e "\033[31mWGL module require lvgl config files, please input the path to the lvgl SDK include path:\033[0m" - read -a extra_file_path - - if [[ -z "${extra_file_path}" ]] || [[ ! -d "${extra_file_path}" ]]; then - echo -e "\033[31mThe extra SDK path is empty\033[0m" - else - CM_DEXTRA_SDK_INCLUDE_PATH="-DEXTRA_SDK_INCLUDE_PATH=${extra_file_path}" - fi - fi - - cd ${wamr_root_dir}/core/app-framework/wgl/app - ./prepare_headers.sh -fi - -cd ${sdk_root}/app -rm -fr build && mkdir build -cd build - -out=`grep WAMR_BUILD_LIBC_WASI ${wamr_config_cmake_file} |grep 1` -if [ -n "$out" ]; then - LIBC_SUPPORT="WASI" -fi -if [ "${LIBC_SUPPORT}" = "WASI" ]; then - echo "using wasi toolchain" - cmake .. $CM_DEXTRA_SDK_INCLUDE_PATH \ - -DWAMR_BUILD_SDK_PROFILE=${PROFILE} \ - -DCONFIG_PATH=${wamr_config_cmake_file} \ - -DWASI_SDK_DIR="${wasi_sdk_home}" \ - -DCMAKE_TOOLCHAIN_FILE=../wasi_toolchain.cmake -else - echo "using builtin libc toolchain" - cmake .. $CM_DEXTRA_SDK_INCLUDE_PATH \ - -DWAMR_BUILD_SDK_PROFILE=${PROFILE} \ - -DCONFIG_PATH=${wamr_config_cmake_file} \ - -DWASI_SDK_DIR="${wasi_sdk_home}" \ - -DCMAKE_TOOLCHAIN_FILE=../wamr_toolchain.cmake -fi -[ $? -eq 0 ] || exit $? - -make -if (( $? == 0 )); then - echo -e "\033[32mSuccessfully built app-sdk under ${curr_profile_dir}/app-sdk\033[0m" -else - echo -e "\033[31mFailed to build app-sdk for wasm application\033[0m" - exit 1 -fi - -cd .. -rm -fr build -echo -e "\n\n" - - - -echo "############## Start to build runtime sdk ###############" -cd ${sdk_root}/runtime -rm -fr build-runtime-sdk && mkdir build-runtime-sdk -cd build-runtime-sdk -cmake .. $CM_DEXTRA_SDK_INCLUDE_PATH \ - -DWAMR_BUILD_SDK_PROFILE=${PROFILE} \ - -DCONFIG_PATH=${wamr_config_cmake_file} \ - $CM_TOOLCHAIN $CM_BUILD_TYPE -[ $? -eq 0 ] || exit $? -make - -if (( $? == 0 )); then - echo -e "\033[32mSuccessfully built runtime library under ${curr_profile_dir}/runtime-sdk/lib\033[0m" -else - echo -e "\033[31mFailed to build runtime sdk\033[0m" - exit 1 -fi - -APP=`grep WAMR_BUILD_APP_FRAMEWORK ${wamr_config_cmake_file} |grep 1` -if [ -n "$APP" ]; then - # Generate defined-symbol list for app-sdk - cd ${wamr_app_out_dir}/share - cat ${curr_profile_dir}/runtime-sdk/include/*.inl | egrep "^ *EXPORT_WASM_API *[(] *[a-zA-Z_][a-zA-Z0-9_]* *?[)]" | cut -d '(' -f2 | cut -d ')' -f1 > defined-symbols.txt -fi - - -cd .. -rm -fr build-runtime-sdk - -exit 0 diff --git a/wamr-sdk/menuconfig.sh b/wamr-sdk/menuconfig.sh deleted file mode 100755 index b2f6fa628..000000000 --- a/wamr-sdk/menuconfig.sh +++ /dev/null @@ -1,223 +0,0 @@ -#!/bin/bash - -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - - -usage () -{ - echo "menuconfig.sh [options]" - echo " -x [config file path name]" - exit 1 -} - - -while getopts "x:" opt -do - case $opt in - x) - wamr_config_cmake_file=$OPTARG - ;; - ?) - echo "Unknown arg: $arg" - usage - exit 1 - ;; - esac -done - - -if [ -z $wamr_config_cmake_file ]; then - usage - exit -fi - - -function set_build_target () { - target=$1 - - if [[ "${target}" = "X86_64" ]]; then - echo -e "set (WAMR_BUILD_TARGET \"X86_64\")" >> ${wamr_config_cmake_file} - elif [[ "${target}" = "X86_32" ]]; then - echo -e "set (WAMR_BUILD_TARGET \"X86_32\")" >> ${wamr_config_cmake_file} - else - echo "unknown build target." - exit 1 - fi -} - -function set_build_platform () { - platform=$1 - - if [[ "${platform}" = "linux" ]]; then - echo -e "set (WAMR_BUILD_PLATFORM \"linux\")" >> ${wamr_config_cmake_file} - # TODO: add other platforms - else - echo "${platform} platform currently not supported" - exit 1 - fi -} - -# input: array of selected exec modes [aot jit interp] -function set_exec_mode () { - modes=($1) - - for mode in ${modes[@]} - do - if [[ "$mode" = "aot" ]]; then - echo "set (WAMR_BUILD_AOT 1)" >> ${wamr_config_cmake_file} - elif [[ "$mode" = "jit" ]]; then - echo "set (WAMR_BUILD_JIT 1)" >> ${wamr_config_cmake_file} - BUILD_LLVM="TRUE" - elif [[ "$mode" = "interp" ]]; then - echo "set (WAMR_BUILD_INTERP 1)" >> ${wamr_config_cmake_file} - else - echo "unknown execute mode." - exit 1 - fi - done -} - -function set_libc_support () { - libc=$1 - - if [ "$libc" = "WASI" ]; then - echo "set (WAMR_BUILD_LIBC_WASI 1)" >> ${wamr_config_cmake_file} - else - echo "set (WAMR_BUILD_LIBC_BUILTIN 1)" >> ${wamr_config_cmake_file} - fi -} - -function set_app_framework () { - app_support=$1 - - if [ "$app_support" = "TRUE" ]; then - echo "set (WAMR_BUILD_APP_FRAMEWORK 1)" >> ${wamr_config_cmake_file} - fi -} - -# input: array of selected app modules -function set_app_module () { - modules=($1) - - for module in ${modules[*]} - do - if [ "${module}" = "all" ]; then - cmake_app_list="WAMR_APP_BUILD_ALL" - break - fi - - cmake_app_list="${cmake_app_list} WAMR_APP_BUILD_${module^^}" - done - - # APP module list - if [ -n "${cmake_app_list}" ]; then - echo "set (WAMR_BUILD_APP_LIST ${cmake_app_list# })" >> ${wamr_config_cmake_file} - fi -} - - - - -sdk_root=$(cd "$(dirname "$0")/" && pwd) -wamr_root=${sdk_root}/.. - -if [ ! `command -v menuconfig` ]; then - echo "Can't find kconfiglib python lib on this computer" - echo "Downloading it through pip" - echo "If this fails, you can try `pip install kconfiglib` to install it manually" - echo "Or download the repo from https://github.com/ulfalizer/Kconfiglib" - - pip install kconfiglib -fi - -if [ -f ".wamr_modules" ]; then - rm -f .wamr_modules -fi - -# get all modules under core/app-framework -for module in `ls ${wamr_root}/core/app-framework -F | grep "/$" | grep -v "base" | grep -v "app-native-shared" | grep -v "template"` -do - module=${module%*/} - echo "config APP_BUILD_${module^^}" >> .wamr_modules - echo " bool \"enable ${module}\"" >> .wamr_modules -done - -menuconfig Kconfig -[ $? -eq 0 ] || exit $? - -if [ ! -e ".config" ]; then - exit 0 -fi - -# parse platform -platform=`cat .config | grep "^CONFIG_PLATFORM"` -platform=${platform%*=y} -platform=${platform,,} -platform=${platform#config_platform_} - -# parse target -target=`cat .config | grep "^CONFIG_TARGET"` -target=${target%*=y} -target=${target#CONFIG_TARGET_} - -# parse execution mode -modes=`cat .config | grep "^CONFIG_EXEC"` -mode_list="" -for mode in ${modes} -do - mode=${mode%*=y} - mode=${mode#CONFIG_EXEC_} - mode_list="${mode_list} ${mode,,}" -done -if [ -z "${mode_list}" ]; then - echo "execution mode are not selected" - exit 1 -fi - -# parse libc support -libc=`cat .config | grep "^CONFIG_LIBC"` -libc=${libc%*=y} -if [ "${libc}" = "CONFIG_LIBC_WASI" ]; then - libc_support="WASI" -else - libc_support="BUILTIN" -fi - -# parse application framework options -app_option=`cat .config | grep "^CONFIG_APP_FRAMEWORK"` -app_option=${app_option%*=y} -app_option=${app_option#CONFIG_APP_FRAMEWORK_} - -if [ "${app_option}" != "DISABLE" ]; then - app_enable="TRUE" - - # Default components - if [ "${app_option}" = "DEFAULT" ]; then - app_list="base connection sensor" - # All components - elif [ "${app_option}" = "ALL" ]; then - app_list="all" - # Customize - elif [ "${app_option}" = "CUSTOM" ]; then - app_option=`cat .config | grep "^CONFIG_APP_BUILD"` - app_list="base" - for app in ${app_option} - do - app=${app%*=y} - app=${app#CONFIG_APP_BUILD_} - app_list="${app_list} ${app,,}" - done - fi -fi - -if [[ -f $wamr_config_cmake_file ]]; then - rm $wamr_config_cmake_file -fi - -set_build_target ${target} -set_build_platform ${platform} -set_exec_mode "${mode_list[*]}" -set_libc_support ${libc_support} -set_app_module "${app_list[*]}" -set_app_framework ${app_enable} diff --git a/wamr-sdk/runtime/CMakeLists.txt b/wamr-sdk/runtime/CMakeLists.txt deleted file mode 100644 index e8e5c363d..000000000 --- a/wamr-sdk/runtime/CMakeLists.txt +++ /dev/null @@ -1,58 +0,0 @@ -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -cmake_minimum_required(VERSION 2.8) -project(runtime-sdk) - -SET (CMAKE_C_FLAGS "-O3") -set (CMAKE_BUILD_TYPE Release) - -add_definitions(-DBH_MALLOC=wasm_runtime_malloc) -add_definitions(-DBH_FREE=wasm_runtime_free) - -if (NOT DEFINED WAMR_BUILD_SDK_PROFILE) - set (WAMR_BUILD_SDK_PROFILE "default") -endif () - -if (NOT DEFINED CONFIG_PATH) - set (CONFIG_PATH ${CMAKE_CURRENT_LIST_DIR}/../wamr_config_default.cmake) -endif () - -if (NOT EXISTS "${CONFIG_PATH}") - message (FATAL_ERROR "${CONFIG_PATH} not exist") -endif () - -include(${CONFIG_PATH}) - -if (NOT DEFINED OUT_DIR) - set (OUT_DIR "${CMAKE_CURRENT_LIST_DIR}/../out/${WAMR_BUILD_SDK_PROFILE}") -endif () -set (RUNTIME_SDK_DIR "${OUT_DIR}/runtime-sdk") - -include(${CMAKE_CURRENT_LIST_DIR}/../../build-scripts/runtime_lib.cmake) - -# build vmlib -add_library(vmlib ${WAMR_RUNTIME_LIB_SOURCE}) - -# copy vmlib.a to ${SDK_ROOT}/out/runtime-sdk/lib -add_custom_command( - TARGET vmlib POST_BUILD - - COMMAND ${CMAKE_COMMAND} -E make_directory ${RUNTIME_SDK_DIR}/lib - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/*.a ${RUNTIME_SDK_DIR}/lib -) - -# copy headers to ${SDK_ROOT}/out/runtime-sdk/include -FOREACH (header IN LISTS RUNTIME_LIB_HEADER_LIST) - execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory ${RUNTIME_SDK_DIR}/include) - execute_process(COMMAND ${CMAKE_COMMAND} -E copy "${header}" ${RUNTIME_SDK_DIR}/include) -ENDFOREACH (header) - - -if (DEFINED EXTRA_SDK_INCLUDE_PATH) - execute_process(COMMAND ${CMAKE_COMMAND} -E copy_directory ${EXTRA_SDK_INCLUDE_PATH} ${RUNTIME_SDK_DIR}/include) -endif () - -# config.h is not needed when building a runtime product with pre-built library -# erase the file to avoid compile error -file (WRITE ${RUNTIME_SDK_DIR}/include/config.h "") diff --git a/wamr-sdk/wamr_config_default.cmake b/wamr-sdk/wamr_config_default.cmake deleted file mode 100644 index 98cc6e9cf..000000000 --- a/wamr-sdk/wamr_config_default.cmake +++ /dev/null @@ -1,12 +0,0 @@ -set (WAMR_BUILD_PLATFORM "linux") -set (WAMR_BUILD_TARGET X86_64) -set (WAMR_BUILD_INTERP 1) -set (WAMR_BUILD_AOT 1) -set (WAMR_BUILD_JIT 0) -set (WAMR_BUILD_LIBC_BUILTIN 1) -set (WAMR_BUILD_LIBC_WASI 0) -set (WAMR_BUILD_APP_FRAMEWORK 1) -set (WAMR_BUILD_APP_LIST WAMR_APP_BUILD_BASE) - -# -# set (EXTRA_SDK_INCLUDE_PATH "") diff --git a/wamr-sdk/wamr_config_macos_release.cmake b/wamr-sdk/wamr_config_macos_release.cmake deleted file mode 100644 index cbcec2d6f..000000000 --- a/wamr-sdk/wamr_config_macos_release.cmake +++ /dev/null @@ -1,40 +0,0 @@ -set (WAMR_BUILD_PLATFORM "darwin") -set (WAMR_BUILD_TARGET X86_64) - -# Running mode -set (WAMR_BUILD_AOT 1) -set (WAMR_BUILD_INTERP 1) -set (WAMR_BUILD_JIT 0) - -# Runtime SDK Features -set (WAMR_BUILD_CUSTOM_NAME_SECTION 0) -set (WAMR_BUILD_DEBUG_INTERP 0) -set (WAMR_BUILD_DEBUG_AOT 0) -set (WAMR_BUILD_DUMP_CALL_STACK 0) -set (WAMR_BUILD_LIBC_UVWASI 0) -set (WAMR_BUILD_LIBC_EMCC 0) -set (WAMR_BUILD_LIB_RATS 0) -set (WAMR_BUILD_LOAD_CUSTOM_SECTION 0) -set (WAMR_BUILD_MEMORY_PROFILING 0) -set (WAMR_BUILD_MINI_LOADER 0) -set (WAMR_BUILD_MULTI_MODULE 0) -set (WAMR_BUILD_PERF_PROFILING 0) -set (WAMR_BUILD_SPEC_TEST 0) -set (WAMR_BUILD_BULK_MEMORY 1) -set (WAMR_BUILD_LIB_PTHREAD 1) -set (WAMR_BUILD_LIB_PTHREAD_SEMAPHORE 1) -set (WAMR_BUILD_LIBC_BUILTIN 1) -set (WAMR_BUILD_LIBC_WASI 1) -set (WAMR_BUILD_REF_TYPES 1) -set (WAMR_BUILD_SIMD 1) -set (WAMR_BUILD_SHARED_MEMORY 1) -set (WAMR_BUILD_TAIL_CALL 1) -set (WAMR_BUILD_THREAD_MGR 1) - -# APP SDK Features -set (WAMR_BUILD_APP_FRAMEWORK 1) -set (WAMR_BUILD_APP_LIST WAMR_APP_BUILD_BASE) - -# -# set (EXTRA_SDK_INCLUDE_PATH "") - diff --git a/wamr-sdk/wamr_config_ubuntu_release.cmake b/wamr-sdk/wamr_config_ubuntu_release.cmake deleted file mode 100644 index 8919c4e41..000000000 --- a/wamr-sdk/wamr_config_ubuntu_release.cmake +++ /dev/null @@ -1,40 +0,0 @@ -set (WAMR_BUILD_PLATFORM "linux") -set (WAMR_BUILD_TARGET X86_64) - -# Running mode -set (WAMR_BUILD_AOT 1) -set (WAMR_BUILD_INTERP 1) -set (WAMR_BUILD_JIT 0) - -# Runtime SDK Features -set (WAMR_BUILD_CUSTOM_NAME_SECTION 0) -set (WAMR_BUILD_DEBUG_INTERP 0) -set (WAMR_BUILD_DEBUG_AOT 0) -set (WAMR_BUILD_DUMP_CALL_STACK 0) -set (WAMR_BUILD_LIBC_UVWASI 0) -set (WAMR_BUILD_LIBC_EMCC 0) -set (WAMR_BUILD_LIB_RATS 0) -set (WAMR_BUILD_LOAD_CUSTOM_SECTION 0) -set (WAMR_BUILD_MEMORY_PROFILING 0) -set (WAMR_BUILD_MINI_LOADER 0) -set (WAMR_BUILD_MULTI_MODULE 0) -set (WAMR_BUILD_PERF_PROFILING 0) -set (WAMR_BUILD_SPEC_TEST 0) -set (WAMR_BUILD_BULK_MEMORY 1) -set (WAMR_BUILD_LIB_PTHREAD 1) -set (WAMR_BUILD_LIB_PTHREAD_SEMAPHORE 1) -set (WAMR_BUILD_LIBC_BUILTIN 1) -set (WAMR_BUILD_LIBC_WASI 1) -set (WAMR_BUILD_REF_TYPES 1) -set (WAMR_BUILD_SIMD 1) -set (WAMR_BUILD_SHARED_MEMORY 1) -set (WAMR_BUILD_TAIL_CALL 1) -set (WAMR_BUILD_THREAD_MGR 1) - -# APP SDK Features -set (WAMR_BUILD_APP_FRAMEWORK 1) -set (WAMR_BUILD_APP_LIST WAMR_APP_BUILD_BASE) - -# -# set (EXTRA_SDK_INCLUDE_PATH "") -