llvm-project
llvm-project copied to clipboard
Increasing the Hamming distance for defense programming may be optimized by the compiler.
- The code that caused the error is as follows:(test.c)
enum {
TEST_XXX_ENABLED = 0x5AA55AA5,
TEST_XXX_DISABLED = 0xA55AA55A,
};
static unsigned int g_test_xxx_flag = TEST_XXX_DISABLED;
bool test_xxx_is_enable(void)
{
return g_test_xxx_flag == TEST_XXX_ENABLED;
}
vold test_xxx_enable(void)
{
g_test_xxx_flag = TEST_XXX_ENABLED;
}
- The optimization level is Os.
- Problem Description:
The function works normally, but the secure programming design (increasing the Hamming distance) is optimized by the compiler. In the final generated executable program:
- The size of g_test_xxx_flag is reduced from 4 bytes to 1 byte.
- The operations of assigning and comparing g_test_xxx_flag are both replaced with 0/1.
We expect to generate the following assembly instruction sequence:
Currently, we add "volatile" when defining variables to prevent optimization.
It's a legal optimization. If you want to prevent it, make the value observable (e.g. via volatile as you did, or by making it non-static assuming you don't use LTO.)