blob: 9bf290d8d5a1f7994ec40bad6bdea76d425bc834 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001"""This module includes tests of the code object representation.
2
3>>> def f(x):
4... def g(y):
5... return x + y
6... return g
7...
8
Neal Norwitz221085d2007-02-25 20:55:47 +00009>>> dump(f.__code__)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010name: f
11argcount: 1
Pablo Galindo8c77b8c2019-04-29 13:36:57 +010012posonlyargcount: 0
Guido van Rossum4f72a782006-10-27 23:31:49 +000013kwonlyargcount: 0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000014names: ()
15varnames: ('x', 'g')
16cellvars: ('x',)
17freevars: ()
18nlocals: 2
19flags: 3
Antoine Pitrou86a36b52011-11-25 18:56:07 +010020consts: ('None', '<code object g>', "'f.<locals>.g'")
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000021
Neal Norwitz221085d2007-02-25 20:55:47 +000022>>> dump(f(4).__code__)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000023name: g
24argcount: 1
Pablo Galindo8c77b8c2019-04-29 13:36:57 +010025posonlyargcount: 0
Guido van Rossum4f72a782006-10-27 23:31:49 +000026kwonlyargcount: 0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000027names: ()
28varnames: ('y',)
29cellvars: ()
30freevars: ('x',)
31nlocals: 1
32flags: 19
33consts: ('None',)
34
35>>> def h(x, y):
36... a = x + y
37... b = x - y
38... c = a * b
39... return c
Tim Peters536cf992005-12-25 23:18:31 +000040...
Guido van Rossum4f72a782006-10-27 23:31:49 +000041
Neal Norwitz221085d2007-02-25 20:55:47 +000042>>> dump(h.__code__)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000043name: h
44argcount: 2
Pablo Galindo8c77b8c2019-04-29 13:36:57 +010045posonlyargcount: 0
Guido van Rossum4f72a782006-10-27 23:31:49 +000046kwonlyargcount: 0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000047names: ()
48varnames: ('x', 'y', 'a', 'b', 'c')
49cellvars: ()
50freevars: ()
51nlocals: 5
52flags: 67
53consts: ('None',)
54
55>>> def attrs(obj):
Guido van Rossum7131f842007-02-09 20:13:25 +000056... print(obj.attr1)
57... print(obj.attr2)
58... print(obj.attr3)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000059
Neal Norwitz221085d2007-02-25 20:55:47 +000060>>> dump(attrs.__code__)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000061name: attrs
62argcount: 1
Pablo Galindo8c77b8c2019-04-29 13:36:57 +010063posonlyargcount: 0
Guido van Rossum4f72a782006-10-27 23:31:49 +000064kwonlyargcount: 0
Georg Brandl88fc6642007-02-09 21:28:07 +000065names: ('print', 'attr1', 'attr2', 'attr3')
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000066varnames: ('obj',)
67cellvars: ()
68freevars: ()
69nlocals: 1
70flags: 67
71consts: ('None',)
72
Thomas Wouters0e3f5912006-08-11 14:57:12 +000073>>> def optimize_away():
74... 'doc string'
75... 'not a docstring'
76... 53
Guido van Rossume2a383d2007-01-15 16:59:06 +000077... 0x53
Thomas Wouters0e3f5912006-08-11 14:57:12 +000078
Neal Norwitz221085d2007-02-25 20:55:47 +000079>>> dump(optimize_away.__code__)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000080name: optimize_away
81argcount: 0
Pablo Galindo8c77b8c2019-04-29 13:36:57 +010082posonlyargcount: 0
Guido van Rossum4f72a782006-10-27 23:31:49 +000083kwonlyargcount: 0
Thomas Wouters0e3f5912006-08-11 14:57:12 +000084names: ()
85varnames: ()
86cellvars: ()
87freevars: ()
88nlocals: 0
89flags: 67
90consts: ("'doc string'", 'None')
91
Guido van Rossum4f72a782006-10-27 23:31:49 +000092>>> def keywordonly_args(a,b,*,k1):
93... return a,b,k1
94...
95
Neal Norwitz221085d2007-02-25 20:55:47 +000096>>> dump(keywordonly_args.__code__)
Guido van Rossum4f72a782006-10-27 23:31:49 +000097name: keywordonly_args
98argcount: 2
Pablo Galindo8c77b8c2019-04-29 13:36:57 +010099posonlyargcount: 0
Guido van Rossum4f72a782006-10-27 23:31:49 +0000100kwonlyargcount: 1
101names: ()
102varnames: ('a', 'b', 'k1')
103cellvars: ()
104freevars: ()
105nlocals: 3
106flags: 67
107consts: ('None',)
108
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100109>>> def posonly_args(a,b,/,c):
110... return a,b,c
111...
112
113>>> dump(posonly_args.__code__)
114name: posonly_args
115argcount: 1
116posonlyargcount: 2
117kwonlyargcount: 0
118names: ()
119varnames: ('a', 'b', 'c')
120cellvars: ()
121freevars: ()
122nlocals: 3
123flags: 67
124consts: ('None',)
125
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000126"""
127
Nick Coghlan078f1812017-12-03 11:12:20 +1000128import inspect
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +0300129import sys
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700130import threading
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000131import unittest
Collin Winter4222e9c2010-03-18 22:46:40 +0000132import weakref
Pablo Galindof00828a2019-05-09 16:52:02 +0100133import opcode
Victor Stinnera4b091e2017-06-23 15:08:55 +0200134try:
135 import ctypes
136except ImportError:
137 ctypes = None
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700138from test.support import (run_doctest, run_unittest, cpython_only,
139 check_impl_detail)
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000140
Collin Winter4222e9c2010-03-18 22:46:40 +0000141
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000142def consts(t):
143 """Yield a doctest-safe sequence of object reprs."""
144 for elt in t:
145 r = repr(elt)
146 if r.startswith("<code object"):
147 yield "<code object %s>" % elt.co_name
148 else:
149 yield r
150
151def dump(co):
152 """Print out a text representation of a code object."""
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100153 for attr in ["name", "argcount", "posonlyargcount",
154 "kwonlyargcount", "names", "varnames",
Guido van Rossum4f72a782006-10-27 23:31:49 +0000155 "cellvars", "freevars", "nlocals", "flags"]:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000156 print("%s: %s" % (attr, getattr(co, "co_" + attr)))
157 print("consts:", tuple(consts(co.co_consts)))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000158
Nick Coghlan078f1812017-12-03 11:12:20 +1000159# Needed for test_closure_injection below
160# Defined at global scope to avoid implicitly closing over __class__
161def external_getitem(self, i):
162 return f"Foreign getitem: {super().__getitem__(i)}"
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000163
164class CodeTest(unittest.TestCase):
165
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200166 @cpython_only
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000167 def test_newempty(self):
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200168 import _testcapi
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000169 co = _testcapi.code_newempty("filename", "funcname", 15)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000170 self.assertEqual(co.co_filename, "filename")
171 self.assertEqual(co.co_name, "funcname")
172 self.assertEqual(co.co_firstlineno, 15)
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000173
Nick Coghlan078f1812017-12-03 11:12:20 +1000174 @cpython_only
175 def test_closure_injection(self):
176 # From https://bugs.python.org/issue32176
177 from types import FunctionType, CodeType
178
179 def create_closure(__class__):
180 return (lambda: __class__).__closure__
181
182 def new_code(c):
183 '''A new code object with a __class__ cell added to freevars'''
184 return CodeType(
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100185 c.co_argcount, c.co_posonlyargcount, c.co_kwonlyargcount, c.co_nlocals,
Nick Coghlan078f1812017-12-03 11:12:20 +1000186 c.co_stacksize, c.co_flags, c.co_code, c.co_consts, c.co_names,
187 c.co_varnames, c.co_filename, c.co_name, c.co_firstlineno,
188 c.co_lnotab, c.co_freevars + ('__class__',), c.co_cellvars)
189
190 def add_foreign_method(cls, name, f):
191 code = new_code(f.__code__)
192 assert not f.__closure__
193 closure = create_closure(cls)
194 defaults = f.__defaults__
195 setattr(cls, name, FunctionType(code, globals(), name, defaults, closure))
196
197 class List(list):
198 pass
199
200 add_foreign_method(List, "__getitem__", external_getitem)
201
202 # Ensure the closure injection actually worked
203 function = List.__getitem__
204 class_ref = function.__closure__[0].cell_contents
205 self.assertIs(class_ref, List)
206
207 # Ensure the code correctly indicates it accesses a free variable
208 self.assertFalse(function.__code__.co_flags & inspect.CO_NOFREE,
209 hex(function.__code__.co_flags))
210
211 # Ensure the zero-arg super() call in the injected method works
212 obj = List([1, 2, 3])
213 self.assertEqual(obj[0], "Foreign getitem: 1")
Serhiy Storchaka09f3d082016-10-04 18:17:22 +0300214
215def isinterned(s):
216 return s is sys.intern(('_' + s + '_')[1:-1])
217
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +0300218class CodeConstsTest(unittest.TestCase):
219
220 def find_const(self, consts, value):
221 for v in consts:
222 if v == value:
223 return v
Serhiy Storchaka09f3d082016-10-04 18:17:22 +0300224 self.assertIn(value, consts) # raises an exception
225 self.fail('Should never be reached')
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +0300226
227 def assertIsInterned(self, s):
Serhiy Storchaka09f3d082016-10-04 18:17:22 +0300228 if not isinterned(s):
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +0300229 self.fail('String %r is not interned' % (s,))
230
Serhiy Storchaka09f3d082016-10-04 18:17:22 +0300231 def assertIsNotInterned(self, s):
232 if isinterned(s):
233 self.fail('String %r is interned' % (s,))
234
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +0300235 @cpython_only
236 def test_interned_string(self):
237 co = compile('res = "str_value"', '?', 'exec')
238 v = self.find_const(co.co_consts, 'str_value')
239 self.assertIsInterned(v)
240
241 @cpython_only
242 def test_interned_string_in_tuple(self):
243 co = compile('res = ("str_value",)', '?', 'exec')
244 v = self.find_const(co.co_consts, ('str_value',))
245 self.assertIsInterned(v[0])
246
247 @cpython_only
248 def test_interned_string_in_frozenset(self):
249 co = compile('res = a in {"str_value"}', '?', 'exec')
250 v = self.find_const(co.co_consts, frozenset(('str_value',)))
251 self.assertIsInterned(tuple(v)[0])
252
253 @cpython_only
254 def test_interned_string_default(self):
255 def f(a='str_value'):
256 return a
257 self.assertIsInterned(f())
258
Serhiy Storchaka09f3d082016-10-04 18:17:22 +0300259 @cpython_only
260 def test_interned_string_with_null(self):
261 co = compile(r'res = "str\0value!"', '?', 'exec')
262 v = self.find_const(co.co_consts, 'str\0value!')
263 self.assertIsNotInterned(v)
264
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000265
Collin Winter4222e9c2010-03-18 22:46:40 +0000266class CodeWeakRefTest(unittest.TestCase):
267
268 def test_basic(self):
269 # Create a code object in a clean environment so that we know we have
270 # the only reference to it left.
271 namespace = {}
272 exec("def f(): pass", globals(), namespace)
273 f = namespace["f"]
274 del namespace
275
276 self.called = False
277 def callback(code):
278 self.called = True
279
280 # f is now the last reference to the function, and through it, the code
281 # object. While we hold it, check that we can create a weakref and
282 # deref it. Then delete it, and check that the callback gets called and
283 # the reference dies.
284 coderef = weakref.ref(f.__code__, callback)
285 self.assertTrue(bool(coderef()))
286 del f
287 self.assertFalse(bool(coderef()))
288 self.assertTrue(self.called)
289
290
Victor Stinnera4b091e2017-06-23 15:08:55 +0200291if check_impl_detail(cpython=True) and ctypes is not None:
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700292 py = ctypes.pythonapi
293 freefunc = ctypes.CFUNCTYPE(None,ctypes.c_voidp)
294
295 RequestCodeExtraIndex = py._PyEval_RequestCodeExtraIndex
296 RequestCodeExtraIndex.argtypes = (freefunc,)
297 RequestCodeExtraIndex.restype = ctypes.c_ssize_t
298
299 SetExtra = py._PyCode_SetExtra
300 SetExtra.argtypes = (ctypes.py_object, ctypes.c_ssize_t, ctypes.c_voidp)
301 SetExtra.restype = ctypes.c_int
302
303 GetExtra = py._PyCode_GetExtra
304 GetExtra.argtypes = (ctypes.py_object, ctypes.c_ssize_t,
305 ctypes.POINTER(ctypes.c_voidp))
306 GetExtra.restype = ctypes.c_int
307
308 LAST_FREED = None
309 def myfree(ptr):
310 global LAST_FREED
311 LAST_FREED = ptr
312
313 FREE_FUNC = freefunc(myfree)
314 FREE_INDEX = RequestCodeExtraIndex(FREE_FUNC)
315
316 class CoExtra(unittest.TestCase):
317 def get_func(self):
318 # Defining a function causes the containing function to have a
319 # reference to the code object. We need the code objects to go
320 # away, so we eval a lambda.
321 return eval('lambda:42')
322
323 def test_get_non_code(self):
324 f = self.get_func()
325
326 self.assertRaises(SystemError, SetExtra, 42, FREE_INDEX,
327 ctypes.c_voidp(100))
328 self.assertRaises(SystemError, GetExtra, 42, FREE_INDEX,
329 ctypes.c_voidp(100))
330
331 def test_bad_index(self):
332 f = self.get_func()
333 self.assertRaises(SystemError, SetExtra, f.__code__,
334 FREE_INDEX+100, ctypes.c_voidp(100))
335 self.assertEqual(GetExtra(f.__code__, FREE_INDEX+100,
336 ctypes.c_voidp(100)), 0)
337
338 def test_free_called(self):
339 # Verify that the provided free function gets invoked
340 # when the code object is cleaned up.
341 f = self.get_func()
342
343 SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(100))
344 del f
345 self.assertEqual(LAST_FREED, 100)
346
347 def test_get_set(self):
348 # Test basic get/set round tripping.
349 f = self.get_func()
350
351 extra = ctypes.c_voidp()
352
353 SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(200))
354 # reset should free...
355 SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(300))
356 self.assertEqual(LAST_FREED, 200)
357
358 extra = ctypes.c_voidp()
359 GetExtra(f.__code__, FREE_INDEX, extra)
360 self.assertEqual(extra.value, 300)
361 del f
362
363 def test_free_different_thread(self):
364 # Freeing a code object on a different thread then
365 # where the co_extra was set should be safe.
366 f = self.get_func()
367 class ThreadTest(threading.Thread):
368 def __init__(self, f, test):
369 super().__init__()
370 self.f = f
371 self.test = test
372 def run(self):
373 del self.f
374 self.test.assertEqual(LAST_FREED, 500)
375
376 SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(500))
377 tt = ThreadTest(f, self)
378 del f
379 tt.start()
380 tt.join()
381 self.assertEqual(LAST_FREED, 500)
382
Pablo Galindof00828a2019-05-09 16:52:02 +0100383 @cpython_only
384 def test_clean_stack_on_return(self):
385
386 def f(x):
387 return x
388
389 code = f.__code__
390 ct = type(f.__code__)
391
392 # Insert an extra LOAD_FAST, this duplicates the value of
393 # 'x' in the stack, leaking it if the frame is not properly
394 # cleaned up upon exit.
395
396 bytecode = list(code.co_code)
397 bytecode.insert(-2, opcode.opmap['LOAD_FAST'])
398 bytecode.insert(-2, 0)
399
400 c = ct(code.co_argcount, code.co_posonlyargcount,
401 code.co_kwonlyargcount, code.co_nlocals, code.co_stacksize+1,
402 code.co_flags, bytes(bytecode),
403 code.co_consts, code.co_names, code.co_varnames,
404 code.co_filename, code.co_name, code.co_firstlineno,
405 code.co_lnotab, code.co_freevars, code.co_cellvars)
406 new_function = type(f)(c, f.__globals__, 'nf', f.__defaults__, f.__closure__)
407
408 class Var:
409 pass
410 the_object = Var()
411 var = weakref.ref(the_object)
412
413 new_function(the_object)
414
415 # Check if the_object is leaked
416 del the_object
417 assert var() is None
418
419
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000420def test_main(verbose=None):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000421 from test import test_code
422 run_doctest(test_code, verbose)
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700423 tests = [CodeTest, CodeConstsTest, CodeWeakRefTest]
Victor Stinnera4b091e2017-06-23 15:08:55 +0200424 if check_impl_detail(cpython=True) and ctypes is not None:
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700425 tests.append(CoExtra)
426 run_unittest(*tests)
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000427
Collin Winter4222e9c2010-03-18 22:46:40 +0000428if __name__ == "__main__":
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000429 test_main()