Coverage Report

Created: 2026-07-14 06:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython-install/include/python3.16/cpython/pystate.h
Line
Count
Source
1
#ifndef Py_CPYTHON_PYSTATE_H
2
#  error "this header file must not be included directly"
3
#endif
4
5
6
/* private interpreter helpers */
7
8
PyAPI_FUNC(int) _PyInterpreterState_RequiresIDRef(PyInterpreterState *);
9
PyAPI_FUNC(void) _PyInterpreterState_RequireIDRef(PyInterpreterState *, int);
10
11
/* State unique per thread */
12
13
/* Py_tracefunc return -1 when raising an exception, or 0 for success. */
14
typedef int (*Py_tracefunc)(PyObject *, PyFrameObject *, int, PyObject *);
15
16
/* The following values are used for 'what' for tracefunc functions
17
 *
18
 * To add a new kind of trace event, also update "trace_init" in
19
 * Python/sysmodule.c to define the Python level event name
20
 */
21
#define PyTrace_CALL 0
22
#define PyTrace_EXCEPTION 1
23
#define PyTrace_LINE 2
24
#define PyTrace_RETURN 3
25
#define PyTrace_C_CALL 4
26
#define PyTrace_C_EXCEPTION 5
27
#define PyTrace_C_RETURN 6
28
#define PyTrace_OPCODE 7
29
30
/* Remote debugger support */
31
#define _Py_MAX_SCRIPT_PATH_SIZE 512
32
typedef struct {
33
    int32_t debugger_pending_call;
34
    char debugger_script_path[_Py_MAX_SCRIPT_PATH_SIZE];
35
} _PyRemoteDebuggerSupport;
36
37
typedef struct _err_stackitem {
38
    /* This struct represents a single execution context where we might
39
     * be currently handling an exception.  It is a per-coroutine state
40
     * (coroutine in the computer science sense, including the thread
41
     * and generators).
42
     *
43
     * This is used as an entry on the exception stack, where each
44
     * entry indicates if it is currently handling an exception.
45
     * This ensures that the exception state is not impacted
46
     * by "yields" from an except handler.  The thread
47
     * always has an entry (the bottom-most one).
48
     */
49
50
    /* The exception currently being handled in this context, if any. */
51
    PyObject *exc_value;
52
53
    struct _err_stackitem *previous_item;
54
55
} _PyErr_StackItem;
56
57
typedef struct _stack_chunk {
58
    struct _stack_chunk *previous;
59
    size_t size;
60
    size_t top;
61
    PyObject * data[1]; /* Variable sized */
62
} _PyStackChunk;
63
64
/* Minimum size of data stack chunk */
65
#define _PY_DATA_STACK_CHUNK_SIZE (16*1024)
66
struct _ts {
67
    /* See Python/ceval.c for comments explaining most fields */
68
69
    PyThreadState *prev;
70
    PyThreadState *next;
71
    PyInterpreterState *interp;
72
73
    /* The global instrumentation version in high bits, plus flags indicating
74
       when to break out of the interpreter loop in lower bits. See details in
75
       pycore_ceval.h. */
76
    uintptr_t eval_breaker;
77
78
    struct {
79
        /* Has been initialized to a safe state.
80
81
           In order to be effective, this must be set to 0 during or right
82
           after allocation. */
83
        unsigned int initialized:1;
84
85
        /* Has been bound to an OS thread. */
86
        unsigned int bound:1;
87
        /* Has been unbound from its OS thread. */
88
        unsigned int unbound:1;
89
        /* Has been bound aa current for the GILState API. */
90
        unsigned int bound_gilstate:1;
91
        /* Currently in use (maybe holds the GIL). */
92
        unsigned int active:1;
93
94
        /* various stages of finalization */
95
        unsigned int finalizing:1;
96
        unsigned int cleared:1;
97
        unsigned int finalized:1;
98
99
        /* padding to align to 4 bytes */
100
        unsigned int :24;
101
    } _status;
102
#ifdef Py_BUILD_CORE
103
#  define _PyThreadState_WHENCE_NOTSET -1
104
#  define _PyThreadState_WHENCE_UNKNOWN 0
105
#  define _PyThreadState_WHENCE_INIT 1
106
#  define _PyThreadState_WHENCE_FINI 2
107
#  define _PyThreadState_WHENCE_THREADING 3
108
#  define _PyThreadState_WHENCE_C_API 4
109
#  define _PyThreadState_WHENCE_EXEC 5
110
#  define _PyThreadState_WHENCE_THREADING_DAEMON 6
111
#endif
112
113
    /* Currently holds the GIL. Must be its own field to avoid data races */
114
    int holds_gil;
115
116
    /* Currently requesting the GIL */
117
    int gil_requested;
118
119
    int _whence;
120
121
    /* Thread state (_Py_THREAD_ATTACHED, _Py_THREAD_DETACHED, _Py_THREAD_SUSPENDED).
122
       See Include/internal/pycore_pystate.h for more details. */
123
    int state;
124
125
    int py_recursion_remaining;
126
    int py_recursion_limit;
127
    int recursion_headroom; /* Allow 50 more calls to handle any errors. */
128
129
    /* 'tracing' keeps track of the execution depth when tracing/profiling.
130
       This is to prevent the actual trace/profile code from being recorded in
131
       the trace/profile. */
132
    int tracing;
133
    int what_event; /* The event currently being monitored, if any. */
134
135
    /* Pointer to currently executing frame. */
136
    struct _PyInterpreterFrame *current_frame;
137
138
    /* Pointer to the base frame (bottommost sentinel frame).
139
       Used by profilers to validate complete stack unwinding.
140
       Points to the embedded base_frame in _PyThreadStateImpl.
141
       The frame is embedded there rather than here because _PyInterpreterFrame
142
       is defined in internal headers that cannot be exposed in the public API. */
143
    struct _PyInterpreterFrame *base_frame;
144
145
    struct _PyInterpreterFrame *last_profiled_frame;
146
    uintptr_t last_profiled_frame_seq;
147
148
    Py_tracefunc c_profilefunc;
149
    Py_tracefunc c_tracefunc;
150
    PyObject *c_profileobj;
151
    PyObject *c_traceobj;
152
153
    /* The exception currently being raised */
154
    PyObject *current_exception;
155
156
    /* Pointer to the top of the exception stack for the exceptions
157
     * we may be currently handling.  (See _PyErr_StackItem above.)
158
     * This is never NULL. */
159
    _PyErr_StackItem *exc_info;
160
161
    PyObject *dict;  /* Stores per-thread state */
162
163
    int gilstate_counter;
164
165
    PyObject *async_exc; /* Asynchronous exception to raise */
166
    unsigned long thread_id; /* Thread id where this tstate was created */
167
168
    /* Native thread id where this tstate was created. This will be 0 except on
169
     * those platforms that have the notion of native thread id, for which the
170
     * macro PY_HAVE_THREAD_NATIVE_ID is then defined.
171
     */
172
    unsigned long native_thread_id;
173
174
    /* List of objects that still need to be cleaned up, singly linked
175
     * via their gc headers' gc_next pointers. The list is populated by
176
     * _PyTrash_thread_deposit_object and cleaned up by
177
     * _PyTrash_thread_destroy_chain.
178
     */
179
    PyObject *delete_later;
180
181
    /* Tagged pointer to top-most critical section, or zero if there is no
182
     * active critical section. Critical sections are only used in
183
     * `--disable-gil` builds (i.e., when Py_GIL_DISABLED is defined to 1). In the
184
     * default build, this field is always zero.
185
     */
186
    uintptr_t critical_section;
187
188
    int coroutine_origin_tracking_depth;
189
190
    PyObject *async_gen_firstiter;
191
    PyObject *async_gen_finalizer;
192
193
    PyObject *context;
194
    uint64_t context_ver;
195
196
    /* Unique thread state id. */
197
    uint64_t id;
198
199
    _PyStackChunk *datastack_chunk;
200
    PyObject **datastack_top;
201
    PyObject **datastack_limit;
202
    _PyStackChunk *datastack_cached_chunk;
203
    /* XXX signal handlers should also be here */
204
205
    /* The following fields are here to avoid allocation during init.
206
       The data is exposed through PyThreadState pointer fields.
207
       These fields should not be accessed directly outside of init.
208
       This is indicated by an underscore prefix on the field names.
209
210
       All other PyInterpreterState pointer fields are populated when
211
       needed and default to NULL.
212
       */
213
       // Note some fields do not have a leading underscore for backward
214
       // compatibility.  See https://bugs.python.org/issue45953#msg412046.
215
216
    /* The thread's exception stack entry.  (Always the last entry.) */
217
    _PyErr_StackItem exc_state;
218
219
    PyObject *current_executor;
220
221
    /* Internal to the JIT */
222
    struct _PyExitData *jit_exit;
223
224
    uint64_t dict_global_version;
225
226
    /* Used to store/retrieve `threading.local` keys/values for this thread */
227
    PyObject *threading_local_key;
228
229
    /* Used by `threading.local`s to be remove keys/values for dying threads.
230
       The PyThreadObject must hold the only reference to this value.
231
    */
232
    PyObject *threading_local_sentinel;
233
    _PyRemoteDebuggerSupport remote_debugger_support;
234
235
#ifdef Py_STATS
236
    // Pointer to PyStats structure, NULL if recording is off.  For the
237
    // free-threaded build, the structure is per-thread (stored as a pointer
238
    // in _PyThreadStateImpl).  For the default build, the structure is stored
239
    // in the PyInterpreterState structure (threads do not have their own
240
    // structure and all share the same per-interpreter structure).
241
    PyStats *pystats;
242
#endif
243
244
    struct {
245
        /* Number of nested PyThreadState_Ensure() calls on this thread state */
246
        Py_ssize_t counter;
247
248
        /* Should this thread state be deleted upon calling
249
           PyThreadState_Release() (with the counter at 1)?
250
251
           This is only true for thread states created by PyThreadState_Ensure() */
252
        int delete_on_release;
253
254
        /* The interpreter guard owned by PyThreadState_EnsureFromView(), if any. */
255
        PyInterpreterGuard *owned_guard;
256
    } ensure;
257
};
258
259
/* other API */
260
261
/* Similar to PyThreadState_Get(), but don't issue a fatal error
262
 * if it is NULL. */
