Skip to content

Commit

Permalink
examples(allocation): ensures data used in host functions isn't freed…
Browse files Browse the repository at this point in the history
… before invocation

Signed-off-by: Luca Burgazzoli <[email protected]>
  • Loading branch information
lburgazzoli committed May 4, 2023
1 parent 6dd0cef commit c1f1bd5
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
25 changes: 20 additions & 5 deletions examples/allocation/tinygo/testdata/greet.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import "C"
import (
"fmt"
"reflect"
"runtime"
"unsafe"
)

Expand All @@ -21,6 +22,11 @@ func greet(name string) {
func log(message string) {
ptr, size := stringToPtr(message)
_log(ptr, size)

// the stringToPtr returns a pointer to the underlying bytes
// of the message it must be ensured that the string is not
// freed
runtime.KeepAlive(message)
}

// _log is a WebAssembly import which prints a string (linear memory offset,
Expand Down Expand Up @@ -72,13 +78,22 @@ 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.
// stringToPtr returns a pointer and size pair to the underlying bytes of the given
// string in a way compatible with WebAssembly numeric types. Since Go strings are
// immutable, the pointer returned by stringToPtr must not be modified.
func stringToPtr(s string) (uint32, uint32) {
buf := []byte(s)
ptr := &buf[0]
// for an empty string the return value by TinyGo 0.27 is nil, however the
// subsequent are still safe and result in the method returning pointer = 0
// and size = 0
//
// Note that:
// - we assume that the given string is never empty so there is no special
// handling for such case
// - this method does not keep the given string alive, hence it is the
// responsibility of the caller to ensure the string is kept alive
ptr := unsafe.StringData(s)
unsafePtr := uintptr(unsafe.Pointer(ptr))
return uint32(unsafePtr), uint32(len(buf))
return uint32(unsafePtr), uint32(len(s))
}

// stringToLeakedPtr returns a pointer and size pair for the given string in a way
Expand Down
Binary file modified examples/allocation/tinygo/testdata/greet.wasm
Binary file not shown.

0 comments on commit c1f1bd5

Please sign in to comment.