Coverage Report

Created: 2026-10-17 06:15

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/ceval_gil.c
Line
Count
Source
1
#include "Python.h"
2
#include "pycore_ceval.h"         // _PyEval_SignalReceived()
3
#include "pycore_gc.h"            // _Py_RunGC()
4
#include "pycore_initconfig.h"    // _PyStatus_OK()
5
#include "pycore_optimizer.h"     // _Py_Executors_InvalidateCold()
6
#include "pycore_pyerrors.h"      // _PyErr_GetRaisedException()
7
#include "pycore_pylifecycle.h"   // _PyErr_Print()
8
#include "pycore_pystats.h"       // _Py_PrintSpecializationStats()
9
#include "pycore_runtime.h"       // _PyRuntime
10
11
12
/*
13
   Notes about the implementation:
14
15
   - The GIL is just a boolean variable (locked) whose access is protected
16
     by a mutex (gil_mutex), and whose changes are signalled by a condition
17
     variable (gil_cond). gil_mutex is taken for short periods of time,
18
     and therefore mostly uncontended.
19
20
   - In the GIL-holding thread, the main loop (PyEval_EvalFrameEx) must be
21
     able to release the GIL on demand by another thread. A volatile boolean
22
     variable (gil_drop_request) is used for that purpose, which is checked
23
     at every turn of the eval loop. That variable is set after a wait of
24
     `interval` microseconds on `gil_cond` has timed out.
25
26
      [Actually, another volatile boolean variable (eval_breaker) is used
27
       which ORs several conditions into one. Volatile booleans are
28
       sufficient as inter-thread signalling means since Python is run
29
       on cache-coherent architectures only.]
30
31
   - A thread wanting to take the GIL will first let pass a given amount of
32
     time (`interval` microseconds) before setting gil_drop_request. This
33
     encourages a defined switching period, but doesn't enforce it since
34
     opcodes can take an arbitrary time to execute.
35
36
     The `interval` value is available for the user to read and modify
37
     using the Python API `sys.{get,set}switchinterval()`.
38
39
   - When a thread releases the GIL and gil_drop_request is set, that thread
40
     ensures that another GIL-awaiting thread gets scheduled.
41
     It does so by waiting on a condition variable (switch_cond) until
42
     the value of last_holder is changed to something else than its
43
     own thread state pointer, indicating that another thread was able to
44
     take the GIL.
45
46
     This is meant to prohibit the latency-adverse behaviour on multi-core
47
     machines where one thread would speculatively release the GIL, but still
48
     run and end up being the first to re-acquire it, making the "timeslices"
49
     much longer than expected.
50
     (Note: this mechanism is enabled with FORCE_SWITCHING above)
51
*/
52
53
// Atomically copy the bits indicated by mask between two values.
54
static inline void
55
copy_eval_breaker_bits(uintptr_t *from, uintptr_t *to, uintptr_t mask)
56
2.08M
{
57
2.08M
    uintptr_t from_bits = _Py_atomic_load_uintptr_relaxed(from) & mask;
58
2.08M
    uintptr_t old_value = _Py_atomic_load_uintptr_relaxed(to);
59
2.08M
    uintptr_t to_bits = old_value & mask;
60
2.08M
    if (from_bits == to_bits) {
61
2.08M
        return;
62
2.08M
    }
63
64
0
    uintptr_t new_value;
65
0
    do {
66
0
        new_value = (old_value & ~mask) | from_bits;
67
0
    } while (!_Py_atomic_compare_exchange_uintptr(to, &old_value, new_value));
68
0
}
69
70
// When attaching a thread, set the global instrumentation version and
71
// _PY_CALLS_TO_DO_BIT from the current state of the interpreter.
72
static inline void
73
update_eval_breaker_for_thread(PyInterpreterState *interp, PyThreadState *tstate)
74
2.08M
{
75
#ifdef Py_GIL_DISABLED
76
    // Free-threaded builds eagerly update the eval_breaker on *all* threads as
77
    // needed, so this function doesn't apply.
78
    return;
79
#endif
80
81
2.08M
    int32_t npending = _Py_atomic_load_int32_relaxed(
82
2.08M
        &interp->ceval.pending.npending);
83
2.08M
    if (npending) {
84
0
        _Py_set_eval_breaker_bit(tstate, _PY_CALLS_TO_DO_BIT);
85
0
    }
86
2.08M
    else if (_Py_IsMainThread()) {
87
2.08M
        npending = _Py_atomic_load_int32_relaxed(
88
2.08M
            &_PyRuntime.ceval.pending_mainthread.npending);
89
2.08M
        if (npending) {
90
0
            _Py_set_eval_breaker_bit(tstate, _PY_CALLS_TO_DO_BIT);
91
0
        }
92
2.08M
    }
93
94
    // _PY_CALLS_TO_DO_BIT was derived from other state above, so the only bits
95
    // we copy from our interpreter's state are the instrumentation version.
96
2.08M
    copy_eval_breaker_bits(&interp->ceval.instrumentation_version,
97
2.08M
                           &tstate->eval_breaker,
98
2.08M
                           ~_PY_EVAL_EVENTS_MASK);
99
2.08M
}
100
101
/*
102
 * Implementation of the Global Interpreter Lock (GIL).
103
 */