263
PyAPI_FUNC(PyThreadState *) PyThreadState_GetUnchecked(void);
264
265
// Deprecated alias kept for backward compatibility
266
Py_DEPRECATED(3.14) static inline PyThreadState*
267
_PyThreadState_UncheckedGet(void)
268
0
{
269
0
    return PyThreadState_GetUnchecked();
270
0
}
271
272
// Disable tracing and profiling.
273
PyAPI_FUNC(void) PyThreadState_EnterTracing(PyThreadState *tstate);
274
275
// Reset tracing and profiling: enable them if a trace function or a profile
276
// function is set, otherwise disable them.
277
PyAPI_FUNC(void) PyThreadState_LeaveTracing(PyThreadState *tstate);
278
279
#ifdef Py_STATS
280
#if defined(HAVE_THREAD_LOCAL) && !defined(Py_BUILD_CORE_MODULE)
281
extern _Py_thread_local PyThreadState *_Py_tss_tstate;
282
283
static inline PyStats*
284
_PyThreadState_GetStatsFast(void)
285
{
286
    if (_Py_tss_tstate == NULL) {
287
        return NULL; // no attached thread state
288
    }
289
    return _Py_tss_tstate->pystats;
290
}
291
#endif
292
#endif // Py_STATS
293
294
/* PyGILState */
295
296
/* Helper/diagnostic function - return 1 if the current thread
297
   currently holds the GIL, 0 otherwise.
298
299
   The function returns 1 if _PyGILState_check_enabled is non-zero. */
