From a8b75d0a1c1c5254aba566f476b6e512fee92880 Mon Sep 17 00:00:00 2001 From: Dan Baston Date: Tue, 4 Feb 2025 13:29:50 -0500 Subject: [PATCH] muparser: avoid uncaught exception on invalid variable name --- autotest/gdrivers/vrtderived.py | 7 +++++++ frmts/vrt/vrtexpression_muparser.cpp | 19 +++++++++++++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/autotest/gdrivers/vrtderived.py b/autotest/gdrivers/vrtderived.py index 48cb238dbfdb..90e955a8f806 100755 --- a/autotest/gdrivers/vrtderived.py +++ b/autotest/gdrivers/vrtderived.py @@ -1273,6 +1273,13 @@ def test_vrt_pixelfn_expression( "exceeds maximum of 100000 set by GDAL_EXPRTK_MAX_EXPRESSION_LENGTH", id="expression is too long", ), + pytest.param( + "B[1]", + [("B[1]", 3)], + "muparser", + "Invalid variable name", + id="invalid variable name", + ), ], ) def test_vrt_pixelfn_expression_invalid( diff --git a/frmts/vrt/vrtexpression_muparser.cpp b/frmts/vrt/vrtexpression_muparser.cpp index 6245f7115aea..d9e747302c21 100644 --- a/frmts/vrt/vrtexpression_muparser.cpp +++ b/frmts/vrt/vrtexpression_muparser.cpp @@ -25,17 +25,31 @@ class MuParserExpression::Impl public: explicit Impl(std::string_view osExpression) : m_osExpression(std::string(osExpression)), m_oVectors{}, m_oParser{}, - m_adfResults{1}, m_bIsCompiled{false} + m_adfResults{1}, m_bIsCompiled{false}, m_bCompileFailed{false} { } void Register(std::string_view osVariable, double *pdfValue) { - m_oParser.DefineVar(std::string(osVariable), pdfValue); + try + { + m_oParser.DefineVar(std::string(osVariable), pdfValue); + } + catch (const mu::Parser::exception_type &) + { + CPLError(CE_Failure, CPLE_AppDefined, "Invalid variable name: %s", + std::string(osVariable).c_str()); + m_bCompileFailed = true; + } } CPLErr Compile() { + if (m_bCompileFailed) + { + return CE_Failure; + } + try { CPLString tmpExpression(m_osExpression); @@ -99,6 +113,7 @@ class MuParserExpression::Impl mu::Parser m_oParser; std::vector m_adfResults; bool m_bIsCompiled; + bool m_bCompileFailed; }; MuParserExpression::MuParserExpression(std::string_view osExpression)