ARM-software / LLVM-embedded-toolchain-for-Arm

A project dedicated to building LLVM toolchain for Arm and AArch64 embedded targets.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Increasing the Hamming distance for defense programming may be optimized by the compiler.

zhou-shan opened this issue · comments

  1. 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;
}
  1. The optimization level is Os.
  2. Problem Description:
    image
    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:
image

The current verification results show that this optimization does not exist in GCC. We hope to have a separate option in CLANG-LLVM to control the switch of this optimization.

Currently, we add "volatile" when defining variables to prevent optimization.

Hi,

Thank you for reporting this issue! I am afraid, different compilers can have different optimizations and heuristics, thus differ in generated code, however as long as it honours the language standard, it is a valid optimization.

You are correct, volatile is one of the options to request the compiler to avoid unwanted optimizations.

You may read more about possible optimization issues in regard to security in https://github.com/llsoftsec/llsoftsecbook