From 6ad7fdecced4647a8e481259fcf229a1339d8dd2 Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Mon, 18 Jul 2022 07:26:29 -0700
Subject: [PATCH] Fixed infinite loop for values bigger than 0x40000000
Fixes https://github.com/libsdl-org/SDL/issues/5930
---
src/SDL_utils.c | 30 +++++++++++++++---------------
1 file changed, 15 insertions(+), 15 deletions(-)
diff --git a/src/SDL_utils.c b/src/SDL_utils.c
index e375d7443c7..70cb8ca5e9c 100644
--- a/src/SDL_utils.c
+++ b/src/SDL_utils.c
@@ -28,22 +28,22 @@ int SDL_powerof2(int x)
{
int value;
- /* We could use this trick for 32-bit values:
- * value = x;
- * value -= 1;
- * value |= value >> 1;
- * value |= value >> 2;
- * value |= value >> 4;
- * value |= value >> 8;
- * value |= value >> 16;
- * value += 1;
- *
- * ... but this is more readable:
- */
- value = 1;
- while (value < x) {
- value <<= 1;
+ if (x <= 0) {
+ /* Return some sane value - we shouldn't hit this in our use cases */
+ return 1;
}
+
+ /* This trick works for 32-bit values */
+ SDL_COMPILE_TIME_ASSERT(SDL_powerof2, sizeof(x) == sizeof(Uint32));
+ value = x;
+ value -= 1;
+ value |= value >> 1;
+ value |= value >> 2;
+ value |= value >> 4;
+ value |= value >> 8;
+ value |= value >> 16;
+ value += 1;
+
return value;
}