From e5661bcf60477302b66a0cac3ecf3328d9e426e6 Mon Sep 17 00:00:00 2001 From: qmuntal Date: Tue, 8 Oct 2024 11:11:01 +0200 Subject: [PATCH] prevent RandReader.Read argument from escaping to the heap --- cgo_go124.go | 7 +++++++ rand_test.go | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 cgo_go124.go diff --git a/cgo_go124.go b/cgo_go124.go new file mode 100644 index 00000000..17b572da --- /dev/null +++ b/cgo_go124.go @@ -0,0 +1,7 @@ +//go:build go1.24 && !cmd_go_bootstrap + +package openssl + +// #cgo noescape go_openssl_RAND_bytes +// #cgo nocallback go_openssl_RAND_bytes +import "C" diff --git a/rand_test.go b/rand_test.go index 4735ee75..8fa40192 100644 --- a/rand_test.go +++ b/rand_test.go @@ -1,6 +1,9 @@ package openssl_test import ( + "go/version" + "runtime" + "strings" "testing" "github.com/golang-fips/openssl/v2" @@ -12,3 +15,19 @@ func TestRand(t *testing.T) { t.Fatal(err) } } + +func TestAllocations(t *testing.T) { + n := int(testing.AllocsPerRun(10, func() { + buf := make([]byte, 32) + openssl.RandReader.Read(buf) + sink ^= buf[0] + })) + want := 1 + ver := strings.TrimPrefix(runtime.Version(), "devel ") + if version.Compare(ver, "go1.24") >= 0 { + want = 0 + } + if n > want { + t.Errorf("allocs = %d, want %d", n, want) + } +}