├── .CurrentChangelog.md ├── .clang-format ├── .clang-tidy ├── .github └── workflows │ ├── build.yml │ ├── examples.yml │ └── release.yml ├── .gitignore ├── Changelog.md ├── LICENSE ├── README.md ├── go.mod └── wasmedge ├── ast.go ├── async.go ├── callframe.go ├── cgo.go ├── chostfunc.go ├── cli.go ├── compiler.go ├── configure.go ├── executor.go ├── hostfunc.go ├── instance.go ├── limit.go ├── limit_test.go ├── loader.go ├── log.go ├── plugin.go ├── result.go ├── statistics.go ├── store.go ├── string.go ├── validator.go ├── value.go ├── version.go └── vm.go /.CurrentChangelog.md: -------------------------------------------------------------------------------- 1 | ### v0.14.0 (2025-02-14) 2 | 3 | Breaking Changes: 4 | 5 | * Removed `wasmedge.ValType` and `wasmedge.RefType` const values, and introduce the `wasmedge.ValType` struct. 6 | * Added the `wasmedge.NewValTypeI32()` API to replace the `wasmedge.ValType_I32` const value. 7 | * Added the `wasmedge.NewValTypeI64()` API to replace the `wasmedge.ValType_I64` const value. 8 | * Added the `wasmedge.NewValTypeF32()` API to replace the `wasmedge.ValType_F32` const value. 9 | * Added the `wasmedge.NewValTypeF64()` API to replace the `wasmedge.ValType_F64` const value. 10 | * Added the `wasmedge.NewValTypeV128()` API to replace the `wasmedge.ValType_V128` const value. 11 | * Added the `wasmedge.NewValTypeFuncRef()` API to replace the `wasmedge.ValType_FuncRef` const value. 12 | * Added the `wasmedge.NewValTypeExternRef()` API to replace the `wasmedge.ValType_ExterunRef` const value. 13 | * Added the `(*wasmedge.ValType).IsEqual()` API to compare the equivalent of two value types. 14 | * Added the `(*wasmedge.ValType).IsI32()` API to specify the value type is `i32` or not. 15 | * Added the `(*wasmedge.ValType).IsI64()` API to specify the value type is `i64` or not. 16 | * Added the `(*wasmedge.ValType).IsF32()` API to specify the value type is `f32` or not. 17 | * Added the `(*wasmedge.ValType).IsF64()` API to specify the value type is `f64` or not. 18 | * Added the `(*wasmedge.ValType).IsV128()` API to specify the value type is `v128` or not. 19 | * Added the `(*wasmedge.ValType).IsFuncRef()` API to specify the value type is `funcref` or not. 20 | * Added the `(*wasmedge.ValType).IsExternRef()` API to specify the value type is `externref` or not. 21 | * Added the `(*wasmedge.ValType).IsRef()` API to specify the value type is a reference type or not. 22 | * Added the `(*wasmedge.ValType).IsRefNull()` API to specify the value type is a nullable reference type or not. 23 | * Updated the supported WASM proposals. 24 | * Added the `wasmedge.Proposal.GC`. 25 | * Added the `wasmedge.Proposal.RELAXED_SIMD`. 26 | * Added the `wasmedge.Proposal.COMPONENT_MODEL`. 27 | * Added the error return in `(*wasmedge.Global).SetValue()` API. 28 | * Applied the new `wasmedge.ValType` struct to all related APIs. 29 | * `wasmedge.NewFunctionType()` accepts the new `[]*wasmedge.ValType` for parameters now. 30 | * `(*wasmedge.FunctionType).GetParameters()` returns the new `[]*wasmedge.ValType` now. 31 | * `(*wasmedge.FunctionType).GetReturns()` returns the new `[]*wasmedge.ValType` now. 32 | * `wasmedge.NewTableType()` accepts the new `*wasmedge.ValType` instead of `wasmedge.RefType` for parameters now. 33 | * `(*wasmedge.TableType).GetRefType()` returns the new `*wasmedge.ValType` now. 34 | * `wasmedge.NewGlobalType()` accepts the new `*wasmedge.ValType` for parameters now. 35 | * `(*wasmedge.GlobalType).GetValType()` returns the new `*wasmedge.ValType` now. 36 | 37 | Features: 38 | 39 | * Updated to the [WasmEdge 0.14.0](https://github.com/WasmEdge/WasmEdge/releases/tag/0.14.0). 40 | * Added the new `(*wasmedge.Compiler).CompileBuffer()` API for compiling WASM from buffer. 41 | * Added the tag type and tag instance for the exception-handling proposal. 42 | * Added the `wasmedge.ExternType_Tag` const value. 43 | * Added the `wasmedge.TagType` struct for tag type. 44 | * Added the `(*wasmedge.TagType).GetFunctionType()` API. 45 | * Added the `wasmedge.Tag` struct for tag instance. 46 | * Added the `(*wasmedge.Tag).GetTagType()` API. 47 | * Added the `(*wasmedge.Module).FindTag()` API to retrieve exported tag instances from a module instance. 48 | * Added the `(*wasmedge.Module).ListTag()` API to list all exported tag instance names from a module instance. 49 | -------------------------------------------------------------------------------- /.clang-format: -------------------------------------------------------------------------------- 1 | BasedOnStyle: LLVM 2 | IndentWidth: 2 3 | -------------------------------------------------------------------------------- /.clang-tidy: -------------------------------------------------------------------------------- 1 | Checks: '-*,clang-diagnostic-*,llvm-*,misc-*,-misc-unused-parameters,-misc-non-private-member-variables-in-classes,readability-identifier-naming' 2 | CheckOptions: 3 | - key: readability-identifier-naming.ClassCase 4 | value: CamelCase 5 | - key: readability-identifier-naming.EnumCase 6 | value: CamelCase 7 | - key: readability-identifier-naming.FunctionCase 8 | value: camelBack 9 | - key: readability-identifier-naming.MemberCase 10 | value: CamelCase 11 | - key: readability-identifier-naming.ParameterCase 12 | value: CamelCase 13 | - key: readability-identifier-naming.UnionCase 14 | value: CamelCase 15 | - key: readability-identifier-naming.VariableCase 16 | value: CamelCase 17 | 18 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | concurrency: 4 | group: build-${{ github.head_ref }} 5 | cancel-in-progress: true 6 | 7 | on: 8 | push: 9 | branches: 10 | - master 11 | tags: 12 | - "*" 13 | pull_request: 14 | branches: 15 | - master 16 | 17 | jobs: 18 | build_ubuntu: 19 | runs-on: ubuntu-24.04 20 | strategy: 21 | matrix: 22 | go: [ '1.22.x', '1.23.x' ] 23 | name: Build WasmEdge-go on Ubuntu 24.04 x86_64 with Go ${{ matrix.go }} 24 | steps: 25 | - uses: actions/checkout@v2 26 | - name: Install go 27 | uses: actions/setup-go@v2 28 | with: 29 | go-version: ${{ matrix.go }} 30 | - name: Check go version 31 | run: go version 32 | - name: Install wasmedge 33 | run: | 34 | wget -qO- https://raw.githubusercontent.com/WasmEdge/WasmEdge/master/utils/install.sh | bash -s -- -v 0.14.0 35 | - name: Build WasmEdge-go 36 | run: | 37 | source $HOME/.wasmedge/env 38 | go build ./wasmedge/ 39 | 40 | build_macos: 41 | runs-on: macos-14 42 | strategy: 43 | matrix: 44 | go: [ '1.22.x', '1.23.x' ] 45 | name: Build WasmEdge-go on MacOS 14 x86_64 with Go ${{ matrix.go }} 46 | steps: 47 | - uses: actions/checkout@v2 48 | - name: Install go 49 | uses: actions/setup-go@v2 50 | with: 51 | go-version: ${{ matrix.go }} 52 | - name: Check go version 53 | run: go version 54 | - name: Install wasmedge 55 | run: | 56 | wget -qO- https://raw.githubusercontent.com/WasmEdge/WasmEdge/master/utils/install.sh | bash -s -- -v 0.14.0 57 | - name: Build WasmEdge-go 58 | run: | 59 | source $HOME/.wasmedge/env 60 | go build ./wasmedge/ 61 | -------------------------------------------------------------------------------- /.github/workflows/examples.yml: -------------------------------------------------------------------------------- 1 | name: examples 2 | 3 | on: 4 | workflow_dispatch: 5 | inputs: 6 | logLevel: 7 | description: 'Log level' 8 | required: true 9 | default: 'info' 10 | push: 11 | branches: [ master ] 12 | pull_request: 13 | branches: [ master ] 14 | 15 | jobs: 16 | build_aot: 17 | runs-on: ubuntu-24.04 18 | strategy: 19 | matrix: 20 | go: [ '1.22.x', '1.23.x' ] 21 | name: Run WasmEdge-go-examples in AOT mode with Go ${{ matrix.go }} 22 | 23 | steps: 24 | 25 | - name: Install apt-get packages 26 | run: | 27 | sudo ACCEPT_EULA=Y apt-get update 28 | sudo ACCEPT_EULA=Y apt-get upgrade 29 | sudo apt-get install wget git curl software-properties-common 30 | 31 | - name: Setup Go 32 | uses: actions/setup-go@v2 33 | with: 34 | go-version: ${{ matrix.go }} 35 | 36 | - name: Check go version 37 | run: go version 38 | 39 | - name: Install WasmEdge 40 | run: | 41 | wget -qO- https://raw.githubusercontent.com/WasmEdge/WasmEdge/master/utils/install.sh | sudo bash -s -- -p /usr/local --plugins wasmedge_tensorflow wasmedge_tensorflowlite wasmedge_image -v 0.14.0 42 | 43 | - name: Install the examples 44 | run: | 45 | git clone https://github.com/second-state/wasmedge-go-examples 46 | 47 | - name: go_WasmAOT 48 | run: | 49 | cd wasmedge-go-examples/go_WasmAOT 50 | go get . 51 | go build 52 | 53 | - name: go_ThreadsMandelbrot 54 | run: | 55 | cd wasmedge-go-examples/go_ThreadsMandelbrot 56 | go get . 57 | go build threads.go 58 | wasmedgec --enable-threads mandelbrot.wasm out.wasm 59 | ./threads out.wasm 4 60 | 61 | - name: go_ReadFile 62 | run: | 63 | cd wasmedge-go-examples/go_ReadFile 64 | go get . 65 | go build 66 | wasmedgec rust_readfile.wasm out.wasm 67 | ./read_file out.wasm file.txt 68 | 69 | - name: go_ExternRef 70 | run: | 71 | cd wasmedge-go-examples/go_ExternRef 72 | go get . 73 | go build 74 | wasmedgec funcs.wasm out.wasm 75 | ./externref out.wasm 76 | 77 | - name: go_AccessMemory 78 | run: | 79 | cd wasmedge-go-examples/go_AccessMemory 80 | go get . 81 | go build run.go 82 | wasmedgec rust_access_memory_lib.wasm out.wasm 83 | ./run out.wasm 84 | 85 | - name: go_AccessMemoryTinyGo 86 | run: | 87 | cd wasmedge-go-examples/go_AccessMemoryTinyGo 88 | go get . 89 | go build run.go 90 | wasmedgec fib.wasm out.wasm 91 | ./run out.wasm 92 | 93 | - name: go_MemoryGreet 94 | run: | 95 | cd wasmedge-go-examples/go_MemoryGreet 96 | go get . 97 | go build greet_memory.go 98 | wasmedgec rust_memory_greet_lib.wasm out.wasm 99 | ./greet_memory out.wasm 100 | 101 | - name: go_MemoryGreetTinyGo 102 | run: | 103 | cd wasmedge-go-examples/go_MemoryGreetTinyGo 104 | go get . 105 | go build greet_memory.go 106 | wasmedgec greet.wasm out.wasm 107 | ./greet_memory out.wasm 108 | 109 | - name: go_BindgenFuncs 110 | run: | 111 | cd wasmedge-go-examples/go_BindgenFuncs 112 | go get . 113 | go build 114 | wasmedgec rust_bindgen_funcs_lib.wasm out.wasm 115 | ./bindgen_funcs out.wasm 116 | 117 | - name: go_BindgenKmeans 118 | run: | 119 | cd wasmedge-go-examples/go_BindgenKmeans 120 | go get . 121 | go build 122 | wasmedgec rust_bindgen_kmeans_lib.wasm out.wasm 123 | ./bindgen_kmeans out.wasm 124 | 125 | - name: go_BindgenWasi 126 | run: | 127 | cd wasmedge-go-examples/go_BindgenWasi 128 | go get . 129 | go build 130 | wasmedgec rust_bindgen_wasi_lib.wasm out.wasm 131 | ./bindgen_wasi out.wasm 132 | 133 | - name: go_Mobilenet 134 | run: | 135 | cd wasmedge-go-examples/go_Mobilenet 136 | go get . 137 | go build 138 | wasmedgec rust_mobilenet_lib.wasm out.wasm 139 | ./mobilenet out.wasm grace_hopper.jpg 140 | 141 | - name: go_MobilenetBirds 142 | run: | 143 | cd wasmedge-go-examples/go_MobilenetBirds 144 | go get . 145 | go build 146 | wasmedgec rust_mobilenet_birds_lib.wasm out.wasm 147 | ./mobilenet_birds out.wasm PurpleGallinule.jpg 148 | 149 | - name: go_MobilenetFood 150 | run: | 151 | cd wasmedge-go-examples/go_MobilenetFood 152 | go get . 153 | go build 154 | wasmedgec rust_mobilenet_food_lib.wasm out.wasm 155 | ./mobilenet_food out.wasm food.jpg 156 | 157 | - name: go_MobilenetInsects 158 | run: | 159 | cd wasmedge-go-examples/go_MobilenetInsects 160 | go get . 161 | go build 162 | wasmedgec rust_mobilenet_insects_lib.wasm out.wasm 163 | ./mobilenet_insects out.wasm ladybug.jpg 164 | 165 | - name: go_MobilenetPlants 166 | run: | 167 | cd wasmedge-go-examples/go_MobilenetPlants 168 | go get . 169 | go build 170 | wasmedgec rust_mobilenet_plants_lib.wasm out.wasm 171 | ./mobilenet_plants out.wasm sunflower.jpg 172 | 173 | - name: go_mtcnn 174 | run: | 175 | cd wasmedge-go-examples/go_mtcnn 176 | go get . 177 | go build 178 | wasmedgec rust_mtcnn.wasm out.wasm 179 | ./mtcnn out.wasm mtcnn.pb solvay.jpg out.jpg 180 | 181 | build_interpreter: 182 | runs-on: ubuntu-24.04 183 | needs: build_aot 184 | 185 | strategy: 186 | matrix: 187 | go: [ '1.22.x', '1.23.x' ] 188 | name: Run WasmEdge-go-examples in interpreter mode with Go ${{ matrix.go }} 189 | 190 | steps: 191 | 192 | - name: Install apt-get packages 193 | run: | 194 | sudo ACCEPT_EULA=Y apt-get update 195 | sudo ACCEPT_EULA=Y apt-get upgrade 196 | sudo apt-get install wget git curl software-properties-common 197 | 198 | - name: Setup Go 199 | uses: actions/setup-go@v2 200 | with: 201 | go-version: ${{ matrix.go }} 202 | 203 | - name: Check go version 204 | run: go version 205 | 206 | - name: Install WasmEdge 207 | run: | 208 | wget -qO- https://raw.githubusercontent.com/WasmEdge/WasmEdge/master/utils/install.sh | sudo bash -s -- -p /usr/local --plugins wasmedge_tensorflow wasmedge_tensorflowlite wasmedge_image -v 0.14.0 209 | 210 | - name: Install the examples 211 | run: | 212 | git clone https://github.com/second-state/wasmedge-go-examples 213 | 214 | - name: go_PrintFibonacci 215 | run: | 216 | cd wasmedge-go-examples/go_PrintFibonacci 217 | go get . 218 | go build 219 | ./print_fibonacci 220 | 221 | - name: go_WasmAOT 222 | run: | 223 | cd wasmedge-go-examples/go_WasmAOT 224 | go get . 225 | go build 226 | ./wasmAOT fibonacci.wasm out.wasm 227 | 228 | - name: go_ThreadsMandelbrot 229 | run: | 230 | cd wasmedge-go-examples/go_ThreadsMandelbrot 231 | go get . 232 | go build threads.go 233 | ./threads mandelbrot.wasm 4 234 | 235 | - name: go_ReadFile 236 | run: | 237 | cd wasmedge-go-examples/go_ReadFile 238 | go get . 239 | go build 240 | ./read_file rust_readfile.wasm file.txt 241 | 242 | - name: go_ExternRef 243 | run: | 244 | cd wasmedge-go-examples/go_ExternRef 245 | go get . 246 | go build 247 | ./externref funcs.wasm 248 | 249 | - name: go_AccessMemory 250 | run: | 251 | cd wasmedge-go-examples/go_AccessMemory 252 | go get . 253 | go build run.go 254 | ./run rust_access_memory_lib.wasm 255 | 256 | - name: go_AccessMemoryTinyGo 257 | run: | 258 | cd wasmedge-go-examples/go_AccessMemoryTinyGo 259 | go get . 260 | go build run.go 261 | ./run fib.wasm 262 | 263 | - name: go_MemoryGreet 264 | run: | 265 | cd wasmedge-go-examples/go_MemoryGreet 266 | go get . 267 | go build greet_memory.go 268 | ./greet_memory rust_memory_greet_lib.wasm 269 | 270 | - name: go_MemoryGreetTinyGo 271 | run: | 272 | cd wasmedge-go-examples/go_MemoryGreetTinyGo 273 | go get . 274 | go build greet_memory.go 275 | ./greet_memory greet.wasm 276 | 277 | - name: go_BindgenFuncs 278 | run: | 279 | cd wasmedge-go-examples/go_BindgenFuncs 280 | go get . 281 | go build 282 | ./bindgen_funcs rust_bindgen_funcs_lib.wasm 283 | 284 | # Not to run this example in interpreter mode to reduce CI time. 285 | #- name: go_BindgenKmeans 286 | # run: | 287 | # cd wasmedge-go-examples/go_BindgenKmeans 288 | # go get . 289 | # go build 290 | # ./bindgen_kmeans rust_bindgen_kmeans_lib.wasm 291 | 292 | - name: go_BindgenWasi 293 | run: | 294 | cd wasmedge-go-examples/go_BindgenWasi 295 | go get . 296 | go build 297 | ./bindgen_wasi rust_bindgen_wasi_lib.wasm 298 | 299 | - name: go_Mobilenet 300 | run: | 301 | cd wasmedge-go-examples/go_Mobilenet 302 | go get . 303 | go build 304 | ./mobilenet rust_mobilenet_lib.wasm grace_hopper.jpg 305 | 306 | - name: go_MobilenetBirds 307 | run: | 308 | cd wasmedge-go-examples/go_MobilenetBirds 309 | go get . 310 | go build 311 | ./mobilenet_birds rust_mobilenet_birds_lib.wasm PurpleGallinule.jpg 312 | 313 | - name: go_MobilenetFood 314 | run: | 315 | cd wasmedge-go-examples/go_MobilenetFood 316 | go get . 317 | go build 318 | ./mobilenet_food rust_mobilenet_food_lib.wasm food.jpg 319 | 320 | - name: go_MobilenetInsects 321 | run: | 322 | cd wasmedge-go-examples/go_MobilenetInsects 323 | go get . 324 | go build 325 | ./mobilenet_insects rust_mobilenet_insects_lib.wasm ladybug.jpg 326 | 327 | - name: go_MobilenetPlants 328 | run: | 329 | cd wasmedge-go-examples/go_MobilenetPlants 330 | go get . 331 | go build 332 | ./mobilenet_plants rust_mobilenet_plants_lib.wasm sunflower.jpg 333 | 334 | - name: go_mtcnn 335 | run: | 336 | cd wasmedge-go-examples/go_mtcnn 337 | go get . 338 | go build 339 | ./mtcnn rust_mtcnn.wasm mtcnn.pb solvay.jpg out.jpg 340 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: release 2 | 3 | on: 4 | push: 5 | tags: 6 | - "*" 7 | 8 | jobs: 9 | create: 10 | name: Create Release 11 | runs-on: ubuntu-latest 12 | container: 13 | image: wasmedge/wasmedge:latest 14 | outputs: 15 | version: ${{ steps.prep.outputs.version }} 16 | upload_url: ${{ steps.create_release.outputs.upload_url }} 17 | steps: 18 | - name: Checkout code 19 | uses: actions/checkout@v2 20 | - name: Get version 21 | id: prep 22 | run: | 23 | git config --global --add safe.directory $(pwd) 24 | echo ::set-output name=version::$(git describe --tag) 25 | - name: Create Release 26 | id: create_release 27 | uses: actions/create-release@v1 28 | env: 29 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 30 | with: 31 | tag_name: ${{ github.ref }} 32 | release_name: WasmEdge Go ${{ steps.prep.outputs.version }} 33 | body_path: .CurrentChangelog.md 34 | draft: true 35 | prerelease: true 36 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | #==============================================================================# 2 | # This file specifies intentionally untracked files that git should ignore. 3 | # See: http://www.kernel.org/pub/software/scm/git/docs/gitignore.html 4 | # 5 | # This file is intentionally different from the output of `git svn show-ignore`, 6 | # as most of those are useless. 7 | #==============================================================================# 8 | 9 | #==============================================================================# 10 | # File extensions to be ignored anywhere in the tree. 11 | #==============================================================================# 12 | # Temp files created by most text editors. 13 | *~ 14 | # Merge files created by git. 15 | *.orig 16 | # Byte compiled python modules. 17 | *.pyc 18 | # vim swap files 19 | .*.sw? 20 | .sw? 21 | #OS X specific files. 22 | .DS_store 23 | 24 | # Nested build directory 25 | /build 26 | 27 | #==============================================================================# 28 | # Explicit files to ignore (only matches one). 29 | #==============================================================================# 30 | # Various tag programs 31 | /tags 32 | /TAGS 33 | /GPATH 34 | /GRTAGS 35 | /GSYMS 36 | /GTAGS 37 | .gitusers 38 | autom4te.cache 39 | cscope.files 40 | cscope.out 41 | autoconf/aclocal.m4 42 | autoconf/autom4te.cache 43 | /compile_commands.json 44 | # Visual Studio built-in CMake configuration 45 | /CMakeSettings.json 46 | # CLion project configuration 47 | /.idea 48 | 49 | #==============================================================================# 50 | # Directories to ignore (do not add trailing '/'s, they skip symlinks). 51 | #==============================================================================# 52 | # External projects that are tracked independently. 53 | projects/* 54 | !projects/*.* 55 | !projects/Makefile 56 | runtimes/* 57 | !runtimes/*.* 58 | # Sphinx build tree, if building in-source dir. 59 | docs/_build 60 | # VS2017 and VSCode config files. 61 | .vscode 62 | .vs 63 | # clangd index 64 | .clangd 65 | 66 | pkg/ 67 | target/ 68 | Cargo.lock 69 | -------------------------------------------------------------------------------- /Changelog.md: -------------------------------------------------------------------------------- 1 | ### v0.14.0 (2025-02-14) 2 | 3 | Breaking Changes: 4 | 5 | * Removed `wasmedge.ValType` and `wasmedge.RefType` const values, and introduce the `wasmedge.ValType` struct. 6 | * Added the `wasmedge.NewValTypeI32()` API to replace the `wasmedge.ValType_I32` const value. 7 | * Added the `wasmedge.NewValTypeI64()` API to replace the `wasmedge.ValType_I64` const value. 8 | * Added the `wasmedge.NewValTypeF32()` API to replace the `wasmedge.ValType_F32` const value. 9 | * Added the `wasmedge.NewValTypeF64()` API to replace the `wasmedge.ValType_F64` const value. 10 | * Added the `wasmedge.NewValTypeV128()` API to replace the `wasmedge.ValType_V128` const value. 11 | * Added the `wasmedge.NewValTypeFuncRef()` API to replace the `wasmedge.ValType_FuncRef` const value. 12 | * Added the `wasmedge.NewValTypeExternRef()` API to replace the `wasmedge.ValType_ExterunRef` const value. 13 | * Added the `(*wasmedge.ValType).IsEqual()` API to compare the equivalent of two value types. 14 | * Added the `(*wasmedge.ValType).IsI32()` API to specify the value type is `i32` or not. 15 | * Added the `(*wasmedge.ValType).IsI64()` API to specify the value type is `i64` or not. 16 | * Added the `(*wasmedge.ValType).IsF32()` API to specify the value type is `f32` or not. 17 | * Added the `(*wasmedge.ValType).IsF64()` API to specify the value type is `f64` or not. 18 | * Added the `(*wasmedge.ValType).IsV128()` API to specify the value type is `v128` or not. 19 | * Added the `(*wasmedge.ValType).IsFuncRef()` API to specify the value type is `funcref` or not. 20 | * Added the `(*wasmedge.ValType).IsExternRef()` API to specify the value type is `externref` or not. 21 | * Added the `(*wasmedge.ValType).IsRef()` API to specify the value type is a reference type or not. 22 | * Added the `(*wasmedge.ValType).IsRefNull()` API to specify the value type is a nullable reference type or not. 23 | * Updated the supported WASM proposals. 24 | * Added the `wasmedge.Proposal.GC`. 25 | * Added the `wasmedge.Proposal.RELAXED_SIMD`. 26 | * Added the `wasmedge.Proposal.COMPONENT_MODEL`. 27 | * Added the error return in `(*wasmedge.Global).SetValue()` API. 28 | * Applied the new `wasmedge.ValType` struct to all related APIs. 29 | * `wasmedge.NewFunctionType()` accepts the new `[]*wasmedge.ValType` for parameters now. 30 | * `(*wasmedge.FunctionType).GetParameters()` returns the new `[]*wasmedge.ValType` now. 31 | * `(*wasmedge.FunctionType).GetReturns()` returns the new `[]*wasmedge.ValType` now. 32 | * `wasmedge.NewTableType()` accepts the new `*wasmedge.ValType` instead of `wasmedge.RefType` for parameters now. 33 | * `(*wasmedge.TableType).GetRefType()` returns the new `*wasmedge.ValType` now. 34 | * `wasmedge.NewGlobalType()` accepts the new `*wasmedge.ValType` for parameters now. 35 | * `(*wasmedge.GlobalType).GetValType()` returns the new `*wasmedge.ValType` now. 36 | 37 | Features: 38 | 39 | * Updated to the [WasmEdge 0.14.0](https://github.com/WasmEdge/WasmEdge/releases/tag/0.14.0). 40 | * Added the new `(*wasmedge.Compiler).CompileBuffer()` API for compiling WASM from buffer. 41 | * Added the tag type and tag instance for the exception-handling proposal. 42 | * Added the `wasmedge.ExternType_Tag` const value. 43 | * Added the `wasmedge.TagType` struct for tag type. 44 | * Added the `(*wasmedge.TagType).GetFunctionType()` API. 45 | * Added the `wasmedge.Tag` struct for tag instance. 46 | * Added the `(*wasmedge.Tag).GetTagType()` API. 47 | * Added the `(*wasmedge.Module).FindTag()` API to retrieve exported tag instances from a module instance. 48 | * Added the `(*wasmedge.Module).ListTag()` API to list all exported tag instance names from a module instance. 49 | 50 | ### v0.13.5 (2025-02-04) 51 | 52 | This is the internal fix for WasmEdge. 53 | 54 | Features: 55 | 56 | * Updated to the [WasmEdge 0.13.5](https://github.com/WasmEdge/WasmEdge/releases/tag/0.13.5). 57 | 58 | ### v0.13.4 (2023-09-05) 59 | 60 | This is the internal fix for WasmEdge. 61 | 62 | Features: 63 | 64 | * Updated to the [WasmEdge 0.13.4](https://github.com/WasmEdge/WasmEdge/releases/tag/0.13.4). 65 | 66 | ### v0.13.3 (2023-09-05) 67 | 68 | This is the internal fix for WasmEdge. 69 | 70 | Features: 71 | 72 | * Updated to the [WasmEdge 0.13.3](https://github.com/WasmEdge/WasmEdge/releases/tag/0.13.3). 73 | 74 | ### v0.13.2 (2023-07-26) 75 | 76 | This is the internal fix for WasmEdge. 77 | 78 | Features: 79 | 80 | * Updated to the [WasmEdge 0.13.2](https://github.com/WasmEdge/WasmEdge/releases/tag/0.13.2). 81 | 82 | ### v0.13.1 (2023-07-25) 83 | 84 | This is the internal fix for WasmEdge. 85 | 86 | Features: 87 | 88 | * Updated to the [WasmEdge 0.13.1](https://github.com/WasmEdge/WasmEdge/releases/tag/0.13.1). 89 | 90 | ### v0.13.0 (2023-07-19) 91 | 92 | Breaking Changes: 93 | 94 | * Removed the WasmEdge extensions related APIs. Replaced by the corresponding plug-ins. 95 | * Removed `wasmedge.NewImageModule()` API. 96 | * Removed `wasmedge.NewTensorflowModule()` API. 97 | * Removed `wasmedge.NewTensorflowLiteModule()` API. 98 | * Fixed the `(wasmedge.Executor).Invoke()` API to remove the first `wasmedge.Store` parameter. 99 | * Added `wasmedge.RunWasmEdgeUnifiedCLI()` API. 100 | * Added `wasmedge.AsyncInvoke()` API. 101 | 102 | Features: 103 | 104 | * Updated to the [WasmEdge 0.13.0](https://github.com/WasmEdge/WasmEdge/releases/tag/0.13.0). 105 | 106 | ### v0.12.1 (2023-06-28) 107 | 108 | Features: 109 | 110 | * Updated to the [WasmEdge 0.12.1](https://github.com/WasmEdge/WasmEdge/releases/tag/0.12.1). 111 | 112 | ### v0.12.0 (2023-03-25) 113 | 114 | Breaking Changes: 115 | 116 | * `WasmEdge` updated. Please install the `WasmEdge 0.12.0` or newer version. 117 | * Removed the plug-in related module instance creation functions. 118 | * Developers can use the `wasmedge.Plugin` related APIs to find the plug-in and create the module instances. 119 | * Removed the `wasmedge.NewWasiNNModule()` API. 120 | * Removed the `wasmedge.NewWasiCryptoCommonModule()` API. 121 | * Removed the `wasmedge.NewWasiCryptoAsymmetricCommonModule()` API. 122 | * Removed the `wasmedge.NewWasiCryptoKxModule()` API. 123 | * Removed the `wasmedge.NewWasiCryptoSignaturesModule()` API. 124 | * Removed the `wasmedge.NewWasiCryptoSymmetricModule()` API. 125 | * Removed the `wasmedge.NewWasmEdgeProcessModule()` API. 126 | * Removed the plug-in related `wasmedge.HostRegistration` const values. 127 | * The `wasmedge.VM` object will automatically load the module instances of the plug-ins. 128 | * Removed the `wasmedge.WasmEdge_PROCESS`. 129 | * Removed the `wasmedge.WasiNN`. 130 | * Removed the `wasmedge.WasiCrypto_Common`. 131 | * Removed the `wasmedge.WasiCrypto_AsymmetricCommon`. 132 | * Removed the `wasmedge.WasiCrypto_Kx`. 133 | * Removed the `wasmedge.WasiCrypto_Signatures`. 134 | * Removed the `wasmedge.WasiCrypto_Symmetric`. 135 | 136 | Features: 137 | 138 | * Updated to the [WasmEdge 0.12.0](https://github.com/WasmEdge/WasmEdge/releases/tag/0.12.0). 139 | * Added new APIs. 140 | * Added the `(*wasmedge.Module).GetName()` API to retrieve the module instance exported name. 141 | * Added the plug-in related APIs. 142 | * Added the `wasmedge.Plugin` struct. 143 | * Added the `wasmedge.LoadPluginFromPath()` API. 144 | * Added the `wasmedge.ListPlugins()` API. 145 | * Added the `wasmedge.FindPlugin()` API. 146 | * Added the `(*wasmedge.Plugin).ListModule()` API. 147 | * Added the `(*wasmedge.Plugin).CreateModule()` API. 148 | 149 | ### v0.11.2 (2022-11-03) 150 | 151 | Breaking Changes: 152 | 153 | * `WasmEdge` updated. Please install the `WasmEdge 0.11.2` or newer version. 154 | 155 | Features: 156 | 157 | * Updated to the [WasmEdge 0.11.2](https://github.com/WasmEdge/WasmEdge/releases/tag/0.11.2). 158 | * Added new APIs. 159 | * Added `wasmedge.SetLogOff()` to turn off the logging. 160 | * Added `(*wasmedge.Configure).SetForceInterpreter()` to set the forcibly interpreter mode in configuration. 161 | * Added `(*wasmedge.Configure).IsForceInterpreter()` to retrieve the forcibly interpreter mode setting in configuration. 162 | 163 | ### v0.11.1 (2022-10-28) 164 | 165 | Breaking Changes: 166 | 167 | * `WasmEdge` updated. Please install the `WasmEdge 0.11.1` or newer version. 168 | 169 | Features: 170 | 171 | * Updated to the [WasmEdge 0.11.1](https://github.com/WasmEdge/WasmEdge/releases/tag/0.11.1). 172 | 173 | ### v0.11.0 (2022-08-31) 174 | 175 | Breaking Changes: 176 | 177 | * `WasmEdge` updated. Please install the `WasmEdge 0.11.0` or newer version. 178 | * `CallingFrame` in host functions. 179 | * The second parameter of host functions are replaced by `CallingFrame`. 180 | * Developers can use the `(*wasmedge.CallingFrame).GetExecutor()` to get the currently used executor. 181 | * Developers can use the `(*wasmedge.CallingFrame).GetModule()` to get the module instance on the top frame of the stack. 182 | * Developers can use the `(*wasmedge.CallingFrame).GetMemoryByIndex()` to get the memory instance by index. 183 | * For simply getting the memory index as previous, developers can use the `GetMemoryByIndex(0)`. 184 | 185 | Features: 186 | 187 | * Updated to the [WasmEdge 0.11.0](https://github.com/WasmEdge/WasmEdge/releases/tag/0.11.0). 188 | * Supported user-defined error codes. 189 | * Developers can use the `wasmedge.NewResult()` API to create and return the result with user-defined error code. 190 | 191 | ### v0.10.1 (2022-08-02) 192 | 193 | Fixed issues: 194 | 195 | * Supported the platforms with only `tensorflow-lite`. Please build with the `tensorflowlite` tags: `go build --tags tensorflowlite`. 196 | 197 | Features: 198 | 199 | * Updated to the [WasmEdge 0.10.1](https://github.com/WasmEdge/WasmEdge/releases/tag/0.10.1). 200 | * Supported the `threads` proposal and its data structures. 201 | 202 | ### v0.10.0 (2022-05-26) 203 | 204 | Breaking Changes: 205 | 206 | * `WasmEdge` updated. Please install the `WasmEdge 0.10.0` or newer version. 207 | * The `Module`-based resource management. 208 | * The `Executor` will output a `Module` instance after instantiation now. Developers have the responsibility to destroy them by `(*wasmedge.Module).Release()` API. 209 | * Merged the `ImportObject` into the `Module`. 210 | * Removed the `ImportObject` structure. 211 | * `FuncRef` mechanism changes. 212 | * For the better performance and security, the `FuncRef` related APIs used the `*wasmedge.Function` for the parameters and returns. 213 | * API changes. 214 | * `wasmedge.NewFuncRef()` is changed to use the `*Function` as it's argument. 215 | * Added `(wasmedge.FuncRef).GetRef()` to retrieve the `*Function`. 216 | * Renamed `wasmedge.NewImportObject()` to `wasmedge.NewModule()`. 217 | * Renamed `(*wasmedge.ImportObject).Release()` to `(*wasmedge.Module).Release()`. 218 | * Renamed `(*wasmedge.ImportObject).AddFunction()` to `(*wasmedge.Module).AddFunction()`. 219 | * Renamed `(*wasmedge.ImportObject).AddTable()` to `(*wasmedge.Module).AddTable()`. 220 | * Renamed `(*wasmedge.ImportObject).AddMemory()` to `(*wasmedge.Module).AddMemory()`. 221 | * Renamed `(*wasmedge.ImportObject).AddGlobal()` to `(*wasmedge.Module).AddGlobal()`. 222 | * Renamed `(*wasmedge.ImportObject).NewWasiImportObject()` to `(*wasmedge.Module).NewWasiModule()`. 223 | * Renamed `(*wasmedge.ImportObject).NewWasmEdgeProcessImportObject()` to `(*wasmedge.Module).NewWasmEdgeProcessModule()`. 224 | * Renamed `(*wasmedge.ImportObject).InitWASI()` to `(*wasmedge.Module).InitWASI()`. 225 | * Renamed `(*wasmedge.ImportObject).InitWasmEdgeProcess()` to `(*wasmedge.Module).InitWasmEdgeProcess()`. 226 | * Renamed `(*wasmedge.ImportObject).WasiGetExitCode()` to `(*wasmedge.Module).WasiGetExitCode`. 227 | * Renamed `(*wasmedge.VM).RegisterImport()` to `(*wasmedge.VM).RegisterModule()`. 228 | * Renamed `(*wasmedge.VM).GetImportObject()` to `(*wasmedge.VM).GetImportModule()`. 229 | * `(*wasmedge.Store).ListFunction()` and `(*wasmedge.Store).ListFunctionRegistered()` is replaced by `(*wasmedge.Module).ListFunction()`. 230 | * `(*wasmedge.Store).ListTable()` and `(*wasmedge.Store).ListTableRegistered()` is replaced by `(*wasmedge.Module).ListTable()`. 231 | * `(*wasmedge.Store).ListMemory()` and `(*wasmedge.Store).ListMemoryRegistered()` is replaced by `(*wasmedge.Module).ListMemory()`. 232 | * `(*wasmedge.Store).ListGlobal()` and `(*wasmedge.Store).ListGlobalRegistered()` is replaced by `(*wasmedge.Module).ListGlobal()`. 233 | * `(*wasmedge.Store).FindFunction()` and `(*wasmedge.Store).FindFunctionRegistered()` is replaced by `(*wasmedge.Module).FindFunction()`. 234 | * `(*wasmedge.Store).FindTable()` and `(*wasmedge.Store).FindTableRegistered()` is replaced by `(*wasmedge.Module).FindTable()`. 235 | * `(*wasmedge.Store).FindMemory()` and `(*wasmedge.Store).FindMemoryRegistered()` is replaced by `(*wasmedge.Module).FindMemory()`. 236 | * `(*wasmedge.Store).FindGlobal()` and `(*wasmedge.Store).FindGlobalRegistered()` is replaced by `(*wasmedge.Module).FindGlobal()`. 237 | * Temporarily removed the `wasmedge_process` related APIs for supporting plug-in architecture in the future. 238 | * Removed the `(*wasmedge.Module).NewWasmEdgeProcessModule()` API. 239 | * Removed the `(*wasmedge.Module).InitWasmEdgeProcess()` API. 240 | 241 | Features: 242 | 243 | * Updated to the [WasmEdge 0.10.0](https://github.com/WasmEdge/WasmEdge/releases/tag/0.10.0). 244 | 245 | Documentation: 246 | 247 | * Updated the [documentation](https://wasmedge.org/book/en/embed/go/ref.html). 248 | 249 | ### v0.9.2 (2022-02-11) 250 | 251 | This version is the bug fixing for `WasmEdge-go v0.9.1`, and the version `v0.9.1` is retracted. 252 | Developers should install the [WasmEdge 0.9.1](https://github.com/WasmEdge/WasmEdge/releases/tag/0.9.1) for using this package. 253 | 254 | Fixed issues: 255 | 256 | * Fixed the lost headers. 257 | 258 | Features: 259 | 260 | * Updated to the [WasmEdge 0.9.1](https://github.com/WasmEdge/WasmEdge/releases/tag/0.9.1). 261 | * Added the new APIs. 262 | * Added the `Async` struct for asynchronize function execution. 263 | * Added `(*Async).WaitFor` API. 264 | * Added `(*Async).Cancel` API. 265 | * Added `(*Async).GetResult` API. 266 | * Added `(*Async).Release` API. 267 | * Added the asynchronize function execution in `VM`. 268 | * Added `(*VM).AsyncRunWasmFile` API. 269 | * Added `(*VM).AsyncRunWasmBuffer` API. 270 | * Added `(*VM).AsyncRunWasmAST` API. 271 | * Added `(*VM).AsyncExecute` API. 272 | * Added `(*VM).AsyncExecuteRegistered` API. 273 | * Synchronized and Updated the `Proposal` order with `WasmEdge 0.9.1`. 274 | 275 | ### v0.9.1 (2022-02-10) (Retract) 276 | 277 | Features: 278 | 279 | * Updated to the [WasmEdge 0.9.1](https://github.com/WasmEdge/WasmEdge/releases/tag/0.9.1). 280 | * Added the new APIs. 281 | * Added the `Async` struct for asynchronize function execution. 282 | * Added `(*Async).WaitFor` API. 283 | * Added `(*Async).Cancel` API. 284 | * Added `(*Async).GetResult` API. 285 | * Added `(*Async).Release` API. 286 | * Added the asynchronize function execution in `VM`. 287 | * Added `(*VM).AsyncRunWasmFile` API. 288 | * Added `(*VM).AsyncRunWasmBuffer` API. 289 | * Added `(*VM).AsyncRunWasmAST` API. 290 | * Added `(*VM).AsyncExecute` API. 291 | * Added `(*VM).AsyncExecuteRegistered` API. 292 | * Synchronized and Updated the `Proposal` order with `WasmEdge 0.9.1`. 293 | 294 | ### v0.9.0 (2021-12-09) 295 | 296 | Breaking Changes: 297 | 298 | * `WasmEdge` updated. Please install the `WasmEdge 0.9.0` or newer version. 299 | * Resource releasing behavior changes. 300 | * Renamed the `Delete` functions into `Release`. 301 | * Developers should call the `Release` methods of objects that created by themselves to release resources. 302 | * API changes. 303 | * AST 304 | * Renamed `(*AST).Delete` to `(*AST).Release`. 305 | * Limit 306 | * Removed `(*Limit).WithMaxVal`. 307 | * Configure 308 | * Renamed `(*Configure).Delete` to `(*Configure).Release`. 309 | * Renamed `(*Configure).SetCompilerInstructionCounting` to `(*Configure).SetStatisticsInstructionCounting`. 310 | * Renamed `(*Configure).IsCompilerInstructionCounting` to `(*Configure).IsStatisticsInstructionCounting`. 311 | * Renamed `(*Configure).SetCompilerCostMeasuring` to `(*Configure).SetStatisticsCostMeasuring`. 312 | * Renamed `(*Configure).IsCompilerCostMeasuring` to `(*Configure).IsStatisticsCostMeasuring`. 313 | * Statistics 314 | * Renamed `(*Statistics).Delete` to `(*Statistics).Release`. 315 | * Compiler 316 | * Renamed `(*Compiler).Delete` to `(*Compiler).Release`. 317 | * Loader 318 | * Renamed `(*Loader).Delete` to `(*Loader).Release`. 319 | * Validator 320 | * Renamed `(*Validator).Delete` to `(*Validator).Release`. 321 | * Interpreter: Renamed `Interpreter` to `Executor` 322 | * Renamed `NewInterpreter` to `NewExecutor`. 323 | * Renamed `NewInterpreterWithConfig` to `NewExecutorWithConfig`. 324 | * Renamed `NewInterpreterWithStatistics` to `NewExecutorWithStatistics`. 325 | * Renamed `NewInterpreterWithConfigAndStatistics` to `NewExecutorWithConfigAndStatistics`. 326 | * Renamed `(*Interpreter).Instantiate` to `(*Executor).Instantiate`. 327 | * Renamed `(*Interpreter).RegisterImport` to `(*Executor).RegisterImport`. 328 | * Renamed `(*Interpreter).RegisterModule` to `(*Executor).RegisterModule`. 329 | * Renamed `(*Interpreter).Invoke` to `(*Executor).Invoke`. 330 | * Renamed `(*Interpreter).InvokeRegistered` to `(*Executor).InvokeRegistered`. 331 | * Renamed `(*Interpreter).Delete` to `(*Executor).Release`. 332 | * Store 333 | * Renamed `(*Store).Delete` to `(*Store).Release`. 334 | * ImportObject 335 | * Removed the `additional` column in `NewImportObject`. The additional data to set into host functions are in the `NewFunction` now. 336 | * Removed the `dirs` column in `NewWasiImportObject` and `InitWasi`. Please combine the `dirs` list into the `preopens`. 337 | * Renamed `(*ImportObject).Delete` to `(*ImportObject).Release`. 338 | * Renamed `(*ImportObject).AddHostFunction` to `(*ImportObject).AddFunction`. 339 | * Instances 340 | * Merged `HostFunction` into `Function`. 341 | * Renamed `NewHostFunction` to `NewFunction`. 342 | * Renamed `(*HostFunction).Delete` to `(*Function).Release`. 343 | * Added the `additional` column in `NewFunction`. 344 | * Modified the `NewTable` API. 345 | * Renamed `(*Table).Delete` to `(*Table).Release`. 346 | * Modified the `NewMemory` API. 347 | * Renamed `(*Memory).Delete` to `(*Memory).Release`. 348 | * Modified the `NewGlobal` API. 349 | * Renamed `(*Global).Delete` to `(*Global).Release`. 350 | 351 | Features: 352 | 353 | * Updated to the [WasmEdge 0.9.0](https://github.com/WasmEdge/WasmEdge/releases/tag/0.9.0). 354 | * Added the new APIs. 355 | * Added the CI for testing with [WasmEdge-go-examples](https://github.com/second-state/WasmEdge-go-examples/). 356 | 357 | Fixed issues: 358 | 359 | * Fixed the bugs in the load-WASM-from-buffer functions. 360 | * Fixed the bugs in bindgen execution functions. 361 | * Fixed the memory issue in `(*Memory).GetData`. Wrap the memory instead of copying. 362 | 363 | Documentation: 364 | 365 | * Updated the installation guide. 366 | * Added the [quick start guide](https://github.com/second-state/WasmEdge-go/blob/master/docs/go_api.md). 367 | 368 | ### v0.8.2 (2021-09-09) 369 | 370 | Features: 371 | 372 | * Updated to the [WasmEdge 0.8.2](https://github.com/WasmEdge/WasmEdge/releases/tag/0.8.2). 373 | * Added the CI for build testing with every tags. 374 | 375 | Fixed issues: 376 | 377 | * Fixed the GC slice in host function implementation. 378 | 379 | Docmentation: 380 | 381 | * Added the golang version notification. 382 | * Added the example links. 383 | 384 | ### v0.8.1 (2021-06-25) 385 | 386 | Features: 387 | 388 | * Updated to the [WasmEdge 0.8.1](https://github.com/WasmEdge/WasmEdge/releases/tag/0.8.1). 389 | * WasmEdge Golang binding for C API 390 | * Added the new APIs about compiler options. 391 | * Added the new APIs about `wasmedge_process` settings. 392 | 393 | ### v0.8.0 (2021-06-01) 394 | 395 | Features: 396 | 397 | * WasmEdge Golang binding for C API 398 | * Please refer to the [README](https://github.com/second-state/WasmEdge-go/blob/master/README.md) for installation. 399 | * Update to the [WasmEdge 0.8.0](https://github.com/WasmEdge/WasmEdge/releases/tag/0.8.0). 400 | * WasmEdge-go for tensorflow extension 401 | * The extension of [WasmEdge-tensorflow](https://github.com/second-state/WasmEdge-tensorflow) for supplying the tensorflow related host functions. 402 | * Please refer to the [MTCNN](https://github.com/second-state/WasmEdge-go-examples/tree/master/go_mtcnn) example. 403 | * WasmEdge-go for image extension 404 | * The extension of [WasmEdge-image](https://github.com/second-state/WasmEdge-image) for supplying the image related host functions. 405 | * Wasm-bindgen for Golang 406 | * Support Wasm-bindgen in WasmEdge-go. 407 | * Please refer to the [BindgenFuncs](https://github.com/second-state/WasmEdge-go-examples/tree/master/go_BindgenFuncs) example. 408 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WasmEdge for Go Package 2 | 3 | The [WasmEdge](https://github.com/WasmEdge/WasmEdge) is a high performance WebAssembly runtime optimized for server side applications. This project provides a [golang](https://golang.org/) package for accessing to WasmEdge. 4 | 5 | * For a complete tutorial, please read the article [Extend Your Golang App with Embedded WebAssembly Functions in WasmEdge](https://www.secondstate.io/articles/extend-golang-app-with-webassembly-rust/), which demonstrates how to embed a Wasm function and how to embed a full Wasm program from the Golang app. 6 | * WasmEdge in real-time data strems: [AI Inference for Real-time Data Streams with WasmEdge and YoMo](https://www.secondstate.io/articles/yomo-wasmedge-real-time-data-streams/) 7 | * For more examples, please go to the [WasmEdge-go-examples repo](https://github.com/second-state/WasmEdge-go-examples). Contributing your own example is much appreciated. 8 | 9 | ## Getting Started 10 | 11 | The `WasmEdge-go` requires `golang` version >= `1.22`. Please check your `golang` version before installation. 12 | Developers can [download golang here](https://golang.org/dl/). 13 | 14 | ```bash 15 | $ go version 16 | go version go1.23.1 linux/amd64 17 | ``` 18 | 19 | Developers must [install the WasmEdge shared library](https://wasmedge.org/docs/start/install) with the same `WasmEdge-go` release version. 20 | 21 | ```bash 22 | curl -sSf https://raw.githubusercontent.com/WasmEdge/WasmEdge/master/utils/install.sh | bash -s -- -v 0.14.0 23 | ``` 24 | 25 | For the developers need the `WasmEdge-TensorFlow` or `WasmEdge-Image` plug-ins for `WasmEdge-go`, please install the `WasmEdge` with the corresponding plug-ins: 26 | 27 | ```bash 28 | curl -sSf https://raw.githubusercontent.com/WasmEdge/WasmEdge/master/utils/install.sh | bash -s -- --plugins wasmedge_tensorflow wasmedge_tensorflowlite wasmedge_image -v 0.14.0 29 | ``` 30 | 31 | > Note: Please refer to the [install guide for plug-ins](https://wasmedge.org/docs/start/install/#install-wasmedge-plug-ins-and-dependencies) to check that you've installed the plug-ins with their dependencies. 32 | 33 | For examples, please refer to the [example repository](https://github.com/second-state/WasmEdge-go-examples/). 34 | 35 | ## WasmEdge-go Documentation 36 | 37 | Please refer to the [API Documentation](https://wasmedge.org/docs/embed/go/reference/latest) for details. 38 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/second-state/WasmEdge-go 2 | 3 | go 1.16 4 | 5 | // Lost header in v0.9.1 version. Please use the WasmEdge-go v0.9.2 for WasmEdge 0.9.1. 6 | retract v0.9.1 7 | -------------------------------------------------------------------------------- /wasmedge/ast.go: -------------------------------------------------------------------------------- 1 | package wasmedge 2 | 3 | // #include 4 | import "C" 5 | 6 | type ExternType C.enum_WasmEdge_ExternalType 7 | 8 | const ( 9 | ExternType_Function = ExternType(C.WasmEdge_ExternalType_Function) 10 | ExternType_Table = ExternType(C.WasmEdge_ExternalType_Table) 11 | ExternType_Memory = ExternType(C.WasmEdge_ExternalType_Memory) 12 | ExternType_Global = ExternType(C.WasmEdge_ExternalType_Global) 13 | ExternType_Tag = ExternType(C.WasmEdge_ExternalType_Tag) 14 | ) 15 | 16 | type AST struct { 17 | _inner *C.WasmEdge_ASTModuleContext 18 | _own bool 19 | } 20 | 21 | type FunctionType struct { 22 | _inner *C.WasmEdge_FunctionTypeContext 23 | _own bool 24 | } 25 | 26 | type TableType struct { 27 | _inner *C.WasmEdge_TableTypeContext 28 | _own bool 29 | } 30 | 31 | type MemoryType struct { 32 | _inner *C.WasmEdge_MemoryTypeContext 33 | _own bool 34 | } 35 | 36 | type TagType struct { 37 | _inner *C.WasmEdge_TagTypeContext 38 | _own bool 39 | } 40 | 41 | type GlobalType struct { 42 | _inner *C.WasmEdge_GlobalTypeContext 43 | _own bool 44 | } 45 | 46 | type ImportType struct { 47 | _inner *C.WasmEdge_ImportTypeContext 48 | _ast *C.WasmEdge_ASTModuleContext 49 | _own bool 50 | } 51 | 52 | type ExportType struct { 53 | _inner *C.WasmEdge_ExportTypeContext 54 | _ast *C.WasmEdge_ASTModuleContext 55 | _own bool 56 | } 57 | 58 | func (self *AST) ListImports() []*ImportType { 59 | if self._inner != nil { 60 | var imptype []*ImportType 61 | var cimptype []*C.WasmEdge_ImportTypeContext 62 | ltypes := C.WasmEdge_ASTModuleListImportsLength(self._inner) 63 | if uint(ltypes) > 0 { 64 | imptype = make([]*ImportType, uint(ltypes)) 65 | cimptype = make([]*C.WasmEdge_ImportTypeContext, uint(ltypes)) 66 | C.WasmEdge_ASTModuleListImports(self._inner, &(cimptype[0]), ltypes) 67 | for i, val := range cimptype { 68 | imptype[i] = &ImportType{} 69 | imptype[i]._inner = val 70 | imptype[i]._ast = self._inner 71 | imptype[i]._own = false 72 | } 73 | return imptype 74 | } 75 | } 76 | return nil 77 | } 78 | 79 | func (self *AST) ListExports() []*ExportType { 80 | if self._inner != nil { 81 | var exptype []*ExportType 82 | var cexptype []*C.WasmEdge_ExportTypeContext 83 | ltypes := C.WasmEdge_ASTModuleListExportsLength(self._inner) 84 | if uint(ltypes) > 0 { 85 | exptype = make([]*ExportType, uint(ltypes)) 86 | cexptype = make([]*C.WasmEdge_ExportTypeContext, uint(ltypes)) 87 | C.WasmEdge_ASTModuleListExports(self._inner, &(cexptype[0]), ltypes) 88 | for i, val := range cexptype { 89 | exptype[i] = &ExportType{} 90 | exptype[i]._inner = val 91 | exptype[i]._ast = self._inner 92 | exptype[i]._own = false 93 | } 94 | return exptype 95 | } 96 | } 97 | return nil 98 | } 99 | 100 | func (self *AST) Release() { 101 | if self._own { 102 | C.WasmEdge_ASTModuleDelete(self._inner) 103 | } 104 | self._inner = nil 105 | self._own = false 106 | } 107 | 108 | func NewFunctionType(params []*ValType, returns []*ValType) *FunctionType { 109 | var cparams = make([]C.WasmEdge_ValType, len(params)) 110 | var creturns = make([]C.WasmEdge_ValType, len(returns)) 111 | for i, t := range params { 112 | cparams[i] = t._inner 113 | } 114 | for i, t := range returns { 115 | creturns[i] = t._inner 116 | } 117 | var ptrparams *C.WasmEdge_ValType = nil 118 | var ptrreturns *C.WasmEdge_ValType = nil 119 | if len(params) > 0 { 120 | ptrparams = &(cparams[0]) 121 | } 122 | if len(returns) > 0 { 123 | ptrreturns = &(creturns[0]) 124 | } 125 | ftype := C.WasmEdge_FunctionTypeCreate( 126 | ptrparams, C.uint32_t(len(params)), 127 | ptrreturns, C.uint32_t(len(returns))) 128 | if ftype == nil { 129 | return nil 130 | } 131 | return &FunctionType{_inner: ftype, _own: true} 132 | } 133 | 134 | func (self *FunctionType) GetParametersLength() uint { 135 | return uint(C.WasmEdge_FunctionTypeGetParametersLength(self._inner)) 136 | } 137 | 138 | func (self *FunctionType) GetParameters() []*ValType { 139 | if self._inner != nil { 140 | var valtype []*ValType 141 | var cvaltype []C.WasmEdge_ValType 142 | ltypes := C.WasmEdge_FunctionTypeGetParametersLength(self._inner) 143 | if uint(ltypes) > 0 { 144 | valtype = make([]*ValType, uint(ltypes)) 145 | cvaltype = make([]C.WasmEdge_ValType, uint(ltypes)) 146 | C.WasmEdge_FunctionTypeGetParameters(self._inner, &(cvaltype[0]), ltypes) 147 | for i, val := range cvaltype { 148 | valtype[i]._inner = val 149 | } 150 | return valtype 151 | } 152 | } 153 | return nil 154 | } 155 | 156 | func (self *FunctionType) GetReturnsLength() uint { 157 | return uint(C.WasmEdge_FunctionTypeGetReturnsLength(self._inner)) 158 | } 159 | 160 | func (self *FunctionType) GetReturns() []*ValType { 161 | if self._inner != nil { 162 | var valtype []*ValType 163 | var cvaltype []C.WasmEdge_ValType 164 | ltypes := C.WasmEdge_FunctionTypeGetReturnsLength(self._inner) 165 | if uint(ltypes) > 0 { 166 | valtype = make([]*ValType, uint(ltypes)) 167 | cvaltype = make([]C.WasmEdge_ValType, uint(ltypes)) 168 | C.WasmEdge_FunctionTypeGetReturns(self._inner, &(cvaltype[0]), ltypes) 169 | for i, val := range cvaltype { 170 | valtype[i]._inner = val 171 | } 172 | return valtype 173 | } 174 | } 175 | return nil 176 | } 177 | 178 | func (self *FunctionType) Release() { 179 | if self._own { 180 | C.WasmEdge_FunctionTypeDelete(self._inner) 181 | } 182 | self._inner = nil 183 | self._own = false 184 | } 185 | 186 | func NewTableType(rtype *ValType, lim *Limit) *TableType { 187 | climit := C.WasmEdge_Limit{ 188 | HasMax: C.bool(lim.hasmax), 189 | Shared: C.bool(lim.shared), 190 | Min: C.uint32_t(lim.min), 191 | Max: C.uint32_t(lim.max), 192 | } 193 | ttype := C.WasmEdge_TableTypeCreate(rtype._inner, climit) 194 | if ttype == nil { 195 | return nil 196 | } 197 | return &TableType{_inner: ttype, _own: true} 198 | } 199 | 200 | func (self *TableType) GetRefType() *ValType { 201 | return &ValType{_inner: C.WasmEdge_TableTypeGetRefType(self._inner)} 202 | } 203 | 204 | func (self *TableType) GetLimit() *Limit { 205 | if self._inner != nil { 206 | climit := C.WasmEdge_TableTypeGetLimit(self._inner) 207 | return &Limit{ 208 | min: uint(climit.Min), 209 | max: uint(climit.Max), 210 | hasmax: bool(climit.HasMax), 211 | shared: bool(climit.Shared), 212 | } 213 | } 214 | return nil 215 | } 216 | 217 | func (self *TableType) Release() { 218 | if self._own { 219 | C.WasmEdge_TableTypeDelete(self._inner) 220 | } 221 | self._inner = nil 222 | self._own = false 223 | } 224 | 225 | func NewMemoryType(lim *Limit) *MemoryType { 226 | climit := C.WasmEdge_Limit{ 227 | HasMax: C.bool(lim.hasmax), 228 | Shared: C.bool(lim.shared), 229 | Min: C.uint32_t(lim.min), 230 | Max: C.uint32_t(lim.max), 231 | } 232 | mtype := C.WasmEdge_MemoryTypeCreate(climit) 233 | if mtype == nil { 234 | return nil 235 | } 236 | return &MemoryType{_inner: mtype, _own: true} 237 | } 238 | 239 | func (self *MemoryType) GetLimit() *Limit { 240 | if self._inner != nil { 241 | climit := C.WasmEdge_MemoryTypeGetLimit(self._inner) 242 | return &Limit{ 243 | min: uint(climit.Min), 244 | max: uint(climit.Max), 245 | hasmax: bool(climit.HasMax), 246 | shared: bool(climit.Shared), 247 | } 248 | } 249 | return nil 250 | } 251 | 252 | func (self *MemoryType) Release() { 253 | if self._own { 254 | C.WasmEdge_MemoryTypeDelete(self._inner) 255 | } 256 | self._inner = nil 257 | self._own = false 258 | } 259 | 260 | func (self *TagType) GetFunctionType() *FunctionType { 261 | ftype := C.WasmEdge_TagTypeGetFunctionType(self._inner) 262 | if ftype == nil { 263 | return nil 264 | } 265 | return &FunctionType{_inner: ftype, _own: false} 266 | } 267 | 268 | func NewGlobalType(vtype *ValType, vmut ValMut) *GlobalType { 269 | cvmut := C.enum_WasmEdge_Mutability(vmut) 270 | gtype := C.WasmEdge_GlobalTypeCreate(vtype._inner, cvmut) 271 | if gtype == nil { 272 | return nil 273 | } 274 | return &GlobalType{_inner: gtype, _own: true} 275 | } 276 | 277 | func (self *GlobalType) GetValType() *ValType { 278 | return &ValType{_inner: C.WasmEdge_GlobalTypeGetValType(self._inner)} 279 | } 280 | 281 | func (self *GlobalType) GetMutability() ValMut { 282 | return ValMut(C.WasmEdge_GlobalTypeGetMutability(self._inner)) 283 | } 284 | 285 | func (self *GlobalType) Release() { 286 | if self._own { 287 | C.WasmEdge_GlobalTypeDelete(self._inner) 288 | } 289 | self._inner = nil 290 | self._own = false 291 | } 292 | 293 | func (self *ImportType) GetExternalType() ExternType { 294 | return ExternType(C.WasmEdge_ImportTypeGetExternalType(self._inner)) 295 | } 296 | 297 | func (self *ImportType) GetModuleName() string { 298 | return fromWasmEdgeString(C.WasmEdge_ImportTypeGetModuleName(self._inner)) 299 | } 300 | 301 | func (self *ImportType) GetExternalName() string { 302 | return fromWasmEdgeString(C.WasmEdge_ImportTypeGetExternalName(self._inner)) 303 | } 304 | 305 | func (self *ImportType) GetExternalValue() interface{} { 306 | if self._inner == nil { 307 | return nil 308 | } 309 | switch self.GetExternalType() { 310 | case ExternType_Function: 311 | return &FunctionType{ 312 | _inner: C.WasmEdge_ImportTypeGetFunctionType(self._ast, self._inner), 313 | _own: false, 314 | } 315 | case ExternType_Table: 316 | return &TableType{ 317 | _inner: C.WasmEdge_ImportTypeGetTableType(self._ast, self._inner), 318 | _own: false, 319 | } 320 | case ExternType_Memory: 321 | return &MemoryType{ 322 | _inner: C.WasmEdge_ImportTypeGetMemoryType(self._ast, self._inner), 323 | _own: false, 324 | } 325 | case ExternType_Global: 326 | return &GlobalType{ 327 | _inner: C.WasmEdge_ImportTypeGetGlobalType(self._ast, self._inner), 328 | _own: false, 329 | } 330 | case ExternType_Tag: 331 | return &TagType{ 332 | _inner: C.WasmEdge_ImportTypeGetTagType(self._ast, self._inner), 333 | _own: false, 334 | } 335 | } 336 | panic("Unknown external type") 337 | } 338 | 339 | func (self *ExportType) GetExternalType() ExternType { 340 | return ExternType(C.WasmEdge_ExportTypeGetExternalType(self._inner)) 341 | } 342 | 343 | func (self *ExportType) GetExternalName() string { 344 | return fromWasmEdgeString(C.WasmEdge_ExportTypeGetExternalName(self._inner)) 345 | } 346 | 347 | func (self *ExportType) GetExternalValue() interface{} { 348 | if self._inner == nil { 349 | return nil 350 | } 351 | switch self.GetExternalType() { 352 | case ExternType_Function: 353 | return &FunctionType{ 354 | _inner: C.WasmEdge_ExportTypeGetFunctionType(self._ast, self._inner), 355 | _own: false, 356 | } 357 | case ExternType_Table: 358 | return &TableType{ 359 | _inner: C.WasmEdge_ExportTypeGetTableType(self._ast, self._inner), 360 | _own: false, 361 | } 362 | case ExternType_Memory: 363 | return &MemoryType{ 364 | _inner: C.WasmEdge_ExportTypeGetMemoryType(self._ast, self._inner), 365 | _own: false, 366 | } 367 | case ExternType_Global: 368 | return &GlobalType{ 369 | _inner: C.WasmEdge_ExportTypeGetGlobalType(self._ast, self._inner), 370 | _own: false, 371 | } 372 | case ExternType_Tag: 373 | return &TagType{ 374 | _inner: C.WasmEdge_ExportTypeGetTagType(self._ast, self._inner), 375 | _own: false, 376 | } 377 | } 378 | panic("Unknown external type") 379 | } 380 | -------------------------------------------------------------------------------- /wasmedge/async.go: -------------------------------------------------------------------------------- 1 | package wasmedge 2 | 3 | // #include 4 | import "C" 5 | import ( 6 | "unsafe" 7 | ) 8 | 9 | type Async struct { 10 | _inner *C.WasmEdge_Async 11 | _own bool 12 | } 13 | 14 | func (self *Async) WaitFor(millisec int) bool { 15 | return bool(C.WasmEdge_AsyncWaitFor(self._inner, C.uint64_t(millisec))) 16 | } 17 | 18 | func (self *Async) Cancel() { 19 | C.WasmEdge_AsyncCancel(self._inner) 20 | } 21 | 22 | func (self *Async) GetResult() ([]interface{}, error) { 23 | arity := C.WasmEdge_AsyncGetReturnsLength(self._inner) 24 | creturns := make([]C.WasmEdge_Value, arity) 25 | var ptrreturns *C.WasmEdge_Value = nil 26 | if len(creturns) > 0 { 27 | ptrreturns = (*C.WasmEdge_Value)(unsafe.Pointer(&creturns[0])) 28 | } 29 | res := C.WasmEdge_AsyncGet(self._inner, ptrreturns, arity) 30 | if !C.WasmEdge_ResultOK(res) { 31 | return nil, newError(res) 32 | } 33 | return fromWasmEdgeValueSlide(creturns), nil 34 | } 35 | 36 | func (self *Async) Release() { 37 | if self._own { 38 | C.WasmEdge_AsyncDelete(self._inner) 39 | } 40 | self._inner = nil 41 | self._own = false 42 | } 43 | -------------------------------------------------------------------------------- /wasmedge/callframe.go: -------------------------------------------------------------------------------- 1 | package wasmedge 2 | 3 | // #include 4 | import "C" 5 | 6 | type CallingFrame struct { 7 | _inner *C.WasmEdge_CallingFrameContext 8 | } 9 | 10 | func (self *CallingFrame) GetExecutor() *Executor { 11 | cinst := C.WasmEdge_CallingFrameGetExecutor(self._inner) 12 | if cinst == nil { 13 | return nil 14 | } 15 | return &Executor{_inner: cinst, _own: false} 16 | } 17 | 18 | func (self *CallingFrame) GetModule() *Module { 19 | cinst := C.WasmEdge_CallingFrameGetModuleInstance(self._inner) 20 | if cinst == nil { 21 | return nil 22 | } 23 | return &Module{_inner: cinst, _own: false} 24 | } 25 | 26 | func (self *CallingFrame) GetMemoryByIndex(idx int) *Memory { 27 | cinst := C.WasmEdge_CallingFrameGetMemoryInstance(self._inner, C.uint32_t(idx)) 28 | if cinst == nil { 29 | return nil 30 | } 31 | return &Memory{_inner: cinst, _own: false} 32 | } 33 | -------------------------------------------------------------------------------- /wasmedge/cgo.go: -------------------------------------------------------------------------------- 1 | package wasmedge 2 | 3 | /* 4 | #cgo linux LDFLAGS: -lwasmedge 5 | #cgo darwin LDFLAGS: -lwasmedge 6 | 7 | #include 8 | */ 9 | import "C" 10 | -------------------------------------------------------------------------------- /wasmedge/chostfunc.go: -------------------------------------------------------------------------------- 1 | package wasmedge 2 | 3 | /* 4 | #include 5 | 6 | // The gateway function 7 | WasmEdge_Result 8 | wasmedgego_HostFuncInvoke(void *Func, void *Data, 9 | const WasmEdge_CallingFrameContext *CallFrameCxt, 10 | const WasmEdge_Value *Params, const uint32_t ParamLen, 11 | WasmEdge_Value *Returns, const uint32_t ReturnLen) { 12 | WasmEdge_Result wasmedgego_HostFuncInvokeImpl( 13 | void *Func, void *Data, const WasmEdge_CallingFrameContext *CallFrameCxt, 14 | const WasmEdge_Value *Params, const uint32_t ParamLen, 15 | WasmEdge_Value *Returns, const uint32_t ReturnLen); 16 | return wasmedgego_HostFuncInvokeImpl(Func, Data, CallFrameCxt, Params, 17 | ParamLen, Returns, ReturnLen); 18 | } 19 | */ 20 | import "C" 21 | -------------------------------------------------------------------------------- /wasmedge/cli.go: -------------------------------------------------------------------------------- 1 | package wasmedge 2 | 3 | // #include 4 | import "C" 5 | 6 | func RunWasmEdgeAOTCompilerCLI(argv []string) int { 7 | cargv := toCStringArray(argv) 8 | var ptrcargv *(*C.char) = nil 9 | if len(cargv) > 0 { 10 | ptrcargv = &cargv[0] 11 | } 12 | ret := C.WasmEdge_Driver_Compiler(C.int(len(cargv)), ptrcargv) 13 | freeCStringArray(cargv) 14 | return int(ret) 15 | } 16 | 17 | func RunWasmEdgeCLI(argv []string) int { 18 | cargv := toCStringArray(argv) 19 | var ptrcargv *(*C.char) = nil 20 | if len(cargv) > 0 { 21 | ptrcargv = &cargv[0] 22 | } 23 | ret := C.WasmEdge_Driver_Tool(C.int(len(cargv)), ptrcargv) 24 | freeCStringArray(cargv) 25 | return int(ret) 26 | } 27 | 28 | func RunWasmEdgeUnifiedCLI(argv []string) int { 29 | cargv := toCStringArray(argv) 30 | var ptrcargv *(*C.char) = nil 31 | if len(cargv) > 0 { 32 | ptrcargv = &cargv[0] 33 | } 34 | ret := C.WasmEdge_Driver_UniTool(C.int(len(cargv)), ptrcargv) 35 | freeCStringArray(cargv) 36 | return int(ret) 37 | } 38 | -------------------------------------------------------------------------------- /wasmedge/compiler.go: -------------------------------------------------------------------------------- 1 | package wasmedge 2 | 3 | // #include 4 | // #include 5 | import "C" 6 | import ( 7 | "unsafe" 8 | ) 9 | 10 | type Compiler struct { 11 | _inner *C.WasmEdge_CompilerContext 12 | _own bool 13 | } 14 | 15 | func NewCompiler() *Compiler { 16 | compiler := C.WasmEdge_CompilerCreate(nil) 17 | if compiler == nil { 18 | return nil 19 | } 20 | return &Compiler{_inner: compiler, _own: true} 21 | } 22 | 23 | func NewCompilerWithConfig(conf *Configure) *Compiler { 24 | compiler := C.WasmEdge_CompilerCreate(conf._inner) 25 | if compiler == nil { 26 | return nil 27 | } 28 | return &Compiler{_inner: compiler, _own: true} 29 | } 30 | 31 | func (self *Compiler) Compile(inpath string, outpath string) error { 32 | cinpath := C.CString(inpath) 33 | coutpath := C.CString(outpath) 34 | defer C.free(unsafe.Pointer(cinpath)) 35 | defer C.free(unsafe.Pointer(coutpath)) 36 | res := C.WasmEdge_CompilerCompile(self._inner, cinpath, coutpath) 37 | if !C.WasmEdge_ResultOK(res) { 38 | return newError(res) 39 | } 40 | return nil 41 | } 42 | 43 | func (self *Compiler) CompileBuffer(buf []byte, outpath string) (error) { 44 | coutpath := C.CString(outpath) 45 | defer C.free(unsafe.Pointer(coutpath)) 46 | cbytes := C.WasmEdge_BytesWrap((*C.uint8_t)(unsafe.Pointer(&buf[0])), C.uint32_t(len(buf))) 47 | res := C.WasmEdge_CompilerCompileFromBytes(self._inner, cbytes, coutpath) 48 | if !C.WasmEdge_ResultOK(res) { 49 | return newError(res) 50 | } 51 | return nil 52 | } 53 | 54 | func (self *Compiler) Release() { 55 | if self._own { 56 | C.WasmEdge_CompilerDelete(self._inner) 57 | } 58 | self._inner = nil 59 | self._own = false 60 | } 61 | -------------------------------------------------------------------------------- /wasmedge/configure.go: -------------------------------------------------------------------------------- 1 | package wasmedge 2 | 3 | // #include 4 | import "C" 5 | 6 | type Proposal C.enum_WasmEdge_Proposal 7 | 8 | const ( 9 | IMPORT_EXPORT_MUT_GLOBALS = Proposal(C.WasmEdge_Proposal_ImportExportMutGlobals) 10 | NON_TRAP_FLOAT_TO_INT_CONVERSIONS = Proposal(C.WasmEdge_Proposal_NonTrapFloatToIntConversions) 11 | SIGN_EXTENSION_OPERATORS = Proposal(C.WasmEdge_Proposal_SignExtensionOperators) 12 | MULTI_VALUE = Proposal(C.WasmEdge_Proposal_MultiValue) 13 | BULK_MEMORY_OPERATIONS = Proposal(C.WasmEdge_Proposal_BulkMemoryOperations) 14 | REFERENCE_TYPES = Proposal(C.WasmEdge_Proposal_ReferenceTypes) 15 | SIMD = Proposal(C.WasmEdge_Proposal_SIMD) 16 | TAIL_CALL = Proposal(C.WasmEdge_Proposal_TailCall) 17 | EXTENDED_CONST = Proposal(C.WasmEdge_Proposal_ExtendedConst) 18 | FUNCTION_REFERENCES = Proposal(C.WasmEdge_Proposal_FunctionReferences) 19 | GC = Proposal(C.WasmEdge_Proposal_GC) 20 | MULTI_MEMORIES = Proposal(C.WasmEdge_Proposal_MultiMemories) 21 | THREADS = Proposal(C.WasmEdge_Proposal_Threads) 22 | RELAXED_SIMD = Proposal(C.WasmEdge_Proposal_RelaxSIMD) 23 | ANNOTATIONS = Proposal(C.WasmEdge_Proposal_Annotations) 24 | MEMORY64 = Proposal(C.WasmEdge_Proposal_Memory64) 25 | EXCEPTION_HANDLING = Proposal(C.WasmEdge_Proposal_ExceptionHandling) 26 | COMPONENT_MODEL = Proposal(C.WasmEdge_Proposal_Component) 27 | ) 28 | 29 | type HostRegistration C.enum_WasmEdge_HostRegistration 30 | 31 | const ( 32 | WASI = HostRegistration(C.WasmEdge_HostRegistration_Wasi) 33 | ) 34 | 35 | type CompilerOptimizationLevel C.enum_WasmEdge_CompilerOptimizationLevel 36 | 37 | const ( 38 | // Disable as many optimizations as possible. 39 | CompilerOptLevel_O0 = CompilerOptimizationLevel(C.WasmEdge_CompilerOptimizationLevel_O0) 40 | // Optimize quickly without destroying debuggability. 41 | CompilerOptLevel_O1 = CompilerOptimizationLevel(C.WasmEdge_CompilerOptimizationLevel_O1) 42 | // Optimize for fast execution as much as possible without triggering significant incremental compile time or code size growth. 43 | CompilerOptLevel_O2 = CompilerOptimizationLevel(C.WasmEdge_CompilerOptimizationLevel_O2) 44 | // Optimize for fast execution as much as possible. 45 | CompilerOptLevel_O3 = CompilerOptimizationLevel(C.WasmEdge_CompilerOptimizationLevel_O3) 46 | // Optimize for small code size as much as possible without triggering significant incremental compile time or execution time slowdowns. 47 | CompilerOptLevel_Os = CompilerOptimizationLevel(C.WasmEdge_CompilerOptimizationLevel_Os) 48 | /// Optimize for small code size as much as possible. 49 | CompilerOptLevel_Oz = CompilerOptimizationLevel(C.WasmEdge_CompilerOptimizationLevel_Oz) 50 | ) 51 | 52 | type CompilerOutputFormat C.enum_WasmEdge_CompilerOutputFormat 53 | 54 | const ( 55 | /// Native dynamic library format. 56 | CompilerOutputFormat_Native = CompilerOutputFormat(C.WasmEdge_CompilerOutputFormat_Native) 57 | /// WebAssembly with AOT compiled codes in custom section. 58 | CompilerOutputFormat_Wasm = CompilerOutputFormat(C.WasmEdge_CompilerOutputFormat_Wasm) 59 | ) 60 | 61 | type Configure struct { 62 | _inner *C.WasmEdge_ConfigureContext 63 | _own bool 64 | } 65 | 66 | func NewConfigure(params ...interface{}) *Configure { 67 | conf := C.WasmEdge_ConfigureCreate() 68 | if conf == nil { 69 | return nil 70 | } 71 | 72 | for _, val := range params { 73 | switch val.(type) { 74 | case Proposal: 75 | C.WasmEdge_ConfigureAddProposal(conf, C.enum_WasmEdge_Proposal(val.(Proposal))) 76 | case HostRegistration: 77 | C.WasmEdge_ConfigureAddHostRegistration(conf, C.enum_WasmEdge_HostRegistration(val.(HostRegistration))) 78 | default: 79 | panic("Wrong argument of NewConfigure()") 80 | } 81 | } 82 | 83 | return &Configure{_inner: conf, _own: true} 84 | } 85 | 86 | func (self *Configure) HasConfig(conf interface{}) bool { 87 | switch conf.(type) { 88 | case Proposal: 89 | return bool(C.WasmEdge_ConfigureHasProposal(self._inner, C.enum_WasmEdge_Proposal(conf.(Proposal)))) 90 | case HostRegistration: 91 | return bool(C.WasmEdge_ConfigureHasHostRegistration(self._inner, C.enum_WasmEdge_HostRegistration(conf.(HostRegistration)))) 92 | default: 93 | panic("Wrong argument of Configure.HasConfig()") 94 | } 95 | } 96 | 97 | func (self *Configure) AddConfig(conf interface{}) { 98 | switch conf.(type) { 99 | case Proposal: 100 | C.WasmEdge_ConfigureAddProposal(self._inner, C.enum_WasmEdge_Proposal(conf.(Proposal))) 101 | case HostRegistration: 102 | C.WasmEdge_ConfigureAddHostRegistration(self._inner, C.enum_WasmEdge_HostRegistration(conf.(HostRegistration))) 103 | default: 104 | panic("Wrong argument of Configure.AddConfig()") 105 | } 106 | } 107 | 108 | func (self *Configure) RemoveConfig(conf interface{}) { 109 | switch conf.(type) { 110 | case Proposal: 111 | C.WasmEdge_ConfigureRemoveProposal(self._inner, C.enum_WasmEdge_Proposal(conf.(Proposal))) 112 | case HostRegistration: 113 | C.WasmEdge_ConfigureRemoveHostRegistration(self._inner, C.enum_WasmEdge_HostRegistration(conf.(HostRegistration))) 114 | default: 115 | panic("Wrong argument of Configure.RemoveConfig()") 116 | } 117 | } 118 | 119 | func (self *Configure) SetMaxMemoryPage(pagesize uint) { 120 | C.WasmEdge_ConfigureSetMaxMemoryPage(self._inner, C.uint32_t(pagesize)) 121 | } 122 | 123 | func (self *Configure) GetMaxMemoryPage() uint { 124 | return uint(C.WasmEdge_ConfigureGetMaxMemoryPage(self._inner)) 125 | } 126 | 127 | func (self *Configure) SetForceInterpreter(isinterpreter bool) { 128 | C.WasmEdge_ConfigureSetForceInterpreter(self._inner, C.bool(isinterpreter)) 129 | } 130 | 131 | func (self *Configure) IsForceInterpreter() bool { 132 | return bool(C.WasmEdge_ConfigureIsForceInterpreter(self._inner)) 133 | } 134 | 135 | func (self *Configure) SetCompilerOptimizationLevel(level CompilerOptimizationLevel) { 136 | C.WasmEdge_ConfigureCompilerSetOptimizationLevel(self._inner, C.enum_WasmEdge_CompilerOptimizationLevel(level)) 137 | } 138 | 139 | func (self *Configure) GetCompilerOptimizationLevel() CompilerOptimizationLevel { 140 | return CompilerOptimizationLevel(C.WasmEdge_ConfigureCompilerGetOptimizationLevel(self._inner)) 141 | } 142 | 143 | func (self *Configure) SetCompilerOutputFormat(format CompilerOutputFormat) { 144 | C.WasmEdge_ConfigureCompilerSetOutputFormat(self._inner, C.enum_WasmEdge_CompilerOutputFormat(format)) 145 | } 146 | 147 | func (self *Configure) GetCompilerOutputFormat() CompilerOutputFormat { 148 | return CompilerOutputFormat(C.WasmEdge_ConfigureCompilerGetOutputFormat(self._inner)) 149 | } 150 | 151 | func (self *Configure) SetCompilerDumpIR(isdump bool) { 152 | C.WasmEdge_ConfigureCompilerSetDumpIR(self._inner, C.bool(isdump)) 153 | } 154 | 155 | func (self *Configure) IsCompilerDumpIR() bool { 156 | return bool(C.WasmEdge_ConfigureCompilerIsDumpIR(self._inner)) 157 | } 158 | 159 | func (self *Configure) SetCompilerGenericBinary(isgeneric bool) { 160 | C.WasmEdge_ConfigureCompilerSetGenericBinary(self._inner, C.bool(isgeneric)) 161 | } 162 | 163 | func (self *Configure) IsCompilerGenericBinary() bool { 164 | return bool(C.WasmEdge_ConfigureCompilerIsGenericBinary(self._inner)) 165 | } 166 | 167 | func (self *Configure) SetStatisticsInstructionCounting(iscount bool) { 168 | C.WasmEdge_ConfigureStatisticsSetInstructionCounting(self._inner, C.bool(iscount)) 169 | } 170 | 171 | func (self *Configure) IsStatisticsInstructionCounting() bool { 172 | return bool(C.WasmEdge_ConfigureStatisticsIsInstructionCounting(self._inner)) 173 | } 174 | 175 | func (self *Configure) SetStatisticsTimeMeasuring(ismeasure bool) { 176 | C.WasmEdge_ConfigureStatisticsSetTimeMeasuring(self._inner, C.bool(ismeasure)) 177 | } 178 | 179 | func (self *Configure) IsStatisticsTimeMeasuring() bool { 180 | return bool(C.WasmEdge_ConfigureStatisticsIsTimeMeasuring(self._inner)) 181 | } 182 | 183 | func (self *Configure) SetStatisticsCostMeasuring(ismeasure bool) { 184 | C.WasmEdge_ConfigureStatisticsSetCostMeasuring(self._inner, C.bool(ismeasure)) 185 | } 186 | 187 | func (self *Configure) IsStatisticsCostMeasuring() bool { 188 | return bool(C.WasmEdge_ConfigureStatisticsIsCostMeasuring(self._inner)) 189 | } 190 | 191 | func (self *Configure) Release() { 192 | if self._own { 193 | C.WasmEdge_ConfigureDelete(self._inner) 194 | } 195 | self._inner = nil 196 | self._own = false 197 | } 198 | -------------------------------------------------------------------------------- /wasmedge/executor.go: -------------------------------------------------------------------------------- 1 | package wasmedge 2 | 3 | // #include 4 | import "C" 5 | import ( 6 | "unsafe" 7 | ) 8 | 9 | type Executor struct { 10 | _inner *C.WasmEdge_ExecutorContext 11 | _own bool 12 | } 13 | 14 | func NewExecutor() *Executor { 15 | executor := C.WasmEdge_ExecutorCreate(nil, nil) 16 | if executor == nil { 17 | return nil 18 | } 19 | return &Executor{_inner: executor, _own: true} 20 | } 21 | 22 | func NewExecutorWithConfig(conf *Configure) *Executor { 23 | executor := C.WasmEdge_ExecutorCreate(conf._inner, nil) 24 | if executor == nil { 25 | return nil 26 | } 27 | return &Executor{_inner: executor, _own: true} 28 | } 29 | 30 | func NewExecutorWithStatistics(stat *Statistics) *Executor { 31 | executor := C.WasmEdge_ExecutorCreate(nil, stat._inner) 32 | if executor == nil { 33 | return nil 34 | } 35 | return &Executor{_inner: executor, _own: true} 36 | } 37 | 38 | func NewExecutorWithConfigAndStatistics(conf *Configure, stat *Statistics) *Executor { 39 | executor := C.WasmEdge_ExecutorCreate(conf._inner, stat._inner) 40 | if executor == nil { 41 | return nil 42 | } 43 | return &Executor{_inner: executor, _own: true} 44 | } 45 | 46 | func (self *Executor) Instantiate(store *Store, ast *AST) (*Module, error) { 47 | var module *C.WasmEdge_ModuleInstanceContext = nil 48 | res := C.WasmEdge_ExecutorInstantiate(self._inner, &module, store._inner, ast._inner) 49 | if !C.WasmEdge_ResultOK(res) { 50 | return nil, newError(res) 51 | } 52 | return &Module{_inner: module, _own: true}, nil 53 | } 54 | 55 | func (self *Executor) Register(store *Store, ast *AST, modname string) (*Module, error) { 56 | var module *C.WasmEdge_ModuleInstanceContext = nil 57 | modstr := toWasmEdgeStringWrap(modname) 58 | res := C.WasmEdge_ExecutorRegister(self._inner, &module, store._inner, ast._inner, modstr) 59 | if !C.WasmEdge_ResultOK(res) { 60 | return nil, newError(res) 61 | } 62 | return &Module{_inner: module, _own: true}, nil 63 | } 64 | 65 | func (self *Executor) RegisterImport(store *Store, module *Module) error { 66 | res := C.WasmEdge_ExecutorRegisterImport(self._inner, store._inner, module._inner) 67 | if !C.WasmEdge_ResultOK(res) { 68 | return newError(res) 69 | } 70 | return nil 71 | } 72 | 73 | func (self *Executor) Invoke(funcinst *Function, params ...interface{}) ([]interface{}, error) { 74 | ftype := funcinst.GetFunctionType() 75 | cparams := toWasmEdgeValueSlide(params...) 76 | creturns := make([]C.WasmEdge_Value, ftype.GetReturnsLength()) 77 | var ptrparams *C.WasmEdge_Value = nil 78 | var ptrreturns *C.WasmEdge_Value = nil 79 | if len(cparams) > 0 { 80 | ptrparams = (*C.WasmEdge_Value)(unsafe.Pointer(&cparams[0])) 81 | } 82 | if len(creturns) > 0 { 83 | ptrreturns = (*C.WasmEdge_Value)(unsafe.Pointer(&creturns[0])) 84 | } 85 | res := C.WasmEdge_ExecutorInvoke( 86 | self._inner, funcinst._inner, 87 | ptrparams, C.uint32_t(len(cparams)), 88 | ptrreturns, C.uint32_t(len(creturns))) 89 | if !C.WasmEdge_ResultOK(res) { 90 | return nil, newError(res) 91 | } 92 | return fromWasmEdgeValueSlide(creturns), nil 93 | } 94 | 95 | func (self *Executor) AsyncInvoke(funcinst *Function, params ...interface{}) *Async { 96 | cparams := toWasmEdgeValueSlide(params...) 97 | var ptrparams *C.WasmEdge_Value = nil 98 | if len(cparams) > 0 { 99 | ptrparams = (*C.WasmEdge_Value)(unsafe.Pointer(&cparams[0])) 100 | } 101 | async := C.WasmEdge_ExecutorAsyncInvoke(self._inner, funcinst._inner, ptrparams, C.uint32_t(len(cparams))) 102 | if async == nil { 103 | return nil 104 | } 105 | return &Async{_inner: async, _own: true} 106 | } 107 | 108 | func (self *Executor) Release() { 109 | if self._own { 110 | C.WasmEdge_ExecutorDelete(self._inner) 111 | } 112 | self._inner = nil 113 | self._own = false 114 | } 115 | -------------------------------------------------------------------------------- /wasmedge/hostfunc.go: -------------------------------------------------------------------------------- 1 | package wasmedge 2 | 3 | // #include 4 | import "C" 5 | import ( 6 | "reflect" 7 | "sync" 8 | "unsafe" 9 | ) 10 | 11 | type hostFunctionSignature func(data interface{}, callframe *CallingFrame, params []interface{}) ([]interface{}, Result) 12 | 13 | type hostFunctionManager struct { 14 | mu sync.Mutex 15 | // Valid next index of map. Use and increase this index when gc is empty. 16 | idx uint 17 | // Recycled entries of map. Use entry in this slide when allocate a new host function. 18 | gc []uint 19 | data map[uint]interface{} 20 | funcs map[uint]hostFunctionSignature 21 | } 22 | 23 | func (self *hostFunctionManager) add(hostfunc hostFunctionSignature, hostdata interface{}) uint { 24 | self.mu.Lock() 25 | defer self.mu.Unlock() 26 | 27 | var realidx uint 28 | if len(self.gc) > 0 { 29 | realidx = self.gc[len(self.gc)-1] 30 | self.gc = self.gc[0 : len(self.gc)-1] 31 | } else { 32 | realidx = self.idx 33 | self.idx++ 34 | } 35 | self.funcs[realidx] = hostfunc 36 | self.data[realidx] = hostdata 37 | return realidx 38 | } 39 | 40 | func (self *hostFunctionManager) get(i uint) (hostFunctionSignature, interface{}) { 41 | self.mu.Lock() 42 | defer self.mu.Unlock() 43 | return self.funcs[i], self.data[i] 44 | } 45 | 46 | func (self *hostFunctionManager) del(i uint) { 47 | self.mu.Lock() 48 | defer self.mu.Unlock() 49 | delete(self.funcs, i) 50 | delete(self.data, i) 51 | self.gc = append(self.gc, i) 52 | } 53 | 54 | var hostfuncMgr = hostFunctionManager{ 55 | idx: 0, 56 | data: make(map[uint]interface{}), 57 | funcs: make(map[uint]hostFunctionSignature), 58 | } 59 | 60 | //export wasmedgego_HostFuncInvokeImpl 61 | func wasmedgego_HostFuncInvokeImpl(fn uintptr, data *C.void, callframe *C.WasmEdge_CallingFrameContext, params *C.WasmEdge_Value, paramlen C.uint32_t, returns *C.WasmEdge_Value, returnlen C.uint32_t) C.WasmEdge_Result { 62 | gocallgrame := &CallingFrame{ 63 | _inner: callframe, 64 | } 65 | 66 | goparams := make([]interface{}, uint(paramlen)) 67 | var cparams []C.WasmEdge_Value 68 | if paramlen > 0 { 69 | sliceHeader := (*reflect.SliceHeader)((unsafe.Pointer(&cparams))) 70 | sliceHeader.Cap = int(paramlen) 71 | sliceHeader.Len = int(paramlen) 72 | sliceHeader.Data = uintptr(unsafe.Pointer(params)) 73 | for i := 0; i < int(paramlen); i++ { 74 | goparams[i] = fromWasmEdgeValue(cparams[i]) 75 | if C.WasmEdge_ValTypeIsExternRef(cparams[i].Type) == true && !goparams[i].(ExternRef)._valid { 76 | panic("External reference is released") 77 | } 78 | } 79 | } 80 | 81 | gofunc, godata := hostfuncMgr.get(uint(fn)) 82 | goreturns, err := gofunc(godata, gocallgrame, goparams) 83 | 84 | var creturns []C.WasmEdge_Value 85 | if returnlen > 0 && goreturns != nil { 86 | sliceHeader := (*reflect.SliceHeader)((unsafe.Pointer(&creturns))) 87 | sliceHeader.Cap = int(returnlen) 88 | sliceHeader.Len = int(returnlen) 89 | sliceHeader.Data = uintptr(unsafe.Pointer(returns)) 90 | for i, val := range goreturns { 91 | if i < int(returnlen) { 92 | creturns[i] = toWasmEdgeValue(val) 93 | } 94 | } 95 | } 96 | 97 | return C.WasmEdge_Result{Code: C.uint32_t(err.code)} 98 | } 99 | -------------------------------------------------------------------------------- /wasmedge/instance.go: -------------------------------------------------------------------------------- 1 | package wasmedge 2 | 3 | /* 4 | #include 5 | 6 | typedef void (*wasmedgego_HostFuncWrapper)(void *, void *, 7 | const WasmEdge_CallingFrameContext *, 8 | const WasmEdge_Value *, 9 | const uint32_t, WasmEdge_Value *, 10 | const uint32_t); 11 | 12 | WasmEdge_Result 13 | wasmedgego_HostFuncInvoke(void *Func, void *Data, 14 | const WasmEdge_CallingFrameContext *CallFrameCxt, 15 | const WasmEdge_Value *Params, const uint32_t ParamLen, 16 | WasmEdge_Value *Returns, const uint32_t ReturnLen); 17 | 18 | typedef uint32_t (*wasmedgego_GetExport)(const WasmEdge_ModuleInstanceContext *, 19 | WasmEdge_String *, const uint32_t); 20 | typedef uint32_t (*wasmedgego_GetRegExport)( 21 | const WasmEdge_ModuleInstanceContext *, WasmEdge_String, WasmEdge_String *, 22 | const uint32_t); 23 | 24 | uint32_t wasmedgego_WrapListExport(wasmedgego_GetExport F, 25 | const WasmEdge_ModuleInstanceContext *Cxt, 26 | WasmEdge_String *Names, const uint32_t Len) { 27 | return F(Cxt, Names, Len); 28 | } 29 | 30 | WasmEdge_FunctionInstanceContext * 31 | wasmedgego_FunctionInstanceCreateBindingWrapper( 32 | const WasmEdge_FunctionTypeContext *Type, WasmEdge_WrapFunc_t WrapFunc, 33 | uintptr_t Binding, void *Data, const uint64_t Cost) { 34 | return WasmEdge_FunctionInstanceCreateBinding(Type, WrapFunc, (void *)Binding, 35 | Data, Cost); 36 | } 37 | */ 38 | import "C" 39 | import ( 40 | "errors" 41 | "reflect" 42 | "unsafe" 43 | ) 44 | 45 | type Module struct { 46 | _inner *C.WasmEdge_ModuleInstanceContext 47 | _hostfuncs []uint 48 | _own bool 49 | } 50 | 51 | type Function struct { 52 | _inner *C.WasmEdge_FunctionInstanceContext 53 | _index uint 54 | _own bool 55 | } 56 | 57 | type Table struct { 58 | _inner *C.WasmEdge_TableInstanceContext 59 | _own bool 60 | } 61 | 62 | type Memory struct { 63 | _inner *C.WasmEdge_MemoryInstanceContext 64 | _own bool 65 | } 66 | 67 | type Tag struct { 68 | _inner *C.WasmEdge_TagInstanceContext 69 | _own bool 70 | } 71 | 72 | type Global struct { 73 | _inner *C.WasmEdge_GlobalInstanceContext 74 | _own bool 75 | } 76 | 77 | func NewModule(modname string) *Module { 78 | module := C.WasmEdge_ModuleInstanceCreate(toWasmEdgeStringWrap(modname)) 79 | if module == nil { 80 | return nil 81 | } 82 | return &Module{_inner: module, _own: true} 83 | } 84 | 85 | func NewWasiModule(args []string, envs []string, preopens []string) *Module { 86 | cargs := toCStringArray(args) 87 | cenvs := toCStringArray(envs) 88 | cpreopens := toCStringArray(preopens) 89 | var ptrargs *(*C.char) = nil 90 | var ptrenvs *(*C.char) = nil 91 | var ptrpreopens *(*C.char) = nil 92 | if len(cargs) > 0 { 93 | ptrargs = &cargs[0] 94 | } 95 | if len(cenvs) > 0 { 96 | ptrenvs = &cenvs[0] 97 | } 98 | if len(cpreopens) > 0 { 99 | ptrpreopens = &cpreopens[0] 100 | } 101 | 102 | module := C.WasmEdge_ModuleInstanceCreateWASI( 103 | ptrargs, C.uint32_t(len(cargs)), 104 | ptrenvs, C.uint32_t(len(cenvs)), 105 | ptrpreopens, C.uint32_t(len(cpreopens))) 106 | 107 | freeCStringArray(cargs) 108 | freeCStringArray(cenvs) 109 | freeCStringArray(cpreopens) 110 | 111 | if module == nil { 112 | return nil 113 | } 114 | return &Module{_inner: module, _own: true} 115 | } 116 | 117 | func (self *Module) InitWasi(args []string, envs []string, preopens []string) { 118 | cargs := toCStringArray(args) 119 | cenvs := toCStringArray(envs) 120 | cpreopens := toCStringArray(preopens) 121 | var ptrargs *(*C.char) = nil 122 | var ptrenvs *(*C.char) = nil 123 | var ptrpreopens *(*C.char) = nil 124 | if len(cargs) > 0 { 125 | ptrargs = &cargs[0] 126 | } 127 | if len(cenvs) > 0 { 128 | ptrenvs = &cenvs[0] 129 | } 130 | if len(cpreopens) > 0 { 131 | ptrpreopens = &cpreopens[0] 132 | } 133 | 134 | C.WasmEdge_ModuleInstanceInitWASI(self._inner, 135 | ptrargs, C.uint32_t(len(cargs)), 136 | ptrenvs, C.uint32_t(len(cenvs)), 137 | ptrpreopens, C.uint32_t(len(cpreopens))) 138 | 139 | freeCStringArray(cargs) 140 | freeCStringArray(cenvs) 141 | freeCStringArray(cpreopens) 142 | } 143 | 144 | func (self *Module) WasiGetExitCode() uint { 145 | return uint(C.WasmEdge_ModuleInstanceWASIGetExitCode(self._inner)) 146 | } 147 | 148 | func (self *Module) InitWasmEdgeProcess(allowedcmds []string, allowall bool) { 149 | ccmds := toCStringArray(allowedcmds) 150 | var ptrcmds *(*C.char) = nil 151 | if len(ccmds) > 0 { 152 | ptrcmds = &ccmds[0] 153 | } 154 | 155 | C.WasmEdge_ModuleInstanceInitWasmEdgeProcess(ptrcmds, C.uint32_t(len(ccmds)), C.bool(allowall)) 156 | 157 | freeCStringArray(ccmds) 158 | } 159 | 160 | func (self *Module) GetName() string { 161 | cname := C.WasmEdge_ModuleInstanceGetModuleName(self._inner) 162 | return fromWasmEdgeString(cname) 163 | } 164 | 165 | func (self *Module) AddFunction(name string, inst *Function) { 166 | C.WasmEdge_ModuleInstanceAddFunction(self._inner, toWasmEdgeStringWrap(name), inst._inner) 167 | self._hostfuncs = append(self._hostfuncs, inst._index) 168 | inst._inner = nil 169 | inst._own = false 170 | } 171 | 172 | func (self *Module) AddTable(name string, inst *Table) { 173 | C.WasmEdge_ModuleInstanceAddTable(self._inner, toWasmEdgeStringWrap(name), inst._inner) 174 | inst._inner = nil 175 | inst._own = false 176 | } 177 | 178 | func (self *Module) AddMemory(name string, inst *Memory) { 179 | C.WasmEdge_ModuleInstanceAddMemory(self._inner, toWasmEdgeStringWrap(name), inst._inner) 180 | inst._inner = nil 181 | inst._own = false 182 | } 183 | 184 | func (self *Module) AddGlobal(name string, inst *Global) { 185 | C.WasmEdge_ModuleInstanceAddGlobal(self._inner, toWasmEdgeStringWrap(name), inst._inner) 186 | inst._inner = nil 187 | inst._own = false 188 | } 189 | 190 | func (self *Module) getExports(exportlen C.uint32_t, getfunc C.wasmedgego_GetExport) []string { 191 | cnames := make([]C.WasmEdge_String, int(exportlen)) 192 | if int(exportlen) > 0 { 193 | C.wasmedgego_WrapListExport(getfunc, self._inner, &cnames[0], exportlen) 194 | } 195 | names := make([]string, int(exportlen)) 196 | for i := 0; i < int(exportlen); i++ { 197 | names[i] = fromWasmEdgeString(cnames[i]) 198 | } 199 | return names 200 | } 201 | 202 | func (self *Module) FindFunction(name string) *Function { 203 | cname := toWasmEdgeStringWrap(name) 204 | cinst := C.WasmEdge_ModuleInstanceFindFunction(self._inner, cname) 205 | if cinst == nil { 206 | return nil 207 | } 208 | return &Function{_inner: cinst, _own: false} 209 | } 210 | 211 | func (self *Module) FindTable(name string) *Table { 212 | cname := toWasmEdgeStringWrap(name) 213 | cinst := C.WasmEdge_ModuleInstanceFindTable(self._inner, cname) 214 | if cinst == nil { 215 | return nil 216 | } 217 | return &Table{_inner: cinst, _own: false} 218 | } 219 | 220 | func (self *Module) FindMemory(name string) *Memory { 221 | cname := toWasmEdgeStringWrap(name) 222 | cinst := C.WasmEdge_ModuleInstanceFindMemory(self._inner, cname) 223 | if cinst == nil { 224 | return nil 225 | } 226 | return &Memory{_inner: cinst, _own: false} 227 | } 228 | 229 | func (self *Module) FindTag(name string) *Tag { 230 | cname := toWasmEdgeStringWrap(name) 231 | cinst := C.WasmEdge_ModuleInstanceFindTag(self._inner, cname) 232 | if cinst == nil { 233 | return nil 234 | } 235 | return &Tag{_inner: cinst, _own: false} 236 | } 237 | 238 | func (self *Module) FindGlobal(name string) *Global { 239 | cname := toWasmEdgeStringWrap(name) 240 | cinst := C.WasmEdge_ModuleInstanceFindGlobal(self._inner, cname) 241 | if cinst == nil { 242 | return nil 243 | } 244 | return &Global{_inner: cinst, _own: false} 245 | } 246 | 247 | func (self *Module) ListFunction() []string { 248 | return self.getExports( 249 | C.WasmEdge_ModuleInstanceListFunctionLength(self._inner), 250 | C.wasmedgego_GetExport(C.WasmEdge_ModuleInstanceListFunction), 251 | ) 252 | } 253 | 254 | func (self *Module) ListTable() []string { 255 | return self.getExports( 256 | C.WasmEdge_ModuleInstanceListTableLength(self._inner), 257 | C.wasmedgego_GetExport(C.WasmEdge_ModuleInstanceListTable), 258 | ) 259 | } 260 | 261 | func (self *Module) ListMemory() []string { 262 | return self.getExports( 263 | C.WasmEdge_ModuleInstanceListMemoryLength(self._inner), 264 | C.wasmedgego_GetExport(C.WasmEdge_ModuleInstanceListMemory), 265 | ) 266 | } 267 | 268 | func (self *Module) ListTag() []string { 269 | return self.getExports( 270 | C.WasmEdge_ModuleInstanceListTagLength(self._inner), 271 | C.wasmedgego_GetExport(C.WasmEdge_ModuleInstanceListTag), 272 | ) 273 | } 274 | 275 | func (self *Module) ListGlobal() []string { 276 | return self.getExports( 277 | C.WasmEdge_ModuleInstanceListGlobalLength(self._inner), 278 | C.wasmedgego_GetExport(C.WasmEdge_ModuleInstanceListGlobal), 279 | ) 280 | } 281 | 282 | func (self *Module) Release() { 283 | if self._own { 284 | for _, idx := range self._hostfuncs { 285 | hostfuncMgr.del(idx) 286 | } 287 | self._hostfuncs = []uint{} 288 | C.WasmEdge_ModuleInstanceDelete(self._inner) 289 | } 290 | self._inner = nil 291 | self._own = false 292 | } 293 | 294 | func NewFunction(ftype *FunctionType, fn hostFunctionSignature, additional interface{}, cost uint) *Function { 295 | if ftype == nil { 296 | return nil 297 | } 298 | 299 | index := hostfuncMgr.add(fn, additional) 300 | function := C.wasmedgego_FunctionInstanceCreateBindingWrapper( 301 | ftype._inner, 302 | C.wasmedgego_HostFuncWrapper(C.wasmedgego_HostFuncInvoke), 303 | C.uintptr_t(index), 304 | nil, 305 | C.uint64_t(cost)) 306 | if function == nil { 307 | hostfuncMgr.del(index) 308 | return nil 309 | } 310 | return &Function{_inner: function, _index: index, _own: true} 311 | } 312 | 313 | func (self *Function) GetFunctionType() *FunctionType { 314 | return &FunctionType{ 315 | _inner: C.WasmEdge_FunctionInstanceGetFunctionType(self._inner), 316 | _own: false, 317 | } 318 | } 319 | 320 | func (self *Function) Release() { 321 | if self._own && self._inner != nil { 322 | C.WasmEdge_FunctionInstanceDelete(self._inner) 323 | hostfuncMgr.del(self._index) 324 | } 325 | self._inner = nil 326 | self._own = false 327 | } 328 | 329 | func NewTable(ttype *TableType) *Table { 330 | if ttype == nil { 331 | return nil 332 | } 333 | table := C.WasmEdge_TableInstanceCreate(ttype._inner) 334 | if table == nil { 335 | return nil 336 | } 337 | return &Table{_inner: table, _own: true} 338 | } 339 | 340 | func (self *Table) GetTableType() *TableType { 341 | return &TableType{ 342 | _inner: C.WasmEdge_TableInstanceGetTableType(self._inner), 343 | _own: false, 344 | } 345 | } 346 | 347 | func (self *Table) GetData(off uint) (interface{}, error) { 348 | cval := C.WasmEdge_Value{} 349 | res := C.WasmEdge_TableInstanceGetData(self._inner, &cval, C.uint32_t(off)) 350 | if !C.WasmEdge_ResultOK(res) { 351 | return nil, newError(res) 352 | } 353 | return fromWasmEdgeValue(cval), nil 354 | } 355 | 356 | func (self *Table) SetData(data interface{}, off uint) error { 357 | cval := toWasmEdgeValue(data) 358 | res := C.WasmEdge_TableInstanceSetData(self._inner, cval, C.uint32_t(off)) 359 | if !C.WasmEdge_ResultOK(res) { 360 | return newError(res) 361 | } 362 | return nil 363 | } 364 | 365 | func (self *Table) GetSize() uint { 366 | return uint(C.WasmEdge_TableInstanceGetSize(self._inner)) 367 | } 368 | 369 | func (self *Table) Grow(size uint) error { 370 | res := C.WasmEdge_TableInstanceGrow(self._inner, C.uint32_t(size)) 371 | if !C.WasmEdge_ResultOK(res) { 372 | return newError(res) 373 | } 374 | return nil 375 | } 376 | 377 | func (self *Table) Release() { 378 | if self._own { 379 | C.WasmEdge_TableInstanceDelete(self._inner) 380 | } 381 | self._inner = nil 382 | self._own = false 383 | } 384 | 385 | func NewMemory(mtype *MemoryType) *Memory { 386 | if mtype == nil { 387 | return nil 388 | } 389 | memory := C.WasmEdge_MemoryInstanceCreate(mtype._inner) 390 | if memory == nil { 391 | return nil 392 | } 393 | return &Memory{_inner: memory, _own: true} 394 | } 395 | 396 | func (self *Memory) GetMemoryType() *MemoryType { 397 | return &MemoryType{ 398 | _inner: C.WasmEdge_MemoryInstanceGetMemoryType(self._inner), 399 | _own: false, 400 | } 401 | } 402 | 403 | func (self *Memory) GetData(off uint, length uint) ([]byte, error) { 404 | p := C.WasmEdge_MemoryInstanceGetPointer(self._inner, C.uint32_t(off), C.uint32_t(length)) 405 | if p == nil { 406 | return nil, errors.New("Failed get data pointer") 407 | } 408 | // Use SliceHeader to wrap the slice from cgo 409 | var r []byte 410 | s := (*reflect.SliceHeader)(unsafe.Pointer(&r)) 411 | s.Cap = int(length) 412 | s.Len = int(length) 413 | s.Data = uintptr(unsafe.Pointer(p)) 414 | return r, nil 415 | } 416 | 417 | func (self *Memory) SetData(data []byte, off uint, length uint) error { 418 | var ptrdata *C.uint8_t = nil 419 | if len(data) > 0 { 420 | ptrdata = (*C.uint8_t)(unsafe.Pointer(&data[0])) 421 | } 422 | res := C.WasmEdge_MemoryInstanceSetData(self._inner, ptrdata, C.uint32_t(off), C.uint32_t(length)) 423 | if !C.WasmEdge_ResultOK(res) { 424 | return newError(res) 425 | } 426 | return nil 427 | } 428 | 429 | func (self *Memory) GetPageSize() uint { 430 | return uint(C.WasmEdge_MemoryInstanceGetPageSize(self._inner)) 431 | } 432 | 433 | func (self *Memory) GrowPage(size uint) error { 434 | res := C.WasmEdge_MemoryInstanceGrowPage(self._inner, C.uint32_t(size)) 435 | if !C.WasmEdge_ResultOK(res) { 436 | return newError(res) 437 | } 438 | return nil 439 | } 440 | 441 | func (self *Memory) Release() { 442 | if self._own { 443 | C.WasmEdge_MemoryInstanceDelete(self._inner) 444 | } 445 | self._inner = nil 446 | self._own = false 447 | } 448 | 449 | func (self *Tag) GetTagType() *TagType { 450 | return &TagType{ 451 | _inner: C.WasmEdge_TagInstanceGetTagType(self._inner), 452 | _own: false, 453 | } 454 | } 455 | 456 | func NewGlobal(gtype *GlobalType, val interface{}) *Global { 457 | if gtype == nil { 458 | return nil 459 | } 460 | cval := toWasmEdgeValue(val) 461 | global := C.WasmEdge_GlobalInstanceCreate(gtype._inner, cval) 462 | if global == nil { 463 | return nil 464 | } 465 | return &Global{_inner: global, _own: true} 466 | } 467 | 468 | func (self *Global) GetGlobalType() *GlobalType { 469 | return &GlobalType{ 470 | _inner: C.WasmEdge_GlobalInstanceGetGlobalType(self._inner), 471 | _own: false, 472 | } 473 | } 474 | 475 | func (self *Global) GetValue() interface{} { 476 | cval := C.WasmEdge_GlobalInstanceGetValue(self._inner) 477 | return fromWasmEdgeValue(cval) 478 | } 479 | 480 | func (self *Global) SetValue(val interface{}) error { 481 | res := C.WasmEdge_GlobalInstanceSetValue(self._inner, toWasmEdgeValue(val)) 482 | if !C.WasmEdge_ResultOK(res) { 483 | return newError(res) 484 | } 485 | return nil 486 | } 487 | 488 | func (self *Global) Release() { 489 | if self._own { 490 | C.WasmEdge_GlobalInstanceDelete(self._inner) 491 | } 492 | self._inner = nil 493 | self._own = false 494 | } 495 | -------------------------------------------------------------------------------- /wasmedge/limit.go: -------------------------------------------------------------------------------- 1 | package wasmedge 2 | 3 | // #include 4 | import "C" 5 | 6 | type Limit struct { 7 | min uint 8 | max uint 9 | hasmax bool 10 | shared bool 11 | } 12 | 13 | func NewLimit(minVal uint) *Limit { 14 | l := &Limit{ 15 | min: minVal, 16 | max: minVal, 17 | hasmax: false, 18 | shared: false, 19 | } 20 | return l 21 | } 22 | 23 | func NewLimitWithMax(minVal uint, maxVal uint) *Limit { 24 | if maxVal >= minVal { 25 | return &Limit{ 26 | min: minVal, 27 | max: maxVal, 28 | hasmax: true, 29 | shared: false, 30 | } 31 | } 32 | return nil 33 | } 34 | 35 | func NewLimitShared(minVal uint) *Limit { 36 | l := &Limit{ 37 | min: minVal, 38 | max: minVal, 39 | hasmax: false, 40 | shared: true, 41 | } 42 | return l 43 | } 44 | 45 | func NewLimitSharedWithMax(minVal uint, maxVal uint) *Limit { 46 | if maxVal >= minVal { 47 | return &Limit{ 48 | min: minVal, 49 | max: maxVal, 50 | hasmax: true, 51 | shared: true, 52 | } 53 | } 54 | return nil 55 | } 56 | 57 | func (l *Limit) HasMax() bool { 58 | return l.hasmax 59 | } 60 | 61 | func (l *Limit) IsShared() bool { 62 | return l.shared 63 | } 64 | 65 | func (l *Limit) GetMin() uint { 66 | return l.min 67 | } 68 | 69 | func (l *Limit) GetMax() uint { 70 | return l.max 71 | } 72 | -------------------------------------------------------------------------------- /wasmedge/limit_test.go: -------------------------------------------------------------------------------- 1 | package wasmedge 2 | 3 | import "testing" 4 | 5 | const ( 6 | minVal = 1024 7 | ) 8 | 9 | func TestNewLimit(t *testing.T) { 10 | l := NewLimit(minVal) 11 | if l.GetMin() != minVal { 12 | t.Fatal("wrong min value") 13 | } 14 | if l.HasMax() { 15 | t.Fatal("should have no max value") 16 | } 17 | 18 | l = NewLimitWithMax(minVal, minVal*2) 19 | if !l.HasMax() { 20 | t.Fatal("should have max value") 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /wasmedge/loader.go: -------------------------------------------------------------------------------- 1 | package wasmedge 2 | 3 | // #include 4 | // #include 5 | import "C" 6 | import ( 7 | "unsafe" 8 | ) 9 | 10 | type Loader struct { 11 | _inner *C.WasmEdge_LoaderContext 12 | _own bool 13 | } 14 | 15 | func NewLoader() *Loader { 16 | loader := C.WasmEdge_LoaderCreate(nil) 17 | if loader == nil { 18 | return nil 19 | } 20 | return &Loader{_inner: loader, _own: true} 21 | } 22 | 23 | func NewLoaderWithConfig(conf *Configure) *Loader { 24 | loader := C.WasmEdge_LoaderCreate(conf._inner) 25 | if loader == nil { 26 | return nil 27 | } 28 | return &Loader{_inner: loader, _own: true} 29 | } 30 | 31 | func (self *Loader) LoadFile(path string) (*AST, error) { 32 | cpath := C.CString(path) 33 | defer C.free(unsafe.Pointer(cpath)) 34 | var module *C.WasmEdge_ASTModuleContext = nil 35 | result := C.WasmEdge_LoaderParseFromFile(self._inner, &module, cpath) 36 | if !C.WasmEdge_ResultOK(result) { 37 | return nil, newError(result) 38 | } 39 | return &AST{_inner: module, _own: true}, nil 40 | } 41 | 42 | func (self *Loader) LoadBuffer(buf []byte) (*AST, error) { 43 | var module *C.WasmEdge_ASTModuleContext = nil 44 | cbytes := C.WasmEdge_BytesWrap((*C.uint8_t)(unsafe.Pointer(&buf[0])), C.uint32_t(len(buf))) 45 | result := C.WasmEdge_LoaderParseFromBytes(self._inner, &module, cbytes) 46 | if !C.WasmEdge_ResultOK(result) { 47 | return nil, newError(result) 48 | } 49 | return &AST{_inner: module, _own: true}, nil 50 | } 51 | 52 | func (self *Loader) Release() { 53 | if self._own { 54 | C.WasmEdge_LoaderDelete(self._inner) 55 | } 56 | self._inner = nil 57 | self._own = false 58 | } 59 | -------------------------------------------------------------------------------- /wasmedge/log.go: -------------------------------------------------------------------------------- 1 | package wasmedge 2 | 3 | // #include 4 | import "C" 5 | 6 | func SetLogErrorLevel() { 7 | C.WasmEdge_LogSetErrorLevel() 8 | } 9 | 10 | func SetLogDebugLevel() { 11 | C.WasmEdge_LogSetDebugLevel() 12 | } 13 | 14 | func SetLogOff() { 15 | C.WasmEdge_LogOff() 16 | } 17 | -------------------------------------------------------------------------------- /wasmedge/plugin.go: -------------------------------------------------------------------------------- 1 | package wasmedge 2 | 3 | // #include 4 | // #include 5 | import "C" 6 | import "unsafe" 7 | 8 | type Plugin struct { 9 | _inner *C.WasmEdge_PluginContext 10 | _own bool 11 | } 12 | 13 | func LoadPluginDefaultPaths() { 14 | C.WasmEdge_PluginLoadWithDefaultPaths() 15 | } 16 | 17 | func LoadPluginFromPath(name string) { 18 | cpath := C.CString(name) 19 | defer C.free(unsafe.Pointer(cpath)) 20 | C.WasmEdge_PluginLoadFromPath(cpath) 21 | } 22 | 23 | func ListPlugins() []string { 24 | pluginlen := C.WasmEdge_PluginListPluginsLength() 25 | cnames := make([]C.WasmEdge_String, int(pluginlen)) 26 | if int(pluginlen) > 0 { 27 | C.WasmEdge_PluginListPlugins(&cnames[0], pluginlen) 28 | } 29 | names := make([]string, int(pluginlen)) 30 | for i := 0; i < int(pluginlen); i++ { 31 | names[i] = fromWasmEdgeString(cnames[i]) 32 | } 33 | return names 34 | } 35 | 36 | func FindPlugin(name string) *Plugin { 37 | cname := toWasmEdgeStringWrap(name) 38 | cinst := C.WasmEdge_PluginFind(cname) 39 | if cinst == nil { 40 | return nil 41 | } 42 | return &Plugin{_inner: cinst, _own: false} 43 | } 44 | 45 | func (self *Plugin) ListModule() []string { 46 | modlen := C.WasmEdge_PluginListModuleLength(self._inner) 47 | cnames := make([]C.WasmEdge_String, int(modlen)) 48 | if int(modlen) > 0 { 49 | C.WasmEdge_PluginListModule(self._inner, &cnames[0], modlen) 50 | } 51 | names := make([]string, int(modlen)) 52 | for i := 0; i < int(modlen); i++ { 53 | names[i] = fromWasmEdgeString(cnames[i]) 54 | } 55 | return names 56 | } 57 | 58 | func (self *Plugin) CreateModule(name string) *Module { 59 | cname := toWasmEdgeStringWrap(name) 60 | cinst := C.WasmEdge_PluginCreateModule(self._inner, cname) 61 | if cinst == nil { 62 | return nil 63 | } 64 | return &Module{_inner: cinst, _own: true} 65 | } 66 | -------------------------------------------------------------------------------- /wasmedge/result.go: -------------------------------------------------------------------------------- 1 | package wasmedge 2 | 3 | // #include 4 | import "C" 5 | 6 | type Result struct { 7 | code uint32 8 | } 9 | 10 | var ( 11 | Result_Success = Result{code: 0} 12 | Result_Terminate = Result{code: 1} 13 | Result_Fail = Result{code: 2} 14 | ) 15 | 16 | type ErrCategory C.enum_WasmEdge_ErrCategory 17 | 18 | const ( 19 | ErrCategory_WASM = ErrCategory(C.WasmEdge_ErrCategory_WASM) 20 | ErrCategory_UserLevel = ErrCategory(C.WasmEdge_ErrCategory_UserLevelError) 21 | ) 22 | 23 | func newError(res C.WasmEdge_Result) *Result { 24 | if C.WasmEdge_ResultOK(res) { 25 | return nil 26 | } 27 | return &Result{code: uint32(res.Code)} 28 | } 29 | 30 | func NewResult(cate ErrCategory, code int) Result { 31 | res := C.WasmEdge_ResultGen(C.enum_WasmEdge_ErrCategory(cate), C.uint32_t(code)) 32 | return Result{ 33 | code: uint32(res.Code), 34 | } 35 | } 36 | 37 | func (res *Result) Error() string { 38 | return C.GoString(C.WasmEdge_ResultGetMessage(C.WasmEdge_Result{Code: C.uint32_t(res.code)})) 39 | } 40 | 41 | func (res *Result) GetCode() int { 42 | return int(C.WasmEdge_ResultGetCode(C.WasmEdge_Result{Code: C.uint32_t(res.code)})) 43 | } 44 | 45 | func (res *Result) GetErrorCategory() ErrCategory { 46 | return ErrCategory(C.WasmEdge_ResultGetCategory(C.WasmEdge_Result{Code: C.uint32_t(res.code)})) 47 | } 48 | -------------------------------------------------------------------------------- /wasmedge/statistics.go: -------------------------------------------------------------------------------- 1 | package wasmedge 2 | 3 | // #include 4 | import "C" 5 | 6 | type Statistics struct { 7 | _inner *C.WasmEdge_StatisticsContext 8 | _own bool 9 | } 10 | 11 | func NewStatistics() *Statistics { 12 | stat := C.WasmEdge_StatisticsCreate() 13 | if stat == nil { 14 | return nil 15 | } 16 | return &Statistics{_inner: stat, _own: true} 17 | } 18 | 19 | func (self *Statistics) GetInstrCount() uint { 20 | return uint(C.WasmEdge_StatisticsGetInstrCount(self._inner)) 21 | } 22 | 23 | func (self *Statistics) GetInstrPerSecond() float64 { 24 | return float64(C.WasmEdge_StatisticsGetInstrPerSecond(self._inner)) 25 | } 26 | 27 | func (self *Statistics) GetTotalCost() uint { 28 | return uint(C.WasmEdge_StatisticsGetTotalCost(self._inner)) 29 | } 30 | 31 | func (self *Statistics) SetCostTable(table []uint64) { 32 | var ptr *uint64 = nil 33 | if len(table) > 0 { 34 | ptr = &(table[0]) 35 | } 36 | C.WasmEdge_StatisticsSetCostTable(self._inner, (*C.uint64_t)(ptr), C.uint32_t(len(table))) 37 | } 38 | 39 | func (self *Statistics) SetCostLimit(limit uint) { 40 | C.WasmEdge_StatisticsSetCostLimit(self._inner, C.uint64_t(limit)) 41 | } 42 | 43 | func (self *Statistics) Release() { 44 | if self._own { 45 | C.WasmEdge_StatisticsDelete(self._inner) 46 | } 47 | self._inner = nil 48 | self._own = false 49 | } 50 | -------------------------------------------------------------------------------- /wasmedge/store.go: -------------------------------------------------------------------------------- 1 | package wasmedge 2 | 3 | // #include 4 | import "C" 5 | 6 | type Store struct { 7 | _inner *C.WasmEdge_StoreContext 8 | _own bool 9 | } 10 | 11 | func NewStore() *Store { 12 | store := C.WasmEdge_StoreCreate() 13 | if store == nil { 14 | return nil 15 | } 16 | return &Store{_inner: store, _own: true} 17 | } 18 | 19 | func (self *Store) FindModule(name string) *Module { 20 | cname := toWasmEdgeStringWrap(name) 21 | cinst := C.WasmEdge_StoreFindModule(self._inner, cname) 22 | if cinst == nil { 23 | return nil 24 | } 25 | return &Module{_inner: cinst, _own: false} 26 | } 27 | 28 | func (self *Store) ListModule() []string { 29 | modlen := C.WasmEdge_StoreListModuleLength(self._inner) 30 | cnames := make([]C.WasmEdge_String, int(modlen)) 31 | if int(modlen) > 0 { 32 | C.WasmEdge_StoreListModule(self._inner, &cnames[0], modlen) 33 | } 34 | names := make([]string, int(modlen)) 35 | for i := 0; i < int(modlen); i++ { 36 | names[i] = fromWasmEdgeString(cnames[i]) 37 | } 38 | return names 39 | } 40 | 41 | func (self *Store) Release() { 42 | if self._own { 43 | C.WasmEdge_StoreDelete(self._inner) 44 | } 45 | self._inner = nil 46 | self._own = false 47 | } 48 | -------------------------------------------------------------------------------- /wasmedge/string.go: -------------------------------------------------------------------------------- 1 | package wasmedge 2 | 3 | // #include 4 | // #include 5 | import "C" 6 | import "unsafe" 7 | 8 | func toWasmEdgeStringWrap(str string) C.WasmEdge_String { 9 | return C.WasmEdge_StringWrap(C._GoStringPtr(str), C.uint32_t(C._GoStringLen(str))) 10 | } 11 | 12 | func fromWasmEdgeString(str C.WasmEdge_String) string { 13 | if int(str.Length) > 0 { 14 | return C.GoStringN(str.Buf, C.int32_t(str.Length)) 15 | } 16 | return "" 17 | } 18 | 19 | func toCStringArray(strs []string) []*C.char { 20 | cstrs := make([]*C.char, len(strs)) 21 | for i, str := range strs { 22 | cstrs[i] = C.CString(str) 23 | } 24 | return cstrs 25 | } 26 | 27 | func freeCStringArray(cstrs []*C.char) { 28 | for _, cstr := range cstrs { 29 | C.free(unsafe.Pointer(cstr)) 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /wasmedge/validator.go: -------------------------------------------------------------------------------- 1 | package wasmedge 2 | 3 | // #include 4 | import "C" 5 | 6 | type Validator struct { 7 | _inner *C.WasmEdge_ValidatorContext 8 | _own bool 9 | } 10 | 11 | func NewValidator() *Validator { 12 | validator := C.WasmEdge_ValidatorCreate(nil) 13 | if validator == nil { 14 | return nil 15 | } 16 | return &Validator{_inner: validator, _own: true} 17 | } 18 | 19 | func NewValidatorWithConfig(conf *Configure) *Validator { 20 | validator := C.WasmEdge_ValidatorCreate(conf._inner) 21 | if validator == nil { 22 | return nil 23 | } 24 | return &Validator{_inner: validator, _own: true} 25 | } 26 | 27 | func (self *Validator) Validate(ast *AST) error { 28 | res := C.WasmEdge_ValidatorValidate(self._inner, ast._inner) 29 | if !C.WasmEdge_ResultOK(res) { 30 | return newError(res) 31 | } 32 | return nil 33 | } 34 | 35 | func (self *Validator) Release() { 36 | if self._own { 37 | C.WasmEdge_ValidatorDelete(self._inner) 38 | } 39 | self._inner = nil 40 | self._own = false 41 | } 42 | -------------------------------------------------------------------------------- /wasmedge/value.go: -------------------------------------------------------------------------------- 1 | package wasmedge 2 | 3 | // #include 4 | import "C" 5 | import ( 6 | "encoding/binary" 7 | "fmt" 8 | "reflect" 9 | "sync" 10 | "unsafe" 11 | ) 12 | 13 | type ValType struct { 14 | _inner C.WasmEdge_ValType 15 | } 16 | 17 | type ValMut C.enum_WasmEdge_Mutability 18 | 19 | const ( 20 | ValMut_Const = ValMut(C.WasmEdge_Mutability_Const) 21 | ValMut_Var = ValMut(C.WasmEdge_Mutability_Var) 22 | ) 23 | 24 | func NewValTypeI32() *ValType { 25 | return &ValType{_inner: C.WasmEdge_ValTypeGenI32()} 26 | } 27 | 28 | func NewValTypeI64() *ValType { 29 | return &ValType{_inner: C.WasmEdge_ValTypeGenI64()} 30 | } 31 | 32 | func NewValTypeF32() *ValType { 33 | return &ValType{_inner: C.WasmEdge_ValTypeGenF32()} 34 | } 35 | 36 | func NewValTypeF64() *ValType { 37 | return &ValType{_inner: C.WasmEdge_ValTypeGenF64()} 38 | } 39 | 40 | func NewValTypeV128() *ValType { 41 | return &ValType{_inner: C.WasmEdge_ValTypeGenV128()} 42 | } 43 | 44 | func NewValTypeFuncRef() *ValType { 45 | return &ValType{_inner: C.WasmEdge_ValTypeGenFuncRef()} 46 | } 47 | 48 | func NewValTypeExternRef() *ValType { 49 | return &ValType{_inner: C.WasmEdge_ValTypeGenExternRef()} 50 | } 51 | 52 | func (self *ValType) String() string { 53 | if C.WasmEdge_ValTypeIsI32(self._inner) { 54 | return "i32" 55 | } 56 | if C.WasmEdge_ValTypeIsI64(self._inner) { 57 | return "i64" 58 | } 59 | if C.WasmEdge_ValTypeIsF32(self._inner) { 60 | return "f32" 61 | } 62 | if C.WasmEdge_ValTypeIsF64(self._inner) { 63 | return "f64" 64 | } 65 | if C.WasmEdge_ValTypeIsV128(self._inner) { 66 | return "v128" 67 | } 68 | if C.WasmEdge_ValTypeIsFuncRef(self._inner) { 69 | return "funcref" 70 | } 71 | if C.WasmEdge_ValTypeIsExternRef(self._inner) { 72 | return "externref" 73 | } 74 | if C.WasmEdge_ValTypeIsRef(self._inner) { 75 | return "anyref" 76 | } 77 | panic("Unknown value type") 78 | } 79 | 80 | func (self *ValType) IsEqual(vt *ValType) bool { 81 | return bool(C.WasmEdge_ValTypeIsEqual(self._inner, vt._inner)) 82 | } 83 | 84 | func (self *ValType) IsI32() bool { 85 | return bool(C.WasmEdge_ValTypeIsI32(self._inner)) 86 | } 87 | 88 | func (self *ValType) IsI64() bool { 89 | return bool(C.WasmEdge_ValTypeIsI64(self._inner)) 90 | } 91 | 92 | func (self *ValType) IsF32() bool { 93 | return bool(C.WasmEdge_ValTypeIsF32(self._inner)) 94 | } 95 | 96 | func (self *ValType) IsF64() bool { 97 | return bool(C.WasmEdge_ValTypeIsF64(self._inner)) 98 | } 99 | 100 | func (self *ValType) IsV128() bool { 101 | return bool(C.WasmEdge_ValTypeIsV128(self._inner)) 102 | } 103 | 104 | func (self *ValType) IsFuncRef() bool { 105 | return bool(C.WasmEdge_ValTypeIsFuncRef(self._inner)) 106 | } 107 | 108 | func (self *ValType) IsExternRef() bool { 109 | return bool(C.WasmEdge_ValTypeIsExternRef(self._inner)) 110 | } 111 | 112 | func (self *ValType) IsRef() bool { 113 | return bool(C.WasmEdge_ValTypeIsRef(self._inner)) 114 | } 115 | 116 | func (self *ValType) IsRefNull() bool { 117 | return bool(C.WasmEdge_ValTypeIsRefNull(self._inner)) 118 | } 119 | 120 | func (self ValMut) String() string { 121 | switch self { 122 | case ValMut_Const: 123 | return "const" 124 | case ValMut_Var: 125 | return "var" 126 | } 127 | panic("Unknown value mutability") 128 | } 129 | 130 | type externRefManager struct { 131 | mu sync.Mutex 132 | // Valid next index of map. Use and increase this index when gc is empty. 133 | idx uint 134 | // Recycled entries of map. Use entry in this slide when allocate a new external reference. 135 | gc []uint 136 | ref map[uint]interface{} 137 | } 138 | 139 | func (self *externRefManager) add(ptr interface{}) uint { 140 | self.mu.Lock() 141 | defer self.mu.Unlock() 142 | 143 | var realidx uint 144 | if len(self.gc) > 0 { 145 | realidx = self.gc[len(self.gc)-1] 146 | self.gc = self.gc[0 : len(self.gc)-1] 147 | } else { 148 | realidx = self.idx 149 | self.idx++ 150 | } 151 | self.ref[realidx] = ptr 152 | return realidx 153 | } 154 | 155 | func (self *externRefManager) get(i uint) interface{} { 156 | self.mu.Lock() 157 | defer self.mu.Unlock() 158 | return self.ref[i] 159 | } 160 | 161 | func (self *externRefManager) del(i uint) { 162 | self.mu.Lock() 163 | defer self.mu.Unlock() 164 | delete(self.ref, i) 165 | self.gc = append(self.gc, i) 166 | } 167 | 168 | var externRefMgr = externRefManager{ 169 | /// Index = 0 is reserved for ref.null 170 | idx: 1, 171 | ref: make(map[uint]interface{}), 172 | } 173 | 174 | type FuncRef struct { 175 | _inner C.WasmEdge_Value 176 | } 177 | 178 | func NewFuncRef(funcinst *Function) FuncRef { 179 | return FuncRef{ 180 | _inner: C.WasmEdge_ValueGenFuncRef(funcinst._inner), 181 | } 182 | } 183 | 184 | func (self FuncRef) GetRef() *Function { 185 | funcinst := C.WasmEdge_ValueGetFuncRef(self._inner) 186 | if funcinst != nil { 187 | return &Function{_inner: funcinst, _own: false} 188 | } 189 | return nil 190 | } 191 | 192 | type ExternRef struct { 193 | _inner C.WasmEdge_Value 194 | _valid bool 195 | } 196 | 197 | func NewExternRef(ptr interface{}) ExternRef { 198 | // Gen an i64 WasmEdge_Value and change type to externref 199 | idx := uint64(externRefMgr.add(ptr)) 200 | val := C.WasmEdge_ValueGenI64(C.int64_t(idx)) 201 | val.Type = C.WasmEdge_ValTypeGenExternRef() 202 | return ExternRef{ 203 | _inner: val, 204 | _valid: true, 205 | } 206 | } 207 | 208 | func (self ExternRef) Release() { 209 | self._valid = false 210 | // Change type back to WasmEdge_ValType_I64 and get the i64 value 211 | idx := uint(C.WasmEdge_ValueGetI64(self._inner)) 212 | externRefMgr.del(idx) 213 | } 214 | 215 | func (self ExternRef) GetRef() interface{} { 216 | if self._valid { 217 | // Get the original i64 value 218 | idx := uint(C.WasmEdge_ValueGetI64(self._inner)) 219 | return externRefMgr.get(idx) 220 | } 221 | return nil 222 | } 223 | 224 | type V128 struct { 225 | _inner C.WasmEdge_Value 226 | } 227 | 228 | func NewV128(high uint64, low uint64) V128 { 229 | var cval C.__int128 230 | var buf []byte 231 | sliceHeader := (*reflect.SliceHeader)((unsafe.Pointer(&buf))) 232 | sliceHeader.Cap = 16 233 | sliceHeader.Len = 16 234 | sliceHeader.Data = uintptr(unsafe.Pointer(&cval)) 235 | binary.LittleEndian.PutUint64(buf[:8], low) 236 | binary.LittleEndian.PutUint64(buf[8:], high) 237 | return V128{ 238 | _inner: C.WasmEdge_ValueGenV128(cval), 239 | } 240 | } 241 | 242 | func (self V128) GetVal() (uint64, uint64) { 243 | cval := C.WasmEdge_ValueGetV128(self._inner) 244 | var buf []byte 245 | sliceHeader := (*reflect.SliceHeader)((unsafe.Pointer(&buf))) 246 | sliceHeader.Cap = 16 247 | sliceHeader.Len = 16 248 | sliceHeader.Data = uintptr(unsafe.Pointer(&cval)) 249 | return binary.LittleEndian.Uint64(buf[8:]), binary.LittleEndian.Uint64(buf[:8]) 250 | } 251 | 252 | func toWasmEdgeValue(value interface{}) C.WasmEdge_Value { 253 | switch value.(type) { 254 | case FuncRef: 255 | return value.(FuncRef)._inner 256 | case ExternRef: 257 | if !value.(ExternRef)._valid { 258 | panic("External reference is released") 259 | } 260 | return value.(ExternRef)._inner 261 | case V128: 262 | return value.(V128)._inner 263 | case int: 264 | if unsafe.Sizeof(value.(int)) == 4 { 265 | return C.WasmEdge_ValueGenI32(C.int32_t(value.(int))) 266 | } else { 267 | return C.WasmEdge_ValueGenI64(C.int64_t(value.(int))) 268 | } 269 | case int32: 270 | return C.WasmEdge_ValueGenI32(C.int32_t(value.(int32))) 271 | case int64: 272 | return C.WasmEdge_ValueGenI64(C.int64_t(value.(int64))) 273 | case uint: 274 | if unsafe.Sizeof(value.(uint)) == 4 { 275 | return C.WasmEdge_ValueGenI32(C.int32_t(int32(value.(uint)))) 276 | } else { 277 | return C.WasmEdge_ValueGenI64(C.int64_t(int64(value.(uint)))) 278 | } 279 | case uint32: 280 | return C.WasmEdge_ValueGenI32(C.int32_t(int32(value.(uint32)))) 281 | case uint64: 282 | return C.WasmEdge_ValueGenI64(C.int64_t(int64(value.(uint64)))) 283 | case float32: 284 | return C.WasmEdge_ValueGenF32(C.float(value.(float32))) 285 | case float64: 286 | return C.WasmEdge_ValueGenF64(C.double(value.(float64))) 287 | default: 288 | panic("Wrong argument of toWasmEdgeValue()") 289 | } 290 | } 291 | 292 | func fromWasmEdgeValue(value C.WasmEdge_Value) interface{} { 293 | if C.WasmEdge_ValTypeIsI32(value.Type) { 294 | return int32(C.WasmEdge_ValueGetI32(value)) 295 | } 296 | if C.WasmEdge_ValTypeIsI64(value.Type) { 297 | return int64(C.WasmEdge_ValueGetI64(value)) 298 | } 299 | if C.WasmEdge_ValTypeIsF32(value.Type) { 300 | return float32(C.WasmEdge_ValueGetF32(value)) 301 | } 302 | if C.WasmEdge_ValTypeIsF64(value.Type) { 303 | return float64(C.WasmEdge_ValueGetF64(value)) 304 | } 305 | if C.WasmEdge_ValTypeIsV128(value.Type) { 306 | return V128{_inner: value} 307 | } 308 | if C.WasmEdge_ValTypeIsFuncRef(value.Type) { 309 | return FuncRef{_inner: value} 310 | } 311 | if C.WasmEdge_ValTypeIsExternRef(value.Type) { 312 | idx := uint(C.WasmEdge_ValueGetI64(value)) 313 | if _, ok := externRefMgr.ref[idx]; ok { 314 | return ExternRef{_inner: value, _valid: true} 315 | } 316 | return ExternRef{_inner: value, _valid: false} 317 | } 318 | if C.WasmEdge_ValTypeIsRef(value.Type) { 319 | return "externref" 320 | } 321 | panic("Wrong argument of fromWasmEdgeValue()") 322 | } 323 | 324 | func toWasmEdgeValueSlide(vals ...interface{}) []C.WasmEdge_Value { 325 | cvals := make([]C.WasmEdge_Value, len(vals)) 326 | for i, val := range vals { 327 | cvals[i] = toWasmEdgeValue(val) 328 | } 329 | return cvals 330 | } 331 | 332 | func toWasmEdgeValueSlideBindgen(vm *VM, rettype bindgen, modname *string, vals ...interface{}) []C.WasmEdge_Value { 333 | //cvals := make([]C.WasmEdge_Value, len(vals)) 334 | cvals := []C.WasmEdge_Value{} 335 | if rettype == Bindgen_return_array { 336 | // Array result address = 8 337 | cvals = append(cvals, C.WasmEdge_ValueGenI32(C.int32_t(8))) 338 | } else if rettype == Bindgen_return_i64 { 339 | // wasm-bindgen magic: Set memory offset for i64 return value 340 | cvals = append(cvals, C.WasmEdge_ValueGenI32(C.int32_t(0))) 341 | } 342 | for _, val := range vals { 343 | switch t := val.(type) { 344 | case FuncRef: 345 | panic("toWasmEdgeValueSlideBindgen(): Not support FuncRef now") 346 | case ExternRef: 347 | panic("toWasmEdgeValueSlideBindgen(): Not support ExternRef now") 348 | case V128: 349 | panic("toWasmEdgeValueSlideBindgen(): Not support v128 now") 350 | case int32: 351 | cvals = append(cvals, C.WasmEdge_ValueGenI32(C.int32_t(val.(int32)))) 352 | case uint32: 353 | cvals = append(cvals, C.WasmEdge_ValueGenI32(C.int32_t(val.(uint32)))) 354 | case int64: 355 | vall := C.WasmEdge_ValueGenI32(C.int32_t(uint32(val.(int64)))) 356 | valu := C.WasmEdge_ValueGenI32(C.int32_t(uint32(val.(int64) >> 32))) 357 | cvals = append(cvals, vall, valu) 358 | case uint64: 359 | vall := C.WasmEdge_ValueGenI32(C.int32_t(uint32(val.(uint64)))) 360 | valu := C.WasmEdge_ValueGenI32(C.int32_t(uint32(val.(uint64) >> 32))) 361 | cvals = append(cvals, vall, valu) 362 | case int: 363 | panic("toWasmEdgeValueSlideBindgen(): Not support int now, please use int32 or int64 instead") 364 | case uint: 365 | panic("toWasmEdgeValueSlideBindgen(): Not support uint now, please use uint32 or uint64 instead") 366 | case float32: 367 | panic("toWasmEdgeValueSlideBindgen(): Not support float32 now") 368 | case float64: 369 | panic("toWasmEdgeValueSlideBindgen(): Not support float64 now") 370 | case []byte: 371 | // Call malloc function 372 | mallocsize := uint32(len(val.([]byte))) 373 | var rets []interface{} 374 | var err error = nil 375 | if modname == nil { 376 | rets, err = vm.Execute("__wbindgen_malloc", mallocsize) 377 | } else { 378 | rets, err = vm.ExecuteRegistered(*modname, "__wbindgen_malloc", mallocsize) 379 | } 380 | if err != nil { 381 | panic("toWasmEdgeValueSlideBindgen(): malloc failed") 382 | } 383 | if len(rets) <= 0 { 384 | panic("toWasmEdgeValueSlideBindgen(): malloc function signature unexpected") 385 | } 386 | argaddr := C.WasmEdge_ValueGenI32(C.int32_t(rets[0].(int32))) 387 | argsize := C.WasmEdge_ValueGenI32(C.int32_t(mallocsize)) 388 | cvals = append(cvals, argaddr, argsize) 389 | // Set bytes 390 | var mod *Module = nil 391 | var mem *Memory = nil 392 | if modname == nil { 393 | mod = vm.GetActiveModule() 394 | } else { 395 | store := vm.GetStore() 396 | mod = store.FindModule(*modname) 397 | } 398 | if mod != nil { 399 | memnames := mod.ListMemory() 400 | if len(memnames) <= 0 { 401 | panic("toWasmEdgeValueSlideBindgen(): memory instance not found") 402 | } 403 | mem = mod.FindMemory(memnames[0]) 404 | mem.SetData(val.([]byte), uint(rets[0].(int32)), uint(mallocsize)) 405 | } 406 | default: 407 | errorString := fmt.Sprintf("Wrong argument of toWasmEdgeValueSlideBindgen(): %T not supported", t) 408 | panic(errorString) 409 | } 410 | } 411 | return cvals 412 | } 413 | 414 | func fromWasmEdgeValueSlide(cvals []C.WasmEdge_Value) []interface{} { 415 | if len(cvals) > 0 { 416 | vals := make([]interface{}, len(cvals)) 417 | for i, cval := range cvals { 418 | vals[i] = fromWasmEdgeValue(cval) 419 | } 420 | return vals 421 | } 422 | return []interface{}{} 423 | } 424 | 425 | func fromWasmEdgeValueSlideBindgen(vm *VM, rettype bindgen, modname *string, cvals []C.WasmEdge_Value) (interface{}, error) { 426 | returns := fromWasmEdgeValueSlide(cvals) 427 | switch rettype { 428 | case Bindgen_return_void: 429 | return nil, nil 430 | case Bindgen_return_i32: 431 | if len(returns) <= 0 { 432 | panic("Expected return i32, but got empty") 433 | } 434 | return returns[0], nil 435 | case Bindgen_return_i64: 436 | // Get memory context 437 | var mod *Module = nil 438 | var mem *Memory = nil 439 | if modname == nil { 440 | mod = vm.GetActiveModule() 441 | } else { 442 | store := vm.GetStore() 443 | mod = store.FindModule(*modname) 444 | } 445 | if mod != nil { 446 | memnames := mod.ListMemory() 447 | if len(memnames) > 0 { 448 | mem = mod.FindMemory(memnames[0]) 449 | } 450 | } 451 | // Get int64 452 | if mem == nil { 453 | panic("fromWasmEdgeValueSlideBindgen(): memory instance not found") 454 | } 455 | buf, err := mem.GetData(0, 8) 456 | if err != nil { 457 | return nil, err 458 | } 459 | var num int64 = 0 460 | for i, val := range buf { 461 | num += int64(val) << (i * 8) 462 | } 463 | return num, nil 464 | case Bindgen_return_array: 465 | // Get memory context 466 | var mod *Module = nil 467 | var mem *Memory = nil 468 | if modname == nil { 469 | mod = vm.GetActiveModule() 470 | } else { 471 | store := vm.GetStore() 472 | mod = store.FindModule(*modname) 473 | } 474 | if mod != nil { 475 | memnames := mod.ListMemory() 476 | if len(memnames) > 0 { 477 | mem = mod.FindMemory(memnames[0]) 478 | } 479 | } 480 | // Get address and length (array result address = 8) 481 | if mem == nil { 482 | panic("fromWasmEdgeValueSlideBindgen(): memory instance not found") 483 | } 484 | buf, err := mem.GetData(8, 8) 485 | if err != nil { 486 | return nil, err 487 | } 488 | var num int64 = 0 489 | for i, val := range buf { 490 | num += int64(val) << (i * 8) 491 | } 492 | // Get bytes 493 | var arraddr = int32(num) 494 | var arrlen = int32(num >> 32) 495 | buf, err = mem.GetData(uint(arraddr), uint(arrlen)) 496 | if err != nil { 497 | return nil, err 498 | } 499 | // Free array 500 | if modname == nil { 501 | _, err = vm.Execute("__wbindgen_free", arraddr, arrlen) 502 | } else { 503 | _, err = vm.ExecuteRegistered(*modname, "__wbindgen_free", arraddr, arrlen) 504 | } 505 | if err != nil { 506 | panic("fromWasmEdgeValueSlideBindgen(): malloc failed") 507 | } 508 | return buf, nil 509 | default: 510 | panic("Wrong expected return type") 511 | } 512 | } 513 | -------------------------------------------------------------------------------- /wasmedge/version.go: -------------------------------------------------------------------------------- 1 | package wasmedge 2 | 3 | // #include 4 | import "C" 5 | 6 | func GetVersion() string { 7 | return C.GoString(C.WasmEdge_VersionGet()) 8 | } 9 | 10 | func GetVersionMajor() uint { 11 | return uint(C.WasmEdge_VersionGetMajor()) 12 | } 13 | 14 | func GetVersionMinor() uint { 15 | return uint(C.WasmEdge_VersionGetMinor()) 16 | } 17 | 18 | func GetVersionPatch() uint { 19 | return uint(C.WasmEdge_VersionGetPatch()) 20 | } 21 | -------------------------------------------------------------------------------- /wasmedge/vm.go: -------------------------------------------------------------------------------- 1 | package wasmedge 2 | 3 | /* 4 | #include 5 | #include 6 | 7 | size_t _GoStringLen(_GoString_ s); 8 | const char *_GoStringPtr(_GoString_ s); 9 | */ 10 | import "C" 11 | import ( 12 | "unsafe" 13 | ) 14 | 15 | type VM struct { 16 | _inner *C.WasmEdge_VMContext 17 | _own bool 18 | } 19 | 20 | type bindgen int 21 | 22 | const ( 23 | Bindgen_return_void bindgen = iota 24 | Bindgen_return_i32 bindgen = iota 25 | Bindgen_return_i64 bindgen = iota 26 | Bindgen_return_array bindgen = iota 27 | ) 28 | 29 | func NewVM() *VM { 30 | vm := C.WasmEdge_VMCreate(nil, nil) 31 | if vm == nil { 32 | return nil 33 | } 34 | return &VM{_inner: vm, _own: true} 35 | } 36 | 37 | func NewVMWithConfig(conf *Configure) *VM { 38 | vm := C.WasmEdge_VMCreate(conf._inner, nil) 39 | if vm == nil { 40 | return nil 41 | } 42 | return &VM{_inner: vm, _own: true} 43 | } 44 | 45 | func NewVMWithStore(store *Store) *VM { 46 | vm := C.WasmEdge_VMCreate(nil, store._inner) 47 | if vm == nil { 48 | return nil 49 | } 50 | return &VM{_inner: vm, _own: true} 51 | } 52 | 53 | func NewVMWithConfigAndStore(conf *Configure, store *Store) *VM { 54 | vm := C.WasmEdge_VMCreate(conf._inner, store._inner) 55 | if vm == nil { 56 | return nil 57 | } 58 | return &VM{_inner: vm, _own: true} 59 | } 60 | 61 | func (self *VM) RegisterWasmFile(modname string, path string) error { 62 | modstr := toWasmEdgeStringWrap(modname) 63 | var cpath = C.CString(path) 64 | defer C.free(unsafe.Pointer(cpath)) 65 | res := C.WasmEdge_VMRegisterModuleFromFile(self._inner, modstr, cpath) 66 | if !C.WasmEdge_ResultOK(res) { 67 | return newError(res) 68 | } 69 | return nil 70 | } 71 | 72 | func (self *VM) RegisterWasmBuffer(modname string, buf []byte) error { 73 | modstr := toWasmEdgeStringWrap(modname) 74 | cbytes := C.WasmEdge_BytesWrap((*C.uint8_t)(unsafe.Pointer(&buf[0])), C.uint32_t(len(buf))) 75 | res := C.WasmEdge_VMRegisterModuleFromBytes(self._inner, modstr, cbytes) 76 | if !C.WasmEdge_ResultOK(res) { 77 | return newError(res) 78 | } 79 | return nil 80 | } 81 | 82 | func (self *VM) RegisterAST(modname string, ast *AST) error { 83 | modstr := toWasmEdgeStringWrap(modname) 84 | res := C.WasmEdge_VMRegisterModuleFromASTModule(self._inner, modstr, ast._inner) 85 | if !C.WasmEdge_ResultOK(res) { 86 | return newError(res) 87 | } 88 | return nil 89 | } 90 | 91 | func (self *VM) RegisterModule(module *Module) error { 92 | res := C.WasmEdge_VMRegisterModuleFromImport(self._inner, module._inner) 93 | if !C.WasmEdge_ResultOK(res) { 94 | return newError(res) 95 | } 96 | return nil 97 | } 98 | 99 | func (self *VM) runWasm(funcname string, params ...interface{}) ([]interface{}, error) { 100 | res := C.WasmEdge_VMValidate(self._inner) 101 | if !C.WasmEdge_ResultOK(res) { 102 | return nil, newError(res) 103 | } 104 | res = C.WasmEdge_VMInstantiate(self._inner) 105 | if !C.WasmEdge_ResultOK(res) { 106 | return nil, newError(res) 107 | } 108 | return self.Execute(funcname, params...) 109 | } 110 | 111 | func (self *VM) RunWasmFile(path string, funcname string, params ...interface{}) ([]interface{}, error) { 112 | cpath := C.CString(path) 113 | defer C.free(unsafe.Pointer(cpath)) 114 | res := C.WasmEdge_VMLoadWasmFromFile(self._inner, cpath) 115 | if !C.WasmEdge_ResultOK(res) { 116 | return nil, newError(res) 117 | } 118 | return self.runWasm(funcname, params...) 119 | } 120 | 121 | func (self *VM) RunWasmBuffer(buf []byte, funcname string, params ...interface{}) ([]interface{}, error) { 122 | cbytes := C.WasmEdge_BytesWrap((*C.uint8_t)(unsafe.Pointer(&buf[0])), C.uint32_t(len(buf))) 123 | res := C.WasmEdge_VMLoadWasmFromBytes(self._inner, cbytes) 124 | if !C.WasmEdge_ResultOK(res) { 125 | return nil, newError(res) 126 | } 127 | return self.runWasm(funcname, params...) 128 | } 129 | 130 | func (self *VM) RunWasmAST(ast *AST, funcname string, params ...interface{}) ([]interface{}, error) { 131 | res := C.WasmEdge_VMLoadWasmFromASTModule(self._inner, ast._inner) 132 | if !C.WasmEdge_ResultOK(res) { 133 | return nil, newError(res) 134 | } 135 | return self.runWasm(funcname, params...) 136 | } 137 | 138 | func (self *VM) AsyncRunWasmFile(path string, funcname string, params ...interface{}) *Async { 139 | cpath := C.CString(path) 140 | defer C.free(unsafe.Pointer(cpath)) 141 | funcstr := toWasmEdgeStringWrap(funcname) 142 | cparams := toWasmEdgeValueSlide(params...) 143 | var ptrparams *C.WasmEdge_Value = nil 144 | if len(cparams) > 0 { 145 | ptrparams = (*C.WasmEdge_Value)(unsafe.Pointer(&cparams[0])) 146 | } 147 | async := C.WasmEdge_VMAsyncRunWasmFromFile( 148 | self._inner, cpath, funcstr, ptrparams, C.uint32_t(len(cparams))) 149 | if async == nil { 150 | return nil 151 | } 152 | return &Async{_inner: async, _own: true} 153 | } 154 | 155 | func (self *VM) AsyncRunWasmBuffer(buf []byte, funcname string, params ...interface{}) *Async { 156 | funcstr := toWasmEdgeStringWrap(funcname) 157 | cparams := toWasmEdgeValueSlide(params...) 158 | var ptrparams *C.WasmEdge_Value = nil 159 | if len(cparams) > 0 { 160 | ptrparams = (*C.WasmEdge_Value)(unsafe.Pointer(&cparams[0])) 161 | } 162 | cbytes := C.WasmEdge_BytesWrap((*C.uint8_t)(unsafe.Pointer(&buf[0])), C.uint32_t(len(buf))) 163 | async := C.WasmEdge_VMAsyncRunWasmFromBytes(self._inner, cbytes, funcstr, ptrparams, C.uint32_t(len(cparams))) 164 | if async == nil { 165 | return nil 166 | } 167 | return &Async{_inner: async, _own: true} 168 | } 169 | 170 | func (self *VM) AsyncRunWasmAST(ast *AST, funcname string, params ...interface{}) *Async { 171 | funcstr := toWasmEdgeStringWrap(funcname) 172 | cparams := toWasmEdgeValueSlide(params...) 173 | var ptrparams *C.WasmEdge_Value = nil 174 | if len(cparams) > 0 { 175 | ptrparams = (*C.WasmEdge_Value)(unsafe.Pointer(&cparams[0])) 176 | } 177 | async := C.WasmEdge_VMAsyncRunWasmFromASTModule( 178 | self._inner, ast._inner, funcstr, ptrparams, C.uint32_t(len(cparams))) 179 | if async == nil { 180 | return nil 181 | } 182 | return &Async{_inner: async, _own: true} 183 | } 184 | 185 | func (self *VM) LoadWasmFile(path string) error { 186 | cpath := C.CString(path) 187 | defer C.free(unsafe.Pointer(cpath)) 188 | res := C.WasmEdge_VMLoadWasmFromFile(self._inner, cpath) 189 | if !C.WasmEdge_ResultOK(res) { 190 | return newError(res) 191 | } 192 | return nil 193 | } 194 | 195 | func (self *VM) LoadWasmBuffer(buf []byte) error { 196 | cbytes := C.WasmEdge_BytesWrap((*C.uint8_t)(unsafe.Pointer(&buf[0])), C.uint32_t(len(buf))) 197 | res := C.WasmEdge_VMLoadWasmFromBytes(self._inner, cbytes) 198 | if !C.WasmEdge_ResultOK(res) { 199 | return newError(res) 200 | } 201 | return nil 202 | } 203 | 204 | func (self *VM) LoadWasmAST(ast *AST) error { 205 | res := C.WasmEdge_VMLoadWasmFromASTModule(self._inner, ast._inner) 206 | if !C.WasmEdge_ResultOK(res) { 207 | return newError(res) 208 | } 209 | return nil 210 | } 211 | 212 | func (self *VM) Validate() error { 213 | res := C.WasmEdge_VMValidate(self._inner) 214 | if !C.WasmEdge_ResultOK(res) { 215 | return newError(res) 216 | } 217 | return nil 218 | } 219 | 220 | func (self *VM) Instantiate() error { 221 | res := C.WasmEdge_VMInstantiate(self._inner) 222 | if !C.WasmEdge_ResultOK(res) { 223 | return newError(res) 224 | } 225 | return nil 226 | } 227 | 228 | func (self *VM) Execute(funcname string, params ...interface{}) ([]interface{}, error) { 229 | funcstr := toWasmEdgeStringWrap(funcname) 230 | ftype := self.GetFunctionType(funcname) 231 | if ftype == nil { 232 | // If get function type failed, set as NULL and keep running to let the VM to handle the error. 233 | ftype = &FunctionType{_inner: nil, _own: false} 234 | } 235 | cparams := toWasmEdgeValueSlide(params...) 236 | creturns := make([]C.WasmEdge_Value, ftype.GetReturnsLength()) 237 | var ptrparams *C.WasmEdge_Value = nil 238 | var ptrreturns *C.WasmEdge_Value = nil 239 | if len(cparams) > 0 { 240 | ptrparams = (*C.WasmEdge_Value)(unsafe.Pointer(&cparams[0])) 241 | } 242 | if len(creturns) > 0 { 243 | ptrreturns = (*C.WasmEdge_Value)(unsafe.Pointer(&creturns[0])) 244 | } 245 | res := C.WasmEdge_VMExecute( 246 | self._inner, funcstr, 247 | ptrparams, C.uint32_t(len(cparams)), 248 | ptrreturns, C.uint32_t(len(creturns))) 249 | if !C.WasmEdge_ResultOK(res) { 250 | return nil, newError(res) 251 | } 252 | return fromWasmEdgeValueSlide(creturns), nil 253 | } 254 | 255 | func (self *VM) AsyncExecute(funcname string, params ...interface{}) *Async { 256 | funcstr := toWasmEdgeStringWrap(funcname) 257 | cparams := toWasmEdgeValueSlide(params...) 258 | var ptrparams *C.WasmEdge_Value = nil 259 | if len(cparams) > 0 { 260 | ptrparams = (*C.WasmEdge_Value)(unsafe.Pointer(&cparams[0])) 261 | } 262 | async := C.WasmEdge_VMAsyncExecute(self._inner, funcstr, ptrparams, C.uint32_t(len(cparams))) 263 | if async == nil { 264 | return nil 265 | } 266 | return &Async{_inner: async, _own: true} 267 | } 268 | 269 | // Special execute function for running with wasm-bindgen. 270 | func (self *VM) ExecuteBindgen(funcname string, rettype bindgen, params ...interface{}) (interface{}, error) { 271 | funcstr := toWasmEdgeStringWrap(funcname) 272 | ftype := self.GetFunctionType(funcname) 273 | if ftype == nil { 274 | // If get function type failed, set as NULL and keep running to let the VM to handle the error. 275 | ftype = &FunctionType{_inner: nil, _own: false} 276 | } 277 | cparams := toWasmEdgeValueSlideBindgen(self, rettype, nil, params...) 278 | creturns := make([]C.WasmEdge_Value, ftype.GetReturnsLength()) 279 | var ptrparams *C.WasmEdge_Value = nil 280 | var ptrreturns *C.WasmEdge_Value = nil 281 | if len(cparams) > 0 { 282 | ptrparams = (*C.WasmEdge_Value)(unsafe.Pointer(&cparams[0])) 283 | } 284 | if len(creturns) > 0 { 285 | ptrreturns = (*C.WasmEdge_Value)(unsafe.Pointer(&creturns[0])) 286 | } 287 | res := C.WasmEdge_VMExecute( 288 | self._inner, funcstr, 289 | ptrparams, C.uint32_t(len(cparams)), 290 | ptrreturns, C.uint32_t(len(creturns))) 291 | if !C.WasmEdge_ResultOK(res) { 292 | return nil, newError(res) 293 | } 294 | return fromWasmEdgeValueSlideBindgen(self, rettype, nil, creturns) 295 | } 296 | 297 | func (self *VM) ExecuteRegistered(modname string, funcname string, params ...interface{}) ([]interface{}, error) { 298 | modstr := toWasmEdgeStringWrap(modname) 299 | funcstr := toWasmEdgeStringWrap(funcname) 300 | ftype := self.GetFunctionTypeRegistered(modname, funcname) 301 | if ftype == nil { 302 | // If get function type failed, set as NULL and keep running to let the VM to handle the error. 303 | ftype = &FunctionType{_inner: nil, _own: false} 304 | } 305 | cparams := toWasmEdgeValueSlide(params...) 306 | creturns := make([]C.WasmEdge_Value, ftype.GetReturnsLength()) 307 | var ptrparams *C.WasmEdge_Value = nil 308 | var ptrreturns *C.WasmEdge_Value = nil 309 | if len(cparams) > 0 { 310 | ptrparams = (*C.WasmEdge_Value)(unsafe.Pointer(&cparams[0])) 311 | } 312 | if len(creturns) > 0 { 313 | ptrreturns = (*C.WasmEdge_Value)(unsafe.Pointer(&creturns[0])) 314 | } 315 | res := C.WasmEdge_VMExecuteRegistered( 316 | self._inner, modstr, funcstr, 317 | ptrparams, C.uint32_t(len(cparams)), 318 | ptrreturns, C.uint32_t(len(creturns))) 319 | if !C.WasmEdge_ResultOK(res) { 320 | return nil, newError(res) 321 | } 322 | return fromWasmEdgeValueSlide(creturns), nil 323 | } 324 | 325 | func (self *VM) AsyncExecuteRegistered(modname string, funcname string, params ...interface{}) *Async { 326 | modstr := toWasmEdgeStringWrap(modname) 327 | funcstr := toWasmEdgeStringWrap(funcname) 328 | cparams := toWasmEdgeValueSlide(params...) 329 | var ptrparams *C.WasmEdge_Value = nil 330 | if len(cparams) > 0 { 331 | ptrparams = (*C.WasmEdge_Value)(unsafe.Pointer(&cparams[0])) 332 | } 333 | async := C.WasmEdge_VMAsyncExecuteRegistered(self._inner, modstr, funcstr, ptrparams, C.uint32_t(len(cparams))) 334 | if async == nil { 335 | return nil 336 | } 337 | return &Async{_inner: async, _own: true} 338 | } 339 | 340 | // Special execute function for running with wasm-bindgen. 341 | func (self *VM) ExecuteBindgenRegistered(modname string, funcname string, rettype bindgen, params ...interface{}) (interface{}, error) { 342 | modstr := toWasmEdgeStringWrap(modname) 343 | funcstr := toWasmEdgeStringWrap(funcname) 344 | ftype := self.GetFunctionType(funcname) 345 | if ftype == nil { 346 | // If get function type failed, set as NULL and keep running to let the VM to handle the error. 347 | ftype = &FunctionType{_inner: nil, _own: false} 348 | } 349 | cparams := toWasmEdgeValueSlideBindgen(self, rettype, &modname, params...) 350 | creturns := make([]C.WasmEdge_Value, ftype.GetReturnsLength()) 351 | var ptrparams *C.WasmEdge_Value = nil 352 | var ptrreturns *C.WasmEdge_Value = nil 353 | if len(cparams) > 0 { 354 | ptrparams = (*C.WasmEdge_Value)(unsafe.Pointer(&cparams[0])) 355 | } 356 | if len(creturns) > 0 { 357 | ptrreturns = (*C.WasmEdge_Value)(unsafe.Pointer(&creturns[0])) 358 | } 359 | 360 | res := C.WasmEdge_VMExecuteRegistered( 361 | self._inner, modstr, funcstr, 362 | ptrparams, C.uint32_t(len(cparams)), 363 | ptrreturns, C.uint32_t(len(creturns))) 364 | if !C.WasmEdge_ResultOK(res) { 365 | return nil, newError(res) 366 | } 367 | return fromWasmEdgeValueSlideBindgen(self, rettype, &modname, creturns) 368 | } 369 | 370 | func (self *VM) GetFunctionType(funcname string) *FunctionType { 371 | funcstr := toWasmEdgeStringWrap(funcname) 372 | cftype := C.WasmEdge_VMGetFunctionType(self._inner, funcstr) 373 | if cftype == nil { 374 | return nil 375 | } 376 | return &FunctionType{_inner: cftype, _own: false} 377 | } 378 | 379 | func (self *VM) GetFunctionTypeRegistered(modname string, funcname string) *FunctionType { 380 | modstr := toWasmEdgeStringWrap(modname) 381 | funcstr := toWasmEdgeStringWrap(funcname) 382 | cftype := C.WasmEdge_VMGetFunctionTypeRegistered(self._inner, modstr, funcstr) 383 | if cftype == nil { 384 | return nil 385 | } 386 | return &FunctionType{_inner: cftype, _own: false} 387 | } 388 | 389 | func (self *VM) Cleanup() { 390 | C.WasmEdge_VMCleanup(self._inner) 391 | } 392 | 393 | func (self *VM) GetFunctionList() ([]string, []*FunctionType) { 394 | funclen := C.WasmEdge_VMGetFunctionListLength(self._inner) 395 | cfnames := make([]C.WasmEdge_String, int(funclen)) 396 | cftypes := make([]*C.WasmEdge_FunctionTypeContext, int(funclen)) 397 | if int(funclen) > 0 { 398 | C.WasmEdge_VMGetFunctionList(self._inner, &cfnames[0], &cftypes[0], funclen) 399 | } 400 | fnames := make([]string, int(funclen)) 401 | ftypes := make([]*FunctionType, int(funclen)) 402 | for i := 0; i < int(funclen); i++ { 403 | fnames[i] = fromWasmEdgeString(cfnames[i]) 404 | ftypes[i] = &FunctionType{_inner: cftypes[i]} 405 | } 406 | return fnames, ftypes 407 | } 408 | 409 | func (self *VM) GetImportModule(host HostRegistration) *Module { 410 | ptr := C.WasmEdge_VMGetImportModuleContext(self._inner, C.enum_WasmEdge_HostRegistration(host)) 411 | if ptr != nil { 412 | return &Module{_inner: ptr, _own: false} 413 | } 414 | return nil 415 | } 416 | 417 | func (self *VM) GetActiveModule() *Module { 418 | ptr := C.WasmEdge_VMGetActiveModule(self._inner) 419 | if ptr != nil { 420 | return &Module{_inner: ptr, _own: false} 421 | } 422 | return nil 423 | } 424 | 425 | func (self *VM) GetRegisteredModule(name string) *Module { 426 | cname := toWasmEdgeStringWrap(name) 427 | ptr := C.WasmEdge_VMGetRegisteredModule(self._inner, cname) 428 | if ptr != nil { 429 | return &Module{_inner: ptr, _own: false} 430 | } 431 | return nil 432 | } 433 | 434 | func (self *VM) ListRegisteredModule() []string { 435 | modlen := C.WasmEdge_VMListRegisteredModuleLength(self._inner) 436 | cnames := make([]C.WasmEdge_String, int(modlen)) 437 | if int(modlen) > 0 { 438 | C.WasmEdge_VMListRegisteredModule(self._inner, &cnames[0], modlen) 439 | } 440 | names := make([]string, int(modlen)) 441 | for i := 0; i < int(modlen); i++ { 442 | names[i] = fromWasmEdgeString(cnames[i]) 443 | } 444 | return names 445 | } 446 | 447 | func (self *VM) GetStore() *Store { 448 | return &Store{_inner: C.WasmEdge_VMGetStoreContext(self._inner), _own: false} 449 | } 450 | 451 | func (self *VM) GetLoader() *Loader { 452 | return &Loader{_inner: C.WasmEdge_VMGetLoaderContext(self._inner), _own: false} 453 | } 454 | 455 | func (self *VM) GetValidator() *Validator { 456 | return &Validator{_inner: C.WasmEdge_VMGetValidatorContext(self._inner), _own: false} 457 | } 458 | 459 | func (self *VM) GetExecutor() *Executor { 460 | return &Executor{_inner: C.WasmEdge_VMGetExecutorContext(self._inner), _own: false} 461 | } 462 | 463 | func (self *VM) GetStatistics() *Statistics { 464 | return &Statistics{_inner: C.WasmEdge_VMGetStatisticsContext(self._inner), _own: false} 465 | } 466 | 467 | func (self *VM) Release() { 468 | if self._own { 469 | C.WasmEdge_VMDelete(self._inner) 470 | } 471 | self._inner = nil 472 | self._own = false 473 | } 474 | --------------------------------------------------------------------------------