github.com/bananabytelabs/wazero@v0.0.0-20240105073314-54b22a776da8/internal/gojs/util/util.go (about) 1 package util 2 3 import ( 4 "fmt" 5 pathutil "path" 6 7 "github.com/bananabytelabs/wazero/api" 8 "github.com/bananabytelabs/wazero/internal/gojs/custom" 9 "github.com/bananabytelabs/wazero/internal/wasm" 10 ) 11 12 // MustWrite is like api.Memory except that it panics if the offset 13 // is out of range. 14 func MustWrite(mem api.Memory, fieldName string, offset uint32, val []byte) { 15 if ok := mem.Write(offset, val); !ok { 16 panic(fmt.Errorf("out of memory writing %s", fieldName)) 17 } 18 } 19 20 // MustRead is like api.Memory except that it panics if the offset and 21 // byteCount are out of range. 22 func MustRead(mem api.Memory, funcName string, paramIdx int, offset, byteCount uint32) []byte { 23 buf, ok := mem.Read(offset, byteCount) 24 if ok { 25 return buf 26 } 27 var paramName string 28 if names, ok := custom.NameSection[funcName]; ok { 29 if paramIdx < len(names.ParamNames) { 30 paramName = names.ParamNames[paramIdx] 31 } 32 } 33 if paramName == "" { 34 paramName = fmt.Sprintf("%s param[%d]", funcName, paramIdx) 35 } 36 panic(fmt.Errorf("out of memory reading %s", paramName)) 37 } 38 39 func NewFunc(name string, goFunc api.GoModuleFunc) *wasm.HostFunc { 40 return &wasm.HostFunc{ 41 ExportName: name, 42 Name: name, 43 ParamTypes: []api.ValueType{api.ValueTypeI32}, 44 ParamNames: []string{"sp"}, 45 Code: wasm.Code{GoFunc: goFunc}, 46 } 47 } 48 49 // ResolvePath is needed when a non-absolute path is given to a function. 50 // Unlike other host ABI, GOOS=js maintains the CWD host side. 51 func ResolvePath(cwd, path string) (resolved string) { 52 pathLen := len(path) 53 switch { 54 case pathLen == 0: 55 return cwd 56 case pathLen == 1 && path[0] == '.': 57 return cwd 58 case path[0] == '/': 59 resolved = pathutil.Clean(path) 60 default: 61 resolved = pathutil.Join(cwd, path) 62 } 63 64 // If there's a trailing slash, we need to retain it for symlink edge 65 // cases. See https://github.com/golang/go/issues/27225 66 if len(resolved) > 1 && path[pathLen-1] == '/' { 67 return resolved + "/" 68 } 69 return resolved 70 }