From d7c5a0fc5f45519da280cbe55f29511ef8b08ba7 Mon Sep 17 00:00:00 2001 From: Kuzmin Vladimir Date: Sun, 15 Sep 2024 06:47:16 +0300 Subject: [PATCH] Fix int overflow on x32 processors causing panic (#3810) During the roll, "duration" is converted to int, causing overflow on x32 processors. The value may be very small or negative, causing a panic in rand.Intn. --- app/observatory/burst/healthping.go | 2 +- common/dice/dice.go | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/app/observatory/burst/healthping.go b/app/observatory/burst/healthping.go index 41d5e754..cd4d5fc0 100644 --- a/app/observatory/burst/healthping.go +++ b/app/observatory/burst/healthping.go @@ -156,7 +156,7 @@ func (h *HealthPing) doCheck(tags []string, duration time.Duration, rounds int) for i := 0; i < rounds; i++ { delay := time.Duration(0) if duration > 0 { - delay = time.Duration(dice.Roll(int(duration))) + delay = time.Duration(dice.RollInt63n(int64(duration))) } time.AfterFunc(delay, func() { errors.LogDebug(h.ctx, "checking ", handler) diff --git a/common/dice/dice.go b/common/dice/dice.go index 2ff925b8..0a0a40e4 100644 --- a/common/dice/dice.go +++ b/common/dice/dice.go @@ -14,6 +14,14 @@ func Roll(n int) int { return rand.Intn(n) } +// RollInt63n returns a non-negative number between 0 (inclusive) and n (exclusive). +func RollInt63n(n int64) int64 { + if n == 1 { + return 0 + } + return rand.Int63n(n) +} + // Roll returns a non-negative number between 0 (inclusive) and n (exclusive). func RollDeterministic(n int, seed int64) int { if n == 1 {