Coverage Report

Created: 2026-12-01 06:09

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