codekingpro/portable-devtools
114k
1/* This file contains the struct definitions for interpreter state2 * and other necessary structs */3 4#ifndef Py_INTERNAL_INTERP_STRUCTS_H5#define Py_INTERNAL_INTERP_STRUCTS_H6#ifdef __cplusplus7extern "C" {8#endif9 10#include "pycore_ast_state.h" // struct ast_state11#include "pycore_llist.h" // struct llist_node12#include "pycore_opcode_utils.h" // NUM_COMMON_CONSTANTS13#include "pycore_pymath.h" // _PY_SHORT_FLOAT_REPR14#include "pycore_structs.h" // PyHamtObject15#include "pycore_tstate.h" // _PyThreadStateImpl16#include "pycore_typedefs.h" // _PyRuntimeState17 18 19#define CODE_MAX_WATCHERS 820#define CONTEXT_MAX_WATCHERS 821#define FUNC_MAX_WATCHERS 822#define TYPE_MAX_WATCHERS 823 24 25#ifdef Py_GIL_DISABLED26// This should be prime but otherwise the choice is arbitrary. A larger value27// increases concurrency at the expense of memory.28# define NUM_WEAKREF_LIST_LOCKS 12729#endif30 31typedef int (*_Py_pending_call_func)(void *);32 33struct _pending_call {34 _Py_pending_call_func func;35 void *arg;36 int flags;37};38 39#define PENDINGCALLSARRAYSIZE 30040 41struct _pending_calls {42 PyThreadState *handling_thread;43 PyMutex mutex;44 /* Request for running pending calls. */45 int32_t npending;46 /* The maximum allowed number of pending calls.47 If the queue fills up to this point then _PyEval_AddPendingCall()48 will return _Py_ADD_PENDING_FULL. */49 int32_t max;50 /* We don't want a flood of pending calls to interrupt any one thread51 for too long, so we keep a limit on the number handled per pass.52 A value of 0 means there is no limit (other than the maximum53 size of the list of pending calls). */54 int32_t maxloop;55 struct _pending_call calls[PENDINGCALLSARRAYSIZE];56 int first;57 int next;58};59 60typedef enum {61 PERF_STATUS_FAILED = -1, // Perf trampoline is in an invalid state62 PERF_STATUS_NO_INIT = 0, // Perf trampoline is not initialized63 PERF_STATUS_OK = 1, // Perf trampoline is ready to be executed64} perf_status_t;65 66#ifdef PY_HAVE_PERF_TRAMPOLINE67struct code_arena_st;68 69struct trampoline_api_st {70 void* (*init_state)(void);71 void (*write_state)(void* state, const void *code_addr,72 unsigned int code_size, PyCodeObject* code);73 int (*free_state)(void* state);74 void *state;75 Py_ssize_t code_padding;76};77#endif78 79 80struct _ceval_runtime_state {81 struct {82#ifdef PY_HAVE_PERF_TRAMPOLINE83 perf_status_t status;84 int perf_trampoline_type;85 Py_ssize_t extra_code_index;86 struct code_arena_st *code_arena;87 struct trampoline_api_st trampoline_api;88 FILE *map_file;89 Py_ssize_t persist_after_fork;90 _PyFrameEvalFunction prev_eval_frame;91 Py_ssize_t trampoline_refcount;92 int code_watcher_id;93#else94 int _not_used;95#endif96 } perf;97 /* Pending calls to be made only on the main thread. */98 // The signal machinery falls back on this99 // so it must be especially stable and efficient.100 // For example, we use a preallocated array101 // for the list of pending calls.102 struct _pending_calls pending_mainthread;103 PyMutex unused_sys_trace_profile_mutex; // kept for ABI compatibility104};105 106 107struct _ceval_state {108 /* This variable holds the global instrumentation version. When a thread is109 running, this value is overlaid onto PyThreadState.eval_breaker so that110 changes in the instrumentation version will trigger the eval breaker. */111 uintptr_t instrumentation_version;112 int recursion_limit;113 struct _gil_runtime_state *gil;114 int own_gil;115 struct _pending_calls pending;116};117 118 119//###############120// runtime atexit121 122typedef void (*atexit_callbackfunc)(void);123 124struct _atexit_runtime_state {125 PyMutex mutex;126#define NEXITFUNCS 32127 atexit_callbackfunc callbacks[NEXITFUNCS];128 int ncallbacks;129};130 131 132//###################133// interpreter atexit134 135typedef void (*atexit_datacallbackfunc)(void *);136 137typedef struct atexit_callback {138 atexit_datacallbackfunc func;139 void *data;140 struct atexit_callback *next;141} atexit_callback;142 143struct atexit_state {144#ifdef Py_GIL_DISABLED145 PyMutex ll_callbacks_lock;146#endif147 atexit_callback *ll_callbacks;148 149 // XXX The rest of the state could be moved to the atexit module state150 // and a low-level callback added for it during module exec.151 // For the moment we leave it here.152 153 // List containing tuples with callback information.154 // e.g. [(func, args, kwargs), ...]155 PyObject *callbacks;156};157 158 159/****** Garbage collector **********/160 161/* GC information is stored BEFORE the object structure. */162typedef struct {163 // Tagged pointer to next object in the list.164 // 0 means the object is not tracked165 uintptr_t _gc_next;166 167 // Tagged pointer to previous object in the list.168 // Lowest two bits are used for flags documented later.169 uintptr_t _gc_prev;170} PyGC_Head;171 172#define _PyGC_Head_UNUSED PyGC_Head173 174struct gc_generation {175 PyGC_Head head;176 int threshold; /* collection threshold */177 int count; /* count of allocations or collections of younger178 generations */179};180 181struct gc_collection_stats {182 /* number of collected objects */183 Py_ssize_t collected;184 /* total number of uncollectable objects (put into gc.garbage) */185 Py_ssize_t uncollectable;186};187 188/* Running stats per generation */189struct gc_generation_stats {190 /* total number of collections */191 Py_ssize_t collections;192 /* total number of collected objects */193 Py_ssize_t collected;194 /* total number of uncollectable objects (put into gc.garbage) */195 Py_ssize_t uncollectable;196};197 198enum _GCPhase {199 GC_PHASE_MARK = 0,200 GC_PHASE_COLLECT = 1201};202 203/* If we change this, we need to change the default value in the204 signature of gc.collect. */205#define NUM_GENERATIONS 3206 207struct _gc_runtime_state {208 /* List of objects that still need to be cleaned up, singly linked209 * via their gc headers' gc_prev pointers. */210 PyObject *trash_delete_later;211 /* Current call-stack depth of tp_dealloc calls. */212 int trash_delete_nesting;213 214 /* Is automatic collection enabled? */215 int enabled;216 int debug;217 /* linked lists of container objects */218 struct gc_generation young;219 struct gc_generation old[2];220 /* a permanent generation which won't be collected */221 struct gc_generation permanent_generation;222 struct gc_generation_stats generation_stats[NUM_GENERATIONS];223 /* true if we are currently running the collector */224 int collecting;225 /* list of uncollectable objects */226 PyObject *garbage;227 /* a list of callbacks to be invoked when collection is performed */228 PyObject *callbacks;229 230 Py_ssize_t heap_size;231 Py_ssize_t work_to_do;232 /* Which of the old spaces is the visited space */233 int visited_space;234 int phase;235 236#ifdef Py_GIL_DISABLED237 /* This is the number of objects that survived the last full238 collection. It approximates the number of long lived objects239 tracked by the GC.240 241 (by "full collection", we mean a collection of the oldest242 generation). */243 Py_ssize_t long_lived_total;244 /* This is the number of objects that survived all "non-full"245 collections, and are awaiting to undergo a full collection for246 the first time. */247 Py_ssize_t long_lived_pending;248 249 /* True if gc.freeze() has been used. */250 int freeze_active;251 252 /* Memory usage of the process (RSS + swap) after last GC. */253 Py_ssize_t last_mem;254 255 /* This accumulates the new object count whenever collection is deferred256 due to the RSS increase condition not being meet. Reset on collection. */257 Py_ssize_t deferred_count;258 259 /* Mutex held for gc_should_collect_mem_usage(). */260 PyMutex mutex;261#endif262};263 264#include "pycore_gil.h" // struct _gil_runtime_state265 266/**** Import ********/267 268struct _import_runtime_state {269 /* The builtin modules (defined in config.c). */270 struct _inittab *inittab;271 /* The most recent value assigned to a PyModuleDef.m_base.m_index.272 This is incremented each time PyModuleDef_Init() is called,273 which is just about every time an extension module is imported.274 See PyInterpreterState.modules_by_index for more info. */275 Py_ssize_t last_module_index;276 struct {277 /* A lock to guard the cache. */278 PyMutex mutex;279 /* The actual cache of (filename, name, PyModuleDef) for modules.280 Only legacy (single-phase init) extension modules are added281 and only if they support multiple initialization (m_size >= 0)282 or are imported in the main interpreter.283 This is initialized lazily in fix_up_extension() in import.c.284 Modules are added there and looked up in _imp.find_extension(). */285 struct _Py_hashtable_t *hashtable;286 } extensions;287 /* Package context -- the full module name for package imports */288 const char * pkgcontext;289};290 291struct _import_state {292 /* cached sys.modules dictionary */293 PyObject *modules;294 /* This is the list of module objects for all legacy (single-phase init)295 extension modules ever loaded in this process (i.e. imported296 in this interpreter or in any other). Py_None stands in for297 modules that haven't actually been imported in this interpreter.298 299 A module's index (PyModuleDef.m_base.m_index) is used to look up300 the corresponding module object for this interpreter, if any.301 (See PyState_FindModule().) When any extension module302 is initialized during import, its moduledef gets initialized by303 PyModuleDef_Init(), and the first time that happens for each304 PyModuleDef, its index gets set to the current value of305 a global counter (see _PyRuntimeState.imports.last_module_index).306 The entry for that index in this interpreter remains unset until307 the module is actually imported here. (Py_None is used as308 a placeholder.) Note that multi-phase init modules always get309 an index for which there will never be a module set.310 311 This is initialized lazily in PyState_AddModule(), which is also312 where modules get added. */313 PyObject *modules_by_index;314 /* importlib module._bootstrap */315 PyObject *importlib;316 /* override for config->use_frozen_modules (for tests)317 (-1: "off", 1: "on", 0: no override) */318 int override_frozen_modules;319 int override_multi_interp_extensions_check;320#ifdef HAVE_DLOPEN321 int dlopenflags;322#endif323 PyObject *import_func;324 /* The global import lock. */325 _PyRecursiveMutex lock;326 /* diagnostic info in PyImport_ImportModuleLevelObject() */327 struct {328 int import_level;329 PyTime_t accumulated;330 int header;331 } find_and_load;332};333 334 335 336/********** Interpreter state **************/337 338#include "pycore_object_state.h" // struct _py_object_state339#include "pycore_crossinterp.h" // _PyXI_state_t340 341 342struct _Py_long_state {343 int max_str_digits;344};345 346struct codecs_state {347 // A list of callable objects used to search for codecs.348 PyObject *search_path;349 350 // A dict mapping codec names to codecs returned from a callable in351 // search_path.352 PyObject *search_cache;353 354 // A dict mapping error handling strategies to functions to implement them.355 PyObject *error_registry;356 357#ifdef Py_GIL_DISABLED358 // Used to safely delete a specific item from search_path.359 PyMutex search_path_mutex;360#endif361 362 // Whether or not the rest of the state is initialized.363 int initialized;364};365 366// Support for stop-the-world events. This exists in both the PyRuntime struct367// for global pauses and in each PyInterpreterState for per-interpreter pauses.368struct _stoptheworld_state {369 PyMutex mutex; // Serializes stop-the-world attempts.370 371 // NOTE: The below fields are protected by HEAD_LOCK(runtime), not by the372 // above mutex.373 bool requested; // Set when a pause is requested.374 bool world_stopped; // Set when the world is stopped.375 bool is_global; // Set when contained in PyRuntime struct.376 377 PyEvent stop_event; // Set when thread_countdown reaches zero.378 Py_ssize_t thread_countdown; // Number of threads that must pause.379 380 PyThreadState *requester; // Thread that requested the pause (may be NULL).381};382 383/* Tracks some rare events per-interpreter, used by the optimizer to turn on/off384 specific optimizations. */385typedef struct _rare_events {386 /* Setting an object's class, obj.__class__ = ... */387 uint8_t set_class;388 /* Setting the bases of a class, cls.__bases__ = ... */389 uint8_t set_bases;390 /* Setting the PEP 523 frame eval function, _PyInterpreterState_SetFrameEvalFunc() */391 uint8_t set_eval_frame_func;392 /* Modifying the builtins, __builtins__.__dict__[var] = ... */393 uint8_t builtin_dict;394 /* Modifying a function, e.g. func.__defaults__ = ..., etc. */395 uint8_t func_modification;396} _rare_events;397 398struct399Bigint {400 struct Bigint *next;401 int k, maxwds, sign, wds;402 uint32_t x[1];403};404 405#if defined(Py_USING_MEMORY_DEBUGGER) || _PY_SHORT_FLOAT_REPR == 0406 407struct _dtoa_state {408 int _not_used;409};410 411#else // !Py_USING_MEMORY_DEBUGGER && _PY_SHORT_FLOAT_REPR != 0412 413/* The size of the Bigint freelist */414#define Bigint_Kmax 7415 416/* The size of the cached powers of 5 array */417#define Bigint_Pow5size 8418 419#ifndef PRIVATE_MEM420#define PRIVATE_MEM 2304421#endif422#define Bigint_PREALLOC_SIZE \423 ((PRIVATE_MEM+sizeof(double)-1)/sizeof(double))424 425struct _dtoa_state {426 // p5s is an array of powers of 5 of the form:427 // 5**(2**(i+2)) for 0 <= i < Bigint_Pow5size428 struct Bigint *p5s[Bigint_Pow5size];429 // XXX This should be freed during runtime fini.430 struct Bigint *freelist[Bigint_Kmax+1];431 double preallocated[Bigint_PREALLOC_SIZE];432 double *preallocated_next;433};434 435#endif // !Py_USING_MEMORY_DEBUGGER436 437struct _py_code_state {438 PyMutex mutex;439 // Interned constants from code objects. Used by the free-threaded build.440 struct _Py_hashtable_t *constants;441};442 443#define FUNC_VERSION_CACHE_SIZE (1<<12) /* Must be a power of 2 */444 445struct _func_version_cache_item {446 PyFunctionObject *func;447 PyObject *code;448};449 450struct _py_func_state {451#ifdef Py_GIL_DISABLED452 // Protects next_version453 PyMutex mutex;454#endif455 456 uint32_t next_version;457 // Borrowed references to function and code objects whose458 // func_version % FUNC_VERSION_CACHE_SIZE459 // once was equal to the index in the table.460 // They are cleared when the function or code object is deallocated.461 struct _func_version_cache_item func_version_cache[FUNC_VERSION_CACHE_SIZE];462};463 464#include "pycore_dict_state.h" // struct _Py_dict_state465#include "pycore_exceptions.h" // struct _Py_exc_state466 467 468/****** type state *********/469 470/* For now we hard-code this to a value for which we are confident471 all the static builtin types will fit (for all builds). */472#define _Py_MAX_MANAGED_STATIC_BUILTIN_TYPES 200473#define _Py_MAX_MANAGED_STATIC_EXT_TYPES 10474#define _Py_MAX_MANAGED_STATIC_TYPES \475 (_Py_MAX_MANAGED_STATIC_BUILTIN_TYPES + _Py_MAX_MANAGED_STATIC_EXT_TYPES)476 477struct _types_runtime_state {478 /* Used to set PyTypeObject.tp_version_tag for core static types. */479 // bpo-42745: next_version_tag remains shared by all interpreters480 // because of static types.481 unsigned int next_version_tag;482 483 struct {484 struct {485 PyTypeObject *type;486 int64_t interp_count;487 } types[_Py_MAX_MANAGED_STATIC_TYPES];488 } managed_static;489};490 491 492// Type attribute lookup cache: speed up attribute and method lookups,493// see _PyType_Lookup().494struct type_cache_entry {495 unsigned int version; // initialized from type->tp_version_tag496#ifdef Py_GIL_DISABLED497 _PySeqLock sequence;498#endif499 PyObject *name; // reference to exactly a str or None500 PyObject *value; // borrowed reference or NULL501};502 503#define MCACHE_SIZE_EXP 12504 505struct type_cache {506 struct type_cache_entry hashtable[1 << MCACHE_SIZE_EXP];507};508 509typedef struct {510 PyTypeObject *type;511 int isbuiltin;512 int readying;513 int ready;514 // XXX tp_dict can probably be statically allocated,515 // instead of dynamically and stored on the interpreter.516 PyObject *tp_dict;517 PyObject *tp_subclasses;518 /* We never clean up weakrefs for static builtin types since519 they will effectively never get triggered. However, there520 are also some diagnostic uses for the list of weakrefs,521 so we still keep it. */522 PyObject *tp_weaklist;523} managed_static_type_state;524 525#define TYPE_VERSION_CACHE_SIZE (1<<12) /* Must be a power of 2 */526 527struct types_state {528 /* Used to set PyTypeObject.tp_version_tag.529 It starts at _Py_MAX_GLOBAL_TYPE_VERSION_TAG + 1,530 where all those lower numbers are used for core static types. */531 unsigned int next_version_tag;532 533 struct type_cache type_cache;534 535 /* Every static builtin type is initialized for each interpreter536 during its own initialization, including for the main interpreter537 during global runtime initialization. This is done by calling538 _PyStaticType_InitBuiltin().539 540 The first time a static builtin type is initialized, all the541 normal PyType_Ready() stuff happens. The only difference from542 normal is that there are three PyTypeObject fields holding543 objects which are stored here (on PyInterpreterState) rather544 than in the corresponding PyTypeObject fields. Those are:545 tp_dict (cls.__dict__), tp_subclasses (cls.__subclasses__),546 and tp_weaklist.547 548 When a subinterpreter is initialized, each static builtin type549 is still initialized, but only the interpreter-specific portion,550 namely those three objects.551 552 Those objects are stored in the PyInterpreterState.types.builtins553 array, at the index corresponding to each specific static builtin554 type. That index (a size_t value) is stored in the tp_subclasses555 field. For static builtin types, we re-purposed the now-unused556 tp_subclasses to avoid adding another field to PyTypeObject.557 In all other cases tp_subclasses holds a dict like before.558 (The field was previously defined as PyObject*, but is now void*559 to reflect its dual use.)560 561 The index for each static builtin type isn't statically assigned.562 Instead it is calculated the first time a type is initialized563 (by the main interpreter). The index matches the order in which564 the type was initialized relative to the others. The actual565 value comes from the current value of num_builtins_initialized,566 as each type is initialized for the main interpreter.567 568 num_builtins_initialized is incremented once for each static569 builtin type. Once initialization is over for a subinterpreter,570 the value will be the same as for all other interpreters. */571 struct {572 size_t num_initialized;573 managed_static_type_state initialized[_Py_MAX_MANAGED_STATIC_BUILTIN_TYPES];574 } builtins;575 /* We apply a similar strategy for managed extension modules. */576 struct {577 size_t num_initialized;578 size_t next_index;579 managed_static_type_state initialized[_Py_MAX_MANAGED_STATIC_EXT_TYPES];580 } for_extensions;581 PyMutex mutex;582 583 // Borrowed references to type objects whose584 // tp_version_tag % TYPE_VERSION_CACHE_SIZE585 // once was equal to the index in the table.586 // They are cleared when the type object is deallocated.587 PyTypeObject *type_version_cache[TYPE_VERSION_CACHE_SIZE];588};589 590struct _warnings_runtime_state {591 /* Both 'filters' and 'onceregistry' can be set in warnings.py;592 get_warnings_attr() will reset these variables accordingly. */593 PyObject *filters; /* List */594 PyObject *once_registry; /* Dict */595 PyObject *default_action; /* String */596 _PyRecursiveMutex lock;597 long filters_version;598 PyObject *context;599};600 601struct _Py_mem_interp_free_queue {602 int has_work; // true if the queue is not empty603 PyMutex mutex; // protects the queue604 struct llist_node head; // queue of _mem_work_chunk items605};606 607 608/****** Unicode state *********/609 610typedef enum {611 _Py_ERROR_UNKNOWN=0,612 _Py_ERROR_STRICT,613 _Py_ERROR_SURROGATEESCAPE,614 _Py_ERROR_REPLACE,615 _Py_ERROR_IGNORE,616 _Py_ERROR_BACKSLASHREPLACE,617 _Py_ERROR_SURROGATEPASS,618 _Py_ERROR_XMLCHARREFREPLACE,619 _Py_ERROR_OTHER620} _Py_error_handler;621 622struct _Py_unicode_runtime_ids {623 PyMutex mutex;624 // next_index value must be preserved when Py_Initialize()/Py_Finalize()625 // is called multiple times: see _PyUnicode_FromId() implementation.626 Py_ssize_t next_index;627};628 629struct _Py_unicode_runtime_state {630 struct _Py_unicode_runtime_ids ids;631};632 633/* fs_codec.encoding is initialized to NULL.634 Later, it is set to a non-NULL string by _PyUnicode_InitEncodings(). */635struct _Py_unicode_fs_codec {636 char *encoding; // Filesystem encoding (encoded to UTF-8)637 int utf8; // encoding=="utf-8"?638 char *errors; // Filesystem errors (encoded to UTF-8)639 _Py_error_handler error_handler;640};641 642struct _Py_unicode_ids {643 Py_ssize_t size;644 PyObject **array;645};646 647#include "pycore_ucnhash.h" // _PyUnicode_Name_CAPI648 649struct _Py_unicode_state {650 struct _Py_unicode_fs_codec fs_codec;651 652 _PyUnicode_Name_CAPI *ucnhash_capi;653 654 // Unicode identifiers (_Py_Identifier): see _PyUnicode_FromId()655 struct _Py_unicode_ids ids;656};657 658// Borrowed references to common callables:659struct callable_cache {660 PyObject *isinstance;661 PyObject *len;662 PyObject *list_append;663 PyObject *object__getattribute__;664};665 666/* Length of array of slotdef pointers used to store slots with the667 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with668 the same __name__, for any __name__. Since that's a static property, it is669 appropriate to declare fixed-size arrays for this. */670#define MAX_EQUIV 10671 672typedef struct wrapperbase pytype_slotdef;673 674 675struct _Py_interp_cached_objects {676#ifdef Py_GIL_DISABLED677 PyMutex interned_mutex;678#endif679 PyObject *interned_strings;680 681 /* object.__reduce__ */682 PyObject *objreduce;683 PyObject *type_slots_pname;684 pytype_slotdef *type_slots_ptrs[MAX_EQUIV];685 686 /* TypeVar and related types */687 PyTypeObject *generic_type;688 PyTypeObject *typevar_type;689 PyTypeObject *typevartuple_type;690 PyTypeObject *paramspec_type;691 PyTypeObject *paramspecargs_type;692 PyTypeObject *paramspeckwargs_type;693 PyTypeObject *constevaluator_type;694};695 696struct _Py_interp_static_objects {697 struct {698 int _not_used;699 // hamt_empty is here instead of global because of its weakreflist.700 _PyGC_Head_UNUSED _hamt_empty_gc_not_used;701 PyHamtObject hamt_empty;702 PyBaseExceptionObject last_resort_memory_error;703 } singletons;704};705 706#include "pycore_instruments.h" // PY_MONITORING_TOOL_IDS707 708 709#ifdef Py_GIL_DISABLED710 711// A min-heap of indices712typedef struct _PyIndexHeap {713 int32_t *values;714 715 // Number of items stored in values716 Py_ssize_t size;717 718 // Maximum number of items that can be stored in values719 Py_ssize_t capacity;720} _PyIndexHeap;721 722// An unbounded pool of indices. Indices are allocated starting from 0. They723// may be released back to the pool once they are no longer in use.724typedef struct _PyIndexPool {725 PyMutex mutex;726 727 // Min heap of indices available for allocation728 _PyIndexHeap free_indices;729 730 // Next index to allocate if no free indices are available731 int32_t next_index;732 733 // Generation counter incremented on thread creation/destruction734 // Used for TLBC cache invalidation in remote debugging735 uint32_t tlbc_generation;736} _PyIndexPool;737 738typedef union _Py_unique_id_entry {739 // Points to the next free type id, when part of the freelist740 union _Py_unique_id_entry *next;741 742 // Stores the object when the id is assigned743 PyObject *obj;744} _Py_unique_id_entry;745 746struct _Py_unique_id_pool {747 PyMutex mutex;748 749 // combined table of object with allocated unique ids and unallocated ids.750 _Py_unique_id_entry *table;751 752 // Next entry to allocate inside 'table' or NULL753 _Py_unique_id_entry *freelist;754 755 // size of 'table'756 Py_ssize_t size;757};758 759#endif760 761 762/* PyInterpreterState holds the global state for one of the runtime's763 interpreters. Typically the initial (main) interpreter is the only one.764 765 The PyInterpreterState typedef is in Include/pytypedefs.h.766 */767struct _is {768 769 /* This struct contains the eval_breaker,770 * which is by far the hottest field in this struct771 * and should be placed at the beginning. */772 struct _ceval_state ceval;773 774 // unused, kept for ABI compatibility775 void *_malloced;776 777 PyInterpreterState *next;778 779 int64_t id;780 Py_ssize_t id_refcount;781 int requires_idref;782 783 long _whence;784 785 /* Has been initialized to a safe state.786 787 In order to be effective, this must be set to 0 during or right788 after allocation. */789 int _initialized;790 /* Has been fully initialized via pylifecycle.c. */791 int _ready;792 int finalizing;793 794 uintptr_t last_restart_version;795 struct pythreads {796 uint64_t next_unique_id;797 /* The linked list of threads, newest first. */798 PyThreadState *head;799 _PyThreadStateImpl *preallocated;800 /* The thread currently executing in the __main__ module, if any. */801 PyThreadState *main;802 /* Used in Modules/_threadmodule.c. */803 Py_ssize_t count;804 /* Support for runtime thread stack size tuning.805 A value of 0 means using the platform's default stack size806 or the size specified by the THREAD_STACK_SIZE macro. */807 /* Used in Python/thread.c. */808 size_t stacksize;809 } threads;810 811 /* Reference to the _PyRuntime global variable. This field exists812 to not have to pass runtime in addition to tstate to a function.813 Get runtime from tstate: tstate->interp->runtime. */814 _PyRuntimeState *runtime;815 816 /* Set by Py_EndInterpreter().817 818 Use _PyInterpreterState_GetFinalizing()819 and _PyInterpreterState_SetFinalizing()820 to access it, don't access it directly. */821 PyThreadState* _finalizing;822 /* The ID of the OS thread in which we are finalizing. */823 unsigned long _finalizing_id;824 825 struct _gc_runtime_state gc;826 827 /* The following fields are here to avoid allocation during init.828 The data is exposed through PyInterpreterState pointer fields.829 These fields should not be accessed directly outside of init.830 831 All other PyInterpreterState pointer fields are populated when832 needed and default to NULL.833 834 For now there are some exceptions to that rule, which require835 allocation during init. These will be addressed on a case-by-case836 basis. Also see _PyRuntimeState regarding the various mutex fields.837 */838 839 // Dictionary of the sys module840 PyObject *sysdict;841 842 // Dictionary of the builtins module843 PyObject *builtins;844 845 struct _import_state imports;846 847 /* The per-interpreter GIL, which might not be used. */848 struct _gil_runtime_state _gil;849 850 uint64_t _code_object_generation;851 852 /* ---------- IMPORTANT ---------------------------853 The fields above this line are declared as early as854 possible to facilitate out-of-process observability855 tools. */856 857 struct codecs_state codecs;858 859 PyConfig config;860 unsigned long feature_flags;861 862 PyObject *dict; /* Stores per-interpreter state */863 864 PyObject *sysdict_copy;865 PyObject *builtins_copy;866 // Initialized to _PyEval_EvalFrameDefault().867 _PyFrameEvalFunction eval_frame;868 869 PyFunction_WatchCallback func_watchers[FUNC_MAX_WATCHERS];870 // One bit is set for each non-NULL entry in func_watchers871 uint8_t active_func_watchers;872 873 Py_ssize_t co_extra_user_count;874 freefunc co_extra_freefuncs[MAX_CO_EXTRA_USERS];875 876 /* cross-interpreter data and utils */877 _PyXI_state_t xi;878 879#ifdef HAVE_FORK880 PyObject *before_forkers;881 PyObject *after_forkers_parent;882 PyObject *after_forkers_child;883#endif884 885 struct _warnings_runtime_state warnings;886 struct atexit_state atexit;887 struct _stoptheworld_state stoptheworld;888 struct _qsbr_shared qsbr;889 890#if defined(Py_GIL_DISABLED)891 struct _mimalloc_interp_state mimalloc;892 struct _brc_state brc; // biased reference counting state893 struct _Py_unique_id_pool unique_ids; // object ids for per-thread refcounts894 PyMutex weakref_locks[NUM_WEAKREF_LIST_LOCKS];895 _PyIndexPool tlbc_indices;896#endif897 // Per-interpreter list of tasks, any lingering tasks from thread898 // states gets added here and removed from the corresponding899 // thread state's list.900 struct llist_node asyncio_tasks_head;901 // `asyncio_tasks_lock` is used when tasks are moved902 // from thread's list to interpreter's list.903 PyMutex asyncio_tasks_lock;904 905 // Per-interpreter state for the obmalloc allocator. For the main906 // interpreter and for all interpreters that don't have their907 // own obmalloc state, this points to the static structure in908 // obmalloc.c obmalloc_state_main. For other interpreters, it is909 // heap allocated by _PyMem_init_obmalloc() and freed when the910 // interpreter structure is freed. In the case of a heap allocated911 // obmalloc state, it is not safe to hold on to or use memory after912 // the interpreter is freed. The obmalloc state corresponding to913 // that allocated memory is gone. See free_obmalloc_arenas() for914 // more comments.915 struct _obmalloc_state *obmalloc;916 917 PyObject *audit_hooks;918 PyType_WatchCallback type_watchers[TYPE_MAX_WATCHERS];919 PyCode_WatchCallback code_watchers[CODE_MAX_WATCHERS];920 PyContext_WatchCallback context_watchers[CONTEXT_MAX_WATCHERS];921 // One bit is set for each non-NULL entry in code_watchers922 uint8_t active_code_watchers;923 uint8_t active_context_watchers;924 925 struct _py_object_state object_state;926 struct _Py_unicode_state unicode;927 struct _Py_long_state long_state;928 struct _dtoa_state dtoa;929 struct _py_func_state func_state;930 struct _py_code_state code_state;931 932 struct _Py_dict_state dict_state;933 struct _Py_exc_state exc_state;934 struct _Py_mem_interp_free_queue mem_free_queue;935 936 struct ast_state ast;937 struct types_state types;938 struct callable_cache callable_cache;939 PyObject *common_consts[NUM_COMMON_CONSTANTS];940 bool jit;941 struct _PyExecutorObject *executor_list_head;942 struct _PyExecutorObject *executor_deletion_list_head;943 int executor_deletion_list_remaining_capacity;944 size_t trace_run_counter;945 _rare_events rare_events;946 PyDict_WatchCallback builtins_dict_watcher;947 948 _Py_GlobalMonitors monitors;949 _PyOnceFlag sys_profile_once_flag;950 _PyOnceFlag sys_trace_once_flag;951 Py_ssize_t sys_profiling_threads; /* Count of threads with c_profilefunc set */952 Py_ssize_t sys_tracing_threads; /* Count of threads with c_tracefunc set */953 PyObject *monitoring_callables[PY_MONITORING_TOOL_IDS][_PY_MONITORING_EVENTS];954 PyObject *monitoring_tool_names[PY_MONITORING_TOOL_IDS];955 uintptr_t monitoring_tool_versions[PY_MONITORING_TOOL_IDS];956 957 struct _Py_interp_cached_objects cached_objects;958 struct _Py_interp_static_objects static_objects;959 960 Py_ssize_t _interactive_src_count;961 962#if !defined(Py_GIL_DISABLED) && defined(Py_STACKREF_DEBUG)963 uint64_t next_stackref;964 _Py_hashtable_t *open_stackrefs_table;965# ifdef Py_STACKREF_CLOSE_DEBUG966 _Py_hashtable_t *closed_stackrefs_table;967# endif968#endif969 970 /* the initial PyInterpreterState.threads.head */971 _PyThreadStateImpl _initial_thread;972 // _initial_thread should be the last field of PyInterpreterState.973 // See https://github.com/python/cpython/issues/127117.974};975 976 977#ifdef __cplusplus978}979#endif980#endif /* Py_INTERNAL_INTERP_STRUCTS_H */981 