From be73f2b019b45e08df3834aa2189a0b59bd08592 Mon Sep 17 00:00:00 2001 From: Evil Eye Date: Mon, 1 Dec 2025 20:58:25 +0100 Subject: [PATCH] Prevent UB when reading global variables --- components/esm3/variantimp.cpp | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/components/esm3/variantimp.cpp b/components/esm3/variantimp.cpp index 31248556ec..e5337a4dbf 100644 --- a/components/esm3/variantimp.cpp +++ b/components/esm3/variantimp.cpp @@ -1,6 +1,7 @@ #include "variantimp.hpp" #include +#include #include #include @@ -9,6 +10,18 @@ namespace ESM { + namespace + { + template + T floatCast(float value) + { + constexpr float min = static_cast(std::numeric_limits::lowest()); + constexpr float max = static_cast(std::numeric_limits::max()); + if (std::isnan(value) || value < min || value > max) + return {}; + return static_cast(value); + } + } void readESMVariantValue(ESMReader& esm, Variant::Format format, VarType type, std::string& out) { @@ -60,9 +73,9 @@ namespace ESM if (std::isnan(value)) out = 0; else - out = static_cast(value); + out = floatCast(value); else if (type == VT_Long) - out = static_cast(value); + out = floatCast(value); else esm.fail("unsupported global variable integer type"); }