diff --git a/api/wasm.go b/api/wasm.go index 8c101e7d..5768c12c 100644 --- a/api/wasm.go +++ b/api/wasm.go @@ -9,8 +9,6 @@ import ( // ExternType classifies imports and exports with their respective types. // -// See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#import-section%E2%91%A0 -// See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#export-section%E2%91%A0 // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#external-types%E2%91%A0 type ExternType = byte @@ -35,7 +33,6 @@ const ( // ExternTypeName returns the name of the WebAssembly 1.0 (20191205) Text Format field of the given type. // -// See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#imports⑤ // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#exports%E2%91%A4 func ExternTypeName(et ExternType) string { switch et { @@ -55,11 +52,12 @@ func ExternTypeName(et ExternType) string { // only definable as a value type. // // The following describes how to convert between Wasm and Golang types: -// * ValueTypeI32 - uint64(uint32,int32) -// * ValueTypeI64 - uint64(int64) -// * ValueTypeF32 - EncodeF32 DecodeF32 from float32 -// * ValueTypeF64 - EncodeF64 DecodeF64 from float64 -// * ValueTypeExternref - unintptr(unsafe.Pointer(p)) where p is any pointer type in Go (e.g. *string) +// +// * ValueTypeI32 - uint64(uint32,int32) +// * ValueTypeI64 - uint64(int64) +// * ValueTypeF32 - EncodeF32 DecodeF32 from float32 +// * ValueTypeF64 - EncodeF64 DecodeF64 from float64 +// * ValueTypeExternref - unintptr(unsafe.Pointer(p)) where p is any pointer type in Go (e.g. *string) // // Ex. Given a Text Format type use (param i64) (result i64), no conversion is necessary. // @@ -72,6 +70,7 @@ func ExternTypeName(et ExternType) string { // result := api.DecodeF64(result[0]) // // Note: This is a type alias as it is easier to encode and decode in the binary format. +// // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#binary-valtype type ValueType = byte @@ -120,8 +119,11 @@ func ValueTypeName(t ValueType) string { // Module return functions exported in a module, post-instantiation. // -// Note: Closing the wazero.Runtime closes any Module it instantiated. -// Note: This is an interface for decoupling, not third-party implementations. All implementations are in wazero. +// Notes +// +// * Closing the wazero.Runtime closes any Module it instantiated. +// * This is an interface for decoupling, not third-party implementations. All implementations are in wazero. +// // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#external-types%E2%91%A0 type Module interface { fmt.Stringer @@ -139,8 +141,9 @@ type Module interface { // ExportedMemory returns a memory exported from this module or nil if it wasn't. // - // Note: WASI modules require exporting a Memory named "memory". This means that a module successfully initialized + // WASI modules require exporting a Memory named "memory". This means that a module successfully initialized // as a WASI Command or Reactor will never return nil for this name. + // // See https://github.com/WebAssembly/WASI/blob/snapshot-01/design/application-abi.md#current-unstable-abi ExportedMemory(name string) Memory @@ -148,7 +151,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. + // failure to ExportedFunction callers. When the context is nil, it defaults to context.Background. // // 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 @@ -156,7 +159,6 @@ type Module interface { // // Calling this inside a host function is safe, and may cause ExportedFunction callers to receive a sys.ExitError // with the exitCode. - // Note: When the context is nil, it defaults to context.Background. CloseWithExitCode(ctx context.Context, exitCode uint32) error // Closer closes this module by delegating to CloseWithExitCode with an exit code of zero. @@ -167,31 +169,31 @@ 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. - // Note: When the context is nil, it defaults to context.Background. + // Close closes the resource. When the context is nil, it defaults to context.Background. Close(context.Context) error } // Function is a WebAssembly 1.0 (20191205) function exported from an instantiated module (wazero.Runtime InstantiateModule). +// // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#syntax-func type Function interface { // ParamTypes are the possibly empty sequence of value types accepted by a function with this signature. + // // See ValueType documentation for encoding rules. ParamTypes() []ValueType // ResultTypes are the possibly empty sequence of value types returned by a function with this signature. // - // Note: In WebAssembly 1.0 (20191205), there can be at most one result. - // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#result-types%E2%91%A0 + // When WebAssembly 1.0 (20191205), there can be at most one result: https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#result-types%E2%91%A0 + // // See ValueType documentation for decoding rules. ResultTypes() []ValueType // 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. + // including signature mismatch. When the context is nil, it defaults to context.Background. // - // Note: When the context is nil, it defaults to context.Background. - // Note: If Module.Close or Module.CloseWithExitCode were invoked during this call, the error returned may be a + // 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 // function that exits. Call(ctx context.Context, params ...uint64) ([]uint64, error) @@ -220,10 +222,9 @@ type Global interface { // Type describes the numeric type of the global. Type() ValueType - // Get returns the last known value of this global. - // See Type for how to encode this value from a Go type. + // Get returns the last known value of this global. When the context is nil, it defaults to context.Background. // - // Note: When the context is nil, it defaults to context.Background. + // See Type for how to encode this value from a Go type. Get(context.Context) uint64 } @@ -231,18 +232,20 @@ type Global interface { type MutableGlobal interface { Global - // Set updates the value of this global. - // See Global.Type for how to decode this value to a Go type. + // Set updates the value of this global. When the context is nil, it defaults to context.Background. // - // Note: When the context is nil, it defaults to context.Background. + // See Global.Type for how to decode this value to a Go type. Set(ctx context.Context, v uint64) } // Memory allows restricted access to a module's memory. Notably, this does not allow growing. // -// Note: All functions accept a context.Context, which when nil, default to context.Background. -// Note: This is an interface for decoupling, not third-party implementations. All implementations are in wazero. -// Note: This includes all value types available in WebAssembly 1.0 (20191205) and all are encoded little-endian. +// 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. +// // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#storage%E2%91%A0 type Memory interface { @@ -256,8 +259,8 @@ type Memory interface { // // Note: This is the same as the "memory.grow" instruction defined in the WebAssembly Core Specification, except // returns false instead of -1 on failure - // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#grow-mem - // See MemorySizer + // + // See MemorySizer and https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#grow-mem Grow(ctx context.Context, deltaPages uint32) (previousPages uint32, ok bool) // IndexByte returns the index of the first instance of c in the underlying buffer at the offset or returns false if @@ -286,6 +289,7 @@ type Memory interface { // 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) @@ -319,6 +323,7 @@ type Memory interface { // 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 @@ -328,6 +333,7 @@ type Memory interface { // 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 @@ -336,12 +342,14 @@ type Memory interface { } // EncodeExternref encodes the input as a ValueTypeExternref. +// // See DecodeExternref func EncodeExternref(input uintptr) uint64 { return uint64(input) } // DecodeExternref decodes the input as a ValueTypeExternref. +// // See EncodeExternref func DecodeExternref(input uint64) uintptr { return uintptr(input) @@ -358,24 +366,28 @@ func EncodeI64(input int64) uint64 { } // EncodeF32 encodes the input as a ValueTypeF32. +// // See DecodeF32 func EncodeF32(input float32) uint64 { return uint64(math.Float32bits(input)) } // DecodeF32 decodes the input as a ValueTypeF32. +// // See EncodeF32 func DecodeF32(input uint64) float32 { return math.Float32frombits(uint32(input)) } // EncodeF64 encodes the input as a ValueTypeF64. +// // See EncodeF32 func EncodeF64(input float64) uint64 { return math.Float64bits(input) } // DecodeF64 decodes the input as a ValueTypeF64. +// // See EncodeF64 func DecodeF64(input uint64) float64 { return math.Float64frombits(input) diff --git a/assemblyscript/assemblyscript.go b/assemblyscript/assemblyscript.go index bdc59129..ecbd21b2 100644 --- a/assemblyscript/assemblyscript.go +++ b/assemblyscript/assemblyscript.go @@ -1,6 +1,7 @@ // Package assemblyscript contains Go-defined special functions imported by AssemblyScript under the module name "env". // // Note: Some code will only import "env.abort", but even that isn't imported when "import wasi" is used in the source. +// // See https://www.assemblyscript.org/concepts.html#special-imports package assemblyscript @@ -19,15 +20,16 @@ import ( ) // Instantiate instantiates a module implementing special functions defined by AssemblyScript: -// * "env.abort" - exits with 255 with an abort message written to wazero.ModuleConfig WithStderr. -// * "env.trace" - no output unless. -// * "env.seed" - uses wazero.ModuleConfig WithRandSource as the source of seed values. +// * "env.abort" - exits with 255 with an abort message written to wazero.ModuleConfig WithStderr. +// * "env.trace" - no output unless. +// * "env.seed" - uses wazero.ModuleConfig WithRandSource as the source of seed values. // -// Note: To customize behavior, use NewModuleBuilder instead. -// Note: If the AssemblyScript program is configured to use WASI, by calling "import wasi" in any file, these -// functions will not be used. -// See NewModuleBuilder -// See wasi.InstantiateSnapshotPreview1 +// Notes +// +// * To customize behavior, use NewModuleBuilder instead. +// * A program compiled to use WASI, via "import wasi" in any file, won't import these functions. +// +// See NewModuleBuilder and wasi.InstantiateSnapshotPreview1 func Instantiate(ctx context.Context, r wazero.Runtime) (api.Closer, error) { return NewModuleBuilder(r).Instantiate(ctx) } diff --git a/builder.go b/builder.go index aa0d9f7d..5c47b01e 100644 --- a/builder.go +++ b/builder.go @@ -35,17 +35,21 @@ import ( // // env2, _ := r.InstantiateModule(ctx, compiled, wazero.NewModuleConfig().WithName("env.2")) // -// Notes: -// * ModuleBuilder is mutable. WithXXX functions return the same instance for chaining. -// * WithXXX methods do not return errors, to allow chaining. Any validation errors are deferred until Build. -// * Insertion order is not retained. Anything defined by this builder is sorted lexicographically on Build. +// Notes +// +// * ModuleBuilder is mutable. WithXXX functions return the same instance for chaining. +// * WithXXX methods do not return errors, to allow chaining. Any validation errors are deferred until Build. +// * Insertion order is not retained. Anything defined by this builder is sorted lexicographically on Build. type ModuleBuilder interface { // Note: until golang/go#5860, we can't use example tests to embed code in interface godocs. // ExportFunction adds a function written in Go, which a WebAssembly module can import. + // If a function is already exported with the same name, this overwrites it. // - // * name - the name to export. Ex "random_get" - // * goFunc - the `func` to export. + // Parameters + // + // * name - the name to export. Ex "random_get" + // * goFunc - the `func` to export. // // Noting a context exception described later, all parameters or result types must match WebAssembly 1.0 (20191205) value // types. This means uint32, uint64, float32 or float64. Up to one result can be returned. @@ -82,7 +86,6 @@ type ModuleBuilder interface { // results, err := fn(ctx, offset, byteCount) // --snip-- // - // Note: If a function is already exported with the same name, this overwrites it. // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#host-functions%E2%91%A2 ExportFunction(name string, goFunc interface{}) ModuleBuilder @@ -90,17 +93,22 @@ type ModuleBuilder interface { ExportFunctions(nameToGoFunc map[string]interface{}) ModuleBuilder // ExportMemory adds linear memory, which a WebAssembly module can import and become available via api.Memory. + // If a memory is already exported with the same name, this overwrites it. // - // * name - the name to export. Ex "memory" for wasi.ModuleSnapshotPreview1 - // * minPages - the possibly zero initial size in pages (65536 bytes per page). + // Parameters + // + // * name - the name to export. Ex "memory" for wasi.ModuleSnapshotPreview1 + // * minPages - the possibly zero initial size in pages (65536 bytes per page). // // For example, the WebAssembly 1.0 Text Format below is the equivalent of this builder method: // // (memory (export "memory") 1) // builder.ExportMemory(1) // - // Note: This is allowed to grow to RuntimeConfig.WithMemoryLimitPages (4GiB). To bound it, use ExportMemoryWithMax. - // Note: If a memory is already exported with the same name, this overwrites it. - // Note: Version 1.0 (20191205) of the WebAssembly spec allows at most one memory per module. + // Notes + // + // * This is allowed to grow to (4GiB) limited by api.MemorySizer. To bound it, use ExportMemoryWithMax. + // * Version 1.0 (20191205) of the WebAssembly spec allows at most one memory per module. + // // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#memory-section%E2%91%A0 ExportMemory(name string, minPages uint32) ModuleBuilder @@ -110,50 +118,52 @@ type ModuleBuilder interface { // // (memory (export "memory") 1 1) // builder.ExportMemoryWithMax(1, 1) // - // Note: maxPages must be at least minPages and no larger than RuntimeConfig.WithMemoryLimitPages + // Note: api.MemorySizer determines the capacity. ExportMemoryWithMax(name string, minPages, maxPages uint32) ModuleBuilder // ExportGlobalI32 exports a global constant of type api.ValueTypeI32. + // If a global is already exported with the same name, this overwrites it. // // For example, the WebAssembly 1.0 Text Format below is the equivalent of this builder method: // // (global (export "canvas_width") i32 (i32.const 1024)) // builder.ExportGlobalI32("canvas_width", 1024) // - // Note: If a global is already exported with the same name, this overwrites it. // Note: The maximum value of v is math.MaxInt32 to match constraints of initialization in binary format. - // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#value-types%E2%91%A0 - // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#syntax-globaltype + // + // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#value-types%E2%91%A0 and + // https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#syntax-globaltype ExportGlobalI32(name string, v int32) ModuleBuilder // ExportGlobalI64 exports a global constant of type api.ValueTypeI64. + // If a global is already exported with the same name, this overwrites it. // // For example, the WebAssembly 1.0 Text Format below is the equivalent of this builder method: // // (global (export "start_epoch") i64 (i64.const 1620216263544)) // builder.ExportGlobalI64("start_epoch", 1620216263544) // - // Note: If a global is already exported with the same name, this overwrites it. // Note: The maximum value of v is math.MaxInt64 to match constraints of initialization in binary format. - // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#value-types%E2%91%A0 - // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#syntax-globaltype + // + // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#value-types%E2%91%A0 and + // https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#syntax-globaltype ExportGlobalI64(name string, v int64) ModuleBuilder // ExportGlobalF32 exports a global constant of type api.ValueTypeF32. + // If a global is already exported with the same name, this overwrites it. // // For example, the WebAssembly 1.0 Text Format below is the equivalent of this builder method: // // (global (export "math/pi") f32 (f32.const 3.1415926536)) // builder.ExportGlobalF32("math/pi", 3.1415926536) // - // Note: If a global is already exported with the same name, this overwrites it. // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#syntax-globaltype ExportGlobalF32(name string, v float32) ModuleBuilder // ExportGlobalF64 exports a global constant of type api.ValueTypeF64. + // If a global is already exported with the same name, this overwrites it. // // For example, the WebAssembly 1.0 Text Format below is the equivalent of this builder method: // // (global (export "math/pi") f64 (f64.const 3.14159265358979323846264338327950288419716939937510582097494459)) // builder.ExportGlobalF64("math/pi", 3.14159265358979323846264338327950288419716939937510582097494459) // - // Note: If a global is already exported with the same name, this overwrites it. // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#syntax-globaltype ExportGlobalF64(name string, v float64) ModuleBuilder @@ -164,9 +174,11 @@ type ModuleBuilder interface { // Instantiate is a convenience that calls Build, then Runtime.InstantiateModule, using default configuration. // - // Note: Closing the wazero.Runtime closes any api.Module it instantiated. - // Note: Fields in the builder are copied during instantiation: Later changes do not affect the instantiated result. - // Note: To avoid using configuration defaults, use Compile instead. + // Notes + // + // * Closing the wazero.Runtime closes any api.Module it instantiated. + // * Fields in the builder are copied during instantiation: Later changes do not affect the instantiated result. + // * To avoid using configuration defaults, use Compile instead. Instantiate(context.Context) (api.Module, error) } diff --git a/config.go b/config.go index b5b4b180..7fcaefa4 100644 --- a/config.go +++ b/config.go @@ -26,25 +26,26 @@ type RuntimeConfig interface { // ("bulk-memory-operations"). This defaults to false as the feature was not finished in WebAssembly 1.0. // // Here are the notable effects: - // * Adds `memory.fill`, `memory.init`, `memory.copy` and `data.drop` instructions. - // * Adds `table.init`, `table.copy` and `elem.drop` instructions. - // * Introduces a "passive" form of element and data segments. - // * Stops checking "active" element and data segment boundaries at compile-time, meaning they can error at runtime. + // * Adds `memory.fill`, `memory.init`, `memory.copy` and `data.drop` instructions. + // * Adds `table.init`, `table.copy` and `elem.drop` instructions. + // * Introduces a "passive" form of element and data segments. + // * Stops checking "active" element and data segment boundaries at compile-time, meaning they can error at runtime. // // Note: "bulk-memory-operations" is mixed with the "reference-types" proposal // due to the WebAssembly Working Group merging them "mutually dependent". // Therefore, enabling this feature results in enabling WithFeatureReferenceTypes, and vice-versa. + // // See https://github.com/WebAssembly/spec/blob/main/proposals/bulk-memory-operations/Overview.md - // See https://github.com/WebAssembly/spec/blob/main/proposals/reference-types/Overview.md - // See https://github.com/WebAssembly/spec/pull/1287 + // https://github.com/WebAssembly/spec/blob/main/proposals/reference-types/Overview.md and + // https://github.com/WebAssembly/spec/pull/1287 WithFeatureBulkMemoryOperations(bool) RuntimeConfig // WithFeatureMultiValue enables multiple values ("multi-value"). This defaults to false as the feature was not // finished in WebAssembly 1.0 (20191205). // // Here are the notable effects: - // * Function (`func`) types allow more than one result - // * Block types (`block`, `loop` and `if`) can be arbitrary function types + // * Function (`func`) types allow more than one result + // * Block types (`block`, `loop` and `if`) can be arbitrary function types // // See https://github.com/WebAssembly/spec/blob/main/proposals/multi-value/Overview.md WithFeatureMultiValue(bool) RuntimeConfig @@ -60,47 +61,48 @@ type RuntimeConfig interface { // ("nontrapping-float-to-int-conversion"). This defaults to false as the feature was not in WebAssembly 1.0. // // The only effect of enabling is allowing the following instructions, which return 0 on NaN instead of panicking. - // * `i32.trunc_sat_f32_s` - // * `i32.trunc_sat_f32_u` - // * `i32.trunc_sat_f64_s` - // * `i32.trunc_sat_f64_u` - // * `i64.trunc_sat_f32_s` - // * `i64.trunc_sat_f32_u` - // * `i64.trunc_sat_f64_s` - // * `i64.trunc_sat_f64_u` + // * `i32.trunc_sat_f32_s` + // * `i32.trunc_sat_f32_u` + // * `i32.trunc_sat_f64_s` + // * `i32.trunc_sat_f64_u` + // * `i64.trunc_sat_f32_s` + // * `i64.trunc_sat_f32_u` + // * `i64.trunc_sat_f64_s` + // * `i64.trunc_sat_f64_u` // // See https://github.com/WebAssembly/spec/blob/main/proposals/nontrapping-float-to-int-conversion/Overview.md WithFeatureNonTrappingFloatToIntConversion(bool) RuntimeConfig // WithFeatureReferenceTypes enables various instructions and features related to table and new reference types. // - // * Introduction of new value types: `funcref` and `externref`. - // * Support for the following new instructions: - // * `ref.null` - // * `ref.func` - // * `ref.is_null` - // * `table.fill` - // * `table.get` - // * `table.grow` - // * `table.set` - // * `table.size` - // * Support for multiple tables per module: - // * `call_indirect`, `table.init`, `table.copy` and `elem.drop` instructions can take non-zero table index. - // * Element segments can take non-zero table index. + // * Introduction of new value types: `funcref` and `externref`. + // * Support for the following new instructions: + // * `ref.null` + // * `ref.func` + // * `ref.is_null` + // * `table.fill` + // * `table.get` + // * `table.grow` + // * `table.set` + // * `table.size` + // * Support for multiple tables per module: + // * `call_indirect`, `table.init`, `table.copy` and `elem.drop` instructions can take non-zero table index. + // * Element segments can take non-zero table index. // // Note: "reference-types" is mixed with the "bulk-memory-operations" proposal // due to the WebAssembly Working Group merging them "mutually dependent". // Therefore, enabling this feature results in enabling WithFeatureBulkMemoryOperations, and vice-versa. + // // See https://github.com/WebAssembly/spec/blob/main/proposals/bulk-memory-operations/Overview.md - // See https://github.com/WebAssembly/spec/blob/main/proposals/reference-types/Overview.md - // See https://github.com/WebAssembly/spec/pull/1287 + // https://github.com/WebAssembly/spec/blob/main/proposals/reference-types/Overview.md and + // https://github.com/WebAssembly/spec/pull/1287 WithFeatureReferenceTypes(enabled bool) RuntimeConfig // WithFeatureSignExtensionOps enables sign extension instructions ("sign-extension-ops"). This defaults to false // as the feature was not in WebAssembly 1.0. // // Here are the notable effects: - // * Adds instructions `i32.extend8_s`, `i32.extend16_s`, `i64.extend8_s`, `i64.extend16_s` and `i64.extend32_s` + // * Adds instructions `i32.extend8_s`, `i32.extend16_s`, `i64.extend8_s`, `i64.extend16_s` and `i64.extend32_s` // // See https://github.com/WebAssembly/spec/blob/main/proposals/sign-extension-ops/Overview.md WithFeatureSignExtensionOps(bool) RuntimeConfig @@ -155,7 +157,8 @@ var engineLessConfig = &runtimeConfig{ // Note: While this is technically AOT, this does not imply any action on your // part. wazero automatically performs ahead-of-time compilation as needed when // Runtime.CompileModule is invoked. -// Note: This panics at runtime the runtime.GOOS or runtime.GOARCH does not +// +// Warning: This panics at runtime if the runtime.GOOS or runtime.GOARCH does not // support Compiler. Use NewRuntimeConfig to safely detect and fallback to // NewRuntimeConfigInterpreter if needed. func NewRuntimeConfigCompiler() RuntimeConfig { @@ -240,10 +243,11 @@ func (c *runtimeConfig) WithWasmCore2() RuntimeConfig { // CompiledModule is a WebAssembly 1.0 module ready to be instantiated (Runtime.InstantiateModule) as an api.Module. // -// Note: Closing the wazero.Runtime closes any CompiledModule it compiled. -// Note: In WebAssembly language, this is a decoded, validated, and possibly also compiled module. wazero avoids using +// In WebAssembly terminology, this is a decoded, validated, and possibly also compiled module. wazero avoids using // the name "Module" for both before and after instantiation as the name conflation has caused confusion. // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#semantic-phases%E2%91%A0 +// +// Note: Closing the wazero.Runtime closes any CompiledModule it compiled. type CompiledModule interface { // Close releases all the allocated resources for this CompiledModule. // @@ -275,15 +279,13 @@ func (c *compiledCode) Close(_ context.Context) error { type CompileConfig interface { // WithImportRenamer can rename imports or break them into different modules. No default. + // A nil function is invalid and ignored. // - // Note: A nil function is invalid and ignored. // Note: This is currently not relevant for ModuleBuilder as it has no means to define imports. WithImportRenamer(api.ImportRenamer) CompileConfig // WithMemorySizer are the allocation parameters used for a Wasm memory. - // The default is to set cap=min and max=65536 if unset. - // - // Note: A nil function is invalid and ignored. + // The default is to set cap=min and max=65536 if unset. A nil function is invalid and ignored. WithMemorySizer(api.MemorySizer) CompileConfig } @@ -324,14 +326,14 @@ func (c *compileConfig) WithMemorySizer(memorySizer api.MemorySizer) CompileConf // system. Using this, resources such as STDIN can be isolated, so that the same module can be safely instantiated // multiple times. // -// Note: While wazero supports Windows as a platform, host functions using ModuleConfig follow a UNIX dialect. +// While wazero supports Windows as a platform, host functions using ModuleConfig follow a UNIX dialect. // See RATIONALE.md for design background and relationship to WebAssembly System Interfaces (WASI). // // Note: ModuleConfig is immutable. Each WithXXX function returns a new instance including the corresponding change. type ModuleConfig interface { // WithArgs assigns command-line arguments visible to an imported function that reads an arg vector (argv). Defaults to - // none. + // none. Runtime.InstantiateModule errs if any arg is empty. // // These values are commonly read by the functions like "args_get" in "wasi_snapshot_preview1" although they could be // read by functions imported from other modules. @@ -341,12 +343,12 @@ type ModuleConfig interface { // argument to the same value set via WithName. // // Note: This does not default to os.Args as that violates sandboxing. - // Note: Runtime.InstantiateModule errs if any value is empty. - // See https://linux.die.net/man/3/argv - // See https://en.wikipedia.org/wiki/Null-terminated_string + // + // See https://linux.die.net/man/3/argv and https://en.wikipedia.org/wiki/Null-terminated_string WithArgs(...string) ModuleConfig // WithEnv sets an environment variable visible to a Module that imports functions. Defaults to none. + // Runtime.InstantiateModule errs if the key is empty or contains a NULL(0) or equals("") character. // // Validation is the same as os.Setenv on Linux and replaces any existing value. Unlike exec.Cmd Env, this does not // default to the current process environment as that would violate sandboxing. This also does not preserve order. @@ -358,12 +360,11 @@ type ModuleConfig interface { // example, neither WebAssembly nor WebAssembly System Interfaces (WASI) define concerns processes have, such as // case-sensitivity on environment keys. For portability, define entries with case-insensitively unique keys. // - // Note: Runtime.InstantiateModule errs if the key is empty or contains a NULL(0) or equals("") character. - // See https://linux.die.net/man/3/environ - // See https://en.wikipedia.org/wiki/Null-terminated_string + // See https://linux.die.net/man/3/environ and https://en.wikipedia.org/wiki/Null-terminated_string WithEnv(key, value string) ModuleConfig // WithFS assigns the file system to use for any paths beginning at "/". Defaults to not found. + // Note: This sets WithWorkDirFS to the same file-system unless already set. // // Ex. This sets a read-only, embedded file-system to serve files under the root ("/") and working (".") directories: // @@ -376,7 +377,6 @@ type ModuleConfig interface { // // "index.html" is accessible as both "/index.html" and "./index.html" because we didn't use WithWorkDirFS. // config := wazero.NewModuleConfig().WithFS(rooted) // - // Note: This sets WithWorkDirFS to the same file-system unless already set. WithFS(fs.FS) ModuleConfig // WithName configures the module name. Defaults to what was decoded or overridden via CompileConfig.WithModuleName. @@ -392,8 +392,11 @@ type ModuleConfig interface { // This writer is most commonly used by the functions like "fd_write" in "wasi_snapshot_preview1" although it could // be used by functions imported from other modules. // - // Note: The caller is responsible to close any io.Writer they supply: It is not closed on api.Module Close. - // Note: This does not default to os.Stderr as that both violates sandboxing and prevents concurrent modules. + // Notes + // + // * The caller is responsible to close any io.Writer they supply: It is not closed on api.Module Close. + // * This does not default to os.Stderr as that both violates sandboxing and prevents concurrent modules. + // // See https://linux.die.net/man/3/stderr WithStderr(io.Writer) ModuleConfig @@ -402,8 +405,11 @@ type ModuleConfig interface { // This reader is most commonly used by the functions like "fd_read" in "wasi_snapshot_preview1" although it could // be used by functions imported from other modules. // - // Note: The caller is responsible to close any io.Reader they supply: It is not closed on api.Module Close. - // Note: This does not default to os.Stdin as that both violates sandboxing and prevents concurrent modules. + // Notes + // + // * The caller is responsible to close any io.Reader they supply: It is not closed on api.Module Close. + // * This does not default to os.Stdin as that both violates sandboxing and prevents concurrent modules. + // // See https://linux.die.net/man/3/stdin WithStdin(io.Reader) ModuleConfig @@ -412,8 +418,11 @@ type ModuleConfig interface { // This writer is most commonly used by the functions like "fd_write" in "wasi_snapshot_preview1" although it could // be used by functions imported from other modules. // - // Note: The caller is responsible to close any io.Writer they supply: It is not closed on api.Module Close. - // Note: This does not default to os.Stdout as that both violates sandboxing and prevents concurrent modules. + // Notes + // + // * The caller is responsible to close any io.Writer they supply: It is not closed on api.Module Close. + // * This does not default to os.Stdout as that both violates sandboxing and prevents concurrent modules. + // // See https://linux.die.net/man/3/stdout WithStdout(io.Writer) ModuleConfig diff --git a/experimental/listener.go b/experimental/listener.go index bb838537..d277a06b 100644 --- a/experimental/listener.go +++ b/experimental/listener.go @@ -9,6 +9,7 @@ import ( // FunctionListenerFactoryKey is a context.Context Value key. Its associated value should be a FunctionListenerFactory. // // Note: This is interpreter-only for now! +// // See https://github.com/tetratelabs/wazero/issues/451 type FunctionListenerFactoryKey struct{} diff --git a/sys/sys.go b/sys/sys.go index 75f3159d..1ba6a6aa 100644 --- a/sys/sys.go +++ b/sys/sys.go @@ -18,8 +18,9 @@ import ( // // Note: While possible the reason of this was "proc_exit" from "wasi_snapshot_preview1", it could be from other host // functions, for example an AssemblyScript's abort handler, or any arbitrary caller of CloseWithExitCode. -// See https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#proc_exit -// See https://www.assemblyscript.org/concepts.html#special-imports +// +// See https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#proc_exit and +// https://www.assemblyscript.org/concepts.html#special-imports type ExitError struct { moduleName string exitCode uint32 @@ -39,6 +40,7 @@ func (e *ExitError) ExitCode() uint32 { return e.exitCode } +// Error implements the error interface. func (e *ExitError) Error() string { return fmt.Sprintf("module %q closed with exit_code(%d)", e.moduleName, e.exitCode) } diff --git a/wasi/errno.go b/wasi/errno.go index 8a76ba2a..5dd21b54 100644 --- a/wasi/errno.go +++ b/wasi/errno.go @@ -6,10 +6,13 @@ import ( // Errno are the error codes returned by WASI functions. // -// Note: This is not always an error, as ErrnoSuccess is a valid code. -// Note: Codes are defined even when not relevant to WASI for use in higher-level libraries or alignment with POSIX. -// See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#-errno-enumu16 -// See https://linux.die.net/man/3/errno +// Notes +// +// * This is not always an error, as ErrnoSuccess is a valid code. +// * Codes are defined even when not relevant to WASI for use in higher-level libraries or alignment with POSIX. +// +// See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#-errno-enumu16 and +// https://linux.die.net/man/3/errno type Errno = uint32 // alias for parity with wasm.ValueType // ErrnoName returns the POSIX error code name, except ErrnoSuccess, which is not an error. Ex. Errno2big -> "E2BIG" diff --git a/wasi/wasi.go b/wasi/wasi.go index d5f47e41..5cff3564 100644 --- a/wasi/wasi.go +++ b/wasi/wasi.go @@ -19,7 +19,8 @@ import ( "github.com/tetratelabs/wazero/internal/wasm" ) -// ModuleSnapshotPreview1 is the module name WASI functions are exported into +// ModuleSnapshotPreview1 is the module name WASI functions are exported into. +// // See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md const ModuleSnapshotPreview1 = "wasi_snapshot_preview1" @@ -34,8 +35,10 @@ const ModuleSnapshotPreview1 = "wasi_snapshot_preview1" // _, _ = wasi.InstantiateSnapshotPreview1(ctx, r) // mod, _ := r.InstantiateModuleFromCode(ctx, source) // -// Note: All WASI functions return a single Errno result, ErrnoSuccess on success. -// Note: Closing the wazero.Runtime closes this instance of WASI as well. +// Notes +// +// * All WASI functions return a single Errno result, ErrnoSuccess on success. +// * Closing the wazero.Runtime closes this instance of WASI as well. func InstantiateSnapshotPreview1(ctx context.Context, r wazero.Runtime) (api.Closer, error) { _, fns := snapshotPreview1Functions(ctx) return r.NewModuleBuilder(ModuleSnapshotPreview1).ExportFunctions(fns).Instantiate(ctx) diff --git a/wasm.go b/wasm.go index 4eb9fd46..0a8da2f8 100644 --- a/wasm.go +++ b/wasm.go @@ -38,18 +38,22 @@ type Runtime interface { Module(moduleName string) api.Module // CompileModule decodes the WebAssembly text or binary source or errs if invalid. - // Any pre-compilation done after decoding the source is dependent on RuntimeConfig or CompileConfig. + // When the context is nil, it defaults to context.Background. // // There are two main reasons to use CompileModule instead of InstantiateModuleFromCode: - // * Improve performance when the same module is instantiated multiple times under different names - // * Reduce the amount of errors that can occur during InstantiateModule. + // * Improve performance when the same module is instantiated multiple times under different names + // * Reduce the amount of errors that can occur during InstantiateModule. + // + // Notes + // + // * The resulting module name defaults to what was binary from the custom name section. + // * Any pre-compilation done after decoding the source is dependent on RuntimeConfig or CompileConfig. // - // Note: When the context is nil, it defaults to context.Background. - // Note: The resulting module name defaults to what was binary from the custom name section. // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#name-section%E2%91%A0 CompileModule(ctx context.Context, source []byte, config CompileConfig) (CompiledModule, error) // InstantiateModuleFromCode instantiates a module from the WebAssembly text or binary source or errs if invalid. + // When the context is nil, it defaults to context.Background. // // Ex. // ctx := context.Background() @@ -58,13 +62,15 @@ type Runtime interface { // // module, _ := r.InstantiateModuleFromCode(ctx, source) // - // Note: When the context is nil, it defaults to context.Background. - // Note: This is a convenience utility that chains CompileModule with InstantiateModule. To instantiate the same - // source multiple times, use CompileModule as InstantiateModule avoids redundant decoding and/or compilation. - // Note: To avoid using configuration defaults, use InstantiateModule instead. + // Notes + // + // * This is a convenience utility that chains CompileModule with InstantiateModule. To instantiate the same + // source multiple times, use CompileModule as InstantiateModule avoids redundant decoding and/or compilation. + // * To avoid using configuration defaults, use InstantiateModule instead. InstantiateModuleFromCode(ctx context.Context, source []byte) (api.Module, error) // InstantiateModule instantiates the module namespace or errs if the configuration was invalid. + // When the context is nil, it defaults to context.Background. // // Ex. // ctx := context.Background() @@ -75,9 +81,9 @@ type Runtime interface { // module, _ := r.InstantiateModule(ctx, compiled, wazero.NewModuleConfig().WithName("prod")) // // While CompiledModule is pre-validated, there are a few situations which can cause an error: - // * The module name is already in use. - // * The module has a table element initializer that resolves to an index outside the Table minimum size. - // * The module has a start function, and it failed to execute. + // * The module name is already in use. + // * The module has a table element initializer that resolves to an index outside the Table minimum size. + // * The module has a start function, and it failed to execute. // // Configuration can also define different args depending on the importing module. // @@ -95,10 +101,10 @@ type Runtime interface { // module, _ := r.InstantiateModule(ctx, compiled, config.WithName("rotate").WithArgs("rotate", "angle=90", "dir=cw")) // // Note: Config is copied during instantiation: Later changes to config do not affect the instantiated result. - // Note: When the context is nil, it defaults to context.Background. InstantiateModule(ctx context.Context, compiled CompiledModule, config ModuleConfig) (api.Module, error) // 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.