From 47259c497b3fadc2afe1fe7cedbbb165736f2465 Mon Sep 17 00:00:00 2001 From: chai2010 Date: Sat, 3 Sep 2022 23:22:30 +0800 Subject: [PATCH] =?UTF-8?q?wasm=20=E5=91=BD=E4=BB=A4=E8=A1=8C=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0=20run=20=E6=89=A7=E8=A1=8C=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- go.mod | 5 ++++- go.sum | 2 ++ internal/app/wabt_wat2wasm.go | 41 ++++++++++++++++++++++++++++++++++- 3 files changed, 46 insertions(+), 2 deletions(-) diff --git a/go.mod b/go.mod index f493bab..4149181 100644 --- a/go.mod +++ b/go.mod @@ -4,4 +4,7 @@ module github.com/wa-lang/wa go 1.17 -require github.com/wa-lang/wabt-go v1.1.0 // indirect +require ( + github.com/tetratelabs/wazero v1.0.0-pre.1 // indirect + github.com/wa-lang/wabt-go v1.1.0 // indirect +) diff --git a/go.sum b/go.sum index 4b2b33e..f77e863 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +1,4 @@ +github.com/tetratelabs/wazero v1.0.0-pre.1 h1:bUZ4vf21c36RmgA3enNOlLgPElEVDYoRJJ9+McRGF6Q= +github.com/tetratelabs/wazero v1.0.0-pre.1/go.mod h1:M8UDNECGm/HVjOfq0EOe4QfCY9Les1eq54IChMLETbc= github.com/wa-lang/wabt-go v1.1.0 h1:0ois7H69M+6lJhjqU/3c5HxTGeQjwTW0Ncj+SLEW96o= github.com/wa-lang/wabt-go v1.1.0/go.mod h1:I/qIi3rHMN4ECgmZ8FzYwpNr2KfLs4TiXuTi7Ql7H3g= diff --git a/internal/app/wabt_wat2wasm.go b/internal/app/wabt_wat2wasm.go index 5651773..f1a5c3d 100644 --- a/internal/app/wabt_wat2wasm.go +++ b/internal/app/wabt_wat2wasm.go @@ -3,6 +3,7 @@ package app import ( + "context" "errors" "fmt" "os" @@ -11,6 +12,10 @@ import ( "runtime" "strings" + "github.com/tetratelabs/wazero" + "github.com/tetratelabs/wazero/api" + "github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1" + "github.com/wa-lang/wa/internal/config" "github.com/wa-lang/wa/internal/logger" "github.com/wa-lang/wabt-go" @@ -27,7 +32,41 @@ func RunWasm(filename string) (stdoutStderr []byte, err error) { } } - return nil, fmt.Errorf("TODO: run wasm") + wasmBytes, err := os.ReadFile(dst) + if err != nil { + return nil, err + } + + ctx := context.Background() + r := wazero.NewRuntimeWithConfig(ctx, + wazero.NewRuntimeConfig().WithWasmCore2(), + ) + defer r.Close(ctx) + + if false { + if _, err := wasi_snapshot_preview1.Instantiate(ctx, r); err != nil { + return nil, err + } + } + _, err = r.NewModuleBuilder("wasi_snapshot_preview1"). + ExportFunction("fd_write", func(m api.Module, fd, iov, iov_len, p_nwritten uint32) uint32 { + pos, _ := m.Memory().ReadUint32Le(ctx, iov) + n, _ := m.Memory().ReadUint32Le(ctx, iov+4) + bytes, _ := m.Memory().Read(ctx, pos, n) + fmt.Print(string(bytes)) + return 0 + }). + Instantiate(ctx, r) + if err != nil { + return nil, err + } + + _, err = r.InstantiateModuleFromBinary(ctx, wasmBytes) + if err != nil { + return nil, err + } + + return nil, nil } func InstallWat2wasm(path string) error { -- GitLab