From 126bd9050d3a1a19d74ca82f5875e5ce766fd2e8 Mon Sep 17 00:00:00 2001 From: Crypt Keeper <64215+codefromthecrypt@users.noreply.github.com> Date: Wed, 14 Dec 2022 16:08:07 +0900 Subject: [PATCH] Removes context parameter from instruction-scoped operations (#923) We originally had a `context.Context` for anything that might be traced, but it turned out to be only useful for lifecycle and host functions. For instruction-scoped aspects like memory updates, a context parameter is too fine-grained and also invisible in practice. For example, most users will use the compiler engine, and its memory, global or table access will never use go's context. Signed-off-by: Adrian Cole --- RATIONALE.md | 11 + api/wasm.go | 48 ++-- config_test.go | 47 ++-- examples/allocation/rust/greet.go | 10 +- examples/allocation/tinygo/greet.go | 12 +- examples/allocation/zig/greet.go | 12 +- imports/assemblyscript/assemblyscript.go | 22 +- imports/assemblyscript/assemblyscript_test.go | 40 +-- imports/go/gojs.go | 2 +- imports/wasi_snapshot_preview1/args.go | 2 +- imports/wasi_snapshot_preview1/args_test.go | 12 +- imports/wasi_snapshot_preview1/clock.go | 6 +- imports/wasi_snapshot_preview1/clock_test.go | 10 +- imports/wasi_snapshot_preview1/environ.go | 4 +- .../wasi_snapshot_preview1/environ_test.go | 12 +- imports/wasi_snapshot_preview1/fs.go | 56 ++-- imports/wasi_snapshot_preview1/fs_test.go | 92 +++---- imports/wasi_snapshot_preview1/poll.go | 10 +- imports/wasi_snapshot_preview1/poll_test.go | 16 +- imports/wasi_snapshot_preview1/random.go | 2 +- imports/wasi_snapshot_preview1/random_test.go | 6 +- imports/wasi_snapshot_preview1/wasi.go | 6 +- .../wasi_snapshot_preview1/wasi_bench_test.go | 6 +- imports/wasi_snapshot_preview1/wasi_test.go | 4 +- internal/engine/compiler/engine.go | 12 +- internal/engine/compiler/engine_test.go | 2 +- internal/engine/interpreter/interpreter.go | 82 +++--- internal/gojs/argsenv.go | 7 +- internal/gojs/runtime.go | 16 +- internal/gojs/spfunc/spfunc_test.go | 2 +- internal/gojs/state.go | 2 +- internal/gojs/syscall.go | 14 +- internal/gojs/util.go | 17 +- internal/integration_test/bench/bench_test.go | 6 +- .../bench/hostfunc_bench_test.go | 8 +- .../bench/memory_bench_test.go | 10 +- .../integration_test/engine/adhoc_test.go | 12 +- internal/integration_test/fs/fs_test.go | 14 +- .../fuzzcases/fuzzcases_test.go | 2 +- .../integration_test/spectest/spectest.go | 2 +- .../integration_test/vs/bench_allocation.go | 2 +- internal/integration_test/vs/runtime.go | 10 +- .../integration_test/vs/wasmedge/wasmedge.go | 2 +- internal/integration_test/vs/wasmer/wasmer.go | 2 +- .../integration_test/vs/wasmtime/wasmtime.go | 2 +- internal/platform/time.go | 14 +- internal/platform/time_test.go | 23 +- internal/sys/sys.go | 13 +- internal/sys/sys_test.go | 8 +- internal/testing/enginetest/enginetest.go | 10 +- internal/wasm/global.go | 23 +- internal/wasm/global_test.go | 22 +- internal/wasm/memory.go | 37 ++- internal/wasm/memory_test.go | 257 ++++++++---------- internal/wasm/store_test.go | 2 +- internal/wasm/table.go | 3 +- internal/wasm/table_test.go | 2 +- runtime_test.go | 8 +- sys/clock.go | 8 +- 59 files changed, 526 insertions(+), 578 deletions(-) diff --git a/RATIONALE.md b/RATIONALE.md index bb28a304..36720196 100644 --- a/RATIONALE.md +++ b/RATIONALE.md @@ -117,6 +117,17 @@ Besides security, this practice prevents other bugs and allows centralization of ## API Design +### Why is `context.Context` inconsistent? + +It may seem strange that only certain API have an initial `context.Context` +parameter. We originally had a `context.Context` for anything that might be +traced, but it turned out to be only useful for lifecycle and host functions. + +For instruction-scoped aspects like memory updates, a context parameter is too +fine-grained and also invisible in practice. For example, most users will use +the compiler engine, and its memory, global or table access will never use go's +context. + ### Why does `api.ValueType` map to uint64? WebAssembly allows functions to be defined either by the guest or the host, diff --git a/api/wasm.go b/api/wasm.go index 68cdcf90..a45dcdbf 100644 --- a/api/wasm.go +++ b/api/wasm.go @@ -350,7 +350,7 @@ type GoModuleFunction interface { // api.GoModuleFunc(func(ctx context.Context, mod api.Module, stack []uint64) { // offset := api.DecodeU32(stack[0]) // read the parameter from the stack // -// ret, ok := mod.Memory().ReadUint32Le(ctx, offset) +// ret, ok := mod.Memory().ReadUint32Le(offset) // if !ok { // panic("out of memory") // } @@ -413,8 +413,8 @@ type Global interface { // Get returns the last known value of this global. // - // See Type for how to encode this value from a Go type. - Get(context.Context) uint64 + // See Type for how to decode this value to a Go type. + Get() uint64 } // MutableGlobal is a Global whose value can be updated at runtime (variable). @@ -423,8 +423,8 @@ type MutableGlobal interface { // Set updates the value of this global. // - // See Global.Type for how to decode this value to a Go type. - Set(ctx context.Context, v uint64) + // See Global.Type for how to encode this value from a Go type. + Set(v uint64) } // Memory allows restricted access to a module's memory. Notably, this does not allow growing. @@ -443,7 +443,7 @@ type Memory interface { // has 1 page: 65536 // // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#-hrefsyntax-instr-memorymathsfmemorysize%E2%91%A0 - Size(context.Context) uint32 + Size() uint32 // Grow increases memory by the delta in pages (65536 bytes per page). // The return val is the previous memory size in pages, or false if the @@ -456,39 +456,39 @@ type Memory interface { // - When this returns true, any shared views via Read must be refreshed. // // See MemorySizer Read and https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#grow-mem - Grow(ctx context.Context, deltaPages uint32) (previousPages uint32, ok bool) + Grow(deltaPages uint32) (previousPages uint32, ok bool) // ReadByte reads a single byte from the underlying buffer at the offset or returns false if out of range. - ReadByte(ctx context.Context, offset uint32) (byte, bool) + ReadByte(offset uint32) (byte, bool) // ReadUint16Le reads a uint16 in little-endian encoding from the underlying buffer at the offset in or returns // false if out of range. - ReadUint16Le(ctx context.Context, offset uint32) (uint16, bool) + ReadUint16Le(offset uint32) (uint16, bool) // ReadUint32Le reads a uint32 in little-endian encoding from the underlying buffer at the offset in or returns // false if out of range. - ReadUint32Le(ctx context.Context, offset uint32) (uint32, bool) + ReadUint32Le(offset uint32) (uint32, bool) // ReadFloat32Le reads a float32 from 32 IEEE 754 little-endian encoded bits in the underlying buffer at the offset // or returns false if out of range. // See math.Float32bits - ReadFloat32Le(ctx context.Context, offset uint32) (float32, bool) + ReadFloat32Le(offset uint32) (float32, bool) // ReadUint64Le reads a uint64 in little-endian encoding from the underlying buffer at the offset or returns false // if out of range. - ReadUint64Le(ctx context.Context, offset uint32) (uint64, bool) + ReadUint64Le(offset uint32) (uint64, bool) // ReadFloat64Le reads a float64 from 64 IEEE 754 little-endian encoded bits in the underlying buffer at the offset // or returns false if out of range. // // See math.Float64bits - ReadFloat64Le(ctx context.Context, offset uint32) (float64, bool) + ReadFloat64Le(offset uint32) (float64, bool) // Read reads byteCount bytes from the underlying buffer at the offset or // returns false if out of range. // // For example, to search for a NUL-terminated string: - // buf, _ = memory.Read(ctx, offset, byteCount) + // buf, _ = memory.Read(offset, byteCount) // n := bytes.IndexByte(buf, 0) // if n < 0 { // // Not found! @@ -501,7 +501,7 @@ type Memory interface { // Wasm are visible reading the returned slice. // // For example: - // buf, _ = memory.Read(ctx, offset, byteCount) + // buf, _ = memory.Read(offset, byteCount) // buf[1] = 'a' // writes through to memory, meaning Wasm code see 'a'. // // If you don't intend-write through, make a copy of the returned slice. @@ -515,40 +515,40 @@ type Memory interface { // shared. Those who need a stable view must set Wasm memory min=max, or // use wazero.RuntimeConfig WithMemoryCapacityPages to ensure max is always // allocated. - Read(ctx context.Context, offset, byteCount uint32) ([]byte, bool) + Read(offset, byteCount uint32) ([]byte, bool) // WriteByte writes a single byte to the underlying buffer at the offset in or returns false if out of range. - WriteByte(ctx context.Context, offset uint32, v byte) bool + WriteByte(offset uint32, v byte) bool // WriteUint16Le writes the value in little-endian encoding to the underlying buffer at the offset in or returns // false if out of range. - WriteUint16Le(ctx context.Context, offset uint32, v uint16) bool + WriteUint16Le(offset uint32, v uint16) bool // WriteUint32Le writes the value in little-endian encoding to the underlying buffer at the offset in or returns // false if out of range. - WriteUint32Le(ctx context.Context, offset, v uint32) bool + WriteUint32Le(offset, v uint32) bool // WriteFloat32Le writes the value in 32 IEEE 754 little-endian encoded bits to the underlying buffer at the offset // or returns false if out of range. // // See math.Float32bits - WriteFloat32Le(ctx context.Context, offset uint32, v float32) bool + WriteFloat32Le(offset uint32, v float32) bool // WriteUint64Le writes the value in little-endian encoding to the underlying buffer at the offset in or returns // false if out of range. - WriteUint64Le(ctx context.Context, offset uint32, v uint64) bool + WriteUint64Le(offset uint32, v uint64) bool // WriteFloat64Le writes the value in 64 IEEE 754 little-endian encoded bits to the underlying buffer at the offset // or returns false if out of range. // // See math.Float64bits - WriteFloat64Le(ctx context.Context, offset uint32, v float64) bool + WriteFloat64Le(offset uint32, v float64) bool // Write writes the slice to the underlying buffer at the offset or returns false if out of range. - Write(ctx context.Context, offset uint32, v []byte) bool + Write(offset uint32, v []byte) bool // WriteString writes the string to the underlying buffer at the offset or returns false if out of range. - WriteString(ctx context.Context, offset uint32, v string) bool + WriteString(offset uint32, v string) bool } // EncodeExternref encodes the input as a ValueTypeExternref. diff --git a/config_test.go b/config_test.go index d0cde23d..dfdd59c5 100644 --- a/config_test.go +++ b/config_test.go @@ -117,10 +117,10 @@ func TestModuleConfig(t *testing.T) { // sys.NewContext. func TestModuleConfig_toSysContext(t *testing.T) { // Always assigns clocks so that pointers are constant. - var wt sys.Walltime = func(context.Context) (int64, int32) { + var wt sys.Walltime = func() (int64, int32) { return 0, 0 } - var nt sys.Nanotime = func(context.Context) int64 { + var nt sys.Nanotime = func() int64 { return 0 } base := NewModuleConfig() @@ -368,7 +368,7 @@ func TestModuleConfig_toSysContext_WithWalltime(t *testing.T) { { name: "ok", input: NewModuleConfig(). - WithWalltime(func(context.Context) (sec int64, nsec int32) { + WithWalltime(func() (sec int64, nsec int32) { return 1, 2 }, 3), expectedSec: 1, @@ -378,10 +378,10 @@ func TestModuleConfig_toSysContext_WithWalltime(t *testing.T) { { name: "overwrites", input: NewModuleConfig(). - WithWalltime(func(context.Context) (sec int64, nsec int32) { + WithWalltime(func() (sec int64, nsec int32) { return 3, 4 }, 5). - WithWalltime(func(context.Context) (sec int64, nsec int32) { + WithWalltime(func() (sec int64, nsec int32) { return 1, 2 }, 3), expectedSec: 1, @@ -391,7 +391,7 @@ func TestModuleConfig_toSysContext_WithWalltime(t *testing.T) { { name: "invalid resolution", input: NewModuleConfig(). - WithWalltime(func(context.Context) (sec int64, nsec int32) { + WithWalltime(func() (sec int64, nsec int32) { return 1, 2 }, 0), expectedErr: "invalid Walltime resolution: 0", @@ -405,7 +405,7 @@ func TestModuleConfig_toSysContext_WithWalltime(t *testing.T) { sysCtx, err := tc.input.(*moduleConfig).toSysContext() if tc.expectedErr == "" { require.Nil(t, err) - sec, nsec := sysCtx.Walltime(testCtx) + sec, nsec := sysCtx.Walltime() require.Equal(t, tc.expectedSec, sec) require.Equal(t, tc.expectedNsec, nsec) require.Equal(t, tc.expectedResolution, sysCtx.WalltimeResolution()) @@ -417,12 +417,11 @@ func TestModuleConfig_toSysContext_WithWalltime(t *testing.T) { t.Run("context", func(t *testing.T) { sysCtx, err := NewModuleConfig(). - WithWalltime(func(ctx context.Context) (sec int64, nsec int32) { - require.Equal(t, testCtx, ctx) + WithWalltime(func() (sec int64, nsec int32) { return 1, 2 }, 3).(*moduleConfig).toSysContext() require.NoError(t, err) - sec, nsec := sysCtx.Walltime(testCtx) + sec, nsec := sysCtx.Walltime() // If below pass, the context was correct! require.Equal(t, int64(1), sec) require.Equal(t, int32(2), nsec) @@ -442,7 +441,7 @@ func TestModuleConfig_toSysContext_WithNanotime(t *testing.T) { { name: "ok", input: NewModuleConfig(). - WithNanotime(func(context.Context) int64 { + WithNanotime(func() int64 { return 1 }, 2), expectedNanos: 1, @@ -451,10 +450,10 @@ func TestModuleConfig_toSysContext_WithNanotime(t *testing.T) { { name: "overwrites", input: NewModuleConfig(). - WithNanotime(func(context.Context) int64 { + WithNanotime(func() int64 { return 3 }, 4). - WithNanotime(func(context.Context) int64 { + WithNanotime(func() int64 { return 1 }, 2), expectedNanos: 1, @@ -463,7 +462,7 @@ func TestModuleConfig_toSysContext_WithNanotime(t *testing.T) { { name: "invalid resolution", input: NewModuleConfig(). - WithNanotime(func(context.Context) int64 { + WithNanotime(func() int64 { return 1 }, 0), expectedErr: "invalid Nanotime resolution: 0", @@ -477,7 +476,7 @@ func TestModuleConfig_toSysContext_WithNanotime(t *testing.T) { sysCtx, err := tc.input.(*moduleConfig).toSysContext() if tc.expectedErr == "" { require.Nil(t, err) - nanos := sysCtx.Nanotime(testCtx) + nanos := sysCtx.Nanotime() require.Equal(t, tc.expectedNanos, nanos) require.Equal(t, tc.expectedResolution, sysCtx.NanotimeResolution()) } else { @@ -485,29 +484,17 @@ func TestModuleConfig_toSysContext_WithNanotime(t *testing.T) { } }) } - - t.Run("context", func(t *testing.T) { - sysCtx, err := NewModuleConfig(). - WithNanotime(func(ctx context.Context) int64 { - require.Equal(t, testCtx, ctx) - return 1 - }, 2).(*moduleConfig).toSysContext() - require.NoError(t, err) - // If below pass, the context was correct! - require.Equal(t, int64(1), sysCtx.Nanotime(testCtx)) - }) } // TestModuleConfig_toSysContext_WithNanosleep has to test differently because // we can't compare function pointers when functions are passed by value. func TestModuleConfig_toSysContext_WithNanosleep(t *testing.T) { sysCtx, err := NewModuleConfig(). - WithNanosleep(func(ctx context.Context, ns int64) { - require.Equal(t, testCtx, ctx) + WithNanosleep(func(ns int64) { + require.Equal(t, int64(2), ns) }).(*moduleConfig).toSysContext() require.NoError(t, err) - // If below pass, the context was correct! - sysCtx.Nanosleep(testCtx, 2) + sysCtx.Nanosleep(2) } func TestModuleConfig_toSysContext_Errors(t *testing.T) { diff --git a/examples/allocation/rust/greet.go b/examples/allocation/rust/greet.go index f84ab4be..e84f5775 100644 --- a/examples/allocation/rust/greet.go +++ b/examples/allocation/rust/greet.go @@ -67,9 +67,9 @@ func main() { defer deallocate.Call(ctx, namePtr, nameSize) // The pointer is a linear memory offset, which is where we write the name. - if !mod.Memory().Write(ctx, uint32(namePtr), []byte(name)) { + if !mod.Memory().Write(uint32(namePtr), []byte(name)) { log.Panicf("Memory.Write(%d, %d) out of range of memory size %d", - namePtr, nameSize, mod.Memory().Size(ctx)) + namePtr, nameSize, mod.Memory().Size()) } // Now, we can call "greet", which reads the string we wrote to memory! @@ -91,16 +91,16 @@ func main() { defer deallocate.Call(ctx, uint64(greetingPtr), uint64(greetingSize)) // The pointer is a linear memory offset, which is where we write the name. - if bytes, ok := mod.Memory().Read(ctx, greetingPtr, greetingSize); !ok { + if bytes, ok := mod.Memory().Read(greetingPtr, greetingSize); !ok { log.Panicf("Memory.Read(%d, %d) out of range of memory size %d", - greetingPtr, greetingSize, mod.Memory().Size(ctx)) + greetingPtr, greetingSize, mod.Memory().Size()) } else { fmt.Println("go >>", string(bytes)) } } func logString(ctx context.Context, m api.Module, offset, byteCount uint32) { - buf, ok := m.Memory().Read(ctx, offset, byteCount) + buf, ok := m.Memory().Read(offset, byteCount) if !ok { log.Panicf("Memory.Read(%d, %d) out of range", offset, byteCount) } diff --git a/examples/allocation/tinygo/greet.go b/examples/allocation/tinygo/greet.go index c0962c91..aabb1140 100644 --- a/examples/allocation/tinygo/greet.go +++ b/examples/allocation/tinygo/greet.go @@ -73,9 +73,9 @@ func main() { defer free.Call(ctx, namePtr) // The pointer is a linear memory offset, which is where we write the name. - if !mod.Memory().Write(ctx, uint32(namePtr), []byte(name)) { + if !mod.Memory().Write(uint32(namePtr), []byte(name)) { log.Panicf("Memory.Write(%d, %d) out of range of memory size %d", - namePtr, nameSize, mod.Memory().Size(ctx)) + namePtr, nameSize, mod.Memory().Size()) } // Now, we can call "greet", which reads the string we wrote to memory! @@ -94,16 +94,16 @@ func main() { greetingPtr := uint32(ptrSize[0] >> 32) greetingSize := uint32(ptrSize[0]) // The pointer is a linear memory offset, which is where we write the name. - if bytes, ok := mod.Memory().Read(ctx, greetingPtr, greetingSize); !ok { + if bytes, ok := mod.Memory().Read(greetingPtr, greetingSize); !ok { log.Panicf("Memory.Read(%d, %d) out of range of memory size %d", - greetingPtr, greetingSize, mod.Memory().Size(ctx)) + greetingPtr, greetingSize, mod.Memory().Size()) } else { fmt.Println("go >>", string(bytes)) } } -func logString(ctx context.Context, m api.Module, offset, byteCount uint32) { - buf, ok := m.Memory().Read(ctx, offset, byteCount) +func logString(_ context.Context, m api.Module, offset, byteCount uint32) { + buf, ok := m.Memory().Read(offset, byteCount) if !ok { log.Panicf("Memory.Read(%d, %d) out of range", offset, byteCount) } diff --git a/examples/allocation/zig/greet.go b/examples/allocation/zig/greet.go index 49ffdbb7..96ff126a 100644 --- a/examples/allocation/zig/greet.go +++ b/examples/allocation/zig/greet.go @@ -81,9 +81,9 @@ func run() error { defer free.Call(ctx, namePtr, nameSize) // The pointer is a linear memory offset, which is where we write the name. - if !mod.Memory().Write(ctx, uint32(namePtr), []byte(name)) { + if !mod.Memory().Write(uint32(namePtr), []byte(name)) { return fmt.Errorf("Memory.Write(%d, %d) out of range of memory size %d", - namePtr, nameSize, mod.Memory().Size(ctx)) + namePtr, nameSize, mod.Memory().Size()) } // Now, we can call "greet", which reads the string we wrote to memory! @@ -102,9 +102,9 @@ func run() error { greetingPtr := uint32(ptrSize[0] >> 32) greetingSize := uint32(ptrSize[0]) // The pointer is a linear memory offset, which is where we write the name. - if bytes, ok := mod.Memory().Read(ctx, greetingPtr, greetingSize); !ok { + if bytes, ok := mod.Memory().Read(greetingPtr, greetingSize); !ok { return fmt.Errorf("Memory.Read(%d, %d) out of range of memory size %d", - greetingPtr, greetingSize, mod.Memory().Size(ctx)) + greetingPtr, greetingSize, mod.Memory().Size()) } else { fmt.Println("go >>", string(bytes)) } @@ -112,8 +112,8 @@ func run() error { return nil } -func logString(ctx context.Context, m api.Module, offset, byteCount uint32) { - buf, ok := m.Memory().Read(ctx, offset, byteCount) +func logString(_ context.Context, m api.Module, offset, byteCount uint32) { + buf, ok := m.Memory().Read(offset, byteCount) if !ok { log.Panicf("Memory.Read(%d, %d) out of range", offset, byteCount) } diff --git a/imports/assemblyscript/assemblyscript.go b/imports/assemblyscript/assemblyscript.go index 9375882c..554750b1 100644 --- a/imports/assemblyscript/assemblyscript.go +++ b/imports/assemblyscript/assemblyscript.go @@ -166,8 +166,8 @@ func abortWithMessage(ctx context.Context, mod api.Module, stack []uint64) { // Don't panic if there was a problem reading the message stderr := fsc.FdWriter(internalsys.FdStderr) - if msg, msgOk := readAssemblyScriptString(ctx, mem, message); msgOk { - if fn, fnOk := readAssemblyScriptString(ctx, mem, fileName); fnOk { + if msg, msgOk := readAssemblyScriptString(mem, message); msgOk { + if fn, fnOk := readAssemblyScriptString(mem, fileName); fnOk { _, _ = fmt.Fprintf(stderr, "%s at %s:%d:%d\n", msg, fn, lineNumber, columnNumber) } } @@ -198,19 +198,19 @@ var traceStdout = &wasm.HostFunc{ ParamNames: []string{"message", "nArgs", "arg0", "arg1", "arg2", "arg3", "arg4"}, Code: &wasm.Code{ IsHostFunction: true, - GoFunc: api.GoModuleFunc(func(ctx context.Context, mod api.Module, stack []uint64) { + GoFunc: api.GoModuleFunc(func(_ context.Context, mod api.Module, stack []uint64) { fsc := mod.(*wasm.CallContext).Sys.FS() stdout := fsc.FdWriter(internalsys.FdStdout) - traceTo(ctx, mod, stack, stdout) + traceTo(mod, stack, stdout) }), }, } // traceStderr implements trace to the configured Stderr. -var traceStderr = traceStdout.WithGoModuleFunc(func(ctx context.Context, mod api.Module, stack []uint64) { +var traceStderr = traceStdout.WithGoModuleFunc(func(_ context.Context, mod api.Module, stack []uint64) { fsc := mod.(*wasm.CallContext).Sys.FS() stderr := fsc.FdWriter(internalsys.FdStderr) - traceTo(ctx, mod, stack, stderr) + traceTo(mod, stack, stderr) }) // traceTo implements the function "trace" in AssemblyScript. e.g. @@ -223,7 +223,7 @@ var traceStderr = traceStdout.WithGoModuleFunc(func(ctx context.Context, mod api // (import "env" "trace" (func $~lib/builtins/trace (param i32 i32 f64 f64 f64 f64 f64))) // // See https://github.com/AssemblyScript/assemblyscript/blob/fa14b3b03bd4607efa52aaff3132bea0c03a7989/std/assembly/wasi/index.ts#L61 -func traceTo(ctx context.Context, mod api.Module, params []uint64, writer io.Writer) { +func traceTo(mod api.Module, params []uint64, writer io.Writer) { message := uint32(params[0]) nArgs := uint32(params[1]) arg0 := api.DecodeF64(params[2]) @@ -232,7 +232,7 @@ func traceTo(ctx context.Context, mod api.Module, params []uint64, writer io.Wri arg3 := api.DecodeF64(params[5]) arg4 := api.DecodeF64(params[6]) - msg, ok := readAssemblyScriptString(ctx, mod.Memory(), message) + msg, ok := readAssemblyScriptString(mod.Memory(), message) if !ok { return // don't panic if unable to trace } @@ -298,13 +298,13 @@ var seed = &wasm.HostFunc{ } // readAssemblyScriptString reads a UTF-16 string created by AssemblyScript. -func readAssemblyScriptString(ctx context.Context, mem api.Memory, offset uint32) (string, bool) { +func readAssemblyScriptString(mem api.Memory, offset uint32) (string, bool) { // Length is four bytes before pointer. - byteCount, ok := mem.ReadUint32Le(ctx, offset-4) + byteCount, ok := mem.ReadUint32Le(offset - 4) if !ok || byteCount%2 != 0 { return "", false } - buf, ok := mem.Read(ctx, offset, byteCount) + buf, ok := mem.Read(offset, byteCount) if !ok { return "", false } diff --git a/imports/assemblyscript/assemblyscript_test.go b/imports/assemblyscript/assemblyscript_test.go index 96c3544a..39613ee7 100644 --- a/imports/assemblyscript/assemblyscript_test.go +++ b/imports/assemblyscript/assemblyscript_test.go @@ -303,9 +303,9 @@ func TestFunctionExporter_Trace(t *testing.T) { if message == nil { message = encodeUTF16("hello") } - ok := mod.Memory().WriteUint32Le(testCtx, 0, uint32(len(message))) + ok := mod.Memory().WriteUint32Le(0, uint32(len(message))) require.True(t, ok) - ok = mod.Memory().Write(testCtx, uint32(4), message) + ok = mod.Memory().Write(uint32(4), message) require.True(t, ok) _, err := mod.ExportedFunction(functionTrace).Call(testCtx, tc.params...) @@ -319,17 +319,17 @@ func TestFunctionExporter_Trace(t *testing.T) { func Test_readAssemblyScriptString(t *testing.T) { tests := []struct { name string - memory func(context.Context, api.Memory) + memory func(api.Memory) offset int expected string expectedOk bool }{ { name: "success", - memory: func(testCtx context.Context, memory api.Memory) { - memory.WriteUint32Le(testCtx, 0, 10) + memory: func(memory api.Memory) { + memory.WriteUint32Le(0, 10) b := encodeUTF16("hello") - memory.Write(testCtx, 4, b) + memory.Write(4, b) }, offset: 4, expected: "hello", @@ -337,29 +337,29 @@ func Test_readAssemblyScriptString(t *testing.T) { }, { name: "can't read size", - memory: func(testCtx context.Context, memory api.Memory) { + memory: func(memory api.Memory) { b := encodeUTF16("hello") - memory.Write(testCtx, 0, b) + memory.Write(0, b) }, offset: 0, // will attempt to read size from offset -4 expectedOk: false, }, { name: "odd size", - memory: func(testCtx context.Context, memory api.Memory) { - memory.WriteUint32Le(testCtx, 0, 9) + memory: func(memory api.Memory) { + memory.WriteUint32Le(0, 9) b := encodeUTF16("hello") - memory.Write(testCtx, 4, b) + memory.Write(4, b) }, offset: 4, expectedOk: false, }, { name: "can't read string", - memory: func(testCtx context.Context, memory api.Memory) { - memory.WriteUint32Le(testCtx, 0, 10_000_000) // set size to too large value + memory: func(memory api.Memory) { + memory.WriteUint32Le(0, 10_000_000) // set size to too large value b := encodeUTF16("hello") - memory.Write(testCtx, 4, b) + memory.Write(4, b) }, offset: 4, expectedOk: false, @@ -371,9 +371,9 @@ func Test_readAssemblyScriptString(t *testing.T) { t.Run(tc.name, func(t *testing.T) { mem := wasm.NewMemoryInstance(&wasm.Memory{Min: 1, Cap: 1, Max: 1}) - tc.memory(testCtx, mem) + tc.memory(mem) - s, ok := readAssemblyScriptString(testCtx, mem, uint32(tc.offset)) + s, ok := readAssemblyScriptString(mem, uint32(tc.offset)) require.Equal(t, tc.expectedOk, ok) require.Equal(t, tc.expected, s) }) @@ -382,18 +382,18 @@ func Test_readAssemblyScriptString(t *testing.T) { func writeAbortMessageAndFileName(t *testing.T, mem api.Memory, messageUTF16, fileNameUTF16 []byte) (uint32, uint32) { off := uint32(0) - ok := mem.WriteUint32Le(testCtx, off, uint32(len(messageUTF16))) + ok := mem.WriteUint32Le(off, uint32(len(messageUTF16))) require.True(t, ok) off += 4 messageOff := off - ok = mem.Write(testCtx, off, messageUTF16) + ok = mem.Write(off, messageUTF16) require.True(t, ok) off += uint32(len(messageUTF16)) - ok = mem.WriteUint32Le(testCtx, off, uint32(len(fileNameUTF16))) + ok = mem.WriteUint32Le(off, uint32(len(fileNameUTF16))) require.True(t, ok) off += 4 filenameOff := off - ok = mem.Write(testCtx, off, fileNameUTF16) + ok = mem.Write(off, fileNameUTF16) require.True(t, ok) return messageOff, filenameOff } diff --git a/imports/go/gojs.go b/imports/go/gojs.go index 0e09ca52..4d5a7eb8 100644 --- a/imports/go/gojs.go +++ b/imports/go/gojs.go @@ -78,7 +78,7 @@ func Run(ctx context.Context, r wazero.Runtime, compiled wazero.CompiledModule, // Extract the args and env from the module config and write it to memory. ctx = WithState(ctx) - argc, argv, err := WriteArgsAndEnviron(ctx, mod) + argc, argv, err := WriteArgsAndEnviron(mod) if err != nil { return err } diff --git a/imports/wasi_snapshot_preview1/args.go b/imports/wasi_snapshot_preview1/args.go index 15cc9139..35259f02 100644 --- a/imports/wasi_snapshot_preview1/args.go +++ b/imports/wasi_snapshot_preview1/args.go @@ -49,7 +49,7 @@ var argsGet = newHostFunc(argsGetName, argsGetFn, []api.ValueType{i32, i32}, "ar func argsGetFn(ctx context.Context, mod api.Module, params []uint64) Errno { sysCtx := mod.(*wasm.CallContext).Sys argv, argvBuf := uint32(params[0]), uint32(params[1]) - return writeOffsetsAndNullTerminatedValues(ctx, mod.Memory(), sysCtx.Args(), argv, argvBuf, sysCtx.ArgsSize()) + return writeOffsetsAndNullTerminatedValues(mod.Memory(), sysCtx.Args(), argv, argvBuf, sysCtx.ArgsSize()) } // argsSizesGet is the WASI function named argsSizesGetName that reads diff --git a/imports/wasi_snapshot_preview1/args_test.go b/imports/wasi_snapshot_preview1/args_test.go index 8b136e57..a5e46ae0 100644 --- a/imports/wasi_snapshot_preview1/args_test.go +++ b/imports/wasi_snapshot_preview1/args_test.go @@ -22,7 +22,7 @@ func Test_argsGet(t *testing.T) { '?', // stopped after encoding } - maskMemory(t, testCtx, mod, len(expectedMemory)+int(argvBuf)) + maskMemory(t, mod, len(expectedMemory)+int(argvBuf)) // Invoke argsGet and check the memory side effects. requireErrno(t, ErrnoSuccess, mod, argsGetName, uint64(argv), uint64(argvBuf)) @@ -33,7 +33,7 @@ func Test_argsGet(t *testing.T) { <-- 0 `, "\n"+log.String()) - actual, ok := mod.Memory().Read(testCtx, argvBuf-1, uint32(len(expectedMemory))) + actual, ok := mod.Memory().Read(argvBuf-1, uint32(len(expectedMemory))) require.True(t, ok) require.Equal(t, expectedMemory, actual) } @@ -42,7 +42,7 @@ func Test_argsGet_Errors(t *testing.T) { mod, r, log := requireProxyModule(t, wazero.NewModuleConfig().WithArgs("a", "bc")) defer r.Close(testCtx) - memorySize := mod.Memory().Size(testCtx) + memorySize := mod.Memory().Size() validAddress := uint32(0) // arbitrary tests := []struct { @@ -124,7 +124,7 @@ func Test_argsSizesGet(t *testing.T) { '?', // stopped after encoding } - maskMemory(t, testCtx, mod, int(resultArgc)+len(expectedMemory)) + maskMemory(t, mod, int(resultArgc)+len(expectedMemory)) // Invoke argsSizesGet and check the memory side effects. requireErrno(t, ErrnoSuccess, mod, argsSizesGetName, uint64(resultArgc), uint64(resultArgvLen)) @@ -137,7 +137,7 @@ func Test_argsSizesGet(t *testing.T) { <-- 0 `, "\n"+log.String()) - actual, ok := mod.Memory().Read(testCtx, resultArgc-1, uint32(len(expectedMemory))) + actual, ok := mod.Memory().Read(resultArgc-1, uint32(len(expectedMemory))) require.True(t, ok) require.Equal(t, expectedMemory, actual) } @@ -146,7 +146,7 @@ func Test_argsSizesGet_Errors(t *testing.T) { mod, r, log := requireProxyModule(t, wazero.NewModuleConfig().WithArgs("a", "bc")) defer r.Close(testCtx) - memorySize := mod.Memory().Size(testCtx) + memorySize := mod.Memory().Size() validAddress := uint32(0) // arbitrary valid address as arguments to args_sizes_get. We chose 0 here. tests := []struct { diff --git a/imports/wasi_snapshot_preview1/clock.go b/imports/wasi_snapshot_preview1/clock.go index 13c60d22..126228dd 100644 --- a/imports/wasi_snapshot_preview1/clock.go +++ b/imports/wasi_snapshot_preview1/clock.go @@ -116,7 +116,7 @@ var clockTimeGet = proxyResultParams(&wasm.HostFunc{ Code: &wasm.Code{IsHostFunction: true, GoFunc: i64ResultParam(clockTimeGetFn)}, }, clockTimeGetName) -func clockTimeGetFn(ctx context.Context, mod api.Module, stack []uint64) (timestamp int64, errno Errno) { +func clockTimeGetFn(_ context.Context, mod api.Module, stack []uint64) (timestamp int64, errno Errno) { sysCtx := mod.(*wasm.CallContext).Sys id := uint32(stack[0]) // TODO: precision is currently ignored. @@ -124,10 +124,10 @@ func clockTimeGetFn(ctx context.Context, mod api.Module, stack []uint64) (timest switch id { case clockIDRealtime: - sec, nsec := sysCtx.Walltime(ctx) + sec, nsec := sysCtx.Walltime() timestamp = (sec * time.Second.Nanoseconds()) + int64(nsec) case clockIDMonotonic: - timestamp = sysCtx.Nanotime(ctx) + timestamp = sysCtx.Nanotime() default: return 0, ErrnoInval } diff --git a/imports/wasi_snapshot_preview1/clock_test.go b/imports/wasi_snapshot_preview1/clock_test.go index 76af78f8..ee4d9ae0 100644 --- a/imports/wasi_snapshot_preview1/clock_test.go +++ b/imports/wasi_snapshot_preview1/clock_test.go @@ -65,12 +65,12 @@ func Test_clockResGet(t *testing.T) { defer log.Reset() resultResolution := 16 // arbitrary offset - maskMemory(t, testCtx, mod, resultResolution+len(tc.expectedMemory)) + maskMemory(t, mod, resultResolution+len(tc.expectedMemory)) requireErrno(t, ErrnoSuccess, mod, clockResGetName, uint64(tc.clockID), uint64(resultResolution)) require.Equal(t, tc.expectedLog, "\n"+log.String()) - actual, ok := mod.Memory().Read(testCtx, uint32(resultResolution-1), uint32(len(tc.expectedMemory))) + actual, ok := mod.Memory().Read(uint32(resultResolution-1), uint32(len(tc.expectedMemory))) require.True(t, ok) require.Equal(t, tc.expectedMemory, actual) }) @@ -193,12 +193,12 @@ func Test_clockTimeGet(t *testing.T) { defer log.Reset() resultTimestamp := 16 // arbitrary offset - maskMemory(t, testCtx, mod, resultTimestamp+len(tc.expectedMemory)) + maskMemory(t, mod, resultTimestamp+len(tc.expectedMemory)) requireErrno(t, ErrnoSuccess, mod, clockTimeGetName, uint64(tc.clockID), 0 /* TODO: precision */, uint64(resultTimestamp)) require.Equal(t, tc.expectedLog, "\n"+log.String()) - actual, ok := mod.Memory().Read(testCtx, uint32(resultTimestamp-1), uint32(len(tc.expectedMemory))) + actual, ok := mod.Memory().Read(uint32(resultTimestamp-1), uint32(len(tc.expectedMemory))) require.True(t, ok) require.Equal(t, tc.expectedMemory, actual) }) @@ -273,7 +273,7 @@ func Test_clockTimeGet_Errors(t *testing.T) { mod, r, log := requireProxyModule(t, wazero.NewModuleConfig()) defer r.Close(testCtx) - memorySize := mod.Memory().Size(testCtx) + memorySize := mod.Memory().Size() tests := []struct { name string diff --git a/imports/wasi_snapshot_preview1/environ.go b/imports/wasi_snapshot_preview1/environ.go index c8e20eb0..f428c669 100644 --- a/imports/wasi_snapshot_preview1/environ.go +++ b/imports/wasi_snapshot_preview1/environ.go @@ -46,11 +46,11 @@ const ( // See https://en.wikipedia.org/wiki/Null-terminated_string var environGet = newHostFunc(environGetName, environGetFn, []api.ValueType{i32, i32}, "environ", "environ_buf") -func environGetFn(ctx context.Context, mod api.Module, params []uint64) Errno { +func environGetFn(_ context.Context, mod api.Module, params []uint64) Errno { sysCtx := mod.(*wasm.CallContext).Sys environ, environBuf := uint32(params[0]), uint32(params[1]) - return writeOffsetsAndNullTerminatedValues(ctx, mod.Memory(), sysCtx.Environ(), environ, environBuf, sysCtx.EnvironSize()) + return writeOffsetsAndNullTerminatedValues(mod.Memory(), sysCtx.Environ(), environ, environBuf, sysCtx.EnvironSize()) } // environSizesGet is the WASI function named environSizesGetName that diff --git a/imports/wasi_snapshot_preview1/environ_test.go b/imports/wasi_snapshot_preview1/environ_test.go index da943cd4..41ef7b1c 100644 --- a/imports/wasi_snapshot_preview1/environ_test.go +++ b/imports/wasi_snapshot_preview1/environ_test.go @@ -24,7 +24,7 @@ func Test_environGet(t *testing.T) { '?', // stopped after encoding } - maskMemory(t, testCtx, mod, len(expectedMemory)+int(resultEnvironBuf)) + maskMemory(t, mod, len(expectedMemory)+int(resultEnvironBuf)) // Invoke environGet and check the memory side effects. requireErrno(t, ErrnoSuccess, mod, environGetName, uint64(resultEnviron), uint64(resultEnvironBuf)) @@ -35,7 +35,7 @@ func Test_environGet(t *testing.T) { <-- 0 `, "\n"+log.String()) - actual, ok := mod.Memory().Read(testCtx, resultEnvironBuf-1, uint32(len(expectedMemory))) + actual, ok := mod.Memory().Read(resultEnvironBuf-1, uint32(len(expectedMemory))) require.True(t, ok) require.Equal(t, expectedMemory, actual) } @@ -45,7 +45,7 @@ func Test_environGet_Errors(t *testing.T) { WithEnv("a", "bc").WithEnv("b", "cd")) defer r.Close(testCtx) - memorySize := mod.Memory().Size(testCtx) + memorySize := mod.Memory().Size() validAddress := uint32(0) // arbitrary valid address as arguments to environ_get. We chose 0 here. tests := []struct { @@ -128,7 +128,7 @@ func Test_environSizesGet(t *testing.T) { '?', // stopped after encoding } - maskMemory(t, testCtx, mod, len(expectedMemory)+int(resultEnvironc)) + maskMemory(t, mod, len(expectedMemory)+int(resultEnvironc)) // Invoke environSizesGet and check the memory side effects. requireErrno(t, ErrnoSuccess, mod, environSizesGetName, uint64(resultEnvironc), uint64(resultEnvironvLen)) @@ -141,7 +141,7 @@ func Test_environSizesGet(t *testing.T) { <-- 0 `, "\n"+log.String()) - actual, ok := mod.Memory().Read(testCtx, resultEnvironc-1, uint32(len(expectedMemory))) + actual, ok := mod.Memory().Read(resultEnvironc-1, uint32(len(expectedMemory))) require.True(t, ok) require.Equal(t, expectedMemory, actual) } @@ -151,7 +151,7 @@ func Test_environSizesGet_Errors(t *testing.T) { WithEnv("a", "b").WithEnv("b", "cd")) defer r.Close(testCtx) - memorySize := mod.Memory().Size(testCtx) + memorySize := mod.Memory().Size() validAddress := uint32(0) // arbitrary tests := []struct { diff --git a/imports/wasi_snapshot_preview1/fs.go b/imports/wasi_snapshot_preview1/fs.go index af69d21b..60920da4 100644 --- a/imports/wasi_snapshot_preview1/fs.go +++ b/imports/wasi_snapshot_preview1/fs.go @@ -143,11 +143,11 @@ var fdFdstatGet = newHostFunc(fdFdstatGetName, fdFdstatGetFn, []api.ValueType{i3 // fdFdstatGetFn cannot currently use proxyResultParams because fdstat is larger // than api.ValueTypeI64 (i64 == 8 bytes, but fdstat is 24). -func fdFdstatGetFn(ctx context.Context, mod api.Module, params []uint64) Errno { +func fdFdstatGetFn(_ context.Context, mod api.Module, params []uint64) Errno { fd, resultFdstat := uint32(params[0]), uint32(params[1]) // Ensure we can write the fdstat - buf, ok := mod.Memory().Read(ctx, resultFdstat, 24) + buf, ok := mod.Memory().Read(resultFdstat, 24) if !ok { return ErrnoFault } @@ -307,13 +307,13 @@ const ( // fdFilestatGetFn cannot currently use proxyResultParams because filestat is // larger than api.ValueTypeI64 (i64 == 8 bytes, but filestat is 64). -func fdFilestatGetFn(ctx context.Context, mod api.Module, params []uint64) Errno { - return fdFilestatGetFunc(ctx, mod, uint32(params[0]), uint32(params[1])) +func fdFilestatGetFn(_ context.Context, mod api.Module, params []uint64) Errno { + return fdFilestatGetFunc(mod, uint32(params[0]), uint32(params[1])) } -func fdFilestatGetFunc(ctx context.Context, mod api.Module, fd, resultBuf uint32) Errno { +func fdFilestatGetFunc(mod api.Module, fd, resultBuf uint32) Errno { // Ensure we can write the filestat - buf, ok := mod.Memory().Read(ctx, resultBuf, 64) + buf, ok := mod.Memory().Read(resultBuf, 64) if !ok { return ErrnoFault } @@ -414,8 +414,8 @@ var fdPread = proxyResultParams(&wasm.HostFunc{ Code: &wasm.Code{IsHostFunction: true, GoFunc: u32ResultParam(fdPreadFn)}, }, fdPreadName) -func fdPreadFn(ctx context.Context, mod api.Module, stack []uint64) (nread uint32, errno Errno) { - return fdReadOrPread(ctx, mod, stack, true) +func fdPreadFn(_ context.Context, mod api.Module, stack []uint64) (nread uint32, errno Errno) { + return fdReadOrPread(mod, stack, true) } // fdPrestatGet is the WASI function named fdPrestatGetName which returns @@ -515,7 +515,7 @@ var fdPrestatDirName = newHostFunc( "fd", "path", "path_len", ) -func fdPrestatDirNameFn(ctx context.Context, mod api.Module, params []uint64) Errno { +func fdPrestatDirNameFn(_ context.Context, mod api.Module, params []uint64) Errno { fsc := mod.(*wasm.CallContext).Sys.FS() fd, path, pathLen := uint32(params[0]), uint32(params[1]), uint32(params[2]) @@ -534,7 +534,7 @@ func fdPrestatDirNameFn(ctx context.Context, mod api.Module, params []uint64) Er return ErrnoNametoolong } - if !mod.Memory().Write(ctx, path, []byte(f.Name)[:pathLen]) { + if !mod.Memory().Write(path, []byte(f.Name)[:pathLen]) { return ErrnoFault } return ErrnoSuccess @@ -608,11 +608,11 @@ var fdRead = proxyResultParams(&wasm.HostFunc{ Code: &wasm.Code{IsHostFunction: true, GoFunc: u32ResultParam(fdReadFn)}, }, fdReadName) -func fdReadFn(ctx context.Context, mod api.Module, stack []uint64) (nread uint32, errno Errno) { - return fdReadOrPread(ctx, mod, stack, false) +func fdReadFn(_ context.Context, mod api.Module, stack []uint64) (nread uint32, errno Errno) { + return fdReadOrPread(mod, stack, false) } -func fdReadOrPread(ctx context.Context, mod api.Module, stack []uint64, isPread bool) (uint32, Errno) { +func fdReadOrPread(mod api.Module, stack []uint64, isPread bool) (uint32, Errno) { mem := mod.Memory() fsc := mod.(*wasm.CallContext).Sys.FS() @@ -642,7 +642,7 @@ func fdReadOrPread(ctx context.Context, mod api.Module, stack []uint64, isPread var nread uint32 iovsStop := iovsCount << 3 // iovsCount * 8 - iovsBuf, ok := mem.Read(ctx, iovs, iovsStop) + iovsBuf, ok := mem.Read(iovs, iovsStop) if !ok { return 0, ErrnoFault } @@ -651,7 +651,7 @@ func fdReadOrPread(ctx context.Context, mod api.Module, stack []uint64, isPread offset := le.Uint32(iovsBuf[iovsPos:]) l := le.Uint32(iovsBuf[iovsPos+4:]) - b, ok := mem.Read(ctx, offset, l) + b, ok := mem.Read(offset, l) if !ok { return 0, ErrnoFault } @@ -699,7 +699,7 @@ var fdReaddir = proxyResultParams(&wasm.HostFunc{ Code: &wasm.Code{IsHostFunction: true, GoFunc: u32ResultParam(fdReaddirFn)}, }, fdReaddirName) -func fdReaddirFn(ctx context.Context, mod api.Module, stack []uint64) (uint32, Errno) { +func fdReaddirFn(_ context.Context, mod api.Module, stack []uint64) (uint32, Errno) { mem := mod.Memory() fsc := mod.(*wasm.CallContext).Sys.FS() @@ -718,7 +718,7 @@ func fdReaddirFn(ctx context.Context, mod api.Module, stack []uint64) (uint32, E } // Validate the FD is a directory - rd, dir, errno := openedDir(ctx, fsc, fd) + rd, dir, errno := openedDir(fsc, fd) if errno != ErrnoSuccess { return 0, errno } @@ -774,7 +774,7 @@ func fdReaddirFn(ctx context.Context, mod api.Module, stack []uint64) (uint32, E // ^^ yes this can overflow to negative, which means our implementation // doesn't support writing greater than max int64 entries. - dirents, ok := mem.Read(ctx, buf, bufused) + dirents, ok := mem.Read(buf, bufused) if !ok { return 0, ErrnoFault } @@ -939,7 +939,7 @@ func writeDirent(buf []byte, dNext uint64, dNamlen uint32, dType bool) { } // openedDir returns the directory and ErrnoSuccess if the fd points to a readable directory. -func openedDir(ctx context.Context, fsc *internalsys.FSContext, fd uint32) (fs.ReadDirFile, *internalsys.ReadDir, Errno) { +func openedDir(fsc *internalsys.FSContext, fd uint32) (fs.ReadDirFile, *internalsys.ReadDir, Errno) { if f, ok := fsc.OpenedFile(fd); !ok { return nil, nil, ErrnoBadf } else if d, ok := f.File.(fs.ReadDirFile); !ok { @@ -1010,7 +1010,7 @@ var fdSeek = proxyResultParams(&wasm.HostFunc{ Code: &wasm.Code{IsHostFunction: true, GoFunc: i64ResultParam(fdSeekFn)}, }, fdSeekName) -func fdSeekFn(ctx context.Context, mod api.Module, stack []uint64) (int64, Errno) { +func fdSeekFn(_ context.Context, mod api.Module, stack []uint64) (int64, Errno) { fsc := mod.(*wasm.CallContext).Sys.FS() fd := uint32(stack[0]) offset := stack[1] @@ -1120,7 +1120,7 @@ var fdWrite = proxyResultParams(&wasm.HostFunc{ Code: &wasm.Code{IsHostFunction: true, GoFunc: u32ResultParam(fdWriteFn)}, }, fdWriteName) -func fdWriteFn(ctx context.Context, mod api.Module, stack []uint64) (uint32, Errno) { +func fdWriteFn(_ context.Context, mod api.Module, stack []uint64) (uint32, Errno) { mem := mod.Memory() fsc := mod.(*wasm.CallContext).Sys.FS() @@ -1136,7 +1136,7 @@ func fdWriteFn(ctx context.Context, mod api.Module, stack []uint64) (uint32, Err var err error var nwritten uint32 iovsStop := iovsCount << 3 // iovsCount * 8 - iovsBuf, ok := mem.Read(ctx, iovs, iovsStop) + iovsBuf, ok := mem.Read(iovs, iovsStop) if !ok { return 0, ErrnoFault } @@ -1149,7 +1149,7 @@ func fdWriteFn(ctx context.Context, mod api.Module, stack []uint64) (uint32, Err if writer == io.Discard { // special-case default n = int(l) } else { - b, ok := mem.Read(ctx, offset, l) + b, ok := mem.Read(offset, l) if !ok { return 0, ErrnoFault } @@ -1209,7 +1209,7 @@ var pathFilestatGet = newHostFunc( // pathFilestatGetFn cannot currently use proxyResultParams because filestat is // larger than api.ValueTypeI64 (i64 == 8 bytes, but filestat is 64). -func pathFilestatGetFn(ctx context.Context, mod api.Module, params []uint64) Errno { +func pathFilestatGetFn(_ context.Context, mod api.Module, params []uint64) Errno { fsc := mod.(*wasm.CallContext).Sys.FS() dirfd := uint32(params[0]) @@ -1225,7 +1225,7 @@ func pathFilestatGetFn(ctx context.Context, mod api.Module, params []uint64) Err // open_at isn't supported in fs.FS, so we check the path can't escape, // then join it with its parent - b, ok := mod.Memory().Read(ctx, pathOffset, pathLen) + b, ok := mod.Memory().Read(pathOffset, pathLen) if !ok { return ErrnoNametoolong } @@ -1248,7 +1248,7 @@ func pathFilestatGetFn(ctx context.Context, mod api.Module, params []uint64) Err } // Write the stat result to memory - buf, ok := mod.Memory().Read(ctx, resultBuf, 64) + buf, ok := mod.Memory().Read(resultBuf, 64) if !ok { return ErrnoFault } @@ -1354,7 +1354,7 @@ const ( wasiOflagsTrunc // nolint ) -func pathOpenFn(ctx context.Context, mod api.Module, params []uint64) (uint32, Errno) { +func pathOpenFn(_ context.Context, mod api.Module, params []uint64) (uint32, Errno) { fsc := mod.(*wasm.CallContext).Sys.FS() dirfd := uint32(params[0]) @@ -1386,7 +1386,7 @@ func pathOpenFn(ctx context.Context, mod api.Module, params []uint64) (uint32, E return 0, ErrnoBadf } - b, ok := mod.Memory().Read(ctx, path, pathLen) + b, ok := mod.Memory().Read(path, pathLen) if !ok { return 0, ErrnoFault } diff --git a/imports/wasi_snapshot_preview1/fs_test.go b/imports/wasi_snapshot_preview1/fs_test.go index 12a715c1..63760998 100644 --- a/imports/wasi_snapshot_preview1/fs_test.go +++ b/imports/wasi_snapshot_preview1/fs_test.go @@ -105,7 +105,7 @@ func Test_fdFdstatGet(t *testing.T) { mod, r, log := requireProxyModule(t, wazero.NewModuleConfig().WithFS(testFS)) defer r.Close(testCtx) - memorySize := mod.Memory().Size(testCtx) + memorySize := mod.Memory().Size() // open both paths without using WASI fsc := mod.(*wasm.CallContext).Sys.FS() @@ -250,12 +250,12 @@ func Test_fdFdstatGet(t *testing.T) { t.Run(tc.name, func(t *testing.T) { defer log.Reset() - maskMemory(t, testCtx, mod, len(tc.expectedMemory)) + maskMemory(t, mod, len(tc.expectedMemory)) requireErrno(t, tc.expectedErrno, mod, fdFdstatGetName, uint64(tc.fd), uint64(tc.resultFdstat)) require.Equal(t, tc.expectedLog, "\n"+log.String()) - actual, ok := mod.Memory().Read(testCtx, 0, uint32(len(tc.expectedMemory))) + actual, ok := mod.Memory().Read(0, uint32(len(tc.expectedMemory))) require.True(t, ok) require.Equal(t, tc.expectedMemory, actual) }) @@ -294,7 +294,7 @@ func Test_fdFilestatGet(t *testing.T) { mod, r, log := requireProxyModule(t, wazero.NewModuleConfig().WithFS(testFS)) defer r.Close(testCtx) - memorySize := mod.Memory().Size(testCtx) + memorySize := mod.Memory().Size() // open both paths without using WASI fsc := mod.(*wasm.CallContext).Sys.FS() @@ -463,12 +463,12 @@ func Test_fdFilestatGet(t *testing.T) { t.Run(tc.name, func(t *testing.T) { defer log.Reset() - maskMemory(t, testCtx, mod, len(tc.expectedMemory)) + maskMemory(t, mod, len(tc.expectedMemory)) requireErrno(t, tc.expectedErrno, mod, fdFilestatGetName, uint64(tc.fd), uint64(tc.resultFilestat)) require.Equal(t, tc.expectedLog, "\n"+log.String()) - actual, ok := mod.Memory().Read(testCtx, 0, uint32(len(tc.expectedMemory))) + actual, ok := mod.Memory().Read(0, uint32(len(tc.expectedMemory))) require.True(t, ok) require.Equal(t, tc.expectedMemory, actual) }) @@ -567,15 +567,15 @@ func Test_fdPread(t *testing.T) { t.Run(tc.name, func(t *testing.T) { defer log.Reset() - maskMemory(t, testCtx, mod, len(tc.expectedMemory)) + maskMemory(t, mod, len(tc.expectedMemory)) - ok := mod.Memory().Write(testCtx, 0, initialMemory) + ok := mod.Memory().Write(0, initialMemory) require.True(t, ok) requireErrno(t, ErrnoSuccess, mod, fdPreadName, uint64(fd), uint64(iovs), uint64(iovsCount), uint64(tc.offset), uint64(resultNread)) require.Equal(t, tc.expectedLog, "\n"+log.String()) - actual, ok := mod.Memory().Read(testCtx, 0, uint32(len(tc.expectedMemory))) + actual, ok := mod.Memory().Read(0, uint32(len(tc.expectedMemory))) require.True(t, ok) require.Equal(t, tc.expectedMemory, actual) }) @@ -719,7 +719,7 @@ func Test_fdPread_Errors(t *testing.T) { offset := uint32(wasm.MemoryPagesToBytesNum(testMemoryPageSize) - uint64(len(tc.memory))) - memoryWriteOK := mod.Memory().Write(testCtx, offset, tc.memory) + memoryWriteOK := mod.Memory().Write(offset, tc.memory) require.True(t, memoryWriteOK) requireErrno(t, tc.expectedErrno, mod, fdPreadName, uint64(tc.fd), uint64(tc.iovs+offset), uint64(tc.iovsCount+offset), uint64(tc.offset), uint64(tc.resultNread+offset)) @@ -743,7 +743,7 @@ func Test_fdPrestatGet(t *testing.T) { '?', } - maskMemory(t, testCtx, mod, len(expectedMemory)) + maskMemory(t, mod, len(expectedMemory)) requireErrno(t, ErrnoSuccess, mod, fdPrestatGetName, uint64(fd), uint64(resultPrestat)) require.Equal(t, ` @@ -755,7 +755,7 @@ func Test_fdPrestatGet(t *testing.T) { <-- 0 `, "\n"+log.String()) - actual, ok := mod.Memory().Read(testCtx, 0, uint32(len(expectedMemory))) + actual, ok := mod.Memory().Read(0, uint32(len(expectedMemory))) require.True(t, ok) require.Equal(t, expectedMemory, actual) } @@ -765,7 +765,7 @@ func Test_fdPrestatGet_Errors(t *testing.T) { defer r.Close(testCtx) fd := internalsys.FdRoot // only pre-opened directory currently supported. - memorySize := mod.Memory().Size(testCtx) + memorySize := mod.Memory().Size() tests := []struct { name string fd uint32 @@ -825,7 +825,7 @@ func Test_fdPrestatDirName(t *testing.T) { '?', '?', '?', '?', } - maskMemory(t, testCtx, mod, len(expectedMemory)) + maskMemory(t, mod, len(expectedMemory)) requireErrno(t, ErrnoSuccess, mod, fdPrestatDirNameName, uint64(fd), uint64(path), uint64(pathLen)) require.Equal(t, ` @@ -835,7 +835,7 @@ func Test_fdPrestatDirName(t *testing.T) { <-- 0 `, "\n"+log.String()) - actual, ok := mod.Memory().Read(testCtx, 0, uint32(len(expectedMemory))) + actual, ok := mod.Memory().Read(0, uint32(len(expectedMemory))) require.True(t, ok) require.Equal(t, expectedMemory, actual) } @@ -845,7 +845,7 @@ func Test_fdPrestatDirName_Errors(t *testing.T) { defer r.Close(testCtx) fd := internalsys.FdRoot // only pre-opened directory currently supported. - memorySize := mod.Memory().Size(testCtx) + memorySize := mod.Memory().Size() validAddress := uint32(0) // Arbitrary valid address as arguments to fd_prestat_dir_name. We chose 0 here. pathLen := uint32(len("/")) @@ -960,9 +960,9 @@ func Test_fdRead(t *testing.T) { '?', ) - maskMemory(t, testCtx, mod, len(expectedMemory)) + maskMemory(t, mod, len(expectedMemory)) - ok := mod.Memory().Write(testCtx, 0, initialMemory) + ok := mod.Memory().Write(0, initialMemory) require.True(t, ok) requireErrno(t, ErrnoSuccess, mod, fdReadName, uint64(fd), uint64(iovs), uint64(iovsCount), uint64(resultNread)) @@ -975,7 +975,7 @@ func Test_fdRead(t *testing.T) { <-- 0 `, "\n"+log.String()) - actual, ok := mod.Memory().Read(testCtx, 0, uint32(len(expectedMemory))) + actual, ok := mod.Memory().Read(0, uint32(len(expectedMemory))) require.True(t, ok) require.Equal(t, expectedMemory, actual) } @@ -1103,7 +1103,7 @@ func Test_fdRead_Errors(t *testing.T) { offset := uint32(wasm.MemoryPagesToBytesNum(testMemoryPageSize) - uint64(len(tc.memory))) - memoryWriteOK := mod.Memory().Write(testCtx, offset, tc.memory) + memoryWriteOK := mod.Memory().Write(offset, tc.memory) require.True(t, memoryWriteOK) requireErrno(t, tc.expectedErrno, mod, fdReadName, uint64(tc.fd), uint64(tc.iovs+offset), uint64(tc.iovsCount+offset), uint64(tc.resultNread+offset)) @@ -1489,7 +1489,7 @@ func Test_fdReaddir(t *testing.T) { file.File = dir.File file.ReadDir = dir.ReadDir - maskMemory(t, testCtx, mod, int(tc.bufLen)) + maskMemory(t, mod, int(tc.bufLen)) resultBufused := uint32(0) // where to write the amount used out of bufLen buf := uint32(8) // where to start the dirents @@ -1497,11 +1497,11 @@ func Test_fdReaddir(t *testing.T) { uint64(fd), uint64(buf), uint64(tc.bufLen), uint64(tc.cookie), uint64(resultBufused)) // read back the bufused and compare memory against it - bufUsed, ok := mod.Memory().ReadUint32Le(testCtx, resultBufused) + bufUsed, ok := mod.Memory().ReadUint32Le(resultBufused) require.True(t, ok) require.Equal(t, tc.expectedBufused, bufUsed) - mem, ok := mod.Memory().Read(testCtx, buf, bufUsed) + mem, ok := mod.Memory().Read(buf, bufUsed) require.True(t, ok) if tc.expectedMem != nil { @@ -1519,7 +1519,7 @@ func Test_fdReaddir(t *testing.T) { func Test_fdReaddir_Errors(t *testing.T) { mod, r, log := requireProxyModule(t, wazero.NewModuleConfig().WithFS(fdReadDirFs)) defer r.Close(testCtx) - memLen := mod.Memory().Size(testCtx) + memLen := mod.Memory().Size() fsc := mod.(*wasm.CallContext).Sys.FS() @@ -2013,7 +2013,7 @@ func Test_fdSeek(t *testing.T) { t.Run(tc.name, func(t *testing.T) { defer log.Reset() - maskMemory(t, testCtx, mod, len(tc.expectedMemory)) + maskMemory(t, mod, len(tc.expectedMemory)) // Since we initialized this file, we know it is a seeker (because it is a MapFile) fsc := mod.(*wasm.CallContext).Sys.FS() @@ -2029,7 +2029,7 @@ func Test_fdSeek(t *testing.T) { requireErrno(t, ErrnoSuccess, mod, fdSeekName, uint64(fd), uint64(tc.offset), uint64(tc.whence), uint64(resultNewoffset)) require.Equal(t, tc.expectedLog, "\n"+log.String()) - actual, ok := mod.Memory().Read(testCtx, 0, uint32(len(tc.expectedMemory))) + actual, ok := mod.Memory().Read(0, uint32(len(tc.expectedMemory))) require.True(t, ok) require.Equal(t, tc.expectedMemory, actual) @@ -2044,7 +2044,7 @@ func Test_fdSeek_Errors(t *testing.T) { mod, fd, log, r := requireOpenFile(t, "/test_path", []byte("wazero")) defer r.Close(testCtx) - memorySize := mod.Memory().Size(testCtx) + memorySize := mod.Memory().Size() tests := []struct { name string @@ -2155,8 +2155,8 @@ func Test_fdWrite(t *testing.T) { '?', ) - maskMemory(t, testCtx, mod, len(expectedMemory)) - ok := mod.Memory().Write(testCtx, 0, initialMemory) + maskMemory(t, mod, len(expectedMemory)) + ok := mod.Memory().Write(0, initialMemory) require.True(t, ok) requireErrno(t, ErrnoSuccess, mod, fdWriteName, uint64(fd), uint64(iovs), uint64(iovsCount), uint64(resultNwritten)) @@ -2169,7 +2169,7 @@ func Test_fdWrite(t *testing.T) { <-- 0 `, "\n"+log.String()) - actual, ok := mod.Memory().Read(testCtx, 0, uint32(len(expectedMemory))) + actual, ok := mod.Memory().Read(0, uint32(len(expectedMemory))) require.True(t, ok) require.Equal(t, expectedMemory, actual) @@ -2209,8 +2209,8 @@ func Test_fdWrite_discard(t *testing.T) { '?', ) - maskMemory(t, testCtx, mod, len(expectedMemory)) - ok := mod.Memory().Write(testCtx, 0, initialMemory) + maskMemory(t, mod, len(expectedMemory)) + ok := mod.Memory().Write(0, initialMemory) require.True(t, ok) fd := 1 // stdout @@ -2224,7 +2224,7 @@ func Test_fdWrite_discard(t *testing.T) { <-- 0 `, "\n"+log.String()) - actual, ok := mod.Memory().Read(testCtx, 0, uint32(len(expectedMemory))) + actual, ok := mod.Memory().Read(0, uint32(len(expectedMemory))) require.True(t, ok) require.Equal(t, expectedMemory, actual) } @@ -2237,7 +2237,7 @@ func Test_fdWrite_Errors(t *testing.T) { // Setup valid test memory iovsCount := uint32(1) - memSize := mod.Memory().Size(testCtx) + memSize := mod.Memory().Size() tests := []struct { name string @@ -2333,7 +2333,7 @@ func Test_fdWrite_Errors(t *testing.T) { t.Run(tc.name, func(t *testing.T) { defer log.Reset() - mod.Memory().Write(testCtx, tc.iovs, append( + mod.Memory().Write(tc.iovs, append( leb128.EncodeUint32(tc.iovs+8), // = iovs[0].offset (where the data "hi" begins) // = iovs[0].length (how many bytes are in "hi") 2, 0, 0, 0, @@ -2372,7 +2372,7 @@ func Test_pathFilestatGet(t *testing.T) { mod, r, log := requireProxyModule(t, wazero.NewModuleConfig().WithFS(testFS)) defer r.Close(testCtx) - memorySize := mod.Memory().Size(testCtx) + memorySize := mod.Memory().Size() // open both paths without using WASI fsc := mod.(*wasm.CallContext).Sys.FS() @@ -2566,14 +2566,14 @@ func Test_pathFilestatGet(t *testing.T) { t.Run(tc.name, func(t *testing.T) { defer log.Reset() - maskMemory(t, testCtx, mod, len(tc.expectedMemory)) - mod.Memory().Write(testCtx, 0, tc.memory) + maskMemory(t, mod, len(tc.expectedMemory)) + mod.Memory().Write(0, tc.memory) flags := uint32(0) requireErrno(t, tc.expectedErrno, mod, pathFilestatGetName, uint64(tc.fd), uint64(flags), uint64(1), uint64(tc.pathLen), uint64(tc.resultFilestat)) require.Equal(t, tc.expectedLog, "\n"+log.String()) - actual, ok := mod.Memory().Read(testCtx, 0, uint32(len(tc.expectedMemory))) + actual, ok := mod.Memory().Read(0, uint32(len(tc.expectedMemory))) require.True(t, ok) require.Equal(t, tc.expectedMemory, actual) }) @@ -2629,8 +2629,8 @@ func Test_pathOpen(t *testing.T) { mod, r, log := requireProxyModule(t, wazero.NewModuleConfig().WithFS(testFS)) defer r.Close(testCtx) - maskMemory(t, testCtx, mod, len(expectedMemory)) - ok := mod.Memory().Write(testCtx, 0, initialMemory) + maskMemory(t, mod, len(expectedMemory)) + ok := mod.Memory().Write(0, initialMemory) require.True(t, ok) requireErrno(t, ErrnoSuccess, mod, pathOpenName, uint64(rootFD), uint64(dirflags), uint64(path), @@ -2644,7 +2644,7 @@ func Test_pathOpen(t *testing.T) { <-- 0 `, "\n"+log.String()) - actual, ok := mod.Memory().Read(testCtx, 0, uint32(len(expectedMemory))) + actual, ok := mod.Memory().Read(0, uint32(len(expectedMemory))) require.True(t, ok) require.Equal(t, expectedMemory, actual) @@ -2691,7 +2691,7 @@ func Test_pathOpen_Errors(t *testing.T) { { name: "out-of-memory reading path", fd: validFD, - path: mod.Memory().Size(testCtx), + path: mod.Memory().Size(), pathLen: validPathLen, expectedErrno: ErrnoFault, expectedLog: ` @@ -2723,7 +2723,7 @@ func Test_pathOpen_Errors(t *testing.T) { name: "out-of-memory reading pathLen", fd: validFD, path: validPath, - pathLen: mod.Memory().Size(testCtx) + 1, // path is in the valid memory range, but pathLen is out-of-memory for path + pathLen: mod.Memory().Size() + 1, // path is in the valid memory range, but pathLen is out-of-memory for path expectedErrno: ErrnoFault, expectedLog: ` --> proxy.path_open(fd=3,dirflags=0,path=0,path_len=65537,oflags=0,fs_rights_base=0,fs_rights_inheriting=0,fdflags=0,result.opened_fd=0) @@ -2756,7 +2756,7 @@ func Test_pathOpen_Errors(t *testing.T) { pathName: dirName, path: validPath, pathLen: validPathLen, - resultOpenedFd: mod.Memory().Size(testCtx), // path and pathLen correctly point to the right path, but where to write the opened FD is outside memory. + resultOpenedFd: mod.Memory().Size(), // path and pathLen correctly point to the right path, but where to write the opened FD is outside memory. expectedErrno: ErrnoFault, expectedLog: ` --> proxy.path_open(fd=3,dirflags=0,path=0,path_len=6,oflags=0,fs_rights_base=0,fs_rights_inheriting=0,fdflags=0,result.opened_fd=65536) @@ -2789,7 +2789,7 @@ func Test_pathOpen_Errors(t *testing.T) { t.Run(tc.name, func(t *testing.T) { defer log.Reset() - mod.Memory().Write(testCtx, validPath, []byte(tc.pathName)) + mod.Memory().Write(validPath, []byte(tc.pathName)) requireErrno(t, tc.expectedErrno, mod, pathOpenName, uint64(tc.fd), uint64(0), uint64(tc.path), uint64(tc.pathLen), uint64(tc.oflags), 0, 0, 0, uint64(tc.resultOpenedFd)) diff --git a/imports/wasi_snapshot_preview1/poll.go b/imports/wasi_snapshot_preview1/poll.go index bbac008d..09d523ed 100644 --- a/imports/wasi_snapshot_preview1/poll.go +++ b/imports/wasi_snapshot_preview1/poll.go @@ -66,11 +66,11 @@ func pollOneoffFn(ctx context.Context, mod api.Module, params []uint64) (nevents mem := mod.Memory() // Ensure capacity prior to the read loop to reduce error handling. - inBuf, ok := mem.Read(ctx, in, nsubscriptions*48) + inBuf, ok := mem.Read(in, nsubscriptions*48) if !ok { return 0, ErrnoFault } - outBuf, ok := mem.Read(ctx, out, nsubscriptions*32) + outBuf, ok := mem.Read(out, nsubscriptions*32) if !ok { return 0, ErrnoFault } @@ -88,7 +88,7 @@ func pollOneoffFn(ctx context.Context, mod api.Module, params []uint64) (nevents errno = processClockEvent(ctx, mod, inBuf[inOffset+8+8:]) case eventTypeFdRead, eventTypeFdWrite: // +8 past userdata +4 FD alignment - errno = processFDEvent(ctx, mod, eventType, inBuf[inOffset+8+4:]) + errno = processFDEvent(mod, eventType, inBuf[inOffset+8+4:]) default: return 0, ErrnoInval } @@ -126,13 +126,13 @@ func processClockEvent(ctx context.Context, mod api.Module, inBuf []byte) Errno // skip name ID validation and use a single sleep function. sysCtx := mod.(*wasm.CallContext).Sys - sysCtx.Nanosleep(ctx, int64(timeout)) + sysCtx.Nanosleep(int64(timeout)) return ErrnoSuccess } // processFDEvent returns a validation error or ErrnoNotsup as file or socket // subscriptions are not yet supported. -func processFDEvent(_ context.Context, mod api.Module, eventType byte, inBuf []byte) Errno { +func processFDEvent(mod api.Module, eventType byte, inBuf []byte) Errno { fd := le.Uint32(inBuf) fsc := mod.(*wasm.CallContext).Sys.FS() diff --git a/imports/wasi_snapshot_preview1/poll_test.go b/imports/wasi_snapshot_preview1/poll_test.go index 8703e49d..78cfb616 100644 --- a/imports/wasi_snapshot_preview1/poll_test.go +++ b/imports/wasi_snapshot_preview1/poll_test.go @@ -35,8 +35,8 @@ func Test_pollOneoff(t *testing.T) { nsubscriptions := uint32(1) resultNevents := uint32(512) // past out - maskMemory(t, testCtx, mod, 1024) - mod.Memory().Write(testCtx, in, mem) + maskMemory(t, mod, 1024) + mod.Memory().Write(in, mem) requireErrno(t, ErrnoSuccess, mod, pollOneoffName, uint64(in), uint64(out), uint64(nsubscriptions), uint64(resultNevents)) @@ -49,11 +49,11 @@ func Test_pollOneoff(t *testing.T) { <-- 0 `, "\n"+log.String()) - outMem, ok := mod.Memory().Read(testCtx, out, uint32(len(expectedMem))) + outMem, ok := mod.Memory().Read(out, uint32(len(expectedMem))) require.True(t, ok) require.Equal(t, expectedMem, outMem) - nevents, ok := mod.Memory().ReadUint32Le(testCtx, resultNevents) + nevents, ok := mod.Memory().ReadUint32Le(resultNevents) require.True(t, ok) require.Equal(t, nsubscriptions, nevents) } @@ -161,23 +161,23 @@ func Test_pollOneoff_Errors(t *testing.T) { t.Run(tc.name, func(t *testing.T) { defer log.Reset() - maskMemory(t, testCtx, mod, 1024) + maskMemory(t, mod, 1024) if tc.mem != nil { - mod.Memory().Write(testCtx, tc.in, tc.mem) + mod.Memory().Write(tc.in, tc.mem) } requireErrno(t, tc.expectedErrno, mod, pollOneoffName, uint64(tc.in), uint64(tc.out), uint64(tc.nsubscriptions), uint64(tc.resultNevents)) require.Equal(t, tc.expectedLog, "\n"+log.String()) - out, ok := mod.Memory().Read(testCtx, tc.out, uint32(len(tc.expectedMem))) + out, ok := mod.Memory().Read(tc.out, uint32(len(tc.expectedMem))) require.True(t, ok) require.Equal(t, tc.expectedMem, out) // Events should be written on success regardless of nested failure. if tc.expectedErrno == ErrnoSuccess { - nevents, ok := mod.Memory().ReadUint32Le(testCtx, tc.resultNevents) + nevents, ok := mod.Memory().ReadUint32Le(tc.resultNevents) require.True(t, ok) require.Equal(t, uint32(1), nevents) } diff --git a/imports/wasi_snapshot_preview1/random.go b/imports/wasi_snapshot_preview1/random.go index e94b4f39..bb082208 100644 --- a/imports/wasi_snapshot_preview1/random.go +++ b/imports/wasi_snapshot_preview1/random.go @@ -41,7 +41,7 @@ func randomGetFn(ctx context.Context, mod api.Module, params []uint64) Errno { randSource := sysCtx.RandSource() buf, bufLen := uint32(params[0]), uint32(params[1]) - randomBytes, ok := mod.Memory().Read(ctx, buf, bufLen) + randomBytes, ok := mod.Memory().Read(buf, bufLen) if !ok { // out-of-range return ErrnoFault } diff --git a/imports/wasi_snapshot_preview1/random_test.go b/imports/wasi_snapshot_preview1/random_test.go index 63cb510d..9d041528 100644 --- a/imports/wasi_snapshot_preview1/random_test.go +++ b/imports/wasi_snapshot_preview1/random_test.go @@ -24,7 +24,7 @@ func Test_randomGet(t *testing.T) { length := uint32(5) // arbitrary length, offset := uint32(1) // offset, - maskMemory(t, testCtx, mod, len(expectedMemory)) + maskMemory(t, mod, len(expectedMemory)) // Invoke randomGet and check the memory side effects! requireErrno(t, ErrnoSuccess, mod, randomGetName, uint64(offset), uint64(length)) @@ -35,7 +35,7 @@ func Test_randomGet(t *testing.T) { <-- 0 `, "\n"+log.String()) - actual, ok := mod.Memory().Read(testCtx, 0, offset+length+1) + actual, ok := mod.Memory().Read(0, offset+length+1) require.True(t, ok) require.Equal(t, expectedMemory, actual) } @@ -44,7 +44,7 @@ func Test_randomGet_Errors(t *testing.T) { mod, r, log := requireProxyModule(t, wazero.NewModuleConfig()) defer r.Close(testCtx) - memorySize := mod.Memory().Size(testCtx) + memorySize := mod.Memory().Size() tests := []struct { name string diff --git a/imports/wasi_snapshot_preview1/wasi.go b/imports/wasi_snapshot_preview1/wasi.go index 848b6f81..85f617d1 100644 --- a/imports/wasi_snapshot_preview1/wasi.go +++ b/imports/wasi_snapshot_preview1/wasi.go @@ -221,16 +221,16 @@ func exportFunctions(builder wazero.HostModuleBuilder) { // writeOffsetsAndNullTerminatedValues is used to write NUL-terminated values // for args or environ, given a pre-defined bytesLen (which includes NUL // terminators). -func writeOffsetsAndNullTerminatedValues(ctx context.Context, mem api.Memory, values [][]byte, offsets, bytes, bytesLen uint32) Errno { +func writeOffsetsAndNullTerminatedValues(mem api.Memory, values [][]byte, offsets, bytes, bytesLen uint32) Errno { // The caller may not place bytes directly after offsets, so we have to // read them independently. valuesLen := len(values) offsetsLen := uint32(valuesLen * 4) // uint32Le - offsetsBuf, ok := mem.Read(ctx, offsets, offsetsLen) + offsetsBuf, ok := mem.Read(offsets, offsetsLen) if !ok { return ErrnoFault } - bytesBuf, ok := mem.Read(ctx, bytes, bytesLen) + bytesBuf, ok := mem.Read(bytes, bytesLen) if !ok { return ErrnoFault } diff --git a/imports/wasi_snapshot_preview1/wasi_bench_test.go b/imports/wasi_snapshot_preview1/wasi_bench_test.go index ef474db5..b4cdd686 100644 --- a/imports/wasi_snapshot_preview1/wasi_bench_test.go +++ b/imports/wasi_snapshot_preview1/wasi_bench_test.go @@ -71,7 +71,7 @@ func Benchmark_fdRead(b *testing.B) { } fn := mod.ExportedFunction(fdReadName) - mod.Memory().Write(testCtx, 0, []byte{ + mod.Memory().Write(0, []byte{ 32, 0, 0, 0, // = iovs[0].offset 8, 0, 0, 0, // = iovs[0].length 40, 0, 0, 0, // = iovs[1].offset @@ -297,7 +297,7 @@ func Benchmark_pathFilestat(b *testing.B) { pathLen := len(bc.path) resultFilestat := 1024 // where to write the stat - if !mod.Memory().WriteString(testCtx, path, bc.path) { + if !mod.Memory().WriteString(path, bc.path) { b.Fatal("could not write path") } @@ -341,7 +341,7 @@ func Benchmark_fdWrite(b *testing.B) { fn := mod.ExportedFunction(fdWriteName) iovs := uint32(1) // arbitrary offset - mod.Memory().Write(testCtx, 0, []byte{ + mod.Memory().Write(0, []byte{ '?', // `iovs` is after this 18, 0, 0, 0, // = iovs[0].offset 4, 0, 0, 0, // = iovs[0].length diff --git a/imports/wasi_snapshot_preview1/wasi_test.go b/imports/wasi_snapshot_preview1/wasi_test.go index 7d759275..36627172 100644 --- a/imports/wasi_snapshot_preview1/wasi_test.go +++ b/imports/wasi_snapshot_preview1/wasi_test.go @@ -75,9 +75,9 @@ func TestNewFunctionExporter(t *testing.T) { } // maskMemory sets the first memory in the store to '?' * size, so tests can see what's written. -func maskMemory(t *testing.T, ctx context.Context, mod api.Module, size int) { +func maskMemory(t *testing.T, mod api.Module, size int) { for i := uint32(0); i < uint32(size); i++ { - require.True(t, mod.Memory().WriteByte(ctx, i, '?')) + require.True(t, mod.Memory().WriteByte(i, '?')) } } diff --git a/internal/engine/compiler/engine.go b/internal/engine/compiler/engine.go index 207d9074..9e0f99da 100644 --- a/internal/engine/compiler/engine.go +++ b/internal/engine/compiler/engine.go @@ -921,11 +921,11 @@ entry: caller := ce.moduleContext.fn switch ce.exitContext.builtinFunctionCallIndex { case builtinFunctionIndexMemoryGrow: - ce.builtinFunctionMemoryGrow(ce.ctx, caller.source.Module.Memory) + ce.builtinFunctionMemoryGrow(caller.source.Module.Memory) case builtinFunctionIndexGrowStack: ce.builtinFunctionGrowStack(caller.stackPointerCeil) case builtinFunctionIndexTableGrow: - ce.builtinFunctionTableGrow(ce.ctx, caller.source.Module.Tables) + ce.builtinFunctionTableGrow(caller.source.Module.Tables) case builtinFunctionIndexFunctionListenerBefore: ce.builtinFunctionFunctionListenerBefore(ce.ctx, caller) case builtinFunctionIndexFunctionListenerAfter: @@ -970,10 +970,10 @@ func (ce *callEngine) builtinFunctionGrowStack(stackPointerCeil uint64) { ce.stackContext.stackLenInBytes = newLen << 3 } -func (ce *callEngine) builtinFunctionMemoryGrow(ctx context.Context, mem *wasm.MemoryInstance) { +func (ce *callEngine) builtinFunctionMemoryGrow(mem *wasm.MemoryInstance) { newPages := ce.popValue() - if res, ok := mem.Grow(ctx, uint32(newPages)); !ok { + if res, ok := mem.Grow(uint32(newPages)); !ok { ce.pushValue(uint64(0xffffffff)) // = -1 in signed 32-bit integer. } else { ce.pushValue(uint64(res)) @@ -985,12 +985,12 @@ func (ce *callEngine) builtinFunctionMemoryGrow(ctx context.Context, mem *wasm.M ce.moduleContext.memoryElement0Address = bufSliceHeader.Data } -func (ce *callEngine) builtinFunctionTableGrow(ctx context.Context, tables []*wasm.TableInstance) { +func (ce *callEngine) builtinFunctionTableGrow(tables []*wasm.TableInstance) { tableIndex := uint32(ce.popValue()) table := tables[tableIndex] // verified not to be out of range by the func validation at compilation phase. num := ce.popValue() ref := ce.popValue() - res := table.Grow(ctx, uint32(num), uintptr(ref)) + res := table.Grow(uint32(num), uintptr(ref)) ce.pushValue(uint64(res)) } diff --git a/internal/engine/compiler/engine_test.go b/internal/engine/compiler/engine_test.go index d6ed42a4..021a0641 100644 --- a/internal/engine/compiler/engine_test.go +++ b/internal/engine/compiler/engine_test.go @@ -339,7 +339,7 @@ func TestCallEngine_builtinFunctionTableGrow(t *testing.T) { } table := &wasm.TableInstance{References: []wasm.Reference{}, Min: 10} - ce.builtinFunctionTableGrow(context.Background(), []*wasm.TableInstance{table}) + ce.builtinFunctionTableGrow([]*wasm.TableInstance{table}) require.Equal(t, 1, len(table.References)) require.Equal(t, uintptr(0xff), table.References[0]) diff --git a/internal/engine/interpreter/interpreter.go b/internal/engine/interpreter/interpreter.go index 04b831c6..641d3062 100644 --- a/internal/engine/interpreter/interpreter.go +++ b/internal/engine/interpreter/interpreter.go @@ -1009,13 +1009,13 @@ func (ce *callEngine) callNativeFunc(ctx context.Context, callCtx *wasm.CallCont offset := ce.popMemoryOffset(op) switch wazeroir.UnsignedType(op.b1) { case wazeroir.UnsignedTypeI32, wazeroir.UnsignedTypeF32: - if val, ok := memoryInst.ReadUint32Le(ctx, offset); !ok { + if val, ok := memoryInst.ReadUint32Le(offset); !ok { panic(wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess) } else { ce.pushValue(uint64(val)) } case wazeroir.UnsignedTypeI64, wazeroir.UnsignedTypeF64: - if val, ok := memoryInst.ReadUint64Le(ctx, offset); !ok { + if val, ok := memoryInst.ReadUint64Le(offset); !ok { panic(wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess) } else { ce.pushValue(val) @@ -1023,7 +1023,7 @@ func (ce *callEngine) callNativeFunc(ctx context.Context, callCtx *wasm.CallCont } frame.pc++ case wazeroir.OperationKindLoad8: - val, ok := memoryInst.ReadByte(ctx, ce.popMemoryOffset(op)) + val, ok := memoryInst.ReadByte(ce.popMemoryOffset(op)) if !ok { panic(wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess) } @@ -1039,7 +1039,7 @@ func (ce *callEngine) callNativeFunc(ctx context.Context, callCtx *wasm.CallCont frame.pc++ case wazeroir.OperationKindLoad16: - val, ok := memoryInst.ReadUint16Le(ctx, ce.popMemoryOffset(op)) + val, ok := memoryInst.ReadUint16Le(ce.popMemoryOffset(op)) if !ok { panic(wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess) } @@ -1054,7 +1054,7 @@ func (ce *callEngine) callNativeFunc(ctx context.Context, callCtx *wasm.CallCont } frame.pc++ case wazeroir.OperationKindLoad32: - val, ok := memoryInst.ReadUint32Le(ctx, ce.popMemoryOffset(op)) + val, ok := memoryInst.ReadUint32Le(ce.popMemoryOffset(op)) if !ok { panic(wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess) } @@ -1070,11 +1070,11 @@ func (ce *callEngine) callNativeFunc(ctx context.Context, callCtx *wasm.CallCont offset := ce.popMemoryOffset(op) switch wazeroir.UnsignedType(op.b1) { case wazeroir.UnsignedTypeI32, wazeroir.UnsignedTypeF32: - if !memoryInst.WriteUint32Le(ctx, offset, uint32(val)) { + if !memoryInst.WriteUint32Le(offset, uint32(val)) { panic(wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess) } case wazeroir.UnsignedTypeI64, wazeroir.UnsignedTypeF64: - if !memoryInst.WriteUint64Le(ctx, offset, val) { + if !memoryInst.WriteUint64Le(offset, val) { panic(wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess) } } @@ -1082,30 +1082,30 @@ func (ce *callEngine) callNativeFunc(ctx context.Context, callCtx *wasm.CallCont case wazeroir.OperationKindStore8: val := byte(ce.popValue()) offset := ce.popMemoryOffset(op) - if !memoryInst.WriteByte(ctx, offset, val) { + if !memoryInst.WriteByte(offset, val) { panic(wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess) } frame.pc++ case wazeroir.OperationKindStore16: val := uint16(ce.popValue()) offset := ce.popMemoryOffset(op) - if !memoryInst.WriteUint16Le(ctx, offset, val) { + if !memoryInst.WriteUint16Le(offset, val) { panic(wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess) } frame.pc++ case wazeroir.OperationKindStore32: val := uint32(ce.popValue()) offset := ce.popMemoryOffset(op) - if !memoryInst.WriteUint32Le(ctx, offset, val) { + if !memoryInst.WriteUint32Le(offset, val) { panic(wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess) } frame.pc++ case wazeroir.OperationKindMemorySize: - ce.pushValue(uint64(memoryInst.PageSize(ctx))) + ce.pushValue(uint64(memoryInst.PageSize())) frame.pc++ case wazeroir.OperationKindMemoryGrow: n := ce.popValue() - if res, ok := memoryInst.Grow(ctx, uint32(n)); !ok { + if res, ok := memoryInst.Grow(uint32(n)); !ok { ce.pushValue(uint64(0xffffffff)) // = -1 in signed 32-bit integer. } else { ce.pushValue(uint64(res)) @@ -1969,7 +1969,7 @@ func (ce *callEngine) callNativeFunc(ctx context.Context, callCtx *wasm.CallCont case wazeroir.OperationKindTableGrow: table := tables[op.us[0]] num, ref := ce.popValue(), ce.popValue() - ret := table.Grow(ctx, uint32(num), uintptr(ref)) + ret := table.Grow(uint32(num), uintptr(ref)) ce.pushValue(uint64(ret)) frame.pc++ case wazeroir.OperationKindTableFill: @@ -2086,18 +2086,18 @@ func (ce *callEngine) callNativeFunc(ctx context.Context, callCtx *wasm.CallCont offset := ce.popMemoryOffset(op) switch op.b1 { case wazeroir.V128LoadType128: - lo, ok := memoryInst.ReadUint64Le(ctx, offset) + lo, ok := memoryInst.ReadUint64Le(offset) if !ok { panic(wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess) } ce.pushValue(lo) - hi, ok := memoryInst.ReadUint64Le(ctx, offset+8) + hi, ok := memoryInst.ReadUint64Le(offset + 8) if !ok { panic(wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess) } ce.pushValue(hi) case wazeroir.V128LoadType8x8s: - data, ok := memoryInst.Read(ctx, offset, 8) + data, ok := memoryInst.Read(offset, 8) if !ok { panic(wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess) } @@ -2108,7 +2108,7 @@ func (ce *callEngine) callNativeFunc(ctx context.Context, callCtx *wasm.CallCont uint64(uint16(int8(data[7])))<<48 | uint64(uint16(int8(data[6])))<<32 | uint64(uint16(int8(data[5])))<<16 | uint64(uint16(int8(data[4]))), ) case wazeroir.V128LoadType8x8u: - data, ok := memoryInst.Read(ctx, offset, 8) + data, ok := memoryInst.Read(offset, 8) if !ok { panic(wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess) } @@ -2119,7 +2119,7 @@ func (ce *callEngine) callNativeFunc(ctx context.Context, callCtx *wasm.CallCont uint64(data[7])<<48 | uint64(data[6])<<32 | uint64(data[5])<<16 | uint64(data[4]), ) case wazeroir.V128LoadType16x4s: - data, ok := memoryInst.Read(ctx, offset, 8) + data, ok := memoryInst.Read(offset, 8) if !ok { panic(wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess) } @@ -2132,7 +2132,7 @@ func (ce *callEngine) callNativeFunc(ctx context.Context, callCtx *wasm.CallCont uint64(uint32(int16(binary.LittleEndian.Uint16(data[4:])))), ) case wazeroir.V128LoadType16x4u: - data, ok := memoryInst.Read(ctx, offset, 8) + data, ok := memoryInst.Read(offset, 8) if !ok { panic(wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess) } @@ -2143,21 +2143,21 @@ func (ce *callEngine) callNativeFunc(ctx context.Context, callCtx *wasm.CallCont uint64(binary.LittleEndian.Uint16(data[6:]))<<32 | uint64(binary.LittleEndian.Uint16(data[4:])), ) case wazeroir.V128LoadType32x2s: - data, ok := memoryInst.Read(ctx, offset, 8) + data, ok := memoryInst.Read(offset, 8) if !ok { panic(wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess) } ce.pushValue(uint64(int32(binary.LittleEndian.Uint32(data)))) ce.pushValue(uint64(int32(binary.LittleEndian.Uint32(data[4:])))) case wazeroir.V128LoadType32x2u: - data, ok := memoryInst.Read(ctx, offset, 8) + data, ok := memoryInst.Read(offset, 8) if !ok { panic(wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess) } ce.pushValue(uint64(binary.LittleEndian.Uint32(data))) ce.pushValue(uint64(binary.LittleEndian.Uint32(data[4:]))) case wazeroir.V128LoadType8Splat: - v, ok := memoryInst.ReadByte(ctx, offset) + v, ok := memoryInst.ReadByte(offset) if !ok { panic(wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess) } @@ -2166,7 +2166,7 @@ func (ce *callEngine) callNativeFunc(ctx context.Context, callCtx *wasm.CallCont ce.pushValue(v8) ce.pushValue(v8) case wazeroir.V128LoadType16Splat: - v, ok := memoryInst.ReadUint16Le(ctx, offset) + v, ok := memoryInst.ReadUint16Le(offset) if !ok { panic(wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess) } @@ -2174,7 +2174,7 @@ func (ce *callEngine) callNativeFunc(ctx context.Context, callCtx *wasm.CallCont ce.pushValue(v4) ce.pushValue(v4) case wazeroir.V128LoadType32Splat: - v, ok := memoryInst.ReadUint32Le(ctx, offset) + v, ok := memoryInst.ReadUint32Le(offset) if !ok { panic(wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess) } @@ -2182,21 +2182,21 @@ func (ce *callEngine) callNativeFunc(ctx context.Context, callCtx *wasm.CallCont ce.pushValue(vv) ce.pushValue(vv) case wazeroir.V128LoadType64Splat: - lo, ok := memoryInst.ReadUint64Le(ctx, offset) + lo, ok := memoryInst.ReadUint64Le(offset) if !ok { panic(wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess) } ce.pushValue(lo) ce.pushValue(lo) case wazeroir.V128LoadType32zero: - lo, ok := memoryInst.ReadUint32Le(ctx, offset) + lo, ok := memoryInst.ReadUint32Le(offset) if !ok { panic(wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess) } ce.pushValue(uint64(lo)) ce.pushValue(0) case wazeroir.V128LoadType64zero: - lo, ok := memoryInst.ReadUint64Le(ctx, offset) + lo, ok := memoryInst.ReadUint64Le(offset) if !ok { panic(wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess) } @@ -2209,7 +2209,7 @@ func (ce *callEngine) callNativeFunc(ctx context.Context, callCtx *wasm.CallCont offset := ce.popMemoryOffset(op) switch op.b1 { case 8: - b, ok := memoryInst.ReadByte(ctx, offset) + b, ok := memoryInst.ReadByte(offset) if !ok { panic(wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess) } @@ -2221,7 +2221,7 @@ func (ce *callEngine) callNativeFunc(ctx context.Context, callCtx *wasm.CallCont hi = (hi & ^(0xff << s)) | uint64(b)<>(op.b2*8))) + ok = memoryInst.WriteByte(offset, byte(lo>>(op.b2*8))) } else { - ok = memoryInst.WriteByte(ctx, offset, byte(hi>>((op.b2-8)*8))) + ok = memoryInst.WriteByte(offset, byte(hi>>((op.b2-8)*8))) } case 16: if op.b2 < 4 { - ok = memoryInst.WriteUint16Le(ctx, offset, uint16(lo>>(op.b2*16))) + ok = memoryInst.WriteUint16Le(offset, uint16(lo>>(op.b2*16))) } else { - ok = memoryInst.WriteUint16Le(ctx, offset, uint16(hi>>((op.b2-4)*16))) + ok = memoryInst.WriteUint16Le(offset, uint16(hi>>((op.b2-4)*16))) } case 32: if op.b2 < 2 { - ok = memoryInst.WriteUint32Le(ctx, offset, uint32(lo>>(op.b2*32))) + ok = memoryInst.WriteUint32Le(offset, uint32(lo>>(op.b2*32))) } else { - ok = memoryInst.WriteUint32Le(ctx, offset, uint32(hi>>((op.b2-2)*32))) + ok = memoryInst.WriteUint32Le(offset, uint32(hi>>((op.b2-2)*32))) } case 64: if op.b2 == 0 { - ok = memoryInst.WriteUint64Le(ctx, offset, lo) + ok = memoryInst.WriteUint64Le(offset, lo) } else { - ok = memoryInst.WriteUint64Le(ctx, offset, hi) + ok = memoryInst.WriteUint64Le(offset, hi) } } if !ok { diff --git a/internal/gojs/argsenv.go b/internal/gojs/argsenv.go index 4289bee4..5f83a629 100644 --- a/internal/gojs/argsenv.go +++ b/internal/gojs/argsenv.go @@ -1,7 +1,6 @@ package gojs import ( - "context" "errors" "github.com/tetratelabs/wazero/api" @@ -17,7 +16,7 @@ const ( // WriteArgsAndEnviron writes arguments and environment variables to memory, so // they can be read by main, Go compiles as the function export "run". -func WriteArgsAndEnviron(ctx context.Context, mod api.Module) (argc, argv uint32, err error) { +func WriteArgsAndEnviron(mod api.Module) (argc, argv uint32, err error) { mem := mod.Memory() sysCtx := mod.(*wasm.CallContext).Sys args := sysCtx.Args() @@ -29,7 +28,7 @@ func WriteArgsAndEnviron(ctx context.Context, mod api.Module) (argc, argv uint32 strPtr := func(val []byte, field string, i int) (ptr uint32) { // TODO: return err and format "%s[%d], field, i" ptr = offset - mustWrite(ctx, mem, field, offset, append(val, 0)) + mustWrite(mem, field, offset, append(val, 0)) offset += uint32(len(val) + 1) if pad := offset % 8; pad != 0 { offset += 8 - pad @@ -50,7 +49,7 @@ func WriteArgsAndEnviron(ctx context.Context, mod api.Module) (argc, argv uint32 argv = offset for _, ptr := range argvPtrs { // TODO: return err and format "argvPtrs[%d], i" - mustWriteUint64Le(ctx, mem, "argvPtrs[i]", offset, uint64(ptr)) + mustWriteUint64Le(mem, "argvPtrs[i]", offset, uint64(ptr)) offset += 8 } diff --git a/internal/gojs/runtime.go b/internal/gojs/runtime.go index 15802c17..ed494513 100644 --- a/internal/gojs/runtime.go +++ b/internal/gojs/runtime.go @@ -58,7 +58,7 @@ var WasmWrite = spfunc.MustCallFromSP(false, &wasm.HostFunc{ }, }) -func wasmWrite(ctx context.Context, mod api.Module, stack []uint64) { +func wasmWrite(_ context.Context, mod api.Module, stack []uint64) { fsc := mod.(*wasm.CallContext).Sys.FS() fd, p, n := uint32(stack[0]), uint32(stack[1]), uint32(stack[2]) @@ -68,7 +68,7 @@ func wasmWrite(ctx context.Context, mod api.Module, stack []uint64) { panic(fmt.Errorf("unexpected fd %d", fd)) } - if _, err := writer.Write(mustRead(ctx, mod.Memory(), "p", p, n)); err != nil { + if _, err := writer.Write(mustRead(mod.Memory(), "p", p, n)); err != nil { panic(fmt.Errorf("error writing p: %w", err)) } } @@ -99,8 +99,8 @@ var Nanotime1 = spfunc.MustCallFromSP(false, &wasm.HostFunc{ }, }) -func nanotime1(ctx context.Context, mod api.Module, stack []uint64) { - time := mod.(*wasm.CallContext).Sys.Nanotime(ctx) +func nanotime1(_ context.Context, mod api.Module, stack []uint64) { + time := mod.(*wasm.CallContext).Sys.Nanotime() stack[0] = api.EncodeI64(time) } @@ -118,8 +118,8 @@ var Walltime = spfunc.MustCallFromSP(false, &wasm.HostFunc{ }, }) -func walltime(ctx context.Context, mod api.Module, stack []uint64) { - sec, nsec := mod.(*wasm.CallContext).Sys.Walltime(ctx) +func walltime(_ context.Context, mod api.Module, stack []uint64) { + sec, nsec := mod.(*wasm.CallContext).Sys.Walltime() stack[0] = api.EncodeI64(sec) stack[1] = api.EncodeI32(nsec) } @@ -158,11 +158,11 @@ var GetRandomData = spfunc.MustCallFromSP(false, &wasm.HostFunc{ }, }) -func getRandomData(ctx context.Context, mod api.Module, stack []uint64) { +func getRandomData(_ context.Context, mod api.Module, stack []uint64) { randSource := mod.(*wasm.CallContext).Sys.RandSource() buf, bufLen := uint32(stack[0]), uint32(stack[1]) - r := mustRead(ctx, mod.Memory(), "r", buf, bufLen) + r := mustRead(mod.Memory(), "r", buf, bufLen) if n, err := randSource.Read(r); err != nil { panic(fmt.Errorf("RandSource.Read(r /* len=%d */) failed: %w", bufLen, err)) diff --git a/internal/gojs/spfunc/spfunc_test.go b/internal/gojs/spfunc/spfunc_test.go index 33a5e81c..e98043d9 100644 --- a/internal/gojs/spfunc/spfunc_test.go +++ b/internal/gojs/spfunc/spfunc_test.go @@ -248,7 +248,7 @@ func TestMustCallFromSP(t *testing.T) { mod, err := r.InstantiateModuleFromBinary(testCtx, bin) require.NoError(t, err) - memView, ok := mod.Memory().Read(testCtx, 0, uint32(len(spMem))) + memView, ok := mod.Memory().Read(0, uint32(len(spMem))) require.True(t, ok) copy(memView, spMem) diff --git a/internal/gojs/state.go b/internal/gojs/state.go index 2f1515c3..ee440287 100644 --- a/internal/gojs/state.go +++ b/internal/gojs/state.go @@ -107,7 +107,7 @@ func loadValue(ctx context.Context, ref ref) interface{} { // nolint func loadArgs(ctx context.Context, mod api.Module, sliceAddr, sliceLen uint32) []interface{} { // nolint result := make([]interface{}, 0, sliceLen) for i := uint32(0); i < sliceLen; i++ { // nolint - iRef := mustReadUint64Le(ctx, mod.Memory(), "iRef", sliceAddr+i*8) + iRef := mustReadUint64Le(mod.Memory(), "iRef", sliceAddr+i*8) result = append(result, loadValue(ctx, ref(iRef))) } return result diff --git a/internal/gojs/syscall.go b/internal/gojs/syscall.go index 76c6c458..b6b05b2f 100644 --- a/internal/gojs/syscall.go +++ b/internal/gojs/syscall.go @@ -75,7 +75,7 @@ var StringVal = spfunc.MustCallFromSP(false, &wasm.HostFunc{ func stringVal(ctx context.Context, mod api.Module, stack []uint64) { xAddr, xLen := uint32(stack[0]), uint32(stack[1]) - x := string(mustRead(ctx, mod.Memory(), "x", xAddr, xLen)) + x := string(mustRead(mod.Memory(), "x", xAddr, xLen)) stack[0] = storeRef(ctx, x) } @@ -104,7 +104,7 @@ func valueGet(ctx context.Context, mod api.Module, stack []uint64) { pAddr := uint32(stack[1]) pLen := uint32(stack[2]) - p := string(mustRead(ctx, mod.Memory(), "p", pAddr, pLen)) + p := string(mustRead(mod.Memory(), "p", pAddr, pLen)) v := loadValue(ctx, ref(vRef)) var result interface{} @@ -150,7 +150,7 @@ func valueSet(ctx context.Context, mod api.Module, stack []uint64) { xRef := stack[3] v := loadValue(ctx, ref(vRef)) - p := string(mustRead(ctx, mod.Memory(), "p", pAddr, pLen)) + p := string(mustRead(mod.Memory(), "p", pAddr, pLen)) x := loadValue(ctx, ref(xRef)) if v == getState(ctx) { switch p { @@ -240,7 +240,7 @@ func valueCall(ctx context.Context, mod api.Module, stack []uint64) { this := ref(vRef) v := loadValue(ctx, this) - m := string(mustRead(ctx, mod.Memory(), "m", mAddr, mLen)) + m := string(mustRead(mod.Memory(), "m", mAddr, mLen)) args := loadArgs(ctx, mod, argsArray, argsLen) var xRef uint64 @@ -414,7 +414,7 @@ func valueLoadString(ctx context.Context, mod api.Module, stack []uint64) { v := loadValue(ctx, ref(vRef)) s := valueString(v) - b := mustRead(ctx, mod.Memory(), "b", bAddr, bLen) + b := mustRead(mod.Memory(), "b", bAddr, bLen) copy(b, s) } @@ -452,7 +452,7 @@ func copyBytesToGo(ctx context.Context, mod api.Module, stack []uint64) { _ /* unknown */ = uint32(stack[2]) srcRef := stack[3] - dst := mustRead(ctx, mod.Memory(), "dst", dstAddr, dstLen) // nolint + dst := mustRead(mod.Memory(), "dst", dstAddr, dstLen) // nolint v := loadValue(ctx, ref(srcRef)) var n, ok uint32 @@ -493,7 +493,7 @@ func copyBytesToJS(ctx context.Context, mod api.Module, stack []uint64) { srcLen := uint32(stack[2]) _ /* unknown */ = uint32(stack[3]) - src := mustRead(ctx, mod.Memory(), "src", srcAddr, srcLen) // nolint + src := mustRead(mod.Memory(), "src", srcAddr, srcLen) // nolint v := loadValue(ctx, ref(dstRef)) var n, ok uint32 diff --git a/internal/gojs/util.go b/internal/gojs/util.go index 928c2fd7..28723503 100644 --- a/internal/gojs/util.go +++ b/internal/gojs/util.go @@ -1,7 +1,6 @@ package gojs import ( - "context" "fmt" "github.com/tetratelabs/wazero/api" @@ -26,8 +25,8 @@ func stubFunction(name string) *wasm.HostFunc { // mustRead is like api.Memory except that it panics if the offset and // byteCount are out of range. -func mustRead(ctx context.Context, mem api.Memory, fieldName string, offset, byteCount uint32) []byte { - buf, ok := mem.Read(ctx, offset, byteCount) +func mustRead(mem api.Memory, fieldName string, offset, byteCount uint32) []byte { + buf, ok := mem.Read(offset, byteCount) if !ok { panic(fmt.Errorf("out of memory reading %s", fieldName)) } @@ -36,8 +35,8 @@ func mustRead(ctx context.Context, mem api.Memory, fieldName string, offset, byt // mustReadUint64Le is like api.Memory except that it panics if the offset // is out of range. -func mustReadUint64Le(ctx context.Context, mem api.Memory, fieldName string, offset uint32) uint64 { - result, ok := mem.ReadUint64Le(ctx, offset) +func mustReadUint64Le(mem api.Memory, fieldName string, offset uint32) uint64 { + result, ok := mem.ReadUint64Le(offset) if !ok { panic(fmt.Errorf("out of memory reading %s", fieldName)) } @@ -46,16 +45,16 @@ func mustReadUint64Le(ctx context.Context, mem api.Memory, fieldName string, off // mustWrite is like api.Memory except that it panics if the offset // is out of range. -func mustWrite(ctx context.Context, mem api.Memory, fieldName string, offset uint32, val []byte) { - if ok := mem.Write(ctx, offset, val); !ok { +func mustWrite(mem api.Memory, fieldName string, offset uint32, val []byte) { + if ok := mem.Write(offset, val); !ok { panic(fmt.Errorf("out of memory writing %s", fieldName)) } } // mustWriteUint64Le is like api.Memory except that it panics if the offset // is out of range. -func mustWriteUint64Le(ctx context.Context, mem api.Memory, fieldName string, offset uint32, val uint64) { - if ok := mem.WriteUint64Le(ctx, offset, val); !ok { +func mustWriteUint64Le(mem api.Memory, fieldName string, offset uint32, val uint64) { + if ok := mem.WriteUint64Le(offset, val); !ok { panic(fmt.Errorf("out of memory writing %s", fieldName)) } } diff --git a/internal/integration_test/bench/bench_test.go b/internal/integration_test/bench/bench_test.go index 3d206abc..ccdc7f82 100644 --- a/internal/integration_test/bench/bench_test.go +++ b/internal/integration_test/bench/bench_test.go @@ -244,11 +244,11 @@ func createRuntime(b *testing.B, config wazero.RuntimeConfig) wazero.Runtime { } offset := uint32(results[0]) - m.Memory().WriteUint32Le(ctx, retBufPtr, offset) - m.Memory().WriteUint32Le(ctx, retBufSize, 10) + m.Memory().WriteUint32Le(retBufPtr, offset) + m.Memory().WriteUint32Le(retBufSize, 10) b := make([]byte, 10) _, _ = rand.Read(b) - m.Memory().Write(ctx, offset, b) + m.Memory().Write(offset, b) } r := wazero.NewRuntimeWithConfig(testCtx, config) diff --git a/internal/integration_test/bench/hostfunc_bench_test.go b/internal/integration_test/bench/hostfunc_bench_test.go index b4dd2fc4..3e5acf80 100644 --- a/internal/integration_test/bench/hostfunc_bench_test.go +++ b/internal/integration_test/bench/hostfunc_bench_test.go @@ -149,8 +149,8 @@ func setupHostCallBench(requireNoError func(error)) *wasm.ModuleInstance { CodeSection: []*wasm.Code{ { IsHostFunction: true, - GoFunc: api.GoModuleFunc(func(ctx context.Context, mod api.Module, stack []uint64) { - ret, ok := mod.Memory().ReadUint32Le(ctx, uint32(stack[0])) + GoFunc: api.GoModuleFunc(func(_ context.Context, mod api.Module, stack []uint64) { + ret, ok := mod.Memory().ReadUint32Le(uint32(stack[0])) if !ok { panic("couldn't read memory") } @@ -158,8 +158,8 @@ func setupHostCallBench(requireNoError func(error)) *wasm.ModuleInstance { }), }, wasm.MustParseGoReflectFuncCode( - func(ctx context.Context, m api.Module, pos uint32) float32 { - ret, ok := m.Memory().ReadUint32Le(ctx, pos) + func(_ context.Context, m api.Module, pos uint32) float32 { + ret, ok := m.Memory().ReadUint32Le(pos) if !ok { panic("couldn't read memory") } diff --git a/internal/integration_test/bench/memory_bench_test.go b/internal/integration_test/bench/memory_bench_test.go index ef4902ef..558eae0b 100644 --- a/internal/integration_test/bench/memory_bench_test.go +++ b/internal/integration_test/bench/memory_bench_test.go @@ -8,13 +8,13 @@ import ( func BenchmarkMemory(b *testing.B) { mem := &wasm.MemoryInstance{Buffer: make([]byte, wasm.MemoryPageSize), Min: 1} - if !mem.WriteByte(testCtx, 10, 16) { + if !mem.WriteByte(10, 16) { b.Fail() } b.Run("ReadByte", func(b *testing.B) { for i := 0; i < b.N; i++ { - if v, ok := mem.ReadByte(testCtx, 10); !ok || v != 16 { + if v, ok := mem.ReadByte(10); !ok || v != 16 { b.Fail() } } @@ -22,7 +22,7 @@ func BenchmarkMemory(b *testing.B) { b.Run("ReadUint32Le", func(b *testing.B) { for i := 0; i < b.N; i++ { - if v, ok := mem.ReadUint32Le(testCtx, 10); !ok || v != 16 { + if v, ok := mem.ReadUint32Le(10); !ok || v != 16 { b.Fail() } } @@ -30,7 +30,7 @@ func BenchmarkMemory(b *testing.B) { b.Run("WriteByte", func(b *testing.B) { for i := 0; i < b.N; i++ { - if !mem.WriteByte(testCtx, 10, 16) { + if !mem.WriteByte(10, 16) { b.Fail() } } @@ -38,7 +38,7 @@ func BenchmarkMemory(b *testing.B) { b.Run("WriteUint32Le", func(b *testing.B) { for i := 0; i < b.N; i++ { - if !mem.WriteUint32Le(testCtx, 10, 16) { + if !mem.WriteUint32Le(10, 16) { b.Fail() } } diff --git a/internal/integration_test/engine/adhoc_test.go b/internal/integration_test/engine/adhoc_test.go index 4010d62b..7872dcc8 100644 --- a/internal/integration_test/engine/adhoc_test.go +++ b/internal/integration_test/engine/adhoc_test.go @@ -211,7 +211,7 @@ func testRecursiveEntry(t *testing.T, r wazero.Runtime) { func testHostFuncMemory(t *testing.T, r wazero.Runtime) { var memory *wasm.MemoryInstance storeInt := func(ctx context.Context, m api.Module, offset uint32, val uint64) uint32 { - if !m.Memory().WriteUint64Le(ctx, offset, val) { + if !m.Memory().WriteUint64Le(offset, val) { return 1 } // sneak a reference to the memory, so we can check it later @@ -571,7 +571,7 @@ func testMemOps(t *testing.T, r wazero.Runtime) { results, err := sizeFn.Call(testCtx) require.NoError(t, err) require.Zero(t, results[0]) - require.Zero(t, memory.Size(testCtx)) + require.Zero(t, memory.Size()) // Any offset should be out of bounds error even when it is less than memory capacity(=memoryCapacityPages). _, err = storeFn.Call(testCtx, wasm.MemoryPagesToBytesNum(memoryCapacityPages)-8) @@ -589,8 +589,8 @@ func testMemOps(t *testing.T, r wazero.Runtime) { // Check the size command works! results, err = sizeFn.Call(testCtx) require.NoError(t, err) - require.Equal(t, uint64(1), results[0]) // 1 page - require.Equal(t, uint32(65536), memory.Size(testCtx)) // 64KB + require.Equal(t, uint64(1), results[0]) // 1 page + require.Equal(t, uint32(65536), memory.Size()) // 64KB // Grow again so that the memory size matches memory capacity. results, err = growFn.Call(testCtx, 1) @@ -633,7 +633,7 @@ func testMultipleInstantiation(t *testing.T, r wazero.Runtime) { defer module.Close(testCtx) // Ensure that compilation cache doesn't cause race on memory instance. - before, ok := module.Memory().ReadUint64Le(testCtx, 1) + before, ok := module.Memory().ReadUint64Le(1) require.True(t, ok) // Value must be zero as the memory must not be affected by the previously instantiated modules. require.Zero(t, before) @@ -645,7 +645,7 @@ func testMultipleInstantiation(t *testing.T, r wazero.Runtime) { require.NoError(t, err) // After the call, the value must be set properly. - after, ok := module.Memory().ReadUint64Le(testCtx, 1) + after, ok := module.Memory().ReadUint64Le(1) require.True(t, ok) require.Equal(t, uint64(1000), after) } diff --git a/internal/integration_test/fs/fs_test.go b/internal/integration_test/fs/fs_test.go index 7f193d79..2e9be67b 100644 --- a/internal/integration_test/fs/fs_test.go +++ b/internal/integration_test/fs/fs_test.go @@ -48,7 +48,7 @@ func (fs *wasiFs) Open(name string) (fs.File, error) { pathBytes := []byte(name) // Pick anywhere in memory to write the path to. pathPtr := uint32(0) - ok := fs.memory.Write(testCtx, pathPtr, pathBytes) + ok := fs.memory.Write(pathPtr, pathBytes) require.True(fs.t, ok) resultOpenedFd := pathPtr + uint32(len(pathBytes)) @@ -66,7 +66,7 @@ func (fs *wasiFs) Open(name string) (fs.File, error) { require.NoError(fs.t, err) require.Equal(fs.t, uint64(wasi_snapshot_preview1.ErrnoSuccess), res[0]) - resFd, ok := fs.memory.ReadUint32Le(testCtx, resultOpenedFd) + resFd, ok := fs.memory.ReadUint32Le(resultOpenedFd) require.True(fs.t, ok) return &wasiFile{fd: resFd, fs: fs}, nil @@ -96,10 +96,10 @@ func (f *wasiFile) Read(bytes []byte) (int, error) { // iov starts at iovsOff + 8 because we first write four bytes for the offset itself, and // four bytes for the length of the iov. iovOff := iovsOff + uint32(8) - ok := f.fs.memory.WriteUint32Le(testCtx, iovsOff, iovOff) + ok := f.fs.memory.WriteUint32Le(iovsOff, iovOff) require.True(f.fs.t, ok) // next write the length. - ok = f.fs.memory.WriteUint32Le(testCtx, iovsOff+uint32(4), uint32(len(bytes))) + ok = f.fs.memory.WriteUint32Le(iovsOff+uint32(4), uint32(len(bytes))) require.True(f.fs.t, ok) res, err := f.fs.fdRead.Call(testCtx, uint64(f.fd), uint64(iovsOff), uint64(iovsCount), uint64(resultSizeOff)) @@ -107,7 +107,7 @@ func (f *wasiFile) Read(bytes []byte) (int, error) { require.NotEqual(f.fs.t, uint64(wasi_snapshot_preview1.ErrnoFault), res[0]) - numRead, ok := f.fs.memory.ReadUint32Le(testCtx, resultSizeOff) + numRead, ok := f.fs.memory.ReadUint32Le(resultSizeOff) require.True(f.fs.t, ok) if numRead == 0 { @@ -121,7 +121,7 @@ func (f *wasiFile) Read(bytes []byte) (int, error) { } } - buf, ok := f.fs.memory.Read(testCtx, iovOff, numRead) + buf, ok := f.fs.memory.Read(iovOff, numRead) require.True(f.fs.t, ok) copy(bytes, buf) return int(numRead), nil @@ -142,7 +142,7 @@ func (f *wasiFile) Seek(offset int64, whence int) (int64, error) { require.NoError(f.fs.t, err) require.NotEqual(f.fs.t, uint64(wasi_snapshot_preview1.ErrnoFault), res[0]) - newOffset, ok := f.fs.memory.ReadUint32Le(testCtx, resultNewoffsetOff) + newOffset, ok := f.fs.memory.ReadUint32Le(resultNewoffsetOff) require.True(f.fs.t, ok) return int64(newOffset), nil diff --git a/internal/integration_test/fuzzcases/fuzzcases_test.go b/internal/integration_test/fuzzcases/fuzzcases_test.go index 21ae89db..1a53ed1e 100644 --- a/internal/integration_test/fuzzcases/fuzzcases_test.go +++ b/internal/integration_test/fuzzcases/fuzzcases_test.go @@ -325,7 +325,7 @@ func Test733(t *testing.T) { mem := mod.Memory() require.NotNil(t, mem) - v, ok := mem.ReadUint64Le(ctx, 0x80000100) + v, ok := mem.ReadUint64Le(0x80000100) require.True(t, ok) require.Equal(t, uint64(0xffffffffffffffff), v) }) diff --git a/internal/integration_test/spectest/spectest.go b/internal/integration_test/spectest/spectest.go index 5747377b..d588b609 100644 --- a/internal/integration_test/spectest/spectest.go +++ b/internal/integration_test/spectest/spectest.go @@ -492,7 +492,7 @@ func Run(t *testing.T, testDataFS embed.FS, ctx context.Context, newEngine func( expType = wasm.ValueTypeF64 } require.Equal(t, expType, global.Type(), msg) - require.Equal(t, exps[0], global.Get(ctx), msg) + require.Equal(t, exps[0], global.Get(), msg) default: t.Fatalf("unsupported action type type: %v", c) } diff --git a/internal/integration_test/vs/bench_allocation.go b/internal/integration_test/vs/bench_allocation.go index 6ec400b4..1c8d893c 100644 --- a/internal/integration_test/vs/bench_allocation.go +++ b/internal/integration_test/vs/bench_allocation.go @@ -46,7 +46,7 @@ func allocationCall(m Module, _ int) error { } // The pointer is a linear memory offset, which is where we write the name. - if err = m.WriteMemory(testCtx, namePtr, []byte(allocationParam)); err != nil { + if err = m.WriteMemory(namePtr, []byte(allocationParam)); err != nil { return err } diff --git a/internal/integration_test/vs/runtime.go b/internal/integration_test/vs/runtime.go index 04794964..ef4c12fb 100644 --- a/internal/integration_test/vs/runtime.go +++ b/internal/integration_test/vs/runtime.go @@ -40,7 +40,7 @@ type Module interface { CallI32_V(ctx context.Context, funcName string, param uint32) error CallV_V(ctx context.Context, funcName string) error CallI64_I64(ctx context.Context, funcName string, param uint64) (uint64, error) - WriteMemory(ctx context.Context, offset uint32, bytes []byte) error + WriteMemory(offset uint32, bytes []byte) error Memory() []byte Close(context.Context) error } @@ -79,10 +79,10 @@ func (m *wazeroModule) Memory() []byte { return m.mod.Memory().(*wasm.MemoryInstance).Buffer } -func (r *wazeroRuntime) log(ctx context.Context, mod api.Module, stack []uint64) { +func (r *wazeroRuntime) log(_ context.Context, mod api.Module, stack []uint64) { offset, byteCount := uint32(stack[0]), uint32(stack[1]) - buf, ok := mod.Memory().Read(ctx, offset, byteCount) + buf, ok := mod.Memory().Read(offset, byteCount) if !ok { panic("out of memory reading log buffer") } @@ -197,8 +197,8 @@ func (m *wazeroModule) CallI64_I64(ctx context.Context, funcName string, param u return 0, nil } -func (m *wazeroModule) WriteMemory(ctx context.Context, offset uint32, bytes []byte) error { - if !m.mod.Memory().Write(ctx, offset, bytes) { +func (m *wazeroModule) WriteMemory(offset uint32, bytes []byte) error { + if !m.mod.Memory().Write(offset, bytes) { return errors.New("out of memory writing name") } return nil diff --git a/internal/integration_test/vs/wasmedge/wasmedge.go b/internal/integration_test/vs/wasmedge/wasmedge.go index 498a282f..ee932268 100644 --- a/internal/integration_test/vs/wasmedge/wasmedge.go +++ b/internal/integration_test/vs/wasmedge/wasmedge.go @@ -173,7 +173,7 @@ func (m *wasmedgeModule) CallI64_I64(_ context.Context, funcName string, param u } } -func (m *wasmedgeModule) WriteMemory(_ context.Context, offset uint32, bytes []byte) error { +func (m *wasmedgeModule) WriteMemory(offset uint32, bytes []byte) error { mod := m.vm.GetActiveModule() mem := mod.FindMemory("memory") if unsafeSlice, err := mem.GetData(uint(offset), uint(len(bytes))); err != nil { diff --git a/internal/integration_test/vs/wasmer/wasmer.go b/internal/integration_test/vs/wasmer/wasmer.go index 0402b5a5..f11c237d 100644 --- a/internal/integration_test/vs/wasmer/wasmer.go +++ b/internal/integration_test/vs/wasmer/wasmer.go @@ -185,7 +185,7 @@ func (m *wasmerModule) CallI64_I64(_ context.Context, funcName string, param uin } } -func (m *wasmerModule) WriteMemory(_ context.Context, offset uint32, bytes []byte) error { +func (m *wasmerModule) WriteMemory(offset uint32, bytes []byte) error { unsafeSlice := m.mem.Data() copy(unsafeSlice[offset:], bytes) return nil diff --git a/internal/integration_test/vs/wasmtime/wasmtime.go b/internal/integration_test/vs/wasmtime/wasmtime.go index 8f02c691..f799edb2 100644 --- a/internal/integration_test/vs/wasmtime/wasmtime.go +++ b/internal/integration_test/vs/wasmtime/wasmtime.go @@ -187,7 +187,7 @@ func (m *wasmtimeModule) CallI64_I64(_ context.Context, funcName string, param u } } -func (m *wasmtimeModule) WriteMemory(_ context.Context, offset uint32, bytes []byte) error { +func (m *wasmtimeModule) WriteMemory(offset uint32, bytes []byte) error { unsafeSlice := m.mem.UnsafeData(m.store) copy(unsafeSlice[offset:], bytes) return nil diff --git a/internal/platform/time.go b/internal/platform/time.go index 2f5c2a67..21e419d6 100644 --- a/internal/platform/time.go +++ b/internal/platform/time.go @@ -1,7 +1,6 @@ package platform import ( - "context" "sync/atomic" "time" @@ -19,7 +18,7 @@ const ( func NewFakeWalltime() *sys.Walltime { // AddInt64 returns the new value. Adjust so the first reading will be FakeEpochNanos t := FakeEpochNanos - ms - var wt sys.Walltime = func(context.Context) (sec int64, nsec int32) { + var wt sys.Walltime = func() (sec int64, nsec int32) { wt := atomic.AddInt64(&t, ms) return wt / 1e9, int32(wt % 1e9) } @@ -31,15 +30,14 @@ func NewFakeWalltime() *sys.Walltime { func NewFakeNanotime() *sys.Nanotime { // AddInt64 returns the new value. Adjust so the first reading will be zero. t := int64(0) - ms - var nt sys.Nanotime = func(context.Context) int64 { + var nt sys.Nanotime = func() int64 { return atomic.AddInt64(&t, ms) } return &nt } // FakeNanosleep implements sys.Nanosleep by returning without sleeping. -func FakeNanosleep(context.Context, int64) { -} +func FakeNanosleep(int64) {} // Walltime implements sys.Walltime with time.Now. // @@ -48,7 +46,7 @@ func FakeNanosleep(context.Context, int64) { // time.Since is used. This doubles the performance impact. However, wall time // is likely to be read less frequently than Nanotime. Also, doubling the cost // matters less on fast platforms that can return both in <=100ns. -func Walltime(context.Context) (sec int64, nsec int32) { +func Walltime() (sec int64, nsec int32) { t := time.Now() return t.Unix(), int32(t.Nanosecond()) } @@ -67,11 +65,11 @@ func nanotimePortable() int64 { // Nanotime implements sys.Nanotime with runtime.nanotime() if CGO is available // and time.Since if not. -func Nanotime(context.Context) int64 { +func Nanotime() int64 { return nanotime() } // Nanosleep implements sys.Nanosleep with time.Sleep. -func Nanosleep(_ context.Context, ns int64) { +func Nanosleep(ns int64) { time.Sleep(time.Duration(ns)) } diff --git a/internal/platform/time_test.go b/internal/platform/time_test.go index 8adee9d1..d7d2ae2b 100644 --- a/internal/platform/time_test.go +++ b/internal/platform/time_test.go @@ -1,7 +1,6 @@ package platform import ( - "context" "testing" "time" @@ -13,27 +12,27 @@ func Test_NewFakeWalltime(t *testing.T) { wt := NewFakeWalltime() // Base should be the same as FakeEpochNanos - sec, nsec := (*wt)(context.Background()) + sec, nsec := (*wt)() ft := time.UnixMicro(FakeEpochNanos / time.Microsecond.Nanoseconds()).UTC() require.Equal(t, ft, time.Unix(sec, int64(nsec)).UTC()) // next reading should increase by 1ms - sec, nsec = (*wt)(context.Background()) + sec, nsec = (*wt)() require.Equal(t, ft.Add(time.Millisecond), time.Unix(sec, int64(nsec)).UTC()) } func Test_NewFakeNanotime(t *testing.T) { nt := NewFakeNanotime() - require.Equal(t, int64(0), (*nt)(context.Background())) + require.Equal(t, int64(0), (*nt)()) // next reading should increase by 1ms - require.Equal(t, int64(time.Millisecond), (*nt)(context.Background())) + require.Equal(t, int64(time.Millisecond), (*nt)()) } func Test_Walltime(t *testing.T) { now := time.Now().Unix() - sec, nsec := Walltime(context.Background()) + sec, nsec := Walltime() // Loose test that the second variant is close to now. // The only thing that could flake this is a time adjustment during the test. @@ -50,16 +49,14 @@ func Test_Nanotime(t *testing.T) { nanotime sys.Nanotime }{ {"Nanotime", Nanotime}, - {"nanotimePortable", func(ctx context.Context) int64 { - return nanotimePortable() - }}, + {"nanotimePortable", nanotimePortable}, } for _, tt := range tests { tc := tt t.Run(tc.name, func(t *testing.T) { delta := time.Since(nanoBase).Nanoseconds() - nanos := Nanotime(context.Background()) + nanos := Nanotime() // It takes more than a nanosecond to make the two clock readings required // to implement time.Now. Hence, delta will always be less than nanos. @@ -74,9 +71,9 @@ func Test_Nanosleep(t *testing.T) { ns := int64(50 * time.Millisecond) max := ns * 5 - start := Nanotime(context.Background()) - Nanosleep(context.Background(), ns) - duration := Nanotime(context.Background()) - start + start := Nanotime() + Nanosleep(ns) + duration := Nanotime() - start require.True(t, duration > 0 && duration < max, "Nanosleep(%d) slept for %d", ns, duration) } diff --git a/internal/sys/sys.go b/internal/sys/sys.go index 0066cbb8..c678f801 100644 --- a/internal/sys/sys.go +++ b/internal/sys/sys.go @@ -1,7 +1,6 @@ package sys import ( - "context" "errors" "fmt" "io" @@ -64,8 +63,8 @@ func (c *Context) EnvironSize() uint32 { } // Walltime implements sys.Walltime. -func (c *Context) Walltime(ctx context.Context) (sec int64, nsec int32) { - return (*(c.walltime))(ctx) +func (c *Context) Walltime() (sec int64, nsec int32) { + return (*(c.walltime))() } // WalltimeResolution returns resolution of Walltime. @@ -74,8 +73,8 @@ func (c *Context) WalltimeResolution() sys.ClockResolution { } // Nanotime implements sys.Nanotime. -func (c *Context) Nanotime(ctx context.Context) int64 { - return (*(c.nanotime))(ctx) +func (c *Context) Nanotime() int64 { + return (*(c.nanotime))() } // NanotimeResolution returns resolution of Nanotime. @@ -84,8 +83,8 @@ func (c *Context) NanotimeResolution() sys.ClockResolution { } // Nanosleep implements sys.Nanosleep. -func (c *Context) Nanosleep(ctx context.Context, ns int64) { - (*(c.nanosleep))(ctx, ns) +func (c *Context) Nanosleep(ns int64) { + (*(c.nanosleep))(ns) } // FS returns the possibly empty (EmptyFS) file system context. diff --git a/internal/sys/sys_test.go b/internal/sys/sys_test.go index bb84a92f..2300abe0 100644 --- a/internal/sys/sys_test.go +++ b/internal/sys/sys_test.go @@ -2,7 +2,6 @@ package sys import ( "bytes" - "context" "io" "testing" "time" @@ -44,10 +43,10 @@ func TestDefaultSysContext(t *testing.T) { require.Zero(t, sysCtx.EnvironSize()) // To compare functions, we can only compare pointers, but the pointer will // change. Hence, we have to compare the results instead. - sec, _ := sysCtx.Walltime(testCtx) + sec, _ := sysCtx.Walltime() require.Equal(t, platform.FakeEpochNanos/time.Second.Nanoseconds(), sec) require.Equal(t, sys.ClockResolution(1_000), sysCtx.WalltimeResolution()) - require.Zero(t, sysCtx.Nanotime(testCtx)) // See above on functions. + require.Zero(t, sysCtx.Nanotime()) // See above on functions. require.Equal(t, sys.ClockResolution(1), sysCtx.NanotimeResolution()) require.Equal(t, &ns, sysCtx.nanosleep) require.Equal(t, platform.NewFakeRandSource(), sysCtx.RandSource()) @@ -311,8 +310,7 @@ func Test_clockResolutionInvalid(t *testing.T) { } func TestNewContext_Nanosleep(t *testing.T) { - var aNs sys.Nanosleep = func(context.Context, int64) { - } + var aNs sys.Nanosleep = func(int64) {} sysCtx, err := NewContext( 0, // max nil, // args diff --git a/internal/testing/enginetest/enginetest.go b/internal/testing/enginetest/enginetest.go index 22956896..f735d256 100644 --- a/internal/testing/enginetest/enginetest.go +++ b/internal/testing/enginetest/enginetest.go @@ -483,7 +483,7 @@ func RunTestModuleEngine_Memory(t *testing.T, et EngineTester) { require.NoError(t, err) linkModuleToEngine(module, me) - buf, ok := memory.Read(testCtx, 0, wasmPhraseSize) + buf, ok := memory.Read(0, wasmPhraseSize) require.True(t, ok) require.Equal(t, make([]byte, wasmPhraseSize), buf) @@ -505,7 +505,7 @@ func RunTestModuleEngine_Memory(t *testing.T, et EngineTester) { // The underlying memory should be updated. This proves that Memory.Read returns a re-slice, not a copy, and that // programs can rely on this (for example, to update shared state in Wasm and view that in Go and visa versa). - buf2, ok := memory.Read(testCtx, 0, wasmPhraseSize) + buf2, ok := memory.Read(0, wasmPhraseSize) require.True(t, ok) require.Equal(t, buf, buf2) @@ -514,7 +514,7 @@ func RunTestModuleEngine_Memory(t *testing.T, et EngineTester) { require.Equal(t, hostPhrase, string(buf)) // To prove the above, we re-read the memory and should not see the appended bytes (rather zeros instead). - buf2, ok = memory.Read(testCtx, 0, hostPhraseSize) + buf2, ok = memory.Read(0, hostPhraseSize) require.True(t, ok) hostPhraseTruncated := "Goodbye, cruel world. I'm off to join the circ" + string([]byte{0, 0, 0}) require.Equal(t, hostPhraseTruncated, string(buf2)) @@ -567,8 +567,8 @@ const ( callImportCallReadMemName = "call_import->call->read_mem" ) -func readMemGo(ctx context.Context, m api.Module) uint64 { - ret, ok := m.Memory().ReadUint64Le(ctx, 0) +func readMemGo(_ context.Context, m api.Module) uint64 { + ret, ok := m.Memory().ReadUint64Le(0) if !ok { panic("couldn't read memory") } diff --git a/internal/wasm/global.go b/internal/wasm/global.go index 51bf578a..caddaaf0 100644 --- a/internal/wasm/global.go +++ b/internal/wasm/global.go @@ -1,7 +1,6 @@ package wasm import ( - "context" "fmt" "github.com/tetratelabs/wazero/api" @@ -20,12 +19,12 @@ func (g *mutableGlobal) Type() api.ValueType { } // Get implements the same method as documented on api.Global. -func (g *mutableGlobal) Get(context.Context) uint64 { +func (g *mutableGlobal) Get() uint64 { return g.g.Val } // Set implements the same method as documented on api.MutableGlobal. -func (g *mutableGlobal) Set(_ context.Context, v uint64) { +func (g *mutableGlobal) Set(v uint64) { g.g.Val = v } @@ -33,11 +32,11 @@ func (g *mutableGlobal) Set(_ context.Context, v uint64) { func (g *mutableGlobal) String() string { switch g.Type() { case ValueTypeI32, ValueTypeI64: - return fmt.Sprintf("global(%d)", g.Get(context.Background())) + return fmt.Sprintf("global(%d)", g.Get()) case ValueTypeF32: - return fmt.Sprintf("global(%f)", api.DecodeF32(g.Get(context.Background()))) + return fmt.Sprintf("global(%f)", api.DecodeF32(g.Get())) case ValueTypeF64: - return fmt.Sprintf("global(%f)", api.DecodeF64(g.Get(context.Background()))) + return fmt.Sprintf("global(%f)", api.DecodeF64(g.Get())) default: panic(fmt.Errorf("BUG: unknown value type %X", g.Type())) } @@ -54,7 +53,7 @@ func (g globalI32) Type() api.ValueType { } // Get implements the same method as documented on api.Global. -func (g globalI32) Get(context.Context) uint64 { +func (g globalI32) Get() uint64 { return uint64(g) } @@ -74,7 +73,7 @@ func (g globalI64) Type() api.ValueType { } // Get implements the same method as documented on api.Global. -func (g globalI64) Get(context.Context) uint64 { +func (g globalI64) Get() uint64 { return uint64(g) } @@ -94,13 +93,13 @@ func (g globalF32) Type() api.ValueType { } // Get implements the same method as documented on api.Global. -func (g globalF32) Get(context.Context) uint64 { +func (g globalF32) Get() uint64 { return uint64(g) } // String implements fmt.Stringer func (g globalF32) String() string { - return fmt.Sprintf("global(%f)", api.DecodeF32(g.Get(context.Background()))) + return fmt.Sprintf("global(%f)", api.DecodeF32(g.Get())) } type globalF64 uint64 @@ -114,11 +113,11 @@ func (g globalF64) Type() api.ValueType { } // Get implements the same method as documented on api.Global. -func (g globalF64) Get(context.Context) uint64 { +func (g globalF64) Get() uint64 { return uint64(g) } // String implements fmt.Stringer func (g globalF64) String() string { - return fmt.Sprintf("global(%f)", api.DecodeF64(g.Get(context.Background()))) + return fmt.Sprintf("global(%f)", api.DecodeF64(g.Get())) } diff --git a/internal/wasm/global_test.go b/internal/wasm/global_test.go index d519616d..58efed6b 100644 --- a/internal/wasm/global_test.go +++ b/internal/wasm/global_test.go @@ -126,20 +126,18 @@ func TestGlobalTypes(t *testing.T) { tc := tt t.Run(tc.name, func(t *testing.T) { - for _, ctx := range []context.Context{nil, testCtx} { // Ensure it doesn't crash on nil! - require.Equal(t, tc.expectedType, tc.global.Type()) - require.Equal(t, tc.expectedVal, tc.global.Get(ctx)) - require.Equal(t, tc.expectedString, tc.global.String()) + require.Equal(t, tc.expectedType, tc.global.Type()) + require.Equal(t, tc.expectedVal, tc.global.Get()) + require.Equal(t, tc.expectedString, tc.global.String()) - mutable, ok := tc.global.(api.MutableGlobal) - require.Equal(t, tc.expectedMutable, ok) - if ok { - mutable.Set(ctx, 2) - require.Equal(t, uint64(2), tc.global.Get(ctx)) + mutable, ok := tc.global.(api.MutableGlobal) + require.Equal(t, tc.expectedMutable, ok) + if ok { + mutable.Set(2) + require.Equal(t, uint64(2), tc.global.Get()) - mutable.Set(ctx, tc.expectedVal) // Set it back! - require.Equal(t, tc.expectedVal, tc.global.Get(ctx)) - } + mutable.Set(tc.expectedVal) // Set it back! + require.Equal(t, tc.expectedVal, tc.global.Get()) } }) } diff --git a/internal/wasm/memory.go b/internal/wasm/memory.go index 0205695c..3ee69cad 100644 --- a/internal/wasm/memory.go +++ b/internal/wasm/memory.go @@ -1,7 +1,6 @@ package wasm import ( - "context" "encoding/binary" "fmt" "math" @@ -59,12 +58,12 @@ func (m *MemoryInstance) Definition() api.MemoryDefinition { } // Size implements the same method as documented on api.Memory. -func (m *MemoryInstance) Size(context.Context) uint32 { +func (m *MemoryInstance) Size() uint32 { return m.size() } // ReadByte implements the same method as documented on api.Memory. -func (m *MemoryInstance) ReadByte(_ context.Context, offset uint32) (byte, bool) { +func (m *MemoryInstance) ReadByte(offset uint32) (byte, bool) { if offset >= m.size() { return 0, false } @@ -72,7 +71,7 @@ func (m *MemoryInstance) ReadByte(_ context.Context, offset uint32) (byte, bool) } // ReadUint16Le implements the same method as documented on api.Memory. -func (m *MemoryInstance) ReadUint16Le(_ context.Context, offset uint32) (uint16, bool) { +func (m *MemoryInstance) ReadUint16Le(offset uint32) (uint16, bool) { if !m.hasSize(offset, 2) { return 0, false } @@ -80,12 +79,12 @@ func (m *MemoryInstance) ReadUint16Le(_ context.Context, offset uint32) (uint16, } // ReadUint32Le implements the same method as documented on api.Memory. -func (m *MemoryInstance) ReadUint32Le(_ context.Context, offset uint32) (uint32, bool) { +func (m *MemoryInstance) ReadUint32Le(offset uint32) (uint32, bool) { return m.readUint32Le(offset) } // ReadFloat32Le implements the same method as documented on api.Memory. -func (m *MemoryInstance) ReadFloat32Le(_ context.Context, offset uint32) (float32, bool) { +func (m *MemoryInstance) ReadFloat32Le(offset uint32) (float32, bool) { v, ok := m.readUint32Le(offset) if !ok { return 0, false @@ -94,12 +93,12 @@ func (m *MemoryInstance) ReadFloat32Le(_ context.Context, offset uint32) (float3 } // ReadUint64Le implements the same method as documented on api.Memory. -func (m *MemoryInstance) ReadUint64Le(_ context.Context, offset uint32) (uint64, bool) { +func (m *MemoryInstance) ReadUint64Le(offset uint32) (uint64, bool) { return m.readUint64Le(offset) } // ReadFloat64Le implements the same method as documented on api.Memory. -func (m *MemoryInstance) ReadFloat64Le(_ context.Context, offset uint32) (float64, bool) { +func (m *MemoryInstance) ReadFloat64Le(offset uint32) (float64, bool) { v, ok := m.readUint64Le(offset) if !ok { return 0, false @@ -108,7 +107,7 @@ func (m *MemoryInstance) ReadFloat64Le(_ context.Context, offset uint32) (float6 } // Read implements the same method as documented on api.Memory. -func (m *MemoryInstance) Read(_ context.Context, offset, byteCount uint32) ([]byte, bool) { +func (m *MemoryInstance) Read(offset, byteCount uint32) ([]byte, bool) { if !m.hasSize(offset, byteCount) { return nil, false } @@ -116,7 +115,7 @@ func (m *MemoryInstance) Read(_ context.Context, offset, byteCount uint32) ([]by } // WriteByte implements the same method as documented on api.Memory. -func (m *MemoryInstance) WriteByte(_ context.Context, offset uint32, v byte) bool { +func (m *MemoryInstance) WriteByte(offset uint32, v byte) bool { if offset >= m.size() { return false } @@ -125,7 +124,7 @@ func (m *MemoryInstance) WriteByte(_ context.Context, offset uint32, v byte) boo } // WriteUint16Le implements the same method as documented on api.Memory. -func (m *MemoryInstance) WriteUint16Le(_ context.Context, offset uint32, v uint16) bool { +func (m *MemoryInstance) WriteUint16Le(offset uint32, v uint16) bool { if !m.hasSize(offset, 2) { return false } @@ -134,27 +133,27 @@ func (m *MemoryInstance) WriteUint16Le(_ context.Context, offset uint32, v uint1 } // WriteUint32Le implements the same method as documented on api.Memory. -func (m *MemoryInstance) WriteUint32Le(_ context.Context, offset, v uint32) bool { +func (m *MemoryInstance) WriteUint32Le(offset, v uint32) bool { return m.writeUint32Le(offset, v) } // WriteFloat32Le implements the same method as documented on api.Memory. -func (m *MemoryInstance) WriteFloat32Le(_ context.Context, offset uint32, v float32) bool { +func (m *MemoryInstance) WriteFloat32Le(offset uint32, v float32) bool { return m.writeUint32Le(offset, math.Float32bits(v)) } // WriteUint64Le implements the same method as documented on api.Memory. -func (m *MemoryInstance) WriteUint64Le(_ context.Context, offset uint32, v uint64) bool { +func (m *MemoryInstance) WriteUint64Le(offset uint32, v uint64) bool { return m.writeUint64Le(offset, v) } // WriteFloat64Le implements the same method as documented on api.Memory. -func (m *MemoryInstance) WriteFloat64Le(_ context.Context, offset uint32, v float64) bool { +func (m *MemoryInstance) WriteFloat64Le(offset uint32, v float64) bool { return m.writeUint64Le(offset, math.Float64bits(v)) } // Write implements the same method as documented on api.Memory. -func (m *MemoryInstance) Write(_ context.Context, offset uint32, val []byte) bool { +func (m *MemoryInstance) Write(offset uint32, val []byte) bool { if !m.hasSize(offset, uint32(len(val))) { return false } @@ -163,7 +162,7 @@ func (m *MemoryInstance) Write(_ context.Context, offset uint32, val []byte) boo } // WriteString implements the same method as documented on api.Memory. -func (m *MemoryInstance) WriteString(_ context.Context, offset uint32, val string) bool { +func (m *MemoryInstance) WriteString(offset uint32, val string) bool { if !m.hasSize(offset, uint32(len(val))) { return false } @@ -177,7 +176,7 @@ func MemoryPagesToBytesNum(pages uint32) (bytesNum uint64) { } // Grow implements the same method as documented on api.Memory. -func (m *MemoryInstance) Grow(_ context.Context, delta uint32) (result uint32, ok bool) { +func (m *MemoryInstance) Grow(delta uint32) (result uint32, ok bool) { // We take write-lock here as the following might result in a new slice m.mux.Lock() defer m.mux.Unlock() @@ -203,7 +202,7 @@ func (m *MemoryInstance) Grow(_ context.Context, delta uint32) (result uint32, o } // PageSize returns the current memory buffer size in pages. -func (m *MemoryInstance) PageSize(context.Context) (result uint32) { +func (m *MemoryInstance) PageSize() (result uint32) { return memoryBytesNumToPages(uint64(len(m.Buffer))) } diff --git a/internal/wasm/memory_test.go b/internal/wasm/memory_test.go index 7c1155ca..b564eab6 100644 --- a/internal/wasm/memory_test.go +++ b/internal/wasm/memory_test.go @@ -1,7 +1,6 @@ package wasm import ( - "context" "math" "strings" "testing" @@ -31,20 +30,16 @@ func TestMemoryBytesNumToPages(t *testing.T) { func TestMemoryInstance_Grow_Size(t *testing.T) { tests := []struct { name string - ctx context.Context capEqualsMax bool }{ - {name: "nil context"}, - {name: "context", ctx: testCtx}, - {name: "nil context, capEqualsMax", capEqualsMax: true}, - {name: "context, capEqualsMax", ctx: testCtx, capEqualsMax: true}, + {name: ""}, + {name: "capEqualsMax", capEqualsMax: true}, } for _, tt := range tests { tc := tt t.Run(tc.name, func(t *testing.T) { - ctx := tc.ctx max := uint32(10) maxBytes := MemoryPagesToBytesNum(max) var m *MemoryInstance @@ -54,35 +49,35 @@ func TestMemoryInstance_Grow_Size(t *testing.T) { m = &MemoryInstance{Max: max, Buffer: make([]byte, 0)} } - res, ok := m.Grow(ctx, 5) + res, ok := m.Grow(5) require.True(t, ok) require.Equal(t, uint32(0), res) - require.Equal(t, uint32(5), m.PageSize(ctx)) + require.Equal(t, uint32(5), m.PageSize()) // Zero page grow is well-defined, should return the current page correctly. - res, ok = m.Grow(ctx, 0) + res, ok = m.Grow(0) require.True(t, ok) require.Equal(t, uint32(5), res) - require.Equal(t, uint32(5), m.PageSize(ctx)) + require.Equal(t, uint32(5), m.PageSize()) - res, ok = m.Grow(ctx, 4) + res, ok = m.Grow(4) require.True(t, ok) require.Equal(t, uint32(5), res) - require.Equal(t, uint32(9), m.PageSize(ctx)) + require.Equal(t, uint32(9), m.PageSize()) // At this point, the page size equal 9, // so trying to grow two pages should result in failure. - _, ok = m.Grow(ctx, 2) + _, ok = m.Grow(2) require.False(t, ok) - require.Equal(t, uint32(9), m.PageSize(ctx)) + require.Equal(t, uint32(9), m.PageSize()) // But growing one page is still permitted. - res, ok = m.Grow(ctx, 1) + res, ok = m.Grow(1) require.True(t, ok) require.Equal(t, uint32(9), res) // Ensure that the current page size equals the max. - require.Equal(t, max, m.PageSize(ctx)) + require.Equal(t, max, m.PageSize()) if tc.capEqualsMax { // Ensure the capacity isn't more than max. require.Equal(t, maxBytes, uint64(cap(m.Buffer))) @@ -94,18 +89,16 @@ func TestMemoryInstance_Grow_Size(t *testing.T) { } func TestMemoryInstance_ReadByte(t *testing.T) { - for _, ctx := range []context.Context{nil, testCtx} { // Ensure it doesn't crash on nil! - mem := &MemoryInstance{Buffer: []byte{0, 0, 0, 0, 0, 0, 0, 16}, Min: 1} - v, ok := mem.ReadByte(ctx, 7) - require.True(t, ok) - require.Equal(t, byte(16), v) + mem := &MemoryInstance{Buffer: []byte{0, 0, 0, 0, 0, 0, 0, 16}, Min: 1} + v, ok := mem.ReadByte(7) + require.True(t, ok) + require.Equal(t, byte(16), v) - _, ok = mem.ReadByte(ctx, 8) - require.False(t, ok) + _, ok = mem.ReadByte(8) + require.False(t, ok) - _, ok = mem.ReadByte(ctx, 9) - require.False(t, ok) - } + _, ok = mem.ReadByte(9) + require.False(t, ok) } func TestPagesToUnitOfBytes(t *testing.T) { @@ -167,19 +160,19 @@ func TestMemoryInstance_HasSize(t *testing.T) { }, { name: "maximum valid sizeInBytes", - offset: memory.Size(testCtx) - 8, + offset: memory.Size() - 8, sizeInBytes: 8, expected: true, }, { name: "sizeInBytes exceeds the valid size by 1", offset: 100, // arbitrary valid offset - sizeInBytes: uint64(memory.Size(testCtx) - 99), + sizeInBytes: uint64(memory.Size() - 99), expected: false, }, { name: "offset exceeds the memory size", - offset: memory.Size(testCtx), + offset: memory.Size(), sizeInBytes: 1, // arbitrary size expected: false, }, @@ -246,13 +239,11 @@ func TestMemoryInstance_ReadUint16Le(t *testing.T) { tc := tt t.Run(tc.name, func(t *testing.T) { - for _, ctx := range []context.Context{nil, testCtx} { // Ensure it doesn't crash on nil! - memory := &MemoryInstance{Buffer: tc.memory} + memory := &MemoryInstance{Buffer: tc.memory} - v, ok := memory.ReadUint16Le(ctx, tc.offset) - require.Equal(t, tc.expectedOk, ok) - require.Equal(t, tc.expected, v) - } + v, ok := memory.ReadUint16Le(tc.offset) + require.Equal(t, tc.expectedOk, ok) + require.Equal(t, tc.expected, v) }) } } @@ -297,13 +288,11 @@ func TestMemoryInstance_ReadUint32Le(t *testing.T) { tc := tt t.Run(tc.name, func(t *testing.T) { - for _, ctx := range []context.Context{nil, testCtx} { // Ensure it doesn't crash on nil! - memory := &MemoryInstance{Buffer: tc.memory} + memory := &MemoryInstance{Buffer: tc.memory} - v, ok := memory.ReadUint32Le(ctx, tc.offset) - require.Equal(t, tc.expectedOk, ok) - require.Equal(t, tc.expected, v) - } + v, ok := memory.ReadUint32Le(tc.offset) + require.Equal(t, tc.expectedOk, ok) + require.Equal(t, tc.expected, v) }) } } @@ -348,13 +337,11 @@ func TestMemoryInstance_ReadUint64Le(t *testing.T) { tc := tt t.Run(tc.name, func(t *testing.T) { - for _, ctx := range []context.Context{nil, testCtx} { // Ensure it doesn't crash on nil! - memory := &MemoryInstance{Buffer: tc.memory} + memory := &MemoryInstance{Buffer: tc.memory} - v, ok := memory.ReadUint64Le(ctx, tc.offset) - require.Equal(t, tc.expectedOk, ok) - require.Equal(t, tc.expected, v) - } + v, ok := memory.ReadUint64Le(tc.offset) + require.Equal(t, tc.expectedOk, ok) + require.Equal(t, tc.expected, v) }) } } @@ -399,13 +386,11 @@ func TestMemoryInstance_ReadFloat32Le(t *testing.T) { tc := tt t.Run(tc.name, func(t *testing.T) { - for _, ctx := range []context.Context{nil, testCtx} { // Ensure it doesn't crash on nil! - memory := &MemoryInstance{Buffer: tc.memory} + memory := &MemoryInstance{Buffer: tc.memory} - v, ok := memory.ReadFloat32Le(ctx, tc.offset) - require.Equal(t, tc.expectedOk, ok) - require.Equal(t, tc.expected, v) - } + v, ok := memory.ReadFloat32Le(tc.offset) + require.Equal(t, tc.expectedOk, ok) + require.Equal(t, tc.expected, v) }) } } @@ -450,36 +435,32 @@ func TestMemoryInstance_ReadFloat64Le(t *testing.T) { tc := tt t.Run(tc.name, func(t *testing.T) { - for _, ctx := range []context.Context{nil, testCtx} { // Ensure it doesn't crash on nil! - memory := &MemoryInstance{Buffer: tc.memory} + memory := &MemoryInstance{Buffer: tc.memory} - v, ok := memory.ReadFloat64Le(ctx, tc.offset) - require.Equal(t, tc.expectedOk, ok) - require.Equal(t, tc.expected, v) - } + v, ok := memory.ReadFloat64Le(tc.offset) + require.Equal(t, tc.expectedOk, ok) + require.Equal(t, tc.expected, v) }) } } func TestMemoryInstance_Read(t *testing.T) { - for _, ctx := range []context.Context{nil, testCtx} { // Ensure it doesn't crash on nil! - mem := &MemoryInstance{Buffer: []byte{0, 0, 0, 0, 16, 0, 0, 0}, Min: 1} + mem := &MemoryInstance{Buffer: []byte{0, 0, 0, 0, 16, 0, 0, 0}, Min: 1} - buf, ok := mem.Read(ctx, 4, 4) - require.True(t, ok) - require.Equal(t, []byte{16, 0, 0, 0}, buf) + buf, ok := mem.Read(4, 4) + require.True(t, ok) + require.Equal(t, []byte{16, 0, 0, 0}, buf) - // Test write-through - buf[3] = 4 - require.Equal(t, []byte{16, 0, 0, 4}, buf) - require.Equal(t, []byte{0, 0, 0, 0, 16, 0, 0, 4}, mem.Buffer) + // Test write-through + buf[3] = 4 + require.Equal(t, []byte{16, 0, 0, 4}, buf) + require.Equal(t, []byte{0, 0, 0, 0, 16, 0, 0, 4}, mem.Buffer) - _, ok = mem.Read(ctx, 5, 4) - require.False(t, ok) + _, ok = mem.Read(5, 4) + require.False(t, ok) - _, ok = mem.Read(ctx, 9, 4) - require.False(t, ok) - } + _, ok = mem.Read(9, 4) + require.False(t, ok) } func TestMemoryInstance_WriteUint16Le(t *testing.T) { @@ -508,15 +489,15 @@ func TestMemoryInstance_WriteUint16Le(t *testing.T) { }, { name: "maximum boundary valid offset", - offset: memory.Size(testCtx) - 2, // 2 is the size of uint16 - v: 1, // arbitrary valid v + offset: memory.Size() - 2, // 2 is the size of uint16 + v: 1, // arbitrary valid v expectedOk: true, expectedBytes: []byte{0x1, 0x00}, }, { name: "offset exceeds the maximum valid offset by 1", - offset: memory.Size(testCtx) - 2 + 1, // 2 is the size of uint16 - v: 1, // arbitrary valid v + offset: memory.Size() - 2 + 1, // 2 is the size of uint16 + v: 1, // arbitrary valid v expectedBytes: []byte{0xff, 0xff}, }, } @@ -525,11 +506,9 @@ func TestMemoryInstance_WriteUint16Le(t *testing.T) { tc := tt t.Run(tc.name, func(t *testing.T) { - for _, ctx := range []context.Context{nil, testCtx} { // Ensure it doesn't crash on nil! - require.Equal(t, tc.expectedOk, memory.WriteUint16Le(ctx, tc.offset, tc.v)) - if tc.expectedOk { - require.Equal(t, tc.expectedBytes, memory.Buffer[tc.offset:tc.offset+2]) // 2 is the size of uint16 - } + require.Equal(t, tc.expectedOk, memory.WriteUint16Le(tc.offset, tc.v)) + if tc.expectedOk { + require.Equal(t, tc.expectedBytes, memory.Buffer[tc.offset:tc.offset+2]) // 2 is the size of uint16 } }) } @@ -561,15 +540,15 @@ func TestMemoryInstance_WriteUint32Le(t *testing.T) { }, { name: "maximum boundary valid offset", - offset: memory.Size(testCtx) - 4, // 4 is the size of uint32 - v: 1, // arbitrary valid v + offset: memory.Size() - 4, // 4 is the size of uint32 + v: 1, // arbitrary valid v expectedOk: true, expectedBytes: []byte{0x1, 0x00, 0x00, 0x00}, }, { name: "offset exceeds the maximum valid offset by 1", - offset: memory.Size(testCtx) - 4 + 1, // 4 is the size of uint32 - v: 1, // arbitrary valid v + offset: memory.Size() - 4 + 1, // 4 is the size of uint32 + v: 1, // arbitrary valid v expectedBytes: []byte{0xff, 0xff, 0xff, 0xff}, }, } @@ -578,11 +557,9 @@ func TestMemoryInstance_WriteUint32Le(t *testing.T) { tc := tt t.Run(tc.name, func(t *testing.T) { - for _, ctx := range []context.Context{nil, testCtx} { // Ensure it doesn't crash on nil! - require.Equal(t, tc.expectedOk, memory.WriteUint32Le(ctx, tc.offset, tc.v)) - if tc.expectedOk { - require.Equal(t, tc.expectedBytes, memory.Buffer[tc.offset:tc.offset+4]) // 4 is the size of uint32 - } + require.Equal(t, tc.expectedOk, memory.WriteUint32Le(tc.offset, tc.v)) + if tc.expectedOk { + require.Equal(t, tc.expectedBytes, memory.Buffer[tc.offset:tc.offset+4]) // 4 is the size of uint32 } }) } @@ -613,15 +590,15 @@ func TestMemoryInstance_WriteUint64Le(t *testing.T) { }, { name: "maximum boundary valid offset", - offset: memory.Size(testCtx) - 8, // 8 is the size of uint64 - v: 1, // arbitrary valid v + offset: memory.Size() - 8, // 8 is the size of uint64 + v: 1, // arbitrary valid v expectedOk: true, expectedBytes: []byte{0x1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, }, { name: "offset exceeds the maximum valid offset by 1", - offset: memory.Size(testCtx) - 8 + 1, // 8 is the size of uint64 - v: 1, // arbitrary valid v + offset: memory.Size() - 8 + 1, // 8 is the size of uint64 + v: 1, // arbitrary valid v expectedOk: false, }, } @@ -630,11 +607,9 @@ func TestMemoryInstance_WriteUint64Le(t *testing.T) { tc := tt t.Run(tc.name, func(t *testing.T) { - for _, ctx := range []context.Context{nil, testCtx} { // Ensure it doesn't crash on nil! - require.Equal(t, tc.expectedOk, memory.WriteUint64Le(ctx, tc.offset, tc.v)) - if tc.expectedOk { - require.Equal(t, tc.expectedBytes, memory.Buffer[tc.offset:tc.offset+8]) // 8 is the size of uint64 - } + require.Equal(t, tc.expectedOk, memory.WriteUint64Le(tc.offset, tc.v)) + if tc.expectedOk { + require.Equal(t, tc.expectedBytes, memory.Buffer[tc.offset:tc.offset+8]) // 8 is the size of uint64 } }) } @@ -666,15 +641,15 @@ func TestMemoryInstance_WriteFloat32Le(t *testing.T) { }, { name: "maximum boundary valid offset", - offset: memory.Size(testCtx) - 4, // 4 is the size of float32 - v: 0.1, // arbitrary valid v + offset: memory.Size() - 4, // 4 is the size of float32 + v: 0.1, // arbitrary valid v expectedOk: true, expectedBytes: []byte{0xcd, 0xcc, 0xcc, 0x3d}, }, { name: "offset exceeds the maximum valid offset by 1", - offset: memory.Size(testCtx) - 4 + 1, // 4 is the size of float32 - v: math.MaxFloat32, // arbitrary valid v + offset: memory.Size() - 4 + 1, // 4 is the size of float32 + v: math.MaxFloat32, // arbitrary valid v expectedBytes: []byte{0xff, 0xff, 0xff, 0xff}, }, } @@ -683,11 +658,9 @@ func TestMemoryInstance_WriteFloat32Le(t *testing.T) { tc := tt t.Run(tc.name, func(t *testing.T) { - for _, ctx := range []context.Context{nil, testCtx} { // Ensure it doesn't crash on nil! - require.Equal(t, tc.expectedOk, memory.WriteFloat32Le(ctx, tc.offset, tc.v)) - if tc.expectedOk { - require.Equal(t, tc.expectedBytes, memory.Buffer[tc.offset:tc.offset+4]) // 4 is the size of float32 - } + require.Equal(t, tc.expectedOk, memory.WriteFloat32Le(tc.offset, tc.v)) + if tc.expectedOk { + require.Equal(t, tc.expectedBytes, memory.Buffer[tc.offset:tc.offset+4]) // 4 is the size of float32 } }) } @@ -718,15 +691,15 @@ func TestMemoryInstance_WriteFloat64Le(t *testing.T) { }, { name: "maximum boundary valid offset", - offset: memory.Size(testCtx) - 8, // 8 is the size of float64 - v: math.MaxFloat64, // arbitrary valid v + offset: memory.Size() - 8, // 8 is the size of float64 + v: math.MaxFloat64, // arbitrary valid v expectedOk: true, expectedBytes: []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0x7f}, }, { name: "offset exceeds the maximum valid offset by 1", - offset: memory.Size(testCtx) - 8 + 1, // 8 is the size of float64 - v: math.MaxFloat64, // arbitrary valid v + offset: memory.Size() - 8 + 1, // 8 is the size of float64 + v: math.MaxFloat64, // arbitrary valid v expectedOk: false, }, } @@ -735,51 +708,45 @@ func TestMemoryInstance_WriteFloat64Le(t *testing.T) { tc := tt t.Run(tc.name, func(t *testing.T) { - for _, ctx := range []context.Context{nil, testCtx} { // Ensure it doesn't crash on nil! - require.Equal(t, tc.expectedOk, memory.WriteFloat64Le(ctx, tc.offset, tc.v)) - if tc.expectedOk { - require.Equal(t, tc.expectedBytes, memory.Buffer[tc.offset:tc.offset+8]) // 8 is the size of float64 - } + require.Equal(t, tc.expectedOk, memory.WriteFloat64Le(tc.offset, tc.v)) + if tc.expectedOk { + require.Equal(t, tc.expectedBytes, memory.Buffer[tc.offset:tc.offset+8]) // 8 is the size of float64 } }) } } func TestMemoryInstance_Write(t *testing.T) { - for _, ctx := range []context.Context{nil, testCtx} { // Ensure it doesn't crash on nil! - mem := &MemoryInstance{Buffer: []byte{0, 0, 0, 0, 16, 0, 0, 0}, Min: 1} + mem := &MemoryInstance{Buffer: []byte{0, 0, 0, 0, 16, 0, 0, 0}, Min: 1} - buf := []byte{16, 0, 0, 4} - require.True(t, mem.Write(ctx, 4, buf)) - require.Equal(t, []byte{0, 0, 0, 0, 16, 0, 0, 4}, mem.Buffer) + buf := []byte{16, 0, 0, 4} + require.True(t, mem.Write(4, buf)) + require.Equal(t, []byte{0, 0, 0, 0, 16, 0, 0, 4}, mem.Buffer) - // Test it isn't write-through - buf[3] = 0 - require.Equal(t, []byte{16, 0, 0, 0}, buf) - require.Equal(t, []byte{0, 0, 0, 0, 16, 0, 0, 4}, mem.Buffer) + // Test it isn't write-through + buf[3] = 0 + require.Equal(t, []byte{16, 0, 0, 0}, buf) + require.Equal(t, []byte{0, 0, 0, 0, 16, 0, 0, 4}, mem.Buffer) - ok := mem.Write(ctx, 5, buf) - require.False(t, ok) + ok := mem.Write(5, buf) + require.False(t, ok) - ok = mem.Write(ctx, 9, buf) - require.False(t, ok) - } + ok = mem.Write(9, buf) + require.False(t, ok) } func TestMemoryInstance_WriteString(t *testing.T) { - for _, ctx := range []context.Context{nil, testCtx} { // Ensure it doesn't crash on nil! - mem := &MemoryInstance{Buffer: []byte{0, 0, 0, 0, 16, 0, 0, 0}, Min: 1} + mem := &MemoryInstance{Buffer: []byte{0, 0, 0, 0, 16, 0, 0, 0}, Min: 1} - s := "bear" - require.True(t, mem.WriteString(ctx, 4, s)) - require.Equal(t, []byte{0, 0, 0, 0, 'b', 'e', 'a', 'r'}, mem.Buffer) + s := "bear" + require.True(t, mem.WriteString(4, s)) + require.Equal(t, []byte{0, 0, 0, 0, 'b', 'e', 'a', 'r'}, mem.Buffer) - ok := mem.WriteString(ctx, 5, s) - require.False(t, ok) + ok := mem.WriteString(5, s) + require.False(t, ok) - ok = mem.WriteString(ctx, 9, s) - require.False(t, ok) - } + ok = mem.WriteString(9, s) + require.False(t, ok) } func BenchmarkWriteString(b *testing.B) { @@ -796,14 +763,14 @@ func BenchmarkWriteString(b *testing.B) { b.Run("", func(b *testing.B) { b.Run("Write", func(b *testing.B) { for i := 0; i < b.N; i++ { - if !mem.Write(testCtx, 0, []byte(tt)) { + if !mem.Write(0, []byte(tt)) { b.Fail() } } }) b.Run("WriteString", func(b *testing.B) { for i := 0; i < b.N; i++ { - if !mem.WriteString(testCtx, 0, tt) { + if !mem.WriteString(0, tt) { b.Fail() } } diff --git a/internal/wasm/store_test.go b/internal/wasm/store_test.go index aedef24d..1b86e94c 100644 --- a/internal/wasm/store_test.go +++ b/internal/wasm/store_test.go @@ -82,7 +82,7 @@ func TestModuleInstance_Memory(t *testing.T) { mem := instance.ExportedMemory("memory") if tc.expected { - require.Equal(t, tc.expectedLen, mem.Size(testCtx)) + require.Equal(t, tc.expectedLen, mem.Size()) } else { require.Nil(t, mem) } diff --git a/internal/wasm/table.go b/internal/wasm/table.go index 587f7ab8..c5210707 100644 --- a/internal/wasm/table.go +++ b/internal/wasm/table.go @@ -1,7 +1,6 @@ package wasm import ( - "context" "fmt" "math" "sync" @@ -340,7 +339,7 @@ func (m *Module) verifyImportGlobalI32(sectionID SectionID, sectionIdx Index, id // Returns -1 if the operation is not valid, otherwise the old length of the table. // // https://www.w3.org/TR/2022/WD-wasm-core-2-20220419/exec/instructions.html#xref-syntax-instructions-syntax-instr-table-mathsf-table-grow-x -func (t *TableInstance) Grow(_ context.Context, delta uint32, initialRef Reference) (currentLen uint32) { +func (t *TableInstance) Grow(delta uint32, initialRef Reference) (currentLen uint32) { // We take write-lock here as the following might result in a new slice t.mux.Lock() defer t.mux.Unlock() diff --git a/internal/wasm/table_test.go b/internal/wasm/table_test.go index 20b68299..828f8b12 100644 --- a/internal/wasm/table_test.go +++ b/internal/wasm/table_test.go @@ -1080,7 +1080,7 @@ func TestTableInstance_Grow(t *testing.T) { tc := tt t.Run(tc.name, func(t *testing.T) { table := &TableInstance{References: make([]uintptr, tc.currentLen), Max: tc.max} - actual := table.Grow(testCtx, tc.delta, 0) + actual := table.Grow(tc.delta, 0) require.Equal(t, tc.exp, actual) }) } diff --git a/runtime_test.go b/runtime_test.go index bea08e80..310cfc1c 100644 --- a/runtime_test.go +++ b/runtime_test.go @@ -224,7 +224,7 @@ func TestModule_Memory(t *testing.T) { mem := module.ExportedMemory("memory") if tc.expected { - require.Equal(t, tc.expectedLen, mem.Size(testCtx)) + require.Equal(t, tc.expectedLen, mem.Size()) } else { require.Nil(t, mem) } @@ -310,13 +310,13 @@ func TestModule_Global(t *testing.T) { require.Nil(t, global) return } - require.Equal(t, uint64(globalVal), global.Get(testCtx)) + require.Equal(t, uint64(globalVal), global.Get()) mutable, ok := global.(api.MutableGlobal) require.Equal(t, tc.expectedMutable, ok) if ok { - mutable.Set(testCtx, 2) - require.Equal(t, uint64(2), global.Get(testCtx)) + mutable.Set(2) + require.Equal(t, uint64(2), global.Get()) } }) } diff --git a/sys/clock.go b/sys/clock.go index be60859a..74507df1 100644 --- a/sys/clock.go +++ b/sys/clock.go @@ -1,7 +1,5 @@ package sys -import "context" - // ClockResolution is a positive granularity of clock precision in // nanoseconds. For example, if the resolution is 1us, this returns 1000. // @@ -11,14 +9,14 @@ import "context" type ClockResolution uint32 // Walltime returns the current time in epoch seconds with a nanosecond fraction. -type Walltime func(context.Context) (sec int64, nsec int32) +type Walltime func() (sec int64, nsec int32) // Nanotime returns nanoseconds since an arbitrary start point, used to measure // elapsed time. This is sometimes referred to as a tick or monotonic time. // // Note: There are no constraints on the value return except that it // increments. For example, -1 is a valid if the next value is >= 0. -type Nanotime func(context.Context) int64 +type Nanotime func() int64 // Nanosleep puts the current goroutine to sleep for at least ns nanoseconds. -type Nanosleep func(ctx context.Context, ns int64) +type Nanosleep func(ns int64)