Skip to content

Commit

Permalink
Merge pull request #51347 from yuzefovich/backport20.1-51303
Browse files Browse the repository at this point in the history
release-20.1: builtins: fix possible out of bounds in regexp_replace
  • Loading branch information
yuzefovich authored Jul 20, 2020
2 parents a8a4b63 + 816ee1f commit 1554f94
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
16 changes: 16 additions & 0 deletions pkg/sql/logictest/testdata/logic_test/builtin_function
Original file line number Diff line number Diff line change
Expand Up @@ -1233,6 +1233,22 @@ SELECT regexp_replace('ReRe','R(e)','1\\1','g');
----
1\11\1

# Regression test for #51289.
query T
SELECT regexp_replace('TIMESTAMP(6)', '.*(\((\d+)\))?.*', '\2')
----
·

query T
SELECT regexp_replace('TIMESTAMP(6)', '.*(\((\d+)\)).*', '\2')
----
6

query T
SELECT regexp_replace('TIMESTAMP(6)', '.*(\((\d+)\)?).*', '\2')
----
6

query B
SELECT unique_rowid() < unique_rowid()
----
Expand Down
15 changes: 10 additions & 5 deletions pkg/sql/sem/builtins/builtins.go
Original file line number Diff line number Diff line change
Expand Up @@ -4986,11 +4986,16 @@ func regexpReplace(ctx *tree.EvalContext, s, pattern, to, sqlFlags string) (tree
// & refers to the entire match.
newString.WriteString(s[matchStart:matchEnd])
} else {
idx := int(to[i] - '0')
// regexpReplace expects references to "out-of-bounds" capture groups
// to be ignored.
if 2*idx < len(matchIndex) {
newString.WriteString(s[matchIndex[2*idx]:matchIndex[2*idx+1]])
captureGroupNumber := int(to[i] - '0')
// regexpReplace expects references to "out-of-bounds"
// and empty (when the corresponding match indices
// are negative) capture groups to be ignored.
if matchIndexPos := 2 * captureGroupNumber; matchIndexPos < len(matchIndex) {
startPos := matchIndex[matchIndexPos]
endPos := matchIndex[matchIndexPos+1]
if startPos >= 0 {
newString.WriteString(s[startPos:endPos])
}
}
}
}
Expand Down

0 comments on commit 1554f94

Please sign in to comment.