Merge pull request #10318 from keith-packard/gcc-14-3-array-bounds

Avoid invalid gcc 14.3 warning about array bounds in mbedtls_xor
This commit is contained in:
Gilles Peskine
2025-10-08 19:00:48 +00:00
committed by GitHub
2 changed files with 26 additions and 6 deletions
+4
View File
@@ -0,0 +1,4 @@
Bugfix
* Appease GCC 14.3's array bounds checker by inserting checks in mbedtls_xor
that bail before the byte-at-a-time loop when the array size is a constant
(using MBEDTLS_HAS_BUILTIN) and an exact multiple of the larger loop size.
+22 -6
View File
@@ -99,6 +99,13 @@ extern void (*mbedtls_test_hook_test_fail)(const char *test, int line, const cha
* fall back to the unsafe implementation. */
#define ARRAY_LENGTH(array) ARRAY_LENGTH_UNSAFE(array)
#endif
#if defined(__has_builtin)
#define MBEDTLS_HAS_BUILTIN(x) __has_builtin(x)
#else
#define MBEDTLS_HAS_BUILTIN(x) 0
#endif
/** Allow library to access its structs' private members.
*
* Although structs defined in header files are publicly available,
@@ -208,6 +215,11 @@ static inline void mbedtls_xor(unsigned char *r,
return;
}
#endif
#if defined(MBEDTLS_COMPILER_IS_GCC) && MBEDTLS_HAS_BUILTIN(__builtin_constant_p)
if (__builtin_constant_p(n) && n % 16 == 0) {
return;
}
#endif
#elif defined(MBEDTLS_ARCH_IS_X64) || defined(MBEDTLS_ARCH_IS_ARM64)
/* This codepath probably only makes sense on architectures with 64-bit registers */
for (; (i + 8) <= n; i += 8) {
@@ -219,6 +231,11 @@ static inline void mbedtls_xor(unsigned char *r,
return;
}
#endif
#if defined(MBEDTLS_COMPILER_IS_GCC) && MBEDTLS_HAS_BUILTIN(__builtin_constant_p)
if (__builtin_constant_p(n) && n % 8 == 0) {
return;
}
#endif
#else
for (; (i + 4) <= n; i += 4) {
uint32_t x = mbedtls_get_unaligned_uint32(a + i) ^ mbedtls_get_unaligned_uint32(b + i);
@@ -229,6 +246,11 @@ static inline void mbedtls_xor(unsigned char *r,
return;
}
#endif
#if defined(MBEDTLS_COMPILER_IS_GCC) && MBEDTLS_HAS_BUILTIN(__builtin_constant_p)
if (__builtin_constant_p(n) && n % 4 == 0) {
return;
}
#endif
#endif
#endif
for (; i < n; i++) {
@@ -367,12 +389,6 @@ static inline void mbedtls_xor_no_simd(unsigned char *r,
struct ISO_C_does_not_allow_extra_semicolon_outside_of_a_function
#endif
#if defined(__has_builtin)
#define MBEDTLS_HAS_BUILTIN(x) __has_builtin(x)
#else
#define MBEDTLS_HAS_BUILTIN(x) 0
#endif
/* Define compiler branch hints */
#if MBEDTLS_HAS_BUILTIN(__builtin_expect)
#define MBEDTLS_LIKELY(x) __builtin_expect(!!(x), 1)