104
105
#include <stdlib.h>
106
#include <errno.h>
107
108
#include "condvar.h"
109
110
#define MUTEX_INIT(mut) \
111
74
    if (PyMUTEX_INIT(&(mut))) { \
112
74
        Py_FatalError("PyMUTEX_INIT(" #mut ") failed"); };
113
#define MUTEX_FINI(mut) \
114
0
    if (PyMUTEX_FINI(&(mut))) { \
115
0
        Py_FatalError("PyMUTEX_FINI(" #mut ") failed"); };
116
#define MUTEX_LOCK(mut) \
117
6.26M
    if (PyMUTEX_LOCK(&(mut))) { \
118
6.26M
        Py_FatalError("PyMUTEX_LOCK(" #mut ") failed"); };
119
#define MUTEX_UNLOCK(mut) \
120
6.26M
    if (PyMUTEX_UNLOCK(&(mut))) { \
121
6.26M
        Py_FatalError("PyMUTEX_UNLOCK(" #mut ") failed"); };
122
123
#define COND_INIT(cond) \
124
74
    if (PyCOND_INIT(&(cond))) { \
125
74
        Py_FatalError("PyCOND_INIT(" #cond ") failed"); };
126
#define COND_FINI(cond) \
127
0
    if (PyCOND_FINI(&(cond))) { \
128
0
        Py_FatalError("PyCOND_FINI(" #cond ") failed"); };
129
#define COND_SIGNAL(cond) \
130
4.17M
    if (PyCOND_SIGNAL(&(cond))) { \
131
4.17M
        Py_FatalError("PyCOND_SIGNAL(" #cond ") failed"); };
132
#define COND_WAIT(cond, mut) \
133
0
    if (PyCOND_WAIT(&(cond), &(mut))) { \
134
0
        Py_FatalError("PyCOND_WAIT(" #cond ") failed"); };
135
#define COND_TIMED_WAIT(cond, mut, microseconds, timeout_result) \
136
0
    { \
137
0
        int r = PyCOND_TIMEDWAIT(&(cond), &(mut), (microseconds)); \
138
0
        if (r < 0) \
139
0
            Py_FatalError("PyCOND_WAIT(" #cond ") failed"); \
140
0
        if (r) /* 1 == timeout, 2 == impl. can't say, so assume timeout */ \
141
0
            timeout_result = 1; \
142
0
        else \
143
0
            timeout_result = 0; \
144
0
    } \
145
146
147
37
#define DEFAULT_INTERVAL 5000
148
149
static void _gil_initialize(struct _gil_runtime_state *gil)
150
37
{
151
37
    gil->locked = -1;
152
37
    gil->interval = DEFAULT_INTERVAL;
153
37
}
154
155
static int gil_created(struct _gil_runtime_state *gil)
156
0
{
157
0
    if (gil == NULL) {
158
0
        return 0;
159
0
    }
160
0
    return (_Py_atomic_load_int_acquire(&gil->locked) >= 0);
161
0
}
162
163
static void create_gil(struct _gil_runtime_state *gil)
164
37
{
165
37
    MUTEX_INIT(gil->mutex);
166
37
#ifdef FORCE_SWITCHING
167
37
    MUTEX_INIT(gil->switch_mutex);
168
37
#endif
169
37
    COND_INIT(gil->cond);
170
37
#ifdef FORCE_SWITCHING
171
37
    COND_INIT(gil->switch_cond);
172
37
#endif
173
37
    _Py_atomic_store_ptr_relaxed(&gil->last_holder, 0);
174
37
    _Py_ANNOTATE_RWLOCK_CREATE(&gil->locked);
175
37
    _Py_atomic_store_int_release(&gil->locked, 0);
176
37
}
177
178
static void destroy_gil(struct _gil_runtime_state *gil)
179
0
{
180
    /* some pthread-like implementations tie the mutex to the cond
181
     * and must have the cond destroyed first.
182
     */
183
0
    COND_FINI(gil->cond);
184
0
    MUTEX_FINI(gil->mutex);
185
0
#ifdef FORCE_SWITCHING
186
0
    COND_FINI(gil->switch_cond);
187
0
    MUTEX_FINI(gil->switch_mutex);
188
0
#endif
189
0
    _Py_atomic_store_int_release(&gil->locked, -1);
190
0
    _Py_ANNOTATE_RWLOCK_DESTROY(&gil->locked);
191
0
}
192
193
#ifdef HAVE_FORK
194
static void recreate_gil(struct _gil_runtime_state *gil)
195
0
{
196
0
    _Py_ANNOTATE_RWLOCK_DESTROY(&gil->locked);
197
    /* XXX should we destroy the old OS resources here? */
198
0
    create_gil(gil);
199
0
}
200
#endif
201
202
static inline void
203
drop_gil_impl(PyThreadState *tstate, struct _gil_runtime_state *gil)
204
2.08M
{
205
2.08M
    MUTEX_LOCK(gil->mutex);
206
2.08M
    _Py_ANNOTATE_RWLOCK_RELEASED(&gil->locked, /*is_write=*/1);
207
2.08M
    _Py_atomic_store_int_relaxed(&gil->locked, 0);
208
2.08M
    if (tstate != NULL) {
209
2.08M
        tstate->holds_gil = 0;
210
2.08M
        tstate->gil_requested = 0;
211
2.08M
    }
212
2.08M
    COND_SIGNAL(gil->cond);
213
2.08M
    MUTEX_UNLOCK(gil->mutex);
214
2.08M
}
215
216
static void
217
drop_gil(PyInterpreterState *interp, PyThreadState *tstate, int final_release)
218
2.08M
{
219
2.08M
    struct _ceval_state *ceval = &interp->ceval;
220
    /* If final_release is true, the caller is indicating that we're releasing
221
       the GIL for the last time in this thread.  This is particularly
222
       relevant when the current thread state is finalizing or its
223
       interpreter is finalizing (either may be in an inconsistent
224
       state).  In that case the current thread will definitely
225
       never try to acquire the GIL again. */
226
    // XXX It may be more correct to check tstate->_status.finalizing.
227
    // XXX assert(final_release || !tstate->_status.cleared);
228
229
2.08M
    assert(final_release || tstate != NULL);
230
2.08M
    struct _gil_runtime_state *gil = ceval->gil;
231
#ifdef Py_GIL_DISABLED
232
    // Check if we have the GIL before dropping it. tstate will be NULL if
233
    // take_gil() detected that this thread has been destroyed, in which case
234
    // we know we have the GIL.
235
    if (tstate != NULL && !tstate->holds_gil) {
236
        return;
237
    }
238
#endif
239
2.08M
    if (!_Py_atomic_load_int_relaxed(&gil->locked)) {
240
0
        Py_FatalError("drop_gil: GIL is not locked");
241
0
    }
242
243
2.08M
    if (!final_release) {
244
        /* Sub-interpreter support: threads might have been switched
245
           under our feet using PyThreadState_Swap(). Fix the GIL last
246
           holder variable so that our heuristics work. */
247
2.08M
        _Py_atomic_store_ptr_relaxed(&gil->last_holder, tstate);
248
2.08M
    }
249
250
2.08M
    drop_gil_impl(tstate, gil);
251
252
2.08M
#ifdef FORCE_SWITCHING
253
    /* We might be releasing the GIL for the last time in this thread.  In that
254
       case there's a possible race with tstate->interp getting deleted after
255
       gil->mutex is unlocked and before the following code runs, leading to a
256
       crash.  We can use final_release to indicate the thread is done with the
257
       GIL, and that's the only time we might delete the interpreter.  See
258
       https://github.com/python/cpython/issues/104341. */
259
2.08M
    if (!final_release &&
260
2.08M
        _Py_eval_breaker_bit_is_set(tstate, _PY_GIL_DROP_REQUEST_BIT)) {
261
0
        MUTEX_LOCK(gil->switch_mutex);
262
        /* Not switched yet => wait */
263
0
        if (((PyThreadState*)_Py_atomic_load_ptr_relaxed(&gil->last_holder)) == tstate)
264
0
        {
265
0
            assert(_PyThreadState_CheckConsistency(tstate));
266
0
            _Py_unset_eval_breaker_bit(tstate, _PY_GIL_DROP_REQUEST_BIT);
267
            /* NOTE: if COND_WAIT does not atomically start waiting when
268
               releasing the mutex, another thread can run through, take
269
               the GIL and drop it again, and reset the condition
270
               before we even had a chance to wait for it. */
271
0
            COND_WAIT(gil->switch_cond, gil->switch_mutex);
272
0
        }
273
0
        MUTEX_UNLOCK(gil->switch_mutex);
274
0
    }
275
2.08M
#endif
276
2.08M
}
277
278
279
/* Take the GIL.
280
281
   The function saves errno at entry and restores its value at exit.
282
   It may hang rather than return if the interpreter has been finalized.
283
284
   tstate must be non-NULL. */
285
static void
286
take_gil(PyThreadState *tstate)
287
2.08M
{
288
2.08M
    int err = errno;
289
290
2.08M
    assert(tstate != NULL);
291
    /* We shouldn't be using a thread state that isn't viable any more. */
292
    // XXX It may be more correct to check tstate->_status.finalizing.
293
    // XXX assert(!tstate->_status.cleared);
294
295
2.08M
    if (_PyThreadState_MustExit(tstate)) {
296
        /* bpo-39877: If Py_Finalize() has been called and tstate is not the
297
           thread which called Py_Finalize(), this thread cannot continue.
298
299
           This code path can be reached by a daemon thread after Py_Finalize()
300
           completes.
301
302
           This used to call a *thread_exit API, but that was not safe as it
303
           lacks stack unwinding and local variable destruction important to
304
           C++. gh-87135: The best that can be done is to hang the thread as
305
           the public APIs calling this have no error reporting mechanism (!).
306
         */
307
0
        _PyThreadState_HangThread(tstate);
308
0
    }
309
310
2.08M
    assert(_PyThreadState_CheckConsistency(tstate));
311
2.08M
    PyInterpreterState *interp = tstate->interp;
312
2.08M
    struct _gil_runtime_state *gil = interp->ceval.gil;
313
#ifdef Py_GIL_DISABLED
314
    if (!_Py_atomic_load_int_relaxed(&gil->enabled)) {
315
        return;
316
    }
317
#endif
318
319
    /* Check that _PyEval_InitThreads() was called to create the lock */
320
2.08M
    assert(gil_created(gil));
321
322
2.08M
    MUTEX_LOCK(gil->mutex);
323
324
2.08M
    tstate->gil_requested = 1;
325
326
2.08M
    int drop_requested = 0;
327
2.08M
    while (_Py_atomic_load_int_relaxed(&gil->locked)) {
328
0
        unsigned long saved_switchnum = gil->switch_number;
329
330
0
        unsigned long interval = _Py_atomic_load_ulong_relaxed(&gil->interval);
331
0
        if (interval < 1) {
332
0
            interval = 1;
333
0
        }
334
0
        int timed_out = 0;
335
0
        COND_TIMED_WAIT(gil->cond, gil->mutex, interval, timed_out);
336
337
        /* If we timed out and no switch occurred in the meantime, it is time
338
           to ask the GIL-holding thread to drop it. */
339
0
        if (timed_out &&
340
0
            _Py_atomic_load_int_relaxed(&gil->locked) &&
341
0
            gil->switch_number == saved_switchnum)
342
0
        {
343
0
            PyThreadState *holder_tstate =
344
0
                (PyThreadState*)_Py_atomic_load_ptr_relaxed(&gil->last_holder);
345
0
            if (_PyThreadState_MustExit(tstate)) {
346
0
                MUTEX_UNLOCK(gil->mutex);
347
                // gh-96387: If the loop requested a drop request in a previous
348
                // iteration, reset the request. Otherwise, drop_gil() can
349
                // block forever waiting for the thread which exited. Drop
350
                // requests made by other threads are also reset: these threads
351
                // may have to request again a drop request (iterate one more
352
                // time).
353
0
                if (drop_requested) {
354
0
                    _Py_unset_eval_breaker_bit(holder_tstate, _PY_GIL_DROP_REQUEST_BIT);
355
0
                }
356
                // gh-87135: hang the thread as *thread_exit() is not a safe
357
                // API. It lacks stack unwind and local variable destruction.
358
0
                _PyThreadState_HangThread(tstate);
359
0
            }
360
0
            assert(_PyThreadState_CheckConsistency(tstate));
361
362
0
            _Py_set_eval_breaker_bit(holder_tstate, _PY_GIL_DROP_REQUEST_BIT);
363
0
            drop_requested = 1;
364
0
        }
365
0
    }
366
367
#ifdef Py_GIL_DISABLED
368
    if (!_Py_atomic_load_int_relaxed(&gil->enabled)) {
369
        // Another thread disabled the GIL between our check above and
370
        // now. Don't take the GIL, signal any other waiting threads, and
371
        // return.
372
        COND_SIGNAL(gil->cond);
373
        MUTEX_UNLOCK(gil->mutex);
374
        return;
375
    }
376
#endif
377
378
2.08M
#ifdef FORCE_SWITCHING
379
    /* This mutex must be taken before modifying gil->last_holder:
380
       see drop_gil(). */
381
4.17M
    MUTEX_LOCK(gil->switch_mutex);
382
4.17M
#endif
383
    /* We now hold the GIL */
384
4.17M
    _Py_atomic_store_int_relaxed(&gil->locked, 1);
385
4.17M
    _Py_ANNOTATE_RWLOCK_ACQUIRED(&gil->locked, /*is_write=*/1);
386
387
4.17M
    if (tstate != (PyThreadState*)_Py_atomic_load_ptr_relaxed(&gil->last_holder)) {
388
37
        _Py_atomic_store_ptr_relaxed(&gil->last_holder, tstate);
389
37
        ++gil->switch_number;
390
37
    }
391
392
4.17M
#ifdef FORCE_SWITCHING
393
4.17M
    COND_SIGNAL(gil->switch_cond);
394
2.08M
    MUTEX_UNLOCK(gil->switch_mutex);
395
2.08M
#endif
396
397
2.08M
    if (_PyThreadState_MustExit(tstate)) {
398
        /* bpo-36475: If Py_Finalize() has been called and tstate is not
399
           the thread which called Py_Finalize(), gh-87135: hang the
400
           thread.
401
402
           This code path can be reached by a daemon thread which was waiting
403
           in take_gil() while the main thread called
404
           wait_for_thread_shutdown() from Py_Finalize(). */
405
0
        MUTEX_UNLOCK(gil->mutex);
406
        /* tstate could be a dangling pointer, so don't pass it to
407
           drop_gil(). */
408
0
        drop_gil(interp, NULL, 1);
409
0
        _PyThreadState_HangThread(tstate);
410
0
    }
411
2.08M
    assert(_PyThreadState_CheckConsistency(tstate));
412
413
2.08M
    tstate->gil_requested = 0;
414
2.08M
    tstate->holds_gil = 1;
415
2.08M
    _Py_unset_eval_breaker_bit(tstate, _PY_GIL_DROP_REQUEST_BIT);
416
2.08M
    update_eval_breaker_for_thread(interp, tstate);
417
418
2.08M
    MUTEX_UNLOCK(gil->mutex);
419
420
2.08M
    errno = err;
421
2.08M
    return;
422
2.08M
}
423
424
void _PyEval_SetSwitchInterval(unsigned long microseconds)
425
0
{
426
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
427
0
    struct _gil_runtime_state *gil = interp->ceval.gil;
428
0
    assert(gil != NULL);
429
0
    _Py_atomic_store_ulong_relaxed(&gil->interval, microseconds);
430
0
}
431
432
unsigned long _PyEval_GetSwitchInterval(void)
433
0
{
434
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
435
0
    struct _gil_runtime_state *gil = interp->ceval.gil;
436
0
    assert(gil != NULL);
437
0
    return _Py_atomic_load_ulong_relaxed(&gil->interval);
438
0
}
439
440
441
int
442
_PyEval_ThreadsInitialized(void)
443
0
{
444
    /* XXX This is only needed for an assert in PyGILState_Ensure(),
445
     * which currently does not work with subinterpreters.
446
     * Thus we only use the main interpreter. */
447
0
    PyInterpreterState *interp = _PyInterpreterState_Main();
448
0
    if (interp == NULL) {
449
0
        return 0;
450
0
    }
451
0
    struct _gil_runtime_state *gil = interp->ceval.gil;
452
0
    return gil_created(gil);
453
0
}
454
455
// Function removed in the Python 3.13 API but kept in the stable ABI.
456
PyAPI_FUNC(int)
457
PyEval_ThreadsInitialized(void)
458
0
{
459
0
    return _PyEval_ThreadsInitialized();
460
0
}
461
462
#ifndef NDEBUG
463
static inline int
464
current_thread_holds_gil(struct _gil_runtime_state *gil, PyThreadState *tstate)
465
{
466
    int holds_gil = tstate->holds_gil;
467
468
    // holds_gil is the source of truth; check that last_holder and gil->locked
469
    // are consistent with it.
470
    int locked = _Py_atomic_load_int_relaxed(&gil->locked);
471
    int is_last_holder =
472
        ((PyThreadState*)_Py_atomic_load_ptr_relaxed(&gil->last_holder)) == tstate;
473
    assert(!holds_gil || locked);
474
    assert(!holds_gil || is_last_holder);
475
476
    return holds_gil;
477
}
478
#endif
479
480
static void
481
init_shared_gil(PyInterpreterState *interp, struct _gil_runtime_state *gil)
482
0
{
483
0
    assert(gil_created(gil));
484
0
    interp->ceval.gil = gil;
485
0
    interp->ceval.own_gil = 0;
486
0
}
487
488
static void
489
init_own_gil(PyInterpreterState *interp, struct _gil_runtime_state *gil)
490
37
{
491
37
    assert(!gil_created(gil));
492
#ifdef Py_GIL_DISABLED
493
    const PyConfig *config = _PyInterpreterState_GetConfig(interp);
494
    gil->enabled = config->enable_gil == _PyConfig_GIL_ENABLE ? INT_MAX : 0;
495
#endif
496
37
    create_gil(gil);
497
37
    assert(gil_created(gil));
498
37
    interp->ceval.gil = gil;
499
37
    interp->ceval.own_gil = 1;
500
37
}
501
502
void
503
_PyEval_InitGIL(PyThreadState *tstate, int own_gil)
504
37
{
505
37
    assert(tstate->interp->ceval.gil == NULL);
506
37
    if (!own_gil) {
507
        /* The interpreter will share the main interpreter's instead. */
508
0
        PyInterpreterState *main_interp = _PyInterpreterState_Main();
509
0
        assert(tstate->interp != main_interp);
510
0
        struct _gil_runtime_state *gil = main_interp->ceval.gil;
511
0
        init_shared_gil(tstate->interp, gil);
512
0
        assert(!current_thread_holds_gil(gil, tstate));
513
0
    }
514
37
    else {
515
37
        PyThread_init_thread();
516
37
        init_own_gil(tstate->interp, &tstate->interp->_gil);
517
37
    }
518
519
    // Lock the GIL and mark the current thread as attached.
520
37
    _PyThreadState_Attach(tstate);
521
37
}
522
523
void
524
_PyEval_FiniGIL(PyInterpreterState *interp)
525
37
{
526
37
    struct _gil_runtime_state *gil = interp->ceval.gil;
527
37
    if (gil == NULL) {
528
        /* It was already finalized (or hasn't been initialized yet). */
529
37
        assert(!interp->ceval.own_gil);
530
37
        return;
531
37
    }
532
0
    else if (!interp->ceval.own_gil) {
533
#ifdef Py_DEBUG
534
        PyInterpreterState *main_interp = _PyInterpreterState_Main();
535
        assert(main_interp != NULL && interp != main_interp);
536
        assert(interp->ceval.gil == main_interp->ceval.gil);
537
#endif
538
0
        interp->ceval.gil = NULL;
539
0
        return;
540
0
    }
541
542
0
    if (!gil_created(gil)) {
543
        /* First Py_InitializeFromConfig() call: the GIL doesn't exist
544
           yet: do nothing. */
545
0
        return;
546
0
    }
547
548
0
    destroy_gil(gil);
549
0
    assert(!gil_created(gil));
550
0
    interp->ceval.gil = NULL;
551
0
}
552
553
// Function removed in Python 3.16 limited C API, but kept in the stable ABI
554
PyAPI_FUNC(void)
555
PyEval_InitThreads(void)
556
0
{
557
    /* Do nothing: kept for backward compatibility */
558
0
}
559
560
void
561
_PyEval_Fini(void)
562
0
{
563
#ifdef Py_STATS
564
    _Py_PrintSpecializationStats(1);
565
#endif
566
0
}
567
568
// Function removed in the Python 3.13 API but kept in the stable ABI.
569
PyAPI_FUNC(void)
570
PyEval_AcquireLock(void)
571
0
{
572
0
    PyThreadState *tstate = _PyThreadState_GET();
573
0
    _Py_EnsureTstateNotNULL(tstate);
574
575
0
    take_gil(tstate);
576
0
}
577
578
// Function removed in the Python 3.13 API but kept in the stable ABI.
579
PyAPI_FUNC(void)
580
PyEval_ReleaseLock(void)
581
0
{
582
0
    PyThreadState *tstate = _PyThreadState_GET();
583
    /* This function must succeed when the current thread state is NULL.
584
       We therefore avoid PyThreadState_Get() which dumps a fatal error
585
       in debug mode. */
586
0
    drop_gil(tstate->interp, tstate, 0);
587
0
}
588
589
void
590
_PyEval_AcquireLock(PyThreadState *tstate)
591
2.08M
{
592
2.08M
    _Py_EnsureTstateNotNULL(tstate);
593
2.08M
    take_gil(tstate);
594
2.08M
}
595
596
void
597
_PyEval_ReleaseLock(PyInterpreterState *interp,
598
                    PyThreadState *tstate,
599
                    int final_release)
600
2.08M
{
601
2.08M
    assert(tstate != NULL);
602
2.08M
    assert(tstate->interp == interp);
603
2.08M
    drop_gil(interp, tstate, final_release);
604
2.08M
}
605
606
void
607
PyEval_AcquireThread(PyThreadState *tstate)
608
0
{
609
0
    _Py_EnsureTstateNotNULL(tstate);
610
0
    _PyThreadState_Attach(tstate);
611
0
}
612
613
void
614
PyEval_ReleaseThread(PyThreadState *tstate)
615
0
{
616
0
    assert(_PyThreadState_CheckConsistency(tstate));
617
0
    _PyThreadState_Detach(tstate);
618
0
}
619
620
#ifdef HAVE_FORK
621
/* This function is called from PyOS_AfterFork_Child to re-initialize the
622
   GIL and pending calls lock. */
623
PyStatus
624
_PyEval_ReInitThreads(PyThreadState *tstate)
625
0
{
626
0
    assert(tstate->interp == _PyInterpreterState_Main());
627
628
0
    struct _gil_runtime_state *gil = tstate->interp->ceval.gil;
629
0
    if (!gil_created(gil)) {
630
0
        return _PyStatus_OK();
631
0
    }
632
0
    recreate_gil(gil);
633
634
0
    take_gil(tstate);
635
636
0
    struct _pending_calls *pending = &tstate->interp->ceval.pending;
637
0
    _PyMutex_at_fork_reinit(&pending->mutex);
638
639
0
    return _PyStatus_OK();
640
0
}
641
#endif
642
643
PyThreadState *
644
PyEval_SaveThread(void)
645
2.08M
{
646
2.08M
    PyThreadState *tstate = _PyThreadState_GET();
647
2.08M
    _PyThreadState_Detach(tstate);
648
2.08M
    return tstate;
649
2.08M
}
650
651
void
652
PyEval_RestoreThread(PyThreadState *tstate)
653
2.08M
{
654
#ifdef MS_WINDOWS
655
    int err = GetLastError();
656
#endif
657
658
2.08M
    _Py_EnsureTstateNotNULL(tstate);
659
2.08M
    _PyThreadState_Attach(tstate);
660
661
#ifdef MS_WINDOWS
662
    SetLastError(err);
663
#endif
664
2.08M
}
665
666
667
void
668
_PyEval_SignalReceived(void)
669
0
{
670
0
    _Py_set_eval_breaker_bit(_PyRuntime.main_tstate, _PY_SIGNALS_PENDING_BIT);
671
0
}
672
673
674
#ifndef Py_GIL_DISABLED
675
static void
676
signal_active_thread(PyInterpreterState *interp, uintptr_t bit)
677
0
{
678
0
    struct _gil_runtime_state *gil = interp->ceval.gil;
679
680
    // If a thread from the targeted interpreter is holding the GIL, signal
681
    // that thread. Otherwise, the next thread to run from the targeted
682
    // interpreter will have its bit set as part of taking the GIL.
683
0
    MUTEX_LOCK(gil->mutex);
684
0
    if (_Py_atomic_load_int_relaxed(&gil->locked)) {
685
0
        PyThreadState *holder = (PyThreadState*)_Py_atomic_load_ptr_relaxed(&gil->last_holder);
686
0
        if (holder->interp == interp) {
687
0
            _Py_set_eval_breaker_bit(holder, bit);
688
0
        }
689
0
    }
690
0
    MUTEX_UNLOCK(gil->mutex);
691
0
}
692
#endif
693
694
695
/* Mechanism whereby asynchronously executing callbacks (e.g. UNIX
696
   signal handlers or Mac I/O completion routines) can schedule calls
697
   to a function to be called synchronously.
698
   The synchronous function is called with one void* argument.
699
   It should return 0 for success or -1 for failure -- failure should
700
   be accompanied by an exception.
701
702
   If registry succeeds, the registry function returns 0; if it fails
703
   (e.g. due to too many pending calls) it returns -1 (without setting
704
   an exception condition).
705
706
   Note that because registry may occur from within signal handlers,
707
   or other asynchronous events, calling malloc() is unsafe!
708
709
   Any thread can schedule pending calls, but only the main thread
710
   will execute them.
711
   There is no facility to schedule calls to a particular thread, but
712
   that should be easy to change, should that ever be required.  In
713
   that case, the static variables here should go into the python
714
   threadstate.
715
*/
716
717
/* Push one item onto the queue while holding the lock. */
718
static int
719
_push_pending_call(struct _pending_calls *pending,
720
                   _Py_pending_call_func func, void *arg, int flags)
721
0
{
722
0
    if (pending->npending == pending->max) {
723
0
        return _Py_ADD_PENDING_FULL;
724
0
    }
725
0
    assert(pending->npending < pending->max);
726
727
0
    int i = pending->next;
728
0
    assert(pending->calls[i].func == NULL);
729
730
0
    pending->calls[i].func = func;
731
0
    pending->calls[i].arg = arg;
732
0
    pending->calls[i].flags = flags;
733
734
0
    assert(pending->npending < PENDINGCALLSARRAYSIZE);
735
0
    _Py_atomic_add_int32(&pending->npending, 1);
736
737
0
    pending->next = (i + 1) % PENDINGCALLSARRAYSIZE;
738
0
    assert(pending->next != pending->first
739
0
            || pending->npending == pending->max);
740
741
0
    return _Py_ADD_PENDING_SUCCESS;
742
0
}
743
744
static int
745
_next_pending_call(struct _pending_calls *pending,
746
                   int (**func)(void *), void **arg, int *flags)
747
0
{
748
0
    int i = pending->first;
749
0
    if (pending->npending == 0) {
750
        /* Queue empty */
751
0
        assert(i == pending->next);
752
0
        assert(pending->calls[i].func == NULL);
753
0
        return -1;
754
0
    }
755
0
    *func = pending->calls[i].func;
756
0
    *arg = pending->calls[i].arg;
757
0
    *flags = pending->calls[i].flags;
758
0
    return i;
759
0
}
760
761
/* Pop one item off the queue while holding the lock. */
762
static void
763
_pop_pending_call(struct _pending_calls *pending,
764
                  int (**func)(void *), void **arg, int *flags)
765
0
{
766
0
    int i = _next_pending_call(pending, func, arg, flags);
767
0
    if (i >= 0) {
768
0
        pending->calls[i] = (struct _pending_call){0};
769
0
        pending->first = (i + 1) % PENDINGCALLSARRAYSIZE;
770
0
        assert(pending->npending > 0);
771
0
        _Py_atomic_add_int32(&pending->npending, -1);
772
0
    }
773
0
}
774
775
/* This implementation is thread-safe.  It allows
776
   scheduling to be made from any thread, and even from an executing
777
   callback.
778
 */
779
780
_Py_add_pending_call_result
781
_PyEval_AddPendingCall(PyInterpreterState *interp,
782
                       _Py_pending_call_func func, void *arg, int flags)
783
0
{
784
0
    struct _pending_calls *pending = &interp->ceval.pending;
785
0
    int main_only = (flags & _Py_PENDING_MAINTHREADONLY) != 0;
786
0
    if (main_only) {
787
        /* The main thread only exists in the main interpreter. */
788
0
        assert(_Py_IsMainInterpreter(interp));
789
0
        pending = &_PyRuntime.ceval.pending_mainthread;
790
0
    }
791
792
0
    PyMutex_Lock(&pending->mutex);
793
0
    _Py_add_pending_call_result result =
794
0
        _push_pending_call(pending, func, arg, flags);
795
0
    PyMutex_Unlock(&pending->mutex);
796
797
0
    if (main_only) {
798
0
        _Py_set_eval_breaker_bit(_PyRuntime.main_tstate, _PY_CALLS_TO_DO_BIT);
799
0
    }
800
0
    else {
801
#ifdef Py_GIL_DISABLED
802
        _Py_set_eval_breaker_bit_all(interp, _PY_CALLS_TO_DO_BIT);
803
#else
804
0
        signal_active_thread(interp, _PY_CALLS_TO_DO_BIT);
805
0
#endif
806
0
    }
807
808
0
    return result;
809
0
}
810
811
int
812
Py_AddPendingCall(_Py_pending_call_func func, void *arg)
813
0
{
814
    /* Legacy users of this API will continue to target the main thread
815
       (of the main interpreter). */
816
0
    PyInterpreterState *interp = _PyInterpreterState_Main();
817
0
    _Py_add_pending_call_result r =
818
0
        _PyEval_AddPendingCall(interp, func, arg, _Py_PENDING_MAINTHREADONLY);
819
0
    if (r == _Py_ADD_PENDING_FULL) {
820
0
        return -1;
821
0
    }
822
0
    else {
823
0
        assert(r == _Py_ADD_PENDING_SUCCESS);
824
0
        return 0;
825
0
    }
826
0
}
827
828
static int
829
handle_signals(PyThreadState *tstate)
830
0
{
831
0
    assert(_PyThreadState_CheckConsistency(tstate));
832
0
    _Py_unset_eval_breaker_bit(tstate, _PY_SIGNALS_PENDING_BIT);
833
0
    if (!_Py_ThreadCanHandleSignals(tstate->interp)) {
834
0
        return 0;
835
0
    }
836
0
    if (_PyErr_CheckSignalsTstate(tstate) < 0) {
837
        /* On failure, re-schedule a call to handle_signals(). */
838
0
        _Py_set_eval_breaker_bit(tstate, _PY_SIGNALS_PENDING_BIT);
839
0
        return -1;
840
0
    }
841
0
    return 0;
842
0
}
843
844
static int
845
_make_pending_calls(struct _pending_calls *pending, int32_t *p_npending)
846
0
{
847
0
    int res = 0;
848
0
    int32_t npending = -1;
849
850
0
    assert(sizeof(pending->max) <= sizeof(size_t)
851
0
            && ((size_t)pending->max) <= Py_ARRAY_LENGTH(pending->calls));
852
0
    int32_t maxloop = pending->maxloop;
853
0
    if (maxloop == 0) {
854
0
        maxloop = pending->max;
855
0
    }
856
0
    assert(maxloop > 0 && maxloop <= pending->max);
857
858
    /* perform a bounded number of calls, in case of recursion */
859
0
    for (int i=0; i<maxloop; i++) {
860
0
        _Py_pending_call_func func = NULL;
861
0
        void *arg = NULL;
862
0
        int flags = 0;
863
864
        /* pop one item off the queue while holding the lock */
865
0
        PyMutex_Lock(&pending->mutex);
866
0
        _pop_pending_call(pending, &func, &arg, &flags);
867
0
        npending = pending->npending;
868
0
        PyMutex_Unlock(&pending->mutex);
869
870
        /* Check if there are any more pending calls. */
871
0
        if (func == NULL) {
872
0
            assert(npending == 0);
873
0
            break;
874
0
        }
875
876
        /* having released the lock, perform the callback */
877
0
        res = func(arg);
878
0
        if ((flags & _Py_PENDING_RAWFREE) && arg != NULL) {
879
0
            PyMem_RawFree(arg);
880
0
        }
881
0
        if (res != 0) {
882
0
            res = -1;
883
0
            goto finally;
884
0
        }
885
0
    }
886
887
0
finally:
888
0
    *p_npending = npending;
889
0
    return res;
890
0
}
891
892
static void
893
signal_pending_calls(PyThreadState *tstate, PyInterpreterState *interp)
894
0
{
895
#ifdef Py_GIL_DISABLED
896
    _Py_set_eval_breaker_bit_all(interp, _PY_CALLS_TO_DO_BIT);
897
#else
898
0
    _Py_set_eval_breaker_bit(tstate, _PY_CALLS_TO_DO_BIT);
899
0
#endif
900
0
}
901
902
static void
903
unsignal_pending_calls(PyThreadState *tstate, PyInterpreterState *interp)
904
0
{
905
#ifdef Py_GIL_DISABLED
906
    _Py_unset_eval_breaker_bit_all(interp, _PY_CALLS_TO_DO_BIT);
907
#else
908
0
    _Py_unset_eval_breaker_bit(tstate, _PY_CALLS_TO_DO_BIT);
909
0
#endif
910
0
}
911
912
static void
913
clear_pending_handling_thread(struct _pending_calls *pending)
914
0
{
915
0
    FT_MUTEX_LOCK(&pending->mutex);
916
0
    pending->handling_thread = NULL;
917
0
    FT_MUTEX_UNLOCK(&pending->mutex);
918
0
}
919
920
static int
921
make_pending_calls(PyThreadState *tstate)
922
0
{
923
0
    PyInterpreterState *interp = tstate->interp;
924
0
    struct _pending_calls *pending = &interp->ceval.pending;
925
0
    struct _pending_calls *pending_main = &_PyRuntime.ceval.pending_mainthread;
926
927
    /* Only one thread (per interpreter) may run the pending calls
928
       at once.  In the same way, we don't do recursive pending calls. */
929
0
    PyMutex_Lock(&pending->mutex);
930
0
    if (pending->handling_thread != NULL) {
931
        /* A pending call was added after another thread was already
932
           handling the pending calls (and had already "unsignaled").
933
           Once that thread is done, it may have taken care of all the
934
           pending calls, or there might be some still waiting.
935
           To avoid all threads constantly stopping on the eval breaker,
936
           we clear the bit for this thread and make sure it is set
937
           for the thread currently handling the pending call. */
938
0
        _Py_set_eval_breaker_bit(pending->handling_thread, _PY_CALLS_TO_DO_BIT);
939
0
        _Py_unset_eval_breaker_bit(tstate, _PY_CALLS_TO_DO_BIT);
940
0
        PyMutex_Unlock(&pending->mutex);
941
0
        return 0;
942
0
    }
943
0
    pending->handling_thread = tstate;
944
0
    PyMutex_Unlock(&pending->mutex);
945
946
    /* unsignal before starting to call callbacks, so that any callback
947
       added in-between re-signals */
948
0
    unsignal_pending_calls(tstate, interp);
949
950
0
    int32_t npending;
951
0
    if (_make_pending_calls(pending, &npending) != 0) {
952
0
        clear_pending_handling_thread(pending);
953
        /* There might not be more calls to make, but we play it safe. */
954
0
        signal_pending_calls(tstate, interp);
955
0
        return -1;
956
0
    }
957
0
    if (npending > 0) {
958
        /* We hit pending->maxloop. */
959
0
        signal_pending_calls(tstate, interp);
960
0
    }
961
962
0
    if (_Py_IsMainThread() && _Py_IsMainInterpreter(interp)) {
963
0
        if (_make_pending_calls(pending_main, &npending) != 0) {
964
0
            clear_pending_handling_thread(pending);
965
            /* There might not be more calls to make, but we play it safe. */
966
0
            signal_pending_calls(tstate, interp);
967
0
            return -1;
968
0
        }
969
0
        if (npending > 0) {
970
            /* We hit pending_main->maxloop. */
971
0
            signal_pending_calls(tstate, interp);
972
0
        }
973
0
    }
974
975
0
    clear_pending_handling_thread(pending);
976
0
    return 0;
977
0
}
978
979
980
void
981
_Py_set_eval_breaker_bit_all(PyInterpreterState *interp, uintptr_t bit)
982
0
{
983
0
    _Py_FOR_EACH_TSTATE_BEGIN(interp, tstate) {
984
0
        _Py_set_eval_breaker_bit(tstate, bit);
985
0
    }
986
0
    _Py_FOR_EACH_TSTATE_END(interp);
987
0
}
988
989
void
990
_Py_unset_eval_breaker_bit_all(PyInterpreterState *interp, uintptr_t bit)
991
0
{
992
0
    _Py_FOR_EACH_TSTATE_BEGIN(interp, tstate) {
993
0
        _Py_unset_eval_breaker_bit(tstate, bit);
994
0
    }
995
0
    _Py_FOR_EACH_TSTATE_END(interp);
996
0
}
997
998
void
999
_Py_FinishPendingCalls(PyThreadState *tstate)
1000
0
{
1001
0
    _Py_AssertHoldsTstate();
1002
0
    assert(_PyThreadState_CheckConsistency(tstate));
1003
1004
0
    struct _pending_calls *pending = &tstate->interp->ceval.pending;
1005
0
    struct _pending_calls *pending_main =
1006
0
            _Py_IsMainThread() && _Py_IsMainInterpreter(tstate->interp)
1007
0
            ? &_PyRuntime.ceval.pending_mainthread
1008
0
            : NULL;
1009
    /* make_pending_calls() may return early without making all pending
1010
       calls, so we keep trying until we're actually done. */
1011
0
    int32_t npending;
1012
#ifndef NDEBUG
1013
    int32_t npending_prev = INT32_MAX;
1014
#endif
1015
0
    do {
1016
0
        if (make_pending_calls(tstate) < 0) {
1017
0
            PyObject *exc = _PyErr_GetRaisedException(tstate);
1018
0
            PyErr_BadInternalCall();
1019
0
            _PyErr_ChainExceptions1(exc);
1020
0
            _PyErr_Print(tstate);
1021
0
        }
1022
1023
0
        npending = _Py_atomic_load_int32_relaxed(&pending->npending);
1024
0
        if (pending_main != NULL) {
1025
0
            npending += _Py_atomic_load_int32_relaxed(&pending_main->npending);
1026
0
        }
1027
#ifndef NDEBUG
1028
        assert(npending_prev > npending);
1029
        npending_prev = npending;
1030
#endif
1031
0
    } while (npending > 0);
1032
0
}
1033
1034
int
1035
_PyEval_MakePendingCalls(PyThreadState *tstate)
1036
0
{
1037
0
    int res;
1038
1039
0
    if (_Py_IsMainThread() && _Py_IsMainInterpreter(tstate->interp)) {
1040
        /* Python signal handler doesn't really queue a callback:
1041
           it only signals that a signal was received,
1042
           see _PyEval_SignalReceived(). */
1043
0
        res = handle_signals(tstate);
1044
0
        if (res != 0) {
1045
0
            return res;
1046
0
        }
1047
0
    }
1048
1049
0
    res = make_pending_calls(tstate);
1050
0
    if (res != 0) {
1051
0
        return res;
1052
0
    }
1053
1054
0
    return 0;
1055
0
}
1056
1057
/* Py_MakePendingCalls() is a simple wrapper for the sake
1058
   of backward-compatibility. */
1059
int
1060
Py_MakePendingCalls(void)
1061
0
{
1062
0
    _Py_AssertHoldsTstate();
1063
1064
0
    PyThreadState *tstate = _PyThreadState_GET();
1065
0
    assert(_PyThreadState_CheckConsistency(tstate));
1066
1067
    /* Only execute pending calls on the main thread. */
1068
0
    if (!_Py_IsMainThread() || !_Py_IsMainInterpreter(tstate->interp)) {
1069
0
        return 0;
1070
0
    }
1071
0
    return _PyEval_MakePendingCalls(tstate);
1072
0
}
1073
1074
void
1075
_PyEval_InitState(PyInterpreterState *interp)
1076
37
{
1077
37
    _gil_initialize(&interp->_gil);
1078
37
}
1079
1080
#ifdef Py_GIL_DISABLED
1081
int
1082
_PyEval_EnableGILTransient(PyThreadState *tstate)
1083
{
1084
    const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
1085
    if (config->enable_gil != _PyConfig_GIL_DEFAULT) {
1086
        return 0;
1087
    }
1088
    struct _gil_runtime_state *gil = tstate->interp->ceval.gil;
1089
1090
    int enabled = _Py_atomic_load_int_relaxed(&gil->enabled);
1091
    if (enabled == INT_MAX) {
1092
        // The GIL is already enabled permanently.
1093
        return 0;
1094
    }
1095
    if (enabled == INT_MAX - 1) {
1096
        Py_FatalError("Too many transient requests to enable the GIL");
1097
    }
1098
    if (enabled > 0) {
1099
        // If enabled is nonzero, we know we hold the GIL. This means that no
1100
        // other threads are attached, and nobody else can be concurrently
1101
        // mutating it.
1102
        _Py_atomic_store_int_relaxed(&gil->enabled, enabled + 1);
1103
        return 0;
1104
    }
1105
1106
    // Enabling the GIL changes what it means to be an "attached" thread. To
1107
    // safely make this transition, we:
1108
    // 1. Detach the current thread.
1109
    // 2. Stop the world to detach (and suspend) all other threads.
1110
    // 3. Enable the GIL, if nobody else did between our check above and when
1111
    //    our stop-the-world begins.
1112
    // 4. Start the world.
1113
    // 5. Attach the current thread. Other threads may attach and hold the GIL
1114
    //    before this thread, which is harmless.
1115
    _PyThreadState_Detach(tstate);
1116
1117
    // This could be an interpreter-local stop-the-world in situations where we
1118
    // know that this interpreter's GIL is not shared, and that it won't become
1119
    // shared before the stop-the-world begins. For now, we always stop all
1120
    // interpreters for simplicity.
1121
    _PyEval_StopTheWorldAll(&_PyRuntime);
1122
1123
    enabled = _Py_atomic_load_int_relaxed(&gil->enabled);
1124
    int this_thread_enabled = enabled == 0;
1125
    _Py_atomic_store_int_relaxed(&gil->enabled, enabled + 1);
1126
1127
    _PyEval_StartTheWorldAll(&_PyRuntime);
1128
    _PyThreadState_Attach(tstate);
1129
1130
    return this_thread_enabled;
1131
}
1132
1133
int
1134
_PyEval_EnableGILPermanent(PyThreadState *tstate)
1135
{
1136
    const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
1137
    if (config->enable_gil != _PyConfig_GIL_DEFAULT) {
1138
        return 0;
1139
    }
1140
1141
    struct _gil_runtime_state *gil = tstate->interp->ceval.gil;
1142
    assert(current_thread_holds_gil(gil, tstate));
1143
1144
    int enabled = _Py_atomic_load_int_relaxed(&gil->enabled);
1145
    if (enabled == INT_MAX) {
1146
        return 0;
1147
    }
1148
1149
    _Py_atomic_store_int_relaxed(&gil->enabled, INT_MAX);
1150
    return 1;
1151
}
1152
1153
int
1154
_PyEval_DisableGIL(PyThreadState *tstate)
1155
{
1156
    const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
1157
    if (config->enable_gil != _PyConfig_GIL_DEFAULT) {
1158
        return 0;
1159
    }
1160
1161
    struct _gil_runtime_state *gil = tstate->interp->ceval.gil;
1162
    assert(current_thread_holds_gil(gil, tstate));
1163
1164
    int enabled = _Py_atomic_load_int_relaxed(&gil->enabled);
1165
    if (enabled == INT_MAX) {
1166
        return 0;
1167
    }
1168
1169
    assert(enabled >= 1);
1170
    enabled--;
1171
1172
    // Disabling the GIL is much simpler than enabling it, since we know we are
1173
    // the only attached thread. Other threads may start free-threading as soon
1174
    // as this store is complete, if it sets gil->enabled to 0.
1175
    _Py_atomic_store_int_relaxed(&gil->enabled, enabled);
1176
1177
    if (enabled == 0) {
1178
        // We're attached, so we know the GIL will remain disabled until at
1179
        // least the next time we detach, which must be after this function
1180
        // returns.
1181
        //
1182
        // Drop the GIL, which will wake up any threads waiting in take_gil()
1183
        // and let them resume execution without the GIL.
1184
        drop_gil_impl(tstate, gil);
1185
1186
        // If another thread asked us to drop the GIL, they should be
1187
        // free-threading by now. Remove any such request so we have a clean
1188
        // slate if/when the GIL is enabled again.
1189
        _Py_unset_eval_breaker_bit(tstate, _PY_GIL_DROP_REQUEST_BIT);
1190
        return 1;
1191
    }
1192
    return 0;
1193
}
1194
#endif
1195
1196
#if defined(Py_REMOTE_DEBUG) && defined(Py_SUPPORTS_REMOTE_DEBUG)
1197
// Note that this function is inline to avoid creating a PLT entry
1198
// that would be an easy target for a ROP gadget.
1199
static inline int run_remote_debugger_source(PyObject *source)
1200
0
{
1201
0
    const char *str = PyBytes_AsString(source);
1202
0
    if (!str) {
1203
0
        return -1;
1204
0
    }
1205
1206
0
    PyObject *ns = PyDict_New();
1207
0
    if (!ns) {
1208
0
        return -1;
1209
0
    }
1210
1211
0
    PyObject *res = PyRun_String(str, Py_file_input, ns, ns);
1212
0
    Py_DECREF(ns);
1213
0
    if (!res) {
1214
0
        return -1;
1215
0
    }
1216
0
    Py_DECREF(res);
1217
0
    return 0;
1218
0
}
1219
1220
// Note that this function is inline to avoid creating a PLT entry
1221
// that would be an easy target for a ROP gadget.
1222
static inline void run_remote_debugger_script(PyObject *path)
1223
0
{
1224
0
    if (0 != PySys_Audit("cpython.remote_debugger_script", "O", path)) {
1225
0
        PyErr_FormatUnraisable(
1226
0
            "Audit hook failed for remote debugger script %U", path);
1227
0
        return;
1228
0
    }
1229
1230
    // Open the debugger script with the open code hook, and reopen the
1231
    // resulting file object to get a C FILE* object.
1232
0
    PyObject* fileobj = PyFile_OpenCodeObject(path);
1233
0
    if (!fileobj) {
1234
0
        PyErr_FormatUnraisable("Can't open debugger script %U", path);
1235
0
        return;
1236
0
    }
1237
1238
0
    PyObject* source = PyObject_CallMethodNoArgs(fileobj, &_Py_ID(read));
1239
0
    if (!source) {
1240
0
        PyErr_FormatUnraisable("Error reading debugger script %U", path);
1241
0
    }
1242
1243
0
    PyObject* res = PyObject_CallMethodNoArgs(fileobj, &_Py_ID(close));
1244
0
    if (!res) {
1245
0
        PyErr_FormatUnraisable("Error closing debugger script %U", path);
1246
0
    } else {
1247
0
        Py_DECREF(res);
1248
0
    }
1249
0
    Py_DECREF(fileobj);
1250
1251
0
    if (source) {
1252
0
        if (0 != run_remote_debugger_source(source)) {
1253
0
            PyErr_FormatUnraisable("Error executing debugger script %U", path);
1254
0
        }
1255
0
        Py_DECREF(source);
1256
0
    }
1257
0
}
1258
1259
int _PyRunRemoteDebugger(PyThreadState *tstate)
1260
75.9M
{
1261
75.9M
    const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
1262
75.9M
    if (config->remote_debug == 1
1263
75.9M
         && tstate->remote_debugger_support.debugger_pending_call == 1)
1264
0
    {
1265
0
        tstate->remote_debugger_support.debugger_pending_call = 0;
1266
1267
        // Immediately make a copy in case of a race with another debugger
1268
        // process that's trying to write to the buffer. At least this way
1269
        // we'll be internally consistent: what we audit is what we run.
1270
0
        const size_t pathsz
1271
0
            = sizeof(tstate->remote_debugger_support.debugger_script_path);
1272
1273
0
        char *path = PyMem_Malloc(pathsz);
1274
0
        if (path) {
1275
            // And don't assume the debugger correctly null terminated it.
1276
0
            memcpy(
1277
0
                path,
1278
0
                tstate->remote_debugger_support.debugger_script_path,
1279
0
                pathsz);
1280
0
            path[pathsz - 1] = '\0';
1281
0
            if (*path) {
1282
0
                PyObject *path_obj = PyUnicode_DecodeFSDefault(path);
1283
0
                if (path_obj == NULL) {
1284
0
                    PyErr_FormatUnraisable("Can't decode debugger script");
1285
0
                }
1286
0
                else {
1287
0
                    run_remote_debugger_script(path_obj);
1288
0
                    Py_DECREF(path_obj);
1289
0
                }
1290
0
            }
1291
0
            PyMem_Free(path);
1292
0
        }
1293
0
    }
1294
75.9M
    return 0;
1295
75.9M
}
1296
1297
#endif
1298
1299
/* Do periodic things, like check for signals and async I/0.
1300
* We need to do reasonably frequently, but not too frequently.
1301
* All loops should include a check of the eval breaker.
1302
* We also check on return from any builtin function.
1303
*
1304
* ## More Details ###
1305
*
1306
* The eval loop (this function) normally executes the instructions
1307
* of a code object sequentially.  However, the runtime supports a
1308
* number of out-of-band execution scenarios that may pause that
1309
* sequential execution long enough to do that out-of-band work
1310
* in the current thread using the current PyThreadState.
1311
*
1312
* The scenarios include:
1313
*
1314
*  - cyclic garbage collection
1315
*  - GIL drop requests
1316
*  - "async" exceptions
1317
*  - "pending calls"  (some only in the main thread)
1318
*  - signal handling (only in the main thread)
1319
*
1320
* When the need for one of the above is detected, the eval loop
1321
* pauses long enough to handle the detected case.  Then, if doing
1322
* so didn't trigger an exception, the eval loop resumes executing
1323
* the sequential instructions.
1324
*
1325
* To make this work, the eval loop periodically checks if any
1326
* of the above needs to happen.  The individual checks can be
1327
* expensive if computed each time, so a while back we switched
1328
* to using pre-computed, per-interpreter variables for the checks,
1329
* and later consolidated that to a single "eval breaker" variable
1330
* (now a PyInterpreterState field).
1331
*
1332
* For the longest time, the eval breaker check would happen
1333
* frequently, every 5 or so times through the loop, regardless
1334
* of what instruction ran last or what would run next.  Then, in
1335
* early 2021 (gh-18334, commit 4958f5d), we switched to checking
1336
* the eval breaker less frequently, by hard-coding the check to
1337
* specific places in the eval loop (e.g. certain instructions).
1338
* The intent then was to check after returning from calls
1339
* and on the back edges of loops.
1340
*
1341
* In addition to being more efficient, that approach keeps
1342
* the eval loop from running arbitrary code between instructions
1343
* that don't handle that well.  (See gh-74174.)
1344
*
1345
* Currently, the eval breaker check happens on back edges in
1346
* the control flow graph, which pretty much applies to all loops,
1347
* and most calls.
1348
* (See bytecodes.c for exact information.)
1349
*
1350
* One consequence of this approach is that it might not be obvious
1351
* how to force any specific thread to pick up the eval breaker,
1352
* or for any specific thread to not pick it up.  Mostly this
1353
* involves judicious uses of locks and careful ordering of code,
1354
* while avoiding code that might trigger the eval breaker
1355
* until so desired.
1356
*/
1357
int
1358
_Py_HandlePending(PyThreadState *tstate)
1359
125k
{
1360
125k
    uintptr_t breaker = _Py_atomic_load_uintptr_relaxed(&tstate->eval_breaker);
1361
1362
    /* Stop-the-world */
1363
125k
    if ((breaker & _PY_EVAL_PLEASE_STOP_BIT) != 0) {
1364
0
        _Py_unset_eval_breaker_bit(tstate, _PY_EVAL_PLEASE_STOP_BIT);
1365
0
        _PyThreadState_Suspend(tstate);
1366
1367
        /* The attach blocks until the stop-the-world event is complete. */
1368
0
        _PyThreadState_Attach(tstate);
1369
0
    }
1370
1371
    /* Pending signals */
1372
125k
    if ((breaker & _PY_SIGNALS_PENDING_BIT) != 0) {
1373
0
        if (handle_signals(tstate) != 0) {
1374
0
            return -1;
1375
0
        }
1376
0
    }
1377
1378
    /* Pending calls */
1379
125k
    if ((breaker & _PY_CALLS_TO_DO_BIT) != 0) {
1380
0
        if (make_pending_calls(tstate) != 0) {
1381
0
            return -1;
1382
0
        }
1383
0
    }
1384
1385
#ifdef Py_GIL_DISABLED
1386
    /* Objects with refcounts to merge */
1387
    if ((breaker & _PY_EVAL_EXPLICIT_MERGE_BIT) != 0) {
1388
        _Py_unset_eval_breaker_bit(tstate, _PY_EVAL_EXPLICIT_MERGE_BIT);
1389
        _Py_brc_merge_refcounts(tstate);
1390
    }
1391
    /* Process deferred memory frees held by QSBR */
1392
    if (_Py_qsbr_should_process(((_PyThreadStateImpl *)tstate)->qsbr)) {
1393
        _PyMem_ProcessDelayed(tstate);
1394
    }
1395
#endif
1396
1397
    /* GC scheduled to run */
1398
125k
    if ((breaker & _PY_GC_SCHEDULED_BIT) != 0) {
1399
125k
        _Py_unset_eval_breaker_bit(tstate, _PY_GC_SCHEDULED_BIT);
1400
125k
        _Py_RunGC(tstate);
1401
#ifdef _Py_TIER2
1402
        _Py_ClearExecutorDeletionList(tstate->interp);
1403
#endif
1404
125k
    }
1405
1406
#ifdef _Py_TIER2
1407
    if ((breaker & _PY_EVAL_JIT_INVALIDATE_COLD_BIT) != 0) {
1408
        _Py_unset_eval_breaker_bit(tstate, _PY_EVAL_JIT_INVALIDATE_COLD_BIT);
1409
        _Py_Executors_InvalidateCold(tstate->interp);
1410
        tstate->interp->executor_creation_counter = JIT_CLEANUP_THRESHOLD;
1411
        _Py_ClearExecutorDeletionList(tstate->interp);
1412
    }
1413
#endif
1414
1415
    /* GIL drop request */
1416
125k
    if ((breaker & _PY_GIL_DROP_REQUEST_BIT) != 0) {
1417
        /* Give another thread a chance */
1418
0
        _PyThreadState_Detach(tstate);
1419
1420
        /* Other threads may run now */
1421
1422
0
        _PyThreadState_Attach(tstate);
1423
0
    }
1424
1425
    /* Check for asynchronous exception. */
1426
125k
    if ((breaker & _PY_ASYNC_EXCEPTION_BIT) != 0) {
1427
0
        if (_PyEval_RaiseAsyncExc(tstate) < 0) {
1428
0
            return -1;
1429
0
        }
1430
0
    }
1431
1432
125k
#if defined(Py_REMOTE_DEBUG) && defined(Py_SUPPORTS_REMOTE_DEBUG)
1433
125k
    _PyRunRemoteDebugger(tstate);
1434
125k
#endif
1435
1436
125k
    return 0;
1437
125k
}
1438
1439
int
1440
_PyEval_RaiseAsyncExc(PyThreadState *tstate)
1441
0
{
1442
0
    assert(tstate != NULL);
1443
0
    assert(tstate == _PyThreadState_GET());
1444
0
    _Py_unset_eval_breaker_bit(tstate, _PY_ASYNC_EXCEPTION_BIT);
1445
0
    PyObject *exc = _Py_atomic_exchange_ptr(&tstate->async_exc, NULL);
1446
0
    if (exc != NULL) {
1447
0
        _PyErr_SetNone(tstate, exc);
1448
0
        Py_DECREF(exc);
1449
0
        return -1;
1450
0
    }
1451
0
    return 0;
1452
0
}