From: Lukas Herbolt <lukas@herbolt.com>
To: zlang@kernel.org
Cc: fstests@vger.kernel.org, linux-xfs@vger.kernel.org,
Lukas Herbolt <lukas@herbolt.com>
Subject: [PATCH v2] lib/random.c fix undefined behavior on signed integer overflow.
Date: Fri, 16 Oct 2026 11:21:11 +0200 [thread overview]
Message-ID: <20261016092111.296275-1-lukas@herbolt.com> (raw)
The random.c now expects that signed integer to overflow and
triggers the ^MASK branch. But signed int overflow is undefined
behavior and GCC can optimize this branch out with certain
CFLAGS/LDFLAGS. And cleaning up the dead code.
Signed-off-by: Lukas Herbolt <lukas@herbolt.com>
---
lib/random.c | 34 +++++++---------------------------
1 file changed, 7 insertions(+), 27 deletions(-)
diff --git a/lib/random.c b/lib/random.c
index d5c81be817c8..558da4e6888d 100644
--- a/lib/random.c
+++ b/lib/random.c
@@ -162,38 +162,18 @@ static int32_t mt [128] = {
69069
};
-double
-_random (int32_t is [2])
-{
- int32_t it, leh, nit;
-
- it = is [0];
- leh = is [1];
- if (it <= 0)
- it = (it + it) ^ MASK;
- else
- it = it + it;
- nit = it - 1;
-/* to ensure all-ones pattern omitted */
- leh = leh * mt[nit & 127] + nit;
- is [0] = it; is [1] = leh;
- if (leh < 0) leh = ~leh;
- return (SCALE * ((int32_t) (leh | 1)));
-}
-
-
-
int32_t
_irandm (int32_t is [2])
{
- int32_t it, leh, nit;
-
+ int32_t it, leh, nit, apply_mask;
it = is [0];
leh = is [1];
- if (it <= 0)
- it = (it + it) ^ MASK;
- else
- it = it + it;
+
+/* evaluate on original value - no UB here */
+ apply_mask = (it <= 0);
+/* double via unsigned shift - well-defined */
+ it = (unsigned)it << 1;
+ if (apply_mask) it ^= MASK;
nit = it - 1;
/* to ensure all-ones pattern omitted */
leh = leh * mt[nit & 127] + nit;
--
2.56.0
reply other threads:[~2026-10-16 9:21 UTC|newest]
Thread overview: [no followups] expand[flat|nested] mbox.gz Atom feed
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20261016092111.296275-1-lukas@herbolt.com \
--to=lukas@herbolt.com \
--cc=fstests@vger.kernel.org \
--cc=linux-xfs@vger.kernel.org \
--cc=zlang@kernel.org \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox