2 ms·
Compilers would be allowed to do this… but they don't do it. See for yourself: https://gcc.godbolt.org/z/4b5azx5ac https://gcc.godbolt.org/z/4b5azx5ac I repl
by comex 4y ago
Compilers would be allowed to do this… but they don't do it. See for yourself:
https://gcc.godbolt.org/z/4b5azx5ac https://gcc.godbolt.org/z/4b5azx5ac
I replaced the printf with a simple write to a global variable, since as-is, the optimization might actually be illegal on the grounds that the printf might never return (e.g. if stdout is a blocked pipe). But none of GCC, Clang, or MSVC elide the check at max optimization level.
If you put the dereference before the null check, then all of those compilers do elide it. This is pretty easy to justify, since any program without address 0 mapped will always crash before reaching the check. This optimization did cause a brouhaha a decade ago, when it was discovered that it was being applied to the Linux kernel. At the time, it was possible for a user program to map address 0 and have that be directly dereferenceable by the kernel, and an optimized-away null pointer check made an otherwise unexploitable kernel bug exploitable. [1] Linux now passes a flag to turn the optimization off (-fno-delete-null-pointer-checks), which solves that problem without denying user programs the benefits of the optimization.
That said, it appears that Clang elides the check in the dereference-before-check version even on WebAssembly; this is probably a bug.
[1] https://lwn.net/Articles/342330/ https://lwn.net/Articles/342330/
- codeflo 4y agoIt's dangerous to assume that you know better than someone like Raymond Chen, the author of the article the GP linked. This is not a Clang bug, it's just the nature of UB optimizations we're talking about. :) I've found a simple example. Code order and compiler options are very finicky with this sort of thing, but as of posting this, clang optimizes away the null dereference here entirely: https://gcc.godbolt.org/z/zjhY1W67Y https://gcc.godbolt.org/z/zjhY1W67Y (Edit: Simplified example even a bit more.)