Coverage Report

Created: 2026-05-30 06:18

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