Avoid signed right shift UB
Signed-off-by: Dave Rodgman <dave.rodgman@arm.com>
diff --git a/library/constant_time_impl.h b/library/constant_time_impl.h
index 971388c..54bd2b0 100644
--- a/library/constant_time_impl.h
+++ b/library/constant_time_impl.h
@@ -183,8 +183,14 @@
#pragma warning( push )
#pragma warning( disable : 4146 )
#endif
- return (mbedtls_ct_condition_t) (((mbedtls_ct_int_t) ((-xo) | -(xo >> 1))) >>
- (MBEDTLS_CT_SIZE - 1));
+ // y is negative (i.e., top bit set) iff x is non-zero
+ mbedtls_ct_int_t y = (-xo) | -(xo >> 1);
+
+ // extract only the sign bit of y so that y == 1 (if x is non-zero) or 0 (if x is zero)
+ y = (((mbedtls_ct_uint_t) y) >> (MBEDTLS_CT_SIZE - 1));
+
+ // -y has all bits set (if x is non-zero), or all bits clear (if x is zero)
+ return (mbedtls_ct_condition_t) (-y);
#if defined(_MSC_VER)
#pragma warning( pop )
#endif