Coverage Report

Created: 2026-05-16 06:46

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