Fix ancient bug in parsing of BRE-mode regular expressions.
authorTom Lane <[email protected]>
Fri, 8 Jan 2021 17:16:00 +0000 (12:16 -0500)
committerTom Lane <[email protected]>
Fri, 8 Jan 2021 17:16:00 +0000 (12:16 -0500)
brenext(), when parsing a '*' quantifier, forgot to return any "value"
for the token; per the equivalent case in next(), it should return
value 1 to indicate that greedy rather than non-greedy behavior is
wanted.  The result is that the compiled regexp could behave like 'x*?'
rather than the intended 'x*', if we were unlucky enough to have
a zero in v->nextvalue at this point.  That seems to happen with some
reliability if we have '.*' at the beginning of a BRE-mode regexp,
although that depends on the initial contents of a stack-allocated
struct, so it's not guaranteed to fail.

Found by Alexander Lakhin using valgrind testing.  This bug seems
to be aboriginal in Spencer's code, so back- all the way.

Discussion: https://postgr.es/m/16814-6c5e3edd2bdf0d50@postgresql.org

src/backend/regex/regc_lex.c
src/test/modules/test_regex/expected/test_regex.out
src/test/modules/test_regex/sql/test_regex.sql

index 38617b79fd146df87158e2f033fdc21b16ec7a10..ca2bce48312aab1709389eca3a84b87adf6b8b8c 100644 (file)
@@ -994,7 +994,7 @@ brenext(struct vars *v,
        case CHR('*'):
            if (LASTTYPE(EMPTY) || LASTTYPE('(') || LASTTYPE('^'))
                RETV(PLAIN, c);
-           RET('*');
+           RETV('*', 1);
            break;
        case CHR('['):
            if (HAVE(6) && *(v->now + 0) == CHR('[') &&
index ed1b0cbdb9b11819ee66b4c7bfd355d325d6a3c1..0dc2265d8b2ddeddeaa9ed1f6a92e63a842e7181 100644 (file)
@@ -614,6 +614,14 @@ ERROR:  invalid regular expression: quantifier operand invalid
 -- expectError 7.15 -      a*+ BADRPT
 select * from test_regex('a*+', '', '-');
 ERROR:  invalid regular expression: quantifier operand invalid
+-- test for ancient brenext() bug; not currently in Tcl
+select * from test_regex('.*b', 'aaabbb', 'b');
+ test_regex 
+------------
+ {0}
+ {aaabbb}
+(2 rows)
+
 -- doing 8 "braces"
 -- expectMatch 8.1  NQ     "a{0,1}"    ""  ""
 select * from test_regex('a{0,1}', '', 'NQ');
index 4676cd1a06075c50c0770c42fae72d50509ffd07..1a2bfa623572768b5a6638eeb76a603ac68209e5 100644 (file)
@@ -214,6 +214,8 @@ select * from test_regex('a?*', '', '-');
 select * from test_regex('a+*', '', '-');
 -- expectError 7.15 -      a*+ BADRPT
 select * from test_regex('a*+', '', '-');
+-- test for ancient brenext() bug; not currently in Tcl
+select * from test_regex('.*b', 'aaabbb', 'b');
 
 -- doing 8 "braces"