Skip to content
This repository was archived by the owner on Aug 31, 2021. It is now read-only.

Commit e3e009c

Browse files
committed
[CID 14868] libscript: MCBitwisEvalBitwiseShift(): Ensure positive shift.
Shifting by a negative amount invokes undefined behaviour.
1 parent 66c68dc commit e3e009c

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

libscript/src/module-bitwise.cpp

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -38,11 +38,21 @@ extern "C" MC_DLLEXPORT void MCBitwiseEvalBitwiseNot(integer_t p_operand, intege
3838

3939
extern "C" MC_DLLEXPORT void MCBitwiseEvalBitwiseShift(integer_t p_operand, bool p_is_right, integer_t p_shift, integer_t& r_output)
4040
{
41-
if (p_shift < 0 != p_is_right)
42-
// truncate towards 0
43-
r_output = (integer_t)(p_operand >> abs(p_shift));
44-
else
45-
r_output = p_operand << p_shift;
41+
/* Ensure that the shift amount is always positive */
42+
if (p_shift < 0)
43+
{
44+
/* Overflow check (why would anyone do this?) */
45+
if (INTEGER_MIN == p_shift)
46+
++p_shift;
47+
48+
p_shift = -p_shift;
49+
p_is_right = !p_is_right;
50+
}
51+
52+
if (p_is_right)
53+
r_output = p_operand >> p_shift;
54+
else
55+
r_output = p_operand << p_shift;
4656
}
4757

4858
////////////////////////////////////////////////////////////////////////////////////////////////////

0 commit comments

Comments
 (0)