py/misc: Add a way to detect sanitizer builds.

Clang and gcc>=14 can use __has_feature() to detect if a sanitizer
is enabled, but older GCC has no mechanism - need to set a macro
explicitly for this to be recognised.

Necessary for increasing some resource limits in sanitizer builds.
Important not to use to avoid real issues!

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
This commit is contained in:
Angus Gratton 2025-08-06 10:19:43 +10:00
parent d81d56cc4d
commit 3faf229853
2 changed files with 28 additions and 2 deletions

View file

@ -43,6 +43,11 @@ typedef unsigned int uint;
#ifndef __has_builtin #ifndef __has_builtin
#define __has_builtin(x) (0) #define __has_builtin(x) (0)
#endif #endif
#ifndef __has_feature
// This macro is supported by Clang and gcc>=14
#define __has_feature(x) (0)
#endif
/** generic ops *************************************************/ /** generic ops *************************************************/
@ -538,4 +543,23 @@ inline static bool mp_sub_ll_overflow(long long int lhs, long long int rhs, long
} }
#endif #endif
// Helper macros for detecting if sanitizers are enabled
//
// Use sparingly, not for masking issues reported by sanitizers!
//
// Can be detected automatically in Clang and gcc>=14, need to be
// set manually otherwise.
#ifndef MP_UBSAN
#define MP_UBSAN __has_feature(undefined_behavior_sanitizer)
#endif
#ifndef MP_ASAN
#define MP_ASAN __has_feature(address_sanitizer)
#endif
#ifndef MP_SANITIZER_BUILD
#define MP_SANITIZER_BUILD (MP_UBSAN || MP_ASAN)
#endif
#endif // MICROPY_INCLUDED_PY_MISC_H #endif // MICROPY_INCLUDED_PY_MISC_H

View file

@ -518,12 +518,14 @@ CI_UNIX_OPTS_QEMU_RISCV64=(
) )
CI_UNIX_OPTS_SANITIZE_ADDRESS=( CI_UNIX_OPTS_SANITIZE_ADDRESS=(
CFLAGS_EXTRA="-fsanitize=address --param asan-use-after-return=0" # Macro MP_ASAN allows detecting ASan on gcc<=13
CFLAGS_EXTRA="-fsanitize=address --param asan-use-after-return=0 -DMP_ASAN=1"
LDFLAGS_EXTRA="-fsanitize=address --param asan-use-after-return=0" LDFLAGS_EXTRA="-fsanitize=address --param asan-use-after-return=0"
) )
CI_UNIX_OPTS_SANITIZE_UNDEFINED=( CI_UNIX_OPTS_SANITIZE_UNDEFINED=(
CFLAGS_EXTRA="-fsanitize=undefined -fno-sanitize=nonnull-attribute" # Macro MP_UBSAN allows detecting UBSan on gcc<=13
CFLAGS_EXTRA="-fsanitize=undefined -fno-sanitize=nonnull-attribute -DMP_UBSAN=1"
LDFLAGS_EXTRA="-fsanitize=undefined -fno-sanitize=nonnull-attribute" LDFLAGS_EXTRA="-fsanitize=undefined -fno-sanitize=nonnull-attribute"
) )