[libc-commits] [libc] [libc] Fix undefined behavior for nan functions. (PR #106468)
via libc-commits
libc-commits at lists.llvm.org
Wed Sep 4 04:30:11 PDT 2024
================
@@ -1208,6 +1210,15 @@ template <class T> LIBC_INLINE StrToNumResult<T> strtonan(const char *arg) {
using FPBits = typename fputil::FPBits<T>;
using StorageType = typename FPBits::StorageType;
+#ifndef LIBC_HAS_SANITIZER
+ if (LIBC_UNLIKELY(arg == nullptr)) {
+ // Use volatile to prevent undefined behavior of dereferencing nullptr.
----------------
lntue wrote:
It's triggered even without a & d. This got my attention when the nan tests didn't crash and trigger SIGSEGV on some riscv64 configs.
About your worry regarding the performance, if the inputs (runtime or compile-time) have nullptr, our original intention is to crash with SIGSEGV anyway, and the added `nullptr` check and volatile load is negligible compared to crashing part.
If the inputs do not have nullptr, the only extra cost is the nullptr check `arg == nullptr`, which always returns false under the condition / assumption, cost at most 1 CPU clock, and will be hidden away completely by the CPU's branch predictors.
So for this check `arg == nullptr` to incurs observable performance penalty, you'll need to call `strtonan` for a large array with inputs alternating between very short string and `nullptr` in order to beat the CPU's branch predictor. But in that case, we already crash at the first `nullptr` encountered.
https://github.com/llvm/llvm-project/pull/106468
More information about the libc-commits
mailing list