Adds ModuleConfig.Validate() to allow pre-flight checks on source (#281)

This adds `ModuleConfig.Validate()` as needed by wapc-go to ensure a
module instantiated many times later is checked first. This is a method
of config in case we later add the ability to force a format. For now,
it relies on detection and the call-site only use binary anyway.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
This commit is contained in:
Crypt Keeper
2022-02-23 17:17:01 +08:00
committed by GitHub
parent 0186e41b27
commit fc26fdd225
2 changed files with 55 additions and 2 deletions

21
wasm.go
View File

@@ -65,6 +65,17 @@ type ModuleConfig struct {
Name string
// Source is the WebAssembly 1.0 (MVP) text or binary encoding of the module.
Source []byte
validatedSource []byte
decodedModule *internalwasm.Module
}
// Validate eagerly decodes the Source and errs if it is invalid.
//
// This is used to pre-flight check and cache the module for later instantiation.
func (m *ModuleConfig) Validate() (err error) {
_, _, err = decodeModule(m)
return err
}
// InstantiateModule instantiates the module namespace or errs if the configuration was invalid.
@@ -96,6 +107,12 @@ func decodeModule(module *ModuleConfig) (m *internalwasm.Module, name string, er
return
}
// Check if this source was already decoded
if bytes.Equal(module.Source, module.validatedSource) {
m = module.decodedModule
return
}
// Peek to see if this is a binary or text format
if bytes.Equal(module.Source[0:4], binary.Magic) {
m, err = binary.DecodeModule(module.Source)
@@ -106,6 +123,10 @@ func decodeModule(module *ModuleConfig) (m *internalwasm.Module, name string, er
return
}
// Cache as tools like wapc-go re-instantiate the same module many times.
module.validatedSource = module.Source
module.decodedModule = m
name = module.Name
if name == "" && m.NameSection != nil {
name = m.NameSection.ModuleName