1 #ifndef Py_CPYTHON_PYSTATE_H
2 #  error "this header file must not be included directly"
3 #endif
4 
5 PyAPI_FUNC(int) _PyInterpreterState_RequiresIDRef(PyInterpreterState *);
6 PyAPI_FUNC(void) _PyInterpreterState_RequireIDRef(PyInterpreterState *, int);
7 
8 PyAPI_FUNC(PyObject *) _PyInterpreterState_GetMainModule(PyInterpreterState *);
9 
10 /* State unique per thread */
11 
12 /* Py_tracefunc return -1 when raising an exception, or 0 for success. */
13 typedef int (*Py_tracefunc)(PyObject *, PyFrameObject *, int, PyObject *);
14 
15 /* The following values are used for 'what' for tracefunc functions
16  *
17  * To add a new kind of trace event, also update "trace_init" in
18  * Python/sysmodule.c to define the Python level event name
19  */
20 #define PyTrace_CALL 0
21 #define PyTrace_EXCEPTION 1
22 #define PyTrace_LINE 2
23 #define PyTrace_RETURN 3
24 #define PyTrace_C_CALL 4
25 #define PyTrace_C_EXCEPTION 5
26 #define PyTrace_C_RETURN 6
27 #define PyTrace_OPCODE 7
28 
29 
30 typedef struct {
31     PyCodeObject *code; // The code object for the bounds. May be NULL.
32     PyCodeAddressRange bounds; // Only valid if code != NULL.
33 } PyTraceInfo;
34 
35 typedef struct _cframe {
36     /* This struct will be threaded through the C stack
37      * allowing fast access to per-thread state that needs
38      * to be accessed quickly by the interpreter, but can
39      * be modified outside of the interpreter.
40      *
41      * WARNING: This makes data on the C stack accessible from
42      * heap objects. Care must be taken to maintain stack
43      * discipline and make sure that instances of this struct cannot
44      * accessed outside of their lifetime.
45      */
46     int use_tracing;
47     /* Pointer to the currently executing frame (it can be NULL) */
48     struct _interpreter_frame *current_frame;
49     struct _cframe *previous;
50 } CFrame;
51 
52 typedef struct _err_stackitem {
53     /* This struct represents an entry on the exception stack, which is a
54      * per-coroutine state. (Coroutine in the computer science sense,
55      * including the thread and generators).
56      * This ensures that the exception state is not impacted by "yields"
57      * from an except handler.
58      */
59     PyObject *exc_type, *exc_value, *exc_traceback;
60 
61     struct _err_stackitem *previous_item;
62 
63 } _PyErr_StackItem;
64 
65 typedef struct _stack_chunk {
66     struct _stack_chunk *previous;
67     size_t size;
68     size_t top;
69     PyObject * data[1]; /* Variable sized */
70 } _PyStackChunk;
71 
72 // The PyThreadState typedef is in Include/pystate.h.
73 struct _ts {
74     /* See Python/ceval.c for comments explaining most fields */
75 
76     struct _ts *prev;
77     struct _ts *next;
78     PyInterpreterState *interp;
79 
80     /* Has been initialized to a safe state.
81 
82        In order to be effective, this must be set to 0 during or right
83        after allocation. */
84     int _initialized;
85 
86     int recursion_remaining;
87     int recursion_limit;
88     int recursion_headroom; /* Allow 50 more calls to handle any errors. */
89 
90     /* 'tracing' keeps track of the execution depth when tracing/profiling.
91        This is to prevent the actual trace/profile code from being recorded in
92        the trace/profile. */
93     int tracing;
94 
95     /* Pointer to current CFrame in the C stack frame of the currently,
96      * or most recently, executing _PyEval_EvalFrameDefault. */
97     CFrame *cframe;
98 
99     Py_tracefunc c_profilefunc;
100     Py_tracefunc c_tracefunc;
101     PyObject *c_profileobj;
102     PyObject *c_traceobj;
103 
104     /* The exception currently being raised */
105     PyObject *curexc_type;
106     PyObject *curexc_value;
107     PyObject *curexc_traceback;
108 
109     /* The exception currently being handled, if no coroutines/generators
110      * are present. Always last element on the stack referred to be exc_info.
111      */
112     _PyErr_StackItem exc_state;
113 
114     /* Pointer to the top of the stack of the exceptions currently
115      * being handled */
116     _PyErr_StackItem *exc_info;
117 
118     PyObject *dict;  /* Stores per-thread state */
119 
120     int gilstate_counter;
121 
122     PyObject *async_exc; /* Asynchronous exception to raise */
123     unsigned long thread_id; /* Thread id where this tstate was created */
124 
125     /* Native thread id where this tstate was created. This will be 0 except on
126      * those platforms that have the notion of native thread id, for which the
127      * macro PY_HAVE_THREAD_NATIVE_ID is then defined.
128      */
129     unsigned long native_thread_id;
130 
131     int trash_delete_nesting;
132     PyObject *trash_delete_later;
133 
134     /* Called when a thread state is deleted normally, but not when it
135      * is destroyed after fork().
136      * Pain:  to prevent rare but fatal shutdown errors (issue 18808),
137      * Thread.join() must wait for the join'ed thread's tstate to be unlinked
138      * from the tstate chain.  That happens at the end of a thread's life,
139      * in pystate.c.
140      * The obvious way doesn't quite work:  create a lock which the tstate
141      * unlinking code releases, and have Thread.join() wait to acquire that
142      * lock.  The problem is that we _are_ at the end of the thread's life:
143      * if the thread holds the last reference to the lock, decref'ing the
144      * lock will delete the lock, and that may trigger arbitrary Python code
145      * if there's a weakref, with a callback, to the lock.  But by this time
146      * _PyRuntime.gilstate.tstate_current is already NULL, so only the simplest
147      * of C code can be allowed to run (in particular it must not be possible to
148      * release the GIL).
149      * So instead of holding the lock directly, the tstate holds a weakref to
150      * the lock:  that's the value of on_delete_data below.  Decref'ing a
151      * weakref is harmless.
152      * on_delete points to _threadmodule.c's static release_sentinel() function.
153      * After the tstate is unlinked, release_sentinel is called with the
154      * weakref-to-lock (on_delete_data) argument, and release_sentinel releases
155      * the indirectly held lock.
156      */
157     void (*on_delete)(void *);
158     void *on_delete_data;
159 
160     int coroutine_origin_tracking_depth;
161 
162     PyObject *async_gen_firstiter;
163     PyObject *async_gen_finalizer;
164 
165     PyObject *context;
166     uint64_t context_ver;
167 
168     /* Unique thread state id. */
169     uint64_t id;
170 
171     CFrame root_cframe;
172     PyTraceInfo trace_info;
173 
174     _PyStackChunk *datastack_chunk;
175     PyObject **datastack_top;
176     PyObject **datastack_limit;
177     /* XXX signal handlers should also be here */
178 
179 };
180 
181 // Alias for backward compatibility with Python 3.8
182 #define _PyInterpreterState_Get PyInterpreterState_Get
183 
184 PyAPI_FUNC(PyThreadState *) _PyThreadState_Prealloc(PyInterpreterState *);
185 
186 /* Similar to PyThreadState_Get(), but don't issue a fatal error
187  * if it is NULL. */
188 PyAPI_FUNC(PyThreadState *) _PyThreadState_UncheckedGet(void);
189 
190 PyAPI_FUNC(PyObject *) _PyThreadState_GetDict(PyThreadState *tstate);
191 
192 // Disable tracing and profiling.
193 PyAPI_FUNC(void) PyThreadState_EnterTracing(PyThreadState *tstate);
194 
195 // Reset tracing and profiling: enable them if a trace function or a profile
196 // function is set, otherwise disable them.
197 PyAPI_FUNC(void) PyThreadState_LeaveTracing(PyThreadState *tstate);
198 
199 /* PyGILState */
200 
201 /* Helper/diagnostic function - return 1 if the current thread
202    currently holds the GIL, 0 otherwise.
203 
204    The function returns 1 if _PyGILState_check_enabled is non-zero. */
205 PyAPI_FUNC(int) PyGILState_Check(void);
206 
207 /* Get the single PyInterpreterState used by this process' GILState
208    implementation.
209 
210    This function doesn't check for error. Return NULL before _PyGILState_Init()
211    is called and after _PyGILState_Fini() is called.
212 
213    See also _PyInterpreterState_Get() and _PyInterpreterState_GET(). */
214 PyAPI_FUNC(PyInterpreterState *) _PyGILState_GetInterpreterStateUnsafe(void);
215 
216 /* The implementation of sys._current_frames()  Returns a dict mapping
217    thread id to that thread's current frame.
218 */
219 PyAPI_FUNC(PyObject *) _PyThread_CurrentFrames(void);
220 
221 /* The implementation of sys._current_exceptions()  Returns a dict mapping
222    thread id to that thread's current exception.
223 */
224 PyAPI_FUNC(PyObject *) _PyThread_CurrentExceptions(void);
225 
226 /* Routines for advanced debuggers, requested by David Beazley.
227    Don't use unless you know what you are doing! */
228 PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_Main(void);
229 PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_Head(void);
230 PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_Next(PyInterpreterState *);
231 PyAPI_FUNC(PyThreadState *) PyInterpreterState_ThreadHead(PyInterpreterState *);
232 PyAPI_FUNC(PyThreadState *) PyThreadState_Next(PyThreadState *);
233 PyAPI_FUNC(void) PyThreadState_DeleteCurrent(void);
234 
235 /* Frame evaluation API */
236 
237 typedef PyObject* (*_PyFrameEvalFunction)(PyThreadState *tstate, struct _interpreter_frame *, int);
238 
239 PyAPI_FUNC(_PyFrameEvalFunction) _PyInterpreterState_GetEvalFrameFunc(
240     PyInterpreterState *interp);
241 PyAPI_FUNC(void) _PyInterpreterState_SetEvalFrameFunc(
242     PyInterpreterState *interp,
243     _PyFrameEvalFunction eval_frame);
244 
245 PyAPI_FUNC(const PyConfig*) _PyInterpreterState_GetConfig(PyInterpreterState *interp);
246 
247 /* Get a copy of the current interpreter configuration.
248 
249    Return 0 on success. Raise an exception and return -1 on error.
250 
251    The caller must initialize 'config', using PyConfig_InitPythonConfig()
252    for example.
253 
254    Python must be preinitialized to call this method.
255    The caller must hold the GIL. */
256 PyAPI_FUNC(int) _PyInterpreterState_GetConfigCopy(
257     struct PyConfig *config);
258 
259 /* Set the configuration of the current interpreter.
260 
261    This function should be called during or just after the Python
262    initialization.
263 
264    Update the sys module with the new configuration. If the sys module was
265    modified directly after the Python initialization, these changes are lost.
266 
267    Some configuration like faulthandler or warnoptions can be updated in the
268    configuration, but don't reconfigure Python (don't enable/disable
269    faulthandler and don't reconfigure warnings filters).
270 
271    Return 0 on success. Raise an exception and return -1 on error.
272 
273    The configuration should come from _PyInterpreterState_GetConfigCopy(). */
274 PyAPI_FUNC(int) _PyInterpreterState_SetConfig(
275     const struct PyConfig *config);
276 
277 // Get the configuration of the current interpreter.
278 // The caller must hold the GIL.
279 PyAPI_FUNC(const PyConfig*) _Py_GetConfig(void);
280 
281 
282 /* cross-interpreter data */
283 
284 struct _xid;
285 
286 // _PyCrossInterpreterData is similar to Py_buffer as an effectively
287 // opaque struct that holds data outside the object machinery.  This
288 // is necessary to pass safely between interpreters in the same process.
289 typedef struct _xid {
290     // data is the cross-interpreter-safe derivation of a Python object
291     // (see _PyObject_GetCrossInterpreterData).  It will be NULL if the
292     // new_object func (below) encodes the data.
293     void *data;
294     // obj is the Python object from which the data was derived.  This
295     // is non-NULL only if the data remains bound to the object in some
296     // way, such that the object must be "released" (via a decref) when
297     // the data is released.  In that case the code that sets the field,
298     // likely a registered "crossinterpdatafunc", is responsible for
299     // ensuring it owns the reference (i.e. incref).
300     PyObject *obj;
301     // interp is the ID of the owning interpreter of the original
302     // object.  It corresponds to the active interpreter when
303     // _PyObject_GetCrossInterpreterData() was called.  This should only
304     // be set by the cross-interpreter machinery.
305     //
306     // We use the ID rather than the PyInterpreterState to avoid issues
307     // with deleted interpreters.  Note that IDs are never re-used, so
308     // each one will always correspond to a specific interpreter
309     // (whether still alive or not).
310     int64_t interp;
311     // new_object is a function that returns a new object in the current
312     // interpreter given the data.  The resulting object (a new
313     // reference) will be equivalent to the original object.  This field
314     // is required.
315     PyObject *(*new_object)(struct _xid *);
316     // free is called when the data is released.  If it is NULL then
317     // nothing will be done to free the data.  For some types this is
318     // okay (e.g. bytes) and for those types this field should be set
319     // to NULL.  However, for most the data was allocated just for
320     // cross-interpreter use, so it must be freed when
321     // _PyCrossInterpreterData_Release is called or the memory will
322     // leak.  In that case, at the very least this field should be set
323     // to PyMem_RawFree (the default if not explicitly set to NULL).
324     // The call will happen with the original interpreter activated.
325     void (*free)(void *);
326 } _PyCrossInterpreterData;
327 
328 PyAPI_FUNC(int) _PyObject_GetCrossInterpreterData(PyObject *, _PyCrossInterpreterData *);
329 PyAPI_FUNC(PyObject *) _PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *);
330 PyAPI_FUNC(void) _PyCrossInterpreterData_Release(_PyCrossInterpreterData *);
331 
332 PyAPI_FUNC(int) _PyObject_CheckCrossInterpreterData(PyObject *);
333 
334 /* cross-interpreter data registry */
335 
336 typedef int (*crossinterpdatafunc)(PyObject *, struct _xid *);
337 
338 PyAPI_FUNC(int) _PyCrossInterpreterData_RegisterClass(PyTypeObject *, crossinterpdatafunc);
339 PyAPI_FUNC(crossinterpdatafunc) _PyCrossInterpreterData_Lookup(PyObject *);
340