-
Notifications
You must be signed in to change notification settings - Fork 0
/
hostfunc.filewrite.go
75 lines (61 loc) · 2.31 KB
/
hostfunc.filewrite.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package capsule
import (
"context"
"log"
"os"
"github.com/tetratelabs/wazero"
"github.com/tetratelabs/wazero/api"
)
// DefineHostFuncWriteFile creates a new function called hostWriteFile in the
// HostModuleBuilder. It accepts the following parameters:
// - filePath (int32): position
// - filePath (int32): length
// - content (int32): position
// - content (int32): length
// - returned (int32): position
// - returned (int32): length
// The function returns an int32.
func DefineHostFuncWriteFile(builder wazero.HostModuleBuilder) {
builder.NewFunctionBuilder().
WithGoModuleFunction(writeFile,
[]api.ValueType{
api.ValueTypeI32, // filePath position
api.ValueTypeI32, // filePath length
api.ValueTypeI32, // content position
api.ValueTypeI32, // content length
api.ValueTypeI32, // returned position
api.ValueTypeI32, // returned length
},
[]api.ValueType{api.ValueTypeI32}).
Export("hostWriteFile")
}
// writeFile : host function called by the wasm function
// and then returning data to the wasm module
var writeFile = api.GoModuleFunc(func(ctx context.Context, module api.Module, params []uint64) {
filePathPosition := uint32(params[0])
filePathLength := uint32(params[1])
bufferFilePath, err := ReadBytesParameterFromMemory(module, filePathPosition, filePathLength)
if err != nil {
log.Panicf("Error (bufferFilePath): ReadBytesParameterFromMemory(%d, %d) out of range", filePathPosition, filePathLength)
}
contentPosition := uint32(params[2])
contentLength := uint32(params[3])
bufferContent, err := ReadBytesParameterFromMemory(module, contentPosition, contentLength)
if err != nil {
log.Panicf("Error (bufferContent): ReadBytesParameterFromMemory(%d, %d) out of range", contentPosition, contentLength)
}
var resultFromHost []byte
errWriteFile := os.WriteFile(string(bufferFilePath), bufferContent, 0644)
if errWriteFile != nil {
resultFromHost = failure([]byte(errWriteFile.Error()))
} else {
resultFromHost = success(bufferFilePath)
}
positionReturnBuffer := uint32(params[4])
lengthReturnBuffer := uint32(params[5])
_, errReturn := ReturnBytesToMemory(ctx, module, positionReturnBuffer, lengthReturnBuffer, resultFromHost)
if errReturn != nil {
log.Panicf("Error: ReturnBytesToMemory(%d, %d) out of range", positionReturnBuffer, lengthReturnBuffer)
}
params[0] = 0
})