Skip to content

Commit

Permalink
VRT expressions: enable array bounds-checking
Browse files Browse the repository at this point in the history
  • Loading branch information
dbaston committed Nov 12, 2024
1 parent 9698635 commit fd94c9e
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
13 changes: 13 additions & 0 deletions autotest/gdrivers/vrtprocesseddataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -1271,6 +1271,19 @@ def test_vrtprocesseddataset_trimming_errors(tmp_vsimem):
"must return a vector or a list of scalars",
id="return wrong number of bands",
),
pytest.param(
"""
var out[3];
for (var i := 0; i < 100; i += 1) {
out[i] := i;
}
return [out];
""",
np.array([[[1, 2]], [[3, 4]], [[5, 6]]]),
np.array([[[1, 1]], [[2, 2]], [[3, 3]]]),
"Attempted to access index 3",
id="out of bounds vector access",
),
],
)
def test_vrtprocesseddataset_expression(tmp_vsimem, expression, src, expected, error):
Expand Down
38 changes: 37 additions & 1 deletion frmts/vrt/vrtexpression.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,27 @@
#define exprtk_disable_string_capabilities
#include <exprtk.hpp>

#include <sstream>

struct vector_access_check final : public exprtk::vector_access_runtime_check
{
bool handle_runtime_violation(violation_context &context) override
{
auto nElements = (static_cast<std::uint8_t *>(context.end_ptr) -
static_cast<std::uint8_t *>(context.base_ptr)) /
context.type_size;
auto nIndexAccessed = (static_cast<std::uint8_t *>(context.access_ptr) -
static_cast<std::uint8_t *>(context.base_ptr)) /
context.type_size;

std::ostringstream oss;
oss << "Attempted to access index " << nIndexAccessed
<< " in a vector of " << nElements
<< " elements when evaluating VRT expression.",
throw std::runtime_error(oss.str());
}
};

class GDALExpressionEvaluator::Impl
{
public:
Expand All @@ -19,9 +40,15 @@ class GDALExpressionEvaluator::Impl
std::vector<std::pair<std::string, double *>> m_aoVariables{};
std::vector<std::pair<std::string, std::vector<double> *>> m_aoVectors{};
std::vector<double> m_adfResults{};
vector_access_check m_oVectorAccessCheck{};

bool m_bIsCompiled{false};

Impl()
{
m_oParser.register_vector_access_runtime_check(m_oVectorAccessCheck);
}

CPLErr compile()
{
for (const auto &[osVariable, pdfValueLoc] : m_aoVariables)
Expand Down Expand Up @@ -107,7 +134,16 @@ CPLErr GDALExpressionEvaluator::Evaluate()
}

m_pImpl->m_adfResults.clear();
double value = m_pImpl->m_oExpression.value(); // force evaluation
double value;
try
{
value = m_pImpl->m_oExpression.value(); // force evaluation
}
catch (const std::exception &e)
{
CPLError(CE_Failure, CPLE_AppDefined, "%s", e.what());
return CE_Failure;
}

const auto &results = m_pImpl->m_oExpression.results();

Expand Down

0 comments on commit fd94c9e

Please sign in to comment.