Debian Codegraph @

pypy/module/cpyext/pystate.py

raw symbols SCIP
1 from pypy.module.cpyext.api import (
2 cpython_api, CANNOT_FAIL, cpython_struct)
3 from pypy.module.cpyext.pyobject import PyObject, decref, make_ref, from_ref
4 from pypy.module.cpyext.modsupport import PyModuleDef
5 from pypy.interpreter.error import OperationError, oefmt
6 from rpython.rtyper.lltypesystem import rffi, lltype
7 from rpython.rlib import rthread
8 from rpython.rlib.objectmodel import we_are_translated
9 from rpython.rlib.rarithmetic import widen
10
11 PyInterpreterStateStruct = lltype.ForwardReference()
12 PyInterpreterState = lltype.Ptr(PyInterpreterStateStruct)
13 cpython_struct(
14 "PyInterpreterState",
15 [('next', PyInterpreterState),
16 ('modules_by_index', PyObject)],
17 PyInterpreterStateStruct)
18 PyThreadState = lltype.Ptr(cpython_struct(
19 "PyThreadState",
20 [('interp', PyInterpreterState),
21 ('dict', PyObject),
22 ('id', rffi.ULONGLONG),
23 ]))
24
25 class NoThreads(Exception):
26 pass
27
28 @cpython_api([], PyThreadState, error=CANNOT_FAIL, gil="release")
29 def PyEval_SaveThread(space):
30 """Release the global interpreter lock (if it has been created and thread
31 support is enabled) and reset the thread state to NULL, returning the
32 previous thread state. If the lock has been created,
33 the current thread must have acquired it. (This function is available even
34 when thread support is disabled at compile time.)"""
35 state = space.fromcache(InterpreterState)
36 ec = space.getexecutioncontext()
37 tstate = state._get_thread_state(space, ec).memory
38 ec.cpyext_threadstate_is_current = False
39 return tstate
40
41 @cpython_api([PyThreadState], lltype.Void, gil="acquire")
42 def PyEval_RestoreThread(space, tstate):
43 """Acquire the global interpreter lock (if it has been created and thread
44 support is enabled) and set the thread state to tstate, which must not be
45 NULL. If the lock has been created, the current thread must not have
46 acquired it, otherwise deadlock ensues. (This function is available even
47 when thread support is disabled at compile time.)"""
48 PyThreadState_Swap(space, tstate)
49
50 @cpython_api([], lltype.Void)
51 def PyEval_InitThreads(space):
52 if not space.config.translation.thread:
53 raise NoThreads
54 from pypy.module.thread import os_thread
55 os_thread.setup_threads(space)
56
57 @cpython_api([], rffi.INT_real, error=CANNOT_FAIL)
58 def PyEval_ThreadsInitialized(space):
59 if not space.config.translation.thread:
60 return 0
61 from pypy.module.thread import os_thread
62 return int(os_thread.threads_initialized(space))
63
64 # XXX: might be generally useful
65 def encapsulator(T, flavor='raw', dealloc=None):
66 class MemoryCapsule(object):
67 def __init__(self, space):
68 self.space = space
69 if space is not None:
70 self.memory = lltype.malloc(T, flavor=flavor)
71 else:
72 self.memory = lltype.nullptr(T)
73 def __del__(self):
74 if self.memory:
75 if dealloc and self.space:
76 dealloc(self.memory, self.space)
77 lltype.free(self.memory, flavor=flavor)
78 return MemoryCapsule
79
80 def ThreadState_dealloc(ts, space):
81 assert space is not None
82 decref(space, ts.c_dict)
83 ThreadStateCapsule = encapsulator(PyThreadState.TO,
84 dealloc=ThreadState_dealloc)
85
86 from pypy.interpreter.executioncontext import ExecutionContext
87
88 # Keep track of the ThreadStateCapsule for a particular execution context. The
89 # default is for new execution contexts not to have one; it is allocated on the
90 # first cpyext-based request for it.
91 ExecutionContext.cpyext_threadstate = ThreadStateCapsule(None)
92
93 # Also keep track of whether it has been initialized yet or not (None is a valid
94 # PyThreadState for an execution context to have, when the GIL has been
95 # released, so a check against that can't be used to determine the need for
96 # initialization).
97 ExecutionContext.cpyext_initialized_threadstate = False
98 ExecutionContext.cpyext_threadstate_is_current = True
99
100 def cleanup_cpyext_state(self):
101 self.cpyext_threadstate = None
102 self.cpyext_threadstate_is_current = True
103 self.cpyext_initialized_threadstate = False
104 ExecutionContext.cleanup_cpyext_state = cleanup_cpyext_state
105
106 class InterpreterState(object):
107 def __init__(self, space):
108 self.interpreter_state = lltype.malloc(
109 PyInterpreterState.TO, flavor='raw', zero=True, immortal=True)
110
111 def new_thread_state(self, space):
112 """
113 Create a new ThreadStateCapsule to hold the PyThreadState for a
114 particular execution context.
115
116 :param space: A space.
117
118 :returns: A new ThreadStateCapsule holding a newly allocated
119 PyThreadState and referring to this interpreter state.
120 """
121 from pypy.module.cpyext.state import State
122 capsule = ThreadStateCapsule(space)
123 ts = capsule.memory
124 space.fromcache(State).threadstate_count += 1
125 ts.c_id = rffi.cast(rffi.ULONGLONG,
126 space.fromcache(State).threadstate_count)
127 ts.c_interp = self.interpreter_state
128 ts.c_dict = make_ref(space, space.newdict())
129 return capsule
130
131
132 def get_thread_state(self, space):
133 """
134 Get the current PyThreadState for the current execution context.
135
136 :param space: A space.
137
138 :returns: The current PyThreadState for the current execution context,
139 or None if it does not have one.
140 """
141 ec = space.getexecutioncontext()
142 return self._get_thread_state(space, ec).memory
143
144
145 def swap_thread_state(self, space, tstate):
146 """
147 Replace the current thread state of the current execution context with a
148 new thread state.
149
150 :param space: The space.
151
152 :param tstate: The new PyThreadState for the current execution context.
153
154 :returns: The old thread state for the current execution context, either
155 None or a PyThreadState.
156 """
157 ec = space.getexecutioncontext()
158 capsule = self._get_thread_state(space, ec)
159 old_tstate = capsule.memory
160 capsule.memory = tstate
161 return old_tstate
162
163 def _get_thread_state(self, space, ec):
164 """
165 Get the ThreadStateCapsule for the given execution context, possibly
166 creating a new one if it does not already have one.
167
168 :param space: The space.
169 :param ec: The ExecutionContext of which to get the thread state.
170 :returns: The ThreadStateCapsule for the given execution context.
171 """
172 if not ec.cpyext_initialized_threadstate:
173 ec.cpyext_threadstate = self.new_thread_state(space)
174 ec.cpyext_initialized_threadstate = True
175 ec.cpyext_threadstate_is_current = True
176 return ec.cpyext_threadstate
177
178 @cpython_api([], PyThreadState, error=CANNOT_FAIL)
179 def PyThreadState_Get(space):
180 state = space.fromcache(InterpreterState)
181 ts = state.get_thread_state(space)
182 ec = space.getexecutioncontext()
183 if not ts or not ec.cpyext_threadstate_is_current:
184 from pypy.module.cpyext.api import py_fatalerrorfunc
185 py_fatalerrorfunc("PyThreadState_Get", "no current thread")
186 return ts
187
188 @cpython_api([], PyThreadState, error=CANNOT_FAIL)
189 def _PyThreadState_UncheckedGet(space):
190 """Similar to PyThreadState_Get(), but don't issue a fatal error
191 if it is NULL.
192 This is from CPython >= 3.7. On py3.6, it is present anyway and used to
193 implement _Py_Finalizing as a macro.
194 """
195 state = space.fromcache(InterpreterState)
196 ts = state.get_thread_state(space)
197 return ts
198
199 @cpython_api([], PyObject, result_is_ll=True, error=CANNOT_FAIL)
200 def PyThreadState_GetDict(space):
201 """Return a dictionary in which extensions can store thread-specific state
202 information. Each extension should use a unique key to use to store state in
203 the dictionary. It is okay to call this function when no current thread state
204 is available. If this function returns NULL, no exception has been raised and
205 the caller should assume no current thread state is available.
206
207 Previously this could only be called when a current thread is active, and NULL
208 meant that an exception was raised."""
209 state = space.fromcache(InterpreterState)
210 ts = state.get_thread_state(space)
211 if not space.getexecutioncontext().cpyext_threadstate_is_current:
212 return lltype.nullptr(PyObject.TO)
213 return ts.c_dict
214
215 # Part of CPython's internal API, used in testcapi
216 @cpython_api([PyThreadState], PyObject, result_is_ll=True, error=CANNOT_FAIL)
217 def _PyThreadState_GetDict(space, tstate):
218 """Return a dictionary in which extensions can store thread-specific state
219 information. Each extension should use a unique key to use to store state in
220 the dictionary. It is okay to call this function when no current thread state
221 is available. If this function returns NULL, no exception has been raised and
222 the caller should assume no current thread state is available.
223 """
224 return tstate.c_dict
225
226
227 @cpython_api([PyThreadState], PyThreadState, error=CANNOT_FAIL)
228 def PyThreadState_Swap(space, tstate):
229 """Swap the current thread state with the thread state given by the argument
230 tstate, which may be NULL. The global interpreter lock must be held."""
231 ec = space.getexecutioncontext()
232 state = space.fromcache(InterpreterState)
233 old_tstate = state.get_thread_state(space)
234 if not ec.cpyext_threadstate_is_current:
235 old_tstate = lltype.nullptr(PyThreadState.TO)
236 if tstate:
237 if tstate != state.get_thread_state(space):
238 print "Error in cpyext, CPython compatibility layer:"
239 print "PyThreadState_Swap() cannot be used to switch to another"
240 print "different PyThreadState right now"
241 raise AssertionError
242 ec.cpyext_threadstate_is_current = True
243 else:
244 ec.cpyext_threadstate_is_current = False
245 return old_tstate
246
247 @cpython_api([], PyThreadState, error=CANNOT_FAIL)
248 def PyGILState_GetThisThreadState(space):
249 """Get the current thread state for this thread. May return NULL if no
250 GILState API has been used on the current thread. Note that the main thread
251 always has such a thread-state, even if no auto-thread-state call has been
252 made on the main thread. This is mainly a helper/diagnostic function."""
253 state = space.fromcache(InterpreterState)
254 tstate = state.get_thread_state(space)
255 if not tstate:
256 return rffi.cast(PyThreadState, 0)
257 return tstate
258
259 @cpython_api([PyThreadState], lltype.Void, error=CANNOT_FAIL)
260 def PyThreadState_EnterTracing(space, tstate):
261 """Suspend tracing and profiling in the Python thread state tstate."""
262 ec = space.getexecutioncontext()
263 ec.is_tracing += 1
264
265 @cpython_api([PyThreadState], lltype.Void, error=CANNOT_FAIL)
266 def PyThreadState_LeaveTracing(space, tstate):
267 """Resume tracing and profiling in the Python thread state tstate suspended
268 by the PyThreadState_EnterTracing() function.
269
270 See also PyEval_SetTrace() and PyEval_SetProfile() functions."""
271 ec = space.getexecutioncontext()
272 ec.is_tracing -= 1
273
274 @cpython_api([PyThreadState], rffi.ULONGLONG, error=-1)
275 def PyThreadState_GetID(space, tstate):
276 return tstate.c_id
277
278 @cpython_api([PyThreadState], lltype.Void, gil="acquire")
279 def PyEval_AcquireThread(space, tstate):
280 """Acquire the global interpreter lock and set the current thread state to
281 tstate, which should not be NULL. The lock must have been created earlier.
282 If this thread already has the lock, deadlock ensues. This function is not
283 available when thread support is disabled at compile time."""
284
285 @cpython_api([PyThreadState], lltype.Void, gil="release")
286 def PyEval_ReleaseThread(space, tstate):
287 """Reset the current thread state to NULL and release the global interpreter
288 lock. The lock must have been created earlier and must be held by the current
289 thread. The tstate argument, which must not be NULL, is only used to check
290 that it represents the current thread state --- if it isn't, a fatal error is
291 reported. This function is not available when thread support is disabled at
292 compile time."""
293
294 PyGILState_STATE = rffi.INT
295 PyGILState_LOCKED = 0
296 PyGILState_UNLOCKED = 1
297 PyGILState_IGNORE = 2
298
299 ExecutionContext.cpyext_gilstate_counter_noleave = 0
300
301 def _workaround_cpython_untranslated(space):
302 # Workaround when not translated. The problem is that
303 # space.threadlocals.get_ec() is based on "thread._local", but
304 # CPython will clear a "thread._local" as soon as CPython's
305 # PyThreadState goes away. This occurs even if we're in a thread
306 # created from C and we're going to call some more Python code
307 # from this thread. This case shows up in
308 # test_pystate.test_frame_tstate_tracing.
309 def get_possibly_deleted_ec():
310 ec1 = space.threadlocals.raw_thread_local.get()
311 ec2 = space.threadlocals._valuedict.get(rthread.get_ident(), None)
312 if ec1 is None and ec2 is not None:
313 space.threadlocals.raw_thread_local.set(ec2)
314 return space.threadlocals.__class__.get_ec(space.threadlocals)
315 space.threadlocals.get_ec = get_possibly_deleted_ec
316
317
318 @cpython_api([], rffi.INT_real, error=CANNOT_FAIL, gil="pygilstate_check")
319 def PyGILState_Check(space):
320 assert False, "the logic is completely inside wrapper_second_level"
321
322
323 @cpython_api([], PyGILState_STATE, error=CANNOT_FAIL, gil="pygilstate_ensure")
324 def PyGILState_Ensure(space, previous_state):
325 # The argument 'previous_state' is not part of the API; it is inserted
326 # by make_wrapper() and contains PyGILState_LOCKED/UNLOCKED based on
327 # the previous GIL state.
328 must_leave = space.threadlocals.try_enter_thread(space)
329 ec = space.getexecutioncontext()
330 if not must_leave:
331 # This is a counter of how many times we called try_enter_thread()
332 # and it returned False. In PyGILState_Release(), if this counter
333 # is greater than zero, we decrement it; only if the counter is
334 # already zero do we call leave_thread().
335 ec.cpyext_gilstate_counter_noleave += 1
336 else:
337 # This case is for when we just built a fresh threadlocals.
338 # We should only see it when we are in a new thread with no
339 # PyPy code below.
340 assert previous_state == PyGILState_UNLOCKED
341 assert ec.cpyext_gilstate_counter_noleave == 0
342 if not we_are_translated():
343 _workaround_cpython_untranslated(space)
344 #
345 ec.cpyext_threadstate_is_current = True
346 return rffi.cast(PyGILState_STATE, previous_state)
347
348 @cpython_api([PyGILState_STATE], lltype.Void, gil="pygilstate_release")
349 def PyGILState_Release(space, oldstate):
350 oldstate = rffi.cast(lltype.Signed, oldstate)
351 ec = space.getexecutioncontext()
352 if ec.cpyext_gilstate_counter_noleave > 0:
353 ec.cpyext_gilstate_counter_noleave -= 1
354 else:
355 assert ec.cpyext_gilstate_counter_noleave == 0
356 assert oldstate == PyGILState_UNLOCKED
357 assert space.config.translation.thread
358 # ^^^ otherwise, we should not reach this case
359 ec.cpyext_threadstate_is_current = False
360 space.threadlocals.leave_thread(space)
361
362 @cpython_api([], PyInterpreterState, error=CANNOT_FAIL)
363 def PyInterpreterState_Head(space):
364 """Return the interpreter state object at the head of the list of all such objects.
365 """
366 return space.fromcache(InterpreterState).interpreter_state
367
368 @cpython_api([PyInterpreterState], PyInterpreterState, error=CANNOT_FAIL)
369 def PyInterpreterState_Next(space, interp):
370 """Return the next interpreter state object after interp from the list of all
371 such objects.
372 """
373 # PyPy does not support multiple interpreters
374 return lltype.nullptr(PyInterpreterState.TO)
375
376 @cpython_api([PyInterpreterState], rffi.LONG, error=CANNOT_FAIL)
377 def PyInterpreterState_GetID(space, interp):
378 return 0
379
380 @cpython_api([PyInterpreterState], PyThreadState, error=CANNOT_FAIL,
381 gil="around")
382 def PyThreadState_New(space, interp):
383 """Create a new thread state object belonging to the given interpreter
384 object. The global interpreter lock need not be held, but may be held if
385 it is necessary to serialize calls to this function."""
386 if not space.config.translation.thread:
387 raise NoThreads
388 # PyThreadState_Get will allocate a new execution context,
389 # we need to protect gc and other globals with the GIL.
390 rthread.gc_thread_start()
391 return PyThreadState_Get(space)
392
393 @cpython_api([PyThreadState], lltype.Void)
394 def PyThreadState_Clear(space, tstate):
395 """Reset all information in a thread state object. The global
396 interpreter lock must be held."""
397 if not space.config.translation.thread:
398 raise NoThreads
399 decref(space, tstate.c_dict)
400 tstate.c_dict = lltype.nullptr(PyObject.TO)
401 space.threadlocals.leave_thread(space)
402 space.getexecutioncontext().cleanup_cpyext_state()
403 rthread.gc_thread_die()
404
405 @cpython_api([PyThreadState], lltype.Void)
406 def PyThreadState_Delete(space, tstate):
407 """Destroy a thread state object. The global interpreter lock need not
408 be held. The thread state must have been reset with a previous call to
409 PyThreadState_Clear()."""
410
411 @cpython_api([], lltype.Void)
412 def PyThreadState_DeleteCurrent(space):
413 """Destroy a thread state object. The global interpreter lock need not
414 be held. The thread state must have been reset with a previous call to
415 PyThreadState_Clear()."""
416
417 @cpython_api([], lltype.Void)
418 def PyOS_AfterFork(space):
419 """Function to update some internal state after a process fork; this should be
420 called in the new process if the Python interpreter will continue to be used.
421 If a new executable is loaded into the new process, this function does not need
422 to be called."""
423 if not space.config.translation.thread:
424 return
425 from pypy.module.thread import os_thread
426 try:
427 os_thread.reinit_threads(space)
428 except OperationError as e:
429 e.write_unraisable(space, "PyOS_AfterFork()")
430
431 @cpython_api([], rffi.INT_real, error=CANNOT_FAIL)
432 def _Py_IsFinalizing(space):
433 """From CPython >= 3.7. On py3.6, it is present anyway and used to
434 implement _Py_Finalizing as a macro."""
435 return space.sys.finalizing
436
437 @cpython_api([lltype.Unsigned, PyObject], rffi.INT, error=CANNOT_FAIL)
438 def PyThreadState_SetAsyncExc(space, id, w_exc):
439 """ Asynchronously raise an exception in a thread. The id argument is the
440 thread id of the target thread; exc is the exception object to be raised.
441 This function does not steal any references to exc. To prevent naive
442 misuse, you must write your own C extension to call this. Must be called
443 with the GIL held. Returns the number of thread states modified; this is
444 normally one, but will be zero if the thread id isn't found. If exc is
445 NULL, the pending exception (if any) for the thread is cleared. This raises
446 no exceptions.
447 """
448 from rpython.rlib.rarithmetic import r_uint
449 from pypy.module.__pypy__.interp_signal import _raise_in_thread
450 try:
451 _raise_in_thread(space, r_uint(id), w_exc)
452 except OperationError as e:
453 if not e.match(space, space.w_ValueError):
454 e.write_unraisable(space, "PyThreadState_SetAsyncExc")
455 return 0
456 return 1
457 def _PyInterpreterState_GET(space):
458 tstate = PyThreadState_Get(space)
459 return tstate.c_interp
460
461 @cpython_api([PyObject, PyModuleDef], rffi.INT_real, error=-1)
462 def PyState_AddModule(space, w_module, moddef):
463 if not moddef:
464 raise oefmt(space.w_SystemError, "module definition is NULL")
465 interp = _PyInterpreterState_GET(space)
466 index = widen(moddef.c_m_base.c_m_index)
467 if index < 0:
468 raise oefmt(space.w_SystemError, "module index < 0")
469 if not interp.c_modules_by_index:
470 w_by_index = space.newlist([])
471 interp.c_modules_by_index = make_ref(space, w_by_index)
472 else:
473 w_by_index = from_ref(space, interp.c_modules_by_index)
474 if moddef.c_m_slots:
475 raise oefmt(space.w_SystemError,
476 "PyState_AddModule called on module with slots");
477 if index < space.len_w(w_by_index):
478 w_module_seen = space.getitem(w_by_index, space.newint(index))
479 if space.eq_w(w_module_seen, w_module):
480 raise oefmt(space.w_SystemError, "module %R already added", w_module)
481 while space.len_w(w_by_index) <= index:
482 space.call_method(w_by_index, 'append', space.w_None)
483 space.setitem(w_by_index, space.newint(index), w_module)
484 return 0
485
486 @cpython_api([PyModuleDef], rffi.INT_real, error=-1)
487 def PyState_RemoveModule(space, moddef):
488 interp = _PyInterpreterState_GET(space)
489 if moddef.c_m_slots:
490 raise oefmt(space.w_SystemError,
491 "PyState_RemoveModule called on module with slots")
492 index = widen(moddef.c_m_base.c_m_index)
493 if index == 0:
494 raise oefmt(space.w_SystemError, "invalid module index")
495 if not interp.c_modules_by_index:
496 raise oefmt(space.w_SystemError, "Interpreters module-list not accessible.")
497 w_by_index = from_ref(space, interp.c_modules_by_index)
498 if index > space.len_w(w_by_index):
499 raise oefmt(space.w_SystemError, "Module index out of bounds.")
500 space.setitem(w_by_index, space.newint(index), space.w_None)
501 return 0