]> Cypherpunks repositories - gostls13.git/commitdiff
runtime/metrics: fix panic in Read with empty slice
authorAmol Yadav <amolyadav6125@gmail.com>
Wed, 28 Jan 2026 01:14:53 +0000 (01:14 +0000)
committerGopher Robot <gobot@golang.org>
Wed, 28 Jan 2026 16:44:36 +0000 (08:44 -0800)
Calling Read with a nil or empty slice previously caused a panic with
"index out of range" because the function unconditionally accessed the
first element of the slice (via &m[0]) to pass the pointer to the
runtime.

This change adds a check for len(m) == 0 to return early, preventing
the panic when no samples are provided.

Fixes #77231

Change-Id: I442635f5c61de432883c8d0efae9cc6aa1363cc9
GitHub-Last-Rev: 6f24f67b18c77a0b36b92017a3f4ef8aa3aa5229
GitHub-Pull-Request: golang/go#77233
Reviewed-on: https://go-review.googlesource.com/c/go/+/737380
Reviewed-by: Amol Yadav <amolyadav6125@gmail.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Michael Pratt <mpratt@google.com>
Commit-Queue: Michael Pratt <mpratt@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
src/runtime/metrics/description_test.go
src/runtime/metrics/sample.go

index 0ee9ea16d0b9a802b29b8461dedc73073a911088..71c7b00b02ed28a8a8128f917b0ded11d1f54189 100644 (file)
@@ -156,3 +156,10 @@ func TestDocs(t *testing.T) {
                fmt.Fprintf(os.Stderr, "go test -generate: doc.go already up-to-date\n")
        }
 }
+
+func TestReadEmptySlice(t *testing.T) {
+       // Test that Read does not panic when given an empty slice.
+       // This should be a no-op.
+       metrics.Read(nil)
+       metrics.Read([]metrics.Sample{})
+}
index 9efc5c5f06a934f69b550430a88af47514572220..df1341d48c5638713201ea9383791a71178bba8c 100644 (file)
@@ -43,5 +43,8 @@ func runtime_readMetrics(unsafe.Pointer, int, int)
 // Sample values with names not appearing in [All] will have their Value populated
 // as KindBad to indicate that the name is unknown.
 func Read(m []Sample) {
+       if len(m) == 0 {
+               return
+       }
        runtime_readMetrics(unsafe.Pointer(&m[0]), len(m), cap(m))
 }