Disallows nil context and fixes linters (#754)

staticcheck linters broke until recent golangci-lint. Now, normal
behaviour of enforcing no nil context works again. Ex.
```
assemblyscript/assemblyscript_example_test.go:16:25: SA1012: do not pass a nil Context, even if a function permits it; pass context.TODO if you are unsure about which Context to use (staticcheck)
	r := wazero.NewRuntime(nil)
```

Since default lint already checks for nil context, this removes our
permission of nil context args. The original reason we permitted nil is
no longer valid: we once allowed context to be stashed in config, and
removed that as it caused bugs. We forgot to undo allowing nil
explicitly.

Note: this doesn't particularly check in our code for nil context,
similar as we don't particularly check in our code for nil anything
else. End users should use linters as none of our parameters should be
nil anyway.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
This commit is contained in:
Crypt Keeper
2022-08-19 14:52:50 +08:00
committed by GitHub
parent 5b2c25cfed
commit 57a705e594
19 changed files with 22 additions and 121 deletions

View File

@@ -43,7 +43,7 @@ jobs:
- name: Install TinyGo
run: | # installing via curl so commands are similar on OS/x
tinygo_version=0.24.0
tinygo_version=0.25.0
curl -sSL https://github.com/tinygo-org/tinygo/releases/download/v${tinygo_version}/tinygo${tinygo_version}.linux-amd64.tar.gz | sudo tar -C /usr/local -xzf -
echo "TINYGOROOT=/usr/local/tinygo" >> $GITHUB_ENV
echo "/usr/local/tinygo/bin" >> $GITHUB_PATH

View File

@@ -4,10 +4,10 @@ comma := ,
space :=
space +=
goimports := golang.org/x/tools/cmd/goimports@v0.1.10
golangci_lint := github.com/golangci/golangci-lint/cmd/golangci-lint@v1.46.2
goimports := golang.org/x/tools/cmd/goimports@v0.1.12
golangci_lint := github.com/golangci/golangci-lint/cmd/golangci-lint@v1.48.0
# sync this with netlify.toml!
hugo := github.com/gohugoio/hugo@v0.100.0
hugo := github.com/gohugoio/hugo@v0.101.0
# Make 3.81 doesn't support '**' globbing: Set explicitly instead of recursion.
all_sources := $(wildcard *.go */*.go */*/*.go */*/*/*.go */*/*/*.go */*/*/*/*.go)

View File

@@ -157,7 +157,7 @@ type Module interface {
ExportedGlobal(name string) Global
// CloseWithExitCode releases resources allocated for this Module. Use a non-zero exitCode parameter to indicate a
// failure to ExportedFunction callers. When the context is nil, it defaults to context.Background.
// failure to ExportedFunction callers.
//
// The error returned here, if present, is about resource de-allocation (such as I/O errors). Only the last error is
// returned, so a non-nil return means at least one error happened. Regardless of error, this module instance will
@@ -175,7 +175,7 @@ type Module interface {
//
// Note: This is an interface for decoupling, not third-party implementations. All implementations are in wazero.
type Closer interface {
// Close closes the resource. When the context is nil, it defaults to context.Background.
// Close closes the resource.
Close(context.Context) error
}
@@ -267,7 +267,7 @@ type Function interface {
// Call invokes the function with parameters encoded according to ParamTypes. Up to one result is returned,
// encoded according to ResultTypes. An error is returned for any failure looking up or invoking the function
// including signature mismatch. When the context is nil, it defaults to context.Background.
// including signature mismatch.
//
// If Module.Close or Module.CloseWithExitCode were invoked during this call, the error returned may be a
// sys.ExitError. Interpreting this is specific to the module. For example, some "main" functions always call a
@@ -298,7 +298,7 @@ type Global interface {
// Type describes the numeric type of the global.
Type() ValueType
// Get returns the last known value of this global. When the context is nil, it defaults to context.Background.
// 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
@@ -308,7 +308,7 @@ type Global interface {
type MutableGlobal interface {
Global
// Set updates the value of this global. When the context is nil, it defaults to context.Background.
// 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)
@@ -318,7 +318,6 @@ type MutableGlobal interface {
//
// # Notes
//
// - All functions accept a context.Context, which when nil, default to context.Background.
// - This is an interface for decoupling, not third-party implementations. All implementations are in wazero.
// - This includes all value types available in WebAssembly 1.0 (20191205) and all are encoded little-endian.
//

View File

@@ -309,8 +309,6 @@ func (c *compiledModule) Name() (moduleName string) {
// Close implements CompiledModule.Close
func (c *compiledModule) Close(_ context.Context) error {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
c.compiledEngine.DeleteCompiledModule(c.module)
// It is possible the underlying may need to return an error later, but in any case this matches api.Module.Close.
return nil

Binary file not shown.

View File

@@ -76,8 +76,7 @@ func main() {
// Call goodbye_world, which aborts with an error.
// assemblyscript.Instantiate was configured above to abort to stderr.
results, err = goodbyeWorld.Call(ctx)
if err == nil {
if _, err = goodbyeWorld.Call(ctx); err == nil {
log.Panicln("goodbye_world did not fail")
}
}

View File

@@ -3,7 +3,6 @@ package main
import (
"context"
"embed"
_ "embed"
"fmt"
"io/fs"
"log"

Binary file not shown.

View File

@@ -96,8 +96,7 @@ type (
moduleContext struct {
// moduleInstanceAddress is the address of module instance from which we initialize
// the following fields. This is set whenever we enter a function or return from function calls.
// This is only used by Compiler code so mark this as nolint.
moduleInstanceAddress uintptr //nolint
moduleInstanceAddress uintptr //lint:ignore U1000 This is only used by Compiler code.
// globalElement0Address is the address of the first element in the global slice,
// i.e. &ModuleInstance.Globals[0] as uintptr.

View File

@@ -3,7 +3,6 @@ package fuzzcases
import (
"context"
"embed"
_ "embed"
"fmt"
"testing"

View File

@@ -109,8 +109,6 @@ func (m *CallContext) CloseWithExitCode(ctx context.Context, exitCode uint32) er
//
// Note: The caller is responsible for removing the module from the Namespace.
func (m *CallContext) close(ctx context.Context, exitCode uint32) (c bool, err error) {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
closed := uint64(1) + uint64(exitCode)<<32 // Store exitCode as high-order bits.
if !atomic.CompareAndSwapUint64(m.closed, 0, closed) {
return false, nil
@@ -165,9 +163,6 @@ func (f *importedFn) Call(ctx context.Context, params ...uint64) (ret []uint64,
if f.importedFn.IsHostFunction {
return nil, fmt.Errorf("directly calling host function is not supported")
}
if ctx == nil {
ctx = context.Background()
}
mod := f.importingModule
return f.importedFn.Module.Engine.Call(ctx, mod, f.importedFn, params...)
}
@@ -177,9 +172,6 @@ func (f *FunctionInstance) Call(ctx context.Context, params ...uint64) (ret []ui
if f.IsHostFunction {
return nil, fmt.Errorf("directly calling host function is not supported")
}
if ctx == nil {
ctx = context.Background()
}
mod := f.Module
ret, err = mod.Engine.Call(ctx, mod.CallCtx, f, params...)
return

View File

@@ -21,15 +21,11 @@ func (g *mutableGlobal) Type() api.ValueType {
// Get implements the same method as documented on api.Global.
func (g *mutableGlobal) Get(_ context.Context) uint64 {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
return g.g.Val
}
// Set implements the same method as documented on api.MutableGlobal.
func (g *mutableGlobal) Set(_ context.Context, v uint64) {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
g.g.Val = v
}
@@ -59,8 +55,6 @@ func (g globalI32) Type() api.ValueType {
// Get implements the same method as documented on api.Global.
func (g globalI32) Get(_ context.Context) uint64 {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
return uint64(g)
}
@@ -81,8 +75,6 @@ func (g globalI64) Type() api.ValueType {
// Get implements the same method as documented on api.Global.
func (g globalI64) Get(_ context.Context) uint64 {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
return uint64(g)
}
@@ -103,8 +95,6 @@ func (g globalF32) Type() api.ValueType {
// Get implements the same method as documented on api.Global.
func (g globalF32) Get(_ context.Context) uint64 {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
return uint64(g)
}
@@ -125,8 +115,6 @@ func (g globalF64) Type() api.ValueType {
// Get implements the same method as documented on api.Global.
func (g globalF64) Get(_ context.Context) uint64 {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
return uint64(g)
}

View File

@@ -62,15 +62,11 @@ func NewMemoryInstance(memSec *Memory) *MemoryInstance {
// Size implements the same method as documented on api.Memory.
func (m *MemoryInstance) Size(_ context.Context) uint32 {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
return m.size()
}
// ReadByte implements the same method as documented on api.Memory.
func (m *MemoryInstance) ReadByte(_ context.Context, offset uint32) (byte, bool) {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
if offset >= m.size() {
return 0, false
}
@@ -79,8 +75,6 @@ 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) {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
if !m.hasSize(offset, 2) {
return 0, false
}
@@ -89,15 +83,11 @@ 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) {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
return m.readUint32Le(offset)
}
// ReadFloat32Le implements the same method as documented on api.Memory.
func (m *MemoryInstance) ReadFloat32Le(_ context.Context, offset uint32) (float32, bool) {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
v, ok := m.readUint32Le(offset)
if !ok {
return 0, false
@@ -107,15 +97,11 @@ 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) {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
return m.readUint64Le(offset)
}
// ReadFloat64Le implements the same method as documented on api.Memory.
func (m *MemoryInstance) ReadFloat64Le(_ context.Context, offset uint32) (float64, bool) {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
v, ok := m.readUint64Le(offset)
if !ok {
return 0, false
@@ -125,8 +111,6 @@ 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) {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
if !m.hasSize(offset, byteCount) {
return nil, false
}
@@ -135,8 +119,6 @@ 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 {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
if offset >= m.size() {
return false
}
@@ -146,8 +128,6 @@ 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 {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
if !m.hasSize(offset, 2) {
return false
}
@@ -157,36 +137,26 @@ 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 {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
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 {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
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 {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
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 {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
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 {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
if !m.hasSize(offset, uint32(len(val))) {
return false
}
@@ -201,8 +171,6 @@ 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) {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
// We take write-lock here as the following might result in a new slice
m.mux.Lock()
defer m.mux.Unlock()
@@ -229,8 +197,6 @@ 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) {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
return memoryBytesNumToPages(uint64(len(m.Buffer)))
}

View File

@@ -286,8 +286,6 @@ func NewStore(enabledFeatures Features, engine Engine) (*Store, *Namespace) {
// NewNamespace implements the same method as documented on wazero.Runtime.
func (s *Store) NewNamespace(_ context.Context) *Namespace {
// TODO: The above context isn't yet used. If it is, ensure it defaults to context.Background.
ns := newNamespace()
s.mux.Lock()
defer s.mux.Unlock()
@@ -311,10 +309,6 @@ func (s *Store) Instantiate(
sys *internalsys.Context,
listeners []experimentalapi.FunctionListener,
) (*CallContext, error) {
if ctx == nil {
ctx = context.Background()
}
// Collect any imported modules to avoid locking the namespace too long.
importedModuleNames := map[string]struct{}{}
for _, i := range module.ImportSection {

View File

@@ -158,8 +158,7 @@ type compiler struct {
globals []*wasm.GlobalType
}
// For debugging only.
// nolint
//lint:ignore U1000 for debugging only.
func (c *compiler) stackDump() string {
strs := make([]string, 0, len(c.stack))
for _, s := range c.stack {
@@ -225,8 +224,6 @@ type CompilationResult struct {
}
func CompileFunctions(_ context.Context, enabledFeatures wasm.Features, module *wasm.Module) ([]*CompilationResult, error) {
// Note: If you use the context.Context param, don't forget to coerce nil to context.Background()!
functions, globals, mem, tables, err := module.AllDeclarations()
if err != nil {
return nil, err

View File

@@ -16,7 +16,6 @@ type Namespace interface {
Module(moduleName string) api.Module
// InstantiateModule instantiates the module namespace or errs if the configuration was invalid.
// When the context is nil, it defaults to context.Background.
//
// Ex.
// module, _ := n.InstantiateModule(ctx, compiled, wazero.NewModuleConfig().WithName("prod"))

View File

@@ -3,7 +3,7 @@
publish = "public"
[build.environment]
HUGO_VERSION = "0.100.0"
HUGO_VERSION = "0.101.0"
[context.production]
command = "git submodule update --init && hugo --gc --minify"

View File

@@ -49,7 +49,6 @@ type Runtime interface {
CompileModule(ctx context.Context, binary []byte, config CompileConfig) (CompiledModule, error)
// InstantiateModuleFromBinary instantiates a module from the WebAssembly binary (%.wasm) or errs if invalid.
// When the context is nil, it defaults to context.Background.
//
// Ex.
// ctx := context.Background()
@@ -74,7 +73,6 @@ type Runtime interface {
// NewNamespace creates an empty namespace which won't conflict with any other namespace including the default.
// This is more efficient than multiple runtimes, as namespaces share a compiler cache.
// When the context is nil, it defaults to context.Background.
//
// In simplest case, a namespace won't conflict if another has a module with the same name:
// b := assemblyscript.NewBuilder(r)
@@ -103,7 +101,6 @@ type Runtime interface {
NewNamespace(context.Context) Namespace
// CloseWithExitCode closes all the modules that have been initialized in this Runtime with the provided exit code.
// When the context is nil, it defaults to context.Background.
// An error is returned if any module returns an error when closed.
//
// Ex.
@@ -127,9 +124,6 @@ func NewRuntime(ctx context.Context) Runtime {
// NewRuntimeWithConfig returns a runtime with the given configuration.
func NewRuntimeWithConfig(ctx context.Context, rConfig RuntimeConfig) Runtime {
if ctx == nil {
ctx = context.Background()
}
if v := ctx.Value(version.WazeroVersionKey{}); v == nil {
ctx = context.WithValue(ctx, version.WazeroVersionKey{}, wazeroVersion)
}
@@ -202,9 +196,6 @@ func (r *runtime) CompileModule(ctx context.Context, binary []byte, cConfig Comp
}
func buildListeners(ctx context.Context, r *runtime, internal *wasm.Module) ([]experimentalapi.FunctionListener, error) {
if ctx == nil {
return nil, nil
}
// Test to see if internal code are using an experimental feature.
fnlf := ctx.Value(experimentalapi.FunctionListenerFactoryKey{})
if fnlf == nil {

View File

@@ -22,35 +22,16 @@ var (
)
func TestNewRuntimeWithConfig_version(t *testing.T) {
// Make sure nil ctx doesn't panic
tests := []struct {
name string
ctx context.Context
}{
{
name: "not nil",
ctx: testCtx,
},
{
name: "nil",
ctx: nil,
},
}
for _, tc := range tests {
tt := tc
t.Run(tt.name, func(t *testing.T) {
cfg := NewRuntimeConfig().(*runtimeConfig)
oldNewEngine := cfg.newEngine
cfg.newEngine = func(ctx context.Context, features wasm.Features) wasm.Engine {
// Ensures that wazeroVersion is propagated to the engine.
v := ctx.Value(version.WazeroVersionKey{})
require.NotNil(t, v)
require.Equal(t, wazeroVersion, v.(string))
return oldNewEngine(ctx, features)
}
_ = NewRuntimeWithConfig(tt.ctx, cfg)
})
cfg := NewRuntimeConfig().(*runtimeConfig)
oldNewEngine := cfg.newEngine
cfg.newEngine = func(ctx context.Context, features wasm.Features) wasm.Engine {
// Ensures that wazeroVersion is propagated to the engine.
v := ctx.Value(version.WazeroVersionKey{})
require.NotNil(t, v)
require.Equal(t, wazeroVersion, v.(string))
return oldNewEngine(ctx, features)
}
_ = NewRuntimeWithConfig(testCtx, cfg)
}
func TestRuntime_CompileModule(t *testing.T) {