Debian Codegraph @

Lib/test/test_capi/test_mem.py

raw
1 import re
2 import textwrap
3 import unittest
4
5
6 from test import support
7 from test.support import import_helper, requires_subprocess
8 from test.support.script_helper import assert_python_failure, assert_python_ok
9
10
11 # Skip this test if the _testcapi and _testinternalcapi extensions are not
12 # available.
13 _testcapi = import_helper.import_module('_testcapi')
14 _testinternalcapi = import_helper.import_module('_testinternalcapi')
15
16 @requires_subprocess()
17 class PyMemDebugTests(unittest.TestCase):
18 PYTHONMALLOC = 'debug'
19 # '0x04c06e0' or '04C06E0'
20 PTR_REGEX = r'(?:0x)?[0-9a-fA-F]+'
21
22 def check(self, code):
23 with support.SuppressCrashReport():
24 out = assert_python_failure(
25 '-c', code,
26 PYTHONMALLOC=self.PYTHONMALLOC,
27 # FreeBSD: instruct jemalloc to not fill freed() memory
28 # with junk byte 0x5a, see JEMALLOC(3)
29 MALLOC_CONF="junk:false",
30 )
31 stderr = out.err
32 return stderr.decode('ascii', 'replace')
33
34 def test_buffer_overflow(self):
35 out = self.check('import _testcapi; _testcapi.pymem_buffer_overflow()')
36 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
37 r" 16 bytes originally requested\n"
38 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
39 r" The [0-9] pad bytes at tail={ptr} are not all FORBIDDENBYTE \(0x[0-9a-f]{{2}}\):\n"
40 r" at tail\+0: 0x78 \*\*\* OUCH\n"
41 r" at tail\+1: 0xfd\n"
42 r" at tail\+2: 0xfd\n"
43 r" .*\n"
44 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
45 r" Data at p: cd cd cd .*\n"
46 r"\n"
47 r"Enable tracemalloc to get the memory block allocation traceback\n"
48 r"\n"
49 r"Fatal Python error: _PyMem_DebugRawFree: bad trailing pad byte")
50 regex = regex.format(ptr=self.PTR_REGEX)
51 regex = re.compile(regex, flags=re.DOTALL)
52 self.assertRegex(out, regex)
53
54 def test_api_misuse(self):
55 out = self.check('import _testcapi; _testcapi.pymem_api_misuse()')
56 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
57 r" 16 bytes originally requested\n"
58 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
59 r" The [0-9] pad bytes at tail={ptr} are FORBIDDENBYTE, as expected.\n"
60 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
61 r" Data at p: cd cd cd .*\n"
62 r"\n"
63 r"Enable tracemalloc to get the memory block allocation traceback\n"
64 r"\n"
65 r"Fatal Python error: _PyMem_DebugRawFree: bad ID: Allocated using API 'm', verified using API 'r'\n")
66 regex = regex.format(ptr=self.PTR_REGEX)
67 self.assertRegex(out, regex)
68
69 def check_malloc_without_gil(self, code):
70 out = self.check(code)
71 expected = ('Fatal Python error: _PyMem_DebugMalloc: '
72 'Python memory allocator called without holding the GIL')
73 self.assertIn(expected, out)
74
75 def test_pymem_malloc_without_gil(self):
76 # Debug hooks must raise an error if PyMem_Malloc() is called
77 # without holding the GIL
78 code = 'import _testcapi; _testcapi.pymem_malloc_without_gil()'
79 self.check_malloc_without_gil(code)
80
81 def test_pyobject_malloc_without_gil(self):
82 # Debug hooks must raise an error if PyObject_Malloc() is called
83 # without holding the GIL
84 code = 'import _testcapi; _testcapi.pyobject_malloc_without_gil()'
85 self.check_malloc_without_gil(code)
86
87 def check_pyobject_is_freed(self, func_name):
88 code = textwrap.dedent(f'''
89 import gc, os, sys, _testinternalcapi
90 # Disable the GC to avoid crash on GC collection
91 gc.disable()
92 _testinternalcapi.{func_name}()
93 # Exit immediately to avoid a crash while deallocating
94 # the invalid object
95 os._exit(0)
96 ''')
97 assert_python_ok(
98 '-c', code,
99 PYTHONMALLOC=self.PYTHONMALLOC,
100 MALLOC_CONF="junk:false",
101 )
102
103 def test_pyobject_null_is_freed(self):
104 self.check_pyobject_is_freed('check_pyobject_null_is_freed')
105
106 def test_pyobject_uninitialized_is_freed(self):
107 self.check_pyobject_is_freed('check_pyobject_uninitialized_is_freed')
108
109 def test_pyobject_forbidden_bytes_is_freed(self):
110 self.check_pyobject_is_freed('check_pyobject_forbidden_bytes_is_freed')
111
112 def test_pyobject_freed_is_freed(self):
113 self.check_pyobject_is_freed('check_pyobject_freed_is_freed')
114
115 # Python built with Py_TRACE_REFS fail with a fatal error in
116 # _PyRefchain_Trace() on memory allocation error.
117 @unittest.skipIf(support.Py_TRACE_REFS, 'cannot test Py_TRACE_REFS build')
118 def test_set_nomemory(self):
119 code = """if 1:
120 import _testcapi
121
122 class C(): pass
123
124 # The first loop tests both functions and that remove_mem_hooks()
125 # can be called twice in a row. The second loop checks a call to
126 # set_nomemory() after a call to remove_mem_hooks(). The third
127 # loop checks the start and stop arguments of set_nomemory().
128 for outer_cnt in range(1, 4):
129 start = 10 * outer_cnt
130 for j in range(100):
131 if j == 0:
132 if outer_cnt != 3:
133 _testcapi.set_nomemory(start)
134 else:
135 _testcapi.set_nomemory(start, start + 1)
136 try:
137 C()
138 except MemoryError as e:
139 if outer_cnt != 3:
140 _testcapi.remove_mem_hooks()
141 print('MemoryError', outer_cnt, j)
142 _testcapi.remove_mem_hooks()
143 break
144 """
145 rc, out, err = assert_python_ok('-c', code)
146 lines = out.splitlines()
147 for i, line in enumerate(lines, 1):
148 self.assertIn(b'MemoryError', out)
149 *_, count = line.split(b' ')
150 count = int(count)
151 self.assertLessEqual(count, i*10)
152 self.assertGreaterEqual(count, i*10-4)
153
154
155 # free-threading requires mimalloc (not malloc)
156 @support.requires_gil_enabled()
157 class PyMemMallocDebugTests(PyMemDebugTests):
158 PYTHONMALLOC = 'malloc_debug'
159
160
161 @unittest.skipUnless(support.with_pymalloc(), 'need pymalloc')
162 class PyMemPymallocDebugTests(PyMemDebugTests):
163 PYTHONMALLOC = 'pymalloc_debug'
164
165
166 @unittest.skipUnless(support.with_mimalloc(), 'need mimaloc')
167 class PyMemMimallocDebugTests(PyMemDebugTests):
168 PYTHONMALLOC = 'mimalloc_debug'
169
170
171 @unittest.skipUnless(support.Py_DEBUG, 'need Py_DEBUG')
172 class PyMemDefaultTests(PyMemDebugTests):
173 # test default allocator of Python compiled in debug mode
174 PYTHONMALLOC = ''
175
176
177 if __name__ == "__main__":
178 unittest.main()