diff --git a/.github/ISSUE_TEMPLATE/blank_issue.md b/.github/ISSUE_TEMPLATE/blank_issue.md new file mode 100644 index 000000000..57febe7d5 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/blank_issue.md @@ -0,0 +1,5 @@ +--- +name: Blank Issue +about: Create a blank issue. +title: '' +--- diff --git a/.github/ISSUE_TEMPLATE/improvement.md b/.github/ISSUE_TEMPLATE/improvement.md new file mode 100644 index 000000000..ffdf0906f --- /dev/null +++ b/.github/ISSUE_TEMPLATE/improvement.md @@ -0,0 +1,28 @@ +--- +name: Improvement +about: A feature request or code improvement. +title: '' +labels: '' +assignees: '' +--- + +Thanks for filing a feature request! Please fill out the TODOs below. + +#### Feature + +TODO: Brief description of the feature/improvement you'd like to see in WAMR + +#### Benefit + +TODO: What is the value of adding this in WAMR? What problems does it solve? + +#### Implementation + +TODO: Do you have an implementation plan, and/or ideas for data structures or +algorithms to use? + +#### Alternatives + +TODO: What are the alternative implementation approaches or alternative ways to +solve the problem that this feature would solve? How do these alternatives +compare to this proposal? diff --git a/.github/ISSUE_TEMPLATE/report_bug.md b/.github/ISSUE_TEMPLATE/report_bug.md new file mode 100644 index 000000000..d3058c9ca --- /dev/null +++ b/.github/ISSUE_TEMPLATE/report_bug.md @@ -0,0 +1,36 @@ +--- +name: WAMR bug or defect report +about: Report a bug or defect in WAMR +title: '' +--- + +Thanks for filing a bug or defect report! Please fill out the TODOs below. + +### Subject of the issue + +Describe the bug or defect here. + +### Test case + +Upload the related wasm file, wast file or the source files if you can. + +### Your environment + +* Host OS +* WAMR version, platform, cpu architecture, running mode, etc. + +### Steps to reproduce + +Tell us how to reproduce this bug or defect. + +### Expected behavior + +Tell us what should happen + +### Actual behavior + +Tell us what happens instead + +### Extra Info + +Anything else you'd like to add? diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..0676cf741 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,35 @@ +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +version: 2 +updates: + +- package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + +- package-ecosystem: "docker" + directory: "/.devcontainer" + schedule: + interval: "weekly" + +- package-ecosystem: "devcontainers" + directory: "/" + schedule: + interval: "weekly" + +- package-ecosystem: "pip" + directory: "/build-scripts" + schedule: + interval: "weekly" + +- package-ecosystem: "pip" + directory: "/language-bindings/python/wasm-c-api" + schedule: + interval: "weekly" + +- package-ecosystem: "pip" + directory: "/language-bindings/python/wamr-api" + schedule: + interval: "weekly" diff --git a/.github/scripts/fetch_and_compare_version.py b/.github/scripts/fetch_and_compare_version.py index ac206cade..ad9e53a0a 100644 --- a/.github/scripts/fetch_and_compare_version.py +++ b/.github/scripts/fetch_and_compare_version.py @@ -42,9 +42,12 @@ def fetch_version_from_code(): def fetch_latest_git_tag(): - list_tag_cmd = ( - 'git tag --list WAMR-*.*.* --sort=committerdate --format="%(refname:short)"' - ) + """ + Get the most recent tag from the HEAD, + if it's main branch, it should be the latest release tag. + if it's release/x.x.x branch, it should be the latest release tag of the branch. + """ + list_tag_cmd = "git describe --tags --abbrev=0 HEAD" p = subprocess.run(shlex.split(list_tag_cmd), capture_output=True, check=True) all_tags = p.stdout.decode().strip() diff --git a/.github/workflows/build_llvm_libraries.yml b/.github/workflows/build_llvm_libraries.yml index 18b90e568..67eaf614d 100644 --- a/.github/workflows/build_llvm_libraries.yml +++ b/.github/workflows/build_llvm_libraries.yml @@ -33,10 +33,16 @@ jobs: - name: checkout uses: actions/checkout@v4 - - name: install dependencies + - name: install dependencies for non macos-14 + if: inputs.os != 'macos-14' run: /usr/bin/env python3 -m pip install -r requirements.txt working-directory: build-scripts + - name: install dependencies for macos-14 + if: inputs.os == 'macos-14' + run: /usr/bin/env python3 -m pip install -r requirements.txt --break-system-packages + working-directory: build-scripts + - name: retrive the last commit ID id: get_last_commit run: echo "last_commit=$(GH_TOKEN=${{ secrets.GITHUB_TOKEN }} /usr/bin/env python3 ./build_llvm.py --llvm-ver)" >> $GITHUB_OUTPUT diff --git a/.github/workflows/build_wamr_lldb.yml b/.github/workflows/build_wamr_lldb.yml index 3e1e10ffd..03474c53e 100644 --- a/.github/workflows/build_wamr_lldb.yml +++ b/.github/workflows/build_wamr_lldb.yml @@ -82,9 +82,7 @@ jobs: - name: install utils macos if: steps.lldb_build_cache.outputs.cache-hit != 'true' && contains(inputs.runner, 'macos') run: | - brew remove swig - brew install swig@4.1 cmake ninja libedit - brew link --overwrite swig@4.1 + brew install swig cmake ninja libedit sudo rm -rf /Library/Developer/CommandLineTools - name: install utils ubuntu diff --git a/.github/workflows/build_wamr_sdk.yml b/.github/workflows/build_wamr_sdk.yml index f4ca9afd4..519bf9636 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 @@ -46,16 +58,24 @@ jobs: sudo rm ${basename} sudo mv wasi-sdk-* wasi-sdk + - name: download dependencies + run: | + cd ./wamr-app-framework/deps + ./download.sh + working-directory: wamr-sdk + - 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 +83,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 +93,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/build_wamr_vscode_ext.yml b/.github/workflows/build_wamr_vscode_ext.yml index b91f054cf..322ba1c06 100644 --- a/.github/workflows/build_wamr_vscode_ext.yml +++ b/.github/workflows/build_wamr_vscode_ext.yml @@ -21,7 +21,7 @@ jobs: - uses: actions/checkout@v4 - name: Use Node.js 16.x - uses: actions/setup-node@v3 + uses: actions/setup-node@v4 with: node-version: 16.x diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 000000000..5126153d1 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,114 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +name: "CodeQL" + +on: + #pull_request: + # types: + # - opened + # branches: '*' + #push: + # branches: [ "main" ] + # midnight UTC + schedule: + - cron: '0 0 * * *' + # allow to be triggered manually + workflow_dispatch: + +jobs: + analyze: + if: github.repository == 'bytecodealliance/wasm-micro-runtime' + name: Analyze + # Runner size impacts CodeQL analysis time. To learn more, please see: + # - https://gh.io/recommended-hardware-resources-for-running-codeql + # - https://gh.io/supported-runners-and-hardware-resources + # - https://gh.io/using-larger-runners + # Consider using larger runners for possible analysis time improvements. + runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-20.04' }} + timeout-minutes: ${{ (matrix.language == 'swift' && 120) || 360 }} + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: [ 'cpp' ] + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby', 'swift' ] + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + with: + submodules: recursive + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v3 + with: + languages: ${{ matrix.language }} + + # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs + # queries: security-extended,security-and-quality + queries: security-and-quality + + # Command-line programs to run using the OS shell. + # See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun + + # If the Autobuild fails above, remove it and uncomment the following three lines. + # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. + + - run: | + ./.github/workflows/codeql_buildscript.sh + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v3 + with: + category: "/language:${{matrix.language}}" + upload: false + id: step1 + + # Filter out rules with low severity or high false positve rate + # Also filter out warnings in third-party code + - name: Filter out unwanted errors and warnings + uses: advanced-security/filter-sarif@v1 + with: + patterns: | + -**:cpp/path-injection + -**:cpp/world-writable-file-creation + -**:cpp/poorly-documented-function + -**:cpp/potentially-dangerous-function + -**:cpp/use-of-goto + -**:cpp/integer-multiplication-cast-to-long + -**:cpp/comparison-with-wider-type + -**:cpp/leap-year/* + -**:cpp/ambiguously-signed-bit-field + -**:cpp/suspicious-pointer-scaling + -**:cpp/suspicious-pointer-scaling-void + -**:cpp/unsigned-comparison-zero + -**/cmake*/Modules/** + input: ${{ steps.step1.outputs.sarif-output }}/cpp.sarif + output: ${{ steps.step1.outputs.sarif-output }}/cpp.sarif + + - name: Upload CodeQL results to code scanning + uses: github/codeql-action/upload-sarif@v3 + with: + sarif_file: ${{ steps.step1.outputs.sarif-output }} + category: "/language:${{matrix.language}}" + + - name: Upload CodeQL results as an artifact + if: success() || failure() + uses: actions/upload-artifact@v4 + with: + name: codeql-results + path: ${{ steps.step1.outputs.sarif-output }} + retention-days: 10 + + - name: Fail if an error is found + run: | + ./.github/workflows/codeql_fail_on_error.py \ + ${{ steps.step1.outputs.sarif-output }}/cpp.sarif diff --git a/.github/workflows/codeql_buildscript.sh b/.github/workflows/codeql_buildscript.sh new file mode 100755 index 000000000..ed717734e --- /dev/null +++ b/.github/workflows/codeql_buildscript.sh @@ -0,0 +1,277 @@ +#!/usr/bin/env bash + +sudo apt update + +sudo apt install -y build-essential cmake g++-multilib libgcc-11-dev lib32gcc-11-dev ccache ninja-build ccache + +WAMR_DIR=${PWD} + +# TODO: use pre-built llvm binary to build wamrc to +# avoid static code analysing for llvm +: ' +# build wamrc +cd ${WAMR_DIR}/wamr-compiler +./build_llvm.sh +rm -fr build && mkdir build && cd build +cmake .. +make -j +if [[ $? != 0 ]]; then + echo "Failed to build wamrc!" + exit 1; +fi +' + +# build iwasm with default features enabled +cd ${WAMR_DIR}/product-mini/platforms/linux +rm -fr build && mkdir build && cd build +cmake .. +make -j +if [[ $? != 0 ]]; then + echo "Failed to build iwasm with default features enabled!" + exit 1; +fi + +# build iwasm with default features enabled on x86_32 +cd ${WAMR_DIR}/product-mini/platforms/linux +rm -fr build && mkdir build && cd build +cmake .. -DWAMR_BUILD_TARGET=X86_32 +make -j +if [[ $? != 0 ]]; then + echo "Failed to build iwasm with default features enabled on x86_32!" + exit 1; +fi + +# build iwasm with classic interpreter enabled +cd ${WAMR_DIR}/product-mini/platforms/linux +rm -rf build && mkdir build && cd build +cmake .. -DCMAKE_BUILD_TYPE=Debug -DWAMR_BUILD_FAST_INTERP=0 +make -j +if [[ $? != 0 ]]; then + echo "Failed to build iwasm with classic interpreter enabled!" + exit 1; +fi + +# build iwasm with extra features enabled +cd ${WAMR_DIR}/product-mini/platforms/linux +rm -fr build && mkdir build && cd build +cmake .. -DCMAKE_BUILD_TYPE=Debug \ + -DWAMR_BUILD_LIB_PTHREAD=1 -DWAMR_BUILD_LIB_PTHREAD_SEMAPHORE=1 \ + -DWAMR_BUILD_MULTI_MODULE=1 -DWAMR_BUILD_SIMD=1 \ + -DWAMR_BUILD_TAIL_CALL=1 -DWAMR_BUILD_REF_TYPES=1 \ + -DWAMR_BUILD_CUSTOM_NAME_SECTION=1 -DWAMR_BUILD_MEMORY_PROFILING=1 \ + -DWAMR_BUILD_PERF_PROFILING=1 -DWAMR_BUILD_DUMP_CALL_STACK=1 \ + -DWAMR_BUILD_LOAD_CUSTOM_SECTION=1 +make -j +if [[ $? != 0 ]]; then + echo "Failed to build wamrc iwasm with extra features enabled!" + exit 1; +fi + +# build iwasm with global heap pool enabled +cd ${WAMR_DIR}/product-mini/platforms/linux +rm -fr build && mkdir build && cd build +cmake .. -DCMAKE_BUILD_TYPE=Debug \ + -DWAMR_BUILD_ALLOC_WITH_USER_DATA=1 \ + -DWAMR_DISABLE_STACK_HW_BOUND_CHECK=1 \ + -DWAMR_BUILD_GLOBAL_HEAP_POOL=1 \ + -DWAMR_BUILD_GLOBAL_HEAP_SIZE=131072 +make -j +if [[ $? != 0 ]]; then + echo "Failed to build iwasm with global heap pool enabled!" + exit 1; +fi + +# build iwasm with wasi-threads enabled +cd ${WAMR_DIR}/product-mini/platforms/linux +rm -fr build && mkdir build && cd build +cmake .. -DCMAKE_BUILD_TYPE=Debug -DWAMR_BUILD_LIB_WASI_THREADS=1 +make -j +if [[ $? != 0 ]]; then + echo "Failed to build iwasm with wasi-threads enabled!" + exit 1; +fi + +# build iwasm with GC enabled +cd ${WAMR_DIR}/product-mini/platforms/linux +rm -rf build && mkdir build && cd build +cmake .. -DCMAKE_BUILD_TYPE=Debug -DWAMR_BUILD_GC=1 +make -j +if [[ $? != 0 ]]; then + echo "Failed to build iwasm with GC enabled!" + exit 1; +fi + +# build iwasm with exception handling enabled +cd ${WAMR_DIR}/product-mini/platforms/linux +rm -rf build && mkdir build && cd build +cmake .. -DCMAKE_BUILD_TYPE=Debug -DWAMR_BUILD_EXCE_HANDLING=1 +make -j +if [[ $? != 0 ]]; then + echo "Failed to build iwasm with exception handling enabled!" + exit 1; +fi + +# build iwasm with memory64 enabled +cd ${WAMR_DIR}/product-mini/platforms/linux +rm -rf build && mkdir build && cd build +cmake .. -DCMAKE_BUILD_TYPE=Debug -DWAMR_BUILD_MEMORY64=1 +make -j +if [[ $? != 0 ]]; then + echo "Failed to build iwasm with memory64 enabled!" + exit 1; +fi + +# build iwasm with hardware boundary check disabled +cd ${WAMR_DIR}/product-mini/platforms/linux +rm -rf build && mkdir build && cd build +cmake .. -DCMAKE_BUILD_TYPE=Debug -DWAMR_DISABLE_HW_BOUND_CHECK=1 +make -j +if [[ $? != 0 ]]; then + echo "Failed to build iwasm with hardware boundary check disabled!" + exit 1; +fi + +# build iwasm with quick AOT entry disabled +cd ${WAMR_DIR}/product-mini/platforms/linux +rm -rf build && mkdir build && cd build +cmake .. -DCMAKE_BUILD_TYPE=Debug -DWAMR_BUILD_QUICK_AOT_ENTRY=0 +make -j +if [[ $? != 0 ]]; then + echo "Failed to build iwasm with quick AOT entry disabled!" + exit 1; +fi + +# build iwasm with wakeup of blocking operations disabled +cd ${WAMR_DIR}/product-mini/platforms/linux +rm -rf build && mkdir build && cd build +cmake .. -DCMAKE_BUILD_TYPE=Debug -DWAMR_DISABLE_WAKEUP_BLOCKING_OP=1 +make -j +if [[ $? != 0 ]]; then + echo "Failed to build iwasm with wakeup of blocking operations disabled!" + exit 1; +fi + +# build iwasm with module instance context disabled +cd ${WAMR_DIR}/product-mini/platforms/linux +rm -rf build && mkdir build && cd build +cmake .. -DCMAKE_BUILD_TYPE=Debug -DWAMR_BUILD_MODULE_INST_CONTEXT=0 \ + -DWAMR_BUILD_LIBC_BUILTIN=0 -DWAMR_BUILD_LIBC_WASI=0 +make -j +if [[ $? != 0 ]]; then + echo "Failed to build iwasm with module instance context disabled!" + exit 1; +fi + +# build iwasm with libc-uvwasi enabled +cd ${WAMR_DIR}/product-mini/platforms/linux +rm -fr build && mkdir build && cd build +cmake .. -DCMAKE_BUILD_TYPE=Debug -DWAMR_BUILD_LIBC_UVWASI=1 +make -j +if [[ $? != 0 ]]; then + echo "Failed to build iwasm with libc-uvwasi enabled!" + exit 1; +fi + +# build iwasm with fast jit lazy mode enabled +cd ${WAMR_DIR}/product-mini/platforms/linux +rm -rf build && mkdir build && cd build +cmake .. -DCMAKE_BUILD_TYPE=Debug -DWAMR_BUILD_FAST_JIT=1 -DWAMR_BUILD_FAST_JIT_DUMP=1 +make -j +if [[ $? != 0 ]]; then + echo "Failed to build iwasm with fast jit lazy mode enabled!" + exit 1; +fi + +# build iwasm with fast jit eager mode enabled +cd ${WAMR_DIR}/product-mini/platforms/linux +rm -rf build && mkdir build && cd build +cmake .. -DCMAKE_BUILD_TYPE=Debug -DWAMR_BUILD_FAST_JIT=1 -DWAMR_BUILD_FAST_JIT_DUMP=1 +make -j +if [[ $? != 0 ]]; then + echo "Failed to build iwasm with fast jit eager mode enabled!" + exit 1; +fi + +# TODO: use pre-built llvm binary to build llvm-jit and multi-tier-jit +: ' +# build iwasm with llvm jit lazy mode enabled +cd ${WAMR_DIR}/product-mini/platforms/linux +rm -rf build && mkdir build && cd build +cmake .. -DCMAKE_BUILD_TYPE=Debug -DWAMR_BUILD_JIT=1 +make -j +if [[ $? != 0 ]]; then + echo "Failed to build llvm jit lazy mode enabled!" + exit 1; +fi + +# build iwasm with llvm jit eager mode enabled +cd ${WAMR_DIR}/product-mini/platforms/linux +rm -rf build && mkdir build && cd build +cmake .. -DCMAKE_BUILD_TYPE=Debug -DWAMR_BUILD_JIT=1 -DWAMR_BUILD_LAZY_JIT=0 +make -j +if [[ $? != 0 ]]; then + echo "Failed to build llvm jit eager mode enabled!" + exit 1; +fi + +# build iwasm with multi-tier jit enabled +cd ${WAMR_DIR}/product-mini/platforms/linux +rm -rf build && mkdir build && cd build +cmake .. -DCMAKE_BUILD_TYPE=Debug -DWAMR_BUILD_FAST_JIT=1 -DWAMR_BUILD_JIT=1 \ + -DWAMR_BUILD_FAST_JIT_DUMP=1 +make -j +if [[ $? != 0 ]]; then + echo "Failed to build iwasm with multi-tier jit enabled!" + exit 1; +fi +' + +# build iwasm with wasm mini-loader enabled +cd ${WAMR_DIR}/product-mini/platforms/linux +rm -rf build && mkdir build && cd build +cmake .. -DCMAKE_BUILD_TYPE=Debug -DWAMR_BUILD_MINI_LOADER=1 +make -j +if [[ $? != 0 ]]; then + echo "Failed to build with wasm mini-loader enabled!" + exit 1; +fi + +# build iwasm with source debugging enabled +cd ${WAMR_DIR}/product-mini/platforms/linux +rm -rf build && mkdir build && cd build +cmake .. -DCMAKE_BUILD_TYPE=Debug -DWAMR_BUILD_DEBUG_INTERP=1 -DWAMR_BUILD_DEBUG_AOT=1 +make -j +if [[ $? != 0 ]]; then + echo "Failed to build iwasm with source debugging enabled!" + exit 1; +fi + +# build iwasm with AOT static PGO enabled +cd ${WAMR_DIR}/product-mini/platforms/linux +rm -rf build && mkdir build && cd build +cmake .. -DCMAKE_BUILD_TYPE=Debug -DWAMR_BUILD_STATIC_PGO=1 +make -j +if [[ $? != 0 ]]; then + echo "Failed to build iwasm with AOT static PGO enabled!" + exit 1; +fi + +# build iwasm with configurable bounds checks enabled +cd ${WAMR_DIR}/product-mini/platforms/linux +rm -rf build && mkdir build && cd build +cmake .. -DCMAKE_BUILD_TYPE=Debug -DWAMR_CONFIGUABLE_BOUNDS_CHECKS=1 +make -j +if [[ $? != 0 ]]; then + echo "Failed to build iwasm with configurable bounds checks enabled!" + exit 1; +fi + +# build iwasm with linux perf support enabled +cd ${WAMR_DIR}/product-mini/platforms/linux/ +rm -rf build && mkdir build && cd build +cmake .. -DCMAKE_BUILD_TYPE=Debug -DWAMR_BUILD_LINUX_PERF=1 +make -j +if [[ $? != 0 ]]; then + echo "Failed to build iwasm with linux perf support enabled!" + exit 1; +fi diff --git a/.github/workflows/codeql_fail_on_error.py b/.github/workflows/codeql_fail_on_error.py new file mode 100755 index 000000000..29791742b --- /dev/null +++ b/.github/workflows/codeql_fail_on_error.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 + +import json +import sys + +# Return whether SARIF file contains error-level results +def codeql_sarif_contain_error(filename): + with open(filename, 'r') as f: + s = json.load(f) + + for run in s.get('runs', []): + rules_metadata = run['tool']['driver']['rules'] + if not rules_metadata: + rules_metadata = run['tool']['extensions'][0]['rules'] + + for res in run.get('results', []): + if 'ruleIndex' in res: + rule_index = res['ruleIndex'] + elif 'rule' in res and 'index' in res['rule']: + rule_index = res['rule']['index'] + else: + continue + try: + rule_level = rules_metadata[rule_index]['defaultConfiguration']['level'] + except IndexError as e: + print(e, rule_index, len(rules_metadata)) + else: + if rule_level == 'error': + return True + return False + +if __name__ == "__main__": + if codeql_sarif_contain_error(sys.argv[1]): + sys.exit(1) diff --git a/.github/workflows/compilation_on_android_ubuntu.yml b/.github/workflows/compilation_on_android_ubuntu.yml index f88c9be67..6b2a1a114 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: @@ -67,6 +65,7 @@ env: WASI_TEST_OPTIONS: "-s wasi_certification -w" WAMR_COMPILER_TEST_OPTIONS: "-s wamr_compiler -S -b -P" GC_TEST_OPTIONS: "-s spec -G -b -P" + MEMORY64_TEST_OPTIONS: "-s spec -W -b -P" jobs: build_llvm_libraries_on_ubuntu_2204: @@ -146,6 +145,7 @@ jobs: "-DWAMR_BUILD_SIMD=1", "-DWAMR_BUILD_TAIL_CALL=1", "-DWAMR_DISABLE_HW_BOUND_CHECK=1", + "-DWAMR_BUILD_MEMORY64=1", ] os: [ubuntu-22.04] platform: [android, linux] @@ -204,11 +204,32 @@ jobs: make_options_feature: "-DWAMR_BUILD_MINI_LOADER=1" - make_options_run_mode: $MULTI_TIER_JIT_BUILD_OPTIONS make_options_feature: "-DWAMR_BUILD_MINI_LOADER=1" - # Fast-JIT and Multi-Tier-JIT mode don't support android(X86-32) + # Memory64 only on CLASSIC INTERP mode, and only on 64-bit platform + - make_options_feature: "-DWAMR_BUILD_MEMORY64=1" + platform: android + - make_options_run_mode: $AOT_BUILD_OPTIONS + make_options_feature: "-DWAMR_BUILD_MEMORY64=1" + - make_options_run_mode: $FAST_INTERP_BUILD_OPTIONS + make_options_feature: "-DWAMR_BUILD_MEMORY64=1" + - make_options_run_mode: $FAST_JIT_BUILD_OPTIONS + make_options_feature: "-DWAMR_BUILD_MEMORY64=1" + - make_options_run_mode: $LLVM_LAZY_JIT_BUILD_OPTIONS + make_options_feature: "-DWAMR_BUILD_MEMORY64=1" + - make_options_run_mode: $LLVM_EAGER_JIT_BUILD_OPTIONS + make_options_feature: "-DWAMR_BUILD_MEMORY64=1" + - make_options_run_mode: $MULTI_TIER_JIT_BUILD_OPTIONS + make_options_feature: "-DWAMR_BUILD_MEMORY64=1" + # Fast-JIT and Multi-Tier-JIT mode don't support android - make_options_run_mode: $FAST_JIT_BUILD_OPTIONS platform: android - make_options_run_mode: $MULTI_TIER_JIT_BUILD_OPTIONS platform: android + # LLVM JIT pre-built binary wasn't compiled by Android NDK + # and isn't available for android + - make_options_run_mode: $LLVM_LAZY_JIT_BUILD_OPTIONS + platform: android + - make_options_run_mode: $LLVM_EAGER_JIT_BUILD_OPTIONS + platform: android include: - os: ubuntu-22.04 llvm_cache_key: ${{ needs.build_llvm_libraries_on_ubuntu_2204.outputs.cache_key }} @@ -234,13 +255,23 @@ jobs: if: endsWith(matrix.make_options_run_mode, '_JIT_BUILD_OPTIONS') && (steps.retrieve_llvm_libs.outputs.cache-hit != 'true') run: echo "::error::can not get prebuilt llvm libraries" && exit 1 - - name: Build iwasm + - name: Build iwasm for linux + if: matrix.platform == 'linux' run: | mkdir build && cd build cmake .. ${{ matrix.make_options_run_mode }} ${{ matrix.make_options_feature }} cmake --build . --config Release --parallel 4 working-directory: product-mini/platforms/${{ matrix.platform }} + - name: Build iwasm for android + if: matrix.platform == 'android' + run: | + mkdir build && cd build + cmake .. ${{ matrix.make_options_run_mode }} ${{ matrix.make_options_feature }} \ + -DWAMR_BUILD_TARGET=X86_64 + cmake --build . --config Release --parallel 4 + working-directory: product-mini/platforms/${{ matrix.platform }} + - name: Build and run unit tests run: | mkdir build-unittests && cd build-unittests @@ -358,14 +389,14 @@ jobs: cd /opt sudo wget ${{ matrix.wasi_sdk_release }} sudo tar -xzf wasi-sdk-*.tar.gz - sudo mv wasi-sdk-20.0 wasi-sdk + sudo ln -sf wasi-sdk-20.0 wasi-sdk - name: download and install wabt run: | cd /opt sudo wget ${{ matrix.wabt_release }} sudo tar -xzf wabt-1.0.31-*.tar.gz - sudo mv wabt-1.0.31 wabt + sudo ln -sf wabt-1.0.31 wabt - name: Get LLVM libraries id: retrieve_llvm_libs uses: actions/cache@v4 @@ -430,13 +461,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 @@ -457,6 +481,16 @@ jobs: ./build.sh ./run.sh + - name: Build Sample [debug-tools] + run: | + cd samples/debug-tools + mkdir build && cd build + cmake .. + cmake --build . --config Debug --parallel 4 + ./iwasm wasm-apps/trap.wasm | grep "#" > call_stack.txt + ./iwasm wasm-apps/trap.aot | grep "#" > call_stack_aot.txt + bash -x ../symbolicate.sh + test: needs: [ @@ -486,6 +520,7 @@ jobs: $THREADS_TEST_OPTIONS, $WASI_TEST_OPTIONS, $GC_TEST_OPTIONS, + $MEMORY64_TEST_OPTIONS, ] wasi_sdk_release: [ @@ -524,19 +559,30 @@ jobs: test_option: $GC_TEST_OPTIONS - running_mode: "multi-tier-jit" test_option: $GC_TEST_OPTIONS + # aot, fast-interp, fast-jit, llvm-jit, multi-tier-jit don't support Memory64 + - running_mode: "aot" + test_option: $MEMORY64_TEST_OPTIONS + - running_mode: "fast-interp" + test_option: $MEMORY64_TEST_OPTIONS + - running_mode: "fast-jit" + test_option: $MEMORY64_TEST_OPTIONS + - running_mode: "jit" + test_option: $MEMORY64_TEST_OPTIONS + - running_mode: "multi-tier-jit" + test_option: $MEMORY64_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' + if: matrix.test_option == '$GC_TEST_OPTIONS' || matrix.test_option == '$MEMORY64_TEST_OPTIONS' with: ocaml-compiler: 4.13 - name: Set-up Ocamlbuild - if: matrix.test_option == '$GC_TEST_OPTIONS' - run: opam install ocamlbuild dune + if: matrix.test_option == '$GC_TEST_OPTIONS' || matrix.test_option == '$MEMORY64_TEST_OPTIONS' + run: opam install ocamlbuild dune menhir - name: download and install wasi-sdk if: matrix.test_option == '$WASI_TEST_OPTIONS' @@ -555,7 +601,6 @@ jobs: make -j AR=/opt/wasi-sdk/bin/llvm-ar NM=/opt/wasi-sdk/bin/llvm-nm CC=/opt/wasi-sdk/bin/clang THREAD_MODEL=posix echo "SYSROOT_PATH=$PWD/sysroot" >> $GITHUB_ENV - - name: set env variable(if llvm are used) if: matrix.running_mode == 'aot' || matrix.running_mode == 'jit' || matrix.running_mode == 'multi-tier-jit' run: echo "USE_LLVM=true" >> $GITHUB_ENV @@ -601,13 +646,13 @@ jobs: - name: run tests timeout-minutes: 30 - if: matrix.test_option != '$GC_TEST_OPTIONS' + if: matrix.test_option != '$GC_TEST_OPTIONS' && matrix.test_option != '$MEMORY64_TEST_OPTIONS' run: ./test_wamr.sh ${{ matrix.test_option }} -t ${{ matrix.running_mode }} working-directory: ./tests/wamr-test-suites - - name: run gc tests + - name: run gc or memory64 tests timeout-minutes: 20 - if: matrix.test_option == '$GC_TEST_OPTIONS' + if: matrix.test_option == '$GC_TEST_OPTIONS' || matrix.test_option == '$MEMORY64_TEST_OPTIONS' run: | eval $(opam env) ./test_wamr.sh ${{ matrix.test_option }} -t ${{ matrix.running_mode }} @@ -659,6 +704,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 9d352fbcf..ec0943234 100644 --- a/.github/workflows/compilation_on_macos.yml +++ b/.github/workflows/compilation_on_macos.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: @@ -244,7 +242,7 @@ jobs: run: | cmake -S . -B build ${{ matrix.make_options }} cmake --build build --config Release --parallel 4 - ctest --test-dir build + ctest --test-dir build --output-on-failure working-directory: samples/wasm-c-api build_samples_others: @@ -275,14 +273,14 @@ jobs: cd /opt sudo wget ${{ matrix.wasi_sdk_release }} sudo tar -xzf wasi-sdk-*.tar.gz - sudo mv wasi-sdk-20.0 wasi-sdk + sudo ln -sf wasi-sdk-20.0 wasi-sdk - name: download and install wabt run: | cd /opt sudo wget ${{ matrix.wabt_release }} sudo tar -xzf wabt-1.0.31-*.tar.gz - sudo mv wabt-1.0.31 wabt + sudo ln -sf wabt-1.0.31 wabt - name: Build Sample [basic] run: | @@ -348,7 +346,7 @@ jobs: cmake .. cmake --build . --config Release --parallel 4 working-directory: wamr-compiler - + - name: Build Sample [wasi-threads] run: | cd samples/wasi-threads @@ -371,3 +369,13 @@ jobs: cd samples/terminate ./build.sh ./run.sh + + - name: Build Sample [debug-tools] + run: | + cd samples/debug-tools + mkdir build && cd build + cmake .. + cmake --build . --config Debug --parallel 4 + ./iwasm wasm-apps/trap.wasm | grep "#" > call_stack.txt + ./iwasm wasm-apps/trap.aot | grep "#" > call_stack_aot.txt + bash -x ../symbolicate.sh 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 787b66725..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: 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/create_tag.yml b/.github/workflows/create_tag.yml index 27eee2acf..5480592a9 100644 --- a/.github/workflows/create_tag.yml +++ b/.github/workflows/create_tag.yml @@ -32,8 +32,22 @@ jobs: - name: prepare id: preparation run: | - # show latest 3 versions - git tag --list WAMR-*.*.* --sort=committerdate --format="%(refname:short)" | tail -n 3 + # show latest 3 versions on the branch that create release + # Set the initial commit to the head of the branch + commit="HEAD" + # + # Loop to get the three most recent tags + for i in {1..3} + do + # Get the most recent tag reachable from the current commit + tag=$(git describe --tags --abbrev=0 $commit) + + # Print the tag + echo "$tag" + + # Move to the commit before the found tag to find the next tag in the next iteration + commit=$(git rev-list -n 1 $tag^) + done # compare latest git tag and semantic version definition result=$(python3 ./.github/scripts/fetch_and_compare_version.py) echo "script result is ${result}" diff --git a/.github/workflows/nightly_run.yml b/.github/workflows/nightly_run.yml index 8b9a0ed5e..4b62d110a 100644 --- a/.github/workflows/nightly_run.yml +++ b/.github/workflows/nightly_run.yml @@ -8,12 +8,12 @@ on: types: - opened - synchronize - # running nightly pipeline if you're changing it + # running nightly pipeline if you're changing it # stress tests are run only in nightly at the moment, so running them in they are changed paths: - ".github/workflows/nightly_run.yml" - "core/iwasm/libraries/lib-wasi-threads/stress-test/**" - + # midnight UTC schedule: - cron: "0 0 * * *" @@ -54,7 +54,7 @@ jobs: with: os: "ubuntu-22.04" arch: "X86" - + build_wamrc: needs: [ @@ -65,7 +65,7 @@ jobs: matrix: include: - os: ubuntu-20.04 - llvm_cache_key: ${{ needs.build_llvm_libraries_on_ubuntu_2004.outputs.cache_key }} + llvm_cache_key: ${{ needs.build_llvm_libraries_on_ubuntu_2004.outputs.cache_key }} steps: - name: checkout uses: actions/checkout@v4 @@ -130,6 +130,7 @@ jobs: "-DWAMR_BUILD_SIMD=1", "-DWAMR_BUILD_TAIL_CALL=1", "-DWAMR_DISABLE_HW_BOUND_CHECK=1", + "-DWAMR_BUILD_MEMORY64=1", ] os: [ubuntu-20.04] platform: [android, linux] @@ -188,11 +189,32 @@ jobs: make_options_feature: "-DWAMR_BUILD_MINI_LOADER=1" - make_options_run_mode: $MULTI_TIER_JIT_BUILD_OPTIONS make_options_feature: "-DWAMR_BUILD_MINI_LOADER=1" - # Fast-JIT and Multi-Tier-JIT mode don't support android(X86-32) + # Memory64 only on CLASSIC INTERP mode, and only on 64-bit platform + - make_options_feature: "-DWAMR_BUILD_MEMORY64=1" + platform: android + - make_options_run_mode: $AOT_BUILD_OPTIONS + make_options_feature: "-DWAMR_BUILD_MEMORY64=1" + - make_options_run_mode: $FAST_INTERP_BUILD_OPTIONS + make_options_feature: "-DWAMR_BUILD_MEMORY64=1" + - make_options_run_mode: $FAST_JIT_BUILD_OPTIONS + make_options_feature: "-DWAMR_BUILD_MEMORY64=1" + - make_options_run_mode: $LLVM_LAZY_JIT_BUILD_OPTIONS + make_options_feature: "-DWAMR_BUILD_MEMORY64=1" + - make_options_run_mode: $LLVM_EAGER_JIT_BUILD_OPTIONS + make_options_feature: "-DWAMR_BUILD_MEMORY64=1" + - make_options_run_mode: $MULTI_TIER_JIT_BUILD_OPTIONS + make_options_feature: "-DWAMR_BUILD_MEMORY64=1" + # Fast-JIT and Multi-Tier-JIT mode don't support android - make_options_run_mode: $FAST_JIT_BUILD_OPTIONS platform: android - make_options_run_mode: $MULTI_TIER_JIT_BUILD_OPTIONS platform: android + # LLVM JIT pre-built binary wasn't compiled by Android NDK + # and isn't available for android + - make_options_run_mode: $LLVM_LAZY_JIT_BUILD_OPTIONS + platform: android + - make_options_run_mode: $LLVM_EAGER_JIT_BUILD_OPTIONS + platform: android include: - os: ubuntu-20.04 llvm_cache_key: ${{ needs.build_llvm_libraries_on_ubuntu_2004.outputs.cache_key }} @@ -219,13 +241,23 @@ jobs: if: endsWith(matrix.make_options_run_mode, '_JIT_BUILD_OPTIONS') && (steps.retrieve_llvm_libs.outputs.cache-hit != 'true') run: echo "::error::can not get prebuilt llvm libraries" && exit 1 - - name: Build iwasm + - name: Build iwasm for linux + if: matrix.platform == 'linux' run: | mkdir build && cd build cmake .. ${{ matrix.make_options_run_mode }} ${{ matrix.make_options_feature }} cmake --build . --config Release --parallel 4 working-directory: product-mini/platforms/${{ matrix.platform }} + - name: Build iwasm for android + if: matrix.platform == 'android' + run: | + mkdir build && cd build + cmake .. ${{ matrix.make_options_run_mode }} ${{ matrix.make_options_feature }} \ + -DWAMR_BUILD_TARGET=X86_64 + cmake --build . --config Release --parallel 4 + working-directory: product-mini/platforms/${{ matrix.platform }} + build_iwasm_linux_gcc4_8: runs-on: ubuntu-latest container: @@ -255,6 +287,7 @@ jobs: "-DWAMR_BUILD_SIMD=1", "-DWAMR_BUILD_TAIL_CALL=1", "-DWAMR_DISABLE_HW_BOUND_CHECK=1", + "-DWAMR_BUILD_MEMORY64=1", ] exclude: # uncompatiable feature and platform @@ -283,6 +316,11 @@ jobs: # MINI_LOADER only on INTERP mode - make_options_run_mode: $FAST_JIT_BUILD_OPTIONS make_options_feature: "-DWAMR_BUILD_MINI_LOADER=1" + # Memory64 only on CLASSIC INTERP mode + - make_options_run_mode: $FAST_INTERP_BUILD_OPTIONS + make_options_feature: "-DWAMR_BUILD_MEMORY64=1" + - make_options_run_mode: $FAST_JIT_BUILD_OPTIONS + make_options_feature: "-DWAMR_BUILD_MEMORY64=1" steps: - name: checkout uses: actions/checkout@v3 @@ -421,13 +459,13 @@ jobs: cd /opt sudo wget ${{ matrix.wasi_sdk_release }} sudo tar -xzf wasi-sdk-*.tar.gz - sudo mv wasi-sdk-20.0 wasi-sdk + sudo ln -sf wasi-sdk-20.0 wasi-sdk - name: download and install wabt run: | cd /opt sudo wget ${{ matrix.wabt_release }} sudo tar -xzf wabt-1.0.31-*.tar.gz - sudo mv wabt-1.0.31 wabt + sudo ln -sf wabt-1.0.31 wabt - name: Get LLVM libraries id: retrieve_llvm_libs @@ -489,12 +527,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: | @@ -611,7 +643,7 @@ jobs: sudo tar -xzf wasi-sdk-*.tar.gz sudo mv wasi-sdk-20.0 wasi-sdk - # It is a temporary solution until new wasi-sdk that includes bug fixes is released + # It is a temporary solution until new wasi-sdk that includes bug fixes is released - name: build wasi-libc from source if: matrix.test_option == '$WASI_TEST_OPTIONS' run: | @@ -632,7 +664,9 @@ jobs: run: echo "TEST_ON_X86_32=true" >> $GITHUB_ENV - name: set additional tsan options - run: echo "TSAN_OPTIONS=suppressions=$PWD/tsan_suppressions.txt" >> $GITHUB_ENV + run: | + echo "TSAN_OPTIONS=suppressions=$PWD/tsan_suppressions.txt" >> $GITHUB_ENV + sudo sysctl vm.mmap_rnd_bits=28 working-directory: tests/wamr-test-suites #only download llvm libraries in jit and aot mode 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/.gitignore b/.gitignore index 7275e3bef..b85dd392c 100644 --- a/.gitignore +++ b/.gitignore @@ -14,13 +14,9 @@ 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..2c83d6674 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,13 +54,13 @@ 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 -[LICENSE](./core/deps/llvm/llvm/LICENCE.txt) +[LICENSE](./LICENCE.txt) ### wasm-c-api @@ -76,11 +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) - -### wac - -[LICENSE](./tests/wamr-test-suites/spec-test-script/LICENSE) +[LICENSE](https://github.com/bytecodealliance/wamr-app-framework/blob/main/samples/gui/wasm-runtime-wgl/src/platform/zephyr/LICENSE) ### libuv diff --git a/CMakeLists.txt b/CMakeLists.txt index 1c8799494..0ffba05a4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,6 +3,11 @@ cmake_minimum_required (VERSION 3.0) +if(ESP_PLATFORM) + include (${COMPONENT_DIR}/build-scripts/esp-idf/wamr/CMakeLists.txt) + return() +endif() + project (iwasm) set (CMAKE_VERBOSE_MAKEFILE OFF) @@ -151,7 +156,7 @@ if (WAMR_BUILD_WASM_CACHE EQUAL 1) endif () if (MINGW) - target_link_libraries (iwasm_shared -lWs2_32) + target_link_libraries (iwasm_shared INTERFACE -lWs2_32 -lwsock32) endif () install (TARGETS iwasm_shared LIBRARY DESTINATION lib) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9210b3deb..0e04101d2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -27,7 +27,7 @@ We Use Github Flow, So All Code Changes Happen Through Pull Requests. Pull reque Coding Style =============================== Please use [K&R](https://en.wikipedia.org/wiki/Indentation_style#K.26R) coding style, such as 4 spaces for indentation rather than tabs etc. -We suggest use Eclipse like IDE or stable coding format tools to make your code compliant to K&R format. +We suggest using VS Code like IDE or stable coding format tools, like clang-format, to make your code compliant to the customized format(in .clang-format). Report bugs =================== diff --git a/README.md b/README.md index 31156b9cc..5a53536a5 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++ @@ -35,25 +35,24 @@ WebAssembly Micro Runtime (WAMR) is a lightweight standalone WebAssembly (Wasm) - [XIP (Execution In Place) support](./doc/xip.md), ref to [document](./doc/xip.md) - [Berkeley/Posix Socket support](./doc/socket_api.md), ref to [document](./doc/socket_api.md) and [sample](./samples/socket-api) - [Multi-tier JIT](./product-mini#linux) and [Running mode control](https://bytecodealliance.github.io/wamr.dev/blog/introduction-to-wamr-running-modes/) -- Language bindings: [Go](./language-bindings/go/README.md), [Python](./language-bindings/python/README.md) +- Language bindings: [Go](./language-bindings/go/README.md), [Python](./language-bindings/python/README.md), [Rust](./language-bindings/rust/README.md) ### Wasm post-MVP features - [wasm-c-api](https://github.com/WebAssembly/wasm-c-api), ref to [document](doc/wasm_c_api.md) and [sample](samples/wasm-c-api) - [128-bit SIMD](https://github.com/WebAssembly/simd), ref to [samples/workload](samples/workload) - [Reference Types](https://github.com/WebAssembly/reference-types), ref to [document](doc/ref_types.md) and [sample](samples/ref-types) -- [Non-trapping float-to-int conversions](https://github.com/WebAssembly/nontrapping-float-to-int-conversions) -- [Sign-extension operators](https://github.com/WebAssembly/sign-extension-ops), [Bulk memory operations](https://github.com/WebAssembly/bulk-memory-operations) -- [Multi-value](https://github.com/WebAssembly/multi-value), [Tail-call](https://github.com/WebAssembly/tail-call), [Shared memory](https://github.com/WebAssembly/threads/blob/main/proposals/threads/Overview.md#shared-linear-memory) +- [Bulk memory operations](https://github.com/WebAssembly/bulk-memory-operations), [Shared memory](https://github.com/WebAssembly/threads/blob/main/proposals/threads/Overview.md#shared-linear-memory), [Memory64](https://github.com/WebAssembly/memory64) +- [Tail-call](https://github.com/WebAssembly/tail-call), [Garbage Collection](https://github.com/WebAssembly/gc), [Exception Handling](https://github.com/WebAssembly/exception-handling) ### Supported architectures and platforms -The WAMR VMcore supports the following architectures: +The WAMR VMcore supports the following architectures: - X86-64, X86-32 - ARM, THUMB (ARMV7 Cortex-M7 and Cortex-A15 are tested) - AArch64 (Cortex-A57 and Cortex-A53 are tested) - RISCV64, RISCV32 (RISC-V LP64 and RISC-V LP64D are tested) - XTENSA, MIPS, ARC -The following platforms are supported, click each link below for how to build iwasm on that platform. Refer to [WAMR porting guide](./doc/port_wamr.md) for how to port WAMR to a new platform. +The following platforms are supported, click each link below for how to build iwasm on that platform. Refer to [WAMR porting guide](./doc/port_wamr.md) for how to port WAMR to a new platform. - [Linux](./product-mini/README.md#linux), [Linux SGX (Intel Software Guard Extension)](./doc/linux_sgx.md), [MacOS](./product-mini/README.md#macos), [Android](./product-mini/README.md#android), [Windows](./product-mini/README.md#windows), [Windows (MinGW)](./product-mini/README.md#mingw) - [Zephyr](./product-mini/README.md#zephyr), [AliOS-Things](./product-mini/README.md#alios-things), [VxWorks](./product-mini/README.md#vxworks), [NuttX](./product-mini/README.md#nuttx), [RT-Thread](./product-mini/README.md#RT-Thread), [ESP-IDF](./product-mini/README.md#esp-idf) @@ -67,7 +66,8 @@ The following platforms are supported, click each link below for how to build iw - [Build Wasm applications](./doc/build_wasm_app.md) - [Port WAMR to a new platform](./doc/port_wamr.md) - [VS Code development container](./doc/devcontainer.md) -- [Samples](./samples) and [Benchmarks](./tests/benchmarks) +- [Samples](./samples) and [Benchmarks](./tests/benchmarks) +- [End-user APIs documentation](https://bytecodealliance.github.io/wamr.dev/apis/) 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 773ff2837..8422b060b 100644 --- a/build-scripts/config_common.cmake +++ b/build-scripts/config_common.cmake @@ -248,6 +248,15 @@ if (WAMR_BUILD_SHARED_MEMORY EQUAL 1) else () add_definitions (-DWASM_ENABLE_SHARED_MEMORY=0) endif () +if (WAMR_BUILD_MEMORY64 EQUAL 1) + # if native is 32-bit or cross-compiled to 32-bit + if (NOT WAMR_BUILD_TARGET MATCHES ".*64.*") + message (FATAL_ERROR "-- Memory64 is only available on the 64-bit platform/target") + endif() + add_definitions (-DWASM_ENABLE_MEMORY64=1) + set (WAMR_DISABLE_HW_BOUND_CHECK 1) + message (" Memory64 memory enabled") +endif () if (WAMR_BUILD_THREAD_MGR EQUAL 1) message (" Thread manager enabled") endif () @@ -430,6 +439,10 @@ if (WAMR_BUILD_WASI_NN EQUAL 1) if (DEFINED WAMR_BUILD_WASI_NN_EXTERNAL_DELEGATE_PATH) add_definitions (-DWASM_WASI_NN_EXTERNAL_DELEGATE_PATH="${WAMR_BUILD_WASI_NN_EXTERNAL_DELEGATE_PATH}") endif () + if (WAMR_BUILD_WASI_EPHEMERAL_NN EQUAL 1) + message (" WASI-NN: WASI-Ephemeral-NN enabled") + add_definitions (-DWASM_ENABLE_WASI_EPHEMERAL_NN=1) + endif() endif () if (WAMR_BUILD_ALLOC_WITH_USER_DATA EQUAL 1) add_definitions(-DWASM_MEM_ALLOC_WITH_USER_DATA=1) @@ -525,3 +538,19 @@ else () # Disable quick aot/jit entries for interp and fast-jit add_definitions (-DWASM_ENABLE_QUICK_AOT_ENTRY=0) endif () +if (WAMR_BUILD_AOT EQUAL 1) + if (NOT DEFINED WAMR_BUILD_AOT_INTRINSICS) + # Enable aot intrinsics by default + set (WAMR_BUILD_AOT_INTRINSICS 1) + endif () + if (WAMR_BUILD_AOT_INTRINSICS EQUAL 1) + add_definitions (-DWASM_ENABLE_AOT_INTRINSICS=1) + message (" AOT intrinsics enabled") + else () + add_definitions (-DWASM_ENABLE_AOT_INTRINSICS=0) + message (" AOT intrinsics disabled") + endif () +else () + # Disable aot intrinsics for interp, fast-jit and llvm-jit + add_definitions (-DWASM_ENABLE_AOT_INTRINSICS=0) +endif () diff --git a/build-scripts/esp-idf/wamr/CMakeLists.txt b/build-scripts/esp-idf/wamr/CMakeLists.txt index 5ac04ddc9..47ccb055f 100644 --- a/build-scripts/esp-idf/wamr/CMakeLists.txt +++ b/build-scripts/esp-idf/wamr/CMakeLists.txt @@ -2,7 +2,7 @@ # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # Set WAMR's build options -if("${IDF_TARGET}" STREQUAL "esp32c3") +if("${IDF_TARGET}" STREQUAL "esp32c3" OR "${IDF_TARGET}" STREQUAL "esp32c6") set(WAMR_BUILD_TARGET "RISCV32") else() set(WAMR_BUILD_TARGET "XTENSA") diff --git a/build-scripts/runtime_lib.cmake b/build-scripts/runtime_lib.cmake index 832629c01..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 () @@ -88,13 +82,6 @@ if (WAMR_BUILD_GC EQUAL 1) set (WAMR_BUILD_REF_TYPES 1) 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) -endif () - if (WAMR_BUILD_LIBC_BUILTIN EQUAL 1) include (${IWASM_DIR}/libraries/libc-builtin/libc_builtin.cmake) endif () @@ -200,9 +187,6 @@ set (source_all ${IWASM_COMPL_SOURCE} ${IWASM_FAST_JIT_SOURCE} ${IWASM_GC_SOURCE} - ${WASM_APP_LIB_SOURCE_ALL} - ${NATIVE_INTERFACE_SOURCE} - ${APP_MGR_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/README.md b/core/app-mgr/README.md deleted file mode 100644 index 7a561897e..000000000 --- a/core/app-mgr/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# Remote application management - -The WAMR application manager supports [remote application management](../../core/app-mgr) from the host environment or the cloud through any physical communications such as TCP, UPD, UART, BLE, etc. Its modular design makes it able to support application management for different managed runtimes. - -The tool [host_tool](../../test-tools/host-tool) communicates to the WAMR app manager for installing/uninstalling the WASM applications on companion chip from the host system. And the [IoT App Store Demo](../../test-tools/IoT-APP-Store-Demo/) shows the conception of remotely managing the device applications from the cloud. - - - 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 deleted file mode 100644 index cee62e906..000000000 --- a/core/app-mgr/app-manager/module_wasm_app.c +++ /dev/null @@ -1,1747 +0,0 @@ -/* - * Copyright (C) 2019 Intel Corporation. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "module_wasm_app.h" - -#include "native_interface.h" /* for request_t type */ -#include "app_manager_host.h" -#include "bh_platform.h" -#include "bi-inc/attr_container.h" -#include "coap_ext.h" -#include "event.h" -#include "watchdog.h" -#include "runtime_lib.h" -#if WASM_ENABLE_INTERP != 0 -#include "wasm.h" -#endif -#if WASM_ENABLE_AOT != 0 -#include "aot_export.h" -#endif - -/* clang-format off */ -#if WASM_ENABLE_INTERP != 0 || WASM_ENABLE_JIT != 0 -/* Wasm bytecode file 4 version bytes */ -static uint8 wasm_bytecode_version[4] = { - (uint8)0x01, - (uint8)0x00, - (uint8)0x00, - (uint8)0x00 -}; -#endif - -#if WASM_ENABLE_AOT != 0 -/* Wasm aot file 4 version bytes */ -static uint8 wasm_aot_version[4] = { - (uint8)0x02, - (uint8)0x00, - (uint8)0x00, - (uint8)0x00 -}; -#endif -/* clang-format on */ - -static union { - int a; - char b; -} __ue = { .a = 1 }; - -#define is_little_endian() (__ue.b == 1) -/* Wasm App Install Request Receiving Phase */ -typedef enum wasm_app_install_req_recv_phase_t { - Phase_Req_Ver, - Phase_Req_Action, - Phase_Req_Fmt, - Phase_Req_Mid, - Phase_Req_Sender, - Phase_Req_Url_Len, - Phase_Req_Payload_Len, /* payload is wasm app binary */ - Phase_Req_Url, - - /* Magic phase */ - Phase_App_Magic, - -#if WASM_ENABLE_INTERP != 0 || WASM_ENABLE_JIT != 0 - /* Phases of wasm bytecode file */ - Phase_Wasm_Version, - Phase_Wasm_Section_Type, - Phase_Wasm_Section_Size, - Phase_Wasm_Section_Content, -#endif - -#if WASM_ENABLE_AOT != 0 - /* Phases of wasm AOT file */ - Phase_AOT_Version, - Phase_AOT_Section_ID, - Phase_AOT_Section_Size, - Phase_AOT_Section_Content -#endif -} wasm_app_install_req_recv_phase_t; - -/* Message for insall wasm app */ -typedef struct install_wasm_app_msg_t { - uint8 request_version; - uint8 request_action; - uint16 request_fmt; - uint32 request_mid; - uint32 request_sender; - uint16 request_url_len; - uint32 wasm_app_size; /* payload size is just wasm app binary size */ - char *request_url; - wasm_app_file_t app_file; - int app_file_magic; -} install_wasm_app_msg_t; - -/* Wasm App Install Request Receive Context */ -typedef struct wasm_app_install_req_recv_ctx_t { - wasm_app_install_req_recv_phase_t phase; - int size_in_phase; - install_wasm_app_msg_t message; - int total_received_size; -} wasm_app_install_req_recv_ctx_t; - -/* Current wasm app install request receive context */ -static wasm_app_install_req_recv_ctx_t recv_ctx; - -static bool -wasm_app_module_init(void); - -static bool -wasm_app_module_install(request_t *msg); - -static bool -wasm_app_module_uninstall(request_t *msg); - -static void -wasm_app_module_watchdog_kill(module_data *module_data); - -static bool -wasm_app_module_handle_host_url(void *queue_msg); - -static module_data * -wasm_app_module_get_module_data(void *inst); - -static bool -wasm_app_module_on_install_request_byte_arrive(uint8 ch, int request_total_size, - int *received_size); - -static bool -module_wasm_app_handle_install_msg(install_wasm_app_msg_t *message); - -#if WASM_ENABLE_INTERP != 0 || WASM_ENABLE_JIT != 0 -static void -destroy_all_wasm_sections(wasm_section_list_t sections); - -static void -destroy_part_wasm_sections(wasm_section_list_t *p_sections, - uint8 *section_types, int section_cnt); -#endif - -#if WASM_ENABLE_AOT != 0 -static void -destroy_all_aot_sections(aot_section_list_t sections); - -static void -destroy_part_aot_sections(aot_section_list_t *p_sections, uint8 *section_types, - int section_cnt); -#endif - -#define Max_Msg_Callback 10 -int g_msg_type[Max_Msg_Callback] = { 0 }; -message_type_handler_t g_msg_callbacks[Max_Msg_Callback] = { 0 }; - -#define Max_Cleanup_Callback 10 -static resource_cleanup_handler_t g_cleanup_callbacks[Max_Cleanup_Callback] = { - 0 -}; - -module_interface wasm_app_module_interface = { - wasm_app_module_init, - wasm_app_module_install, - wasm_app_module_uninstall, - wasm_app_module_watchdog_kill, - wasm_app_module_handle_host_url, - wasm_app_module_get_module_data, - wasm_app_module_on_install_request_byte_arrive -}; - -#if WASM_ENABLE_INTERP == 0 -static unsigned -align_uint(unsigned v, unsigned b) -{ - unsigned m = b - 1; - return (v + m) & ~m; -} -#endif - -static void -exchange_uint32(uint8 *p_data) -{ - uint8 value = *p_data; - *p_data = *(p_data + 3); - *(p_data + 3) = value; - - value = *(p_data + 1); - *(p_data + 1) = *(p_data + 2); - *(p_data + 2) = value; -} - -static wasm_function_inst_t -app_manager_lookup_function(const wasm_module_inst_t module_inst, - const char *name, const char *signature) -{ - wasm_function_inst_t func; - - func = wasm_runtime_lookup_function(module_inst, name, signature); - if (!func && name[0] == '_') - func = wasm_runtime_lookup_function(module_inst, name + 1, signature); - return func; -} - -static void -app_instance_queue_callback(void *queue_msg, void *arg) -{ - uint32 argv[2]; - wasm_function_inst_t func_onRequest, func_onTimer; - - wasm_module_inst_t inst = (wasm_module_inst_t)arg; - module_data *m_data = app_manager_get_module_data(Module_WASM_App, inst); - wasm_data *wasm_app_data; - int message_type; - - bh_assert(m_data); - wasm_app_data = (wasm_data *)m_data->internal_data; - message_type = bh_message_type(queue_msg); - - if (message_type < BASE_EVENT_MAX) { - switch (message_type) { - case RESTFUL_REQUEST: - { - request_t *request = (request_t *)bh_message_payload(queue_msg); - int size; - char *buffer; - int32 buffer_offset; - - app_manager_printf("App %s got request, url %s, action %d\n", - m_data->module_name, request->url, - request->action); - - func_onRequest = app_manager_lookup_function( - inst, "_on_request", "(i32i32)"); - if (!func_onRequest) { - app_manager_printf("Cannot find function onRequest\n"); - break; - } - - buffer = pack_request(request, &size); - if (buffer == NULL) - break; - - buffer_offset = - wasm_runtime_module_dup_data(inst, buffer, size); - if (buffer_offset == 0) { - const char *exception = wasm_runtime_get_exception(inst); - if (exception) { - app_manager_printf( - "Got exception running wasm code: %s\n", exception); - wasm_runtime_clear_exception(inst); - } - free_req_resp_packet(buffer); - break; - } - - free_req_resp_packet(buffer); - - argv[0] = (uint32)buffer_offset; - argv[1] = (uint32)size; - - if (!wasm_runtime_call_wasm(wasm_app_data->exec_env, - func_onRequest, 2, argv)) { - const char *exception = wasm_runtime_get_exception(inst); - bh_assert(exception); - app_manager_printf("Got exception running wasm code: %s\n", - exception); - wasm_runtime_clear_exception(inst); - wasm_runtime_module_free(inst, buffer_offset); - break; - } - - wasm_runtime_module_free(inst, buffer_offset); - app_manager_printf("Wasm app process request success.\n"); - break; - } - case RESTFUL_RESPONSE: - { - wasm_function_inst_t func_onResponse; - response_t *response = - (response_t *)bh_message_payload(queue_msg); - int size; - char *buffer; - int32 buffer_offset; - - app_manager_printf("App %s got response_t,status %d\n", - m_data->module_name, response->status); - - func_onResponse = app_manager_lookup_function( - inst, "_on_response", "(i32i32)"); - if (!func_onResponse) { - app_manager_printf("Cannot find function on_response\n"); - break; - } - - buffer = pack_response(response, &size); - if (buffer == NULL) - break; - - buffer_offset = - wasm_runtime_module_dup_data(inst, buffer, size); - if (buffer_offset == 0) { - const char *exception = wasm_runtime_get_exception(inst); - if (exception) { - app_manager_printf( - "Got exception running wasm code: %s\n", exception); - wasm_runtime_clear_exception(inst); - } - free_req_resp_packet(buffer); - break; - } - - free_req_resp_packet(buffer); - - argv[0] = (uint32)buffer_offset; - argv[1] = (uint32)size; - - if (!wasm_runtime_call_wasm(wasm_app_data->exec_env, - func_onResponse, 2, argv)) { - const char *exception = wasm_runtime_get_exception(inst); - bh_assert(exception); - app_manager_printf("Got exception running wasm code: %s\n", - exception); - wasm_runtime_clear_exception(inst); - wasm_runtime_module_free(inst, buffer_offset); - break; - } - - wasm_runtime_module_free(inst, buffer_offset); - app_manager_printf("Wasm app process response success.\n"); - break; - } - default: - { - for (int i = 0; i < Max_Msg_Callback; i++) { - if (g_msg_type[i] == message_type) { - g_msg_callbacks[i](m_data, queue_msg); - return; - } - } - app_manager_printf( - "Invalid message type of WASM app queue message.\n"); - break; - } - } - } - else { - switch (message_type) { - case TIMER_EVENT_WASM: - { - unsigned int timer_id; - if (bh_message_payload(queue_msg)) { - /* Call Timer.callOnTimer() method */ - func_onTimer = app_manager_lookup_function( - inst, "_on_timer_callback", "(i32)"); - - if (!func_onTimer) { - app_manager_printf( - "Cannot find function _on_timer_callback\n"); - break; - } - timer_id = - (unsigned int)(uintptr_t)bh_message_payload(queue_msg); - argv[0] = timer_id; - if (!wasm_runtime_call_wasm(wasm_app_data->exec_env, - func_onTimer, 1, argv)) { - const char *exception = - wasm_runtime_get_exception(inst); - bh_assert(exception); - app_manager_printf( - "Got exception running wasm code: %s\n", exception); - wasm_runtime_clear_exception(inst); - } - } - break; - } - default: - { - for (int i = 0; i < Max_Msg_Callback; i++) { - if (g_msg_type[i] == message_type) { - g_msg_callbacks[i](m_data, queue_msg); - return; - } - } - app_manager_printf( - "Invalid message type of WASM app queue message.\n"); - break; - } - } - } -} - -#if WASM_ENABLE_LIBC_WASI != 0 -static bool -wasm_app_prepare_wasi_dir(wasm_module_t module, const char *module_name, - char *wasi_dir_buf, uint32 buf_size) -{ - const char *wasi_root = wasm_get_wasi_root_dir(); - char *p = wasi_dir_buf; - uint32 module_name_len = strlen(module_name); - uint32 wasi_root_len = strlen(wasi_root); - uint32 total_size; - struct stat st = { 0 }; - - bh_assert(wasi_root); - - /* wasi_dir: wasi_root/module_name */ - total_size = wasi_root_len + 1 + module_name_len + 1; - if (total_size > buf_size) - return false; - memcpy(p, wasi_root, wasi_root_len); - p += wasi_root_len; - *p++ = '/'; - memcpy(p, module_name, module_name_len); - p += module_name_len; - *p++ = '\0'; - - if (mkdir(wasi_dir_buf, 0777) != 0) { - if (errno == EEXIST) { - /* Failed due to dir already exist */ - if ((stat(wasi_dir_buf, &st) == 0) && (st.st_mode & S_IFDIR)) { - return true; - } - } - - return false; - } - - return true; -} -#endif - -/* WASM app thread main routine */ -static void * -wasm_app_routine(void *arg) -{ - wasm_function_inst_t func_onInit; - wasm_function_inst_t func_onDestroy; - - module_data *m_data = (module_data *)arg; - wasm_data *wasm_app_data = (wasm_data *)m_data->internal_data; - wasm_module_inst_t inst = wasm_app_data->wasm_module_inst; - - /* Set m_data to the VM managed instance's custom data */ - wasm_runtime_set_custom_data(inst, m_data); - - app_manager_printf("WASM app '%s' started\n", m_data->module_name); - -#if WASM_ENABLE_LIBC_WASI != 0 - if (wasm_runtime_is_wasi_mode(inst)) { - wasm_function_inst_t func_start; - /* In wasi mode, we should call function named "_start" - which initializes the wasi envrionment. The "_start" function - will call "main" function */ - if ((func_start = wasm_runtime_lookup_wasi_start_function(inst))) { - if (!wasm_runtime_call_wasm(wasm_app_data->exec_env, func_start, 0, - NULL)) { - const char *exception = wasm_runtime_get_exception(inst); - bh_assert(exception); - app_manager_printf( - "Got exception running wasi start function: %s\n", - exception); - wasm_runtime_clear_exception(inst); - goto fail1; - } - } - /* if no start function is found, we execute - the _on_init function as normal */ - } -#endif - - /* Call app's onInit() method */ - func_onInit = app_manager_lookup_function(inst, "_on_init", "()"); - if (!func_onInit) { - app_manager_printf("Cannot find function on_init().\n"); - goto fail1; - } - - if (!wasm_runtime_call_wasm(wasm_app_data->exec_env, func_onInit, 0, - NULL)) { - const char *exception = wasm_runtime_get_exception(inst); - bh_assert(exception); - app_manager_printf("Got exception running WASM code: %s\n", exception); - wasm_runtime_clear_exception(inst); - /* call on_destroy() in case some resources are opened in on_init() - * and then exception thrown */ - goto fail2; - } - - /* Enter queue loop run to receive and process applet queue message */ - bh_queue_enter_loop_run(m_data->queue, app_instance_queue_callback, inst); - - app_manager_printf("App instance main thread exit.\n"); - -fail2: - /* Call WASM app onDestroy() method if there is */ - func_onDestroy = app_manager_lookup_function(inst, "_on_destroy", "()"); - if (func_onDestroy) { - if (!wasm_runtime_call_wasm(wasm_app_data->exec_env, func_onDestroy, 0, - NULL)) { - const char *exception = wasm_runtime_get_exception(inst); - bh_assert(exception); - app_manager_printf("Got exception running WASM code: %s\n", - exception); - wasm_runtime_clear_exception(inst); - } - } - -fail1: - - return NULL; -} - -static void -cleanup_app_resource(module_data *m_data) -{ - int i; - wasm_data *wasm_app_data = (wasm_data *)m_data->internal_data; - bool is_bytecode = wasm_app_data->is_bytecode; - - am_cleanup_registeration(m_data->id); - - am_unregister_event(NULL, m_data->id); - - for (i = 0; i < Max_Cleanup_Callback; i++) { - if (g_cleanup_callbacks[i] != NULL) - g_cleanup_callbacks[i](m_data->id); - else - break; - } - - wasm_runtime_deinstantiate(wasm_app_data->wasm_module_inst); - - /* Destroy remain sections (i.e. data segment section for bytecode file - * or text section of aot file) from app file's section list. */ - if (is_bytecode) { -#if WASM_ENABLE_INTERP != 0 || WASM_ENABLE_JIT != 0 - destroy_all_wasm_sections( - (wasm_section_list_t)(wasm_app_data->sections)); -#else - bh_assert(0); -#endif - } - else { -#if WASM_ENABLE_AOT != 0 - destroy_all_aot_sections((aot_section_list_t)(wasm_app_data->sections)); -#else - bh_assert(0); -#endif - } - - if (wasm_app_data->wasm_module) - wasm_runtime_unload(wasm_app_data->wasm_module); - - if (wasm_app_data->exec_env) - wasm_runtime_destroy_exec_env(wasm_app_data->exec_env); - - /* 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); -} - -/************************************************************/ -/* Module specific functions implementation */ -/************************************************************/ - -static bool -wasm_app_module_init(void) -{ - uint32 version; - -#if WASM_ENABLE_INTERP != 0 || WASM_ENABLE_JIT != 0 - version = WASM_CURRENT_VERSION; - if (!is_little_endian()) - exchange_uint32((uint8 *)&version); - bh_memcpy_s(wasm_bytecode_version, 4, &version, 4); -#endif - -#if WASM_ENABLE_AOT != 0 - version = AOT_CURRENT_VERSION; - if (!is_little_endian()) - exchange_uint32((uint8 *)&version); - bh_memcpy_s(wasm_aot_version, 4, &version, 4); -#endif - return true; -} - -#define APP_NAME_MAX_LEN 128 -#define MAX_INT_STR_LEN 11 - -static bool -wasm_app_module_install(request_t *msg) -{ - unsigned int m_data_size, heap_size, stack_size; - unsigned int timeout, timers, err_size; - char *properties; - int properties_offset; - wasm_app_file_t *wasm_app_file; - wasm_data *wasm_app_data; - package_type_t package_type; - module_data *m_data = NULL; - wasm_module_t module = NULL; - wasm_module_inst_t inst = NULL; - wasm_exec_env_t exec_env = NULL; - char m_name[APP_NAME_MAX_LEN] = { 0 }; - char timeout_str[MAX_INT_STR_LEN] = { 0 }; - char heap_size_str[MAX_INT_STR_LEN] = { 0 }; - char timers_str[MAX_INT_STR_LEN] = { 0 }, err[128], err_resp[256]; -#if WASM_ENABLE_LIBC_WASI != 0 - char wasi_dir_buf[PATH_MAX] = { 0 }; - const char *wasi_dir_list[] = { wasi_dir_buf }; -#endif - - err_size = sizeof(err); - - /* Check payload */ - if (!msg->payload || msg->payload_len == 0) { - SEND_ERR_RESPONSE(msg->mid, - "Install WASM app failed: invalid wasm file."); - return false; - } - - /* Judge the app type is AOTed or not */ - package_type = get_package_type((uint8 *)msg->payload, msg->payload_len); - wasm_app_file = (wasm_app_file_t *)msg->payload; - - /* Check app name */ - properties_offset = check_url_start(msg->url, strlen(msg->url), "/applet"); - bh_assert(properties_offset > 0); - if (properties_offset <= 0) { - SEND_ERR_RESPONSE(msg->mid, - "Install WASM app failed: invalid app name."); - goto fail; - } - - properties = msg->url + properties_offset; - find_key_value(properties, strlen(properties), "name", m_name, - sizeof(m_name) - 1, '&'); - - if (strlen(m_name) == 0) { - SEND_ERR_RESPONSE(msg->mid, - "Install WASM app failed: invalid app name."); - goto fail; - } - - if (app_manager_lookup_module_data(m_name)) { - SEND_ERR_RESPONSE(msg->mid, - "Install WASM app failed: app already installed."); - goto fail; - } - - /* Parse heap size */ - heap_size = APP_HEAP_SIZE_DEFAULT; - find_key_value(properties, strlen(properties), "heap", heap_size_str, - sizeof(heap_size_str) - 1, '&'); - if (strlen(heap_size_str) > 0) { - heap_size = atoi(heap_size_str); - if (heap_size < APP_HEAP_SIZE_MIN) - heap_size = APP_HEAP_SIZE_MIN; - else if (heap_size > APP_HEAP_SIZE_MAX) - heap_size = APP_HEAP_SIZE_MAX; - } - - /* Load WASM file and instantiate*/ - switch (package_type) { -#if WASM_ENABLE_AOT != 0 - case Wasm_Module_AoT: - { - wasm_aot_file_t *aot_file; - /* clang-format off */ - /* Sections to be released after loading */ - uint8 sections1[] = { - AOT_SECTION_TYPE_TARGET_INFO, - AOT_SECTION_TYPE_INIT_DATA, - AOT_SECTION_TYPE_FUNCTION, - AOT_SECTION_TYPE_EXPORT, - AOT_SECTION_TYPE_RELOCATION, - AOT_SECTION_TYPE_SIGANATURE, - AOT_SECTION_TYPE_CUSTOM, - }; - /* clang-format on */ - - aot_file = &wasm_app_file->u.aot; - - /* Load AOT module from sections */ - module = wasm_runtime_load_from_sections(aot_file->sections, true, - err, err_size); - if (!module) { - snprintf(err_resp, sizeof(err_resp), - "Install WASM app failed: %s", err); - SEND_ERR_RESPONSE(msg->mid, err_resp); - goto fail; - } - /* Destroy useless sections from list after load */ - destroy_part_aot_sections(&aot_file->sections, sections1, - sizeof(sections1) / sizeof(uint8)); - -#if WASM_ENABLE_LIBC_WASI != 0 - if (!wasm_app_prepare_wasi_dir(module, m_name, wasi_dir_buf, - sizeof(wasi_dir_buf))) { - SEND_ERR_RESPONSE( - msg->mid, - "Install WASM app failed: prepare wasi env failed."); - goto fail; - } - wasm_runtime_set_wasi_args(module, wasi_dir_list, 1, NULL, 0, NULL, - 0, NULL, 0); -#endif - - /* Instantiate the AOT module */ - inst = - wasm_runtime_instantiate(module, 0, heap_size, err, err_size); - if (!inst) { - snprintf(err_resp, sizeof(err_resp), - "Install WASM app failed: %s", err); - SEND_ERR_RESPONSE(msg->mid, err); - goto fail; - } - break; - } -#endif /* endof WASM_ENABLE_AOT != 0 */ - -#if WASM_ENABLE_INTERP != 0 || WASM_ENABLE_JIT != 0 - case Wasm_Module_Bytecode: - { - wasm_bytecode_file_t *bytecode_file; - /* Sections to be released after loading */ - uint8 sections1[] = { - SECTION_TYPE_USER, - SECTION_TYPE_TYPE, - SECTION_TYPE_IMPORT, - SECTION_TYPE_FUNC, - SECTION_TYPE_TABLE, - SECTION_TYPE_MEMORY, - SECTION_TYPE_GLOBAL, - SECTION_TYPE_EXPORT, - SECTION_TYPE_START, - SECTION_TYPE_ELEM, -#if WASM_ENABLE_BULK_MEMORY != 0 - SECTION_TYPE_DATACOUNT -#endif - - }; - /* Sections to be released after instantiating */ - uint8 sections2[] = { SECTION_TYPE_DATA }; - - bytecode_file = &wasm_app_file->u.bytecode; - - /* Load wasm module from sections */ - module = wasm_runtime_load_from_sections(bytecode_file->sections, - false, err, err_size); - if (!module) { - snprintf(err_resp, sizeof(err_resp), - "Install WASM app failed: %s", err); - SEND_ERR_RESPONSE(msg->mid, err_resp); - goto fail; - } - - /* Destroy useless sections from list after load */ - destroy_part_wasm_sections(&bytecode_file->sections, sections1, - sizeof(sections1) / sizeof(uint8)); - -#if WASM_ENABLE_LIBC_WASI != 0 - if (!wasm_app_prepare_wasi_dir(module, m_name, wasi_dir_buf, - sizeof(wasi_dir_buf))) { - SEND_ERR_RESPONSE( - msg->mid, - "Install WASM app failed: prepare wasi env failed."); - goto fail; - } - wasm_runtime_set_wasi_args(module, wasi_dir_list, 1, NULL, 0, NULL, - 0, NULL, 0); -#endif - - /* Instantiate the wasm module */ - inst = - wasm_runtime_instantiate(module, 0, heap_size, err, err_size); - if (!inst) { - snprintf(err_resp, sizeof(err_resp), - "Install WASM app failed: %s", err); - SEND_ERR_RESPONSE(msg->mid, err_resp); - goto fail; - } - - /* Destroy useless sections from list after instantiate */ - destroy_part_wasm_sections(&bytecode_file->sections, sections2, - sizeof(sections2) / sizeof(uint8)); - break; - } -#endif /* endof WASM_ENALBE_INTERP != 0 || WASM_ENABLE_JIT != 0 */ - default: - SEND_ERR_RESPONSE( - msg->mid, - "Install WASM app failed: invalid wasm package type."); - goto fail; - } - - /* Create module data including the wasm_app_data as its internal_data*/ - m_data_size = offsetof(module_data, module_name) + strlen(m_name) + 1; - m_data_size = align_uint(m_data_size, 4); - m_data = APP_MGR_MALLOC(m_data_size + sizeof(wasm_data)); - if (!m_data) { - SEND_ERR_RESPONSE(msg->mid, - "Install WASM app failed: allocate memory failed."); - goto fail; - } - memset(m_data, 0, m_data_size + sizeof(wasm_data)); - - m_data->module_type = Module_WASM_App; - m_data->internal_data = (uint8 *)m_data + m_data_size; - wasm_app_data = (wasm_data *)m_data->internal_data; - wasm_app_data->wasm_module_inst = inst; - wasm_app_data->wasm_module = module; - wasm_app_data->m_data = m_data; - if (package_type == Wasm_Module_Bytecode) { - wasm_app_data->is_bytecode = true; - wasm_app_data->sections = wasm_app_file->u.bytecode.sections; - } - else { - wasm_app_data->is_bytecode = false; - wasm_app_data->sections = wasm_app_file->u.aot.sections; - } - - if (!(wasm_app_data->exec_env = exec_env = - wasm_runtime_create_exec_env(inst, DEFAULT_WASM_STACK_SIZE))) { - SEND_ERR_RESPONSE(msg->mid, - "Install WASM app failed: create exec env failed."); - goto fail; - } - - /* Set module data - name and module type */ - bh_strcpy_s(m_data->module_name, strlen(m_name) + 1, m_name); - - /* Set module data - execution timeout */ - timeout = DEFAULT_WATCHDOG_INTERVAL; - find_key_value(properties, strlen(properties), "wd", timeout_str, - sizeof(timeout_str) - 1, '&'); - if (strlen(timeout_str) > 0) - timeout = atoi(timeout_str); - m_data->timeout = timeout; - - /* Set module data - create queue */ - m_data->queue = bh_queue_create(); - if (!m_data->queue) { - SEND_ERR_RESPONSE(msg->mid, - "Install WASM app failed: create app queue failed."); - goto fail; - } - - /* Set heap size */ - m_data->heap_size = heap_size; - - /* Set module data - timers number */ - timers = DEFAULT_TIMERS_PER_APP; - find_key_value(properties, strlen(properties), "timers", timers_str, - sizeof(timers_str) - 1, '&'); - if (strlen(timers_str) > 0) { - timers = atoi(timers_str); - if (timers > MAX_TIMERS_PER_APP) - timers = MAX_TIMERS_PER_APP; - } - - /* Attention: must add the module before start the thread! */ - app_manager_add_module_data(m_data); - - m_data->timer_ctx = create_wasm_timer_ctx(m_data->id, timers); - if (!m_data->timer_ctx) { - SEND_ERR_RESPONSE(msg->mid, - "Install WASM app failed: create app timers failed."); - goto fail; - } - - /* Initialize watchdog timer */ - if (!watchdog_timer_init(m_data)) { - SEND_ERR_RESPONSE( - msg->mid, - "Install WASM app failed: create app watchdog timer failed."); - goto fail; - } - - stack_size = APP_THREAD_STACK_SIZE_DEFAULT; -#ifdef OS_ENABLE_HW_BOUND_CHECK - stack_size += 4 * BH_KB; -#endif - /* Create WASM app thread. */ - if (os_thread_create(&wasm_app_data->thread_id, wasm_app_routine, - (void *)m_data, stack_size) - != 0) { - module_data_list_remove(m_data); - SEND_ERR_RESPONSE(msg->mid, - "Install WASM app failed: create app thread failed."); - goto fail; - } - - /* only when thread is created it is the flag of installation success */ - app_manager_post_applets_update_event(); - - app_manager_printf("Install WASM app success!\n"); - send_error_response_to_host(msg->mid, CREATED_2_01, NULL); /* CREATED */ - - return true; - -fail: - if (m_data) - release_module(m_data); - - if (inst) - wasm_runtime_deinstantiate(inst); - - if (module) - wasm_runtime_unload(module); - - if (exec_env) - wasm_runtime_destroy_exec_env(exec_env); - - switch (package_type) { -#if WASM_ENABLE_INTERP != 0 || WASM_ENABLE_JIT != 0 - case Wasm_Module_Bytecode: - destroy_all_wasm_sections(wasm_app_file->u.bytecode.sections); - break; -#endif -#if WASM_ENABLE_AOT != 0 - case Wasm_Module_AoT: - destroy_all_aot_sections(wasm_app_file->u.aot.sections); - break; -#endif - default: - break; - } - - return false; -} - -/* For internal use: if defined to 1, the process will - * exit when wasm app is uninstalled. Hence valgrind can - * print memory leak report. */ -#ifndef VALGRIND_CHECK -#define VALGRIND_CHECK 0 -#endif - -/* Uninstall WASM app */ -static bool -wasm_app_module_uninstall(request_t *msg) -{ - module_data *m_data; - wasm_data *wasm_app_data; - char m_name[APP_NAME_MAX_LEN] = { 0 }; - char *properties; - int properties_offset; - - properties_offset = check_url_start(msg->url, strlen(msg->url), "/applet"); - /* TODO: assert(properties_offset > 0) */ - if (properties_offset <= 0) - return false; - properties = msg->url + properties_offset; - find_key_value(properties, strlen(properties), "name", m_name, - sizeof(m_name) - 1, '&'); - - if (strlen(m_name) == 0) { - SEND_ERR_RESPONSE(msg->mid, - "Uninstall WASM app failed: invalid app name."); - return false; - } - - m_data = app_manager_lookup_module_data(m_name); - if (!m_data) { - SEND_ERR_RESPONSE(msg->mid, "Uninstall WASM app failed: no app found."); - return false; - } - - if (m_data->module_type != Module_WASM_App) { - SEND_ERR_RESPONSE(msg->mid, - "Uninstall WASM app failed: invalid module type."); - return false; - } - - if (m_data->wd_timer.is_interrupting) { - SEND_ERR_RESPONSE( - msg->mid, - "Uninstall WASM app failed: app is being interrupted by watchdog."); - return false; - } - - /* Exit app queue loop run */ - bh_queue_exit_loop_run(m_data->queue); - - /* Wait for wasm app thread to exit */ - wasm_app_data = (wasm_data *)m_data->internal_data; - os_thread_join(wasm_app_data->thread_id, NULL); - - cleanup_app_resource(m_data); - - app_manager_post_applets_update_event(); - - app_manager_printf("Uninstall WASM app successful!\n"); - -#ifdef COLLECT_CODE_COVERAGE - /* Exit app manager so as to collect code coverage data */ - if (!strcmp(m_name, "__exit_app_manager__")) { - app_manager_printf("Exit app manager\n"); - bh_queue_exit_loop_run(get_app_manager_queue()); - } -#endif - -#if VALGRIND_CHECK != 0 - bh_queue_exit_loop_run(get_app_manager_queue()); -#endif - - send_error_response_to_host(msg->mid, DELETED_2_02, NULL); /* DELETED */ - return true; -} - -static bool -wasm_app_module_handle_host_url(void *queue_msg) -{ - /* TODO: implement in future */ - app_manager_printf("App handles host url address %d\n", - (int)(uintptr_t)queue_msg); - return false; -} - -static module_data * -wasm_app_module_get_module_data(void *inst) -{ - wasm_module_inst_t module_inst = (wasm_module_inst_t)inst; - return (module_data *)wasm_runtime_get_custom_data(module_inst); -} - -static void -wasm_app_module_watchdog_kill(module_data *m_data) -{ - /* TODO: implement in future */ - app_manager_printf("Watchdog kills app: %s\n", m_data->module_name); - return; -} - -bool -wasm_register_msg_callback(int message_type, - message_type_handler_t message_handler) -{ - int i; - int freeslot = -1; - for (i = 0; i < Max_Msg_Callback; i++) { - /* replace handler for the same event registered */ - if (g_msg_type[i] == message_type) - break; - - if (g_msg_callbacks[i] == NULL && freeslot == -1) - freeslot = i; - } - - if (i != Max_Msg_Callback) - g_msg_callbacks[i] = message_handler; - else if (freeslot != -1) { - g_msg_callbacks[freeslot] = message_handler; - g_msg_type[freeslot] = message_type; - } - else - return false; - - return true; -} - -bool -wasm_register_cleanup_callback(resource_cleanup_handler_t handler) -{ - int i; - - for (i = 0; i < Max_Cleanup_Callback; i++) { - if (g_cleanup_callbacks[i] == NULL) { - g_cleanup_callbacks[i] = handler; - return true; - } - } - - return false; -} - -#define RECV_INTEGER(value, next_phase) \ - do { \ - uint8 *p = (uint8 *)&value; \ - p[recv_ctx.size_in_phase++] = ch; \ - if (recv_ctx.size_in_phase == sizeof(value)) { \ - if (sizeof(value) == 4) \ - value = ntohl(value); \ - else if (sizeof(value) == 2) \ - value = ntohs(value); \ - recv_ctx.phase = next_phase; \ - recv_ctx.size_in_phase = 0; \ - } \ - } while (0) - -/* return: - * 1: whole wasm app arrived - * 0: one valid byte arrived - * -1: fail to process the byte arrived, e.g. allocate memory fail - */ -static bool -wasm_app_module_on_install_request_byte_arrive(uint8 ch, int request_total_size, - int *received_size) -{ - uint8 *p; - int magic; - package_type_t package_type = Package_Type_Unknown; - - if (recv_ctx.phase == Phase_Req_Ver) { - recv_ctx.phase = Phase_Req_Ver; - recv_ctx.size_in_phase = 0; - recv_ctx.total_received_size = 0; - } - - recv_ctx.total_received_size++; - *received_size = recv_ctx.total_received_size; - - if (recv_ctx.phase == Phase_Req_Ver) { - if (ch != 1 /* REQUES_PACKET_VER from restful_utils.c */) - return false; - recv_ctx.phase = Phase_Req_Action; - return true; - } - else if (recv_ctx.phase == Phase_Req_Action) { - recv_ctx.message.request_action = ch; - recv_ctx.phase = Phase_Req_Fmt; - recv_ctx.size_in_phase = 0; - return true; - } - else if (recv_ctx.phase == Phase_Req_Fmt) { - RECV_INTEGER(recv_ctx.message.request_fmt, Phase_Req_Mid); - return true; - } - else if (recv_ctx.phase == Phase_Req_Mid) { - RECV_INTEGER(recv_ctx.message.request_mid, Phase_Req_Sender); - return true; - } - else if (recv_ctx.phase == Phase_Req_Sender) { - RECV_INTEGER(recv_ctx.message.request_sender, Phase_Req_Url_Len); - return true; - } - else if (recv_ctx.phase == Phase_Req_Url_Len) { - p = (uint8 *)&recv_ctx.message.request_url_len; - - p[recv_ctx.size_in_phase++] = ch; - if (recv_ctx.size_in_phase - == sizeof(recv_ctx.message.request_url_len)) { - recv_ctx.message.request_url_len = - ntohs(recv_ctx.message.request_url_len); - recv_ctx.message.request_url = - APP_MGR_MALLOC(recv_ctx.message.request_url_len + 1); - if (NULL == recv_ctx.message.request_url) { - app_manager_printf("Allocate memory failed!\n"); - SEND_ERR_RESPONSE(recv_ctx.message.request_mid, - "Install WASM app failed: " - "allocate memory failed."); - goto fail; - } - memset(recv_ctx.message.request_url, 0, - recv_ctx.message.request_url_len + 1); - recv_ctx.phase = Phase_Req_Payload_Len; - recv_ctx.size_in_phase = 0; - } - return true; - } - else if (recv_ctx.phase == Phase_Req_Payload_Len) { - RECV_INTEGER(recv_ctx.message.wasm_app_size, Phase_Req_Url); - return true; - } - else if (recv_ctx.phase == Phase_Req_Url) { - recv_ctx.message.request_url[recv_ctx.size_in_phase++] = ch; - if (recv_ctx.size_in_phase == recv_ctx.message.request_url_len) { - recv_ctx.phase = Phase_App_Magic; - recv_ctx.size_in_phase = 0; - } - return true; - } - else if (recv_ctx.phase == Phase_App_Magic) { - /* start to receive wasm app magic: bytecode or aot */ - p = (uint8 *)&recv_ctx.message.app_file_magic; - - p[recv_ctx.size_in_phase++] = ch; - - if (recv_ctx.size_in_phase == sizeof(recv_ctx.message.app_file_magic)) { - magic = recv_ctx.message.app_file_magic; - package_type = get_package_type((uint8 *)&magic, sizeof(magic) + 1); - switch (package_type) { -#if WASM_ENABLE_INTERP != 0 || WASM_ENABLE_JIT != 0 - case Wasm_Module_Bytecode: - recv_ctx.message.app_file.u.bytecode.magic = - recv_ctx.message.app_file_magic; - recv_ctx.phase = Phase_Wasm_Version; - recv_ctx.size_in_phase = 0; - break; -#endif -#if WASM_ENABLE_AOT != 0 - case Wasm_Module_AoT: - recv_ctx.message.app_file.u.aot.magic = - recv_ctx.message.app_file_magic; - recv_ctx.phase = Phase_AOT_Version; - recv_ctx.size_in_phase = 0; - break; -#endif - default: - SEND_ERR_RESPONSE(recv_ctx.message.request_mid, - "Install WASM app failed: " - "invalid file format."); - goto fail; - } - } - return true; - } -#if WASM_ENABLE_INTERP != 0 || WASM_ENABLE_JIT != 0 - else if (recv_ctx.phase == Phase_Wasm_Version) { - p = (uint8 *)&recv_ctx.message.app_file.u.bytecode.version; - - if (ch == wasm_bytecode_version[recv_ctx.size_in_phase]) - p[recv_ctx.size_in_phase++] = ch; - else { - app_manager_printf("Invalid WASM version!\n"); - SEND_ERR_RESPONSE(recv_ctx.message.request_mid, - "Install WASM app failed: invalid WASM version."); - goto fail; - } - - if (recv_ctx.size_in_phase - == sizeof(recv_ctx.message.app_file.u.bytecode.version)) { - recv_ctx.phase = Phase_Wasm_Section_Type; - recv_ctx.size_in_phase = 0; - } - return true; - } - else if (recv_ctx.phase == Phase_Wasm_Section_Type) { - 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; - if (!(new_section = (wasm_section_t *)APP_MGR_MALLOC( - sizeof(wasm_section_t)))) { - app_manager_printf("Allocate memory failed!\n"); - SEND_ERR_RESPONSE(recv_ctx.message.request_mid, - "Install WASM app failed: " - "allocate memory failed."); - goto fail; - } - memset(new_section, 0, sizeof(wasm_section_t)); - new_section->section_type = section_type; - new_section->next = NULL; - - /* add the section to tail of link list */ - if (NULL == recv_ctx.message.app_file.u.bytecode.sections) { - recv_ctx.message.app_file.u.bytecode.sections = new_section; - recv_ctx.message.app_file.u.bytecode.section_end = new_section; - } - else { - recv_ctx.message.app_file.u.bytecode.section_end->next = - new_section; - recv_ctx.message.app_file.u.bytecode.section_end = new_section; - } - - recv_ctx.phase = Phase_Wasm_Section_Size; - recv_ctx.size_in_phase = 0; - - return true; - } - else { - char error_buf[128]; - - app_manager_printf("Invalid wasm section type: %d\n", section_type); - snprintf(error_buf, sizeof(error_buf), - "Install WASM app failed: invalid wasm section type %d", - section_type); - SEND_ERR_RESPONSE(recv_ctx.message.request_mid, error_buf); - goto fail; - } - } - else if (recv_ctx.phase == Phase_Wasm_Section_Size) { - /* the last section is the current receiving one */ - wasm_section_t *section = - recv_ctx.message.app_file.u.bytecode.section_end; - uint32 byte; - - bh_assert(section); - - byte = ch; - - section->section_body_size |= - ((byte & 0x7f) << recv_ctx.size_in_phase * 7); - recv_ctx.size_in_phase++; - /* check leab128 overflow for uint32 value */ - if (recv_ctx.size_in_phase - > (sizeof(section->section_body_size) * 8 + 7 - 1) / 7) { - app_manager_printf("LEB overflow when parsing section size\n"); - SEND_ERR_RESPONSE(recv_ctx.message.request_mid, - "Install WASM app failed: " - "LEB overflow when parsing section size"); - goto fail; - } - - if ((byte & 0x80) == 0) { - /* leb128 encoded section size parsed done */ - if (!(section->section_body = - APP_MGR_MALLOC(section->section_body_size))) { - app_manager_printf("Allocate memory failed!\n"); - SEND_ERR_RESPONSE( - recv_ctx.message.request_mid, - "Install WASM app failed: allocate memory failed"); - goto fail; - } - recv_ctx.phase = Phase_Wasm_Section_Content; - recv_ctx.size_in_phase = 0; - } - - return true; - } - else if (recv_ctx.phase == Phase_Wasm_Section_Content) { - /* the last section is the current receiving one */ - wasm_section_t *section = - recv_ctx.message.app_file.u.bytecode.section_end; - - bh_assert(section); - - section->section_body[recv_ctx.size_in_phase++] = ch; - - if (recv_ctx.size_in_phase == section->section_body_size) { - if (recv_ctx.total_received_size == request_total_size) { - /* whole wasm app received */ - if (module_wasm_app_handle_install_msg(&recv_ctx.message)) { - APP_MGR_FREE(recv_ctx.message.request_url); - recv_ctx.message.request_url = NULL; - memset(&recv_ctx, 0, sizeof(recv_ctx)); - return true; - } - else { - app_manager_printf("Handle install message failed!\n"); - SEND_ERR_RESPONSE(recv_ctx.message.request_mid, - "Install WASM app failed: " - "handle install message failed"); - /** - * The sections were destroyed inside - * module_wasm_app_handle_install_msg(), - * no need to destroy again. - */ - return false; - } - } - else { - recv_ctx.phase = Phase_Wasm_Section_Type; - recv_ctx.size_in_phase = 0; - return true; - } - } - - return true; - } -#endif /* end of WASM_ENABLE_INTERP != 0 || WASM_ENABLE_JIT != 0 */ -#if WASM_ENABLE_AOT != 0 - else if (recv_ctx.phase == Phase_AOT_Version) { - p = (uint8 *)&recv_ctx.message.app_file.u.aot.version; - - if (ch == wasm_aot_version[recv_ctx.size_in_phase]) - p[recv_ctx.size_in_phase++] = ch; - else { - app_manager_printf("Invalid AOT version!\n"); - SEND_ERR_RESPONSE(recv_ctx.message.request_mid, - "Install WASM app failed: invalid AOT version"); - goto fail; - } - - if (recv_ctx.size_in_phase - == sizeof(recv_ctx.message.app_file.u.aot.version)) { - recv_ctx.phase = Phase_AOT_Section_ID; - recv_ctx.size_in_phase = 0; - } - return true; - } - else if (recv_ctx.phase == Phase_AOT_Section_ID) { - aot_section_t *cur_section; - uint32 aot_file_cur_offset = - recv_ctx.total_received_size - 1 - - 18 /* Request fixed part */ - recv_ctx.message.request_url_len; - - if (recv_ctx.size_in_phase == 0) { - /* Skip paddings */ - if (aot_file_cur_offset % 4) - return true; - - if (!(cur_section = - (aot_section_t *)APP_MGR_MALLOC(sizeof(aot_section_t)))) { - app_manager_printf("Allocate memory failed!\n"); - SEND_ERR_RESPONSE(recv_ctx.message.request_mid, - "Install WASM app failed: " - "allocate memory failed"); - goto fail; - } - memset(cur_section, 0, sizeof(aot_section_t)); - - /* add the section to tail of link list */ - if (NULL == recv_ctx.message.app_file.u.aot.sections) { - recv_ctx.message.app_file.u.aot.sections = cur_section; - recv_ctx.message.app_file.u.aot.section_end = cur_section; - } - else { - recv_ctx.message.app_file.u.aot.section_end->next = cur_section; - recv_ctx.message.app_file.u.aot.section_end = cur_section; - } - } - else { - cur_section = recv_ctx.message.app_file.u.aot.section_end; - bh_assert(cur_section); - } - - p = (uint8 *)&cur_section->section_type; - p[recv_ctx.size_in_phase++] = ch; - if (recv_ctx.size_in_phase == sizeof(cur_section->section_type)) { - /* Notes: integers are always little endian encoded in AOT file */ - if (!is_little_endian()) - exchange_uint32(p); - if (cur_section->section_type < AOT_SECTION_TYPE_SIGANATURE - || cur_section->section_type == AOT_SECTION_TYPE_CUSTOM) { - recv_ctx.phase = Phase_AOT_Section_Size; - recv_ctx.size_in_phase = 0; - } - else { - char error_buf[128]; - - app_manager_printf("Invalid AOT section id: %d\n", - cur_section->section_type); - snprintf(error_buf, sizeof(error_buf), - "Install WASM app failed: invalid AOT section id %d", - cur_section->section_type); - SEND_ERR_RESPONSE(recv_ctx.message.request_mid, error_buf); - goto fail; - } - } - - return true; - } - else if (recv_ctx.phase == Phase_AOT_Section_Size) { - /* the last section is the current receiving one */ - aot_section_t *section = recv_ctx.message.app_file.u.aot.section_end; - bh_assert(section); - - p = (uint8 *)§ion->section_body_size; - p[recv_ctx.size_in_phase++] = ch; - if (recv_ctx.size_in_phase == sizeof(section->section_body_size)) { - /* Notes: integers are always little endian encoded in AOT file */ - if (!is_little_endian()) - exchange_uint32(p); - /* Allocate memory for section body */ - if (section->section_body_size > 0) { - if (section->section_type == AOT_SECTION_TYPE_TEXT) { - int map_prot = - MMAP_PROT_READ | MMAP_PROT_WRITE | MMAP_PROT_EXEC; -#if defined(BUILD_TARGET_X86_64) || defined(BUILD_TARGET_AMD_64) \ - || defined(BUILD_TARGET_RISCV64_LP64D) \ - || defined(BUILD_TARGET_RISCV64_LP64) - /* aot code and data in x86_64 must be in range 0 to 2G due - to relocation for R_X86_64_32/32S/PC32 */ - int map_flags = MMAP_MAP_32BIT; -#else - int map_flags = MMAP_MAP_NONE; -#endif - uint64 total_size = (uint64)section->section_body_size - + aot_get_plt_table_size(); - total_size = (total_size + 3) & ~((uint64)3); - if (total_size >= UINT32_MAX - || !(section->section_body = - os_mmap(NULL, (uint32)total_size, map_prot, - map_flags, os_get_invalid_handle()))) { - app_manager_printf( - "Allocate executable memory failed!\n"); - SEND_ERR_RESPONSE(recv_ctx.message.request_mid, - "Install WASM app failed: " - "allocate memory failed"); - goto fail; - } -#if defined(BUILD_TARGET_X86_64) || defined(BUILD_TARGET_AMD_64) - /* address must be in the first 2 Gigabytes of - the process address space */ - bh_assert((uintptr_t)section->section_body < INT32_MAX); -#endif - } - else { - if (!(section->section_body = - APP_MGR_MALLOC(section->section_body_size))) { - app_manager_printf("Allocate memory failed!\n"); - SEND_ERR_RESPONSE(recv_ctx.message.request_mid, - "Install WASM app failed: " - "allocate memory failed"); - goto fail; - } - } - } - - recv_ctx.phase = Phase_AOT_Section_Content; - recv_ctx.size_in_phase = 0; - } - - return true; - } - else if (recv_ctx.phase == Phase_AOT_Section_Content) { - /* the last section is the current receiving one */ - aot_section_t *section = recv_ctx.message.app_file.u.aot.section_end; - bh_assert(section && section->section_body); - - section->section_body[recv_ctx.size_in_phase++] = ch; - - if (recv_ctx.size_in_phase == section->section_body_size) { - if (section->section_type == AOT_SECTION_TYPE_TEXT) { - uint32 total_size = - section->section_body_size + aot_get_plt_table_size(); - total_size = (total_size + 3) & ~3; - if (total_size > section->section_body_size) { - memset(section->section_body + section->section_body_size, - 0, total_size - section->section_body_size); - section->section_body_size = total_size; - } - } - if (recv_ctx.total_received_size == request_total_size) { - /* whole aot file received */ - if (module_wasm_app_handle_install_msg(&recv_ctx.message)) { - APP_MGR_FREE(recv_ctx.message.request_url); - recv_ctx.message.request_url = NULL; - memset(&recv_ctx, 0, sizeof(recv_ctx)); - return true; - } - else { - app_manager_printf("Handle install message failed!\n"); - SEND_ERR_RESPONSE(recv_ctx.message.request_mid, - "Install WASM app failed: " - "handle install message failed"); - /** - * The sections were destroyed inside - * module_wasm_app_handle_install_msg(), - * no need to destroy again. - */ - return false; - } - } - else { - recv_ctx.phase = Phase_AOT_Section_ID; - recv_ctx.size_in_phase = 0; - return true; - } - } - - return true; - } -#endif /* end of WASM_ENABLE_AOT != 0 */ - -fail: - /* Restore the package type */ - magic = recv_ctx.message.app_file_magic; - package_type = get_package_type((uint8 *)&magic, sizeof(magic) + 1); - switch (package_type) { -#if WASM_ENABLE_INTERP != 0 || WASM_ENABLE_JIT != 0 - case Wasm_Module_Bytecode: - destroy_all_wasm_sections( - recv_ctx.message.app_file.u.bytecode.sections); - break; -#endif -#if WASM_ENABLE_AOT != 0 - case Wasm_Module_AoT: - destroy_all_aot_sections(recv_ctx.message.app_file.u.aot.sections); - break; -#endif - default: - break; - } - - if (recv_ctx.message.request_url != NULL) { - APP_MGR_FREE(recv_ctx.message.request_url); - recv_ctx.message.request_url = NULL; - } - - memset(&recv_ctx, 0, sizeof(recv_ctx)); - return false; -} - -static bool -module_wasm_app_handle_install_msg(install_wasm_app_msg_t *message) -{ - request_t *request = NULL; - bh_message_t msg; - - request = (request_t *)APP_MGR_MALLOC(sizeof(request_t)); - if (request == NULL) - return false; - - memset(request, 0, sizeof(*request)); - request->action = message->request_action; - request->fmt = message->request_fmt; - request->url = bh_strdup(message->request_url); - request->sender = ID_HOST; - request->mid = message->request_mid; - request->payload_len = sizeof(message->app_file); - request->payload = APP_MGR_MALLOC(request->payload_len); - - if (request->url == NULL || request->payload == NULL) { - request_cleaner(request); - return false; - } - - /* Request payload is set to wasm_app_file_t struct, - * but not whole app buffer */ - bh_memcpy_s(request->payload, request->payload_len, &message->app_file, - request->payload_len); - - /* Since it's a wasm app install request, so directly post to app-mgr's - * queue. The benefit is that section list can be freed when the msg - * failed to post to app-mgr's queue. The defect is missing url check. */ - if (!(msg = bh_new_msg(RESTFUL_REQUEST, request, sizeof(*request), - request_cleaner))) { - request_cleaner(request); - return false; - } - - if (!bh_post_msg2(get_app_manager_queue(), msg)) - return false; - - return true; -} - -#if WASM_ENABLE_INTERP != 0 || WASM_ENABLE_JIT != 0 -static void -destroy_all_wasm_sections(wasm_section_list_t sections) -{ - wasm_section_t *cur = sections; - while (cur) { - wasm_section_t *next = cur->next; - if (cur->section_body != NULL) - APP_MGR_FREE(cur->section_body); - APP_MGR_FREE(cur); - cur = next; - } -} - -static void -destroy_part_wasm_sections(wasm_section_list_t *p_sections, - uint8 *section_types, int section_cnt) -{ - int i; - for (i = 0; i < section_cnt; i++) { - uint8 section_type = section_types[i]; - wasm_section_t *cur = *p_sections, *prev = NULL; - - while (cur) { - wasm_section_t *next = cur->next; - if (cur->section_type == section_type) { - if (prev) - prev->next = next; - else - *p_sections = next; - - if (cur->section_body != NULL) - APP_MGR_FREE(cur->section_body); - APP_MGR_FREE(cur); - break; - } - else { - prev = cur; - cur = next; - } - } - } -} -#endif - -#if WASM_ENABLE_AOT != 0 -static void -destroy_all_aot_sections(aot_section_list_t sections) -{ - aot_section_t *cur = sections; - while (cur) { - aot_section_t *next = cur->next; - if (cur->section_body != NULL) { - if (cur->section_type == AOT_SECTION_TYPE_TEXT) - os_munmap(cur->section_body, cur->section_body_size); - else - APP_MGR_FREE(cur->section_body); - } - APP_MGR_FREE(cur); - cur = next; - } -} - -static void -destroy_part_aot_sections(aot_section_list_t *p_sections, uint8 *section_types, - int section_cnt) -{ - int i; - for (i = 0; i < section_cnt; i++) { - uint8 section_type = section_types[i]; - aot_section_t *cur = *p_sections, *prev = NULL; - - while (cur) { - aot_section_t *next = cur->next; - if (cur->section_type == section_type) { - if (prev) - prev->next = next; - else - *p_sections = next; - - if (cur->section_body != NULL) { - if (cur->section_type == AOT_SECTION_TYPE_TEXT) - os_munmap(cur->section_body, cur->section_body_size); - else - APP_MGR_FREE(cur->section_body); - } - APP_MGR_FREE(cur); - break; - } - else { - prev = cur; - cur = next; - } - } - } -} -#endif - -#if WASM_ENABLE_LIBC_WASI != 0 -static char wasi_root_dir[PATH_MAX] = { '.' }; - -bool -wasm_set_wasi_root_dir(const char *root_dir) -{ - char *path, resolved_path[PATH_MAX]; - - if (!(path = realpath(root_dir, resolved_path))) - return false; - - snprintf(wasi_root_dir, sizeof(wasi_root_dir), "%s", path); - return true; -} - -const char * -wasm_get_wasi_root_dir() -{ - return wasi_root_dir; -} -#endif diff --git a/core/app-mgr/app-manager/module_wasm_app.h b/core/app-mgr/app-manager/module_wasm_app.h 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/platform/zephyr/app_mgr_zephyr.c b/core/app-mgr/app-manager/platform/zephyr/app_mgr_zephyr.c deleted file mode 100644 index 68147c062..000000000 --- a/core/app-mgr/app-manager/platform/zephyr/app_mgr_zephyr.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 "app_manager.h" -#include "bh_platform.h" -#include - -#if KERNEL_VERSION_NUMBER < 0x030200 /* version 3.2.0 */ -#include -#include -#else -#include -#endif - -#if 0 -#include -#endif -typedef struct k_timer_watchdog { - struct k_timer timer; - watchdog_timer *wd_timer; -} k_timer_watchdog; - -void * -app_manager_timer_create(void (*timer_callback)(void *), - watchdog_timer *wd_timer) -{ - struct k_timer_watchdog *timer = - APP_MGR_MALLOC(sizeof(struct k_timer_watchdog)); - - if (timer) { - k_timer_init(&timer->timer, (void (*)(struct k_timer *))timer_callback, - NULL); - timer->wd_timer = wd_timer; - } - - return timer; -} - -void -app_manager_timer_destroy(void *timer) -{ - APP_MGR_FREE(timer); -} - -void -app_manager_timer_start(void *timer, int timeout) -{ - k_timer_start(timer, Z_TIMEOUT_MS(timeout), Z_TIMEOUT_MS(0)); -} - -void -app_manager_timer_stop(void *timer) -{ - k_timer_stop(timer); -} - -watchdog_timer * -app_manager_get_wd_timer_from_timer_handle(void *timer) -{ - return ((k_timer_watchdog *)timer)->wd_timer; -} -#if 0 -int app_manager_signature_verify(const uint8_t *file, unsigned int file_len, - const uint8_t *signature, unsigned int sig_size) -{ - return signature_verify(file, file_len, signature, sig_size); -} -#endif 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 be9ebfc3a..d84ed3f36 100644 --- a/core/config.h +++ b/core/config.h @@ -152,6 +152,10 @@ #define WASM_ENABLE_WASI_NN_EXTERNAL_DELEGATE 0 #endif +#ifndef WASM_ENABLE_WASI_EPHEMERAL_NN +#define WASM_ENABLE_WASI_EPHEMERAL_NN 0 +#endif + /* Default disable libc emcc */ #ifndef WASM_ENABLE_LIBC_EMCC #define WASM_ENABLE_LIBC_EMCC 0 @@ -411,7 +415,7 @@ #else #define DEFAULT_WASM_STACK_SIZE (12 * 1024) #endif -/* Min auxilliary stack size of each wasm thread */ +/* Min auxiliary stack size of each wasm thread */ #define WASM_THREAD_AUX_STACK_SIZE_MIN (256) /* Default/min native stack size of each app thread */ @@ -560,12 +564,25 @@ #endif /* Support registering quick AOT/JIT function entries of some func types - to speedup the calling process of invoking the AOT/JIT functions of + to speed up the calling process of invoking the AOT/JIT functions of these types from the host embedder */ #ifndef WASM_ENABLE_QUICK_AOT_ENTRY #define WASM_ENABLE_QUICK_AOT_ENTRY 1 #endif +/* Support AOT intrinsic functions which can be called from the AOT code + when `--disable-llvm-intrinsics` flag or + `--enable-builtin-intrinsics=` is used by wamrc to + generate the AOT file */ +#ifndef WASM_ENABLE_AOT_INTRINSICS +#define WASM_ENABLE_AOT_INTRINSICS 1 +#endif + +/* Disable memory64 by default */ +#ifndef WASM_ENABLE_MEMORY64 +#define WASM_ENABLE_MEMORY64 0 +#endif + #ifndef WASM_TABLE_MAX_SIZE #define WASM_TABLE_MAX_SIZE 1024 #endif 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_intrinsic.c b/core/iwasm/aot/aot_intrinsic.c index 189b43b09..7b455cbb0 100644 --- a/core/iwasm/aot/aot_intrinsic.c +++ b/core/iwasm/aot/aot_intrinsic.c @@ -5,86 +5,6 @@ #include "aot_intrinsic.h" -typedef struct { - const char *llvm_intrinsic; - const char *native_intrinsic; - uint64 flag; -} aot_intrinsic; - -/* clang-format off */ -static const aot_intrinsic g_intrinsic_mapping[] = { - { "llvm.experimental.constrained.fadd.f32", "aot_intrinsic_fadd_f32", AOT_INTRINSIC_FLAG_F32_FADD }, - { "llvm.experimental.constrained.fadd.f64", "aot_intrinsic_fadd_f64", AOT_INTRINSIC_FLAG_F64_FADD }, - { "llvm.experimental.constrained.fsub.f32", "aot_intrinsic_fsub_f32", AOT_INTRINSIC_FLAG_F32_FSUB }, - { "llvm.experimental.constrained.fsub.f64", "aot_intrinsic_fsub_f64", AOT_INTRINSIC_FLAG_F64_FSUB }, - { "llvm.experimental.constrained.fmul.f32", "aot_intrinsic_fmul_f32", AOT_INTRINSIC_FLAG_F32_FMUL }, - { "llvm.experimental.constrained.fmul.f64", "aot_intrinsic_fmul_f64", AOT_INTRINSIC_FLAG_F64_FMUL }, - { "llvm.experimental.constrained.fdiv.f32", "aot_intrinsic_fdiv_f32", AOT_INTRINSIC_FLAG_F32_FDIV }, - { "llvm.experimental.constrained.fdiv.f64", "aot_intrinsic_fdiv_f64", AOT_INTRINSIC_FLAG_F64_FDIV }, - { "llvm.fabs.f32", "aot_intrinsic_fabs_f32", AOT_INTRINSIC_FLAG_F32_FABS }, - { "llvm.fabs.f64", "aot_intrinsic_fabs_f64", AOT_INTRINSIC_FLAG_F64_FABS }, - { "llvm.ceil.f32", "aot_intrinsic_ceil_f32", AOT_INTRINSIC_FLAG_F32_CEIL }, - { "llvm.ceil.f64", "aot_intrinsic_ceil_f64", AOT_INTRINSIC_FLAG_F64_CEIL }, - { "llvm.floor.f32", "aot_intrinsic_floor_f32", AOT_INTRINSIC_FLAG_F32_FLOOR }, - { "llvm.floor.f64", "aot_intrinsic_floor_f64", AOT_INTRINSIC_FLAG_F64_FLOOR }, - { "llvm.trunc.f32", "aot_intrinsic_trunc_f32", AOT_INTRINSIC_FLAG_F32_TRUNC }, - { "llvm.trunc.f64", "aot_intrinsic_trunc_f64", AOT_INTRINSIC_FLAG_F64_TRUNC }, - { "llvm.rint.f32", "aot_intrinsic_rint_f32", AOT_INTRINSIC_FLAG_F32_RINT }, - { "llvm.rint.f64", "aot_intrinsic_rint_f64", AOT_INTRINSIC_FLAG_F64_RINT }, - { "llvm.sqrt.f32", "aot_intrinsic_sqrt_f32", AOT_INTRINSIC_FLAG_F32_SQRT }, - { "llvm.sqrt.f64", "aot_intrinsic_sqrt_f64", AOT_INTRINSIC_FLAG_F64_SQRT }, - { "llvm.copysign.f32", "aot_intrinsic_copysign_f32", AOT_INTRINSIC_FLAG_F32_COPYSIGN }, - { "llvm.copysign.f64", "aot_intrinsic_copysign_f64", AOT_INTRINSIC_FLAG_F64_COPYSIGN }, - { "llvm.minnum.f32", "aot_intrinsic_fmin_f32", AOT_INTRINSIC_FLAG_F32_MIN }, - { "llvm.minnum.f64", "aot_intrinsic_fmin_f64", AOT_INTRINSIC_FLAG_F64_MIN }, - { "llvm.maxnum.f32", "aot_intrinsic_fmax_f32", AOT_INTRINSIC_FLAG_F32_MAX }, - { "llvm.maxnum.f64", "aot_intrinsic_fmax_f64", AOT_INTRINSIC_FLAG_F64_MAX }, - { "llvm.ctlz.i32", "aot_intrinsic_clz_i32", AOT_INTRINSIC_FLAG_I32_CLZ }, - { "llvm.ctlz.i64", "aot_intrinsic_clz_i64", AOT_INTRINSIC_FLAG_I64_CLZ }, - { "llvm.cttz.i32", "aot_intrinsic_ctz_i32", AOT_INTRINSIC_FLAG_I32_CTZ }, - { "llvm.cttz.i64", "aot_intrinsic_ctz_i64", AOT_INTRINSIC_FLAG_I64_CTZ }, - { "llvm.ctpop.i32", "aot_intrinsic_popcnt_i32", AOT_INTRINSIC_FLAG_I32_POPCNT }, - { "llvm.ctpop.i64", "aot_intrinsic_popcnt_i64", AOT_INTRINSIC_FLAG_I64_POPCNT }, - { "f64_convert_i32_s", "aot_intrinsic_i32_to_f64", AOT_INTRINSIC_FLAG_I32_TO_F64 }, - { "f64_convert_i32_u", "aot_intrinsic_u32_to_f64", AOT_INTRINSIC_FLAG_U32_TO_F64 }, - { "f32_convert_i32_s", "aot_intrinsic_i32_to_f32", AOT_INTRINSIC_FLAG_I32_TO_F32 }, - { "f32_convert_i32_u", "aot_intrinsic_u32_to_f32", AOT_INTRINSIC_FLAG_U32_TO_F32 }, - { "f64_convert_i64_s", "aot_intrinsic_i64_to_f64", AOT_INTRINSIC_FLAG_I32_TO_F64 }, - { "f64_convert_i64_u", "aot_intrinsic_u64_to_f64", AOT_INTRINSIC_FLAG_U64_TO_F64 }, - { "f32_convert_i64_s", "aot_intrinsic_i64_to_f32", AOT_INTRINSIC_FLAG_I64_TO_F32 }, - { "f32_convert_i64_u", "aot_intrinsic_u64_to_f32", AOT_INTRINSIC_FLAG_U64_TO_F32 }, - { "i32_trunc_f32_u", "aot_intrinsic_f32_to_u32", AOT_INTRINSIC_FLAG_F32_TO_U32 }, - { "i32_trunc_f32_s", "aot_intrinsic_f32_to_i32", AOT_INTRINSIC_FLAG_F32_TO_I32 }, - { "i32_trunc_f64_u", "aot_intrinsic_f64_to_u32", AOT_INTRINSIC_FLAG_F64_TO_U32 }, - { "i32_trunc_f64_s", "aot_intrinsic_f64_to_i32", AOT_INTRINSIC_FLAG_F64_TO_I32 }, - { "i64_trunc_f64_u", "aot_intrinsic_f64_to_u64", AOT_INTRINSIC_FLAG_F64_TO_U64 }, - { "i64_trunc_f32_s", "aot_intrinsic_f32_to_i64", AOT_INTRINSIC_FLAG_F32_TO_I64 }, - { "i64_trunc_f32_u", "aot_intrinsic_f32_to_u64", AOT_INTRINSIC_FLAG_F32_TO_U64 }, - { "i64_trunc_f64_s", "aot_intrinsic_f64_to_i64", AOT_INTRINSIC_FLAG_F64_TO_I64 }, - { "f32_demote_f64", "aot_intrinsic_f64_to_f32", AOT_INTRINSIC_FLAG_F64_TO_F32 }, - { "f64_promote_f32", "aot_intrinsic_f32_to_f64", AOT_INTRINSIC_FLAG_F32_TO_F64 }, - { "f32_cmp", "aot_intrinsic_f32_cmp", AOT_INTRINSIC_FLAG_F32_CMP }, - { "f64_cmp", "aot_intrinsic_f64_cmp", AOT_INTRINSIC_FLAG_F64_CMP }, - { "i32.const", NULL, AOT_INTRINSIC_FLAG_I32_CONST }, - { "i64.const", NULL, AOT_INTRINSIC_FLAG_I64_CONST }, - { "f32.const", NULL, AOT_INTRINSIC_FLAG_F32_CONST }, - { "f64.const", NULL, AOT_INTRINSIC_FLAG_F64_CONST }, - { "i64.div_s", "aot_intrinsic_i64_div_s", AOT_INTRINSIC_FLAG_I64_DIV_S}, - { "i32.div_s", "aot_intrinsic_i32_div_s", AOT_INTRINSIC_FLAG_I32_DIV_S}, - { "i32.div_u", "aot_intrinsic_i32_div_u", AOT_INTRINSIC_FLAG_I32_DIV_U}, - { "i32.rem_s", "aot_intrinsic_i32_rem_s", AOT_INTRINSIC_FLAG_I32_REM_S}, - { "i32.rem_u", "aot_intrinsic_i32_rem_u", AOT_INTRINSIC_FLAG_I32_REM_U}, - { "i64.div_u", "aot_intrinsic_i64_div_u", AOT_INTRINSIC_FLAG_I64_DIV_U}, - { "i64.rem_s", "aot_intrinsic_i64_rem_s", AOT_INTRINSIC_FLAG_I64_REM_S}, - { "i64.rem_u", "aot_intrinsic_i64_rem_u", AOT_INTRINSIC_FLAG_I64_REM_U}, - { "i64.or", "aot_intrinsic_i64_bit_or", AOT_INTRINSIC_FLAG_I64_BIT_OR}, - { "i64.and", "aot_intrinsic_i64_bit_and", AOT_INTRINSIC_FLAG_I64_BIT_AND}, -}; -/* clang-format on */ - -static const uint32 g_intrinsic_count = - sizeof(g_intrinsic_mapping) / sizeof(aot_intrinsic); - float32 aot_intrinsic_fadd_f32(float32 a, float32 b) { @@ -565,6 +485,88 @@ aot_intrinsic_i64_bit_and(uint64 l, uint64 r) return l & r; } +#if WASM_ENABLE_WAMR_COMPILER != 0 || WASM_ENABLE_JIT != 0 + +typedef struct { + const char *llvm_intrinsic; + const char *native_intrinsic; + uint64 flag; +} aot_intrinsic; + +/* clang-format off */ +static const aot_intrinsic g_intrinsic_mapping[] = { + { "llvm.experimental.constrained.fadd.f32", "aot_intrinsic_fadd_f32", AOT_INTRINSIC_FLAG_F32_FADD }, + { "llvm.experimental.constrained.fadd.f64", "aot_intrinsic_fadd_f64", AOT_INTRINSIC_FLAG_F64_FADD }, + { "llvm.experimental.constrained.fsub.f32", "aot_intrinsic_fsub_f32", AOT_INTRINSIC_FLAG_F32_FSUB }, + { "llvm.experimental.constrained.fsub.f64", "aot_intrinsic_fsub_f64", AOT_INTRINSIC_FLAG_F64_FSUB }, + { "llvm.experimental.constrained.fmul.f32", "aot_intrinsic_fmul_f32", AOT_INTRINSIC_FLAG_F32_FMUL }, + { "llvm.experimental.constrained.fmul.f64", "aot_intrinsic_fmul_f64", AOT_INTRINSIC_FLAG_F64_FMUL }, + { "llvm.experimental.constrained.fdiv.f32", "aot_intrinsic_fdiv_f32", AOT_INTRINSIC_FLAG_F32_FDIV }, + { "llvm.experimental.constrained.fdiv.f64", "aot_intrinsic_fdiv_f64", AOT_INTRINSIC_FLAG_F64_FDIV }, + { "llvm.fabs.f32", "aot_intrinsic_fabs_f32", AOT_INTRINSIC_FLAG_F32_FABS }, + { "llvm.fabs.f64", "aot_intrinsic_fabs_f64", AOT_INTRINSIC_FLAG_F64_FABS }, + { "llvm.ceil.f32", "aot_intrinsic_ceil_f32", AOT_INTRINSIC_FLAG_F32_CEIL }, + { "llvm.ceil.f64", "aot_intrinsic_ceil_f64", AOT_INTRINSIC_FLAG_F64_CEIL }, + { "llvm.floor.f32", "aot_intrinsic_floor_f32", AOT_INTRINSIC_FLAG_F32_FLOOR }, + { "llvm.floor.f64", "aot_intrinsic_floor_f64", AOT_INTRINSIC_FLAG_F64_FLOOR }, + { "llvm.trunc.f32", "aot_intrinsic_trunc_f32", AOT_INTRINSIC_FLAG_F32_TRUNC }, + { "llvm.trunc.f64", "aot_intrinsic_trunc_f64", AOT_INTRINSIC_FLAG_F64_TRUNC }, + { "llvm.rint.f32", "aot_intrinsic_rint_f32", AOT_INTRINSIC_FLAG_F32_RINT }, + { "llvm.rint.f64", "aot_intrinsic_rint_f64", AOT_INTRINSIC_FLAG_F64_RINT }, + { "llvm.sqrt.f32", "aot_intrinsic_sqrt_f32", AOT_INTRINSIC_FLAG_F32_SQRT }, + { "llvm.sqrt.f64", "aot_intrinsic_sqrt_f64", AOT_INTRINSIC_FLAG_F64_SQRT }, + { "llvm.copysign.f32", "aot_intrinsic_copysign_f32", AOT_INTRINSIC_FLAG_F32_COPYSIGN }, + { "llvm.copysign.f64", "aot_intrinsic_copysign_f64", AOT_INTRINSIC_FLAG_F64_COPYSIGN }, + { "llvm.minnum.f32", "aot_intrinsic_fmin_f32", AOT_INTRINSIC_FLAG_F32_MIN }, + { "llvm.minnum.f64", "aot_intrinsic_fmin_f64", AOT_INTRINSIC_FLAG_F64_MIN }, + { "llvm.maxnum.f32", "aot_intrinsic_fmax_f32", AOT_INTRINSIC_FLAG_F32_MAX }, + { "llvm.maxnum.f64", "aot_intrinsic_fmax_f64", AOT_INTRINSIC_FLAG_F64_MAX }, + { "llvm.ctlz.i32", "aot_intrinsic_clz_i32", AOT_INTRINSIC_FLAG_I32_CLZ }, + { "llvm.ctlz.i64", "aot_intrinsic_clz_i64", AOT_INTRINSIC_FLAG_I64_CLZ }, + { "llvm.cttz.i32", "aot_intrinsic_ctz_i32", AOT_INTRINSIC_FLAG_I32_CTZ }, + { "llvm.cttz.i64", "aot_intrinsic_ctz_i64", AOT_INTRINSIC_FLAG_I64_CTZ }, + { "llvm.ctpop.i32", "aot_intrinsic_popcnt_i32", AOT_INTRINSIC_FLAG_I32_POPCNT }, + { "llvm.ctpop.i64", "aot_intrinsic_popcnt_i64", AOT_INTRINSIC_FLAG_I64_POPCNT }, + { "f64_convert_i32_s", "aot_intrinsic_i32_to_f64", AOT_INTRINSIC_FLAG_I32_TO_F64 }, + { "f64_convert_i32_u", "aot_intrinsic_u32_to_f64", AOT_INTRINSIC_FLAG_U32_TO_F64 }, + { "f32_convert_i32_s", "aot_intrinsic_i32_to_f32", AOT_INTRINSIC_FLAG_I32_TO_F32 }, + { "f32_convert_i32_u", "aot_intrinsic_u32_to_f32", AOT_INTRINSIC_FLAG_U32_TO_F32 }, + { "f64_convert_i64_s", "aot_intrinsic_i64_to_f64", AOT_INTRINSIC_FLAG_I32_TO_F64 }, + { "f64_convert_i64_u", "aot_intrinsic_u64_to_f64", AOT_INTRINSIC_FLAG_U64_TO_F64 }, + { "f32_convert_i64_s", "aot_intrinsic_i64_to_f32", AOT_INTRINSIC_FLAG_I64_TO_F32 }, + { "f32_convert_i64_u", "aot_intrinsic_u64_to_f32", AOT_INTRINSIC_FLAG_U64_TO_F32 }, + { "i32_trunc_f32_u", "aot_intrinsic_f32_to_u32", AOT_INTRINSIC_FLAG_F32_TO_U32 }, + { "i32_trunc_f32_s", "aot_intrinsic_f32_to_i32", AOT_INTRINSIC_FLAG_F32_TO_I32 }, + { "i32_trunc_f64_u", "aot_intrinsic_f64_to_u32", AOT_INTRINSIC_FLAG_F64_TO_U32 }, + { "i32_trunc_f64_s", "aot_intrinsic_f64_to_i32", AOT_INTRINSIC_FLAG_F64_TO_I32 }, + { "i64_trunc_f64_u", "aot_intrinsic_f64_to_u64", AOT_INTRINSIC_FLAG_F64_TO_U64 }, + { "i64_trunc_f32_s", "aot_intrinsic_f32_to_i64", AOT_INTRINSIC_FLAG_F32_TO_I64 }, + { "i64_trunc_f32_u", "aot_intrinsic_f32_to_u64", AOT_INTRINSIC_FLAG_F32_TO_U64 }, + { "i64_trunc_f64_s", "aot_intrinsic_f64_to_i64", AOT_INTRINSIC_FLAG_F64_TO_I64 }, + { "f32_demote_f64", "aot_intrinsic_f64_to_f32", AOT_INTRINSIC_FLAG_F64_TO_F32 }, + { "f64_promote_f32", "aot_intrinsic_f32_to_f64", AOT_INTRINSIC_FLAG_F32_TO_F64 }, + { "f32_cmp", "aot_intrinsic_f32_cmp", AOT_INTRINSIC_FLAG_F32_CMP }, + { "f64_cmp", "aot_intrinsic_f64_cmp", AOT_INTRINSIC_FLAG_F64_CMP }, + { "i32.const", NULL, AOT_INTRINSIC_FLAG_I32_CONST }, + { "i64.const", NULL, AOT_INTRINSIC_FLAG_I64_CONST }, + { "f32.const", NULL, AOT_INTRINSIC_FLAG_F32_CONST }, + { "f64.const", NULL, AOT_INTRINSIC_FLAG_F64_CONST }, + { "i64.div_s", "aot_intrinsic_i64_div_s", AOT_INTRINSIC_FLAG_I64_DIV_S}, + { "i32.div_s", "aot_intrinsic_i32_div_s", AOT_INTRINSIC_FLAG_I32_DIV_S}, + { "i32.div_u", "aot_intrinsic_i32_div_u", AOT_INTRINSIC_FLAG_I32_DIV_U}, + { "i32.rem_s", "aot_intrinsic_i32_rem_s", AOT_INTRINSIC_FLAG_I32_REM_S}, + { "i32.rem_u", "aot_intrinsic_i32_rem_u", AOT_INTRINSIC_FLAG_I32_REM_U}, + { "i64.div_u", "aot_intrinsic_i64_div_u", AOT_INTRINSIC_FLAG_I64_DIV_U}, + { "i64.rem_s", "aot_intrinsic_i64_rem_s", AOT_INTRINSIC_FLAG_I64_REM_S}, + { "i64.rem_u", "aot_intrinsic_i64_rem_u", AOT_INTRINSIC_FLAG_I64_REM_U}, + { "i64.or", "aot_intrinsic_i64_bit_or", AOT_INTRINSIC_FLAG_I64_BIT_OR}, + { "i64.and", "aot_intrinsic_i64_bit_and", AOT_INTRINSIC_FLAG_I64_BIT_AND}, +}; +/* clang-format on */ + +static const uint32 g_intrinsic_count = + sizeof(g_intrinsic_mapping) / sizeof(aot_intrinsic); + const char * aot_intrinsic_get_symbol(const char *llvm_intrinsic) { @@ -577,8 +579,6 @@ aot_intrinsic_get_symbol(const char *llvm_intrinsic) return NULL; } -#if WASM_ENABLE_WAMR_COMPILER != 0 || WASM_ENABLE_JIT != 0 - static void add_intrinsic_capability(AOTCompContext *comp_ctx, uint64 flag) { diff --git a/core/iwasm/aot/aot_intrinsic.h b/core/iwasm/aot/aot_intrinsic.h index 2123058b9..6a456efda 100644 --- a/core/iwasm/aot/aot_intrinsic.h +++ b/core/iwasm/aot/aot_intrinsic.h @@ -287,10 +287,10 @@ aot_intrinsic_i64_bit_or(uint64 l, uint64 r); uint64 aot_intrinsic_i64_bit_and(uint64 l, uint64 r); +#if WASM_ENABLE_WAMR_COMPILER != 0 || WASM_ENABLE_JIT != 0 const char * aot_intrinsic_get_symbol(const char *llvm_intrinsic); -#if WASM_ENABLE_WAMR_COMPILER != 0 || WASM_ENABLE_JIT != 0 bool aot_intrinsic_check_capability(const AOTCompContext *comp_ctx, const char *llvm_intrinsic); diff --git a/core/iwasm/aot/aot_loader.c b/core/iwasm/aot/aot_loader.c index 5803f5391..df487039c 100644 --- a/core/iwasm/aot/aot_loader.c +++ b/core/iwasm/aot/aot_loader.c @@ -16,6 +16,10 @@ #include "debug/jit_debug.h" #endif +#if WASM_ENABLE_LINUX_PERF != 0 +#include "aot_perf_map.h" +#endif + #define YMM_PLT_PREFIX "__ymm@" #define XMM_PLT_PREFIX "__xmm@" #define REAL_PLT_PREFIX "__real@" @@ -289,55 +293,6 @@ loader_malloc(uint64 size, char *error_buf, uint32 error_buf_size) return mem; } -static char * -const_str_set_insert(const uint8 *str, int32 len, AOTModule *module, -#if (WASM_ENABLE_WORD_ALIGN_READ != 0) - bool is_vram_word_align, -#endif - char *error_buf, uint32 error_buf_size) -{ - HashMap *set = module->const_str_set; - char *c_str, *value; - - /* Create const string set if it isn't created */ - if (!set - && !(set = module->const_str_set = bh_hash_map_create( - 32, false, (HashFunc)wasm_string_hash, - (KeyEqualFunc)wasm_string_equal, NULL, wasm_runtime_free))) { - set_error_buf(error_buf, error_buf_size, - "create const string set failed"); - return NULL; - } - - /* Lookup const string set, use the string if found */ - 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, str, (uint32)len); - } - else -#endif - { - bh_memcpy_s(c_str, len, str, (uint32)len); - } - - if ((value = bh_hash_map_find(set, c_str))) { - wasm_runtime_free(c_str); - return value; - } - - if (!bh_hash_map_insert(set, c_str, c_str)) { - set_error_buf(error_buf, error_buf_size, - "insert string to hash map failed"); - wasm_runtime_free(c_str); - return NULL; - } - - return c_str; -} - static char * load_string(uint8 **p_buf, const uint8 *buf_end, AOTModule *module, bool is_load_from_file_buf, @@ -359,9 +314,9 @@ load_string(uint8 **p_buf, const uint8 *buf_end, AOTModule *module, } #if (WASM_ENABLE_WORD_ALIGN_READ != 0) else if (is_vram_word_align) { - if (!(str = const_str_set_insert((uint8 *)p, str_len, module, - is_vram_word_align, error_buf, - error_buf_size))) { + if (!(str = aot_const_str_set_insert((uint8 *)p, str_len, module, + is_vram_word_align, error_buf, + error_buf_size))) { goto fail; } } @@ -378,11 +333,11 @@ load_string(uint8 **p_buf, const uint8 *buf_end, AOTModule *module, 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 (!(str = aot_const_str_set_insert((uint8 *)p, str_len, module, #if (WASM_ENABLE_WORD_ALIGN_READ != 0) - is_vram_word_align, + is_vram_word_align, #endif - error_buf, error_buf_size))) { + error_buf, error_buf_size))) { goto fail; } } @@ -1479,9 +1434,20 @@ load_table_init_data_list(const uint8 **p_buf, const uint8 *buf_end, read_uint64(buf, buf_end, init_expr_value); #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); + uint16 ref_type, nullable; + read_uint16(buf, buf_end, ref_type); + if (elem_type != ref_type) { + set_error_buf(error_buf, error_buf_size, "invalid elem type"); + return false; + } + reftype.ref_ht_common.ref_type = (uint8)ref_type; + read_uint16(buf, buf_end, nullable); + if (nullable != 0 && nullable != 1) { + set_error_buf(error_buf, error_buf_size, + "invalid nullable value"); + return false; + } + reftype.ref_ht_common.nullable = (uint8)nullable; read_uint32(buf, buf_end, reftype.ref_ht_common.heap_type); } else @@ -2423,13 +2389,22 @@ load_init_data_section(const uint8 *buf, const uint8 *buf_end, } read_uint32(p, p_end, module->aux_data_end_global_index); - read_uint32(p, p_end, module->aux_data_end); + read_uint64(p, p_end, module->aux_data_end); read_uint32(p, p_end, module->aux_heap_base_global_index); - read_uint32(p, p_end, module->aux_heap_base); + read_uint64(p, p_end, module->aux_heap_base); read_uint32(p, p_end, module->aux_stack_top_global_index); - read_uint32(p, p_end, module->aux_stack_bottom); + read_uint64(p, p_end, module->aux_stack_bottom); read_uint32(p, p_end, module->aux_stack_size); + if (module->aux_data_end >= MAX_LINEAR_MEMORY_SIZE + || module->aux_heap_base >= MAX_LINEAR_MEMORY_SIZE + || module->aux_stack_bottom >= MAX_LINEAR_MEMORY_SIZE) { + set_error_buf( + error_buf, error_buf_size, + "invalid range of aux_date_end/aux_heap_base/aux_stack_bottom"); + return false; + } + if (!load_object_data_sections_info(&p, p_end, module, is_load_from_file_buf, error_buf, error_buf_size)) @@ -2500,15 +2475,26 @@ load_function_section(const uint8 *buf, const uint8 *buf_end, AOTModule *module, const uint8 *p = buf, *p_end = buf_end; uint32 i; uint64 size, text_offset; + uint32 func_count = module->func_count; - size = sizeof(void *) * (uint64)module->func_count; +#if defined(BUILD_TARGET_XTENSA) + /* + * For Xtensa XIP, real func_count is doubled, including aot_func and + * aot_func_internal, so need to multipy func_count by 2 here. + */ + if (module->is_indirect_mode) { + func_count *= 2; + } +#endif + + size = sizeof(void *) * (uint64)func_count; if (size > 0 && !(module->func_ptrs = loader_malloc(size, error_buf, error_buf_size))) { return false; } - for (i = 0; i < module->func_count; i++) { + for (i = 0; i < func_count; i++) { if (sizeof(void *) == 8) { read_uint64(p, p_end, text_offset); } @@ -2543,14 +2529,14 @@ load_function_section(const uint8 *buf, const uint8 *buf_end, AOTModule *module, module->start_function = NULL; } - size = sizeof(uint32) * (uint64)module->func_count; + size = sizeof(uint32) * (uint64)func_count; if (size > 0 && !(module->func_type_indexes = loader_malloc(size, error_buf, error_buf_size))) { return false; } - for (i = 0; i < module->func_count; i++) { + for (i = 0; i < func_count; i++) { read_uint32(p, p_end, module->func_type_indexes[i]); if (module->func_type_indexes[i] >= module->type_count) { set_error_buf(error_buf, error_buf_size, "unknown type"); @@ -2897,6 +2883,17 @@ do_text_relocation(AOTModule *module, AOTRelocationGroup *group, } symbol_addr = module->func_ptrs[func_index]; } + else if (!strncmp(symbol, "_" AOT_FUNC_INTERNAL_PREFIX, + strlen("_" AOT_FUNC_INTERNAL_PREFIX))) { + p = symbol + strlen("_" AOT_FUNC_INTERNAL_PREFIX); + if (*p == '\0' + || (func_index = (uint32)atoi(p)) > module->func_count) { + set_error_buf_v(error_buf, error_buf_size, "invalid symbol %s", + symbol); + goto check_symbol_fail; + } + symbol_addr = module->func_ptrs[func_index]; + } #endif else if (is_text_section(symbol)) { symbol_addr = module->code; @@ -3608,104 +3605,6 @@ fail: return ret; } -#if WASM_ENABLE_LINUX_PERF != 0 -struct func_info { - uint32 idx; - void *ptr; -}; - -static uint32 -get_func_size(const AOTModule *module, struct func_info *sorted_func_ptrs, - uint32 idx) -{ - uint32 func_sz; - - if (idx == module->func_count - 1) - func_sz = (uintptr_t)module->code + module->code_size - - (uintptr_t)(sorted_func_ptrs[idx].ptr); - else - func_sz = (uintptr_t)(sorted_func_ptrs[idx + 1].ptr) - - (uintptr_t)(sorted_func_ptrs[idx].ptr); - - return func_sz; -} - -static int -compare_func_ptrs(const void *f1, const void *f2) -{ - return (intptr_t)((struct func_info *)f1)->ptr - - (intptr_t)((struct func_info *)f2)->ptr; -} - -static struct func_info * -sort_func_ptrs(const AOTModule *module, char *error_buf, uint32 error_buf_size) -{ - uint64 content_len; - struct func_info *sorted_func_ptrs; - unsigned i; - - content_len = (uint64)sizeof(struct func_info) * module->func_count; - sorted_func_ptrs = loader_malloc(content_len, error_buf, error_buf_size); - if (!sorted_func_ptrs) - return NULL; - - for (i = 0; i < module->func_count; i++) { - sorted_func_ptrs[i].idx = i; - sorted_func_ptrs[i].ptr = module->func_ptrs[i]; - } - - qsort(sorted_func_ptrs, module->func_count, sizeof(struct func_info), - compare_func_ptrs); - - return sorted_func_ptrs; -} - -static bool -create_perf_map(const AOTModule *module, char *error_buf, uint32 error_buf_size) -{ - struct func_info *sorted_func_ptrs = NULL; - char perf_map_info[128] = { 0 }; - FILE *perf_map = NULL; - uint32 i; - pid_t pid = getpid(); - bool ret = false; - - sorted_func_ptrs = sort_func_ptrs(module, error_buf, error_buf_size); - if (!sorted_func_ptrs) - goto quit; - - snprintf(perf_map_info, 128, "/tmp/perf-%d.map", pid); - perf_map = fopen(perf_map_info, "w"); - if (!perf_map) { - LOG_WARNING("warning: can't create /tmp/perf-%d.map, because %s", pid, - strerror(errno)); - goto quit; - } - - for (i = 0; i < module->func_count; i++) { - memset(perf_map_info, 0, 128); - snprintf(perf_map_info, 128, "%lx %x aot_func#%u\n", - (uintptr_t)sorted_func_ptrs[i].ptr, - get_func_size(module, sorted_func_ptrs, i), - sorted_func_ptrs[i].idx); - - fwrite(perf_map_info, 1, strlen(perf_map_info), perf_map); - } - - LOG_VERBOSE("generate /tmp/perf-%d.map", pid); - ret = true; - -quit: - if (sorted_func_ptrs) - free(sorted_func_ptrs); - - if (perf_map) - fclose(perf_map); - - return ret; -} -#endif /* WASM_ENABLE_LINUX_PERF != 0*/ - static bool load_from_sections(AOTModule *module, AOTSection *sections, bool is_load_from_file_buf, char *error_buf, @@ -3896,7 +3795,7 @@ load_from_sections(AOTModule *module, AOTSection *sections, } static AOTModule * -create_module(char *error_buf, uint32 error_buf_size) +create_module(char *name, char *error_buf, uint32 error_buf_size) { AOTModule *module = loader_malloc(sizeof(AOTModule), error_buf, error_buf_size); @@ -3908,6 +3807,8 @@ create_module(char *error_buf, uint32 error_buf_size) module->module_type = Wasm_Module_AoT; + module->name = name; + #if WASM_ENABLE_MULTI_MODULE != 0 module->import_module_list = &module->import_module_list_head; ret = bh_list_init(module->import_module_list); @@ -3942,7 +3843,7 @@ AOTModule * aot_load_from_sections(AOTSection *section_list, char *error_buf, uint32 error_buf_size) { - AOTModule *module = create_module(error_buf, error_buf_size); + AOTModule *module = create_module("", error_buf, error_buf_size); if (!module) return NULL; @@ -4188,7 +4089,7 @@ load(const uint8 *buf, uint32 size, AOTModule *module, char *error_buf, #if WASM_ENABLE_LINUX_PERF != 0 if (wasm_runtime_get_linux_perf()) - if (!create_perf_map(module, error_buf, error_buf_size)) + if (!aot_create_perf_map(module, error_buf, error_buf_size)) goto fail; #endif @@ -4198,10 +4099,10 @@ fail: } AOTModule * -aot_load_from_aot_file(const uint8 *buf, uint32 size, char *error_buf, - uint32 error_buf_size) +aot_load_from_aot_file(const uint8 *buf, uint32 size, const LoadArgs *args, + char *error_buf, uint32 error_buf_size) { - AOTModule *module = create_module(error_buf, error_buf_size); + AOTModule *module = create_module(args->name, error_buf, error_buf_size); if (!module) return NULL; @@ -4395,7 +4296,7 @@ aot_unload(AOTModule *module) } if (module->string_literal_ptrs) { - wasm_runtime_free(module->string_literal_ptrs); + wasm_runtime_free((void *)module->string_literal_ptrs); } } #endif diff --git a/core/iwasm/aot/aot_perf_map.c b/core/iwasm/aot/aot_perf_map.c new file mode 100644 index 000000000..22700dcdd --- /dev/null +++ b/core/iwasm/aot/aot_perf_map.c @@ -0,0 +1,120 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include "aot_perf_map.h" +#include "bh_log.h" +#include "bh_platform.h" + +#if WASM_ENABLE_LINUX_PERF != 0 +struct func_info { + uint32 idx; + void *ptr; +}; + +static uint32 +get_func_size(const AOTModule *module, struct func_info *sorted_func_ptrs, + uint32 idx) +{ + uint32 func_sz; + + if (idx == module->func_count - 1) + func_sz = (uintptr_t)module->code + module->code_size + - (uintptr_t)(sorted_func_ptrs[idx].ptr); + else + func_sz = (uintptr_t)(sorted_func_ptrs[idx + 1].ptr) + - (uintptr_t)(sorted_func_ptrs[idx].ptr); + + return func_sz; +} + +static int +compare_func_ptrs(const void *f1, const void *f2) +{ + return (intptr_t)((struct func_info *)f1)->ptr + - (intptr_t)((struct func_info *)f2)->ptr; +} + +static struct func_info * +sort_func_ptrs(const AOTModule *module, char *error_buf, uint32 error_buf_size) +{ + uint64 content_len; + struct func_info *sorted_func_ptrs; + unsigned i; + + content_len = (uint64)sizeof(struct func_info) * module->func_count; + sorted_func_ptrs = wasm_runtime_malloc(content_len); + if (!sorted_func_ptrs) { + snprintf(error_buf, error_buf_size, + "allocate memory failed when creating perf map"); + return NULL; + } + + for (i = 0; i < module->func_count; i++) { + sorted_func_ptrs[i].idx = i; + sorted_func_ptrs[i].ptr = module->func_ptrs[i]; + } + + qsort(sorted_func_ptrs, module->func_count, sizeof(struct func_info), + compare_func_ptrs); + + return sorted_func_ptrs; +} + +bool +aot_create_perf_map(const AOTModule *module, char *error_buf, + uint32 error_buf_size) +{ + struct func_info *sorted_func_ptrs = NULL; + char perf_map_path[64] = { 0 }; + char perf_map_info[128] = { 0 }; + FILE *perf_map = NULL; + uint32 i; + pid_t pid = getpid(); + bool ret = false; + + sorted_func_ptrs = sort_func_ptrs(module, error_buf, error_buf_size); + if (!sorted_func_ptrs) + goto quit; + + snprintf(perf_map_path, sizeof(perf_map_path) - 1, "/tmp/perf-%d.map", pid); + perf_map = fopen(perf_map_path, "a"); + if (!perf_map) { + LOG_WARNING("warning: can't create /tmp/perf-%d.map, because %s", pid, + strerror(errno)); + goto quit; + } + + const char *module_name = aot_get_module_name((AOTModule *)module); + for (i = 0; i < module->func_count; i++) { + memset(perf_map_info, 0, 128); + if (strlen(module_name) > 0) + snprintf(perf_map_info, 128, "%lx %x [%s]#aot_func#%u\n", + (uintptr_t)sorted_func_ptrs[i].ptr, + get_func_size(module, sorted_func_ptrs, i), module_name, + sorted_func_ptrs[i].idx); + else + snprintf(perf_map_info, 128, "%lx %x aot_func#%u\n", + (uintptr_t)sorted_func_ptrs[i].ptr, + get_func_size(module, sorted_func_ptrs, i), + sorted_func_ptrs[i].idx); + + /* fwrite() is thread safe */ + fwrite(perf_map_info, 1, strlen(perf_map_info), perf_map); + } + + LOG_VERBOSE("write map information from %s into /tmp/perf-%d.map", + module_name, pid); + ret = true; + +quit: + if (sorted_func_ptrs) + wasm_runtime_free(sorted_func_ptrs); + + if (perf_map) + fclose(perf_map); + + return ret; +} +#endif /* WASM_ENABLE_LINUX_PERF != 0 */ \ No newline at end of file diff --git a/core/iwasm/aot/aot_perf_map.h b/core/iwasm/aot/aot_perf_map.h new file mode 100644 index 000000000..3e6583c5c --- /dev/null +++ b/core/iwasm/aot/aot_perf_map.h @@ -0,0 +1,15 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef _AOT_PERF_MAP_H_ +#define _AOT_PERF_MAP_H_ + +#include "aot_runtime.h" + +bool +aot_create_perf_map(const AOTModule *module, char *error_buf, + uint32 error_buf_size); + +#endif /* _AOT_PERF_MAP_H_ */ \ No newline at end of file diff --git a/core/iwasm/aot/aot_reloc.h b/core/iwasm/aot/aot_reloc.h index c250f20a7..293e2fc79 100644 --- a/core/iwasm/aot/aot_reloc.h +++ b/core/iwasm/aot/aot_reloc.h @@ -62,6 +62,7 @@ typedef struct { #define REG_AOT_TRACE_SYM() #endif +#if WASM_ENABLE_AOT_INTRINSICS != 0 #define REG_INTRINSIC_SYM() \ REG_SYM(aot_intrinsic_fabs_f32), \ REG_SYM(aot_intrinsic_fabs_f64), \ @@ -124,7 +125,10 @@ typedef struct { REG_SYM(aot_intrinsic_i32_div_s), \ REG_SYM(aot_intrinsic_i32_div_u), \ REG_SYM(aot_intrinsic_i32_rem_s), \ - REG_SYM(aot_intrinsic_i32_rem_u), \ + REG_SYM(aot_intrinsic_i32_rem_u), +#else +#define REG_INTRINSIC_SYM() +#endif #if WASM_ENABLE_STATIC_PGO != 0 #define REG_LLVM_PGO_SYM() \ diff --git a/core/iwasm/aot/aot_runtime.c b/core/iwasm/aot/aot_runtime.c index abfccc7b7..f8757fcc6 100644 --- a/core/iwasm/aot/aot_runtime.c +++ b/core/iwasm/aot/aot_runtime.c @@ -47,15 +47,15 @@ bh_static_assert(offsetof(AOTModuleInstance, func_type_indexes) == 6 * sizeof(uint64)); bh_static_assert(offsetof(AOTModuleInstance, cur_exception) == 13 * sizeof(uint64)); +bh_static_assert(offsetof(AOTModuleInstance, c_api_func_imports) + == 13 * sizeof(uint64) + 128 + 7 * sizeof(uint64)); bh_static_assert(offsetof(AOTModuleInstance, global_table_data) - == 13 * sizeof(uint64) + 128 + 11 * sizeof(uint64)); + == 13 * sizeof(uint64) + 128 + 14 * sizeof(uint64)); -bh_static_assert(sizeof(AOTMemoryInstance) == 104); +bh_static_assert(sizeof(AOTMemoryInstance) == 120); 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) - == sizeof(uint64)); bh_static_assert(sizeof(CApiFuncImport) == sizeof(uintptr_t) * 3); @@ -783,15 +783,19 @@ static AOTMemoryInstance * memory_instantiate(AOTModuleInstance *module_inst, AOTModuleInstance *parent, AOTModule *module, AOTMemoryInstance *memory_inst, AOTMemory *memory, uint32 memory_idx, uint32 heap_size, - char *error_buf, uint32 error_buf_size) + uint32 max_memory_pages, char *error_buf, + uint32 error_buf_size) { void *heap_handle; uint32 num_bytes_per_page = memory->num_bytes_per_page; uint32 init_page_count = memory->mem_init_page_count; - uint32 max_page_count = memory->mem_max_page_count; - uint32 inc_page_count, aux_heap_base, global_idx; + uint32 max_page_count = + wasm_runtime_get_max_mem(max_memory_pages, memory->mem_init_page_count, + memory->mem_max_page_count); + uint32 inc_page_count, global_idx; uint32 bytes_of_last_page, bytes_to_page_end; - uint32 heap_offset = num_bytes_per_page * init_page_count; + uint64 aux_heap_base, + heap_offset = (uint64)num_bytes_per_page * init_page_count; uint64 memory_data_size, max_memory_data_size; uint8 *p = NULL, *global_addr; @@ -816,6 +820,15 @@ memory_instantiate(AOTModuleInstance *module_inst, AOTModuleInstance *parent, heap_size = 0; } + /* If initial memory is the largest size allowed, disallowing insert host + * managed heap */ + if (heap_size > 0 && heap_offset == MAX_LINEAR_MEMORY_SIZE) { + set_error_buf(error_buf, error_buf_size, + "failed to insert app heap into linear memory, " + "try using `--heap-size=0` option"); + return NULL; + } + if (init_page_count == max_page_count && init_page_count == 1) { /* If only one page and at most one page, we just append the app heap to the end of linear memory, enlarge the @@ -839,7 +852,7 @@ memory_instantiate(AOTModuleInstance *module_inst, AOTModuleInstance *parent, } else if (module->aux_heap_base_global_index != (uint32)-1 && module->aux_heap_base - < num_bytes_per_page * init_page_count) { + < (uint64)num_bytes_per_page * init_page_count) { /* Insert app heap before __heap_base */ aux_heap_base = module->aux_heap_base; bytes_of_last_page = aux_heap_base % num_bytes_per_page; @@ -866,15 +879,15 @@ memory_instantiate(AOTModuleInstance *module_inst, AOTModuleInstance *parent, - module->import_global_count; global_addr = module_inst->global_data + module->globals[global_idx].data_offset; - *(uint32 *)global_addr = aux_heap_base; - LOG_VERBOSE("Reset __heap_base global to %u", aux_heap_base); + *(uint32 *)global_addr = (uint32)aux_heap_base; + LOG_VERBOSE("Reset __heap_base global to %" PRIu64, aux_heap_base); } else { /* Insert app heap before new page */ inc_page_count = (heap_size + num_bytes_per_page - 1) / num_bytes_per_page; - heap_offset = num_bytes_per_page * init_page_count; - heap_size = num_bytes_per_page * inc_page_count; + heap_offset = (uint64)num_bytes_per_page * init_page_count; + heap_size = (uint64)num_bytes_per_page * inc_page_count; if (heap_size > 0) heap_size -= 1 * BH_KB; } @@ -886,34 +899,26 @@ memory_instantiate(AOTModuleInstance *module_inst, AOTModuleInstance *parent, "try using `--heap-size=0` option"); return NULL; } - else if (init_page_count == DEFAULT_MAX_PAGES) { - num_bytes_per_page = UINT32_MAX; - init_page_count = max_page_count = 1; - } if (max_page_count > DEFAULT_MAX_PAGES) max_page_count = DEFAULT_MAX_PAGES; } - else { /* heap_size == 0 */ - if (init_page_count == DEFAULT_MAX_PAGES) { - num_bytes_per_page = UINT32_MAX; - init_page_count = max_page_count = 1; - } - } LOG_VERBOSE("Memory instantiate:"); LOG_VERBOSE(" page bytes: %u, init pages: %u, max pages: %u", num_bytes_per_page, init_page_count, max_page_count); - LOG_VERBOSE(" data offset: %u, stack size: %d", module->aux_data_end, - module->aux_stack_size); - LOG_VERBOSE(" heap offset: %u, heap size: %d\n", heap_offset, heap_size); + LOG_VERBOSE(" data offset: %" PRIu64 ", stack size: %d", + module->aux_data_end, module->aux_stack_size); + LOG_VERBOSE(" heap offset: %" PRIu64 ", heap size: %d\n", heap_offset, + heap_size); max_memory_data_size = (uint64)num_bytes_per_page * max_page_count; - bh_assert(max_memory_data_size <= 4 * (uint64)BH_GB); + bh_assert(max_memory_data_size <= MAX_LINEAR_MEMORY_SIZE); (void)max_memory_data_size; - if (wasm_allocate_linear_memory(&p, is_shared_memory, num_bytes_per_page, - init_page_count, max_page_count, - &memory_data_size) + /* TODO: memory64 uses is_memory64 flag */ + if (wasm_allocate_linear_memory(&p, is_shared_memory, false, + 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"); @@ -924,11 +929,11 @@ memory_instantiate(AOTModuleInstance *module_inst, AOTModuleInstance *parent, memory_inst->num_bytes_per_page = num_bytes_per_page; memory_inst->cur_page_count = init_page_count; memory_inst->max_page_count = max_page_count; - memory_inst->memory_data_size = (uint32)memory_data_size; + memory_inst->memory_data_size = memory_data_size; /* Init memory info */ memory_inst->memory_data = p; - memory_inst->memory_data_end = p + (uint32)memory_data_size; + memory_inst->memory_data_end = p + memory_data_size; /* Initialize heap info */ memory_inst->heap_data = p + heap_offset; @@ -984,7 +989,8 @@ aot_get_default_memory(AOTModuleInstance *module_inst) static bool memories_instantiate(AOTModuleInstance *module_inst, AOTModuleInstance *parent, - AOTModule *module, uint32 heap_size, char *error_buf, + AOTModule *module, uint32 heap_size, + uint32 max_memory_pages, char *error_buf, uint32 error_buf_size) { uint32 global_index, global_data_offset, base_offset, length; @@ -1002,9 +1008,9 @@ memories_instantiate(AOTModuleInstance *module_inst, AOTModuleInstance *parent, memories = module_inst->global_table_data.memory_instances; for (i = 0; i < memory_count; i++, memories++) { - memory_inst = memory_instantiate(module_inst, parent, module, memories, - &module->memories[i], i, heap_size, - error_buf, error_buf_size); + memory_inst = memory_instantiate( + module_inst, parent, module, memories, &module->memories[i], i, + heap_size, max_memory_pages, error_buf, error_buf_size); if (!memory_inst) { return false; } @@ -1065,8 +1071,8 @@ memories_instantiate(AOTModuleInstance *module_inst, AOTModuleInstance *parent, /* Check memory data */ /* check offset since length might negative */ if (base_offset > memory_inst->memory_data_size) { - LOG_DEBUG("base_offset(%d) > memory_data_size(%d)", base_offset, - memory_inst->memory_data_size); + LOG_DEBUG("base_offset(%d) > memory_data_size(%" PRIu64 ")", + base_offset, memory_inst->memory_data_size); #if WASM_ENABLE_REF_TYPES != 0 set_error_buf(error_buf, error_buf_size, "out of bounds memory access"); @@ -1080,7 +1086,8 @@ memories_instantiate(AOTModuleInstance *module_inst, AOTModuleInstance *parent, /* check offset + length(could be zero) */ length = data_seg->byte_count; if (base_offset + length > memory_inst->memory_data_size) { - LOG_DEBUG("base_offset(%d) + length(%d) > memory_data_size(%d)", + LOG_DEBUG("base_offset(%d) + length(%d) > memory_data_size(%" PRIu64 + ")", base_offset, length, memory_inst->memory_data_size); #if WASM_ENABLE_REF_TYPES != 0 set_error_buf(error_buf, error_buf_size, @@ -1094,7 +1101,7 @@ memories_instantiate(AOTModuleInstance *module_inst, AOTModuleInstance *parent, if (memory_inst->memory_data) { bh_memcpy_s((uint8 *)memory_inst->memory_data + base_offset, - memory_inst->memory_data_size - base_offset, + (uint32)memory_inst->memory_data_size - base_offset, data_seg->bytes, length); } } @@ -1108,10 +1115,21 @@ init_func_ptrs(AOTModuleInstance *module_inst, AOTModule *module, { uint32 i; void **func_ptrs; - uint64 total_size = ((uint64)module->import_func_count + module->func_count) - * sizeof(void *); + uint32 func_count = module->func_count; +#if defined(BUILD_TARGET_XTENSA) + /* + * For Xtensa XIP, real func_count is doubled, including aot_func and + * aot_func_internal, so need to multipy func_count by 2 here. + */ + if (module->is_indirect_mode) { + func_count *= 2; + } +#endif - if (module->import_func_count + module->func_count == 0) + uint64 total_size = + ((uint64)module->import_func_count + func_count) * sizeof(void *); + + if (module->import_func_count + func_count == 0) return true; /* Allocate memory */ @@ -1133,8 +1151,8 @@ init_func_ptrs(AOTModuleInstance *module_inst, AOTModule *module, } /* Set defined function pointers */ - bh_memcpy_s(func_ptrs, sizeof(void *) * module->func_count, - module->func_ptrs, sizeof(void *) * module->func_count); + bh_memcpy_s(func_ptrs, sizeof(void *) * func_count, module->func_ptrs, + sizeof(void *) * func_count); return true; } @@ -1144,10 +1162,21 @@ init_func_type_indexes(AOTModuleInstance *module_inst, AOTModule *module, { uint32 i; uint32 *func_type_index; - uint64 total_size = ((uint64)module->import_func_count + module->func_count) - * sizeof(uint32); + uint32 func_count = module->func_count; +#if defined(BUILD_TARGET_XTENSA) + /* + * For Xtensa XIP, real func_count is doubled, including aot_func and + * aot_func_internal, so need to multipy func_count by 2 here. + */ + if (module->is_indirect_mode) { + func_count *= 2; + } +#endif - if (module->import_func_count + module->func_count == 0) + uint64 total_size = + ((uint64)module->import_func_count + func_count) * sizeof(uint32); + + if (module->import_func_count + func_count == 0) return true; /* Allocate memory */ @@ -1161,8 +1190,8 @@ init_func_type_indexes(AOTModuleInstance *module_inst, AOTModule *module, for (i = 0; i < module->import_func_count; i++, func_type_index++) *func_type_index = module->import_funcs[i].func_type_index; - bh_memcpy_s(func_type_index, sizeof(uint32) * module->func_count, - module->func_type_indexes, sizeof(uint32) * module->func_count); + bh_memcpy_s(func_type_index, sizeof(uint32) * func_count, + module->func_type_indexes, sizeof(uint32) * func_count); return true; } @@ -1247,7 +1276,7 @@ lookup_post_instantiate_func(AOTModuleInstance *module_inst, AOTFunctionInstance *func; AOTFuncType *func_type; - if (!(func = aot_lookup_function(module_inst, func_name, NULL))) + if (!(func = aot_lookup_function(module_inst, func_name))) /* Not found */ return NULL; @@ -1439,7 +1468,7 @@ check_linked_symbol(AOTModule *module, char *error_buf, uint32 error_buf_size) AOTModuleInstance * aot_instantiate(AOTModule *module, AOTModuleInstance *parent, WASMExecEnv *exec_env_main, uint32 stack_size, uint32 heap_size, - char *error_buf, uint32 error_buf_size) + uint32 max_memory_pages, char *error_buf, uint32 error_buf_size) { AOTModuleInstance *module_inst; #if WASM_ENABLE_BULK_MEMORY != 0 || WASM_ENABLE_REF_TYPES != 0 @@ -1529,7 +1558,7 @@ aot_instantiate(AOTModule *module, AOTModuleInstance *parent, &((AOTModuleInstanceExtra *)module_inst->e)->sub_module_inst_list_head; ret = wasm_runtime_sub_module_instantiate( (WASMModuleCommon *)module, (WASMModuleInstanceCommon *)module_inst, - stack_size, heap_size, error_buf, error_buf_size); + stack_size, heap_size, max_memory_pages, error_buf, error_buf_size); if (!ret) { LOG_DEBUG("build a sub module list failed"); goto fail; @@ -1591,8 +1620,8 @@ aot_instantiate(AOTModule *module, AOTModuleInstance *parent, goto fail; /* Initialize memory space */ - if (!memories_instantiate(module_inst, parent, module, heap_size, error_buf, - error_buf_size)) + if (!memories_instantiate(module_inst, parent, module, heap_size, + max_memory_pages, error_buf, error_buf_size)) goto fail; /* Initialize function pointers */ @@ -1882,9 +1911,8 @@ aot_deinstantiate(AOTModuleInstance *module_inst, bool is_sub_inst) if (module_inst->func_type_indexes) wasm_runtime_free(module_inst->func_type_indexes); - if (common->c_api_func_imports) - wasm_runtime_free(((AOTModuleInstanceExtra *)module_inst->e) - ->common.c_api_func_imports); + if (module_inst->c_api_func_imports) + wasm_runtime_free(module_inst->c_api_func_imports); #if WASM_ENABLE_GC != 0 if (!is_sub_inst) { @@ -1915,8 +1943,7 @@ aot_deinstantiate(AOTModuleInstance *module_inst, bool is_sub_inst) } AOTFunctionInstance * -aot_lookup_function(const AOTModuleInstance *module_inst, const char *name, - const char *signature) +aot_lookup_function(const AOTModuleInstance *module_inst, const char *name) { uint32 i; AOTFunctionInstance *export_funcs = @@ -1925,7 +1952,6 @@ aot_lookup_function(const AOTModuleInstance *module_inst, const char *name, for (i = 0; i < module_inst->export_func_count; i++) if (!strcmp(export_funcs[i].func_name, name)) return &export_funcs[i]; - (void)signature; return NULL; } @@ -2131,8 +2157,8 @@ aot_call_function(WASMExecEnv *exec_env, AOTFunctionInstance *function, hw bound check is enabled */ #endif - /* Set exec env so it can be later retrieved from instance */ - ((AOTModuleInstanceExtra *)module_inst->e)->common.cur_exec_env = exec_env; + /* Set exec env, so it can be later retrieved from instance */ + module_inst->cur_exec_env = exec_env; if (ext_ret_count > 0) { uint32 cell_num = 0, i; @@ -2446,9 +2472,9 @@ execute_free_function(AOTModuleInstance *module_inst, WASMExecEnv *exec_env, return ret; } -uint32 +uint64 aot_module_malloc_internal(AOTModuleInstance *module_inst, - WASMExecEnv *exec_env, uint32 size, + WASMExecEnv *exec_env, uint64 size, void **p_native_addr) { AOTMemoryInstance *memory_inst = aot_get_default_memory(module_inst); @@ -2456,38 +2482,37 @@ aot_module_malloc_internal(AOTModuleInstance *module_inst, uint8 *addr = NULL; uint32 offset = 0; + /* TODO: Memory64 size check based on memory idx type */ + bh_assert(size <= UINT32_MAX); + if (!memory_inst) { aot_set_exception(module_inst, "uninitialized memory"); return 0; } if (memory_inst->heap_handle) { - addr = mem_allocator_malloc(memory_inst->heap_handle, size); + addr = mem_allocator_malloc(memory_inst->heap_handle, (uint32)size); } else if (module->malloc_func_index != (uint32)-1 && module->free_func_index != (uint32)-1) { AOTFunctionInstance *malloc_func, *retain_func = NULL; char *malloc_func_name; - char *malloc_func_sig; if (module->retain_func_index != (uint32)-1) { malloc_func_name = "__new"; - malloc_func_sig = "(ii)i"; - retain_func = aot_lookup_function(module_inst, "__retain", "(i)i"); + retain_func = aot_lookup_function(module_inst, "__retain"); if (!retain_func) - retain_func = aot_lookup_function(module_inst, "__pin", "(i)i"); + retain_func = aot_lookup_function(module_inst, "__pin"); bh_assert(retain_func); } else { malloc_func_name = "malloc"; - malloc_func_sig = "(i)i"; } - malloc_func = - aot_lookup_function(module_inst, malloc_func_name, malloc_func_sig); + malloc_func = aot_lookup_function(module_inst, malloc_func_name); if (!malloc_func || !execute_malloc_function(module_inst, exec_env, malloc_func, - retain_func, size, &offset)) { + retain_func, (uint32)size, &offset)) { return 0; } addr = offset ? (uint8 *)memory_inst->memory_data + offset : NULL; @@ -2500,23 +2525,28 @@ aot_module_malloc_internal(AOTModuleInstance *module_inst, aot_set_exception(module_inst, "app heap corrupted"); } else { - LOG_WARNING("warning: allocate %u bytes memory failed", size); + LOG_WARNING("warning: allocate %" PRIu64 " bytes memory failed", + size); } return 0; } if (p_native_addr) *p_native_addr = addr; - return (uint32)(addr - memory_inst->memory_data); + return (uint64)(addr - memory_inst->memory_data); } -uint32 +uint64 aot_module_realloc_internal(AOTModuleInstance *module_inst, - WASMExecEnv *exec_env, uint32 ptr, uint32 size, + WASMExecEnv *exec_env, uint64 ptr, uint64 size, void **p_native_addr) { AOTMemoryInstance *memory_inst = aot_get_default_memory(module_inst); uint8 *addr = NULL; + /* TODO: Memory64 ptr and size check based on memory idx type */ + bh_assert(ptr <= UINT32_MAX); + bh_assert(size <= UINT32_MAX); + if (!memory_inst) { aot_set_exception(module_inst, "uninitialized memory"); return 0; @@ -2525,7 +2555,8 @@ aot_module_realloc_internal(AOTModuleInstance *module_inst, if (memory_inst->heap_handle) { addr = mem_allocator_realloc( memory_inst->heap_handle, - ptr ? memory_inst->memory_data + ptr : NULL, size); + (uint32)ptr ? memory_inst->memory_data + (uint32)ptr : NULL, + (uint32)size); } /* Only support realloc in WAMR's app heap */ @@ -2544,12 +2575,12 @@ aot_module_realloc_internal(AOTModuleInstance *module_inst, if (p_native_addr) *p_native_addr = addr; - return (uint32)(addr - memory_inst->memory_data); + return (uint64)(addr - memory_inst->memory_data); } void aot_module_free_internal(AOTModuleInstance *module_inst, WASMExecEnv *exec_env, - uint32 ptr) + uint64 ptr) { AOTMemoryInstance *memory_inst = aot_get_default_memory(module_inst); AOTModule *module = (AOTModule *)module_inst->module; @@ -2558,8 +2589,11 @@ aot_module_free_internal(AOTModuleInstance *module_inst, WASMExecEnv *exec_env, return; } + /* TODO: Memory64 ptr and size check based on memory idx type */ + bh_assert(ptr <= UINT32_MAX); + if (ptr) { - uint8 *addr = memory_inst->memory_data + ptr; + uint8 *addr = memory_inst->memory_data + (uint32)ptr; uint8 *memory_data_end; /* memory->memory_data_end may be changed in memory grow */ @@ -2584,26 +2618,26 @@ aot_module_free_internal(AOTModuleInstance *module_inst, WASMExecEnv *exec_env, else { free_func_name = "free"; } - free_func = - aot_lookup_function(module_inst, free_func_name, "(i)i"); + free_func = aot_lookup_function(module_inst, free_func_name); if (!free_func && module->retain_func_index != (uint32)-1) - free_func = aot_lookup_function(module_inst, "__unpin", "(i)i"); + free_func = aot_lookup_function(module_inst, "__unpin"); if (free_func) - execute_free_function(module_inst, exec_env, free_func, ptr); + execute_free_function(module_inst, exec_env, free_func, + (uint32)ptr); } } } -uint32 -aot_module_malloc(AOTModuleInstance *module_inst, uint32 size, +uint64 +aot_module_malloc(AOTModuleInstance *module_inst, uint64 size, void **p_native_addr) { return aot_module_malloc_internal(module_inst, NULL, size, p_native_addr); } -uint32 -aot_module_realloc(AOTModuleInstance *module_inst, uint32 ptr, uint32 size, +uint64 +aot_module_realloc(AOTModuleInstance *module_inst, uint64 ptr, uint64 size, void **p_native_addr) { return aot_module_realloc_internal(module_inst, NULL, ptr, size, @@ -2611,23 +2645,27 @@ aot_module_realloc(AOTModuleInstance *module_inst, uint32 ptr, uint32 size, } void -aot_module_free(AOTModuleInstance *module_inst, uint32 ptr) +aot_module_free(AOTModuleInstance *module_inst, uint64 ptr) { aot_module_free_internal(module_inst, NULL, ptr); } -uint32 +uint64 aot_module_dup_data(AOTModuleInstance *module_inst, const char *src, - uint32 size) + uint64 size) { char *buffer; - uint32 buffer_offset = - aot_module_malloc(module_inst, size, (void **)&buffer); + uint64 buffer_offset; + + /* TODO: Memory64 size check based on memory idx type */ + bh_assert(size <= UINT32_MAX); + + buffer_offset = aot_module_malloc(module_inst, size, (void **)&buffer); if (buffer_offset != 0) { buffer = wasm_runtime_addr_app_to_native( (WASMModuleInstanceCommon *)module_inst, buffer_offset); - bh_memcpy_s(buffer, size, src, size); + bh_memcpy_s(buffer, (uint32)size, src, (uint32)size); } return buffer_offset; } @@ -2645,11 +2683,9 @@ aot_invoke_native(WASMExecEnv *exec_env, uint32 func_idx, uint32 argc, AOTModuleInstance *module_inst = (AOTModuleInstance *)wasm_runtime_get_module_inst(exec_env); AOTModule *aot_module = (AOTModule *)module_inst->module; - AOTModuleInstanceExtra *module_inst_extra = - (AOTModuleInstanceExtra *)module_inst->e; CApiFuncImport *c_api_func_import = - module_inst_extra->common.c_api_func_imports - ? module_inst_extra->common.c_api_func_imports + func_idx + module_inst->c_api_func_imports + ? module_inst->c_api_func_imports + func_idx : NULL; uint32 *func_type_indexes = module_inst->func_type_indexes; uint32 func_type_idx = func_type_indexes[func_idx]; @@ -2773,7 +2809,7 @@ aot_call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 table_elem_idx, } #if WASM_ENABLE_GC == 0 - func_idx = tbl_elem_val; + func_idx = (uint32)tbl_elem_val; #else func_idx = wasm_func_obj_get_func_idx_bound((WASMFuncObjectRef)tbl_elem_val); @@ -2909,7 +2945,7 @@ fail: bool aot_check_app_addr_and_convert(AOTModuleInstance *module_inst, bool is_str, - uint32 app_buf_addr, uint32 app_buf_size, + uint64 app_buf_addr, uint64 app_buf_size, void **p_native_addr) { bool ret; @@ -2973,7 +3009,7 @@ aot_memory_init(AOTModuleInstance *module_inst, uint32 seg_index, uint32 offset, } if (!wasm_runtime_validate_app_addr((WASMModuleInstanceCommon *)module_inst, - dst, len)) + (uint64)dst, (uint64)len)) return false; if ((uint64)offset + (uint64)len > seg_len) { @@ -2982,10 +3018,11 @@ aot_memory_init(AOTModuleInstance *module_inst, uint32 seg_index, uint32 offset, } maddr = wasm_runtime_addr_app_to_native( - (WASMModuleInstanceCommon *)module_inst, dst); + (WASMModuleInstanceCommon *)module_inst, (uint64)dst); SHARED_MEMORY_LOCK(memory_inst); - bh_memcpy_s(maddr, memory_inst->memory_data_size - dst, data + offset, len); + bh_memcpy_s(maddr, (uint32)(memory_inst->memory_data_size - dst), + data + offset, len); SHARED_MEMORY_UNLOCK(memory_inst); return true; } @@ -3004,14 +3041,14 @@ aot_data_drop(AOTModuleInstance *module_inst, uint32 seg_index) #if WASM_ENABLE_THREAD_MGR != 0 bool -aot_set_aux_stack(WASMExecEnv *exec_env, uint32 start_offset, uint32 size) +aot_set_aux_stack(WASMExecEnv *exec_env, uint64 start_offset, uint32 size) { AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst; AOTModule *module = (AOTModule *)module_inst->module; uint32 stack_top_idx = module->aux_stack_top_global_index; - uint32 data_end = module->aux_data_end; - uint32 stack_bottom = module->aux_stack_bottom; + uint64 data_end = module->aux_data_end; + uint64 stack_bottom = module->aux_stack_bottom; bool is_stack_before_data = stack_bottom < data_end ? true : false; /* Check the aux stack space, currently we don't allocate space in heap */ @@ -3024,12 +3061,13 @@ aot_set_aux_stack(WASMExecEnv *exec_env, uint32 start_offset, uint32 size) set the initial value for the global */ uint32 global_offset = module->globals[stack_top_idx].data_offset; uint8 *global_addr = module_inst->global_data + global_offset; - *(int32 *)global_addr = start_offset; + /* TODO: Memory64 the type i32/i64 depends on memory idx type*/ + *(int32 *)global_addr = (uint32)start_offset; /* The aux stack boundary is a constant value, set the value to exec_env */ - exec_env->aux_stack_boundary.boundary = start_offset - size; - exec_env->aux_stack_bottom.bottom = start_offset; + exec_env->aux_stack_boundary = (uintptr_t)start_offset - size; + exec_env->aux_stack_bottom = (uintptr_t)start_offset; return true; } @@ -3037,14 +3075,14 @@ aot_set_aux_stack(WASMExecEnv *exec_env, uint32 start_offset, uint32 size) } bool -aot_get_aux_stack(WASMExecEnv *exec_env, uint32 *start_offset, uint32 *size) +aot_get_aux_stack(WASMExecEnv *exec_env, uint64 *start_offset, uint32 *size) { AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst; AOTModule *module = (AOTModule *)module_inst->module; /* The aux stack information is resolved in loader and store in module */ - uint32 stack_bottom = module->aux_stack_bottom; + uint64 stack_bottom = module->aux_stack_bottom; uint32 total_aux_stack_size = module->aux_stack_size; if (stack_bottom != 0 && total_aux_stack_size != 0) { @@ -3662,14 +3700,14 @@ aot_create_call_stack(struct WASMExecEnv *exec_env) frame.instance = module_inst; frame.module_offset = 0; - frame.func_index = cur_frame->func_index; - frame.func_offset = cur_frame->ip_offset; - frame.func_name_wp = - get_func_name_from_index(module_inst, cur_frame->func_index); + frame.func_index = (uint32)cur_frame->func_index; + frame.func_offset = (uint32)cur_frame->ip_offset; + frame.func_name_wp = get_func_name_from_index( + module_inst, (uint32)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; + (uint32)(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]; } @@ -4629,3 +4667,74 @@ aot_traverse_gc_rootset(WASMExecEnv *exec_env, void *heap) return true; } #endif /* end of WASM_ENABLE_GC != 0 */ + +char * +aot_const_str_set_insert(const uint8 *str, int32 len, AOTModule *module, +#if (WASM_ENABLE_WORD_ALIGN_READ != 0) + bool is_vram_word_align, +#endif + char *error_buf, uint32 error_buf_size) +{ + HashMap *set = module->const_str_set; + char *c_str, *value; + + /* Create const string set if it isn't created */ + if (!set + && !(set = module->const_str_set = bh_hash_map_create( + 32, false, (HashFunc)wasm_string_hash, + (KeyEqualFunc)wasm_string_equal, NULL, wasm_runtime_free))) { + set_error_buf(error_buf, error_buf_size, + "create const string set failed"); + return NULL; + } + + /* Lookup const string set, use the string if found */ + if (!(c_str = runtime_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, str, (uint32)len); + } + else +#endif + { + bh_memcpy_s(c_str, len, str, (uint32)len); + } + + if ((value = bh_hash_map_find(set, c_str))) { + wasm_runtime_free(c_str); + return value; + } + + if (!bh_hash_map_insert(set, c_str, c_str)) { + set_error_buf(error_buf, error_buf_size, + "insert string to hash map failed"); + wasm_runtime_free(c_str); + return NULL; + } + + return c_str; +} + +bool +aot_set_module_name(AOTModule *module, const char *name, char *error_buf, + uint32_t error_buf_size) +{ + if (!name) + return false; + + module->name = aot_const_str_set_insert((const uint8 *)name, + (uint32)(strlen(name) + 1), module, +#if (WASM_ENABLE_WORD_ALIGN_READ != 0) + false, +#endif + error_buf, error_buf_size); + return module->name != NULL; +} + +const char * +aot_get_module_name(AOTModule *module) +{ + return module->name; +} diff --git a/core/iwasm/aot/aot_runtime.h b/core/iwasm/aot/aot_runtime.h index 71baeb171..2d3013467 100644 --- a/core/iwasm/aot/aot_runtime.h +++ b/core/iwasm/aot/aot_runtime.h @@ -246,19 +246,19 @@ typedef struct AOTModule { -1 means unexported */ uint32 aux_data_end_global_index; /* auxiliary __data_end exported by wasm app */ - uint32 aux_data_end; + uint64 aux_data_end; /* the index of auxiliary __heap_base global, -1 means unexported */ uint32 aux_heap_base_global_index; /* auxiliary __heap_base exported by wasm app */ - uint32 aux_heap_base; + uint64 aux_heap_base; /* the index of auxiliary stack top global, -1 means unexported */ uint32 aux_stack_top_global_index; /* auxiliary stack bottom resolved */ - uint32 aux_stack_bottom; + uint64 aux_stack_bottom; /* auxiliary stack size resolved */ uint32 aux_stack_size; @@ -307,6 +307,9 @@ typedef struct AOTModule { #if WASM_ENABLE_LOAD_CUSTOM_SECTION != 0 WASMCustomSection *custom_section_list; #endif + + /* user defined name */ + char *name; } AOTModule; #define AOTMemoryInstance WASMMemoryInstance @@ -441,8 +444,8 @@ typedef struct LLVMProfileData_64 { * @return return AOT module loaded, NULL if failed */ AOTModule * -aot_load_from_aot_file(const uint8 *buf, uint32 size, char *error_buf, - uint32 error_buf_size); +aot_load_from_aot_file(const uint8 *buf, uint32 size, const LoadArgs *args, + char *error_buf, uint32 error_buf_size); /** * Load a AOT module from a specified AOT section list. @@ -482,7 +485,8 @@ aot_unload(AOTModule *module); AOTModuleInstance * aot_instantiate(AOTModule *module, AOTModuleInstance *parent, WASMExecEnv *exec_env_main, uint32 stack_size, uint32 heap_size, - char *error_buf, uint32 error_buf_size); + uint32 max_memory_pages, char *error_buf, + uint32 error_buf_size); /** * Deinstantiate a AOT module instance, destroy the resources. @@ -498,14 +502,12 @@ aot_deinstantiate(AOTModuleInstance *module_inst, bool is_sub_inst); * * @param module_inst the module instance * @param name the name of the function - * @param signature the signature of the function, use "i32"/"i64"/"f32"/"f64" - * to represent the type of i32/i64/f32/f64, e.g. "(i32i64)" "(i32)f32" * * @return the function instance found */ AOTFunctionInstance * -aot_lookup_function(const AOTModuleInstance *module_inst, const char *name, - const char *signature); +aot_lookup_function(const AOTModuleInstance *module_inst, const char *name); + /** * Call the given AOT function of a AOT module instance with * arguments. @@ -557,32 +559,32 @@ aot_get_exception(AOTModuleInstance *module_inst); bool aot_copy_exception(AOTModuleInstance *module_inst, char *exception_buf); -uint32 +uint64 aot_module_malloc_internal(AOTModuleInstance *module_inst, WASMExecEnv *env, - uint32 size, void **p_native_addr); + uint64 size, void **p_native_addr); -uint32 +uint64 aot_module_realloc_internal(AOTModuleInstance *module_inst, WASMExecEnv *env, - uint32 ptr, uint32 size, void **p_native_addr); + uint64 ptr, uint64 size, void **p_native_addr); void aot_module_free_internal(AOTModuleInstance *module_inst, WASMExecEnv *env, - uint32 ptr); + uint64 ptr); -uint32 -aot_module_malloc(AOTModuleInstance *module_inst, uint32 size, +uint64 +aot_module_malloc(AOTModuleInstance *module_inst, uint64 size, void **p_native_addr); -uint32 -aot_module_realloc(AOTModuleInstance *module_inst, uint32 ptr, uint32 size, +uint64 +aot_module_realloc(AOTModuleInstance *module_inst, uint64 ptr, uint64 size, void **p_native_addr); void -aot_module_free(AOTModuleInstance *module_inst, uint32 ptr); +aot_module_free(AOTModuleInstance *module_inst, uint64 ptr); -uint32 +uint64 aot_module_dup_data(AOTModuleInstance *module_inst, const char *src, - uint32 size); + uint64 size); bool aot_enlarge_memory(AOTModuleInstance *module_inst, uint32 inc_page_count); @@ -604,7 +606,7 @@ aot_call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 table_elem_idx, */ bool aot_check_app_addr_and_convert(AOTModuleInstance *module_inst, bool is_str, - uint32 app_buf_addr, uint32 app_buf_size, + uint64 app_buf_addr, uint64 app_buf_size, void **p_native_addr); uint32 @@ -633,10 +635,10 @@ aot_data_drop(AOTModuleInstance *module_inst, uint32 seg_index); #if WASM_ENABLE_THREAD_MGR != 0 bool -aot_set_aux_stack(WASMExecEnv *exec_env, uint32 start_offset, uint32 size); +aot_set_aux_stack(WASMExecEnv *exec_env, uint64 start_offset, uint32 size); bool -aot_get_aux_stack(WASMExecEnv *exec_env, uint32 *start_offset, uint32 *size); +aot_get_aux_stack(WASMExecEnv *exec_env, uint64 *start_offset, uint32 *size); #endif void @@ -762,6 +764,20 @@ bool aot_traverse_gc_rootset(WASMExecEnv *exec_env, void *heap); #endif /* end of WASM_ENABLE_GC != 0 */ +char * +aot_const_str_set_insert(const uint8 *str, int32 len, AOTModule *module, +#if (WASM_ENABLE_WORD_ALIGN_READ != 0) + bool is_vram_word_align, +#endif + char *error_buf, uint32 error_buf_size); + +bool +aot_set_module_name(AOTModule *module, const char *name, char *error_buf, + uint32_t error_buf_size); + +const char * +aot_get_module_name(AOTModule *module); + #ifdef __cplusplus } /* end of extern "C" */ #endif diff --git a/core/iwasm/common/gc/gc_object.c b/core/iwasm/common/gc/gc_object.c index 57743a35d..333effcf6 100644 --- a/core/iwasm/common/gc/gc_object.c +++ b/core/iwasm/common/gc/gc_object.c @@ -189,6 +189,16 @@ wasm_struct_obj_get_field(const WASMStructObjectRef struct_obj, } } +uint32 +wasm_struct_obj_get_field_count(const WASMStructObjectRef struct_obj) +{ + WASMRttTypeRef rtt_type = + (WASMRttTypeRef)wasm_object_header((WASMObjectRef)struct_obj); + WASMStructType *struct_type = (WASMStructType *)rtt_type->defined_type; + + return struct_type->field_count; +} + WASMArrayObjectRef wasm_array_obj_new_internal(void *heap_handle, WASMRttTypeRef rtt_type, uint32 length, WASMValue *init_value) diff --git a/core/iwasm/common/gc/gc_object.h b/core/iwasm/common/gc/gc_object.h index 4c0cc4538..2d1336881 100644 --- a/core/iwasm/common/gc/gc_object.h +++ b/core/iwasm/common/gc/gc_object.h @@ -157,6 +157,16 @@ void wasm_struct_obj_get_field(const WASMStructObjectRef struct_obj, uint32 field_idx, bool sign_extend, WASMValue *value); +/** + * Return the field count of the WASM struct object. + * + * @param struct_obj the WASM struct object + * + * @return the field count of the WASM struct object + */ +uint32 +wasm_struct_obj_get_field_count(const WASMStructObjectRef struct_obj); + WASMArrayObjectRef wasm_array_obj_new_internal(void *heap_handle, WASMRttTypeRef rtt_type, uint32 length, WASMValue *init_value); diff --git a/core/iwasm/common/gc/gc_type.c b/core/iwasm/common/gc/gc_type.c index 0c9271c87..60f0e7e7a 100644 --- a/core/iwasm/common/gc/gc_type.c +++ b/core/iwasm/common/gc/gc_type.c @@ -148,7 +148,7 @@ wasm_dump_func_type(const WASMFuncType *type) os_printf("] -> ["); - for (; i < type->param_count + type->result_count; i++) { + for (; i < (uint32)(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); @@ -264,7 +264,7 @@ wasm_func_type_equal(const WASMFuncType *type1, const WASMFuncType *type2, || type1->ref_type_map_count != type2->ref_type_map_count) return false; - for (i = 0; i < type1->param_count + type1->result_count; i++) { + for (i = 0; i < (uint32)(type1->param_count + type1->result_count); i++) { if (type1->types[i] != type2->types[i]) return false; @@ -399,7 +399,7 @@ wasm_func_type_is_subtype_of(const WASMFuncType *type1, } } - for (; i < type1->param_count + type1->result_count; i++) { + for (; i < (uint32)(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; diff --git a/core/iwasm/common/wasm_application.c b/core/iwasm/common/wasm_application.c index 4e5d17deb..13ad2b1a6 100644 --- a/core/iwasm/common/wasm_application.c +++ b/core/iwasm/common/wasm_application.c @@ -61,7 +61,7 @@ static union { * Implementation of wasm_application_execute_main() */ static bool -check_main_func_type(const WASMFuncType *type) +check_main_func_type(const WASMFuncType *type, bool is_memory64) { if (!(type->param_count == 0 || type->param_count == 2) || type->result_count > 1) { @@ -72,7 +72,8 @@ check_main_func_type(const WASMFuncType *type) if (type->param_count == 2 && !(type->types[0] == VALUE_TYPE_I32 - && type->types[1] == VALUE_TYPE_I32)) { + && type->types[1] + == (is_memory64 ? VALUE_TYPE_I64 : VALUE_TYPE_I32))) { LOG_ERROR( "WASM execute application failed: invalid main function type.\n"); return false; @@ -94,14 +95,18 @@ execute_main(WASMModuleInstanceCommon *module_inst, int32 argc, char *argv[]) WASMFunctionInstanceCommon *func; WASMFuncType *func_type = NULL; WASMExecEnv *exec_env = NULL; - uint32 argc1 = 0, argv1[2] = { 0 }; + uint32 argc1 = 0, argv1[3] = { 0 }; uint32 total_argv_size = 0; uint64 total_size; - uint32 argv_buf_offset = 0; + uint64 argv_buf_offset = 0; int32 i; char *argv_buf, *p, *p_end; uint32 *argv_offsets, module_type; - bool ret, is_import_func = true; + bool ret, is_import_func = true, is_memory64 = false; +#if WASM_ENABLE_MEMORY64 != 0 + WASMModuleInstance *wasm_module_inst = (WASMModuleInstance *)module_inst; + is_memory64 = wasm_module_inst->memories[0]->is_memory64; +#endif exec_env = wasm_runtime_get_exec_env_singleton(module_inst); if (!exec_env) { @@ -147,10 +152,10 @@ execute_main(WASMModuleInstanceCommon *module_inst, int32 argc, char *argv[]) } #endif /* end of WASM_ENABLE_LIBC_WASI */ - if (!(func = wasm_runtime_lookup_function(module_inst, "main", NULL)) - && !(func = wasm_runtime_lookup_function(module_inst, - "__main_argc_argv", NULL)) - && !(func = wasm_runtime_lookup_function(module_inst, "_main", NULL))) { + if (!(func = wasm_runtime_lookup_function(module_inst, "main")) + && !(func = + wasm_runtime_lookup_function(module_inst, "__main_argc_argv")) + && !(func = wasm_runtime_lookup_function(module_inst, "_main"))) { #if WASM_ENABLE_LIBC_WASI != 0 wasm_runtime_set_exception( module_inst, "lookup the entry point symbol (like _start, main, " @@ -187,7 +192,7 @@ execute_main(WASMModuleInstanceCommon *module_inst, int32 argc, char *argv[]) return false; } - if (!check_main_func_type(func_type)) { + if (!check_main_func_type(func_type, is_memory64)) { wasm_runtime_set_exception(module_inst, "invalid function type of main function"); return false; @@ -202,7 +207,7 @@ execute_main(WASMModuleInstanceCommon *module_inst, int32 argc, char *argv[]) if (total_size >= UINT32_MAX || !(argv_buf_offset = wasm_runtime_module_malloc( - module_inst, (uint32)total_size, (void **)&argv_buf))) { + module_inst, total_size, (void **)&argv_buf))) { wasm_runtime_set_exception(module_inst, "allocate memory failed"); return false; } @@ -214,14 +219,25 @@ execute_main(WASMModuleInstanceCommon *module_inst, int32 argc, char *argv[]) for (i = 0; i < argc; i++) { bh_memcpy_s(p, (uint32)(p_end - p), argv[i], (uint32)(strlen(argv[i]) + 1)); - argv_offsets[i] = argv_buf_offset + (uint32)(p - argv_buf); + argv_offsets[i] = (uint32)argv_buf_offset + (uint32)(p - argv_buf); p += strlen(argv[i]) + 1; } - argc1 = 2; argv1[0] = (uint32)argc; - argv1[1] = - (uint32)wasm_runtime_addr_native_to_app(module_inst, argv_offsets); +#if WASM_ENABLE_MEMORY64 != 0 + if (is_memory64) { + argc1 = 3; + uint64 app_addr = + wasm_runtime_addr_native_to_app(module_inst, argv_offsets); + PUT_I64_TO_ADDR(&argv[1], app_addr); + } + else +#endif + { + argc1 = 2; + argv1[1] = (uint32)wasm_runtime_addr_native_to_app(module_inst, + argv_offsets); + } } ret = wasm_runtime_call_wasm(exec_env, func, argc1, argv1); @@ -336,8 +352,7 @@ execute_func(WASMModuleInstanceCommon *module_inst, const char *name, bh_assert(argc >= 0); LOG_DEBUG("call a function \"%s\" with %d arguments", name, argc); - if (!(target_func = - wasm_runtime_lookup_function(module_inst, name, NULL))) { + if (!(target_func = wasm_runtime_lookup_function(module_inst, name))) { snprintf(buf, sizeof(buf), "lookup function %s failed", name); wasm_runtime_set_exception(module_inst, buf); goto fail; diff --git a/core/iwasm/common/wasm_c_api.c b/core/iwasm/common/wasm_c_api.c index bffa870cf..456ce505e 100644 --- a/core/iwasm/common/wasm_c_api.c +++ b/core/iwasm/common/wasm_c_api.c @@ -2234,7 +2234,8 @@ quit: #endif /* WASM_ENABLE_WASM_CACHE != 0 */ wasm_module_t * -wasm_module_new(wasm_store_t *store, const wasm_byte_vec_t *binary) +wasm_module_new_ex(wasm_store_t *store, const wasm_byte_vec_t *binary, + const LoadArgs *args) { char error_buf[128] = { 0 }; wasm_module_ex_t *module_ex = NULL; @@ -2290,8 +2291,8 @@ wasm_module_new(wasm_store_t *store, const wasm_byte_vec_t *binary) if (!module_ex->binary->data) goto free_binary; - module_ex->module_comm_rt = wasm_runtime_load( - (uint8 *)module_ex->binary->data, (uint32)module_ex->binary->size, + module_ex->module_comm_rt = wasm_runtime_load_ex( + (uint8 *)module_ex->binary->data, (uint32)module_ex->binary->size, args, error_buf, (uint32)sizeof(error_buf)); if (!(module_ex->module_comm_rt)) { LOG_ERROR("%s", error_buf); @@ -2337,6 +2338,14 @@ quit: return NULL; } +wasm_module_t * +wasm_module_new(wasm_store_t *store, const wasm_byte_vec_t *binary) +{ + LoadArgs args = { 0 }; + args.name = ""; + return wasm_module_new_ex(store, binary, &args); +} + bool wasm_module_validate(wasm_store_t *store, const wasm_byte_vec_t *binary) { @@ -2949,6 +2958,34 @@ wasm_shared_module_delete(own wasm_shared_module_t *shared_module) wasm_module_delete_internal((wasm_module_t *)shared_module); } +bool +wasm_module_set_name(wasm_module_t *module, const char *name) +{ + char error_buf[256] = { 0 }; + wasm_module_ex_t *module_ex = NULL; + + if (!module) + return false; + + module_ex = module_to_module_ext(module); + bool ret = wasm_runtime_set_module_name(module_ex->module_comm_rt, name, + error_buf, sizeof(error_buf) - 1); + if (!ret) + LOG_WARNING("set module name failed: %s", error_buf); + return ret; +} + +const char * +wasm_module_get_name(wasm_module_t *module) +{ + wasm_module_ex_t *module_ex = NULL; + if (!module) + return ""; + + module_ex = module_to_module_ext(module); + return wasm_runtime_get_module_name(module_ex->module_comm_rt); +} + static wasm_func_t * wasm_func_new_basic(wasm_store_t *store, const wasm_functype_t *type, wasm_func_callback_t func_callback) @@ -3959,7 +3996,7 @@ wasm_table_get(const wasm_table_t *table, wasm_table_size_t index) if (index >= table_interp->cur_size) { return NULL; } - ref_idx = table_interp->elems[index]; + ref_idx = (uint32)table_interp->elems[index]; } #endif @@ -3970,7 +4007,7 @@ wasm_table_get(const wasm_table_t *table, wasm_table_size_t index) if (index >= table_aot->cur_size) { return NULL; } - ref_idx = table_aot->elems[index]; + ref_idx = (uint32)table_aot->elems[index]; } #endif @@ -4872,6 +4909,19 @@ wasm_instance_new_with_args(wasm_store_t *store, const wasm_module_t *module, const wasm_extern_vec_t *imports, own wasm_trap_t **trap, const uint32 stack_size, const uint32 heap_size) +{ + InstantiationArgs inst_args = { 0 }; + inst_args.default_stack_size = stack_size; + inst_args.host_managed_heap_size = heap_size; + return wasm_instance_new_with_args_ex(store, module, imports, trap, + &inst_args); +} + +wasm_instance_t * +wasm_instance_new_with_args_ex(wasm_store_t *store, const wasm_module_t *module, + const wasm_extern_vec_t *imports, + own wasm_trap_t **trap, + const InstantiationArgs *inst_args) { char sub_error_buf[128] = { 0 }; char error_buf[256] = { 0 }; @@ -4911,8 +4961,8 @@ wasm_instance_new_with_args(wasm_store_t *store, const wasm_module_t *module, * will do the linking result check at the end of wasm_runtime_instantiate */ - instance->inst_comm_rt = wasm_runtime_instantiate( - *module, stack_size, heap_size, sub_error_buf, sizeof(sub_error_buf)); + instance->inst_comm_rt = wasm_runtime_instantiate_ex( + *module, inst_args, sub_error_buf, sizeof(sub_error_buf)); if (!instance->inst_comm_rt) { goto failed; } @@ -4926,19 +4976,17 @@ wasm_instance_new_with_args(wasm_store_t *store, const wasm_module_t *module, /* create the c-api func import list */ #if WASM_ENABLE_INTERP != 0 if (instance->inst_comm_rt->module_type == Wasm_Module_Bytecode) { - WASMModuleInstanceExtra *e = - ((WASMModuleInstance *)instance->inst_comm_rt)->e; - p_func_imports = &(e->common.c_api_func_imports); + WASMModuleInstance *wasm_module_inst = + (WASMModuleInstance *)instance->inst_comm_rt; + p_func_imports = &(wasm_module_inst->c_api_func_imports); import_func_count = MODULE_INTERP(module)->import_function_count; } #endif #if WASM_ENABLE_AOT != 0 if (instance->inst_comm_rt->module_type == Wasm_Module_AoT) { - AOTModuleInstanceExtra *e = - (AOTModuleInstanceExtra *)((AOTModuleInstance *) - instance->inst_comm_rt) - ->e; - p_func_imports = &(e->common.c_api_func_imports); + AOTModuleInstance *aot_module_inst = + (AOTModuleInstance *)instance->inst_comm_rt; + p_func_imports = &(aot_module_inst->c_api_func_imports); import_func_count = MODULE_AOT(module)->import_func_count; } #endif @@ -4952,7 +5000,7 @@ wasm_instance_new_with_args(wasm_store_t *store, const wasm_module_t *module, goto failed; } - /* fill in module_inst->e->c_api_func_imports */ + /* fill in module_inst->c_api_func_imports */ for (i = 0; imports && i < imports->num_elems; i++) { wasm_func_t *func_host = NULL; wasm_extern_t *in = imports->data[i]; diff --git a/core/iwasm/common/wasm_exec_env.c b/core/iwasm/common/wasm_exec_env.c index 0b3778e60..373ac463b 100644 --- a/core/iwasm/common/wasm_exec_env.c +++ b/core/iwasm/common/wasm_exec_env.c @@ -149,9 +149,9 @@ wasm_exec_env_create(struct WASMModuleInstanceCommon *module_inst, /* Set the aux_stack_boundary and aux_stack_bottom */ if (module_inst->module_type == Wasm_Module_Bytecode) { WASMModule *module = ((WASMModuleInstance *)module_inst)->module; - exec_env->aux_stack_bottom.bottom = module->aux_stack_bottom; - exec_env->aux_stack_boundary.boundary = - module->aux_stack_bottom - module->aux_stack_size; + exec_env->aux_stack_bottom = (uintptr_t)module->aux_stack_bottom; + exec_env->aux_stack_boundary = + (uintptr_t)module->aux_stack_bottom - module->aux_stack_size; #if WASM_ENABLE_GC != 0 gc_heap_handle = ((WASMModuleInstance *)module_inst)->e->common.gc_heap_pool; @@ -163,9 +163,9 @@ wasm_exec_env_create(struct WASMModuleInstanceCommon *module_inst, if (module_inst->module_type == Wasm_Module_AoT) { AOTModule *module = (AOTModule *)((AOTModuleInstance *)module_inst)->module; - exec_env->aux_stack_bottom.bottom = module->aux_stack_bottom; - exec_env->aux_stack_boundary.boundary = - module->aux_stack_bottom - module->aux_stack_size; + exec_env->aux_stack_bottom = (uintptr_t)module->aux_stack_bottom; + exec_env->aux_stack_boundary = + (uintptr_t)module->aux_stack_bottom - module->aux_stack_size; #if WASM_ENABLE_GC != 0 gc_heap_handle = ((AOTModuleInstanceExtra *)((AOTModuleInstance *)module_inst)->e) diff --git a/core/iwasm/common/wasm_exec_env.h b/core/iwasm/common/wasm_exec_env.h index 4f93493ef..53d248755 100644 --- a/core/iwasm/common/wasm_exec_env.h +++ b/core/iwasm/common/wasm_exec_env.h @@ -62,16 +62,10 @@ typedef struct WASMExecEnv { WASMSuspendFlags suspend_flags; /* Auxiliary stack boundary */ - union { - uint32 boundary; - uintptr_t __padding__; - } aux_stack_boundary; + uintptr_t aux_stack_boundary; /* Auxiliary stack bottom */ - union { - uint32 bottom; - uintptr_t __padding__; - } aux_stack_bottom; + uintptr_t aux_stack_bottom; #if WASM_ENABLE_AOT != 0 /* Native symbol list, reserved */ @@ -123,6 +117,9 @@ typedef struct WASMExecEnv { /* whether current thread is detached */ bool thread_is_detached; + + /* whether the aux stack is allocated */ + bool is_aux_stack_allocated; #endif #if WASM_ENABLE_GC != 0 @@ -195,8 +192,7 @@ wasm_exec_env_destroy(WASMExecEnv *exec_env); static inline bool wasm_exec_env_is_aux_stack_managed_by_runtime(WASMExecEnv *exec_env) { - return exec_env->aux_stack_boundary.boundary != 0 - || exec_env->aux_stack_bottom.bottom != 0; + return exec_env->aux_stack_boundary != 0 || exec_env->aux_stack_bottom != 0; } /** diff --git a/core/iwasm/common/wasm_memory.c b/core/iwasm/common/wasm_memory.c index 019e0c129..50ee917ed 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,22 +41,22 @@ static void (*free_func)(void *ptr) = NULL; static unsigned int global_pool_size; -static uint32 +static uint64 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; + return 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; } @@ -84,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 @@ -104,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; @@ -119,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; @@ -284,10 +282,11 @@ wasm_runtime_get_mem_alloc_info(mem_alloc_info_t *mem_alloc_info) bool wasm_runtime_validate_app_addr(WASMModuleInstanceCommon *module_inst_comm, - uint32 app_offset, uint32 size) + uint64 app_offset, uint64 size) { WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm; WASMMemoryInstance *memory_inst; + uint64 max_linear_memory_size = MAX_LINEAR_MEMORY_SIZE; bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode || module_inst_comm->module_type == Wasm_Module_AoT); @@ -301,8 +300,13 @@ wasm_runtime_validate_app_addr(WASMModuleInstanceCommon *module_inst_comm, goto fail; } - /* integer overflow check */ - if (app_offset > UINT32_MAX - size) { +#if WASM_ENABLE_MEMORY64 != 0 + if (memory_inst->is_memory64) + max_linear_memory_size = MAX_LINEAR_MEM64_MEMORY_SIZE; +#endif + /* boundary overflow check */ + if (size > max_linear_memory_size + || app_offset > max_linear_memory_size - size) { goto fail; } @@ -322,10 +326,10 @@ fail: bool wasm_runtime_validate_app_str_addr(WASMModuleInstanceCommon *module_inst_comm, - uint32 app_str_offset) + uint64 app_str_offset) { WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm; - uint32 app_end_offset; + uint64 app_end_offset, max_linear_memory_size = MAX_LINEAR_MEMORY_SIZE; char *str, *str_end; bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode @@ -339,6 +343,16 @@ wasm_runtime_validate_app_str_addr(WASMModuleInstanceCommon *module_inst_comm, &app_end_offset)) goto fail; +#if WASM_ENABLE_MEMORY64 != 0 + if (module_inst->memories[0]->is_memory64) + max_linear_memory_size = MAX_LINEAR_MEM64_MEMORY_SIZE; +#endif + /* boundary overflow check, max start offset can only be size - 1, while end + * offset can be size */ + if (app_str_offset >= max_linear_memory_size + || app_end_offset > max_linear_memory_size) + goto fail; + str = wasm_runtime_addr_app_to_native(module_inst_comm, app_str_offset); str_end = str + (app_end_offset - app_str_offset); while (str < str_end && *str != '\0') @@ -354,11 +368,12 @@ fail: bool wasm_runtime_validate_native_addr(WASMModuleInstanceCommon *module_inst_comm, - void *native_ptr, uint32 size) + void *native_ptr, uint64 size) { WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm; WASMMemoryInstance *memory_inst; uint8 *addr = (uint8 *)native_ptr; + uint64 max_linear_memory_size = MAX_LINEAR_MEMORY_SIZE; bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode || module_inst_comm->module_type == Wasm_Module_AoT); @@ -372,8 +387,12 @@ wasm_runtime_validate_native_addr(WASMModuleInstanceCommon *module_inst_comm, goto fail; } - /* integer overflow check */ - if ((uintptr_t)addr > UINTPTR_MAX - size) { +#if WASM_ENABLE_MEMORY64 != 0 + if (memory_inst->is_memory64) + max_linear_memory_size = MAX_LINEAR_MEM64_MEMORY_SIZE; +#endif + /* boundary overflow check */ + if (size > max_linear_memory_size || (uintptr_t)addr > UINTPTR_MAX - size) { goto fail; } @@ -394,7 +413,7 @@ fail: void * wasm_runtime_addr_app_to_native(WASMModuleInstanceCommon *module_inst_comm, - uint32 app_offset) + uint64 app_offset) { WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm; WASMMemoryInstance *memory_inst; @@ -413,7 +432,7 @@ wasm_runtime_addr_app_to_native(WASMModuleInstanceCommon *module_inst_comm, SHARED_MEMORY_LOCK(memory_inst); - addr = memory_inst->memory_data + app_offset; + addr = memory_inst->memory_data + (uintptr_t)app_offset; if (bounds_checks) { if (memory_inst->memory_data <= addr @@ -421,18 +440,16 @@ wasm_runtime_addr_app_to_native(WASMModuleInstanceCommon *module_inst_comm, SHARED_MEMORY_UNLOCK(memory_inst); return addr; } - } - /* If bounds checks is disabled, return the address directly */ - else if (app_offset != 0) { SHARED_MEMORY_UNLOCK(memory_inst); - return addr; + return NULL; } + /* If bounds checks is disabled, return the address directly */ SHARED_MEMORY_UNLOCK(memory_inst); - return NULL; + return addr; } -uint32 +uint64 wasm_runtime_addr_native_to_app(WASMModuleInstanceCommon *module_inst_comm, void *native_ptr) { @@ -440,7 +457,7 @@ wasm_runtime_addr_native_to_app(WASMModuleInstanceCommon *module_inst_comm, WASMMemoryInstance *memory_inst; uint8 *addr = (uint8 *)native_ptr; bool bounds_checks; - uint32 ret; + uint64 ret; bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode || module_inst_comm->module_type == Wasm_Module_AoT); @@ -457,14 +474,14 @@ wasm_runtime_addr_native_to_app(WASMModuleInstanceCommon *module_inst_comm, if (bounds_checks) { if (memory_inst->memory_data <= addr && addr < memory_inst->memory_data_end) { - ret = (uint32)(addr - memory_inst->memory_data); + ret = (uint64)(addr - memory_inst->memory_data); SHARED_MEMORY_UNLOCK(memory_inst); return ret; } } /* If bounds checks is disabled, return the offset directly */ else if (addr != NULL) { - ret = (uint32)(addr - memory_inst->memory_data); + ret = (uint64)(addr - memory_inst->memory_data); SHARED_MEMORY_UNLOCK(memory_inst); return ret; } @@ -475,12 +492,12 @@ wasm_runtime_addr_native_to_app(WASMModuleInstanceCommon *module_inst_comm, bool wasm_runtime_get_app_addr_range(WASMModuleInstanceCommon *module_inst_comm, - uint32 app_offset, uint32 *p_app_start_offset, - uint32 *p_app_end_offset) + uint64 app_offset, uint64 *p_app_start_offset, + uint64 *p_app_end_offset) { WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm; WASMMemoryInstance *memory_inst; - uint32 memory_data_size; + uint64 memory_data_size; bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode || module_inst_comm->module_type == Wasm_Module_AoT); @@ -543,19 +560,21 @@ wasm_runtime_get_native_addr_range(WASMModuleInstanceCommon *module_inst_comm, bool wasm_check_app_addr_and_convert(WASMModuleInstance *module_inst, bool is_str, - uint32 app_buf_addr, uint32 app_buf_size, + uint64 app_buf_addr, uint64 app_buf_size, void **p_native_addr) { WASMMemoryInstance *memory_inst = wasm_get_default_memory(module_inst); uint8 *native_addr; bool bounds_checks; + bh_assert(app_buf_addr <= UINTPTR_MAX && app_buf_size <= UINTPTR_MAX); + if (!memory_inst) { wasm_set_exception(module_inst, "out of bounds memory access"); return false; } - native_addr = memory_inst->memory_data + app_buf_addr; + native_addr = memory_inst->memory_data + (uintptr_t)app_buf_addr; bounds_checks = is_bounds_checks_enabled((wasm_module_inst_t)module_inst); @@ -697,9 +716,9 @@ wasm_enlarge_memory_internal(WASMModuleInstance *module, uint32 inc_page_count) { WASMMemoryInstance *memory = wasm_get_default_memory(module); uint8 *memory_data_old, *memory_data_new, *heap_data_old; - uint32 num_bytes_per_page, heap_size, total_size_old = 0; + uint32 num_bytes_per_page, heap_size; uint32 cur_page_count, max_page_count, total_page_count; - uint64 total_size_new; + uint64 total_size_old = 0, total_size_new; bool ret = true, full_size_mmaped; enlarge_memory_error_reason_t failure_reason = INTERNAL_ERROR; @@ -743,18 +762,13 @@ wasm_enlarge_memory_internal(WASMModuleInstance *module, uint32 inc_page_count) 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; - } + bh_assert(total_size_new + <= GET_MAX_LINEAR_MEMORY_SIZE(memory->is_memory64)); if (full_size_mmaped) { #ifdef BH_PLATFORM_WINDOWS if (!os_mem_commit(memory->memory_data_end, - (uint32)total_size_new - total_size_old, + (mem_offset_t)(total_size_new - total_size_old), MMAP_PROT_READ | MMAP_PROT_WRITE)) { ret = false; goto return_func; @@ -762,12 +776,12 @@ wasm_enlarge_memory_internal(WASMModuleInstance *module, uint32 inc_page_count) #endif if (os_mprotect(memory->memory_data_end, - (uint32)total_size_new - total_size_old, + (mem_offset_t)(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); + (mem_offset_t)(total_size_new - total_size_old)); #endif ret = false; goto return_func; @@ -782,9 +796,9 @@ wasm_enlarge_memory_internal(WASMModuleInstance *module, uint32 inc_page_count) } } - if (!(memory_data_new = wasm_mremap_linear_memory( - memory_data_old, total_size_old, (uint32)total_size_new, - (uint32)total_size_new))) { + if (!(memory_data_new = + wasm_mremap_linear_memory(memory_data_old, total_size_old, + total_size_new, total_size_new))) { ret = false; goto return_func; } @@ -813,8 +827,8 @@ wasm_enlarge_memory_internal(WASMModuleInstance *module, uint32 inc_page_count) 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; + SET_LINEAR_MEMORY_SIZE(memory, total_size_new); + memory->memory_data_end = memory->memory_data + total_size_new; wasm_runtime_set_mem_bound_check_bytes(memory, total_size_new); @@ -824,13 +838,11 @@ return_func: #if WASM_ENABLE_INTERP != 0 if (module->module_type == Wasm_Module_Bytecode) - exec_env = - ((WASMModuleInstanceExtra *)module->e)->common.cur_exec_env; + exec_env = ((WASMModuleInstance *)module)->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; + exec_env = ((AOTModuleInstance *)module)->cur_exec_env; #endif enlarge_memory_error_cb(inc_page_count, total_size_old, 0, @@ -898,8 +910,9 @@ 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) + bool is_memory64, uint64 num_bytes_per_page, + uint64 init_page_count, uint64 max_page_count, + uint64 *memory_data_size) { uint64 map_size, page_size; @@ -928,8 +941,17 @@ wasm_allocate_linear_memory(uint8 **data, bool is_shared_memory, 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 WASM_ENABLE_MEMORY64 != 0 + if (is_memory64) { + bh_assert(*memory_data_size <= MAX_LINEAR_MEM64_MEMORY_SIZE); + } + else +#endif + { + bh_assert(*memory_data_size <= MAX_LINEAR_MEMORY_SIZE); + } + *memory_data_size = align_as_and_cast(*memory_data_size, page_size); if (map_size > 0) { if (!(*data = wasm_mmap_linear_memory(map_size, *memory_data_size))) { @@ -938,4 +960,4 @@ wasm_allocate_linear_memory(uint8 **data, bool is_shared_memory, } 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 381266b61..a5dfefae9 100644 --- a/core/iwasm/common/wasm_memory.h +++ b/core/iwasm/common/wasm_memory.h @@ -9,16 +9,33 @@ #include "bh_common.h" #include "../include/wasm_export.h" #include "../interpreter/wasm_runtime.h" +#include "../common/wasm_shared_memory.h" #ifdef __cplusplus extern "C" { #endif -#if WASM_ENABLE_SHARED_MEMORY != 0 +#if WASM_ENABLE_SHARED_MEMORY != 0 && BH_ATOMIC_64_IS_ATOMIC != 0 #define GET_LINEAR_MEMORY_SIZE(memory) \ - BH_ATOMIC_32_LOAD(memory->memory_data_size) + BH_ATOMIC_64_LOAD(memory->memory_data_size) #define SET_LINEAR_MEMORY_SIZE(memory, size) \ - BH_ATOMIC_32_STORE(memory->memory_data_size, size) + BH_ATOMIC_64_STORE(memory->memory_data_size, size) +#elif WASM_ENABLE_SHARED_MEMORY != 0 +static inline uint64 +GET_LINEAR_MEMORY_SIZE(const WASMMemoryInstance *memory) +{ + SHARED_MEMORY_LOCK(memory); + uint64 memory_data_size = BH_ATOMIC_64_LOAD(memory->memory_data_size); + SHARED_MEMORY_UNLOCK(memory); + return memory_data_size; +} +static inline void +SET_LINEAR_MEMORY_SIZE(WASMMemoryInstance *memory, uint64 size) +{ + SHARED_MEMORY_LOCK(memory); + BH_ATOMIC_64_STORE(memory->memory_data_size, size); + SHARED_MEMORY_UNLOCK(memory); +} #else #define GET_LINEAR_MEMORY_SIZE(memory) memory->memory_data_size #define SET_LINEAR_MEMORY_SIZE(memory, size) memory->memory_data_size = size @@ -47,8 +64,9 @@ 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); + bool is_memory64, uint64 num_bytes_per_page, + uint64 init_page_count, uint64 max_page_count, + uint64 *memory_data_size); #ifdef __cplusplus } diff --git a/core/iwasm/common/wasm_native.c b/core/iwasm/common/wasm_native.c index 3cf7451e3..14b295ee7 100644 --- a/core/iwasm/common/wasm_native.c +++ b/core/iwasm/common/wasm_native.c @@ -567,7 +567,12 @@ wasm_native_init() #if WASM_ENABLE_WASI_NN != 0 n_native_symbols = get_wasi_nn_export_apis(&native_symbols); - if (!wasm_native_register_natives("wasi_nn", native_symbols, +#if WASM_ENABLE_WASI_EPHEMERAL_NN != 0 +#define wasi_nn_module_name "wasi_ephemeral_nn" +#else /* WASM_ENABLE_WASI_EPHEMERAL_NN == 0 */ +#define wasi_nn_module_name "wasi_nn" +#endif /* WASM_ENABLE_WASI_EPHEMERAL_NN != 0 */ + if (!wasm_native_register_natives(wasi_nn_module_name, native_symbols, n_native_symbols)) goto fail; #endif diff --git a/core/iwasm/common/wasm_runtime_common.c b/core/iwasm/common/wasm_runtime_common.c index 5f466344f..d93bb682e 100644 --- a/core/iwasm/common/wasm_runtime_common.c +++ b/core/iwasm/common/wasm_runtime_common.c @@ -65,7 +65,7 @@ #if WASM_ENABLE_MULTI_MODULE != 0 /** * A safety insurance to prevent - * circular depencies which leads stack overflow + * circular dependencies which leads stack overflow * try to break early */ typedef struct LoadingModule { @@ -275,11 +275,11 @@ decode_insn(uint8 *insn) buffer, sizeof(buffer), runtime_address); +#if 0 /* Print current instruction */ - /* os_printf("%012" PRIX64 " ", runtime_address); puts(buffer); - */ +#endif return instruction.length; } @@ -564,8 +564,20 @@ wasm_runtime_exec_env_check(WASMExecEnv *exec_env) && exec_env->wasm_stack.top <= exec_env->wasm_stack.top_boundary; } -bool -wasm_runtime_init() +#if defined(OS_THREAD_MUTEX_INITIALIZER) +/** + * lock for wasm_runtime_init/wasm_runtime_full_init and runtime_ref_count + * Note: if the platform has mutex initializer, we use a global lock to + * lock the operations of runtime init/full_init, otherwise when there are + * operations happening simultaneously in multiple threads, developer + * must create the lock by himself, and use it to lock the operations + */ +static korp_mutex runtime_lock = OS_THREAD_MUTEX_INITIALIZER; +#endif +static int32 runtime_ref_count = 0; + +static bool +wasm_runtime_init_internal() { if (!wasm_runtime_memory_init(Alloc_With_System_Allocator, NULL)) return false; @@ -578,8 +590,32 @@ wasm_runtime_init() return true; } -void -wasm_runtime_destroy() +bool +wasm_runtime_init() +{ + bool ret = true; + +#if defined(OS_THREAD_MUTEX_INITIALIZER) + os_mutex_lock(&runtime_lock); +#endif + + bh_assert(runtime_ref_count >= 0); + if (runtime_ref_count == 0) { + ret = wasm_runtime_init_internal(); + } + if (ret) { + runtime_ref_count++; + } + +#if defined(OS_THREAD_MUTEX_INITIALIZER) + os_mutex_unlock(&runtime_lock); +#endif + + return ret; +} + +static void +wasm_runtime_destroy_internal() { #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 wasm_externref_map_destroy(); @@ -640,6 +676,24 @@ wasm_runtime_destroy() wasm_runtime_memory_destroy(); } +void +wasm_runtime_destroy() +{ +#if defined(OS_THREAD_MUTEX_INITIALIZER) + os_mutex_lock(&runtime_lock); +#endif + + bh_assert(runtime_ref_count > 0); + runtime_ref_count--; + if (runtime_ref_count == 0) { + wasm_runtime_destroy_internal(); + } + +#if defined(OS_THREAD_MUTEX_INITIALIZER) + os_mutex_unlock(&runtime_lock); +#endif +} + RunningMode wasm_runtime_get_default_running_mode(void) { @@ -662,8 +716,8 @@ wasm_runtime_get_gc_heap_size_default(void) } #endif -bool -wasm_runtime_full_init(RuntimeInitArgs *init_args) +static bool +wasm_runtime_full_init_internal(RuntimeInitArgs *init_args) { if (!wasm_runtime_memory_init(init_args->mem_alloc_type, &init_args->mem_alloc_option)) @@ -725,6 +779,30 @@ wasm_runtime_full_init(RuntimeInitArgs *init_args) return true; } +bool +wasm_runtime_full_init(RuntimeInitArgs *init_args) +{ + bool ret = true; + +#if defined(OS_THREAD_MUTEX_INITIALIZER) + os_mutex_lock(&runtime_lock); +#endif + + bh_assert(runtime_ref_count >= 0); + if (runtime_ref_count == 0) { + ret = wasm_runtime_full_init_internal(init_args); + } + if (ret) { + runtime_ref_count++; + } + +#if defined(OS_THREAD_MUTEX_INITIALIZER) + os_mutex_unlock(&runtime_lock); +#endif + + return ret; +} + void wasm_runtime_set_log_level(log_level_t level) { @@ -965,7 +1043,7 @@ wasm_runtime_register_module_internal(const char *module_name, /* module hasn't been registered */ node = runtime_malloc(sizeof(WASMRegisteredModule), NULL, NULL, 0); if (!node) { - LOG_DEBUG("malloc WASMRegisteredModule failed. SZ=%d", + LOG_DEBUG("malloc WASMRegisteredModule failed. SZ=%zu", sizeof(WASMRegisteredModule)); return false; } @@ -1190,7 +1268,7 @@ wasm_runtime_is_built_in_module(const char *module_name) #if WASM_ENABLE_THREAD_MGR != 0 bool -wasm_exec_env_set_aux_stack(WASMExecEnv *exec_env, uint32 start_offset, +wasm_exec_env_set_aux_stack(WASMExecEnv *exec_env, uint64 start_offset, uint32 size) { WASMModuleInstanceCommon *module_inst = @@ -1209,7 +1287,7 @@ wasm_exec_env_set_aux_stack(WASMExecEnv *exec_env, uint32 start_offset, } bool -wasm_exec_env_get_aux_stack(WASMExecEnv *exec_env, uint32 *start_offset, +wasm_exec_env_get_aux_stack(WASMExecEnv *exec_env, uint64 *start_offset, uint32 *size) { WASMModuleInstanceCommon *module_inst = @@ -1255,11 +1333,15 @@ register_module_with_null_name(WASMModuleCommon *module_common, char *error_buf, } WASMModuleCommon * -wasm_runtime_load(uint8 *buf, uint32 size, char *error_buf, - uint32 error_buf_size) +wasm_runtime_load_ex(uint8 *buf, uint32 size, const LoadArgs *args, + char *error_buf, uint32 error_buf_size) { WASMModuleCommon *module_common = NULL; + if (!args) { + return NULL; + } + if (get_package_type(buf, size) == Wasm_Module_Bytecode) { #if WASM_ENABLE_INTERP != 0 module_common = @@ -1267,13 +1349,13 @@ wasm_runtime_load(uint8 *buf, uint32 size, char *error_buf, #if WASM_ENABLE_MULTI_MODULE != 0 true, #endif - error_buf, error_buf_size); + args, error_buf, error_buf_size); #endif } else if (get_package_type(buf, size) == Wasm_Module_AoT) { #if WASM_ENABLE_AOT != 0 module_common = (WASMModuleCommon *)aot_load_from_aot_file( - buf, size, error_buf, error_buf_size); + buf, size, args, error_buf, error_buf_size); #endif } else { @@ -1289,10 +1371,21 @@ wasm_runtime_load(uint8 *buf, uint32 size, char *error_buf, LOG_DEBUG("WASM module load failed"); return NULL; } + + /*TODO: use file name as name and register with name? */ return register_module_with_null_name(module_common, error_buf, error_buf_size); } +WASMModuleCommon * +wasm_runtime_load(uint8 *buf, uint32 size, char *error_buf, + uint32 error_buf_size) +{ + LoadArgs args = { 0 }; + args.name = ""; + return wasm_runtime_load_ex(buf, size, &args, error_buf, error_buf_size); +} + WASMModuleCommon * wasm_runtime_load_from_sections(WASMSection *section_list, bool is_aot, char *error_buf, uint32 error_buf_size) @@ -1357,24 +1450,48 @@ wasm_runtime_unload(WASMModuleCommon *module) #endif } +uint32 +wasm_runtime_get_max_mem(uint32 max_memory_pages, uint32 module_init_page_count, + uint32 module_max_page_count) +{ + if (max_memory_pages == 0) { + /* Max memory not overwritten by runtime, use value from wasm module */ + return module_max_page_count; + } + + if (max_memory_pages < module_init_page_count) { + LOG_WARNING("Cannot override max memory with value lower than module " + "initial memory"); + return module_init_page_count; + } + + if (max_memory_pages > module_max_page_count) { + LOG_WARNING("Cannot override max memory with value greater than module " + "max memory"); + return module_max_page_count; + } + + return max_memory_pages; +} + WASMModuleInstanceCommon * wasm_runtime_instantiate_internal(WASMModuleCommon *module, WASMModuleInstanceCommon *parent, WASMExecEnv *exec_env_main, uint32 stack_size, - uint32 heap_size, char *error_buf, - uint32 error_buf_size) + uint32 heap_size, uint32 max_memory_pages, + char *error_buf, uint32 error_buf_size) { #if WASM_ENABLE_INTERP != 0 if (module->module_type == Wasm_Module_Bytecode) return (WASMModuleInstanceCommon *)wasm_instantiate( (WASMModule *)module, (WASMModuleInstance *)parent, exec_env_main, - stack_size, heap_size, error_buf, error_buf_size); + stack_size, heap_size, max_memory_pages, error_buf, error_buf_size); #endif #if WASM_ENABLE_AOT != 0 if (module->module_type == Wasm_Module_AoT) return (WASMModuleInstanceCommon *)aot_instantiate( (AOTModule *)module, (AOTModuleInstance *)parent, exec_env_main, - stack_size, heap_size, error_buf, error_buf_size); + stack_size, heap_size, max_memory_pages, error_buf, error_buf_size); #endif set_error_buf(error_buf, error_buf_size, "Instantiate module failed, invalid module type"); @@ -1385,9 +1502,21 @@ WASMModuleInstanceCommon * wasm_runtime_instantiate(WASMModuleCommon *module, uint32 stack_size, uint32 heap_size, char *error_buf, uint32 error_buf_size) +{ + return wasm_runtime_instantiate_internal(module, NULL, NULL, stack_size, + heap_size, 0, error_buf, + error_buf_size); +} + +WASMModuleInstanceCommon * +wasm_runtime_instantiate_ex(WASMModuleCommon *module, + const InstantiationArgs *args, char *error_buf, + uint32 error_buf_size) { return wasm_runtime_instantiate_internal( - module, NULL, NULL, stack_size, heap_size, error_buf, error_buf_size); + module, NULL, NULL, args->default_stack_size, + args->host_managed_heap_size, args->max_memory_pages, error_buf, + error_buf_size); } void @@ -1575,11 +1704,11 @@ wasm_runtime_dump_module_inst_mem_consumption( } #endif - os_printf("WASM module inst memory consumption, total size: %u\n", + os_printf("WASM module inst memory consumption, total size: %lu\n", mem_conspn.total_size); os_printf(" module inst struct size: %u\n", mem_conspn.module_inst_struct_size); - os_printf(" memories size: %u\n", mem_conspn.memories_size); + os_printf(" memories size: %lu\n", mem_conspn.memories_size); os_printf(" app heap size: %u\n", mem_conspn.app_heap_size); os_printf(" tables size: %u\n", mem_conspn.tables_size); os_printf(" functions size: %u\n", mem_conspn.functions_size); @@ -1614,8 +1743,9 @@ wasm_runtime_dump_mem_consumption(WASMExecEnv *exec_env) WASMModuleInstanceCommon *module_inst_common; WASMModuleCommon *module_common = NULL; void *heap_handle = NULL; - uint32 total_size = 0, app_heap_peak_size = 0; + uint32 app_heap_peak_size = 0; uint32 max_aux_stack_used = -1; + uint64 total_size = 0; module_inst_common = exec_env->module_inst; #if WASM_ENABLE_INTERP != 0 @@ -1665,7 +1795,7 @@ wasm_runtime_dump_mem_consumption(WASMExecEnv *exec_env) wasm_runtime_dump_module_inst_mem_consumption(module_inst_common); wasm_runtime_dump_exec_env_mem_consumption(exec_env); os_printf("\nTotal memory consumption of module, module inst and " - "exec env: %u\n", + "exec env: %" PRIu64 "\n", total_size); os_printf("Total interpreter stack used: %u\n", exec_env->max_wasm_stack_used); @@ -1816,17 +1946,17 @@ wasm_runtime_get_function_type(const WASMFunctionInstanceCommon *function, WASMFunctionInstanceCommon * wasm_runtime_lookup_function(WASMModuleInstanceCommon *const module_inst, - const char *name, const char *signature) + const char *name) { #if WASM_ENABLE_INTERP != 0 if (module_inst->module_type == Wasm_Module_Bytecode) return (WASMFunctionInstanceCommon *)wasm_lookup_function( - (const WASMModuleInstance *)module_inst, name, signature); + (const WASMModuleInstance *)module_inst, name); #endif #if WASM_ENABLE_AOT != 0 if (module_inst->module_type == Wasm_Module_AoT) return (WASMFunctionInstanceCommon *)aot_lookup_function( - (const AOTModuleInstance *)module_inst, name, signature); + (const AOTModuleInstance *)module_inst, name); #endif return NULL; } @@ -2736,9 +2866,9 @@ wasm_runtime_is_bounds_checks_enabled(WASMModuleInstanceCommon *module_inst) } #endif -uint32 +uint64 wasm_runtime_module_malloc_internal(WASMModuleInstanceCommon *module_inst, - WASMExecEnv *exec_env, uint32 size, + WASMExecEnv *exec_env, uint64 size, void **p_native_addr) { #if WASM_ENABLE_INTERP != 0 @@ -2754,10 +2884,10 @@ wasm_runtime_module_malloc_internal(WASMModuleInstanceCommon *module_inst, return 0; } -uint32 +uint64 wasm_runtime_module_realloc_internal(WASMModuleInstanceCommon *module_inst, - WASMExecEnv *exec_env, uint32 ptr, - uint32 size, void **p_native_addr) + WASMExecEnv *exec_env, uint64 ptr, + uint64 size, void **p_native_addr) { #if WASM_ENABLE_INTERP != 0 if (module_inst->module_type == Wasm_Module_Bytecode) @@ -2774,7 +2904,7 @@ wasm_runtime_module_realloc_internal(WASMModuleInstanceCommon *module_inst, void wasm_runtime_module_free_internal(WASMModuleInstanceCommon *module_inst, - WASMExecEnv *exec_env, uint32 ptr) + WASMExecEnv *exec_env, uint64 ptr) { #if WASM_ENABLE_INTERP != 0 if (module_inst->module_type == Wasm_Module_Bytecode) { @@ -2792,8 +2922,8 @@ wasm_runtime_module_free_internal(WASMModuleInstanceCommon *module_inst, #endif } -uint32 -wasm_runtime_module_malloc(WASMModuleInstanceCommon *module_inst, uint32 size, +uint64 +wasm_runtime_module_malloc(WASMModuleInstanceCommon *module_inst, uint64 size, void **p_native_addr) { #if WASM_ENABLE_INTERP != 0 @@ -2809,9 +2939,9 @@ wasm_runtime_module_malloc(WASMModuleInstanceCommon *module_inst, uint32 size, return 0; } -uint32 -wasm_runtime_module_realloc(WASMModuleInstanceCommon *module_inst, uint32 ptr, - uint32 size, void **p_native_addr) +uint64 +wasm_runtime_module_realloc(WASMModuleInstanceCommon *module_inst, uint64 ptr, + uint64 size, void **p_native_addr) { #if WASM_ENABLE_INTERP != 0 if (module_inst->module_type == Wasm_Module_Bytecode) @@ -2827,7 +2957,7 @@ wasm_runtime_module_realloc(WASMModuleInstanceCommon *module_inst, uint32 ptr, } void -wasm_runtime_module_free(WASMModuleInstanceCommon *module_inst, uint32 ptr) +wasm_runtime_module_free(WASMModuleInstanceCommon *module_inst, uint64 ptr) { #if WASM_ENABLE_INTERP != 0 if (module_inst->module_type == Wasm_Module_Bytecode) { @@ -2843,9 +2973,9 @@ wasm_runtime_module_free(WASMModuleInstanceCommon *module_inst, uint32 ptr) #endif } -uint32 +uint64 wasm_runtime_module_dup_data(WASMModuleInstanceCommon *module_inst, - const char *src, uint32 size) + const char *src, uint64 size) { #if WASM_ENABLE_INTERP != 0 if (module_inst->module_type == Wasm_Module_Bytecode) { @@ -3630,8 +3760,8 @@ wasm_runtime_invoke_native_raw(WASMExecEnv *exec_env, void *func_ptr, { WASMModuleInstanceCommon *module = wasm_runtime_get_module_inst(exec_env); typedef void (*NativeRawFuncPtr)(WASMExecEnv *, uint64 *); - NativeRawFuncPtr invokeNativeRaw = (NativeRawFuncPtr)func_ptr; - uint64 argv_buf[16] = { 0 }, *argv1 = argv_buf, *argv_dst, size; + NativeRawFuncPtr invoke_native_raw = (NativeRawFuncPtr)func_ptr; + uint64 argv_buf[16] = { 0 }, *argv1 = argv_buf, *argv_dst, size, arg_i64; uint32 *argv_src = argv, i, argc1, ptr_len; uint32 arg_i32; bool ret = false; @@ -3656,6 +3786,10 @@ wasm_runtime_invoke_native_raw(WASMExecEnv *exec_env, void *func_ptr, #endif { *(uint32 *)argv_dst = arg_i32 = *argv_src++; + /* TODO: memory64 if future there is a way for supporting + * wasm64 and wasm32 in libc at the same time, remove the + * macro control */ +#if WASM_ENABLE_MEMORY64 == 0 if (signature) { if (signature[i + 1] == '*') { /* param is a pointer */ @@ -3666,28 +3800,68 @@ wasm_runtime_invoke_native_raw(WASMExecEnv *exec_env, void *func_ptr, /* pointer without length followed */ ptr_len = 1; - if (!wasm_runtime_validate_app_addr(module, arg_i32, - ptr_len)) + if (!wasm_runtime_validate_app_addr( + module, (uint64)arg_i32, (uint64)ptr_len)) goto fail; *(uintptr_t *)argv_dst = - (uintptr_t)wasm_runtime_addr_app_to_native(module, - arg_i32); + (uintptr_t)wasm_runtime_addr_app_to_native( + module, (uint64)arg_i32); + } + else if (signature[i + 1] == '$') { + /* param is a string */ + if (!wasm_runtime_validate_app_str_addr( + module, (uint64)arg_i32)) + goto fail; + + *(uintptr_t *)argv_dst = + (uintptr_t)wasm_runtime_addr_app_to_native( + module, (uint64)arg_i32); + } + } +#endif + break; + } + case VALUE_TYPE_I64: +#if WASM_ENABLE_MEMORY64 != 0 + { + PUT_I64_TO_ADDR((uint32 *)argv_dst, + GET_I64_FROM_ADDR(argv_src)); + argv_src += 2; + arg_i64 = *argv_dst; + if (signature) { + /* TODO: memory64 pointer with length need a new symbol + * to represent type i64, with '~' still represent i32 + * length */ + if (signature[i + 1] == '*') { + /* param is a pointer */ + if (signature[i + 2] == '~') + /* pointer with length followed */ + ptr_len = *argv_src; + else + /* pointer without length followed */ + ptr_len = 1; + + if (!wasm_runtime_validate_app_addr(module, arg_i64, + (uint64)ptr_len)) + goto fail; + + *argv_dst = (uint64)wasm_runtime_addr_app_to_native( + module, arg_i64); } else if (signature[i + 1] == '$') { /* param is a string */ if (!wasm_runtime_validate_app_str_addr(module, - arg_i32)) + arg_i64)) goto fail; - *(uintptr_t *)argv_dst = - (uintptr_t)wasm_runtime_addr_app_to_native(module, - arg_i32); + *argv_dst = (uint64)wasm_runtime_addr_app_to_native( + module, arg_i64); } } break; } - case VALUE_TYPE_I64: +#endif case VALUE_TYPE_F64: bh_memcpy_s(argv_dst, sizeof(uint64), argv_src, sizeof(uint32) * 2); @@ -3744,7 +3918,7 @@ 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) { @@ -3816,6 +3990,9 @@ wasm_runtime_invoke_native_raw(WASMExecEnv *exec_env, void *func_ptr, fail: if (argv1 != argv_buf) wasm_runtime_free(argv1); +#if WASM_ENABLE_MEMORY64 == 0 + (void)arg_i64; +#endif return ret; } @@ -4088,21 +4265,21 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, /* pointer without length followed */ ptr_len = 1; - if (!wasm_runtime_validate_app_addr(module, arg_i32, - ptr_len)) + if (!wasm_runtime_validate_app_addr( + module, (uint64)arg_i32, (uint64)ptr_len)) goto fail; arg_i32 = (uintptr_t)wasm_runtime_addr_app_to_native( - module, arg_i32); + module, (uint64)arg_i32); } else if (signature[i + 1] == '$') { /* param is a string */ - if (!wasm_runtime_validate_app_str_addr(module, - arg_i32)) + if (!wasm_runtime_validate_app_str_addr( + module, (uint64)arg_i32)) goto fail; arg_i32 = (uintptr_t)wasm_runtime_addr_app_to_native( - module, arg_i32); + module, (uint64)arg_i32); } } @@ -4463,21 +4640,21 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, /* pointer without length followed */ ptr_len = 1; - if (!wasm_runtime_validate_app_addr(module, arg_i32, - ptr_len)) + if (!wasm_runtime_validate_app_addr( + module, (uint64)arg_i32, (uint64)ptr_len)) goto fail; arg_i32 = (uintptr_t)wasm_runtime_addr_app_to_native( - module, arg_i32); + module, (uint64)arg_i32); } else if (signature[i + 1] == '$') { /* param is a string */ - if (!wasm_runtime_validate_app_str_addr(module, - arg_i32)) + if (!wasm_runtime_validate_app_str_addr( + module, (uint64)arg_i32)) goto fail; arg_i32 = (uintptr_t)wasm_runtime_addr_app_to_native( - module, arg_i32); + module, (uint64)arg_i32); } } @@ -4768,6 +4945,10 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, { arg_i32 = *argv_src++; arg_i64 = arg_i32; + /* TODO: memory64 if future there is a way for supporting + * wasm64 and wasm32 in libc at the same time, remove the + * macro control */ +#if WASM_ENABLE_MEMORY64 == 0 if (signature) { if (signature[i + 1] == '*') { /* param is a pointer */ @@ -4778,21 +4959,63 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, /* pointer without length followed */ ptr_len = 1; - if (!wasm_runtime_validate_app_addr(module, arg_i32, - ptr_len)) + if (!wasm_runtime_validate_app_addr( + module, (uint64)arg_i32, (uint64)ptr_len)) goto fail; arg_i64 = (uintptr_t)wasm_runtime_addr_app_to_native( - module, arg_i32); + module, (uint64)arg_i32); + } + else if (signature[i + 1] == '$') { + /* param is a string */ + if (!wasm_runtime_validate_app_str_addr( + module, (uint64)arg_i32)) + goto fail; + + arg_i64 = (uintptr_t)wasm_runtime_addr_app_to_native( + module, (uint64)arg_i32); + } + } +#endif + if (n_ints < MAX_REG_INTS) + ints[n_ints++] = arg_i64; + else + stacks[n_stacks++] = arg_i64; + break; + } + case VALUE_TYPE_I64: +#if WASM_ENABLE_MEMORY64 != 0 + { + arg_i64 = GET_I64_FROM_ADDR(argv_src); + argv_src += 2; + if (signature) { + /* TODO: memory64 pointer with length need a new symbol + * to represent type i64, with '~' still represent i32 + * length */ + if (signature[i + 1] == '*') { + /* param is a pointer */ + if (signature[i + 2] == '~') + /* pointer with length followed */ + ptr_len = *argv_src; + else + /* pointer without length followed */ + ptr_len = 1; + + if (!wasm_runtime_validate_app_addr(module, arg_i64, + (uint64)ptr_len)) + goto fail; + + arg_i64 = (uint64)wasm_runtime_addr_app_to_native( + module, arg_i64); } else if (signature[i + 1] == '$') { /* param is a string */ if (!wasm_runtime_validate_app_str_addr(module, - arg_i32)) + arg_i64)) goto fail; - arg_i64 = (uintptr_t)wasm_runtime_addr_app_to_native( - module, arg_i32); + arg_i64 = (uint64)wasm_runtime_addr_app_to_native( + module, arg_i64); } } if (n_ints < MAX_REG_INTS) @@ -4801,7 +5024,7 @@ wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr, stacks[n_stacks++] = arg_i64; break; } - case VALUE_TYPE_I64: +#endif #if WASM_ENABLE_GC != 0 case REF_TYPE_FUNCREF: case REF_TYPE_EXTERNREF: @@ -5280,6 +5503,7 @@ wasm_externref_set_cleanup(WASMModuleInstanceCommon *module_inst, if (lookup_user_data.found) { void *key = (void *)(uintptr_t)lookup_user_data.externref_idx; ExternRefMapNode *node = bh_hash_map_find(externref_map, key); + bh_assert(node); node->cleanup = extern_obj_cleanup; ok = true; } @@ -6292,6 +6516,7 @@ wasm_runtime_load_depended_module(const WASMModuleCommon *parent_module, bool ret = false; uint8 *buffer = NULL; uint32 buffer_size = 0; + LoadArgs args = { 0 }; /* check the registered module list of the parent */ sub_module = wasm_runtime_search_sub_module(parent_module, sub_module_name); @@ -6331,23 +6556,25 @@ wasm_runtime_load_depended_module(const WASMModuleCommon *parent_module, if (!ret) { LOG_DEBUG("read the file of %s failed", sub_module_name); set_error_buf_v(parent_module, error_buf, error_buf_size, - "unknown import", sub_module_name); + "unknown import %s", sub_module_name); goto delete_loading_module; } if (get_package_type(buffer, buffer_size) != parent_module->module_type) { LOG_DEBUG("moudle %s type error", sub_module_name); - goto delete_loading_module; + goto destroy_file_buffer; } + + args.name = (char *)sub_module_name; if (get_package_type(buffer, buffer_size) == Wasm_Module_Bytecode) { #if WASM_ENABLE_INTERP != 0 - sub_module = (WASMModuleCommon *)wasm_load(buffer, buffer_size, false, - error_buf, error_buf_size); + sub_module = (WASMModuleCommon *)wasm_load( + buffer, buffer_size, false, &args, error_buf, error_buf_size); #endif } else if (get_package_type(buffer, buffer_size) == Wasm_Module_AoT) { #if WASM_ENABLE_AOT != 0 sub_module = (WASMModuleCommon *)aot_load_from_aot_file( - buffer, buffer_size, error_buf, error_buf_size); + buffer, buffer_size, &args, error_buf, error_buf_size); #endif } if (!sub_module) { @@ -6403,7 +6630,8 @@ bool wasm_runtime_sub_module_instantiate(WASMModuleCommon *module, WASMModuleInstanceCommon *module_inst, uint32 stack_size, uint32 heap_size, - char *error_buf, uint32 error_buf_size) + uint32 max_memory_pages, char *error_buf, + uint32 error_buf_size) { bh_list *sub_module_inst_list = NULL; WASMRegisteredModule *sub_module_list_node = NULL; @@ -6431,8 +6659,8 @@ wasm_runtime_sub_module_instantiate(WASMModuleCommon *module, WASMModuleCommon *sub_module = sub_module_list_node->module; WASMModuleInstanceCommon *sub_module_inst = NULL; sub_module_inst = wasm_runtime_instantiate_internal( - sub_module, NULL, NULL, stack_size, heap_size, error_buf, - error_buf_size); + sub_module, NULL, NULL, stack_size, heap_size, max_memory_pages, + error_buf, error_buf_size); if (!sub_module_inst) { LOG_DEBUG("instantiate %s failed", sub_module_list_node->module_name); @@ -6441,7 +6669,7 @@ wasm_runtime_sub_module_instantiate(WASMModuleCommon *module, sub_module_inst_list_node = loader_malloc(sizeof(WASMSubModInstNode), error_buf, error_buf_size); if (!sub_module_inst_list_node) { - LOG_DEBUG("Malloc WASMSubModInstNode failed, SZ:%d", + LOG_DEBUG("Malloc WASMSubModInstNode failed, SZ: %zu", sizeof(WASMSubModInstNode)); if (sub_module_inst) wasm_runtime_deinstantiate_internal(sub_module_inst, false); @@ -6539,3 +6767,44 @@ wasm_runtime_set_linux_perf(bool flag) enable_linux_perf = flag; } #endif + +bool +wasm_runtime_set_module_name(wasm_module_t module, const char *name, + char *error_buf, uint32_t error_buf_size) +{ + if (!module) + return false; + +#if WASM_ENABLE_INTERP != 0 + if (module->module_type == Wasm_Module_Bytecode) + return wasm_set_module_name((WASMModule *)module, name, error_buf, + error_buf_size); +#endif + +#if WASM_ENABLE_AOT != 0 + if (module->module_type == Wasm_Module_AoT) + return aot_set_module_name((AOTModule *)module, name, error_buf, + error_buf_size); +#endif + + return false; +} + +const char * +wasm_runtime_get_module_name(wasm_module_t module) +{ + if (!module) + return ""; + +#if WASM_ENABLE_INTERP != 0 + if (module->module_type == Wasm_Module_Bytecode) + return wasm_get_module_name((WASMModule *)module); +#endif + +#if WASM_ENABLE_AOT != 0 + if (module->module_type == Wasm_Module_AoT) + return aot_get_module_name((AOTModule *)module); +#endif + + return ""; +} diff --git a/core/iwasm/common/wasm_runtime_common.h b/core/iwasm/common/wasm_runtime_common.h index 0d449c328..62c35473a 100644 --- a/core/iwasm/common/wasm_runtime_common.h +++ b/core/iwasm/common/wasm_runtime_common.h @@ -373,7 +373,7 @@ typedef struct WASMModuleCommon { /* 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 + Typically, it should be accessed by casting to the corresponding actual module_type dependent structure, not via this member. */ uint8 module_data[1]; } WASMModuleCommon; @@ -389,7 +389,7 @@ typedef struct WASMModuleInstanceCommon { /* 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 + Typically, it should be accessed by casting to the corresponding actual module_type dependent structure, not via this member. */ uint8 module_inst_data[1]; } WASMModuleInstanceCommon; @@ -413,10 +413,10 @@ typedef struct WASMModuleMemConsumption { } WASMModuleMemConsumption; typedef struct WASMModuleInstMemConsumption { - uint32 total_size; + uint64 total_size; uint32 module_inst_struct_size; - uint32 memories_size; uint32 app_heap_size; + uint64 memories_size; uint32 tables_size; uint32 globals_size; uint32 functions_size; @@ -561,13 +561,18 @@ wasm_runtime_load_from_sections(WASMSection *section_list, bool is_aot, WASM_RUNTIME_API_EXTERN void wasm_runtime_unload(WASMModuleCommon *module); +/* Internal API */ +uint32 +wasm_runtime_get_max_mem(uint32 max_memory_pages, uint32 module_init_page_count, + uint32 module_max_page_count); + /* Internal API */ WASMModuleInstanceCommon * wasm_runtime_instantiate_internal(WASMModuleCommon *module, WASMModuleInstanceCommon *parent, WASMExecEnv *exec_env_main, uint32 stack_size, - uint32 heap_size, char *error_buf, - uint32 error_buf_size); + uint32 heap_size, uint32 max_memory_pages, + char *error_buf, uint32 error_buf_size); /* Internal API */ void @@ -580,6 +585,12 @@ wasm_runtime_instantiate(WASMModuleCommon *module, uint32 default_stack_size, uint32 host_managed_heap_size, char *error_buf, uint32 error_buf_size); +/* See wasm_export.h for description */ +WASM_RUNTIME_API_EXTERN WASMModuleInstanceCommon * +wasm_runtime_instantiate_ex(WASMModuleCommon *module, + const InstantiationArgs *args, char *error_buf, + uint32 error_buf_size); + /* See wasm_export.h for description */ WASM_RUNTIME_API_EXTERN bool wasm_runtime_set_running_mode(wasm_module_inst_t module_inst, @@ -600,7 +611,7 @@ wasm_runtime_get_module(WASMModuleInstanceCommon *module_inst); /* See wasm_export.h for description */ WASM_RUNTIME_API_EXTERN WASMFunctionInstanceCommon * wasm_runtime_lookup_function(WASMModuleInstanceCommon *const module_inst, - const char *name, const char *signature); + const char *name); /* Internal API */ WASMFuncType * @@ -759,66 +770,66 @@ WASM_RUNTIME_API_EXTERN void * wasm_runtime_get_custom_data(WASMModuleInstanceCommon *module_inst); /* Internal API */ -uint32 +uint64 wasm_runtime_module_malloc_internal(WASMModuleInstanceCommon *module_inst, - WASMExecEnv *exec_env, uint32 size, + WASMExecEnv *exec_env, uint64 size, void **p_native_addr); /* Internal API */ -uint32 +uint64 wasm_runtime_module_realloc_internal(WASMModuleInstanceCommon *module_inst, - WASMExecEnv *exec_env, uint32 ptr, - uint32 size, void **p_native_addr); + WASMExecEnv *exec_env, uint64 ptr, + uint64 size, void **p_native_addr); /* Internal API */ void wasm_runtime_module_free_internal(WASMModuleInstanceCommon *module_inst, - WASMExecEnv *exec_env, uint32 ptr); + WASMExecEnv *exec_env, uint64 ptr); /* See wasm_export.h for description */ -WASM_RUNTIME_API_EXTERN uint32 -wasm_runtime_module_malloc(WASMModuleInstanceCommon *module_inst, uint32 size, +WASM_RUNTIME_API_EXTERN uint64 +wasm_runtime_module_malloc(WASMModuleInstanceCommon *module_inst, uint64 size, void **p_native_addr); /* See wasm_export.h for description */ WASM_RUNTIME_API_EXTERN void -wasm_runtime_module_free(WASMModuleInstanceCommon *module_inst, uint32 ptr); +wasm_runtime_module_free(WASMModuleInstanceCommon *module_inst, uint64 ptr); /* See wasm_export.h for description */ -WASM_RUNTIME_API_EXTERN uint32 +WASM_RUNTIME_API_EXTERN uint64 wasm_runtime_module_dup_data(WASMModuleInstanceCommon *module_inst, - const char *src, uint32 size); + const char *src, uint64 size); /* See wasm_export.h for description */ WASM_RUNTIME_API_EXTERN bool wasm_runtime_validate_app_addr(WASMModuleInstanceCommon *module_inst, - uint32 app_offset, uint32 size); + uint64 app_offset, uint64 size); /* See wasm_export.h for description */ WASM_RUNTIME_API_EXTERN bool wasm_runtime_validate_app_str_addr(WASMModuleInstanceCommon *module_inst, - uint32 app_str_offset); + uint64 app_str_offset); /* See wasm_export.h for description */ WASM_RUNTIME_API_EXTERN bool wasm_runtime_validate_native_addr(WASMModuleInstanceCommon *module_inst, - void *native_ptr, uint32 size); + void *native_ptr, uint64 size); /* See wasm_export.h for description */ WASM_RUNTIME_API_EXTERN void * wasm_runtime_addr_app_to_native(WASMModuleInstanceCommon *module_inst, - uint32 app_offset); + uint64 app_offset); /* See wasm_export.h for description */ -WASM_RUNTIME_API_EXTERN uint32 +WASM_RUNTIME_API_EXTERN uint64 wasm_runtime_addr_native_to_app(WASMModuleInstanceCommon *module_inst, void *native_ptr); /* See wasm_export.h for description */ WASM_RUNTIME_API_EXTERN bool wasm_runtime_get_app_addr_range(WASMModuleInstanceCommon *module_inst, - uint32 app_offset, uint32 *p_app_start_offset, - uint32 *p_app_end_offset); + uint64 app_offset, uint64 *p_app_start_offset, + uint64 *p_app_end_offset); /* See wasm_export.h for description */ WASM_RUNTIME_API_EXTERN bool @@ -887,7 +898,8 @@ bool wasm_runtime_sub_module_instantiate(WASMModuleCommon *module, WASMModuleInstanceCommon *module_inst, uint32 stack_size, uint32 heap_size, - char *error_buf, uint32 error_buf_size); + uint32 max_memory_pages, char *error_buf, + uint32 error_buf_size); void wasm_runtime_sub_module_deinstantiate(WASMModuleInstanceCommon *module_inst); #endif @@ -904,11 +916,11 @@ wasm_runtime_is_built_in_module(const char *module_name); #if WASM_ENABLE_THREAD_MGR != 0 bool -wasm_exec_env_get_aux_stack(WASMExecEnv *exec_env, uint32 *start_offset, +wasm_exec_env_get_aux_stack(WASMExecEnv *exec_env, uint64 *start_offset, uint32 *size); bool -wasm_exec_env_set_aux_stack(WASMExecEnv *exec_env, uint32 start_offset, +wasm_exec_env_set_aux_stack(WASMExecEnv *exec_env, uint64 start_offset, uint32 size); #endif 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.h b/core/iwasm/compilation/aot.h index 484531426..c0b68e05f 100644 --- a/core/iwasm/compilation/aot.h +++ b/core/iwasm/compilation/aot.h @@ -316,11 +316,11 @@ typedef struct AOTCompData { uint32 retain_func_index; uint32 aux_data_end_global_index; - uint32 aux_data_end; + uint64 aux_data_end; uint32 aux_heap_base_global_index; - uint32 aux_heap_base; + uint64 aux_heap_base; uint32 aux_stack_top_global_index; - uint32 aux_stack_bottom; + uint64 aux_stack_bottom; uint32 aux_stack_size; #if WASM_ENABLE_STRINGREF != 0 diff --git a/core/iwasm/compilation/aot_compiler.c b/core/iwasm/compilation/aot_compiler.c index 9bca81d24..5c257742a 100644 --- a/core/iwasm/compilation/aot_compiler.c +++ b/core/iwasm/compilation/aot_compiler.c @@ -83,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; \ @@ -93,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; \ @@ -103,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; \ @@ -327,7 +330,7 @@ aot_gen_commit_values(AOTCompFrame *frame) if (!p->dirty) continue; - n = p - frame->lp; + n = (uint32)(p - frame->lp); /* Commit reference flag */ if (comp_ctx->enable_gc) { @@ -429,7 +432,7 @@ aot_gen_commit_values(AOTCompFrame *frame) continue; p->dirty = 0; - n = p - frame->lp; + n = (uint32)(p - frame->lp); /* Commit values */ switch (p->type) { @@ -535,7 +538,7 @@ aot_gen_commit_values(AOTCompFrame *frame) /* Clear reference flags for unused stack slots. */ for (p = frame->sp; p < end; p++) { bh_assert(!p->ref); - n = p - frame->lp; + n = (uint32)(p - frame->lp); /* Commit reference flag. */ if (p->ref != p->committed_ref - 1) { @@ -618,7 +621,7 @@ aot_gen_commit_sp_ip(AOTCompFrame *frame, bool commit_sp, bool commit_ip) } if (commit_sp) { - n = sp - frame->lp; + n = (uint32)(sp - frame->lp); value = I32_CONST(offset_of_local(comp_ctx, n)); if (!value) { aot_set_last_error("llvm build const failed"); @@ -963,7 +966,9 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) location = dwarf_gen_location( comp_ctx, func_ctx, (frame_ip - 1) - comp_ctx->comp_data->wasm_module->buf_code); - LLVMSetCurrentDebugLocation2(comp_ctx->builder, location); + if (location != NULL) { + LLVMSetCurrentDebugLocation2(comp_ctx->builder, location); + } #endif switch (opcode) { @@ -3447,16 +3452,6 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) break; } - case SIMD_i32x4_narrow_i64x2_s: - case SIMD_i32x4_narrow_i64x2_u: - { - if (!aot_compile_simd_i32x4_narrow_i64x2( - comp_ctx, func_ctx, - SIMD_i32x4_narrow_i64x2_s == opcode)) - return false; - break; - } - case SIMD_i32x4_extend_low_i16x8_s: case SIMD_i32x4_extend_high_i16x8_s: { @@ -3496,16 +3491,6 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) break; } - case SIMD_i32x4_add_sat_s: - case SIMD_i32x4_add_sat_u: - { - if (!aot_compile_simd_i32x4_saturate( - comp_ctx, func_ctx, V128_ADD, - opcode == SIMD_i32x4_add_sat_s)) - return false; - break; - } - case SIMD_i32x4_sub: { if (!aot_compile_simd_i32x4_arith(comp_ctx, func_ctx, @@ -3514,16 +3499,6 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) break; } - case SIMD_i32x4_sub_sat_s: - case SIMD_i32x4_sub_sat_u: - { - if (!aot_compile_simd_i32x4_saturate( - comp_ctx, func_ctx, V128_SUB, - opcode == SIMD_i32x4_add_sat_s)) - return false; - break; - } - case SIMD_i32x4_mul: { if (!aot_compile_simd_i32x4_arith(comp_ctx, func_ctx, @@ -3560,13 +3535,6 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) break; } - case SIMD_i32x4_avgr_u: - { - if (!aot_compile_simd_i32x4_avgr_u(comp_ctx, func_ctx)) - return false; - break; - } - case SIMD_i32x4_extmul_low_i16x8_s: case SIMD_i32x4_extmul_high_i16x8_s: { @@ -3723,13 +3691,6 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) break; } - case SIMD_f32x4_round: - { - if (!aot_compile_simd_f32x4_round(comp_ctx, func_ctx)) - return false; - break; - } - case SIMD_f32x4_sqrt: { if (!aot_compile_simd_f32x4_sqrt(comp_ctx, func_ctx)) @@ -3783,13 +3744,6 @@ aot_compile_func(AOTCompContext *comp_ctx, uint32 func_index) break; } - case SIMD_f64x2_round: - { - if (!aot_compile_simd_f64x2_round(comp_ctx, func_ctx)) - return false; - break; - } - case SIMD_f64x2_sqrt: { if (!aot_compile_simd_f64x2_sqrt(comp_ctx, func_ctx)) diff --git a/core/iwasm/compilation/aot_compiler.h b/core/iwasm/compilation/aot_compiler.h index 3bf1509d9..5038a4130 100644 --- a/core/iwasm/compilation/aot_compiler.h +++ b/core/iwasm/compilation/aot_compiler.h @@ -569,6 +569,10 @@ set_local_gc_ref(AOTCompFrame *frame, int n, LLVMValueRef value, uint8 ref_type) 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; \ diff --git a/core/iwasm/compilation/aot_emit_aot_file.c b/core/iwasm/compilation/aot_emit_aot_file.c index 00a1d3c91..52637686f 100644 --- a/core/iwasm/compilation/aot_emit_aot_file.c +++ b/core/iwasm/compilation/aot_emit_aot_file.c @@ -25,73 +25,6 @@ } \ } while (0) -#if WASM_ENABLE_LOAD_CUSTOM_SECTION != 0 -static bool -check_utf8_str(const uint8 *str, uint32 len) -{ - /* The valid ranges are taken from page 125, below link - https://www.unicode.org/versions/Unicode9.0.0/ch03.pdf */ - const uint8 *p = str, *p_end = str + len; - uint8 chr; - - while (p < p_end) { - chr = *p; - if (chr < 0x80) { - p++; - } - else if (chr >= 0xC2 && chr <= 0xDF && p + 1 < p_end) { - if (p[1] < 0x80 || p[1] > 0xBF) { - return false; - } - p += 2; - } - else if (chr >= 0xE0 && chr <= 0xEF && p + 2 < p_end) { - if (chr == 0xE0) { - if (p[1] < 0xA0 || p[1] > 0xBF || p[2] < 0x80 || p[2] > 0xBF) { - return false; - } - } - else if (chr == 0xED) { - if (p[1] < 0x80 || p[1] > 0x9F || p[2] < 0x80 || p[2] > 0xBF) { - return false; - } - } - else if (chr >= 0xE1 && chr <= 0xEF) { - if (p[1] < 0x80 || p[1] > 0xBF || p[2] < 0x80 || p[2] > 0xBF) { - return false; - } - } - p += 3; - } - else if (chr >= 0xF0 && chr <= 0xF4 && p + 3 < p_end) { - if (chr == 0xF0) { - if (p[1] < 0x90 || p[1] > 0xBF || p[2] < 0x80 || p[2] > 0xBF - || p[3] < 0x80 || p[3] > 0xBF) { - return false; - } - } - else if (chr >= 0xF1 && chr <= 0xF3) { - if (p[1] < 0x80 || p[1] > 0xBF || p[2] < 0x80 || p[2] > 0xBF - || p[3] < 0x80 || p[3] > 0xBF) { - return false; - } - } - else if (chr == 0xF4) { - if (p[1] < 0x80 || p[1] > 0x8F || p[2] < 0x80 || p[2] > 0xBF - || p[3] < 0x80 || p[3] > 0xBF) { - return false; - } - } - p += 4; - } - else { - return false; - } - } - return (p == p_end); -} -#endif /* end of WASM_ENABLE_LOAD_CUSTOM_SECTION != 0 */ - /* Internal function in object file */ typedef struct AOTObjectFunc { char *func_name; @@ -179,6 +112,16 @@ is_little_endian_binary(const AOTObjectData *obj_data) return obj_data->target_info.bin_type & 1 ? false : true; } +static bool +need_call_wrapped_indirect(const AOTObjectData *obj_data) +{ + const bool need_precheck = obj_data->comp_ctx->enable_stack_bound_check + || obj_data->comp_ctx->enable_stack_estimation; + + return obj_data->comp_ctx->is_indirect_mode && need_precheck + && !strncmp(obj_data->comp_ctx->target_arch, "xtensa", 6); +} + static bool str_starts_with(const char *str, const char *prefix) { @@ -840,7 +783,7 @@ get_init_data_section_size(AOTCompContext *comp_ctx, AOTCompData *comp_data, size += (uint32)sizeof(uint32) * 2; /* aux data/heap/stack data */ - size += sizeof(uint32) * 7; + size += sizeof(uint32) * 10; size += get_object_data_section_info_size(comp_ctx, obj_data); return size; @@ -870,6 +813,10 @@ get_func_section_size(AOTCompContext *comp_ctx, AOTCompData *comp_data, /* function type indexes */ size += (uint32)sizeof(uint32) * comp_data->func_count; + /* aot_func#xxx + aot_func_internal#xxx in XIP mode for xtensa */ + if (need_call_wrapped_indirect(obj_data)) + size *= 2; + /* max_local_cell_nums */ size += (uint32)sizeof(uint32) * comp_data->func_count; @@ -1342,28 +1289,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 { @@ -1529,6 +1476,7 @@ fail_integer_too_large: return false; } +/* NOLINTNEXTLINE */ #define read_leb_uint32(p, p_end, res) \ do { \ uint64 res64; \ @@ -1537,9 +1485,16 @@ fail_integer_too_large: res = (uint32)res64; \ } while (0) +/* + * - transfer .name section in .wasm (comp_data->name_section_buf) to + * aot buf (comp_data->aot_name_section_buf) + * - leb128 to u32 + * - add `\0` at the end of every name, and adjust length(+1) + */ static uint32 get_name_section_size(AOTCompData *comp_data) { + /* original name section content in .wasm */ const uint8 *p = comp_data->name_section_buf, *p_end = comp_data->name_section_buf_end; uint8 *buf, *buf_end; @@ -1566,22 +1521,20 @@ get_name_section_size(AOTCompData *comp_data) aot_set_last_error("allocate memory for custom name section failed."); return 0; } + memset(buf, 0, (uint32)max_aot_buf_size); buf_end = buf + max_aot_buf_size; + /* the size of "name". it should be 4 */ read_leb_uint32(p, p_end, name_len); offset = align_uint(offset, 4); EMIT_U32(name_len); - if (name_len == 0 || p + name_len > p_end) { + if (name_len != 4 || p + name_len > p_end) { aot_set_last_error("unexpected end"); return 0; } - if (!check_utf8_str(p, name_len)) { - aot_set_last_error("invalid UTF-8 encoding"); - return 0; - } - + /* "name" */ if (memcmp(p, "name", 4) != 0) { aot_set_last_error("invalid custom name section"); return 0; @@ -1630,9 +1583,18 @@ get_name_section_size(AOTCompData *comp_data) previous_func_index = func_index; read_leb_uint32(p, p_end, func_name_len); offset = align_uint(offset, 2); - EMIT_U16(func_name_len); + + /* emit a string ends with `\0` */ + if (func_name_len + 1 > UINT16_MAX) { + aot_set_last_error( + "emit string failed: string too long"); + goto fail; + } + /* extra 1 byte for \0 */ + EMIT_U16(func_name_len + 1); EMIT_BUF(p, func_name_len); p += func_name_len; + EMIT_U8(0); } } break; @@ -2413,11 +2375,11 @@ aot_emit_init_data_section(uint8 *buf, uint8 *buf_end, uint32 *p_offset, EMIT_U32(comp_data->start_func_index); EMIT_U32(comp_data->aux_data_end_global_index); - EMIT_U32(comp_data->aux_data_end); + EMIT_U64(comp_data->aux_data_end); EMIT_U32(comp_data->aux_heap_base_global_index); - EMIT_U32(comp_data->aux_heap_base); + EMIT_U64(comp_data->aux_heap_base); EMIT_U32(comp_data->aux_stack_top_global_index); - EMIT_U32(comp_data->aux_stack_bottom); + EMIT_U64(comp_data->aux_stack_bottom); EMIT_U32(comp_data->aux_stack_size); if (!aot_emit_object_data_section_info(buf, buf_end, &offset, comp_ctx, @@ -2594,9 +2556,30 @@ aot_emit_func_section(uint8 *buf, uint8 *buf_end, uint32 *p_offset, EMIT_U64(func->text_offset); } + if (need_call_wrapped_indirect(obj_data)) { + /* + * Explicitly emit aot_func_internal#xxx for Xtensa XIP, therefore, + * for aot_func#xxx, func_indexes ranged from 0 ~ func_count, + * for aot_func_internal#xxxx, from func_count + 1 ~ 2 * func_count. + */ + for (i = 0, func = obj_data->funcs; i < obj_data->func_count; + i++, func++) { + if (is_32bit_binary(obj_data)) + EMIT_U32(func->text_offset_of_aot_func_internal); + else + EMIT_U64(func->text_offset_of_aot_func_internal); + } + } + for (i = 0; i < comp_data->func_count; i++) EMIT_U32(funcs[i]->func_type_index); + if (need_call_wrapped_indirect(obj_data)) { + /* func_type_index for aot_func_internal#xxxx */ + 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; @@ -3911,7 +3894,12 @@ aot_resolve_object_relocation_group(AOTObjectData *obj_data, * Note: aot_stack_sizes_section_name section only contains * stack_sizes table. */ - if (!strcmp(relocation->symbol_name, aot_stack_sizes_name)) { + if (!strcmp(relocation->symbol_name, aot_stack_sizes_name) + /* in windows 32, the symbol name may start with '_' */ + || (strlen(relocation->symbol_name) > 0 + && relocation->symbol_name[0] == '_' + && !strcmp(relocation->symbol_name + 1, + aot_stack_sizes_name))) { /* discard const */ relocation->symbol_name = (char *)aot_stack_sizes_section_name; } diff --git a/core/iwasm/compilation/aot_emit_control.c b/core/iwasm/compilation/aot_emit_control.c index 8b24bcab8..24511ffd0 100644 --- a/core/iwasm/compilation/aot_emit_control.c +++ b/core/iwasm/compilation/aot_emit_control.c @@ -374,7 +374,9 @@ handle_next_reachable_block(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, goto fail; } #if WASM_ENABLE_DEBUG_AOT != 0 - LLVMInstructionSetDebugLoc(ret, return_location); + if (return_location != NULL) { + LLVMInstructionSetDebugLoc(ret, return_location); + } #endif } else { @@ -383,7 +385,9 @@ handle_next_reachable_block(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, goto fail; } #if WASM_ENABLE_DEBUG_AOT != 0 - LLVMInstructionSetDebugLoc(ret, return_location); + if (return_location != NULL) { + LLVMInstructionSetDebugLoc(ret, return_location); + } #endif } } @@ -1265,6 +1269,7 @@ aot_compile_op_br_table(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, PUSH(values[j], target_block->result_types[j]); } wasm_runtime_free(values); + values = NULL; } target_block->is_reachable = true; if (i == br_count) @@ -1290,6 +1295,7 @@ aot_compile_op_br_table(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, PUSH(values[j], target_block->param_types[j]); } wasm_runtime_free(values); + values = NULL; } if (i == br_count) default_llvm_block = target_block->llvm_entry_block; diff --git a/core/iwasm/compilation/aot_emit_exception.c b/core/iwasm/compilation/aot_emit_exception.c index 1e4cccbe6..d3dcf719d 100644 --- a/core/iwasm/compilation/aot_emit_exception.c +++ b/core/iwasm/compilation/aot_emit_exception.c @@ -88,6 +88,12 @@ aot_emit_exception(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, aot_set_last_error("llvm build phi failed."); return false; } + + /* Commit ip to current frame */ + if (!commit_ip(comp_ctx, func_ctx, func_ctx->exception_ip_phi, + is_64bit)) { + return false; + } } /* Call aot_set_exception_with_id() to throw exception */ @@ -154,12 +160,6 @@ 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)) { diff --git a/core/iwasm/compilation/aot_emit_function.c b/core/iwasm/compilation/aot_emit_function.c index 36bbc2222..224173163 100644 --- a/core/iwasm/compilation/aot_emit_function.c +++ b/core/iwasm/compilation/aot_emit_function.c @@ -329,13 +329,9 @@ call_aot_invoke_c_api_native(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, param_values[0] = func_ctx->aot_inst; - /* Get module_inst->e->common.c_api_func_imports */ - offset_c_api_func_imports = - get_module_inst_extra_offset(comp_ctx) - + (comp_ctx->is_jit_mode - ? offsetof(WASMModuleInstanceExtra, common.c_api_func_imports) - /* offsetof(AOTModuleInstanceExtra, common.c_api_func_imports) */ - : sizeof(uint64)); + /* Get module_inst->c_api_func_imports, jit mode WASMModuleInstance is the + * same layout with AOTModuleInstance */ + offset_c_api_func_imports = offsetof(AOTModuleInstance, c_api_func_imports); offset = I32_CONST(offset_c_api_func_imports); CHECK_LLVM_CONST(offset); c_api_func_imports = @@ -1167,8 +1163,8 @@ check_app_addr_and_convert(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, /* prepare function type of aot_check_app_addr_and_convert */ func_param_types[0] = comp_ctx->aot_inst_type; /* module_inst */ func_param_types[1] = INT8_TYPE; /* is_str_arg */ - func_param_types[2] = I32_TYPE; /* app_offset */ - func_param_types[3] = I32_TYPE; /* buf_size */ + func_param_types[2] = I64_TYPE; /* app_offset */ + func_param_types[3] = I64_TYPE; /* buf_size */ func_param_types[4] = comp_ctx->basic_types.int8_pptr_type; /* p_native_addr */ if (!(func_type = @@ -1555,7 +1551,19 @@ aot_compile_op_call(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, if (signature[i + 2] == '~') native_addr_size = param_values[i + 2]; else - native_addr_size = I32_ONE; + native_addr_size = I64_CONST(1); + if (!(native_addr_size = LLVMBuildZExtOrBitCast( + comp_ctx->builder, native_addr_size, I64_TYPE, + "native_addr_size_i64"))) { + aot_set_last_error("llvm build zextOrBitCast failed."); + goto fail; + } + if (!(param_values[j] = LLVMBuildZExtOrBitCast( + comp_ctx->builder, param_values[j], I64_TYPE, + "native_addr_i64"))) { + aot_set_last_error("llvm build zextOrBitCast failed."); + goto fail; + } if (!check_app_addr_and_convert( comp_ctx, func_ctx, false, param_values[j], native_addr_size, &native_addr)) { @@ -1564,7 +1572,13 @@ aot_compile_op_call(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, param_values[j] = native_addr; } else if (signature[i + 1] == '$') { - native_addr_size = I32_ZERO; + native_addr_size = I64_ZERO; + if (!(param_values[j] = LLVMBuildZExtOrBitCast( + comp_ctx->builder, param_values[j], I64_TYPE, + "native_addr_i64"))) { + aot_set_last_error("llvm build zextOrBitCast failed."); + goto fail; + } if (!check_app_addr_and_convert( comp_ctx, func_ctx, true, param_values[j], native_addr_size, &native_addr)) { diff --git a/core/iwasm/compilation/aot_emit_memory.c b/core/iwasm/compilation/aot_emit_memory.c index fc9952de0..eedc5420a 100644 --- a/core/iwasm/compilation/aot_emit_memory.c +++ b/core/iwasm/compilation/aot_emit_memory.c @@ -919,7 +919,7 @@ check_bulk_memory_overflow(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, comp_ctx->comp_data->memories[0].num_bytes_per_page; uint32 init_page_count = comp_ctx->comp_data->memories[0].mem_init_page_count; - uint32 mem_data_size = num_bytes_per_page * init_page_count; + uint64 mem_data_size = (uint64)num_bytes_per_page * init_page_count; if (mem_data_size > 0 && mem_offset + mem_len <= mem_data_size) { /* inside memory space */ /* maddr = mem_base_addr + moffset */ @@ -938,7 +938,7 @@ check_bulk_memory_overflow(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, } else { if (!(mem_size = LLVMBuildLoad2( - comp_ctx->builder, I32_TYPE, + comp_ctx->builder, I64_TYPE, func_ctx->mem_info[0].mem_data_size_addr, "mem_size"))) { aot_set_last_error("llvm build load failed."); goto fail; @@ -951,8 +951,6 @@ check_bulk_memory_overflow(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, offset = LLVMBuildZExt(comp_ctx->builder, offset, I64_TYPE, "extend_offset"); bytes = LLVMBuildZExt(comp_ctx->builder, bytes, I64_TYPE, "extend_len"); - mem_size = - LLVMBuildZExt(comp_ctx->builder, mem_size, I64_TYPE, "extend_size"); BUILD_OP(Add, offset, bytes, max_addr, "max_addr"); BUILD_ICMP(LLVMIntUGT, max_addr, mem_size, cmp, "cmp_max_mem_addr"); diff --git a/core/iwasm/compilation/aot_emit_variable.c b/core/iwasm/compilation/aot_emit_variable.c index 73edbf085..6cd32217e 100644 --- a/core/iwasm/compilation/aot_emit_variable.c +++ b/core/iwasm/compilation/aot_emit_variable.c @@ -251,7 +251,7 @@ compile_global(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, LLVMBasicBlockRef block_curr = LLVMGetInsertBlock(comp_ctx->builder); LLVMBasicBlockRef check_overflow_succ, check_underflow_succ; - LLVMValueRef cmp; + LLVMValueRef cmp, global_i64; /* Add basic blocks */ if (!(check_overflow_succ = LLVMAppendBasicBlockInContext( @@ -270,8 +270,14 @@ compile_global(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, } LLVMMoveBasicBlockAfter(check_underflow_succ, check_overflow_succ); + if (!(global_i64 = LLVMBuildZExt(comp_ctx->builder, global, + I64_TYPE, "global_i64"))) { + aot_set_last_error("llvm build zext failed."); + return false; + } + /* Check aux stack overflow */ - if (!(cmp = LLVMBuildICmp(comp_ctx->builder, LLVMIntULE, global, + if (!(cmp = LLVMBuildICmp(comp_ctx->builder, LLVMIntULE, global_i64, func_ctx->aux_stack_bound, "cmp"))) { aot_set_last_error("llvm build icmp failed."); return false; @@ -283,7 +289,7 @@ compile_global(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, /* Check aux stack underflow */ LLVMPositionBuilderAtEnd(comp_ctx->builder, check_overflow_succ); - if (!(cmp = LLVMBuildICmp(comp_ctx->builder, LLVMIntUGT, global, + if (!(cmp = LLVMBuildICmp(comp_ctx->builder, LLVMIntUGT, global_i64, func_ctx->aux_stack_bottom, "cmp"))) { aot_set_last_error("llvm build icmp failed."); return false; diff --git a/core/iwasm/compilation/aot_llvm.c b/core/iwasm/compilation/aot_llvm.c index bc50107dc..3af56e8b6 100644 --- a/core/iwasm/compilation/aot_llvm.c +++ b/core/iwasm/compilation/aot_llvm.c @@ -24,6 +24,8 @@ create_native_stack_bound(const AOTCompContext *comp_ctx, static bool create_native_stack_top_min(const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx); +static bool +create_func_ptrs(const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx); LLVMTypeRef wasm_type_to_llvm_type(const AOTCompContext *comp_ctx, @@ -83,7 +85,7 @@ aot_add_llvm_func1(const AOTCompContext *comp_ctx, LLVMModuleRef module, uint32 func_index, uint32 param_count, LLVMTypeRef func_type, const char *prefix) { - char func_name[48]; + char func_name[48] = { 0 }; LLVMValueRef func; LLVMValueRef local_value; uint32 i, j; @@ -122,7 +124,7 @@ create_basic_func_context(const AOTCompContext *comp_ctx, { LLVMValueRef aot_inst_offset = I32_TWO, aot_inst_addr; - /* Save the pameters for fast access */ + /* Save the parameters for fast access */ func_ctx->exec_env = LLVMGetParam(func_ctx->func, 0); /* Get aot inst address, the layout of exec_env is: @@ -537,8 +539,51 @@ aot_build_precheck_function(AOTCompContext *comp_ctx, LLVMModuleRef module, if (ret_type == VOID_TYPE) { name = ""; } - LLVMValueRef retval = - LLVMBuildCall2(b, func_type, wrapped_func, params, param_count, name); + + LLVMValueRef retval; + if (comp_ctx->is_indirect_mode + && !strncmp(comp_ctx->target_arch, "xtensa", 6)) { + /* call wrapped_func indirectly */ + if (!create_func_ptrs(comp_ctx, func_ctx)) { + goto fail; + } + + LLVMTypeRef func_ptr_type; + LLVMValueRef wrapped_func_indirect; + uint32 import_func_count = comp_ctx->comp_data->import_func_count; + uint32 func_count = comp_ctx->func_ctx_count; + + /* Check function index */ + if (func_index >= import_func_count + func_count) { + aot_set_last_error("Function index out of range."); + goto fail; + } + + /* Get function type */ + if (!(func_ptr_type = LLVMPointerType(func_type, 0))) { + aot_set_last_error("create LLVM function type failed."); + goto fail; + } + + /* + * func_index layout : + * aot_func#xxx, range from 0 ~ func_conut - 1; + * aot_func#internal#xxx, range from func_conut ~ 2 * func_conut - 1; + */ + if (!(wrapped_func_indirect = aot_get_func_from_table( + comp_ctx, func_ctx->func_ptrs, func_ptr_type, + func_index + func_count + import_func_count))) { + goto fail; + } + + /* Call the function indirectly */ + retval = LLVMBuildCall2(b, func_type, wrapped_func_indirect, params, + param_count, name); + } + else + retval = LLVMBuildCall2(b, func_type, wrapped_func, params, param_count, + name); + if (!retval) { goto fail; } @@ -629,7 +674,8 @@ aot_add_llvm_func(AOTCompContext *comp_ctx, LLVMModuleRef module, 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; + for (i = 0; + i < (uint32)(aot_func_type->param_count + aot_func_type->result_count); i++) { if (!check_wasm_type(comp_ctx, aot_func_type->types[i])) return NULL; @@ -686,10 +732,12 @@ 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; + LLVMValueRef precheck_func = NULL; + if (need_precheck) { precheck_func = aot_add_llvm_func1(comp_ctx, module, func_index, aot_func_type->param_count, @@ -732,7 +780,9 @@ aot_add_llvm_func(AOTCompContext *comp_ctx, LLVMModuleRef module, } if (need_precheck) { - if (!comp_ctx->is_jit_mode) + if (!comp_ctx->is_jit_mode + && !(comp_ctx->is_indirect_mode + && !strncmp(comp_ctx->target_arch, "xtensa", 6))) LLVMSetLinkage(func, LLVMInternalLinkage); unsigned int kind = LLVMGetEnumAttributeKindForName("noinline", strlen("noinline")); @@ -955,17 +1005,23 @@ create_aux_stack_info(const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) if (!(aux_stack_bound_addr = LLVMBuildBitCast(comp_ctx->builder, aux_stack_bound_addr, - INT32_PTR_TYPE, "aux_stack_bound_ptr"))) { + INTPTR_T_PTR_TYPE, "aux_stack_bound_ptr"))) { aot_set_last_error("llvm build bit cast failed"); return false; } if (!(func_ctx->aux_stack_bound = - LLVMBuildLoad2(comp_ctx->builder, I32_TYPE, aux_stack_bound_addr, - "aux_stack_bound"))) { + LLVMBuildLoad2(comp_ctx->builder, INTPTR_T_TYPE, + aux_stack_bound_addr, "aux_stack_bound_intptr"))) { aot_set_last_error("llvm build load failed"); return false; } + if (!(func_ctx->aux_stack_bound = + LLVMBuildZExt(comp_ctx->builder, func_ctx->aux_stack_bound, + I64_TYPE, "aux_stack_bound_i64"))) { + aot_set_last_error("llvm build truncOrBitCast failed."); + return false; + } /* Get aux stack bottom address */ if (!(aux_stack_bottom_addr = LLVMBuildInBoundsGEP2( @@ -977,16 +1033,23 @@ create_aux_stack_info(const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) if (!(aux_stack_bottom_addr = LLVMBuildBitCast(comp_ctx->builder, aux_stack_bottom_addr, - INT32_PTR_TYPE, "aux_stack_bottom_ptr"))) { + INTPTR_T_PTR_TYPE, "aux_stack_bottom_ptr"))) { aot_set_last_error("llvm build bit cast failed"); return false; } + if (!(func_ctx->aux_stack_bottom = - LLVMBuildLoad2(comp_ctx->builder, I32_TYPE, aux_stack_bottom_addr, - "aux_stack_bottom"))) { + LLVMBuildLoad2(comp_ctx->builder, INTPTR_T_TYPE, + aux_stack_bottom_addr, "aux_stack_bottom"))) { aot_set_last_error("llvm build load failed"); return false; } + if (!(func_ctx->aux_stack_bottom = + LLVMBuildZExt(comp_ctx->builder, func_ctx->aux_stack_bottom, + I64_TYPE, "aux_stack_bottom_i64"))) { + aot_set_last_error("llvm build truncOrBitCast failed."); + return false; + } return true; } @@ -1316,7 +1379,7 @@ create_memory_info(const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, } if (!(func_ctx->mem_info[0].mem_data_size_addr = LLVMBuildBitCast( comp_ctx->builder, func_ctx->mem_info[0].mem_data_size_addr, - INT32_PTR_TYPE, "mem_data_size_ptr"))) { + INT64_PTR_TYPE, "mem_data_size_ptr"))) { aot_set_last_error("llvm build bit cast failed"); return false; } @@ -1335,7 +1398,7 @@ create_memory_info(const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, return false; } if (!(func_ctx->mem_info[0].mem_data_size_addr = LLVMBuildLoad2( - comp_ctx->builder, I32_TYPE, + comp_ctx->builder, I64_TYPE, func_ctx->mem_info[0].mem_data_size_addr, "mem_data_size"))) { aot_set_last_error("llvm build load failed"); return false; @@ -1916,8 +1979,8 @@ aot_set_llvm_basic_types(AOTLLVMTypes *basic_types, LLVMContextRef context, 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); + basic_types->gc_ref_type = basic_types->int8_ptr_type; + basic_types->gc_ref_ptr_type = basic_types->int8_pptr_type; return (basic_types->int8_ptr_type && basic_types->int8_pptr_type && basic_types->int16_ptr_type && basic_types->int32_ptr_type @@ -2485,6 +2548,9 @@ aot_create_comp_context(const AOTCompData *comp_data, aot_comp_option_t option) aot_set_last_error("create LLVM module failed."); goto fail; } +#if LLVM_VERSION_MAJOR >= 19 + LLVMSetIsNewDbgInfoFormat(comp_ctx->module, true); +#endif #if WASM_ENABLE_LINUX_PERF != 0 if (wasm_runtime_get_linux_perf()) { diff --git a/core/iwasm/compilation/debug/dwarf_extractor.cpp b/core/iwasm/compilation/debug/dwarf_extractor.cpp index d322aefe5..e2e515ba0 100644 --- a/core/iwasm/compilation/debug/dwarf_extractor.cpp +++ b/core/iwasm/compilation/debug/dwarf_extractor.cpp @@ -295,6 +295,28 @@ lldb_function_to_function_dbi(const AOTCompContext *comp_ctx, const size_t num_function_args = function_args.GetSize(); dwarf_extractor *extractor; + /* + * Process only known languages. + * We have a few assumptions which might not be true for non-C functions. + * + * At least it's known broken for C++ and Rust: + * https://github.com/bytecodealliance/wasm-micro-runtime/issues/3187 + * https://github.com/bytecodealliance/wasm-micro-runtime/issues/3163 + */ + LanguageType language_type = function.GetLanguage(); + switch (language_type) { + case eLanguageTypeC89: + case eLanguageTypeC: + case eLanguageTypeC99: + case eLanguageTypeC11: + case eLanguageTypeC17: + break; + default: + LOG_WARNING("func %s has unsuppoted language_type 0x%x", + function_name, (int)language_type); + return NULL; + } + if (!(extractor = TO_EXTACTOR(comp_ctx->comp_data->extractor))) return NULL; @@ -313,6 +335,17 @@ lldb_function_to_function_dbi(const AOTCompContext *comp_ctx, if (function_arg_type.IsValid()) { ParamTypes[function_arg_idx + 1] = lldb_type_to_type_dbi(comp_ctx, function_arg_type); + if (ParamTypes[function_arg_idx + 1] == NULL) { + LOG_WARNING( + "func %s arg %" PRIu32 + " has a type not implemented by lldb_type_to_type_dbi", + function_name, function_arg_idx); + } + } + else { + LOG_WARNING("func %s arg %" PRIu32 ": GetTypeAtIndex failed", + function_name, function_arg_idx); + ParamTypes[function_arg_idx + 1] = NULL; } } @@ -381,15 +414,16 @@ lldb_function_to_function_dbi(const AOTCompContext *comp_ctx, for (uint32_t function_arg_idx = 0; function_arg_idx < variable_list.GetSize(); ++function_arg_idx) { SBValue variable(variable_list.GetValueAtIndex(function_arg_idx)); - if (variable.IsValid()) { + if (variable.IsValid() && ParamTypes[function_arg_idx + 1] != NULL) { SBDeclaration dec(variable.GetDeclaration()); auto valtype = variable.GetType(); LLVMMetadataRef ParamLocation = LLVMDIBuilderCreateDebugLocation( comp_ctx->context, dec.GetLine(), dec.GetColumn(), FunctionMetadata, NULL); + const char *varname = variable.GetName(); LLVMMetadataRef ParamVar = LLVMDIBuilderCreateParameterVariable( - DIB, FunctionMetadata, variable.GetName(), - strlen(variable.GetName()), function_arg_idx + 1 + 1, + DIB, FunctionMetadata, varname, varname ? strlen(varname) : 0, + function_arg_idx + 1 + 1, File, // starts form 1, and 1 is exenv, dec.GetLine(), ParamTypes[function_arg_idx + 1], true, LLVMDIFlagZero); @@ -473,6 +507,8 @@ dwarf_gen_location(const AOTCompContext *comp_ctx, dwarf_extractor *extractor; AOTFunc *func = func_ctx->aot_func; + if (func_ctx->debug_func == NULL) + return NULL; if (!(extractor = TO_EXTACTOR(comp_ctx->comp_data->extractor))) return NULL; diff --git a/core/iwasm/compilation/simd/simd_conversions.c b/core/iwasm/compilation/simd/simd_conversions.c index 8e4c17ed3..042e28089 100644 --- a/core/iwasm/compilation/simd/simd_conversions.c +++ b/core/iwasm/compilation/simd/simd_conversions.c @@ -226,15 +226,6 @@ aot_compile_simd_i16x8_narrow_i32x4(AOTCompContext *comp_ctx, } } -bool -aot_compile_simd_i32x4_narrow_i64x2(AOTCompContext *comp_ctx, - AOTFuncContext *func_ctx, bool is_signed) -{ - /* TODO: x86 intrinsics */ - return simd_integer_narrow_common(comp_ctx, func_ctx, e_sat_i64x2, - is_signed); -} - enum integer_extend_type { e_ext_i8x16, e_ext_i16x8, diff --git a/core/iwasm/compilation/simd/simd_conversions.h b/core/iwasm/compilation/simd/simd_conversions.h index 87b8bd684..e3a1a3521 100644 --- a/core/iwasm/compilation/simd/simd_conversions.h +++ b/core/iwasm/compilation/simd/simd_conversions.h @@ -20,10 +20,6 @@ bool aot_compile_simd_i16x8_narrow_i32x4(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, bool is_signed); -bool -aot_compile_simd_i32x4_narrow_i64x2(AOTCompContext *comp_ctx, - AOTFuncContext *func_ctx, bool is_signed); - bool aot_compile_simd_i16x8_extend_i8x16(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, bool is_low, diff --git a/core/iwasm/compilation/simd/simd_floating_point.c b/core/iwasm/compilation/simd/simd_floating_point.c index 7fcc1ab65..536ef5b28 100644 --- a/core/iwasm/compilation/simd/simd_floating_point.c +++ b/core/iwasm/compilation/simd/simd_floating_point.c @@ -129,20 +129,6 @@ aot_compile_simd_f64x2_abs(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) "llvm.fabs.v2f64"); } -bool -aot_compile_simd_f32x4_round(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) -{ - return simd_float_intrinsic(comp_ctx, func_ctx, V128_f32x4_TYPE, - "llvm.round.v4f32"); -} - -bool -aot_compile_simd_f64x2_round(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) -{ - return simd_float_intrinsic(comp_ctx, func_ctx, V128_f64x2_TYPE, - "llvm.round.v2f64"); -} - bool aot_compile_simd_f32x4_sqrt(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) { diff --git a/core/iwasm/compilation/simd/simd_floating_point.h b/core/iwasm/compilation/simd/simd_floating_point.h index 213b4391f..39e37c872 100644 --- a/core/iwasm/compilation/simd/simd_floating_point.h +++ b/core/iwasm/compilation/simd/simd_floating_point.h @@ -32,14 +32,6 @@ aot_compile_simd_f32x4_abs(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx); bool aot_compile_simd_f64x2_abs(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx); -bool -aot_compile_simd_f32x4_round(AOTCompContext *comp_ctx, - AOTFuncContext *func_ctx); - -bool -aot_compile_simd_f64x2_round(AOTCompContext *comp_ctx, - AOTFuncContext *func_ctx); - bool aot_compile_simd_f32x4_sqrt(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx); diff --git a/core/iwasm/compilation/simd/simd_int_arith.c b/core/iwasm/compilation/simd/simd_int_arith.c index 1d0e6967b..6a1902d1f 100644 --- a/core/iwasm/compilation/simd/simd_int_arith.c +++ b/core/iwasm/compilation/simd/simd_int_arith.c @@ -243,7 +243,6 @@ aot_compile_simd_i64x2_abs(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) enum integer_avgr_u { e_avgr_u_i8x16, e_avgr_u_i16x8, - e_avgr_u_i32x4, }; /* TODO: try int_x86_mmx_pavg_b and int_x86_mmx_pavg_w */ @@ -257,9 +256,8 @@ simd_v128_avg(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, LLVMTypeRef vector_type[] = { V128_i8x16_TYPE, V128_i16x8_TYPE, - V128_i32x4_TYPE, }; - unsigned lanes[] = { 16, 8, 4 }; + unsigned lanes[] = { 16, 8 }; if (!(rhs = simd_pop_v128_and_bitcast(comp_ctx, func_ctx, vector_type[itype], "rhs")) @@ -325,13 +323,6 @@ aot_compile_simd_i16x8_avgr_u(AOTCompContext *comp_ctx, return simd_v128_avg(comp_ctx, func_ctx, e_avgr_u_i16x8); } -bool -aot_compile_simd_i32x4_avgr_u(AOTCompContext *comp_ctx, - AOTFuncContext *func_ctx) -{ - return simd_v128_avg(comp_ctx, func_ctx, e_avgr_u_i32x4); -} - bool aot_compile_simd_i32x4_dot_i16x8(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) diff --git a/core/iwasm/compilation/simd/simd_int_arith.h b/core/iwasm/compilation/simd/simd_int_arith.h index a7a21170a..49827d51d 100644 --- a/core/iwasm/compilation/simd/simd_int_arith.h +++ b/core/iwasm/compilation/simd/simd_int_arith.h @@ -76,10 +76,6 @@ bool aot_compile_simd_i16x8_avgr_u(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx); -bool -aot_compile_simd_i32x4_avgr_u(AOTCompContext *comp_ctx, - AOTFuncContext *func_ctx); - bool aot_compile_simd_i32x4_dot_i16x8(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx); diff --git a/core/iwasm/compilation/simd/simd_sat_int_arith.c b/core/iwasm/compilation/simd/simd_sat_int_arith.c index 1de4520a7..ea250b7e0 100644 --- a/core/iwasm/compilation/simd/simd_sat_int_arith.c +++ b/core/iwasm/compilation/simd/simd_sat_int_arith.c @@ -64,18 +64,3 @@ aot_compile_simd_i16x8_saturate(AOTCompContext *comp_ctx, is_signed ? intrinsics[arith_op][0] : intrinsics[arith_op][1]); } - -bool -aot_compile_simd_i32x4_saturate(AOTCompContext *comp_ctx, - AOTFuncContext *func_ctx, - V128Arithmetic arith_op, bool is_signed) -{ - char *intrinsics[][2] = { - { "llvm.sadd.sat.v4i32", "llvm.uadd.sat.v4i32" }, - { "llvm.ssub.sat.v4i32", "llvm.usub.sat.v4i32" }, - }; - - return simd_sat_int_arith(comp_ctx, func_ctx, V128_i16x8_TYPE, - is_signed ? intrinsics[arith_op][0] - : intrinsics[arith_op][1]); -} diff --git a/core/iwasm/compilation/simd/simd_sat_int_arith.h b/core/iwasm/compilation/simd/simd_sat_int_arith.h index e30acaaf4..67c602fc5 100644 --- a/core/iwasm/compilation/simd/simd_sat_int_arith.h +++ b/core/iwasm/compilation/simd/simd_sat_int_arith.h @@ -22,10 +22,6 @@ aot_compile_simd_i16x8_saturate(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, V128Arithmetic arith_op, bool is_signed); -bool -aot_compile_simd_i32x4_saturate(AOTCompContext *comp_ctx, - AOTFuncContext *func_ctx, - V128Arithmetic arith_op, bool is_signed); #ifdef __cplusplus } /* end of extern "C" */ #endif 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 f5605b6f2..79c72503e 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 @@ -7511,7 +7511,7 @@ at_rmw_xor_r_base_r_offset_r(x86::Assembler &a, uint32 bytes_dst, CHECK_KIND(r3, JIT_REG_KIND_I64); \ } \ /* r0: read/return value r2: memory base addr can't be const */ \ - /* already check it's not const in LOAD_4ARGS(); */ \ + /* already check it's not const in LOAD_4ARGS() */ \ reg_no_dst = jit_reg_no(r0); \ CHECK_REG_NO(reg_no_dst, jit_reg_kind(r0)); \ /* mem_data base address has to be non-const */ \ @@ -9293,8 +9293,8 @@ jit_codegen_init() imm.setValue(INT32_MAX); a.jne(imm); - char *stream = (char *)a.code()->sectionById(0)->buffer().data() - + a.code()->sectionById(0)->buffer().size(); + char *stream_old = (char *)a.code()->sectionById(0)->buffer().data() + + a.code()->sectionById(0)->buffer().size(); /* If yes, call jit_set_exception_with_id to throw exception, and then set eax to JIT_INTERP_ACTION_THROWN, and jump to @@ -9319,7 +9319,7 @@ jit_codegen_init() /* Patch the offset of jne instruction */ char *stream_new = (char *)a.code()->sectionById(0)->buffer().data() + a.code()->sectionById(0)->buffer().size(); - *(int32 *)(stream - 4) = (int32)(stream_new - stream); + *(int32 *)(stream_old - 4) = (int32)(stream_new - stream_old); } /* Load compiled func ptr and call it */ @@ -9419,7 +9419,7 @@ static uint8 hreg_info_F64[3][16] = { 1, 1, 1, 1, 1, 1, 1, 0 }, /* caller_saved_jitted */ }; -static const JitHardRegInfo hreg_info = { +static const JitHardRegInfo g_hreg_info = { { { 0, NULL, NULL, NULL }, /* VOID */ @@ -9459,7 +9459,7 @@ static const JitHardRegInfo hreg_info = { const JitHardRegInfo * jit_codegen_get_hreg_info() { - return &hreg_info; + return &g_hreg_info; } static const char *reg_names_i32[] = { diff --git a/core/iwasm/fast-jit/fe/jit_emit_control.c b/core/iwasm/fast-jit/fe/jit_emit_control.c index 94c27f10b..9274e7217 100644 --- a/core/iwasm/fast-jit/fe/jit_emit_control.c +++ b/core/iwasm/fast-jit/fe/jit_emit_control.c @@ -1102,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 d1c71c309..1e4199440 100644 --- a/core/iwasm/fast-jit/fe/jit_emit_function.c +++ b/core/iwasm/fast-jit/fe/jit_emit_function.c @@ -331,12 +331,14 @@ jit_compile_op_call(JitCompContext *cc, uint32 func_idx, bool tail_call) func_params[1] = NEW_CONST(I32, false); /* is_str = false */ func_params[2] = argvs[i]; if (signature[i + 2] == '~') { + /* TODO: Memory64 no need to convert if mem idx type i64 */ + func_params[3] = jit_cc_new_reg_I64(cc); /* pointer with length followed */ - func_params[3] = argvs[i + 1]; + GEN_INSN(I32TOI64, func_params[3], argvs[i + 1]); } else { /* pointer with length followed */ - func_params[3] = NEW_CONST(I32, 1); + func_params[3] = NEW_CONST(I64, 1); } } else if (signature[i + 1] == '$') { @@ -344,10 +346,15 @@ jit_compile_op_call(JitCompContext *cc, uint32 func_idx, bool tail_call) is_pointer_arg = true; func_params[1] = NEW_CONST(I32, true); /* is_str = true */ func_params[2] = argvs[i]; - func_params[3] = NEW_CONST(I32, 1); + func_params[3] = NEW_CONST(I64, 1); } if (is_pointer_arg) { + JitReg native_addr_64 = jit_cc_new_reg_I64(cc); + /* TODO: Memory64 no need to convert if mem idx type i64 */ + GEN_INSN(I32TOI64, native_addr_64, func_params[2]); + func_params[2] = native_addr_64; + if (!jit_emit_callnative(cc, jit_check_app_addr_and_convert, ret, func_params, 5)) { goto fail; diff --git a/core/iwasm/fast-jit/fe/jit_emit_memory.c b/core/iwasm/fast-jit/fe/jit_emit_memory.c index 420b4dd8e..ea245ba34 100644 --- a/core/iwasm/fast-jit/fe/jit_emit_memory.c +++ b/core/iwasm/fast-jit/fe/jit_emit_memory.c @@ -630,13 +630,13 @@ wasm_init_memory(WASMModuleInstance *inst, uint32 mem_idx, uint32 seg_idx, { WASMMemoryInstance *mem_inst; WASMDataSeg *data_segment; - uint32 mem_size; + uint64 mem_size; uint8 *mem_addr, *data_addr; uint32 seg_len; /* if d + n > the length of mem.data */ mem_inst = inst->memories[mem_idx]; - mem_size = mem_inst->cur_page_count * mem_inst->num_bytes_per_page; + mem_size = mem_inst->cur_page_count * (uint64)mem_inst->num_bytes_per_page; if (mem_size < mem_offset || mem_size - mem_offset < len) goto out_of_bounds; @@ -655,7 +655,7 @@ wasm_init_memory(WASMModuleInstance *inst, uint32 mem_idx, uint32 seg_idx, goto out_of_bounds; mem_addr = mem_inst->memory_data + mem_offset; - bh_memcpy_s(mem_addr, mem_size - mem_offset, data_addr, len); + bh_memcpy_s(mem_addr, (uint32)(mem_size - mem_offset), data_addr, len); return 0; out_of_bounds: @@ -719,13 +719,15 @@ wasm_copy_memory(WASMModuleInstance *inst, uint32 src_mem_idx, uint32 dst_offset) { WASMMemoryInstance *src_mem, *dst_mem; - uint32 src_mem_size, dst_mem_size; + uint64 src_mem_size, dst_mem_size; uint8 *src_addr, *dst_addr; src_mem = inst->memories[src_mem_idx]; dst_mem = inst->memories[dst_mem_idx]; - src_mem_size = src_mem->cur_page_count * src_mem->num_bytes_per_page; - dst_mem_size = dst_mem->cur_page_count * dst_mem->num_bytes_per_page; + src_mem_size = + src_mem->cur_page_count * (uint64)src_mem->num_bytes_per_page; + dst_mem_size = + dst_mem->cur_page_count * (uint64)dst_mem->num_bytes_per_page; /* if s + n > the length of mem.data */ if (src_mem_size < src_offset || src_mem_size - src_offset < len) @@ -738,7 +740,7 @@ wasm_copy_memory(WASMModuleInstance *inst, uint32 src_mem_idx, src_addr = src_mem->memory_data + src_offset; dst_addr = dst_mem->memory_data + dst_offset; /* allowing the destination and source to overlap */ - bh_memmove_s(dst_addr, dst_mem_size - dst_offset, src_addr, len); + bh_memmove_s(dst_addr, (uint32)(dst_mem_size - dst_offset), src_addr, len); return 0; out_of_bounds: @@ -784,11 +786,11 @@ wasm_fill_memory(WASMModuleInstance *inst, uint32 mem_idx, uint32 len, uint32 val, uint32 dst) { WASMMemoryInstance *mem_inst; - uint32 mem_size; + uint64 mem_size; uint8 *dst_addr; mem_inst = inst->memories[mem_idx]; - mem_size = mem_inst->cur_page_count * mem_inst->num_bytes_per_page; + mem_size = mem_inst->cur_page_count * (uint64)mem_inst->num_bytes_per_page; if (mem_size < dst || mem_size - dst < len) goto out_of_bounds; diff --git a/core/iwasm/fast-jit/jit_frontend.c b/core/iwasm/fast-jit/jit_frontend.c index f770b274c..b8d40f97f 100644 --- a/core/iwasm/fast-jit/jit_frontend.c +++ b/core/iwasm/fast-jit/jit_frontend.c @@ -194,12 +194,15 @@ JitReg get_aux_stack_bound_reg(JitFrame *frame) { JitCompContext *cc = frame->cc; + JitReg tmp = jit_cc_new_reg_I32(cc); if (!frame->aux_stack_bound_reg) { frame->aux_stack_bound_reg = cc->aux_stack_bound_reg; - GEN_INSN( - LDI32, frame->aux_stack_bound_reg, cc->exec_env_reg, - NEW_CONST(I32, offsetof(WASMExecEnv, aux_stack_boundary.boundary))); + GEN_INSN(LDPTR, frame->aux_stack_bound_reg, cc->exec_env_reg, + NEW_CONST(I32, offsetof(WASMExecEnv, aux_stack_boundary))); + /* TODO: Memory64 whether to convert depends on memory idx type */ + GEN_INSN(I64TOI32, tmp, frame->aux_stack_bound_reg); + frame->aux_stack_bound_reg = tmp; } return frame->aux_stack_bound_reg; } @@ -208,12 +211,15 @@ JitReg get_aux_stack_bottom_reg(JitFrame *frame) { JitCompContext *cc = frame->cc; + JitReg tmp = jit_cc_new_reg_I32(cc); if (!frame->aux_stack_bottom_reg) { frame->aux_stack_bottom_reg = cc->aux_stack_bottom_reg; - GEN_INSN( - LDI32, frame->aux_stack_bottom_reg, cc->exec_env_reg, - NEW_CONST(I32, offsetof(WASMExecEnv, aux_stack_bottom.bottom))); + GEN_INSN(LDPTR, frame->aux_stack_bottom_reg, cc->exec_env_reg, + NEW_CONST(I32, offsetof(WASMExecEnv, aux_stack_bottom))); + /* TODO: Memory64 whether to convert depends on memory idx type */ + GEN_INSN(I64TOI32, tmp, frame->aux_stack_bottom_reg); + frame->aux_stack_bottom_reg = tmp; } return frame->aux_stack_bottom_reg; } @@ -915,8 +921,8 @@ create_fixed_virtual_regs(JitCompContext *cc) cc->import_func_ptrs_reg = jit_cc_new_reg_ptr(cc); cc->fast_jit_func_ptrs_reg = jit_cc_new_reg_ptr(cc); cc->func_type_indexes_reg = jit_cc_new_reg_ptr(cc); - cc->aux_stack_bound_reg = jit_cc_new_reg_I32(cc); - cc->aux_stack_bottom_reg = jit_cc_new_reg_I32(cc); + cc->aux_stack_bound_reg = jit_cc_new_reg_ptr(cc); + cc->aux_stack_bottom_reg = jit_cc_new_reg_ptr(cc); count = module->import_memory_count + module->memory_count; if (count > 0) { diff --git a/core/iwasm/include/aot_export.h b/core/iwasm/include/aot_export.h index c1a03d86c..d06fef1dd 100644 --- a/core/iwasm/include/aot_export.h +++ b/core/iwasm/include/aot_export.h @@ -3,6 +3,12 @@ * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ +/** + * @file aot_export.h + * + * @brief This file defines the exported AOT compilation APIs + */ + #ifndef _AOT_EXPORT_H #define _AOT_EXPORT_H diff --git a/core/iwasm/include/gc_export.h b/core/iwasm/include/gc_export.h index 8a1003194..777551edc 100644 --- a/core/iwasm/include/gc_export.h +++ b/core/iwasm/include/gc_export.h @@ -3,6 +3,12 @@ * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ +/** + * @file gc_export.h + * + * @brief This file defines the exported GC APIs + */ + #ifndef _GC_EXPORT_H #define _GC_EXPORT_H @@ -437,6 +443,16 @@ 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); +/** + * Get the field count of the a struct object. + * + * @param obj the WASM struct object + * + * @return the field count of the a struct object + */ +WASM_RUNTIME_API_EXTERN uint32_t +wasm_struct_obj_get_field_count(const wasm_struct_obj_t obj); + /** * Create an array object with the index of defined type, the obj's length is * length, init value is init_value diff --git a/core/iwasm/include/lib_export.h b/core/iwasm/include/lib_export.h index e4829e4fe..0ca668f52 100644 --- a/core/iwasm/include/lib_export.h +++ b/core/iwasm/include/lib_export.h @@ -3,6 +3,11 @@ * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ +/** + * @file lib_export.h + * + */ + #ifndef _LIB_EXPORT_H_ #define _LIB_EXPORT_H_ diff --git a/core/iwasm/include/wasm_c_api.h b/core/iwasm/include/wasm_c_api.h index 304b3a4ee..63d18f3ae 100644 --- a/core/iwasm/include/wasm_c_api.h +++ b/core/iwasm/include/wasm_c_api.h @@ -1,5 +1,11 @@ // WebAssembly C API +/** + * @file wasm_c_api.h + * + * @brief This file defines the WebAssembly C APIs + */ + #ifndef _WASM_C_API_H_ #define _WASM_C_API_H_ @@ -186,6 +192,16 @@ struct wasm_config_t { /*TODO: wasi args*/ }; +#ifndef INSTANTIATION_ARGS_OPTION_DEFINED +#define INSTANTIATION_ARGS_OPTION_DEFINED +/* WASM module instantiation arguments */ +typedef struct InstantiationArgs { + uint32_t default_stack_size; + uint32_t host_managed_heap_size; + uint32_t max_memory_pages; +} InstantiationArgs; +#endif /* INSTANTIATION_ARGS_OPTION_DEFINED */ + /* * by default: * - mem_alloc_type is Alloc_With_System_Allocator @@ -507,10 +523,21 @@ struct WASMModuleCommon; typedef struct WASMModuleCommon *wasm_module_t; #endif +#ifndef LOAD_ARGS_OPTION_DEFINED +#define LOAD_ARGS_OPTION_DEFINED +typedef struct LoadArgs { + char *name; + /* TODO: more fields? */ +} LoadArgs; +#endif /* LOAD_ARGS_OPTION_DEFINED */ WASM_API_EXTERN own wasm_module_t* wasm_module_new( wasm_store_t*, const wasm_byte_vec_t* binary); +// please refer to wasm_runtime_load_ex(...) in core/iwasm/include/wasm_export.h +WASM_API_EXTERN own wasm_module_t* wasm_module_new_ex( + wasm_store_t*, const wasm_byte_vec_t* binary, const LoadArgs *args); + WASM_API_EXTERN void wasm_module_delete(own wasm_module_t*); WASM_API_EXTERN bool wasm_module_validate(wasm_store_t*, const wasm_byte_vec_t* binary); @@ -526,6 +553,9 @@ WASM_API_EXTERN own wasm_shared_module_t* wasm_module_share(wasm_module_t*); WASM_API_EXTERN own wasm_module_t* wasm_module_obtain(wasm_store_t*, wasm_shared_module_t*); WASM_API_EXTERN void wasm_shared_module_delete(own wasm_shared_module_t*); +WASM_API_EXTERN bool wasm_module_set_name(wasm_module_t*, const char* name); +WASM_API_EXTERN const char *wasm_module_get_name(wasm_module_t*); + // Function Instances @@ -644,6 +674,12 @@ WASM_API_EXTERN own wasm_instance_t* wasm_instance_new_with_args( own wasm_trap_t** trap, const uint32_t stack_size, const uint32_t heap_size ); +// please refer to wasm_runtime_instantiate_ex(...) in core/iwasm/include/wasm_export.h +WASM_API_EXTERN own wasm_instance_t* wasm_instance_new_with_args_ex( + wasm_store_t*, const wasm_module_t*, const wasm_extern_vec_t *imports, + own wasm_trap_t** trap, const InstantiationArgs *inst_args +); + WASM_API_EXTERN void wasm_instance_exports(const wasm_instance_t*, own wasm_extern_vec_t* out); diff --git a/core/iwasm/include/wasm_export.h b/core/iwasm/include/wasm_export.h index 32114c490..bc43ea0b9 100644 --- a/core/iwasm/include/wasm_export.h +++ b/core/iwasm/include/wasm_export.h @@ -3,6 +3,12 @@ * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ +/** + * @file wasm_export.h + * + * @brief This file defines the exported common runtime APIs + */ + #ifndef _WASM_EXPORT_H #define _WASM_EXPORT_H @@ -183,6 +189,24 @@ typedef struct RuntimeInitArgs { bool enable_linux_perf; } RuntimeInitArgs; +#ifndef LOAD_ARGS_OPTION_DEFINED +#define LOAD_ARGS_OPTION_DEFINED +typedef struct LoadArgs { + char *name; + /* TODO: more fields? */ +} LoadArgs; +#endif /* LOAD_ARGS_OPTION_DEFINED */ + +#ifndef INSTANTIATION_ARGS_OPTION_DEFINED +#define INSTANTIATION_ARGS_OPTION_DEFINED +/* WASM module instantiation arguments */ +typedef struct InstantiationArgs { + uint32_t default_stack_size; + uint32_t host_managed_heap_size; + uint32_t max_memory_pages; +} InstantiationArgs; +#endif /* INSTANTIATION_ARGS_OPTION_DEFINED */ + #ifndef WASM_VALKIND_T_DEFINED #define WASM_VALKIND_T_DEFINED typedef uint8_t wasm_valkind_t; @@ -409,6 +433,13 @@ WASM_RUNTIME_API_EXTERN wasm_module_t wasm_runtime_load(uint8_t *buf, uint32_t size, char *error_buf, uint32_t error_buf_size); +/** + * Load a WASM module with specified load argument. + */ +WASM_RUNTIME_API_EXTERN wasm_module_t +wasm_runtime_load_ex(uint8_t *buf, uint32_t size, const LoadArgs *args, + char *error_buf, uint32_t error_buf_size); + /** * Load a WASM module from a specified WASM or AOT section list. * @@ -527,6 +558,16 @@ wasm_runtime_instantiate(const wasm_module_t module, uint32_t default_stack_size, uint32_t host_managed_heap_size, char *error_buf, uint32_t error_buf_size); +/** + * Instantiate a WASM module, with specified instantiation arguments + * + * Same as wasm_runtime_instantiate, but it also allows overwriting maximum memory + */ +WASM_RUNTIME_API_EXTERN wasm_module_inst_t +wasm_runtime_instantiate_ex(const wasm_module_t module, + const InstantiationArgs *args, + char *error_buf, uint32_t error_buf_size); + /** * Set the running mode of a WASM module instance, override the * default running mode of the runtime. Note that it only makes sense when @@ -596,13 +637,12 @@ wasm_runtime_get_wasi_exit_code(wasm_module_inst_t module_inst); * * @param module_inst the module instance * @param name the name of the function - * @param signature the signature of the function, ignored currently * * @return the function instance found, NULL if not found */ WASM_RUNTIME_API_EXTERN wasm_function_inst_t wasm_runtime_lookup_function(wasm_module_inst_t const module_inst, - const char *name, const char *signature); + const char *name); /** * Get parameter count of the function instance @@ -1011,8 +1051,8 @@ wasm_runtime_is_bounds_checks_enabled( * it is not an absolute address. * Return non-zero if success, zero if failed. */ -WASM_RUNTIME_API_EXTERN uint32_t -wasm_runtime_module_malloc(wasm_module_inst_t module_inst, uint32_t size, +WASM_RUNTIME_API_EXTERN uint64_t +wasm_runtime_module_malloc(wasm_module_inst_t module_inst, uint64_t size, void **p_native_addr); /** @@ -1022,7 +1062,7 @@ wasm_runtime_module_malloc(wasm_module_inst_t module_inst, uint32_t size, * @param ptr the pointer to free */ WASM_RUNTIME_API_EXTERN void -wasm_runtime_module_free(wasm_module_inst_t module_inst, uint32_t ptr); +wasm_runtime_module_free(wasm_module_inst_t module_inst, uint64_t ptr); /** * Allocate memory from the heap of WASM module instance and initialize @@ -1037,9 +1077,9 @@ wasm_runtime_module_free(wasm_module_inst_t module_inst, uint32_t ptr); * it is not an absolute address. * Return non-zero if success, zero if failed. */ -WASM_RUNTIME_API_EXTERN uint32_t +WASM_RUNTIME_API_EXTERN uint64_t wasm_runtime_module_dup_data(wasm_module_inst_t module_inst, - const char *src, uint32_t size); + const char *src, uint64_t size); /** * Validate the app address, check whether it belongs to WASM module @@ -1054,7 +1094,7 @@ wasm_runtime_module_dup_data(wasm_module_inst_t module_inst, */ WASM_RUNTIME_API_EXTERN bool wasm_runtime_validate_app_addr(wasm_module_inst_t module_inst, - uint32_t app_offset, uint32_t size); + uint64_t app_offset, uint64_t size); /** * Similar to wasm_runtime_validate_app_addr(), except that the size parameter @@ -1076,7 +1116,7 @@ wasm_runtime_validate_app_addr(wasm_module_inst_t module_inst, */ WASM_RUNTIME_API_EXTERN bool wasm_runtime_validate_app_str_addr(wasm_module_inst_t module_inst, - uint32_t app_str_offset); + uint64_t app_str_offset); /** * Validate the native address, check whether it belongs to WASM module @@ -1092,7 +1132,7 @@ wasm_runtime_validate_app_str_addr(wasm_module_inst_t module_inst, */ WASM_RUNTIME_API_EXTERN bool wasm_runtime_validate_native_addr(wasm_module_inst_t module_inst, - void *native_ptr, uint32_t size); + void *native_ptr, uint64_t size); /** * Convert app address(relative address) to native address(absolute address) @@ -1108,7 +1148,7 @@ wasm_runtime_validate_native_addr(wasm_module_inst_t module_inst, */ WASM_RUNTIME_API_EXTERN void * wasm_runtime_addr_app_to_native(wasm_module_inst_t module_inst, - uint32_t app_offset); + uint64_t app_offset); /** * Convert native address(absolute address) to app address(relative address) @@ -1118,7 +1158,7 @@ wasm_runtime_addr_app_to_native(wasm_module_inst_t module_inst, * * @return the app address converted */ -WASM_RUNTIME_API_EXTERN uint32_t +WASM_RUNTIME_API_EXTERN uint64_t wasm_runtime_addr_native_to_app(wasm_module_inst_t module_inst, void *native_ptr); @@ -1134,9 +1174,9 @@ wasm_runtime_addr_native_to_app(wasm_module_inst_t module_inst, */ WASM_RUNTIME_API_EXTERN bool wasm_runtime_get_app_addr_range(wasm_module_inst_t module_inst, - uint32_t app_offset, - uint32_t *p_app_start_offset, - uint32_t *p_app_end_offset); + uint64_t app_offset, + uint64_t *p_app_start_offset, + uint64_t *p_app_end_offset); /** * Get the native address range (absolute address) that a native address @@ -1650,6 +1690,15 @@ wasm_runtime_begin_blocking_op(wasm_exec_env_t exec_env); WASM_RUNTIME_API_EXTERN void wasm_runtime_end_blocking_op(wasm_exec_env_t exec_env); + +WASM_RUNTIME_API_EXTERN bool +wasm_runtime_set_module_name(wasm_module_t module, const char *name, + char *error_buf, uint32_t error_buf_size); + +/* return the most recently set module name or "" if never set before */ +WASM_RUNTIME_API_EXTERN const char* +wasm_runtime_get_module_name(wasm_module_t module); + /* clang-format on */ #ifdef __cplusplus diff --git a/core/iwasm/interpreter/wasm.h b/core/iwasm/interpreter/wasm.h index d62351a27..80ce67b8e 100644 --- a/core/iwasm/interpreter/wasm.h +++ b/core/iwasm/interpreter/wasm.h @@ -90,8 +90,22 @@ extern "C" { */ #define VALUE_TYPE_GC_REF 0x43 +#define MAX_PAGE_COUNT_FLAG 0x01 +#define SHARED_MEMORY_FLAG 0x02 +#define MEMORY64_FLAG 0x04 + #define DEFAULT_NUM_BYTES_PER_PAGE 65536 #define DEFAULT_MAX_PAGES 65536 +#define DEFAULT_MEM64_MAX_PAGES UINT32_MAX + +/* Max size of linear memory */ +#define MAX_LINEAR_MEMORY_SIZE (4 * (uint64)BH_GB) +/* Roughly 274 TB */ +#define MAX_LINEAR_MEM64_MEMORY_SIZE \ + (DEFAULT_MEM64_MAX_PAGES * (uint64)64 * (uint64)BH_KB) +/* Macro to check memory flag and return appropriate memory size */ +#define GET_MAX_LINEAR_MEMORY_SIZE(is_memory64) \ + (is_memory64 ? MAX_LINEAR_MEM64_MEMORY_SIZE : MAX_LINEAR_MEMORY_SIZE) #if WASM_ENABLE_GC == 0 typedef uintptr_t table_elem_type_t; @@ -481,6 +495,12 @@ typedef struct WASMTable { #endif } WASMTable; +#if WASM_ENABLE_MEMORY64 != 0 +typedef uint64 mem_offset_t; +#else +typedef uint32 mem_offset_t; +#endif + typedef struct WASMMemory { uint32 flags; uint32 num_bytes_per_page; @@ -870,19 +890,19 @@ struct WASMModule { -1 means unexported */ uint32 aux_data_end_global_index; /* auxiliary __data_end exported by wasm app */ - uint32 aux_data_end; + uint64 aux_data_end; /* the index of auxiliary __heap_base global, -1 means unexported */ uint32 aux_heap_base_global_index; /* auxiliary __heap_base exported by wasm app */ - uint32 aux_heap_base; + uint64 aux_heap_base; /* the index of auxiliary stack top global, -1 means unexported */ uint32 aux_stack_top_global_index; /* auxiliary stack bottom resolved */ - uint32 aux_stack_bottom; + uint64 aux_stack_bottom; /* auxiliary stack size resolved */ uint32 aux_stack_size; @@ -1045,6 +1065,9 @@ struct WASMModule { bool is_ref_types_used; bool is_bulk_memory_used; #endif + + /* user defined name */ + char *name; }; typedef struct BlockType { @@ -1091,6 +1114,21 @@ align_uint(unsigned v, unsigned b) return (v + m) & ~m; } +/** + * Align an 64 bit unsigned value on a alignment boundary. + * + * @param v the value to be aligned + * @param b the alignment boundary (2, 4, 8, ...) + * + * @return the aligned value + */ +inline static uint64 +align_uint64(uint64 v, uint64 b) +{ + uint64 m = b - 1; + return (v + m) & ~m; +} + /** * Check whether a piece of data is out of range * @@ -1291,8 +1329,8 @@ block_type_get_param_types(BlockType *block_type, uint8 **p_param_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; + *p_param_reftype_map_count = (uint32)(func_type->result_ref_type_maps + - func_type->ref_type_maps); #endif } else { diff --git a/core/iwasm/interpreter/wasm_interp_classic.c b/core/iwasm/interpreter/wasm_interp_classic.c index 4428c9400..3aec3f4c4 100644 --- a/core/iwasm/interpreter/wasm_interp_classic.c +++ b/core/iwasm/interpreter/wasm_interp_classic.c @@ -46,32 +46,33 @@ typedef float64 CellType_F64; #define get_linear_mem_size() GET_LINEAR_MEMORY_SIZE(memory) #endif -#if !defined(OS_ENABLE_HW_BOUND_CHECK) \ - || WASM_CPU_SUPPORTS_UNALIGNED_ADDR_ACCESS == 0 -#define CHECK_MEMORY_OVERFLOW(bytes) \ - do { \ - uint64 offset1 = (uint64)offset + (uint64)addr; \ - if (disable_bounds_checks \ - || offset1 + bytes <= (uint64)get_linear_mem_size()) \ - /* If offset1 is in valid range, maddr must also \ - be in valid range, no need to check it again. */ \ - maddr = memory->memory_data + offset1; \ - else \ - goto out_of_bounds; \ +#if WASM_ENABLE_MEMORY64 == 0 + +#if (!defined(OS_ENABLE_HW_BOUND_CHECK) \ + || WASM_CPU_SUPPORTS_UNALIGNED_ADDR_ACCESS == 0) +#define CHECK_MEMORY_OVERFLOW(bytes) \ + do { \ + uint64 offset1 = (uint64)offset + (uint64)addr; \ + if (disable_bounds_checks || offset1 + bytes <= get_linear_mem_size()) \ + /* If offset1 is in valid range, maddr must also \ + be in valid range, no need to check it again. */ \ + maddr = memory->memory_data + offset1; \ + else \ + goto out_of_bounds; \ } while (0) -#define CHECK_BULK_MEMORY_OVERFLOW(start, bytes, maddr) \ - do { \ - uint64 offset1 = (uint32)(start); \ - if (disable_bounds_checks \ - || offset1 + bytes <= (uint64)get_linear_mem_size()) \ - /* App heap space is not valid space for \ - bulk memory operation */ \ - maddr = memory->memory_data + offset1; \ - else \ - goto out_of_bounds; \ +#define CHECK_BULK_MEMORY_OVERFLOW(start, bytes, maddr) \ + do { \ + uint64 offset1 = (uint32)(start); \ + if (disable_bounds_checks || offset1 + bytes <= get_linear_mem_size()) \ + /* App heap space is not valid space for \ + bulk memory operation */ \ + maddr = memory->memory_data + offset1; \ + else \ + goto out_of_bounds; \ } while (0) -#else +#else /* else of !defined(OS_ENABLE_HW_BOUND_CHECK) || \ + WASM_CPU_SUPPORTS_UNALIGNED_ADDR_ACCESS == 0 */ #define CHECK_MEMORY_OVERFLOW(bytes) \ do { \ uint64 offset1 = (uint64)offset + (uint64)addr; \ @@ -82,8 +83,37 @@ typedef float64 CellType_F64; do { \ maddr = memory->memory_data + (uint32)(start); \ } while (0) -#endif /* !defined(OS_ENABLE_HW_BOUND_CHECK) \ - || WASM_CPU_SUPPORTS_UNALIGNED_ADDR_ACCESS == 0 */ +#endif /* end of !defined(OS_ENABLE_HW_BOUND_CHECK) || \ + WASM_CPU_SUPPORTS_UNALIGNED_ADDR_ACCESS == 0 */ + +#else /* else of WASM_ENABLE_MEMORY64 == 0 */ + +#define CHECK_MEMORY_OVERFLOW(bytes) \ + do { \ + uint64 offset1 = (uint64)offset + (uint64)addr; \ + /* If memory64 is enabled, offset1, offset1 + bytes can overflow */ \ + if (disable_bounds_checks \ + || (offset1 >= offset && offset1 + bytes >= offset1 \ + && offset1 + bytes <= get_linear_mem_size())) \ + maddr = memory->memory_data + offset1; \ + else \ + goto out_of_bounds; \ + } while (0) +#define CHECK_BULK_MEMORY_OVERFLOW(start, bytes, maddr) \ + do { \ + uint64 offset1 = (uint64)(start); \ + /* If memory64 is enabled, offset1 + bytes can overflow */ \ + if (disable_bounds_checks \ + || (offset1 + bytes >= offset1 \ + && offset1 + bytes <= get_linear_mem_size())) \ + /* App heap space is not valid space for \ + bulk memory operation */ \ + maddr = memory->memory_data + offset1; \ + else \ + goto out_of_bounds; \ + } while (0) + +#endif /* end of WASM_ENABLE_MEMORY64 == 0 */ #define CHECK_ATOMIC_MEMORY_ACCESS() \ do { \ @@ -474,6 +504,23 @@ wasm_interp_get_frame_ref(WASMInterpFrame *frame) #define SET_LABEL_TYPE(_label_type) (void)0 #endif +#if WASM_ENABLE_MEMORY64 != 0 +#define PUSH_MEM_OFFSET(value) \ + do { \ + if (is_memory64) { \ + PUT_I64_TO_ADDR(frame_sp, value); \ + frame_sp += 2; \ + } \ + else { \ + *(int32 *)frame_sp++ = (int32)(value); \ + } \ + } while (0) +#else +#define PUSH_MEM_OFFSET(value) PUSH_I32(value) +#endif + +#define PUSH_PAGE_COUNT(value) PUSH_MEM_OFFSET(value) + #define PUSH_CSP(_label_type, param_cell_num, cell_num, _target_addr) \ do { \ bh_assert(frame_csp < frame->csp_boundary); \ @@ -503,6 +550,14 @@ wasm_interp_get_frame_ref(WASMInterpFrame *frame) GET_REF_FROM_ADDR(frame_sp)) #endif +#if WASM_ENABLE_MEMORY64 != 0 +#define POP_MEM_OFFSET() (is_memory64 ? POP_I64() : POP_I32()) +#else +#define POP_MEM_OFFSET() POP_I32() +#endif + +#define POP_PAGE_COUNT() POP_MEM_OFFSET() + #define POP_CSP_CHECK_OVERFLOW(n) \ do { \ bh_assert(frame_csp - n >= frame->csp_bottom); \ @@ -569,51 +624,73 @@ wasm_interp_get_frame_ref(WASMInterpFrame *frame) frame_csp = frame->csp; \ } while (0) -#define read_leb_int64(p, p_end, res) \ - do { \ - uint8 _val = *p; \ - if (!(_val & 0x80)) { \ - res = (int64)_val; \ - if (_val & 0x40) \ - /* sign extend */ \ - res |= 0xFFFFFFFFFFFFFF80LL; \ - p++; \ - break; \ - } \ - uint32 _off = 0; \ - res = (int64)read_leb(p, &_off, 64, true); \ - p += _off; \ +#define read_leb_int64(p, p_end, res) \ + do { \ + uint8 _val = *p; \ + if (!(_val & 0x80)) { \ + res = (int64)_val; \ + if (_val & 0x40) \ + /* sign extend */ \ + res |= 0xFFFFFFFFFFFFFF80LL; \ + p++; \ + } \ + else { \ + uint32 _off = 0; \ + res = (int64)read_leb(p, &_off, 64, true); \ + p += _off; \ + } \ } while (0) -#define read_leb_uint32(p, p_end, res) \ - do { \ - uint8 _val = *p; \ - if (!(_val & 0x80)) { \ - res = _val; \ - p++; \ - break; \ - } \ - uint32 _off = 0; \ - res = (uint32)read_leb(p, &_off, 32, false); \ - p += _off; \ +#define read_leb_uint32(p, p_end, res) \ + do { \ + uint8 _val = *p; \ + if (!(_val & 0x80)) { \ + res = _val; \ + p++; \ + } \ + else { \ + uint32 _off = 0; \ + res = (uint32)read_leb(p, &_off, 32, false); \ + p += _off; \ + } \ } while (0) -#define read_leb_int32(p, p_end, res) \ - do { \ - uint8 _val = *p; \ - if (!(_val & 0x80)) { \ - res = (int32)_val; \ - if (_val & 0x40) \ - /* sign extend */ \ - res |= 0xFFFFFF80; \ - p++; \ - break; \ - } \ - uint32 _off = 0; \ - res = (int32)read_leb(p, &_off, 32, true); \ - p += _off; \ +#define read_leb_int32(p, p_end, res) \ + do { \ + uint8 _val = *p; \ + if (!(_val & 0x80)) { \ + res = (int32)_val; \ + if (_val & 0x40) \ + /* sign extend */ \ + res |= 0xFFFFFF80; \ + p++; \ + } \ + else { \ + uint32 _off = 0; \ + res = (int32)read_leb(p, &_off, 32, true); \ + p += _off; \ + } \ } while (0) +#if WASM_ENABLE_MEMORY64 != 0 +#define read_leb_mem_offset(p, p_end, res) \ + do { \ + uint8 _val = *p; \ + if (!(_val & 0x80)) { \ + res = (mem_offset_t)_val; \ + p++; \ + } \ + else { \ + uint32 _off = 0; \ + res = (mem_offset_t)read_leb(p, &_off, is_memory64 ? 64 : 32, \ + false); \ + p += _off; \ + } \ + } while (0) +#else +#define read_leb_mem_offset(p, p_end, res) read_leb_uint32(p, p_end, res) +#endif + #if WASM_ENABLE_LABELS_AS_VALUES == 0 #define RECOVER_FRAME_IP_END() frame_ip_end = wasm_get_func_code_end(cur_func) #else @@ -874,7 +951,7 @@ trunc_f64_to_int(WASMModuleInstance *module, uint32 *frame_sp, float64 src_min, uint32 readv, sval; \ \ sval = POP_I32(); \ - addr = POP_I32(); \ + addr = POP_MEM_OFFSET(); \ \ if (opcode == WASM_OP_ATOMIC_RMW_I32_##OP_NAME##8_U) { \ CHECK_MEMORY_OVERFLOW(1); \ @@ -914,7 +991,7 @@ trunc_f64_to_int(WASMModuleInstance *module, uint32 *frame_sp, float64 src_min, uint64 readv, sval; \ \ sval = (uint64)POP_I64(); \ - addr = POP_I32(); \ + addr = POP_MEM_OFFSET(); \ \ if (opcode == WASM_OP_ATOMIC_RMW_I64_##OP_NAME##8_U) { \ CHECK_MEMORY_OVERFLOW(1); \ @@ -1108,9 +1185,8 @@ wasm_interp_call_func_native(WASMModuleInstance *module_inst, if (!func_import->call_conv_wasm_c_api) { native_func_pointer = module_inst->import_func_ptrs[cur_func_index]; } - else if (module_inst->e->common.c_api_func_imports) { - c_api_func_import = - module_inst->e->common.c_api_func_imports + cur_func_index; + else if (module_inst->c_api_func_imports) { + c_api_func_import = module_inst->c_api_func_imports + cur_func_index; native_func_pointer = c_api_func_import->func_ptr_linked; } @@ -1211,8 +1287,8 @@ wasm_interp_call_func_import(WASMModuleInstance *module_inst, uint8 *ip = prev_frame->ip; char buf[128]; WASMExecEnv *sub_module_exec_env = NULL; - uint32 aux_stack_origin_boundary = 0; - uint32 aux_stack_origin_bottom = 0; + uintptr_t aux_stack_origin_boundary = 0; + uintptr_t aux_stack_origin_bottom = 0; if (!sub_func_inst) { snprintf(buf, sizeof(buf), @@ -1235,13 +1311,11 @@ wasm_interp_call_func_import(WASMModuleInstance *module_inst, wasm_exec_env_set_module_inst(exec_env, (WASMModuleInstanceCommon *)sub_module_inst); /* - aux_stack_boundary */ - aux_stack_origin_boundary = exec_env->aux_stack_boundary.boundary; - exec_env->aux_stack_boundary.boundary = - sub_module_exec_env->aux_stack_boundary.boundary; + aux_stack_origin_boundary = exec_env->aux_stack_boundary; + exec_env->aux_stack_boundary = sub_module_exec_env->aux_stack_boundary; /* - aux_stack_bottom */ - aux_stack_origin_bottom = exec_env->aux_stack_bottom.bottom; - exec_env->aux_stack_bottom.bottom = - sub_module_exec_env->aux_stack_bottom.bottom; + aux_stack_origin_bottom = exec_env->aux_stack_bottom; + exec_env->aux_stack_bottom = sub_module_exec_env->aux_stack_bottom; /* set ip NULL to make call_func_bytecode return after executing this function */ @@ -1253,8 +1327,8 @@ wasm_interp_call_func_import(WASMModuleInstance *module_inst, /* restore ip and other replaced */ prev_frame->ip = ip; - exec_env->aux_stack_boundary.boundary = aux_stack_origin_boundary; - exec_env->aux_stack_bottom.bottom = aux_stack_origin_bottom; + exec_env->aux_stack_boundary = aux_stack_origin_boundary; + exec_env->aux_stack_bottom = aux_stack_origin_bottom; wasm_exec_env_restore_module_inst(exec_env, (WASMModuleInstanceCommon *)module_inst); } @@ -1374,7 +1448,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, #if !defined(OS_ENABLE_HW_BOUND_CHECK) \ || WASM_CPU_SUPPORTS_UNALIGNED_ADDR_ACCESS == 0 \ || WASM_ENABLE_BULK_MEMORY != 0 - uint32 linear_mem_size = 0; + uint64 linear_mem_size = 0; if (memory) #if WASM_ENABLE_THREAD_MGR == 0 linear_mem_size = memory->memory_data_size; @@ -1435,6 +1509,16 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, WASMStringviewIterObjectRef stringview_iter_obj; #endif #endif +#if WASM_ENABLE_TAIL_CALL != 0 || WASM_ENABLE_GC != 0 + bool is_return_call = false; +#endif +#if WASM_ENABLE_MEMORY64 != 0 + /* TODO: multi-memories for now assuming the memory idx type is consistent + * across multi-memories */ + bool is_memory64 = false; + if (memory) + is_memory64 = memory->is_memory64; +#endif #if WASM_ENABLE_DEBUG_INTERP != 0 uint8 *frame_ip_orig = NULL; @@ -2437,11 +2521,12 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_REF_AS_NON_NULL) { - gc_obj = GET_REF_FROM_ADDR(frame_sp - REF_CELL_NUM); + 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(); } @@ -4085,28 +4170,46 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_SET_GLOBAL_AUX_STACK) { - uint32 aux_stack_top; + uint64 aux_stack_top; read_leb_uint32(frame_ip, frame_ip_end, global_idx); bh_assert(global_idx < module->e->global_count); global = globals + global_idx; global_addr = get_global_addr(global_data, global); - aux_stack_top = *(uint32 *)(frame_sp - 1); - if (aux_stack_top <= exec_env->aux_stack_boundary.boundary) { +#if WASM_ENABLE_MEMORY64 != 0 + if (is_memory64) { + aux_stack_top = *(uint64 *)(frame_sp - 2); + } + else +#endif + { + aux_stack_top = (uint64)(*(uint32 *)(frame_sp - 1)); + } + if (aux_stack_top <= (uint64)exec_env->aux_stack_boundary) { wasm_set_exception(module, "wasm auxiliary stack overflow"); goto got_exception; } - if (aux_stack_top > exec_env->aux_stack_bottom.bottom) { + if (aux_stack_top > (uint64)exec_env->aux_stack_bottom) { wasm_set_exception(module, "wasm auxiliary stack underflow"); goto got_exception; } - *(int32 *)global_addr = aux_stack_top; - frame_sp--; +#if WASM_ENABLE_MEMORY64 != 0 + if (is_memory64) { + *(uint64 *)global_addr = aux_stack_top; + frame_sp -= 2; + } + else +#endif + { + *(uint32 *)global_addr = aux_stack_top; + frame_sp--; + } #if WASM_ENABLE_MEMORY_PROFILING != 0 if (module->module->aux_stack_top_global_index != (uint32)-1) { - uint32 aux_stack_used = module->module->aux_stack_bottom - - *(uint32 *)global_addr; + uint32 aux_stack_used = + (uint32)(module->module->aux_stack_bottom + - *(uint32 *)global_addr); if (aux_stack_used > module->e->max_aux_stack_used) module->e->max_aux_stack_used = aux_stack_used; } @@ -4128,11 +4231,12 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_I32_LOAD) HANDLE_OP(WASM_OP_F32_LOAD) { - uint32 offset, flags, addr; + uint32 flags; + mem_offset_t offset, addr; read_leb_uint32(frame_ip, frame_ip_end, flags); - read_leb_uint32(frame_ip, frame_ip_end, offset); - addr = POP_I32(); + read_leb_mem_offset(frame_ip, frame_ip_end, offset); + addr = POP_MEM_OFFSET(); CHECK_MEMORY_OVERFLOW(4); PUSH_I32(LOAD_I32(maddr)); CHECK_READ_WATCHPOINT(addr, offset); @@ -4143,11 +4247,12 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_I64_LOAD) HANDLE_OP(WASM_OP_F64_LOAD) { - uint32 offset, flags, addr; + uint32 flags; + mem_offset_t offset, addr; read_leb_uint32(frame_ip, frame_ip_end, flags); - read_leb_uint32(frame_ip, frame_ip_end, offset); - addr = POP_I32(); + read_leb_mem_offset(frame_ip, frame_ip_end, offset); + addr = POP_MEM_OFFSET(); CHECK_MEMORY_OVERFLOW(8); PUSH_I64(LOAD_I64(maddr)); CHECK_READ_WATCHPOINT(addr, offset); @@ -4157,11 +4262,12 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_I32_LOAD8_S) { - uint32 offset, flags, addr; + uint32 flags; + mem_offset_t offset, addr; read_leb_uint32(frame_ip, frame_ip_end, flags); - read_leb_uint32(frame_ip, frame_ip_end, offset); - addr = POP_I32(); + read_leb_mem_offset(frame_ip, frame_ip_end, offset); + addr = POP_MEM_OFFSET(); CHECK_MEMORY_OVERFLOW(1); PUSH_I32(sign_ext_8_32(*(int8 *)maddr)); CHECK_READ_WATCHPOINT(addr, offset); @@ -4171,11 +4277,12 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_I32_LOAD8_U) { - uint32 offset, flags, addr; + uint32 flags; + mem_offset_t offset, addr; read_leb_uint32(frame_ip, frame_ip_end, flags); - read_leb_uint32(frame_ip, frame_ip_end, offset); - addr = POP_I32(); + read_leb_mem_offset(frame_ip, frame_ip_end, offset); + addr = POP_MEM_OFFSET(); CHECK_MEMORY_OVERFLOW(1); PUSH_I32((uint32)(*(uint8 *)maddr)); CHECK_READ_WATCHPOINT(addr, offset); @@ -4185,11 +4292,12 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_I32_LOAD16_S) { - uint32 offset, flags, addr; + uint32 flags; + mem_offset_t offset, addr; read_leb_uint32(frame_ip, frame_ip_end, flags); - read_leb_uint32(frame_ip, frame_ip_end, offset); - addr = POP_I32(); + read_leb_mem_offset(frame_ip, frame_ip_end, offset); + addr = POP_MEM_OFFSET(); CHECK_MEMORY_OVERFLOW(2); PUSH_I32(sign_ext_16_32(LOAD_I16(maddr))); CHECK_READ_WATCHPOINT(addr, offset); @@ -4199,11 +4307,12 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_I32_LOAD16_U) { - uint32 offset, flags, addr; + uint32 flags; + mem_offset_t offset, addr; read_leb_uint32(frame_ip, frame_ip_end, flags); - read_leb_uint32(frame_ip, frame_ip_end, offset); - addr = POP_I32(); + read_leb_mem_offset(frame_ip, frame_ip_end, offset); + addr = POP_MEM_OFFSET(); CHECK_MEMORY_OVERFLOW(2); PUSH_I32((uint32)(LOAD_U16(maddr))); CHECK_READ_WATCHPOINT(addr, offset); @@ -4213,11 +4322,12 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_I64_LOAD8_S) { - uint32 offset, flags, addr; + uint32 flags; + mem_offset_t offset, addr; read_leb_uint32(frame_ip, frame_ip_end, flags); - read_leb_uint32(frame_ip, frame_ip_end, offset); - addr = POP_I32(); + read_leb_mem_offset(frame_ip, frame_ip_end, offset); + addr = POP_MEM_OFFSET(); CHECK_MEMORY_OVERFLOW(1); PUSH_I64(sign_ext_8_64(*(int8 *)maddr)); CHECK_READ_WATCHPOINT(addr, offset); @@ -4227,11 +4337,12 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_I64_LOAD8_U) { - uint32 offset, flags, addr; + uint32 flags; + mem_offset_t offset, addr; read_leb_uint32(frame_ip, frame_ip_end, flags); - read_leb_uint32(frame_ip, frame_ip_end, offset); - addr = POP_I32(); + read_leb_mem_offset(frame_ip, frame_ip_end, offset); + addr = POP_MEM_OFFSET(); CHECK_MEMORY_OVERFLOW(1); PUSH_I64((uint64)(*(uint8 *)maddr)); CHECK_READ_WATCHPOINT(addr, offset); @@ -4241,11 +4352,12 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_I64_LOAD16_S) { - uint32 offset, flags, addr; + uint32 flags; + mem_offset_t offset, addr; read_leb_uint32(frame_ip, frame_ip_end, flags); - read_leb_uint32(frame_ip, frame_ip_end, offset); - addr = POP_I32(); + read_leb_mem_offset(frame_ip, frame_ip_end, offset); + addr = POP_MEM_OFFSET(); CHECK_MEMORY_OVERFLOW(2); PUSH_I64(sign_ext_16_64(LOAD_I16(maddr))); CHECK_READ_WATCHPOINT(addr, offset); @@ -4255,11 +4367,12 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_I64_LOAD16_U) { - uint32 offset, flags, addr; + uint32 flags; + mem_offset_t offset, addr; read_leb_uint32(frame_ip, frame_ip_end, flags); - read_leb_uint32(frame_ip, frame_ip_end, offset); - addr = POP_I32(); + read_leb_mem_offset(frame_ip, frame_ip_end, offset); + addr = POP_MEM_OFFSET(); CHECK_MEMORY_OVERFLOW(2); PUSH_I64((uint64)(LOAD_U16(maddr))); CHECK_READ_WATCHPOINT(addr, offset); @@ -4269,12 +4382,13 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_I64_LOAD32_S) { - uint32 offset, flags, addr; + uint32 flags; + mem_offset_t offset, addr; opcode = *(frame_ip - 1); read_leb_uint32(frame_ip, frame_ip_end, flags); - read_leb_uint32(frame_ip, frame_ip_end, offset); - addr = POP_I32(); + read_leb_mem_offset(frame_ip, frame_ip_end, offset); + addr = POP_MEM_OFFSET(); CHECK_MEMORY_OVERFLOW(4); PUSH_I64(sign_ext_32_64(LOAD_I32(maddr))); CHECK_READ_WATCHPOINT(addr, offset); @@ -4284,11 +4398,12 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_I64_LOAD32_U) { - uint32 offset, flags, addr; + uint32 flags; + mem_offset_t offset, addr; read_leb_uint32(frame_ip, frame_ip_end, flags); - read_leb_uint32(frame_ip, frame_ip_end, offset); - addr = POP_I32(); + read_leb_mem_offset(frame_ip, frame_ip_end, offset); + addr = POP_MEM_OFFSET(); CHECK_MEMORY_OVERFLOW(4); PUSH_I64((uint64)(LOAD_U32(maddr))); CHECK_READ_WATCHPOINT(addr, offset); @@ -4300,14 +4415,23 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_I32_STORE) HANDLE_OP(WASM_OP_F32_STORE) { - uint32 offset, flags, addr; + uint32 flags; + mem_offset_t offset, addr; read_leb_uint32(frame_ip, frame_ip_end, flags); - read_leb_uint32(frame_ip, frame_ip_end, offset); + read_leb_mem_offset(frame_ip, frame_ip_end, offset); frame_sp--; - addr = POP_I32(); + addr = POP_MEM_OFFSET(); CHECK_MEMORY_OVERFLOW(4); - STORE_U32(maddr, frame_sp[1]); +#if WASM_ENABLE_MEMORY64 != 0 + if (is_memory64) { + STORE_U32(maddr, frame_sp[2]); + } + else +#endif + { + STORE_U32(maddr, frame_sp[1]); + } CHECK_WRITE_WATCHPOINT(addr, offset); (void)flags; HANDLE_OP_END(); @@ -4316,15 +4440,26 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_I64_STORE) HANDLE_OP(WASM_OP_F64_STORE) { - uint32 offset, flags, addr; + uint32 flags; + mem_offset_t offset, addr; read_leb_uint32(frame_ip, frame_ip_end, flags); - read_leb_uint32(frame_ip, frame_ip_end, offset); + read_leb_mem_offset(frame_ip, frame_ip_end, offset); frame_sp -= 2; - addr = POP_I32(); + addr = POP_MEM_OFFSET(); CHECK_MEMORY_OVERFLOW(8); - PUT_I64_TO_ADDR((uint32 *)maddr, - GET_I64_FROM_ADDR(frame_sp + 1)); + +#if WASM_ENABLE_MEMORY64 != 0 + if (is_memory64) { + PUT_I64_TO_ADDR((mem_offset_t *)maddr, + GET_I64_FROM_ADDR(frame_sp + 2)); + } + else +#endif + { + PUT_I64_TO_ADDR((uint32 *)maddr, + GET_I64_FROM_ADDR(frame_sp + 1)); + } CHECK_WRITE_WATCHPOINT(addr, offset); (void)flags; HANDLE_OP_END(); @@ -4333,14 +4468,15 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_I32_STORE8) HANDLE_OP(WASM_OP_I32_STORE16) { - uint32 offset, flags, addr; + uint32 flags; + mem_offset_t offset, addr; uint32 sval; opcode = *(frame_ip - 1); read_leb_uint32(frame_ip, frame_ip_end, flags); - read_leb_uint32(frame_ip, frame_ip_end, offset); + read_leb_mem_offset(frame_ip, frame_ip_end, offset); sval = (uint32)POP_I32(); - addr = POP_I32(); + addr = POP_MEM_OFFSET(); if (opcode == WASM_OP_I32_STORE8) { CHECK_MEMORY_OVERFLOW(1); @@ -4359,14 +4495,15 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_I64_STORE16) HANDLE_OP(WASM_OP_I64_STORE32) { - uint32 offset, flags, addr; + uint32 flags; + mem_offset_t offset, addr; uint64 sval; opcode = *(frame_ip - 1); read_leb_uint32(frame_ip, frame_ip_end, flags); - read_leb_uint32(frame_ip, frame_ip_end, offset); + read_leb_mem_offset(frame_ip, frame_ip_end, offset); sval = (uint64)POP_I64(); - addr = POP_I32(); + addr = POP_MEM_OFFSET(); if (opcode == WASM_OP_I64_STORE8) { CHECK_MEMORY_OVERFLOW(1); @@ -4390,7 +4527,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, { uint32 reserved; read_leb_uint32(frame_ip, frame_ip_end, reserved); - PUSH_I32(memory->cur_page_count); + PUSH_PAGE_COUNT(memory->cur_page_count); (void)reserved; HANDLE_OP_END(); } @@ -4401,15 +4538,15 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, prev_page_count = memory->cur_page_count; read_leb_uint32(frame_ip, frame_ip_end, reserved); - delta = (uint32)POP_I32(); + delta = (uint32)POP_PAGE_COUNT(); if (!wasm_enlarge_memory(module, delta)) { /* failed to memory.grow, return -1 */ - PUSH_I32(-1); + PUSH_PAGE_COUNT(-1); } else { /* success, return previous page count */ - PUSH_I32(prev_page_count); + PUSH_PAGE_COUNT(prev_page_count); /* update memory size, no need to update memory ptr as it isn't changed in wasm_enlarge_memory */ #if !defined(OS_ENABLE_HW_BOUND_CHECK) \ @@ -5409,7 +5546,8 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, #if WASM_ENABLE_BULK_MEMORY != 0 case WASM_OP_MEMORY_INIT: { - uint32 addr, segment; + uint32 segment; + mem_offset_t addr; uint64 bytes, offset, seg_len; uint8 *data; @@ -5419,7 +5557,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, bytes = (uint64)(uint32)POP_I32(); offset = (uint64)(uint32)POP_I32(); - addr = (uint32)POP_I32(); + addr = (mem_offset_t)POP_MEM_OFFSET(); #if WASM_ENABLE_THREAD_MGR != 0 linear_mem_size = get_linear_mem_size(); @@ -5428,8 +5566,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, #ifndef OS_ENABLE_HW_BOUND_CHECK CHECK_BULK_MEMORY_OVERFLOW(addr, bytes, maddr); #else - if ((uint64)(uint32)addr + bytes - > (uint64)linear_mem_size) + if ((uint64)(uint32)addr + bytes > linear_mem_size) goto out_of_bounds; maddr = memory->memory_data + (uint32)addr; #endif @@ -5448,7 +5585,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, if (offset + bytes > seg_len) goto out_of_bounds; - bh_memcpy_s(maddr, linear_mem_size - addr, + bh_memcpy_s(maddr, (uint32)(linear_mem_size - addr), data + offset, (uint32)bytes); break; } @@ -5463,14 +5600,13 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, } case WASM_OP_MEMORY_COPY: { - uint32 dst, src, len; + mem_offset_t dst, src, len; uint8 *mdst, *msrc; frame_ip += 2; - - len = POP_I32(); - src = POP_I32(); - dst = POP_I32(); + len = POP_MEM_OFFSET(); + src = POP_MEM_OFFSET(); + dst = POP_MEM_OFFSET(); #if WASM_ENABLE_THREAD_MGR != 0 linear_mem_size = get_linear_mem_size(); @@ -5480,28 +5616,29 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, CHECK_BULK_MEMORY_OVERFLOW(src, len, msrc); CHECK_BULK_MEMORY_OVERFLOW(dst, len, mdst); #else - if ((uint64)(uint32)src + len > (uint64)linear_mem_size) + if ((uint64)(uint32)src + len > linear_mem_size) goto out_of_bounds; msrc = memory->memory_data + (uint32)src; - if ((uint64)(uint32)dst + len > (uint64)linear_mem_size) + if ((uint64)(uint32)dst + len > linear_mem_size) goto out_of_bounds; mdst = memory->memory_data + (uint32)dst; #endif /* allowing the destination and source to overlap */ - bh_memmove_s(mdst, linear_mem_size - dst, msrc, len); + bh_memmove_s(mdst, (uint32)(linear_mem_size - dst), + msrc, len); break; } case WASM_OP_MEMORY_FILL: { - uint32 dst, len; + mem_offset_t dst, len; uint8 fill_val, *mdst; frame_ip++; - len = POP_I32(); + len = POP_MEM_OFFSET(); fill_val = POP_I32(); - dst = POP_I32(); + dst = POP_MEM_OFFSET(); #if WASM_ENABLE_THREAD_MGR != 0 linear_mem_size = get_linear_mem_size(); @@ -5510,7 +5647,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, #ifndef OS_ENABLE_HW_BOUND_CHECK CHECK_BULK_MEMORY_OVERFLOW(dst, len, mdst); #else - if ((uint64)(uint32)dst + len > (uint64)linear_mem_size) + if ((uint64)(uint32)dst + len > linear_mem_size) goto out_of_bounds; mdst = memory->memory_data + (uint32)dst; #endif @@ -5731,7 +5868,8 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, #if WASM_ENABLE_SHARED_MEMORY != 0 HANDLE_OP(WASM_OP_ATOMIC_PREFIX) { - uint32 offset = 0, align = 0, addr; + mem_offset_t offset = 0, addr; + uint32 align = 0; uint32 opcode1; read_leb_uint32(frame_ip, frame_ip_end, opcode1); @@ -5741,7 +5879,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, if (opcode != WASM_OP_ATOMIC_FENCE) { read_leb_uint32(frame_ip, frame_ip_end, align); - read_leb_uint32(frame_ip, frame_ip_end, offset); + read_leb_mem_offset(frame_ip, frame_ip_end, offset); } switch (opcode) { @@ -5750,7 +5888,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, uint32 notify_count, ret; notify_count = POP_I32(); - addr = POP_I32(); + addr = POP_MEM_OFFSET(); CHECK_MEMORY_OVERFLOW(4); CHECK_ATOMIC_MEMORY_ACCESS(); @@ -5770,7 +5908,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, timeout = POP_I64(); expect = POP_I32(); - addr = POP_I32(); + addr = POP_MEM_OFFSET(); CHECK_MEMORY_OVERFLOW(4); CHECK_ATOMIC_MEMORY_ACCESS(); @@ -5794,7 +5932,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, timeout = POP_I64(); expect = POP_I64(); - addr = POP_I32(); + addr = POP_MEM_OFFSET(); CHECK_MEMORY_OVERFLOW(8); CHECK_ATOMIC_MEMORY_ACCESS(); @@ -5825,7 +5963,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, { uint32 readv; - addr = POP_I32(); + addr = POP_MEM_OFFSET(); if (opcode == WASM_OP_ATOMIC_I32_LOAD8_U) { CHECK_MEMORY_OVERFLOW(1); @@ -5860,7 +5998,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, { uint64 readv; - addr = POP_I32(); + addr = POP_MEM_OFFSET(); if (opcode == WASM_OP_ATOMIC_I64_LOAD8_U) { CHECK_MEMORY_OVERFLOW(1); @@ -5902,7 +6040,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, uint32 sval; sval = (uint32)POP_I32(); - addr = POP_I32(); + addr = POP_MEM_OFFSET(); if (opcode == WASM_OP_ATOMIC_I32_STORE8) { CHECK_MEMORY_OVERFLOW(1); @@ -5936,7 +6074,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, uint64 sval; sval = (uint64)POP_I64(); - addr = POP_I32(); + addr = POP_MEM_OFFSET(); if (opcode == WASM_OP_ATOMIC_I64_STORE8) { CHECK_MEMORY_OVERFLOW(1); @@ -5963,7 +6101,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, CHECK_MEMORY_OVERFLOW(8); CHECK_ATOMIC_MEMORY_ACCESS(); shared_memory_lock(memory); - PUT_I64_TO_ADDR((uint32 *)maddr, sval); + STORE_I64(maddr, sval); shared_memory_unlock(memory); } break; @@ -5977,7 +6115,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, sval = POP_I32(); expect = POP_I32(); - addr = POP_I32(); + addr = POP_MEM_OFFSET(); if (opcode == WASM_OP_ATOMIC_RMW_I32_CMPXCHG8_U) { CHECK_MEMORY_OVERFLOW(1); @@ -6023,7 +6161,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, sval = (uint64)POP_I64(); expect = (uint64)POP_I64(); - addr = POP_I32(); + addr = POP_MEM_OFFSET(); if (opcode == WASM_OP_ATOMIC_RMW_I64_CMPXCHG8_U) { CHECK_MEMORY_OVERFLOW(1); @@ -6092,6 +6230,9 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, frame_ip = frame->ip; frame_sp = frame->sp; frame_csp = frame->csp; +#if WASM_ENABLE_TAIL_CALL != 0 || WASM_ENABLE_GC != 0 + is_return_call = false; +#endif goto call_func_from_entry; } @@ -6185,6 +6326,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, } FREE_FRAME(exec_env, frame); wasm_exec_env_set_cur_frame(exec_env, prev_frame); + is_return_call = true; goto call_func_from_entry; } #endif @@ -6198,6 +6340,9 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, } SYNC_ALL_TO_FRAME(); prev_frame = frame; +#if WASM_ENABLE_TAIL_CALL != 0 || WASM_ENABLE_GC != 0 + is_return_call = false; +#endif } call_func_from_entry: @@ -6207,15 +6352,27 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, if (cur_func->import_func_inst) { wasm_interp_call_func_import(module, exec_env, cur_func, prev_frame); +#if WASM_ENABLE_TAIL_CALL != 0 || WASM_ENABLE_GC != 0 + if (is_return_call) { + /* the frame was freed before tail calling and + the prev_frame was set as exec_env's cur_frame, + so here we recover context from prev_frame */ + RECOVER_CONTEXT(prev_frame); + } + else +#endif + { + prev_frame = frame->prev_frame; + cur_func = frame->function; + UPDATE_ALL_FROM_FRAME(); + } + #if WASM_ENABLE_EXCE_HANDLING != 0 char uncaught_exception[128] = { 0 }; bool has_exception = wasm_copy_exception(module, uncaught_exception); if (has_exception && strstr(uncaught_exception, "uncaught wasm exception")) { - /* fix framesp */ - UPDATE_ALL_FROM_FRAME(); - uint32 import_exception; /* initialize imported exception index to be invalid */ SET_INVALID_TAGINDEX(import_exception); @@ -6257,12 +6414,22 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, { wasm_interp_call_func_native(module, exec_env, cur_func, prev_frame); +#if WASM_ENABLE_TAIL_CALL != 0 || WASM_ENABLE_GC != 0 + if (is_return_call) { + /* the frame was freed before tail calling and + the prev_frame was set as exec_env's cur_frame, + so here we recover context from prev_frame */ + RECOVER_CONTEXT(prev_frame); + } + else +#endif + { + prev_frame = frame->prev_frame; + cur_func = frame->function; + UPDATE_ALL_FROM_FRAME(); + } } - prev_frame = frame->prev_frame; - cur_func = frame->function; - UPDATE_ALL_FROM_FRAME(); - /* update memory size, no need to update memory ptr as it isn't changed in wasm_enlarge_memory */ #if !defined(OS_ENABLE_HW_BOUND_CHECK) \ diff --git a/core/iwasm/interpreter/wasm_interp_fast.c b/core/iwasm/interpreter/wasm_interp_fast.c index ca040d02c..c7cb70260 100644 --- a/core/iwasm/interpreter/wasm_interp_fast.c +++ b/core/iwasm/interpreter/wasm_interp_fast.c @@ -39,16 +39,15 @@ typedef float64 CellType_F64; #if !defined(OS_ENABLE_HW_BOUND_CHECK) \ || WASM_CPU_SUPPORTS_UNALIGNED_ADDR_ACCESS == 0 -#define CHECK_MEMORY_OVERFLOW(bytes) \ - do { \ - uint64 offset1 = (uint64)offset + (uint64)addr; \ - if (disable_bounds_checks \ - || offset1 + bytes <= (uint64)get_linear_mem_size()) \ - /* If offset1 is in valid range, maddr must also \ - be in valid range, no need to check it again. */ \ - maddr = memory->memory_data + offset1; \ - else \ - goto out_of_bounds; \ +#define CHECK_MEMORY_OVERFLOW(bytes) \ + do { \ + uint64 offset1 = (uint64)offset + (uint64)addr; \ + if (disable_bounds_checks || offset1 + bytes <= get_linear_mem_size()) \ + /* If offset1 is in valid range, maddr must also \ + be in valid range, no need to check it again. */ \ + maddr = memory->memory_data + offset1; \ + else \ + goto out_of_bounds; \ } while (0) #define CHECK_BULK_MEMORY_OVERFLOW(start, bytes, maddr) \ @@ -1188,9 +1187,8 @@ wasm_interp_call_func_native(WASMModuleInstance *module_inst, if (!func_import->call_conv_wasm_c_api) { native_func_pointer = module_inst->import_func_ptrs[cur_func_index]; } - else if (module_inst->e->common.c_api_func_imports) { - c_api_func_import = - module_inst->e->common.c_api_func_imports + cur_func_index; + else if (module_inst->c_api_func_imports) { + c_api_func_import = module_inst->c_api_func_imports + cur_func_index; native_func_pointer = c_api_func_import->func_ptr_linked; } @@ -1274,8 +1272,8 @@ wasm_interp_call_func_import(WASMModuleInstance *module_inst, uint8 *ip = prev_frame->ip; char buf[128]; WASMExecEnv *sub_module_exec_env = NULL; - uint32 aux_stack_origin_boundary = 0; - uint32 aux_stack_origin_bottom = 0; + uintptr_t aux_stack_origin_boundary = 0; + uintptr_t aux_stack_origin_bottom = 0; if (!sub_func_inst) { snprintf(buf, sizeof(buf), @@ -1298,13 +1296,11 @@ wasm_interp_call_func_import(WASMModuleInstance *module_inst, wasm_exec_env_set_module_inst(exec_env, (WASMModuleInstanceCommon *)sub_module_inst); /* - aux_stack_boundary */ - aux_stack_origin_boundary = exec_env->aux_stack_boundary.boundary; - exec_env->aux_stack_boundary.boundary = - sub_module_exec_env->aux_stack_boundary.boundary; + aux_stack_origin_boundary = exec_env->aux_stack_boundary; + exec_env->aux_stack_boundary = sub_module_exec_env->aux_stack_boundary; /* - aux_stack_bottom */ - aux_stack_origin_bottom = exec_env->aux_stack_bottom.bottom; - exec_env->aux_stack_bottom.bottom = - sub_module_exec_env->aux_stack_bottom.bottom; + aux_stack_origin_bottom = exec_env->aux_stack_bottom; + exec_env->aux_stack_bottom = sub_module_exec_env->aux_stack_bottom; /* set ip NULL to make call_func_bytecode return after executing this function */ @@ -1316,8 +1312,8 @@ wasm_interp_call_func_import(WASMModuleInstance *module_inst, /* restore ip and other replaced */ prev_frame->ip = ip; - exec_env->aux_stack_boundary.boundary = aux_stack_origin_boundary; - exec_env->aux_stack_bottom.bottom = aux_stack_origin_bottom; + exec_env->aux_stack_boundary = aux_stack_origin_boundary; + exec_env->aux_stack_bottom = aux_stack_origin_bottom; wasm_exec_env_restore_module_inst(exec_env, (WASMModuleInstanceCommon *)module_inst); } @@ -1444,7 +1440,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, #if !defined(OS_ENABLE_HW_BOUND_CHECK) \ || WASM_CPU_SUPPORTS_UNALIGNED_ADDR_ACCESS == 0 \ || WASM_ENABLE_BULK_MEMORY != 0 - uint32 linear_mem_size = 0; + uint64 linear_mem_size = 0; if (memory) #if WASM_ENABLE_THREAD_MGR == 0 linear_mem_size = memory->memory_data_size; @@ -1505,6 +1501,9 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, WASMStringviewIterObjectRef stringview_iter_obj; #endif #endif +#if WASM_ENABLE_TAIL_CALL != 0 || WASM_ENABLE_GC != 0 + bool is_return_call = false; +#endif #if WASM_ENABLE_LABELS_AS_VALUES != 0 #define HANDLE_OPCODE(op) &&HANDLE_##op @@ -1697,7 +1696,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, /* clang-format off */ #if WASM_ENABLE_GC == 0 - fidx = tbl_inst->elems[val]; + fidx = (uint32)tbl_inst->elems[val]; if (fidx == (uint32)-1) { wasm_set_exception(module, "uninitialized element"); goto got_exception; @@ -1967,12 +1966,12 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, } HANDLE_OP(WASM_OP_REF_AS_NON_NULL) { - opnd_off = GET_OFFSET(); - gc_obj = GET_REF_FROM_ADDR(frame_lp + opnd_off); + 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) @@ -3527,27 +3526,29 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, HANDLE_OP(WASM_OP_SET_GLOBAL_AUX_STACK) { - uint32 aux_stack_top; + uint64 aux_stack_top; global_idx = read_uint32(frame_ip); bh_assert(global_idx < module->e->global_count); global = globals + global_idx; global_addr = get_global_addr(global_data, global); - aux_stack_top = frame_lp[GET_OFFSET()]; - if (aux_stack_top <= exec_env->aux_stack_boundary.boundary) { + /* TODO: Memory64 the data type depends on mem idx type */ + aux_stack_top = (uint64)frame_lp[GET_OFFSET()]; + if (aux_stack_top <= (uint64)exec_env->aux_stack_boundary) { wasm_set_exception(module, "wasm auxiliary stack overflow"); goto got_exception; } - if (aux_stack_top > exec_env->aux_stack_bottom.bottom) { + if (aux_stack_top > (uint64)exec_env->aux_stack_bottom) { wasm_set_exception(module, "wasm auxiliary stack underflow"); goto got_exception; } - *(int32 *)global_addr = aux_stack_top; + *(int32 *)global_addr = (uint32)aux_stack_top; #if WASM_ENABLE_MEMORY_PROFILING != 0 if (module->module->aux_stack_top_global_index != (uint32)-1) { - uint32 aux_stack_used = module->module->aux_stack_bottom - - *(uint32 *)global_addr; + uint32 aux_stack_used = + (uint32)(module->module->aux_stack_bottom + - *(uint32 *)global_addr); if (aux_stack_used > module->e->max_aux_stack_used) module->e->max_aux_stack_used = aux_stack_used; } @@ -4794,8 +4795,9 @@ 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 */ @@ -4967,8 +4969,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, #ifndef OS_ENABLE_HW_BOUND_CHECK CHECK_BULK_MEMORY_OVERFLOW(addr, bytes, maddr); #else - if ((uint64)(uint32)addr + bytes - > (uint64)linear_mem_size) + if ((uint64)(uint32)addr + bytes > linear_mem_size) goto out_of_bounds; maddr = memory->memory_data + (uint32)addr; #endif @@ -4986,7 +4987,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, if (offset + bytes > seg_len) goto out_of_bounds; - bh_memcpy_s(maddr, linear_mem_size - addr, + bh_memcpy_s(maddr, (uint32)(linear_mem_size - addr), data + offset, (uint32)bytes); break; } @@ -5016,17 +5017,18 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, CHECK_BULK_MEMORY_OVERFLOW(src, len, msrc); CHECK_BULK_MEMORY_OVERFLOW(dst, len, mdst); #else - if ((uint64)(uint32)src + len > (uint64)linear_mem_size) + if ((uint64)(uint32)src + len > linear_mem_size) goto out_of_bounds; msrc = memory->memory_data + (uint32)src; - if ((uint64)(uint32)dst + len > (uint64)linear_mem_size) + if ((uint64)(uint32)dst + len > linear_mem_size) goto out_of_bounds; mdst = memory->memory_data + (uint32)dst; #endif /* allowing the destination and source to overlap */ - bh_memmove_s(mdst, linear_mem_size - dst, msrc, len); + bh_memmove_s(mdst, (uint32)(linear_mem_size - dst), + msrc, len); break; } case WASM_OP_MEMORY_FILL: @@ -5045,7 +5047,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, #ifndef OS_ENABLE_HW_BOUND_CHECK CHECK_BULK_MEMORY_OVERFLOW(dst, len, mdst); #else - if ((uint64)(uint32)dst + len > (uint64)linear_mem_size) + if ((uint64)(uint32)dst + len > linear_mem_size) goto out_of_bounds; mdst = memory->memory_data + (uint32)dst; #endif @@ -5619,6 +5621,9 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, { frame = prev_frame; frame_ip = frame->ip; +#if WASM_ENABLE_TAIL_CALL != 0 || WASM_ENABLE_GC != 0 + is_return_call = false; +#endif goto call_func_from_entry; } @@ -5767,6 +5772,7 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, FREE_FRAME(exec_env, frame); frame_ip += cur_func->param_count * sizeof(int16); wasm_exec_env_set_cur_frame(exec_env, (WASMRuntimeFrame *)prev_frame); + is_return_call = true; goto call_func_from_entry; } #endif /* WASM_ENABLE_TAIL_CALL != 0 || WASM_ENABLE_GC != 0 */ @@ -5839,6 +5845,9 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, } SYNC_ALL_TO_FRAME(); prev_frame = frame; +#if WASM_ENABLE_TAIL_CALL != 0 || WASM_ENABLE_GC != 0 + is_return_call = false; +#endif } call_func_from_entry: @@ -5856,9 +5865,20 @@ wasm_interp_call_func_bytecode(WASMModuleInstance *module, prev_frame); } - prev_frame = frame->prev_frame; - cur_func = frame->function; - UPDATE_ALL_FROM_FRAME(); +#if WASM_ENABLE_TAIL_CALL != 0 || WASM_ENABLE_GC != 0 + if (is_return_call) { + /* the frame was freed before tail calling and + the prev_frame was set as exec_env's cur_frame, + so here we recover context from prev_frame */ + RECOVER_CONTEXT(prev_frame); + } + else +#endif + { + prev_frame = frame->prev_frame; + cur_func = frame->function; + UPDATE_ALL_FROM_FRAME(); + } /* update memory size, no need to update memory ptr as it isn't changed in wasm_enlarge_memory */ diff --git a/core/iwasm/interpreter/wasm_loader.c b/core/iwasm/interpreter/wasm_loader.c index bd5200dac..a7eb6c02d 100644 --- a/core/iwasm/interpreter/wasm_loader.c +++ b/core/iwasm/interpreter/wasm_loader.c @@ -45,6 +45,16 @@ set_error_buf(char *error_buf, uint32 error_buf_size, const char *string) } } +#if WASM_ENABLE_MEMORY64 != 0 +static void +set_error_buf_mem_offset_out_of_range(char *error_buf, uint32 error_buf_size) +{ + if (error_buf != NULL) { + snprintf(error_buf, error_buf_size, "offset out of range"); + } +} +#endif + static void set_error_buf_v(char *error_buf, uint32 error_buf_size, const char *format, ...) { @@ -102,6 +112,7 @@ check_buf1(const uint8 *buf, const uint8 *buf_end, uint32 length, #define skip_leb_int64(p, p_end) skip_leb(p) #define skip_leb_uint32(p, p_end) skip_leb(p) #define skip_leb_int32(p, p_end) skip_leb(p) +#define skip_leb_mem_offset(p, p_end) skip_leb(p) static bool read_leb(uint8 **p_buf, const uint8 *buf_end, uint32 maxbits, bool sign, @@ -139,7 +150,7 @@ read_leb(uint8 **p_buf, const uint8 *buf_end, uint32 maxbits, bool sign, } else if (sign && maxbits == 32) { if (shift < maxbits) { - /* Sign extend, second highest bit is the sign bit */ + /* Sign extend, second-highest bit is the sign bit */ if ((uint8)byte & 0x40) result |= (~((uint64)0)) << shift; } @@ -154,7 +165,7 @@ read_leb(uint8 **p_buf, const uint8 *buf_end, uint32 maxbits, bool sign, } else if (sign && maxbits == 64) { if (shift < maxbits) { - /* Sign extend, second highest bit is the sign bit */ + /* Sign extend, second-highest bit is the sign bit */ if ((uint8)byte & 0x40) result |= (~((uint64)0)) << shift; } @@ -191,6 +202,21 @@ fail: res = (int64)res64; \ } while (0) +#if WASM_ENABLE_MEMORY64 != 0 +#define read_leb_mem_offset(p, p_end, res) \ + do { \ + uint64 res64; \ + if (!read_leb((uint8 **)&p, p_end, is_memory64 ? 64 : 32, false, \ + &res64, error_buf, error_buf_size)) { \ + set_error_buf_mem_offset_out_of_range(error_buf, error_buf_size); \ + goto fail; \ + } \ + res = (mem_offset_t)res64; \ + } while (0) +#else +#define read_leb_mem_offset(p, p_end, res) read_leb_uint32(p, p_end, res) +#endif + #define read_leb_uint32(p, p_end, res) \ do { \ uint64 res64; \ @@ -366,138 +392,6 @@ memory_realloc(void *mem_old, uint32 size_old, uint32 size_new, char *error_buf, mem = mem_new; \ } while (0) -static bool -check_utf8_str(const uint8 *str, uint32 len) -{ - /* The valid ranges are taken from page 125, below link - https://www.unicode.org/versions/Unicode9.0.0/ch03.pdf */ - const uint8 *p = str, *p_end = str + len; - uint8 chr; - - while (p < p_end) { - chr = *p; - - if (chr == 0) { - LOG_WARNING( - "LIMITATION: a string which contains '\\00' is unsupported"); - return false; - } - else if (chr < 0x80) { - p++; - } - else if (chr >= 0xC2 && chr <= 0xDF && p + 1 < p_end) { - if (p[1] < 0x80 || p[1] > 0xBF) { - return false; - } - p += 2; - } - else if (chr >= 0xE0 && chr <= 0xEF && p + 2 < p_end) { - if (chr == 0xE0) { - if (p[1] < 0xA0 || p[1] > 0xBF || p[2] < 0x80 || p[2] > 0xBF) { - return false; - } - } - else if (chr == 0xED) { - if (p[1] < 0x80 || p[1] > 0x9F || p[2] < 0x80 || p[2] > 0xBF) { - return false; - } - } - else { /* chr >= 0xE1 && chr <= 0xEF */ - if (p[1] < 0x80 || p[1] > 0xBF || p[2] < 0x80 || p[2] > 0xBF) { - return false; - } - } - p += 3; - } - else if (chr >= 0xF0 && chr <= 0xF4 && p + 3 < p_end) { - if (chr == 0xF0) { - if (p[1] < 0x90 || p[1] > 0xBF || p[2] < 0x80 || p[2] > 0xBF - || p[3] < 0x80 || p[3] > 0xBF) { - return false; - } - } - else if (chr <= 0xF3) { /* and also chr >= 0xF1 */ - if (p[1] < 0x80 || p[1] > 0xBF || p[2] < 0x80 || p[2] > 0xBF - || p[3] < 0x80 || p[3] > 0xBF) { - return false; - } - } - else { /* chr == 0xF4 */ - if (p[1] < 0x80 || p[1] > 0x8F || p[2] < 0x80 || p[2] > 0xBF - || p[3] < 0x80 || p[3] > 0xBF) { - return false; - } - } - p += 4; - } - else { - return false; - } - } - return (p == p_end); -} - -static char * -const_str_list_insert(const uint8 *str, uint32 len, WASMModule *module, - bool is_load_from_file_buf, char *error_buf, - uint32 error_buf_size) -{ - StringNode *node, *node_next; - - if (!check_utf8_str(str, len)) { - set_error_buf(error_buf, error_buf_size, "invalid UTF-8 encoding"); - return NULL; - } - - if (len == 0) { - return ""; - } - else if (is_load_from_file_buf) { - /* As the file buffer can be referred to after loading, we use - the previous byte of leb encoded size to adjust the string: - move string 1 byte backward and then append '\0' */ - char *c_str = (char *)str - 1; - bh_memmove_s(c_str, len + 1, c_str + 1, len); - c_str[len] = '\0'; - return c_str; - } - - /* Search const str list */ - node = module->const_str_list; - while (node) { - node_next = node->next; - if (strlen(node->str) == len && !memcmp(node->str, str, len)) - break; - node = node_next; - } - - if (node) { - return node->str; - } - - if (!(node = loader_malloc(sizeof(StringNode) + len + 1, error_buf, - error_buf_size))) { - return NULL; - } - - node->str = ((char *)node) + sizeof(StringNode); - bh_memcpy_s(node->str, len + 1, str, len); - node->str[len] = '\0'; - - if (!module->const_str_list) { - /* set as head */ - module->const_str_list = node; - node->next = NULL; - } - else { - /* insert it */ - node->next = module->const_str_list; - module->const_str_list = node; - } - - return node->str; -} - #if WASM_ENABLE_GC != 0 static bool check_type_index(const WASMModule *module, uint32 type_index, char *error_buf, @@ -1568,8 +1462,10 @@ resolve_func_type(const uint8 **p_buf, const uint8 *buf_end, WASMModule *module, type->param_count = param_count; type->result_count = result_count; type->ref_type_map_count = ref_type_map_count; - type->result_ref_type_maps = - type->ref_type_maps + ref_type_map_count - result_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, @@ -1625,7 +1521,7 @@ resolve_func_type(const uint8 **p_buf, const uint8 *buf_end, WASMModule *module, #endif #if WASM_ENABLE_WAMR_COMPILER != 0 - for (i = 0; i < type->param_count + type->result_count; i++) { + for (i = 0; i < (uint32)(type->param_count + type->result_count); i++) { if (type->types[i] == VALUE_TYPE_V128) module->is_simd_used = true; } @@ -2033,8 +1929,8 @@ 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; + uint32 super_type_count = 0, parent_type_idx = (uint32)-1; + uint32 rec_count = 1, j; bool is_sub_final = true; CHECK_BUF(p, p_end, 1); @@ -2046,10 +1942,22 @@ load_type_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, if (rec_count > 1) { uint64 new_total_size; + /* integer overflow */ + if (rec_count - 1 > UINT32_MAX - module->type_count) { + set_error_buf(error_buf, error_buf_size, + "recursive type count too large"); + return false; + } module->type_count += rec_count - 1; new_total_size = sizeof(WASMFuncType *) * (uint64)module->type_count; - MEM_REALLOC(module->types, total_size, new_total_size); + if (new_total_size > UINT32_MAX) { + set_error_buf(error_buf, error_buf_size, + "allocate memory failed"); + return false; + } + MEM_REALLOC(module->types, (uint32)total_size, + (uint32)new_total_size); total_size = new_total_size; } @@ -2712,31 +2620,92 @@ fail: } static bool -check_memory_init_size(uint32 init_size, char *error_buf, uint32 error_buf_size) +check_memory_init_size(bool is_memory64, uint32 init_size, char *error_buf, + uint32 error_buf_size) { - if (init_size > DEFAULT_MAX_PAGES) { + uint32 default_max_size = + is_memory64 ? DEFAULT_MEM64_MAX_PAGES : DEFAULT_MAX_PAGES; + + if (!is_memory64 && init_size > default_max_size) { set_error_buf(error_buf, error_buf_size, "memory size must be at most 65536 pages (4GiB)"); return false; } +#if WASM_ENABLE_MEMORY64 != 0 + else if (is_memory64 && init_size > default_max_size) { + set_error_buf( + error_buf, error_buf_size, + "memory size must be at most 4,294,967,295 pages (274 Terabyte)"); + return false; + } +#endif return true; } static bool -check_memory_max_size(uint32 init_size, uint32 max_size, char *error_buf, - uint32 error_buf_size) +check_memory_max_size(bool is_memory64, uint32 init_size, uint32 max_size, + char *error_buf, uint32 error_buf_size) { + uint32 default_max_size = + is_memory64 ? DEFAULT_MEM64_MAX_PAGES : DEFAULT_MAX_PAGES; + if (max_size < init_size) { set_error_buf(error_buf, error_buf_size, "size minimum must not be greater than maximum"); return false; } - if (max_size > DEFAULT_MAX_PAGES) { + if (!is_memory64 && max_size > default_max_size) { set_error_buf(error_buf, error_buf_size, "memory size must be at most 65536 pages (4GiB)"); return false; } +#if WASM_ENABLE_MEMORY64 != 0 + else if (is_memory64 && max_size > default_max_size) { + set_error_buf( + error_buf, error_buf_size, + "memory size must be at most 4,294,967,295 pages (274 Terabyte)"); + return false; + } +#endif + + return true; +} + +static bool +check_memory_flag(const uint8 mem_flag, char *error_buf, uint32 error_buf_size) +{ + /* Check whether certain features indicated by mem_flag are enabled in + * runtime */ + if (mem_flag > MAX_PAGE_COUNT_FLAG) { +#if WASM_ENABLE_SHARED_MEMORY == 0 + if (mem_flag & SHARED_MEMORY_FLAG) { + LOG_VERBOSE("shared memory flag was found, please enable shared " + "memory, lib-pthread or lib-wasi-threads"); + set_error_buf(error_buf, error_buf_size, "invalid limits flags"); + return false; + } +#endif +#if WASM_ENABLE_MEMORY64 == 0 + if (mem_flag & MEMORY64_FLAG) { + LOG_VERBOSE("memory64 flag was found, please enable memory64"); + set_error_buf(error_buf, error_buf_size, "invalid limits flags"); + return false; + } +#endif + } + + if (mem_flag > MAX_PAGE_COUNT_FLAG + SHARED_MEMORY_FLAG + MEMORY64_FLAG) { + set_error_buf(error_buf, error_buf_size, "invalid limits flags"); + return false; + } + else if ((mem_flag & SHARED_MEMORY_FLAG) + && !(mem_flag & MAX_PAGE_COUNT_FLAG)) { + set_error_buf(error_buf, error_buf_size, + "shared memory must have maximum"); + return false; + } + return true; } @@ -2746,15 +2715,16 @@ load_memory_import(const uint8 **p_buf, const uint8 *buf_end, const char *memory_name, WASMMemoryImport *memory, char *error_buf, uint32 error_buf_size) { - const uint8 *p = *p_buf, *p_end = buf_end; + const uint8 *p = *p_buf, *p_end = buf_end, *p_org; #if WASM_ENABLE_APP_FRAMEWORK != 0 uint32 pool_size = wasm_runtime_memory_pool_size(); uint32 max_page_count = pool_size * APP_MEMORY_MAX_GLOBAL_HEAP_PERCENT / DEFAULT_NUM_BYTES_PER_PAGE; #else - uint32 max_page_count = DEFAULT_MAX_PAGES; + uint32 max_page_count; #endif /* WASM_ENABLE_APP_FRAMEWORK */ - uint32 declare_max_page_count_flag = 0; + uint32 mem_flag = 0; + bool is_memory64 = false; uint32 declare_init_page_count = 0; uint32 declare_max_page_count = 0; #if WASM_ENABLE_MULTI_MODULE != 0 @@ -2762,16 +2732,31 @@ load_memory_import(const uint8 **p_buf, const uint8 *buf_end, WASMMemory *linked_memory = NULL; #endif - read_leb_uint32(p, p_end, declare_max_page_count_flag); + p_org = p; + read_leb_uint32(p, p_end, mem_flag); + is_memory64 = mem_flag & MEMORY64_FLAG; + if (p - p_org > 1) { + LOG_VERBOSE("integer representation too long"); + set_error_buf(error_buf, error_buf_size, "invalid limits flags"); + return false; + } + + if (!check_memory_flag(mem_flag, error_buf, error_buf_size)) { + return false; + } + read_leb_uint32(p, p_end, declare_init_page_count); - if (!check_memory_init_size(declare_init_page_count, error_buf, + if (!check_memory_init_size(is_memory64, declare_init_page_count, error_buf, error_buf_size)) { return false; } - if (declare_max_page_count_flag & 1) { +#if WASM_ENABLE_APP_FRAMEWORK == 0 + max_page_count = is_memory64 ? DEFAULT_MEM64_MAX_PAGES : DEFAULT_MAX_PAGES; +#endif + if (mem_flag & MAX_PAGE_COUNT_FLAG) { read_leb_uint32(p, p_end, declare_max_page_count); - if (!check_memory_max_size(declare_init_page_count, + if (!check_memory_max_size(is_memory64, declare_init_page_count, declare_max_page_count, error_buf, error_buf_size)) { return false; @@ -2794,7 +2779,7 @@ load_memory_import(const uint8 **p_buf, const uint8 *buf_end, #if WASM_ENABLE_LIB_WASI_THREADS != 0 /* Avoid memory import failure when wasi-threads is enabled and the memory is shared */ - if (!(declare_max_page_count_flag & 2)) + if (!(mem_flag & SHARED_MEMORY_FLAG)) return false; #else return false; @@ -2842,7 +2827,7 @@ load_memory_import(const uint8 **p_buf, const uint8 *buf_end, } /* now we believe all declaration are ok */ - memory->flags = declare_max_page_count_flag; + memory->flags = mem_flag; memory->init_page_count = declare_init_page_count; memory->max_page_count = declare_max_page_count; memory->num_bytes_per_page = DEFAULT_NUM_BYTES_PER_PAGE; @@ -3143,53 +3128,34 @@ load_memory(const uint8 **p_buf, const uint8 *buf_end, WASMMemory *memory, uint32 max_page_count = pool_size * APP_MEMORY_MAX_GLOBAL_HEAP_PERCENT / DEFAULT_NUM_BYTES_PER_PAGE; #else - uint32 max_page_count = DEFAULT_MAX_PAGES; + uint32 max_page_count; #endif + bool is_memory64 = false; p_org = p; read_leb_uint32(p, p_end, memory->flags); -#if WASM_ENABLE_SHARED_MEMORY == 0 - if (p - p_org > 1) { - set_error_buf(error_buf, error_buf_size, - "integer representation too long"); - return false; - } - if (memory->flags > 1) { - if (memory->flags & 2) { - set_error_buf(error_buf, error_buf_size, - "shared memory flag was found, " - "please enable shared memory, lib-pthread " - "or lib-wasi-threads"); - } - else { - set_error_buf(error_buf, error_buf_size, "invalid memory flags"); - } - return false; - } -#else + is_memory64 = memory->flags & MEMORY64_FLAG; if (p - p_org > 1) { + LOG_VERBOSE("integer representation too long"); set_error_buf(error_buf, error_buf_size, "invalid limits flags"); return false; } - if (memory->flags > 3) { - set_error_buf(error_buf, error_buf_size, "invalid limits flags"); + + if (!check_memory_flag(memory->flags, error_buf, error_buf_size)) { return false; } - else if (memory->flags == 2) { - set_error_buf(error_buf, error_buf_size, - "shared memory must have maximum"); - return false; - } -#endif read_leb_uint32(p, p_end, memory->init_page_count); - if (!check_memory_init_size(memory->init_page_count, error_buf, + if (!check_memory_init_size(is_memory64, memory->init_page_count, error_buf, error_buf_size)) return false; +#if WASM_ENABLE_APP_FRAMEWORK == 0 + max_page_count = is_memory64 ? DEFAULT_MEM64_MAX_PAGES : DEFAULT_MAX_PAGES; +#endif if (memory->flags & 1) { read_leb_uint32(p, p_end, memory->max_page_count); - if (!check_memory_max_size(memory->init_page_count, + if (!check_memory_max_size(is_memory64, memory->init_page_count, memory->max_page_count, error_buf, error_buf_size)) return false; @@ -3368,7 +3334,7 @@ load_import_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, /* load module name */ read_leb_uint32(p, p_end, name_len); CHECK_BUF(p, p_end, name_len); - if (!(sub_module_name = const_str_list_insert( + if (!(sub_module_name = wasm_const_str_list_insert( p, name_len, module, is_load_from_file_buf, error_buf, error_buf_size))) { return false; @@ -3378,7 +3344,7 @@ load_import_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, /* load field name */ read_leb_uint32(p, p_end, name_len); CHECK_BUF(p, p_end, name_len); - if (!(field_name = const_str_list_insert( + if (!(field_name = wasm_const_str_list_insert( p, name_len, module, is_load_from_file_buf, error_buf, error_buf_size))) { return false; @@ -4101,7 +4067,7 @@ load_export_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, } } - if (!(export->name = const_str_list_insert( + if (!(export->name = wasm_const_str_list_insert( p, str_len, module, is_load_from_file_buf, error_buf, error_buf_size))) { return false; @@ -4530,7 +4496,7 @@ load_table_segment_section(const uint8 *buf, const uint8 *buf_end, "unknown element segment kind"); return false; } -#else +#else /* else of WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */ /* * like: 00 41 05 0b 04 00 01 00 01 * for: (elem 0 (offset (i32.const 5)) $f1 $f2 $f1 $f2) @@ -4546,7 +4512,7 @@ load_table_segment_section(const uint8 *buf, const uint8 *buf_end, if (!load_func_index_vec(&p, p_end, module, table_segment, error_buf, error_buf_size)) return false; -#endif /* WASM_ENABLE_REF_TYPES != 0 */ +#endif /* end of WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */ #if WASM_ENABLE_WAMR_COMPILER != 0 if (table_segment->elem_type == VALUE_TYPE_EXTERNREF) @@ -4580,6 +4546,7 @@ load_data_segment_section(const uint8 *buf, const uint8 *buf_end, bool is_passive = false; uint32 mem_flag; #endif + uint8 mem_offset_type; read_leb_uint32(p, p_end, data_seg_count); @@ -4645,11 +4612,35 @@ load_data_segment_section(const uint8 *buf, const uint8 *buf_end, } #endif /* WASM_ENABLE_BULK_MEMORY */ +#if WASM_ENABLE_BULK_MEMORY != 0 + if (!is_passive) +#endif + { +#if WASM_ENABLE_MEMORY64 != 0 + /* This memory_flag is from memory instead of data segment */ + uint8 memory_flag; + if (module->import_memory_count > 0) { + memory_flag = + module->import_memories[mem_index].u.memory.flags; + } + else { + memory_flag = + module + ->memories[mem_index - module->import_memory_count] + .flags; + } + mem_offset_type = memory_flag & MEMORY64_FLAG ? VALUE_TYPE_I64 + : VALUE_TYPE_I32; +#else + mem_offset_type = VALUE_TYPE_I32; +#endif + } + #if WASM_ENABLE_BULK_MEMORY != 0 if (!is_passive) #endif if (!load_init_expr(module, &p, p_end, &init_expr, - VALUE_TYPE_I32, NULL, error_buf, + mem_offset_type, NULL, error_buf, error_buf_size)) return false; @@ -4985,7 +4976,7 @@ handle_name_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, return false; } if (!(module->functions[func_index]->field_name = - const_str_list_insert( + wasm_const_str_list_insert( p, func_name_len, module, #if WASM_ENABLE_WAMR_COMPILER != 0 false, @@ -5037,7 +5028,7 @@ load_user_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, return false; } - if (!check_utf8_str(p, name_len)) { + if (!wasm_check_utf8_str(p, name_len)) { set_error_buf(error_buf, error_buf_size, "invalid UTF-8 encoding"); return false; } @@ -5053,7 +5044,7 @@ load_user_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, } #if WASM_ENABLE_CUSTOM_NAME_SECTION != 0 - if (memcmp(p, "name", 4) == 0) { + if (name_len == 4 && memcmp(p, "name", 4) == 0) { module->name_section_buf = buf; module->name_section_buf_end = buf_end; p += name_len; @@ -5595,8 +5586,9 @@ load_from_sections(WASMModule *module, WASMSection *sections, *buf_func = NULL, *buf_func_end = NULL; WASMGlobal *aux_data_end_global = NULL, *aux_heap_base_global = NULL; WASMGlobal *aux_stack_top_global = NULL, *global; - uint32 aux_data_end = (uint32)-1, aux_heap_base = (uint32)-1; - uint32 aux_stack_top = (uint32)-1, global_index, func_index, i; + uint64 aux_data_end = (uint64)-1LL, aux_heap_base = (uint64)-1LL, + aux_stack_top = (uint64)-1LL; + uint32 global_index, func_index, i; uint32 aux_data_end_global_index = (uint32)-1; uint32 aux_heap_base_global_index = (uint32)-1; WASMFuncType *func_type; @@ -5733,9 +5725,9 @@ load_from_sections(WASMModule *module, WASMSection *sections, && global->init_expr.init_expr_type == INIT_EXPR_TYPE_I32_CONST) { aux_heap_base_global = global; - aux_heap_base = global->init_expr.u.i32; + aux_heap_base = (uint64)(uint32)global->init_expr.u.i32; aux_heap_base_global_index = export->index; - LOG_VERBOSE("Found aux __heap_base global, value: %d", + LOG_VERBOSE("Found aux __heap_base global, value: %" PRIu64, aux_heap_base); } } @@ -5746,12 +5738,12 @@ load_from_sections(WASMModule *module, WASMSection *sections, && global->init_expr.init_expr_type == INIT_EXPR_TYPE_I32_CONST) { aux_data_end_global = global; - aux_data_end = global->init_expr.u.i32; + aux_data_end = (uint64)(uint32)global->init_expr.u.i32; aux_data_end_global_index = export->index; - LOG_VERBOSE("Found aux __data_end global, value: %d", + LOG_VERBOSE("Found aux __data_end global, value: %" PRIu64, aux_data_end); - aux_data_end = align_uint(aux_data_end, 16); + aux_data_end = align_uint64(aux_data_end, 16); } } @@ -5787,20 +5779,22 @@ load_from_sections(WASMModule *module, WASMSection *sections, && global->type == VALUE_TYPE_I32 && global->init_expr.init_expr_type == INIT_EXPR_TYPE_I32_CONST - && (uint32)global->init_expr.u.i32 <= aux_heap_base) { + && (uint64)(uint32)global->init_expr.u.i32 + <= aux_heap_base) { aux_stack_top_global = global; - aux_stack_top = (uint32)global->init_expr.u.i32; + aux_stack_top = (uint64)(uint32)global->init_expr.u.i32; module->aux_stack_top_global_index = module->import_global_count + global_index; module->aux_stack_bottom = aux_stack_top; module->aux_stack_size = aux_stack_top > aux_data_end - ? aux_stack_top - aux_data_end - : aux_stack_top; - LOG_VERBOSE("Found aux stack top global, value: %d, " - "global index: %d, stack size: %d", - aux_stack_top, global_index, - module->aux_stack_size); + ? (uint32)(aux_stack_top - aux_data_end) + : (uint32)aux_stack_top; + LOG_VERBOSE( + "Found aux stack top global, value: %" PRIu64 ", " + "global index: %d, stack size: %d", + aux_stack_top, global_index, + module->aux_stack_size); break; } } @@ -5937,29 +5931,36 @@ load_from_sections(WASMModule *module, WASMSection *sections, if (aux_data_end_global && aux_heap_base_global && aux_stack_top_global) { uint64 init_memory_size; - uint32 shrunk_memory_size = align_uint(aux_heap_base, 8); + uint64 shrunk_memory_size = align_uint64(aux_heap_base, 8); - if (module->import_memory_count) { - memory_import = &module->import_memories[0].u.memory; - init_memory_size = (uint64)memory_import->num_bytes_per_page - * memory_import->init_page_count; - if (shrunk_memory_size <= init_memory_size) { - /* Reset memory info to decrease memory usage */ - memory_import->num_bytes_per_page = shrunk_memory_size; - memory_import->init_page_count = 1; - LOG_VERBOSE("Shrink import memory size to %d", - shrunk_memory_size); + /* Only resize(shrunk) the memory size if num_bytes_per_page is in + * valid range of uint32 */ + if (shrunk_memory_size <= UINT32_MAX) { + if (module->import_memory_count) { + memory_import = &module->import_memories[0].u.memory; + init_memory_size = (uint64)memory_import->num_bytes_per_page + * memory_import->init_page_count; + if (shrunk_memory_size <= init_memory_size) { + /* Reset memory info to decrease memory usage */ + memory_import->num_bytes_per_page = + (uint32)shrunk_memory_size; + memory_import->init_page_count = 1; + LOG_VERBOSE("Shrink import memory size to %" PRIu64, + shrunk_memory_size); + } } - } - if (module->memory_count) { - memory = &module->memories[0]; - init_memory_size = (uint64)memory->num_bytes_per_page - * memory->init_page_count; - if (shrunk_memory_size <= init_memory_size) { - /* Reset memory info to decrease memory usage */ - memory->num_bytes_per_page = shrunk_memory_size; - memory->init_page_count = 1; - LOG_VERBOSE("Shrink memory size to %d", shrunk_memory_size); + + if (module->memory_count) { + memory = &module->memories[0]; + init_memory_size = (uint64)memory->num_bytes_per_page + * memory->init_page_count; + if (shrunk_memory_size <= init_memory_size) { + /* Reset memory info to decrease memory usage */ + memory->num_bytes_per_page = (uint32)shrunk_memory_size; + memory->init_page_count = 1; + LOG_VERBOSE("Shrink memory size to %" PRIu64, + shrunk_memory_size); + } } } } @@ -5967,30 +5968,31 @@ load_from_sections(WASMModule *module, WASMSection *sections, #if WASM_ENABLE_MULTI_MODULE == 0 if (module->import_memory_count) { memory_import = &module->import_memories[0].u.memory; - if (memory_import->init_page_count < DEFAULT_MAX_PAGES) + /* Only resize the memory to one big page if num_bytes_per_page is + * in valid range of uint32 */ + if (memory_import->init_page_count < DEFAULT_MAX_PAGES) { memory_import->num_bytes_per_page *= memory_import->init_page_count; - else - memory_import->num_bytes_per_page = UINT32_MAX; - if (memory_import->init_page_count > 0) - memory_import->init_page_count = memory_import->max_page_count = - 1; - else - memory_import->init_page_count = memory_import->max_page_count = - 0; + if (memory_import->init_page_count > 0) + memory_import->init_page_count = + memory_import->max_page_count = 1; + else + memory_import->init_page_count = + memory_import->max_page_count = 0; + } } if (module->memory_count) { memory = &module->memories[0]; - if (memory->init_page_count < DEFAULT_MAX_PAGES) + /* Only resize(shrunk) the memory size if num_bytes_per_page is in + * valid range of uint32 */ + if (memory->init_page_count < DEFAULT_MAX_PAGES) { memory->num_bytes_per_page *= memory->init_page_count; - else - memory->num_bytes_per_page = UINT32_MAX; - - if (memory->init_page_count > 0) - memory->init_page_count = memory->max_page_count = 1; - else - memory->init_page_count = memory->max_page_count = 0; + if (memory->init_page_count > 0) + memory->init_page_count = memory->max_page_count = 1; + else + memory->init_page_count = memory->max_page_count = 0; + } } #endif } @@ -6041,7 +6043,7 @@ load_from_sections(WASMModule *module, WASMSection *sections, } static WASMModule * -create_module(char *error_buf, uint32 error_buf_size) +create_module(char *name, char *error_buf, uint32 error_buf_size) { WASMModule *module = loader_malloc(sizeof(WASMModule), error_buf, error_buf_size); @@ -6056,6 +6058,8 @@ create_module(char *error_buf, uint32 error_buf_size) /* Set start_function to -1, means no start function */ module->start_function = (uint32)-1; + module->name = name; + #if WASM_ENABLE_FAST_INTERP == 0 module->br_table_cache_list = &module->br_table_cache_list_head; ret = bh_list_init(module->br_table_cache_list); @@ -6134,7 +6138,7 @@ WASMModule * wasm_loader_load_from_sections(WASMSection *section_list, char *error_buf, uint32 error_buf_size) { - WASMModule *module = create_module(error_buf, error_buf_size); + WASMModule *module = create_module("", error_buf, error_buf_size); if (!module) return NULL; @@ -6475,9 +6479,9 @@ wasm_loader_load(uint8 *buf, uint32 size, #if WASM_ENABLE_MULTI_MODULE != 0 bool main_module, #endif - char *error_buf, uint32 error_buf_size) + const LoadArgs *args, char *error_buf, uint32 error_buf_size) { - WASMModule *module = create_module(error_buf, error_buf_size); + WASMModule *module = create_module(args->name, error_buf, error_buf_size); if (!module) { return NULL; } @@ -6664,7 +6668,7 @@ wasm_loader_unload(WASMModule *module) #if WASM_ENABLE_STRINGREF != 0 if (module->string_literal_ptrs) { - wasm_runtime_free(module->string_literal_ptrs); + wasm_runtime_free((void *)module->string_literal_ptrs); } if (module->string_literal_lengths) { wasm_runtime_free(module->string_literal_lengths); @@ -7098,8 +7102,8 @@ wasm_loader_find_block_addr(WASMExecEnv *exec_env, BlockAddr *block_addr_cache, case WASM_OP_I64_STORE8: case WASM_OP_I64_STORE16: case WASM_OP_I64_STORE32: - skip_leb_uint32(p, p_end); /* align */ - skip_leb_uint32(p, p_end); /* offset */ + skip_leb_uint32(p, p_end); /* align */ + skip_leb_mem_offset(p, p_end); /* offset */ break; case WASM_OP_MEMORY_SIZE: @@ -7445,6 +7449,7 @@ wasm_loader_find_block_addr(WASMExecEnv *exec_env, BlockAddr *block_addr_cache, #if (WASM_ENABLE_WAMR_COMPILER != 0) || (WASM_ENABLE_JIT != 0) case WASM_OP_SIMD_PREFIX: { + /* TODO: memory64 offset type changes */ uint32 opcode1; read_leb_uint32(p, p_end, opcode1); @@ -7541,6 +7546,7 @@ wasm_loader_find_block_addr(WASMExecEnv *exec_env, BlockAddr *block_addr_cache, #if WASM_ENABLE_SHARED_MEMORY != 0 case WASM_OP_ATOMIC_PREFIX: { + /* TODO: memory64 offset type changes */ uint32 opcode1; /* atomic_op (u32_leb) + memarg (2 u32_leb) */ @@ -7550,8 +7556,8 @@ wasm_loader_find_block_addr(WASMExecEnv *exec_env, BlockAddr *block_addr_cache, opcode = (uint8)opcode1; if (opcode != WASM_OP_ATOMIC_FENCE) { - skip_leb_uint32(p, p_end); /* align */ - skip_leb_uint32(p, p_end); /* offset */ + skip_leb_uint32(p, p_end); /* align */ + skip_leb_mem_offset(p, p_end); /* offset */ } else { /* atomic.fence doesn't have memarg */ @@ -8364,12 +8370,12 @@ wasm_loader_pop_nullable_ht(WASMLoaderContext *ctx, uint8 *p_type, } /* 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) + if (type >= REF_TYPE_ARRAYREF && type <= REF_TYPE_NULLFUNCREF) { + /* Return (ref array/struct/i31/eq/any/extern/func/none/noextern/nofunc) */ wasm_set_refheaptype_common(&ref_ht_ret->ref_ht_common, false, - HEAP_TYPE_FUNC + (type - REF_TYPE_FUNCREF)); + HEAP_TYPE_ARRAY + + (type - REF_TYPE_ARRAYREF)); type = ref_ht_ret->ref_type; } else if (wasm_is_reftype_htref_nullable(type) @@ -8567,11 +8573,11 @@ fail: wasm_loader_emit_ptr(loader_ctx, NULL); \ } while (0) -#define emit_br_info(frame_csp) \ - do { \ - if (!wasm_loader_emit_br_info(loader_ctx, frame_csp, error_buf, \ - error_buf_size)) \ - goto fail; \ +#define emit_br_info(frame_csp, is_br) \ + do { \ + if (!wasm_loader_emit_br_info(loader_ctx, frame_csp, is_br, error_buf, \ + error_buf_size)) \ + goto fail; \ } while (0) #define LAST_OP_OUTPUT_I32() \ @@ -8965,7 +8971,7 @@ apply_label_patch(WASMLoaderContext *ctx, uint8 depth, uint8 patch_type) static bool wasm_loader_emit_br_info(WASMLoaderContext *ctx, BranchBlock *frame_csp, - char *error_buf, uint32 error_buf_size) + bool is_br, char *error_buf, uint32 error_buf_size) { /* br info layout: * a) arity of target block @@ -9026,6 +9032,8 @@ wasm_loader_emit_br_info(WASMLoaderContext *ctx, BranchBlock *frame_csp, /* Part e */ dynamic_offset = frame_csp->dynamic_offset + wasm_get_cell_num(types, arity); + if (is_br) + ctx->dynamic_offset = dynamic_offset; for (i = (int32)arity - 1; i >= 0; i--) { cell = (uint8)wasm_value_type_cell_num(types[i]); dynamic_offset -= cell; @@ -9451,6 +9459,8 @@ fail: #define PUSH_EXTERNREF() TEMPLATE_PUSH(EXTERNREF) #define PUSH_REF(Type) TEMPLATE_PUSH_REF(Type) #define POP_REF(Type) TEMPLATE_POP_REF(Type) +#define PUSH_MEM_OFFSET() TEMPLATE_PUSH_REF(mem_offset_type) +#define PUSH_PAGE_COUNT() PUSH_MEM_OFFSET() #define POP_I32() TEMPLATE_POP(I32) #define POP_F32() TEMPLATE_POP(F32) @@ -9460,6 +9470,7 @@ fail: #define POP_FUNCREF() TEMPLATE_POP(FUNCREF) #define POP_EXTERNREF() TEMPLATE_POP(EXTERNREF) #define POP_STRINGREF() TEMPLATE_POP(STRINGREF) +#define POP_MEM_OFFSET() TEMPLATE_POP_REF(mem_offset_type) #if WASM_ENABLE_FAST_INTERP != 0 @@ -9711,13 +9722,6 @@ fail: GET_LOCAL_REFTYPE(); \ } while (0) -#define CHECK_BR(depth) \ - do { \ - if (!wasm_loader_check_br(loader_ctx, depth, error_buf, \ - error_buf_size)) \ - goto fail; \ - } while (0) - static bool check_memory(WASMModule *module, char *error_buf, uint32 error_buf_size) { @@ -9900,8 +9904,8 @@ check_memory_align_equal(uint8 opcode, uint32 align, char *error_buf, #endif /* end of WASM_ENABLE_SHARED_MEMORY */ static bool -wasm_loader_check_br(WASMLoaderContext *loader_ctx, uint32 depth, - bool is_br_table, char *error_buf, uint32 error_buf_size) +wasm_loader_check_br(WASMLoaderContext *loader_ctx, uint32 depth, uint8 opcode, + char *error_buf, uint32 error_buf_size) { BranchBlock *target_block, *cur_block; BlockType *target_block_type; @@ -9918,6 +9922,27 @@ wasm_loader_check_br(WASMLoaderContext *loader_ctx, uint32 depth, bool is_type_multi_byte; #endif + 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, @@ -9954,7 +9979,7 @@ wasm_loader_check_br(WASMLoaderContext *loader_ctx, uint32 depth, /* 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 && !is_br_table) { + if (cur_block->is_stack_polymorphic) { #if WASM_ENABLE_GC != 0 int32 j = reftype_map_count - 1; #endif @@ -9973,6 +9998,52 @@ 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 (opcode == WASM_OP_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 @@ -9993,7 +10064,56 @@ 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, opcode == WASM_OP_BR); +#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 (opcode == WASM_OP_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 = @@ -10029,7 +10149,7 @@ wasm_loader_check_br(WASMLoaderContext *loader_ctx, uint32 depth, ref_type, #endif error_buf, error_buf_size)) { - return false; + goto fail; } cell_num = wasm_value_type_cell_num(types[i]); frame_ref -= cell_num; @@ -10043,30 +10163,43 @@ wasm_loader_check_br(WASMLoaderContext *loader_ctx, uint32 depth, #endif } - return true; +#if WASM_ENABLE_FAST_INTERP != 0 + emit_br_info(target_block, opcode == WASM_OP_BR); +#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_buf); +#endif + + return ret; } static BranchBlock * check_branch_block(WASMLoaderContext *loader_ctx, uint8 **p_buf, uint8 *buf_end, - bool is_br_table, char *error_buf, uint32 error_buf_size) + uint8 opcode, 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); - if (!wasm_loader_check_br(loader_ctx, depth, is_br_table, error_buf, + if (!wasm_loader_check_br(loader_ctx, depth, opcode, 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; @@ -10102,7 +10235,7 @@ check_branch_block_for_delegate(WASMLoaderContext *loader_ctx, uint8 **p_buf, } frame_csp_tmp = loader_ctx->frame_csp - depth - 2; #if WASM_ENABLE_FAST_INTERP != 0 - emit_br_info(frame_csp_tmp); + emit_br_info(frame_csp_tmp, false); #endif *p_buf = p; @@ -10506,11 +10639,12 @@ wasm_loader_prepare_bytecode(WASMModule *module, WASMFunction *func, { uint8 *p = func->code, *p_end = func->code + func->code_size, *p_org; uint32 param_count, local_count, global_count; - uint8 *param_types, *local_types, local_type, global_type; + uint8 *param_types, *local_types, local_type, global_type, mem_offset_type; BlockType func_block_type; uint16 *local_offsets, local_offset; uint32 type_idx, func_idx, local_idx, global_idx, table_idx; - uint32 table_seg_idx, data_seg_idx, count, align, mem_offset, i; + uint32 table_seg_idx, data_seg_idx, count, align, i; + mem_offset_t mem_offset; int32 i32_const = 0; int64 i64_const; uint8 opcode; @@ -10535,6 +10669,19 @@ wasm_loader_prepare_bytecode(WASMModule *module, WASMFunction *func, LOG_OP("\nProcessing func | [%d] params | [%d] locals | [%d] return\n", func->param_cell_num, func->local_cell_num, func->ret_cell_num); #endif +#if WASM_ENABLE_MEMORY64 != 0 + bool is_memory64 = false; + /* TODO: multi-memories for now assuming the memory idx type is consistent + * across multi-memories */ + if (module->import_memory_count > 0) + is_memory64 = module->import_memories[0].u.memory.flags & MEMORY64_FLAG; + else if (module->memory_count > 0) + is_memory64 = module->memories[0].flags & MEMORY64_FLAG; + + mem_offset_type = is_memory64 ? VALUE_TYPE_I64 : VALUE_TYPE_I32; +#else + mem_offset_type = VALUE_TYPE_I32; +#endif global_count = module->import_global_count + module->global_count; @@ -10796,8 +10943,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; } } @@ -10971,7 +11125,7 @@ re_scan: /* check the target catching block: LABEL_TYPE_CATCH */ if (!(frame_csp_tmp = - check_branch_block(loader_ctx, &p, p_end, false, + check_branch_block(loader_ctx, &p, p_end, opcode, error_buf, error_buf_size))) goto fail; @@ -11258,7 +11412,7 @@ re_scan: case WASM_OP_BR: { if (!(frame_csp_tmp = - check_branch_block(loader_ctx, &p, p_end, false, + check_branch_block(loader_ctx, &p, p_end, opcode, error_buf, error_buf_size))) goto fail; @@ -11272,7 +11426,7 @@ re_scan: POP_I32(); if (!(frame_csp_tmp = - check_branch_block(loader_ctx, &p, p_end, false, + check_branch_block(loader_ctx, &p, p_end, opcode, error_buf, error_buf_size))) goto fail; @@ -11281,7 +11435,7 @@ re_scan: case WASM_OP_BR_TABLE: { - uint32 depth, default_arity, arity = 0; + uint32 depth = 0, default_arity, arity = 0; BranchBlock *target_block; BlockType *target_block_type; #if WASM_ENABLE_FAST_INTERP == 0 @@ -11342,7 +11496,7 @@ re_scan: } if (!(frame_csp_tmp = - check_branch_block(loader_ctx, &p, p_end, true, + check_branch_block(loader_ctx, &p, p_end, opcode, error_buf, error_buf_size))) { goto fail; } @@ -12171,7 +12325,14 @@ re_scan: note that it doesn't matter whether the table seg's mode is passive, active or declarative. */ for (i = 0; i < module->table_seg_count; i++, table_seg++) { - if (table_seg->elem_type == VALUE_TYPE_FUNCREF) { + if (table_seg->elem_type == VALUE_TYPE_FUNCREF +#if WASM_ENABLE_GC != 0 + || (table_seg->elem_type == REF_TYPE_HT_NON_NULLABLE + && table_seg->elem_ref_type->ref_ht_common + .heap_type + == HEAP_TYPE_FUNC) +#endif + ) { for (j = 0; j < table_seg->value_count; j++) { if (table_seg->init_values[j].u.ref_index == func_idx) { @@ -12240,15 +12401,14 @@ re_scan: if (opcode == WASM_OP_BR_ON_NULL) { if (!(frame_csp_tmp = - check_branch_block(loader_ctx, &p, p_end, false, + check_branch_block(loader_ctx, &p, p_end, opcode, error_buf, error_buf_size))) { goto fail; } - } - #if WASM_ENABLE_FAST_INTERP != 0 - disable_emit = true; + disable_emit = true; #endif + } /* PUSH the converted (ref ht) */ if (type != VALUE_TYPE_ANY) { @@ -12288,7 +12448,7 @@ re_scan: PUSH_REF(type); } if (!(frame_csp_tmp = - check_branch_block(loader_ctx, &p, p_end, false, + check_branch_block(loader_ctx, &p, p_end, opcode, error_buf, error_buf_size))) { goto fail; } @@ -12713,8 +12873,8 @@ re_scan: } #endif CHECK_MEMORY(); - read_leb_uint32(p, p_end, align); /* align */ - read_leb_uint32(p, p_end, mem_offset); /* offset */ + read_leb_uint32(p, p_end, align); /* align */ + read_leb_mem_offset(p, p_end, mem_offset); /* offset */ if (!check_memory_access_align(opcode, align, error_buf, error_buf_size)) { goto fail; @@ -12732,7 +12892,7 @@ re_scan: case WASM_OP_I32_LOAD8_U: case WASM_OP_I32_LOAD16_S: case WASM_OP_I32_LOAD16_U: - POP_AND_PUSH(VALUE_TYPE_I32, VALUE_TYPE_I32); + POP_AND_PUSH(mem_offset_type, VALUE_TYPE_I32); break; case WASM_OP_I64_LOAD: case WASM_OP_I64_LOAD8_S: @@ -12741,35 +12901,35 @@ re_scan: case WASM_OP_I64_LOAD16_U: case WASM_OP_I64_LOAD32_S: case WASM_OP_I64_LOAD32_U: - POP_AND_PUSH(VALUE_TYPE_I32, VALUE_TYPE_I64); + POP_AND_PUSH(mem_offset_type, VALUE_TYPE_I64); break; case WASM_OP_F32_LOAD: - POP_AND_PUSH(VALUE_TYPE_I32, VALUE_TYPE_F32); + POP_AND_PUSH(mem_offset_type, VALUE_TYPE_F32); break; case WASM_OP_F64_LOAD: - POP_AND_PUSH(VALUE_TYPE_I32, VALUE_TYPE_F64); + POP_AND_PUSH(mem_offset_type, VALUE_TYPE_F64); break; /* store */ case WASM_OP_I32_STORE: case WASM_OP_I32_STORE8: case WASM_OP_I32_STORE16: POP_I32(); - POP_I32(); + POP_MEM_OFFSET(); break; case WASM_OP_I64_STORE: case WASM_OP_I64_STORE8: case WASM_OP_I64_STORE16: case WASM_OP_I64_STORE32: POP_I64(); - POP_I32(); + POP_MEM_OFFSET(); break; case WASM_OP_F32_STORE: POP_F32(); - POP_I32(); + POP_MEM_OFFSET(); break; case WASM_OP_F64_STORE: POP_F64(); - POP_I32(); + POP_MEM_OFFSET(); break; default: break; @@ -12785,7 +12945,7 @@ re_scan: "zero byte expected"); goto fail; } - PUSH_I32(); + PUSH_PAGE_COUNT(); module->possible_memory_grow = true; #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 @@ -12801,7 +12961,7 @@ re_scan: "zero byte expected"); goto fail; } - POP_AND_PUSH(VALUE_TYPE_I32, VALUE_TYPE_I32); + POP_AND_PUSH(mem_offset_type, mem_offset_type); module->possible_memory_grow = true; #if WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0 \ @@ -12848,6 +13008,7 @@ re_scan: break; case WASM_OP_F32_CONST: + CHECK_BUF(p, p_end, sizeof(float32)); p += sizeof(float32); #if WASM_ENABLE_FAST_INTERP != 0 skip_label(); @@ -12866,6 +13027,7 @@ re_scan: break; case WASM_OP_F64_CONST: + CHECK_BUF(p, p_end, sizeof(float64)); p += sizeof(float64); #if WASM_ENABLE_FAST_INTERP != 0 skip_label(); @@ -13770,7 +13932,7 @@ re_scan: } PUSH_REF(type_tmp); if (!(frame_csp_tmp = check_branch_block( - loader_ctx, &p, p_end, false, error_buf, + loader_ctx, &p, p_end, opcode, error_buf, error_buf_size))) { goto fail; } @@ -14162,7 +14324,7 @@ re_scan: POP_I32(); POP_I32(); - POP_I32(); + POP_MEM_OFFSET(); #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 func->has_memory_operations = true; #endif @@ -14196,6 +14358,7 @@ re_scan: } case WASM_OP_MEMORY_COPY: { + CHECK_BUF(p, p_end, sizeof(int16)); /* both src and dst memory index should be 0 */ if (*(int16 *)p != 0x0000) goto fail_zero_byte_expected; @@ -14205,9 +14368,9 @@ re_scan: && module->memory_count == 0) goto fail_unknown_memory; - POP_I32(); - POP_I32(); - POP_I32(); + POP_MEM_OFFSET(); + POP_MEM_OFFSET(); + POP_MEM_OFFSET(); #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 func->has_memory_operations = true; #endif @@ -14225,10 +14388,9 @@ re_scan: && module->memory_count == 0) { goto fail_unknown_memory; } - - POP_I32(); - POP_I32(); + POP_MEM_OFFSET(); POP_I32(); + POP_MEM_OFFSET(); #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 func->has_memory_operations = true; #endif @@ -14474,6 +14636,7 @@ re_scan: #if (WASM_ENABLE_WAMR_COMPILER != 0) || (WASM_ENABLE_JIT != 0) case WASM_OP_SIMD_PREFIX: { + /* TODO: memory64 offset type changes */ uint32 opcode1; #if WASM_ENABLE_WAMR_COMPILER != 0 @@ -14969,13 +15132,6 @@ re_scan: break; } - case SIMD_i32x4_narrow_i64x2_s: - case SIMD_i32x4_narrow_i64x2_u: - { - POP2_AND_PUSH(VALUE_TYPE_V128, VALUE_TYPE_V128); - break; - } - case SIMD_i32x4_extend_low_i16x8_s: case SIMD_i32x4_extend_high_i16x8_s: case SIMD_i32x4_extend_low_i16x8_u: @@ -15002,7 +15158,6 @@ re_scan: case SIMD_i32x4_max_s: case SIMD_i32x4_max_u: case SIMD_i32x4_dot_i16x8_s: - case SIMD_i32x4_avgr_u: case SIMD_i32x4_extmul_low_i16x8_s: case SIMD_i32x4_extmul_high_i16x8_s: case SIMD_i32x4_extmul_low_i16x8_u: @@ -15066,7 +15221,6 @@ re_scan: /* f32x4 operation */ case SIMD_f32x4_abs: case SIMD_f32x4_neg: - case SIMD_f32x4_round: case SIMD_f32x4_sqrt: { POP_AND_PUSH(VALUE_TYPE_V128, VALUE_TYPE_V128); @@ -15089,7 +15243,6 @@ re_scan: /* f64x2 operation */ case SIMD_f64x2_abs: case SIMD_f64x2_neg: - case SIMD_f64x2_round: case SIMD_f64x2_sqrt: { POP_AND_PUSH(VALUE_TYPE_V128, VALUE_TYPE_V128); @@ -15150,8 +15303,8 @@ re_scan: #endif if (opcode1 != WASM_OP_ATOMIC_FENCE) { CHECK_MEMORY(); - read_leb_uint32(p, p_end, align); /* align */ - read_leb_uint32(p, p_end, mem_offset); /* offset */ + read_leb_uint32(p, p_end, align); /* align */ + read_leb_mem_offset(p, p_end, mem_offset); /* offset */ if (!check_memory_align_equal(opcode1, align, error_buf, error_buf_size)) { goto fail; @@ -15165,18 +15318,20 @@ re_scan: #endif switch (opcode1) { case WASM_OP_ATOMIC_NOTIFY: - POP2_AND_PUSH(VALUE_TYPE_I32, VALUE_TYPE_I32); + POP_I32(); + POP_MEM_OFFSET(); + PUSH_I32(); break; case WASM_OP_ATOMIC_WAIT32: POP_I64(); POP_I32(); - POP_I32(); + POP_MEM_OFFSET(); PUSH_I32(); break; case WASM_OP_ATOMIC_WAIT64: POP_I64(); POP_I64(); - POP_I32(); + POP_MEM_OFFSET(); PUSH_I32(); break; case WASM_OP_ATOMIC_FENCE: @@ -15190,26 +15345,26 @@ re_scan: case WASM_OP_ATOMIC_I32_LOAD: case WASM_OP_ATOMIC_I32_LOAD8_U: case WASM_OP_ATOMIC_I32_LOAD16_U: - POP_AND_PUSH(VALUE_TYPE_I32, VALUE_TYPE_I32); + POP_AND_PUSH(mem_offset_type, VALUE_TYPE_I32); break; case WASM_OP_ATOMIC_I32_STORE: case WASM_OP_ATOMIC_I32_STORE8: case WASM_OP_ATOMIC_I32_STORE16: POP_I32(); - POP_I32(); + POP_MEM_OFFSET(); break; case WASM_OP_ATOMIC_I64_LOAD: case WASM_OP_ATOMIC_I64_LOAD8_U: case WASM_OP_ATOMIC_I64_LOAD16_U: case WASM_OP_ATOMIC_I64_LOAD32_U: - POP_AND_PUSH(VALUE_TYPE_I32, VALUE_TYPE_I64); + POP_AND_PUSH(mem_offset_type, VALUE_TYPE_I64); break; case WASM_OP_ATOMIC_I64_STORE: case WASM_OP_ATOMIC_I64_STORE8: case WASM_OP_ATOMIC_I64_STORE16: case WASM_OP_ATOMIC_I64_STORE32: POP_I64(); - POP_I32(); + POP_MEM_OFFSET(); break; case WASM_OP_ATOMIC_RMW_I32_ADD: case WASM_OP_ATOMIC_RMW_I32_ADD8_U: @@ -15229,7 +15384,9 @@ re_scan: case WASM_OP_ATOMIC_RMW_I32_XCHG: case WASM_OP_ATOMIC_RMW_I32_XCHG8_U: case WASM_OP_ATOMIC_RMW_I32_XCHG16_U: - POP2_AND_PUSH(VALUE_TYPE_I32, VALUE_TYPE_I32); + POP_I32(); + POP_MEM_OFFSET(); + PUSH_I32(); break; case WASM_OP_ATOMIC_RMW_I64_ADD: case WASM_OP_ATOMIC_RMW_I64_ADD8_U: @@ -15256,7 +15413,7 @@ re_scan: case WASM_OP_ATOMIC_RMW_I64_XCHG16_U: case WASM_OP_ATOMIC_RMW_I64_XCHG32_U: POP_I64(); - POP_I32(); + POP_MEM_OFFSET(); PUSH_I64(); break; case WASM_OP_ATOMIC_RMW_I32_CMPXCHG: @@ -15264,7 +15421,7 @@ re_scan: case WASM_OP_ATOMIC_RMW_I32_CMPXCHG16_U: POP_I32(); POP_I32(); - POP_I32(); + POP_MEM_OFFSET(); PUSH_I32(); break; case WASM_OP_ATOMIC_RMW_I64_CMPXCHG: @@ -15273,7 +15430,7 @@ re_scan: case WASM_OP_ATOMIC_RMW_I64_CMPXCHG32_U: POP_I64(); POP_I64(); - POP_I32(); + POP_MEM_OFFSET(); PUSH_I64(); break; default: diff --git a/core/iwasm/interpreter/wasm_loader.h b/core/iwasm/interpreter/wasm_loader.h index 8b0dc77d6..676770ee2 100644 --- a/core/iwasm/interpreter/wasm_loader.h +++ b/core/iwasm/interpreter/wasm_loader.h @@ -28,7 +28,7 @@ wasm_loader_load(uint8 *buf, uint32 size, #if WASM_ENABLE_MULTI_MODULE != 0 bool main_module, #endif - char *error_buf, uint32 error_buf_size); + const LoadArgs *args, char *error_buf, uint32 error_buf_size); /** * Load a WASM module from a specified WASM section list. diff --git a/core/iwasm/interpreter/wasm_mini_loader.c b/core/iwasm/interpreter/wasm_mini_loader.c index 643e310d3..3b452af92 100644 --- a/core/iwasm/interpreter/wasm_mini_loader.c +++ b/core/iwasm/interpreter/wasm_mini_loader.c @@ -47,6 +47,7 @@ set_error_buf(char *error_buf, uint32 error_buf_size, const char *string) #define skip_leb_int64(p, p_end) skip_leb(p) #define skip_leb_uint32(p, p_end) skip_leb(p) #define skip_leb_int32(p, p_end) skip_leb(p) +#define skip_leb_mem_offset(p, p_end) skip_leb(p) static bool is_32bit_type(uint8 type) @@ -116,7 +117,7 @@ read_leb(uint8 **p_buf, const uint8 *buf_end, uint32 maxbits, bool sign, } else if (sign && maxbits == 32) { if (shift < maxbits) { - /* Sign extend, second highest bit is the sign bit */ + /* Sign extend, second-highest bit is the sign bit */ if ((uint8)byte & 0x40) result |= (~((uint64)0)) << shift; } @@ -132,7 +133,7 @@ read_leb(uint8 **p_buf, const uint8 *buf_end, uint32 maxbits, bool sign, } else if (sign && maxbits == 64) { if (shift < maxbits) { - /* Sign extend, second highest bit is the sign bit */ + /* Sign extend, second-highest bit is the sign bit */ if ((uint8)byte & 0x40) result |= (~((uint64)0)) << shift; } @@ -180,6 +181,18 @@ read_leb(uint8 **p_buf, const uint8 *buf_end, uint32 maxbits, bool sign, res = (int32)res64; \ } while (0) +#if WASM_ENABLE_MEMORY64 != 0 +#define read_leb_mem_offset(p, p_end, res) \ + do { \ + uint64 res64; \ + read_leb((uint8 **)&p, p_end, is_memory64 ? 64 : 32, false, &res64, \ + error_buf, error_buf_size); \ + res = (mem_offset_t)res64; \ + } while (0) +#else +#define read_leb_mem_offset(p, p_end, res) read_leb_uint32(p, p_end, res) +#endif + static void * loader_malloc(uint64 size, char *error_buf, uint32 error_buf_size) { @@ -217,63 +230,6 @@ memory_realloc(void *mem_old, uint32 size_old, uint32 size_new, char *error_buf, 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, - uint32 error_buf_size) -{ - StringNode *node, *node_next; - - if (len == 0) { - return ""; - } - else if (is_load_from_file_buf) { - /* As the file buffer can be referred to after loading, we use - the previous byte of leb encoded size to adjust the string: - move string 1 byte backward and then append '\0' */ - char *c_str = (char *)str - 1; - bh_memmove_s(c_str, len + 1, c_str + 1, len); - c_str[len] = '\0'; - return c_str; - } - - /* Search const str list */ - node = module->const_str_list; - while (node) { - node_next = node->next; - if (strlen(node->str) == len && !memcmp(node->str, str, len)) - break; - node = node_next; - } - - if (node) { - LOG_DEBUG("reuse %s", node->str); - return node->str; - } - - if (!(node = loader_malloc(sizeof(StringNode) + len + 1, error_buf, - error_buf_size))) { - return NULL; - } - - node->str = ((char *)node) + sizeof(StringNode); - bh_memcpy_s(node->str, len + 1, str, len); - node->str[len] = '\0'; - - if (!module->const_str_list) { - /* set as head */ - module->const_str_list = node; - node->next = NULL; - } - else { - /* insert it */ - node->next = module->const_str_list; - module->const_str_list = node; - } - - return node->str; -} - static void destroy_wasm_type(WASMFuncType *type) { @@ -740,6 +696,38 @@ load_table_import(const uint8 **p_buf, const uint8 *buf_end, return true; } +static bool +check_memory_flag(const uint8 mem_flag) +{ + /* Check whether certain features indicated by mem_flag are enabled in + * runtime */ + if (mem_flag > MAX_PAGE_COUNT_FLAG) { +#if WASM_ENABLE_SHARED_MEMORY == 0 + if (mem_flag & SHARED_MEMORY_FLAG) { + LOG_VERBOSE("shared memory flag was found, please enable shared " + "memory, lib-pthread or lib-wasi-threads"); + return false; + } +#endif +#if WASM_ENABLE_MEMORY64 == 0 + if (mem_flag & MEMORY64_FLAG) { + LOG_VERBOSE("memory64 flag was found, please enable memory64"); + return false; + } +#endif + } + + if (mem_flag > MAX_PAGE_COUNT_FLAG + SHARED_MEMORY_FLAG + MEMORY64_FLAG) { + return false; + } + else if ((mem_flag & SHARED_MEMORY_FLAG) + && !(mem_flag & MAX_PAGE_COUNT_FLAG)) { + return false; + } + + return true; +} + static bool load_memory_import(const uint8 **p_buf, const uint8 *buf_end, WASMModule *parent_module, const char *sub_module_name, @@ -752,20 +740,28 @@ load_memory_import(const uint8 **p_buf, const uint8 *buf_end, uint32 max_page_count = pool_size * APP_MEMORY_MAX_GLOBAL_HEAP_PERCENT / DEFAULT_NUM_BYTES_PER_PAGE; #else - uint32 max_page_count = DEFAULT_MAX_PAGES; + uint32 max_page_count; #endif /* WASM_ENABLE_APP_FRAMEWORK */ - uint32 declare_max_page_count_flag = 0; + uint32 mem_flag = 0; + bool is_memory64 = false; uint32 declare_init_page_count = 0; uint32 declare_max_page_count = 0; - read_leb_uint32(p, p_end, declare_max_page_count_flag); - read_leb_uint32(p, p_end, declare_init_page_count); - bh_assert(declare_init_page_count <= 65536); + read_leb_uint32(p, p_end, mem_flag); + bh_assert(check_memory_flag(mem_flag)); - if (declare_max_page_count_flag & 1) { +#if WASM_ENABLE_APP_FRAMEWORK == 0 + is_memory64 = mem_flag & MEMORY64_FLAG; + max_page_count = is_memory64 ? DEFAULT_MEM64_MAX_PAGES : DEFAULT_MAX_PAGES; +#endif + + read_leb_uint32(p, p_end, declare_init_page_count); + bh_assert(declare_init_page_count <= max_page_count); + + if (mem_flag & MAX_PAGE_COUNT_FLAG) { read_leb_uint32(p, p_end, declare_max_page_count); bh_assert(declare_init_page_count <= declare_max_page_count); - bh_assert(declare_max_page_count <= 65536); + bh_assert(declare_max_page_count <= max_page_count); if (declare_max_page_count > max_page_count) { declare_max_page_count = max_page_count; } @@ -776,12 +772,13 @@ load_memory_import(const uint8 **p_buf, const uint8 *buf_end, } /* now we believe all declaration are ok */ - memory->flags = declare_max_page_count_flag; + memory->flags = mem_flag; memory->init_page_count = declare_init_page_count; memory->max_page_count = declare_max_page_count; memory->num_bytes_per_page = DEFAULT_NUM_BYTES_PER_PAGE; *p_buf = p; + (void)check_memory_flag; return true; } @@ -868,26 +865,28 @@ load_memory(const uint8 **p_buf, const uint8 *buf_end, WASMMemory *memory, uint32 max_page_count = pool_size * APP_MEMORY_MAX_GLOBAL_HEAP_PERCENT / DEFAULT_NUM_BYTES_PER_PAGE; #else - uint32 max_page_count = DEFAULT_MAX_PAGES; + uint32 max_page_count; + bool is_memory64 = false; #endif p_org = p; read_leb_uint32(p, p_end, memory->flags); bh_assert(p - p_org <= 1); (void)p_org; -#if WASM_ENABLE_SHARED_MEMORY == 0 - bh_assert(memory->flags <= 1); -#else - bh_assert(memory->flags <= 3 && memory->flags != 2); + bh_assert(check_memory_flag(memory->flags)); + +#if WASM_ENABLE_APP_FRAMEWORK == 0 + is_memory64 = memory->flags & MEMORY64_FLAG; + max_page_count = is_memory64 ? DEFAULT_MEM64_MAX_PAGES : DEFAULT_MAX_PAGES; #endif read_leb_uint32(p, p_end, memory->init_page_count); - bh_assert(memory->init_page_count <= 65536); + bh_assert(memory->init_page_count <= max_page_count); if (memory->flags & 1) { read_leb_uint32(p, p_end, memory->max_page_count); bh_assert(memory->init_page_count <= memory->max_page_count); - bh_assert(memory->max_page_count <= 65536); + bh_assert(memory->max_page_count <= max_page_count); if (memory->max_page_count > max_page_count) memory->max_page_count = max_page_count; } @@ -899,6 +898,7 @@ load_memory(const uint8 **p_buf, const uint8 *buf_end, WASMMemory *memory, memory->num_bytes_per_page = DEFAULT_NUM_BYTES_PER_PAGE; *p_buf = p; + (void)check_memory_flag; return true; } @@ -1008,7 +1008,7 @@ load_import_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, /* load module name */ read_leb_uint32(p, p_end, name_len); CHECK_BUF(p, p_end, name_len); - if (!(sub_module_name = const_str_list_insert( + if (!(sub_module_name = wasm_const_str_list_insert( p, name_len, module, is_load_from_file_buf, error_buf, error_buf_size))) { return false; @@ -1018,7 +1018,7 @@ load_import_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, /* load field name */ read_leb_uint32(p, p_end, name_len); CHECK_BUF(p, p_end, name_len); - if (!(field_name = const_str_list_insert( + if (!(field_name = wasm_const_str_list_insert( p, name_len, module, is_load_from_file_buf, error_buf, error_buf_size))) { return false; @@ -1426,7 +1426,7 @@ load_export_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, && memcmp(name, p, str_len) == 0)); } - if (!(export->name = const_str_list_insert( + if (!(export->name = wasm_const_str_list_insert( p, str_len, module, is_load_from_file_buf, error_buf, error_buf_size))) { return false; @@ -1761,6 +1761,7 @@ load_data_segment_section(const uint8 *buf, const uint8 *buf_end, bool is_passive = false; uint32 mem_flag; #endif + uint8 mem_offset_type; read_leb_uint32(p, p_end, data_seg_count); @@ -1807,11 +1808,35 @@ load_data_segment_section(const uint8 *buf, const uint8 *buf_end, < module->import_memory_count + module->memory_count); #endif /* WASM_ENABLE_BULK_MEMORY */ +#if WASM_ENABLE_BULK_MEMORY != 0 + if (!is_passive) +#endif /* WASM_ENABLE_BULK_MEMORY */ + { +#if WASM_ENABLE_MEMORY64 != 0 + /* This memory_flag is from memory instead of data segment */ + uint8 memory_flag; + if (module->import_memory_count > 0) { + memory_flag = + module->import_memories[mem_index].u.memory.flags; + } + else { + memory_flag = + module + ->memories[mem_index - module->import_memory_count] + .flags; + } + mem_offset_type = memory_flag & MEMORY64_FLAG ? VALUE_TYPE_I64 + : VALUE_TYPE_I32; +#else + mem_offset_type = VALUE_TYPE_I32; +#endif /* WASM_ENABLE_MEMORY64 */ + } + #if WASM_ENABLE_BULK_MEMORY != 0 if (!is_passive) #endif if (!load_init_expr(module, &p, p_end, &init_expr, - VALUE_TYPE_I32, error_buf, error_buf_size)) + mem_offset_type, error_buf, error_buf_size)) return false; read_leb_uint32(p, p_end, data_seg_len); @@ -1957,7 +1982,7 @@ handle_name_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, func_index -= module->import_function_count; bh_assert(func_index < module->function_count); if (!(module->functions[func_index]->field_name = - const_str_list_insert( + wasm_const_str_list_insert( p, func_name_len, module, is_load_from_file_buf, error_buf, error_buf_size))) { @@ -1999,7 +2024,7 @@ load_user_section(const uint8 *buf, const uint8 *buf_end, WASMModule *module, bh_assert(name_len > 0 && p + name_len <= p_end); #if WASM_ENABLE_CUSTOM_NAME_SECTION != 0 - if (memcmp(p, "name", 4) == 0) { + if (name_len == 4 && memcmp(p, "name", 4) == 0) { p += name_len; handle_name_section(p, p_end, module, is_load_from_file_buf, error_buf, error_buf_size); @@ -2542,8 +2567,9 @@ load_from_sections(WASMModule *module, WASMSection *sections, *buf_func = NULL, *buf_func_end = NULL; WASMGlobal *aux_data_end_global = NULL, *aux_heap_base_global = NULL; WASMGlobal *aux_stack_top_global = NULL, *global; - uint32 aux_data_end = (uint32)-1, aux_heap_base = (uint32)-1; - uint32 aux_stack_top = (uint32)-1, global_index, func_index, i; + uint64 aux_data_end = (uint64)-1LL, aux_heap_base = (uint64)-1LL, + aux_stack_top = (uint64)-1LL; + uint32 global_index, func_index, i; uint32 aux_data_end_global_index = (uint32)-1; uint32 aux_heap_base_global_index = (uint32)-1; WASMFuncType *func_type; @@ -2661,9 +2687,9 @@ load_from_sections(WASMModule *module, WASMSection *sections, && global->init_expr.init_expr_type == INIT_EXPR_TYPE_I32_CONST) { aux_heap_base_global = global; - aux_heap_base = global->init_expr.u.i32; + aux_heap_base = (uint64)(uint32)global->init_expr.u.i32; aux_heap_base_global_index = export->index; - LOG_VERBOSE("Found aux __heap_base global, value: %d", + LOG_VERBOSE("Found aux __heap_base global, value: %" PRIu64, aux_heap_base); } } @@ -2674,12 +2700,11 @@ load_from_sections(WASMModule *module, WASMSection *sections, && global->init_expr.init_expr_type == INIT_EXPR_TYPE_I32_CONST) { aux_data_end_global = global; - aux_data_end = global->init_expr.u.i32; + aux_data_end = (uint64)(uint32)global->init_expr.u.i32; aux_data_end_global_index = export->index; - LOG_VERBOSE("Found aux __data_end global, value: %d", + LOG_VERBOSE("Found aux __data_end global, value: %" PRIu64, aux_data_end); - - aux_data_end = align_uint(aux_data_end, 16); + aux_data_end = align_uint64(aux_data_end, 16); } } @@ -2715,20 +2740,22 @@ load_from_sections(WASMModule *module, WASMSection *sections, && global->type == VALUE_TYPE_I32 && global->init_expr.init_expr_type == INIT_EXPR_TYPE_I32_CONST - && (uint32)global->init_expr.u.i32 <= aux_heap_base) { + && (uint64)(uint32)global->init_expr.u.i32 + <= aux_heap_base) { aux_stack_top_global = global; - aux_stack_top = (uint32)global->init_expr.u.i32; + aux_stack_top = (uint64)(uint32)global->init_expr.u.i32; module->aux_stack_top_global_index = module->import_global_count + global_index; module->aux_stack_bottom = aux_stack_top; module->aux_stack_size = aux_stack_top > aux_data_end - ? aux_stack_top - aux_data_end - : aux_stack_top; - LOG_VERBOSE("Found aux stack top global, value: %d, " - "global index: %d, stack size: %d", - aux_stack_top, global_index, - module->aux_stack_size); + ? (uint32)(aux_stack_top - aux_data_end) + : (uint32)aux_stack_top; + LOG_VERBOSE( + "Found aux stack top global, value: %" PRIu64 ", " + "global index: %d, stack size: %d", + aux_stack_top, global_index, + module->aux_stack_size); break; } } @@ -2862,60 +2889,62 @@ load_from_sections(WASMModule *module, WASMSection *sections, if (aux_data_end_global && aux_heap_base_global && aux_stack_top_global) { uint64 init_memory_size; - uint32 shrunk_memory_size = align_uint(aux_heap_base, 8); + uint64 shrunk_memory_size = align_uint64(aux_heap_base, 8); - if (module->import_memory_count) { - memory_import = &module->import_memories[0].u.memory; - init_memory_size = (uint64)memory_import->num_bytes_per_page - * memory_import->init_page_count; - if (shrunk_memory_size <= init_memory_size) { - /* Reset memory info to decrease memory usage */ - memory_import->num_bytes_per_page = shrunk_memory_size; - memory_import->init_page_count = 1; - LOG_VERBOSE("Shrink import memory size to %d", - shrunk_memory_size); + /* Only resize(shrunk) the memory size if num_bytes_per_page is in + * valid range of uint32 */ + if (shrunk_memory_size <= UINT32_MAX) { + if (module->import_memory_count) { + memory_import = &module->import_memories[0].u.memory; + init_memory_size = (uint64)memory_import->num_bytes_per_page + * memory_import->init_page_count; + if (shrunk_memory_size <= init_memory_size) { + /* Reset memory info to decrease memory usage */ + memory_import->num_bytes_per_page = shrunk_memory_size; + memory_import->init_page_count = 1; + LOG_VERBOSE("Shrink import memory size to %" PRIu64, + shrunk_memory_size); + } } - } - if (module->memory_count) { - memory = &module->memories[0]; - init_memory_size = (uint64)memory->num_bytes_per_page - * memory->init_page_count; - if (shrunk_memory_size <= init_memory_size) { - /* Reset memory info to decrease memory usage */ - memory->num_bytes_per_page = shrunk_memory_size; - memory->init_page_count = 1; - LOG_VERBOSE("Shrink memory size to %d", shrunk_memory_size); + + if (module->memory_count) { + memory = &module->memories[0]; + init_memory_size = (uint64)memory->num_bytes_per_page + * memory->init_page_count; + if (shrunk_memory_size <= init_memory_size) { + /* Reset memory info to decrease memory usage */ + memory->num_bytes_per_page = shrunk_memory_size; + memory->init_page_count = 1; + LOG_VERBOSE("Shrink memory size to %" PRIu64, + shrunk_memory_size); + } } } } if (module->import_memory_count) { memory_import = &module->import_memories[0].u.memory; - if (memory_import->init_page_count < DEFAULT_MAX_PAGES) + if (memory_import->init_page_count < DEFAULT_MAX_PAGES) { memory_import->num_bytes_per_page *= memory_import->init_page_count; - else - memory_import->num_bytes_per_page = UINT32_MAX; - - if (memory_import->init_page_count > 0) - memory_import->init_page_count = memory_import->max_page_count = - 1; - else - memory_import->init_page_count = memory_import->max_page_count = - 0; + if (memory_import->init_page_count > 0) + memory_import->init_page_count = + memory_import->max_page_count = 1; + else + memory_import->init_page_count = + memory_import->max_page_count = 0; + } } if (module->memory_count) { memory = &module->memories[0]; - if (memory->init_page_count < DEFAULT_MAX_PAGES) + if (memory->init_page_count < DEFAULT_MAX_PAGES) { memory->num_bytes_per_page *= memory->init_page_count; - else - memory->num_bytes_per_page = UINT32_MAX; - - if (memory->init_page_count > 0) - memory->init_page_count = memory->max_page_count = 1; - else - memory->init_page_count = memory->max_page_count = 0; + if (memory->init_page_count > 0) + memory->init_page_count = memory->max_page_count = 1; + else + memory->init_page_count = memory->max_page_count = 0; + } } } @@ -2965,7 +2994,7 @@ load_from_sections(WASMModule *module, WASMSection *sections, } static WASMModule * -create_module(char *error_buf, uint32 error_buf_size) +create_module(char *name, char *error_buf, uint32 error_buf_size) { WASMModule *module = loader_malloc(sizeof(WASMModule), error_buf, error_buf_size); @@ -2980,6 +3009,8 @@ create_module(char *error_buf, uint32 error_buf_size) /* Set start_function to -1, means no start function */ module->start_function = (uint32)-1; + module->name = name; + #if WASM_ENABLE_FAST_INTERP == 0 module->br_table_cache_list = &module->br_table_cache_list_head; ret = bh_list_init(module->br_table_cache_list); @@ -3004,7 +3035,7 @@ WASMModule * wasm_loader_load_from_sections(WASMSection *section_list, char *error_buf, uint32 error_buf_size) { - WASMModule *module = create_module(error_buf, error_buf_size); + WASMModule *module = create_module("", error_buf, error_buf_size); if (!module) return NULL; @@ -3175,10 +3206,10 @@ load(const uint8 *buf, uint32 size, WASMModule *module, char *error_buf, } WASMModule * -wasm_loader_load(uint8 *buf, uint32 size, char *error_buf, +wasm_loader_load(uint8 *buf, uint32 size, const LoadArgs *args, char *error_buf, uint32 error_buf_size) { - WASMModule *module = create_module(error_buf, error_buf_size); + WASMModule *module = create_module(args->name, error_buf, error_buf_size); if (!module) { return NULL; } @@ -3584,8 +3615,8 @@ wasm_loader_find_block_addr(WASMExecEnv *exec_env, BlockAddr *block_addr_cache, case WASM_OP_I64_STORE8: case WASM_OP_I64_STORE16: case WASM_OP_I64_STORE32: - skip_leb_uint32(p, p_end); /* align */ - skip_leb_uint32(p, p_end); /* offset */ + skip_leb_uint32(p, p_end); /* align */ + skip_leb_mem_offset(p, p_end); /* offset */ break; case WASM_OP_MEMORY_SIZE: @@ -3800,6 +3831,7 @@ wasm_loader_find_block_addr(WASMExecEnv *exec_env, BlockAddr *block_addr_cache, #if WASM_ENABLE_SHARED_MEMORY != 0 case WASM_OP_ATOMIC_PREFIX: { + /* TODO: memory64 offset type changes */ uint32 opcode1; /* atomic_op (u32_leb) + memarg (2 u32_leb) */ @@ -3809,8 +3841,8 @@ wasm_loader_find_block_addr(WASMExecEnv *exec_env, BlockAddr *block_addr_cache, opcode = (uint8)opcode1; if (opcode != WASM_OP_ATOMIC_FENCE) { - skip_leb_uint32(p, p_end); /* align */ - skip_leb_uint32(p, p_end); /* offset */ + skip_leb_uint32(p, p_end); /* align */ + skip_leb_mem_offset(p, p_end); /* offset */ } else { /* atomic.fence doesn't have memarg */ @@ -4312,11 +4344,11 @@ wasm_loader_pop_frame_csp(WASMLoaderContext *ctx, char *error_buf, wasm_loader_emit_ptr(loader_ctx, NULL); \ } while (0) -#define emit_br_info(frame_csp) \ - do { \ - if (!wasm_loader_emit_br_info(loader_ctx, frame_csp, error_buf, \ - error_buf_size)) \ - goto fail; \ +#define emit_br_info(frame_csp, is_br) \ + do { \ + if (!wasm_loader_emit_br_info(loader_ctx, frame_csp, is_br, error_buf, \ + error_buf_size)) \ + goto fail; \ } while (0) #define LAST_OP_OUTPUT_I32() \ @@ -4701,7 +4733,7 @@ apply_label_patch(WASMLoaderContext *ctx, uint8 depth, uint8 patch_type) static bool wasm_loader_emit_br_info(WASMLoaderContext *ctx, BranchBlock *frame_csp, - char *error_buf, uint32 error_buf_size) + bool is_br, char *error_buf, uint32 error_buf_size) { /* br info layout: * a) arity of target block @@ -4750,6 +4782,8 @@ wasm_loader_emit_br_info(WASMLoaderContext *ctx, BranchBlock *frame_csp, /* Part e */ dynamic_offset = frame_csp->dynamic_offset + wasm_get_cell_num(types, arity); + if (is_br) + ctx->dynamic_offset = dynamic_offset; for (i = (int32)arity - 1; i >= 0; i--) { cell = (uint8)wasm_value_type_cell_num(types[i]); dynamic_offset -= cell; @@ -5125,6 +5159,11 @@ fail: goto fail; \ } while (0) +#define PUSH_MEM_OFFSET() PUSH_OFFSET_TYPE(mem_offset_type) +#define PUSH_PAGE_COUNT() PUSH_MEM_OFFSET() + +#define POP_MEM_OFFSET() POP_OFFSET_TYPE(mem_offset_type) + #define POP_AND_PUSH(type_pop, type_push) \ do { \ if (!(wasm_loader_push_pop_frame_ref_offset( \ @@ -5179,6 +5218,15 @@ fail: goto fail; \ } while (0) +#define PUSH_MEM_OFFSET() \ + do { \ + if (!(wasm_loader_push_frame_ref(loader_ctx, mem_offset_type, \ + error_buf, error_buf_size))) \ + goto fail; \ + } while (0) + +#define PUSH_PAGE_COUNT() PUSH_MEM_OFFSET() + #define POP_I32() \ do { \ if (!(wasm_loader_pop_frame_ref(loader_ctx, VALUE_TYPE_I32, error_buf, \ @@ -5214,6 +5262,13 @@ fail: goto fail; \ } while (0) +#define POP_MEM_OFFSET() \ + do { \ + if (!(wasm_loader_pop_frame_ref(loader_ctx, mem_offset_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, \ @@ -5428,20 +5483,13 @@ 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); \ } while (0) static bool -wasm_loader_check_br(WASMLoaderContext *loader_ctx, uint32 depth, +wasm_loader_check_br(WASMLoaderContext *loader_ctx, uint32 depth, uint8 opcode, char *error_buf, uint32 error_buf_size) { BranchBlock *target_block, *cur_block; @@ -5451,6 +5499,20 @@ wasm_loader_check_br(WASMLoaderContext *loader_ctx, uint32 depth, int32 i, available_stack_cell; uint16 cell_num; + 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, @@ -5482,6 +5544,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 (opcode == WASM_OP_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; @@ -5490,7 +5584,41 @@ 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, opcode == WASM_OP_BR); +#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 (opcode == WASM_OP_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 + 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 = @@ -5499,33 +5627,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, opcode == WASM_OP_BR); +#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_buf); +#endif + + return ret; } static BranchBlock * check_branch_block(WASMLoaderContext *loader_ctx, uint8 **p_buf, uint8 *buf_end, - char *error_buf, uint32 error_buf_size) + uint8 opcode, 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, opcode, 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; @@ -5737,10 +5879,11 @@ wasm_loader_prepare_bytecode(WASMModule *module, WASMFunction *func, { uint8 *p = func->code, *p_end = func->code + func->code_size, *p_org; uint32 param_count, local_count, global_count; - uint8 *param_types, *local_types, local_type, global_type; + uint8 *param_types, *local_types, local_type, global_type, mem_offset_type; BlockType func_block_type; uint16 *local_offsets, local_offset; - uint32 count, local_idx, global_idx, u32, align, mem_offset, i; + uint32 count, local_idx, global_idx, u32, align, i; + mem_offset_t mem_offset; int32 i32, i32_const = 0; int64 i64_const; uint8 opcode, u8; @@ -5762,6 +5905,19 @@ wasm_loader_prepare_bytecode(WASMModule *module, WASMFunction *func, LOG_OP("\nProcessing func | [%d] params | [%d] locals | [%d] return\n", func->param_cell_num, func->local_cell_num, func->ret_cell_num); #endif +#if WASM_ENABLE_MEMORY64 != 0 + bool is_memory64 = false; + /* TODO: multi-memories for now assuming the memory idx type is consistent + * across multi-memories */ + if (module->import_memory_count > 0) + is_memory64 = module->import_memories[0].u.memory.flags & MEMORY64_FLAG; + else if (module->memory_count > 0) + is_memory64 = module->memories[0].flags & MEMORY64_FLAG; + + mem_offset_type = is_memory64 ? VALUE_TYPE_I64 : VALUE_TYPE_I32; +#else + mem_offset_type = VALUE_TYPE_I32; +#endif global_count = module->import_global_count + module->global_count; @@ -5931,8 +6087,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; } } @@ -6136,8 +6299,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, opcode, + error_buf, error_buf_size))) goto fail; RESET_STACK(); @@ -6149,8 +6313,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, opcode, + error_buf, error_buf_size))) goto fail; break; @@ -6179,7 +6344,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, opcode, error_buf, error_buf_size))) goto fail; @@ -7061,8 +7226,8 @@ re_scan: } #endif CHECK_MEMORY(); - read_leb_uint32(p, p_end, align); /* align */ - read_leb_uint32(p, p_end, mem_offset); /* offset */ + read_leb_uint32(p, p_end, align); /* align */ + read_leb_mem_offset(p, p_end, mem_offset); /* offset */ #if WASM_ENABLE_FAST_INTERP != 0 emit_uint32(loader_ctx, mem_offset); #endif @@ -7076,7 +7241,7 @@ re_scan: case WASM_OP_I32_LOAD8_U: case WASM_OP_I32_LOAD16_S: case WASM_OP_I32_LOAD16_U: - POP_AND_PUSH(VALUE_TYPE_I32, VALUE_TYPE_I32); + POP_AND_PUSH(mem_offset_type, VALUE_TYPE_I32); break; case WASM_OP_I64_LOAD: case WASM_OP_I64_LOAD8_S: @@ -7085,35 +7250,35 @@ re_scan: case WASM_OP_I64_LOAD16_U: case WASM_OP_I64_LOAD32_S: case WASM_OP_I64_LOAD32_U: - POP_AND_PUSH(VALUE_TYPE_I32, VALUE_TYPE_I64); + POP_AND_PUSH(mem_offset_type, VALUE_TYPE_I64); break; case WASM_OP_F32_LOAD: - POP_AND_PUSH(VALUE_TYPE_I32, VALUE_TYPE_F32); + POP_AND_PUSH(mem_offset_type, VALUE_TYPE_F32); break; case WASM_OP_F64_LOAD: - POP_AND_PUSH(VALUE_TYPE_I32, VALUE_TYPE_F64); + POP_AND_PUSH(mem_offset_type, VALUE_TYPE_F64); break; /* store */ case WASM_OP_I32_STORE: case WASM_OP_I32_STORE8: case WASM_OP_I32_STORE16: POP_I32(); - POP_I32(); + POP_MEM_OFFSET(); break; case WASM_OP_I64_STORE: case WASM_OP_I64_STORE8: case WASM_OP_I64_STORE16: case WASM_OP_I64_STORE32: POP_I64(); - POP_I32(); + POP_MEM_OFFSET(); break; case WASM_OP_F32_STORE: POP_F32(); - POP_I32(); + POP_MEM_OFFSET(); break; case WASM_OP_F64_STORE: POP_F64(); - POP_I32(); + POP_MEM_OFFSET(); break; default: break; @@ -7126,7 +7291,7 @@ re_scan: /* reserved byte 0x00 */ bh_assert(*p == 0x00); p++; - PUSH_I32(); + PUSH_PAGE_COUNT(); module->possible_memory_grow = true; #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 @@ -7139,7 +7304,7 @@ re_scan: /* reserved byte 0x00 */ bh_assert(*p == 0x00); p++; - POP_AND_PUSH(VALUE_TYPE_I32, VALUE_TYPE_I32); + POP_AND_PUSH(mem_offset_type, mem_offset_type); module->possible_memory_grow = true; #if WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0 \ @@ -7186,6 +7351,7 @@ re_scan: break; case WASM_OP_F32_CONST: + CHECK_BUF(p, p_end, sizeof(float32)); p += sizeof(float32); #if WASM_ENABLE_FAST_INTERP != 0 skip_label(); @@ -7204,6 +7370,7 @@ re_scan: break; case WASM_OP_F64_CONST: + CHECK_BUF(p, p_end, sizeof(float64)); p += sizeof(float64); #if WASM_ENABLE_FAST_INTERP != 0 skip_label(); @@ -7490,7 +7657,7 @@ re_scan: POP_I32(); POP_I32(); - POP_I32(); + POP_MEM_OFFSET(); #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 func->has_memory_operations = true; #endif @@ -7511,6 +7678,7 @@ re_scan: } case WASM_OP_MEMORY_COPY: { + CHECK_BUF(p, p_end, sizeof(int16)); /* both src and dst memory index should be 0 */ bh_assert(*(int16 *)p == 0x0000); p += 2; @@ -7519,9 +7687,9 @@ re_scan: + module->memory_count > 0); - POP_I32(); - POP_I32(); - POP_I32(); + POP_MEM_OFFSET(); + POP_MEM_OFFSET(); + POP_MEM_OFFSET(); #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 func->has_memory_operations = true; #endif @@ -7536,9 +7704,9 @@ re_scan: + module->memory_count > 0); + POP_MEM_OFFSET(); POP_I32(); - POP_I32(); - POP_I32(); + POP_MEM_OFFSET(); #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 func->has_memory_operations = true; #endif @@ -7702,8 +7870,8 @@ re_scan: #endif if (opcode1 != WASM_OP_ATOMIC_FENCE) { CHECK_MEMORY(); - read_leb_uint32(p, p_end, align); /* align */ - read_leb_uint32(p, p_end, mem_offset); /* offset */ + read_leb_uint32(p, p_end, align); /* align */ + read_leb_mem_offset(p, p_end, mem_offset); /* offset */ #if WASM_ENABLE_FAST_INTERP != 0 emit_uint32(loader_ctx, mem_offset); #endif @@ -7713,18 +7881,20 @@ re_scan: #endif switch (opcode1) { case WASM_OP_ATOMIC_NOTIFY: - POP2_AND_PUSH(VALUE_TYPE_I32, VALUE_TYPE_I32); + POP_I32(); + POP_MEM_OFFSET(); + PUSH_I32(); break; case WASM_OP_ATOMIC_WAIT32: POP_I64(); POP_I32(); - POP_I32(); + POP_MEM_OFFSET(); PUSH_I32(); break; case WASM_OP_ATOMIC_WAIT64: POP_I64(); POP_I64(); - POP_I32(); + POP_MEM_OFFSET(); PUSH_I32(); break; case WASM_OP_ATOMIC_FENCE: @@ -7735,26 +7905,26 @@ re_scan: case WASM_OP_ATOMIC_I32_LOAD: case WASM_OP_ATOMIC_I32_LOAD8_U: case WASM_OP_ATOMIC_I32_LOAD16_U: - POP_AND_PUSH(VALUE_TYPE_I32, VALUE_TYPE_I32); + POP_AND_PUSH(mem_offset_type, VALUE_TYPE_I32); break; case WASM_OP_ATOMIC_I32_STORE: case WASM_OP_ATOMIC_I32_STORE8: case WASM_OP_ATOMIC_I32_STORE16: POP_I32(); - POP_I32(); + POP_MEM_OFFSET(); break; case WASM_OP_ATOMIC_I64_LOAD: case WASM_OP_ATOMIC_I64_LOAD8_U: case WASM_OP_ATOMIC_I64_LOAD16_U: case WASM_OP_ATOMIC_I64_LOAD32_U: - POP_AND_PUSH(VALUE_TYPE_I32, VALUE_TYPE_I64); + POP_AND_PUSH(mem_offset_type, VALUE_TYPE_I64); break; case WASM_OP_ATOMIC_I64_STORE: case WASM_OP_ATOMIC_I64_STORE8: case WASM_OP_ATOMIC_I64_STORE16: case WASM_OP_ATOMIC_I64_STORE32: POP_I64(); - POP_I32(); + POP_MEM_OFFSET(); break; case WASM_OP_ATOMIC_RMW_I32_ADD: case WASM_OP_ATOMIC_RMW_I32_ADD8_U: @@ -7774,7 +7944,9 @@ re_scan: case WASM_OP_ATOMIC_RMW_I32_XCHG: case WASM_OP_ATOMIC_RMW_I32_XCHG8_U: case WASM_OP_ATOMIC_RMW_I32_XCHG16_U: - POP2_AND_PUSH(VALUE_TYPE_I32, VALUE_TYPE_I32); + POP_I32(); + POP_MEM_OFFSET(); + PUSH_I32(); break; case WASM_OP_ATOMIC_RMW_I64_ADD: case WASM_OP_ATOMIC_RMW_I64_ADD8_U: @@ -7801,7 +7973,7 @@ re_scan: case WASM_OP_ATOMIC_RMW_I64_XCHG16_U: case WASM_OP_ATOMIC_RMW_I64_XCHG32_U: POP_I64(); - POP_I32(); + POP_MEM_OFFSET(); PUSH_I64(); break; case WASM_OP_ATOMIC_RMW_I32_CMPXCHG: @@ -7809,7 +7981,7 @@ re_scan: case WASM_OP_ATOMIC_RMW_I32_CMPXCHG16_U: POP_I32(); POP_I32(); - POP_I32(); + POP_MEM_OFFSET(); PUSH_I32(); break; case WASM_OP_ATOMIC_RMW_I64_CMPXCHG: @@ -7818,7 +7990,7 @@ re_scan: case WASM_OP_ATOMIC_RMW_I64_CMPXCHG32_U: POP_I64(); POP_I64(); - POP_I32(); + POP_MEM_OFFSET(); PUSH_I64(); break; default: diff --git a/core/iwasm/interpreter/wasm_opcode.h b/core/iwasm/interpreter/wasm_opcode.h index 98e5b1325..db5e5e40b 100644 --- a/core/iwasm/interpreter/wasm_opcode.h +++ b/core/iwasm/interpreter/wasm_opcode.h @@ -593,8 +593,8 @@ typedef enum WASMSimdEXTOpcode { /* placeholder = 0xa2 */ SIMD_i32x4_all_true = 0xa3, SIMD_i32x4_bitmask = 0xa4, - SIMD_i32x4_narrow_i64x2_s = 0xa5, - SIMD_i32x4_narrow_i64x2_u = 0xa6, + /* placeholder = 0xa5 */ + /* placeholder = 0xa6 */ SIMD_i32x4_extend_low_i16x8_s = 0xa7, SIMD_i32x4_extend_high_i16x8_s = 0xa8, SIMD_i32x4_extend_low_i16x8_u = 0xa9, @@ -603,19 +603,19 @@ typedef enum WASMSimdEXTOpcode { SIMD_i32x4_shr_s = 0xac, SIMD_i32x4_shr_u = 0xad, SIMD_i32x4_add = 0xae, - SIMD_i32x4_add_sat_s = 0xaf, - SIMD_i32x4_add_sat_u = 0xb0, + /* placeholder = 0xaf */ + /* placeholder = 0xb0 */ SIMD_i32x4_sub = 0xb1, - SIMD_i32x4_sub_sat_s = 0xb2, - SIMD_i32x4_sub_sat_u = 0xb3, - /* placeholder = 0xb4 */ + /* placeholder = 0xb2 */ + /* placeholder = 0xb3 */ + /* placeholder = 0xb4 */ SIMD_i32x4_mul = 0xb5, SIMD_i32x4_min_s = 0xb6, SIMD_i32x4_min_u = 0xb7, SIMD_i32x4_max_s = 0xb8, SIMD_i32x4_max_u = 0xb9, SIMD_i32x4_dot_i16x8_s = 0xba, - SIMD_i32x4_avgr_u = 0xbb, + /* placeholder = 0xbb */ SIMD_i32x4_extmul_low_i16x8_s = 0xbc, SIMD_i32x4_extmul_high_i16x8_s = 0xbd, SIMD_i32x4_extmul_low_i16x8_u = 0xbe, @@ -658,7 +658,7 @@ typedef enum WASMSimdEXTOpcode { /* f32x4 operation */ SIMD_f32x4_abs = 0xe0, SIMD_f32x4_neg = 0xe1, - SIMD_f32x4_round = 0xe2, + /* placeholder = 0xe2 */ SIMD_f32x4_sqrt = 0xe3, SIMD_f32x4_add = 0xe4, SIMD_f32x4_sub = 0xe5, @@ -672,7 +672,7 @@ typedef enum WASMSimdEXTOpcode { /* f64x2 operation */ SIMD_f64x2_abs = 0xec, SIMD_f64x2_neg = 0xed, - SIMD_f64x2_round = 0xee, + /* placeholder = 0xee */ SIMD_f64x2_sqrt = 0xef, SIMD_f64x2_add = 0xf0, SIMD_f64x2_sub = 0xf1, diff --git a/core/iwasm/interpreter/wasm_runtime.c b/core/iwasm/interpreter/wasm_runtime.c index a75a204bb..688f1c2c1 100644 --- a/core/iwasm/interpreter/wasm_runtime.c +++ b/core/iwasm/interpreter/wasm_runtime.c @@ -60,13 +60,13 @@ wasm_load(uint8 *buf, uint32 size, #if WASM_ENABLE_MULTI_MODULE != 0 bool main_module, #endif - char *error_buf, uint32 error_buf_size) + const LoadArgs *name, char *error_buf, uint32 error_buf_size) { return wasm_loader_load(buf, size, #if WASM_ENABLE_MULTI_MODULE != 0 main_module, #endif - error_buf, error_buf_size); + name, error_buf, error_buf_size); } WASMModule * @@ -162,15 +162,16 @@ memory_instantiate(WASMModuleInstance *module_inst, WASMModuleInstance *parent, char *error_buf, uint32 error_buf_size) { WASMModule *module = module_inst->module; - uint64 memory_data_size, max_memory_data_size; - uint32 heap_offset = num_bytes_per_page * init_page_count; - uint32 inc_page_count, aux_heap_base, global_idx; + uint32 inc_page_count, global_idx, default_max_page; uint32 bytes_of_last_page, bytes_to_page_end; + uint64 aux_heap_base, + heap_offset = (uint64)num_bytes_per_page * init_page_count; + uint64 memory_data_size, max_memory_data_size; uint8 *global_addr; bool is_shared_memory = false; #if WASM_ENABLE_SHARED_MEMORY != 0 - is_shared_memory = flags & 0x02 ? true : false; + is_shared_memory = flags & SHARED_MEMORY_FLAG ? true : false; /* shared memory */ if (is_shared_memory && parent != NULL) { @@ -185,6 +186,14 @@ memory_instantiate(WASMModuleInstance *module_inst, WASMModuleInstance *parent, (void)flags; #endif /* end of WASM_ENABLE_SHARED_MEMORY */ +#if WASM_ENABLE_MEMORY64 != 0 + if (flags & MEMORY64_FLAG) { + memory->is_memory64 = 1; + } +#endif + default_max_page = + memory->is_memory64 ? DEFAULT_MEM64_MAX_PAGES : DEFAULT_MAX_PAGES; + if (heap_size > 0 && module_inst->module->malloc_function != (uint32)-1 && module_inst->module->free_function != (uint32)-1) { /* Disable app heap, use malloc/free function exported @@ -192,6 +201,16 @@ memory_instantiate(WASMModuleInstance *module_inst, WASMModuleInstance *parent, heap_size = 0; } + /* If initial memory is the largest size allowed, disallowing insert host + * managed heap */ + if (heap_size > 0 + && heap_offset == GET_MAX_LINEAR_MEMORY_SIZE(memory->is_memory64)) { + set_error_buf(error_buf, error_buf_size, + "failed to insert app heap into linear memory, " + "try using `--heap-size=0` option"); + return NULL; + } + if (init_page_count == max_page_count && init_page_count == 1) { /* If only one page and at most one page, we just append the app heap to the end of linear memory, enlarge the @@ -215,7 +234,7 @@ memory_instantiate(WASMModuleInstance *module_inst, WASMModuleInstance *parent, } else if (module->aux_heap_base_global_index != (uint32)-1 && module->aux_heap_base - < num_bytes_per_page * init_page_count) { + < (uint64)num_bytes_per_page * init_page_count) { /* Insert app heap before __heap_base */ aux_heap_base = module->aux_heap_base; bytes_of_last_page = aux_heap_base % num_bytes_per_page; @@ -243,54 +262,58 @@ memory_instantiate(WASMModuleInstance *module_inst, WASMModuleInstance *parent, && global_idx < module_inst->e->global_count); global_addr = module_inst->global_data + module_inst->e->globals[global_idx].data_offset; - *(uint32 *)global_addr = aux_heap_base; - LOG_VERBOSE("Reset __heap_base global to %u", aux_heap_base); +#if WASM_ENABLE_MEMORY64 != 0 + if (memory->is_memory64) { + /* For memory64, the global value should be i64 */ + *(uint64 *)global_addr = aux_heap_base; + } + else +#endif + { + /* For memory32, the global value should be i32 */ + *(uint32 *)global_addr = (uint32)aux_heap_base; + } + LOG_VERBOSE("Reset __heap_base global to %" PRIu64, aux_heap_base); } else { /* Insert app heap before new page */ inc_page_count = (heap_size + num_bytes_per_page - 1) / num_bytes_per_page; - heap_offset = num_bytes_per_page * init_page_count; - heap_size = num_bytes_per_page * inc_page_count; + heap_offset = (uint64)num_bytes_per_page * init_page_count; + heap_size = (uint64)num_bytes_per_page * inc_page_count; if (heap_size > 0) heap_size -= 1 * BH_KB; } init_page_count += inc_page_count; max_page_count += inc_page_count; - if (init_page_count > DEFAULT_MAX_PAGES) { + if (init_page_count > default_max_page) { set_error_buf(error_buf, error_buf_size, "failed to insert app heap into linear memory, " "try using `--heap-size=0` option"); return NULL; } - else if (init_page_count == DEFAULT_MAX_PAGES) { - num_bytes_per_page = UINT32_MAX; - init_page_count = max_page_count = 1; - } - if (max_page_count > DEFAULT_MAX_PAGES) - max_page_count = DEFAULT_MAX_PAGES; - } - else { /* heap_size == 0 */ - if (init_page_count == DEFAULT_MAX_PAGES) { - num_bytes_per_page = UINT32_MAX; - init_page_count = max_page_count = 1; - } + + if (max_page_count > default_max_page) + max_page_count = default_max_page; } LOG_VERBOSE("Memory instantiate:"); LOG_VERBOSE(" page bytes: %u, init pages: %u, max pages: %u", num_bytes_per_page, init_page_count, max_page_count); - LOG_VERBOSE(" heap offset: %u, heap size: %d\n", heap_offset, heap_size); + LOG_VERBOSE(" heap offset: %" PRIu64 ", heap size: %u\n", heap_offset, + heap_size); max_memory_data_size = (uint64)num_bytes_per_page * max_page_count; - bh_assert(max_memory_data_size <= 4 * (uint64)BH_GB); + bh_assert(max_memory_data_size + <= GET_MAX_LINEAR_MEMORY_SIZE(memory->is_memory64)); (void)max_memory_data_size; bh_assert(memory != NULL); if (wasm_allocate_linear_memory(&memory->memory_data, is_shared_memory, - num_bytes_per_page, init_page_count, - max_page_count, &memory_data_size) + memory->is_memory64, 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"); @@ -301,11 +324,11 @@ memory_instantiate(WASMModuleInstance *module_inst, WASMModuleInstance *parent, memory->num_bytes_per_page = num_bytes_per_page; memory->cur_page_count = init_page_count; memory->max_page_count = max_page_count; - memory->memory_data_size = (uint32)memory_data_size; + memory->memory_data_size = memory_data_size; memory->heap_data = memory->memory_data + heap_offset; memory->heap_data_end = memory->heap_data + heap_size; - memory->memory_data_end = memory->memory_data + (uint32)memory_data_size; + memory->memory_data_end = memory->memory_data + memory_data_size; /* Initialize heap */ if (heap_size > 0) { @@ -353,7 +376,8 @@ fail1: static WASMMemoryInstance ** memories_instantiate(const WASMModule *module, WASMModuleInstance *module_inst, WASMModuleInstance *parent, uint32 heap_size, - char *error_buf, uint32 error_buf_size) + uint32 max_memory_pages, char *error_buf, + uint32 error_buf_size) { WASMImport *import; uint32 mem_index = 0, i, @@ -374,7 +398,9 @@ memories_instantiate(const WASMModule *module, WASMModuleInstance *module_inst, for (i = 0; i < module->import_memory_count; i++, import++, memory++) { uint32 num_bytes_per_page = import->u.memory.num_bytes_per_page; uint32 init_page_count = import->u.memory.init_page_count; - uint32 max_page_count = import->u.memory.max_page_count; + uint32 max_page_count = wasm_runtime_get_max_mem( + max_memory_pages, import->u.memory.init_page_count, + import->u.memory.max_page_count); uint32 flags = import->u.memory.flags; uint32 actual_heap_size = heap_size; @@ -412,12 +438,15 @@ memories_instantiate(const WASMModule *module, WASMModuleInstance *module_inst, /* instantiate memories from memory section */ for (i = 0; i < module->memory_count; i++, memory++) { + uint32 max_page_count = wasm_runtime_get_max_mem( + max_memory_pages, module->memories[i].init_page_count, + module->memories[i].max_page_count); if (!(memories[mem_index] = memory_instantiate( module_inst, parent, memory, mem_index, module->memories[i].num_bytes_per_page, - module->memories[i].init_page_count, - module->memories[i].max_page_count, heap_size, - module->memories[i].flags, error_buf, error_buf_size))) { + module->memories[i].init_page_count, max_page_count, + heap_size, module->memories[i].flags, error_buf, + error_buf_size))) { memories_deinstantiate(module_inst, memories, memory_count); return NULL; } @@ -650,7 +679,7 @@ functions_instantiate(const WASMModule *module, WASMModuleInstance *module_inst, if (function->import_module_inst) { function->import_func_inst = wasm_lookup_function(function->import_module_inst, - import->u.function.field_name, NULL); + import->u.function.field_name); } } #endif /* WASM_ENABLE_MULTI_MODULE */ @@ -1214,7 +1243,7 @@ lookup_post_instantiate_func(WASMModuleInstance *module_inst, WASMFunctionInstance *func; WASMFuncType *func_type; - if (!(func = wasm_lookup_function(module_inst, func_name, NULL))) + if (!(func = wasm_lookup_function(module_inst, func_name))) /* Not found */ return NULL; @@ -1934,13 +1963,15 @@ wasm_set_running_mode(WASMModuleInstance *module_inst, RunningMode running_mode) WASMModuleInstance * wasm_instantiate(WASMModule *module, WASMModuleInstance *parent, WASMExecEnv *exec_env_main, uint32 stack_size, - uint32 heap_size, char *error_buf, uint32 error_buf_size) + uint32 heap_size, uint32 max_memory_pages, char *error_buf, + uint32 error_buf_size) { WASMModuleInstance *module_inst; WASMGlobalInstance *globals = NULL, *global; WASMTableInstance *first_table; uint32 global_count, i; - uint32 base_offset, length, extra_info_offset; + uint32 length, extra_info_offset; + mem_offset_t base_offset; uint32 module_inst_struct_size = offsetof(WASMModuleInstance, global_table_data.bytes); uint64 module_inst_mem_inst_size; @@ -2022,7 +2053,7 @@ wasm_instantiate(WASMModule *module, WASMModuleInstance *parent, &module_inst->e->sub_module_inst_list_head; ret = wasm_runtime_sub_module_instantiate( (WASMModuleCommon *)module, (WASMModuleInstanceCommon *)module_inst, - stack_size, heap_size, error_buf, error_buf_size); + stack_size, heap_size, max_memory_pages, error_buf, error_buf_size); if (!ret) { LOG_DEBUG("build a sub module list failed"); goto fail; @@ -2131,9 +2162,9 @@ wasm_instantiate(WASMModule *module, WASMModuleInstance *parent, /* Instantiate memories/tables/functions/tags */ if ((module_inst->memory_count > 0 - && !(module_inst->memories = - memories_instantiate(module, module_inst, parent, heap_size, - error_buf, error_buf_size))) + && !(module_inst->memories = memories_instantiate( + module, module_inst, parent, heap_size, max_memory_pages, + error_buf, error_buf_size))) || (module_inst->table_count > 0 && !(module_inst->tables = tables_instantiate(module, module_inst, first_table, @@ -2298,10 +2329,12 @@ wasm_instantiate(WASMModule *module, WASMModuleInstance *parent, (uint64)memory->num_bytes_per_page * memory->cur_page_count; bh_assert(memory_data || memory_size == 0); - bh_assert(data_seg->base_offset.init_expr_type - == INIT_EXPR_TYPE_I32_CONST - || data_seg->base_offset.init_expr_type - == INIT_EXPR_TYPE_GET_GLOBAL); + bh_assert( + data_seg->base_offset.init_expr_type == INIT_EXPR_TYPE_GET_GLOBAL + || (data_seg->base_offset.init_expr_type == INIT_EXPR_TYPE_I32_CONST + && !memory->is_memory64) + || (data_seg->base_offset.init_expr_type == INIT_EXPR_TYPE_I64_CONST + && memory->is_memory64)); if (data_seg->base_offset.init_expr_type == INIT_EXPR_TYPE_GET_GLOBAL) { if (!check_global_init_expr(module, @@ -2312,23 +2345,48 @@ wasm_instantiate(WASMModule *module, WASMModuleInstance *parent, if (!globals || globals[data_seg->base_offset.u.global_index].type - != VALUE_TYPE_I32) { + != (memory->is_memory64 ? VALUE_TYPE_I64 + : VALUE_TYPE_I32)) { set_error_buf(error_buf, error_buf_size, "data segment does not fit"); goto fail; } - base_offset = - globals[data_seg->base_offset.u.global_index].initial_value.i32; +#if WASM_ENABLE_MEMORY64 != 0 + if (memory->is_memory64) { + base_offset = + (uint64)globals[data_seg->base_offset.u.global_index] + .initial_value.i64; + } + else +#endif + { + base_offset = + (uint32)globals[data_seg->base_offset.u.global_index] + .initial_value.i32; + } } else { - base_offset = (uint32)data_seg->base_offset.u.i32; +#if WASM_ENABLE_MEMORY64 != 0 + if (memory->is_memory64) { + base_offset = (uint64)data_seg->base_offset.u.i64; + } + else +#endif + { + base_offset = (uint32)data_seg->base_offset.u.i32; + } } /* check offset */ if (base_offset > memory_size) { - LOG_DEBUG("base_offset(%d) > memory_size(%d)", base_offset, +#if WASM_ENABLE_MEMORY64 != 0 + LOG_DEBUG("base_offset(%" PRIu64 ") > memory_size(%" PRIu64 ")", + base_offset, memory_size); +#else + LOG_DEBUG("base_offset(%u) > memory_size(%" PRIu64 ")", base_offset, memory_size); +#endif #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 set_error_buf(error_buf, error_buf_size, "out of bounds memory access"); @@ -2342,8 +2400,14 @@ wasm_instantiate(WASMModule *module, WASMModuleInstance *parent, /* check offset + length(could be zero) */ length = data_seg->data_length; if ((uint64)base_offset + length > memory_size) { - LOG_DEBUG("base_offset(%d) + length(%d) > memory_size(%d)", +#if WASM_ENABLE_MEMORY64 != 0 + LOG_DEBUG("base_offset(%" PRIu64 + ") + length(%d) > memory_size(%" PRIu64 ")", base_offset, length, memory_size); +#else + LOG_DEBUG("base_offset(%u) + length(%d) > memory_size(%" PRIu64 ")", + base_offset, length, memory_size); +#endif #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 set_error_buf(error_buf, error_buf_size, "out of bounds memory access"); @@ -2960,8 +3024,8 @@ wasm_deinstantiate(WASMModuleInstance *module_inst, bool is_sub_inst) } #endif - if (module_inst->e->common.c_api_func_imports) - wasm_runtime_free(module_inst->e->common.c_api_func_imports); + if (module_inst->c_api_func_imports) + wasm_runtime_free(module_inst->c_api_func_imports); if (!is_sub_inst) { #if WASM_ENABLE_WASI_NN != 0 @@ -2981,14 +3045,12 @@ wasm_deinstantiate(WASMModuleInstance *module_inst, bool is_sub_inst) } WASMFunctionInstance * -wasm_lookup_function(const WASMModuleInstance *module_inst, const char *name, - const char *signature) +wasm_lookup_function(const WASMModuleInstance *module_inst, const char *name) { uint32 i; for (i = 0; i < module_inst->export_func_count; i++) if (!strcmp(module_inst->export_functions[i].name, name)) return module_inst->export_functions[i].function; - (void)signature; return NULL; } @@ -3162,8 +3224,8 @@ wasm_call_function(WASMExecEnv *exec_env, WASMFunctionInstance *function, hw bound check is enabled */ #endif - /* Set exec env so it can be later retrieved from instance */ - module_inst->e->common.cur_exec_env = exec_env; + /* Set exec env, so it can be later retrieved from instance */ + module_inst->cur_exec_env = exec_env; interp_call_wasm(module_inst, exec_env, function, argc, argv); return !wasm_copy_exception(module_inst, NULL); @@ -3267,27 +3329,30 @@ wasm_get_wasm_func_exec_time(const WASMModuleInstance *inst, } #endif /*WASM_ENABLE_PERF_PROFILING != 0*/ -uint32 +uint64 wasm_module_malloc_internal(WASMModuleInstance *module_inst, - WASMExecEnv *exec_env, uint32 size, + WASMExecEnv *exec_env, uint64 size, void **p_native_addr) { WASMMemoryInstance *memory = wasm_get_default_memory(module_inst); uint8 *addr = NULL; uint32 offset = 0; + /* TODO: Memory64 size check based on memory idx type */ + bh_assert(size <= UINT32_MAX); + if (!memory) { wasm_set_exception(module_inst, "uninitialized memory"); return 0; } if (memory->heap_handle) { - addr = mem_allocator_malloc(memory->heap_handle, size); + addr = mem_allocator_malloc(memory->heap_handle, (uint32)size); } else if (module_inst->e->malloc_function && module_inst->e->free_function) { if (!execute_malloc_function( module_inst, exec_env, module_inst->e->malloc_function, - module_inst->e->retain_function, size, &offset)) { + module_inst->e->retain_function, (uint32)size, &offset)) { return 0; } /* If we use app's malloc function, @@ -3303,24 +3368,29 @@ wasm_module_malloc_internal(WASMModuleInstance *module_inst, wasm_set_exception(module_inst, "app heap corrupted"); } else { - LOG_WARNING("warning: allocate %u bytes memory failed", size); + LOG_WARNING("warning: allocate %" PRIu64 " bytes memory failed", + size); } return 0; } if (p_native_addr) *p_native_addr = addr; - return (uint32)(addr - memory->memory_data); + return (uint64)(addr - memory->memory_data); } -uint32 +uint64 wasm_module_realloc_internal(WASMModuleInstance *module_inst, - WASMExecEnv *exec_env, uint32 ptr, uint32 size, + WASMExecEnv *exec_env, uint64 ptr, uint64 size, void **p_native_addr) { WASMMemoryInstance *memory = wasm_get_default_memory(module_inst); uint8 *addr = NULL; + /* TODO: Memory64 ptr and size check based on memory idx type */ + bh_assert(ptr <= UINT32_MAX); + bh_assert(size <= UINT32_MAX); + if (!memory) { wasm_set_exception(module_inst, "uninitialized memory"); return 0; @@ -3328,7 +3398,9 @@ wasm_module_realloc_internal(WASMModuleInstance *module_inst, if (memory->heap_handle) { addr = mem_allocator_realloc( - memory->heap_handle, ptr ? memory->memory_data + ptr : NULL, size); + memory->heap_handle, + (uint32)ptr ? memory->memory_data + (uint32)ptr : NULL, + (uint32)size); } /* Only support realloc in WAMR's app heap */ @@ -3347,21 +3419,24 @@ wasm_module_realloc_internal(WASMModuleInstance *module_inst, if (p_native_addr) *p_native_addr = addr; - return (uint32)(addr - memory->memory_data); + return (uint64)(addr - memory->memory_data); } void wasm_module_free_internal(WASMModuleInstance *module_inst, - WASMExecEnv *exec_env, uint32 ptr) + WASMExecEnv *exec_env, uint64 ptr) { WASMMemoryInstance *memory = wasm_get_default_memory(module_inst); + /* TODO: Memory64 ptr and size check based on memory idx type */ + bh_assert(ptr <= UINT32_MAX); + if (!memory) { return; } if (ptr) { - uint8 *addr = memory->memory_data + ptr; + uint8 *addr = memory->memory_data + (uint32)ptr; uint8 *memory_data_end; /* memory->memory_data_end may be changed in memory grow */ @@ -3377,20 +3452,20 @@ wasm_module_free_internal(WASMModuleInstance *module_inst, && module_inst->e->free_function && memory->memory_data <= addr && addr < memory_data_end) { execute_free_function(module_inst, exec_env, - module_inst->e->free_function, ptr); + module_inst->e->free_function, (uint32)ptr); } } } -uint32 -wasm_module_malloc(WASMModuleInstance *module_inst, uint32 size, +uint64 +wasm_module_malloc(WASMModuleInstance *module_inst, uint64 size, void **p_native_addr) { return wasm_module_malloc_internal(module_inst, NULL, size, p_native_addr); } -uint32 -wasm_module_realloc(WASMModuleInstance *module_inst, uint32 ptr, uint32 size, +uint64 +wasm_module_realloc(WASMModuleInstance *module_inst, uint64 ptr, uint64 size, void **p_native_addr) { return wasm_module_realloc_internal(module_inst, NULL, ptr, size, @@ -3398,22 +3473,27 @@ wasm_module_realloc(WASMModuleInstance *module_inst, uint32 ptr, uint32 size, } void -wasm_module_free(WASMModuleInstance *module_inst, uint32 ptr) +wasm_module_free(WASMModuleInstance *module_inst, uint64 ptr) { wasm_module_free_internal(module_inst, NULL, ptr); } -uint32 +uint64 wasm_module_dup_data(WASMModuleInstance *module_inst, const char *src, - uint32 size) + uint64 size) { char *buffer; - uint32 buffer_offset = - wasm_module_malloc(module_inst, size, (void **)&buffer); + uint64 buffer_offset; + + /* TODO: Memory64 size check based on memory idx type */ + bh_assert(size <= UINT32_MAX); + + buffer_offset = wasm_module_malloc(module_inst, size, (void **)&buffer); + if (buffer_offset != 0) { buffer = wasm_runtime_addr_app_to_native( (WASMModuleInstanceCommon *)module_inst, buffer_offset); - bh_memcpy_s(buffer, size, src, size); + bh_memcpy_s(buffer, (uint32)size, src, (uint32)size); } return buffer_offset; } @@ -3488,7 +3568,7 @@ call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 tbl_elem_idx, } #if WASM_ENABLE_GC == 0 - func_idx = tbl_elem_val; + func_idx = (uint32)tbl_elem_val; #else func_idx = wasm_func_obj_get_func_idx_bound((WASMFuncObjectRef)tbl_elem_val); @@ -3536,7 +3616,7 @@ wasm_call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 elem_idx, #if WASM_ENABLE_THREAD_MGR != 0 bool -wasm_set_aux_stack(WASMExecEnv *exec_env, uint32 start_offset, uint32 size) +wasm_set_aux_stack(WASMExecEnv *exec_env, uint64 start_offset, uint32 size) { WASMModuleInstance *module_inst = (WASMModuleInstance *)exec_env->module_inst; @@ -3544,8 +3624,8 @@ wasm_set_aux_stack(WASMExecEnv *exec_env, uint32 start_offset, uint32 size) #if WASM_ENABLE_HEAP_AUX_STACK_ALLOCATION == 0 /* Check the aux stack space */ - uint32 data_end = module_inst->module->aux_data_end; - uint32 stack_bottom = module_inst->module->aux_stack_bottom; + uint64 data_end = module_inst->module->aux_data_end; + uint64 stack_bottom = module_inst->module->aux_stack_bottom; bool is_stack_before_data = stack_bottom < data_end ? true : false; if ((is_stack_before_data && (size > start_offset)) || ((!is_stack_before_data) && (start_offset - data_end < size))) @@ -3558,11 +3638,11 @@ wasm_set_aux_stack(WASMExecEnv *exec_env, uint32 start_offset, uint32 size) uint8 *global_addr = module_inst->global_data + module_inst->e->globals[stack_top_idx].data_offset; - *(int32 *)global_addr = start_offset; + *(int32 *)global_addr = (uint32)start_offset; /* The aux stack boundary is a constant value, set the value to exec_env */ - exec_env->aux_stack_boundary.boundary = start_offset - size; - exec_env->aux_stack_bottom.bottom = start_offset; + exec_env->aux_stack_boundary = (uintptr_t)start_offset - size; + exec_env->aux_stack_bottom = (uintptr_t)start_offset; return true; } @@ -3570,14 +3650,14 @@ wasm_set_aux_stack(WASMExecEnv *exec_env, uint32 start_offset, uint32 size) } bool -wasm_get_aux_stack(WASMExecEnv *exec_env, uint32 *start_offset, uint32 *size) +wasm_get_aux_stack(WASMExecEnv *exec_env, uint64 *start_offset, uint32 *size) { WASMModuleInstance *module_inst = (WASMModuleInstance *)exec_env->module_inst; /* The aux stack information is resolved in loader and store in module */ - uint32 stack_bottom = module_inst->module->aux_stack_bottom; + uint64 stack_bottom = module_inst->module->aux_stack_bottom; uint32 total_aux_stack_size = module_inst->module->aux_stack_size; if (stack_bottom != 0 && total_aux_stack_size != 0) { @@ -3671,7 +3751,8 @@ void wasm_get_module_inst_mem_consumption(const WASMModuleInstance *module_inst, WASMModuleInstMemConsumption *mem_conspn) { - uint32 i, size; + uint32 i; + uint64 size; memset(mem_conspn, 0, sizeof(*mem_conspn)); @@ -3951,7 +4032,7 @@ jit_set_exception_with_id(WASMModuleInstance *module_inst, uint32 id) bool jit_check_app_addr_and_convert(WASMModuleInstance *module_inst, bool is_str, - uint32 app_buf_addr, uint32 app_buf_size, + uint64 app_buf_addr, uint64 app_buf_size, void **p_native_addr) { bool ret = wasm_check_app_addr_and_convert( @@ -4025,9 +4106,8 @@ llvm_jit_invoke_native(WASMExecEnv *exec_env, uint32 func_idx, uint32 argc, import_func = &module->import_functions[func_idx].u.function; if (import_func->call_conv_wasm_c_api) { - if (module_inst->e->common.c_api_func_imports) { - c_api_func_import = - module_inst->e->common.c_api_func_imports + func_idx; + if (module_inst->c_api_func_imports) { + c_api_func_import = module_inst->c_api_func_imports + func_idx; func_ptr = c_api_func_import->func_ptr_linked; } else { @@ -4097,7 +4177,7 @@ llvm_jit_memory_init(WASMModuleInstance *module_inst, uint32 seg_index, } if (!wasm_runtime_validate_app_addr((WASMModuleInstanceCommon *)module_inst, - dst, len)) + (uint64)dst, (uint64)len)) return false; if ((uint64)offset + (uint64)len > seg_len) { @@ -4106,10 +4186,11 @@ llvm_jit_memory_init(WASMModuleInstance *module_inst, uint32 seg_index, } maddr = wasm_runtime_addr_app_to_native( - (WASMModuleInstanceCommon *)module_inst, dst); + (WASMModuleInstanceCommon *)module_inst, (uint64)dst); SHARED_MEMORY_LOCK(memory_inst); - bh_memcpy_s(maddr, memory_inst->memory_data_size - dst, data + offset, len); + bh_memcpy_s(maddr, (uint32)(memory_inst->memory_data_size - dst), + data + offset, len); SHARED_MEMORY_UNLOCK(memory_inst); return true; } @@ -4377,3 +4458,154 @@ wasm_propagate_wasi_args(WASMModule *module) } } #endif + +bool +wasm_check_utf8_str(const uint8 *str, uint32 len) +{ + /* The valid ranges are taken from page 125, below link + https://www.unicode.org/versions/Unicode9.0.0/ch03.pdf */ + const uint8 *p = str, *p_end = str + len; + uint8 chr; + + while (p < p_end) { + chr = *p; + + if (chr == 0) { + LOG_WARNING( + "LIMITATION: a string which contains '\\00' is unsupported"); + return false; + } + else if (chr < 0x80) { + p++; + } + else if (chr >= 0xC2 && chr <= 0xDF && p + 1 < p_end) { + if (p[1] < 0x80 || p[1] > 0xBF) { + return false; + } + p += 2; + } + else if (chr >= 0xE0 && chr <= 0xEF && p + 2 < p_end) { + if (chr == 0xE0) { + if (p[1] < 0xA0 || p[1] > 0xBF || p[2] < 0x80 || p[2] > 0xBF) { + return false; + } + } + else if (chr == 0xED) { + if (p[1] < 0x80 || p[1] > 0x9F || p[2] < 0x80 || p[2] > 0xBF) { + return false; + } + } + else { /* chr >= 0xE1 && chr <= 0xEF */ + if (p[1] < 0x80 || p[1] > 0xBF || p[2] < 0x80 || p[2] > 0xBF) { + return false; + } + } + p += 3; + } + else if (chr >= 0xF0 && chr <= 0xF4 && p + 3 < p_end) { + if (chr == 0xF0) { + if (p[1] < 0x90 || p[1] > 0xBF || p[2] < 0x80 || p[2] > 0xBF + || p[3] < 0x80 || p[3] > 0xBF) { + return false; + } + } + else if (chr <= 0xF3) { /* and also chr >= 0xF1 */ + if (p[1] < 0x80 || p[1] > 0xBF || p[2] < 0x80 || p[2] > 0xBF + || p[3] < 0x80 || p[3] > 0xBF) { + return false; + } + } + else { /* chr == 0xF4 */ + if (p[1] < 0x80 || p[1] > 0x8F || p[2] < 0x80 || p[2] > 0xBF + || p[3] < 0x80 || p[3] > 0xBF) { + return false; + } + } + p += 4; + } + else { + return false; + } + } + return (p == p_end); +} + +char * +wasm_const_str_list_insert(const uint8 *str, uint32 len, WASMModule *module, + bool is_load_from_file_buf, char *error_buf, + uint32 error_buf_size) +{ + StringNode *node, *node_next; + + if (!wasm_check_utf8_str(str, len)) { + set_error_buf(error_buf, error_buf_size, "invalid UTF-8 encoding"); + return NULL; + } + + if (len == 0) { + return ""; + } + else if (is_load_from_file_buf) { + /* As the file buffer can be referred to after loading, we use + the previous byte of leb encoded size to adjust the string: + move string 1 byte backward and then append '\0' */ + char *c_str = (char *)str - 1; + bh_memmove_s(c_str, len + 1, c_str + 1, len); + c_str[len] = '\0'; + return c_str; + } + + /* Search const str list */ + node = module->const_str_list; + while (node) { + node_next = node->next; + if (strlen(node->str) == len && !memcmp(node->str, str, len)) + break; + node = node_next; + } + + if (node) { + return node->str; + } + + if (!(node = runtime_malloc(sizeof(StringNode) + len + 1, error_buf, + error_buf_size))) { + return NULL; + } + + node->str = ((char *)node) + sizeof(StringNode); + bh_memcpy_s(node->str, len + 1, str, len); + node->str[len] = '\0'; + + if (!module->const_str_list) { + /* set as head */ + module->const_str_list = node; + node->next = NULL; + } + else { + /* insert it */ + node->next = module->const_str_list; + module->const_str_list = node; + } + + return node->str; +} + +bool +wasm_set_module_name(WASMModule *module, const char *name, char *error_buf, + uint32_t error_buf_size) +{ + if (!name) + return false; + + module->name = + wasm_const_str_list_insert((const uint8 *)name, (uint32)strlen(name), + module, false, error_buf, error_buf_size); + return module->name != NULL; +} + +const char * +wasm_get_module_name(WASMModule *module) +{ + return module->name; +} diff --git a/core/iwasm/interpreter/wasm_runtime.h b/core/iwasm/interpreter/wasm_runtime.h index 1007dc27c..13b738f9e 100644 --- a/core/iwasm/interpreter/wasm_runtime.h +++ b/core/iwasm/interpreter/wasm_runtime.h @@ -103,13 +103,17 @@ struct WASMMemoryInstance { /* Whether the memory is shared */ uint8 is_shared_memory; - /* One byte padding */ - uint8 __padding__; + /* Whether the memory has 64-bit memory addresses */ + uint8 is_memory64; /* Reference count of the memory instance: 0: non-shared memory, > 0: shared memory */ bh_atomic_16_t ref_count; + /* Four-byte paddings to ensure the layout of WASMMemoryInstance is the same + * in both 64-bit and 32-bit */ + uint8 __paddings[4]; + /* Number bytes per page */ uint32 num_bytes_per_page; /* Current page count */ @@ -117,7 +121,7 @@ struct WASMMemoryInstance { /* Maximum page count */ uint32 max_page_count; /* Memory data size */ - uint32 memory_data_size; + uint64 memory_data_size; /** * Memory data begin address, Note: * the app-heap might be inserted in to the linear memory, @@ -134,6 +138,8 @@ struct WASMMemoryInstance { DefPointer(uint8 *, heap_data_end); /* The heap created */ DefPointer(void *, heap_handle); + /* TODO: use it to replace the g_shared_memory_lock */ + DefPointer(korp_mutex *, memory_lock); #if WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0 \ || WASM_ENABLE_WAMR_COMPILER != 0 || WASM_ENABLE_AOT != 0 @@ -175,7 +181,8 @@ struct WASMGlobalInstance { uint8 type; /* mutable or constant */ bool is_mutable; - /* data offset to base_addr of WASMMemoryInstance */ + /* data offset to the address of initial_value, started from the end of + * WASMMemoryInstance(start of WASMGlobalInstance)*/ uint32 data_offset; /* initial value */ WASMValue initial_value; @@ -292,10 +299,9 @@ typedef struct CApiFuncImport { /* The common part of WASMModuleInstanceExtra and AOTModuleInstanceExtra */ typedef struct WASMModuleInstanceExtraCommon { - CApiFuncImport *c_api_func_imports; +#if WASM_ENABLE_MODULE_INST_CONTEXT != 0 void *contexts[WASM_MAX_INSTANCE_CONTEXTS]; - /* pointer to the exec env currently used */ - WASMExecEnv *cur_exec_env; +#endif #if WASM_CONFIGURABLE_BOUNDS_CHECKS != 0 /* Disable bounds checks or not */ bool disable_bounds_checks; @@ -401,8 +407,6 @@ struct WASMModuleInstance { it denotes `AOTModule *` */ DefPointer(WASMModule *, module); - DefPointer(void *, used_to_be_wasi_ctx); /* unused */ - DefPointer(WASMExecEnv *, exec_env_singleton); /* Array of function pointers to import functions, not available in AOTModuleInstance */ @@ -421,13 +425,16 @@ struct WASMModuleInstance { /* Function performance profiling info list, only available in AOTModuleInstance */ DefPointer(struct AOTFuncPerfProfInfo *, func_perf_profilings); + DefPointer(CApiFuncImport *, c_api_func_imports); + /* Pointer to the exec env currently used */ + DefPointer(WASMExecEnv *, cur_exec_env); /* WASM/AOT module extra info, for AOTModuleInstance, it denotes `AOTModuleInstanceExtra *` */ DefPointer(WASMModuleInstanceExtra *, e); /* Default WASM operand stack size */ uint32 default_wasm_stack_size; - uint32 reserved[3]; + uint32 reserved[7]; /* * +------------------------------+ <-- memories @@ -501,7 +508,7 @@ wasm_load(uint8 *buf, uint32 size, #if WASM_ENABLE_MULTI_MODULE != 0 bool main_module, #endif - char *error_buf, uint32 error_buf_size); + const LoadArgs *args, char *error_buf, uint32 error_buf_size); WASMModule * wasm_load_from_sections(WASMSection *section_list, char *error_buf, @@ -513,7 +520,8 @@ wasm_unload(WASMModule *module); WASMModuleInstance * wasm_instantiate(WASMModule *module, WASMModuleInstance *parent, WASMExecEnv *exec_env_main, uint32 stack_size, - uint32 heap_size, char *error_buf, uint32 error_buf_size); + uint32 heap_size, uint32 max_memory_pages, char *error_buf, + uint32 error_buf_size); void wasm_dump_perf_profiling(const WASMModuleInstance *module_inst); @@ -533,8 +541,7 @@ wasm_set_running_mode(WASMModuleInstance *module_inst, RunningMode running_mode); WASMFunctionInstance * -wasm_lookup_function(const WASMModuleInstance *module_inst, const char *name, - const char *signature); +wasm_lookup_function(const WASMModuleInstance *module_inst, const char *name); #if WASM_ENABLE_MULTI_MODULE != 0 WASMGlobalInstance * @@ -576,34 +583,34 @@ wasm_get_exception(WASMModuleInstance *module); bool wasm_copy_exception(WASMModuleInstance *module_inst, char *exception_buf); -uint32 +uint64 wasm_module_malloc_internal(WASMModuleInstance *module_inst, - WASMExecEnv *exec_env, uint32 size, + WASMExecEnv *exec_env, uint64 size, void **p_native_addr); -uint32 +uint64 wasm_module_realloc_internal(WASMModuleInstance *module_inst, - WASMExecEnv *exec_env, uint32 ptr, uint32 size, + WASMExecEnv *exec_env, uint64 ptr, uint64 size, void **p_native_addr); void wasm_module_free_internal(WASMModuleInstance *module_inst, - WASMExecEnv *exec_env, uint32 ptr); + WASMExecEnv *exec_env, uint64 ptr); -uint32 -wasm_module_malloc(WASMModuleInstance *module_inst, uint32 size, +uint64 +wasm_module_malloc(WASMModuleInstance *module_inst, uint64 size, void **p_native_addr); -uint32 -wasm_module_realloc(WASMModuleInstance *module_inst, uint32 ptr, uint32 size, +uint64 +wasm_module_realloc(WASMModuleInstance *module_inst, uint64 ptr, uint64 size, void **p_native_addr); void -wasm_module_free(WASMModuleInstance *module_inst, uint32 ptr); +wasm_module_free(WASMModuleInstance *module_inst, uint64 ptr); -uint32 +uint64 wasm_module_dup_data(WASMModuleInstance *module_inst, const char *src, - uint32 size); + uint64 size); /** * Check whether the app address and the buf is inside the linear memory, @@ -611,7 +618,7 @@ wasm_module_dup_data(WASMModuleInstance *module_inst, const char *src, */ bool wasm_check_app_addr_and_convert(WASMModuleInstance *module_inst, bool is_str, - uint32 app_buf_addr, uint32 app_buf_size, + uint64 app_buf_addr, uint64 app_buf_size, void **p_native_addr); WASMMemoryInstance * @@ -626,10 +633,10 @@ wasm_call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 elem_idx, #if WASM_ENABLE_THREAD_MGR != 0 bool -wasm_set_aux_stack(WASMExecEnv *exec_env, uint32 start_offset, uint32 size); +wasm_set_aux_stack(WASMExecEnv *exec_env, uint64 start_offset, uint32 size); bool -wasm_get_aux_stack(WASMExecEnv *exec_env, uint32 *start_offset, uint32 *size); +wasm_get_aux_stack(WASMExecEnv *exec_env, uint64 *start_offset, uint32 *size); #endif void @@ -726,7 +733,7 @@ jit_set_exception_with_id(WASMModuleInstance *module_inst, uint32 id); */ bool jit_check_app_addr_and_convert(WASMModuleInstance *module_inst, bool is_str, - uint32 app_buf_addr, uint32 app_buf_size, + uint64 app_buf_addr, uint64 app_buf_size, void **p_native_addr); #endif /* end of WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0 \ || WASM_ENABLE_WAMR_COMPILER != 0 */ @@ -829,6 +836,21 @@ exception_unlock(WASMModuleInstance *module_inst); #define exception_unlock(module_inst) (void)(module_inst) #endif +bool +wasm_check_utf8_str(const uint8 *str, uint32 len); + +char * +wasm_const_str_list_insert(const uint8 *str, uint32 len, WASMModule *module, + bool is_load_from_file_buf, char *error_buf, + uint32 error_buf_size); + +bool +wasm_set_module_name(WASMModule *module, const char *name, char *error_buf, + uint32_t error_buf_size); + +const char * +wasm_get_module_name(WASMModule *module); + #ifdef __cplusplus } #endif diff --git a/core/iwasm/libraries/debug-engine/debug_engine.c b/core/iwasm/libraries/debug-engine/debug_engine.c index 1b3db1d49..0ffc78ad9 100644 --- a/core/iwasm/libraries/debug-engine/debug_engine.c +++ b/core/iwasm/libraries/debug-engine/debug_engine.c @@ -409,7 +409,7 @@ wasm_debug_instance_create(WASMCluster *cluster, int32 port) * expressions */ instance->exec_mem_info.size = DEBUG_EXECUTION_MEMORY_SIZE; instance->exec_mem_info.start_offset = wasm_runtime_module_malloc( - module_inst, instance->exec_mem_info.size, NULL); + module_inst, (uint64)instance->exec_mem_info.size, NULL); if (instance->exec_mem_info.start_offset == 0) { LOG_WARNING( "WASM Debug Engine warning: failed to allocate linear memory for " @@ -1393,7 +1393,7 @@ wasm_debug_instance_mmap(WASMDebugInstance *instance, uint32 size, return 0; } - if ((uint64)instance->exec_mem_info.current_pos + if (instance->exec_mem_info.current_pos - instance->exec_mem_info.start_offset + size <= (uint64)instance->exec_mem_info.size) { offset = instance->exec_mem_info.current_pos; diff --git a/core/iwasm/libraries/debug-engine/debug_engine.h b/core/iwasm/libraries/debug-engine/debug_engine.h index e12f827bd..68738213e 100644 --- a/core/iwasm/libraries/debug-engine/debug_engine.h +++ b/core/iwasm/libraries/debug-engine/debug_engine.h @@ -53,9 +53,9 @@ typedef enum debug_state_t { } debug_state_t; typedef struct WASMDebugExecutionMemory { - uint32 start_offset; + uint64 start_offset; + uint64 current_pos; uint32 size; - uint32 current_pos; } WASMDebugExecutionMemory; struct WASMDebugInstance { diff --git a/core/iwasm/libraries/debug-engine/handler.c b/core/iwasm/libraries/debug-engine/handler.c index 8d451b1a3..905ca2f7c 100644 --- a/core/iwasm/libraries/debug-engine/handler.c +++ b/core/iwasm/libraries/debug-engine/handler.c @@ -309,9 +309,11 @@ handle_general_query(WASMGDBServer *server, char *payload) } if (!strcmp(name, "WasmData")) { + write_packet(server, ""); } if (!strcmp(name, "WasmMem")) { + write_packet(server, ""); } if (!strcmp(name, "Symbol")) { @@ -447,7 +449,7 @@ send_thread_stop_status(WASMGDBServer *server, uint32 status, korp_tid tid) "thread-pcs:%" PRIx64 ";00:%s;reason:%s;", pc, pc_string, "trace"); } - else if (status > 0) { + else { /* status > 0 (== 0 is checked at the function beginning) */ len += snprintf(tmpbuf + len, MAX_PACKET_SIZE - len, "thread-pcs:%" PRIx64 ";00:%s;reason:%s;", pc, pc_string, "signal"); diff --git a/core/iwasm/libraries/lib-pthread/lib_pthread_wrapper.c b/core/iwasm/libraries/lib-pthread/lib_pthread_wrapper.c index 3092f5d03..b3fa57d72 100644 --- a/core/iwasm/libraries/lib-pthread/lib_pthread_wrapper.c +++ b/core/iwasm/libraries/lib-pthread/lib_pthread_wrapper.c @@ -558,7 +558,8 @@ pthread_create_wrapper(wasm_exec_env_t exec_env, ThreadRoutineArgs *routine_args = NULL; uint32 thread_handle; uint32 stack_size = 8192; - uint32 aux_stack_start = 0, aux_stack_size; + uint32 aux_stack_size; + uint64 aux_stack_start = 0; int32 ret = -1; bh_assert(module); @@ -579,7 +580,7 @@ pthread_create_wrapper(wasm_exec_env_t exec_env, #endif if (!(new_module_inst = wasm_runtime_instantiate_internal( - module, module_inst, exec_env, stack_size, 0, NULL, 0))) + module, module_inst, exec_env, stack_size, 0, 0, NULL, 0))) return -1; /* Set custom_data to new module instance */ @@ -669,14 +670,14 @@ pthread_join_wrapper(wasm_exec_env_t exec_env, uint32 thread, /* validate addr, we can use current thread's module instance here as the memory is shared */ - if (!validate_app_addr(retval_offset, sizeof(int32))) { + if (!validate_app_addr((uint64)retval_offset, (uint64)sizeof(int32))) { /* Join failed, but we don't want to terminate all threads, do not spread exception here */ wasm_runtime_set_exception(module_inst, NULL); return -1; } - retval = (void **)addr_app_to_native(retval_offset); + retval = (void **)addr_app_to_native((uint64)retval_offset); node = get_thread_info(exec_env, thread); if (!node) { @@ -1122,7 +1123,8 @@ posix_memalign_wrapper(wasm_exec_env_t exec_env, void **memptr, int32 align, wasm_module_inst_t module_inst = get_module_inst(exec_env); void *p = NULL; - *((int32 *)memptr) = module_malloc(size, (void **)&p); + /* TODO: for memory 64, module_malloc may return uint64 offset */ + *((uint32 *)memptr) = (uint32)module_malloc(size, (void **)&p); if (!p) return -1; @@ -1263,7 +1265,7 @@ sem_getvalue_wrapper(wasm_exec_env_t exec_env, uint32 sem, int32 *sval) (void)exec_env; SemCallbackArgs args = { sem, NULL }; - if (validate_native_addr(sval, sizeof(int32))) { + if (validate_native_addr(sval, (uint64)sizeof(int32))) { bh_hash_map_traverse(sem_info_map, sem_fetch_cb, &args); 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/lib-socket/lib_socket_wasi.cmake b/core/iwasm/libraries/lib-socket/lib_socket_wasi.cmake index 209b0c4c9..8ddddffeb 100644 --- a/core/iwasm/libraries/lib-socket/lib_socket_wasi.cmake +++ b/core/iwasm/libraries/lib-socket/lib_socket_wasi.cmake @@ -3,7 +3,7 @@ cmake_minimum_required (VERSION 2.8...3.16) -project(socket_wasi_ext) +project(socket_wasi_ext LANGUAGES C) add_library(${PROJECT_NAME} STATIC ${CMAKE_CURRENT_LIST_DIR}/src/wasi/wasi_socket_ext.c) target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_LIST_DIR}/inc/) diff --git a/core/iwasm/libraries/lib-wasi-threads/lib_wasi_threads_wrapper.c b/core/iwasm/libraries/lib-wasi-threads/lib_wasi_threads_wrapper.c index 392266113..aeaafced7 100644 --- a/core/iwasm/libraries/lib-wasi-threads/lib_wasi_threads_wrapper.c +++ b/core/iwasm/libraries/lib-wasi-threads/lib_wasi_threads_wrapper.c @@ -87,7 +87,7 @@ thread_spawn_wrapper(wasm_exec_env_t exec_env, uint32 start_arg) stack_size = ((WASMModuleInstance *)module_inst)->default_wasm_stack_size; if (!(new_module_inst = wasm_runtime_instantiate_internal( - module, module_inst, exec_env, stack_size, 0, NULL, 0))) + module, module_inst, exec_env, stack_size, 0, 0, NULL, 0))) return -1; wasm_runtime_set_custom_data_internal( @@ -98,8 +98,8 @@ thread_spawn_wrapper(wasm_exec_env_t exec_env, uint32 start_arg) wasm_native_inherit_contexts(new_module_inst, module_inst); - start_func = wasm_runtime_lookup_function(new_module_inst, - THREAD_START_FUNCTION, NULL); + start_func = + wasm_runtime_lookup_function(new_module_inst, THREAD_START_FUNCTION); if (!start_func) { LOG_ERROR("Failed to find thread start function %s", THREAD_START_FUNCTION); diff --git a/core/iwasm/libraries/libc-builtin/libc_builtin_wrapper.c b/core/iwasm/libraries/libc-builtin/libc_builtin_wrapper.c index d19e1bbbb..2ac381033 100644 --- a/core/iwasm/libraries/libc-builtin/libc_builtin_wrapper.c +++ b/core/iwasm/libraries/libc-builtin/libc_builtin_wrapper.c @@ -17,7 +17,7 @@ void wasm_runtime_set_exception(wasm_module_inst_t module, const char *exception); uint32 -wasm_runtime_module_realloc(wasm_module_inst_t module, uint32 ptr, uint32 size, +wasm_runtime_module_realloc(wasm_module_inst_t module, uint64 ptr, uint64 size, void **p_native_addr); /* clang-format off */ @@ -233,7 +233,7 @@ _vprintf_wa(out_func_t out, void *ctx, const char *fmt, _va_list ap, return false; } - s = start = addr_app_to_native(s_offset); + s = start = addr_app_to_native((uint64)s_offset); str_len = (uint32)strlen(start); if (str_len >= UINT32_MAX - 64) { @@ -401,7 +401,7 @@ printf_wrapper(wasm_exec_env_t exec_env, const char *format, _va_list va_args) struct str_context ctx = { NULL, 0, 0 }; /* format has been checked by runtime */ - if (!validate_native_addr(va_args, sizeof(int32))) + if (!validate_native_addr(va_args, (uint64)sizeof(int32))) return 0; if (!_vprintf_wa((out_func_t)printf_out, &ctx, format, va_args, @@ -420,13 +420,13 @@ sprintf_wrapper(wasm_exec_env_t exec_env, char *str, const char *format, struct str_context ctx; /* str and format have been checked by runtime */ - if (!validate_native_addr(va_args, sizeof(uint32))) + if (!validate_native_addr(va_args, (uint64)sizeof(uint32))) return 0; if (!wasm_runtime_get_native_addr_range(module_inst, (uint8 *)str, NULL, &native_end_offset)) { wasm_runtime_set_exception(module_inst, "out of bounds memory access"); - return false; + return 0; } ctx.str = str; @@ -452,7 +452,7 @@ snprintf_wrapper(wasm_exec_env_t exec_env, char *str, uint32 size, struct str_context ctx; /* str and format have been checked by runtime */ - if (!validate_native_addr(va_args, sizeof(uint32))) + if (!validate_native_addr(va_args, (uint64)sizeof(uint32))) return 0; ctx.str = str; @@ -499,7 +499,7 @@ strdup_wrapper(wasm_exec_env_t exec_env, const char *str) if (str) { len = (uint32)strlen(str) + 1; - str_ret_offset = module_malloc(len, (void **)&str_ret); + str_ret_offset = (uint32)module_malloc((uint64)len, (void **)&str_ret); if (str_ret_offset) { bh_memcpy_s(str_ret, len, str, len); } @@ -521,7 +521,7 @@ memcmp_wrapper(wasm_exec_env_t exec_env, const void *s1, const void *s2, wasm_module_inst_t module_inst = get_module_inst(exec_env); /* s2 has been checked by runtime */ - if (!validate_native_addr((void *)s1, size)) + if (!validate_native_addr((void *)s1, (uint64)size)) return 0; return memcmp(s1, s2, size); @@ -532,13 +532,13 @@ memcpy_wrapper(wasm_exec_env_t exec_env, void *dst, const void *src, uint32 size) { wasm_module_inst_t module_inst = get_module_inst(exec_env); - uint32 dst_offset = addr_native_to_app(dst); + uint32 dst_offset = (uint32)addr_native_to_app(dst); if (size == 0) return dst_offset; /* src has been checked by runtime */ - if (!validate_native_addr(dst, size)) + if (!validate_native_addr(dst, (uint64)size)) return dst_offset; bh_memcpy_s(dst, size, src, size); @@ -549,13 +549,13 @@ static uint32 memmove_wrapper(wasm_exec_env_t exec_env, void *dst, void *src, uint32 size) { wasm_module_inst_t module_inst = get_module_inst(exec_env); - uint32 dst_offset = addr_native_to_app(dst); + uint32 dst_offset = (uint32)addr_native_to_app(dst); if (size == 0) return dst_offset; /* src has been checked by runtime */ - if (!validate_native_addr(dst, size)) + if (!validate_native_addr(dst, (uint64)size)) return dst_offset; memmove(dst, src, size); @@ -566,9 +566,9 @@ static uint32 memset_wrapper(wasm_exec_env_t exec_env, void *s, int32 c, uint32 size) { wasm_module_inst_t module_inst = get_module_inst(exec_env); - uint32 s_offset = addr_native_to_app(s); + uint32 s_offset = (uint32)addr_native_to_app(s); - if (!validate_native_addr(s, size)) + if (!validate_native_addr(s, (uint64)size)) return s_offset; memset(s, c, size); @@ -583,7 +583,7 @@ strchr_wrapper(wasm_exec_env_t exec_env, const char *s, int32 c) /* s has been checked by runtime */ ret = strchr(s, c); - return ret ? addr_native_to_app(ret) : 0; + return ret ? (uint32)addr_native_to_app(ret) : 0; } static int32 @@ -602,7 +602,7 @@ strncmp_wrapper(wasm_exec_env_t exec_env, const char *s1, const char *s2, wasm_module_inst_t module_inst = get_module_inst(exec_env); /* s2 has been checked by runtime */ - if (!validate_native_addr((void *)s1, size)) + if (!validate_native_addr((void *)s1, (uint64)size)) return 0; return strncmp(s1, s2, size); @@ -615,7 +615,7 @@ strcpy_wrapper(wasm_exec_env_t exec_env, char *dst, const char *src) uint32 len = (uint32)strlen(src) + 1; /* src has been checked by runtime */ - if (!validate_native_addr(dst, len)) + if (!validate_native_addr(dst, (uint64)len)) return 0; #ifndef BH_PLATFORM_WINDOWS @@ -623,7 +623,7 @@ strcpy_wrapper(wasm_exec_env_t exec_env, char *dst, const char *src) #else strncpy_s(dst, len, src, len); #endif - return addr_native_to_app(dst); + return (uint32)addr_native_to_app(dst); } static uint32 @@ -633,7 +633,7 @@ strncpy_wrapper(wasm_exec_env_t exec_env, char *dst, const char *src, wasm_module_inst_t module_inst = get_module_inst(exec_env); /* src has been checked by runtime */ - if (!validate_native_addr(dst, size)) + if (!validate_native_addr(dst, (uint64)size)) return 0; #ifndef BH_PLATFORM_WINDOWS @@ -641,7 +641,7 @@ strncpy_wrapper(wasm_exec_env_t exec_env, char *dst, const char *src, #else strncpy_s(dst, size, src, size); #endif - return addr_native_to_app(dst); + return (uint32)addr_native_to_app(dst); } static uint32 @@ -657,7 +657,7 @@ static uint32 malloc_wrapper(wasm_exec_env_t exec_env, uint32 size) { wasm_module_inst_t module_inst = get_module_inst(exec_env); - return module_malloc(size, NULL); + return (uint32)module_malloc((uint64)size, NULL); } static uint32 @@ -671,7 +671,7 @@ calloc_wrapper(wasm_exec_env_t exec_env, uint32 nmemb, uint32 size) if (total_size >= UINT32_MAX) return 0; - ret_offset = module_malloc((uint32)total_size, (void **)&ret_ptr); + ret_offset = (uint32)module_malloc(total_size, (void **)&ret_ptr); if (ret_offset) { memset(ret_ptr, 0, (uint32)total_size); } @@ -692,7 +692,7 @@ free_wrapper(wasm_exec_env_t exec_env, void *ptr) { wasm_module_inst_t module_inst = get_module_inst(exec_env); - if (!validate_native_addr(ptr, sizeof(uint32))) + if (!validate_native_addr(ptr, (uint64)sizeof(uint32))) return; module_free(addr_native_to_app(ptr)); @@ -723,11 +723,11 @@ strtol_wrapper(wasm_exec_env_t exec_env, const char *nptr, char **endptr, int32 num = 0; /* nptr has been checked by runtime */ - if (!validate_native_addr(endptr, sizeof(uint32))) + if (!validate_native_addr(endptr, (uint64)sizeof(uint32))) return 0; num = (int32)strtol(nptr, endptr, base); - *(uint32 *)endptr = addr_native_to_app(*endptr); + *(uint32 *)endptr = (uint32)addr_native_to_app(*endptr); return num; } @@ -740,11 +740,11 @@ strtoul_wrapper(wasm_exec_env_t exec_env, const char *nptr, char **endptr, uint32 num = 0; /* nptr has been checked by runtime */ - if (!validate_native_addr(endptr, sizeof(uint32))) + if (!validate_native_addr(endptr, (uint64)sizeof(uint32))) return 0; num = (uint32)strtoul(nptr, endptr, base); - *(uint32 *)endptr = addr_native_to_app(*endptr); + *(uint32 *)endptr = (uint32)addr_native_to_app(*endptr); return num; } @@ -755,11 +755,11 @@ memchr_wrapper(wasm_exec_env_t exec_env, const void *s, int32 c, uint32 n) wasm_module_inst_t module_inst = get_module_inst(exec_env); void *res; - if (!validate_native_addr((void *)s, n)) + if (!validate_native_addr((void *)s, (uint64)n)) return 0; res = memchr(s, c, n); - return addr_native_to_app(res); + return (uint32)addr_native_to_app(res); } static int32 @@ -796,7 +796,7 @@ strstr_wrapper(wasm_exec_env_t exec_env, const char *s, const char *find) wasm_module_inst_t module_inst = get_module_inst(exec_env); /* s and find have been checked by runtime */ char *res = strstr(s, find); - return addr_native_to_app(res); + return (uint32)addr_native_to_app(res); } static int32 @@ -884,10 +884,10 @@ emscripten_memcpy_big_wrapper(wasm_exec_env_t exec_env, void *dst, const void *src, uint32 size) { wasm_module_inst_t module_inst = get_module_inst(exec_env); - uint32 dst_offset = addr_native_to_app(dst); + uint32 dst_offset = (uint32)addr_native_to_app(dst); /* src has been checked by runtime */ - if (!validate_native_addr(dst, size)) + if (!validate_native_addr(dst, (uint64)size)) return dst_offset; bh_memcpy_s(dst, size, src, size); @@ -925,7 +925,7 @@ static uint32 __cxa_allocate_exception_wrapper(wasm_exec_env_t exec_env, uint32 thrown_size) { wasm_module_inst_t module_inst = get_module_inst(exec_env); - uint32 exception = module_malloc(thrown_size, NULL); + uint32 exception = (uint32)module_malloc((uint64)thrown_size, NULL); if (!exception) return 0; @@ -968,7 +968,7 @@ clock_gettime_wrapper(wasm_exec_env_t exec_env, uint32 clk_id, (void)clk_id; - if (!validate_native_addr(ts_app, sizeof(struct timespec_app))) + if (!validate_native_addr(ts_app, (uint64)sizeof(struct timespec_app))) return (uint32)-1; time = os_time_get_boot_us(); diff --git a/core/iwasm/libraries/libc-emcc/libc_emcc_wrapper.c b/core/iwasm/libraries/libc-emcc/libc_emcc_wrapper.c index c21b96261..969955415 100644 --- a/core/iwasm/libraries/libc-emcc/libc_emcc_wrapper.c +++ b/core/iwasm/libraries/libc-emcc/libc_emcc_wrapper.c @@ -184,7 +184,8 @@ __sys_stat64_wrapper(wasm_exec_env_t exec_env, const char *pathname, int ret; struct stat statbuf; - if (!validate_native_addr((void *)statbuf_app, sizeof(struct stat_emcc))) + if (!validate_native_addr((void *)statbuf_app, + (uint64)sizeof(struct stat_emcc))) return -1; if (pathname == NULL) @@ -204,7 +205,8 @@ __sys_fstat64_wrapper(wasm_exec_env_t exec_env, int fd, int ret; struct stat statbuf; - if (!validate_native_addr((void *)statbuf_app, sizeof(struct stat_emcc))) + if (!validate_native_addr((void *)statbuf_app, + (uint64)sizeof(struct stat_emcc))) return -1; if (fd <= 0) @@ -225,7 +227,7 @@ mmap_wrapper(wasm_exec_env_t exec_env, void *addr, int length, int prot, char *buf; int size_read; - buf_offset = module_malloc(length, (void **)&buf); + buf_offset = module_malloc((uint64)length, (void **)&buf); if (buf_offset == 0) return -1; @@ -244,7 +246,7 @@ static int munmap_wrapper(wasm_exec_env_t exec_env, uint32 buf_offset, int length) { wasm_module_inst_t module_inst = get_module_inst(exec_env); - module_free(buf_offset); + module_free((uint64)buf_offset); return 0; } @@ -422,7 +424,7 @@ __sys_getcwd_wrapper(wasm_exec_env_t exec_env, char *buf, uint32 size) return -1; ret = getcwd(buf, size); - return ret ? addr_native_to_app(ret) : 0; + return ret ? (uint32)addr_native_to_app(ret) : 0; } #include @@ -443,7 +445,7 @@ __sys_uname_wrapper(wasm_exec_env_t exec_env, struct utsname_app *uname_app) struct utsname uname_native = { 0 }; uint32 length; - if (!validate_native_addr(uname_app, sizeof(struct utsname_app))) + if (!validate_native_addr(uname_app, (uint64)sizeof(struct utsname_app))) return -1; if (uname(&uname_native) != 0) { diff --git a/core/iwasm/libraries/libc-uvwasi/libc_uvwasi_wrapper.c b/core/iwasm/libraries/libc-uvwasi/libc_uvwasi_wrapper.c index 6ead65406..35d091e78 100644 --- a/core/iwasm/libraries/libc-uvwasi/libc_uvwasi_wrapper.c +++ b/core/iwasm/libraries/libc-uvwasi/libc_uvwasi_wrapper.c @@ -115,9 +115,9 @@ wasi_args_get(wasm_exec_env_t exec_env, uint32 *argv_offsets, char *argv_buf) total_size = sizeof(int32) * ((uint64)argc + 1); if (total_size >= UINT32_MAX - || !validate_native_addr(argv_offsets, (uint32)total_size) + || !validate_native_addr(argv_offsets, total_size) || argv_buf_size >= UINT32_MAX - || !validate_native_addr(argv_buf, (uint32)argv_buf_size)) + || !validate_native_addr(argv_buf, (uint64)argv_buf_size)) return (wasi_errno_t)-1; total_size = sizeof(char *) * ((uint64)argc + 1); @@ -132,7 +132,7 @@ wasi_args_get(wasm_exec_env_t exec_env, uint32 *argv_offsets, char *argv_buf) } for (i = 0; i < argc; i++) - argv_offsets[i] = addr_native_to_app(argv[i]); + argv_offsets[i] = (uint32)addr_native_to_app(argv[i]); wasm_runtime_free(argv); return 0; @@ -150,8 +150,8 @@ wasi_args_sizes_get(wasm_exec_env_t exec_env, uint32 *argc_app, if (!uvwasi) return (wasi_errno_t)-1; - if (!validate_native_addr(argc_app, sizeof(uint32)) - || !validate_native_addr(argv_buf_size_app, sizeof(uint32))) + if (!validate_native_addr(argc_app, (uint64)sizeof(uint32)) + || !validate_native_addr(argv_buf_size_app, (uint64)sizeof(uint32))) return (wasi_errno_t)-1; err = uvwasi_args_sizes_get(uvwasi, &argc, &argv_buf_size); @@ -170,7 +170,7 @@ wasi_clock_res_get(wasm_exec_env_t exec_env, wasi_clockid_t clock_id, wasm_module_inst_t module_inst = get_module_inst(exec_env); uvwasi_t *uvwasi = get_wasi_ctx(module_inst); - if (!validate_native_addr(resolution, sizeof(wasi_timestamp_t))) + if (!validate_native_addr(resolution, (uint64)sizeof(wasi_timestamp_t))) return (wasi_errno_t)-1; return uvwasi_clock_res_get(uvwasi, clock_id, resolution); @@ -183,7 +183,7 @@ wasi_clock_time_get(wasm_exec_env_t exec_env, wasi_clockid_t clock_id, wasm_module_inst_t module_inst = get_module_inst(exec_env); uvwasi_t *uvwasi = get_wasi_ctx(module_inst); - if (!validate_native_addr(time, sizeof(wasi_timestamp_t))) + if (!validate_native_addr(time, (uint64)sizeof(wasi_timestamp_t))) return (wasi_errno_t)-1; return uvwasi_clock_time_get(uvwasi, clock_id, precision, time); @@ -212,9 +212,9 @@ wasi_environ_get(wasm_exec_env_t exec_env, uint32 *environ_offsets, total_size = sizeof(int32) * ((uint64)environ_count + 1); if (total_size >= UINT32_MAX - || !validate_native_addr(environ_offsets, (uint32)total_size) + || !validate_native_addr(environ_offsets, total_size) || environ_buf_size >= UINT32_MAX - || !validate_native_addr(environ_buf, (uint32)environ_buf_size)) + || !validate_native_addr(environ_buf, (uint64)environ_buf_size)) return (wasi_errno_t)-1; total_size = sizeof(char *) * (((uint64)environ_count + 1)); @@ -230,7 +230,7 @@ wasi_environ_get(wasm_exec_env_t exec_env, uint32 *environ_offsets, } for (i = 0; i < environ_count; i++) - environ_offsets[i] = addr_native_to_app(environs[i]); + environ_offsets[i] = (uint32)addr_native_to_app(environs[i]); wasm_runtime_free(environs); return 0; @@ -248,8 +248,8 @@ wasi_environ_sizes_get(wasm_exec_env_t exec_env, uint32 *environ_count_app, if (!uvwasi) return (wasi_errno_t)-1; - if (!validate_native_addr(environ_count_app, sizeof(uint32)) - || !validate_native_addr(environ_buf_size_app, sizeof(uint32))) + if (!validate_native_addr(environ_count_app, (uint64)sizeof(uint32)) + || !validate_native_addr(environ_buf_size_app, (uint64)sizeof(uint32))) return (wasi_errno_t)-1; err = uvwasi_environ_sizes_get(uvwasi, &environ_count, &environ_buf_size); @@ -273,7 +273,7 @@ wasi_fd_prestat_get(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!uvwasi) return (wasi_errno_t)-1; - if (!validate_native_addr(prestat_app, sizeof(wasi_prestat_app_t))) + if (!validate_native_addr(prestat_app, (uint64)sizeof(wasi_prestat_app_t))) return (wasi_errno_t)-1; err = uvwasi_fd_prestat_get(uvwasi, fd, &prestat); @@ -338,9 +338,9 @@ wasi_fd_pread(wasm_exec_env_t exec_env, wasi_fd_t fd, iovec_app_t *iovec_app, return (wasi_errno_t)-1; total_size = sizeof(iovec_app_t) * (uint64)iovs_len; - if (!validate_native_addr(nread_app, (uint32)sizeof(uint32)) + if (!validate_native_addr(nread_app, (uint64)sizeof(uint32)) || total_size >= UINT32_MAX - || !validate_native_addr(iovec_app, (uint32)total_size)) + || !validate_native_addr(iovec_app, total_size)) return (wasi_errno_t)-1; total_size = sizeof(wasi_iovec_t) * (uint64)iovs_len; @@ -350,11 +350,12 @@ wasi_fd_pread(wasm_exec_env_t exec_env, wasi_fd_t fd, iovec_app_t *iovec_app, iovec = iovec_begin; for (i = 0; i < iovs_len; i++, iovec_app++, iovec++) { - if (!validate_app_addr(iovec_app->buf_offset, iovec_app->buf_len)) { + if (!validate_app_addr((uint64)iovec_app->buf_offset, + (uint64)iovec_app->buf_len)) { err = (wasi_errno_t)-1; goto fail; } - iovec->buf = (void *)addr_app_to_native(iovec_app->buf_offset); + iovec->buf = (void *)addr_app_to_native((uint64)iovec_app->buf_offset); iovec->buf_len = iovec_app->buf_len; } @@ -389,9 +390,9 @@ wasi_fd_pwrite(wasm_exec_env_t exec_env, wasi_fd_t fd, return (wasi_errno_t)-1; total_size = sizeof(iovec_app_t) * (uint64)iovs_len; - if (!validate_native_addr(nwritten_app, (uint32)sizeof(uint32)) + if (!validate_native_addr(nwritten_app, (uint64)sizeof(uint32)) || total_size >= UINT32_MAX - || !validate_native_addr((void *)iovec_app, (uint32)total_size)) + || !validate_native_addr((void *)iovec_app, total_size)) return (wasi_errno_t)-1; total_size = sizeof(wasi_ciovec_t) * (uint64)iovs_len; @@ -401,11 +402,12 @@ wasi_fd_pwrite(wasm_exec_env_t exec_env, wasi_fd_t fd, ciovec = ciovec_begin; for (i = 0; i < iovs_len; i++, iovec_app++, ciovec++) { - if (!validate_app_addr(iovec_app->buf_offset, iovec_app->buf_len)) { + if (!validate_app_addr((uint64)iovec_app->buf_offset, + (uint64)iovec_app->buf_len)) { err = (wasi_errno_t)-1; goto fail; } - ciovec->buf = (char *)addr_app_to_native(iovec_app->buf_offset); + ciovec->buf = (char *)addr_app_to_native((uint64)iovec_app->buf_offset); ciovec->buf_len = iovec_app->buf_len; } @@ -440,9 +442,9 @@ wasi_fd_read(wasm_exec_env_t exec_env, wasi_fd_t fd, return (wasi_errno_t)-1; total_size = sizeof(iovec_app_t) * (uint64)iovs_len; - if (!validate_native_addr(nread_app, (uint32)sizeof(uint32)) + if (!validate_native_addr(nread_app, (uint64)sizeof(uint32)) || total_size >= UINT32_MAX - || !validate_native_addr((void *)iovec_app, (uint32)total_size)) + || !validate_native_addr((void *)iovec_app, total_size)) return (wasi_errno_t)-1; total_size = sizeof(wasi_iovec_t) * (uint64)iovs_len; @@ -452,11 +454,12 @@ wasi_fd_read(wasm_exec_env_t exec_env, wasi_fd_t fd, iovec = iovec_begin; for (i = 0; i < iovs_len; i++, iovec_app++, iovec++) { - if (!validate_app_addr(iovec_app->buf_offset, iovec_app->buf_len)) { + if (!validate_app_addr((uint64)iovec_app->buf_offset, + (uint64)iovec_app->buf_len)) { err = (wasi_errno_t)-1; goto fail; } - iovec->buf = (void *)addr_app_to_native(iovec_app->buf_offset); + iovec->buf = (void *)addr_app_to_native((uint64)iovec_app->buf_offset); iovec->buf_len = iovec_app->buf_len; } @@ -496,7 +499,7 @@ wasi_fd_seek(wasm_exec_env_t exec_env, wasi_fd_t fd, wasi_filedelta_t offset, if (!uvwasi) return (wasi_errno_t)-1; - if (!validate_native_addr(newoffset, sizeof(wasi_filesize_t))) + if (!validate_native_addr(newoffset, (uint64)sizeof(wasi_filesize_t))) return (wasi_errno_t)-1; return uvwasi_fd_seek(uvwasi, fd, offset, whence, newoffset); @@ -511,7 +514,7 @@ wasi_fd_tell(wasm_exec_env_t exec_env, wasi_fd_t fd, wasi_filesize_t *newoffset) if (!uvwasi) return (wasi_errno_t)-1; - if (!validate_native_addr(newoffset, sizeof(wasi_filesize_t))) + if (!validate_native_addr(newoffset, (uint64)sizeof(wasi_filesize_t))) return (wasi_errno_t)-1; return uvwasi_fd_tell(uvwasi, fd, newoffset); @@ -529,7 +532,7 @@ wasi_fd_fdstat_get(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!uvwasi) return (wasi_errno_t)-1; - if (!validate_native_addr(fdstat_app, sizeof(wasi_fdstat_t))) + if (!validate_native_addr(fdstat_app, (uint64)sizeof(wasi_fdstat_t))) return (wasi_errno_t)-1; err = uvwasi_fd_fdstat_get(uvwasi, fd, &fdstat); @@ -597,9 +600,9 @@ wasi_fd_write(wasm_exec_env_t exec_env, wasi_fd_t fd, return (wasi_errno_t)-1; total_size = sizeof(iovec_app_t) * (uint64)iovs_len; - if (!validate_native_addr(nwritten_app, (uint32)sizeof(uint32)) + if (!validate_native_addr(nwritten_app, (uint64)sizeof(uint32)) || total_size >= UINT32_MAX - || !validate_native_addr((void *)iovec_app, (uint32)total_size)) + || !validate_native_addr((void *)iovec_app, total_size)) return (wasi_errno_t)-1; total_size = sizeof(wasi_ciovec_t) * (uint64)iovs_len; @@ -609,11 +612,12 @@ wasi_fd_write(wasm_exec_env_t exec_env, wasi_fd_t fd, ciovec = ciovec_begin; for (i = 0; i < iovs_len; i++, iovec_app++, ciovec++) { - if (!validate_app_addr(iovec_app->buf_offset, iovec_app->buf_len)) { + if (!validate_app_addr((uint64)iovec_app->buf_offset, + (uint64)iovec_app->buf_len)) { err = (wasi_errno_t)-1; goto fail; } - ciovec->buf = (char *)addr_app_to_native(iovec_app->buf_offset); + ciovec->buf = (char *)addr_app_to_native((uint64)iovec_app->buf_offset); ciovec->buf_len = iovec_app->buf_len; } @@ -725,7 +729,7 @@ wasi_path_open(wasm_exec_env_t exec_env, wasi_fd_t dirfd, if (!uvwasi) return (wasi_errno_t)-1; - if (!validate_native_addr(fd_app, sizeof(wasi_fd_t))) + if (!validate_native_addr(fd_app, (uint64)sizeof(wasi_fd_t))) return (wasi_errno_t)-1; err = uvwasi_path_open(uvwasi, dirfd, dirflags, path, path_len, oflags, @@ -747,7 +751,7 @@ wasi_fd_readdir(wasm_exec_env_t exec_env, wasi_fd_t fd, void *buf, if (!uvwasi) return (wasi_errno_t)-1; - if (!validate_native_addr(bufused_app, sizeof(uint32))) + if (!validate_native_addr(bufused_app, (uint64)sizeof(uint32))) return (wasi_errno_t)-1; err = uvwasi_fd_readdir(uvwasi, fd, buf, buf_len, cookie, &bufused); @@ -771,7 +775,7 @@ wasi_path_readlink(wasm_exec_env_t exec_env, wasi_fd_t fd, const char *path, if (!uvwasi) return (wasi_errno_t)-1; - if (!validate_native_addr(bufused_app, sizeof(uint32))) + if (!validate_native_addr(bufused_app, (uint64)sizeof(uint32))) return (wasi_errno_t)-1; err = uvwasi_path_readlink(uvwasi, fd, path, path_len, buf, buf_len, @@ -808,7 +812,7 @@ wasi_fd_filestat_get(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!uvwasi) return (wasi_errno_t)-1; - if (!validate_native_addr(filestat, sizeof(wasi_filestat_t))) + if (!validate_native_addr(filestat, (uint64)sizeof(wasi_filestat_t))) return (wasi_errno_t)-1; return uvwasi_fd_filestat_get(uvwasi, fd, filestat); @@ -852,7 +856,7 @@ wasi_path_filestat_get(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!uvwasi) return (wasi_errno_t)-1; - if (!validate_native_addr(filestat, sizeof(wasi_filestat_t))) + if (!validate_native_addr(filestat, (uint64)sizeof(wasi_filestat_t))) return (wasi_errno_t)-1; return uvwasi_path_filestat_get(uvwasi, fd, flags, path, path_len, @@ -928,9 +932,9 @@ wasi_poll_oneoff(wasm_exec_env_t exec_env, const wasi_subscription_t *in, if (!uvwasi) return (wasi_errno_t)-1; - if (!validate_native_addr((void *)in, sizeof(wasi_subscription_t)) - || !validate_native_addr(out, sizeof(wasi_event_t)) - || !validate_native_addr(nevents_app, sizeof(uint32))) + if (!validate_native_addr((void *)in, (uint64)sizeof(wasi_subscription_t)) + || !validate_native_addr(out, (uint64)sizeof(wasi_event_t)) + || !validate_native_addr(nevents_app, (uint64)sizeof(uint32))) return (wasi_errno_t)-1; err = uvwasi_poll_oneoff(uvwasi, in, out, nsubscriptions, &nevents); @@ -1002,11 +1006,12 @@ wasi_sock_recv(wasm_exec_env_t exec_env, wasi_fd_t sock, iovec_app_t *ri_data, iovec = iovec_begin; for (i = 0; i < ri_data_len; i++, ri_data++, iovec++) { - if (!validate_app_addr(ri_data->buf_offset, ri_data->buf_len)) { + if (!validate_app_addr((uint64)ri_data->buf_offset, + (uint64)ri_data->buf_len)) { err = (wasi_errno_t)-1; goto fail; } - iovec->buf = (void *)addr_app_to_native(ri_data->buf_offset); + iovec->buf = (void *)addr_app_to_native((uint64)ri_data->buf_offset); iovec->buf_len = ri_data->buf_len; } @@ -1042,9 +1047,9 @@ wasi_sock_send(wasm_exec_env_t exec_env, wasi_fd_t sock, return (wasi_errno_t)-1; total_size = sizeof(iovec_app_t) * (uint64)si_data_len; - if (!validate_native_addr(so_datalen_app, sizeof(uint32)) + if (!validate_native_addr(so_datalen_app, (uint64)sizeof(uint32)) || total_size >= UINT32_MAX - || !validate_native_addr((void *)si_data, (uint32)total_size)) + || !validate_native_addr((void *)si_data, total_size)) return (wasi_errno_t)-1; total_size = sizeof(wasi_ciovec_t) * (uint64)si_data_len; @@ -1054,11 +1059,12 @@ wasi_sock_send(wasm_exec_env_t exec_env, wasi_fd_t sock, ciovec = ciovec_begin; for (i = 0; i < si_data_len; i++, si_data++, ciovec++) { - if (!validate_app_addr(si_data->buf_offset, si_data->buf_len)) { + if (!validate_app_addr((uint64)si_data->buf_offset, + (uint64)si_data->buf_len)) { err = (wasi_errno_t)-1; goto fail; } - ciovec->buf = (char *)addr_app_to_native(si_data->buf_offset); + ciovec->buf = (char *)addr_app_to_native((uint64)si_data->buf_offset); ciovec->buf_len = si_data->buf_len; } diff --git a/core/iwasm/libraries/libc-wasi/libc_wasi_wrapper.c b/core/iwasm/libraries/libc-wasi/libc_wasi_wrapper.c index 0b69de6b9..aef8f1703 100644 --- a/core/iwasm/libraries/libc-wasi/libc_wasi_wrapper.c +++ b/core/iwasm/libraries/libc-wasi/libc_wasi_wrapper.c @@ -132,9 +132,9 @@ wasi_args_get(wasm_exec_env_t exec_env, uint32 *argv_offsets, char *argv_buf) total_size = sizeof(int32) * ((uint64)argc + 1); if (total_size >= UINT32_MAX - || !validate_native_addr(argv_offsets, (uint32)total_size) + || !validate_native_addr(argv_offsets, total_size) || argv_buf_size >= UINT32_MAX - || !validate_native_addr(argv_buf, (uint32)argv_buf_size)) + || !validate_native_addr(argv_buf, (uint64)argv_buf_size)) return (wasi_errno_t)-1; total_size = sizeof(char *) * ((uint64)argc + 1); @@ -149,7 +149,7 @@ wasi_args_get(wasm_exec_env_t exec_env, uint32 *argv_offsets, char *argv_buf) } for (i = 0; i < argc; i++) - argv_offsets[i] = addr_native_to_app(argv[i]); + argv_offsets[i] = (uint32)addr_native_to_app(argv[i]); wasm_runtime_free(argv); return 0; @@ -168,8 +168,8 @@ wasi_args_sizes_get(wasm_exec_env_t exec_env, uint32 *argc_app, if (!wasi_ctx) return (wasi_errno_t)-1; - if (!validate_native_addr(argc_app, sizeof(uint32)) - || !validate_native_addr(argv_buf_size_app, sizeof(uint32))) + if (!validate_native_addr(argc_app, (uint64)sizeof(uint32)) + || !validate_native_addr(argv_buf_size_app, (uint64)sizeof(uint32))) return (wasi_errno_t)-1; argv_environ = wasi_ctx->argv_environ; @@ -190,7 +190,7 @@ wasi_clock_res_get(wasm_exec_env_t exec_env, { wasm_module_inst_t module_inst = get_module_inst(exec_env); - if (!validate_native_addr(resolution, sizeof(wasi_timestamp_t))) + if (!validate_native_addr(resolution, (uint64)sizeof(wasi_timestamp_t))) return (wasi_errno_t)-1; return os_clock_res_get(clock_id, resolution); @@ -204,7 +204,7 @@ wasi_clock_time_get(wasm_exec_env_t exec_env, { wasm_module_inst_t module_inst = get_module_inst(exec_env); - if (!validate_native_addr(time, sizeof(wasi_timestamp_t))) + if (!validate_native_addr(time, (uint64)sizeof(wasi_timestamp_t))) return (wasi_errno_t)-1; return os_clock_time_get(clock_id, precision, time); @@ -233,9 +233,9 @@ wasi_environ_get(wasm_exec_env_t exec_env, uint32 *environ_offsets, total_size = sizeof(int32) * ((uint64)environ_count + 1); if (total_size >= UINT32_MAX - || !validate_native_addr(environ_offsets, (uint32)total_size) + || !validate_native_addr(environ_offsets, total_size) || environ_buf_size >= UINT32_MAX - || !validate_native_addr(environ_buf, (uint32)environ_buf_size)) + || !validate_native_addr(environ_buf, (uint64)environ_buf_size)) return (wasi_errno_t)-1; total_size = sizeof(char *) * (((uint64)environ_count + 1)); @@ -251,7 +251,7 @@ wasi_environ_get(wasm_exec_env_t exec_env, uint32 *environ_offsets, } for (i = 0; i < environ_count; i++) - environ_offsets[i] = addr_native_to_app(environs[i]); + environ_offsets[i] = (uint32)addr_native_to_app(environs[i]); wasm_runtime_free(environs); return 0; @@ -271,8 +271,8 @@ wasi_environ_sizes_get(wasm_exec_env_t exec_env, uint32 *environ_count_app, if (!wasi_ctx) return (wasi_errno_t)-1; - if (!validate_native_addr(environ_count_app, sizeof(uint32)) - || !validate_native_addr(environ_buf_size_app, sizeof(uint32))) + if (!validate_native_addr(environ_count_app, (uint64)sizeof(uint32)) + || !validate_native_addr(environ_buf_size_app, (uint64)sizeof(uint32))) return (wasi_errno_t)-1; err = wasmtime_ssp_environ_sizes_get(argv_environ, &environ_count, @@ -299,7 +299,7 @@ wasi_fd_prestat_get(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return (wasi_errno_t)-1; - if (!validate_native_addr(prestat_app, sizeof(wasi_prestat_app_t))) + if (!validate_native_addr(prestat_app, (uint64)sizeof(wasi_prestat_app_t))) return (wasi_errno_t)-1; err = wasmtime_ssp_fd_prestat_get(prestats, fd, &prestat); @@ -369,9 +369,9 @@ wasi_fd_pread(wasm_exec_env_t exec_env, wasi_fd_t fd, iovec_app_t *iovec_app, return (wasi_errno_t)-1; total_size = sizeof(iovec_app_t) * (uint64)iovs_len; - if (!validate_native_addr(nread_app, (uint32)sizeof(uint32)) + if (!validate_native_addr(nread_app, (uint64)sizeof(uint32)) || total_size >= UINT32_MAX - || !validate_native_addr(iovec_app, (uint32)total_size)) + || !validate_native_addr(iovec_app, total_size)) return (wasi_errno_t)-1; total_size = sizeof(wasi_iovec_t) * (uint64)iovs_len; @@ -382,11 +382,12 @@ wasi_fd_pread(wasm_exec_env_t exec_env, wasi_fd_t fd, iovec_app_t *iovec_app, iovec = iovec_begin; for (i = 0; i < iovs_len; i++, iovec_app++, iovec++) { - if (!validate_app_addr(iovec_app->buf_offset, iovec_app->buf_len)) { + if (!validate_app_addr((uint64)iovec_app->buf_offset, + (uint64)iovec_app->buf_len)) { err = (wasi_errno_t)-1; goto fail; } - iovec->buf = (void *)addr_app_to_native(iovec_app->buf_offset); + iovec->buf = (void *)addr_app_to_native((uint64)iovec_app->buf_offset); iovec->buf_len = iovec_app->buf_len; } @@ -423,9 +424,9 @@ wasi_fd_pwrite(wasm_exec_env_t exec_env, wasi_fd_t fd, return (wasi_errno_t)-1; total_size = sizeof(iovec_app_t) * (uint64)iovs_len; - if (!validate_native_addr(nwritten_app, (uint32)sizeof(uint32)) + if (!validate_native_addr(nwritten_app, (uint64)sizeof(uint32)) || total_size >= UINT32_MAX - || !validate_native_addr((void *)iovec_app, (uint32)total_size)) + || !validate_native_addr((void *)iovec_app, total_size)) return (wasi_errno_t)-1; total_size = sizeof(wasi_ciovec_t) * (uint64)iovs_len; @@ -436,11 +437,12 @@ wasi_fd_pwrite(wasm_exec_env_t exec_env, wasi_fd_t fd, ciovec = ciovec_begin; for (i = 0; i < iovs_len; i++, iovec_app++, ciovec++) { - if (!validate_app_addr(iovec_app->buf_offset, iovec_app->buf_len)) { + if (!validate_app_addr((uint64)iovec_app->buf_offset, + (uint64)iovec_app->buf_len)) { err = (wasi_errno_t)-1; goto fail; } - ciovec->buf = (char *)addr_app_to_native(iovec_app->buf_offset); + ciovec->buf = (char *)addr_app_to_native((uint64)iovec_app->buf_offset); ciovec->buf_len = iovec_app->buf_len; } @@ -476,9 +478,9 @@ wasi_fd_read(wasm_exec_env_t exec_env, wasi_fd_t fd, return (wasi_errno_t)-1; total_size = sizeof(iovec_app_t) * (uint64)iovs_len; - if (!validate_native_addr(nread_app, (uint32)sizeof(uint32)) + if (!validate_native_addr(nread_app, (uint64)sizeof(uint32)) || total_size >= UINT32_MAX - || !validate_native_addr((void *)iovec_app, (uint32)total_size)) + || !validate_native_addr((void *)iovec_app, total_size)) return (wasi_errno_t)-1; total_size = sizeof(wasi_iovec_t) * (uint64)iovs_len; @@ -489,11 +491,12 @@ wasi_fd_read(wasm_exec_env_t exec_env, wasi_fd_t fd, iovec = iovec_begin; for (i = 0; i < iovs_len; i++, iovec_app++, iovec++) { - if (!validate_app_addr(iovec_app->buf_offset, iovec_app->buf_len)) { + if (!validate_app_addr((uint64)iovec_app->buf_offset, + (uint64)iovec_app->buf_len)) { err = (wasi_errno_t)-1; goto fail; } - iovec->buf = (void *)addr_app_to_native(iovec_app->buf_offset); + iovec->buf = (void *)addr_app_to_native((uint64)iovec_app->buf_offset); iovec->buf_len = iovec_app->buf_len; } @@ -537,7 +540,7 @@ wasi_fd_seek(wasm_exec_env_t exec_env, wasi_fd_t fd, wasi_filedelta_t offset, if (!wasi_ctx) return (wasi_errno_t)-1; - if (!validate_native_addr(newoffset, sizeof(wasi_filesize_t))) + if (!validate_native_addr(newoffset, (uint64)sizeof(wasi_filesize_t))) return (wasi_errno_t)-1; return wasmtime_ssp_fd_seek(exec_env, curfds, fd, offset, whence, @@ -554,7 +557,7 @@ wasi_fd_tell(wasm_exec_env_t exec_env, wasi_fd_t fd, wasi_filesize_t *newoffset) if (!wasi_ctx) return (wasi_errno_t)-1; - if (!validate_native_addr(newoffset, sizeof(wasi_filesize_t))) + if (!validate_native_addr(newoffset, (uint64)sizeof(wasi_filesize_t))) return (wasi_errno_t)-1; return wasmtime_ssp_fd_tell(exec_env, curfds, fd, newoffset); @@ -573,7 +576,7 @@ wasi_fd_fdstat_get(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return (wasi_errno_t)-1; - if (!validate_native_addr(fdstat_app, sizeof(wasi_fdstat_t))) + if (!validate_native_addr(fdstat_app, (uint64)sizeof(wasi_fdstat_t))) return (wasi_errno_t)-1; err = wasmtime_ssp_fd_fdstat_get(exec_env, curfds, fd, &fdstat); @@ -645,9 +648,9 @@ wasi_fd_write(wasm_exec_env_t exec_env, wasi_fd_t fd, return (wasi_errno_t)-1; total_size = sizeof(iovec_app_t) * (uint64)iovs_len; - if (!validate_native_addr(nwritten_app, (uint32)sizeof(uint32)) + if (!validate_native_addr(nwritten_app, (uint64)sizeof(uint32)) || total_size >= UINT32_MAX - || !validate_native_addr((void *)iovec_app, (uint32)total_size)) + || !validate_native_addr((void *)iovec_app, total_size)) return (wasi_errno_t)-1; total_size = sizeof(wasi_ciovec_t) * (uint64)iovs_len; @@ -658,11 +661,12 @@ wasi_fd_write(wasm_exec_env_t exec_env, wasi_fd_t fd, ciovec = ciovec_begin; for (i = 0; i < iovs_len; i++, iovec_app++, ciovec++) { - if (!validate_app_addr(iovec_app->buf_offset, iovec_app->buf_len)) { + if (!validate_app_addr((uint64)iovec_app->buf_offset, + (uint64)iovec_app->buf_len)) { err = (wasi_errno_t)-1; goto fail; } - ciovec->buf = (char *)addr_app_to_native(iovec_app->buf_offset); + ciovec->buf = (char *)addr_app_to_native((uint64)iovec_app->buf_offset); ciovec->buf_len = iovec_app->buf_len; } @@ -759,7 +763,7 @@ wasi_path_open(wasm_exec_env_t exec_env, wasi_fd_t dirfd, if (!wasi_ctx) return (wasi_errno_t)-1; - if (!validate_native_addr(fd_app, sizeof(wasi_fd_t))) + if (!validate_native_addr(fd_app, (uint64)sizeof(wasi_fd_t))) return (wasi_errno_t)-1; err = wasmtime_ssp_path_open(exec_env, curfds, dirfd, dirflags, path, @@ -783,7 +787,7 @@ wasi_fd_readdir(wasm_exec_env_t exec_env, wasi_fd_t fd, void *buf, if (!wasi_ctx) return (wasi_errno_t)-1; - if (!validate_native_addr(bufused_app, sizeof(uint32))) + if (!validate_native_addr(bufused_app, (uint64)sizeof(uint32))) return (wasi_errno_t)-1; err = wasmtime_ssp_fd_readdir(exec_env, curfds, fd, buf, buf_len, cookie, @@ -809,7 +813,7 @@ wasi_path_readlink(wasm_exec_env_t exec_env, wasi_fd_t fd, const char *path, if (!wasi_ctx) return (wasi_errno_t)-1; - if (!validate_native_addr(bufused_app, sizeof(uint32))) + if (!validate_native_addr(bufused_app, (uint64)sizeof(uint32))) return (wasi_errno_t)-1; err = wasmtime_ssp_path_readlink(exec_env, curfds, fd, path, path_len, buf, @@ -849,7 +853,7 @@ wasi_fd_filestat_get(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return (wasi_errno_t)-1; - if (!validate_native_addr(filestat, sizeof(wasi_filestat_t))) + if (!validate_native_addr(filestat, (uint64)sizeof(wasi_filestat_t))) return (wasi_errno_t)-1; return wasmtime_ssp_fd_filestat_get(exec_env, curfds, fd, filestat); @@ -897,7 +901,7 @@ wasi_path_filestat_get(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return (wasi_errno_t)-1; - if (!validate_native_addr(filestat, sizeof(wasi_filestat_t))) + if (!validate_native_addr(filestat, (uint64)sizeof(wasi_filestat_t))) return (wasi_errno_t)-1; return wasmtime_ssp_path_filestat_get(exec_env, curfds, fd, flags, path, @@ -1083,9 +1087,9 @@ wasi_poll_oneoff(wasm_exec_env_t exec_env, const wasi_subscription_t *in, if (!wasi_ctx) return (wasi_errno_t)-1; - if (!validate_native_addr((void *)in, sizeof(wasi_subscription_t)) - || !validate_native_addr(out, sizeof(wasi_event_t)) - || !validate_native_addr(nevents_app, sizeof(uint32))) + if (!validate_native_addr((void *)in, (uint64)sizeof(wasi_subscription_t)) + || !validate_native_addr(out, (uint64)sizeof(wasi_event_t)) + || !validate_native_addr(nevents_app, (uint64)sizeof(uint32))) return (wasi_errno_t)-1; #if WASM_ENABLE_THREAD_MGR == 0 @@ -1160,7 +1164,7 @@ wasi_sock_addr_local(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return __WASI_EACCES; - if (!validate_native_addr(addr, sizeof(__wasi_addr_t))) + if (!validate_native_addr(addr, (uint64)sizeof(__wasi_addr_t))) return __WASI_EINVAL; curfds = wasi_ctx_get_curfds(wasi_ctx); @@ -1179,7 +1183,7 @@ wasi_sock_addr_remote(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return __WASI_EACCES; - if (!validate_native_addr(addr, sizeof(__wasi_addr_t))) + if (!validate_native_addr(addr, (uint64)sizeof(__wasi_addr_t))) return __WASI_EINVAL; curfds = wasi_ctx_get_curfds(wasi_ctx); @@ -1264,7 +1268,7 @@ wasi_sock_get_broadcast(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return __WASI_EACCES; - if (!validate_native_addr(is_enabled, sizeof(bool))) + if (!validate_native_addr(is_enabled, (uint64)sizeof(bool))) return __WASI_EINVAL; curfds = wasi_ctx_get_curfds(wasi_ctx); @@ -1283,7 +1287,7 @@ wasi_sock_get_keep_alive(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return __WASI_EACCES; - if (!validate_native_addr(is_enabled, sizeof(bool))) + if (!validate_native_addr(is_enabled, (uint64)sizeof(bool))) return __WASI_EINVAL; curfds = wasi_ctx_get_curfds(wasi_ctx); @@ -1302,8 +1306,8 @@ wasi_sock_get_linger(wasm_exec_env_t exec_env, wasi_fd_t fd, bool *is_enabled, if (!wasi_ctx) return __WASI_EACCES; - if (!validate_native_addr(is_enabled, sizeof(bool)) - || !validate_native_addr(linger_s, sizeof(int))) + if (!validate_native_addr(is_enabled, (uint64)sizeof(bool)) + || !validate_native_addr(linger_s, (uint64)sizeof(int))) return __WASI_EINVAL; curfds = wasi_ctx_get_curfds(wasi_ctx); @@ -1323,7 +1327,7 @@ wasi_sock_get_recv_buf_size(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return __WASI_EACCES; - if (!validate_native_addr(size, sizeof(wasi_size_t))) + if (!validate_native_addr(size, (uint64)sizeof(wasi_size_t))) return __WASI_EINVAL; curfds = wasi_ctx_get_curfds(wasi_ctx); @@ -1342,7 +1346,7 @@ wasi_sock_get_recv_timeout(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return __WASI_EACCES; - if (!validate_native_addr(timeout_us, sizeof(uint64_t))) + if (!validate_native_addr(timeout_us, (uint64)sizeof(uint64_t))) return __WASI_EINVAL; curfds = wasi_ctx_get_curfds(wasi_ctx); @@ -1361,7 +1365,7 @@ wasi_sock_get_reuse_addr(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return __WASI_EACCES; - if (!validate_native_addr(is_enabled, sizeof(bool))) + if (!validate_native_addr(is_enabled, (uint64)sizeof(bool))) return __WASI_EINVAL; curfds = wasi_ctx_get_curfds(wasi_ctx); @@ -1380,7 +1384,7 @@ wasi_sock_get_reuse_port(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return __WASI_EACCES; - if (!validate_native_addr(is_enabled, sizeof(bool))) + if (!validate_native_addr(is_enabled, (uint64)sizeof(bool))) return __WASI_EINVAL; curfds = wasi_ctx_get_curfds(wasi_ctx); @@ -1399,7 +1403,7 @@ wasi_sock_get_send_buf_size(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return __WASI_EACCES; - if (!validate_native_addr(size, sizeof(__wasi_size_t))) + if (!validate_native_addr(size, (uint64)sizeof(__wasi_size_t))) return __WASI_EINVAL; curfds = wasi_ctx_get_curfds(wasi_ctx); @@ -1418,7 +1422,7 @@ wasi_sock_get_send_timeout(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return __WASI_EACCES; - if (!validate_native_addr(timeout_us, sizeof(uint64_t))) + if (!validate_native_addr(timeout_us, (uint64)sizeof(uint64_t))) return __WASI_EINVAL; curfds = wasi_ctx_get_curfds(wasi_ctx); @@ -1437,7 +1441,7 @@ wasi_sock_get_tcp_fastopen_connect(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return __WASI_EACCES; - if (!validate_native_addr(is_enabled, sizeof(bool))) + if (!validate_native_addr(is_enabled, (uint64)sizeof(bool))) return __WASI_EINVAL; curfds = wasi_ctx_get_curfds(wasi_ctx); @@ -1457,7 +1461,7 @@ wasi_sock_get_tcp_no_delay(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return __WASI_EACCES; - if (!validate_native_addr(is_enabled, sizeof(bool))) + if (!validate_native_addr(is_enabled, (uint64)sizeof(bool))) return __WASI_EINVAL; curfds = wasi_ctx_get_curfds(wasi_ctx); @@ -1476,7 +1480,7 @@ wasi_sock_get_tcp_quick_ack(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return __WASI_EACCES; - if (!validate_native_addr(is_enabled, sizeof(bool))) + if (!validate_native_addr(is_enabled, (uint64)sizeof(bool))) return __WASI_EINVAL; curfds = wasi_ctx_get_curfds(wasi_ctx); @@ -1496,7 +1500,7 @@ wasi_sock_get_tcp_keep_idle(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return __WASI_EACCES; - if (!validate_native_addr(time_s, sizeof(uint32_t))) + if (!validate_native_addr(time_s, (uint64)sizeof(uint32_t))) return __WASI_EINVAL; curfds = wasi_ctx_get_curfds(wasi_ctx); @@ -1515,7 +1519,7 @@ wasi_sock_get_tcp_keep_intvl(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return __WASI_EACCES; - if (!validate_native_addr(time_s, sizeof(uint32_t))) + if (!validate_native_addr(time_s, (uint64)sizeof(uint32_t))) return __WASI_EINVAL; curfds = wasi_ctx_get_curfds(wasi_ctx); @@ -1534,7 +1538,7 @@ wasi_sock_get_ip_multicast_loop(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return __WASI_EACCES; - if (!validate_native_addr(is_enabled, sizeof(bool))) + if (!validate_native_addr(is_enabled, (uint64)sizeof(bool))) return __WASI_EINVAL; curfds = wasi_ctx_get_curfds(wasi_ctx); @@ -1553,7 +1557,7 @@ wasi_sock_get_ip_ttl(wasm_exec_env_t exec_env, wasi_fd_t fd, uint8_t *ttl_s) if (!wasi_ctx) return __WASI_EACCES; - if (!validate_native_addr(ttl_s, sizeof(uint8_t))) + if (!validate_native_addr(ttl_s, (uint64)sizeof(uint8_t))) return __WASI_EINVAL; curfds = wasi_ctx_get_curfds(wasi_ctx); @@ -1572,7 +1576,7 @@ wasi_sock_get_ip_multicast_ttl(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return __WASI_EACCES; - if (!validate_native_addr(ttl_s, sizeof(uint8_t))) + if (!validate_native_addr(ttl_s, (uint64)sizeof(uint8_t))) return __WASI_EINVAL; curfds = wasi_ctx_get_curfds(wasi_ctx); @@ -1591,7 +1595,7 @@ wasi_sock_get_ipv6_only(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return __WASI_EACCES; - if (!validate_native_addr(is_enabled, sizeof(bool))) + if (!validate_native_addr(is_enabled, (uint64)sizeof(bool))) return __WASI_EINVAL; curfds = wasi_ctx_get_curfds(wasi_ctx); @@ -1884,7 +1888,7 @@ wasi_sock_set_ip_add_membership(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return __WASI_EACCES; - if (!validate_native_addr(imr_multiaddr, sizeof(__wasi_addr_ip_t))) + if (!validate_native_addr(imr_multiaddr, (uint64)sizeof(__wasi_addr_ip_t))) return __WASI_EINVAL; curfds = wasi_ctx_get_curfds(wasi_ctx); @@ -1905,7 +1909,7 @@ wasi_sock_set_ip_drop_membership(wasm_exec_env_t exec_env, wasi_fd_t fd, if (!wasi_ctx) return __WASI_EACCES; - if (!validate_native_addr(imr_multiaddr, sizeof(__wasi_addr_ip_t))) + if (!validate_native_addr(imr_multiaddr, (uint64)sizeof(__wasi_addr_ip_t))) return __WASI_EINVAL; curfds = wasi_ctx_get_curfds(wasi_ctx); @@ -1975,7 +1979,7 @@ allocate_iovec_app_buffer(wasm_module_inst_t module_inst, total_size = sizeof(iovec_app_t) * (uint64)data_len; if (total_size >= UINT32_MAX - || !validate_native_addr((void *)data, (uint32)total_size)) + || !validate_native_addr((void *)data, total_size)) return __WASI_EINVAL; for (total_size = 0, i = 0; i < data_len; i++, data++) { @@ -2013,7 +2017,8 @@ copy_buffer_to_iovec_app(wasm_module_inst_t module_inst, uint8 *buf_begin, for (i = 0; i < data_len; data++, i++) { char *native_addr; - if (!validate_app_addr(data->buf_offset, data->buf_len)) { + if (!validate_app_addr((uint64)data->buf_offset, + (uint64)data->buf_len)) { return __WASI_EINVAL; } @@ -2032,7 +2037,7 @@ copy_buffer_to_iovec_app(wasm_module_inst_t module_inst, uint8 *buf_begin, */ size_to_copy_into_iovec = min_uint32(data->buf_len, size_to_copy); - native_addr = (void *)addr_app_to_native(data->buf_offset); + native_addr = (void *)addr_app_to_native((uint64)data->buf_offset); bh_memcpy_s(native_addr, size_to_copy_into_iovec, buf, size_to_copy_into_iovec); buf += size_to_copy_into_iovec; @@ -2064,7 +2069,7 @@ wasi_sock_recv_from(wasm_exec_env_t exec_env, wasi_fd_t sock, return __WASI_EINVAL; } - if (!validate_native_addr(ro_data_len, (uint32)sizeof(uint32))) + if (!validate_native_addr(ro_data_len, (uint64)sizeof(uint32))) return __WASI_EINVAL; err = allocate_iovec_app_buffer(module_inst, ri_data, ri_data_len, @@ -2103,7 +2108,7 @@ wasi_sock_recv(wasm_exec_env_t exec_env, wasi_fd_t sock, iovec_app_t *ri_data, __wasi_addr_t src_addr; wasi_errno_t error; - if (!validate_native_addr(ro_flags, (uint32)sizeof(wasi_roflags_t))) + if (!validate_native_addr(ro_flags, (uint64)sizeof(wasi_roflags_t))) return __WASI_EINVAL; error = wasi_sock_recv_from(exec_env, sock, ri_data, ri_data_len, ri_flags, @@ -2134,12 +2139,13 @@ convert_iovec_app_to_buffer(wasm_module_inst_t module_inst, for (i = 0; i < si_data_len; i++, si_data++) { char *native_addr; - if (!validate_app_addr(si_data->buf_offset, si_data->buf_len)) { + if (!validate_app_addr((uint64)si_data->buf_offset, + (uint64)si_data->buf_len)) { wasm_runtime_free(*buf_ptr); return __WASI_EINVAL; } - native_addr = (char *)addr_app_to_native(si_data->buf_offset); + native_addr = (char *)addr_app_to_native((uint64)si_data->buf_offset); bh_memcpy_s(buf, si_data->buf_len, native_addr, si_data->buf_len); buf += si_data->buf_len; } @@ -2168,7 +2174,7 @@ wasi_sock_send(wasm_exec_env_t exec_env, wasi_fd_t sock, return __WASI_EINVAL; } - if (!validate_native_addr(so_data_len, sizeof(uint32))) + if (!validate_native_addr(so_data_len, (uint64)sizeof(uint32))) return __WASI_EINVAL; err = convert_iovec_app_to_buffer(module_inst, si_data, si_data_len, &buf, @@ -2209,7 +2215,7 @@ wasi_sock_send_to(wasm_exec_env_t exec_env, wasi_fd_t sock, return __WASI_EINVAL; } - if (!validate_native_addr(so_data_len, sizeof(uint32))) + if (!validate_native_addr(so_data_len, (uint64)sizeof(uint32))) return __WASI_EINVAL; err = convert_iovec_app_to_buffer(module_inst, si_data, si_data_len, &buf, diff --git a/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/src/blocking_op.h b/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/src/blocking_op.h index 9c36d7df6..a32e5d662 100644 --- a/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/src/blocking_op.h +++ b/core/iwasm/libraries/libc-wasi/sandboxed-system-primitives/src/blocking_op.h @@ -3,6 +3,9 @@ * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ +#ifndef _BLOCKING_OP_H_ +#define _BLOCKING_OP_H_ + #include "bh_platform.h" #include "wasm_export.h" @@ -57,3 +60,5 @@ __wasi_errno_t blocking_op_poll(wasm_exec_env_t exec_env, struct pollfd *pfds, nfds_t nfds, int timeout, int *retp); #endif + +#endif /* end of _BLOCKING_OP_H_ */ diff --git a/core/iwasm/libraries/thread-mgr/thread_manager.c b/core/iwasm/libraries/thread-mgr/thread_manager.c index bdfc38dde..ac4deb92c 100644 --- a/core/iwasm/libraries/thread-mgr/thread_manager.c +++ b/core/iwasm/libraries/thread-mgr/thread_manager.c @@ -139,14 +139,14 @@ final: /* The caller must not have any locks */ bool -wasm_cluster_allocate_aux_stack(WASMExecEnv *exec_env, uint32 *p_start, +wasm_cluster_allocate_aux_stack(WASMExecEnv *exec_env, uint64 *p_start, uint32 *p_size) { WASMCluster *cluster = wasm_exec_env_get_cluster(exec_env); #if WASM_ENABLE_HEAP_AUX_STACK_ALLOCATION != 0 WASMModuleInstanceCommon *module_inst = wasm_exec_env_get_module_inst(exec_env); - uint32 stack_end; + uint64 stack_end; stack_end = wasm_runtime_module_malloc_internal(module_inst, exec_env, cluster->stack_size, NULL); @@ -185,7 +185,7 @@ wasm_cluster_allocate_aux_stack(WASMExecEnv *exec_env, uint32 *p_start, /* The caller must not have any locks */ bool -wasm_cluster_free_aux_stack(WASMExecEnv *exec_env, uint32 start) +wasm_cluster_free_aux_stack(WASMExecEnv *exec_env, uint64 start) { WASMCluster *cluster = wasm_exec_env_get_cluster(exec_env); @@ -223,7 +223,8 @@ WASMCluster * wasm_cluster_create(WASMExecEnv *exec_env) { WASMCluster *cluster; - uint32 aux_stack_start, aux_stack_size; + uint32 aux_stack_size; + uint64 aux_stack_start; bh_assert(exec_env->cluster == NULL); if (!(cluster = wasm_runtime_malloc(sizeof(WASMCluster)))) { @@ -280,7 +281,7 @@ wasm_cluster_create(WASMExecEnv *exec_env) #if WASM_ENABLE_HEAP_AUX_STACK_ALLOCATION == 0 if (cluster_max_thread_num != 0) { - uint64 total_size = cluster_max_thread_num * sizeof(uint32); + uint64 total_size = cluster_max_thread_num * sizeof(uint64); uint32 i; if (total_size >= UINT32_MAX || !(cluster->stack_tops = @@ -496,7 +497,8 @@ wasm_cluster_spawn_exec_env(WASMExecEnv *exec_env) wasm_module_t module; wasm_module_inst_t new_module_inst; WASMExecEnv *new_exec_env; - uint32 aux_stack_start, aux_stack_size; + uint32 aux_stack_size; + uint64 aux_stack_start; uint32 stack_size = 8192; if (!module_inst || !(module = wasm_exec_env_get_module(exec_env))) { @@ -504,7 +506,7 @@ wasm_cluster_spawn_exec_env(WASMExecEnv *exec_env) } if (!(new_module_inst = wasm_runtime_instantiate_internal( - module, module_inst, exec_env, stack_size, 0, NULL, 0))) { + module, module_inst, exec_env, stack_size, 0, 0, NULL, 0))) { return NULL; } @@ -556,6 +558,7 @@ wasm_cluster_spawn_exec_env(WASMExecEnv *exec_env) aux_stack_size)) { goto fail3; } + new_exec_env->is_aux_stack_allocated = true; /* Inherit suspend_flags of parent thread */ new_exec_env->suspend_flags.flags = @@ -601,9 +604,11 @@ wasm_cluster_destroy_spawned_exec_env(WASMExecEnv *exec_env) exec_env_tls = exec_env; } - /* Free aux stack space */ + /* Free aux stack space which was allocated in + wasm_cluster_spawn_exec_env */ + bh_assert(exec_env_tls->is_aux_stack_allocated); wasm_cluster_free_aux_stack(exec_env_tls, - exec_env->aux_stack_bottom.bottom); + (uint64)exec_env->aux_stack_bottom); os_mutex_lock(&cluster->lock); @@ -653,7 +658,9 @@ thread_manager_start_routine(void *arg) #endif /* Free aux stack space */ - wasm_cluster_free_aux_stack(exec_env, exec_env->aux_stack_bottom.bottom); + if (exec_env->is_aux_stack_allocated) + wasm_cluster_free_aux_stack(exec_env, + (uint64)exec_env->aux_stack_bottom); os_mutex_lock(&cluster_list_lock); @@ -693,7 +700,7 @@ thread_manager_start_routine(void *arg) int32 wasm_cluster_create_thread(WASMExecEnv *exec_env, wasm_module_inst_t module_inst, - bool is_aux_stack_allocated, uint32 aux_stack_start, + bool is_aux_stack_allocated, uint64 aux_stack_start, uint32 aux_stack_size, void *(*thread_routine)(void *), void *arg) { @@ -721,11 +728,13 @@ wasm_cluster_create_thread(WASMExecEnv *exec_env, aux_stack_size)) { goto fail2; } + new_exec_env->is_aux_stack_allocated = true; } else { /* Disable aux stack */ - new_exec_env->aux_stack_boundary.boundary = 0; - new_exec_env->aux_stack_bottom.bottom = UINT32_MAX; + new_exec_env->aux_stack_boundary = 0; + new_exec_env->aux_stack_bottom = UINTPTR_MAX; + new_exec_env->is_aux_stack_allocated = false; } /* Inherit suspend_flags of parent thread */ @@ -779,10 +788,10 @@ wasm_cluster_dup_c_api_imports(WASMModuleInstanceCommon *module_inst_dst, #if WASM_ENABLE_INTERP != 0 if (module_inst_src->module_type == Wasm_Module_Bytecode) { - new_c_api_func_imports = &(((WASMModuleInstance *)module_inst_dst) - ->e->common.c_api_func_imports); - c_api_func_imports = ((const WASMModuleInstance *)module_inst_src) - ->e->common.c_api_func_imports; + new_c_api_func_imports = + &(((WASMModuleInstance *)module_inst_dst)->c_api_func_imports); + c_api_func_imports = + ((const WASMModuleInstance *)module_inst_src)->c_api_func_imports; import_func_count = ((WASMModule *)(((const WASMModuleInstance *)module_inst_src) ->module)) @@ -791,13 +800,10 @@ wasm_cluster_dup_c_api_imports(WASMModuleInstanceCommon *module_inst_dst, #endif #if WASM_ENABLE_AOT != 0 if (module_inst_src->module_type == Wasm_Module_AoT) { - AOTModuleInstanceExtra *e = - (AOTModuleInstanceExtra *)((AOTModuleInstance *)module_inst_dst)->e; - new_c_api_func_imports = &(e->common.c_api_func_imports); - - e = (AOTModuleInstanceExtra *)((AOTModuleInstance *)module_inst_src)->e; - c_api_func_imports = e->common.c_api_func_imports; - + new_c_api_func_imports = + &(((AOTModuleInstance *)module_inst_dst)->c_api_func_imports); + c_api_func_imports = + ((const AOTModuleInstance *)module_inst_src)->c_api_func_imports; import_func_count = ((AOTModule *)(((AOTModuleInstance *)module_inst_src)->module)) ->import_func_count; @@ -1050,7 +1056,9 @@ wasm_cluster_exit_thread(WASMExecEnv *exec_env, void *retval) #endif /* Free aux stack space */ - wasm_cluster_free_aux_stack(exec_env, exec_env->aux_stack_bottom.bottom); + if (exec_env->is_aux_stack_allocated) + wasm_cluster_free_aux_stack(exec_env, + (uint64)exec_env->aux_stack_bottom); /* App exit the thread, free the resources before exit native thread */ diff --git a/core/iwasm/libraries/thread-mgr/thread_manager.h b/core/iwasm/libraries/thread-mgr/thread_manager.h index 06d208836..ee2383a33 100644 --- a/core/iwasm/libraries/thread-mgr/thread_manager.h +++ b/core/iwasm/libraries/thread-mgr/thread_manager.h @@ -30,7 +30,7 @@ struct WASMCluster { /* The aux stack of a module with shared memory will be divided into several segments. This array store the stack top of different segments */ - uint32 *stack_tops; + uint64 *stack_tops; /* Record which segments are occupied */ bool *stack_segment_occupied; #endif @@ -89,7 +89,7 @@ wasm_cluster_dup_c_api_imports(WASMModuleInstanceCommon *module_inst_dst, int32 wasm_cluster_create_thread(WASMExecEnv *exec_env, wasm_module_inst_t module_inst, - bool is_aux_stack_allocated, uint32 aux_stack_start, + bool is_aux_stack_allocated, uint64 aux_stack_start, uint32 aux_stack_size, void *(*thread_routine)(void *), void *arg); @@ -231,11 +231,11 @@ void wasm_cluster_traverse_unlock(WASMExecEnv *exec_env); bool -wasm_cluster_allocate_aux_stack(WASMExecEnv *exec_env, uint32 *p_start, +wasm_cluster_allocate_aux_stack(WASMExecEnv *exec_env, uint64 *p_start, uint32 *p_size); bool -wasm_cluster_free_aux_stack(WASMExecEnv *exec_env, uint32 start); +wasm_cluster_free_aux_stack(WASMExecEnv *exec_env, uint64 start); #ifdef __cplusplus } diff --git a/core/iwasm/libraries/wasi-nn/src/utils/wasi_nn_app_native.c b/core/iwasm/libraries/wasi-nn/src/utils/wasi_nn_app_native.c index fe04b657b..44aef5359 100644 --- a/core/iwasm/libraries/wasi-nn/src/utils/wasi_nn_app_native.c +++ b/core/iwasm/libraries/wasi-nn/src/utils/wasi_nn_app_native.c @@ -10,49 +10,75 @@ graph_builder_app_native(wasm_module_inst_t instance, graph_builder_wasm *builder_wasm, graph_builder *builder) { - if (!wasm_runtime_validate_app_addr(instance, builder_wasm->buf_offset, - builder_wasm->size * sizeof(uint8_t))) { + if (!wasm_runtime_validate_app_addr( + instance, (uint64)builder_wasm->buf_offset, + (uint64)builder_wasm->size * sizeof(uint8_t))) { NN_ERR_PRINTF("builder_wasm->buf_offset is invalid"); return invalid_argument; } builder->buf = (uint8_t *)wasm_runtime_addr_app_to_native( - instance, builder_wasm->buf_offset); + instance, (uint64)builder_wasm->buf_offset); builder->size = builder_wasm->size; return success; } +/** + * builder_array_wasm is consisted of {builder_wasm, size} + */ +#if WASM_ENABLE_WASI_EPHEMERAL_NN != 0 +error +graph_builder_array_app_native(wasm_module_inst_t instance, + graph_builder_wasm *builder_wasm, uint32_t size, + graph_builder_array *builder_array) +#else /* WASM_ENABLE_WASI_EPHEMERAL_NN == 0 */ error graph_builder_array_app_native(wasm_module_inst_t instance, graph_builder_array_wasm *builder_array_wasm, graph_builder_array *builder_array) +#endif /* WASM_ENABLE_WASI_EPHEMERAL_NN != 0 */ { - if (!wasm_runtime_validate_native_addr(instance, builder_array_wasm, - sizeof(graph_builder_array_wasm))) { +#if WASM_ENABLE_WASI_EPHEMERAL_NN != 0 +#define array_size size +#else /* WASM_ENABLE_WASI_EPHEMERAL_NN == 0 */ +#define array_size builder_array_wasm->size + + if (!wasm_runtime_validate_native_addr( + instance, builder_array_wasm, + (uint64)sizeof(graph_builder_array_wasm))) { NN_ERR_PRINTF("builder_array_wasm is invalid"); return invalid_argument; } +#endif /* WASM_ENABLE_WASI_EPHEMERAL_NN != 0 */ - NN_DBG_PRINTF("Graph builder array contains %d elements", - builder_array_wasm->size); + NN_DBG_PRINTF("Graph builder array contains %d elements", array_size); +#if WASM_ENABLE_WASI_EPHEMERAL_NN != 0 + if (!wasm_runtime_validate_native_addr(instance, builder_wasm, + (uint64)array_size + * sizeof(graph_builder_wasm))) { + NN_ERR_PRINTF("builder_wasm is invalid"); + return invalid_argument; + } +#else /* WASM_ENABLE_WASI_EPHEMERAL_NN == 0 */ if (!wasm_runtime_validate_app_addr( - instance, builder_array_wasm->buf_offset, - builder_array_wasm->size * sizeof(graph_builder_wasm))) { + instance, (uint64)builder_array_wasm->buf_offset, + (uint64)array_size * sizeof(graph_builder_wasm))) { NN_ERR_PRINTF("builder_array_wasm->buf_offset is invalid"); return invalid_argument; } graph_builder_wasm *builder_wasm = (graph_builder_wasm *)wasm_runtime_addr_app_to_native( - instance, builder_array_wasm->buf_offset); + instance, (uint64)builder_array_wasm->buf_offset); +#endif /* WASM_ENABLE_WASI_EPHEMERAL_NN != 0 */ graph_builder *builder = (graph_builder *)wasm_runtime_malloc( - builder_array_wasm->size * sizeof(graph_builder)); + array_size * sizeof(graph_builder)); if (builder == NULL) return missing_memory; - for (uint32_t i = 0; i < builder_array_wasm->size; ++i) { + for (uint32_t i = 0; i < array_size; ++i) { error res; if (success != (res = graph_builder_app_native(instance, &builder_wasm[i], @@ -66,22 +92,31 @@ graph_builder_array_app_native(wasm_module_inst_t instance, } builder_array->buf = builder; - builder_array->size = builder_array_wasm->size; + builder_array->size = array_size; return success; +#undef array_size } static error tensor_data_app_native(wasm_module_inst_t instance, uint32_t total_elements, tensor_wasm *input_tensor_wasm, tensor_data *data) { - if (!wasm_runtime_validate_app_addr( - instance, input_tensor_wasm->data_offset, total_elements)) { +#if WASM_ENABLE_WASI_EPHEMERAL_NN != 0 +#define data_size input_tensor_wasm->data_size +#else +#define data_size total_elements +#endif + + if (!wasm_runtime_validate_app_addr(instance, + (uint64)input_tensor_wasm->data_offset, + (uint64)data_size)) { NN_ERR_PRINTF("input_tensor_wasm->data_offset is invalid"); return invalid_argument; } *data = (tensor_data)wasm_runtime_addr_app_to_native( - instance, input_tensor_wasm->data_offset); + instance, (uint64)input_tensor_wasm->data_offset); return success; +#undef data_size } static error @@ -89,19 +124,24 @@ tensor_dimensions_app_native(wasm_module_inst_t instance, tensor_wasm *input_tensor_wasm, tensor_dimensions **dimensions) { - if (!wasm_runtime_validate_app_addr(instance, - input_tensor_wasm->dimensions_offset, - sizeof(tensor_dimensions_wasm))) { +#if WASM_ENABLE_WASI_EPHEMERAL_NN != 0 + tensor_dimensions_wasm *dimensions_wasm = &input_tensor_wasm->dimensions; +#else /* WASM_ENABLE_WASI_EPHEMERAL_NN == 0 */ + if (!wasm_runtime_validate_app_addr( + instance, (uint64)input_tensor_wasm->dimensions_offset, + (uint64)sizeof(tensor_dimensions_wasm))) { NN_ERR_PRINTF("input_tensor_wasm->dimensions_offset is invalid"); return invalid_argument; } tensor_dimensions_wasm *dimensions_wasm = (tensor_dimensions_wasm *)wasm_runtime_addr_app_to_native( - instance, input_tensor_wasm->dimensions_offset); + instance, (uint64)input_tensor_wasm->dimensions_offset); +#endif /* WASM_ENABLE_WASI_EPHEMERAL_NN != 0 */ - if (!wasm_runtime_validate_app_addr(instance, dimensions_wasm->buf_offset, - sizeof(tensor_dimensions))) { + if (!wasm_runtime_validate_app_addr(instance, + (uint64)dimensions_wasm->buf_offset, + (uint64)sizeof(tensor_dimensions))) { NN_ERR_PRINTF("dimensions_wasm->buf_offset is invalid"); return invalid_argument; } @@ -113,7 +153,7 @@ tensor_dimensions_app_native(wasm_module_inst_t instance, (*dimensions)->size = dimensions_wasm->size; (*dimensions)->buf = (uint32_t *)wasm_runtime_addr_app_to_native( - instance, dimensions_wasm->buf_offset); + instance, (uint64)dimensions_wasm->buf_offset); NN_DBG_PRINTF("Number of dimensions: %d", (*dimensions)->size); return success; @@ -125,7 +165,7 @@ tensor_app_native(wasm_module_inst_t instance, tensor_wasm *input_tensor_wasm, { NN_DBG_PRINTF("Converting tensor_wasm to tensor"); if (!wasm_runtime_validate_native_addr(instance, input_tensor_wasm, - sizeof(tensor_wasm))) { + (uint64)sizeof(tensor_wasm))) { NN_ERR_PRINTF("input_tensor_wasm is invalid"); return invalid_argument; } diff --git a/core/iwasm/libraries/wasi-nn/src/utils/wasi_nn_app_native.h b/core/iwasm/libraries/wasi-nn/src/utils/wasi_nn_app_native.h index 15154bd31..f0930a883 100644 --- a/core/iwasm/libraries/wasi-nn/src/utils/wasi_nn_app_native.h +++ b/core/iwasm/libraries/wasi-nn/src/utils/wasi_nn_app_native.h @@ -34,15 +34,29 @@ typedef struct { } tensor_dimensions_wasm; typedef struct { +#if WASM_ENABLE_WASI_EPHEMERAL_NN != 0 + tensor_dimensions_wasm dimensions; + tensor_type type; + uint32_t data_offset; + uint32_t data_size; +#else /* WASM_ENABLE_WASI_EPHEMERAL_NN == 0 */ uint32_t dimensions_offset; tensor_type type; uint32_t data_offset; +#endif /* WASM_ENABLE_WASI_EPHEMERAL_NN != 0 */ } tensor_wasm; +#if WASM_ENABLE_WASI_EPHEMERAL_NN != 0 +error +graph_builder_array_app_native(wasm_module_inst_t instance, + graph_builder_wasm *builder_wasm, uint32_t size, + graph_builder_array *builder_array); +#else /* WASM_ENABLE_WASI_EPHEMERAL_NN == 0 */ error graph_builder_array_app_native(wasm_module_inst_t instance, graph_builder_array_wasm *builder, graph_builder_array *builder_native); +#endif /* WASM_ENABLE_WASI_EPHEMERAL_NN != 0 */ error tensor_app_native(wasm_module_inst_t instance, tensor_wasm *input_tensor, diff --git a/core/iwasm/libraries/wasi-nn/src/wasi_nn.c b/core/iwasm/libraries/wasi-nn/src/wasi_nn.c index c234e450a..1fbb94428 100644 --- a/core/iwasm/libraries/wasi-nn/src/wasi_nn.c +++ b/core/iwasm/libraries/wasi-nn/src/wasi_nn.c @@ -189,9 +189,16 @@ is_model_initialized(WASINNContext *wasi_nn_ctx) /* WASI-NN implementation */ +#if WASM_ENABLE_WASI_EPHEMERAL_NN != 0 +error +wasi_nn_load(wasm_exec_env_t exec_env, graph_builder_wasm *builder, + uint32_t builder_wasm_size, graph_encoding encoding, + execution_target target, graph *g) +#else /* WASM_ENABLE_WASI_EPHEMERAL_NN == 0 */ error wasi_nn_load(wasm_exec_env_t exec_env, graph_builder_array_wasm *builder, graph_encoding encoding, execution_target target, graph *g) +#endif /* WASM_ENABLE_WASI_EPHEMERAL_NN != 0 */ { NN_DBG_PRINTF("Running wasi_nn_load [encoding=%d, target=%d]...", encoding, target); @@ -206,12 +213,20 @@ wasi_nn_load(wasm_exec_env_t exec_env, graph_builder_array_wasm *builder, error res; graph_builder_array builder_native = { 0 }; +#if WASM_ENABLE_WASI_EPHEMERAL_NN != 0 + if (success + != (res = graph_builder_array_app_native( + instance, builder, builder_wasm_size, &builder_native))) + return res; +#else /* WASM_ENABLE_WASI_EPHEMERAL_NN == 0 */ if (success != (res = graph_builder_array_app_native(instance, builder, &builder_native))) return res; +#endif /* WASM_ENABLE_WASI_EPHEMERAL_NN != 0 */ - if (!wasm_runtime_validate_native_addr(instance, g, sizeof(graph))) { + if (!wasm_runtime_validate_native_addr(instance, g, + (uint64)sizeof(graph))) { NN_ERR_PRINTF("graph is invalid"); res = invalid_argument; goto fail; @@ -248,8 +263,8 @@ wasi_nn_init_execution_context(wasm_exec_env_t exec_env, graph g, if (success != (res = is_model_initialized(wasi_nn_ctx))) return res; - if (!wasm_runtime_validate_native_addr(instance, ctx, - sizeof(graph_execution_context))) { + if (!wasm_runtime_validate_native_addr( + instance, ctx, (uint64)sizeof(graph_execution_context))) { NN_ERR_PRINTF("ctx is invalid"); return invalid_argument; } @@ -314,10 +329,17 @@ wasi_nn_compute(wasm_exec_env_t exec_env, graph_execution_context ctx) return res; } +#if WASM_ENABLE_WASI_EPHEMERAL_NN != 0 +error +wasi_nn_get_output(wasm_exec_env_t exec_env, graph_execution_context ctx, + uint32_t index, tensor_data output_tensor, + uint32_t output_tensor_len, uint32_t *output_tensor_size) +#else /* WASM_ENABLE_WASI_EPHEMERAL_NN == 0 */ error wasi_nn_get_output(wasm_exec_env_t exec_env, graph_execution_context ctx, uint32_t index, tensor_data output_tensor, uint32_t *output_tensor_size) +#endif /* WASM_ENABLE_WASI_EPHEMERAL_NN != 0 */ { NN_DBG_PRINTF("Running wasi_nn_get_output [ctx=%d, index=%d]...", ctx, index); @@ -331,13 +353,19 @@ wasi_nn_get_output(wasm_exec_env_t exec_env, graph_execution_context ctx, return res; if (!wasm_runtime_validate_native_addr(instance, output_tensor_size, - sizeof(uint32_t))) { + (uint64)sizeof(uint32_t))) { NN_ERR_PRINTF("output_tensor_size is invalid"); return invalid_argument; } +#if WASM_ENABLE_WASI_EPHEMERAL_NN != 0 + res = lookup[wasi_nn_ctx->current_encoding].get_output( + wasi_nn_ctx->tflite_ctx, ctx, index, output_tensor, &output_tensor_len); + *output_tensor_size = output_tensor_len; +#else /* WASM_ENABLE_WASI_EPHEMERAL_NN == 0 */ res = lookup[wasi_nn_ctx->current_encoding].get_output( wasi_nn_ctx->tflite_ctx, ctx, index, output_tensor, output_tensor_size); +#endif /* WASM_ENABLE_WASI_EPHEMERAL_NN != 0 */ NN_DBG_PRINTF("wasi_nn_get_output finished with status %d [data_size=%d]", res, *output_tensor_size); return res; @@ -351,11 +379,19 @@ wasi_nn_get_output(wasm_exec_env_t exec_env, graph_execution_context ctx, /* clang-format on */ static NativeSymbol native_symbols_wasi_nn[] = { +#if WASM_ENABLE_WASI_EPHEMERAL_NN != 0 + REG_NATIVE_FUNC(load, "(*iii*)i"), + REG_NATIVE_FUNC(init_execution_context, "(i*)i"), + REG_NATIVE_FUNC(set_input, "(ii*)i"), + REG_NATIVE_FUNC(compute, "(i)i"), + REG_NATIVE_FUNC(get_output, "(ii*i*)i"), +#else /* WASM_ENABLE_WASI_EPHEMERAL_NN == 0 */ REG_NATIVE_FUNC(load, "(*ii*)i"), REG_NATIVE_FUNC(init_execution_context, "(i*)i"), REG_NATIVE_FUNC(set_input, "(ii*)i"), REG_NATIVE_FUNC(compute, "(i)i"), REG_NATIVE_FUNC(get_output, "(ii**)i"), +#endif /* WASM_ENABLE_WASI_EPHEMERAL_NN != 0 */ }; uint32_t diff --git a/core/shared/mem-alloc/ems/ems_alloc.c b/core/shared/mem-alloc/ems/ems_alloc.c index b667fbe9f..4863527d6 100644 --- a/core/shared/mem-alloc/ems/ems_alloc.c +++ b/core/shared/mem-alloc/ems/ems_alloc.c @@ -785,8 +785,8 @@ gc_alloc_wo_internal(void *vheap, gc_size_t size, const char *file, int line) if (!hmu) goto finish; - /* Do we need to memset the memory to 0? */ - /* memset((char *)hmu + sizeof(*hmu), 0, tot_size - sizeof(*hmu)); */ + /* Don't memset the memory to improve performance, the caller should + decide whether to memset it or not */ bh_assert(hmu_get_size(hmu) >= tot_size); /* the total size allocated may be larger than diff --git a/core/shared/mem-alloc/ems/ems_gc.c b/core/shared/mem-alloc/ems/ems_gc.c index b0f14772b..26e83a975 100644 --- a/core/shared/mem-alloc/ems/ems_gc.c +++ b/core/shared/mem-alloc/ems/ems_gc.c @@ -114,8 +114,8 @@ sweep_instance_heap(gc_heap_t *heap) else { /* current block is still live */ if (last) { - tot_free += (char *)cur - (char *)last; - gci_add_fc(heap, last, (char *)cur - (char *)last); + tot_free += (gc_size_t)((char *)cur - (char *)last); + gci_add_fc(heap, last, (gc_size_t)((char *)cur - (char *)last)); hmu_mark_pinuse(last); last = NULL; } @@ -132,8 +132,8 @@ sweep_instance_heap(gc_heap_t *heap) bh_assert(cur == end); if (last) { - tot_free += (char *)cur - (char *)last; - gci_add_fc(heap, last, (char *)cur - (char *)last); + tot_free += (gc_size_t)((char *)cur - (char *)last); + gci_add_fc(heap, last, (gc_size_t)((char *)cur - (char *)last)); hmu_mark_pinuse(last); } @@ -449,7 +449,9 @@ gci_gc_heap(void *h) LOG_VERBOSE("#reclaim instance heap %p", heap); - gct_vm_gc_prepare(); + /* TODO: get exec_env of current thread when GC multi-threading + is enabled, and pass it to runtime */ + gct_vm_gc_prepare(NULL); gct_vm_mutex_lock(&heap->lock); heap->is_doing_reclaim = 1; @@ -459,7 +461,9 @@ gci_gc_heap(void *h) heap->is_doing_reclaim = 0; gct_vm_mutex_unlock(&heap->lock); - gct_vm_gc_finished(); + /* TODO: get exec_env of current thread when GC multi-threading + is enabled, and pass it to runtime */ + gct_vm_gc_finished(NULL); LOG_VERBOSE("#reclaim instance heap %p done", heap); diff --git a/core/shared/mem-alloc/mem_alloc.c b/core/shared/mem-alloc/mem_alloc.c index 1f9e03d5a..df1a4de4c 100644 --- a/core/shared/mem-alloc/mem_alloc.c +++ b/core/shared/mem-alloc/mem_alloc.c @@ -77,13 +77,13 @@ mem_allocator_free_with_gc(mem_allocator_t allocator, void *ptr) void mem_allocator_enable_gc_reclaim(mem_allocator_t allocator, void *exec_env) { - return gc_enable_gc_reclaim((gc_handle_t)allocator, exec_env); + 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); + gc_enable_gc_reclaim((gc_handle_t)allocator, cluster); } #endif 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 index bbd287e77..dca10a342 100644 --- a/core/shared/platform/common/memory/mremap.c +++ b/core/shared/platform/common/memory/mremap.c @@ -3,10 +3,10 @@ * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ -#include "bh_memutils.h" +#include "platform_api_vmcore.h" void * os_mremap(void *old_addr, size_t old_size, size_t new_size) { - return bh_memory_remap_slow(old_addr, old_size, new_size); + return os_mremap_slow(old_addr, old_size, new_size); } diff --git a/core/shared/platform/common/posix/platform_api_posix.cmake b/core/shared/platform/common/posix/platform_api_posix.cmake index 17ee04f82..15d6daf3f 100644 --- a/core/shared/platform/common/posix/platform_api_posix.cmake +++ b/core/shared/platform/common/posix/platform_api_posix.cmake @@ -25,6 +25,7 @@ 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) diff --git a/core/shared/platform/common/posix/posix_file.c b/core/shared/platform/common/posix/posix_file.c index ad5589f73..20f94fba3 100644 --- a/core/shared/platform/common/posix/posix_file.c +++ b/core/shared/platform/common/posix/posix_file.c @@ -384,7 +384,7 @@ os_openat(os_file_handle handle, const char *path, __wasi_oflags_t oflags, // Linux returns ENXIO instead of EOPNOTSUPP when opening a socket. if (openat_errno == ENXIO) { struct stat sb; - int ret = fstatat(fd, path, &sb, + int ret = fstatat(handle, path, &sb, (lookup_flags & __WASI_LOOKUP_SYMLINK_FOLLOW) ? 0 : AT_SYMLINK_NOFOLLOW); @@ -396,7 +396,7 @@ os_openat(os_file_handle handle, const char *path, __wasi_oflags_t oflags, if (openat_errno == ENOTDIR && (open_flags & (O_NOFOLLOW | O_DIRECTORY)) != 0) { struct stat sb; - int ret = fstatat(fd, path, &sb, AT_SYMLINK_NOFOLLOW); + int ret = fstatat(handle, path, &sb, AT_SYMLINK_NOFOLLOW); if (S_ISLNK(sb.st_mode)) { return __WASI_ELOOP; } diff --git a/core/shared/platform/common/posix/posix_memmap.c b/core/shared/platform/common/posix/posix_memmap.c index afc549cdd..c76abf137 100644 --- a/core/shared/platform/common/posix/posix_memmap.c +++ b/core/shared/platform/common/posix/posix_memmap.c @@ -3,12 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ -#if !defined(_GNU_SOURCE) && WASM_HAVE_MREMAP != 0 -/* Enable mremap */ -#define _GNU_SOURCE -#include "bh_memutils.h" -#endif - #include "platform_api_vmcore.h" #if defined(__APPLE__) || defined(__MACH__) @@ -71,9 +65,11 @@ os_mmap(void *hint, size_t size, int prot, int flags, os_file_handle file) /* integer overflow */ return NULL; +#if WASM_ENABLE_MEMORY64 == 0 if (request_size > 16 * (uint64)UINT32_MAX) - /* at most 16 G is allowed */ + /* at most 64 G is allowed */ return NULL; +#endif if (prot & MMAP_PROT_READ) map_prot |= PROT_READ; @@ -140,7 +136,7 @@ os_mmap(void *hint, size_t size, int prot, int flags, os_file_handle file) } #endif /* end of BUILD_TARGET_RISCV64_LP64D || BUILD_TARGET_RISCV64_LP64 */ - /* memory has't been mapped or was mapped failed previously */ + /* memory hasn't been mapped or was mapped failed previously */ if (addr == MAP_FAILED) { /* try 5 times */ for (i = 0; i < 5; i++) { @@ -252,7 +248,7 @@ os_mremap(void *old_addr, size_t old_size, size_t new_size) #if BH_ENABLE_TRACE_MMAP != 0 os_printf("mremap failed: %d\n", errno); #endif - return bh_memory_remap_slow(old_addr, old_size, new_size); + return os_mremap_slow(old_addr, old_size, new_size); } return ptr; diff --git a/core/shared/platform/esp-idf/espidf_memmap.c b/core/shared/platform/esp-idf/espidf_memmap.c index 9f3ec47a6..21f186b90 100644 --- a/core/shared/platform/esp-idf/espidf_memmap.c +++ b/core/shared/platform/esp-idf/espidf_memmap.c @@ -55,10 +55,33 @@ os_mmap(void *hint, size_t size, int prot, int flags, os_file_handle file) #else uint32_t mem_caps = MALLOC_CAP_8BIT; #endif - return heap_caps_malloc(size, mem_caps); + void *buf_origin = + heap_caps_malloc(size + 4 + sizeof(uintptr_t), mem_caps); + if (!buf_origin) { + return NULL; + } + + // Memory allocation with MALLOC_CAP_SPIRAM or MALLOC_CAP_8BIT will + // return 4-byte aligned Reserve extra 4 byte to fixup alignment and + // size for the pointer to the originally allocated address + void *buf_fixed = buf_origin + sizeof(void *); + if ((uintptr_t)buf_fixed & (uintptr_t)0x7) { + buf_fixed = (void *)((uintptr_t)(buf_fixed + 4) & (~(uintptr_t)7)); + } + + uintptr_t *addr_field = buf_fixed - sizeof(uintptr_t); + *addr_field = (uintptr_t)buf_origin; + + return buf_fixed; } } +void * +os_mremap(void *old_addr, size_t old_size, size_t new_size) +{ + return os_mremap_slow(old_addr, old_size, new_size); +} + void os_munmap(void *addr, size_t size) { diff --git a/core/shared/platform/esp-idf/espidf_platform.c b/core/shared/platform/esp-idf/espidf_platform.c index 0a1dd3c9d..8fea32546 100644 --- a/core/shared/platform/esp-idf/espidf_platform.c +++ b/core/shared/platform/esp-idf/espidf_platform.c @@ -6,6 +6,12 @@ #include "platform_api_vmcore.h" #include "platform_api_extension.h" +#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0)) \ + && (ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 2, 0)) +#define UTIMENSAT_TIMESPEC_POINTER 1 +#define FUTIMENS_TIMESPEC_POINTER 1 +#endif + int bh_platform_init() { @@ -23,7 +29,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 +42,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 @@ -226,7 +240,13 @@ unlinkat(int fd, const char *path, int flag) } int -utimensat(int fd, const char *path, const struct timespec *ts, int flag) +utimensat(int fd, const char *path, +#if UTIMENSAT_TIMESPEC_POINTER + const struct timespec *ts, +#else + const struct timespec ts[2], +#endif + int flag) { errno = ENOSYS; return -1; @@ -249,7 +269,13 @@ ftruncate(int fd, off_t length) #endif int -futimens(int fd, const struct timespec *times) +futimens(int fd, +#if FUTIMENS_TIMESPEC_POINTER + const struct timespec *times +#else + const struct timespec times[2] +#endif +) { errno = ENOSYS; return -1; @@ -260,4 +286,4 @@ nanosleep(const struct timespec *req, struct timespec *rem) { errno = ENOSYS; return -1; -} \ No newline at end of file +} diff --git a/core/shared/platform/esp-idf/platform_internal.h b/core/shared/platform/esp-idf/platform_internal.h index 70c4fe7b1..0f873810e 100644 --- a/core/shared/platform/esp-idf/platform_internal.h +++ b/core/shared/platform/esp-idf/platform_internal.h @@ -109,6 +109,12 @@ typedef unsigned int korp_sem; #define DT_LNK DTYPE_LINK #define DT_SOCK DTYPE_SOCK +static inline int +os_getpagesize() +{ + return 4096; +} + typedef int os_file_handle; typedef DIR *os_dir_stream; typedef int os_raw_file_handle; diff --git a/core/shared/platform/include/platform_api_vmcore.h b/core/shared/platform/include/platform_api_vmcore.h index 1c948f58c..1fa524f9e 100644 --- a/core/shared/platform/include/platform_api_vmcore.h +++ b/core/shared/platform/include/platform_api_vmcore.h @@ -142,6 +142,24 @@ 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 * diff --git a/core/shared/platform/nuttx/shared_platform.cmake b/core/shared/platform/nuttx/shared_platform.cmake index ff70cc031..d691068f2 100644 --- a/core/shared/platform/nuttx/shared_platform.cmake +++ b/core/shared/platform/nuttx/shared_platform.cmake @@ -8,6 +8,10 @@ add_definitions(-DBH_PLATFORM_NUTTX) include_directories(${PLATFORM_SHARED_DIR}) include_directories(${PLATFORM_SHARED_DIR}/../include) +include (${CMAKE_CURRENT_LIST_DIR}/../common/posix/platform_api_posix.cmake) + +include (${SHARED_DIR}/utils/uncommon/shared_uncommon.cmake) + file (GLOB_RECURSE source_all ${PLATFORM_SHARED_DIR}/*.c) if (WAMR_BUILD_LIBC_WASI EQUAL 1) @@ -16,6 +20,7 @@ if (WAMR_BUILD_LIBC_WASI EQUAL 1) set(source_all ${source_all} ${PLATFORM_COMMON_LIBC_UTIL_SOURCE}) endif () -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}) +set (PLATFORM_SHARED_SOURCE ${source_all} ${PLATFORM_COMMON_MATH_SOURCE} ${PLATFORM_COMMON_POSIX_SOURCE} ${UNCOMMON_SHARED_SOURCE}) +# remove posix_memmap.c for NuttX +list(REMOVE_ITEM ${PLATFORM_SHARED_SOURCE} ${PLATFORM_COMMON_POSIX_DIR}/posix_memmap.c) diff --git a/core/shared/platform/windows/win_file.c b/core/shared/platform/windows/win_file.c index 2c4e19f8b..63dfb5b5f 100644 --- a/core/shared/platform/windows/win_file.c +++ b/core/shared/platform/windows/win_file.c @@ -213,14 +213,6 @@ has_symlink_attribute(DWORD attributes) return (attributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0; } -static bool -is_symlink(const wchar_t *path) -{ - DWORD attributes = GetFileAttributesW(path); - - return has_symlink_attribute(attributes); -} - static void init_dir_stream(os_dir_stream dir_stream, os_file_handle handle) { @@ -229,6 +221,13 @@ init_dir_stream(os_dir_stream dir_stream, os_file_handle handle) dir_stream->cookie = 0; } +static void +reset_dir_stream(os_dir_stream dir_stream) +{ + dir_stream->cursor = 0; + dir_stream->cookie = 0; +} + // Advances to the next directory entry and optionally reads into to the // provided buffer if not NULL. static __wasi_errno_t @@ -562,7 +561,32 @@ os_fstatat(os_file_handle handle, const char *path, { CHECK_VALID_FILE_HANDLE(handle); - return __WASI_ENOSYS; + wchar_t absolute_path[PATH_MAX]; + + __wasi_errno_t error = get_absolute_filepath(handle->raw.handle, path, + absolute_path, PATH_MAX); + + if (error != __WASI_ESUCCESS) + return error; + + windows_handle resolved_handle = { + .type = windows_handle_type_file, + .fdflags = 0, + .raw = { .handle = create_handle( + absolute_path, is_directory(absolute_path), + ((lookup_flags & __WASI_LOOKUP_SYMLINK_FOLLOW) != 0), + true) }, + .access_mode = windows_access_mode_read + }; + + if (resolved_handle.raw.handle == INVALID_HANDLE_VALUE) + return convert_windows_error_code(GetLastError()); + + error = get_file_information(&resolved_handle, buf); + + CloseHandle(resolved_handle.raw.handle); + + return error; } __wasi_errno_t @@ -579,7 +603,33 @@ os_file_set_fdflags(os_file_handle handle, __wasi_fdflags_t flags) { CHECK_VALID_HANDLE(handle); - return __WASI_ENOSYS; + if (handle->type == windows_handle_type_socket + && (((handle->fdflags ^ flags) & __WASI_FDFLAG_NONBLOCK) != 0)) { + u_long non_block = flags & __WASI_FDFLAG_NONBLOCK; + + int ret = ioctlsocket(handle->raw.socket, (long)FIONBIO, &non_block); + + if (ret != 0) + return convert_winsock_error_code(WSAGetLastError()); + + if (non_block) + handle->fdflags |= __WASI_FDFLAG_NONBLOCK; + else + handle->fdflags &= ~__WASI_FDFLAG_NONBLOCK; + return __WASI_ESUCCESS; + } + + // It's not supported setting FILE_FLAG_WRITE_THROUGH or + // FILE_FLAG_NO_BUFFERING via SetFileAttributes so __WASI_FDFLAG_APPEND is + // the only flags we can do anything with. + if (((handle->fdflags ^ flags) & __WASI_FDFLAG_APPEND) != 0) { + if ((flags & __WASI_FDFLAG_APPEND) != 0) + handle->fdflags |= __WASI_FDFLAG_APPEND; + else + handle->fdflags &= ~__WASI_FDFLAG_APPEND; + } + + return __WASI_ESUCCESS; } __wasi_errno_t @@ -599,12 +649,21 @@ os_file_get_access_mode(os_file_handle handle, return __WASI_ESUCCESS; } +static __wasi_errno_t +flush_file_buffers_on_handle(HANDLE handle) +{ + bool success = FlushFileBuffers(handle); + + return success ? __WASI_ESUCCESS + : convert_windows_error_code(GetLastError()); +} + __wasi_errno_t os_fdatasync(os_file_handle handle) { CHECK_VALID_FILE_HANDLE(handle); - return __WASI_ENOSYS; + return flush_file_buffers_on_handle(handle->raw.handle); } __wasi_errno_t @@ -612,7 +671,7 @@ os_fsync(os_file_handle handle) { CHECK_VALID_FILE_HANDLE(handle); - return __WASI_ENOSYS; + return flush_file_buffers_on_handle(handle->raw.handle); } __wasi_errno_t @@ -680,16 +739,6 @@ os_openat(os_file_handle handle, const char *path, __wasi_oflags_t oflags, __wasi_errno_t error = __WASI_ESUCCESS; DWORD access_flags = 0; - if ((fs_flags & __WASI_FDFLAG_APPEND) != 0) { - if ((attributes & (FILE_FLAG_NO_BUFFERING)) != 0) { - // FILE_APPEND_DATA and FILE_FLAG_NO_BUFFERING are mutually - // exclusive - CreateFile2 returns 87 (invalid parameter) when they - // are combined. - error = __WASI_ENOTSUP; - goto fail; - } - access_flags |= FILE_APPEND_DATA; - } switch (access_mode) { case WASI_LIBC_ACCESS_MODE_READ_ONLY: @@ -743,14 +792,30 @@ os_openat(os_file_handle handle, const char *path, __wasi_oflags_t oflags, if ((lookup_flags & __WASI_LOOKUP_SYMLINK_FOLLOW) == 0) attributes |= FILE_FLAG_OPEN_REPARSE_POINT; - // Check that we're not trying to open an existing file as a directory. - // Windows doesn't seem to throw an error in this case so add an - // explicit check. - if ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0 - && creation_disposition == OPEN_EXISTING - && !is_directory(absolute_path)) { - error = __WASI_ENOTDIR; - goto fail; + // Windows doesn't seem to throw an error for the following cases where the + // file/directory already exists so add explicit checks. + if (creation_disposition == OPEN_EXISTING) { + DWORD file_attributes = GetFileAttributesW(absolute_path); + + if (file_attributes != INVALID_FILE_ATTRIBUTES) { + bool is_dir = file_attributes & FILE_ATTRIBUTE_DIRECTORY; + bool is_symlink = file_attributes & FILE_ATTRIBUTE_REPARSE_POINT; + // Check that we're not trying to open an existing file/symlink as a + // directory. + if ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0 + && (!is_dir || is_symlink)) { + error = __WASI_ENOTDIR; + goto fail; + } + + // Check that we're not trying to open an existing symlink with + // O_NOFOLLOW. + if ((file_attributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0 + && (lookup_flags & __WASI_LOOKUP_SYMLINK_FOLLOW) == 0) { + error = __WASI_ELOOP; + goto fail; + } + } } CREATEFILE2_EXTENDED_PARAMETERS create_params; @@ -1035,7 +1100,31 @@ os_fallocate(os_file_handle handle, __wasi_filesize_t offset, { CHECK_VALID_FILE_HANDLE(handle); - return __WASI_ENOSYS; + LARGE_INTEGER current_file_size; + int ret = GetFileSizeEx(handle->raw.handle, ¤t_file_size); + + if (ret == 0) + return convert_windows_error_code(GetLastError()); + + if (offset > INT64_MAX || length > INT64_MAX || offset + length > INT64_MAX) + return __WASI_EINVAL; + + // The best we can do here is to increase the size of the file if it's less + // than the offset + length. + const LONGLONG requested_size = (LONGLONG)(offset + length); + + FILE_END_OF_FILE_INFO end_of_file_info; + end_of_file_info.EndOfFile.QuadPart = requested_size; + + if (requested_size <= current_file_size.QuadPart) + return __WASI_ESUCCESS; + + bool success = + SetFileInformationByHandle(handle->raw.handle, FileEndOfFileInfo, + &end_of_file_info, sizeof(end_of_file_info)); + + return success ? __WASI_ESUCCESS + : convert_windows_error_code(GetLastError()); } __wasi_errno_t @@ -1043,7 +1132,42 @@ os_ftruncate(os_file_handle handle, __wasi_filesize_t size) { CHECK_VALID_FILE_HANDLE(handle); - return __WASI_ENOSYS; + FILE_END_OF_FILE_INFO end_of_file_info; + end_of_file_info.EndOfFile.QuadPart = (LONGLONG)size; + + bool success = + SetFileInformationByHandle(handle->raw.handle, FileEndOfFileInfo, + &end_of_file_info, sizeof(end_of_file_info)); + + return success ? __WASI_ESUCCESS + : convert_windows_error_code(GetLastError()); +} + +static __wasi_errno_t +set_file_times(HANDLE handle, __wasi_timestamp_t access_time, + __wasi_timestamp_t modification_time, __wasi_fstflags_t fstflags) +{ + FILETIME atim = { 0, 0 }; + FILETIME mtim = { 0, 0 }; + + if ((fstflags & __WASI_FILESTAT_SET_ATIM) != 0) { + atim = convert_wasi_timestamp_to_filetime(access_time); + } + else if ((fstflags & __WASI_FILESTAT_SET_ATIM_NOW) != 0) { + GetSystemTimePreciseAsFileTime(&atim); + } + + if ((fstflags & __WASI_FILESTAT_SET_MTIM) != 0) { + mtim = convert_wasi_timestamp_to_filetime(modification_time); + } + else if ((fstflags & __WASI_FILESTAT_SET_MTIM_NOW) != 0) { + GetSystemTimePreciseAsFileTime(&mtim); + } + + bool success = SetFileTime(handle, NULL, &atim, &mtim); + + return success ? __WASI_ESUCCESS + : convert_windows_error_code(GetLastError()); } __wasi_errno_t @@ -1052,7 +1176,8 @@ os_futimens(os_file_handle handle, __wasi_timestamp_t access_time, { CHECK_VALID_FILE_HANDLE(handle); - return __WASI_ENOSYS; + return set_file_times(handle->raw.handle, access_time, modification_time, + fstflags); } __wasi_errno_t @@ -1063,7 +1188,26 @@ os_utimensat(os_file_handle handle, const char *path, { CHECK_VALID_FILE_HANDLE(handle); - return __WASI_ENOSYS; + wchar_t absolute_path[PATH_MAX]; + __wasi_errno_t error = get_absolute_filepath(handle->raw.handle, path, + absolute_path, PATH_MAX); + + if (error != __WASI_ESUCCESS) + return error; + + HANDLE resolved_handle = create_handle( + absolute_path, is_directory(absolute_path), + (lookup_flags & __WASI_LOOKUP_SYMLINK_FOLLOW) != 0, false); + + if (resolved_handle == INVALID_HANDLE_VALUE) + return convert_windows_error_code(GetLastError()); + + error = set_file_times(resolved_handle, access_time, modification_time, + fstflags); + + CloseHandle(resolved_handle); + + return error; } __wasi_errno_t @@ -1213,7 +1357,7 @@ os_readlinkat(os_file_handle handle, const char *path, char *buf, } #else error = __WASI_ENOTSUP; -#endif +#endif /* end of WINAPI_PARTITION_DESKTOP == 0 */ fail: CloseHandle(link_handle); return error; @@ -1224,18 +1368,96 @@ os_linkat(os_file_handle from_handle, const char *from_path, os_file_handle to_handle, const char *to_path, __wasi_lookupflags_t lookup_flags) { +#if WINAPI_PARTITION_DESKTOP == 0 + return __WASI_ENOSYS; +#else CHECK_VALID_FILE_HANDLE(from_handle); CHECK_VALID_FILE_HANDLE(to_handle); - return __WASI_ENOSYS; + wchar_t absolute_from_path[PATH_MAX]; + __wasi_errno_t error = get_absolute_filepath( + from_handle->raw.handle, from_path, absolute_from_path, PATH_MAX); + + if (error != __WASI_ESUCCESS) + return error; + + wchar_t absolute_to_path[PATH_MAX]; + error = get_absolute_filepath(to_handle->raw.handle, to_path, + absolute_to_path, PATH_MAX); + + if (error != __WASI_ESUCCESS) + return error; + + size_t to_path_len = strlen(to_path); + + // Windows doesn't throw an error in the case that the new path has a + // trailing slash but the target to link to is a file. + if (to_path[to_path_len - 1] == '/' + || to_path[to_path_len - 1] == '\\' + && !is_directory(absolute_from_path)) { + return __WASI_ENOENT; + } + + int ret = CreateHardLinkW(absolute_to_path, absolute_from_path, NULL); + + if (ret == 0) + error = convert_windows_error_code(GetLastError()); + + return error; +#endif /* end of WINAPI_PARTITION_DESKTOP == 0 */ } __wasi_errno_t os_symlinkat(const char *old_path, os_file_handle handle, const char *new_path) { +#if WINAPI_PARTITION_DESKTOP == 0 + return __WASI_ENOSYS; +#else CHECK_VALID_FILE_HANDLE(handle); - return __WASI_ENOSYS; + wchar_t absolute_new_path[PATH_MAX]; + __wasi_errno_t error = get_absolute_filepath(handle->raw.handle, new_path, + absolute_new_path, PATH_MAX); + + if (error != __WASI_ESUCCESS) + return error; + + DWORD target_type = SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE; + + wchar_t old_wpath[PATH_MAX]; + size_t old_path_len = 0; + + error = convert_to_wchar(old_path, old_wpath, PATH_MAX); + + if (error != __WASI_ESUCCESS) + goto fail; + + wchar_t absolute_old_path[PATH_MAX]; + error = get_absolute_filepath(handle->raw.handle, old_path, + absolute_old_path, PATH_MAX); + + if (error != __WASI_ESUCCESS) + goto fail; + + if (is_directory(absolute_old_path)) + target_type |= SYMBOLIC_LINK_FLAG_DIRECTORY; + + bool success = + CreateSymbolicLinkW(absolute_new_path, old_wpath, target_type); + + if (!success) { + DWORD win_error = GetLastError(); + + // Return a more useful error code if a file/directory already exists at + // the symlink location. + if (win_error == ERROR_ACCESS_DENIED || win_error == ERROR_INVALID_NAME) + error = __WASI_ENOENT; + else + error = convert_windows_error_code(GetLastError()); + } +fail: + return error; +#endif /* end of WINAPI_PARTITION_DESKTOP == 0 */ } __wasi_errno_t @@ -1265,56 +1487,28 @@ os_renameat(os_file_handle old_handle, const char *old_path, CHECK_VALID_FILE_HANDLE(old_handle); CHECK_VALID_FILE_HANDLE(new_handle); - return __WASI_ENOSYS; -} - -__wasi_errno_t -os_unlinkat(os_file_handle handle, const char *path, bool is_dir) -{ - CHECK_VALID_FILE_HANDLE(handle); - - wchar_t absolute_path[PATH_MAX]; - __wasi_errno_t error = get_absolute_filepath(handle->raw.handle, path, - absolute_path, PATH_MAX); + wchar_t old_absolute_path[PATH_MAX]; + __wasi_errno_t error = get_absolute_filepath( + old_handle->raw.handle, old_path, old_absolute_path, PATH_MAX); if (error != __WASI_ESUCCESS) return error; - DWORD attributes = GetFileAttributesW(absolute_path); + wchar_t new_absolute_path[PATH_MAX]; + error = get_absolute_filepath(new_handle->raw.handle, new_path, + new_absolute_path, PATH_MAX); - if (has_symlink_attribute(attributes)) { - // Override is_dir for symlinks. A symlink to a directory counts - // as a directory itself in Windows. - is_dir = has_directory_attribute(attributes); - } - - int ret = - is_dir ? RemoveDirectoryW(absolute_path) : DeleteFileW(absolute_path); + if (error != __WASI_ESUCCESS) + return error; + int ret = MoveFileExW(old_absolute_path, new_absolute_path, + MOVEFILE_REPLACE_EXISTING); if (ret == 0) error = convert_windows_error_code(GetLastError()); return error; } -__wasi_errno_t -os_lseek(os_file_handle handle, __wasi_filedelta_t offset, - __wasi_whence_t whence, __wasi_filesize_t *new_offset) -{ - CHECK_VALID_FILE_HANDLE(handle); - - return __WASI_ENOSYS; -} - -__wasi_errno_t -os_fadvise(os_file_handle handle, __wasi_filesize_t offset, - __wasi_filesize_t length, __wasi_advice_t advice) -{ - CHECK_VALID_FILE_HANDLE(handle); - - return __WASI_ENOSYS; -} - __wasi_errno_t os_isatty(os_file_handle handle) { @@ -1364,10 +1558,115 @@ os_convert_stderr_handle(os_raw_file_handle raw_stderr) return create_stdio_handle(raw_stderr, STD_ERROR_HANDLE); } +__wasi_errno_t +os_unlinkat(os_file_handle handle, const char *path, bool is_dir) +{ + CHECK_VALID_FILE_HANDLE(handle); + + wchar_t absolute_path[PATH_MAX]; + __wasi_errno_t error = get_absolute_filepath(handle->raw.handle, path, + absolute_path, PATH_MAX); + + DWORD attributes = GetFileAttributesW(absolute_path); + + if (attributes != INVALID_FILE_ATTRIBUTES + && (attributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0) { + // Override is_dir for symlinks. A symlink to a directory counts as a + // directory itself in Windows. + is_dir = (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0; + } + + if (error != __WASI_ESUCCESS) + return error; + + int ret = + is_dir ? RemoveDirectoryW(absolute_path) : DeleteFileW(absolute_path); + + if (ret == 0) + error = convert_windows_error_code(GetLastError()); + + return error; +} + +__wasi_errno_t +os_lseek(os_file_handle handle, __wasi_filedelta_t offset, + __wasi_whence_t whence, __wasi_filesize_t *new_offset) +{ + CHECK_VALID_FILE_HANDLE(handle); + DWORD sys_whence = 0; + + switch (whence) { + case __WASI_WHENCE_SET: + sys_whence = FILE_BEGIN; + break; + case __WASI_WHENCE_END: + sys_whence = FILE_END; + break; + case __WASI_WHENCE_CUR: + sys_whence = FILE_CURRENT; + break; + default: + return __WASI_EINVAL; + } + + LARGE_INTEGER distance_to_move = { .QuadPart = offset }; + LARGE_INTEGER updated_offset = { .QuadPart = 0 }; + + int ret = SetFilePointerEx(handle->raw.handle, distance_to_move, + &updated_offset, sys_whence); + + if (ret == 0) + return convert_windows_error_code(GetLastError()); + + *new_offset = (__wasi_filesize_t)updated_offset.QuadPart; + return __WASI_ESUCCESS; +} + +__wasi_errno_t +os_fadvise(os_file_handle handle, __wasi_filesize_t offset, + __wasi_filesize_t length, __wasi_advice_t advice) +{ + CHECK_VALID_FILE_HANDLE(handle); + // Advisory information can be safely ignored if not supported + switch (advice) { + case __WASI_ADVICE_DONTNEED: + case __WASI_ADVICE_NOREUSE: + case __WASI_ADVICE_NORMAL: + case __WASI_ADVICE_RANDOM: + case __WASI_ADVICE_SEQUENTIAL: + case __WASI_ADVICE_WILLNEED: + return __WASI_ESUCCESS; + default: + return __WASI_EINVAL; + } +} + __wasi_errno_t os_fdopendir(os_file_handle handle, os_dir_stream *dir_stream) { - return __WASI_ENOSYS; + CHECK_VALID_FILE_HANDLE(handle); + + // Check the handle is a directory handle first + DWORD windows_filetype = GetFileType(handle->raw.handle); + + __wasi_filetype_t filetype = __WASI_FILETYPE_UNKNOWN; + __wasi_errno_t error = + convert_windows_filetype(handle, windows_filetype, &filetype); + + if (error != __WASI_ESUCCESS) + return error; + + if (filetype != __WASI_FILETYPE_DIRECTORY) + return __WASI_ENOTDIR; + + *dir_stream = BH_MALLOC(sizeof(windows_dir_stream)); + + if (*dir_stream == NULL) + return __WASI_ENOMEM; + + init_dir_stream(*dir_stream, handle); + + return error; } __wasi_errno_t @@ -1375,7 +1674,9 @@ os_rewinddir(os_dir_stream dir_stream) { CHECK_VALID_WIN_DIR_STREAM(dir_stream); - return __WASI_ENOSYS; + reset_dir_stream(dir_stream); + + return __WASI_ESUCCESS; } __wasi_errno_t @@ -1383,7 +1684,25 @@ os_seekdir(os_dir_stream dir_stream, __wasi_dircookie_t position) { CHECK_VALID_WIN_DIR_STREAM(dir_stream); - return __WASI_ENOSYS; + if (dir_stream->cookie == position) + return __WASI_ESUCCESS; + + if (dir_stream->cookie > position) { + reset_dir_stream(dir_stream); + } + + while (dir_stream->cookie < position) { + __wasi_errno_t error = read_next_dir_entry(dir_stream, NULL); + + if (error != __WASI_ESUCCESS) + return error; + + // We've reached the end of the directory. + if (dir_stream->cookie == 0) { + break; + } + } + return __WASI_ESUCCESS; } __wasi_errno_t @@ -1392,7 +1711,23 @@ os_readdir(os_dir_stream dir_stream, __wasi_dirent_t *entry, { CHECK_VALID_WIN_DIR_STREAM(dir_stream); - return __WASI_ENOSYS; + FILE_ID_BOTH_DIR_INFO *file_id_both_dir_info = NULL; + + __wasi_errno_t error = + read_next_dir_entry(dir_stream, &file_id_both_dir_info); + + if (error != __WASI_ESUCCESS || file_id_both_dir_info == NULL) + return error; + + entry->d_ino = (__wasi_inode_t)file_id_both_dir_info->FileId.QuadPart; + entry->d_namlen = (__wasi_dirnamlen_t)(file_id_both_dir_info->FileNameLength + / (sizeof(wchar_t) / sizeof(char))); + entry->d_next = (__wasi_dircookie_t)dir_stream->cookie; + entry->d_type = get_disk_filetype(file_id_both_dir_info->FileAttributes); + + *d_name = dir_stream->current_entry_name; + + return __WASI_ESUCCESS; } __wasi_errno_t @@ -1400,7 +1735,19 @@ os_closedir(os_dir_stream dir_stream) { CHECK_VALID_WIN_DIR_STREAM(dir_stream); - return __WASI_ENOSYS; + bool success = CloseHandle(dir_stream->handle->raw.handle); + + if (!success) { + DWORD win_error = GetLastError(); + + if (win_error = ERROR_INVALID_HANDLE) + BH_FREE(dir_stream); + return convert_windows_error_code(win_error); + } + + BH_FREE(dir_stream); + + return __WASI_ESUCCESS; } os_dir_stream diff --git a/core/shared/platform/windows/win_util.c b/core/shared/platform/windows/win_util.c index ee0e82fb9..58987fa00 100644 --- a/core/shared/platform/windows/win_util.c +++ b/core/shared/platform/windows/win_util.c @@ -6,19 +6,31 @@ #include "platform_common.h" #include "win_util.h" +// From 1601-01-01 to 1970-01-01 there are 134774 days. +static const uint64_t NT_to_UNIX_epoch_in_ns = + 134774ull * 86400ull * 1000ull * 1000ull * 1000ull; + __wasi_timestamp_t convert_filetime_to_wasi_timestamp(LPFILETIME filetime) { - // From 1601-01-01 to 1970-01-01 there are 134774 days. - static const uint64_t NT_to_UNIX_epoch = - 134774ull * 86400ull * 1000ull * 1000ull * 1000ull; - ULARGE_INTEGER temp = { .HighPart = filetime->dwHighDateTime, .LowPart = filetime->dwLowDateTime }; // WASI timestamps are measured in nanoseconds whereas FILETIME structs are // represented in terms 100-nanosecond intervals. - return (temp.QuadPart * 100ull) - NT_to_UNIX_epoch; + return (temp.QuadPart * 100ull) - NT_to_UNIX_epoch_in_ns; +} + +FILETIME +convert_wasi_timestamp_to_filetime(__wasi_timestamp_t timestamp) +{ + ULARGE_INTEGER temp = { .QuadPart = + (timestamp + NT_to_UNIX_epoch_in_ns) / 100ull }; + + FILETIME ret = { .dwLowDateTime = temp.LowPart, + .dwHighDateTime = temp.HighPart }; + + return ret; } __wasi_errno_t diff --git a/core/shared/platform/windows/win_util.h b/core/shared/platform/windows/win_util.h index 3960fe946..033c393b5 100644 --- a/core/shared/platform/windows/win_util.h +++ b/core/shared/platform/windows/win_util.h @@ -12,6 +12,9 @@ __wasi_timestamp_t convert_filetime_to_wasi_timestamp(LPFILETIME filetime); +FILETIME +convert_wasi_timestamp_to_filetime(__wasi_timestamp_t timestamp); + /* Convert a Windows error code to a WASI error code */ __wasi_errno_t convert_windows_error_code(DWORD windows_error_code); diff --git a/core/shared/platform/zephyr/platform_internal.h b/core/shared/platform/zephyr/platform_internal.h index a5d563a6c..3c0f55266 100644 --- a/core/shared/platform/zephyr/platform_internal.h +++ b/core/shared/platform/zephyr/platform_internal.h @@ -50,6 +50,10 @@ #include #endif /* end of KERNEL_VERSION_NUMBER < 0x030200 */ +#if KERNEL_VERSION_NUMBER >= 0x030300 /* version 3.3.0 */ +#include +#endif /* end of KERNEL_VERSION_NUMBER > 0x030300 */ + #ifdef CONFIG_ARM_MPU #if KERNEL_VERSION_NUMBER < 0x030200 /* version 3.2.0 */ #include @@ -96,7 +100,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 +128,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 */ @@ -166,4 +175,15 @@ os_get_invalid_handle() return -1; } +static inline int +os_getpagesize() +{ +#ifdef CONFIG_MMU + return CONFIG_MMU_PAGE_SIZE; +#else + /* Return a default page size if the MMU is not enabled */ + return 4096; /* 4KB */ +#endif +} + #endif 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..fc54ba559 100644 --- a/core/shared/platform/zephyr/zephyr_platform.c +++ b/core/shared/platform/zephyr/zephyr_platform.c @@ -25,9 +25,11 @@ disable_mpu_rasr_xn(void) would most likely be set at index 2. */ for (index = 0U; index < 8; index++) { MPU->RNR = index; +#ifdef MPU_RASR_XN_Msk if (MPU->RASR & MPU_RASR_XN_Msk) { MPU->RASR |= ~MPU_RASR_XN_Msk; } +#endif } } #endif /* end of CONFIG_ARM_MPU */ @@ -72,18 +74,20 @@ bh_platform_destroy() void * os_malloc(unsigned size) { - return NULL; + return malloc(size); } void * os_realloc(void *ptr, unsigned size) { - return NULL; + return realloc(ptr, size); } void os_free(void *ptr) -{} +{ + free(ptr); +} int os_dumps_proc_mem_info(char *out, unsigned int size) @@ -183,6 +187,12 @@ os_mmap(void *hint, size_t size, int prot, int flags, os_file_handle file) return BH_MALLOC(size); } +void * +os_mremap(void *old_addr, size_t old_size, size_t new_size) +{ + return os_mremap_slow(old_addr, old_size, new_size); +} + void os_munmap(void *addr, size_t size) { @@ -202,10 +212,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 +230,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/platform/zephyr/zephyr_thread.c b/core/shared/platform/zephyr/zephyr_thread.c index 105d53993..53ca71f62 100644 --- a/core/shared/platform/zephyr/zephyr_thread.c +++ b/core/shared/platform/zephyr/zephyr_thread.c @@ -577,4 +577,34 @@ os_thread_get_stack_boundary() void os_thread_jit_write_protect_np(bool enabled) -{} \ No newline at end of file +{} + +int +os_thread_detach(korp_tid thread) +{ + (void)thread; + return BHT_OK; +} + +void +os_thread_exit(void *retval) +{ + (void)retval; + os_thread_cleanup(); + k_thread_abort(k_current_get()); +} + +int +os_cond_broadcast(korp_cond *cond) +{ + os_thread_wait_node *node; + k_mutex_lock(&cond->wait_list_lock, K_FOREVER); + node = cond->thread_wait_list; + while (node) { + os_thread_wait_node *next = node->next; + k_sem_give(&node->sem); + node = next; + } + k_mutex_unlock(&cond->wait_list_lock); + return BHT_OK; +} diff --git a/core/shared/utils/bh_atomic.h b/core/shared/utils/bh_atomic.h index 5744a64c0..4f7d9bc83 100644 --- a/core/shared/utils/bh_atomic.h +++ b/core/shared/utils/bh_atomic.h @@ -44,6 +44,7 @@ extern "C" { * #endif */ +typedef uint64 bh_atomic_64_t; typedef uint32 bh_atomic_32_t; typedef uint16 bh_atomic_16_t; @@ -52,6 +53,10 @@ typedef uint16 bh_atomic_16_t; * If left undefined, it will be automatically defined * according to the platform. */ +#ifdef WASM_UINT64_IS_ATOMIC +#define BH_ATOMIC_64_IS_ATOMIC WASM_UINT64_IS_ATOMIC +#endif /* WASM_UINT64_IS_ATOMIC */ + #ifdef WASM_UINT32_IS_ATOMIC #define BH_ATOMIC_32_IS_ATOMIC WASM_UINT32_IS_ATOMIC #endif /* WASM_UINT32_IS_ATOMIC */ @@ -71,6 +76,9 @@ typedef uint16 bh_atomic_16_t; #endif #if defined(CLANG_GCC_HAS_ATOMIC_BUILTIN) +#ifndef BH_ATOMIC_64_IS_ATOMIC +#define BH_ATOMIC_64_IS_ATOMIC 1 +#endif #ifndef BH_ATOMIC_32_IS_ATOMIC #define BH_ATOMIC_32_IS_ATOMIC 1 #endif @@ -78,6 +86,9 @@ typedef uint16 bh_atomic_16_t; #define BH_ATOMIC_16_IS_ATOMIC 1 #endif #else +#ifndef BH_ATOMIC_64_IS_ATOMIC +#define BH_ATOMIC_64_IS_ATOMIC 0 +#endif #ifndef BH_ATOMIC_32_IS_ATOMIC #define BH_ATOMIC_32_IS_ATOMIC 0 #endif @@ -101,6 +112,72 @@ typedef uint16 bh_atomic_16_t; #endif #endif +/* On some 32-bit platform, disable 64-bit atomic operations, otherwise + * undefined reference to `__atomic_load_8' */ +#ifndef WASM_UINT64_IS_ATOMIC +#if !defined(__linux__) && !defined(__FreeBSD__) && !defined(__NetBSD__) \ + && !defined(__OpenBSD__) && (defined(__riscv) || defined(__arm__)) \ + && UINT32_MAX == UINTPTR_MAX +#undef BH_ATOMIC_64_IS_ATOMIC +#define BH_ATOMIC_64_IS_ATOMIC 0 +#endif +#endif + +#if BH_ATOMIC_64_IS_ATOMIC != 0 + +#define BH_ATOMIC_64_LOAD(v) __atomic_load_n(&(v), __ATOMIC_SEQ_CST) +#define BH_ATOMIC_64_STORE(v, val) __atomic_store_n(&(v), val, __ATOMIC_SEQ_CST) +#define BH_ATOMIC_64_FETCH_OR(v, val) \ + __atomic_fetch_or(&(v), (val), __ATOMIC_SEQ_CST) +#define BH_ATOMIC_64_FETCH_AND(v, val) \ + __atomic_fetch_and(&(v), (val), __ATOMIC_SEQ_CST) +#define BH_ATOMIC_64_FETCH_ADD(v, val) \ + __atomic_fetch_add(&(v), (val), __ATOMIC_SEQ_CST) +#define BH_ATOMIC_64_FETCH_SUB(v, val) \ + __atomic_fetch_sub(&(v), (val), __ATOMIC_SEQ_CST) + +#else /* else of BH_ATOMIC_64_IS_ATOMIC != 0 */ + +#define BH_ATOMIC_64_LOAD(v) (v) +#define BH_ATOMIC_64_STORE(v, val) (v) = val +#define BH_ATOMIC_64_FETCH_OR(v, val) nonatomic_64_fetch_or(&(v), val) +#define BH_ATOMIC_64_FETCH_AND(v, val) nonatomic_64_fetch_and(&(v), val) +#define BH_ATOMIC_64_FETCH_ADD(v, val) nonatomic_64_fetch_add(&(v), val) +#define BH_ATOMIC_64_FETCH_SUB(v, val) nonatomic_64_fetch_sub(&(v), val) + +static inline uint64 +nonatomic_64_fetch_or(bh_atomic_64_t *p, uint64 val) +{ + uint64 old = *p; + *p |= val; + return old; +} + +static inline uint64 +nonatomic_64_fetch_and(bh_atomic_64_t *p, uint64 val) +{ + uint64 old = *p; + *p &= val; + return old; +} + +static inline uint64 +nonatomic_64_fetch_add(bh_atomic_64_t *p, uint64 val) +{ + uint64 old = *p; + *p += val; + return old; +} + +static inline uint64 +nonatomic_64_fetch_sub(bh_atomic_64_t *p, uint64 val) +{ + uint64 old = *p; + *p -= val; + return old; +} +#endif + #if BH_ATOMIC_32_IS_ATOMIC != 0 #define BH_ATOMIC_32_LOAD(v) __atomic_load_n(&(v), __ATOMIC_SEQ_CST) diff --git a/core/shared/utils/bh_memutils.c b/core/shared/utils/bh_memutils.c deleted file mode 100644 index a655d8ac2..000000000 --- a/core/shared/utils/bh_memutils.c +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (C) 2024 Amazon Inc. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#include "bh_memutils.h" - -void * -bh_memory_remap_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, -1); - 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; -} diff --git a/core/shared/utils/bh_memutils.h b/core/shared/utils/bh_memutils.h deleted file mode 100644 index 7581860bd..000000000 --- a/core/shared/utils/bh_memutils.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2024 Amazon Inc. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - */ - -#ifndef _BH_MEMUTILS_H -#define _BH_MEMUTILS_H - -#include "bh_platform.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * Remaps memory by mapping a new region, copying data from the old - * region and umapping the old region. - * - * Unless the behavior is desired, in most cases os_mremap should be used - * as it's at worst equally slow as this function, and on some platforms - * (e.g. posix with mremap) os_mremap will perform better. - * - * @param old_addr an old address. - * @param old_size a size of the old address. - * @param new_size a size of the new memory region. - * @return a pointer to the new memory region. - */ -void * -bh_memory_remap_slow(void *old_addr, size_t old_size, size_t new_size); - -#ifdef __cplusplus -} -#endif - -#endif /* end of _BH_MEMUTILS_H */ diff --git a/core/shared/utils/runtime_timer.c b/core/shared/utils/runtime_timer.c index b9ace567f..9d390c214 100644 --- a/core/shared/utils/runtime_timer.c +++ b/core/shared/utils/runtime_timer.c @@ -394,7 +394,7 @@ handle_expired_timers(timer_ctx_t ctx, app_timer_t *expired) operation may change expired->next */ expired = expired->next; if (t->is_periodic) { - /* if it is repeating, then reschedule it; */ + /* if it is repeating, then reschedule it */ reschedule_timer(ctx, t); } else { diff --git a/doc/build_wamr.md b/doc/build_wamr.md index 75c17e634..b0a8ea35f 100644 --- a/doc/build_wamr.md +++ b/doc/build_wamr.md @@ -76,6 +76,11 @@ cmake -DWAMR_BUILD_PLATFORM=linux -DWAMR_BUILD_TARGET=ARM #### **Enable bulk memory feature** - **WAMR_BUILD_BULK_MEMORY**=1/0, default to disable if not set +#### **Enable memory64 feature** +- **WAMR_BUILD_MEMORY64**=1/0, default to disable if not set + +> Note: Currently, the memory64 feature is only supported in classic interpreter running mode. + #### **Enable thread manager** - **WAMR_BUILD_THREAD_MGR**=1/0, default to disable if not set @@ -107,6 +112,9 @@ cmake -DWAMR_BUILD_PLATFORM=linux -DWAMR_BUILD_TARGET=ARM - **WAMR_BUILD_WASI_NN_EXTERNAL_DELEGATE_PATH**=Path to the external delegate shared library (e.g. `libedgetpu.so.1.0` for Coral USB) +#### **Enable lib wasi-nn with `wasi_ephemeral_nn` module support** +- **WAMR_BUILD_WASI_EPHEMERAL_NN**=1/0, default to disable if not set + #### **Disable boundary check with hardware trap** - **WAMR_DISABLE_HW_BOUND_CHECK**=1/0, default to enable if not set and supported by platform > Note: by default only platform [linux/darwin/android/windows/vxworks 64-bit](https://github.com/bytecodealliance/wasm-micro-runtime/blob/5fb5119239220b0803e7045ca49b0a29fe65e70e/core/shared/platform/linux/platform_internal.h#L81) will enable the boundary check with hardware trap feature, for 32-bit platforms it's automatically disabled even when the flag is set to 0, and the wamrc tool will generate AOT code without boundary check instructions in all 64-bit targets except SGX to improve performance. The boundary check includes linear memory access boundary and native stack access boundary, if `WAMR_DISABLE_STACK_HW_BOUND_CHECK` below isn't set. @@ -126,6 +134,14 @@ cmake -DWAMR_BUILD_PLATFORM=linux -DWAMR_BUILD_TARGET=ARM - **WAMR_BUILD_SIMD**=1/0, default to enable if not set > Note: only supported in AOT mode x86-64 target. +#### **Enable Exception Handling** +- **WAMR_BUILD_EXCE_HANDLING**=1/0, default to disable if not set + +> Note: Currently, the exception handling feature is only supported in classic interpreter running mode. + +#### **Enable Garbage Collection** +- **WAMR_BUILD_GC**=1/0, default to disable if not set + #### **Configure Debug** - **WAMR_BUILD_CUSTOM_NAME_SECTION**=1/0, load the function name from custom name section, default to disable if not set @@ -176,7 +192,7 @@ Currently we only profile the memory consumption of module, module_instance and #### **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 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: +> 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) @@ -261,6 +277,10 @@ Currently we only profile the memory consumption of module, module_instance and - **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. +#### **Enable AOT intrinsics** +- **WAMR_BUILD_AOT_INTRINSICS**=1/0, enable the AOT intrinsic functions, default to enable if not set. These functions can be called from the AOT code when `--disable-llvm-intrinsics` flag or `--enable-builtin-intrinsics=` flag is used by wamrc to generate the AOT file. +> Note: See [Tuning the XIP intrinsic functions](./xip.md#tuning-the-xip-intrinsic-functions) 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. diff --git a/doc/embed_wamr.md b/doc/embed_wamr.md index b83817589..5e4e3a512 100644 --- a/doc/embed_wamr.md +++ b/doc/embed_wamr.md @@ -100,7 +100,7 @@ After a module is instantiated, the runtime embedder can lookup the target WASM ```c /* lookup a WASM function by its name The function signature can NULL here */ - func = wasm_runtime_lookup_function(module_inst, "fib", NULL); + func = wasm_runtime_lookup_function(module_inst, "fib"); /* creat an execution environment to execute the WASM functions */ exec_env = wasm_runtime_create_exec_env(module_inst, stack_size); @@ -211,9 +211,9 @@ There are two runtime APIs available for this purpose. * p_native_addr: return the native address of allocated memory * size: the buffer size to allocate */ -uint32_t +uint64_t wasm_runtime_module_malloc(wasm_module_inst_t module_inst, - uint32_t size, void **p_native_addr); + uint64_t size, void **p_native_addr); /** * malloc a buffer from instance's private memory space, @@ -223,28 +223,28 @@ wasm_runtime_module_malloc(wasm_module_inst_t module_inst, * src: the native buffer address * size: the size of buffer to be allocated and copy data */ -uint32_t +uint64_t wasm_runtime_module_dup_data(wasm_module_inst_t module_inst, - const char *src, uint32_t size); + const char *src, uint64_t size); /* free the memory allocated from module memory space */ void -wasm_runtime_module_free(wasm_module_inst_t module_inst, uint32_t ptr); +wasm_runtime_module_free(wasm_module_inst_t module_inst, uint64_t ptr); ``` Usage sample: ```c char * buffer = NULL; -uint32_t buffer_for_wasm; +uint64_t buffer_for_wasm; buffer_for_wasm = wasm_runtime_module_malloc(module_inst, 100, &buffer); if (buffer_for_wasm != 0) { - uint32 argv[2]; + uint32 argv[3]; strncpy(buffer, "hello", 100); /* use native address for accessing in runtime */ argv[0] = buffer_for_wasm; /* pass the buffer address for WASM space */ - argv[1] = 100; /* the size of buffer */ - wasm_runtime_call_wasm(exec_env, func, 2, argv); + argv[2] = 100; /* the size of buffer */ + wasm_runtime_call_wasm(exec_env, func, 3, argv); /* it is runtime embedder's responsibility to release the memory, unless the WASM app will free the passed pointer in its code */ diff --git a/doc/export_native_api.md b/doc/export_native_api.md index ed7385539..b8f77f262 100644 --- a/doc/export_native_api.md +++ b/doc/export_native_api.md @@ -170,12 +170,12 @@ void foo2(wasm_exec_env_t exec_env, if (!wasm_runtime_validate_app_str_add(msg_offset)) return 0; - if (!wasm_runtime_validate_app_addr(buffer_offset, buf_len)) + if (!wasm_runtime_validate_app_addr((uint64)buffer_offset, (uint64)buf_len)) return; // do address conversion - buffer = wasm_runtime_addr_app_to_native(buffer_offset); - msg = wasm_runtime_addr_app_to_native(msg_offset); + buffer = wasm_runtime_addr_app_to_native((uint64)buffer_offset); + msg = wasm_runtime_addr_app_to_native((uint64)msg_offset); strncpy(buffer, msg, buf_len); } @@ -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/multi_module.md b/doc/multi_module.md index 9ab26673e..ac9e3bbde 100644 --- a/doc/multi_module.md +++ b/doc/multi_module.md @@ -62,8 +62,7 @@ WAMR hopes that the native host or embedding environment loads/unloads the modul ```c wasm_function_inst_t wasm_runtime_lookup_function(wasm_module_inst_t const module_inst, - const char *name, - const char *signature); + const char *name); ``` Multi-module allows one to look up an exported function of a submodule. There are two ways to indicate the function _name_: diff --git a/doc/perf_tune.md b/doc/perf_tune.md index b366f09c0..7858cc854 100644 --- a/doc/perf_tune.md +++ b/doc/perf_tune.md @@ -98,17 +98,22 @@ You should only use this method for well tested wasm applications and make sure Linux perf is a powerful tool to analyze the performance of a program, developer can use it to find the hot functions and optimize them. It is one profiler supported by WAMR. In order to use it, you need to add `--perf-profile` while running _iwasm_. By default, it is disabled. > [!CAUTION] -> For now, only llvm-jit mode supports linux-perf. +> For now, only llvm-jit mode and aot mode supports linux-perf. Here is a basic example, if there is a Wasm application _foo.wasm_, you'll execute. ``` -$ perf record --output=perf.data.raw -- iwasm --perf-profile foo.wasm +$ perf record --output=perf.data.raw -- iwasm --enable-linux-perf foo.wasm ``` -This will create a _perf.data_ and a _jit-xxx.dump_ under _~/.debug.jit/_ folder. This extra file is WAMR generated at runtime, and it contains the mapping between the JIT code and the original Wasm function names. +This will create a _perf.data_ and +- a _jit-xxx.dump_ under _~/.debug/jit/_ folder if running llvm-jit mode +- or _/tmp/perf-.map_ if running AOT mode -The next thing need to do is to merge _jit-xxx.dump_ file into the _perf.data_. + +This file is WAMR generated. It contains information which includes jitted(precompiled) code addresses in memory, names of jitted (precompiled) functions which are named as *aot_func#N* and so on. + +If running with llvm-jit mode, the next thing is to merge _jit-xxx.dump_ file into the _perf.data_. ``` $ perf inject --jit --input=perf.data.raw --output=perf.data @@ -141,28 +146,28 @@ $ perf report --input=perf.data [Flamegraph](https://www.brendangregg.com/flamegraphs.html) is a powerful tool to visualize stack traces of profiled software so that the most frequent code-paths can be identified quickly and accurately. In order to use it, you need to [capture graphs](https://github.com/brendangregg/FlameGraph#1-capture-stacks) when running `perf record` ``` -$ perf record -k mono --call-graph=fp --output=perf.data.raw -- iwasm --perf-profile foo.wasm +$ perf record -k mono --call-graph=fp --output=perf.data.raw -- iwasm --enable-linux-perf foo.wasm ``` -merge the _jit-xxx.dump_ file into the _perf.data.raw_. +If running with llvm-jit mode, merge the _jit-xxx.dump_ file into the _perf.data.raw_. ``` $ perf inject --jit --input=perf.data.raw --output=perf.data ``` -generate the stack trace file. +Generate the stack trace file. ``` $ perf script > out.perf ``` -[fold stacks](https://github.com/brendangregg/FlameGraph#2-fold-stacks). +[Fold stacks](https://github.com/brendangregg/FlameGraph#2-fold-stacks). ``` $ ./FlameGraph/stackcollapse-perf.pl out.perf > out.folded ``` -[render a flamegraph](https://github.com/brendangregg/FlameGraph#3-flamegraphpl) +[Render a flamegraph](https://github.com/brendangregg/FlameGraph#3-flamegraphpl) ``` $ ./FlameGraph/flamegraph.pl out.folded > perf.foo.wasm.svg @@ -288,7 +293,7 @@ And in the host embedder: bool ret; argv[0] = *(uint32 *)&arg_f32; - func = wasm_runtime_lookup_function(module_inst, "foo1", NULL); + func = wasm_runtime_lookup_function(module_inst, "foo1"); ret = wasm_runtime_call_wasm(exec_env, func, 1, argv); if (!ret) { /* handle exception */ 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/idf_component.yml b/idf_component.yml new file mode 100644 index 000000000..ff25b32cb --- /dev/null +++ b/idf_component.yml @@ -0,0 +1,15 @@ +version: "2.0.0" +description: WebAssembly Micro Runtime - A lightweight standalone WebAssembly (Wasm) runtime with small footprint, high performance and highly configurable features +url: https://bytecodealliance.org/ +repository: https://github.com/bytecodealliance/wasm-micro-runtime.git +documentation: https://wamr.gitbook.io/ +issues: https://github.com/bytecodealliance/wasm-micro-runtime/issues +dependencies: + idf: ">=4.4" +targets: + - esp32 + - esp32s3 + - esp32c3 + - esp32c6 +examples: + - path: product-mini/platforms/esp-idf \ No newline at end of file diff --git a/language-bindings/go/samples/test.go b/language-bindings/go/samples/test.go index d0fc7d8b2..19b2814a8 100644 --- a/language-bindings/go/samples/test.go +++ b/language-bindings/go/samples/test.go @@ -87,7 +87,7 @@ func main() { var instance *wamr.Instance var argv []uint32 var results []interface{} - var offset uint32 + var offset uint64 var native_addr *uint8 var err error diff --git a/language-bindings/go/wamr/instance.go b/language-bindings/go/wamr/instance.go index 7c761ee99..111d795bc 100644 --- a/language-bindings/go/wamr/instance.go +++ b/language-bindings/go/wamr/instance.go @@ -129,8 +129,7 @@ func (self *Instance) CallFunc(funcName string, cName := C.CString(funcName) defer C.free(unsafe.Pointer(cName)) - _func = C.wasm_runtime_lookup_function(self._instance, - cName, (*C.char)(C.NULL)) + _func = C.wasm_runtime_lookup_function(self._instance, cName) if _func == nil { return fmt.Errorf("CallFunc error: lookup function failed") } @@ -170,8 +169,7 @@ func (self *Instance) CallFuncV(funcName string, cName := C.CString(funcName) defer C.free(unsafe.Pointer(cName)) - _func = C.wasm_runtime_lookup_function(self._instance, - cName, (*C.char)(C.NULL)) + _func = C.wasm_runtime_lookup_function(self._instance, cName) if _func == nil { return fmt.Errorf("CallFunc error: lookup function failed") } @@ -309,62 +307,62 @@ func (self *Instance) GetException() string { } /* Allocate memory from the heap of the instance */ -func (self Instance) ModuleMalloc(size uint32) (uint32, *uint8) { - var offset C.uint32_t +func (self Instance) ModuleMalloc(size uint64) (uint64, *uint8) { + var offset C.uint64_t native_addrs := make([]*uint8, 1, 1) ptr := unsafe.Pointer(&native_addrs[0]) - offset = C.wasm_runtime_module_malloc(self._instance, (C.uint32_t)(size), + offset = C.wasm_runtime_module_malloc(self._instance, (C.uint64_t)(size), (*unsafe.Pointer)(ptr)) - return (uint32)(offset), native_addrs[0] + return (uint64)(offset), native_addrs[0] } /* Free memory to the heap of the instance */ -func (self Instance) ModuleFree(offset uint32) { - C.wasm_runtime_module_free(self._instance, (C.uint32_t)(offset)) +func (self Instance) ModuleFree(offset uint64) { + C.wasm_runtime_module_free(self._instance, (C.uint64_t)(offset)) } -func (self Instance) ValidateAppAddr(app_offset uint32, size uint32) bool { +func (self Instance) ValidateAppAddr(app_offset uint64, size uint64) bool { ret := C.wasm_runtime_validate_app_addr(self._instance, - (C.uint32_t)(app_offset), - (C.uint32_t)(size)) + (C.uint64_t)(app_offset), + (C.uint64_t)(size)) return (bool)(ret) } -func (self Instance) ValidateStrAddr(app_str_offset uint32) bool { +func (self Instance) ValidateStrAddr(app_str_offset uint64) bool { ret := C.wasm_runtime_validate_app_str_addr(self._instance, - (C.uint32_t)(app_str_offset)) + (C.uint64_t)(app_str_offset)) return (bool)(ret) } -func (self Instance) ValidateNativeAddr(native_ptr *uint8, size uint32) bool { +func (self Instance) ValidateNativeAddr(native_ptr *uint8, size uint64) bool { native_ptr_C := (unsafe.Pointer)(native_ptr) ret := C.wasm_runtime_validate_native_addr(self._instance, native_ptr_C, - (C.uint32_t)(size)) + (C.uint64_t)(size)) return (bool)(ret) } -func (self Instance) AddrAppToNative(app_offset uint32) *uint8 { +func (self Instance) AddrAppToNative(app_offset uint64) *uint8 { native_ptr := C.wasm_runtime_addr_app_to_native(self._instance, - (C.uint32_t)(app_offset)) + (C.uint64_t)(app_offset)) return (*uint8)(native_ptr) } -func (self Instance) AddrNativeToApp(native_ptr *uint8) uint32 { +func (self Instance) AddrNativeToApp(native_ptr *uint8) uint64 { native_ptr_C := (unsafe.Pointer)(native_ptr) offset := C.wasm_runtime_addr_native_to_app(self._instance, native_ptr_C) - return (uint32)(offset) + return (uint64)(offset) } -func (self Instance) GetAppAddrRange(app_offset uint32) (bool, - uint32, - uint32) { - var start_offset, end_offset C.uint32_t +func (self Instance) GetAppAddrRange(app_offset uint64) (bool, + uint64, + uint64) { + var start_offset, end_offset C.uint64_t ret := C.wasm_runtime_get_app_addr_range(self._instance, - (C.uint32_t)(app_offset), + (C.uint64_t)(app_offset), &start_offset, &end_offset) - return (bool)(ret), (uint32)(start_offset), (uint32)(end_offset) + return (bool)(ret), (uint64)(start_offset), (uint64)(end_offset) } func (self Instance) GetNativeAddrRange(native_ptr *uint8) (bool, diff --git a/language-bindings/go/wamr/module.go b/language-bindings/go/wamr/module.go index 13480b221..7fd131ea6 100644 --- a/language-bindings/go/wamr/module.go +++ b/language-bindings/go/wamr/module.go @@ -117,8 +117,8 @@ func (self *Module) SetWasiArgsEx(dirList [][]byte, mapDirList [][]byte, C.wasm_runtime_set_wasi_args_ex(self.module, dirPtr, dirCount, mapDirPtr, mapDirCount, envPtr, envCount, argvPtr, argc, - C.int(stdinfd), C.int(stdoutfd), - C.int(stderrfd)) + C.int64_t(stdinfd), C.int64_t(stdoutfd), + C.int64_t(stderrfd)) } /* Set module's wasi network address pool */ diff --git a/language-bindings/python/README.md b/language-bindings/python/README.md index 96b7a7ff9..45604af7f 100644 --- a/language-bindings/python/README.md +++ b/language-bindings/python/README.md @@ -4,7 +4,7 @@ The WAMR Python package contains a set of high-level bindings for WAMR API and W ## Installation -* **Notice**: This python package need python >= `3.9`. +* **Notice**: This python package need python >= `3.10`. To Install from local source tree in _development mode_ run the following command, diff --git a/language-bindings/python/setup.py b/language-bindings/python/setup.py index ec080e4ee..1087c6425 100755 --- a/language-bindings/python/setup.py +++ b/language-bindings/python/setup.py @@ -62,5 +62,5 @@ setup( 'install': PreInstallCommand, 'egg_info': PreEggInfoCommand, }, - python_requires='>=3.9' + python_requires='>=3.10' ) diff --git a/language-bindings/python/src/wamr/wamrapi/wamr.py b/language-bindings/python/src/wamr/wamrapi/wamr.py index 1bd6e547d..9727faa37 100644 --- a/language-bindings/python/src/wamr/wamrapi/wamr.py +++ b/language-bindings/python/src/wamr/wamrapi/wamr.py @@ -6,6 +6,7 @@ from ctypes import addressof from ctypes import c_char from ctypes import c_uint from ctypes import c_uint8 +from ctypes import c_uint64 from ctypes import c_void_p from ctypes import cast from ctypes import create_string_buffer @@ -167,14 +168,14 @@ class Instance: raise Exception("Error while creating module instance") return module_inst - def malloc(self, nbytes: int, native_handler) -> c_uint: + def malloc(self, nbytes: int, native_handler) -> c_uint64: return wasm_runtime_module_malloc(self.module_inst, nbytes, native_handler) def free(self, wasm_handler) -> None: wasm_runtime_module_free(self.module_inst, wasm_handler) def lookup_function(self, name: str) -> wasm_function_inst_t: - func = wasm_runtime_lookup_function(self.module_inst, name, None) + func = wasm_runtime_lookup_function(self.module_inst, name) if not func: raise Exception("Error while looking-up function") return func diff --git a/language-bindings/python/src/wamr/wasmcapi/binding.py b/language-bindings/python/src/wamr/wasmcapi/binding.py index dd7adadf6..1f4e0cfd0 100644 --- a/language-bindings/python/src/wamr/wasmcapi/binding.py +++ b/language-bindings/python/src/wamr/wasmcapi/binding.py @@ -2013,6 +2013,15 @@ def wasm_instance_new_with_args(arg0,arg1,arg2,arg3,arg4,arg5): _wasm_instance_new_with_args.argtypes = [POINTER(wasm_store_t),POINTER(wasm_module_t),POINTER(wasm_extern_vec_t),POINTER(POINTER(wasm_trap_t)),c_uint32,c_uint32] return _wasm_instance_new_with_args(arg0,arg1,arg2,arg3,arg4,arg5) +class InstantiationArgs(Structure): + pass + +def wasm_instance_new_with_args_ex(arg0,arg1,arg2,arg3,arg4): + _wasm_instance_new_with_args_ex = libiwasm.wasm_instance_new_with_args_ex + _wasm_instance_new_with_args_ex.restype = POINTER(wasm_instance_t) + _wasm_instance_new_with_args_ex.argtypes = [POINTER(wasm_store_t),POINTER(wasm_module_t),POINTER(wasm_extern_vec_t),POINTER(POINTER(wasm_trap_t)),POINTER(InstantiationArgs)] + return _wasm_instance_new_with_args_ex(arg0,arg1,arg2,arg3,arg4) + def wasm_instance_exports(arg0,arg1): _wasm_instance_exports = libiwasm.wasm_instance_exports _wasm_instance_exports.restype = None diff --git a/language-bindings/python/wamr-api/README.md b/language-bindings/python/wamr-api/README.md index 236150ce4..38a440144 100644 --- a/language-bindings/python/wamr-api/README.md +++ b/language-bindings/python/wamr-api/README.md @@ -1,6 +1,6 @@ # WARM API -* **Notice**: The python package `wamr.wamrapi.wamr` need python >= `3.9`. +* **Notice**: The python package `wamr.wamrapi.wamr` need python >= `3.10`. ## Setup @@ -8,7 +8,7 @@ Install requirements, -``` +```shell pip install -r requirements.txt ``` @@ -17,6 +17,7 @@ pip install -r requirements.txt The following command builds the iwasm library and generates the Python bindings, ```sh +# In WAMR root directory bash language-bindings/python/utils/create_lib.sh ``` diff --git a/language-bindings/python/wasm-c-api/docs/design.md b/language-bindings/python/wasm-c-api/docs/design.md index 6c3bc9168..78bf56df0 100644 --- a/language-bindings/python/wasm-c-api/docs/design.md +++ b/language-bindings/python/wasm-c-api/docs/design.md @@ -431,130 +431,131 @@ In next phase, we will create OOP APIs. Almost follow the ## A big list -| WASM Concept | Procedural APIs | OOP APIs | OOP APIs methods | -| ------------ | ------------------------------ | ---------- | ---------------- | -| XXX_vec | wasm_xxx_vec_new | | list | -| | wasm_xxx_vec_new_uninitialized | | | -| | wasm_xxx_vec_new_empty | | | -| | wasm_xxx_vec_copy | | | -| | wasm_xxx_vec_delete | | | -| valtype | wasm_valtype_new | valtype | \_\_init\_\_ | -| | wasm_valtype_delete | | \_\_del\_\_ | -| | wasm_valtype_kind | | \_\_eq\_\_ | -| | wasm_valtype_copy | | | -| | _vector methods_ | | | -| functype | wasm_functype_new | functype | | -| | wasm_functype_delete | | | -| | wasm_functype_params | | | -| | wasm_functype_results | | | -| | wasm_functype_copy | | | -| | _vector methods_ | | | -| globaltype | wasm_globaltype_new | globaltype | \_\_init\_\_ | -| | wasm_globaltype_delete | | \_\_del\_\_ | -| | wasm_globaltype_content | | \_\_eq\_\_ | -| | wasm_globaltype_mutability | | | -| | wasm_globaltype_copy | | | -| | _vector methods_ | | | -| tabletype | wasm_tabletype_new | tabletype | \_\_init\_\_ | -| | wasm_tabletype_delete | | \_\_del\_\_ | -| | wasm_tabletype_element | | \_\_eq\_\_ | -| | wasm_tabletype_limits | | | -| | wasm_tabletype_copy | | | -| | _vector methods_ | | | -| memorytype | wasm_memorytype_new | memorytype | \_\_init\_\_ | -| | wasm_memorytype_delete | | \_\_del\_\_ | -| | wasm_memorytype_limits | | \_\_eq\_\_ | -| | wasm_memorytype_copy | | | -| | _vector methods_ | | | -| externtype | wasm_externtype_as_XXX | externtype | | -| | wasm_XXX_as_externtype | | | -| | wasm_externtype_copy | | | -| | wasm_externtype_delete | | | -| | wasm_externtype_kind | | | -| | _vector methods_ | | | -| importtype | wasm_importtype_new | importtype | | -| | wasm_importtype_delete | | | -| | wasm_importtype_module | | | -| | wasm_importtype_name | | | -| | wasm_importtype_type | | | -| | wasm_importtype_copy | | | -| | _vector methods_ | | | -| exportype | wasm_exporttype_new | exporttype | | -| | wasm_exporttype_delete | | | -| | wasm_exporttype_name | | | -| | wasm_exporttype_type | | | -| | wasm_exporttype_copy | | | -| | _vector methods_ | | | -| val | wasm_val_delete | val | | -| | wasm_val_copy | | | -| | _vector methods_ | | | -| frame | wasm_frame_delete | frame | | -| | wasm_frame_instance | | | -| | wasm_frame_func_index | | | -| | wasm_frame_func_offset | | | -| | wasm_frame_module_offset | | | -| | wasm_frame_copy | | | -| | _vector methods_ | | | -| trap | wasm_trap_new | trap | | -| | wasm_trap_delete | | | -| | wasm_trap_message | | | -| | wasm_trap_origin | | | -| | wasm_trap_trace | | | -| | _vector methods_ | | | -| foreign | wasm_foreign_new | foreign | | -| | wasm_foreign_delete | | | -| | _vector methods_ | | | -| engine | wasm_engine_new | engine | | -| | wasm_engine_new_with_args\* | | | -| | wasm_engine_new_with_config | | | -| | wasm_engine_delete | | | -| store | wasm_store_new | store | | -| | wasm_store_delete | | | -| | _vector methods_ | | | -| module | wasm_module_new | module | | -| | wasm_module_delete | | | -| | wasm_module_validate | | | -| | wasm_module_imports | | | -| | wasm_module_exports | | | -| instance | wasm_instance_new | instance | | -| | wasm_instance_delete | | | -| | wasm_instance_new_with_args\* | | | -| | wasm_instance_exports | | | -| | _vector methods_ | | | -| func | wasm_func_new | func | | -| | wasm_func_new_with_env | | | -| | wasm_func_delete | | | -| | wasm_func_type | | | -| | wasm_func_call | | | -| | wasm_func_param_arity | | | -| | wasm_func_result_arity | | | -| | _vector methods_ | | | -| global | wasm_global_new | global | | -| | wasm_global_delete | | | -| | wasm_global_type | | | -| | wasm_global_get | | | -| | wasm_global_set | | | -| | _vector methods_ | | | -| table | wasm_table_new | table | | -| | wasm_table_delete | | | -| | wasm_table_type | | | -| | wasm_table_get | | | -| | wasm_table_set | | | -| | wasm_table_size | | | -| | _vector methods_ | | | -| memory | wasm_memory_new | memory | | -| | wasm_memory_delete | | | -| | wasm_memory_type | | | -| | wasm_memory_data | | | -| | wasm_memory_data_size | | | -| | wasm_memory_size | | | -| | _vector methods_ | | | -| extern | wasm_extern_delete | extern | | -| | wasm_extern_as_XXX | | | -| | wasm_XXX_as_extern | | | -| | wasm_extern_kind | | | -| | wasm_extern_type | | | -| | _vector methods_ | | | +| WASM Concept | Procedural APIs | OOP APIs | OOP APIs methods | +| ------------ | -------------------------------- | ---------- | ---------------- | +| XXX_vec | wasm_xxx_vec_new | | list | +| | wasm_xxx_vec_new_uninitialized | | | +| | wasm_xxx_vec_new_empty | | | +| | wasm_xxx_vec_copy | | | +| | wasm_xxx_vec_delete | | | +| valtype | wasm_valtype_new | valtype | \_\_init\_\_ | +| | wasm_valtype_delete | | \_\_del\_\_ | +| | wasm_valtype_kind | | \_\_eq\_\_ | +| | wasm_valtype_copy | | | +| | _vector methods_ | | | +| functype | wasm_functype_new | functype | | +| | wasm_functype_delete | | | +| | wasm_functype_params | | | +| | wasm_functype_results | | | +| | wasm_functype_copy | | | +| | _vector methods_ | | | +| globaltype | wasm_globaltype_new | globaltype | \_\_init\_\_ | +| | wasm_globaltype_delete | | \_\_del\_\_ | +| | wasm_globaltype_content | | \_\_eq\_\_ | +| | wasm_globaltype_mutability | | | +| | wasm_globaltype_copy | | | +| | _vector methods_ | | | +| tabletype | wasm_tabletype_new | tabletype | \_\_init\_\_ | +| | wasm_tabletype_delete | | \_\_del\_\_ | +| | wasm_tabletype_element | | \_\_eq\_\_ | +| | wasm_tabletype_limits | | | +| | wasm_tabletype_copy | | | +| | _vector methods_ | | | +| memorytype | wasm_memorytype_new | memorytype | \_\_init\_\_ | +| | wasm_memorytype_delete | | \_\_del\_\_ | +| | wasm_memorytype_limits | | \_\_eq\_\_ | +| | wasm_memorytype_copy | | | +| | _vector methods_ | | | +| externtype | wasm_externtype_as_XXX | externtype | | +| | wasm_XXX_as_externtype | | | +| | wasm_externtype_copy | | | +| | wasm_externtype_delete | | | +| | wasm_externtype_kind | | | +| | _vector methods_ | | | +| importtype | wasm_importtype_new | importtype | | +| | wasm_importtype_delete | | | +| | wasm_importtype_module | | | +| | wasm_importtype_name | | | +| | wasm_importtype_type | | | +| | wasm_importtype_copy | | | +| | _vector methods_ | | | +| exportype | wasm_exporttype_new | exporttype | | +| | wasm_exporttype_delete | | | +| | wasm_exporttype_name | | | +| | wasm_exporttype_type | | | +| | wasm_exporttype_copy | | | +| | _vector methods_ | | | +| val | wasm_val_delete | val | | +| | wasm_val_copy | | | +| | _vector methods_ | | | +| frame | wasm_frame_delete | frame | | +| | wasm_frame_instance | | | +| | wasm_frame_func_index | | | +| | wasm_frame_func_offset | | | +| | wasm_frame_module_offset | | | +| | wasm_frame_copy | | | +| | _vector methods_ | | | +| trap | wasm_trap_new | trap | | +| | wasm_trap_delete | | | +| | wasm_trap_message | | | +| | wasm_trap_origin | | | +| | wasm_trap_trace | | | +| | _vector methods_ | | | +| foreign | wasm_foreign_new | foreign | | +| | wasm_foreign_delete | | | +| | _vector methods_ | | | +| engine | wasm_engine_new | engine | | +| | wasm_engine_new_with_args\* | | | +| | wasm_engine_new_with_config | | | +| | wasm_engine_delete | | | +| store | wasm_store_new | store | | +| | wasm_store_delete | | | +| | _vector methods_ | | | +| module | wasm_module_new | module | | +| | wasm_module_delete | | | +| | wasm_module_validate | | | +| | wasm_module_imports | | | +| | wasm_module_exports | | | +| instance | wasm_instance_new | instance | | +| | wasm_instance_delete | | | +| | wasm_instance_new_with_args\* | | | +| | wasm_instance_new_with_args_ex\* | | | +| | wasm_instance_exports | | | +| | _vector methods_ | | | +| func | wasm_func_new | func | | +| | wasm_func_new_with_env | | | +| | wasm_func_delete | | | +| | wasm_func_type | | | +| | wasm_func_call | | | +| | wasm_func_param_arity | | | +| | wasm_func_result_arity | | | +| | _vector methods_ | | | +| global | wasm_global_new | global | | +| | wasm_global_delete | | | +| | wasm_global_type | | | +| | wasm_global_get | | | +| | wasm_global_set | | | +| | _vector methods_ | | | +| table | wasm_table_new | table | | +| | wasm_table_delete | | | +| | wasm_table_type | | | +| | wasm_table_get | | | +| | wasm_table_set | | | +| | wasm_table_size | | | +| | _vector methods_ | | | +| memory | wasm_memory_new | memory | | +| | wasm_memory_delete | | | +| | wasm_memory_type | | | +| | wasm_memory_data | | | +| | wasm_memory_data_size | | | +| | wasm_memory_size | | | +| | _vector methods_ | | | +| extern | wasm_extern_delete | extern | | +| | wasm_extern_as_XXX | | | +| | wasm_XXX_as_extern | | | +| | wasm_extern_kind | | | +| | wasm_extern_type | | | +| | _vector methods_ | | | not supported _functions_ diff --git a/language-bindings/rust/README.md b/language-bindings/rust/README.md new file mode 100644 index 000000000..06bdbd2fc --- /dev/null +++ b/language-bindings/rust/README.md @@ -0,0 +1 @@ +We use a separate repository to host the WAMR Rust SDK. Please refer to [WAMR Rust SDK](https://github.com/bytecodealliance/wamr-rust-sdk) for more details. diff --git a/product-mini/README.md b/product-mini/README.md index 4a8275618..18813bef5 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: @@ -313,7 +312,7 @@ WAMR provides some features which can be easily configured by passing options to ## Android -able to generate a shared library support Android platform. +Able to generate a shared library support Android platform. - need an [android SDK](https://developer.android.com/studio). Go and get the "Command line tools only" - look for a command named *sdkmanager* and download below components. version numbers might need to check and pick others - "build-tools;29.0.3" @@ -327,7 +326,7 @@ able to generate a shared library support Android platform. - export ANDROID_NDK_LATEST_HOME=/the/path/of/downloaded/sdk/ndk/2x.xxx/ - ready to go -Use such commands, you are able to compile with default configurations. Any compiling requirement should be satisfied by modifying product-mini/platforms/android/CMakeList.txt. For example, chaning ${WAMR_BUILD_TARGET} in CMakeList could get different libraries support different ABIs. +Use such commands, you are able to compile with default configurations. ``` shell $ cd product-mini/platforms/android/ @@ -340,6 +339,15 @@ $ # include/ includes all necesary head files $ # lib includes libiwasm.so ``` +To change the target architecture and ABI, you can define `WAMR_BUILD_TARGET` or `ANDROID_ABI` respectively. To build for [supported Android ABIs](https://developer.android.com/ndk/guides/abis#sa): + +```shell +$ cmake .. -DWAMR_BUILD_TARGET=X86_32 -DANDROID_ABI=x86 # 32-bit Intel CPU +$ cmake .. -DWAMR_BUILD_TARGET=X86_64 -DANDROID_ABI=x86_64 # 64-bit Intel CPU +$ cmake .. -DWAMR_BUILD_TARGET=ARMV7A -DANDROID_ABI=armeabi-v7a # 32-bit ARM CPU +$ cmake .. -DWAMR_BUILD_TARGET=AARCH64 -DANDROID_ABI=arm64-v8a # 64-bit ARM CPU +``` + ## NuttX WAMR is intergrated with NuttX, just enable the WAMR in Kconfig option (Application Configuration/Interpreters). diff --git a/product-mini/platforms/android/CMakeLists.txt b/product-mini/platforms/android/CMakeLists.txt index 638b6ab0d..db60e8649 100644 --- a/product-mini/platforms/android/CMakeLists.txt +++ b/product-mini/platforms/android/CMakeLists.txt @@ -1,53 +1,59 @@ # Copyright (C) 2019 Intel Corporation. All rights reserved. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -cmake_minimum_required (VERSION 3.4.1) - -set (CMAKE_VERBOSE_MAKEFILE on) -set (CMAKE_BUILD_TYPE Release) - -# https://github.com/actions/virtual-environments/blob/main/images/linux/Ubuntu2004-Readme.md#environment-variables-3 -set (CMAKE_TOOLCHAIN_FILE "$ENV{ANDROID_NDK_LATEST_HOME}/build/cmake/android.toolchain.cmake") -set (ANDROID_SDK $ENV{ANDROID_HOME}) -set (ANDROID_NDK $ENV{ANDROID_NDK_LATEST_HOME}) - -set (ANDROID_ABI "x86") -set (ANDROID_LD lld) -if (NOT DEFINED ANDROID_PLATFORM) - set (ANDROID_PLATFORM 24) -endif () - -project (iwasm) - -set (WAMR_BUILD_PLATFORM "android") -set (WAMR_BUILD_TARGET "X86_32") -set (WAMR_BUILD_TYPE Release) -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) +cmake_minimum_required (VERSION 3.14) # Reset default linker flags set (CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "") set (CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS "") -# Set WAMR_BUILD_TARGET, currently values supported: -# "X86_64", "AMD_64", "X86_32", "AARCH64[sub]", "ARM[sub]", "THUMB[sub]", "MIPS", "XTENSA" 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") - elseif (CMAKE_SIZEOF_VOID_P EQUAL 4) - # Build as X86_32 by default in 32-bit platform - set (WAMR_BUILD_TARGET "X86_32") + message (FATAL_ERROR "WAMR_BUILD_TARGET isn't set") +endif () + +if (NOT (WAMR_BUILD_TARGET STREQUAL "X86_64" + OR WAMR_BUILD_TARGET STREQUAL "X86_32" + OR WAMR_BUILD_TARGET MATCHES "AARCH64.*" + OR WAMR_BUILD_TARGET MATCHES "ARM.*" + OR WAMR_BUILD_TARGET MATCHES "RISCV64.*")) + message (FATAL_ERROR "Unsupported build target platform ${WAMR_BUILD_TARGET}!") +endif () + +if (NOT DEFINED ANDROID_ABI) + if (WAMR_BUILD_TARGET STREQUAL "X86_64") + set (ANDROID_ABI "x86_64") + elseif (WAMR_BUILD_TARGET STREQUAL "X86_32") + set (ANDROID_ABI "x86") + elseif (WAMR_BUILD_TARGET MATCHES "AARCH64.*") + set (ANDROID_ABI "arm64-v8a") + elseif (WAMR_BUILD_TARGET MATCHES "ARM.*") + set (ANDROID_ABI "armeabi-v7a") else () - message(SEND_ERROR "Unsupported build target platform!") + set (ANDROID_ABI "riscv64") endif () endif () +if (NOT DEFINED ANDROID_LD) + set (ANDROID_LD lld) +endif () + +if (NOT DEFINED ANDROID_PLATFORM) + set (ANDROID_PLATFORM 24) +endif () + +# https://android.googlesource.com/platform/ndk/+/master/build/cmake/android.toolchain.cmake +set (CMAKE_TOOLCHAIN_FILE "$ENV{ANDROID_NDK_LATEST_HOME}/build/cmake/android.toolchain.cmake") +set (ANDROID_SDK $ENV{ANDROID_HOME}) +set (ANDROID_NDK $ENV{ANDROID_NDK_LATEST_HOME}) + +project (iwasm) + +set (WAMR_BUILD_PLATFORM "android") + +set (CMAKE_VERBOSE_MAKEFILE ON) + if (NOT CMAKE_BUILD_TYPE) - set(CMAKE_BUILD_TYPE Release) + set (CMAKE_BUILD_TYPE Release) endif () if (NOT DEFINED WAMR_BUILD_INTERP) @@ -55,6 +61,11 @@ if (NOT DEFINED WAMR_BUILD_INTERP) set (WAMR_BUILD_INTERP 1) endif () +if (NOT DEFINED WAMR_BUILD_FAST_INTERP) + # Enable fast interpreter + set (WAMR_BUILD_FAST_INTERP 1) +endif () + if (NOT DEFINED WAMR_BUILD_AOT) # Enable AOT by default. set (WAMR_BUILD_AOT 1) @@ -75,6 +86,21 @@ if (NOT DEFINED WAMR_BUILD_LIBC_WASI) set (WAMR_BUILD_LIBC_WASI 1) endif () +if (NOT DEFINED WAMR_BUILD_MULTI_MODULE) + # Disable multiple modules by default + set (WAMR_BUILD_MULTI_MODULE 0) +endif () + +if (NOT DEFINED WAMR_BUILD_LIB_PTHREAD) + # Disable pthread library by default + set (WAMR_BUILD_LIB_PTHREAD 0) +endif () + +if (NOT DEFINED WAMR_BUILD_LIB_WASI_THREADS) + # Disable wasi threads library by default + set (WAMR_BUILD_LIB_WASI_THREADS 0) +endif() + set (WAMR_ROOT_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../..) include (${WAMR_ROOT_DIR}/build-scripts/runtime_lib.cmake) diff --git a/product-mini/platforms/esp-idf/CMakeLists.txt b/product-mini/platforms/esp-idf/CMakeLists.txt index d8a3d2f96..8472df8dd 100644 --- a/product-mini/platforms/esp-idf/CMakeLists.txt +++ b/product-mini/platforms/esp-idf/CMakeLists.txt @@ -6,7 +6,4 @@ cmake_minimum_required(VERSION 3.5) include($ENV{IDF_PATH}/tools/cmake/project.cmake) -set (COMPONENTS ${IDF_TARGET} main freertos esptool_py wamr) -list(APPEND EXTRA_COMPONENT_DIRS "$ENV{WAMR_PATH}/build-scripts/esp-idf") - project(wamr-simple) \ No newline at end of file diff --git a/product-mini/platforms/esp-idf/build_and_run.sh b/product-mini/platforms/esp-idf/build_and_run.sh index f764a3013..7ce1b57a5 100755 --- a/product-mini/platforms/esp-idf/build_and_run.sh +++ b/product-mini/platforms/esp-idf/build_and_run.sh @@ -6,6 +6,7 @@ ESP32_TARGET="esp32" ESP32C3_TARGET="esp32c3" ESP32S3_TARGET="esp32s3" +ESP32C6_TARGET="esp32c6" usage () { @@ -15,6 +16,7 @@ usage () echo " $0 $ESP32_TARGET" echo " $0 $ESP32C3_TARGET" echo " $0 $ESP32S3_TARGET" + echo " $0 $ESP32C6_TARGET" exit 1 } diff --git a/product-mini/platforms/esp-idf/main/CMakeLists.txt b/product-mini/platforms/esp-idf/main/CMakeLists.txt index 55e725670..1bb61bad9 100644 --- a/product-mini/platforms/esp-idf/main/CMakeLists.txt +++ b/product-mini/platforms/esp-idf/main/CMakeLists.txt @@ -2,5 +2,4 @@ # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception idf_component_register(SRCS "main.c" - INCLUDE_DIRS "." - REQUIRES wamr) + INCLUDE_DIRS ".") diff --git a/product-mini/platforms/esp-idf/main/idf_component.yml b/product-mini/platforms/esp-idf/main/idf_component.yml new file mode 100644 index 000000000..1c05f476e --- /dev/null +++ b/product-mini/platforms/esp-idf/main/idf_component.yml @@ -0,0 +1,7 @@ +## IDF Component Manager Manifest File +dependencies: + wasm-micro-runtime: + version: "^2" + override_path: "../../../.." + idf: + version: ">=4.4" \ No newline at end of file diff --git a/product-mini/platforms/esp-idf/main/main.c b/product-mini/platforms/esp-idf/main/main.c index fbfb04c21..1a34096d7 100644 --- a/product-mini/platforms/esp-idf/main/main.c +++ b/product-mini/platforms/esp-idf/main/main.c @@ -12,11 +12,7 @@ #include "esp_log.h" -#ifdef CONFIG_IDF_TARGET_ESP32S3 #define IWASM_MAIN_STACK_SIZE 5120 -#else -#define IWASM_MAIN_STACK_SIZE 4096 -#endif #define LOG_TAG "wamr" diff --git a/product-mini/platforms/nuttx/CMakeLists.txt b/product-mini/platforms/nuttx/CMakeLists.txt new file mode 100644 index 000000000..f83e79916 --- /dev/null +++ b/product-mini/platforms/nuttx/CMakeLists.txt @@ -0,0 +1,199 @@ +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +# select platform configuration setting WAMR_BUILD_TARGET +set(WAMR_BUILD_PLATFORM nuttx) + +if(CONFIG_ARCH_ARMV6M) + set(WAMR_BUILD_TARGET THUMBV6M) +elseif(CONFIG_ARCH_ARMV7A) + set(WAMR_BUILD_TARGET THUMBV7) +elseif(CONFIG_ARCH_ARMV7M) + set(WAMR_BUILD_TARGET THUMBV7EM) +elseif(CONFIG_ARCH_ARMV8M) + set(WAMR_BUILD_TARGET THUMBV8M) +elseif(CONFIG_ARCH_X86) + set(WAMR_BUILD_TARGET X86_32) +elseif(CONFIG_ARCH_X86_64) + set(WAMR_BUILD_TARGET X86_64) +elseif(CONFIG_ARCH_XTENSA) + set(WAMR_BUILD_TARGET XTENSA) +elseif(CONFIG_ARCH_RV64GC OR CONFIG_ARCH_RV64) + set(WAMR_BUILD_TARGET RISCV64) +elseif(CONFIG_ARCH_RV32IM OR CONFIG_ARCH_RV32) + set(WAMR_BUILD_TARGET RISCV32) +elseif(CONFIG_ARCH_SIM) + if(CONFIG_SIM_M32 OR CONFIG_HOST_X86) + set(WAMR_BUILD_TARGET X86_32) + elseif(CONFIG_HOST_ARM) + set(WAMR_BUILD_TARGET ARM) + elseif(CONFIG_HOST_ARM64) + set(WAMR_BUILD_TARGET AARCH64) + else() + set(WAMR_BUILD_TARGET X86_64) + endif() + if(CONFIG_HOST_MACOS) + add_definitions(-DBH_PLATFORM_DARWIN) + endif() +endif() + +if(CONFIG_INTERPRETERS_WAMR_LOG) + add_definitions(-DWASM_ENABLE_LOG=1) +else() + add_definitions(-DWASM_ENABLE_LOG=0) +endif() + +if(CONFIG_INTERPRETERS_WAMR_AOT_WORD_ALIGN_READ) + add_definitions(-DWASM_ENABLE_WORD_ALIGN_READ=1) +else() + add_definitions(-DWASM_ENABLE_WORD_ALIGN_READ=0) +endif() + +if(CONFIG_INTERPRETERS_WAMR_STACK_GUARD_SIZE) + add_definitions(-DWASM_STACK_GUARD_SIZE=0) +else() + add_definitions( + -DWASM_STACK_GUARD_SIZE=${CONFIG_INTERPRETERS_WAMR_STACK_GUARD_SIZE}) +endif() + +if(CONFIG_INTERPRETERS_WAMR_MEMORY_TRACING) + add_definitions(-DWASM_ENABLE_MEMORY_TRACING=1) +else() + add_definitions(-DWASM_ENABLE_MEMORY_TRACING=0) +endif() + +if(CONFIG_INTERPRETERS_WAMR_SHARED_MEMORY) + set(WAMR_BUILD_SHARED_MEMORY 1) +endif() + +if(CONFIG_INTERPRETERS_WAMR_BULK_MEMORY) + set(WAMR_BUILD_BULK_MEMORY 1) +endif() + +if(CONFIG_INTERPRETERS_WAMR_AOT_STACK_FRAME) + set(WAMR_BUILD_AOT_STACK_FRAME 1) +endif() + +if(CONFIG_INTERPRETERS_WAMR_PERF_PROFILING) + set(WAMR_BUILD_PERF_PROFILING 1) +endif() + +if(CONFIG_INTERPRETERS_WAMR_GC) + set(WAMR_BUILD_GC 1) + set(WAMR_BUILD_STRINGREF 1) + set(WAMR_BUILD_REF_TYPES 1) +endif() + +if(CONFIG_INTERPRETERS_WAMR_GC_MANUALLY) + add_definitions(-DWASM_GC_MANUALLY=1) +else() + add_definitions(-DWASM_GC_MANUALLY=0) +endif() + +if(CONFIG_INTERPRETERS_WAMR_GC_PERF_PROFILING) + set(WAMR_BUILD_GC_PERF_PROFILING 1) +endif() + +if(CONFIG_INTERPRETERS_WAMR_ENABLE_EXCE_HANDLING) + set(WAMR_BUILD_EXCE_HANDLING 1) +endif() + +if(CONFIG_INTERPRETERS_WAMR_TAIL_CALL) + set(WAMR_BUILD_TAIL_CALL 1) +endif() + +if(CONFIG_INTERPRETERS_WAMR_MEMORY_PROFILING) + set(WAMR_BUILD_MEMORY_PROFILING 1) +endif() + +if(CONFIG_INTERPRETERS_WAMR_MULTI_MODULE) + set(WAMR_BUILD_MULTI_MODULE 1) +endif() + +if(CONFIG_INTERPRETERS_WAMR_LIB_PTHREAD_SEMAPHORE) + set(WAMR_BUILD_LIB_PTHREAD_SEMAPHORE 1) +endif() + +if(CONFIG_INTERPRETERS_WAMR_DISABLE_HW_BOUND_CHECK) + set(WAMR_DISABLE_HW_BOUND_CHECK 1) +endif() + +if(CONFIG_INTERPRETERS_WAMR_CUSTOM_NAME_SECTIONS) + set(WAMR_BUILD_CUSTOM_NAME_SECTION 1) +endif() + +if(CONFIG_INTERPRETERS_WAMR_GLOBAL_HEAP_POOL) + set(WAMR_BUILD_GLOBAL_HEAP_POOL 1) + math(EXPR _HEAP_SIZE_ + "${CONFIG_INTERPRETERS_WAMR_GLOBAL_HEAP_POOL_SIZE} * 1024") + set(WAMR_BUILD_GLOBAL_HEAP_SIZE ${_HEAP_SIZE_}) +endif() + +if(CONFIG_INTERPRETERS_WAMR_ENABLE_SPEC_TEST) + set(WAMR_BUILD_SPEC_TEST 1) +endif() + +if(CONFIG_INTERPRETERS_WAMR_REF_TYPES) + set(WAMR_BUILD_REF_TYPES 1) +endif() + +if(CONFIG_INTERPRETERS_WAMR_CLASSIC) + # include iwasm_interp.cmake + set(WAMR_BUILD_INTERP 1) +endif() + +if(CONFIG_INTERPRETERS_WAMR_FAST) + # enable iwasm_interp.cmake + set(WAMR_BUILD_FAST_INTERP 1) +endif() + +if((CONFIG_INTERPRETERS_WAMR_FAST OR CONFIG_INTERPRETERS_WAMR_CLASSIC) + AND CONFIG_INTERPRETERS_WAMR_MINILOADER) + # enable iwasm_interp.cmake + set(WAMR_BUILD_MINI_LOADER 1) +else() + set(WAMR_BUILD_MINI_LOADER 0) +endif() + +if(CONFIG_INTERPRETERS_WAMR_AOT) + # include iwasm_aot.cmake + set(WAMR_BUILD_AOT 1) +endif() + +if(CONFIG_INTERPRETERS_WAMR_DEBUG_INTERP) + # include debug_engine.cmake + set(WAMR_BUILD_DEBUG_INTERP 1) +endif() + +if(CONFIG_INTERPRETERS_WAMR_LIBC_BUILTIN) + # include libc_builtin.cmake + set(WAMR_BUILD_LIBC_BUILTIN 1) +endif() + +if(CONFIG_INTERPRETERS_WAMR_LIBC_WASI) + # include libc_wasi.cmake + set(WAMR_BUILD_LIBC_WASI 1) +endif() + +if(CONFIG_INTERPRETERS_WAMR_THREAD_MGR) + # include thread_mgr.cmake + set(WAMR_BUILD_THREAD_MGR 1) +endif() + +if(CONFIG_INTERPRETERS_WAMR_LIB_PTHREAD) + # include lib_pthread.cmake + set(WAMR_BUILD_LIB_PTHREAD 1) +endif() + +set(WAMR_ROOT_DIR ${CMAKE_CURRENT_LIST_DIR}/../../..) + +# enable WAMR build system +include(${WAMR_ROOT_DIR}/build-scripts/runtime_lib.cmake) + +# NuttX wamr lib complie required: `WAMR_SOURCES` `WAMR_CFLAGS` `WAMR_INCDIRS` +# `WAMR_DEFINITIONS` +set(WAMR_SOURCES ${WAMR_RUNTIME_LIB_SOURCE}) +set(WAMR_CFLAGS -Wno-strict-prototypes -Wno-shadow -Wno-unused-variable + -Wno-int-conversion -Wno-implicit-function-declaration) +get_directory_property(WAMR_INCDIRS INCLUDE_DIRECTORIES) +get_directory_property(WAMR_DEFINITIONS COMPILE_DEFINITIONS) diff --git a/product-mini/platforms/nuttx/wamr.mk b/product-mini/platforms/nuttx/wamr.mk index e329601a2..e414a7cda 100644 --- a/product-mini/platforms/nuttx/wamr.mk +++ b/product-mini/platforms/nuttx/wamr.mk @@ -437,7 +437,6 @@ CSRCS += nuttx_platform.c \ bh_hashmap.c \ bh_list.c \ bh_log.c \ - bh_memutils.c \ bh_queue.c \ bh_vector.c \ bh_read_file.c \ diff --git a/product-mini/platforms/posix/main.c b/product-mini/platforms/posix/main.c index 37ee0cb87..2acd2190a 100644 --- a/product-mini/platforms/posix/main.c +++ b/product-mini/platforms/posix/main.c @@ -675,7 +675,7 @@ main(int argc, char *argv[]) #endif #if WASM_ENABLE_GC != 0 else if (!strncmp(argv[0], "--gc-heap-size=", 15)) { - if (argv[0][21] == '\0') + if (argv[0][15] == '\0') return print_help(); gc_heap_size = atoi(argv[0] + 15); } @@ -851,7 +851,8 @@ main(int argc, char *argv[]) #if WASM_ENABLE_DEBUG_INTERP != 0 init_args.instance_port = instance_port; if (ip_addr) - strcpy(init_args.ip_addr, ip_addr); + /* ensure that init_args.ip_addr is null terminated */ + strncpy(init_args.ip_addr, ip_addr, sizeof(init_args.ip_addr) - 1); #endif /* initialize runtime environment */ diff --git a/product-mini/platforms/windows/main.c b/product-mini/platforms/windows/main.c index 6461e9172..35a489721 100644 --- a/product-mini/platforms/windows/main.c +++ b/product-mini/platforms/windows/main.c @@ -464,7 +464,9 @@ main(int argc, char *argv[]) #if WASM_ENABLE_DEBUG_INTERP != 0 init_args.instance_port = instance_port; if (ip_addr) - strcpy(init_args.ip_addr, ip_addr); + /* ensure that init_args.ip_addr is null terminated */ + strncpy_s(init_args.ip_addr, sizeof(init_args.ip_addr) - 1, ip_addr, + strlen(ip_addr)); #endif /* initialize runtime environment */ diff --git a/product-mini/platforms/windows/wasi_filtered_tests.json b/product-mini/platforms/windows/wasi_filtered_tests.json index 492a746eb..63910435c 100644 --- a/product-mini/platforms/windows/wasi_filtered_tests.json +++ b/product-mini/platforms/windows/wasi_filtered_tests.json @@ -1,34 +1,6 @@ { - "WASI C tests": { - "fdopendir-with-access": "Not implemented", - "lseek": "Not implemented" - }, "WASI Rust tests": { - "dangling_symlink": "Not implemented", - "directory_seek": "Not implemented", - "dir_fd_op_failures": "Not implemented", - "fd_advise": "Not implemented", - "fd_fdstat_set_rights": "Not implemented", - "fd_filestat_set": "Not implemented", - "fd_flags_set": "Not implemented", - "fd_readdir": "Not implemented", - "file_allocate": "Not implemented", - "file_seek_tell": "Not implemented", - "file_truncation": "Not implemented", - "nofollow_errors": "Not implemented", - "path_exists": "Not implemented", - "path_filestat": "Not implemented", - "path_link": "Not implemented", - "path_open_preopen": "Not implemented", - "path_rename": "Not implemented", - "path_rename_dir_trailing_slashes": "Not implemented", - "path_symlink_trailing_slashes": "Not implemented", - "poll_oneoff_stdio": "Not implemented", - "readlink": "Not implemented (path_symlink)", - "symlink_create": "Not implemented", - "symlink_filestat": "Not implemented", - "symlink_loop": "Not implemented", - "truncation_rights": "Not implemented" + "poll_oneoff_stdio": "Not implemented" }, "WASI threads proposal": { "wasi_threads_exit_main_wasi_read": "Blocking ops not implemented", diff --git a/product-mini/platforms/zephyr/simple/src/main.c b/product-mini/platforms/zephyr/simple/src/main.c index 5d209a868..3b389826f 100644 --- a/product-mini/platforms/zephyr/simple/src/main.c +++ b/product-mini/platforms/zephyr/simple/src/main.c @@ -65,14 +65,12 @@ app_instance_main(wasm_module_inst_t module_inst) wasm_exec_env_t exec_env; unsigned argv[2] = { 0 }; - if (wasm_runtime_lookup_function(module_inst, "main", NULL) - || wasm_runtime_lookup_function(module_inst, "__main_argc_argv", - NULL)) { + if (wasm_runtime_lookup_function(module_inst, "main") + || wasm_runtime_lookup_function(module_inst, "__main_argc_argv")) { LOG_VERBOSE("Calling main function\n"); wasm_application_execute_main(module_inst, app_argc, app_argv); } - else if ((func = wasm_runtime_lookup_function(module_inst, "app_main", - NULL))) { + else if ((func = wasm_runtime_lookup_function(module_inst, "app_main"))) { exec_env = wasm_runtime_create_exec_env(module_inst, CONFIG_APP_HEAP_SIZE); if (!exec_env) { @@ -129,8 +127,12 @@ iwasm_main(void *arg1, void *arg2, void *arg3) 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); +#elif (defined(CONFIG_COMMON_LIBC_MALLOC) \ + && CONFIG_COMMON_LIBC_MALLOC_ARENA_SIZE != 0) \ + || defined(CONFIG_NEWLIB_LIBC) + init_args.mem_alloc_type = Alloc_With_System_Allocator; #else -#error Another memory allocation scheme than global heap pool is not implemented yet for Zephyr. +#error "memory allocation scheme is not defined." #endif /* initialize runtime environment */ diff --git a/samples/README.md b/samples/README.md index 21a735268..872e1798f 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. @@ -15,3 +12,4 @@ - **[native-lib](./native-lib/README.md)**: Demonstrating how to write required interfaces in native library, build it into a shared library and register the shared library to iwasm. - **[sgx-ra](./sgx-ra/README.md)**: Demonstrating how to execute Remote Attestation on SGX with [librats](https://github.com/inclavare-containers/librats), which enables mutual attestation with other runtimes or other entities that support librats to ensure that each is running within the TEE. - **[workload](./workload/README.md)**: Demonstrating how to build and run some complex workloads, e.g. tensorflow-lite, XNNPACK, wasm-av1, meshoptimizer and bwa. +- **[debug-tools](./debug-tools/README.md)**: Demonstrating how to symbolicate a stack trace. diff --git a/samples/basic/src/main.c b/samples/basic/src/main.c index ca580af33..406b2427c 100644 --- a/samples/basic/src/main.c +++ b/samples/basic/src/main.c @@ -61,7 +61,7 @@ main(int argc, char *argv_main[]) wasm_function_inst_t func = NULL; wasm_function_inst_t func2 = NULL; char *native_buffer = NULL; - uint32_t wasm_buffer = 0; + uint64_t wasm_buffer = 0; RuntimeInitArgs init_args; memset(&init_args, 0, sizeof(RuntimeInitArgs)); @@ -149,8 +149,7 @@ main(int argc, char *argv_main[]) goto fail; } - if (!(func = wasm_runtime_lookup_function(module_inst, "generate_float", - NULL))) { + if (!(func = wasm_runtime_lookup_function(module_inst, "generate_float"))) { printf("The generate_float wasm function is not found.\n"); goto fail; } @@ -176,7 +175,7 @@ main(int argc, char *argv_main[]) ret_val); // Next we will pass a buffer to the WASM function - uint32 argv2[4]; + uint32 argv2[5]; // must allocate buffer from wasm instance memory space (never use pointer // from host runtime) @@ -185,12 +184,12 @@ main(int argc, char *argv_main[]) memcpy(argv2, &ret_val, sizeof(float)); // the first argument argv2[1] = wasm_buffer; // the second argument is the wasm buffer address - argv2[2] = 100; // the third argument is the wasm buffer size - argv2[3] = 3; // the last argument is the digits after decimal point for + argv2[3] = 100; // the third argument is the wasm buffer size + argv2[4] = 3; // the last argument is the digits after decimal point for // converting float to string - if (!(func2 = wasm_runtime_lookup_function(module_inst, "float_to_string", - NULL))) { + if (!(func2 = + wasm_runtime_lookup_function(module_inst, "float_to_string"))) { printf( "The wasm function float_to_string wasm function is not found.\n"); goto fail; @@ -208,7 +207,7 @@ main(int argc, char *argv_main[]) } wasm_function_inst_t func3 = - wasm_runtime_lookup_function(module_inst, "calculate", NULL); + wasm_runtime_lookup_function(module_inst, "calculate"); if (!func3) { printf("The wasm function calculate is not found.\n"); goto fail; @@ -231,7 +230,7 @@ fail: wasm_runtime_destroy_exec_env(exec_env); if (module_inst) { if (wasm_buffer) - wasm_runtime_module_free(module_inst, wasm_buffer); + wasm_runtime_module_free(module_inst, (uint64)wasm_buffer); wasm_runtime_deinstantiate(module_inst); } if (module) diff --git a/samples/debug-tools/CMakeLists.txt b/samples/debug-tools/CMakeLists.txt new file mode 100644 index 000000000..ce06029a5 --- /dev/null +++ b/samples/debug-tools/CMakeLists.txt @@ -0,0 +1,107 @@ +# Copyright (C) 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required(VERSION 3.14) + +include(CheckPIESupported) + +project(debug_tools_sample) + +list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake) +find_package(WASISDK REQUIRED) + +option(SOURCE_MAP_DEMO "Enable source map demo" OFF) +if (SOURCE_MAP_DEMO) + find_package(EMSCRIPTEN 3.1.50 REQUIRED) +endif () + +################ runtime settings ################ +string (TOLOWER ${CMAKE_HOST_SYSTEM_NAME} WAMR_BUILD_PLATFORM) +if (APPLE) + add_definitions(-DBH_PLATFORM_DARWIN) +endif () + +# Resetdefault linker flags +set(CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "") +set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS "") + +# WAMR features switch + +# Set WAMR_BUILD_TARGET, currently values supported: +# "X86_64", "AMD_64", "X86_32", "AARCH64[sub]", "ARM[sub]", "THUMB[sub]", +# "MIPS", "XTENSA", "RISCV64[sub]", "RISCV32[sub]" +if (NOT DEFINED WAMR_BUILD_TARGET) + if (CMAKE_SYSTEM_PROCESSOR MATCHES "^(arm64|aarch64)") + set (WAMR_BUILD_TARGET "AARCH64") + elseif (CMAKE_SYSTEM_PROCESSOR STREQUAL "riscv64") + set (WAMR_BUILD_TARGET "RISCV64") + elseif (CMAKE_SIZEOF_VOID_P EQUAL 8) + # Build as X86_64 by default in 64-bit platform + set (WAMR_BUILD_TARGET "X86_64") + elseif (CMAKE_SIZEOF_VOID_P EQUAL 4) + # Build as X86_32 by default in 32-bit platform + set (WAMR_BUILD_TARGET "X86_32") + else () + message(SEND_ERROR "Unsupported build target platform!") + endif () +endif () + +if (NOT CMAKE_BUILD_TYPE) + set (CMAKE_BUILD_TYPE Release) +endif () + +set(WAMR_BUILD_INTERP 1) +set(WAMR_BUILD_LIBC_WASI 1) +set(WAMR_BUILD_FAST_INTERP 0) # Otherwise addresses don't match llvm-dwarfdump (addr2line) +set(WAMR_BUILD_AOT 1) +set(WAMR_BUILD_DUMP_CALL_STACK 1) # Otherwise stack trace is not printed (addr2line) + +# compiling and linking flags +if (NOT (CMAKE_C_COMPILER MATCHES ".*clang.*" OR CMAKE_C_COMPILER_ID MATCHES ".*Clang")) + set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--gc-sections") +endif () +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wextra -Wformat -Wformat-security") + +# build out vmlib +set(WAMR_ROOT_DIR ${CMAKE_CURRENT_LIST_DIR}/../..) +include (${WAMR_ROOT_DIR}/build-scripts/runtime_lib.cmake) + +add_library(vmlib ${WAMR_RUNTIME_LIB_SOURCE}) + +################ wasm application ################ +include(ExternalProject) + +# wasm32-wasi +ExternalProject_Add(wasm33-wasi + SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/wasm-apps" + CONFIGURE_COMMAND ${CMAKE_COMMAND} -S ${CMAKE_CURRENT_SOURCE_DIR}/wasm-apps -B build + -DWASI_SDK_PREFIX=${WASISDK_HOME} + -DCMAKE_TOOLCHAIN_FILE=${WASISDK_TOOLCHAIN} + BUILD_COMMAND ${CMAKE_COMMAND} --build build + INSTALL_COMMAND ${CMAKE_COMMAND} --install build --prefix ${CMAKE_CURRENT_BINARY_DIR} +) + +if (EMSCRIPTEN_FOUND) + # wasm32-emscripten + ExternalProject_Add(wasm32-emscripten + SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/wasm-apps" + CONFIGURE_COMMAND ${CMAKE_COMMAND} -S ${CMAKE_CURRENT_SOURCE_DIR}/wasm-apps -B build + -DCMAKE_TOOLCHAIN_FILE=${EMSCRIPTEN_TOOLCHAIN} + -DCMAKE_VERBOSE_MAKEFILE=On + -DSOURCE_MAP_DEMO=On + BUILD_COMMAND ${CMAKE_COMMAND} --build build + INSTALL_COMMAND ${CMAKE_COMMAND} --install build --prefix ${CMAKE_CURRENT_BINARY_DIR}/emscripten + ) +endif () + +################ wamr runtime ################ +include (${SHARED_DIR}/utils/uncommon/shared_uncommon.cmake) + +set (RUNTIME_SOURCE_ALL + ${CMAKE_CURRENT_LIST_DIR}/../../product-mini/platforms/linux/main.c + ${UNCOMMON_SHARED_SOURCE} +) +add_executable (iwasm ${RUNTIME_SOURCE_ALL}) +check_pie_supported() +set_target_properties (iwasm PROPERTIES POSITION_INDEPENDENT_CODE ON) +target_link_libraries(iwasm vmlib -lm -ldl) diff --git a/samples/debug-tools/README.md b/samples/debug-tools/README.md new file mode 100644 index 000000000..b0358b9e4 --- /dev/null +++ b/samples/debug-tools/README.md @@ -0,0 +1,133 @@ +# "debug-tools" sample introduction + +Tool to symoblicate stack traces. When using wasm in production, debug info are usually stripped using tools like `wasm-opt`, to decrease the binary size. If a corresponding unstripped wasm file is kept, location information (function, file, line, column) can be retrieved from the stripped stack trace. + +## Build and run the sample + +### Generate the stack trace + +Build `iwasm` with `WAMR_BUILD_DUMP_CALL_STACK=1` and `WAMR_BUILD_FAST_INTERP=0` and the wasm file with debug info (e.g. `clang -g`). As it is done in [CMakeLists.txt](./CMakeLists.txt) and [wasm-apps/CMakeLists.txt](./wasm-apps/CMakeLists.txt) (look for `addr2line`): + +```bash +$ mkdir build && cd build +$ cmake .. +$ make +$ ./iwasm wasm-apps/trap.wasm +``` + +The output should be something like + +```text +#00: 0x0159 - $f5 +#01: 0x01b2 - $f6 +#02: 0x0200 - $f7 +#03: 0x026b - $f8 +#04: 0x236b - $f15 +#05: 0x011f - _start + +Exception: unreachable +``` + +Copy the stack trace printed to stdout into a separate file (`call_stack.txt`): + +```bash +$ ./iwasm wasm-apps/trap.wasm | grep "#" > call_stack.txt +``` + +Same for AOT. The AOT binary has to be generated using the `--enable-dump-call-stack` option of `wamrc`, as in [CMakeLists.txt](./wasm-apps/CMakeLists.txt). Then run: + +```bash +$ ./iwasm wasm-apps/trap.aot | grep "#" > call_stack.txt +``` + +### Symbolicate the stack trace + +Run the [addr2line](../../test-tools/addr2line/addr2line.py) script to symbolicate the stack trace: + +```bash +$ python3 ../../../test-tools/addr2line/addr2line.py \ + --wasi-sdk /opt/wasi-sdk \ + --wabt /opt/wabt \ + --wasm-file wasm-apps/trap.wasm \ + call_stack.txt +``` + +The output should be something like: + +```text +0: c + at wasm-micro-runtime/samples/debug-tools/wasm-apps/trap.c:5:1 +1: b + at wasm-micro-runtime/samples/debug-tools/wasm-apps/trap.c:11:12 +2: a + at wasm-micro-runtime/samples/debug-tools/wasm-apps/trap.c:17:12 +3: main + at wasm-micro-runtime/samples/debug-tools/wasm-apps/trap.c:24:5 +4: __main_void + at unknown:?:? +5: _start +``` + +If WAMR is run in fast interpreter mode (`WAMR_BUILD_FAST_INTERP=1`), addresses in the stack trace cannot be tracked back to location info. +If WAMR <= `1.3.2` is used, the stack trace does not contain addresses. +In those two cases, run the script with `--no-addr`: the line info returned refers to the start of the function + +```bash +$ python3 ../../../test-tools/addr2line/addr2line.py \ + --wasi-sdk /opt/wasi-sdk \ + --wabt /opt/wabt \ + --wasm-file wasm-apps/trap.wasm \ + call_stack.txt --no-addr +``` + +#### sourcemap + +This script also supports _sourcemap_ which is produced by [_emscripten_](https://emscripten.org/docs/tools_reference/emcc.html). The _sourcemap_ is used to map the wasm function to the original source file. To use it, add `-gsource-map` option to _emcc_ command line. The output should be a section named "sourceMappingURL" and a separated file named "_.map_. + +If the wasm file is with _sourcemap_, the script will use it to get the source file and line info. It needs an extra command line option `--emsdk` to specify the path of _emsdk_. The script will use _emsymbolizer_ to query the source file and line info. + +````bash +$ python3 ../../../test-tools/addr2line/addr2line.py \ + --wasi-sdk /opt/wasi-sdk \ + --wabt /opt/wabt \ + --wasm-file emscripten/wasm-apps/trap.wasm \ + --emsdk /opt/emsdk \ + call_stack.from_wasm_w_sourcemap.txt + +The output should be something like: + +```text +1: c + at ../../../../../wasm-apps/trap.c:5:1 +2: b + at ../../../../../wasm-apps/trap.c:11:12 +3: a + at ../../../../../wasm-apps/trap.c:17:12 +4: main + at ../../../../../wasm-apps/trap.c:24:5 +5: __main_void + at ../../../../../../../../../emsdk/emscripten/system/lib/standalone/__main_void.c:53:10 +6: _start + at ../../../../../../../../../emsdk/emscripten/system/lib/libc/crt1.c:27:3 +```` + +> The script assume the separated map file _.map_ is in the same directory as the wasm file. + +### Another approach + +If the wasm file is with "name" section, it is able to output function name in the stack trace. To achieve that, need to enable `WAMR_BUILD_LOAD_CUSTOM_SECTION` and `WAMR_BUILD_CUSTOM_NAME_SECTION`. If using .aot file, need to add `--emit-custom-sections=name` into wamrc command line options. + +Then the output should be something like + +```text +#00: 0x0159 - c +#01: 0x01b2 - b +#02: 0x0200 - a +#03: 0x026b - main +#04: 0x236b - __main_void +#05: 0x011f - _start + +Exception: unreachable +``` + +Also, it is able to use _addr2line.py_ to add file and line info to the stack trace. diff --git a/samples/debug-tools/cmake/FindEMSCRIPTEN.cmake b/samples/debug-tools/cmake/FindEMSCRIPTEN.cmake new file mode 100644 index 000000000..8f63ec545 --- /dev/null +++ b/samples/debug-tools/cmake/FindEMSCRIPTEN.cmake @@ -0,0 +1,45 @@ +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +include(FindPackageHandleStandardArgs) + +find_path(EMSCRIPTEN_HOME + NAMES upstream/emscripten + PATHS /opt/emsdk + NO_DEFAULT_PATH + NO_CMAKE_PATH + NO_CMAKE_SYSTEM_PATH + NO_CMAKE_FIND_ROOT_PATH + REQUIRED +) + +find_file(EMSCRIPTEN_VERSION_FILE + NAMES emscripten-version.txt + PATHS ${EMSCRIPTEN_HOME}/upstream/emscripten + NO_DEFAULT_PATH + NO_CMAKE_PATH + NO_CMAKE_SYSTEM_PATH + NO_CMAKE_FIND_ROOT_PATH + REQUIRED +) + +file(READ ${EMSCRIPTEN_VERSION_FILE} EMSCRIPTEN_VERSION_FILE_CONTENT) + +string(REGEX + MATCH + "[0-9]+\.[0-9]+(\.[0-9]+)*" + EMSCRIPTEN_VERSION + ${EMSCRIPTEN_VERSION_FILE_CONTENT} +) + +find_package_handle_standard_args(EMSCRIPTEN + REQUIRED_VARS EMSCRIPTEN_HOME + VERSION_VAR EMSCRIPTEN_VERSION + HANDLE_VERSION_RANGE +) + +if(EMSCRIPTEN_FOUND) + set(EMSCRIPTEN_TOOLCHAIN ${EMSCRIPTEN_HOME}/upstream/emscripten/cmake/Modules/Platform/Emscripten.cmake) + set(EMCC ${EMSCRIPTEN_HOME}/upstream/emscripten/emcc) +endif() +mark_as_advanced(EMSCRIPTEN_TOOLCHAIN EMCC) diff --git a/samples/debug-tools/cmake/FindWAMRC.cmake b/samples/debug-tools/cmake/FindWAMRC.cmake new file mode 100644 index 000000000..20f9416f7 --- /dev/null +++ b/samples/debug-tools/cmake/FindWAMRC.cmake @@ -0,0 +1,27 @@ +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +include(FindPackageHandleStandardArgs) + +find_path(WAMRC_HOME + wamr-compiler + PATHS ${CMAKE_CURRENT_SOURCE_DIR}/../../.. + NO_DEFAULT_PATH + NO_CMAKE_PATH + NO_CMAKE_SYSTEM_PATH + NO_CMAKE_FIND_ROOT_PATH + REQUIRED +) + +find_file(WAMRC_BIN + wamrc + HINTS ${WAMRC_HOME}/wamr-compiler/build + NO_DEFAULT_PATH + NO_CMAKE_PATH + NO_CMAKE_SYSTEM_PATH + NO_CMAKE_FIND_ROOT_PATH + REQUIRED +) + +find_package_handle_standard_args(WAMRC REQUIRED_VARS WAMRC_BIN) +mark_as_advanced(WAMRC_BIN) diff --git a/samples/debug-tools/cmake/FindWASISDK.cmake b/samples/debug-tools/cmake/FindWASISDK.cmake new file mode 100644 index 000000000..0caf374df --- /dev/null +++ b/samples/debug-tools/cmake/FindWASISDK.cmake @@ -0,0 +1,24 @@ +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +include(FindPackageHandleStandardArgs) + +file(GLOB WASISDK_SEARCH_PATH "/opt/wasi-sdk-*") +find_path(WASISDK_HOME + NAMES share/wasi-sysroot + PATHS ${WASISDK_SEARCH_PATH} + NO_DEFAULT_PATH + REQUIRED +) + +string(REGEX MATCH [0-9]+\.[0-9]+\.*[0-9]* WASISDK_VERSION ${WASISDK_HOME}) + +find_package_handle_standard_args(WASISDK REQUIRED_VARS WASISDK_HOME VERSION_VAR WASISDK_VERSION) + +if(WASISDK_FOUND) + set(WASISDK_CC_COMMAND ${WASISDK_HOME}/bin/clang) + set(WASISDK_CXX_COMMAND ${WASISDK_HOME}/bin/clang++) + set(WASISDK_TOOLCHAIN ${WASISDK_HOME}/share/cmake/wasi-sdk.cmake) + set(WASISDK_SYSROOT ${WASISDK_HOME}/share/wasi-sysroot) +endif() +mark_as_advanced(WASISDK_CC_COMMAND WASISDK_CXX_COMMAND WASISDK_TOOLCHAIN WASISDK_SYSROOT WASISDK_HOME) diff --git a/samples/debug-tools/symbolicate.sh b/samples/debug-tools/symbolicate.sh new file mode 100644 index 000000000..709622f03 --- /dev/null +++ b/samples/debug-tools/symbolicate.sh @@ -0,0 +1,23 @@ +#!/bin/bash +set -euox pipefail + +# Symbolicate .wasm +python3 ../../../test-tools/addr2line/addr2line.py \ + --wasi-sdk /opt/wasi-sdk \ + --wabt /opt/wabt \ + --wasm-file wasm-apps/trap.wasm \ + call_stack.txt + +# Symbolicate .wasm with `--no-addr` +python3 ../../../test-tools/addr2line/addr2line.py \ + --wasi-sdk /opt/wasi-sdk \ + --wabt /opt/wabt \ + --wasm-file wasm-apps/trap.wasm \ + call_stack.txt --no-addr + +# Symbolicate .aot +python3 ../../../test-tools/addr2line/addr2line.py \ + --wasi-sdk /opt/wasi-sdk \ + --wabt /opt/wabt \ + --wasm-file wasm-apps/trap.wasm \ + call_stack_aot.txt \ No newline at end of file diff --git a/samples/debug-tools/wasm-apps/CMakeLists.txt b/samples/debug-tools/wasm-apps/CMakeLists.txt new file mode 100644 index 000000000..527b5f37a --- /dev/null +++ b/samples/debug-tools/wasm-apps/CMakeLists.txt @@ -0,0 +1,58 @@ +# Copyright (C) 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required (VERSION 3.14) + +project (debut_tools_wasm) + +set (CMAKE_BUILD_TYPE Debug) # Otherwise no debug symbols (addr2line) + +list (APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/../cmake) +find_package (WAMRC REQUIRED) + +option(SOURCE_MAP_DEMO "Enable source map demo" OFF) +if (SOURCE_MAP_DEMO) + find_package(EMSCRIPTEN 3.1.50 REQUIRED) +endif () + +################ wasm and aot compilation ################ +function (compile_sample SOURCE_FILE) + get_filename_component (FILE_NAME ${SOURCE_FILE} NAME_WLE) + + ## wasm + set (WASM_FILE ${FILE_NAME}.wasm) + add_executable (${FILE_NAME} ${SOURCE_FILE}) + set_target_properties (${FILE_NAME} PROPERTIES SUFFIX .wasm) + + ## aot + set (AOT_FILE ${FILE_NAME}.aot) + add_custom_target ( + ${FILE_NAME}_aot + ALL + DEPENDS ${WAMRC_BIN} ${WASM_FILE} + # Use --enable-dump-call-stack to generate stack trace (addr2line) + COMMAND ${WAMRC_BIN} --size-level=0 --enable-dump-call-stack -o ${AOT_FILE} ${WASM_FILE} + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} + ) + + ## wasm + sourcemap + if (DEFINED EMSCRIPTEN) + add_custom_target( + ${FILE_NAME}_w_sourcemap + ALL + DEPENDS ${SOURCE_FILE} + COMMAND ${EMCC} -O0 -gsource-map -o ${FILE_NAME}.sourcemap.wasm ${CMAKE_CURRENT_SOURCE_DIR}/${SOURCE_FILE} + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} + ) + endif () + + ## install both + install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${WASM_FILE} DESTINATION wasm-apps) + install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${AOT_FILE} DESTINATION wasm-apps) + if (DEFINED EMSCRIPTEN) + install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${FILE_NAME}.sourcemap.wasm DESTINATION wasm-apps) + install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${FILE_NAME}.sourcemap.wasm.map DESTINATION wasm-apps) + endif () +endfunction () + +compile_sample(trap.c) diff --git a/samples/debug-tools/wasm-apps/trap.c b/samples/debug-tools/wasm-apps/trap.c new file mode 100644 index 000000000..364c430d1 --- /dev/null +++ b/samples/debug-tools/wasm-apps/trap.c @@ -0,0 +1,27 @@ +int +c(int n) +{ + __builtin_trap(); +} + +int +b(int n) +{ + n += 3; + return c(n); +} + +int +a(int n) +{ + return b(n); +} + +int +main(int argc, char **argv) +{ + int i = 5; + a(i); + + return 0; +} 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/inst-context/src/main.c b/samples/inst-context/src/main.c index 0d774735e..f5068deff 100644 --- a/samples/inst-context/src/main.c +++ b/samples/inst-context/src/main.c @@ -128,7 +128,7 @@ main(int argc, char *argv_main[]) } wasm_function_inst_t func3 = - wasm_runtime_lookup_function(module_inst, "calculate", NULL); + wasm_runtime_lookup_function(module_inst, "calculate"); if (!func3) { printf("The wasm function calculate is not found.\n"); goto fail; diff --git a/samples/linux-perf/CMakeLists.txt b/samples/linux-perf/CMakeLists.txt new file mode 100644 index 000000000..e9882c835 --- /dev/null +++ b/samples/linux-perf/CMakeLists.txt @@ -0,0 +1,63 @@ +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required (VERSION 3.14) + +project(linux_perf_sample) + +if(NOT CMAKE_HOST_LINUX) + message(FATAL_ERROR "This sample only works on linux") +endif() + +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE Release) +endif() + +set(CMAKE_CXX_STANDARD 17) + +list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake) +find_package(WASISDK REQUIRED) + +################ runtime settings ################ +string (TOLOWER ${CMAKE_HOST_SYSTEM_NAME} WAMR_BUILD_PLATFORM) +include(CheckPIESupported) + +# AOT and JIT byd default +set(WAMR_BUILD_AOT 1) +set(WAMR_BUILD_INTERP 0) +set(WAMR_BUILD_JIT 1) +# wasm32-wasi +set(WAMR_BUILD_LIBC_BUILTIN 0) +set(WAMR_BUILD_LIBC_WASI 1) +# mvp +set(WAMR_BUILD_BULK_MEMORY 1) +set(WAMR_BUILD_REF_TYPES 1) +set(WAMR_BUILD_SIMD 1) +set(WAMR_BUILD_TAIL_CALL 1) +# trap information +set(WAMR_BUILD_DUMP_CALL_STACK 1) +# linux perf +set(WAMR_BUILD_LINUX_PERF 1) +# +#set(WAMR_BUILD_THREAD_MGR 0) + +# vmlib +set(WAMR_ROOT_DIR ${CMAKE_CURRENT_LIST_DIR}/../..) +include(${WAMR_ROOT_DIR}/build-scripts/runtime_lib.cmake) +add_library(vmlib SHARED ${WAMR_RUNTIME_LIB_SOURCE}) +target_include_directories(vmlib INTERFACE ${WAMR_ROOT_DIR}/core/iwasm/include) +target_link_libraries (vmlib ${LLVM_AVAILABLE_LIBS} -lm -ldl) + +################ host ################ +add_executable(${PROJECT_NAME} host/demo.c) +target_link_libraries(${PROJECT_NAME} vmlib) + +################ aot + wasm ################ +include(ExternalProject) +ExternalProject_Add(wasm + SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/wasm" + CONFIGURE_COMMAND ${CMAKE_COMMAND} -S ${CMAKE_CURRENT_SOURCE_DIR}/wasm -B build + -DCMAKE_TOOLCHAIN_FILE=${WASISDK_TOOLCHAIN} + BUILD_COMMAND ${CMAKE_COMMAND} --build build + INSTALL_COMMAND ${CMAKE_COMMAND} --install build --prefix ${CMAKE_CURRENT_BINARY_DIR} +) \ No newline at end of file diff --git a/samples/linux-perf/README.md b/samples/linux-perf/README.md new file mode 100644 index 000000000..5a8dc578f --- /dev/null +++ b/samples/linux-perf/README.md @@ -0,0 +1,90 @@ +# linux perf sample introduction + +This is a sample to show how to use the Linux perf tool to profile the execution of a WebAssembly application. And how to use the [Flamegraph](https://www.brendangregg.com/flamegraphs.html) tool to visualize the profiling result. + +## Build and run the sample + +There are two Wasm modules and their instance will be created and run in the sample. [The first module](./wasm/fib.c) is a simple Wasm module that calculates the Fibonacci number. [The second module](./wasm/ackermann.c) is a simple Wasm module that execute the Ackermann function. The target is enable to profile the execution of both two modules separately. + +```bash +$ cmake -S . -B build +$ cmake --build build +``` + +### Profile the execution + +```bash +$ cd build +$ perf record -k mono -g --output=perf.data -- ./linux_perf_sample +``` + +Enable to use `perf report --stdio` to do a quick analysis of the profiling result. + +### Visualize the profiling result + +Need to download Flamegraph tool from [Flamegraph](https://github.com/brendangregg/FlameGraph/releases/tag/v1.0) firstly. + +```bash +$ perf script > out.perf +$ ./FlameGraph/stackcollapse-perf.pl out.perf > out.folded +$ ./FlameGraph/flamegraph.pl out.folded > perf.svg +``` + +In this result, you'll see two modules's profiling result and all wasm functions are named as "aot_func#N" which is a little hard to distinguish. + +![perf.png](./pics/perf.png) + +### Separate profiling result + +[process_folded_data.py](../../test-tools/flame-graph-helper/process_folded_data.py) is a script can a) translate "aot_func#N" into its original function name in name sections, b) separate the profiling result of different modules. + +In this sample, we want to separate `fib` and `ackermann` profiling data from _out.folded_. In [demo](host/demo.c), we decide to name the module of `fib1.wasm` as `fib2` and the module of `ackermann1.wasm` as `ackermann2`. + +```bash +$ python process_folded_data.py --wabt_home /opt/wabt --wasm_names fib2=./fib1.wasm,ackermann2=./ackermann1.wasm out.folded +-> write into out.fib2.translated +-> write into out.ackermann2.translated +-> write into out.translated +``` + +More scenarios: + +if only using one wasm during profiling, the script can be used like this: + +```bash +$ python process_folded_data.py --wabt_home /opt/wabt --wasm --folded +``` + +if only using one wasm during profiling and specify the module name via APIs, the script can be used like this: + +```bash +$ python process_folded_data.py --wabt_home /opt/wabt --wasm_names = --folded +``` + +if only using one wasm during profiling and specify the module name, which is same with the basename of wasm file, via APIs, the script can be used like this: + +```bash +$ python process_folded_data.py --wabt_home /opt/wabt --wasm --folded +``` + +if using multiple wasm during profiling and specify module names, which are same with basename of wasm files, via APIs, the script can be used like this: + +```bash +$ python process_folded_data.py --wabt_home /opt/wabt --wasm --wasm --wasm --folded +``` + +if using multiple wasm during profiling and specify module names via APIs, the script can be used like this: + +```bash +$ python process_folded_data.py --wabt_home /opt/wabt --wasm_names =,=,= --folded +``` + +Now we have two flame-graphs for two wasm modules: + +![fib.svg](./pics/perf.fib.svg) + +![ackermann.svg](./pics/perf.ackermann.svg) + +## Reference + +- [perf_tune](../../doc/perf_tune.md) diff --git a/samples/linux-perf/cmake/FindWAMRC.cmake b/samples/linux-perf/cmake/FindWAMRC.cmake new file mode 100644 index 000000000..586263edd --- /dev/null +++ b/samples/linux-perf/cmake/FindWAMRC.cmake @@ -0,0 +1,14 @@ +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +include(FindPackageHandleStandardArgs) + +find_file(WAMRC_BIN + NAMES wamrc + DOC "search wamrc" + HINTS ${CMAKE_CURRENT_SOURCE_DIR}/../../../wamr-compiler/build + REQUIRED +) + +find_package_handle_standard_args(WAMRC REQUIRED_VARS WAMRC_BIN) +mark_as_advanced(WAMRC_BIN) \ No newline at end of file diff --git a/samples/linux-perf/cmake/FindWASISDK.cmake b/samples/linux-perf/cmake/FindWASISDK.cmake new file mode 100644 index 000000000..5cdfea41e --- /dev/null +++ b/samples/linux-perf/cmake/FindWASISDK.cmake @@ -0,0 +1,23 @@ +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +include(FindPackageHandleStandardArgs) + +file(GLOB WASISDK_SEARCH_PATH "/opt/wasi-sdk-*") +find_path(WASISDK_HOME + NAMES share/wasi-sysroot + PATHS ${WASISDK_SEARCH_PATH} + NO_DEFAULT_PATH + REQUIRED +) + +string(REGEX MATCH [0-9]+\.[0-9]+\.*[0-9]* WASISDK_VERSION ${WASISDK_HOME}) + +find_package_handle_standard_args(WASISDK REQUIRED_VARS WASISDK_HOME VERSION_VAR WASISDK_VERSION) + +if(WASISDK_FOUND) + set(WASISDK_CC_COMMAND ${WASISDK_HOME}/bin/clang) + set(WASISDK_CXX_COMMAND ${WASISDK_HOME}/bin/clang++) + set(WASISDK_TOOLCHAIN ${WASISDK_HOME}/share/cmake/wasi-sdk.cmake) + set(WASISDK_SYSROOT ${WASISDK_HOME}/share/wasi-sysroot) +endif() diff --git a/samples/linux-perf/host/demo.c b/samples/linux-perf/host/demo.c new file mode 100644 index 000000000..8ea446ed4 --- /dev/null +++ b/samples/linux-perf/host/demo.c @@ -0,0 +1,198 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include +#include +#include +#include +#include +#include + +#include "wasm_c_api.h" + +#define own + +/* return a copy of the file stem of a file path */ +static own char * +stem(const char *file_path) +{ + char *base_name = basename(file_path); + char *s = strdup(base_name); + char *dot = strchr(s, '.'); + assert(dot); + *dot = '\0'; + return s; +} + +static void +guest_i32_to_wasm_i32_array(int *args, unsigned argc, wasm_val_t *data, + unsigned datac) +{ + for (unsigned i = 0; i < argc && i < datac; i++) { + memset(&data[i], 0, sizeof(wasm_val_t)); + data[i].kind = WASM_I32; + data[i].of.i32 = args[i]; + } +} + +int +load_run_wasm_file(wasm_engine_t *engine, const char *file_path, int *args, + unsigned argc) +{ + wasm_store_t *store = wasm_store_new(engine); + // Load binary. + printf("Loading binary...\n"); + FILE *file = fopen(file_path, "rb"); + assert(file); + + int ret = fseek(file, 0L, SEEK_END); + assert(ret == 0); + + long file_size = ftell(file); + assert(file_size != -1); + + ret = fseek(file, 0L, SEEK_SET); + assert(ret == 0); + + wasm_byte_vec_t binary = { 0 }; + wasm_byte_vec_new_uninitialized(&binary, file_size); + + size_t nread = fread(binary.data, file_size, 1, file); + fclose(file); + + // Compile. + printf("Compiling module...\n"); + + // Use its file name as the module name + char *file_name = stem(file_path); + assert(file_name); + + LoadArgs load_args = { 0 }; + load_args.name = file_name; + own wasm_module_t *module = wasm_module_new_ex(store, &binary, &load_args); + wasm_byte_vec_delete(&binary); + assert(module); + + // Use export type to find the function index to call later + wasm_exporttype_vec_t export_types = { 0 }; + wasm_module_exports(module, &export_types); + int func_to_call = -1; + for (unsigned i = 0; i < export_types.num_elems; i++) { + const wasm_name_t *name = wasm_exporttype_name(export_types.data[i]); + if (strncmp(name->data, "run", 3) == 0) { + func_to_call = i; + break; + } + } + assert(func_to_call != -1); + + // Instantiate. + printf("Instantiating module...\n"); + wasm_extern_vec_t imports = WASM_EMPTY_VEC; + own wasm_instance_t *instance = wasm_instance_new_with_args( + store, module, &imports, NULL, 16 * 1024 * 1024, 1 * 1024 * 1024); + assert(instance); + + // Extract export. + printf("Extracting export...\n"); + own wasm_extern_vec_t exports; + wasm_instance_exports(instance, &exports); + assert(exports.size); + + assert(wasm_extern_kind(exports.data[func_to_call]) == WASM_EXTERN_FUNC); + const wasm_func_t *run_func = + wasm_extern_as_func(exports.data[func_to_call]); + assert(run_func); + + wasm_module_delete(module); + wasm_instance_delete(instance); + + // Call. + printf("Calling export...\n"); + wasm_val_t as[4] = { 0 }; + guest_i32_to_wasm_i32_array(args, argc, as, 4); + + wasm_val_vec_t params = WASM_ARRAY_VEC(as); + wasm_val_t rs[1] = { WASM_I32_VAL(0) }; + wasm_val_vec_t results = WASM_ARRAY_VEC(rs); + wasm_trap_t *trap = wasm_func_call(run_func, ¶ms, &results); + assert(!trap); + + wasm_extern_vec_delete(&exports); + free(file_name); + wasm_store_delete(store); + + { + nread = nread; + ret = ret; + trap = trap; + } + return 0; +} + +void * +load_run_fib_wasm(void *arg) +{ + wasm_engine_t *engine = (wasm_engine_t *)arg; + int args[] = { 40 }; + load_run_wasm_file(engine, "./fib1.wasm", args, 1); + return NULL; +} + +void * +load_run_fib_aot(void *arg) +{ + wasm_engine_t *engine = (wasm_engine_t *)arg; + int args[] = { 40 }; + load_run_wasm_file(engine, "./fib2.aot", args, 1); + return NULL; +} + +void * +load_run_ackermann_wasm(void *arg) +{ + wasm_engine_t *engine = (wasm_engine_t *)arg; + int args[] = { 3, 12 }; + load_run_wasm_file(engine, "./ackermann1.wasm", args, 2); + return NULL; +} + +void * +load_run_ackermann_aot(void *arg) +{ + wasm_engine_t *engine = (wasm_engine_t *)arg; + int args[] = { 3, 12 }; + load_run_wasm_file(engine, "./ackermann2.aot", args, 2); + return NULL; +} + +int +main(int argc, const char *argv[]) +{ + // Initialize. + printf("Initializing...\n"); + wasm_config_t *config = wasm_config_new(); + wasm_config_set_linux_perf_opt(config, true); + wasm_engine_t *engine = wasm_engine_new_with_config(config); + + pthread_t tid[4] = { 0 }; + /* FIXME: uncomment when it is able to run two modules with llvm-jit */ + // pthread_create(&tid[0], NULL, load_run_fib_wasm, (void *)engine); + // pthread_create(&tid[2], NULL, load_run_ackermann_wasm, (void *)engine); + + pthread_create(&tid[1], NULL, load_run_fib_aot, (void *)engine); + pthread_create(&tid[3], NULL, load_run_ackermann_aot, (void *)engine); + + for (unsigned i = 0; i < sizeof(tid) / sizeof(tid[0]); i++) + pthread_join(tid[i], NULL); + + // Shut down. + printf("Shutting down...\n"); + wasm_engine_delete(engine); + + // All done. + printf("Done.\n"); + return 0; +} diff --git a/samples/linux-perf/pics/perf.ackermann.svg b/samples/linux-perf/pics/perf.ackermann.svg new file mode 100644 index 000000000..c2e1d8747 --- /dev/null +++ b/samples/linux-perf/pics/perf.ackermann.svg @@ -0,0 +1,1349 @@ + + + + + + + + + + + + + + +Flame Graph + +Reset Zoom +Search +ic + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +load_run_wasm_file (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +invoke_ii_i (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +load_run_ackermann_aot (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] run (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +wasm_runtime_call_wasm (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +all (11,485,868,643 samples, 100%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +aot_call_function (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +linux_perf_samp (11,485,868,643 samples, 100.00%) +linux_perf_samp + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +wasm_func_call (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +invoke_native_with_hw_bound_check (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +start_thread (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (11,484,299,081 samples, 99.99%) +[Wasm] [ackermann2] ackermann + + +[Wasm] [ackermann2] ackermann (1,569,562 samples, 0.01%) + + + + diff --git a/samples/linux-perf/pics/perf.fib.svg b/samples/linux-perf/pics/perf.fib.svg new file mode 100644 index 000000000..a1db059a7 --- /dev/null +++ b/samples/linux-perf/pics/perf.fib.svg @@ -0,0 +1,605 @@ + + + + + + + + + + + + + + +Flame Graph + +Reset Zoom +Search +ic + + + +[Wasm] [fib2] fibonacci (1,321,095,222 samples, 93.80%) +[Wasm] [fib2] fibonacci + + +[Wasm] [fib2] fibonacci (382,407,564 samples, 27.15%) +[Wasm] [fib2] fibonacci + + +[Wasm] [fib2] fibonacci (15,340,273 samples, 1.09%) + + + +[Wasm] [fib2] fibonacci (1,359,552,763 samples, 96.53%) +[Wasm] [fib2] fibonacci + + +[Wasm] [fib2] fibonacci (1,408,481,525 samples, 100.00%) +[Wasm] [fib2] fibonacci + + +[Wasm] [fib2] fibonacci (27,274,310 samples, 1.94%) +[.. + + +[Wasm] [fib2] fibonacci (62,450,767 samples, 4.43%) +[Wasm.. + + +[Wasm] [fib2] fibonacci (1,408,481,525 samples, 100.00%) +[Wasm] [fib2] fibonacci + + +[Wasm] [fib2] fibonacci (1,388,674,508 samples, 98.59%) +[Wasm] [fib2] fibonacci + + +[Wasm] [fib2] fibonacci (1,170,751,868 samples, 83.12%) +[Wasm] [fib2] fibonacci + + +[Wasm] [fib2] fibonacci (1,408,481,525 samples, 100.00%) +[Wasm] [fib2] fibonacci + + +[Wasm] [fib2] fibonacci (120,820,158 samples, 8.58%) +[Wasm] [fib2.. + + +invoke_i_i (1,408,481,525 samples, 100.00%) +invoke_i_i + + +[Wasm] [fib2] fibonacci (1,375,872,224 samples, 97.68%) +[Wasm] [fib2] fibonacci + + +load_run_wasm_file (1,408,481,525 samples, 100.00%) +load_run_wasm_file + + +load_run_fib_aot (1,408,481,525 samples, 100.00%) +load_run_fib_aot + + +[Wasm] [fib2] run (1,408,481,525 samples, 100.00%) +[Wasm] [fib2] run + + +[Wasm] [fib2] fibonacci (42,420,273 samples, 3.01%) +[Wa.. + + +[Wasm] [fib2] fibonacci (1,266,323,684 samples, 89.91%) +[Wasm] [fib2] fibonacci + + +linux_perf_samp (1,408,481,525 samples, 100.00%) +linux_perf_samp + + +[Wasm] [fib2] fibonacci (280,259,464 samples, 19.90%) +[Wasm] [fib2] fibonacci + + +start_thread (1,408,481,525 samples, 100.00%) +start_thread + + +[Wasm] [fib2] fibonacci (2,334,521 samples, 0.17%) + + + +[Wasm] [fib2] fibonacci (666,394,609 samples, 47.31%) +[Wasm] [fib2] fibonacci + + +[Wasm] [fib2] fibonacci (943,121,736 samples, 66.96%) +[Wasm] [fib2] fibonacci + + +[Wasm] [fib2] fibonacci (1,169,581 samples, 0.08%) + + + +[Wasm] [fib2] fibonacci (1,169,581 samples, 0.08%) + + + +[Wasm] [fib2] fibonacci (194,755,877 samples, 13.83%) +[Wasm] [fib2] fibonacci + + +[Wasm] [fib2] fibonacci (1,406,148,966 samples, 99.83%) +[Wasm] [fib2] fibonacci + + +all (1,408,481,525 samples, 100%) + + + +wasm_func_call (1,408,481,525 samples, 100.00%) +wasm_func_call + + +[Wasm] [fib2] fibonacci (5,943,602 samples, 0.42%) + + + +[Wasm] [fib2] fibonacci (1,408,481,525 samples, 100.00%) +[Wasm] [fib2] fibonacci + + +wasm_runtime_call_wasm (1,408,481,525 samples, 100.00%) +wasm_runtime_call_wasm + + +[Wasm] [fib2] fibonacci (1,401,486,191 samples, 99.50%) +[Wasm] [fib2] fibonacci + + +aot_call_function (1,408,481,525 samples, 100.00%) +aot_call_function + + +[Wasm] [fib2] fibonacci (531,941,563 samples, 37.77%) +[Wasm] [fib2] fibonacci + + +[Wasm] [fib2] fibonacci (1,406,148,966 samples, 99.83%) +[Wasm] [fib2] fibonacci + + +[Wasm] [fib2] fibonacci (1,061,055,435 samples, 75.33%) +[Wasm] [fib2] fibonacci + + +[Wasm] [fib2] fibonacci (1,408,481,525 samples, 100.00%) +[Wasm] [fib2] fibonacci + + +[Wasm] [fib2] fibonacci (1,403,816,880 samples, 99.67%) +[Wasm] [fib2] fibonacci + + +[Wasm] [fib2] fibonacci (800,646,766 samples, 56.84%) +[Wasm] [fib2] fibonacci + + +invoke_native_with_hw_bound_check (1,408,481,525 samples, 100.00%) +invoke_native_with_hw_bound_check + + + diff --git a/samples/linux-perf/pics/perf.png b/samples/linux-perf/pics/perf.png new file mode 100755 index 000000000..fc4c0930f Binary files /dev/null and b/samples/linux-perf/pics/perf.png differ diff --git a/samples/linux-perf/wasm/CMakeLists.txt b/samples/linux-perf/wasm/CMakeLists.txt new file mode 100644 index 000000000..8d36e28df --- /dev/null +++ b/samples/linux-perf/wasm/CMakeLists.txt @@ -0,0 +1,42 @@ +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required (VERSION 3.14) + +project(linux_perf_sample_wasm) + +include(CMakePrintHelpers) + +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE Release) +endif() + +list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/../cmake) +find_package(WAMRC REQUIRED) + +################ wasm ################ +add_executable(fib_wasm fib.c) +set_target_properties(fib_wasm PROPERTIES SUFFIX .wasm) +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/fib_wasm.wasm DESTINATION . RENAME fib1.wasm) + +add_executable(ackermann_wasm ackermann.c) +set_target_properties(ackermann_wasm PROPERTIES SUFFIX .wasm) +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/ackermann_wasm.wasm DESTINATION . RENAME ackermann1.wasm) + + +################ aot ################ +add_custom_target(fib_aot + ALL + COMMAND ${WAMRC_BIN} --enable-linux-perf -o fib2.aot fib_wasm.wasm + DEPENDS fib_wasm + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} +) +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/fib2.aot DESTINATION .) + +add_custom_target(ackermann_aot + ALL + COMMAND ${WAMRC_BIN} --enable-linux-perf -o ackermann2.aot ackermann_wasm.wasm + DEPENDS ackermann_wasm + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} +) +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/ackermann2.aot DESTINATION .) diff --git a/samples/linux-perf/wasm/ackermann.c b/samples/linux-perf/wasm/ackermann.c new file mode 100644 index 000000000..d6eb4346f --- /dev/null +++ b/samples/linux-perf/wasm/ackermann.c @@ -0,0 +1,38 @@ +#include + +// Ackermann function +unsigned long +ackermann(unsigned long m, unsigned long n) +{ + if (m == 0) { + return n + 1; + } + else if (n == 0) { + return ackermann(m - 1, 1); + } + else { + return ackermann(m - 1, ackermann(m, n - 1)); + } +} + +__attribute__((export_name("run"))) int +run(int m, int n) +{ + int result = ackermann(m, n); + printf("ackermann(%d, %d)=%d\n", m, n, result); + return result; +} + +int +main() +{ + unsigned long m, n, result; + + // Example usage: + m = 3; + n = 2; + result = ackermann(m, n); + printf("Ackermann(%lu, %lu) = %lu\n", m, n, result); + + return 0; +} diff --git a/samples/linux-perf/wasm/fib.c b/samples/linux-perf/wasm/fib.c new file mode 100644 index 000000000..cb928f65d --- /dev/null +++ b/samples/linux-perf/wasm/fib.c @@ -0,0 +1,32 @@ +#include +#include + +int +fibonacci(int n) +{ + if (n <= 0) + return 0; + + if (n == 1) + return 1; + + return fibonacci(n - 1) + fibonacci(n - 2); +} + +__attribute__((export_name("run"))) int +run(int n) +{ + int result = fibonacci(n); + printf("fibonacci(%d)=%d\n", n, result); + return result; +} + +int +main(int argc, char **argv) +{ + int n = atoi(argv[1]); + + printf("fibonacci(%d)=%d\n", n, fibonacci(n)); + + return 0; +} 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/native-lib/test_hello2.c b/samples/native-lib/test_hello2.c index 5dae79ca4..53ea663a7 100644 --- a/samples/native-lib/test_hello2.c +++ b/samples/native-lib/test_hello2.c @@ -30,12 +30,14 @@ test_hello2_wrapper(wasm_exec_env_t exec_env, uint32_t nameaddr, wasm_runtime_free(p); wasm_module_inst_t inst = wasm_runtime_get_module_inst(exec_env); - if (!wasm_runtime_validate_app_str_addr(inst, nameaddr) - || !wasm_runtime_validate_app_addr(inst, resultaddr, resultlen)) { + if (!wasm_runtime_validate_app_str_addr(inst, (uint64_t)nameaddr) + || !wasm_runtime_validate_app_addr(inst, (uint64_t)resultaddr, + (uint64_t)resultlen)) { return -1; } - const char *name = wasm_runtime_addr_app_to_native(inst, nameaddr); - char *result = wasm_runtime_addr_app_to_native(inst, resultaddr); + const char *name = + wasm_runtime_addr_app_to_native(inst, (uint64_t)nameaddr); + char *result = wasm_runtime_addr_app_to_native(inst, (uint64_t)resultaddr); return snprintf(result, resultlen, "Hello, %s. This is %s! Your wasm_module_inst_t is %p.\n", name, __func__, inst); diff --git a/samples/ref-types/src/hello.c b/samples/ref-types/src/hello.c index 0ee1aee88..8a6f968c3 100644 --- a/samples/ref-types/src/hello.c +++ b/samples/ref-types/src/hello.c @@ -234,19 +234,19 @@ main(int argc, char *argv[]) /* lookup function instance */ if (!(wasm_cmp_externref_ptr = wasm_runtime_lookup_function( - wasm_module_inst, "cmp-externref", NULL))) { + wasm_module_inst, "cmp-externref"))) { printf("%s\n", "lookup function cmp-externref failed"); goto fail; } if (!(wasm_get_externref_ptr = wasm_runtime_lookup_function( - wasm_module_inst, "get-externref", NULL))) { + wasm_module_inst, "get-externref"))) { printf("%s\n", "lookup function get-externref failed"); goto fail; } if (!(wasm_set_externref_ptr = wasm_runtime_lookup_function( - wasm_module_inst, "set-externref", NULL))) { + wasm_module_inst, "set-externref"))) { printf("%s\n", "lookup function set-externref failed"); goto fail; } 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/shared-module/src/main.c b/samples/shared-module/src/main.c index ebea0c6bf..7efbc4d0b 100644 --- a/samples/shared-module/src/main.c +++ b/samples/shared-module/src/main.c @@ -104,15 +104,15 @@ main(int argc, char *argv_main[]) goto fail; } - func_test_data_drop[i] = wasm_runtime_lookup_function( - module_inst[i], name_test_data_drop, NULL); + func_test_data_drop[i] = + wasm_runtime_lookup_function(module_inst[i], name_test_data_drop); if (!func_test_data_drop[i]) { printf("The wasm function %s is not found.\n", name_test_data_drop); goto fail; } - func_test_elem_drop[i] = wasm_runtime_lookup_function( - module_inst[i], name_test_elem_drop, NULL); + func_test_elem_drop[i] = + wasm_runtime_lookup_function(module_inst[i], name_test_elem_drop); if (!func_test_elem_drop[i]) { printf("The wasm function %s is not found.\n", name_test_elem_drop); goto fail; 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/spawn-thread/src/main.c b/samples/spawn-thread/src/main.c index 9501ae4c0..ecdf679a2 100644 --- a/samples/spawn-thread/src/main.c +++ b/samples/spawn-thread/src/main.c @@ -29,7 +29,7 @@ thread(void *arg) return NULL; } - func = wasm_runtime_lookup_function(module_inst, "sum", NULL); + func = wasm_runtime_lookup_function(module_inst, "sum"); if (!func) { printf("failed to lookup function sum"); wasm_runtime_destroy_thread_env(); @@ -57,7 +57,7 @@ wamr_thread_cb(wasm_exec_env_t exec_env, void *arg) wasm_function_inst_t func; uint32 argv[2]; - func = wasm_runtime_lookup_function(module_inst, "sum", NULL); + func = wasm_runtime_lookup_function(module_inst, "sum"); if (!func) { printf("failed to lookup function sum"); return NULL; @@ -133,7 +133,7 @@ main(int argc, char *argv[]) goto fail4; } - func = wasm_runtime_lookup_function(wasm_module_inst, "sum", NULL); + func = wasm_runtime_lookup_function(wasm_module_inst, "sum"); if (!func) { printf("failed to lookup function sum"); goto fail5; diff --git a/samples/terminate/src/main.c b/samples/terminate/src/main.c index 4885b0b11..fb0842a2b 100644 --- a/samples/terminate/src/main.c +++ b/samples/terminate/src/main.c @@ -39,7 +39,7 @@ runner_with_spawn_exec_env(void *vp) wasm_function_inst_t func; bool ok = wasm_runtime_init_thread_env(); assert(ok); - func = wasm_runtime_lookup_function(inst, "block_forever", NULL); + func = wasm_runtime_lookup_function(inst, "block_forever"); assert(func != NULL); wasm_runtime_call_wasm(env, func, 0, NULL); wasm_runtime_destroy_spawned_exec_env(env); diff --git a/samples/wasm-c-api/src/hello.c b/samples/wasm-c-api/src/hello.c index 966e141d7..6650f3485 100644 --- a/samples/wasm-c-api/src/hello.c +++ b/samples/wasm-c-api/src/hello.c @@ -1,3 +1,4 @@ +#include #include #include #include @@ -81,6 +82,8 @@ int main(int argc, const char* argv[]) { wasm_byte_vec_delete(&binary); + assert(wasm_module_set_name(module, "hello")); + // Create external print functions. printf("Creating callback...\n"); own wasm_functype_t* hello_type = wasm_functype_new_0_0(); @@ -117,6 +120,12 @@ int main(int argc, const char* argv[]) { return 1; } + { + const char* name = wasm_module_get_name(module); + assert(strncmp(name, "hello", 5) == 0); + printf("> removing module %s \n", name); + } + wasm_module_delete(module); wasm_instance_delete(instance); 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 ...` +This is a tool to convert addresses, which are from a call-stack dump generated by iwasm, into line info for a wasm file. When a wasm file is compiled with debug info, it is possible to transfer the address to line info. @@ -28,24 +26,45 @@ For example, there is a call-stack dump: ``` - store the call-stack dump into a file, e.g. call_stack.txt -- run the following command to transfer the address to line info: +- run the following command to convert the address into 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 + 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: +- if addresses are not available in the stack trace (i.e. iwasm <= 1.3.2) or iwasm is used in fast interpreter mode, + run the following command to convert the function index into line info (passing the `--no-addr` option): ``` - #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 + $ python3 addr2line.py --wasi-sdk --wabt --wasm-file call_stack.txt --no-addr ``` - + The script will use *wasm-objdump* in wabt to get the function names corresponding to function indexes, then use *llvm-dwarfdump* to lookup the line info for each + function index in the call-stack dump. """ +def locate_sourceMappingURL_section(wasm_objdump: Path, wasm_file: Path) -> bool: + """ + Figure out if the wasm file has a sourceMappingURL section. + """ + 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) + + for line in outputs: + line = line.strip() + if "sourceMappingURL" in line: + return True + + return False + + def get_code_section_start(wasm_objdump: Path, wasm_file: Path) -> int: """ Find the start offset of Code section in a wasm file. @@ -65,15 +84,6 @@ def get_code_section_start(wasm_objdump: Path, wasm_file: Path) -> int: ) 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: @@ -82,7 +92,9 @@ def get_code_section_start(wasm_objdump: Path, wasm_file: Path) -> int: return -1 -def get_line_info(dwarf_dump: Path, wasm_file: Path, offset: int) -> str: +def get_line_info_from_function_addr_dwarf( + dwarf_dump: Path, wasm_file: Path, offset: int +) -> tuple[str, str, str, str]: """ Find the location info of a given offset in a wasm file. """ @@ -96,29 +108,117 @@ def get_line_info(dwarf_dump: Path, wasm_file: Path, offset: int) -> str: ) outputs = p.stdout.split(os.linesep) - capture_name = False + function_name, function_file = "", "unknown" + function_line, function_column = "?", "?" + for line in outputs: line = line.strip() - if "DW_TAG_subprogram" in line: - capture_name = True + if "DW_AT_name" in line: + function_name = get_dwarf_tag_value("DW_AT_name", line) + + if "DW_AT_decl_file" in line: + function_file = get_dwarf_tag_value("DW_AT_decl_file", line) + + if "Line info" in line: + _, function_line, function_column = parse_line_info(line) + + return (function_name, function_file, function_line, function_column) + + +def get_dwarf_tag_value(tag: str, line: str) -> str: + # Try extracting value as string + STR_PATTERN = rf"{tag}\s+\(\"(.*)\"\)" + m = re.match(STR_PATTERN, line) + if m: + return m.groups()[0] + + # Try extracting value as integer + INT_PATTERN = rf"{tag}\s+\((\d+)\)" + m = re.match(INT_PATTERN, line) + return m.groups()[0] + + +def get_line_info_from_function_name_dwarf( + dwarf_dump: Path, wasm_file: Path, function_name: str +) -> tuple[str, str, str]: + """ + Find the location info of a given function in a wasm file. + """ + cmd = f"{dwarf_dump} --name={function_name} {wasm_file}" + p = subprocess.run( + shlex.split(cmd), + check=False, + capture_output=True, + text=True, + universal_newlines=True, + ) + outputs = p.stdout.split(os.linesep) + + function_name, function_file = "", "unknown" + function_line = "?" + + for line in outputs: + line = line.strip() + + if "DW_AT_name" in line: + function_name = get_dwarf_tag_value("DW_AT_name", line) + + if "DW_AT_decl_file" in line: + function_file = get_dwarf_tag_value("DW_AT_decl_file", line) + + if "DW_AT_decl_line" in line: + function_line = get_dwarf_tag_value("DW_AT_decl_line", line) + + return (function_name, function_file, function_line) + + +def get_line_info_from_function_addr_sourcemapping( + emsymbolizer: Path, wasm_file: Path, offset: int +) -> tuple[str, str, str, str]: + """ + Find the location info of a given offset in a wasm file which is compiled with emcc. + + {emsymbolizer} {wasm_file} {offset of file} + + there usually are two lines: + ?? + relative path to source file:line:column + """ + debug_info_source = wasm_file.with_name(f"{wasm_file.name}.map") + cmd = f"{emsymbolizer} -t code -f {debug_info_source} {wasm_file} {offset}" + p = subprocess.run( + shlex.split(cmd), + check=False, + capture_output=True, + text=True, + universal_newlines=True, + cwd=Path.cwd(), + ) + outputs = p.stdout.split(os.linesep) + + function_name, function_file = "", "unknown" + function_line, function_column = "?", "?" + + for line in outputs: + line = line.strip() + + if not line: 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 + m = re.match("(.*):(\d+):(\d+)", line) + if m: + function_file, function_line, function_column = m.groups() + continue + else: + # it's always ??, not sure about that + if "??" != line: + function_name = line - function_name = m.groups()[0] - - if line.startswith("Line info"): - location = line - return (function_name, location) - - return () + return (function_name, function_file, function_line, function_column) -def parse_line_info(line_info: str) -> (): +def parse_line_info(line_info: str) -> tuple[str, str, str]: """ line_info -> [file, line, column] """ @@ -130,13 +230,71 @@ def parse_line_info(line_info: str) -> (): return (file, int(line), int(column)) -def parse_call_stack_line(line: str) -> (): +def parse_call_stack_line(line: str) -> tuple[str, str, str]: """ + New format (WAMR > 1.3.2): #00: 0x0a04 - $f18 => (00, 0x0a04, $f18) + Old format: + #00 $f18 => (00, _, $f18) + Text format (-DWAMR_BUILD_LOAD_CUSTOM_SECTION=1 -DWAMR_BUILD_CUSTOM_NAME_SECTION=1): + #02: 0x0200 - a => (02, 0x0200, a) + _start (always): + #05: 0x011f - _start => (05, 0x011f, _start) """ + + # New format and Text format and _start PATTERN = r"#([0-9]+): 0x([0-9a-f]+) - (\S+)" m = re.match(PATTERN, line) - return m.groups() if m else None + if m is not None: + return m.groups() + + # Old format + PATTERN = r"#([0-9]+) (\S+)" + m = re.match(PATTERN, line) + if m is not None: + return (m.groups()[0], None, m.groups()[1]) + + return None + + +def parse_module_functions(wasm_objdump: Path, wasm_file: Path) -> dict[str, str]: + function_index_to_name = {} + + cmd = f"{wasm_objdump} -x {wasm_file} --section=function" + p = subprocess.run( + shlex.split(cmd), + check=True, + capture_output=True, + text=True, + universal_newlines=True, + ) + outputs = p.stdout.split(os.linesep) + + for line in outputs: + if not f"func[" in line: + continue + + PATTERN = r".*func\[([0-9]+)\].*<(.*)>" + m = re.match(PATTERN, line) + assert m is not None + + index = m.groups()[0] + name = m.groups()[1] + function_index_to_name[index] = name + + return function_index_to_name + + +def demangle(cxxfilt: Path, function_name: str) -> str: + cmd = f"{cxxfilt} -n {function_name}" + p = subprocess.run( + shlex.split(cmd), + check=True, + capture_output=True, + text=True, + universal_newlines=True, + ) + return p.stdout.strip() def main(): @@ -145,6 +303,12 @@ def main(): 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") + parser.add_argument( + "--no-addr", + action="store_true", + help="use call stack without addresses or from fast interpreter mode", + ) + parser.add_argument("--emsdk", type=Path, help="path to emsdk") args = parser.parse_args() wasm_objdump = args.wabt.joinpath("bin/wasm-objdump") @@ -153,37 +317,94 @@ def main(): llvm_dwarf_dump = args.wasi_sdk.joinpath("bin/llvm-dwarfdump") assert llvm_dwarf_dump.exists() + llvm_cxxfilt = args.wasi_sdk.joinpath("bin/llvm-cxxfilt") + assert llvm_cxxfilt.exists() + + emcc_production = locate_sourceMappingURL_section(wasm_objdump, args.wasm_file) + if emcc_production: + if args.emsdk is None: + print("Please provide the path to emsdk via --emsdk") + return -1 + + emsymbolizer = args.emsdk.joinpath("upstream/emscripten/emsymbolizer") + assert emsymbolizer.exists() + code_section_start = get_code_section_start(wasm_objdump, args.wasm_file) if code_section_start == -1: return -1 + function_index_to_name = parse_module_functions(wasm_objdump, args.wasm_file) + assert args.call_stack_file.exists() with open(args.call_stack_file, "rt", encoding="ascii") as f: - for line in f: + for i, line in enumerate(f): line = line.strip() - if not line: continue splitted = parse_call_stack_line(line) if splitted is None: - print(line) + print(f"{line}") continue - _, offset, _ = splitted + _, offset, index = splitted + if args.no_addr: + # FIXME: w/ emcc production + if not index.startswith("$f"): # E.g. _start or Text format + print(f"{i}: {index}") + continue + index = index[2:] - 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 + if index not in function_index_to_name: + print(f"{i}: {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})" - ) + if not emcc_production: + _, function_file, function_line = ( + get_line_info_from_function_name_dwarf( + llvm_dwarf_dump, + args.wasm_file, + function_index_to_name[index], + ) + ) + else: + _, function_file, function_line = _, "unknown", "?" + + function_name = demangle(llvm_cxxfilt, function_index_to_name[index]) + print(f"{i}: {function_name}") + print(f"\tat {function_file}:{function_line}") + else: + offset = int(offset, 16) + # match the algorithm in wasm_interp_create_call_stack() + # either a *offset* to *code* section start + # or a *offset* in a file + assert offset > code_section_start + offset = offset - code_section_start + + if emcc_production: + function_name, function_file, function_line, function_column = ( + get_line_info_from_function_addr_sourcemapping( + emsymbolizer, args.wasm_file, offset + ) + ) + else: + function_name, function_file, function_line, function_column = ( + get_line_info_from_function_addr_dwarf( + llvm_dwarf_dump, args.wasm_file, offset + ) + ) + + # if can't parse function_name, use name section or + if function_name == "": + if index.startswith("$f"): + function_name = function_index_to_name.get(index[2:], index) + else: + function_name = index + + function_name = demangle(llvm_cxxfilt, function_name) + + print(f"{i}: {function_name}") + print(f"\tat {function_file}:{function_line}:{function_column}") return 0 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/flame-graph-helper/.gitignore b/test-tools/flame-graph-helper/.gitignore new file mode 100644 index 000000000..b5ddc69ff --- /dev/null +++ b/test-tools/flame-graph-helper/.gitignore @@ -0,0 +1,2 @@ +*.* +!*.py \ No newline at end of file diff --git a/test-tools/flame-graph-helper/process_folded_data.py b/test-tools/flame-graph-helper/process_folded_data.py new file mode 100644 index 000000000..e4650fe25 --- /dev/null +++ b/test-tools/flame-graph-helper/process_folded_data.py @@ -0,0 +1,325 @@ +#!/usr/bin/env python3 +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# +""" +It is used to process *out.folded* file generated by [FlameGraph](https://github.com/brendangregg/FlameGraph). + +- translate jitted function names, which are in a form like `aot_func#N` or `[module name]#aot_func#N`, into corresponding names in a name section in .wasm +- divide the translated functions into different modules if the module name is specified in the symbol + +Usage: + +After +``` bash +# collect profiling data in perf.data + +$ perf script -i perf.data > out.perf + +$ ./FlameGraph/stackcollapse-perf.pl out.perf > out.folded +``` + +Use this script to translate the function names in out.folded + +``` +$ python translate_wasm_function_name.py --wabt_home --folded out.folded <.wasm> +# out.folded -> out.folded.translated +``` + +""" + +import argparse +import os +from pathlib import Path +import re +import shlex +import subprocess +from typing import Dict, List + + +# parse arguments like "foo=bar,fiz=biz" into a dictatory {foo:bar,fiz=biz} +class ParseKVArgs(argparse.Action): + def __call__(self, parser, namespace, values, option_string=None): + setattr(namespace, self.dest, dict()) + for value in values.split(","): + k, v = value.split("=") + getattr(namespace, self.dest)[k] = v + + +def calculate_import_function_count( + wasm_objdump_bin: Path, module_names: Dict[str, Path] +) -> Dict[str, int]: + """ + for every wasm file in , calculate the number of functions in the import section. + + using " -j Import -x " + """ + + assert wasm_objdump_bin.exists() + + import_function_counts = {} + for module_name, wasm_path in module_names.items(): + assert wasm_path.exists() + command = f"{wasm_objdump_bin} -j Import -x {wasm_path}" + p = subprocess.run( + shlex.split(command), + capture_output=True, + check=False, + text=True, + universal_newlines=True, + ) + + if p.stderr: + print("No content in import section") + import_function_counts[module_name] = 0 + continue + + import_function_count = 0 + for line in p.stdout.split(os.linesep): + line = line.strip() + + if not line: + continue + + if not " func" in line: + continue + + m = re.search(r"^-\s+func", line) + assert m + + import_function_count += 1 + + # print(f"! there are {import_function_count} import function in {module_name}") + import_function_counts[module_name] = import_function_count + + return import_function_counts + + +def collect_name_section_content( + wasm_objdump_bin: Path, module_names: Dict[str, Path] +) -> Dict[str, Dict[int, str]]: + """ + for every wasm file in , get the content of name section. + + execute "wasm_objdump_bin -j name -x wasm_file" + """ + assert wasm_objdump_bin.exists() + + name_sections = {} + for module_name, wasm_path in module_names.items(): + assert wasm_path.exists() + command = f"{wasm_objdump_bin} -j name -x {wasm_path}" + p = subprocess.run( + shlex.split(command), + capture_output=True, + check=False, + text=True, + universal_newlines=True, + ) + + if p.stderr: + print("No content in name section") + name_sections[module_name] = {} + continue + + name_section = {} + for line in p.stdout.split(os.linesep): + line = line.strip() + + if not line: + continue + + if not " func" in line: + continue + + # - func[N] <__imported_wasi_snapshot_preview1_fd_close> + m = re.match(r"- func\[(\d+)\] <(.+)>", line) + assert m + + func_index, func_name = m.groups() + name_section.update({int(func_index): func_name}) + + name_sections[module_name] = name_section + + return name_sections + + +def is_stack_check_mode(folded: Path) -> bool: + """ + check if there is a function name looks like "aot_func_internal#N", it means that WAMR adds a stack check function before the original function. + """ + with open(folded, "rt", encoding="utf-8") as f: + for line in f: + line = line.strip() + if "aot_func_internal" in line: + return True + return False + + +def replace_function_name( + import_function_counts: Dict[str, int], + name_sections: Dict[str, Dict[int, str]], + folded_in: Path, + module_names: Dict[str, Path], +) -> None: + """ + read content in . every line contains symbols which are separated by ";". + + Usually, all jitted functions are in the form of "aot_func#N". N is its function index. Use the index to find the corresponding function name in the name section. + + if there is a function name looks like "aot_func_internal#N", it means that WAMR adds a stack check function before the original function. + In this case, "aot_func#N" should be translated with "_precheck" as a suffix and "aot_func_internal#N" should be treated as the original one + """ + + assert folded_in.exists(), f"{folded_in} doesn't exist" + + stack_check_mode = is_stack_check_mode(folded_in) + + # every wasm has a translated out.folded, like out..folded.translated + folded_out_files = {} + for module_name in module_names.keys(): + wasm_folded_out_path = folded_in.with_suffix(f".{module_name}.translated") + print(f"-> write into {wasm_folded_out_path}") + folded_out_files[module_name] = wasm_folded_out_path.open( + "wt", encoding="utf-8" + ) + # Plus a default translated out.folded + default_folded_out_path = folded_in.with_suffix(".translated") + print(f"-> write into {default_folded_out_path}") + default_folded_out = default_folded_out_path.open("wt", encoding="utf-8") + + with folded_in.open("rt", encoding="utf-8") as f_in: + for line in f_in: + line = line.strip() + + m = re.match(r"(.*) (\d+)", line) + assert m + syms, samples = m.groups() + + new_line = [] + last_function_module_name = "" + for sym in syms.split(";"): + if not "aot_func" in sym: + new_line.append(sym) + continue + + # [module_name]#aot_func#N or aot_func#N + splitted = sym.split("#") + module_name = "" if splitted[0] == "aot_func" else splitted[0] + # remove [ and ] + module_name = module_name[1:-1] + + if len(module_name) == 0 and len(module_names) > 1: + raise RuntimeError( + f"❌ {sym} doesn't have a module name, but there are multiple wasm files" + ) + + if not module_name in module_names: + raise RuntimeError( + f"❌ can't find corresponds wasm file for {module_name}" + ) + + last_function_module_name = module_name + + func_idx = int(splitted[-1]) + # adjust index + func_idx = func_idx + import_function_counts[module_name] + + # print(f"🔍 {module_name} {splitted[1]} {func_idx}") + + if func_idx in name_sections[module_name]: + if len(module_name) > 0: + wasm_func_name = f"[Wasm] [{module_name}] {name_sections[module_name][func_idx]}" + else: + wasm_func_name = ( + f"[Wasm] {name_sections[module_name][func_idx]}" + ) + else: + if len(module_name) > 0: + wasm_func_name = f"[Wasm] [{module_name}] func[{func_idx}]" + else: + wasm_func_name = f"[Wasm] func[{func_idx}]" + + if stack_check_mode: + # aot_func_internal -> xxx + # aot_func --> xxx_precheck + if "aot_func" == splitted[1]: + wasm_func_name += "_precheck" + + new_line.append(wasm_func_name) + + line = ";".join(new_line) + line += f" {samples}" + + # always write into the default output + default_folded_out.write(line + os.linesep) + # based on the module name of last function, write into the corresponding output + if len(last_function_module_name) > 0: + folded_out_files[last_function_module_name].write(line + os.linesep) + + default_folded_out.close() + for f in folded_out_files.values(): + f.close() + + +def main(wabt_home: str, folded: str, module_names: Dict[str, Path]) -> None: + wabt_home = Path(wabt_home) + assert wabt_home.exists() + + folded = Path(folded) + assert folded.exists() + + wasm_objdump_bin = wabt_home.joinpath("bin", "wasm-objdump") + import_function_counts = calculate_import_function_count( + wasm_objdump_bin, module_names + ) + + name_sections = collect_name_section_content(wasm_objdump_bin, module_names) + + replace_function_name(import_function_counts, name_sections, folded, module_names) + + +if __name__ == "__main__": + argparse = argparse.ArgumentParser() + argparse.add_argument( + "--wabt_home", required=True, help="wabt home, like /opt/wabt-1.0.33" + ) + argparse.add_argument( + "--wasm", + action="append", + default=[], + help="wasm files for profiling before. like --wasm apple.wasm --wasm banana.wasm", + ) + argparse.add_argument( + "--wasm_names", + action=ParseKVArgs, + default={}, + metavar="module_name=wasm_file, ...", + help="multiple wasm files and their module names, like a=apple.wasm,b=banana.wasm,c=cake.wasm", + ) + argparse.add_argument( + "folded_file", + help="a out.folded generated by flamegraph/stackcollapse-perf.pl", + ) + + args = argparse.parse_args() + + if not args.wasm and not args.wasm_names: + print("Please specify wasm files with either --wasm or --wasm_names") + exit(1) + + # - only one wasm file. And there is no [module name] in out.folded + # - multiple wasm files. via `--wasm X --wasm Y --wasm Z`. And there is [module name] in out.folded. use the basename of wasm as the module name + # - multiple wasm files. via `--wasm_names X=x,Y=y,Z=z`. And there is [module name] in out.folded. use the specified module name + module_names = {} + if args.wasm_names: + for name, wasm_path in args.wasm_names.items(): + module_names[name] = Path(wasm_path) + else: + # use the basename of wasm as the module name + for wasm in args.wasm: + wasm_path = Path(wasm) + module_names[wasm_path.stem] = wasm_path + + main(args.wabt_home, args.folded_file, module_names) 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/trans-jitted-func-name/trans_wasm_func_name.py b/test-tools/trans-jitted-func-name/trans_wasm_func_name.py deleted file mode 100644 index 1380cd52a..000000000 --- a/test-tools/trans-jitted-func-name/trans_wasm_func_name.py +++ /dev/null @@ -1,210 +0,0 @@ -#!/usr/bin/env python3 -# -# Copyright (C) 2019 Intel Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# -""" -It is used to translate jitted functions' names(in out.folded) to coorespond name in name section in .wasm - -Usage: - -After -``` -$ perf script -i perf.data > out.perf - -# fold call stacks -$ ./FlameGraph/stackcollapse-perf.pl out.perf > out.folded -``` - -Add a step: -``` -# translate jitted functions' names -$ python translate_wasm_function_name.py --wabt_home --folded out.folded <.wasm> -# out.folded -> out.folded.translated -$ ls out.folded.translated -``` - -Then -``` -# generate flamegraph -$ ./FlameGraph/flamegraph.pl out.folded.translated > perf.wasm.svg -``` - -""" - -import argparse -import os -from pathlib import Path -import re -import shlex -import subprocess - - -def preflight_check(wabt_home: Path) -> Path: - """ - if wasm-objdump exists in wabt_home - """ - wasm_objdump_bin = wabt_home.joinpath("bin", "wasm-objdump") - if not wasm_objdump_bin.exists(): - raise RuntimeError(f"wasm-objdump not found in {wabt_home}") - - return wasm_objdump_bin - - -def collect_import_section_content(wasm_objdump_bin: Path, wasm_file: Path) -> dict: - """ - execute "wasm_objdump_bin -j Import -x " and return a dict like {function: X, global: Y, memory: Z, table: N} - """ - assert wasm_objdump_bin.exists() - assert wasm_file.exists() - - command = f"{wasm_objdump_bin} -j Import -x {wasm_file}" - p = subprocess.run( - shlex.split(command), - capture_output=True, - check=False, - text=True, - universal_newlines=True, - ) - - if p.stderr: - return {} - - import_section = {} - for line in p.stdout.split(os.linesep): - line = line.strip() - - if not line: - continue - - if line.startswith(" - func"): - import_section.update("function", import_section.get("function", 0) + 1) - else: - pass - - return import_section - - -def collect_name_section_content(wasm_objdump_bin: Path, wasm_file: Path) -> dict: - """ - execute "wasm_objdump_bin -j name -x wasm_file" and store the output in a list - """ - assert wasm_objdump_bin.exists() - assert wasm_file.exists() - - command = f"{wasm_objdump_bin} -j name -x {wasm_file}" - p = subprocess.run( - shlex.split(command), - capture_output=True, - check=False, - text=True, - universal_newlines=True, - ) - - if p.stderr: - raise RuntimeError(f"not found name section in {wasm_file}") - - name_section = {} - for line in p.stdout.split(os.linesep): - line = line.strip() - - if not line: - continue - - # - func[0] <__imported_wasi_snapshot_preview1_fd_close> - if line.startswith("- func"): - m = re.match(r"- func\[(\d+)\] <(.+)>", line) - assert m - - func_index, func_name = m.groups() - name_section.update({func_index: func_name}) - - assert name_section - return name_section - - -def replace_function_name( - import_section: dict, name_section: dict, folded_in: str, folded_out: str -) -> None: - """ - read content in . each line will be like: - - quiche::BalsaFrame::ProcessHeaders;non-virtual thunk to Envoy::Http::Http1::BalsaParser::MessageDone;Envoy::Http::Http1::ConnectionImpl::onMessageComplete;Envoy::Http::Http1::ConnectionImpl::onMessageCompleteImpl;Envoy::Http::Http1::ServerConnectionImpl::onMessageCompleteBase;Envoy::Http::ConnectionManagerImpl::ActiveStream::decodeHeaders;Envoy::Http::FilterManager::decodeHeaders;virtual thunk to Envoy::Extensions::Common::Wasm::Context::decodeHeaders;proxy_wasm::ContextBase::onRequestHeaders;proxy_wasm::wamr::Wamr::getModuleFunctionImpl;wasm_func_call;wasm_runtime_call_wasm;wasm_call_function;call_wasm_with_hw_bound_check;wasm_interp_call_wasm;llvm_jit_call_func_bytecode;wasm_runtime_invoke_native;push_args_end;aot_func_internal#3302;aot_func_internal#3308;asm_sysvec_apic_timer_interrupt;sysvec_apic_timer_interrupt;__sysvec_apic_timer_interrupt;hrtimer_interrupt;__hrtimer_run_queues;__remove_hrtimer;rb_next 1110899 - - symbol names are spearated by ";" - - if there is a symbol named like "aot_func#XXX" or "aot_func_internal#XXX", it will be replaced with the function name in name section by index - """ - folded_in = Path(folded_in) - assert folded_in.exists() - folded_out = Path(folded_out) - - import_function_count = import_section.get("function", 0) - with folded_in.open("rt", encoding="utf-8") as f_in, folded_out.open( - "wt", encoding="utf-8" - ) as f_out: - precheck_mode = False - for line in f_in: - line = line.strip() - if "aot_func_internal" in line: - precheck_mode = True - - f_in.seek(0) - for line in f_in: - new_line = [] - line = line.strip() - - m = re.match(r"(.*) (\d+)", line) - syms, samples = m.groups() - for sym in syms.split(";"): - m = re.match(r"aot_func(_internal)?#(\d+)", sym) - if not m: - new_line.append(sym) - continue - - func_idx = m.groups()[-1] - if func_idx in name_section: - wasm_func_name = f"[Wasm] {name_section[func_idx]}" - else: - wasm_func_name = ( - f"[Wasm] function[{func_idx + import_function_count}]" - ) - - if precheck_mode: - # aot_func_internal -> xxx - # aot_func --> xxx_precheck - wasm_func_name += "_precheck" if not m.groups()[0] else "" - else: - # aot_func --> xxx - pass - - new_line.append(wasm_func_name) - - line = ";".join(new_line) - line += f" {samples}" - f_out.write(line + os.linesep) - - print(f"⚙️ {folded_in} -> {folded_out}") - - -def main(wabt_home: str, wasm_file: str, folded: str) -> None: - wabt_home = Path(wabt_home) - wasm_file = Path(wasm_file) - - wasm_objdump_bin = preflight_check(wabt_home) - import_section = collect_import_section_content(wasm_objdump_bin, wasm_file) - name_section = collect_name_section_content(wasm_objdump_bin, wasm_file) - - replace_function_name(import_section, name_section, folded, folded + ".translated") - - -if __name__ == "__main__": - argparse = argparse.ArgumentParser() - argparse.add_argument( - "--folded", help="stackcollapse-perf.pl generated, like out.folded" - ) - argparse.add_argument("wasm_file", help="wasm file") - argparse.add_argument("--wabt_home", help="wabt home, like /opt/wabt-1.0.33") - - args = argparse.parse_args() - main(args.wabt_home, args.wasm_file, args.folded) 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/benchmarks/jetstream/build.sh b/tests/benchmarks/jetstream/build.sh index ca8401cda..019b4073d 100755 --- a/tests/benchmarks/jetstream/build.sh +++ b/tests/benchmarks/jetstream/build.sh @@ -7,11 +7,11 @@ source /opt/emsdk/emsdk_env.sh PLATFORM=$(uname -s | tr A-Z a-z) +WORK_DIR=$PWD OUT_DIR=$PWD/out WAMRC_CMD=$PWD/../../../wamr-compiler/build/wamrc +JETSTREAM_DIR=$PWD/perf-automation/benchmarks/JetStream2/wasm -mkdir -p jetstream -mkdir -p tsf-src mkdir -p ${OUT_DIR} if [[ $1 != "--no-simd" ]];then @@ -22,20 +22,16 @@ else WASM_SIMD_FLAGS="" fi -cd jetstream - -echo "Download source files .." -wget -N https://browserbench.org/JetStream/wasm/gcc-loops.cpp -wget -N https://browserbench.org/JetStream/wasm/quicksort.c -wget -N https://browserbench.org/JetStream/wasm/HashSet.cpp -wget -N https://browserbench.org/JetStream/simple/float-mm.c - -if [[ $? != 0 ]]; then - exit +if [ ! -d perf-automation ]; then + git clone https://github.com/mozilla/perf-automation.git + echo "Patch source files .." + cd perf-automation + patch -p1 -N < ../jetstream.patch fi -echo "Patch source files .." -patch -p1 -N < ../jetstream.patch +cd ${JETSTREAM_DIR} + +# Build gcc-loops echo "Build gcc-loops with g++ .." g++ -O3 ${NATIVE_SIMD_FLAGS} -o ${OUT_DIR}/gcc-loops_native gcc-loops.cpp @@ -56,6 +52,8 @@ if [[ ${PLATFORM} == "linux" ]]; then ${WAMRC_CMD} --enable-segue -o ${OUT_DIR}/gcc-loops_segue.aot ${OUT_DIR}/gcc-loops.wasm fi +# Build quicksort + echo "Build quicksort with gcc .." gcc -O3 ${NATIVE_SIMD_FLAGS} -o ${OUT_DIR}/quicksort_native quicksort.c @@ -74,6 +72,8 @@ if [[ ${PLATFORM} == "linux" ]]; then ${WAMRC_CMD} --enable-segue -o ${OUT_DIR}/quicksort_segue.aot ${OUT_DIR}/quicksort.wasm fi +# Build HashSet + echo "Build HashSet with g++ .." g++ -O3 ${NATIVE_SIMD_FLAGS} -o ${OUT_DIR}/HashSet_native HashSet.cpp \ -lstdc++ @@ -93,6 +93,10 @@ if [[ ${PLATFORM} == "linux" ]]; then ${WAMRC_CMD} --enable-segue -o ${OUT_DIR}/HashSet_segue.aot ${OUT_DIR}/HashSet.wasm fi +# Build float-mm + +cd ${JETSTREAM_DIR}/../simple + echo "Build float-mm with gcc .." gcc -O3 ${NATIVE_SIMD_FLAGS} -o ${OUT_DIR}/float-mm_native float-mm.c @@ -111,7 +115,9 @@ if [[ ${PLATFORM} == "linux" ]]; then ${WAMRC_CMD} --enable-segue -o ${OUT_DIR}/float-mm_segue.aot ${OUT_DIR}/float-mm.wasm fi -cd ../tsf-src +# Build tsf + +cd ${JETSTREAM_DIR}/TSF tsf_srcs="tsf_asprintf.c tsf_buffer.c tsf_error.c tsf_reflect.c tsf_st.c \ tsf_type.c tsf_io.c tsf_native.c tsf_generator.c tsf_st_typetable.c \ @@ -127,28 +133,6 @@ tsf_srcs="tsf_asprintf.c tsf_buffer.c tsf_error.c tsf_reflect.c tsf_st.c \ tsf_fsdb.c tsf_fsdb_protocol.c tsf_define_helpers.c tsf_ir.c \ tsf_ir_different.c tsf_ir_speed.c" -tsf_files="${tsf_srcs} config.h gpc_worklist.h \ - tsf_config_stub.h tsf.h tsf_internal.h tsf_region.h tsf_types.h \ - gpc.h tsf_atomics.h tsf_define_helpers.h tsf_indent.h tsf_inttypes.h \ - tsf_serial_protocol.h tsf_util.h gpc_int_common.h tsf_build_defines.h \ - tsf_format.h tsf_internal_config.h tsf_ir_different.h tsf_sha1.h \ - tsf_zip_abstract.h gpc_internal.h tsf_config.h tsf_fsdb_protocol.h \ - tsf_internal_config_stub.h tsf_ir.h tsf_st.h \ - gpc_instruction_dispatch.gen gpc_instruction_stack_effects.gen \ - gpc_instruction_to_string.gen gpc_instruction_size.gen \ - gpc_instruction_static_size.gen gpc_interpreter.gen" - -echo "Download tsf source files .." -for t in ${tsf_files} -do - wget -N "https://browserbench.org/JetStream/wasm/TSF/${t}" - if [[ $? != 0 ]]; then - exit - fi -done - -patch -p1 -N < ../tsf.patch - echo "Build tsf with gcc .." gcc \ -o ${OUT_DIR}/tsf_native -O3 ${NATIVE_SIMD_FLAGS} \ diff --git a/tests/benchmarks/jetstream/jetstream.patch b/tests/benchmarks/jetstream/jetstream.patch index bc680d98a..8799fb6c5 100644 --- a/tests/benchmarks/jetstream/jetstream.patch +++ b/tests/benchmarks/jetstream/jetstream.patch @@ -1,8 +1,9 @@ -diff -urN jetstream-org/HashSet.cpp jetstream/HashSet.cpp ---- jetstream-org/HashSet.cpp 2020-10-30 04:12:42.000000000 +0800 -+++ jetstream/HashSet.cpp 2022-01-24 17:11:08.619831711 +0800 +diff --git a/benchmarks/JetStream2/wasm/HashSet.cpp b/benchmarks/JetStream2/wasm/HashSet.cpp +index eca979b0..d1bf4d3d 100644 +--- a/benchmarks/JetStream2/wasm/HashSet.cpp ++++ b/benchmarks/JetStream2/wasm/HashSet.cpp @@ -22,8 +22,10 @@ - + #include #include +#include @@ -10,9 +11,9 @@ diff -urN jetstream-org/HashSet.cpp jetstream/HashSet.cpp #include +#include #include - + // Compile with: xcrun clang++ -o HashSet HashSet.cpp -O2 -W -framework Foundation -licucore -std=c++11 -fvisibility=hidden -DNDEBUG=1 -@@ -76,7 +78,7 @@ +@@ -76,7 +78,7 @@ template inline ToType bitwise_cast(FromType from) { typename std::remove_const::type to { }; @@ -20,4 +21,43 @@ diff -urN jetstream-org/HashSet.cpp jetstream/HashSet.cpp + memcpy(&to, &from, sizeof(to)); return to; } - + +diff --git a/benchmarks/JetStream2/wasm/TSF/gpc_code_gen_util.c b/benchmarks/JetStream2/wasm/TSF/gpc_code_gen_util.c +index 56220fa7..7e3a365b 100644 +--- a/benchmarks/JetStream2/wasm/TSF/gpc_code_gen_util.c ++++ b/benchmarks/JetStream2/wasm/TSF/gpc_code_gen_util.c +@@ -34,6 +34,8 @@ + #include + #include + ++int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result); ++ + /* code generation debugging */ + + /* NOTE: It is now the case that the count may be incremented multiple times, +diff --git a/benchmarks/JetStream2/wasm/TSF/tsf_internal.h b/benchmarks/JetStream2/wasm/TSF/tsf_internal.h +index 225a248b..ae39d3d3 100644 +--- a/benchmarks/JetStream2/wasm/TSF/tsf_internal.h ++++ b/benchmarks/JetStream2/wasm/TSF/tsf_internal.h +@@ -429,6 +429,7 @@ struct tsf_fsdb { + #endif + tsf_fsdb_connection_t *connection; + #endif ++ uint32_t __padding; + } remote; + } u; + tsf_limits_t *limits; +diff --git a/benchmarks/JetStream2/wasm/TSF/tsf_ir_speed.c b/benchmarks/JetStream2/wasm/TSF/tsf_ir_speed.c +index dd75c43e..79435c42 100644 +--- a/benchmarks/JetStream2/wasm/TSF/tsf_ir_speed.c ++++ b/benchmarks/JetStream2/wasm/TSF/tsf_ir_speed.c +@@ -63,6 +63,9 @@ static void writeTest(const char *filename, + Program_t *program; + unsigned elementIndex; + ++ if (!(programIndex % 100)) ++ printf("##programIndex: %u\n", programIndex); ++ + CS(program = tsf_region_create(sizeof(Program_t))); + + program->globals.len = numDecls + numDefns; diff --git a/tests/benchmarks/jetstream/tsf.patch b/tests/benchmarks/jetstream/tsf.patch deleted file mode 100644 index 98355b08c..000000000 --- a/tests/benchmarks/jetstream/tsf.patch +++ /dev/null @@ -1,36 +0,0 @@ -diff -urN tsf-src-org/gpc_code_gen_util.c tsf-src/gpc_code_gen_util.c ---- tsf-src-org/gpc_code_gen_util.c 2023-09-21 11:12:40.211166472 +0800 -+++ tsf-src/gpc_code_gen_util.c 2023-09-21 11:09:13.643170967 +0800 -@@ -34,6 +34,8 @@ - #include - #include - -+int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result); -+ - /* code generation debugging */ - - /* NOTE: It is now the case that the count may be incremented multiple times, -diff -urN tsf-src-org/tsf_internal.h tsf-src/tsf_internal.h ---- tsf-src-org/tsf_internal.h 2023-09-21 11:11:50.843167546 +0800 -+++ tsf-src/tsf_internal.h 2023-09-21 11:06:53.031174027 +0800 -@@ -429,6 +429,7 @@ - #endif - tsf_fsdb_connection_t *connection; - #endif -+ uint32_t __padding; - } remote; - } u; - tsf_limits_t *limits; -diff -urN tsf-src-org/tsf_ir_speed.c tsf-src/tsf_ir_speed.c ---- tsf-src-org/tsf_ir_speed.c 2023-09-21 11:12:15.699167005 +0800 -+++ tsf-src/tsf_ir_speed.c 2023-09-21 11:06:53.031174027 +0800 -@@ -63,6 +63,9 @@ - Program_t *program; - unsigned elementIndex; - -+ if (!(programIndex % 100)) -+ printf("##programIndex: %u\n", programIndex); -+ - CS(program = tsf_region_create(sizeof(Program_t))); - - program->globals.len = numDecls + numDefns; diff --git a/tests/wamr-test-suites/spec-test-script/all.py b/tests/wamr-test-suites/spec-test-script/all.py index 8027abde0..98f5c1e63 100644 --- a/tests/wamr-test-suites/spec-test-script/all.py +++ b/tests/wamr-test-suites/spec-test-script/all.py @@ -14,7 +14,7 @@ import time """ The script itself has to be put under the same directory with the "spec". -To run a single non-GC case with interpreter mode: +To run a single non-GC and non-memory64 case with interpreter mode: cd workspace python3 runtest.py --wast2wasm wabt/bin/wat2wasm --interpreter iwasm \ spec/test/core/xxx.wast @@ -22,7 +22,7 @@ To run a single non-GC case with aot mode: cd workspace python3 runtest.py --aot --wast2wasm wabt/bin/wat2wasm --interpreter iwasm \ --aot-compiler wamrc spec/test/core/xxx.wast -To run a single GC case: +To run a single GC case or single memory64 case: cd workspace python3 runtest.py --wast2wasm spec/interpreter/wasm --interpreter iwasm \ --aot-compiler wamrc --gc spec/test/core/xxx.wast @@ -78,6 +78,7 @@ def ignore_the_case( multi_thread_flag=False, simd_flag=False, gc_flag=False, + memory64_flag=False, xip_flag=False, eh_flag=False, qemu_flag=False, @@ -162,6 +163,7 @@ def test_case( clean_up_flag=True, verbose_flag=True, gc_flag=False, + memory64_flag=False, qemu_flag=False, qemu_firmware="", log="", @@ -169,7 +171,7 @@ def test_case( ): CMD = [sys.executable, "runtest.py"] CMD.append("--wast2wasm") - CMD.append(WAST2WASM_CMD if not gc_flag else SPEC_INTERPRETER_CMD) + CMD.append(WAST2WASM_CMD if not gc_flag and not memory64_flag else SPEC_INTERPRETER_CMD) CMD.append("--interpreter") if sgx_flag: CMD.append(IWASM_SGX_CMD) @@ -217,6 +219,9 @@ def test_case( if gc_flag: CMD.append("--gc") + if memory64_flag: + CMD.append("--memory64") + if log != "": CMD.append("--log-dir") CMD.append(log) @@ -283,6 +288,7 @@ def test_suite( clean_up_flag=True, verbose_flag=True, gc_flag=False, + memory64_flag=False, parl_flag=False, qemu_flag=False, qemu_firmware="", @@ -325,6 +331,7 @@ def test_suite( multi_thread_flag, simd_flag, gc_flag, + memory64_flag, xip_flag, eh_flag, qemu_flag, @@ -357,6 +364,7 @@ def test_suite( clean_up_flag, verbose_flag, gc_flag, + memory64_flag, qemu_flag, qemu_firmware, log, @@ -382,6 +390,7 @@ def test_suite( else: print(f"----- Run the whole spec test suite -----") for case_path in case_list: + print(case_path) try: test_case( str(case_path), @@ -396,6 +405,7 @@ def test_suite( clean_up_flag, verbose_flag, gc_flag, + memory64_flag, qemu_flag, qemu_firmware, log, @@ -521,6 +531,13 @@ def main(): dest="gc_flag", help="Running with GC feature", ) + parser.add_argument( + "--memory64", + action="store_true", + default=False, + dest="memory64_flag", + help="Running with memory64 feature", + ) parser.add_argument( "cases", metavar="path_to__case", @@ -563,6 +580,7 @@ def main(): options.clean_up_flag, options.verbose_flag, options.gc_flag, + options.memory64_flag, options.parl_flag, options.qemu_flag, options.qemu_firmware, @@ -589,6 +607,7 @@ def main(): options.clean_up_flag, options.verbose_flag, options.gc_flag, + options.memory64_flag, options.qemu_flag, options.qemu_firmware, options.log, 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/memory64.patch b/tests/wamr-test-suites/spec-test-script/memory64.patch new file mode 100644 index 000000000..739a1df60 --- /dev/null +++ b/tests/wamr-test-suites/spec-test-script/memory64.patch @@ -0,0 +1,28 @@ +diff --git a/test/core/memory.wast b/test/core/memory.wast +index 1dd5b84..497b69f 100644 +--- a/test/core/memory.wast ++++ b/test/core/memory.wast +@@ -76,17 +76,17 @@ + "memory size must be at most 65536 pages (4GiB)" + ) + +-(assert_invalid ++(assert_malformed + (module quote "(memory 0x1_0000_0000)") +- "memory size must be at most 65536 pages (4GiB)" ++ "i32 constant out of range" + ) +-(assert_invalid ++(assert_malformed + (module quote "(memory 0x1_0000_0000 0x1_0000_0000)") +- "memory size must be at most 65536 pages (4GiB)" ++ "i32 constant out of range" + ) +-(assert_invalid ++(assert_malformed + (module quote "(memory 0 0x1_0000_0000)") +- "memory size must be at most 65536 pages (4GiB)" ++ "i32 constant out of range" + ) + + (module diff --git a/tests/wamr-test-suites/spec-test-script/runtest.py b/tests/wamr-test-suites/spec-test-script/runtest.py index 344e4fd44..13229d977 100755 --- a/tests/wamr-test-suites/spec-test-script/runtest.py +++ b/tests/wamr-test-suites/spec-test-script/runtest.py @@ -313,6 +313,9 @@ parser.add_argument('--multi-thread', default=False, action='store_true', parser.add_argument('--gc', default=False, action='store_true', help='Test with GC') +parser.add_argument('--memory64', default=False, action='store_true', + help='Test with Memory64') + parser.add_argument('--qemu', default=False, action='store_true', help="Enable QEMU") @@ -1071,7 +1074,7 @@ def compile_wast_to_wasm(form, wast_tempfile, wasm_tempfile, opts): log("Compiling WASM to '%s'" % wasm_tempfile) # default arguments - if opts.gc: + if opts.gc or opts.memory64: cmd = [opts.wast2wasm, "-u", "-d", wast_tempfile, "-o", wasm_tempfile] elif opts.eh: cmd = [opts.wast2wasm, "--enable-thread", "--no-check", "--enable-exceptions", "--enable-tail-call", wast_tempfile, "-o", wasm_tempfile ] @@ -1116,6 +1119,9 @@ def compile_wasm_to_aot(wasm_tempfile, aot_tempfile, runner, opts, r, output = ' cmd.append("--enable-gc") cmd.append("--enable-tail-call") + if opts.memory64: + cmd.append("--enable-memory64") + if output == 'object': cmd.append("--format=object") elif output == 'ir': diff --git a/tests/wamr-test-suites/test_wamr.sh b/tests/wamr-test-suites/test_wamr.sh index 933583816..0c56acac4 100755 --- a/tests/wamr-test-suites/test_wamr.sh +++ b/tests/wamr-test-suites/test_wamr.sh @@ -23,6 +23,7 @@ function help() echo "-p enable multi thread feature" echo "-S enable SIMD feature" echo "-G enable GC feature" + echo "-W enable memory64 feature" echo "-X enable XIP feature" echo "-e enable exception handling" echo "-x test SGX" @@ -50,6 +51,7 @@ ENABLE_MULTI_THREAD=0 COLLECT_CODE_COVERAGE=0 ENABLE_SIMD=0 ENABLE_GC=0 +ENABLE_MEMORY64=0 ENABLE_XIP=0 ENABLE_EH=0 ENABLE_DEBUG_VERSION=0 @@ -72,7 +74,7 @@ WASI_TESTSUITE_COMMIT="ee807fc551978490bf1c277059aabfa1e589a6c2" TARGET_LIST=("AARCH64" "AARCH64_VFP" "ARMV7" "ARMV7_VFP" "THUMBV7" "THUMBV7_VFP" \ "RISCV32" "RISCV32_ILP32F" "RISCV32_ILP32D" "RISCV64" "RISCV64_LP64F" "RISCV64_LP64D") -while getopts ":s:cabgvt:m:MCpSXexwPGQF:j:T:" opt +while getopts ":s:cabgvt:m:MCpSXexwWPGQF:j:T:" opt do OPT_PARSED="TRUE" case $opt in @@ -131,6 +133,10 @@ do echo "enable multi module feature" ENABLE_MULTI_MODULE=1 ;; + W) + echo "enable wasm64(memory64) feature" + ENABLE_MEMORY64=1 + ;; C) echo "enable code coverage" COLLECT_CODE_COVERAGE=1 @@ -478,6 +484,29 @@ function spec_test() popd fi + # update memory64 cases + if [[ ${ENABLE_MEMORY64} == 1 ]]; then + echo "checkout spec for memory64 proposal" + + popd + rm -fr spec + # check spec test cases for memory64 + git clone -b main --single-branch https://github.com/WebAssembly/memory64.git spec + pushd spec + + git restore . && git clean -ffd . + # Reset to commit: "Merge remote-tracking branch 'upstream/main' into merge2" + git reset --hard 48e69f394869c55b7bbe14ac963c09f4605490b6 + git checkout 044d0d2e77bdcbe891f7e0b9dd2ac01d56435f0b -- test/core/elem.wast + git apply ../../spec-test-script/ignore_cases.patch + git apply ../../spec-test-script/memory64.patch + + echo "compile the reference intepreter" + pushd interpreter + make + popd + fi + popd echo $(pwd) @@ -488,7 +517,7 @@ function spec_test() local ARGS_FOR_SPEC_TEST="" - # multi-module only enable in interp mode + # multi-module only enable in interp mode and aot mode if [[ 1 == ${ENABLE_MULTI_MODULE} ]]; then if [[ $1 == 'classic-interp' || $1 == 'fast-interp' || $1 == 'aot' ]]; then ARGS_FOR_SPEC_TEST+="-M " @@ -537,6 +566,13 @@ function spec_test() ARGS_FOR_SPEC_TEST+="--gc " fi + # wasm64(memory64) is only enabled in interp and aot mode + if [[ 1 == ${ENABLE_MEMORY64} ]]; then + if [[ $1 == 'classic-interp' || $1 == 'aot' ]]; then + ARGS_FOR_SPEC_TEST+="--memory64 " + fi + fi + if [[ ${ENABLE_QEMU} == 1 ]]; then ARGS_FOR_SPEC_TEST+="--qemu " ARGS_FOR_SPEC_TEST+="--qemu-firmware ${QEMU_FIRMWARE} " @@ -833,6 +869,12 @@ function trigger() EXTRA_COMPILE_FLAGS+=" -DWAMR_BUILD_MULTI_MODULE=0" fi + if [[ ${ENABLE_MEMORY64} == 1 ]];then + EXTRA_COMPILE_FLAGS+=" -DWAMR_BUILD_MEMORY64=1" + else + EXTRA_COMPILE_FLAGS+=" -DWAMR_BUILD_MEMORY64=0" + fi + if [[ ${ENABLE_MULTI_THREAD} == 1 ]];then EXTRA_COMPILE_FLAGS+=" -DWAMR_BUILD_LIB_PTHREAD=1" fi diff --git a/tests/wamr-test-suites/wasi-test-script/run_wasi_tests.sh b/tests/wamr-test-suites/wasi-test-script/run_wasi_tests.sh index 4cfe6c29b..9ea733c3f 100755 --- a/tests/wamr-test-suites/wasi-test-script/run_wasi_tests.sh +++ b/tests/wamr-test-suites/wasi-test-script/run_wasi_tests.sh @@ -41,6 +41,12 @@ readonly THREAD_INTERNAL_TESTS="${WAMR_DIR}/core/iwasm/libraries/lib-wasi-thread readonly THREAD_STRESS_TESTS="${WAMR_DIR}/core/iwasm/libraries/lib-wasi-threads/stress-test/" readonly LIB_SOCKET_TESTS="${WAMR_DIR}/core/iwasm/libraries/lib-socket/test/" +add_env_key_to_test_config_file() { + filepath="tests/$2/testsuite/$3.json" + modified_contents=$(jq ".env.$1 = 1" "$filepath") + echo "$modified_contents" > "$filepath" +} + run_aot_tests () { local -n tests=$1 local -n excluded_tests=$2 @@ -95,6 +101,15 @@ if [[ $MODE != "aot" ]];then export TEST_RUNTIME_EXE="${IWASM_CMD}" + # Some of the WASI test assertions can be controlled via environment + # variables. The following ones are set on Windows so that the tests pass. + if [ "$PLATFORM" == "windows" ]; then + add_env_key_to_test_config_file NO_DANGLING_FILESYSTEM rust symlink_loop + add_env_key_to_test_config_file NO_DANGLING_FILESYSTEM rust dangling_symlink + add_env_key_to_test_config_file ERRNO_MODE_WINDOWS rust path_open_preopen + add_env_key_to_test_config_file NO_RENAME_DIR_TO_EMPTY_DIR rust path_rename + fi + TEST_OPTIONS="-r adapters/wasm-micro-runtime.py \ -t \ ${C_TESTS} \ diff --git a/wamr-compiler/CMakeLists.txt b/wamr-compiler/CMakeLists.txt index a11db40aa..6a3f97521 100644 --- a/wamr-compiler/CMakeLists.txt +++ b/wamr-compiler/CMakeLists.txt @@ -214,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) 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 "") -