github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/modules/wasm/host/util.go (about) 1 package host 2 3 import ( 4 "golang.org/x/text/encoding/unicode" 5 6 "github.com/machinefi/w3bstream/pkg/modules/wasm/abi/types" 7 "github.com/machinefi/w3bstream/pkg/modules/wasm/consts" 8 ) 9 10 func GetImportsHandler(i types.Instance) types.ImportsHandler { 11 ctx := GetContext(i) 12 if ctx == nil { 13 return nil 14 } 15 return ctx.GetImports() 16 } 17 18 func GetContext(i types.Instance) types.Context { 19 if c, ok := i.GetUserdata().(types.Context); ok { 20 return c 21 } 22 return nil 23 } 24 25 func CopyHostDataToWasm(i types.Instance, data []byte, dataaddrptr, datasizeptr int32) error { 26 addr, err := i.Malloc(int32(len(data))) 27 if err != nil { 28 return err 29 } 30 31 err = i.PutMemory(addr, int32(len(data)), data) 32 if err != nil { 33 return err 34 } 35 36 err = i.PutUint32(dataaddrptr, uint32(addr)) 37 if err != nil { 38 return err 39 } 40 41 err = i.PutUint32(datasizeptr, uint32(len(data))) 42 if err != nil { 43 return err 44 } 45 46 return nil 47 } 48 49 func ReadStringFromAddr(i types.Instance, addr int32) (string, error) { 50 if addr < 4 { 51 return "", consts.RESULT__INVALID_MEM_ACCESS 52 } 53 dec := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM).NewDecoder() 54 55 size, err := i.GetUint32(addr - 4) 56 if err != nil { 57 return "", err 58 } 59 mem, err := i.GetMemory(addr, int32(size)) 60 if err != nil { 61 return "", err 62 } 63 bytes, err := dec.Bytes(mem) 64 if err != nil { 65 return "", err 66 } 67 return string(bytes), nil 68 }