From 04d0950c9e635074345f7735bf8b0c2136027ddd Mon Sep 17 00:00:00 2001 From: Dmitry Marakasov Date: Tue, 17 May 2022 20:38:43 +0300 Subject: [PATCH] Fix UB in random generator abs(INT_MIN) is undefined behavior, so process this case without calling abs() --- Source/engine/random.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Source/engine/random.cpp b/Source/engine/random.cpp index 0eae54c3e..3b5d4d6cb 100644 --- a/Source/engine/random.cpp +++ b/Source/engine/random.cpp @@ -1,5 +1,7 @@ #include "engine/random.hpp" +#include + #include "utils/stdcompat/abs.hpp" namespace devilution { @@ -29,7 +31,9 @@ uint32_t GetLCGEngineState() int32_t GetRndSeed() { - return abs(static_cast(sglGameSeed)); + const int32_t seed = static_cast(sglGameSeed); + // since abs(INT_MIN) is undefined behavior, handle this value specially + return seed == std::numeric_limits::min() ? std::numeric_limits::min() : abs(seed); } int32_t AdvanceRndSeed()