Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

examples(allocation): free memory after unmarshalling a result from the guest #1368

Merged
merged 1 commit into from
Apr 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion examples/allocation/tinygo/greet.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,15 @@ func main() {
if err != nil {
log.Panicln(err)
}
// Note: This pointer is still owned by TinyGo, so don't try to free it!

greetingPtr := uint32(ptrSize[0] >> 32)
greetingSize := uint32(ptrSize[0])

// We don't need the memory after deserialization: make sure it is freed.
if greetingPtr != 0 {
defer free.Call(ctx, uint64(greetingPtr))
}

// The pointer is a linear memory offset, which is where we write the name.
if bytes, ok := mod.Memory().Read(greetingPtr, greetingSize); !ok {
log.Panicf("Memory.Read(%d, %d) out of range of memory size %d",
Expand Down
20 changes: 15 additions & 5 deletions examples/allocation/tinygo/testdata/greet.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ import (
"unsafe"
)

// #include <stdlib.h>
import "C"

// main is required for TinyGo to compile to Wasm.
func main() {}

Expand Down Expand Up @@ -70,10 +73,17 @@ func ptrToString(ptr uint32, size uint32) string {
}

// stringToPtr returns a pointer and size pair for the given string in a way
// compatible with WebAssembly numeric types.
// compatible with WebAssembly numeric types. The pointer is not automatically
// managed by tinygo but must be freed by the host.
func stringToPtr(s string) (uint32, uint32) {
buf := []byte(s)
ptr := &buf[0]
unsafePtr := uintptr(unsafe.Pointer(ptr))
return uint32(unsafePtr), uint32(len(buf))
if len(s) == 0 {
return 0, 0
}

size := C.ulong(len(s))
ptr := unsafe.Pointer(C.malloc(size))

copy(unsafe.Slice((*byte)(ptr), size), []byte(s))

return uint32(uintptr(ptr)), uint32(len(s))
}
Binary file modified examples/allocation/tinygo/testdata/greet.wasm
Binary file not shown.