300
PyAPI_FUNC(int) PyGILState_Check(void);
301
302
/* The implementation of sys._current_frames()  Returns a dict mapping
303
   thread id to that thread's current frame.
304
*/
305
PyAPI_FUNC(PyObject*) _PyThread_CurrentFrames(void);
306
307
// Set the stack protection start address and stack protection size
308
// of a Python thread state
309
PyAPI_FUNC(int) PyUnstable_ThreadState_SetStackProtection(
310
    PyThreadState *tstate,
311
    void *stack_start_addr,  // Stack start address
312
    size_t stack_size);      // Stack size (in bytes)
313
314
// Reset the stack protection start address and stack protection size
315
// of a Python thread state
316
PyAPI_FUNC(void) PyUnstable_ThreadState_ResetStackProtection(
317
    PyThreadState *tstate);
318
319
/* Routines for advanced debuggers, requested by David Beazley.
320
   Don't use unless you know what you are doing! */
321
PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_Main(void);
322
PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_Head(void);
323
PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_Next(PyInterpreterState *);
324
PyAPI_FUNC(PyThreadState *) PyInterpreterState_ThreadHead(PyInterpreterState *);
325
PyAPI_FUNC(PyThreadState *) PyThreadState_Next(PyThreadState *);
326
PyAPI_FUNC(void) PyThreadState_DeleteCurrent(void);
327
328
/* Frame evaluation API */
329
330
typedef PyObject* (*_PyFrameEvalFunction)(PyThreadState *tstate, struct _PyInterpreterFrame *, int);
331
332
PyAPI_FUNC(_PyFrameEvalFunction) _PyInterpreterState_GetEvalFrameFunc(
333
    PyInterpreterState *interp);
334
PyAPI_FUNC(void) _PyInterpreterState_SetEvalFrameFunc(
335
    PyInterpreterState *interp,
336
    _PyFrameEvalFunction eval_frame);
337
PyAPI_FUNC(void) _PyInterpreterState_SetEvalFrameAllowSpecialization(
338
    PyInterpreterState *interp,
339
    int allow_specialization);
340
PyAPI_FUNC(int) _PyInterpreterState_IsSpecializationEnabled(
341
    PyInterpreterState *interp);