/src/cpython/Python/pystate.c
Line | Count | Source |
1 | | |
2 | | /* Thread and interpreter state structures and their interfaces */ |
3 | | |
4 | | #include "Python.h" |
5 | | #include "pycore_abstract.h" // _PyIndex_Check() |
6 | | #include "pycore_audit.h" // _Py_AuditHookEntry |
7 | | #include "pycore_backoff.h" // JUMP_BACKWARD_INITIAL_VALUE, SIDE_EXIT_INITIAL_VALUE |
8 | | #include "pycore_ceval.h" // _PyEval_AcquireLock() |
9 | | #include "pycore_codecs.h" // _PyCodec_Fini() |
10 | | #include "pycore_critical_section.h" // _PyCriticalSection_Resume() |
11 | | #include "pycore_dtoa.h" // _dtoa_state_INIT() |
12 | | #include "pycore_freelist.h" // _PyObject_ClearFreeLists() |
13 | | #include "pycore_initconfig.h" // _PyStatus_OK() |
14 | | #include "pycore_interpframe.h" // _PyThreadState_HasStackSpace() |
15 | | #include "pycore_object.h" // _Py_ClearImmortal() |
16 | | #include "pycore_obmalloc.h" // _PyMem_obmalloc_state_on_heap() |
17 | | #include "pycore_opcode_utils.h" // NUM_COMMON_CONSTANTS |
18 | | #include "pycore_optimizer.h" // JIT_CLEANUP_THRESHOLD |
19 | | #include "pycore_parking_lot.h" // _PyParkingLot_AfterFork() |
20 | | #include "pycore_pyerrors.h" // _PyErr_Clear() |
21 | | #include "pycore_pylifecycle.h" // _PyAST_Fini() |
22 | | #include "pycore_pymem.h" // _PyMem_DebugEnabled() |
23 | | #include "pycore_runtime.h" // _PyRuntime |
24 | | #include "pycore_runtime_init.h" // _PyRuntimeState_INIT |
25 | | #include "pycore_stackref.h" // PyStackRef_AsPyObjectBorrow() |
26 | | #include "pycore_stats.h" // FT_STAT_WORLD_STOP_INC() |
27 | | #include "pycore_time.h" // _PyTime_Init() |
28 | | #include "pycore_uniqueid.h" // _PyObject_FinalizePerThreadRefcounts() |
29 | | |
30 | | |
31 | | /* -------------------------------------------------------------------------- |
32 | | CAUTION |
33 | | |
34 | | Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A |
35 | | number of these functions are advertised as safe to call when the GIL isn't |
36 | | held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's |
37 | | debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL |
38 | | to avoid the expense of doing their own locking). |
39 | | -------------------------------------------------------------------------- */ |
40 | | |
41 | | #ifdef HAVE_DLOPEN |
42 | | # ifdef HAVE_DLFCN_H |
43 | | # include <dlfcn.h> |
44 | | # endif |
45 | | # if !HAVE_DECL_RTLD_LAZY |
46 | | # define RTLD_LAZY 1 |
47 | | # endif |
48 | | #endif |
49 | | |
50 | | |
51 | | /****************************************/ |
52 | | /* helpers for the current thread state */ |
53 | | /****************************************/ |
54 | | |
55 | | // API for the current thread state is further down. |
56 | | |
57 | | /* "current" means one of: |
58 | | - bound to the current OS thread |
59 | | - holds the GIL |
60 | | */ |
61 | | |
62 | | //------------------------------------------------- |
63 | | // a highly efficient lookup for the current thread |
64 | | //------------------------------------------------- |
65 | | |
66 | | /* |
67 | | The stored thread state is set by PyThreadState_Swap(). |
68 | | |
69 | | For each of these functions, the GIL must be held by the current thread. |
70 | | */ |
71 | | |
72 | | |
73 | | /* The attached thread state for the current thread. */ |
74 | | _Py_thread_local PyThreadState *_Py_tss_tstate = NULL; |
75 | | |
76 | | /* The "bound" thread state used by PyGILState_Ensure(), |
77 | | also known as a "gilstate." */ |
78 | | _Py_thread_local PyThreadState *_Py_tss_gilstate = NULL; |
79 | | |
80 | | /* The interpreter of the attached thread state, |
81 | | and is same as tstate->interp. */ |
82 | | _Py_thread_local PyInterpreterState *_Py_tss_interp = NULL; |
83 | | |
84 | | static inline PyThreadState * |
85 | | current_fast_get(void) |
86 | 18.2M | { |
87 | 18.2M | return _Py_tss_tstate; |
88 | 18.2M | } |
89 | | |
90 | | static inline void |
91 | | current_fast_set(_PyRuntimeState *Py_UNUSED(runtime), PyThreadState *tstate) |
92 | 1.95M | { |
93 | 1.95M | assert(tstate != NULL); |
94 | 1.95M | _Py_tss_tstate = tstate; |
95 | 1.95M | assert(tstate->interp != NULL); |
96 | 1.95M | _Py_tss_interp = tstate->interp; |
97 | 1.95M | } |
98 | | |
99 | | static inline void |
100 | | current_fast_clear(_PyRuntimeState *Py_UNUSED(runtime)) |
101 | 1.95M | { |
102 | 1.95M | _Py_tss_tstate = NULL; |
103 | 1.95M | _Py_tss_interp = NULL; |
104 | 1.95M | } |
105 | | |
106 | | #define tstate_verify_not_active(tstate) \ |
107 | 0 | if (tstate == current_fast_get()) { \ |
108 | 0 | _Py_FatalErrorFormat(__func__, "tstate %p is still current", tstate); \ |
109 | 0 | } |
110 | | |
111 | | PyThreadState * |
112 | | _PyThreadState_GetCurrent(void) |
113 | 7.92M | { |
114 | 7.92M | return current_fast_get(); |
115 | 7.92M | } |
116 | | |
117 | | |
118 | | //--------------------------------------------- |
119 | | // The thread state used by PyGILState_Ensure() |
120 | | //--------------------------------------------- |
121 | | |
122 | | /* |
123 | | The stored thread state is set by bind_tstate() (AKA PyThreadState_Bind(). |
124 | | |
125 | | The GIL does no need to be held for these. |
126 | | */ |
127 | | |
128 | | static inline PyThreadState * |
129 | | gilstate_get(void) |
130 | 74 | { |
131 | 74 | return _Py_tss_gilstate; |
132 | 74 | } |
133 | | |
134 | | static inline void |
135 | | gilstate_set(PyThreadState *tstate) |
136 | 37 | { |
137 | 37 | assert(tstate != NULL); |
138 | 37 | _Py_tss_gilstate = tstate; |
139 | 37 | } |
140 | | |
141 | | static inline void |
142 | | gilstate_clear(void) |
143 | 0 | { |
144 | 0 | _Py_tss_gilstate = NULL; |
145 | 0 | } |
146 | | |
147 | | |
148 | | #ifndef NDEBUG |
149 | | static inline int tstate_is_alive(PyThreadState *tstate); |
150 | | |
151 | | static inline int |
152 | | tstate_is_bound(PyThreadState *tstate) |
153 | | { |
154 | | return tstate->_status.bound && !tstate->_status.unbound; |
155 | | } |
156 | | #endif // !NDEBUG |
157 | | |
158 | | static void bind_gilstate_tstate(PyThreadState *); |
159 | | static void unbind_gilstate_tstate(PyThreadState *); |
160 | | |
161 | | static void tstate_mimalloc_bind(PyThreadState *); |
162 | | |
163 | | static void |
164 | | bind_tstate(PyThreadState *tstate) |
165 | 37 | { |
166 | 37 | assert(tstate != NULL); |
167 | 37 | assert(tstate_is_alive(tstate) && !tstate->_status.bound); |
168 | 37 | assert(!tstate->_status.unbound); // just in case |
169 | 37 | assert(!tstate->_status.bound_gilstate); |
170 | 37 | assert(tstate != gilstate_get()); |
171 | 37 | assert(!tstate->_status.active); |
172 | 37 | assert(tstate->thread_id == 0); |
173 | 37 | assert(tstate->native_thread_id == 0); |
174 | | |
175 | | // Currently we don't necessarily store the thread state |
176 | | // in thread-local storage (e.g. per-interpreter). |
177 | | |
178 | 37 | tstate->thread_id = PyThread_get_thread_ident(); |
179 | 37 | #ifdef PY_HAVE_THREAD_NATIVE_ID |
180 | 37 | tstate->native_thread_id = PyThread_get_thread_native_id(); |
181 | 37 | #endif |
182 | | |
183 | | #ifdef Py_GIL_DISABLED |
184 | | // Initialize biased reference counting inter-thread queue. Note that this |
185 | | // needs to be initialized from the active thread. |
186 | | _Py_brc_init_thread(tstate); |
187 | | #endif |
188 | | |
189 | | // mimalloc state needs to be initialized from the active thread. |
190 | 37 | tstate_mimalloc_bind(tstate); |
191 | | |
192 | 37 | tstate->_status.bound = 1; |
193 | 37 | } |
194 | | |
195 | | static void |
196 | | unbind_tstate(PyThreadState *tstate) |
197 | 0 | { |
198 | 0 | assert(tstate != NULL); |
199 | 0 | assert(tstate_is_bound(tstate)); |
200 | 0 | #ifndef HAVE_PTHREAD_STUBS |
201 | 0 | assert(tstate->thread_id > 0); |
202 | 0 | #endif |
203 | 0 | #ifdef PY_HAVE_THREAD_NATIVE_ID |
204 | 0 | assert(tstate->native_thread_id > 0); |
205 | 0 | #endif |
206 | | |
207 | | // We leave thread_id and native_thread_id alone |
208 | | // since they can be useful for debugging. |
209 | | // Check the `_status` field to know if these values |
210 | | // are still valid. |
211 | | |
212 | | // We leave tstate->_status.bound set to 1 |
213 | | // to indicate it was previously bound. |
214 | 0 | tstate->_status.unbound = 1; |
215 | 0 | } |
216 | | |
217 | | |
218 | | /* Stick the thread state for this thread in thread specific storage. |
219 | | |
220 | | When a thread state is created for a thread by some mechanism |
221 | | other than PyGILState_Ensure(), it's important that the GILState |
222 | | machinery knows about it so it doesn't try to create another |
223 | | thread state for the thread. |
224 | | (This is a better fix for SF bug #1010677 than the first one attempted.) |
225 | | |
226 | | The only situation where you can legitimately have more than one |
227 | | thread state for an OS level thread is when there are multiple |
228 | | interpreters. |
229 | | |
230 | | Before 3.12, the PyGILState_*() APIs didn't work with multiple |
231 | | interpreters (see bpo-10915 and bpo-15751), so this function used |
232 | | to set TSS only once. Thus, the first thread state created for that |
233 | | given OS level thread would "win", which seemed reasonable behaviour. |
234 | | */ |
235 | | |
236 | | static void |
237 | | bind_gilstate_tstate(PyThreadState *tstate) |
238 | 37 | { |
239 | 37 | assert(tstate != NULL); |
240 | 37 | assert(tstate_is_alive(tstate)); |
241 | 37 | assert(tstate_is_bound(tstate)); |
242 | | // XXX assert(!tstate->_status.active); |
243 | 37 | assert(!tstate->_status.bound_gilstate); |
244 | | |
245 | 37 | PyThreadState *tcur = gilstate_get(); |
246 | 37 | assert(tstate != tcur); |
247 | | |
248 | 37 | if (tcur != NULL) { |
249 | 0 | tcur->_status.bound_gilstate = 0; |
250 | 0 | } |
251 | 37 | gilstate_set(tstate); |
252 | 37 | tstate->_status.bound_gilstate = 1; |
253 | 37 | } |
254 | | |
255 | | static void |
256 | | unbind_gilstate_tstate(PyThreadState *tstate) |
257 | 0 | { |
258 | 0 | assert(tstate != NULL); |
259 | | // XXX assert(tstate_is_alive(tstate)); |
260 | 0 | assert(tstate_is_bound(tstate)); |
261 | | // XXX assert(!tstate->_status.active); |
262 | 0 | assert(tstate->_status.bound_gilstate); |
263 | 0 | assert(tstate == gilstate_get()); |
264 | 0 | gilstate_clear(); |
265 | 0 | tstate->_status.bound_gilstate = 0; |
266 | 0 | } |
267 | | |
268 | | |
269 | | //---------------------------------------------- |
270 | | // the thread state that currently holds the GIL |
271 | | //---------------------------------------------- |
272 | | |
273 | | /* This is not exported, as it is not reliable! It can only |
274 | | ever be compared to the state for the *current* thread. |
275 | | * If not equal, then it doesn't matter that the actual |
276 | | value may change immediately after comparison, as it can't |
277 | | possibly change to the current thread's state. |
278 | | * If equal, then the current thread holds the lock, so the value can't |
279 | | change until we yield the lock. |
280 | | */ |
281 | | static int |
282 | | holds_gil(PyThreadState *tstate) |
283 | 0 | { |
284 | | // XXX Fall back to tstate->interp->runtime->ceval.gil.last_holder |
285 | | // (and tstate->interp->runtime->ceval.gil.locked). |
286 | 0 | assert(tstate != NULL); |
287 | | /* Must be the tstate for this thread */ |
288 | 0 | assert(tstate == gilstate_get()); |
289 | 0 | return tstate == current_fast_get(); |
290 | 0 | } |
291 | | |
292 | | |
293 | | /****************************/ |
294 | | /* the global runtime state */ |
295 | | /****************************/ |
296 | | |
297 | | //---------- |
298 | | // lifecycle |
299 | | //---------- |
300 | | |
301 | | /* Suppress deprecation warning for PyBytesObject.ob_shash */ |
302 | | _Py_COMP_DIAG_PUSH |
303 | | _Py_COMP_DIAG_IGNORE_DEPR_DECLS |
304 | | /* We use "initial" if the runtime gets re-used |
305 | | (e.g. Py_Finalize() followed by Py_Initialize(). |
306 | | Note that we initialize "initial" relative to _PyRuntime, |
307 | | to ensure pre-initialized pointers point to the active |
308 | | runtime state (and not "initial"). */ |
309 | | static const _PyRuntimeState initial = _PyRuntimeState_INIT(_PyRuntime, ""); |
310 | | _Py_COMP_DIAG_POP |
311 | | |
312 | | #define LOCKS_INIT(runtime) \ |
313 | 0 | { \ |
314 | 0 | &(runtime)->interpreters.mutex, \ |
315 | 0 | &(runtime)->xi.data_lookup.registry.mutex, \ |
316 | 0 | &(runtime)->unicode_state.ids.mutex, \ |
317 | 0 | &(runtime)->imports.extensions.mutex, \ |
318 | 0 | &(runtime)->ceval.pending_mainthread.mutex, \ |
319 | 0 | &(runtime)->atexit.mutex, \ |
320 | 0 | &(runtime)->audit_hooks.mutex, \ |
321 | 0 | &(runtime)->allocators.mutex, \ |
322 | 0 | &(runtime)->_main_interpreter.types.mutex, \ |
323 | 0 | &(runtime)->_main_interpreter.code_state.mutex, \ |
324 | 0 | &(runtime)->_main_interpreter.dict_state.watcher_mutex, \ |
325 | 0 | } |
326 | | |
327 | | static void |
328 | | init_runtime(_PyRuntimeState *runtime, |
329 | | void *open_code_hook, void *open_code_userdata, |
330 | | _Py_AuditHookEntry *audit_hook_head, |
331 | | Py_ssize_t unicode_next_index) |
332 | 37 | { |
333 | 37 | assert(!runtime->preinitializing); |
334 | 37 | assert(!runtime->preinitialized); |
335 | 37 | assert(!_PyRuntimeState_GetCoreInitialized(runtime)); |
336 | 37 | assert(!_PyRuntimeState_GetInitialized(runtime)); |
337 | 37 | assert(!runtime->_initialized); |
338 | | |
339 | 37 | runtime->open_code_hook = open_code_hook; |
340 | 37 | runtime->open_code_userdata = open_code_userdata; |
341 | 37 | runtime->audit_hooks.head = audit_hook_head; |
342 | | |
343 | 37 | PyPreConfig_InitPythonConfig(&runtime->preconfig); |
344 | | |
345 | | // Set it to the ID of the main thread of the main interpreter. |
346 | 37 | runtime->main_thread = PyThread_get_thread_ident(); |
347 | | |
348 | 37 | runtime->unicode_state.ids.next_index = unicode_next_index; |
349 | 37 | runtime->_initialized = 1; |
350 | 37 | } |
351 | | |
352 | | PyStatus |
353 | | _PyRuntimeState_Init(_PyRuntimeState *runtime) |
354 | 37 | { |
355 | | /* We preserve the hook across init, because there is |
356 | | currently no public API to set it between runtime |
357 | | initialization and interpreter initialization. */ |
358 | 37 | void *open_code_hook = runtime->open_code_hook; |
359 | 37 | void *open_code_userdata = runtime->open_code_userdata; |
360 | 37 | _Py_AuditHookEntry *audit_hook_head = runtime->audit_hooks.head; |
361 | | // bpo-42882: Preserve next_index value if Py_Initialize()/Py_Finalize() |
362 | | // is called multiple times. |
363 | 37 | Py_ssize_t unicode_next_index = runtime->unicode_state.ids.next_index; |
364 | | |
365 | 37 | if (runtime->_initialized) { |
366 | | // Py_Initialize() must be running again. |
367 | | // Reset to _PyRuntimeState_INIT. |
368 | 0 | memcpy(runtime, &initial, sizeof(*runtime)); |
369 | | // Preserve the cookie from the original runtime. |
370 | 0 | memcpy(runtime->debug_offsets.cookie, _Py_Debug_Cookie, 8); |
371 | 0 | assert(!runtime->_initialized); |
372 | 0 | } |
373 | | |
374 | 37 | PyStatus status = _PyTime_Init(&runtime->time); |
375 | 37 | if (_PyStatus_EXCEPTION(status)) { |
376 | 0 | return status; |
377 | 0 | } |
378 | | |
379 | 37 | init_runtime(runtime, open_code_hook, open_code_userdata, audit_hook_head, |
380 | 37 | unicode_next_index); |
381 | | |
382 | 37 | return _PyStatus_OK(); |
383 | 37 | } |
384 | | |
385 | | void |
386 | | _PyRuntimeState_Fini(_PyRuntimeState *runtime) |
387 | 0 | { |
388 | | #ifdef Py_REF_DEBUG |
389 | | /* The count is cleared by _Py_FinalizeRefTotal(). */ |
390 | | assert(runtime->object_state.interpreter_leaks == 0); |
391 | | #endif |
392 | 0 | gilstate_clear(); |
393 | 0 | } |
394 | | |
395 | | #ifdef HAVE_FORK |
396 | | /* This function is called from PyOS_AfterFork_Child to ensure that |
397 | | newly created child processes do not share locks with the parent. */ |
398 | | PyStatus |
399 | | _PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime) |
400 | 0 | { |
401 | | // This was initially set in _PyRuntimeState_Init(). |
402 | 0 | runtime->main_thread = PyThread_get_thread_ident(); |
403 | | |
404 | | // Clears the parking lot. Any waiting threads are dead. This must be |
405 | | // called before releasing any locks that use the parking lot. |
406 | 0 | _PyParkingLot_AfterFork(); |
407 | | |
408 | | // Re-initialize global locks |
409 | 0 | PyMutex *locks[] = LOCKS_INIT(runtime); |
410 | 0 | for (size_t i = 0; i < Py_ARRAY_LENGTH(locks); i++) { |
411 | 0 | _PyMutex_at_fork_reinit(locks[i]); |
412 | 0 | } |
413 | | #ifdef Py_GIL_DISABLED |
414 | | for (PyInterpreterState *interp = runtime->interpreters.head; |
415 | | interp != NULL; interp = interp->next) |
416 | | { |
417 | | for (int i = 0; i < NUM_WEAKREF_LIST_LOCKS; i++) { |
418 | | _PyMutex_at_fork_reinit(&interp->weakref_locks[i]); |
419 | | } |
420 | | } |
421 | | #endif |
422 | |
|
423 | 0 | _PyThread_AfterFork(&runtime->threads); |
424 | |
|
425 | 0 | return _PyStatus_OK(); |
426 | 0 | } |
427 | | #endif |
428 | | |
429 | | |
430 | | /*************************************/ |
431 | | /* the per-interpreter runtime state */ |
432 | | /*************************************/ |
433 | | |
434 | | //---------- |
435 | | // lifecycle |
436 | | //---------- |
437 | | |
438 | | /* Calling this indicates that the runtime is ready to create interpreters. */ |
439 | | |
440 | | PyStatus |
441 | | _PyInterpreterState_Enable(_PyRuntimeState *runtime) |
442 | 37 | { |
443 | 37 | struct pyinterpreters *interpreters = &runtime->interpreters; |
444 | 37 | interpreters->next_id = 0; |
445 | 37 | return _PyStatus_OK(); |
446 | 37 | } |
447 | | |
448 | | static PyInterpreterState * |
449 | | alloc_interpreter(void) |
450 | 0 | { |
451 | | // Aligned allocation for PyInterpreterState. |
452 | | // the first word of the memory block is used to store |
453 | | // the original pointer to be used later to free the memory. |
454 | 0 | size_t alignment = _Alignof(PyInterpreterState); |
455 | 0 | size_t allocsize = sizeof(PyInterpreterState) + sizeof(void *) + alignment - 1; |
456 | 0 | void *mem = PyMem_RawCalloc(1, allocsize); |
457 | 0 | if (mem == NULL) { |
458 | 0 | return NULL; |
459 | 0 | } |
460 | 0 | void *ptr = _Py_ALIGN_UP((char *)mem + sizeof(void *), alignment); |
461 | 0 | ((void **)ptr)[-1] = mem; |
462 | 0 | assert(_Py_IS_ALIGNED(ptr, alignment)); |
463 | 0 | return ptr; |
464 | 0 | } |
465 | | |
466 | | static void |
467 | | free_interpreter(PyInterpreterState *interp) |
468 | 0 | { |
469 | | #ifdef Py_GIL_DISABLED |
470 | | mi_subproc_t *subproc = interp->mimalloc.subproc; |
471 | | if (subproc != NULL) { |
472 | | // Delete the sub-process only when no abandoned segment points to it. |
473 | | if (mi_atomic_load_relaxed(&subproc->abandoned_count) == 0) { |
474 | | mi_subproc_delete(subproc); |
475 | | } |
476 | | interp->mimalloc.subproc = NULL; |
477 | | } |
478 | | #endif |
479 | | #ifdef Py_STATS |
480 | | if (interp->pystats_struct) { |
481 | | PyMem_RawFree(interp->pystats_struct); |
482 | | interp->pystats_struct = NULL; |
483 | | } |
484 | | #endif |
485 | | // The main interpreter is statically allocated so |
486 | | // should not be freed. |
487 | 0 | if (interp != &_PyRuntime._main_interpreter) { |
488 | 0 | if (_PyMem_obmalloc_state_on_heap(interp)) { |
489 | | // interpreter has its own obmalloc state, free it |
490 | 0 | PyMem_RawFree(interp->obmalloc); |
491 | 0 | interp->obmalloc = NULL; |
492 | 0 | } |
493 | 0 | assert(_Py_IS_ALIGNED(interp, _Alignof(PyInterpreterState))); |
494 | 0 | PyMem_RawFree(((void **)interp)[-1]); |
495 | 0 | } |
496 | 0 | } |
497 | | |
498 | | #ifndef NDEBUG |
499 | | static inline int check_interpreter_whence(long); |
500 | | #endif |
501 | | |
502 | | /* Get the interpreter state to a minimal consistent state. |
503 | | Further init happens in pylifecycle.c before it can be used. |
504 | | All fields not initialized here are expected to be zeroed out, |
505 | | e.g. by PyMem_RawCalloc() or memset(), or otherwise pre-initialized. |
506 | | The runtime state is not manipulated. Instead it is assumed that |
507 | | the interpreter is getting added to the runtime. |
508 | | |
509 | | Note that the main interpreter was statically initialized as part |
510 | | of the runtime and most state is already set properly. That leaves |
511 | | a small number of fields to initialize dynamically, as well as some |
512 | | that are initialized lazily. |
513 | | |
514 | | For subinterpreters we memcpy() the main interpreter in |
515 | | PyInterpreterState_New(), leaving it in the same mostly-initialized |
516 | | state. The only difference is that the interpreter has some |
517 | | self-referential state that is statically initializexd to the |
518 | | main interpreter. We fix those fields here, in addition |
519 | | to the other dynamically initialized fields. |
520 | | */ |
521 | | |
522 | | static inline bool |
523 | | is_env_enabled(const char *env_name) |
524 | 74 | { |
525 | 74 | char *env = Py_GETENV(env_name); |
526 | 74 | return env && *env != '\0' && *env != '0'; |
527 | 74 | } |
528 | | |
529 | | static inline bool |
530 | | is_env_disabled(const char *env_name) |
531 | 37 | { |
532 | 37 | char *env = Py_GETENV(env_name); |
533 | 37 | return env != NULL && *env == '0'; |
534 | 37 | } |
535 | | |
536 | | static inline void |
537 | | init_policy(uint16_t *target, const char *env_name, uint16_t default_value, |
538 | | long min_value, long max_value) |
539 | 259 | { |
540 | 259 | *target = default_value; |
541 | 259 | char *env = Py_GETENV(env_name); |
542 | 259 | if (env && *env != '\0') { |
543 | 0 | long value = atol(env); |
544 | 0 | if (value >= min_value && value <= max_value) { |
545 | 0 | *target = (uint16_t)value; |
546 | 0 | } |
547 | 0 | } |
548 | 259 | } |
549 | | |
550 | | static PyStatus |
551 | | init_interpreter(PyInterpreterState *interp, |
552 | | _PyRuntimeState *runtime, int64_t id, |
553 | | PyInterpreterState *next, |
554 | | long whence) |
555 | 37 | { |
556 | 37 | if (interp->_initialized) { |
557 | 0 | return _PyStatus_ERR("interpreter already initialized"); |
558 | 0 | } |
559 | | |
560 | 37 | assert(interp->_whence == _PyInterpreterState_WHENCE_NOTSET); |
561 | 37 | assert(check_interpreter_whence(whence) == 0); |
562 | 37 | interp->_whence = whence; |
563 | | |
564 | 37 | assert(runtime != NULL); |
565 | 37 | interp->runtime = runtime; |
566 | | |
567 | 37 | assert(id > 0 || (id == 0 && interp == runtime->interpreters.main)); |
568 | 37 | interp->id = id; |
569 | | |
570 | 37 | interp->id_refcount = 0; |
571 | | |
572 | 37 | assert(runtime->interpreters.head == interp); |
573 | 37 | assert(next != NULL || (interp == runtime->interpreters.main)); |
574 | 37 | interp->next = next; |
575 | | |
576 | 37 | interp->threads.preallocated = &interp->_initial_thread; |
577 | | |
578 | | // We would call _PyObject_InitState() at this point |
579 | | // if interp->feature_flags were alredy set. |
580 | | |
581 | 37 | _PyEval_InitState(interp); |
582 | 37 | _PyGC_InitState(&interp->gc); |
583 | 37 | PyConfig_InitPythonConfig(&interp->config); |
584 | | #ifdef Py_GIL_DISABLED |
585 | | _Py_brc_init_state(interp); |
586 | | |
587 | | interp->mimalloc.subproc = mi_subproc_new(); |
588 | | if (interp->mimalloc.subproc == NULL) { |
589 | | return _PyStatus_NO_MEMORY(); |
590 | | } |
591 | | #endif |
592 | | |
593 | 37 | llist_init(&interp->mem_free_queue.head); |
594 | 37 | llist_init(&interp->asyncio_tasks_head); |
595 | 37 | interp->asyncio_tasks_lock = (PyMutex){0}; |
596 | 629 | for (int i = 0; i < _PY_MONITORING_UNGROUPED_EVENTS; i++) { |
597 | 592 | interp->monitors.tools[i] = 0; |
598 | 592 | } |
599 | 333 | for (int t = 0; t < PY_MONITORING_TOOL_IDS; t++) { |
600 | 5.92k | for (int e = 0; e < _PY_MONITORING_EVENTS; e++) { |
601 | 5.62k | interp->monitoring_callables[t][e] = NULL; |
602 | | |
603 | 5.62k | } |
604 | 296 | interp->monitoring_tool_versions[t] = 0; |
605 | 296 | } |
606 | 37 | interp->_code_object_generation = 0; |
607 | 37 | interp->jit = false; |
608 | 37 | interp->compiling = false; |
609 | 37 | interp->executor_blooms = NULL; |
610 | 37 | interp->executor_ptrs = NULL; |
611 | 37 | interp->executor_count = 0; |
612 | 37 | interp->executor_capacity = 0; |
613 | 37 | interp->executor_deletion_list_head = NULL; |
614 | 37 | interp->executor_creation_counter = JIT_CLEANUP_THRESHOLD; |
615 | | |
616 | | // Initialize optimization configuration from environment variables |
617 | | // PYTHON_JIT_STRESS sets aggressive defaults for testing, but can be overridden |
618 | 37 | uint16_t jump_default = JUMP_BACKWARD_INITIAL_VALUE; |
619 | 37 | uint16_t resume_default = RESUME_INITIAL_VALUE; |
620 | 37 | uint16_t side_exit_default = SIDE_EXIT_INITIAL_VALUE; |
621 | | |
622 | 37 | if (is_env_enabled("PYTHON_JIT_STRESS")) { |
623 | 0 | jump_default = 63; |
624 | 0 | side_exit_default = 63; |
625 | 0 | resume_default = 127; |
626 | 0 | } |
627 | | |
628 | 37 | init_policy(&interp->opt_config.jump_backward_initial_value, |
629 | 37 | "PYTHON_JIT_JUMP_BACKWARD_INITIAL_VALUE", |
630 | 37 | jump_default, 1, MAX_VALUE); |
631 | 37 | init_policy(&interp->opt_config.jump_backward_initial_backoff, |
632 | 37 | "PYTHON_JIT_JUMP_BACKWARD_INITIAL_BACKOFF", |
633 | 37 | JUMP_BACKWARD_INITIAL_BACKOFF, 0, MAX_BACKOFF); |
634 | 37 | init_policy(&interp->opt_config.resume_initial_value, |
635 | 37 | "PYTHON_JIT_RESUME_INITIAL_VALUE", |
636 | 37 | resume_default, 1, MAX_VALUE); |
637 | 37 | init_policy(&interp->opt_config.resume_initial_backoff, |
638 | 37 | "PYTHON_JIT_RESUME_INITIAL_BACKOFF", |
639 | 37 | RESUME_INITIAL_BACKOFF, 0, MAX_BACKOFF); |
640 | 37 | init_policy(&interp->opt_config.side_exit_initial_value, |
641 | 37 | "PYTHON_JIT_SIDE_EXIT_INITIAL_VALUE", |
642 | 37 | side_exit_default, 1, MAX_VALUE); |
643 | 37 | init_policy(&interp->opt_config.side_exit_initial_backoff, |
644 | 37 | "PYTHON_JIT_SIDE_EXIT_INITIAL_BACKOFF", |
645 | 37 | SIDE_EXIT_INITIAL_BACKOFF, 0, MAX_BACKOFF); |
646 | | |
647 | | // Trace fitness configuration |
648 | 37 | init_policy(&interp->opt_config.fitness_initial, |
649 | 37 | "PYTHON_JIT_FITNESS_INITIAL", |
650 | 37 | FITNESS_INITIAL, EXIT_QUALITY_CLOSE_LOOP, FITNESS_INITIAL); |
651 | | |
652 | 37 | interp->opt_config.specialization_enabled = !is_env_enabled("PYTHON_SPECIALIZATION_OFF"); |
653 | 37 | interp->opt_config.uops_optimize_enabled = !is_env_disabled("PYTHON_UOPS_OPTIMIZE"); |
654 | 37 | if (interp != &runtime->_main_interpreter) { |
655 | | /* Fix the self-referential, statically initialized fields. */ |
656 | 0 | interp->dtoa = (struct _dtoa_state)_dtoa_state_INIT(interp); |
657 | 0 | } |
658 | | #if !defined(Py_GIL_DISABLED) && defined(Py_STACKREF_DEBUG) |
659 | | interp->next_stackref = INITIAL_STACKREF_INDEX; |
660 | | _Py_hashtable_allocator_t alloc = { |
661 | | .malloc = malloc, |
662 | | .free = free, |
663 | | }; |
664 | | interp->open_stackrefs_table = _Py_hashtable_new_full( |
665 | | _Py_hashtable_hash_ptr, |
666 | | _Py_hashtable_compare_direct, |
667 | | NULL, |
668 | | NULL, |
669 | | &alloc |
670 | | ); |
671 | | if (interp->open_stackrefs_table == NULL) { |
672 | | return _PyStatus_NO_MEMORY(); |
673 | | } |
674 | | # ifdef Py_STACKREF_CLOSE_DEBUG |
675 | | interp->closed_stackrefs_table = _Py_hashtable_new_full( |
676 | | _Py_hashtable_hash_ptr, |
677 | | _Py_hashtable_compare_direct, |
678 | | NULL, |
679 | | NULL, |
680 | | &alloc |
681 | | ); |
682 | | if (interp->closed_stackrefs_table == NULL) { |
683 | | return _PyStatus_NO_MEMORY(); |
684 | | } |
685 | | # endif |
686 | | _Py_stackref_associate(interp, Py_None, PyStackRef_None); |
687 | | _Py_stackref_associate(interp, Py_False, PyStackRef_False); |
688 | | _Py_stackref_associate(interp, Py_True, PyStackRef_True); |
689 | | #endif |
690 | | |
691 | 37 | interp->_initialized = 1; |
692 | 37 | return _PyStatus_OK(); |
693 | 37 | } |
694 | | |
695 | | |
696 | | PyStatus |
697 | | _PyInterpreterState_New(PyThreadState *tstate, PyInterpreterState **pinterp) |
698 | 37 | { |
699 | 37 | *pinterp = NULL; |
700 | | |
701 | | // Don't get runtime from tstate since tstate can be NULL |
702 | 37 | _PyRuntimeState *runtime = &_PyRuntime; |
703 | | |
704 | | // tstate is NULL when pycore_create_interpreter() calls |
705 | | // _PyInterpreterState_New() to create the main interpreter. |
706 | 37 | if (tstate != NULL) { |
707 | 0 | if (_PySys_Audit(tstate, "cpython.PyInterpreterState_New", NULL) < 0) { |
708 | 0 | return _PyStatus_ERR("sys.audit failed"); |
709 | 0 | } |
710 | 0 | } |
711 | | |
712 | | /* We completely serialize creation of multiple interpreters, since |
713 | | it simplifies things here and blocking concurrent calls isn't a problem. |
714 | | Regardless, we must fully block subinterpreter creation until |
715 | | after the main interpreter is created. */ |
716 | 37 | HEAD_LOCK(runtime); |
717 | | |
718 | 37 | struct pyinterpreters *interpreters = &runtime->interpreters; |
719 | 37 | int64_t id = interpreters->next_id; |
720 | 37 | interpreters->next_id += 1; |
721 | | |
722 | | // Allocate the interpreter and add it to the runtime state. |
723 | 37 | PyInterpreterState *interp; |
724 | 37 | PyStatus status; |
725 | 37 | PyInterpreterState *old_head = interpreters->head; |
726 | 37 | if (old_head == NULL) { |
727 | | // We are creating the main interpreter. |
728 | 37 | assert(interpreters->main == NULL); |
729 | 37 | assert(id == 0); |
730 | | |
731 | 37 | interp = &runtime->_main_interpreter; |
732 | 37 | assert(interp->id == 0); |
733 | 37 | assert(interp->next == NULL); |
734 | | |
735 | 37 | interpreters->main = interp; |
736 | 37 | } |
737 | 0 | else { |
738 | 0 | assert(interpreters->main != NULL); |
739 | 0 | assert(id != 0); |
740 | |
|
741 | 0 | interp = alloc_interpreter(); |
742 | 0 | if (interp == NULL) { |
743 | 0 | status = _PyStatus_NO_MEMORY(); |
744 | 0 | goto error; |
745 | 0 | } |
746 | | // Set to _PyInterpreterState_INIT. |
747 | 0 | memcpy(interp, &initial._main_interpreter, sizeof(*interp)); |
748 | |
|
749 | 0 | if (id < 0) { |
750 | | /* overflow or Py_Initialize() not called yet! */ |
751 | 0 | status = _PyStatus_ERR("failed to get an interpreter ID"); |
752 | 0 | goto error; |
753 | 0 | } |
754 | 0 | } |
755 | 37 | interpreters->head = interp; |
756 | | |
757 | 37 | long whence = _PyInterpreterState_WHENCE_UNKNOWN; |
758 | 37 | status = init_interpreter(interp, runtime, |
759 | 37 | id, old_head, whence); |
760 | 37 | if (_PyStatus_EXCEPTION(status)) { |
761 | 0 | goto error; |
762 | 0 | } |
763 | | |
764 | 37 | HEAD_UNLOCK(runtime); |
765 | | |
766 | 37 | assert(interp != NULL); |
767 | 37 | *pinterp = interp; |
768 | 37 | return _PyStatus_OK(); |
769 | | |
770 | 0 | error: |
771 | 0 | HEAD_UNLOCK(runtime); |
772 | |
|
773 | 0 | if (interp != NULL) { |
774 | 0 | free_interpreter(interp); |
775 | 0 | } |
776 | 0 | return status; |
777 | 37 | } |
778 | | |
779 | | |
780 | | PyInterpreterState * |
781 | | PyInterpreterState_New(void) |
782 | 0 | { |
783 | | // tstate can be NULL |
784 | 0 | PyThreadState *tstate = current_fast_get(); |
785 | |
|
786 | 0 | PyInterpreterState *interp; |
787 | 0 | PyStatus status = _PyInterpreterState_New(tstate, &interp); |
788 | 0 | if (_PyStatus_EXCEPTION(status)) { |
789 | 0 | Py_ExitStatusException(status); |
790 | 0 | } |
791 | 0 | assert(interp != NULL); |
792 | 0 | return interp; |
793 | 0 | } |
794 | | |
795 | | #if !defined(Py_GIL_DISABLED) && defined(Py_STACKREF_DEBUG) |
796 | | extern void |
797 | | _Py_stackref_report_leaks(PyInterpreterState *interp); |
798 | | #endif |
799 | | |
800 | | static int |
801 | | common_const_is_initialized(_PyStackRef ref) |
802 | 0 | { |
803 | | #if !defined(Py_GIL_DISABLED) && defined(Py_STACKREF_DEBUG) |
804 | | return !PyStackRef_IsNull(ref); |
805 | | #else |
806 | 0 | return ref.bits != 0 && !PyStackRef_IsNull(ref); |
807 | 0 | #endif |
808 | 0 | } |
809 | | |
810 | | |
811 | | static void |
812 | | common_constants_clear(PyInterpreterState *interp) |
813 | 0 | { |
814 | 0 | for (int i = 0; i < NUM_COMMON_CONSTANTS; i++) { |
815 | 0 | _PyStackRef ref = interp->common_consts[i]; |
816 | 0 | if (!common_const_is_initialized(ref)) { |
817 | 0 | continue; |
818 | 0 | } |
819 | 0 | PyObject *obj = PyStackRef_AsPyObjectBorrow(ref); |
820 | 0 | PyStackRef_XCLOSE(ref); |
821 | 0 | interp->common_consts[i] = PyStackRef_NULL; |
822 | | // Refcount reclamation skips heap immortals; release manually. |
823 | 0 | if (_Py_IsImmortal(obj) && !_Py_IsStaticImmortal(obj)) { |
824 | 0 | _Py_ClearImmortal(obj); |
825 | 0 | } |
826 | 0 | } |
827 | 0 | } |
828 | | |
829 | | |
830 | | static void |
831 | | interpreter_clear(PyInterpreterState *interp, PyThreadState *tstate) |
832 | 0 | { |
833 | 0 | assert(interp != NULL); |
834 | 0 | assert(tstate != NULL); |
835 | 0 | _PyRuntimeState *runtime = interp->runtime; |
836 | | |
837 | | /* XXX Conditions we need to enforce: |
838 | | |
839 | | * the GIL must be held by the current thread |
840 | | * tstate must be the "current" thread state (current_fast_get()) |
841 | | * tstate->interp must be interp |
842 | | * for the main interpreter, tstate must be the main thread |
843 | | */ |
844 | | // XXX Ideally, we would not rely on any thread state in this function |
845 | | // (and we would drop the "tstate" argument). |
846 | |
|
847 | 0 | if (_PySys_Audit(tstate, "cpython.PyInterpreterState_Clear", NULL) < 0) { |
848 | 0 | _PyErr_Clear(tstate); |
849 | 0 | } |
850 | | |
851 | | // Clear the current/main thread state last. |
852 | 0 | _Py_FOR_EACH_TSTATE_BEGIN(interp, p) { |
853 | | // See https://github.com/python/cpython/issues/102126 |
854 | | // Must be called without HEAD_LOCK held as it can deadlock |
855 | | // if any finalizer tries to acquire that lock. |
856 | 0 | HEAD_UNLOCK(runtime); |
857 | 0 | PyThreadState_Clear(p); |
858 | 0 | HEAD_LOCK(runtime); |
859 | 0 | } |
860 | 0 | _Py_FOR_EACH_TSTATE_END(interp); |
861 | 0 | if (tstate->interp == interp) { |
862 | | /* We fix tstate->_status below when we for sure aren't using it |
863 | | (e.g. no longer need the GIL). */ |
864 | | // XXX Eliminate the need to do this. |
865 | 0 | tstate->_status.cleared = 0; |
866 | 0 | } |
867 | | |
868 | | /* It is possible that any of the objects below have a finalizer |
869 | | that runs Python code or otherwise relies on a thread state |
870 | | or even the interpreter state. For now we trust that isn't |
871 | | a problem. |
872 | | */ |
873 | | // XXX Make sure we properly deal with problematic finalizers. |
874 | |
|
875 | 0 | Py_CLEAR(interp->audit_hooks); |
876 | | |
877 | | // gh-140257: Threads have already been cleared, but daemon threads may |
878 | | // still access eval_breaker atomically via take_gil() right before they |
879 | | // hang. Use an atomic store to prevent data races during finalization. |
880 | 0 | interp->ceval.instrumentation_version = 0; |
881 | 0 | _Py_atomic_store_uintptr(&tstate->eval_breaker, 0); |
882 | |
|
883 | 0 | for (int i = 0; i < _PY_MONITORING_UNGROUPED_EVENTS; i++) { |
884 | 0 | interp->monitors.tools[i] = 0; |
885 | 0 | } |
886 | 0 | for (int t = 0; t < PY_MONITORING_TOOL_IDS; t++) { |
887 | 0 | for (int e = 0; e < _PY_MONITORING_EVENTS; e++) { |
888 | 0 | Py_CLEAR(interp->monitoring_callables[t][e]); |
889 | 0 | } |
890 | 0 | } |
891 | 0 | for (int t = 0; t < PY_MONITORING_TOOL_IDS; t++) { |
892 | 0 | Py_CLEAR(interp->monitoring_tool_names[t]); |
893 | 0 | } |
894 | 0 | interp->_code_object_generation = 0; |
895 | | #ifdef Py_GIL_DISABLED |
896 | | interp->tlbc_indices.tlbc_generation = 0; |
897 | | #endif |
898 | |
|
899 | 0 | PyConfig_Clear(&interp->config); |
900 | 0 | _PyCodec_Fini(interp); |
901 | |
|
902 | 0 | assert(interp->imports.modules == NULL); |
903 | 0 | assert(interp->imports.modules_by_index == NULL); |
904 | 0 | assert(interp->imports.importlib == NULL); |
905 | 0 | assert(interp->imports.import_func == NULL); |
906 | |
|
907 | 0 | Py_CLEAR(interp->sysdict_copy); |
908 | 0 | Py_CLEAR(interp->builtins_copy); |
909 | 0 | Py_CLEAR(interp->dict); |
910 | 0 | #ifdef HAVE_FORK |
911 | 0 | Py_CLEAR(interp->before_forkers); |
912 | 0 | Py_CLEAR(interp->after_forkers_parent); |
913 | 0 | Py_CLEAR(interp->after_forkers_child); |
914 | 0 | #endif |
915 | | |
916 | |
|
917 | | #ifdef _Py_TIER2 |
918 | | _Py_ClearExecutorDeletionList(interp); |
919 | | #endif |
920 | 0 | _PyAST_Fini(interp); |
921 | 0 | _PyAtExit_Fini(interp); |
922 | | |
923 | | // All Python types must be destroyed before the last GC collection. Python |
924 | | // types create a reference cycle to themselves in their in their |
925 | | // PyTypeObject.tp_mro member (the tuple contains the type). |
926 | | |
927 | | /* Last garbage collection on this interpreter */ |
928 | 0 | _PyGC_CollectNoFail(tstate); |
929 | 0 | _PyGC_Fini(interp); |
930 | | |
931 | | // Finalize warnings after last gc so that any finalizers can |
932 | | // access warnings state |
933 | 0 | _PyWarnings_Fini(interp); |
934 | 0 | struct _PyExecutorObject *cold = interp->cold_executor; |
935 | 0 | if (cold != NULL) { |
936 | 0 | interp->cold_executor = NULL; |
937 | 0 | assert(cold->vm_data.valid); |
938 | 0 | assert(!cold->vm_data.cold); |
939 | 0 | _PyExecutor_Free(cold); |
940 | 0 | } |
941 | |
|
942 | 0 | struct _PyExecutorObject *cold_dynamic = interp->cold_dynamic_executor; |
943 | 0 | if (cold_dynamic != NULL) { |
944 | 0 | interp->cold_dynamic_executor = NULL; |
945 | 0 | assert(cold_dynamic->vm_data.valid); |
946 | 0 | assert(!cold_dynamic->vm_data.cold); |
947 | 0 | _PyExecutor_Free(cold_dynamic); |
948 | 0 | } |
949 | | /* We don't clear sysdict and builtins until the end of this function. |
950 | | Because clearing other attributes can execute arbitrary Python code |
951 | | which requires sysdict and builtins. */ |
952 | 0 | PyDict_Clear(interp->sysdict); |
953 | 0 | PyDict_Clear(interp->builtins); |
954 | 0 | Py_CLEAR(interp->sysdict); |
955 | 0 | Py_CLEAR(interp->builtins); |
956 | 0 | common_constants_clear(interp); |
957 | |
|
958 | | #if !defined(Py_GIL_DISABLED) && defined(Py_STACKREF_DEBUG) |
959 | | # ifdef Py_STACKREF_CLOSE_DEBUG |
960 | | _Py_hashtable_destroy(interp->closed_stackrefs_table); |
961 | | interp->closed_stackrefs_table = NULL; |
962 | | # endif |
963 | | _Py_stackref_report_leaks(interp); |
964 | | _Py_hashtable_destroy(interp->open_stackrefs_table); |
965 | | interp->open_stackrefs_table = NULL; |
966 | | #endif |
967 | |
|
968 | 0 | if (tstate->interp == interp) { |
969 | | /* We are now safe to fix tstate->_status.cleared. */ |
970 | | // XXX Do this (much) earlier? |
971 | 0 | tstate->_status.cleared = 1; |
972 | 0 | } |
973 | |
|
974 | 0 | for (int i=0; i < DICT_MAX_WATCHERS; i++) { |
975 | 0 | interp->dict_state.watchers[i] = NULL; |
976 | 0 | } |
977 | |
|
978 | 0 | for (int i=0; i < TYPE_MAX_WATCHERS; i++) { |
979 | 0 | interp->type_watchers[i] = NULL; |
980 | 0 | } |
981 | |
|
982 | 0 | for (int i=0; i < FUNC_MAX_WATCHERS; i++) { |
983 | 0 | interp->func_watchers[i] = NULL; |
984 | 0 | } |
985 | 0 | interp->active_func_watchers = 0; |
986 | |
|
987 | 0 | for (int i=0; i < CODE_MAX_WATCHERS; i++) { |
988 | 0 | interp->code_watchers[i] = NULL; |
989 | 0 | } |
990 | 0 | interp->active_code_watchers = 0; |
991 | |
|
992 | 0 | for (int i=0; i < CONTEXT_MAX_WATCHERS; i++) { |
993 | 0 | interp->context_watchers[i] = NULL; |
994 | 0 | } |
995 | 0 | interp->active_context_watchers = 0; |
996 | | // XXX Once we have one allocator per interpreter (i.e. |
997 | | // per-interpreter GC) we must ensure that all of the interpreter's |
998 | | // objects have been cleaned up at the point. |
999 | | |
1000 | | // We could clear interp->threads.freelist here |
1001 | | // if it held more than just the initial thread state. |
1002 | 0 | } |
1003 | | |
1004 | | |
1005 | | void |
1006 | | PyInterpreterState_Clear(PyInterpreterState *interp) |
1007 | 0 | { |
1008 | | // Use the current Python thread state to call audit hooks and to collect |
1009 | | // garbage. It can be different than the current Python thread state |
1010 | | // of 'interp'. |
1011 | 0 | PyThreadState *current_tstate = current_fast_get(); |
1012 | 0 | _PyImport_ClearCore(interp); |
1013 | 0 | interpreter_clear(interp, current_tstate); |
1014 | 0 | } |
1015 | | |
1016 | | |
1017 | | void |
1018 | | _PyInterpreterState_Clear(PyThreadState *tstate) |
1019 | 0 | { |
1020 | 0 | _PyImport_ClearCore(tstate->interp); |
1021 | 0 | interpreter_clear(tstate->interp, tstate); |
1022 | 0 | } |
1023 | | |
1024 | | |
1025 | | static inline void tstate_deactivate(PyThreadState *tstate); |
1026 | | static void tstate_set_detached(PyThreadState *tstate, int detached_state); |
1027 | | static void zapthreads(PyInterpreterState *interp); |
1028 | | |
1029 | | void |
1030 | | PyInterpreterState_Delete(PyInterpreterState *interp) |
1031 | 0 | { |
1032 | 0 | _PyRuntimeState *runtime = interp->runtime; |
1033 | 0 | struct pyinterpreters *interpreters = &runtime->interpreters; |
1034 | | |
1035 | | // XXX Clearing the "current" thread state should happen before |
1036 | | // we start finalizing the interpreter (or the current thread state). |
1037 | 0 | PyThreadState *tcur = current_fast_get(); |
1038 | 0 | if (tcur != NULL && interp == tcur->interp) { |
1039 | | /* Unset current thread. After this, many C API calls become crashy. */ |
1040 | 0 | _PyThreadState_Detach(tcur); |
1041 | 0 | } |
1042 | |
|
1043 | 0 | zapthreads(interp); |
1044 | | |
1045 | | // XXX These two calls should be done at the end of clear_interpreter(), |
1046 | | // but currently some objects get decref'ed after that. |
1047 | | #ifdef Py_REF_DEBUG |
1048 | | _PyInterpreterState_FinalizeRefTotal(interp); |
1049 | | #endif |
1050 | 0 | _PyInterpreterState_FinalizeAllocatedBlocks(interp); |
1051 | |
|
1052 | 0 | HEAD_LOCK(runtime); |
1053 | 0 | PyInterpreterState **p; |
1054 | 0 | for (p = &interpreters->head; ; p = &(*p)->next) { |
1055 | 0 | if (*p == NULL) { |
1056 | 0 | Py_FatalError("NULL interpreter"); |
1057 | 0 | } |
1058 | 0 | if (*p == interp) { |
1059 | 0 | break; |
1060 | 0 | } |
1061 | 0 | } |
1062 | 0 | if (interp->threads.head != NULL) { |
1063 | 0 | Py_FatalError("remaining threads"); |
1064 | 0 | } |
1065 | 0 | *p = interp->next; |
1066 | |
|
1067 | 0 | if (interpreters->main == interp) { |
1068 | 0 | interpreters->main = NULL; |
1069 | 0 | if (interpreters->head != NULL) { |
1070 | 0 | Py_FatalError("remaining subinterpreters"); |
1071 | 0 | } |
1072 | 0 | } |
1073 | 0 | HEAD_UNLOCK(runtime); |
1074 | |
|
1075 | 0 | _Py_qsbr_fini(interp); |
1076 | |
|
1077 | 0 | _PyObject_FiniState(interp); |
1078 | |
|
1079 | 0 | PyConfig_Clear(&interp->config); |
1080 | |
|
1081 | 0 | free_interpreter(interp); |
1082 | 0 | } |
1083 | | |
1084 | | |
1085 | | #ifdef HAVE_FORK |
1086 | | /* |
1087 | | * Delete all interpreter states except the main interpreter. If there |
1088 | | * is a current interpreter state, it *must* be the main interpreter. |
1089 | | */ |
1090 | | PyStatus |
1091 | | _PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime) |
1092 | 0 | { |
1093 | 0 | struct pyinterpreters *interpreters = &runtime->interpreters; |
1094 | |
|
1095 | 0 | PyThreadState *tstate = _PyThreadState_Swap(runtime, NULL); |
1096 | 0 | if (tstate != NULL && tstate->interp != interpreters->main) { |
1097 | 0 | return _PyStatus_ERR("not main interpreter"); |
1098 | 0 | } |
1099 | | |
1100 | 0 | HEAD_LOCK(runtime); |
1101 | 0 | PyInterpreterState *interp = interpreters->head; |
1102 | 0 | interpreters->head = NULL; |
1103 | 0 | while (interp != NULL) { |
1104 | 0 | if (interp == interpreters->main) { |
1105 | 0 | interpreters->main->next = NULL; |
1106 | 0 | interpreters->head = interp; |
1107 | 0 | interp = interp->next; |
1108 | 0 | continue; |
1109 | 0 | } |
1110 | | |
1111 | | // XXX Won't this fail since PyInterpreterState_Clear() requires |
1112 | | // the "current" tstate to be set? |
1113 | 0 | PyInterpreterState_Clear(interp); // XXX must activate? |
1114 | 0 | zapthreads(interp); |
1115 | 0 | PyInterpreterState *prev_interp = interp; |
1116 | 0 | interp = interp->next; |
1117 | 0 | free_interpreter(prev_interp); |
1118 | 0 | } |
1119 | 0 | HEAD_UNLOCK(runtime); |
1120 | |
|
1121 | 0 | if (interpreters->head == NULL) { |
1122 | 0 | return _PyStatus_ERR("missing main interpreter"); |
1123 | 0 | } |
1124 | 0 | _PyThreadState_Swap(runtime, tstate); |
1125 | 0 | return _PyStatus_OK(); |
1126 | 0 | } |
1127 | | #endif |
1128 | | |
1129 | | static inline void |
1130 | | set_main_thread(PyInterpreterState *interp, PyThreadState *tstate) |
1131 | 0 | { |
1132 | 0 | _Py_atomic_store_ptr_relaxed(&interp->threads.main, tstate); |
1133 | 0 | } |
1134 | | |
1135 | | static inline PyThreadState * |
1136 | | get_main_thread(PyInterpreterState *interp) |
1137 | 0 | { |
1138 | 0 | return _Py_atomic_load_ptr_relaxed(&interp->threads.main); |
1139 | 0 | } |
1140 | | |
1141 | | void |
1142 | | _PyErr_SetInterpreterAlreadyRunning(void) |
1143 | 0 | { |
1144 | 0 | PyErr_SetString(PyExc_InterpreterError, "interpreter already running"); |
1145 | 0 | } |
1146 | | |
1147 | | int |
1148 | | _PyInterpreterState_SetRunningMain(PyInterpreterState *interp) |
1149 | 0 | { |
1150 | 0 | if (get_main_thread(interp) != NULL) { |
1151 | 0 | _PyErr_SetInterpreterAlreadyRunning(); |
1152 | 0 | return -1; |
1153 | 0 | } |
1154 | 0 | PyThreadState *tstate = current_fast_get(); |
1155 | 0 | _Py_EnsureTstateNotNULL(tstate); |
1156 | 0 | if (tstate->interp != interp) { |
1157 | 0 | PyErr_SetString(PyExc_RuntimeError, |
1158 | 0 | "current tstate has wrong interpreter"); |
1159 | 0 | return -1; |
1160 | 0 | } |
1161 | 0 | set_main_thread(interp, tstate); |
1162 | |
|
1163 | 0 | return 0; |
1164 | 0 | } |
1165 | | |
1166 | | void |
1167 | | _PyInterpreterState_SetNotRunningMain(PyInterpreterState *interp) |
1168 | 0 | { |
1169 | 0 | assert(get_main_thread(interp) == current_fast_get()); |
1170 | 0 | set_main_thread(interp, NULL); |
1171 | 0 | } |
1172 | | |
1173 | | int |
1174 | | _PyInterpreterState_IsRunningMain(PyInterpreterState *interp) |
1175 | 0 | { |
1176 | 0 | if (get_main_thread(interp) != NULL) { |
1177 | 0 | return 1; |
1178 | 0 | } |
1179 | | // Embedders might not know to call _PyInterpreterState_SetRunningMain(), |
1180 | | // so their main thread wouldn't show it is running the main interpreter's |
1181 | | // program. (Py_Main() doesn't have this problem.) For now this isn't |
1182 | | // critical. If it were, we would need to infer "running main" from other |
1183 | | // information, like if it's the main interpreter. We used to do that |
1184 | | // but the naive approach led to some inconsistencies that caused problems. |
1185 | 0 | return 0; |
1186 | 0 | } |
1187 | | |
1188 | | int |
1189 | | _PyThreadState_IsRunningMain(PyThreadState *tstate) |
1190 | 0 | { |
1191 | 0 | PyInterpreterState *interp = tstate->interp; |
1192 | | // See the note in _PyInterpreterState_IsRunningMain() about |
1193 | | // possible false negatives here for embedders. |
1194 | 0 | return get_main_thread(interp) == tstate; |
1195 | 0 | } |
1196 | | |
1197 | | void |
1198 | | _PyInterpreterState_ReinitRunningMain(PyThreadState *tstate) |
1199 | 0 | { |
1200 | 0 | PyInterpreterState *interp = tstate->interp; |
1201 | 0 | if (get_main_thread(interp) != tstate) { |
1202 | 0 | set_main_thread(interp, NULL); |
1203 | 0 | } |
1204 | 0 | } |
1205 | | |
1206 | | |
1207 | | //---------- |
1208 | | // accessors |
1209 | | //---------- |
1210 | | |
1211 | | int |
1212 | | _PyInterpreterState_IsReady(PyInterpreterState *interp) |
1213 | 0 | { |
1214 | 0 | return interp->_ready; |
1215 | 0 | } |
1216 | | |
1217 | | #ifndef NDEBUG |
1218 | | static inline int |
1219 | | check_interpreter_whence(long whence) |
1220 | | { |
1221 | | if(whence < 0) { |
1222 | | return -1; |
1223 | | } |
1224 | | if (whence > _PyInterpreterState_WHENCE_MAX) { |
1225 | | return -1; |
1226 | | } |
1227 | | return 0; |
1228 | | } |
1229 | | #endif |
1230 | | |
1231 | | long |
1232 | | _PyInterpreterState_GetWhence(PyInterpreterState *interp) |
1233 | 0 | { |
1234 | 0 | assert(check_interpreter_whence(interp->_whence) == 0); |
1235 | 0 | return interp->_whence; |
1236 | 0 | } |
1237 | | |
1238 | | void |
1239 | | _PyInterpreterState_SetWhence(PyInterpreterState *interp, long whence) |
1240 | 37 | { |
1241 | 37 | assert(interp->_whence != _PyInterpreterState_WHENCE_NOTSET); |
1242 | 37 | assert(check_interpreter_whence(whence) == 0); |
1243 | 37 | interp->_whence = whence; |
1244 | 37 | } |
1245 | | |
1246 | | |
1247 | | PyObject * |
1248 | | _Py_GetMainModule(PyThreadState *tstate) |
1249 | 0 | { |
1250 | | // We return None to indicate "not found" or "bogus". |
1251 | 0 | PyObject *modules = _PyImport_GetModulesRef(tstate->interp); |
1252 | 0 | if (modules == Py_None) { |
1253 | 0 | return modules; |
1254 | 0 | } |
1255 | 0 | PyObject *module = NULL; |
1256 | 0 | (void)PyMapping_GetOptionalItem(modules, &_Py_ID(__main__), &module); |
1257 | 0 | Py_DECREF(modules); |
1258 | 0 | if (module == NULL && !PyErr_Occurred()) { |
1259 | 0 | Py_RETURN_NONE; |
1260 | 0 | } |
1261 | 0 | return module; |
1262 | 0 | } |
1263 | | |
1264 | | int |
1265 | | _Py_CheckMainModule(PyObject *module) |
1266 | 0 | { |
1267 | 0 | if (module == NULL || module == Py_None) { |
1268 | 0 | if (!PyErr_Occurred()) { |
1269 | 0 | (void)_PyErr_SetModuleNotFoundError(&_Py_ID(__main__)); |
1270 | 0 | } |
1271 | 0 | return -1; |
1272 | 0 | } |
1273 | 0 | if (!Py_IS_TYPE(module, &PyModule_Type)) { |
1274 | | /* The __main__ module has been tampered with. */ |
1275 | 0 | PyObject *msg = PyUnicode_FromString("invalid __main__ module"); |
1276 | 0 | if (msg != NULL) { |
1277 | 0 | (void)PyErr_SetImportError(msg, &_Py_ID(__main__), NULL); |
1278 | 0 | Py_DECREF(msg); |
1279 | 0 | } |
1280 | 0 | return -1; |
1281 | 0 | } |
1282 | 0 | return 0; |
1283 | 0 | } |
1284 | | |
1285 | | |
1286 | | PyObject * |
1287 | | PyInterpreterState_GetDict(PyInterpreterState *interp) |
1288 | 26.9k | { |
1289 | 26.9k | if (interp->dict == NULL) { |
1290 | 13 | interp->dict = PyDict_New(); |
1291 | 13 | if (interp->dict == NULL) { |
1292 | 0 | PyErr_Clear(); |
1293 | 0 | } |
1294 | 13 | } |
1295 | | /* Returning NULL means no per-interpreter dict is available. */ |
1296 | 26.9k | return interp->dict; |
1297 | 26.9k | } |
1298 | | |
1299 | | |
1300 | | //---------- |
1301 | | // interp ID |
1302 | | //---------- |
1303 | | |
1304 | | int64_t |
1305 | | _PyInterpreterState_ObjectToID(PyObject *idobj) |
1306 | 0 | { |
1307 | 0 | if (!_PyIndex_Check(idobj)) { |
1308 | 0 | PyErr_Format(PyExc_TypeError, |
1309 | 0 | "interpreter ID must be an int, got %.100s", |
1310 | 0 | Py_TYPE(idobj)->tp_name); |
1311 | 0 | return -1; |
1312 | 0 | } |
1313 | | |
1314 | | // This may raise OverflowError. |
1315 | | // For now, we don't worry about if LLONG_MAX < INT64_MAX. |
1316 | 0 | long long id = PyLong_AsLongLong(idobj); |
1317 | 0 | if (id == -1 && PyErr_Occurred()) { |
1318 | 0 | return -1; |
1319 | 0 | } |
1320 | | |
1321 | 0 | if (id < 0) { |
1322 | 0 | PyErr_Format(PyExc_ValueError, |
1323 | 0 | "interpreter ID must be a non-negative int, got %R", |
1324 | 0 | idobj); |
1325 | 0 | return -1; |
1326 | 0 | } |
1327 | | #if LLONG_MAX > INT64_MAX |
1328 | | else if (id > INT64_MAX) { |
1329 | | PyErr_SetString(PyExc_OverflowError, "int too big to convert"); |
1330 | | return -1; |
1331 | | } |
1332 | | #endif |
1333 | 0 | else { |
1334 | 0 | return (int64_t)id; |
1335 | 0 | } |
1336 | 0 | } |
1337 | | |
1338 | | int64_t |
1339 | | PyInterpreterState_GetID(PyInterpreterState *interp) |
1340 | 12 | { |
1341 | 12 | if (interp == NULL) { |
1342 | 0 | PyErr_SetString(PyExc_RuntimeError, "no interpreter provided"); |
1343 | 0 | return -1; |
1344 | 0 | } |
1345 | 12 | return interp->id; |
1346 | 12 | } |
1347 | | |
1348 | | PyObject * |
1349 | | _PyInterpreterState_GetIDObject(PyInterpreterState *interp) |
1350 | 0 | { |
1351 | 0 | int64_t interpid = interp->id; |
1352 | 0 | if (interpid < 0) { |
1353 | 0 | return NULL; |
1354 | 0 | } |
1355 | 0 | assert(interpid < LLONG_MAX); |
1356 | 0 | return PyLong_FromLongLong(interpid); |
1357 | 0 | } |
1358 | | |
1359 | | |
1360 | | |
1361 | | void |
1362 | | _PyInterpreterState_IDIncref(PyInterpreterState *interp) |
1363 | 0 | { |
1364 | 0 | _Py_atomic_add_ssize(&interp->id_refcount, 1); |
1365 | 0 | } |
1366 | | |
1367 | | |
1368 | | void |
1369 | | _PyInterpreterState_IDDecref(PyInterpreterState *interp) |
1370 | 0 | { |
1371 | 0 | _PyRuntimeState *runtime = interp->runtime; |
1372 | |
|
1373 | 0 | Py_ssize_t refcount = _Py_atomic_add_ssize(&interp->id_refcount, -1); |
1374 | |
|
1375 | 0 | if (refcount == 1 && interp->requires_idref) { |
1376 | 0 | PyThreadState *tstate = |
1377 | 0 | _PyThreadState_NewBound(interp, _PyThreadState_WHENCE_FINI); |
1378 | | |
1379 | | // XXX Possible GILState issues? |
1380 | 0 | PyThreadState *save_tstate = _PyThreadState_Swap(runtime, tstate); |
1381 | 0 | Py_EndInterpreter(tstate); |
1382 | 0 | _PyThreadState_Swap(runtime, save_tstate); |
1383 | 0 | } |
1384 | 0 | } |
1385 | | |
1386 | | int |
1387 | | _PyInterpreterState_RequiresIDRef(PyInterpreterState *interp) |
1388 | 0 | { |
1389 | 0 | return interp->requires_idref; |
1390 | 0 | } |
1391 | | |
1392 | | void |
1393 | | _PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required) |
1394 | 0 | { |
1395 | 0 | interp->requires_idref = required ? 1 : 0; |
1396 | 0 | } |
1397 | | |
1398 | | |
1399 | | //----------------------------- |
1400 | | // look up an interpreter state |
1401 | | //----------------------------- |
1402 | | |
1403 | | /* Return the interpreter associated with the current OS thread. |
1404 | | |
1405 | | The GIL must be held. |
1406 | | */ |
1407 | | |
1408 | | PyInterpreterState* |
1409 | | PyInterpreterState_Get(void) |
1410 | 27.0k | { |
1411 | 27.0k | _Py_AssertHoldsTstate(); |
1412 | 27.0k | PyInterpreterState *interp = _Py_tss_interp; |
1413 | 27.0k | if (interp == NULL) { |
1414 | 0 | Py_FatalError("no current interpreter"); |
1415 | 0 | } |
1416 | 27.0k | return interp; |
1417 | 27.0k | } |
1418 | | |
1419 | | |
1420 | | static PyInterpreterState * |
1421 | | interp_look_up_id(_PyRuntimeState *runtime, int64_t requested_id) |
1422 | 0 | { |
1423 | 0 | PyInterpreterState *interp = runtime->interpreters.head; |
1424 | 0 | while (interp != NULL) { |
1425 | 0 | int64_t id = interp->id; |
1426 | 0 | assert(id >= 0); |
1427 | 0 | if (requested_id == id) { |
1428 | 0 | return interp; |
1429 | 0 | } |
1430 | 0 | interp = PyInterpreterState_Next(interp); |
1431 | 0 | } |
1432 | 0 | return NULL; |
1433 | 0 | } |
1434 | | |
1435 | | /* Return the interpreter state with the given ID. |
1436 | | |
1437 | | Fail with RuntimeError if the interpreter is not found. */ |
1438 | | |
1439 | | PyInterpreterState * |
1440 | | _PyInterpreterState_LookUpID(int64_t requested_id) |
1441 | 0 | { |
1442 | 0 | PyInterpreterState *interp = NULL; |
1443 | 0 | if (requested_id >= 0) { |
1444 | 0 | _PyRuntimeState *runtime = &_PyRuntime; |
1445 | 0 | HEAD_LOCK(runtime); |
1446 | 0 | interp = interp_look_up_id(runtime, requested_id); |
1447 | 0 | HEAD_UNLOCK(runtime); |
1448 | 0 | } |
1449 | 0 | if (interp == NULL && !PyErr_Occurred()) { |
1450 | 0 | PyErr_Format(PyExc_InterpreterNotFoundError, |
1451 | 0 | "unrecognized interpreter ID %lld", requested_id); |
1452 | 0 | } |
1453 | 0 | return interp; |
1454 | 0 | } |
1455 | | |
1456 | | PyInterpreterState * |
1457 | | _PyInterpreterState_LookUpIDObject(PyObject *requested_id) |
1458 | 0 | { |
1459 | 0 | int64_t id = _PyInterpreterState_ObjectToID(requested_id); |
1460 | 0 | if (id < 0) { |
1461 | 0 | return NULL; |
1462 | 0 | } |
1463 | 0 | return _PyInterpreterState_LookUpID(id); |
1464 | 0 | } |
1465 | | |
1466 | | |
1467 | | /********************************/ |
1468 | | /* the per-thread runtime state */ |
1469 | | /********************************/ |
1470 | | |
1471 | | #ifndef NDEBUG |
1472 | | static inline int |
1473 | | tstate_is_alive(PyThreadState *tstate) |
1474 | | { |
1475 | | return (tstate->_status.initialized && |
1476 | | !tstate->_status.finalized && |
1477 | | !tstate->_status.cleared && |
1478 | | !tstate->_status.finalizing); |
1479 | | } |
1480 | | #endif |
1481 | | |
1482 | | |
1483 | | //---------- |
1484 | | // lifecycle |
1485 | | //---------- |
1486 | | |
1487 | | static _PyStackChunk* |
1488 | | allocate_chunk(int size_in_bytes, _PyStackChunk* previous) |
1489 | 36.5k | { |
1490 | 36.5k | assert(size_in_bytes % sizeof(PyObject **) == 0); |
1491 | 36.5k | _PyStackChunk *res = _PyObject_VirtualAlloc(size_in_bytes); |
1492 | 36.5k | if (res == NULL) { |
1493 | 0 | return NULL; |
1494 | 0 | } |
1495 | 36.5k | res->previous = previous; |
1496 | 36.5k | res->size = size_in_bytes; |
1497 | 36.5k | res->top = 0; |
1498 | 36.5k | return res; |
1499 | 36.5k | } |
1500 | | |
1501 | | static void |
1502 | | reset_threadstate(_PyThreadStateImpl *tstate) |
1503 | 0 | { |
1504 | | // Set to _PyThreadState_INIT directly? |
1505 | 0 | memcpy(tstate, |
1506 | 0 | &initial._main_interpreter._initial_thread, |
1507 | 0 | sizeof(*tstate)); |
1508 | 0 | } |
1509 | | |
1510 | | static _PyThreadStateImpl * |
1511 | | alloc_threadstate(PyInterpreterState *interp) |
1512 | 37 | { |
1513 | 37 | _PyThreadStateImpl *tstate; |
1514 | | |
1515 | | // Try the preallocated tstate first. |
1516 | 37 | tstate = _Py_atomic_exchange_ptr(&interp->threads.preallocated, NULL); |
1517 | | |
1518 | | // Fall back to the allocator. |
1519 | 37 | if (tstate == NULL) { |
1520 | 0 | tstate = PyMem_RawCalloc(1, sizeof(_PyThreadStateImpl)); |
1521 | 0 | if (tstate == NULL) { |
1522 | 0 | return NULL; |
1523 | 0 | } |
1524 | 0 | reset_threadstate(tstate); |
1525 | 0 | } |
1526 | | // Set the interpreter before any later initialization can fail. |
1527 | 37 | tstate->base.interp = interp; |
1528 | 37 | return tstate; |
1529 | 37 | } |
1530 | | |
1531 | | static void |
1532 | | free_threadstate(_PyThreadStateImpl *tstate) |
1533 | 0 | { |
1534 | 0 | PyInterpreterState *interp = tstate->base.interp; |
1535 | | #ifdef Py_STATS |
1536 | | _PyStats_ThreadFini(tstate); |
1537 | | #endif |
1538 | | // The initial thread state of the interpreter is allocated |
1539 | | // as part of the interpreter state so should not be freed. |
1540 | 0 | if (tstate == &interp->_initial_thread) { |
1541 | | // Make it available again. |
1542 | 0 | reset_threadstate(tstate); |
1543 | 0 | assert(interp->threads.preallocated == NULL); |
1544 | 0 | _Py_atomic_store_ptr(&interp->threads.preallocated, tstate); |
1545 | 0 | } |
1546 | 0 | else { |
1547 | 0 | PyMem_RawFree(tstate); |
1548 | 0 | } |
1549 | 0 | } |
1550 | | |
1551 | | static void |
1552 | | decref_threadstate(_PyThreadStateImpl *tstate) |
1553 | 0 | { |
1554 | 0 | if (_Py_atomic_add_ssize(&tstate->refcount, -1) == 1) { |
1555 | | // The last reference to the thread state is gone. |
1556 | 0 | free_threadstate(tstate); |
1557 | 0 | } |
1558 | 0 | } |
1559 | | |
1560 | | /* Get the thread state to a minimal consistent state. |
1561 | | Further init happens in pylifecycle.c before it can be used. |
1562 | | All fields not initialized here are expected to be zeroed out, |
1563 | | e.g. by PyMem_RawCalloc() or memset(), or otherwise pre-initialized. |
1564 | | The interpreter state is not manipulated. Instead it is assumed that |
1565 | | the thread is getting added to the interpreter. |
1566 | | */ |
1567 | | |
1568 | | static void |
1569 | | init_threadstate(_PyThreadStateImpl *_tstate, |
1570 | | PyInterpreterState *interp, uint64_t id, int whence) |
1571 | 37 | { |
1572 | 37 | PyThreadState *tstate = (PyThreadState *)_tstate; |
1573 | 37 | if (tstate->_status.initialized) { |
1574 | 0 | Py_FatalError("thread state already initialized"); |
1575 | 0 | } |
1576 | | |
1577 | 37 | assert(interp != NULL); |
1578 | 37 | tstate->interp = interp; |
1579 | 37 | tstate->eval_breaker = |
1580 | 37 | _Py_atomic_load_uintptr_relaxed(&interp->ceval.instrumentation_version); |
1581 | | |
1582 | | // next/prev are set in add_threadstate(). |
1583 | 37 | assert(tstate->next == NULL); |
1584 | 37 | assert(tstate->prev == NULL); |
1585 | | |
1586 | 37 | assert(tstate->_whence == _PyThreadState_WHENCE_NOTSET); |
1587 | 37 | assert(whence >= 0 && whence <= _PyThreadState_WHENCE_THREADING_DAEMON); |
1588 | 37 | tstate->_whence = whence; |
1589 | | |
1590 | 37 | assert(id > 0); |
1591 | 37 | tstate->id = id; |
1592 | | |
1593 | | // thread_id and native_thread_id are set in bind_tstate(). |
1594 | | |
1595 | 37 | tstate->py_recursion_limit = interp->ceval.recursion_limit; |
1596 | 37 | tstate->py_recursion_remaining = interp->ceval.recursion_limit; |
1597 | 37 | tstate->exc_info = &tstate->exc_state; |
1598 | | |
1599 | | // PyGILState_Release must not try to delete this thread state. |
1600 | | // This is cleared when PyGILState_Ensure() creates the thread state. |
1601 | 37 | tstate->gilstate_counter = 1; |
1602 | | |
1603 | | // Initialize the embedded base frame - sentinel at the bottom of the frame stack |
1604 | 37 | _tstate->base_frame.previous = NULL; |
1605 | 37 | _tstate->base_frame.f_executable = PyStackRef_None; |
1606 | 37 | _tstate->base_frame.f_funcobj = PyStackRef_NULL; |
1607 | 37 | _tstate->base_frame.f_globals = NULL; |
1608 | 37 | _tstate->base_frame.f_builtins = NULL; |
1609 | 37 | _tstate->base_frame.f_locals = NULL; |
1610 | 37 | _tstate->base_frame.frame_obj = NULL; |
1611 | 37 | _tstate->base_frame.instr_ptr = NULL; |
1612 | 37 | _tstate->base_frame.stackpointer = _tstate->base_frame.localsplus; |
1613 | 37 | _tstate->base_frame.return_offset = 0; |
1614 | 37 | _tstate->base_frame.owner = FRAME_OWNED_BY_INTERPRETER; |
1615 | 37 | _tstate->base_frame.visited = 0; |
1616 | | #ifdef Py_DEBUG |
1617 | | _tstate->base_frame.lltrace = 0; |
1618 | | #endif |
1619 | | #ifdef Py_GIL_DISABLED |
1620 | | _tstate->base_frame.tlbc_index = 0; |
1621 | | #endif |
1622 | 37 | _tstate->base_frame.localsplus[0] = PyStackRef_NULL; |
1623 | | |
1624 | | // current_frame starts pointing to the base frame |
1625 | 37 | tstate->current_frame = &_tstate->base_frame; |
1626 | | // base_frame pointer for profilers to validate stack unwinding |
1627 | 37 | tstate->base_frame = &_tstate->base_frame; |
1628 | 37 | tstate->last_profiled_frame = NULL; |
1629 | 37 | tstate->last_profiled_frame_seq = 0; |
1630 | 37 | tstate->datastack_chunk = NULL; |
1631 | 37 | tstate->datastack_top = NULL; |
1632 | 37 | tstate->datastack_limit = NULL; |
1633 | 37 | tstate->datastack_cached_chunk = NULL; |
1634 | 37 | tstate->what_event = -1; |
1635 | 37 | tstate->current_executor = NULL; |
1636 | 37 | tstate->jit_exit = NULL; |
1637 | 37 | tstate->dict_global_version = 0; |
1638 | | |
1639 | 37 | _tstate->c_stack_soft_limit = UINTPTR_MAX; |
1640 | 37 | _tstate->c_stack_top = 0; |
1641 | 37 | _tstate->c_stack_hard_limit = 0; |
1642 | | |
1643 | 37 | _tstate->c_stack_init_base = 0; |
1644 | 37 | _tstate->c_stack_init_top = 0; |
1645 | | |
1646 | 37 | _tstate->asyncio_running_loop = NULL; |
1647 | 37 | _tstate->asyncio_running_task = NULL; |
1648 | 37 | _tstate->lazy_imports = NULL; |
1649 | | |
1650 | | #ifdef _Py_TIER2 |
1651 | | _tstate->jit_tracer_state = NULL; |
1652 | | #endif |
1653 | 37 | tstate->delete_later = NULL; |
1654 | | |
1655 | 37 | llist_init(&_tstate->mem_free_queue); |
1656 | 37 | llist_init(&_tstate->asyncio_tasks_head); |
1657 | 37 | if (interp->stoptheworld.requested || _PyRuntime.stoptheworld.requested) { |
1658 | | // Start in the suspended state if there is an ongoing stop-the-world. |
1659 | 0 | tstate->state = _Py_THREAD_SUSPENDED; |
1660 | 0 | } |
1661 | | |
1662 | 37 | tstate->_status.initialized = 1; |
1663 | 37 | } |
1664 | | |
1665 | | static void |
1666 | | add_threadstate(PyInterpreterState *interp, PyThreadState *tstate, |
1667 | | PyThreadState *next) |
1668 | 37 | { |
1669 | 37 | assert(interp->threads.head != tstate); |
1670 | 37 | if (next != NULL) { |
1671 | 0 | assert(next->prev == NULL || next->prev == tstate); |
1672 | 0 | next->prev = tstate; |
1673 | 0 | } |
1674 | 37 | tstate->next = next; |
1675 | 37 | assert(tstate->prev == NULL); |
1676 | 37 | interp->threads.head = tstate; |
1677 | 37 | } |
1678 | | |
1679 | | static PyThreadState * |
1680 | | new_threadstate(PyInterpreterState *interp, int whence) |
1681 | 37 | { |
1682 | | // Allocate the thread state. |
1683 | 37 | _PyThreadStateImpl *tstate = alloc_threadstate(interp); |
1684 | 37 | if (tstate == NULL) { |
1685 | 0 | return NULL; |
1686 | 0 | } |
1687 | | |
1688 | | #ifdef Py_STATS |
1689 | | // The PyStats structure is quite large and is allocated separated from |
1690 | | // tstate. |
1691 | | if (!_PyStats_ThreadInit(interp, tstate)) { |
1692 | | free_threadstate(tstate); |
1693 | | return NULL; |
1694 | | } |
1695 | | #endif |
1696 | | #ifdef Py_GIL_DISABLED |
1697 | | int32_t tlbc_idx = _Py_ReserveTLBCIndex(interp); |
1698 | | if (tlbc_idx < 0) { |
1699 | | free_threadstate(tstate); |
1700 | | return NULL; |
1701 | | } |
1702 | | Py_ssize_t qsbr_idx = _Py_qsbr_reserve(interp); |
1703 | | if (qsbr_idx < 0) { |
1704 | | _Py_UnreserveTLBCIndex(interp, tlbc_idx); |
1705 | | free_threadstate(tstate); |
1706 | | return NULL; |
1707 | | } |
1708 | | #endif |
1709 | | |
1710 | | /* We serialize concurrent creation to protect global state. */ |
1711 | 37 | HEAD_LOCK(interp->runtime); |
1712 | | |
1713 | | // Initialize the new thread state. |
1714 | 37 | interp->threads.next_unique_id += 1; |
1715 | 37 | uint64_t id = interp->threads.next_unique_id; |
1716 | 37 | init_threadstate(tstate, interp, id, whence); |
1717 | | |
1718 | | // Add the new thread state to the interpreter. |
1719 | 37 | PyThreadState *old_head = interp->threads.head; |
1720 | 37 | add_threadstate(interp, (PyThreadState *)tstate, old_head); |
1721 | | |
1722 | 37 | HEAD_UNLOCK(interp->runtime); |
1723 | | |
1724 | | #ifdef Py_GIL_DISABLED |
1725 | | // Must be called with lock unlocked to avoid lock ordering deadlocks. |
1726 | | _Py_qsbr_register(tstate, interp, qsbr_idx); |
1727 | | tstate->tlbc_index = tlbc_idx; |
1728 | | #endif |
1729 | | |
1730 | 37 | return (PyThreadState *)tstate; |
1731 | 37 | } |
1732 | | |
1733 | | PyThreadState * |
1734 | | PyThreadState_New(PyInterpreterState *interp) |
1735 | 0 | { |
1736 | 0 | return _PyThreadState_NewBound(interp, _PyThreadState_WHENCE_UNKNOWN); |
1737 | 0 | } |
1738 | | |
1739 | | PyThreadState * |
1740 | | _PyThreadState_NewBound(PyInterpreterState *interp, int whence) |
1741 | 0 | { |
1742 | 0 | PyThreadState *tstate = new_threadstate(interp, whence); |
1743 | 0 | if (tstate) { |
1744 | 0 | bind_tstate(tstate); |
1745 | | // This makes sure there's a gilstate tstate bound |
1746 | | // as soon as possible. |
1747 | 0 | if (gilstate_get() == NULL) { |
1748 | 0 | bind_gilstate_tstate(tstate); |
1749 | 0 | } |
1750 | 0 | } |
1751 | 0 | return tstate; |
1752 | 0 | } |
1753 | | |
1754 | | // This must be followed by a call to _PyThreadState_Bind(); |
1755 | | PyThreadState * |
1756 | | _PyThreadState_New(PyInterpreterState *interp, int whence) |
1757 | 37 | { |
1758 | 37 | return new_threadstate(interp, whence); |
1759 | 37 | } |
1760 | | |
1761 | | // We keep this for stable ABI compabibility. |
1762 | | PyAPI_FUNC(PyThreadState*) |
1763 | | _PyThreadState_Prealloc(PyInterpreterState *interp) |
1764 | 0 | { |
1765 | 0 | return _PyThreadState_New(interp, _PyThreadState_WHENCE_UNKNOWN); |
1766 | 0 | } |
1767 | | |
1768 | | // We keep this around for (accidental) stable ABI compatibility. |
1769 | | // Realistically, no extensions are using it. |
1770 | | PyAPI_FUNC(void) |
1771 | | _PyThreadState_Init(PyThreadState *tstate) |
1772 | 0 | { |
1773 | 0 | Py_FatalError("_PyThreadState_Init() is for internal use only"); |
1774 | 0 | } |
1775 | | |
1776 | | |
1777 | | static void |
1778 | | clear_datastack(PyThreadState *tstate) |
1779 | 0 | { |
1780 | 0 | _PyStackChunk *chunk = tstate->datastack_chunk; |
1781 | 0 | tstate->datastack_chunk = NULL; |
1782 | 0 | while (chunk != NULL) { |
1783 | 0 | _PyStackChunk *prev = chunk->previous; |
1784 | 0 | _PyObject_VirtualFree(chunk, chunk->size); |
1785 | 0 | chunk = prev; |
1786 | 0 | } |
1787 | 0 | if (tstate->datastack_cached_chunk != NULL) { |
1788 | 0 | _PyObject_VirtualFree(tstate->datastack_cached_chunk, |
1789 | 0 | tstate->datastack_cached_chunk->size); |
1790 | 0 | tstate->datastack_cached_chunk = NULL; |
1791 | 0 | } |
1792 | 0 | } |
1793 | | |
1794 | | void |
1795 | | PyThreadState_Clear(PyThreadState *tstate) |
1796 | 0 | { |
1797 | 0 | assert(tstate->_status.initialized && !tstate->_status.cleared); |
1798 | 0 | assert(current_fast_get()->interp == tstate->interp); |
1799 | | // GH-126016: In the _interpreters module, KeyboardInterrupt exceptions |
1800 | | // during PyEval_EvalCode() are sent to finalization, which doesn't let us |
1801 | | // mark threads as "not running main". So, for now this assertion is |
1802 | | // disabled. |
1803 | | // XXX assert(!_PyThreadState_IsRunningMain(tstate)); |
1804 | | // XXX assert(!tstate->_status.bound || tstate->_status.unbound); |
1805 | 0 | tstate->_status.finalizing = 1; // just in case |
1806 | | |
1807 | | /* XXX Conditions we need to enforce: |
1808 | | |
1809 | | * the GIL must be held by the current thread |
1810 | | * current_fast_get()->interp must match tstate->interp |
1811 | | * for the main interpreter, current_fast_get() must be the main thread |
1812 | | */ |
1813 | |
|
1814 | 0 | int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose; |
1815 | |
|
1816 | 0 | if (verbose && tstate->current_frame != tstate->base_frame) { |
1817 | | /* bpo-20526: After the main thread calls |
1818 | | _PyInterpreterState_SetFinalizing() in Py_FinalizeEx() |
1819 | | (or in Py_EndInterpreter() for subinterpreters), |
1820 | | threads must exit when trying to take the GIL. |
1821 | | If a thread exit in the middle of _PyEval_EvalFrameDefault(), |
1822 | | tstate->frame is not reset to its previous value. |
1823 | | It is more likely with daemon threads, but it can happen |
1824 | | with regular threads if threading._shutdown() fails |
1825 | | (ex: interrupted by CTRL+C). */ |
1826 | 0 | fprintf(stderr, |
1827 | 0 | "PyThreadState_Clear: warning: thread still has a frame\n"); |
1828 | 0 | } |
1829 | |
|
1830 | 0 | if (verbose && tstate->current_exception != NULL) { |
1831 | 0 | fprintf(stderr, "PyThreadState_Clear: warning: thread has an exception set\n"); |
1832 | 0 | _PyErr_Print(tstate); |
1833 | 0 | } |
1834 | | |
1835 | | /* At this point tstate shouldn't be used any more, |
1836 | | neither to run Python code nor for other uses. |
1837 | | |
1838 | | This is tricky when current_fast_get() == tstate, in the same way |
1839 | | as noted in interpreter_clear() above. The below finalizers |
1840 | | can possibly run Python code or otherwise use the partially |
1841 | | cleared thread state. For now we trust that isn't a problem |
1842 | | in practice. |
1843 | | */ |
1844 | | // XXX Deal with the possibility of problematic finalizers. |
1845 | | |
1846 | | /* Don't clear tstate->pyframe: it is a borrowed reference */ |
1847 | |
|
1848 | 0 | Py_CLEAR(tstate->threading_local_key); |
1849 | 0 | Py_CLEAR(tstate->threading_local_sentinel); |
1850 | |
|
1851 | 0 | Py_CLEAR(((_PyThreadStateImpl *)tstate)->asyncio_running_loop); |
1852 | 0 | Py_CLEAR(((_PyThreadStateImpl *)tstate)->asyncio_running_task); |
1853 | | |
1854 | |
|
1855 | 0 | Py_CLEAR(tstate->dict); |
1856 | 0 | Py_CLEAR(tstate->async_exc); |
1857 | |
|
1858 | 0 | Py_CLEAR(tstate->current_exception); |
1859 | |
|
1860 | 0 | Py_CLEAR(tstate->exc_state.exc_value); |
1861 | | |
1862 | | /* The stack of exception states should contain just this thread. */ |
1863 | 0 | if (verbose && tstate->exc_info != &tstate->exc_state) { |
1864 | 0 | fprintf(stderr, |
1865 | 0 | "PyThreadState_Clear: warning: thread still has a generator\n"); |
1866 | 0 | } |
1867 | |
|
1868 | 0 | if (tstate->c_profilefunc != NULL) { |
1869 | 0 | FT_ATOMIC_ADD_SSIZE(tstate->interp->sys_profiling_threads, -1); |
1870 | 0 | tstate->c_profilefunc = NULL; |
1871 | 0 | } |
1872 | 0 | if (tstate->c_tracefunc != NULL) { |
1873 | 0 | FT_ATOMIC_ADD_SSIZE(tstate->interp->sys_tracing_threads, -1); |
1874 | 0 | tstate->c_tracefunc = NULL; |
1875 | 0 | } |
1876 | |
|
1877 | 0 | Py_CLEAR(tstate->c_profileobj); |
1878 | 0 | Py_CLEAR(tstate->c_traceobj); |
1879 | |
|
1880 | 0 | Py_CLEAR(tstate->async_gen_firstiter); |
1881 | 0 | Py_CLEAR(tstate->async_gen_finalizer); |
1882 | |
|
1883 | 0 | Py_CLEAR(tstate->context); |
1884 | | |
1885 | | // Finalizers above may resolve imports and create this set. |
1886 | 0 | Py_CLEAR(((_PyThreadStateImpl *)tstate)->lazy_imports); |
1887 | |
|
1888 | | #ifdef Py_GIL_DISABLED |
1889 | | // Each thread should clear own freelists in free-threading builds. |
1890 | | struct _Py_freelists *freelists = _Py_freelists_GET(); |
1891 | | _PyObject_ClearFreeLists(freelists, 1); |
1892 | | |
1893 | | // Flush the thread's local GC allocation count to the global count |
1894 | | // before the thread state is cleared, otherwise the count is lost. |
1895 | | _PyThreadStateImpl *tstate_impl = (_PyThreadStateImpl *)tstate; |
1896 | | _Py_atomic_add_int(&tstate->interp->gc.young.count, |
1897 | | (int)tstate_impl->gc.alloc_count); |
1898 | | tstate_impl->gc.alloc_count = 0; |
1899 | | |
1900 | | // Merge our thread-local refcounts into the type's own refcount and |
1901 | | // free our local refcount array. |
1902 | | _PyObject_FinalizePerThreadRefcounts(tstate_impl); |
1903 | | |
1904 | | // Remove ourself from the biased reference counting table of threads. |
1905 | | _Py_brc_remove_thread(tstate); |
1906 | | |
1907 | | // Release our thread-local copies of the bytecode for reuse by another |
1908 | | // thread |
1909 | | _Py_ClearTLBCIndex(tstate_impl); |
1910 | | #endif |
1911 | | |
1912 | | // Merge our queue of pointers to be freed into the interpreter queue. |
1913 | 0 | _PyMem_AbandonDelayed(tstate); |
1914 | |
|
1915 | 0 | _PyThreadState_ClearMimallocHeaps(tstate); |
1916 | |
|
1917 | | #ifdef _Py_TIER2 |
1918 | | _PyJit_TracerFree((_PyThreadStateImpl *)tstate); |
1919 | | #endif |
1920 | |
|
1921 | 0 | tstate->_status.cleared = 1; |
1922 | | |
1923 | | // XXX Call _PyThreadStateSwap(runtime, NULL) here if "current". |
1924 | | // XXX Do it as early in the function as possible. |
1925 | 0 | } |
1926 | | |
1927 | | static void |
1928 | | decrement_stoptheworld_countdown(struct _stoptheworld_state *stw); |
1929 | | |
1930 | | // `release_gil` releases the current thread's GIL. For states already removed |
1931 | | // by _PyThreadState_RemoveExcept(), `is_unlinked` limits cleanup to task transfer. |
1932 | | static void |
1933 | | tstate_delete_common(PyThreadState *tstate, int release_gil, int is_unlinked) |
1934 | 0 | { |
1935 | 0 | assert(tstate->_status.cleared && !tstate->_status.finalized); |
1936 | 0 | assert(!is_unlinked || !release_gil); |
1937 | |
|
1938 | 0 | _PyThreadStateImpl *tstate_impl = (_PyThreadStateImpl *)tstate; |
1939 | | // Finalizers may register tasks during or after PyThreadState_Clear(). |
1940 | | // Transfer them before normal unlinking or GIL release: cross-thread task |
1941 | | // removal uses stop-the-world or the GIL, not asyncio_tasks_lock. |
1942 | 0 | if (!llist_empty(&tstate_impl->asyncio_tasks_head)) { |
1943 | | // Serialize transfers from concurrently exiting threads. |
1944 | 0 | PyMutex_Lock(&tstate->interp->asyncio_tasks_lock); |
1945 | 0 | llist_concat(&tstate->interp->asyncio_tasks_head, |
1946 | 0 | &tstate_impl->asyncio_tasks_head); |
1947 | 0 | PyMutex_Unlock(&tstate->interp->asyncio_tasks_lock); |
1948 | 0 | } |
1949 | 0 | assert(llist_empty(&tstate_impl->asyncio_tasks_head)); |
1950 | 0 | if (is_unlinked) { |
1951 | 0 | return; |
1952 | 0 | } |
1953 | | |
1954 | 0 | tstate_verify_not_active(tstate); |
1955 | 0 | assert(!_PyThreadState_IsRunningMain(tstate)); |
1956 | |
|
1957 | 0 | PyInterpreterState *interp = tstate->interp; |
1958 | 0 | if (interp == NULL) { |
1959 | 0 | Py_FatalError("NULL interpreter"); |
1960 | 0 | } |
1961 | 0 | _PyRuntimeState *runtime = interp->runtime; |
1962 | |
|
1963 | 0 | HEAD_LOCK(runtime); |
1964 | 0 | if (tstate->prev) { |
1965 | 0 | tstate->prev->next = tstate->next; |
1966 | 0 | } |
1967 | 0 | else { |
1968 | 0 | interp->threads.head = tstate->next; |
1969 | 0 | } |
1970 | 0 | if (tstate->next) { |
1971 | 0 | tstate->next->prev = tstate->prev; |
1972 | 0 | } |
1973 | 0 | int state = _Py_atomic_load_int_relaxed(&tstate->state); |
1974 | 0 | if (state != _Py_THREAD_SUSPENDED && |
1975 | 0 | state != _Py_THREAD_SUSPENDED_WAITING) |
1976 | 0 | { |
1977 | | // Any ongoing stop-the-world request should not wait for us because |
1978 | | // our thread is getting deleted. |
1979 | 0 | if (interp->stoptheworld.requested) { |
1980 | 0 | decrement_stoptheworld_countdown(&interp->stoptheworld); |
1981 | 0 | } |
1982 | 0 | if (runtime->stoptheworld.requested) { |
1983 | 0 | decrement_stoptheworld_countdown(&runtime->stoptheworld); |
1984 | 0 | } |
1985 | 0 | } |
1986 | |
|
1987 | | #if defined(Py_REF_DEBUG) && defined(Py_GIL_DISABLED) |
1988 | | // Add our portion of the total refcount to the interpreter's total. |
1989 | | tstate->interp->object_state.reftotal += tstate_impl->reftotal; |
1990 | | tstate_impl->reftotal = 0; |
1991 | | assert(tstate_impl->refcounts.values == NULL); |
1992 | | #endif |
1993 | |
|
1994 | | #if _Py_TIER2 |
1995 | | _PyJit_TracerFree((_PyThreadStateImpl *)tstate); |
1996 | | #endif |
1997 | |
|
1998 | 0 | HEAD_UNLOCK(runtime); |
1999 | | |
2000 | | // XXX Unbind in PyThreadState_Clear(), or earlier |
2001 | | // (and assert not-equal here)? |
2002 | 0 | if (tstate->_status.bound_gilstate) { |
2003 | 0 | unbind_gilstate_tstate(tstate); |
2004 | 0 | } |
2005 | 0 | if (tstate->_status.bound) { |
2006 | 0 | unbind_tstate(tstate); |
2007 | 0 | } |
2008 | | |
2009 | | // XXX Move to PyThreadState_Clear()? |
2010 | 0 | clear_datastack(tstate); |
2011 | |
|
2012 | 0 | if (release_gil) { |
2013 | 0 | _PyEval_ReleaseLock(tstate->interp, tstate, 1); |
2014 | 0 | } |
2015 | |
|
2016 | | #ifdef Py_GIL_DISABLED |
2017 | | _Py_qsbr_unregister(tstate); |
2018 | | #endif |
2019 | |
|
2020 | 0 | tstate->_status.finalized = 1; |
2021 | 0 | } |
2022 | | |
2023 | | static void |
2024 | | zapthreads(PyInterpreterState *interp) |
2025 | 0 | { |
2026 | 0 | PyThreadState *tstate; |
2027 | | /* No need to lock the mutex here because this should only happen |
2028 | | when the threads are all really dead (XXX famous last words). |
2029 | | |
2030 | | Cannot use _Py_FOR_EACH_TSTATE_UNLOCKED because we are freeing |
2031 | | the thread states here. |
2032 | | */ |
2033 | 0 | while ((tstate = interp->threads.head) != NULL) { |
2034 | 0 | tstate_verify_not_active(tstate); |
2035 | 0 | tstate_delete_common(tstate, /*release_gil=*/0, /*is_unlinked=*/0); |
2036 | 0 | free_threadstate((_PyThreadStateImpl *)tstate); |
2037 | 0 | } |
2038 | 0 | } |
2039 | | |
2040 | | |
2041 | | void |
2042 | | PyThreadState_Delete(PyThreadState *tstate) |
2043 | 0 | { |
2044 | 0 | _Py_EnsureTstateNotNULL(tstate); |
2045 | 0 | tstate_verify_not_active(tstate); |
2046 | 0 | tstate_delete_common(tstate, /*release_gil=*/0, /*is_unlinked=*/0); |
2047 | 0 | free_threadstate((_PyThreadStateImpl *)tstate); |
2048 | 0 | } |
2049 | | |
2050 | | |
2051 | | void |
2052 | | _PyThreadState_DeleteCurrent(PyThreadState *tstate) |
2053 | 0 | { |
2054 | 0 | _Py_EnsureTstateNotNULL(tstate); |
2055 | | #ifdef Py_GIL_DISABLED |
2056 | | _Py_qsbr_detach(((_PyThreadStateImpl *)tstate)->qsbr); |
2057 | | #endif |
2058 | | #ifdef Py_STATS |
2059 | | _PyStats_Detach((_PyThreadStateImpl *)tstate); |
2060 | | #endif |
2061 | 0 | current_fast_clear(tstate->interp->runtime); |
2062 | 0 | tstate_delete_common(tstate, /*release_gil=*/1, /*is_unlinked=*/0); |
2063 | 0 | free_threadstate((_PyThreadStateImpl *)tstate); |
2064 | 0 | } |
2065 | | |
2066 | | void |
2067 | | PyThreadState_DeleteCurrent(void) |
2068 | 0 | { |
2069 | 0 | PyThreadState *tstate = current_fast_get(); |
2070 | 0 | _PyThreadState_DeleteCurrent(tstate); |
2071 | 0 | } |
2072 | | |
2073 | | |
2074 | | // Unlinks and removes all thread states from `tstate->interp`, with the |
2075 | | // exception of the one passed as an argument. However, it does not delete |
2076 | | // these thread states. Instead, it returns the removed thread states as a |
2077 | | // linked list. |
2078 | | // |
2079 | | // Note that if there is a current thread state, it *must* be the one |
2080 | | // passed as argument. Also, this won't touch any interpreters other |
2081 | | // than the current one, since we don't know which thread state should |
2082 | | // be kept in those other interpreters. |
2083 | | PyThreadState * |
2084 | | _PyThreadState_RemoveExcept(PyThreadState *tstate) |
2085 | 0 | { |
2086 | 0 | assert(tstate != NULL); |
2087 | 0 | PyInterpreterState *interp = tstate->interp; |
2088 | 0 | _PyRuntimeState *runtime = interp->runtime; |
2089 | |
|
2090 | | #ifdef Py_GIL_DISABLED |
2091 | | assert(runtime->stoptheworld.world_stopped); |
2092 | | #endif |
2093 | |
|
2094 | 0 | HEAD_LOCK(runtime); |
2095 | | /* Remove all thread states, except tstate, from the linked list of |
2096 | | thread states. */ |
2097 | 0 | PyThreadState *list = interp->threads.head; |
2098 | 0 | if (list == tstate) { |
2099 | 0 | list = tstate->next; |
2100 | 0 | } |
2101 | 0 | if (tstate->prev) { |
2102 | 0 | tstate->prev->next = tstate->next; |
2103 | 0 | } |
2104 | 0 | if (tstate->next) { |
2105 | 0 | tstate->next->prev = tstate->prev; |
2106 | 0 | } |
2107 | 0 | tstate->prev = tstate->next = NULL; |
2108 | 0 | interp->threads.head = tstate; |
2109 | 0 | HEAD_UNLOCK(runtime); |
2110 | |
|
2111 | 0 | return list; |
2112 | 0 | } |
2113 | | |
2114 | | // Deletes the thread states in the linked list `list`. |
2115 | | // |
2116 | | // This is intended to be used in conjunction with _PyThreadState_RemoveExcept. |
2117 | | // |
2118 | | // If `is_after_fork` is true, the thread states are immediately freed. |
2119 | | // Otherwise, they are decref'd because they may still be referenced by an |
2120 | | // OS thread. |
2121 | | void |
2122 | | _PyThreadState_DeleteList(PyThreadState *list, int is_after_fork) |
2123 | 0 | { |
2124 | | // The world can't be stopped because we PyThreadState_Clear() can |
2125 | | // call destructors. |
2126 | 0 | assert(!_PyRuntime.stoptheworld.world_stopped); |
2127 | |
|
2128 | 0 | PyThreadState *p, *next; |
2129 | 0 | for (p = list; p; p = next) { |
2130 | 0 | next = p->next; |
2131 | 0 | PyThreadState_Clear(p); |
2132 | 0 | tstate_delete_common(p, /*release_gil=*/0, /*is_unlinked=*/1); |
2133 | 0 | if (is_after_fork) { |
2134 | 0 | free_threadstate((_PyThreadStateImpl *)p); |
2135 | 0 | } |
2136 | 0 | else { |
2137 | 0 | decref_threadstate((_PyThreadStateImpl *)p); |
2138 | 0 | } |
2139 | 0 | } |
2140 | 0 | } |
2141 | | |
2142 | | |
2143 | | //---------- |
2144 | | // accessors |
2145 | | //---------- |
2146 | | |
2147 | | /* An extension mechanism to store arbitrary additional per-thread state. |
2148 | | PyThreadState_GetDict() returns a dictionary that can be used to hold such |
2149 | | state; the caller should pick a unique key and store its state there. If |
2150 | | PyThreadState_GetDict() returns NULL, an exception has *not* been raised |
2151 | | and the caller should assume no per-thread state is available. */ |
2152 | | |
2153 | | PyObject * |
2154 | | _PyThreadState_GetDict(PyThreadState *tstate) |
2155 | 8.09M | { |
2156 | 8.09M | assert(tstate != NULL); |
2157 | 8.09M | if (tstate->dict == NULL) { |
2158 | 4 | tstate->dict = PyDict_New(); |
2159 | 4 | if (tstate->dict == NULL) { |
2160 | 0 | _PyErr_Clear(tstate); |
2161 | 0 | } |
2162 | 4 | } |
2163 | 8.09M | return tstate->dict; |
2164 | 8.09M | } |
2165 | | |
2166 | | |
2167 | | PyObject * |
2168 | | PyThreadState_GetDict(void) |
2169 | 8.09M | { |
2170 | 8.09M | PyThreadState *tstate = current_fast_get(); |
2171 | 8.09M | if (tstate == NULL) { |
2172 | 0 | return NULL; |
2173 | 0 | } |
2174 | 8.09M | return _PyThreadState_GetDict(tstate); |
2175 | 8.09M | } |
2176 | | |
2177 | | |
2178 | | PyInterpreterState * |
2179 | | PyThreadState_GetInterpreter(PyThreadState *tstate) |
2180 | 0 | { |
2181 | 0 | assert(tstate != NULL); |
2182 | 0 | return tstate->interp; |
2183 | 0 | } |
2184 | | |
2185 | | |
2186 | | PyFrameObject* |
2187 | | PyThreadState_GetFrame(PyThreadState *tstate) |
2188 | 710k | { |
2189 | 710k | assert(tstate != NULL); |
2190 | 710k | _PyInterpreterFrame *f = _PyThreadState_GetFrame(tstate); |
2191 | 710k | if (f == NULL) { |
2192 | 0 | return NULL; |
2193 | 0 | } |
2194 | 710k | PyFrameObject *frame = _PyFrame_GetFrameObject(f); |
2195 | 710k | if (frame == NULL) { |
2196 | 0 | PyErr_Clear(); |
2197 | 0 | } |
2198 | 710k | return (PyFrameObject*)Py_XNewRef(frame); |
2199 | 710k | } |
2200 | | |
2201 | | |
2202 | | uint64_t |
2203 | | PyThreadState_GetID(PyThreadState *tstate) |
2204 | 0 | { |
2205 | 0 | assert(tstate != NULL); |
2206 | 0 | return tstate->id; |
2207 | 0 | } |
2208 | | |
2209 | | |
2210 | | static inline void |
2211 | | tstate_activate(PyThreadState *tstate) |
2212 | 1.95M | { |
2213 | 1.95M | assert(tstate != NULL); |
2214 | | // XXX assert(tstate_is_alive(tstate)); |
2215 | 1.95M | assert(tstate_is_bound(tstate)); |
2216 | 1.95M | assert(!tstate->_status.active); |
2217 | | |
2218 | 1.95M | assert(!tstate->_status.bound_gilstate || |
2219 | 1.95M | tstate == gilstate_get()); |
2220 | 1.95M | if (!tstate->_status.bound_gilstate) { |
2221 | 0 | bind_gilstate_tstate(tstate); |
2222 | 0 | } |
2223 | | |
2224 | 1.95M | tstate->_status.active = 1; |
2225 | 1.95M | } |
2226 | | |
2227 | | static inline void |
2228 | | tstate_deactivate(PyThreadState *tstate) |
2229 | 1.95M | { |
2230 | 1.95M | assert(tstate != NULL); |
2231 | | // XXX assert(tstate_is_alive(tstate)); |
2232 | 1.95M | assert(tstate_is_bound(tstate)); |
2233 | 1.95M | assert(tstate->_status.active); |
2234 | | |
2235 | | #if Py_STATS |
2236 | | _PyStats_Detach((_PyThreadStateImpl *)tstate); |
2237 | | #endif |
2238 | | |
2239 | 1.95M | tstate->_status.active = 0; |
2240 | | |
2241 | | // We do not unbind the gilstate tstate here. |
2242 | | // It will still be used in PyGILState_Ensure(). |
2243 | 1.95M | } |
2244 | | |
2245 | | static int |
2246 | | tstate_try_attach(PyThreadState *tstate) |
2247 | 1.95M | { |
2248 | | #ifdef Py_GIL_DISABLED |
2249 | | int expected = _Py_THREAD_DETACHED; |
2250 | | return _Py_atomic_compare_exchange_int(&tstate->state, |
2251 | | &expected, |
2252 | | _Py_THREAD_ATTACHED); |
2253 | | #else |
2254 | 1.95M | assert(tstate->state == _Py_THREAD_DETACHED); |
2255 | 1.95M | tstate->state = _Py_THREAD_ATTACHED; |
2256 | 1.95M | return 1; |
2257 | 1.95M | #endif |
2258 | 1.95M | } |
2259 | | |
2260 | | static int |
2261 | | tstate_try_attach_detached(PyThreadState *tstate, int *state) |
2262 | 0 | { |
2263 | | #ifdef Py_GIL_DISABLED |
2264 | | assert(*state == _Py_THREAD_DETACHED || |
2265 | | *state == _Py_THREAD_DETACHED_WAITING); |
2266 | | return _Py_atomic_compare_exchange_int(&tstate->state, |
2267 | | state, |
2268 | | _Py_THREAD_ATTACHED); |
2269 | | #else |
2270 | 0 | assert(tstate->state == _Py_THREAD_DETACHED); |
2271 | 0 | tstate->state = _Py_THREAD_ATTACHED; |
2272 | 0 | return 1; |
2273 | 0 | #endif |
2274 | 0 | } |
2275 | | |
2276 | | static void |
2277 | | tstate_set_detached(PyThreadState *tstate, int detached_state) |
2278 | 1.95M | { |
2279 | 1.95M | assert(_Py_atomic_load_int_relaxed(&tstate->state) == _Py_THREAD_ATTACHED); |
2280 | | #ifdef Py_GIL_DISABLED |
2281 | | _Py_atomic_store_int(&tstate->state, detached_state); |
2282 | | #else |
2283 | 1.95M | tstate->state = detached_state; |
2284 | 1.95M | #endif |
2285 | 1.95M | } |
2286 | | |
2287 | | static void |
2288 | | tstate_wait_attach(PyThreadState *tstate) |
2289 | 0 | { |
2290 | 0 | for (;;) { |
2291 | 0 | int state = _Py_atomic_load_int_relaxed(&tstate->state); |
2292 | 0 | if (state == _Py_THREAD_SUSPENDED) { |
2293 | | // Register an active attach waiter. The next stop-the-world |
2294 | | // request must let this thread attach before suspending it again. |
2295 | 0 | if (!_Py_atomic_compare_exchange_int( |
2296 | 0 | &tstate->state, &state, _Py_THREAD_SUSPENDED_WAITING)) |
2297 | 0 | { |
2298 | 0 | continue; |
2299 | 0 | } |
2300 | 0 | state = _Py_THREAD_SUSPENDED_WAITING; |
2301 | 0 | } |
2302 | 0 | if (state == _Py_THREAD_SUSPENDED_WAITING) { |
2303 | | // Park rechecks the state before sleeping, in case we were resumed. |
2304 | 0 | _PyParkingLot_Park(&tstate->state, &state, sizeof(tstate->state), |
2305 | 0 | /*timeout=*/-1, NULL, /*detach=*/0); |
2306 | 0 | } |
2307 | 0 | else if (state == _Py_THREAD_SHUTTING_DOWN) { |
2308 | | // We're shutting down, so we can't attach. |
2309 | 0 | _PyThreadState_HangThread(tstate); |
2310 | 0 | } |
2311 | 0 | else { |
2312 | 0 | assert(state == _Py_THREAD_DETACHED || |
2313 | 0 | state == _Py_THREAD_DETACHED_WAITING); |
2314 | 0 | if (tstate_try_attach_detached(tstate, &state)) { |
2315 | 0 | return; |
2316 | 0 | } |
2317 | 0 | } |
2318 | 0 | } |
2319 | 0 | } |
2320 | | |
2321 | | void |
2322 | | _PyThreadState_Attach(PyThreadState *tstate) |
2323 | 1.95M | { |
2324 | | #if defined(Py_DEBUG) |
2325 | | // This is called from PyEval_RestoreThread(). Similar |
2326 | | // to it, we need to ensure errno doesn't change. |
2327 | | int err = errno; |
2328 | | #endif |
2329 | | |
2330 | 1.95M | _Py_EnsureTstateNotNULL(tstate); |
2331 | 1.95M | if (current_fast_get() != NULL) { |
2332 | 0 | Py_FatalError("non-NULL old thread state"); |
2333 | 0 | } |
2334 | 1.95M | _PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate; |
2335 | 1.95M | if (_tstate->c_stack_hard_limit == 0) { |
2336 | 37 | _Py_InitializeRecursionLimits(tstate); |
2337 | 37 | } |
2338 | | |
2339 | 1.95M | while (1) { |
2340 | 1.95M | _PyEval_AcquireLock(tstate); |
2341 | | |
2342 | | // XXX assert(tstate_is_alive(tstate)); |
2343 | 1.95M | current_fast_set(&_PyRuntime, tstate); |
2344 | 1.95M | if (!tstate_try_attach(tstate)) { |
2345 | 0 | tstate_wait_attach(tstate); |
2346 | 0 | } |
2347 | 1.95M | tstate_activate(tstate); |
2348 | | |
2349 | | #ifdef Py_GIL_DISABLED |
2350 | | if (_PyEval_IsGILEnabled(tstate) && !tstate->holds_gil) { |
2351 | | // The GIL was enabled between our call to _PyEval_AcquireLock() |
2352 | | // and when we attached (the GIL can't go from enabled to disabled |
2353 | | // here because only a thread holding the GIL can disable |
2354 | | // it). Detach and try again. |
2355 | | tstate_set_detached(tstate, _Py_THREAD_DETACHED); |
2356 | | tstate_deactivate(tstate); |
2357 | | current_fast_clear(&_PyRuntime); |
2358 | | continue; |
2359 | | } |
2360 | | _Py_qsbr_attach(((_PyThreadStateImpl *)tstate)->qsbr); |
2361 | | #endif |
2362 | 1.95M | break; |
2363 | 1.95M | } |
2364 | | |
2365 | | // Resume previous critical section. This acquires the lock(s) from the |
2366 | | // top-most critical section. |
2367 | 1.95M | if (tstate->critical_section != 0) { |
2368 | 0 | _PyCriticalSection_Resume(tstate); |
2369 | 0 | } |
2370 | | |
2371 | | #ifdef Py_STATS |
2372 | | _PyStats_Attach((_PyThreadStateImpl *)tstate); |
2373 | | #endif |
2374 | | |
2375 | | #if defined(Py_DEBUG) |
2376 | | errno = err; |
2377 | | #endif |
2378 | 1.95M | } |
2379 | | |
2380 | | static void |
2381 | | detach_thread(PyThreadState *tstate, int detached_state) |
2382 | 1.95M | { |
2383 | | // XXX assert(tstate_is_alive(tstate) && tstate_is_bound(tstate)); |
2384 | 1.95M | assert(_Py_atomic_load_int_relaxed(&tstate->state) == _Py_THREAD_ATTACHED); |
2385 | 1.95M | assert(tstate == current_fast_get()); |
2386 | 1.95M | if (tstate->critical_section != 0) { |
2387 | 0 | _PyCriticalSection_SuspendAll(tstate); |
2388 | 0 | } |
2389 | | #ifdef Py_GIL_DISABLED |
2390 | | _Py_qsbr_detach(((_PyThreadStateImpl *)tstate)->qsbr); |
2391 | | #endif |
2392 | 1.95M | tstate_deactivate(tstate); |
2393 | 1.95M | tstate_set_detached(tstate, detached_state); |
2394 | 1.95M | current_fast_clear(&_PyRuntime); |
2395 | 1.95M | _PyEval_ReleaseLock(tstate->interp, tstate, 0); |
2396 | 1.95M | } |
2397 | | |
2398 | | void |
2399 | | _PyThreadState_Detach(PyThreadState *tstate) |
2400 | 1.95M | { |
2401 | 1.95M | detach_thread(tstate, _Py_THREAD_DETACHED); |
2402 | 1.95M | } |
2403 | | |
2404 | | void |
2405 | | _PyThreadState_Suspend(PyThreadState *tstate) |
2406 | 0 | { |
2407 | 0 | _PyRuntimeState *runtime = &_PyRuntime; |
2408 | |
|
2409 | 0 | assert(_Py_atomic_load_int_relaxed(&tstate->state) == _Py_THREAD_ATTACHED); |
2410 | |
|
2411 | 0 | struct _stoptheworld_state *stw = NULL; |
2412 | 0 | HEAD_LOCK(runtime); |
2413 | 0 | if (runtime->stoptheworld.requested) { |
2414 | 0 | stw = &runtime->stoptheworld; |
2415 | 0 | } |
2416 | 0 | else if (tstate->interp->stoptheworld.requested) { |
2417 | 0 | stw = &tstate->interp->stoptheworld; |
2418 | 0 | } |
2419 | 0 | HEAD_UNLOCK(runtime); |
2420 | |
|
2421 | 0 | if (stw == NULL) { |
2422 | | // Switch directly to "detached" if there is no active stop-the-world |
2423 | | // request. |
2424 | 0 | detach_thread(tstate, _Py_THREAD_DETACHED); |
2425 | 0 | return; |
2426 | 0 | } |
2427 | | |
2428 | | // Switch to "suspended" state. |
2429 | 0 | detach_thread(tstate, _Py_THREAD_SUSPENDED); |
2430 | | |
2431 | | // Decrease the count of remaining threads needing to park. |
2432 | 0 | HEAD_LOCK(runtime); |
2433 | 0 | decrement_stoptheworld_countdown(stw); |
2434 | 0 | HEAD_UNLOCK(runtime); |
2435 | 0 | } |
2436 | | |
2437 | | void |
2438 | | _PyThreadState_SetShuttingDown(PyThreadState *tstate) |
2439 | 0 | { |
2440 | 0 | _Py_atomic_store_int(&tstate->state, _Py_THREAD_SHUTTING_DOWN); |
2441 | | #ifdef Py_GIL_DISABLED |
2442 | | _PyParkingLot_UnparkAll(&tstate->state); |
2443 | | #endif |
2444 | 0 | } |
2445 | | |
2446 | | #ifdef Py_GIL_DISABLED |
2447 | | int |
2448 | | _PyThreadState_TrySuspendDetached(PyThreadState *tstate) |
2449 | | { |
2450 | | assert(tstate != _PyThreadState_GET()); |
2451 | | int expected = _Py_THREAD_DETACHED; |
2452 | | return _Py_atomic_compare_exchange_int(&tstate->state, &expected, |
2453 | | _Py_THREAD_SUSPENDED); |
2454 | | } |
2455 | | |
2456 | | void |
2457 | | _PyThreadState_ResumeDetached(PyThreadState *tstate) |
2458 | | { |
2459 | | assert(tstate != _PyThreadState_GET()); |
2460 | | int state = _Py_atomic_load_int_relaxed(&tstate->state); |
2461 | | int next_state; |
2462 | | do { |
2463 | | assert(state == _Py_THREAD_SUSPENDED || |
2464 | | state == _Py_THREAD_SUSPENDED_WAITING); |
2465 | | if (state == _Py_THREAD_SUSPENDED_WAITING) { |
2466 | | next_state = _Py_THREAD_DETACHED_WAITING; |
2467 | | } |
2468 | | else { |
2469 | | next_state = _Py_THREAD_DETACHED; |
2470 | | } |
2471 | | // Retry if an attach waiter registered concurrently. |
2472 | | } while (!_Py_atomic_compare_exchange_int( |
2473 | | &tstate->state, &state, next_state)); |
2474 | | // Wake the thread if it is parked in tstate_wait_attach(). |
2475 | | if (state == _Py_THREAD_SUSPENDED_WAITING) { |
2476 | | _PyParkingLot_UnparkAll(&tstate->state); |
2477 | | } |
2478 | | } |
2479 | | #endif |
2480 | | |
2481 | | // Decrease stop-the-world counter of remaining number of threads that need to |
2482 | | // pause. If we are the final thread to pause, notify the requesting thread. |
2483 | | static void |
2484 | | decrement_stoptheworld_countdown(struct _stoptheworld_state *stw) |
2485 | 0 | { |
2486 | 0 | assert(stw->thread_countdown > 0); |
2487 | 0 | if (--stw->thread_countdown == 0) { |
2488 | 0 | _PyEvent_Notify(&stw->stop_event); |
2489 | 0 | } |
2490 | 0 | } |
2491 | | |
2492 | | #ifdef Py_GIL_DISABLED |
2493 | | // Interpreter for _Py_FOR_EACH_STW_INTERP(). For global stop-the-world events, |
2494 | | // we start with the first interpreter and then iterate over all interpreters. |
2495 | | // For per-interpreter stop-the-world events, we only operate on the one |
2496 | | // interpreter. |
2497 | | static PyInterpreterState * |
2498 | | interp_for_stop_the_world(struct _stoptheworld_state *stw) |
2499 | | { |
2500 | | return (stw->is_global |
2501 | | ? PyInterpreterState_Head() |
2502 | | : _Py_CONTAINER_OF(stw, PyInterpreterState, stoptheworld)); |
2503 | | } |
2504 | | |
2505 | | // Loops over threads for a stop-the-world event. |
2506 | | // For global: all threads in all interpreters |
2507 | | // For per-interpreter: all threads in the interpreter |
2508 | | #define _Py_FOR_EACH_STW_INTERP(stw, i) \ |
2509 | | for (PyInterpreterState *i = interp_for_stop_the_world((stw)); \ |
2510 | | i != NULL; i = ((stw->is_global) ? i->next : NULL)) |
2511 | | |
2512 | | |
2513 | | // Try to transition threads atomically from the "detached" state to the |
2514 | | // "gc stopped" state. Returns true if all threads are in the "gc stopped" |
2515 | | static bool |
2516 | | park_detached_threads(struct _stoptheworld_state *stw) |
2517 | | { |
2518 | | int num_parked = 0; |
2519 | | _Py_FOR_EACH_STW_INTERP(stw, i) { |
2520 | | _Py_FOR_EACH_TSTATE_UNLOCKED(i, t) { |
2521 | | int state = _Py_atomic_load_int_relaxed(&t->state); |
2522 | | // DETACHED_WAITING threads remain counted until they attach and |
2523 | | // stop, so repeated pauses cannot prevent them from attaching. |
2524 | | if (state == _Py_THREAD_DETACHED) { |
2525 | | // Atomically transition to "suspended" if in "detached" state. |
2526 | | if (_Py_atomic_compare_exchange_int( |
2527 | | &t->state, &state, _Py_THREAD_SUSPENDED)) { |
2528 | | num_parked++; |
2529 | | } |
2530 | | } |
2531 | | else if (state == _Py_THREAD_ATTACHED && t != stw->requester) { |
2532 | | _Py_set_eval_breaker_bit(t, _PY_EVAL_PLEASE_STOP_BIT); |
2533 | | } |
2534 | | } |
2535 | | } |
2536 | | stw->thread_countdown -= num_parked; |
2537 | | assert(stw->thread_countdown >= 0); |
2538 | | return num_parked > 0 && stw->thread_countdown == 0; |
2539 | | } |
2540 | | |
2541 | | static void |
2542 | | stop_the_world(struct _stoptheworld_state *stw) |
2543 | | { |
2544 | | _PyRuntimeState *runtime = &_PyRuntime; |
2545 | | |
2546 | | // gh-137433: Acquire the rwmutex first to avoid deadlocks with daemon |
2547 | | // threads that may hang when blocked on lock acquisition. |
2548 | | if (stw->is_global) { |
2549 | | _PyRWMutex_Lock(&runtime->stoptheworld_mutex); |
2550 | | } |
2551 | | else { |
2552 | | _PyRWMutex_RLock(&runtime->stoptheworld_mutex); |
2553 | | } |
2554 | | PyMutex_Lock(&stw->mutex); |
2555 | | |
2556 | | HEAD_LOCK(runtime); |
2557 | | stw->requested = 1; |
2558 | | stw->thread_countdown = 0; |
2559 | | stw->stop_event = (PyEvent){0}; // zero-initialize (unset) |
2560 | | stw->requester = _PyThreadState_GET(); // may be NULL |
2561 | | FT_STAT_WORLD_STOP_INC(); |
2562 | | |
2563 | | _Py_FOR_EACH_STW_INTERP(stw, i) { |
2564 | | _Py_FOR_EACH_TSTATE_UNLOCKED(i, t) { |
2565 | | if (t != stw->requester) { |
2566 | | // Count all the other threads (we don't wait on ourself). |
2567 | | stw->thread_countdown++; |
2568 | | } |
2569 | | } |
2570 | | } |
2571 | | |
2572 | | if (stw->thread_countdown == 0) { |
2573 | | HEAD_UNLOCK(runtime); |
2574 | | stw->world_stopped = 1; |
2575 | | return; |
2576 | | } |
2577 | | |
2578 | | for (;;) { |
2579 | | // Switch threads that are detached to the GC stopped state |
2580 | | bool stopped_all_threads = park_detached_threads(stw); |
2581 | | HEAD_UNLOCK(runtime); |
2582 | | |
2583 | | if (stopped_all_threads) { |
2584 | | break; |
2585 | | } |
2586 | | |
2587 | | PyTime_t wait_ns = 1000*1000; // 1ms (arbitrary, may need tuning) |
2588 | | int detach = 0; |
2589 | | if (PyEvent_WaitTimed(&stw->stop_event, wait_ns, detach)) { |
2590 | | assert(stw->thread_countdown == 0); |
2591 | | break; |
2592 | | } |
2593 | | |
2594 | | HEAD_LOCK(runtime); |
2595 | | } |
2596 | | stw->world_stopped = 1; |
2597 | | } |
2598 | | |
2599 | | static void |
2600 | | start_the_world(struct _stoptheworld_state *stw) |
2601 | | { |
2602 | | _PyRuntimeState *runtime = &_PyRuntime; |
2603 | | assert(PyMutex_IsLocked(&stw->mutex)); |
2604 | | |
2605 | | HEAD_LOCK(runtime); |
2606 | | stw->requested = 0; |
2607 | | stw->world_stopped = 0; |
2608 | | // Switch threads back to the detached state. |
2609 | | _Py_FOR_EACH_STW_INTERP(stw, i) { |
2610 | | _Py_FOR_EACH_TSTATE_UNLOCKED(i, t) { |
2611 | | if (t != stw->requester) { |
2612 | | _PyThreadState_ResumeDetached(t); |
2613 | | } |
2614 | | } |
2615 | | } |
2616 | | stw->requester = NULL; |
2617 | | HEAD_UNLOCK(runtime); |
2618 | | PyMutex_Unlock(&stw->mutex); |
2619 | | if (stw->is_global) { |
2620 | | _PyRWMutex_Unlock(&runtime->stoptheworld_mutex); |
2621 | | } |
2622 | | else { |
2623 | | _PyRWMutex_RUnlock(&runtime->stoptheworld_mutex); |
2624 | | } |
2625 | | } |
2626 | | #endif // Py_GIL_DISABLED |
2627 | | |
2628 | | void |
2629 | | _PyEval_StopTheWorldAll(_PyRuntimeState *runtime) |
2630 | 0 | { |
2631 | | #ifdef Py_GIL_DISABLED |
2632 | | stop_the_world(&runtime->stoptheworld); |
2633 | | #endif |
2634 | 0 | } |
2635 | | |
2636 | | void |
2637 | | _PyEval_StartTheWorldAll(_PyRuntimeState *runtime) |
2638 | 0 | { |
2639 | | #ifdef Py_GIL_DISABLED |
2640 | | start_the_world(&runtime->stoptheworld); |
2641 | | #endif |
2642 | 0 | } |
2643 | | |
2644 | | void |
2645 | | _PyEval_StopTheWorld(PyInterpreterState *interp) |
2646 | 1.14k | { |
2647 | | #ifdef Py_GIL_DISABLED |
2648 | | stop_the_world(&interp->stoptheworld); |
2649 | | #endif |
2650 | 1.14k | } |
2651 | | |
2652 | | void |
2653 | | _PyEval_StartTheWorld(PyInterpreterState *interp) |
2654 | 1.14k | { |
2655 | | #ifdef Py_GIL_DISABLED |
2656 | | start_the_world(&interp->stoptheworld); |
2657 | | #endif |
2658 | 1.14k | } |
2659 | | |
2660 | | //---------- |
2661 | | // other API |
2662 | | //---------- |
2663 | | |
2664 | | /* Asynchronously raise an exception in a thread. |
2665 | | Requested by Just van Rossum and Alex Martelli. |
2666 | | To prevent naive misuse, you must write your own extension |
2667 | | to call this, or use ctypes. Must be called with the GIL held. |
2668 | | Returns the number of tstates modified (normally 1, but 0 if `id` didn't |
2669 | | match any known thread id). Can be called with exc=NULL to clear an |
2670 | | existing async exception. This raises no exceptions. */ |
2671 | | |
2672 | | // XXX Move this to Python/ceval_gil.c? |
2673 | | // XXX Deprecate this. |
2674 | | int |
2675 | | PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc) |
2676 | 0 | { |
2677 | 0 | PyInterpreterState *interp = _PyInterpreterState_GET(); |
2678 | | |
2679 | | /* Although the GIL is held, a few C API functions can be called |
2680 | | * without the GIL held, and in particular some that create and |
2681 | | * destroy thread and interpreter states. Those can mutate the |
2682 | | * list of thread states we're traversing, so to prevent that we lock |
2683 | | * head_mutex for the duration. |
2684 | | */ |
2685 | 0 | PyThreadState *tstate = NULL; |
2686 | 0 | _Py_FOR_EACH_TSTATE_BEGIN(interp, t) { |
2687 | 0 | if (t->thread_id == id) { |
2688 | 0 | tstate = t; |
2689 | 0 | break; |
2690 | 0 | } |
2691 | 0 | } |
2692 | 0 | _Py_FOR_EACH_TSTATE_END(interp); |
2693 | |
|
2694 | 0 | if (tstate != NULL) { |
2695 | | /* Tricky: we need to decref the current value |
2696 | | * (if any) in tstate->async_exc, but that can in turn |
2697 | | * allow arbitrary Python code to run, including |
2698 | | * perhaps calls to this function. To prevent |
2699 | | * deadlock, we need to release head_mutex before |
2700 | | * the decref. |
2701 | | */ |
2702 | 0 | Py_XINCREF(exc); |
2703 | 0 | PyObject *old_exc = _Py_atomic_exchange_ptr(&tstate->async_exc, exc); |
2704 | |
|
2705 | 0 | Py_XDECREF(old_exc); |
2706 | 0 | _Py_set_eval_breaker_bit(tstate, _PY_ASYNC_EXCEPTION_BIT); |
2707 | 0 | } |
2708 | |
|
2709 | 0 | return tstate != NULL; |
2710 | 0 | } |
2711 | | |
2712 | | //--------------------------------- |
2713 | | // API for the current thread state |
2714 | | //--------------------------------- |
2715 | | |
2716 | | PyThreadState * |
2717 | | PyThreadState_GetUnchecked(void) |
2718 | 444 | { |
2719 | 444 | return current_fast_get(); |
2720 | 444 | } |
2721 | | |
2722 | | |
2723 | | PyThreadState * |
2724 | | PyThreadState_Get(void) |
2725 | 150k | { |
2726 | 150k | PyThreadState *tstate = current_fast_get(); |
2727 | 150k | _Py_EnsureTstateNotNULL(tstate); |
2728 | 150k | return tstate; |
2729 | 150k | } |
2730 | | |
2731 | | PyThreadState * |
2732 | | _PyThreadState_Swap(_PyRuntimeState *runtime, PyThreadState *newts) |
2733 | 0 | { |
2734 | 0 | PyThreadState *oldts = current_fast_get(); |
2735 | 0 | if (oldts != NULL) { |
2736 | 0 | _PyThreadState_Detach(oldts); |
2737 | 0 | } |
2738 | 0 | if (newts != NULL) { |
2739 | 0 | _PyThreadState_Attach(newts); |
2740 | 0 | } |
2741 | 0 | return oldts; |
2742 | 0 | } |
2743 | | |
2744 | | PyThreadState * |
2745 | | PyThreadState_Swap(PyThreadState *newts) |
2746 | 0 | { |
2747 | 0 | return _PyThreadState_Swap(&_PyRuntime, newts); |
2748 | 0 | } |
2749 | | |
2750 | | |
2751 | | void |
2752 | | _PyThreadState_Bind(PyThreadState *tstate) |
2753 | 37 | { |
2754 | | // gh-104690: If Python is being finalized and PyInterpreterState_Delete() |
2755 | | // was called, tstate becomes a dangling pointer. |
2756 | 37 | assert(_PyThreadState_CheckConsistency(tstate)); |
2757 | | |
2758 | 37 | bind_tstate(tstate); |
2759 | | // This makes sure there's a gilstate tstate bound |
2760 | | // as soon as possible. |
2761 | 37 | if (gilstate_get() == NULL) { |
2762 | 37 | bind_gilstate_tstate(tstate); |
2763 | 37 | } |
2764 | 37 | } |
2765 | | |
2766 | | #if defined(Py_GIL_DISABLED) && !defined(Py_LIMITED_API) |
2767 | | uintptr_t |
2768 | | _Py_GetThreadLocal_Addr(void) |
2769 | | { |
2770 | | // gh-112535: Use the address of the thread-local PyThreadState variable as |
2771 | | // a unique identifier for the current thread. Each thread has a unique |
2772 | | // _Py_tss_tstate variable with a unique address. |
2773 | | return (uintptr_t)&_Py_tss_tstate; |
2774 | | } |
2775 | | #endif |
2776 | | |
2777 | | /***********************************/ |
2778 | | /* routines for advanced debuggers */ |
2779 | | /***********************************/ |
2780 | | |
2781 | | // (requested by David Beazley) |
2782 | | // Don't use unless you know what you are doing! |
2783 | | |
2784 | | PyInterpreterState * |
2785 | | PyInterpreterState_Head(void) |
2786 | 0 | { |
2787 | 0 | return _PyRuntime.interpreters.head; |
2788 | 0 | } |
2789 | | |
2790 | | PyInterpreterState * |
2791 | | PyInterpreterState_Main(void) |
2792 | 0 | { |
2793 | 0 | return _PyInterpreterState_Main(); |
2794 | 0 | } |
2795 | | |
2796 | | PyInterpreterState * |
2797 | 0 | PyInterpreterState_Next(PyInterpreterState *interp) { |
2798 | 0 | return interp->next; |
2799 | 0 | } |
2800 | | |
2801 | | PyThreadState * |
2802 | 0 | PyInterpreterState_ThreadHead(PyInterpreterState *interp) { |
2803 | 0 | return interp->threads.head; |
2804 | 0 | } |
2805 | | |
2806 | | PyThreadState * |
2807 | 0 | PyThreadState_Next(PyThreadState *tstate) { |
2808 | 0 | return tstate->next; |
2809 | 0 | } |
2810 | | |
2811 | | |
2812 | | /********************************************/ |
2813 | | /* reporting execution state of all threads */ |
2814 | | /********************************************/ |
2815 | | |
2816 | | /* The implementation of sys._current_frames(). This is intended to be |
2817 | | called with the GIL held, as it will be when called via |
2818 | | sys._current_frames(). It's possible it would work fine even without |
2819 | | the GIL held, but haven't thought enough about that. |
2820 | | */ |
2821 | | PyObject * |
2822 | | _PyThread_CurrentFrames(void) |
2823 | 0 | { |
2824 | 0 | _PyRuntimeState *runtime = &_PyRuntime; |
2825 | 0 | PyThreadState *tstate = current_fast_get(); |
2826 | 0 | if (_PySys_Audit(tstate, "sys._current_frames", NULL) < 0) { |
2827 | 0 | return NULL; |
2828 | 0 | } |
2829 | | |
2830 | 0 | PyObject *result = PyDict_New(); |
2831 | 0 | if (result == NULL) { |
2832 | 0 | return NULL; |
2833 | 0 | } |
2834 | | |
2835 | | /* for t in all of the current interpreter's thread states: |
2836 | | * if t's frame isn't NULL, map t's id to its frame |
2837 | | * Because these lists can mutate even when the GIL is held, we |
2838 | | * need to grab head_mutex for the duration. |
2839 | | */ |
2840 | 0 | PyInterpreterState *interp = tstate->interp; |
2841 | 0 | _PyEval_StopTheWorld(interp); |
2842 | 0 | HEAD_LOCK(runtime); |
2843 | 0 | _Py_FOR_EACH_TSTATE_UNLOCKED(interp, t) { |
2844 | 0 | _PyInterpreterFrame *frame = t->current_frame; |
2845 | 0 | frame = _PyFrame_GetFirstComplete(frame); |
2846 | 0 | if (frame == NULL) { |
2847 | 0 | continue; |
2848 | 0 | } |
2849 | 0 | PyObject *id = PyLong_FromUnsignedLong(t->thread_id); |
2850 | 0 | if (id == NULL) { |
2851 | 0 | goto fail; |
2852 | 0 | } |
2853 | 0 | PyObject *frameobj = (PyObject *)_PyFrame_GetFrameObject(frame); |
2854 | 0 | if (frameobj == NULL) { |
2855 | 0 | Py_DECREF(id); |
2856 | 0 | goto fail; |
2857 | 0 | } |
2858 | 0 | int stat = PyDict_SetItem(result, id, frameobj); |
2859 | 0 | Py_DECREF(id); |
2860 | 0 | if (stat < 0) { |
2861 | 0 | goto fail; |
2862 | 0 | } |
2863 | 0 | } |
2864 | 0 | goto done; |
2865 | | |
2866 | 0 | fail: |
2867 | 0 | Py_CLEAR(result); |
2868 | |
|
2869 | 0 | done: |
2870 | 0 | HEAD_UNLOCK(runtime); |
2871 | 0 | _PyEval_StartTheWorld(interp); |
2872 | 0 | return result; |
2873 | 0 | } |
2874 | | |
2875 | | /* The implementation of sys._current_exceptions(). This is intended to be |
2876 | | called with the GIL held, as it will be when called via |
2877 | | sys._current_exceptions(). It's possible it would work fine even without |
2878 | | the GIL held, but haven't thought enough about that. |
2879 | | */ |
2880 | | PyObject * |
2881 | | _PyThread_CurrentExceptions(void) |
2882 | 0 | { |
2883 | 0 | _PyRuntimeState *runtime = &_PyRuntime; |
2884 | 0 | PyThreadState *tstate = current_fast_get(); |
2885 | |
|
2886 | 0 | _Py_EnsureTstateNotNULL(tstate); |
2887 | |
|
2888 | 0 | if (_PySys_Audit(tstate, "sys._current_exceptions", NULL) < 0) { |
2889 | 0 | return NULL; |
2890 | 0 | } |
2891 | | |
2892 | 0 | PyObject *result = PyDict_New(); |
2893 | 0 | if (result == NULL) { |
2894 | 0 | return NULL; |
2895 | 0 | } |
2896 | | |
2897 | | /* for t in all of the current interpreter's thread states: |
2898 | | * if t's frame isn't NULL, map t's id to its exception |
2899 | | * Because these lists can mutate even when the GIL is held, we |
2900 | | * need to grab head_mutex for the duration. |
2901 | | */ |
2902 | 0 | PyInterpreterState *interp = tstate->interp; |
2903 | 0 | _PyEval_StopTheWorld(interp); |
2904 | 0 | HEAD_LOCK(runtime); |
2905 | 0 | _Py_FOR_EACH_TSTATE_UNLOCKED(interp, t) { |
2906 | 0 | _PyErr_StackItem *err_info = _PyErr_GetTopmostException(t); |
2907 | 0 | if (err_info == NULL) { |
2908 | 0 | continue; |
2909 | 0 | } |
2910 | 0 | PyObject *id = PyLong_FromUnsignedLong(t->thread_id); |
2911 | 0 | if (id == NULL) { |
2912 | 0 | goto fail; |
2913 | 0 | } |
2914 | 0 | PyObject *exc = err_info->exc_value; |
2915 | 0 | assert(exc == NULL || |
2916 | 0 | exc == Py_None || |
2917 | 0 | PyExceptionInstance_Check(exc)); |
2918 | |
|
2919 | 0 | int stat = PyDict_SetItem(result, id, exc == NULL ? Py_None : exc); |
2920 | 0 | Py_DECREF(id); |
2921 | 0 | if (stat < 0) { |
2922 | 0 | goto fail; |
2923 | 0 | } |
2924 | 0 | } |
2925 | 0 | goto done; |
2926 | | |
2927 | 0 | fail: |
2928 | 0 | Py_CLEAR(result); |
2929 | |
|
2930 | 0 | done: |
2931 | 0 | HEAD_UNLOCK(runtime); |
2932 | 0 | _PyEval_StartTheWorld(interp); |
2933 | 0 | return result; |
2934 | 0 | } |
2935 | | |
2936 | | |
2937 | | /***********************************/ |
2938 | | /* Python "auto thread state" API. */ |
2939 | | /***********************************/ |
2940 | | |
2941 | | /* Internal initialization/finalization functions called by |
2942 | | Py_Initialize/Py_FinalizeEx |
2943 | | */ |
2944 | | PyStatus |
2945 | | _PyGILState_Init(PyInterpreterState *interp) |
2946 | 37 | { |
2947 | 37 | if (!_Py_IsMainInterpreter(interp)) { |
2948 | | /* Currently, PyGILState is shared by all interpreters. The main |
2949 | | * interpreter is responsible to initialize it. */ |
2950 | 0 | return _PyStatus_OK(); |
2951 | 0 | } |
2952 | 37 | _PyRuntimeState *runtime = interp->runtime; |
2953 | 37 | assert(gilstate_get() == NULL); |
2954 | 37 | assert(runtime->gilstate.autoInterpreterState == NULL); |
2955 | 37 | runtime->gilstate.autoInterpreterState = interp; |
2956 | 37 | return _PyStatus_OK(); |
2957 | 37 | } |
2958 | | |
2959 | | void |
2960 | | _PyGILState_Fini(PyInterpreterState *interp) |
2961 | 0 | { |
2962 | 0 | if (!_Py_IsMainInterpreter(interp)) { |
2963 | | /* Currently, PyGILState is shared by all interpreters. The main |
2964 | | * interpreter is responsible to initialize it. */ |
2965 | 0 | return; |
2966 | 0 | } |
2967 | 0 | interp->runtime->gilstate.autoInterpreterState = NULL; |
2968 | 0 | } |
2969 | | |
2970 | | |
2971 | | // XXX Drop this. |
2972 | | void |
2973 | | _PyGILState_SetTstate(PyThreadState *tstate) |
2974 | 37 | { |
2975 | | /* must init with valid states */ |
2976 | 37 | assert(tstate != NULL); |
2977 | 37 | assert(tstate->interp != NULL); |
2978 | | |
2979 | 37 | if (!_Py_IsMainInterpreter(tstate->interp)) { |
2980 | | /* Currently, PyGILState is shared by all interpreters. The main |
2981 | | * interpreter is responsible to initialize it. */ |
2982 | 0 | return; |
2983 | 0 | } |
2984 | | |
2985 | | #ifndef NDEBUG |
2986 | | _PyRuntimeState *runtime = tstate->interp->runtime; |
2987 | | |
2988 | | assert(runtime->gilstate.autoInterpreterState == tstate->interp); |
2989 | | assert(gilstate_get() == tstate); |
2990 | | assert(tstate->gilstate_counter == 1); |
2991 | | #endif |
2992 | 37 | } |
2993 | | |
2994 | | PyInterpreterState * |
2995 | | _PyGILState_GetInterpreterStateUnsafe(void) |
2996 | 0 | { |
2997 | 0 | return _PyRuntime.gilstate.autoInterpreterState; |
2998 | 0 | } |
2999 | | |
3000 | | /* The public functions */ |
3001 | | |
3002 | | PyThreadState * |
3003 | | PyGILState_GetThisThreadState(void) |
3004 | 0 | { |
3005 | 0 | return gilstate_get(); |
3006 | 0 | } |
3007 | | |
3008 | | int |
3009 | | PyGILState_Check(void) |
3010 | 0 | { |
3011 | 0 | _PyRuntimeState *runtime = &_PyRuntime; |
3012 | 0 | if (!_Py_atomic_load_int_relaxed(&runtime->gilstate.check_enabled)) { |
3013 | 0 | return 1; |
3014 | 0 | } |
3015 | | |
3016 | 0 | PyThreadState *tstate = current_fast_get(); |
3017 | 0 | if (tstate == NULL) { |
3018 | 0 | return 0; |
3019 | 0 | } |
3020 | | |
3021 | 0 | PyThreadState *tcur = gilstate_get(); |
3022 | 0 | return (tstate == tcur); |
3023 | 0 | } |
3024 | | |
3025 | | static PyInterpreterGuard * |
3026 | | get_main_interp_guard(void) |
3027 | 0 | { |
3028 | 0 | PyInterpreterView *view = PyInterpreterView_FromMain(); |
3029 | 0 | if (view == NULL) { |
3030 | 0 | return NULL; |
3031 | 0 | } |
3032 | | |
3033 | 0 | PyInterpreterGuard *guard = PyInterpreterGuard_FromView(view); |
3034 | 0 | PyInterpreterView_Close(view); |
3035 | 0 | return guard; |
3036 | 0 | } |
3037 | | |
3038 | | PyGILState_STATE |
3039 | | PyGILState_Ensure(void) |
3040 | 0 | { |
3041 | | /* Note that we do not auto-init Python here - apart from |
3042 | | potential races with 2 threads auto-initializing, pep-311 |
3043 | | spells out other issues. Embedders are expected to have |
3044 | | called Py_Initialize(). */ |
3045 | |
|
3046 | 0 | PyThreadState *tcur = gilstate_get(); |
3047 | 0 | int has_gil; |
3048 | 0 | if (tcur == NULL) { |
3049 | | /* Create a new Python thread state for this thread */ |
3050 | 0 | PyInterpreterGuard *guard = get_main_interp_guard(); |
3051 | 0 | if (guard == NULL) { |
3052 | | // The main interpreter has finished, so we don't have |
3053 | | // any intepreter to make a thread state for. Hang the |
3054 | | // thread to act as failure. |
3055 | 0 | PyThread_hang_thread(); |
3056 | 0 | } |
3057 | 0 | tcur = new_threadstate(guard->interp, |
3058 | 0 | _PyThreadState_WHENCE_C_API); |
3059 | 0 | if (tcur == NULL) { |
3060 | 0 | Py_FatalError("Couldn't create thread-state for new thread"); |
3061 | 0 | } |
3062 | 0 | bind_tstate(tcur); |
3063 | 0 | bind_gilstate_tstate(tcur); |
3064 | | |
3065 | | /* This is our thread state! We'll need to delete it in the |
3066 | | matching call to PyGILState_Release(). */ |
3067 | 0 | assert(tcur->gilstate_counter == 1); |
3068 | 0 | tcur->gilstate_counter = 0; |
3069 | 0 | has_gil = 0; /* new thread state is never current */ |
3070 | 0 | PyInterpreterGuard_Close(guard); |
3071 | 0 | } |
3072 | 0 | else { |
3073 | 0 | has_gil = holds_gil(tcur); |
3074 | 0 | } |
3075 | | |
3076 | 0 | if (!has_gil) { |
3077 | 0 | PyEval_RestoreThread(tcur); |
3078 | 0 | } |
3079 | | |
3080 | | /* Update our counter in the thread-state - no need for locks: |
3081 | | - tcur will remain valid as we hold the GIL. |
3082 | | - the counter is safe as we are the only thread "allowed" |
3083 | | to modify this value |
3084 | | */ |
3085 | 0 | ++tcur->gilstate_counter; |
3086 | |
|
3087 | 0 | return has_gil ? PyGILState_LOCKED : PyGILState_UNLOCKED; |
3088 | 0 | } |
3089 | | |
3090 | | void |
3091 | | PyGILState_Release(PyGILState_STATE oldstate) |
3092 | 0 | { |
3093 | 0 | PyThreadState *tstate = gilstate_get(); |
3094 | 0 | if (tstate == NULL) { |
3095 | 0 | Py_FatalError("auto-releasing thread-state, " |
3096 | 0 | "but no thread-state for this thread"); |
3097 | 0 | } |
3098 | | |
3099 | | /* We must hold the GIL and have our thread state current */ |
3100 | 0 | if (!holds_gil(tstate)) { |
3101 | 0 | _Py_FatalErrorFormat(__func__, |
3102 | 0 | "thread state %p must be current when releasing", |
3103 | 0 | tstate); |
3104 | 0 | } |
3105 | 0 | --tstate->gilstate_counter; |
3106 | 0 | assert(tstate->gilstate_counter >= 0); /* illegal counter value */ |
3107 | | |
3108 | | /* If we're going to destroy this thread-state, we must |
3109 | | * clear it while the GIL is held, as destructors may run. |
3110 | | */ |
3111 | 0 | if (tstate->gilstate_counter == 0) { |
3112 | | /* can't have been locked when we created it */ |
3113 | 0 | assert(oldstate == PyGILState_UNLOCKED); |
3114 | | // XXX Unbind tstate here. |
3115 | | // gh-119585: `PyThreadState_Clear()` may call destructors that |
3116 | | // themselves use PyGILState_Ensure and PyGILState_Release, so make |
3117 | | // sure that gilstate_counter is not zero when calling it. |
3118 | 0 | ++tstate->gilstate_counter; |
3119 | 0 | PyThreadState_Clear(tstate); |
3120 | 0 | --tstate->gilstate_counter; |
3121 | | /* Delete the thread-state. Note this releases the GIL too! |
3122 | | * It's vital that the GIL be held here, to avoid shutdown |
3123 | | * races; see bugs 225673 and 1061968 (that nasty bug has a |
3124 | | * habit of coming back). |
3125 | | */ |
3126 | 0 | assert(tstate->gilstate_counter == 0); |
3127 | 0 | assert(current_fast_get() == tstate); |
3128 | 0 | _PyThreadState_DeleteCurrent(tstate); |
3129 | 0 | } |
3130 | | /* Release the lock if necessary */ |
3131 | 0 | else if (oldstate == PyGILState_UNLOCKED) { |
3132 | 0 | PyEval_SaveThread(); |
3133 | 0 | } |
3134 | 0 | } |
3135 | | |
3136 | | |
3137 | | /*************/ |
3138 | | /* Other API */ |
3139 | | /*************/ |
3140 | | |
3141 | | _PyFrameEvalFunction |
3142 | | _PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp) |
3143 | 0 | { |
3144 | 0 | if (interp->eval_frame == NULL) { |
3145 | 0 | return _PyEval_EvalFrameDefault; |
3146 | 0 | } |
3147 | 0 | return interp->eval_frame; |
3148 | 0 | } |
3149 | | |
3150 | | |
3151 | | void |
3152 | | _PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp, |
3153 | | _PyFrameEvalFunction eval_frame) |
3154 | 0 | { |
3155 | 0 | if (eval_frame == _PyEval_EvalFrameDefault) { |
3156 | 0 | eval_frame = NULL; |
3157 | 0 | } |
3158 | 0 | if (eval_frame == interp->eval_frame) { |
3159 | 0 | return; |
3160 | 0 | } |
3161 | | #ifdef _Py_TIER2 |
3162 | | if (eval_frame != NULL) { |
3163 | | _Py_Executors_InvalidateAll(interp, 1); |
3164 | | } |
3165 | | #endif |
3166 | 0 | RARE_EVENT_INC(set_eval_frame_func); |
3167 | 0 | _PyEval_StopTheWorld(interp); |
3168 | 0 | interp->eval_frame = eval_frame; |
3169 | | // reset when evaluator is reset |
3170 | 0 | interp->eval_frame_allow_specialization = 0; |
3171 | 0 | _PyEval_StartTheWorld(interp); |
3172 | 0 | } |
3173 | | |
3174 | | void |
3175 | | _PyInterpreterState_SetEvalFrameAllowSpecialization(PyInterpreterState *interp, |
3176 | | int allow_specialization) |
3177 | 0 | { |
3178 | 0 | if (allow_specialization == interp->eval_frame_allow_specialization) { |
3179 | 0 | return; |
3180 | 0 | } |
3181 | 0 | _Py_Executors_InvalidateAll(interp, 1); |
3182 | 0 | RARE_EVENT_INC(set_eval_frame_func); |
3183 | 0 | _PyEval_StopTheWorld(interp); |
3184 | 0 | interp->eval_frame_allow_specialization = allow_specialization; |
3185 | 0 | _PyEval_StartTheWorld(interp); |
3186 | 0 | } |
3187 | | |
3188 | | int |
3189 | | _PyInterpreterState_IsSpecializationEnabled(PyInterpreterState *interp) |
3190 | 280k | { |
3191 | 280k | return interp->eval_frame == NULL |
3192 | 0 | || interp->eval_frame_allow_specialization; |
3193 | 280k | } |
3194 | | |
3195 | | |
3196 | | const PyConfig* |
3197 | | _PyInterpreterState_GetConfig(PyInterpreterState *interp) |
3198 | 124M | { |
3199 | 124M | return &interp->config; |
3200 | 124M | } |
3201 | | |
3202 | | |
3203 | | const PyConfig* |
3204 | | _Py_GetConfig(void) |
3205 | 173k | { |
3206 | 173k | PyThreadState *tstate = current_fast_get(); |
3207 | 173k | _Py_EnsureTstateNotNULL(tstate); |
3208 | 173k | return _PyInterpreterState_GetConfig(tstate->interp); |
3209 | 173k | } |
3210 | | |
3211 | | |
3212 | | int |
3213 | | _PyInterpreterState_HasFeature(PyInterpreterState *interp, unsigned long feature) |
3214 | 0 | { |
3215 | 0 | return ((interp->feature_flags & feature) != 0); |
3216 | 0 | } |
3217 | | |
3218 | | |
3219 | 607k | #define MINIMUM_OVERHEAD 1000 |
3220 | | |
3221 | | static PyObject ** |
3222 | | push_chunk(PyThreadState *tstate, int size) |
3223 | 607k | { |
3224 | 607k | int allocate_size = _PY_DATA_STACK_CHUNK_SIZE; |
3225 | 607k | while (allocate_size < (int)sizeof(PyObject*)*(size + MINIMUM_OVERHEAD)) { |
3226 | 0 | allocate_size *= 2; |
3227 | 0 | } |
3228 | 607k | _PyStackChunk *new; |
3229 | 607k | if (tstate->datastack_cached_chunk != NULL |
3230 | 571k | && (size_t)allocate_size <= tstate->datastack_cached_chunk->size) |
3231 | 571k | { |
3232 | 571k | new = tstate->datastack_cached_chunk; |
3233 | 571k | tstate->datastack_cached_chunk = NULL; |
3234 | 571k | new->previous = tstate->datastack_chunk; |
3235 | 571k | new->top = 0; |
3236 | 571k | } |
3237 | 36.5k | else { |
3238 | 36.5k | new = allocate_chunk(allocate_size, tstate->datastack_chunk); |
3239 | 36.5k | if (new == NULL) { |
3240 | 0 | return NULL; |
3241 | 0 | } |
3242 | 36.5k | } |
3243 | 607k | if (tstate->datastack_chunk) { |
3244 | 607k | tstate->datastack_chunk->top = tstate->datastack_top - |
3245 | 607k | &tstate->datastack_chunk->data[0]; |
3246 | 607k | } |
3247 | 607k | tstate->datastack_chunk = new; |
3248 | 607k | tstate->datastack_limit = (PyObject **)(((char *)new) + allocate_size); |
3249 | | // When new is the "root" chunk (i.e. new->previous == NULL), we can keep |
3250 | | // _PyThreadState_PopFrame from freeing it later by "skipping" over the |
3251 | | // first element: |
3252 | 607k | PyObject **res = &new->data[new->previous == NULL]; |
3253 | 607k | tstate->datastack_top = res + size; |
3254 | 607k | return res; |
3255 | 607k | } |
3256 | | |
3257 | | _PyInterpreterFrame * |
3258 | | _PyThreadState_PushFrame(PyThreadState *tstate, size_t size) |
3259 | 248M | { |
3260 | 248M | assert(size < INT_MAX/sizeof(PyObject *)); |
3261 | 248M | if (_PyThreadState_HasStackSpace(tstate, (int)size)) { |
3262 | 248M | _PyInterpreterFrame *res = (_PyInterpreterFrame *)tstate->datastack_top; |
3263 | 248M | tstate->datastack_top += size; |
3264 | 248M | return res; |
3265 | 248M | } |
3266 | 607k | return (_PyInterpreterFrame *)push_chunk(tstate, (int)size); |
3267 | 248M | } |
3268 | | |
3269 | | void |
3270 | | _PyThreadState_PopFrame(PyThreadState *tstate, _PyInterpreterFrame * frame) |
3271 | 1.28G | { |
3272 | 1.28G | assert(tstate->datastack_chunk); |
3273 | 1.28G | PyObject **base = (PyObject **)frame; |
3274 | 1.28G | if (base == &tstate->datastack_chunk->data[0]) { |
3275 | 607k | _PyStackChunk *chunk = tstate->datastack_chunk; |
3276 | 607k | _PyStackChunk *previous = chunk->previous; |
3277 | 607k | _PyStackChunk *cached = tstate->datastack_cached_chunk; |
3278 | | // push_chunk ensures that the root chunk is never popped: |
3279 | 607k | assert(previous); |
3280 | 607k | tstate->datastack_top = &previous->data[previous->top]; |
3281 | 607k | tstate->datastack_chunk = previous; |
3282 | 607k | tstate->datastack_limit = (PyObject **)(((char *)previous) + previous->size); |
3283 | 607k | chunk->previous = NULL; |
3284 | 607k | if (cached != NULL) { |
3285 | 36.4k | _PyObject_VirtualFree(cached, cached->size); |
3286 | 36.4k | } |
3287 | 607k | tstate->datastack_cached_chunk = chunk; |
3288 | 607k | } |
3289 | 1.28G | else { |
3290 | 1.28G | assert(tstate->datastack_top); |
3291 | 1.28G | assert(tstate->datastack_top >= base); |
3292 | 1.28G | tstate->datastack_top = base; |
3293 | 1.28G | } |
3294 | 1.28G | } |
3295 | | |
3296 | | |
3297 | | #ifndef NDEBUG |
3298 | | // Check that a Python thread state valid. In practice, this function is used |
3299 | | // on a Python debug build to check if 'tstate' is a dangling pointer, if the |
3300 | | // PyThreadState memory has been freed. |
3301 | | // |
3302 | | // Usage: |
3303 | | // |
3304 | | // assert(_PyThreadState_CheckConsistency(tstate)); |
3305 | | int |
3306 | | _PyThreadState_CheckConsistency(PyThreadState *tstate) |
3307 | | { |
3308 | | assert(!_PyMem_IsPtrFreed(tstate)); |
3309 | | assert(!_PyMem_IsPtrFreed(tstate->interp)); |
3310 | | return 1; |
3311 | | } |
3312 | | #endif |
3313 | | |
3314 | | |
3315 | | // Check if a Python thread must call _PyThreadState_HangThread(), rather than |
3316 | | // taking the GIL or attaching to the interpreter if Py_Finalize() has been |
3317 | | // called. |
3318 | | // |
3319 | | // When this function is called by a daemon thread after Py_Finalize() has been |
3320 | | // called, the GIL may no longer exist. |
3321 | | // |
3322 | | // tstate must be non-NULL. |
3323 | | int |
3324 | | _PyThreadState_MustExit(PyThreadState *tstate) |
3325 | 3.90M | { |
3326 | 3.90M | int state = _Py_atomic_load_int_relaxed(&tstate->state); |
3327 | 3.90M | return state == _Py_THREAD_SHUTTING_DOWN; |
3328 | 3.90M | } |
3329 | | |
3330 | | void |
3331 | | _PyThreadState_HangThread(PyThreadState *tstate) |
3332 | 0 | { |
3333 | 0 | _PyThreadStateImpl *tstate_impl = (_PyThreadStateImpl *)tstate; |
3334 | 0 | decref_threadstate(tstate_impl); |
3335 | 0 | PyThread_hang_thread(); |
3336 | 0 | } |
3337 | | |
3338 | | /********************/ |
3339 | | /* mimalloc support */ |
3340 | | /********************/ |
3341 | | |
3342 | | static void |
3343 | | tstate_mimalloc_bind(PyThreadState *tstate) |
3344 | 37 | { |
3345 | | #ifdef Py_GIL_DISABLED |
3346 | | struct _mimalloc_thread_state *mts = &((_PyThreadStateImpl*)tstate)->mimalloc; |
3347 | | |
3348 | | // Initialize the mimalloc thread state. This must be called from the |
3349 | | // same thread that will use the thread state. The "mem" heap doubles as |
3350 | | // the "backing" heap. |
3351 | | mi_tld_t *tld = &mts->tld; |
3352 | | _mi_tld_init(tld, &mts->heaps[_Py_MIMALLOC_HEAP_MEM]); |
3353 | | llist_init(&mts->page_list); |
3354 | | |
3355 | | // Exiting threads abandon any remaining in-use segments to be re-claimed |
3356 | | // later by other threads. We use a per-interpreter mimalloc sub-process |
3357 | | // to keep Python objects from different interpreters separate. |
3358 | | assert(tstate->interp->mimalloc.subproc != NULL); |
3359 | | tld->segments.subproc = tstate->interp->mimalloc.subproc; |
3360 | | |
3361 | | // Don't fill in the first N bytes up to ob_type in debug builds. We may |
3362 | | // access ob_tid and the refcount fields in the dict and list lock-less |
3363 | | // accesses, so they must remain valid for a while after deallocation. |
3364 | | size_t base_offset = offsetof(PyObject, ob_type); |
3365 | | if (_PyMem_DebugEnabled()) { |
3366 | | // The debug allocator adds two words at the beginning of each block. |
3367 | | base_offset += 2 * sizeof(size_t); |
3368 | | } |
3369 | | size_t debug_offsets[_Py_MIMALLOC_HEAP_COUNT] = { |
3370 | | [_Py_MIMALLOC_HEAP_OBJECT] = base_offset, |
3371 | | [_Py_MIMALLOC_HEAP_GC] = base_offset, |
3372 | | [_Py_MIMALLOC_HEAP_GC_PRE] = base_offset + 2 * sizeof(PyObject *), |
3373 | | }; |
3374 | | |
3375 | | // Initialize each heap |
3376 | | for (uint8_t i = 0; i < _Py_MIMALLOC_HEAP_COUNT; i++) { |
3377 | | _mi_heap_init(&mts->heaps[i], tld, _mi_arena_id_none(), false, i); |
3378 | | mts->heaps[i].debug_offset = (uint8_t)debug_offsets[i]; |
3379 | | } |
3380 | | |
3381 | | // Heaps that store Python objects should use QSBR to delay freeing |
3382 | | // mimalloc pages while there may be concurrent lock-free readers. |
3383 | | mts->heaps[_Py_MIMALLOC_HEAP_OBJECT].page_use_qsbr = true; |
3384 | | mts->heaps[_Py_MIMALLOC_HEAP_GC].page_use_qsbr = true; |
3385 | | mts->heaps[_Py_MIMALLOC_HEAP_GC_PRE].page_use_qsbr = true; |
3386 | | |
3387 | | // By default, object allocations use _Py_MIMALLOC_HEAP_OBJECT. |
3388 | | // _PyObject_GC_New() and similar functions temporarily override this to |
3389 | | // use one of the GC heaps. |
3390 | | mts->current_object_heap = &mts->heaps[_Py_MIMALLOC_HEAP_OBJECT]; |
3391 | | |
3392 | | _Py_atomic_store_int(&mts->initialized, 1); |
3393 | | #endif |
3394 | 37 | } |
3395 | | |
3396 | | void |
3397 | | _PyThreadState_ClearMimallocHeaps(PyThreadState *tstate) |
3398 | 0 | { |
3399 | | #ifdef Py_GIL_DISABLED |
3400 | | if (!tstate->_status.bound) { |
3401 | | // The mimalloc heaps are only initialized when the thread is bound. |
3402 | | return; |
3403 | | } |
3404 | | |
3405 | | _PyThreadStateImpl *tstate_impl = (_PyThreadStateImpl *)tstate; |
3406 | | for (Py_ssize_t i = 0; i < _Py_MIMALLOC_HEAP_COUNT; i++) { |
3407 | | // Abandon all segments in use by this thread. This pushes them to |
3408 | | // a shared pool to later be reclaimed by other threads. It's important |
3409 | | // to do this before the thread state is destroyed so that objects |
3410 | | // remain visible to the GC. |
3411 | | _mi_heap_collect_abandon(&tstate_impl->mimalloc.heaps[i]); |
3412 | | } |
3413 | | #endif |
3414 | 0 | } |
3415 | | |
3416 | | |
3417 | | int |
3418 | | _Py_IsMainThread(void) |
3419 | 80.7M | { |
3420 | 80.7M | unsigned long thread = PyThread_get_thread_ident(); |
3421 | 80.7M | return (thread == _PyRuntime.main_thread); |
3422 | 80.7M | } |
3423 | | |
3424 | | |
3425 | | PyInterpreterState * |
3426 | | _PyInterpreterState_Main(void) |
3427 | 78.7M | { |
3428 | 78.7M | return _PyRuntime.interpreters.main; |
3429 | 78.7M | } |
3430 | | |
3431 | | |
3432 | | int |
3433 | | _Py_IsMainInterpreterFinalizing(PyInterpreterState *interp) |
3434 | 0 | { |
3435 | | /* bpo-39877: Access _PyRuntime directly rather than using |
3436 | | tstate->interp->runtime to support calls from Python daemon threads. |
3437 | | After Py_Finalize() has been called, tstate can be a dangling pointer: |
3438 | | point to PyThreadState freed memory. */ |
3439 | 0 | return (_PyRuntimeState_GetFinalizing(&_PyRuntime) != NULL && |
3440 | 0 | interp == &_PyRuntime._main_interpreter); |
3441 | 0 | } |
3442 | | |
3443 | | |
3444 | | const PyConfig * |
3445 | | _Py_GetMainConfig(void) |
3446 | 0 | { |
3447 | 0 | PyInterpreterState *interp = _PyInterpreterState_Main(); |
3448 | 0 | if (interp == NULL) { |
3449 | 0 | return NULL; |
3450 | 0 | } |
3451 | 0 | return _PyInterpreterState_GetConfig(interp); |
3452 | 0 | } |
3453 | | |
3454 | | Py_ssize_t |
3455 | | _PyInterpreterState_GuardCountdown(PyInterpreterState *interp) |
3456 | 0 | { |
3457 | 0 | assert(interp != NULL); |
3458 | 0 | Py_ssize_t count = _Py_atomic_load_uintptr(&interp->finalization_guards); |
3459 | 0 | assert(count >= 0); |
3460 | 0 | return count; |
3461 | 0 | } |
3462 | | |
3463 | | PyInterpreterState * |
3464 | | _PyInterpreterGuard_GetInterpreter(PyInterpreterGuard *guard) |
3465 | 0 | { |
3466 | 0 | assert(guard != NULL); |
3467 | 0 | assert(guard->interp != NULL); |
3468 | 0 | return guard->interp; |
3469 | 0 | } |
3470 | | |
3471 | | static int |
3472 | | try_acquire_interp_guard(PyInterpreterState *interp, PyInterpreterGuard *guard) |
3473 | 0 | { |
3474 | 0 | assert(interp != NULL); |
3475 | |
|
3476 | 0 | uintptr_t expected; |
3477 | 0 | do { |
3478 | 0 | expected = _Py_atomic_load_uintptr(&interp->finalization_guards); |
3479 | 0 | if (expected == _PyInterpreterGuard_GUARDS_NOT_ALLOWED) { |
3480 | 0 | return -1; |
3481 | 0 | } |
3482 | 0 | } while (_Py_atomic_compare_exchange_uintptr(&interp->finalization_guards, |
3483 | 0 | &expected, |
3484 | 0 | expected + 1) == 0); |
3485 | 0 | assert(_Py_atomic_load_uintptr(&interp->finalization_guards) > 0); |
3486 | 0 | assert(_Py_atomic_load_uintptr(&interp->finalization_guards) != _PyInterpreterGuard_GUARDS_NOT_ALLOWED); |
3487 | |
|
3488 | 0 | guard->interp = interp; |
3489 | 0 | return 0; |
3490 | 0 | } |
3491 | | |
3492 | | PyInterpreterGuard * |
3493 | | PyInterpreterGuard_FromCurrent(void) |
3494 | 0 | { |
3495 | 0 | PyInterpreterState *interp = _PyInterpreterState_GET(); |
3496 | 0 | assert(interp != NULL); |
3497 | |
|
3498 | 0 | PyInterpreterGuard *guard = PyMem_RawMalloc(sizeof(PyInterpreterGuard)); |
3499 | 0 | if (guard == NULL) { |
3500 | 0 | PyErr_NoMemory(); |
3501 | 0 | return NULL; |
3502 | 0 | } |
3503 | | |
3504 | 0 | if (try_acquire_interp_guard(interp, guard) < 0) { |
3505 | 0 | PyMem_RawFree(guard); |
3506 | 0 | PyErr_SetString(PyExc_PythonFinalizationError, |
3507 | 0 | "cannot acquire finalization guard anymore"); |
3508 | 0 | return NULL; |
3509 | 0 | } |
3510 | | |
3511 | 0 | return guard; |
3512 | 0 | } |
3513 | | |
3514 | | static void |
3515 | | release_interp_guard(PyInterpreterGuard *guard) |
3516 | 0 | { |
3517 | 0 | PyInterpreterState *interp = guard->interp; |
3518 | 0 | assert(interp != NULL); |
3519 | |
|
3520 | 0 | assert(_Py_atomic_load_uintptr(&interp->finalization_guards) != _PyInterpreterGuard_GUARDS_NOT_ALLOWED); |
3521 | 0 | uintptr_t old_value = _Py_atomic_add_uintptr(&interp->finalization_guards, -1); |
3522 | 0 | if (old_value == 1) { |
3523 | 0 | _PyParkingLot_UnparkAll(&interp->finalization_guards); |
3524 | 0 | } |
3525 | |
|
3526 | 0 | assert(old_value > 0); |
3527 | 0 | } |
3528 | | |
3529 | | void |
3530 | | PyInterpreterGuard_Close(PyInterpreterGuard *guard) |
3531 | 0 | { |
3532 | 0 | release_interp_guard(guard); |
3533 | 0 | PyMem_RawFree(guard); |
3534 | 0 | } |
3535 | | |
3536 | | int |
3537 | | _PyInterpreterGuard_TryAcquire(PyInterpreterState *interp, |
3538 | | PyInterpreterGuard *guard) |
3539 | 0 | { |
3540 | 0 | return try_acquire_interp_guard(interp, guard); |
3541 | 0 | } |
3542 | | |
3543 | | void |
3544 | | _PyInterpreterGuard_Release(PyInterpreterGuard *guard) |
3545 | 0 | { |
3546 | 0 | release_interp_guard(guard); |
3547 | 0 | } |
3548 | | |
3549 | | PyInterpreterView * |
3550 | | PyInterpreterView_FromCurrent(void) |
3551 | 0 | { |
3552 | 0 | PyInterpreterState *interp = _PyInterpreterState_GET(); |
3553 | 0 | assert(interp != NULL); |
3554 | | |
3555 | | // PyInterpreterView_Close() can be called without an attached thread |
3556 | | // state, so we have to use the raw allocator. |
3557 | 0 | PyInterpreterView *view = PyMem_RawMalloc(sizeof(PyInterpreterView)); |
3558 | 0 | if (view == NULL) { |
3559 | 0 | PyErr_NoMemory(); |
3560 | 0 | return NULL; |
3561 | 0 | } |
3562 | | |
3563 | 0 | view->id = interp->id; |
3564 | 0 | return view; |
3565 | 0 | } |
3566 | | |
3567 | | void |
3568 | | PyInterpreterView_Close(PyInterpreterView *view) |
3569 | 0 | { |
3570 | 0 | assert(view != NULL); |
3571 | 0 | PyMem_RawFree(view); |
3572 | 0 | } |
3573 | | |
3574 | | PyInterpreterGuard * |
3575 | | PyInterpreterGuard_FromView(PyInterpreterView *view) |
3576 | 0 | { |
3577 | 0 | assert(view != NULL); |
3578 | 0 | int64_t interp_id = view->id; |
3579 | 0 | assert(interp_id >= 0); |
3580 | | |
3581 | | // This allocation has to happen before we acquire the runtime lock, because |
3582 | | // PyMem_RawMalloc() might call some weird callback (such as tracemalloc) |
3583 | | // that tries to re-entrantly acquire the lock. |
3584 | 0 | PyInterpreterGuard *guard = PyMem_RawMalloc(sizeof(PyInterpreterGuard)); |
3585 | 0 | if (guard == NULL) { |
3586 | 0 | return NULL; |
3587 | 0 | } |
3588 | | |
3589 | | // Interpreters cannot be deleted while we hold the runtime lock. |
3590 | 0 | _PyRuntimeState *runtime = &_PyRuntime; |
3591 | 0 | HEAD_LOCK(runtime); |
3592 | 0 | PyInterpreterState *interp = interp_look_up_id(runtime, interp_id); |
3593 | 0 | if (interp == NULL) { |
3594 | 0 | HEAD_UNLOCK(runtime); |
3595 | 0 | PyMem_RawFree(guard); |
3596 | 0 | return NULL; |
3597 | 0 | } |
3598 | | |
3599 | 0 | int result = try_acquire_interp_guard(interp, guard); |
3600 | 0 | HEAD_UNLOCK(runtime); |
3601 | |
|
3602 | 0 | if (result < 0) { |
3603 | 0 | PyMem_RawFree(guard); |
3604 | 0 | return NULL; |
3605 | 0 | } |
3606 | | |
3607 | 0 | assert(guard->interp != NULL); |
3608 | 0 | return guard; |
3609 | 0 | } |
3610 | | |
3611 | | PyInterpreterView * |
3612 | | PyInterpreterView_FromMain(void) |
3613 | 0 | { |
3614 | 0 | PyInterpreterView *view = PyMem_RawMalloc(sizeof(PyInterpreterView)); |
3615 | 0 | if (view == NULL) { |
3616 | 0 | return NULL; |
3617 | 0 | } |
3618 | | |
3619 | | // The main interpreter always has an ID of zero. |
3620 | 0 | view->id = 0; |
3621 | |
|
3622 | 0 | return view; |
3623 | 0 | } |
3624 | | |
3625 | | static const PyThreadStateToken *_no_tstate_sentinel = (const PyThreadStateToken *)&_no_tstate_sentinel; |
3626 | 0 | #define NO_TSTATE_SENTINEL ((PyThreadStateToken *)_no_tstate_sentinel) |
3627 | | |
3628 | | PyThreadStateToken * |
3629 | | PyThreadState_Ensure(PyInterpreterGuard *guard) |
3630 | 0 | { |
3631 | 0 | assert(guard != NULL); |
3632 | 0 | PyInterpreterState *interp = guard->interp; |
3633 | 0 | assert(interp != NULL); |
3634 | 0 | PyThreadState *attached_tstate = current_fast_get(); |
3635 | 0 | if (attached_tstate != NULL && attached_tstate->interp == interp) { |
3636 | | /* Yay! We already have an attached thread state that matches. */ |
3637 | 0 | ++attached_tstate->ensure.counter; |
3638 | 0 | return attached_tstate; |
3639 | 0 | } |
3640 | | |
3641 | 0 | PyThreadState *detached_gilstate = gilstate_get(); |
3642 | 0 | if (detached_gilstate != NULL && detached_gilstate->interp == interp) { |
3643 | | /* There's a detached thread state that works. */ |
3644 | 0 | assert(attached_tstate == NULL); |
3645 | 0 | ++detached_gilstate->ensure.counter; |
3646 | 0 | _PyThreadState_Attach(detached_gilstate); |
3647 | 0 | return NO_TSTATE_SENTINEL; |
3648 | 0 | } |
3649 | | |
3650 | 0 | PyThreadState *fresh_tstate = _PyThreadState_NewBound(interp, |
3651 | 0 | _PyThreadState_WHENCE_C_API); |
3652 | 0 | if (fresh_tstate == NULL) { |
3653 | 0 | return NULL; |
3654 | 0 | } |
3655 | 0 | fresh_tstate->ensure.counter = 1; |
3656 | 0 | fresh_tstate->ensure.delete_on_release = 1; |
3657 | |
|
3658 | 0 | if (attached_tstate != NULL) { |
3659 | 0 | return (PyThreadStateToken *)PyThreadState_Swap(fresh_tstate); |
3660 | 0 | } |
3661 | | |
3662 | 0 | _PyThreadState_Attach(fresh_tstate); |
3663 | 0 | return NO_TSTATE_SENTINEL; |
3664 | 0 | } |
3665 | | |
3666 | | PyThreadStateToken * |
3667 | | PyThreadState_EnsureFromView(PyInterpreterView *view) |
3668 | 0 | { |
3669 | 0 | assert(view != NULL); |
3670 | 0 | PyInterpreterGuard *guard = PyInterpreterGuard_FromView(view); |
3671 | 0 | if (guard == NULL) { |
3672 | 0 | return NULL; |
3673 | 0 | } |
3674 | | |
3675 | 0 | PyThreadStateToken *result = (PyThreadStateToken *)PyThreadState_Ensure(guard); |
3676 | 0 | if (result == NULL) { |
3677 | 0 | PyInterpreterGuard_Close(guard); |
3678 | 0 | return NULL; |
3679 | 0 | } |
3680 | | |
3681 | 0 | PyThreadState *tstate = current_fast_get(); |
3682 | 0 | assert(tstate != NULL); |
3683 | |
|
3684 | 0 | if (tstate->ensure.owned_guard != NULL) { |
3685 | 0 | assert(tstate->ensure.owned_guard->interp == guard->interp); |
3686 | 0 | PyInterpreterGuard_Close(guard); |
3687 | 0 | } |
3688 | 0 | else { |
3689 | 0 | assert(tstate->ensure.owned_guard == NULL); |
3690 | 0 | tstate->ensure.owned_guard = guard; |
3691 | 0 | } |
3692 | |
|
3693 | 0 | return result; |
3694 | 0 | } |
3695 | | |
3696 | | void |
3697 | | PyThreadState_Release(PyThreadStateToken *token) |
3698 | 0 | { |
3699 | 0 | PyThreadState *tstate = current_fast_get(); |
3700 | 0 | _Py_EnsureTstateNotNULL(tstate); |
3701 | 0 | Py_ssize_t remaining = --tstate->ensure.counter; |
3702 | 0 | if (remaining < 0) { |
3703 | 0 | Py_FatalError("PyThreadState_Release() called more times than PyThreadState_Ensure()"); |
3704 | 0 | } |
3705 | | |
3706 | 0 | if (remaining != 0) { |
3707 | | // If the corresponding PyThreadState_Ensure() call used a detached |
3708 | | // thread state, we want to detach it again. |
3709 | 0 | if (token == NO_TSTATE_SENTINEL) { |
3710 | 0 | PyThreadState_Swap(NULL); |
3711 | 0 | } |
3712 | 0 | return; |
3713 | 0 | } |
3714 | | |
3715 | 0 | PyThreadState *to_restore; |
3716 | 0 | if (token == NO_TSTATE_SENTINEL) { |
3717 | 0 | to_restore = NULL; |
3718 | 0 | } |
3719 | 0 | else { |
3720 | 0 | to_restore = (PyThreadState *)token; |
3721 | 0 | } |
3722 | |
|
3723 | 0 | PyInterpreterGuard *owned_guard = tstate->ensure.owned_guard; |
3724 | 0 | assert(tstate->ensure.delete_on_release == 1 || tstate->ensure.delete_on_release == 0); |
3725 | 0 | if (tstate->ensure.delete_on_release) { |
3726 | 0 | ++tstate->ensure.counter; |
3727 | 0 | PyThreadState_Clear(tstate); |
3728 | 0 | --tstate->ensure.counter; |
3729 | 0 | } |
3730 | 0 | else if (owned_guard != NULL) { |
3731 | 0 | tstate->ensure.owned_guard = NULL; |
3732 | 0 | } |
3733 | |
|
3734 | 0 | PyThreadState *check_tstate = PyThreadState_Swap(to_restore); |
3735 | 0 | (void)check_tstate; |
3736 | 0 | assert(check_tstate == tstate); |
3737 | |
|
3738 | 0 | if (tstate->ensure.delete_on_release) { |
3739 | 0 | PyThreadState_Delete(tstate); |
3740 | 0 | } |
3741 | |
|
3742 | 0 | if (owned_guard != NULL) { |
3743 | 0 | PyInterpreterGuard_Close(owned_guard); |
3744 | 0 | } |
3745 | 0 | } |