[C-safe-secure-studygroup] Dead store optimization
Wheeler, David A
dwheeler at ida.org
Fri May 5 18:40:06 UTC 2017
Robert Seacord:
> memset(ptr,0,size);
> free(ptr);
> ... But compilers almost always eliminate the memset() as a dead code store.
Indeed, I mention this issue in my book here:
https://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/protect-secrets.html
In particular:
> In many languages (including C and C++), be careful that the compiler doesn’t optimize away the "dead code" for overwriting the value - since in this case it’s not dead code. Many compilers, including many C/C++ compilers, remove writes to stores that are no longer used - this is often referred to as "dead store removal."
Clive Pygott:
> I assume its clear that the solution is to declare ptr as volatile TYPE *ptr; as the compiler can't then ignore memset
Has anyone verified that widely-used compilers generate the correct code in this case? This is an edge case for compilers that matters for security. I'd love a paper reference if there is one.
Oh, and two asides:
1. If you want this to really protect the memory, you also need to ensure that the array isn't paged out. E.G., mlock() and friends.
2. At least it's *possible* to do this in C and C#. I've never found a way to safely do this in Java, in part due to its interaction with the garbage collector (the JVM is free to make copies, and there's no guarantee that finalization ever actually occurs in Java). The only way I've found to correctly do this in Java is to call out to C.
--- David A. Wheeler
More information about the C-safe-secure-studygroup
mailing list