Skip to content

Commit 640b47f

Browse files
committed
gh-163137: Fix quadratic time in fnmatch.translate() for unclosed '['
Each '[' scanned to the end of the pattern looking for ']'. When there is no ']' after the current position, that scan always fails, and so does the scan for every later '['. Find the last ']' once and treat any '[' after it as a literal without scanning.
1 parent 128b502 commit 640b47f

3 files changed

Lines changed: 20 additions & 0 deletions

File tree

‎Lib/fnmatch.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@ def _translate(pat, star, question_mark):
9898
star_indices = []
9999

100100
i, n = 0, len(pat)
101+
last_close = pat.rfind(']')
101102
while i < n:
102103
c = pat[i]
103104
i = i+1
@@ -111,6 +112,10 @@ def _translate(pat, star, question_mark):
111112
elif c == '?':
112113
add(question_mark)
113114
elif c == '[':
115+
if i > last_close:
116+
# No ']' after this point: every later '[' is a literal too.
117+
add('\\[')
118+
continue
114119
j = i
115120
if j < n and pat[j] == '!':
116121
j = j+1

‎Lib/test/test_fnmatch.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,18 @@ def test_translate(self):
248248
self.assertTrue(re.match(fatre, 'cbabcaxc'))
249249
self.assertFalse(re.match(fatre, 'dabccbad'))
250250

251+
def test_translate_unclosed_brackets(self):
252+
# An unclosed '[' is a literal. Many of them used to take quadratic
253+
# time, because each one scanned to the end of the pattern (gh-163137).
254+
self.assertEqual(translate('[!a[b'), r'(?s:\[!a\[b)\z')
255+
self.assertEqual(translate('[a]b[c'), r'(?s:[a]b\[c)\z')
256+
self.assertEqual(translate(']['), r'(?s:\]\[)\z')
257+
self.assertEqual(translate('[!]'), r'(?s:\[!\])\z')
258+
self.assertEqual(translate('a[]b['), r'(?s:a\[\]b\[)\z')
259+
n = 30_000
260+
self.assertEqual(translate('[!' * n), '(?s:' + r'\[!' * n + r')\z')
261+
self.assertTrue(fnmatch('[!' * n, '[!' * n))
262+
251263
def test_translate_wildcards(self):
252264
for pattern, expect in [
253265
('ab*', r'(?s:ab.*)\z'),
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix quadratic time in :func:`fnmatch.translate` and the functions that use
2+
it, such as :func:`fnmatch.fnmatch`, :func:`glob.translate` and
3+
:meth:`pathlib.PurePath.full_match`, for patterns with many unclosed ``[``.

0 commit comments

Comments
 (0)