summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorR. David Murray <rdmurray@bitdance.com>2010-07-09 12:23:21 (GMT)
committerR. David Murray <rdmurray@bitdance.com>2010-07-09 12:23:21 (GMT)
commitea340a317a412148333c4c48807efc3af18ae4b4 (patch)
treed55f9db8eaa857d0d76df7f97baf849c1c47d06d
parentfacb0e9a764679d9a1bb76246a9c06d6f136602c (diff)
downloadcpython-ea340a317a412148333c4c48807efc3af18ae4b4.zip
cpython-ea340a317a412148333c4c48807efc3af18ae4b4.tar.gz
cpython-ea340a317a412148333c4c48807efc3af18ae4b4.tar.bz2
7846: limit fnmatch pattern cache to _MAXCACHE=100 entries.
Patch by Andrew Clegg.
-rw-r--r--Lib/fnmatch.py3
-rw-r--r--Lib/test/test_fnmatch.py17
-rw-r--r--Misc/ACKS1
-rw-r--r--Misc/NEWS2
4 files changed, 22 insertions, 1 deletions
diff --git a/Lib/fnmatch.py b/Lib/fnmatch.py
index 30c0a92..26ae4cc 100644
--- a/Lib/fnmatch.py
+++ b/Lib/fnmatch.py
@@ -16,6 +16,7 @@ __all__ = ["filter", "fnmatch","fnmatchcase","translate"]
_cache = {} # Maps text patterns to compiled regexen.
_cacheb = {} # Ditto for bytes patterns.
+_MAXCACHE = 100 # Maximum size of caches
def fnmatch(name, pat):
"""Test whether FILENAME matches PATTERN.
@@ -48,6 +49,8 @@ def _compile_pattern(pat):
res = bytes(res_str, 'ISO-8859-1')
else:
res = translate(pat)
+ if len(cache) >= _MAXCACHE:
+ cache.clear()
cache[pat] = regex = re.compile(res)
return regex.match
diff --git a/Lib/test/test_fnmatch.py b/Lib/test/test_fnmatch.py
index 6d2f9ad..81b9ce6 100644
--- a/Lib/test/test_fnmatch.py
+++ b/Lib/test/test_fnmatch.py
@@ -3,7 +3,7 @@
from test import support
import unittest
-from fnmatch import fnmatch, fnmatchcase
+from fnmatch import fnmatch, fnmatchcase, _MAXCACHE, _cache, _cacheb
class FnmatchTestCase(unittest.TestCase):
@@ -60,6 +60,21 @@ class FnmatchTestCase(unittest.TestCase):
self.check_match(b'test\xff', b'te*\xff')
self.check_match(b'foo\nbar', b'foo*')
+ def test_cache_clearing(self):
+ # check that caches do not grow too large
+ # http://bugs.python.org/issue7846
+
+ # string pattern cache
+ for i in range(_MAXCACHE + 1):
+ fnmatch('foo', '?' * i)
+
+ self.assertLessEqual(len(_cache), _MAXCACHE)
+
+ # bytes pattern cache
+ for i in range(_MAXCACHE + 1):
+ fnmatch(b'foo', b'?' * i)
+ self.assertLessEqual(len(_cacheb), _MAXCACHE)
+
def test_main():
support.run_unittest(FnmatchTestCase)
diff --git a/Misc/ACKS b/Misc/ACKS
index ec42bf9..023890d 100644
--- a/Misc/ACKS
+++ b/Misc/ACKS
@@ -146,6 +146,7 @@ Vadim Chugunov
David Cinege
Mike Clarkson
Brad Clements
+Andrew Clegg
Steve Clift
Nick Coghlan
Josh Cogliati
diff --git a/Misc/NEWS b/Misc/NEWS
index 729c010..b63c84c 100644
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -470,6 +470,8 @@ C-API
Library
-------
+- Issue #7646: The fnmatch pattern cache no longer grows without bound.
+
- Issue #9136: Fix 'dictionary changed size during iteration'
RuntimeError produced when profiling the decimal module. This was
due to a dangerous iteration over 'locals()' in Context.__init__.