On 30/11/2022 17:41, Jonathan Wakely wrote: > On Wed, 30 Nov 2022 at 17:40, Jonathan Wakely <jwakely.gcc@xxxxxxxxx> wrote: >> >> On Wed, 30 Nov 2022 at 16:27, Jonny Grant <jg@xxxxxxxx> wrote: >>> >>> Hello >>> >>> Does GCC have a clear way to avoid memset being compiled out by optimiser? >>> >>> This article came up, so I combined the broken.c with GCC >>> gcc -Wall -O2 -o broken broken.c >>> >>> Note, I've been using gcc for many years, I'm not looking for just tips how to compile code. I only want to discuss this optimiser issue :-) >>> >>> https://blog.cloudflare.com/the-linux-kernel-key-retention-service-and-why-you-should-use-it-in-your-next-application/ >>> >>> If I modify to clear the buffer, it gets removed by the compiler >>> >>> The only way I could get it to not remove the memset is by adding another printf, (propagating a return code after checking memset wasn't enough) >> >> This is simpler and works for me, but I'm not sure if it's guaranteed >> to always work: >> >> __attribute__((noinline,noipa)) >> void wipe(void* p, size_t n) >> { >> memset(p, 0, n); >> } >> >> static int encrypt(void) > > Oops, I meant to change that to return void, because you don't need to > jump through hoops checking its return value to ensure the side > effects aren't optimized out. > >> { >> uint8_t key[] = "hunter2"; >> printf("encrypting with super secret key: %s\n", key); >> wipe(key, 8); >> } >> >> There is discussion of alternatives in >> https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1358.pdf (starting >> on page 6). >> >> The memset_s function was added to C in Annex K, but most >> implementations of the C library do not support Annex K. Thank you Jonathan and David for your replies. That "noipa" looks to have sorted this issue https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html That page also suggests "noinline" attribute which seems to suggest I'd need to add asm (""); in each wrapper of memset() I'd much rather have memset_s - Jonathan, do you think GCC could add some built-in functions for memset_s ? __builtin_memset_s() would be great. There are quite a few similar ones that should be easy to add based on existing (memcpy_s, memmove_s, strcpy_s, strncpy_s, strcat_s, strncat_s, strtok_s, memset_s, strerror_s, strerrorlen_s, strnlen_s). I did speak to someone at LLVM who was considering adding built-ins to clang. Kind regards Jonny