From 1089f61868c906b39861c2e72be30ac3d7c3886f Mon Sep 17 00:00:00 2001 From: aaronp64 Date: Thu, 5 Dec 2024 14:31:05 -0500 Subject: [PATCH] Fix RandomPCG::random(int, int) overflow bug - Use int64_t for subtraction before converting to uint32_t - Don't add one to uint32_t max value for rand() bounds --- core/math/random_pcg.cpp | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/core/math/random_pcg.cpp b/core/math/random_pcg.cpp index 2b0f8f12ee4..3f40c0084e0 100644 --- a/core/math/random_pcg.cpp +++ b/core/math/random_pcg.cpp @@ -80,5 +80,15 @@ int RandomPCG::random(int p_from, int p_to) { if (p_from == p_to) { return p_from; } - return int(rand(uint32_t(Math::abs(p_from - p_to)) + 1U)) + MIN(p_from, p_to); + + int64_t min = MIN(p_from, p_to); + int64_t max = MAX(p_from, p_to); + uint32_t diff = static_cast(max - min); + + if (diff == UINT32_MAX) { + // Can't add 1 to max uint32_t value for inclusive range, so call rand without passing bounds. + return static_cast(rand()) + min; + } + + return static_cast(rand(diff + 1U)) + min; }