Coverage Report

Created: 2026-10-17 06:15

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