pystate.h 17 KB

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