[Cryptography] Compiler optimization side channel
Christian Huitema
huitema at huitema.net
Sat Aug 24 02:32:52 EDT 2024
On 8/23/2024 7:16 PM, Dave Horsfall wrote:
> On Fri, 23 Aug 2024, Phillip Hallam-Baker wrote:
>
> [...]
>
>> Which looked all well and good. But then I thought to myself, what if
>> the compiler gets hold of that data and decides to optimize the
>> arithmetic creating temporary variables that it leaves hanging about?
> This raises something that I've been thinking about for a while; having
> written your carefully-crafted code, why would anyone want an "optimiser"
> to get its paws on it?
>
> I've been bitten before by the optimiser (C, not C#) which decided that a
> floating point instruction was redundant; I had to buy a book on Intel
> assembly (ick!), and study the code before and after "-O".
In theory, it is possible to turn off compiler optimization by
surrounding the segment of code with pragmas. For example, GCC
advertises support for:
|#pragma GCC push_options #pragma GCC optimize ("O0") your code #pragma
GCC pop_options (See
https://stackoverflow.com/questions/2219829/how-can-i-prevent-gcc-optimizing-some-statements-in-c)
Of course, this is compiler specific. The Visual Studio compiler has: ||#pragma optimize( "", off ) /* unoptimized code section */ #pragma
optimize( "", on ) ||(per
https://learn.microsoft.com/en-us/cpp/preprocessor/optimize?view=msvc-170)
And then Clang supports this with attributes instead of pragmas, as in: ||__attribute__((optnone)) void* always_memset(void *b, int c, size_t
len) { return memset(b, c, len); }|
||(see https://stackoverflow.com/questions/26266820/in-clang-how-do-you-use-per-function-optimization-attributes)
Visual Studio does not support attributes, but GCC does, although of course they
don't use quite the same attributes as clang:
|void __attribute__((optimize("O0"))) foo(unsigned char data) { //
unmodifiable compiler code } So the state of the art is that you might
be able to force a compiler to do the right thing, but you have to know
which compiler is compiling the code. | Or at least that the theory.
-- Christian Huitema
More information about the cryptography
mailing list