Skip to content

Commit

Permalink
Merge pull request #190 from supermetrics-public/fix/RegexSegmentatio…
Browse files Browse the repository at this point in the history
…nFault

Fix segmentation fault when matching regex string against non-string values
  • Loading branch information
crocodele authored Jan 14, 2025
2 parents 793914e + 1cbc017 commit ad6f53f
Show file tree
Hide file tree
Showing 2 changed files with 105 additions and 2 deletions.
29 changes: 27 additions & 2 deletions src/jsonpath/interpreter.c
Original file line number Diff line number Diff line change
Expand Up @@ -285,14 +285,39 @@ static bool compare_rgxp(zval* lh, zval* rh) {
return false;
}

zend_string* zs_lh;
if (Z_TYPE_P(lh) == IS_STRING) {
zs_lh = zend_string_copy(Z_STR_P(lh));
} else if (Z_TYPE_P(lh) == IS_ARRAY) {
// Skip silently
return false;
} else if (Z_TYPE_P(lh) == IS_OBJECT) {
if (!zend_hash_str_exists(&Z_OBJCE_P(lh)->function_table, "__tostring", sizeof("__tostring") - 1)) {
// Object doesn't provide a __toString() method, skip silently
return false;
}

zs_lh = zval_get_string(lh);
} else if (Z_TYPE_P(lh) == IS_NULL) {
zs_lh = zend_string_init("", 0, 0);
} else if (Z_TYPE_P(lh) == IS_TRUE) {
zs_lh = zend_string_init("true", 4, 0);
} else if (Z_TYPE_P(lh) == IS_FALSE) {
zs_lh = zend_string_init("false", 5, 0);
} else {
zs_lh = zval_get_string(lh);
if (!zs_lh) {
throw_jsonpath_exception("Failed to convert value to string for regex matching");
return false;
}
}

zval retval;
zval subpats;

ZVAL_NULL(&retval);
ZVAL_NULL(&subpats);

zend_string* zs_lh = zend_string_copy(Z_STR_P(lh));

#if PHP_VERSION_ID >= 80400
php_pcre_match_impl(pce, zs_lh, &retval, &subpats, 0, 0, 0);
#else
Expand Down
78 changes: 78 additions & 0 deletions tests/regex/004.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
--TEST--
Test regex comparison against non-string values
--SKIPIF--
<?php if (!extension_loaded("jsonpath")) print "skip"; ?>
--FILE--
<?php

$byRef = 44;

$data = [
'test' => [
[
'id' => 1,
'quantity' => 25,
],
[
'id' => 2,
'quantity' => 15,
],
[
'id' => 3,
'quantity' => false,
],
[
'id' => 4,
'quantity' => true,
],
[
'id' => 5,
'quantity' => null,
],
[
'id' => 6,
'quantity' => 107.3,
],
[
'id' => 7,
'quantity' => ['foo'],
],
[
'id' => 8,
'quantity' => new WeakMap(),
],
[
'id' => 9,
'quantity' => &$byRef,
],
],
];

$jsonPath = new \JsonPath\JsonPath();
$result = $jsonPath->find($data, '$.test[?(@.quantity =~ /^[0-9]+$/)]');

var_dump($result);
--EXPECT--
array(3) {
[0]=>
array(2) {
["id"]=>
int(1)
["quantity"]=>
int(25)
}
[1]=>
array(2) {
["id"]=>
int(2)
["quantity"]=>
int(15)
}
[2]=>
array(2) {
["id"]=>
int(9)
["quantity"]=>
&int(44)
}
}

0 comments on commit ad6f53f

Please sign in to comment.