Skip to content

Commit fb68a39

Browse files
committed
strengthen undef behavior prevention in checkSignedBitfieldOverflow
Signed-off-by: Fusl <[email protected]>
1 parent 3b12132 commit fb68a39

File tree

1 file changed

+4
-6
lines changed

1 file changed

+4
-6
lines changed

src/bitops.c

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -491,12 +491,10 @@ int checkSignedBitfieldOverflow(int64_t value, int64_t incr, uint64_t bits, int
491491
int64_t max = (bits == 64) ? INT64_MAX : (((int64_t)1 << (bits - 1)) - 1);
492492
int64_t min = (-max) - 1;
493493

494-
/* Note that maxincr and minincr could overflow, but we use the values
495-
* only after checking 'value' range, so when we use it no overflow
496-
* happens. 'uint64_t' cast is there just to prevent undefined behavior on
497-
* overflow */
498-
int64_t maxincr = (uint64_t)max - value;
499-
int64_t minincr = min - value;
494+
/* max/min and value are signed integers but to avoid undefined behavior
495+
* we temporarily cast them to unsigned integers before subtracting. */
496+
int64_t maxincr = (int64_t)((uint64_t)max - (uint64_t)value);
497+
int64_t minincr = (int64_t)((uint64_t)min - (uint64_t)value);
500498

501499
if (value > max || (bits != 64 && incr > maxincr) || (value >= 0 && incr > 0 && incr > maxincr)) {
502500
if (limit) {

0 commit comments

Comments
 (0)