Coverage Report

Created: 2026-07-14 06:16

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