LCOV - code coverage report
Current view: top level - Python - pystate.c (source / functions) Hit Total Coverage
Test: CPython 3.12 LCOV report [commit 5e6661bce9] Lines: 463 1022 45.3 %
Date: 2023-03-20 08:15:36 Functions: 64 123 52.0 %
Branches: 143 440 32.5 %

           Branch data     Line data    Source code
       1                 :            : 
       2                 :            : /* Thread and interpreter state structures and their interfaces */
       3                 :            : 
       4                 :            : #include "Python.h"
       5                 :            : #include "pycore_ceval.h"
       6                 :            : #include "pycore_code.h"          // stats
       7                 :            : #include "pycore_dtoa.h"          // _dtoa_state_INIT()
       8                 :            : #include "pycore_frame.h"
       9                 :            : #include "pycore_initconfig.h"
      10                 :            : #include "pycore_object.h"        // _PyType_InitCache()
      11                 :            : #include "pycore_pyerrors.h"
      12                 :            : #include "pycore_pylifecycle.h"
      13                 :            : #include "pycore_pymem.h"         // _PyMem_SetDefaultAllocator()
      14                 :            : #include "pycore_pystate.h"
      15                 :            : #include "pycore_runtime_init.h"  // _PyRuntimeState_INIT
      16                 :            : #include "pycore_sysmodule.h"
      17                 :            : 
      18                 :            : /* --------------------------------------------------------------------------
      19                 :            : CAUTION
      20                 :            : 
      21                 :            : Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file.  A
      22                 :            : number of these functions are advertised as safe to call when the GIL isn't
      23                 :            : held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
      24                 :            : debugging obmalloc functions.  Those aren't thread-safe (they rely on the GIL
      25                 :            : to avoid the expense of doing their own locking).
      26                 :            : -------------------------------------------------------------------------- */
      27                 :            : 
      28                 :            : #ifdef HAVE_DLOPEN
      29                 :            : #ifdef HAVE_DLFCN_H
      30                 :            : #include <dlfcn.h>
      31                 :            : #endif
      32                 :            : #if !HAVE_DECL_RTLD_LAZY
      33                 :            : #define RTLD_LAZY 1
      34                 :            : #endif
      35                 :            : #endif
      36                 :            : 
      37                 :            : #ifdef __cplusplus
      38                 :            : extern "C" {
      39                 :            : #endif
      40                 :            : 
      41                 :            : 
      42                 :            : /****************************************/
      43                 :            : /* helpers for the current thread state */
      44                 :            : /****************************************/
      45                 :            : 
      46                 :            : // API for the current thread state is further down.
      47                 :            : 
      48                 :            : /* "current" means one of:
      49                 :            :    - bound to the current OS thread
      50                 :            :    - holds the GIL
      51                 :            :  */
      52                 :            : 
      53                 :            : //-------------------------------------------------
      54                 :            : // a highly efficient lookup for the current thread
      55                 :            : //-------------------------------------------------
      56                 :            : 
      57                 :            : /*
      58                 :            :    The stored thread state is set by PyThreadState_Swap().
      59                 :            : 
      60                 :            :    For each of these functions, the GIL must be held by the current thread.
      61                 :            :  */
      62                 :            : 
      63                 :            : static inline PyThreadState *
      64                 :    7479704 : current_fast_get(_PyRuntimeState *runtime)
      65                 :            : {
      66                 :    7479704 :     return (PyThreadState*)_Py_atomic_load_relaxed(&runtime->tstate_current);
      67                 :            : }
      68                 :            : 
      69                 :            : static inline void
      70                 :      30180 : current_fast_set(_PyRuntimeState *runtime, PyThreadState *tstate)
      71                 :            : {
      72                 :            :     assert(tstate != NULL);
      73                 :      30180 :     _Py_atomic_store_relaxed(&runtime->tstate_current, (uintptr_t)tstate);
      74                 :      30180 : }
      75                 :            : 
      76                 :            : static inline void
      77                 :      60356 : current_fast_clear(_PyRuntimeState *runtime)
      78                 :            : {
      79                 :      60356 :     _Py_atomic_store_relaxed(&runtime->tstate_current, (uintptr_t)NULL);
      80                 :      60356 : }
      81                 :            : 
      82                 :            : #define tstate_verify_not_active(tstate) \
      83                 :            :     if (tstate == current_fast_get((tstate)->interp->runtime)) { \
      84                 :            :         _Py_FatalErrorFormat(__func__, "tstate %p is still current", tstate); \
      85                 :            :     }
      86                 :            : 
      87                 :            : 
      88                 :            : //------------------------------------------------
      89                 :            : // the thread state bound to the current OS thread
      90                 :            : //------------------------------------------------
      91                 :            : 
      92                 :            : static inline int
      93                 :         50 : tstate_tss_initialized(Py_tss_t *key)
      94                 :            : {
      95                 :         50 :     return PyThread_tss_is_created(key);
      96                 :            : }
      97                 :            : 
      98                 :            : static inline int
      99                 :         29 : tstate_tss_init(Py_tss_t *key)
     100                 :            : {
     101                 :            :     assert(!tstate_tss_initialized(key));
     102                 :         29 :     return PyThread_tss_create(key);
     103                 :            : }
     104                 :            : 
     105                 :            : static inline void
     106                 :         25 : tstate_tss_fini(Py_tss_t *key)
     107                 :            : {
     108                 :            :     assert(tstate_tss_initialized(key));
     109                 :         25 :     PyThread_tss_delete(key);
     110                 :         25 : }
     111                 :            : 
     112                 :            : static inline PyThreadState *
     113                 :         58 : tstate_tss_get(Py_tss_t *key)
     114                 :            : {
     115                 :            :     assert(tstate_tss_initialized(key));
     116                 :         58 :     return (PyThreadState *)PyThread_tss_get(key);
     117                 :            : }
     118                 :            : 
     119                 :            : static inline int
     120                 :         29 : tstate_tss_set(Py_tss_t *key, PyThreadState *tstate)
     121                 :            : {
     122                 :            :     assert(tstate != NULL);
     123                 :            :     assert(tstate_tss_initialized(key));
     124                 :         29 :     return PyThread_tss_set(key, (void *)tstate);
     125                 :            : }
     126                 :            : 
     127                 :            : static inline int
     128                 :         25 : tstate_tss_clear(Py_tss_t *key)
     129                 :            : {
     130                 :            :     assert(tstate_tss_initialized(key));
     131                 :         25 :     return PyThread_tss_set(key, (void *)NULL);
     132                 :            : }
     133                 :            : 
     134                 :            : #ifdef HAVE_FORK
     135                 :            : /* Reset the TSS key - called by PyOS_AfterFork_Child().
     136                 :            :  * This should not be necessary, but some - buggy - pthread implementations
     137                 :            :  * don't reset TSS upon fork(), see issue #10517.
     138                 :            :  */
     139                 :            : static PyStatus
     140                 :          0 : tstate_tss_reinit(Py_tss_t *key)
     141                 :            : {
     142         [ #  # ]:          0 :     if (!tstate_tss_initialized(key)) {
     143                 :          0 :         return _PyStatus_OK();
     144                 :            :     }
     145                 :          0 :     PyThreadState *tstate = tstate_tss_get(key);
     146                 :            : 
     147                 :          0 :     tstate_tss_fini(key);
     148         [ #  # ]:          0 :     if (tstate_tss_init(key) != 0) {
     149                 :          0 :         return _PyStatus_NO_MEMORY();
     150                 :            :     }
     151                 :            : 
     152                 :            :     /* If the thread had an associated auto thread state, reassociate it with
     153                 :            :      * the new key. */
     154   [ #  #  #  # ]:          0 :     if (tstate && tstate_tss_set(key, tstate) != 0) {
     155                 :          0 :         return _PyStatus_ERR("failed to re-set autoTSSkey");
     156                 :            :     }
     157                 :          0 :     return _PyStatus_OK();
     158                 :            : }
     159                 :            : #endif
     160                 :            : 
     161                 :            : 
     162                 :            : /*
     163                 :            :    The stored thread state is set by bind_tstate() (AKA PyThreadState_Bind().
     164                 :            : 
     165                 :            :    The GIL does no need to be held for these.
     166                 :            :   */
     167                 :            : 
     168                 :            : #define gilstate_tss_initialized(runtime) \
     169                 :            :     tstate_tss_initialized(&(runtime)->autoTSSkey)
     170                 :            : #define gilstate_tss_init(runtime) \
     171                 :            :     tstate_tss_init(&(runtime)->autoTSSkey)
     172                 :            : #define gilstate_tss_fini(runtime) \
     173                 :            :     tstate_tss_fini(&(runtime)->autoTSSkey)
     174                 :            : #define gilstate_tss_get(runtime) \
     175                 :            :     tstate_tss_get(&(runtime)->autoTSSkey)
     176                 :            : #define _gilstate_tss_set(runtime, tstate) \
     177                 :            :     tstate_tss_set(&(runtime)->autoTSSkey, tstate)
     178                 :            : #define _gilstate_tss_clear(runtime) \
     179                 :            :     tstate_tss_clear(&(runtime)->autoTSSkey)
     180                 :            : #define gilstate_tss_reinit(runtime) \
     181                 :            :     tstate_tss_reinit(&(runtime)->autoTSSkey)
     182                 :            : 
     183                 :            : static inline void
     184                 :         29 : gilstate_tss_set(_PyRuntimeState *runtime, PyThreadState *tstate)
     185                 :            : {
     186                 :            :     assert(tstate != NULL && tstate->interp->runtime == runtime);
     187         [ -  + ]:         29 :     if (_gilstate_tss_set(runtime, tstate) != 0) {
     188                 :          0 :         Py_FatalError("failed to set current tstate (TSS)");
     189                 :            :     }
     190                 :         29 : }
     191                 :            : 
     192                 :            : static inline void
     193                 :         25 : gilstate_tss_clear(_PyRuntimeState *runtime)
     194                 :            : {
     195         [ -  + ]:         25 :     if (_gilstate_tss_clear(runtime) != 0) {
     196                 :          0 :         Py_FatalError("failed to clear current tstate (TSS)");
     197                 :            :     }
     198                 :         25 : }
     199                 :            : 
     200                 :            : 
     201                 :            : #ifndef NDEBUG
     202                 :            : static inline int tstate_is_alive(PyThreadState *tstate);
     203                 :            : 
     204                 :            : static inline int
     205                 :            : tstate_is_bound(PyThreadState *tstate)
     206                 :            : {
     207                 :            :     return tstate->_status.bound && !tstate->_status.unbound;
     208                 :            : }
     209                 :            : #endif  // !NDEBUG
     210                 :            : 
     211                 :            : static void bind_gilstate_tstate(PyThreadState *);
     212                 :            : static void unbind_gilstate_tstate(PyThreadState *);
     213                 :            : 
     214                 :            : static void
     215                 :         29 : bind_tstate(PyThreadState *tstate)
     216                 :            : {
     217                 :            :     assert(tstate != NULL);
     218                 :            :     assert(tstate_is_alive(tstate) && !tstate->_status.bound);
     219                 :            :     assert(!tstate->_status.unbound);  // just in case
     220                 :            :     assert(!tstate->_status.bound_gilstate);
     221                 :            :     assert(tstate != gilstate_tss_get(tstate->interp->runtime));
     222                 :            :     assert(!tstate->_status.active);
     223                 :            :     assert(tstate->thread_id == 0);
     224                 :            :     assert(tstate->native_thread_id == 0);
     225                 :            : 
     226                 :            :     // Currently we don't necessarily store the thread state
     227                 :            :     // in thread-local storage (e.g. per-interpreter).
     228                 :            : 
     229                 :         29 :     tstate->thread_id = PyThread_get_thread_ident();
     230                 :            : #ifdef PY_HAVE_THREAD_NATIVE_ID
     231                 :         29 :     tstate->native_thread_id = PyThread_get_thread_native_id();
     232                 :            : #endif
     233                 :            : 
     234                 :         29 :     tstate->_status.bound = 1;
     235                 :         29 : }
     236                 :            : 
     237                 :            : static void
     238                 :         25 : unbind_tstate(PyThreadState *tstate)
     239                 :            : {
     240                 :            :     assert(tstate != NULL);
     241                 :            :     // XXX assert(tstate_is_alive(tstate));
     242                 :            :     assert(tstate_is_bound(tstate));
     243                 :            :     // XXX assert(!tstate->_status.active);
     244                 :            :     assert(tstate->thread_id > 0);
     245                 :            : #ifdef PY_HAVE_THREAD_NATIVE_ID
     246                 :            :     assert(tstate->native_thread_id > 0);
     247                 :            : #endif
     248                 :            : 
     249                 :            :     // We leave thread_id and native_thread_id alone
     250                 :            :     // since they can be useful for debugging.
     251                 :            :     // Check the `_status` field to know if these values
     252                 :            :     // are still valid.
     253                 :            : 
     254                 :            :     // We leave tstate->_status.bound set to 1
     255                 :            :     // to indicate it was previously bound.
     256                 :         25 :     tstate->_status.unbound = 1;
     257                 :         25 : }
     258                 :            : 
     259                 :            : 
     260                 :            : /* Stick the thread state for this thread in thread specific storage.
     261                 :            : 
     262                 :            :    When a thread state is created for a thread by some mechanism
     263                 :            :    other than PyGILState_Ensure(), it's important that the GILState
     264                 :            :    machinery knows about it so it doesn't try to create another
     265                 :            :    thread state for the thread.
     266                 :            :    (This is a better fix for SF bug #1010677 than the first one attempted.)
     267                 :            : 
     268                 :            :    The only situation where you can legitimately have more than one
     269                 :            :    thread state for an OS level thread is when there are multiple
     270                 :            :    interpreters.
     271                 :            : 
     272                 :            :    Before 3.12, the PyGILState_*() APIs didn't work with multiple
     273                 :            :    interpreters (see bpo-10915 and bpo-15751), so this function used
     274                 :            :    to set TSS only once.  Thus, the first thread state created for that
     275                 :            :    given OS level thread would "win", which seemed reasonable behaviour.
     276                 :            : */
     277                 :            : 
     278                 :            : static void
     279                 :         29 : bind_gilstate_tstate(PyThreadState *tstate)
     280                 :            : {
     281                 :            :     assert(tstate != NULL);
     282                 :            :     assert(tstate_is_alive(tstate));
     283                 :            :     assert(tstate_is_bound(tstate));
     284                 :            :     // XXX assert(!tstate->_status.active);
     285                 :            :     assert(!tstate->_status.bound_gilstate);
     286                 :            : 
     287                 :         29 :     _PyRuntimeState *runtime = tstate->interp->runtime;
     288                 :         29 :     PyThreadState *tcur = gilstate_tss_get(runtime);
     289                 :            :     assert(tstate != tcur);
     290                 :            : 
     291         [ -  + ]:         29 :     if (tcur != NULL) {
     292                 :          0 :         tcur->_status.bound_gilstate = 0;
     293                 :            :     }
     294                 :         29 :     gilstate_tss_set(runtime, tstate);
     295                 :         29 :     tstate->_status.bound_gilstate = 1;
     296                 :         29 : }
     297                 :            : 
     298                 :            : static void
     299                 :         25 : unbind_gilstate_tstate(PyThreadState *tstate)
     300                 :            : {
     301                 :            :     assert(tstate != NULL);
     302                 :            :     // XXX assert(tstate_is_alive(tstate));
     303                 :            :     assert(tstate_is_bound(tstate));
     304                 :            :     // XXX assert(!tstate->_status.active);
     305                 :            :     assert(tstate->_status.bound_gilstate);
     306                 :            :     assert(tstate == gilstate_tss_get(tstate->interp->runtime));
     307                 :            : 
     308                 :         25 :     gilstate_tss_clear(tstate->interp->runtime);
     309                 :         25 :     tstate->_status.bound_gilstate = 0;
     310                 :         25 : }
     311                 :            : 
     312                 :            : 
     313                 :            : //----------------------------------------------
     314                 :            : // the thread state that currently holds the GIL
     315                 :            : //----------------------------------------------
     316                 :            : 
     317                 :            : /* This is not exported, as it is not reliable!  It can only
     318                 :            :    ever be compared to the state for the *current* thread.
     319                 :            :    * If not equal, then it doesn't matter that the actual
     320                 :            :      value may change immediately after comparison, as it can't
     321                 :            :      possibly change to the current thread's state.
     322                 :            :    * If equal, then the current thread holds the lock, so the value can't
     323                 :            :      change until we yield the lock.
     324                 :            : */
     325                 :            : static int
     326                 :          0 : holds_gil(PyThreadState *tstate)
     327                 :            : {
     328                 :            :     // XXX Fall back to tstate->interp->runtime->ceval.gil.last_holder
     329                 :            :     // (and tstate->interp->runtime->ceval.gil.locked).
     330                 :            :     assert(tstate != NULL);
     331                 :          0 :     _PyRuntimeState *runtime = tstate->interp->runtime;
     332                 :            :     /* Must be the tstate for this thread */
     333                 :            :     assert(tstate == gilstate_tss_get(runtime));
     334                 :          0 :     return tstate == current_fast_get(runtime);
     335                 :            : }
     336                 :            : 
     337                 :            : 
     338                 :            : /****************************/
     339                 :            : /* the global runtime state */
     340                 :            : /****************************/
     341                 :            : 
     342                 :            : //----------
     343                 :            : // lifecycle
     344                 :            : //----------
     345                 :            : 
     346                 :            : /* Suppress deprecation warning for PyBytesObject.ob_shash */
     347                 :            : _Py_COMP_DIAG_PUSH
     348                 :            : _Py_COMP_DIAG_IGNORE_DEPR_DECLS
     349                 :            : /* We use "initial" if the runtime gets re-used
     350                 :            :    (e.g. Py_Finalize() followed by Py_Initialize().
     351                 :            :    Note that we initialize "initial" relative to _PyRuntime,
     352                 :            :    to ensure pre-initialized pointers point to the active
     353                 :            :    runtime state (and not "initial"). */
     354                 :            : static const _PyRuntimeState initial = _PyRuntimeState_INIT(_PyRuntime);
     355                 :            : _Py_COMP_DIAG_POP
     356                 :            : 
     357                 :            : static int
     358                 :         29 : alloc_for_runtime(PyThread_type_lock *plock1, PyThread_type_lock *plock2,
     359                 :            :                   PyThread_type_lock *plock3, PyThread_type_lock *plock4)
     360                 :            : {
     361                 :            :     /* Force default allocator, since _PyRuntimeState_Fini() must
     362                 :            :        use the same allocator than this function. */
     363                 :            :     PyMemAllocatorEx old_alloc;
     364                 :         29 :     _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
     365                 :            : 
     366                 :         29 :     PyThread_type_lock lock1 = PyThread_allocate_lock();
     367         [ -  + ]:         29 :     if (lock1 == NULL) {
     368                 :          0 :         return -1;
     369                 :            :     }
     370                 :            : 
     371                 :         29 :     PyThread_type_lock lock2 = PyThread_allocate_lock();
     372         [ -  + ]:         29 :     if (lock2 == NULL) {
     373                 :          0 :         PyThread_free_lock(lock1);
     374                 :          0 :         return -1;
     375                 :            :     }
     376                 :            : 
     377                 :         29 :     PyThread_type_lock lock3 = PyThread_allocate_lock();
     378         [ -  + ]:         29 :     if (lock3 == NULL) {
     379                 :          0 :         PyThread_free_lock(lock1);
     380                 :          0 :         PyThread_free_lock(lock2);
     381                 :          0 :         return -1;
     382                 :            :     }
     383                 :            : 
     384                 :         29 :     PyThread_type_lock lock4 = PyThread_allocate_lock();
     385         [ -  + ]:         29 :     if (lock4 == NULL) {
     386                 :          0 :         PyThread_free_lock(lock1);
     387                 :          0 :         PyThread_free_lock(lock2);
     388                 :          0 :         PyThread_free_lock(lock3);
     389                 :          0 :         return -1;
     390                 :            :     }
     391                 :            : 
     392                 :         29 :     PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
     393                 :            : 
     394                 :         29 :     *plock1 = lock1;
     395                 :         29 :     *plock2 = lock2;
     396                 :         29 :     *plock3 = lock3;
     397                 :         29 :     *plock4 = lock4;
     398                 :         29 :     return 0;
     399                 :            : }
     400                 :            : 
     401                 :            : static void
     402                 :         29 : init_runtime(_PyRuntimeState *runtime,
     403                 :            :              void *open_code_hook, void *open_code_userdata,
     404                 :            :              _Py_AuditHookEntry *audit_hook_head,
     405                 :            :              Py_ssize_t unicode_next_index,
     406                 :            :              PyThread_type_lock unicode_ids_mutex,
     407                 :            :              PyThread_type_lock interpreters_mutex,
     408                 :            :              PyThread_type_lock xidregistry_mutex,
     409                 :            :              PyThread_type_lock getargs_mutex)
     410                 :            : {
     411         [ -  + ]:         29 :     if (runtime->_initialized) {
     412                 :          0 :         Py_FatalError("runtime already initialized");
     413                 :            :     }
     414                 :            :     assert(!runtime->preinitializing &&
     415                 :            :            !runtime->preinitialized &&
     416                 :            :            !runtime->core_initialized &&
     417                 :            :            !runtime->initialized);
     418                 :            : 
     419                 :         29 :     runtime->open_code_hook = open_code_hook;
     420                 :         29 :     runtime->open_code_userdata = open_code_userdata;
     421                 :         29 :     runtime->audit_hook_head = audit_hook_head;
     422                 :            : 
     423                 :         29 :     _PyEval_InitRuntimeState(&runtime->ceval);
     424                 :            : 
     425                 :         29 :     PyPreConfig_InitPythonConfig(&runtime->preconfig);
     426                 :            : 
     427                 :         29 :     runtime->interpreters.mutex = interpreters_mutex;
     428                 :            : 
     429                 :         29 :     runtime->xidregistry.mutex = xidregistry_mutex;
     430                 :            : 
     431                 :         29 :     runtime->getargs.mutex = getargs_mutex;
     432                 :            : 
     433                 :            :     // Set it to the ID of the main thread of the main interpreter.
     434                 :         29 :     runtime->main_thread = PyThread_get_thread_ident();
     435                 :            : 
     436                 :         29 :     runtime->unicode_state.ids.next_index = unicode_next_index;
     437                 :         29 :     runtime->unicode_state.ids.lock = unicode_ids_mutex;
     438                 :            : 
     439                 :         29 :     runtime->_initialized = 1;
     440                 :         29 : }
     441                 :            : 
     442                 :            : PyStatus
     443                 :         29 : _PyRuntimeState_Init(_PyRuntimeState *runtime)
     444                 :            : {
     445                 :            :     /* We preserve the hook across init, because there is
     446                 :            :        currently no public API to set it between runtime
     447                 :            :        initialization and interpreter initialization. */
     448                 :         29 :     void *open_code_hook = runtime->open_code_hook;
     449                 :         29 :     void *open_code_userdata = runtime->open_code_userdata;
     450                 :         29 :     _Py_AuditHookEntry *audit_hook_head = runtime->audit_hook_head;
     451                 :            :     // bpo-42882: Preserve next_index value if Py_Initialize()/Py_Finalize()
     452                 :            :     // is called multiple times.
     453                 :         29 :     Py_ssize_t unicode_next_index = runtime->unicode_state.ids.next_index;
     454                 :            : 
     455                 :            :     PyThread_type_lock lock1, lock2, lock3, lock4;
     456         [ -  + ]:         29 :     if (alloc_for_runtime(&lock1, &lock2, &lock3, &lock4) != 0) {
     457                 :          0 :         return _PyStatus_NO_MEMORY();
     458                 :            :     }
     459                 :            : 
     460         [ -  + ]:         29 :     if (runtime->_initialized) {
     461                 :            :         // Py_Initialize() must be running again.
     462                 :            :         // Reset to _PyRuntimeState_INIT.
     463                 :          0 :         memcpy(runtime, &initial, sizeof(*runtime));
     464                 :            :     }
     465                 :            : 
     466         [ -  + ]:         29 :     if (gilstate_tss_init(runtime) != 0) {
     467                 :          0 :         _PyRuntimeState_Fini(runtime);
     468                 :          0 :         return _PyStatus_NO_MEMORY();
     469                 :            :     }
     470                 :            : 
     471         [ -  + ]:         29 :     if (PyThread_tss_create(&runtime->trashTSSkey) != 0) {
     472                 :          0 :         _PyRuntimeState_Fini(runtime);
     473                 :          0 :         return _PyStatus_NO_MEMORY();
     474                 :            :     }
     475                 :            : 
     476                 :         29 :     init_runtime(runtime, open_code_hook, open_code_userdata, audit_hook_head,
     477                 :            :                  unicode_next_index, lock1, lock2, lock3, lock4);
     478                 :            : 
     479                 :         29 :     return _PyStatus_OK();
     480                 :            : }
     481                 :            : 
     482                 :            : void
     483                 :         50 : _PyRuntimeState_Fini(_PyRuntimeState *runtime)
     484                 :            : {
     485         [ +  + ]:         50 :     if (gilstate_tss_initialized(runtime)) {
     486                 :         25 :         gilstate_tss_fini(runtime);
     487                 :            :     }
     488                 :            : 
     489         [ +  + ]:         50 :     if (PyThread_tss_is_created(&runtime->trashTSSkey)) {
     490                 :         25 :         PyThread_tss_delete(&runtime->trashTSSkey);
     491                 :            :     }
     492                 :            : 
     493                 :            :     /* Force the allocator used by _PyRuntimeState_Init(). */
     494                 :            :     PyMemAllocatorEx old_alloc;
     495                 :         50 :     _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
     496                 :            : #define FREE_LOCK(LOCK) \
     497                 :            :     if (LOCK != NULL) { \
     498                 :            :         PyThread_free_lock(LOCK); \
     499                 :            :         LOCK = NULL; \
     500                 :            :     }
     501                 :            : 
     502         [ +  + ]:         50 :     FREE_LOCK(runtime->interpreters.mutex);
     503         [ +  + ]:         50 :     FREE_LOCK(runtime->xidregistry.mutex);
     504         [ +  + ]:         50 :     FREE_LOCK(runtime->unicode_state.ids.lock);
     505         [ +  + ]:         50 :     FREE_LOCK(runtime->getargs.mutex);
     506                 :            : 
     507                 :            : #undef FREE_LOCK
     508                 :         50 :     PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
     509                 :         50 : }
     510                 :            : 
     511                 :            : #ifdef HAVE_FORK
     512                 :            : /* This function is called from PyOS_AfterFork_Child to ensure that
     513                 :            :    newly created child processes do not share locks with the parent. */
     514                 :            : PyStatus
     515                 :          0 : _PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime)
     516                 :            : {
     517                 :            :     // This was initially set in _PyRuntimeState_Init().
     518                 :          0 :     runtime->main_thread = PyThread_get_thread_ident();
     519                 :            : 
     520                 :            :     /* Force default allocator, since _PyRuntimeState_Fini() must
     521                 :            :        use the same allocator than this function. */
     522                 :            :     PyMemAllocatorEx old_alloc;
     523                 :          0 :     _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
     524                 :            : 
     525                 :          0 :     int reinit_interp = _PyThread_at_fork_reinit(&runtime->interpreters.mutex);
     526                 :          0 :     int reinit_xidregistry = _PyThread_at_fork_reinit(&runtime->xidregistry.mutex);
     527                 :          0 :     int reinit_unicode_ids = _PyThread_at_fork_reinit(&runtime->unicode_state.ids.lock);
     528                 :          0 :     int reinit_getargs = _PyThread_at_fork_reinit(&runtime->getargs.mutex);
     529                 :            : 
     530                 :          0 :     PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
     531                 :            : 
     532                 :            :     /* bpo-42540: id_mutex is freed by _PyInterpreterState_Delete, which does
     533                 :            :      * not force the default allocator. */
     534                 :          0 :     int reinit_main_id = _PyThread_at_fork_reinit(&runtime->interpreters.main->id_mutex);
     535                 :            : 
     536         [ #  # ]:          0 :     if (reinit_interp < 0
     537         [ #  # ]:          0 :         || reinit_main_id < 0
     538         [ #  # ]:          0 :         || reinit_xidregistry < 0
     539         [ #  # ]:          0 :         || reinit_unicode_ids < 0
     540         [ #  # ]:          0 :         || reinit_getargs < 0)
     541                 :            :     {
     542                 :          0 :         return _PyStatus_ERR("Failed to reinitialize runtime locks");
     543                 :            : 
     544                 :            :     }
     545                 :            : 
     546                 :          0 :     PyStatus status = gilstate_tss_reinit(runtime);
     547         [ #  # ]:          0 :     if (_PyStatus_EXCEPTION(status)) {
     548                 :          0 :         return status;
     549                 :            :     }
     550                 :            : 
     551         [ #  # ]:          0 :     if (PyThread_tss_is_created(&runtime->trashTSSkey)) {
     552                 :          0 :         PyThread_tss_delete(&runtime->trashTSSkey);
     553                 :            :     }
     554         [ #  # ]:          0 :     if (PyThread_tss_create(&runtime->trashTSSkey) != 0) {
     555                 :          0 :         return _PyStatus_NO_MEMORY();
     556                 :            :     }
     557                 :            : 
     558                 :          0 :     return _PyStatus_OK();
     559                 :            : }
     560                 :            : #endif
     561                 :            : 
     562                 :            : 
     563                 :            : /*************************************/
     564                 :            : /* the per-interpreter runtime state */
     565                 :            : /*************************************/
     566                 :            : 
     567                 :            : //----------
     568                 :            : // lifecycle
     569                 :            : //----------
     570                 :            : 
     571                 :            : /* Calling this indicates that the runtime is ready to create interpreters. */
     572                 :            : 
     573                 :            : PyStatus
     574                 :         29 : _PyInterpreterState_Enable(_PyRuntimeState *runtime)
     575                 :            : {
     576                 :         29 :     struct pyinterpreters *interpreters = &runtime->interpreters;
     577                 :         29 :     interpreters->next_id = 0;
     578                 :            : 
     579                 :            :     /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
     580                 :            :        Create a new mutex if needed. */
     581         [ -  + ]:         29 :     if (interpreters->mutex == NULL) {
     582                 :            :         /* Force default allocator, since _PyRuntimeState_Fini() must
     583                 :            :            use the same allocator than this function. */
     584                 :            :         PyMemAllocatorEx old_alloc;
     585                 :          0 :         _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
     586                 :            : 
     587                 :          0 :         interpreters->mutex = PyThread_allocate_lock();
     588                 :            : 
     589                 :          0 :         PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
     590                 :            : 
     591         [ #  # ]:          0 :         if (interpreters->mutex == NULL) {
     592                 :          0 :             return _PyStatus_ERR("Can't initialize threads for interpreter");
     593                 :            :         }
     594                 :            :     }
     595                 :            : 
     596                 :         29 :     return _PyStatus_OK();
     597                 :            : }
     598                 :            : 
     599                 :            : 
     600                 :            : static PyInterpreterState *
     601                 :          0 : alloc_interpreter(void)
     602                 :            : {
     603                 :          0 :     return PyMem_RawCalloc(1, sizeof(PyInterpreterState));
     604                 :            : }
     605                 :            : 
     606                 :            : static void
     607                 :         25 : free_interpreter(PyInterpreterState *interp)
     608                 :            : {
     609                 :            :     // The main interpreter is statically allocated so
     610                 :            :     // should not be freed.
     611         [ -  + ]:         25 :     if (interp != &_PyRuntime._main_interpreter) {
     612                 :          0 :         PyMem_RawFree(interp);
     613                 :            :     }
     614                 :         25 : }
     615                 :            : 
     616                 :            : /* Get the interpreter state to a minimal consistent state.
     617                 :            :    Further init happens in pylifecycle.c before it can be used.
     618                 :            :    All fields not initialized here are expected to be zeroed out,
     619                 :            :    e.g. by PyMem_RawCalloc() or memset(), or otherwise pre-initialized.
     620                 :            :    The runtime state is not manipulated.  Instead it is assumed that
     621                 :            :    the interpreter is getting added to the runtime.
     622                 :            : 
     623                 :            :    Note that the main interpreter was statically initialized as part
     624                 :            :    of the runtime and most state is already set properly.  That leaves
     625                 :            :    a small number of fields to initialize dynamically, as well as some
     626                 :            :    that are initialized lazily.
     627                 :            : 
     628                 :            :    For subinterpreters we memcpy() the main interpreter in
     629                 :            :    PyInterpreterState_New(), leaving it in the same mostly-initialized
     630                 :            :    state.  The only difference is that the interpreter has some
     631                 :            :    self-referential state that is statically initializexd to the
     632                 :            :    main interpreter.  We fix those fields here, in addition
     633                 :            :    to the other dynamically initialized fields.
     634                 :            :   */
     635                 :            : 
     636                 :            : static void
     637                 :         29 : init_interpreter(PyInterpreterState *interp,
     638                 :            :                  _PyRuntimeState *runtime, int64_t id,
     639                 :            :                  PyInterpreterState *next,
     640                 :            :                  PyThread_type_lock pending_lock)
     641                 :            : {
     642         [ -  + ]:         29 :     if (interp->_initialized) {
     643                 :          0 :         Py_FatalError("interpreter already initialized");
     644                 :            :     }
     645                 :            : 
     646                 :            :     assert(runtime != NULL);
     647                 :         29 :     interp->runtime = runtime;
     648                 :            : 
     649                 :            :     assert(id > 0 || (id == 0 && interp == runtime->interpreters.main));
     650                 :         29 :     interp->id = id;
     651                 :            : 
     652                 :            :     assert(runtime->interpreters.head == interp);
     653                 :            :     assert(next != NULL || (interp == runtime->interpreters.main));
     654                 :         29 :     interp->next = next;
     655                 :            : 
     656                 :         29 :     _PyEval_InitState(&interp->ceval, pending_lock);
     657                 :         29 :     _PyGC_InitState(&interp->gc);
     658                 :         29 :     PyConfig_InitPythonConfig(&interp->config);
     659                 :         29 :     _PyType_InitCache(interp);
     660                 :            : 
     661         [ -  + ]:         29 :     if (interp != &runtime->_main_interpreter) {
     662                 :            :         /* Fix the self-referential, statically initialized fields. */
     663                 :          0 :         interp->dtoa = (struct _dtoa_state)_dtoa_state_INIT(interp);
     664                 :            :     }
     665                 :            : 
     666                 :         29 :     interp->_initialized = 1;
     667                 :         29 : }
     668                 :            : 
     669                 :            : PyInterpreterState *
     670                 :         29 : PyInterpreterState_New(void)
     671                 :            : {
     672                 :            :     PyInterpreterState *interp;
     673                 :         29 :     _PyRuntimeState *runtime = &_PyRuntime;
     674                 :         29 :     PyThreadState *tstate = current_fast_get(runtime);
     675                 :            : 
     676                 :            :     /* tstate is NULL when Py_InitializeFromConfig() calls
     677                 :            :        PyInterpreterState_New() to create the main interpreter. */
     678         [ -  + ]:         29 :     if (_PySys_Audit(tstate, "cpython.PyInterpreterState_New", NULL) < 0) {
     679                 :          0 :         return NULL;
     680                 :            :     }
     681                 :            : 
     682                 :         29 :     PyThread_type_lock pending_lock = PyThread_allocate_lock();
     683         [ -  + ]:         29 :     if (pending_lock == NULL) {
     684         [ #  # ]:          0 :         if (tstate != NULL) {
     685                 :          0 :             _PyErr_NoMemory(tstate);
     686                 :            :         }
     687                 :          0 :         return NULL;
     688                 :            :     }
     689                 :            : 
     690                 :            :     /* Don't get runtime from tstate since tstate can be NULL. */
     691                 :         29 :     struct pyinterpreters *interpreters = &runtime->interpreters;
     692                 :            : 
     693                 :            :     /* We completely serialize creation of multiple interpreters, since
     694                 :            :        it simplifies things here and blocking concurrent calls isn't a problem.
     695                 :            :        Regardless, we must fully block subinterpreter creation until
     696                 :            :        after the main interpreter is created. */
     697                 :         29 :     HEAD_LOCK(runtime);
     698                 :            : 
     699                 :         29 :     int64_t id = interpreters->next_id;
     700                 :         29 :     interpreters->next_id += 1;
     701                 :            : 
     702                 :            :     // Allocate the interpreter and add it to the runtime state.
     703                 :         29 :     PyInterpreterState *old_head = interpreters->head;
     704         [ +  - ]:         29 :     if (old_head == NULL) {
     705                 :            :         // We are creating the main interpreter.
     706                 :            :         assert(interpreters->main == NULL);
     707                 :            :         assert(id == 0);
     708                 :            : 
     709                 :         29 :         interp = &runtime->_main_interpreter;
     710                 :            :         assert(interp->id == 0);
     711                 :            :         assert(interp->next == NULL);
     712                 :            : 
     713                 :         29 :         interpreters->main = interp;
     714                 :            :     }
     715                 :            :     else {
     716                 :            :         assert(interpreters->main != NULL);
     717                 :            :         assert(id != 0);
     718                 :            : 
     719                 :          0 :         interp = alloc_interpreter();
     720         [ #  # ]:          0 :         if (interp == NULL) {
     721                 :          0 :             goto error;
     722                 :            :         }
     723                 :            :         // Set to _PyInterpreterState_INIT.
     724                 :          0 :         memcpy(interp, &initial._main_interpreter,
     725                 :            :                sizeof(*interp));
     726                 :            : 
     727         [ #  # ]:          0 :         if (id < 0) {
     728                 :            :             /* overflow or Py_Initialize() not called yet! */
     729         [ #  # ]:          0 :             if (tstate != NULL) {
     730                 :          0 :                 _PyErr_SetString(tstate, PyExc_RuntimeError,
     731                 :            :                                  "failed to get an interpreter ID");
     732                 :            :             }
     733                 :          0 :             goto error;
     734                 :            :         }
     735                 :            :     }
     736                 :         29 :     interpreters->head = interp;
     737                 :            : 
     738                 :         29 :     init_interpreter(interp, runtime, id, old_head, pending_lock);
     739                 :            : 
     740                 :         29 :     HEAD_UNLOCK(runtime);
     741                 :         29 :     return interp;
     742                 :            : 
     743                 :          0 : error:
     744                 :          0 :     HEAD_UNLOCK(runtime);
     745                 :            : 
     746                 :          0 :     PyThread_free_lock(pending_lock);
     747         [ #  # ]:          0 :     if (interp != NULL) {
     748                 :          0 :         free_interpreter(interp);
     749                 :            :     }
     750                 :          0 :     return NULL;
     751                 :            : }
     752                 :            : 
     753                 :            : 
     754                 :            : static void
     755                 :         25 : interpreter_clear(PyInterpreterState *interp, PyThreadState *tstate)
     756                 :            : {
     757                 :            :     assert(interp != NULL);
     758                 :            :     assert(tstate != NULL);
     759                 :         25 :     _PyRuntimeState *runtime = interp->runtime;
     760                 :            : 
     761                 :            :     /* XXX Conditions we need to enforce:
     762                 :            : 
     763                 :            :        * the GIL must be held by the current thread
     764                 :            :        * tstate must be the "current" thread state (current_fast_get())
     765                 :            :        * tstate->interp must be interp
     766                 :            :        * for the main interpreter, tstate must be the main thread
     767                 :            :      */
     768                 :            :     // XXX Ideally, we would not rely on any thread state in this function
     769                 :            :     // (and we would drop the "tstate" argument).
     770                 :            : 
     771         [ -  + ]:         25 :     if (_PySys_Audit(tstate, "cpython.PyInterpreterState_Clear", NULL) < 0) {
     772                 :          0 :         _PyErr_Clear(tstate);
     773                 :            :     }
     774                 :            : 
     775                 :            :     // Clear the current/main thread state last.
     776                 :         25 :     HEAD_LOCK(runtime);
     777                 :         25 :     PyThreadState *p = interp->threads.head;
     778                 :         25 :     HEAD_UNLOCK(runtime);
     779         [ +  + ]:         50 :     while (p != NULL) {
     780                 :            :         // See https://github.com/python/cpython/issues/102126
     781                 :            :         // Must be called without HEAD_LOCK held as it can deadlock
     782                 :            :         // if any finalizer tries to acquire that lock.
     783                 :         25 :         PyThreadState_Clear(p);
     784                 :         25 :         HEAD_LOCK(runtime);
     785                 :         25 :         p = p->next;
     786                 :         25 :         HEAD_UNLOCK(runtime);
     787                 :            :     }
     788                 :            : 
     789                 :            :     /* It is possible that any of the objects below have a finalizer
     790                 :            :        that runs Python code or otherwise relies on a thread state
     791                 :            :        or even the interpreter state.  For now we trust that isn't
     792                 :            :        a problem.
     793                 :            :      */
     794                 :            :     // XXX Make sure we properly deal with problematic finalizers.
     795                 :            : 
     796         [ +  + ]:         25 :     Py_CLEAR(interp->audit_hooks);
     797                 :            : 
     798                 :         25 :     PyConfig_Clear(&interp->config);
     799         [ +  - ]:         25 :     Py_CLEAR(interp->codec_search_path);
     800         [ +  - ]:         25 :     Py_CLEAR(interp->codec_search_cache);
     801         [ +  - ]:         25 :     Py_CLEAR(interp->codec_error_registry);
     802                 :            : 
     803                 :            :     assert(interp->imports.modules == NULL);
     804                 :            :     assert(interp->imports.modules_by_index == NULL);
     805                 :            :     assert(interp->imports.importlib == NULL);
     806                 :            :     assert(interp->imports.import_func == NULL);
     807                 :            : 
     808         [ +  - ]:         25 :     Py_CLEAR(interp->sysdict_copy);
     809         [ +  - ]:         25 :     Py_CLEAR(interp->builtins_copy);
     810         [ -  + ]:         25 :     Py_CLEAR(interp->dict);
     811                 :            : #ifdef HAVE_FORK
     812         [ +  + ]:         25 :     Py_CLEAR(interp->before_forkers);
     813         [ +  + ]:         25 :     Py_CLEAR(interp->after_forkers_parent);
     814         [ +  + ]:         25 :     Py_CLEAR(interp->after_forkers_child);
     815                 :            : #endif
     816                 :            : 
     817                 :         25 :     _PyAST_Fini(interp);
     818                 :         25 :     _PyWarnings_Fini(interp);
     819                 :         25 :     _PyAtExit_Fini(interp);
     820                 :            : 
     821                 :            :     // All Python types must be destroyed before the last GC collection. Python
     822                 :            :     // types create a reference cycle to themselves in their in their
     823                 :            :     // PyTypeObject.tp_mro member (the tuple contains the type).
     824                 :            : 
     825                 :            :     /* Last garbage collection on this interpreter */
     826                 :         25 :     _PyGC_CollectNoFail(tstate);
     827                 :         25 :     _PyGC_Fini(interp);
     828                 :            : 
     829                 :            :     /* We don't clear sysdict and builtins until the end of this function.
     830                 :            :        Because clearing other attributes can execute arbitrary Python code
     831                 :            :        which requires sysdict and builtins. */
     832                 :         25 :     PyDict_Clear(interp->sysdict);
     833                 :         25 :     PyDict_Clear(interp->builtins);
     834         [ +  - ]:         25 :     Py_CLEAR(interp->sysdict);
     835         [ +  - ]:         25 :     Py_CLEAR(interp->builtins);
     836         [ +  - ]:         25 :     Py_CLEAR(interp->interpreter_trampoline);
     837                 :            : 
     838         [ +  + ]:        225 :     for (int i=0; i < DICT_MAX_WATCHERS; i++) {
     839                 :        200 :         interp->dict_state.watchers[i] = NULL;
     840                 :            :     }
     841                 :            : 
     842         [ +  + ]:        225 :     for (int i=0; i < TYPE_MAX_WATCHERS; i++) {
     843                 :        200 :         interp->type_watchers[i] = NULL;
     844                 :            :     }
     845                 :            : 
     846         [ +  + ]:        225 :     for (int i=0; i < FUNC_MAX_WATCHERS; i++) {
     847                 :        200 :         interp->func_watchers[i] = NULL;
     848                 :            :     }
     849                 :         25 :     interp->active_func_watchers = 0;
     850                 :            : 
     851         [ +  + ]:        225 :     for (int i=0; i < CODE_MAX_WATCHERS; i++) {
     852                 :        200 :         interp->code_watchers[i] = NULL;
     853                 :            :     }
     854                 :         25 :     interp->active_code_watchers = 0;
     855                 :            : 
     856                 :            :     // XXX Once we have one allocator per interpreter (i.e.
     857                 :            :     // per-interpreter GC) we must ensure that all of the interpreter's
     858                 :            :     // objects have been cleaned up at the point.
     859                 :         25 : }
     860                 :            : 
     861                 :            : 
     862                 :            : void
     863                 :          0 : PyInterpreterState_Clear(PyInterpreterState *interp)
     864                 :            : {
     865                 :            :     // Use the current Python thread state to call audit hooks and to collect
     866                 :            :     // garbage. It can be different than the current Python thread state
     867                 :            :     // of 'interp'.
     868                 :          0 :     PyThreadState *current_tstate = current_fast_get(interp->runtime);
     869                 :          0 :     _PyImport_ClearCore(interp);
     870                 :          0 :     interpreter_clear(interp, current_tstate);
     871                 :          0 : }
     872                 :            : 
     873                 :            : 
     874                 :            : void
     875                 :         25 : _PyInterpreterState_Clear(PyThreadState *tstate)
     876                 :            : {
     877                 :         25 :     _PyImport_ClearCore(tstate->interp);
     878                 :         25 :     interpreter_clear(tstate->interp, tstate);
     879                 :         25 : }
     880                 :            : 
     881                 :            : 
     882                 :            : static void zapthreads(PyInterpreterState *interp);
     883                 :            : 
     884                 :            : void
     885                 :         25 : PyInterpreterState_Delete(PyInterpreterState *interp)
     886                 :            : {
     887                 :         25 :     _PyRuntimeState *runtime = interp->runtime;
     888                 :         25 :     struct pyinterpreters *interpreters = &runtime->interpreters;
     889                 :            : 
     890                 :            :     // XXX Clearing the "current" thread state should happen before
     891                 :            :     // we start finalizing the interpreter (or the current thread state).
     892                 :         25 :     PyThreadState *tcur = current_fast_get(runtime);
     893   [ +  -  +  - ]:         25 :     if (tcur != NULL && interp == tcur->interp) {
     894                 :            :         /* Unset current thread.  After this, many C API calls become crashy. */
     895                 :         25 :         _PyThreadState_Swap(runtime, NULL);
     896                 :            :     }
     897                 :            : 
     898                 :         25 :     zapthreads(interp);
     899                 :            : 
     900                 :         25 :     _PyEval_FiniState(&interp->ceval);
     901                 :            : 
     902                 :         25 :     HEAD_LOCK(runtime);
     903                 :            :     PyInterpreterState **p;
     904                 :         25 :     for (p = &interpreters->head; ; p = &(*p)->next) {
     905         [ -  + ]:         25 :         if (*p == NULL) {
     906                 :          0 :             Py_FatalError("NULL interpreter");
     907                 :            :         }
     908         [ +  - ]:         25 :         if (*p == interp) {
     909                 :         25 :             break;
     910                 :            :         }
     911                 :            :     }
     912         [ -  + ]:         25 :     if (interp->threads.head != NULL) {
     913                 :          0 :         Py_FatalError("remaining threads");
     914                 :            :     }
     915                 :         25 :     *p = interp->next;
     916                 :            : 
     917         [ +  - ]:         25 :     if (interpreters->main == interp) {
     918                 :         25 :         interpreters->main = NULL;
     919         [ -  + ]:         25 :         if (interpreters->head != NULL) {
     920                 :          0 :             Py_FatalError("remaining subinterpreters");
     921                 :            :         }
     922                 :            :     }
     923                 :         25 :     HEAD_UNLOCK(runtime);
     924                 :            : 
     925         [ -  + ]:         25 :     if (interp->id_mutex != NULL) {
     926                 :          0 :         PyThread_free_lock(interp->id_mutex);
     927                 :            :     }
     928                 :         25 :     free_interpreter(interp);
     929                 :         25 : }
     930                 :            : 
     931                 :            : 
     932                 :            : #ifdef HAVE_FORK
     933                 :            : /*
     934                 :            :  * Delete all interpreter states except the main interpreter.  If there
     935                 :            :  * is a current interpreter state, it *must* be the main interpreter.
     936                 :            :  */
     937                 :            : PyStatus
     938                 :          0 : _PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
     939                 :            : {
     940                 :          0 :     struct pyinterpreters *interpreters = &runtime->interpreters;
     941                 :            : 
     942                 :          0 :     PyThreadState *tstate = _PyThreadState_Swap(runtime, NULL);
     943   [ #  #  #  # ]:          0 :     if (tstate != NULL && tstate->interp != interpreters->main) {
     944                 :          0 :         return _PyStatus_ERR("not main interpreter");
     945                 :            :     }
     946                 :            : 
     947                 :          0 :     HEAD_LOCK(runtime);
     948                 :          0 :     PyInterpreterState *interp = interpreters->head;
     949                 :          0 :     interpreters->head = NULL;
     950         [ #  # ]:          0 :     while (interp != NULL) {
     951         [ #  # ]:          0 :         if (interp == interpreters->main) {
     952                 :          0 :             interpreters->main->next = NULL;
     953                 :          0 :             interpreters->head = interp;
     954                 :          0 :             interp = interp->next;
     955                 :          0 :             continue;
     956                 :            :         }
     957                 :            : 
     958                 :            :         // XXX Won't this fail since PyInterpreterState_Clear() requires
     959                 :            :         // the "current" tstate to be set?
     960                 :          0 :         PyInterpreterState_Clear(interp);  // XXX must activate?
     961                 :          0 :         zapthreads(interp);
     962         [ #  # ]:          0 :         if (interp->id_mutex != NULL) {
     963                 :          0 :             PyThread_free_lock(interp->id_mutex);
     964                 :            :         }
     965                 :          0 :         PyInterpreterState *prev_interp = interp;
     966                 :          0 :         interp = interp->next;
     967                 :          0 :         free_interpreter(prev_interp);
     968                 :            :     }
     969                 :          0 :     HEAD_UNLOCK(runtime);
     970                 :            : 
     971         [ #  # ]:          0 :     if (interpreters->head == NULL) {
     972                 :          0 :         return _PyStatus_ERR("missing main interpreter");
     973                 :            :     }
     974                 :          0 :     _PyThreadState_Swap(runtime, tstate);
     975                 :          0 :     return _PyStatus_OK();
     976                 :            : }
     977                 :            : #endif
     978                 :            : 
     979                 :            : 
     980                 :            : //----------
     981                 :            : // accessors
     982                 :            : //----------
     983                 :            : 
     984                 :            : int64_t
     985                 :          0 : PyInterpreterState_GetID(PyInterpreterState *interp)
     986                 :            : {
     987         [ #  # ]:          0 :     if (interp == NULL) {
     988                 :          0 :         PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
     989                 :          0 :         return -1;
     990                 :            :     }
     991                 :          0 :     return interp->id;
     992                 :            : }
     993                 :            : 
     994                 :            : 
     995                 :            : int
     996                 :          0 : _PyInterpreterState_IDInitref(PyInterpreterState *interp)
     997                 :            : {
     998         [ #  # ]:          0 :     if (interp->id_mutex != NULL) {
     999                 :          0 :         return 0;
    1000                 :            :     }
    1001                 :          0 :     interp->id_mutex = PyThread_allocate_lock();
    1002         [ #  # ]:          0 :     if (interp->id_mutex == NULL) {
    1003                 :          0 :         PyErr_SetString(PyExc_RuntimeError,
    1004                 :            :                         "failed to create init interpreter ID mutex");
    1005                 :          0 :         return -1;
    1006                 :            :     }
    1007                 :          0 :     interp->id_refcount = 0;
    1008                 :          0 :     return 0;
    1009                 :            : }
    1010                 :            : 
    1011                 :            : 
    1012                 :            : int
    1013                 :          0 : _PyInterpreterState_IDIncref(PyInterpreterState *interp)
    1014                 :            : {
    1015         [ #  # ]:          0 :     if (_PyInterpreterState_IDInitref(interp) < 0) {
    1016                 :          0 :         return -1;
    1017                 :            :     }
    1018                 :            : 
    1019                 :          0 :     PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
    1020                 :          0 :     interp->id_refcount += 1;
    1021                 :          0 :     PyThread_release_lock(interp->id_mutex);
    1022                 :          0 :     return 0;
    1023                 :            : }
    1024                 :            : 
    1025                 :            : 
    1026                 :            : void
    1027                 :          0 : _PyInterpreterState_IDDecref(PyInterpreterState *interp)
    1028                 :            : {
    1029                 :            :     assert(interp->id_mutex != NULL);
    1030                 :          0 :     _PyRuntimeState *runtime = interp->runtime;
    1031                 :            : 
    1032                 :          0 :     PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
    1033                 :            :     assert(interp->id_refcount != 0);
    1034                 :          0 :     interp->id_refcount -= 1;
    1035                 :          0 :     int64_t refcount = interp->id_refcount;
    1036                 :          0 :     PyThread_release_lock(interp->id_mutex);
    1037                 :            : 
    1038   [ #  #  #  # ]:          0 :     if (refcount == 0 && interp->requires_idref) {
    1039                 :            :         // XXX Using the "head" thread isn't strictly correct.
    1040                 :          0 :         PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
    1041                 :            :         // XXX Possible GILState issues?
    1042                 :          0 :         PyThreadState *save_tstate = _PyThreadState_Swap(runtime, tstate);
    1043                 :          0 :         Py_EndInterpreter(tstate);
    1044                 :          0 :         _PyThreadState_Swap(runtime, save_tstate);
    1045                 :            :     }
    1046                 :          0 : }
    1047                 :            : 
    1048                 :            : int
    1049                 :          0 : _PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
    1050                 :            : {
    1051                 :          0 :     return interp->requires_idref;
    1052                 :            : }
    1053                 :            : 
    1054                 :            : void
    1055                 :          0 : _PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
    1056                 :            : {
    1057                 :          0 :     interp->requires_idref = required ? 1 : 0;
    1058                 :          0 : }
    1059                 :            : 
    1060                 :            : PyObject *
    1061                 :          0 : _PyInterpreterState_GetMainModule(PyInterpreterState *interp)
    1062                 :            : {
    1063                 :          0 :     PyObject *modules = _PyImport_GetModules(interp);
    1064         [ #  # ]:          0 :     if (modules == NULL) {
    1065                 :          0 :         PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
    1066                 :          0 :         return NULL;
    1067                 :            :     }
    1068                 :          0 :     return PyMapping_GetItemString(modules, "__main__");
    1069                 :            : }
    1070                 :            : 
    1071                 :            : PyObject *
    1072                 :          0 : PyInterpreterState_GetDict(PyInterpreterState *interp)
    1073                 :            : {
    1074         [ #  # ]:          0 :     if (interp->dict == NULL) {
    1075                 :          0 :         interp->dict = PyDict_New();
    1076         [ #  # ]:          0 :         if (interp->dict == NULL) {
    1077                 :          0 :             PyErr_Clear();
    1078                 :            :         }
    1079                 :            :     }
    1080                 :            :     /* Returning NULL means no per-interpreter dict is available. */
    1081                 :          0 :     return interp->dict;
    1082                 :            : }
    1083                 :            : 
    1084                 :            : 
    1085                 :            : //-----------------------------
    1086                 :            : // look up an interpreter state
    1087                 :            : //-----------------------------
    1088                 :            : 
    1089                 :            : /* Return the interpreter associated with the current OS thread.
    1090                 :            : 
    1091                 :            :    The GIL must be held.
    1092                 :            :   */
    1093                 :            : 
    1094                 :            : PyInterpreterState *
    1095                 :     102301 : PyInterpreterState_Get(void)
    1096                 :            : {
    1097                 :     102301 :     PyThreadState *tstate = current_fast_get(&_PyRuntime);
    1098                 :     102301 :     _Py_EnsureTstateNotNULL(tstate);
    1099                 :     102301 :     PyInterpreterState *interp = tstate->interp;
    1100         [ -  + ]:     102301 :     if (interp == NULL) {
    1101                 :          0 :         Py_FatalError("no current interpreter");
    1102                 :            :     }
    1103                 :     102301 :     return interp;
    1104                 :            : }
    1105                 :            : 
    1106                 :            : 
    1107                 :            : static PyInterpreterState *
    1108                 :          0 : interp_look_up_id(_PyRuntimeState *runtime, int64_t requested_id)
    1109                 :            : {
    1110                 :          0 :     PyInterpreterState *interp = runtime->interpreters.head;
    1111         [ #  # ]:          0 :     while (interp != NULL) {
    1112                 :          0 :         int64_t id = PyInterpreterState_GetID(interp);
    1113         [ #  # ]:          0 :         if (id < 0) {
    1114                 :          0 :             return NULL;
    1115                 :            :         }
    1116         [ #  # ]:          0 :         if (requested_id == id) {
    1117                 :          0 :             return interp;
    1118                 :            :         }
    1119                 :          0 :         interp = PyInterpreterState_Next(interp);
    1120                 :            :     }
    1121                 :          0 :     return NULL;
    1122                 :            : }
    1123                 :            : 
    1124                 :            : /* Return the interpreter state with the given ID.
    1125                 :            : 
    1126                 :            :    Fail with RuntimeError if the interpreter is not found. */
    1127                 :            : 
    1128                 :            : PyInterpreterState *
    1129                 :          0 : _PyInterpreterState_LookUpID(int64_t requested_id)
    1130                 :            : {
    1131                 :          0 :     PyInterpreterState *interp = NULL;
    1132         [ #  # ]:          0 :     if (requested_id >= 0) {
    1133                 :          0 :         _PyRuntimeState *runtime = &_PyRuntime;
    1134                 :          0 :         HEAD_LOCK(runtime);
    1135                 :          0 :         interp = interp_look_up_id(runtime, requested_id);
    1136                 :          0 :         HEAD_UNLOCK(runtime);
    1137                 :            :     }
    1138   [ #  #  #  # ]:          0 :     if (interp == NULL && !PyErr_Occurred()) {
    1139                 :          0 :         PyErr_Format(PyExc_RuntimeError,
    1140                 :            :                      "unrecognized interpreter ID %lld", requested_id);
    1141                 :            :     }
    1142                 :          0 :     return interp;
    1143                 :            : }
    1144                 :            : 
    1145                 :            : 
    1146                 :            : /********************************/
    1147                 :            : /* the per-thread runtime state */
    1148                 :            : /********************************/
    1149                 :            : 
    1150                 :            : #ifndef NDEBUG
    1151                 :            : static inline int
    1152                 :            : tstate_is_alive(PyThreadState *tstate)
    1153                 :            : {
    1154                 :            :     return (tstate->_status.initialized &&
    1155                 :            :             !tstate->_status.finalized &&
    1156                 :            :             !tstate->_status.cleared &&
    1157                 :            :             !tstate->_status.finalizing);
    1158                 :            : }
    1159                 :            : #endif
    1160                 :            : 
    1161                 :            : 
    1162                 :            : //----------
    1163                 :            : // lifecycle
    1164                 :            : //----------
    1165                 :            : 
    1166                 :            : /* Minimum size of data stack chunk */
    1167                 :            : #define DATA_STACK_CHUNK_SIZE (16*1024)
    1168                 :            : 
    1169                 :            : static _PyStackChunk*
    1170                 :         25 : allocate_chunk(int size_in_bytes, _PyStackChunk* previous)
    1171                 :            : {
    1172                 :            :     assert(size_in_bytes % sizeof(PyObject **) == 0);
    1173                 :         25 :     _PyStackChunk *res = _PyObject_VirtualAlloc(size_in_bytes);
    1174         [ -  + ]:         25 :     if (res == NULL) {
    1175                 :          0 :         return NULL;
    1176                 :            :     }
    1177                 :         25 :     res->previous = previous;
    1178                 :         25 :     res->size = size_in_bytes;
    1179                 :         25 :     res->top = 0;
    1180                 :         25 :     return res;
    1181                 :            : }
    1182                 :            : 
    1183                 :            : static PyThreadState *
    1184                 :         29 : alloc_threadstate(void)
    1185                 :            : {
    1186                 :         29 :     return PyMem_RawCalloc(1, sizeof(PyThreadState));
    1187                 :            : }
    1188                 :            : 
    1189                 :            : static void
    1190                 :         25 : free_threadstate(PyThreadState *tstate)
    1191                 :            : {
    1192                 :            :     // The initial thread state of the interpreter is allocated
    1193                 :            :     // as part of the interpreter state so should not be freed.
    1194         [ -  + ]:         25 :     if (tstate != &tstate->interp->_initial_thread) {
    1195                 :          0 :         PyMem_RawFree(tstate);
    1196                 :            :     }
    1197                 :         25 : }
    1198                 :            : 
    1199                 :            : /* Get the thread state to a minimal consistent state.
    1200                 :            :    Further init happens in pylifecycle.c before it can be used.
    1201                 :            :    All fields not initialized here are expected to be zeroed out,
    1202                 :            :    e.g. by PyMem_RawCalloc() or memset(), or otherwise pre-initialized.
    1203                 :            :    The interpreter state is not manipulated.  Instead it is assumed that
    1204                 :            :    the thread is getting added to the interpreter.
    1205                 :            :   */
    1206                 :            : 
    1207                 :            : static void
    1208                 :         29 : init_threadstate(PyThreadState *tstate,
    1209                 :            :                  PyInterpreterState *interp, uint64_t id,
    1210                 :            :                  PyThreadState *next)
    1211                 :            : {
    1212         [ -  + ]:         29 :     if (tstate->_status.initialized) {
    1213                 :          0 :         Py_FatalError("thread state already initialized");
    1214                 :            :     }
    1215                 :            : 
    1216                 :            :     assert(interp != NULL);
    1217                 :         29 :     tstate->interp = interp;
    1218                 :            : 
    1219                 :            :     assert(id > 0);
    1220                 :         29 :     tstate->id = id;
    1221                 :            : 
    1222                 :            :     assert(interp->threads.head == tstate);
    1223                 :            :     assert((next != NULL && id != 1) || (next == NULL && id == 1));
    1224         [ -  + ]:         29 :     if (next != NULL) {
    1225                 :            :         assert(next->prev == NULL || next->prev == tstate);
    1226                 :          0 :         next->prev = tstate;
    1227                 :            :     }
    1228                 :         29 :     tstate->next = next;
    1229                 :            :     assert(tstate->prev == NULL);
    1230                 :            : 
    1231                 :            :     // thread_id and native_thread_id are set in bind_tstate().
    1232                 :            : 
    1233                 :         29 :     tstate->py_recursion_limit = interp->ceval.recursion_limit,
    1234                 :         29 :     tstate->py_recursion_remaining = interp->ceval.recursion_limit,
    1235                 :         29 :     tstate->c_recursion_remaining = C_RECURSION_LIMIT;
    1236                 :            : 
    1237                 :         29 :     tstate->exc_info = &tstate->exc_state;
    1238                 :            : 
    1239                 :            :     // PyGILState_Release must not try to delete this thread state.
    1240                 :            :     // This is cleared when PyGILState_Ensure() creates the thread state.
    1241                 :         29 :     tstate->gilstate_counter = 1;
    1242                 :            : 
    1243                 :         29 :     tstate->cframe = &tstate->root_cframe;
    1244                 :         29 :     tstate->datastack_chunk = NULL;
    1245                 :         29 :     tstate->datastack_top = NULL;
    1246                 :         29 :     tstate->datastack_limit = NULL;
    1247                 :            : 
    1248                 :         29 :     tstate->_status.initialized = 1;
    1249                 :         29 : }
    1250                 :            : 
    1251                 :            : static PyThreadState *
    1252                 :         29 : new_threadstate(PyInterpreterState *interp)
    1253                 :            : {
    1254                 :            :     PyThreadState *tstate;
    1255                 :         29 :     _PyRuntimeState *runtime = interp->runtime;
    1256                 :            :     // We don't need to allocate a thread state for the main interpreter
    1257                 :            :     // (the common case), but doing it later for the other case revealed a
    1258                 :            :     // reentrancy problem (deadlock).  So for now we always allocate before
    1259                 :            :     // taking the interpreters lock.  See GH-96071.
    1260                 :         29 :     PyThreadState *new_tstate = alloc_threadstate();
    1261                 :            :     int used_newtstate;
    1262         [ -  + ]:         29 :     if (new_tstate == NULL) {
    1263                 :          0 :         return NULL;
    1264                 :            :     }
    1265                 :            :     /* We serialize concurrent creation to protect global state. */
    1266                 :         29 :     HEAD_LOCK(runtime);
    1267                 :            : 
    1268                 :         29 :     interp->threads.next_unique_id += 1;
    1269                 :         29 :     uint64_t id = interp->threads.next_unique_id;
    1270                 :            : 
    1271                 :            :     // Allocate the thread state and add it to the interpreter.
    1272                 :         29 :     PyThreadState *old_head = interp->threads.head;
    1273         [ +  - ]:         29 :     if (old_head == NULL) {
    1274                 :            :         // It's the interpreter's initial thread state.
    1275                 :            :         assert(id == 1);
    1276                 :         29 :         used_newtstate = 0;
    1277                 :         29 :         tstate = &interp->_initial_thread;
    1278                 :            :     }
    1279                 :            :     else {
    1280                 :            :         // Every valid interpreter must have at least one thread.
    1281                 :            :         assert(id > 1);
    1282                 :            :         assert(old_head->prev == NULL);
    1283                 :          0 :         used_newtstate = 1;
    1284                 :          0 :         tstate = new_tstate;
    1285                 :            :         // Set to _PyThreadState_INIT.
    1286                 :          0 :         memcpy(tstate,
    1287                 :            :                &initial._main_interpreter._initial_thread,
    1288                 :            :                sizeof(*tstate));
    1289                 :            :     }
    1290                 :         29 :     interp->threads.head = tstate;
    1291                 :            : 
    1292                 :         29 :     init_threadstate(tstate, interp, id, old_head);
    1293                 :            : 
    1294                 :         29 :     HEAD_UNLOCK(runtime);
    1295         [ +  - ]:         29 :     if (!used_newtstate) {
    1296                 :            :         // Must be called with lock unlocked to avoid re-entrancy deadlock.
    1297                 :         29 :         PyMem_RawFree(new_tstate);
    1298                 :            :     }
    1299                 :         29 :     return tstate;
    1300                 :            : }
    1301                 :            : 
    1302                 :            : PyThreadState *
    1303                 :          0 : PyThreadState_New(PyInterpreterState *interp)
    1304                 :            : {
    1305                 :          0 :     PyThreadState *tstate = new_threadstate(interp);
    1306         [ #  # ]:          0 :     if (tstate) {
    1307                 :          0 :         bind_tstate(tstate);
    1308                 :            :         // This makes sure there's a gilstate tstate bound
    1309                 :            :         // as soon as possible.
    1310         [ #  # ]:          0 :         if (gilstate_tss_get(tstate->interp->runtime) == NULL) {
    1311                 :          0 :             bind_gilstate_tstate(tstate);
    1312                 :            :         }
    1313                 :            :     }
    1314                 :          0 :     return tstate;
    1315                 :            : }
    1316                 :            : 
    1317                 :            : // This must be followed by a call to _PyThreadState_Bind();
    1318                 :            : PyThreadState *
    1319                 :         29 : _PyThreadState_New(PyInterpreterState *interp)
    1320                 :            : {
    1321                 :         29 :     return new_threadstate(interp);
    1322                 :            : }
    1323                 :            : 
    1324                 :            : // We keep this for stable ABI compabibility.
    1325                 :            : PyThreadState *
    1326                 :          0 : _PyThreadState_Prealloc(PyInterpreterState *interp)
    1327                 :            : {
    1328                 :          0 :     return _PyThreadState_New(interp);
    1329                 :            : }
    1330                 :            : 
    1331                 :            : // We keep this around for (accidental) stable ABI compatibility.
    1332                 :            : // Realistically, no extensions are using it.
    1333                 :            : void
    1334                 :          0 : _PyThreadState_Init(PyThreadState *tstate)
    1335                 :            : {
    1336                 :          0 :     Py_FatalError("_PyThreadState_Init() is for internal use only");
    1337                 :            : }
    1338                 :            : 
    1339                 :            : void
    1340                 :         25 : PyThreadState_Clear(PyThreadState *tstate)
    1341                 :            : {
    1342                 :            :     assert(tstate->_status.initialized && !tstate->_status.cleared);
    1343                 :            :     // XXX assert(!tstate->_status.bound || tstate->_status.unbound);
    1344                 :         25 :     tstate->_status.finalizing = 1;  // just in case
    1345                 :            : 
    1346                 :            :     /* XXX Conditions we need to enforce:
    1347                 :            : 
    1348                 :            :        * the GIL must be held by the current thread
    1349                 :            :        * current_fast_get()->interp must match tstate->interp
    1350                 :            :        * for the main interpreter, current_fast_get() must be the main thread
    1351                 :            :      */
    1352                 :            : 
    1353                 :         25 :     int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
    1354                 :            : 
    1355   [ -  +  -  - ]:         25 :     if (verbose && tstate->cframe->current_frame != NULL) {
    1356                 :            :         /* bpo-20526: After the main thread calls
    1357                 :            :            _PyRuntimeState_SetFinalizing() in Py_FinalizeEx(), threads must
    1358                 :            :            exit when trying to take the GIL. If a thread exit in the middle of
    1359                 :            :            _PyEval_EvalFrameDefault(), tstate->frame is not reset to its
    1360                 :            :            previous value. It is more likely with daemon threads, but it can
    1361                 :            :            happen with regular threads if threading._shutdown() fails
    1362                 :            :            (ex: interrupted by CTRL+C). */
    1363                 :          0 :         fprintf(stderr,
    1364                 :            :           "PyThreadState_Clear: warning: thread still has a frame\n");
    1365                 :            :     }
    1366                 :            : 
    1367                 :            :     /* At this point tstate shouldn't be used any more,
    1368                 :            :        neither to run Python code nor for other uses.
    1369                 :            : 
    1370                 :            :        This is tricky when current_fast_get() == tstate, in the same way
    1371                 :            :        as noted in interpreter_clear() above.  The below finalizers
    1372                 :            :        can possibly run Python code or otherwise use the partially
    1373                 :            :        cleared thread state.  For now we trust that isn't a problem
    1374                 :            :        in practice.
    1375                 :            :      */
    1376                 :            :     // XXX Deal with the possibility of problematic finalizers.
    1377                 :            : 
    1378                 :            :     /* Don't clear tstate->pyframe: it is a borrowed reference */
    1379                 :            : 
    1380         [ +  + ]:         25 :     Py_CLEAR(tstate->dict);
    1381         [ -  + ]:         25 :     Py_CLEAR(tstate->async_exc);
    1382                 :            : 
    1383         [ -  + ]:         25 :     Py_CLEAR(tstate->current_exception);
    1384                 :            : 
    1385         [ +  - ]:         25 :     Py_CLEAR(tstate->exc_state.exc_value);
    1386                 :            : 
    1387                 :            :     /* The stack of exception states should contain just this thread. */
    1388   [ -  +  -  - ]:         25 :     if (verbose && tstate->exc_info != &tstate->exc_state) {
    1389                 :          0 :         fprintf(stderr,
    1390                 :            :           "PyThreadState_Clear: warning: thread still has a generator\n");
    1391                 :            :     }
    1392                 :            : 
    1393                 :         25 :     tstate->c_profilefunc = NULL;
    1394                 :         25 :     tstate->c_tracefunc = NULL;
    1395         [ -  + ]:         25 :     Py_CLEAR(tstate->c_profileobj);
    1396         [ -  + ]:         25 :     Py_CLEAR(tstate->c_traceobj);
    1397                 :            : 
    1398         [ -  + ]:         25 :     Py_CLEAR(tstate->async_gen_firstiter);
    1399         [ -  + ]:         25 :     Py_CLEAR(tstate->async_gen_finalizer);
    1400                 :            : 
    1401         [ +  + ]:         25 :     Py_CLEAR(tstate->context);
    1402                 :            : 
    1403         [ +  + ]:         25 :     if (tstate->on_delete != NULL) {
    1404                 :          4 :         tstate->on_delete(tstate->on_delete_data);
    1405                 :            :     }
    1406                 :            : 
    1407                 :         25 :     tstate->_status.cleared = 1;
    1408                 :            : 
    1409                 :            :     // XXX Call _PyThreadStateSwap(runtime, NULL) here if "current".
    1410                 :            :     // XXX Do it as early in the function as possible.
    1411                 :         25 : }
    1412                 :            : 
    1413                 :            : 
    1414                 :            : /* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
    1415                 :            : static void
    1416                 :         25 : tstate_delete_common(PyThreadState *tstate)
    1417                 :            : {
    1418                 :            :     assert(tstate->_status.cleared && !tstate->_status.finalized);
    1419                 :            : 
    1420                 :         25 :     PyInterpreterState *interp = tstate->interp;
    1421         [ -  + ]:         25 :     if (interp == NULL) {
    1422                 :          0 :         Py_FatalError("NULL interpreter");
    1423                 :            :     }
    1424                 :         25 :     _PyRuntimeState *runtime = interp->runtime;
    1425                 :            : 
    1426                 :         25 :     HEAD_LOCK(runtime);
    1427         [ -  + ]:         25 :     if (tstate->prev) {
    1428                 :          0 :         tstate->prev->next = tstate->next;
    1429                 :            :     }
    1430                 :            :     else {
    1431                 :         25 :         interp->threads.head = tstate->next;
    1432                 :            :     }
    1433         [ -  + ]:         25 :     if (tstate->next) {
    1434                 :          0 :         tstate->next->prev = tstate->prev;
    1435                 :            :     }
    1436                 :         25 :     HEAD_UNLOCK(runtime);
    1437                 :            : 
    1438                 :            :     // XXX Unbind in PyThreadState_Clear(), or earlier
    1439                 :            :     // (and assert not-equal here)?
    1440         [ +  - ]:         25 :     if (tstate->_status.bound_gilstate) {
    1441                 :         25 :         unbind_gilstate_tstate(tstate);
    1442                 :            :     }
    1443                 :         25 :     unbind_tstate(tstate);
    1444                 :            : 
    1445                 :            :     // XXX Move to PyThreadState_Clear()?
    1446                 :         25 :     _PyStackChunk *chunk = tstate->datastack_chunk;
    1447                 :         25 :     tstate->datastack_chunk = NULL;
    1448         [ +  + ]:         50 :     while (chunk != NULL) {
    1449                 :         25 :         _PyStackChunk *prev = chunk->previous;
    1450                 :         25 :         _PyObject_VirtualFree(chunk, chunk->size);
    1451                 :         25 :         chunk = prev;
    1452                 :            :     }
    1453                 :            : 
    1454                 :         25 :     tstate->_status.finalized = 1;
    1455                 :         25 : }
    1456                 :            : 
    1457                 :            : 
    1458                 :            : static void
    1459                 :         25 : zapthreads(PyInterpreterState *interp)
    1460                 :            : {
    1461                 :            :     PyThreadState *tstate;
    1462                 :            :     /* No need to lock the mutex here because this should only happen
    1463                 :            :        when the threads are all really dead (XXX famous last words). */
    1464         [ +  + ]:         50 :     while ((tstate = interp->threads.head) != NULL) {
    1465         [ -  + ]:         25 :         tstate_verify_not_active(tstate);
    1466                 :         25 :         tstate_delete_common(tstate);
    1467                 :         25 :         free_threadstate(tstate);
    1468                 :            :     }
    1469                 :         25 : }
    1470                 :            : 
    1471                 :            : 
    1472                 :            : void
    1473                 :          0 : PyThreadState_Delete(PyThreadState *tstate)
    1474                 :            : {
    1475                 :          0 :     _Py_EnsureTstateNotNULL(tstate);
    1476         [ #  # ]:          0 :     tstate_verify_not_active(tstate);
    1477                 :          0 :     tstate_delete_common(tstate);
    1478                 :          0 :     free_threadstate(tstate);
    1479                 :          0 : }
    1480                 :            : 
    1481                 :            : 
    1482                 :            : void
    1483                 :          0 : _PyThreadState_DeleteCurrent(PyThreadState *tstate)
    1484                 :            : {
    1485                 :          0 :     _Py_EnsureTstateNotNULL(tstate);
    1486                 :          0 :     tstate_delete_common(tstate);
    1487                 :          0 :     current_fast_clear(tstate->interp->runtime);
    1488                 :          0 :     _PyEval_ReleaseLock(tstate);
    1489                 :          0 :     free_threadstate(tstate);
    1490                 :          0 : }
    1491                 :            : 
    1492                 :            : void
    1493                 :          0 : PyThreadState_DeleteCurrent(void)
    1494                 :            : {
    1495                 :          0 :     PyThreadState *tstate = current_fast_get(&_PyRuntime);
    1496                 :          0 :     _PyThreadState_DeleteCurrent(tstate);
    1497                 :          0 : }
    1498                 :            : 
    1499                 :            : 
    1500                 :            : /*
    1501                 :            :  * Delete all thread states except the one passed as argument.
    1502                 :            :  * Note that, if there is a current thread state, it *must* be the one
    1503                 :            :  * passed as argument.  Also, this won't touch any other interpreters
    1504                 :            :  * than the current one, since we don't know which thread state should
    1505                 :            :  * be kept in those other interpreters.
    1506                 :            :  */
    1507                 :            : void
    1508                 :         25 : _PyThreadState_DeleteExcept(PyThreadState *tstate)
    1509                 :            : {
    1510                 :            :     assert(tstate != NULL);
    1511                 :         25 :     PyInterpreterState *interp = tstate->interp;
    1512                 :         25 :     _PyRuntimeState *runtime = interp->runtime;
    1513                 :            : 
    1514                 :         25 :     HEAD_LOCK(runtime);
    1515                 :            :     /* Remove all thread states, except tstate, from the linked list of
    1516                 :            :        thread states.  This will allow calling PyThreadState_Clear()
    1517                 :            :        without holding the lock. */
    1518                 :         25 :     PyThreadState *list = interp->threads.head;
    1519         [ +  - ]:         25 :     if (list == tstate) {
    1520                 :         25 :         list = tstate->next;
    1521                 :            :     }
    1522         [ -  + ]:         25 :     if (tstate->prev) {
    1523                 :          0 :         tstate->prev->next = tstate->next;
    1524                 :            :     }
    1525         [ -  + ]:         25 :     if (tstate->next) {
    1526                 :          0 :         tstate->next->prev = tstate->prev;
    1527                 :            :     }
    1528                 :         25 :     tstate->prev = tstate->next = NULL;
    1529                 :         25 :     interp->threads.head = tstate;
    1530                 :         25 :     HEAD_UNLOCK(runtime);
    1531                 :            : 
    1532                 :            :     /* Clear and deallocate all stale thread states.  Even if this
    1533                 :            :        executes Python code, we should be safe since it executes
    1534                 :            :        in the current thread, not one of the stale threads. */
    1535                 :            :     PyThreadState *p, *next;
    1536         [ -  + ]:         25 :     for (p = list; p; p = next) {
    1537                 :          0 :         next = p->next;
    1538                 :          0 :         PyThreadState_Clear(p);
    1539                 :          0 :         free_threadstate(p);
    1540                 :            :     }
    1541                 :         25 : }
    1542                 :            : 
    1543                 :            : 
    1544                 :            : //----------
    1545                 :            : // accessors
    1546                 :            : //----------
    1547                 :            : 
    1548                 :            : /* An extension mechanism to store arbitrary additional per-thread state.
    1549                 :            :    PyThreadState_GetDict() returns a dictionary that can be used to hold such
    1550                 :            :    state; the caller should pick a unique key and store its state there.  If
    1551                 :            :    PyThreadState_GetDict() returns NULL, an exception has *not* been raised
    1552                 :            :    and the caller should assume no per-thread state is available. */
    1553                 :            : 
    1554                 :            : PyObject *
    1555                 :      30209 : _PyThreadState_GetDict(PyThreadState *tstate)
    1556                 :            : {
    1557                 :            :     assert(tstate != NULL);
    1558         [ +  + ]:      30209 :     if (tstate->dict == NULL) {
    1559                 :          3 :         tstate->dict = PyDict_New();
    1560         [ -  + ]:          3 :         if (tstate->dict == NULL) {
    1561                 :          0 :             _PyErr_Clear(tstate);
    1562                 :            :         }
    1563                 :            :     }
    1564                 :      30209 :     return tstate->dict;
    1565                 :            : }
    1566                 :            : 
    1567                 :            : 
    1568                 :            : PyObject *
    1569                 :      30209 : PyThreadState_GetDict(void)
    1570                 :            : {
    1571                 :      30209 :     PyThreadState *tstate = current_fast_get(&_PyRuntime);
    1572         [ -  + ]:      30209 :     if (tstate == NULL) {
    1573                 :          0 :         return NULL;
    1574                 :            :     }
    1575                 :      30209 :     return _PyThreadState_GetDict(tstate);
    1576                 :            : }
    1577                 :            : 
    1578                 :            : 
    1579                 :            : PyInterpreterState *
    1580                 :          4 : PyThreadState_GetInterpreter(PyThreadState *tstate)
    1581                 :            : {
    1582                 :            :     assert(tstate != NULL);
    1583                 :          4 :     return tstate->interp;
    1584                 :            : }
    1585                 :            : 
    1586                 :            : 
    1587                 :            : PyFrameObject*
    1588                 :          4 : PyThreadState_GetFrame(PyThreadState *tstate)
    1589                 :            : {
    1590                 :            :     assert(tstate != NULL);
    1591                 :          4 :     _PyInterpreterFrame *f = _PyThreadState_GetFrame(tstate);
    1592         [ -  + ]:          4 :     if (f == NULL) {
    1593                 :          0 :         return NULL;
    1594                 :            :     }
    1595                 :          4 :     PyFrameObject *frame = _PyFrame_GetFrameObject(f);
    1596         [ -  + ]:          4 :     if (frame == NULL) {
    1597                 :          0 :         PyErr_Clear();
    1598                 :            :     }
    1599                 :          4 :     return (PyFrameObject*)Py_XNewRef(frame);
    1600                 :            : }
    1601                 :            : 
    1602                 :            : 
    1603                 :            : uint64_t
    1604                 :          0 : PyThreadState_GetID(PyThreadState *tstate)
    1605                 :            : {
    1606                 :            :     assert(tstate != NULL);
    1607                 :          0 :     return tstate->id;
    1608                 :            : }
    1609                 :            : 
    1610                 :            : 
    1611                 :            : static inline void
    1612                 :      30180 : tstate_activate(PyThreadState *tstate)
    1613                 :            : {
    1614                 :            :     assert(tstate != NULL);
    1615                 :            :     // XXX assert(tstate_is_alive(tstate));
    1616                 :            :     assert(tstate_is_bound(tstate));
    1617                 :            :     assert(!tstate->_status.active);
    1618                 :            : 
    1619                 :            :     assert(!tstate->_status.bound_gilstate ||
    1620                 :            :            tstate == gilstate_tss_get((tstate->interp->runtime)));
    1621         [ -  + ]:      30180 :     if (!tstate->_status.bound_gilstate) {
    1622                 :          0 :         bind_gilstate_tstate(tstate);
    1623                 :            :     }
    1624                 :            : 
    1625                 :      30180 :     tstate->_status.active = 1;
    1626                 :      30180 : }
    1627                 :            : 
    1628                 :            : static inline void
    1629                 :      30176 : tstate_deactivate(PyThreadState *tstate)
    1630                 :            : {
    1631                 :            :     assert(tstate != NULL);
    1632                 :            :     // XXX assert(tstate_is_alive(tstate));
    1633                 :            :     assert(tstate_is_bound(tstate));
    1634                 :            :     assert(tstate->_status.active);
    1635                 :            : 
    1636                 :      30176 :     tstate->_status.active = 0;
    1637                 :            : 
    1638                 :            :     // We do not unbind the gilstate tstate here.
    1639                 :            :     // It will still be used in PyGILState_Ensure().
    1640                 :      30176 : }
    1641                 :            : 
    1642                 :            : 
    1643                 :            : //----------
    1644                 :            : // other API
    1645                 :            : //----------
    1646                 :            : 
    1647                 :            : /* Asynchronously raise an exception in a thread.
    1648                 :            :    Requested by Just van Rossum and Alex Martelli.
    1649                 :            :    To prevent naive misuse, you must write your own extension
    1650                 :            :    to call this, or use ctypes.  Must be called with the GIL held.
    1651                 :            :    Returns the number of tstates modified (normally 1, but 0 if `id` didn't
    1652                 :            :    match any known thread id).  Can be called with exc=NULL to clear an
    1653                 :            :    existing async exception.  This raises no exceptions. */
    1654                 :            : 
    1655                 :            : // XXX Move this to Python/ceval_gil.c?
    1656                 :            : // XXX Deprecate this.
    1657                 :            : int
    1658                 :          0 : PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
    1659                 :            : {
    1660                 :          0 :     _PyRuntimeState *runtime = &_PyRuntime;
    1661                 :          0 :     PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
    1662                 :            : 
    1663                 :            :     /* Although the GIL is held, a few C API functions can be called
    1664                 :            :      * without the GIL held, and in particular some that create and
    1665                 :            :      * destroy thread and interpreter states.  Those can mutate the
    1666                 :            :      * list of thread states we're traversing, so to prevent that we lock
    1667                 :            :      * head_mutex for the duration.
    1668                 :            :      */
    1669                 :          0 :     HEAD_LOCK(runtime);
    1670         [ #  # ]:          0 :     for (PyThreadState *tstate = interp->threads.head; tstate != NULL; tstate = tstate->next) {
    1671         [ #  # ]:          0 :         if (tstate->thread_id != id) {
    1672                 :          0 :             continue;
    1673                 :            :         }
    1674                 :            : 
    1675                 :            :         /* Tricky:  we need to decref the current value
    1676                 :            :          * (if any) in tstate->async_exc, but that can in turn
    1677                 :            :          * allow arbitrary Python code to run, including
    1678                 :            :          * perhaps calls to this function.  To prevent
    1679                 :            :          * deadlock, we need to release head_mutex before
    1680                 :            :          * the decref.
    1681                 :            :          */
    1682                 :          0 :         PyObject *old_exc = tstate->async_exc;
    1683                 :          0 :         tstate->async_exc = Py_XNewRef(exc);
    1684                 :          0 :         HEAD_UNLOCK(runtime);
    1685                 :            : 
    1686                 :          0 :         Py_XDECREF(old_exc);
    1687                 :          0 :         _PyEval_SignalAsyncExc(tstate->interp);
    1688                 :          0 :         return 1;
    1689                 :            :     }
    1690                 :          0 :     HEAD_UNLOCK(runtime);
    1691                 :          0 :     return 0;
    1692                 :            : }
    1693                 :            : 
    1694                 :            : 
    1695                 :            : //---------------------------------
    1696                 :            : // API for the current thread state
    1697                 :            : //---------------------------------
    1698                 :            : 
    1699                 :            : PyThreadState *
    1700                 :    7255519 : _PyThreadState_UncheckedGet(void)
    1701                 :            : {
    1702                 :    7255519 :     return current_fast_get(&_PyRuntime);
    1703                 :            : }
    1704                 :            : 
    1705                 :            : 
    1706                 :            : PyThreadState *
    1707                 :          0 : PyThreadState_Get(void)
    1708                 :            : {
    1709                 :          0 :     PyThreadState *tstate = current_fast_get(&_PyRuntime);
    1710                 :          0 :     _Py_EnsureTstateNotNULL(tstate);
    1711                 :          0 :     return tstate;
    1712                 :            : }
    1713                 :            : 
    1714                 :            : 
    1715                 :            : PyThreadState *
    1716                 :      60356 : _PyThreadState_Swap(_PyRuntimeState *runtime, PyThreadState *newts)
    1717                 :            : {
    1718                 :            : #if defined(Py_DEBUG)
    1719                 :            :     /* This can be called from PyEval_RestoreThread(). Similar
    1720                 :            :        to it, we need to ensure errno doesn't change.
    1721                 :            :     */
    1722                 :            :     int err = errno;
    1723                 :            : #endif
    1724                 :      60356 :     PyThreadState *oldts = current_fast_get(runtime);
    1725                 :            : 
    1726                 :      60356 :     current_fast_clear(runtime);
    1727                 :            : 
    1728         [ +  + ]:      60356 :     if (oldts != NULL) {
    1729                 :            :         // XXX assert(tstate_is_alive(oldts) && tstate_is_bound(oldts));
    1730                 :      30176 :         tstate_deactivate(oldts);
    1731                 :            :     }
    1732                 :            : 
    1733         [ +  + ]:      60356 :     if (newts != NULL) {
    1734                 :            :         // XXX assert(tstate_is_alive(newts));
    1735                 :            :         assert(tstate_is_bound(newts));
    1736                 :      30180 :         current_fast_set(runtime, newts);
    1737                 :      30180 :         tstate_activate(newts);
    1738                 :            :     }
    1739                 :            : 
    1740                 :            : #if defined(Py_DEBUG)
    1741                 :            :     errno = err;
    1742                 :            : #endif
    1743                 :      60356 :     return oldts;
    1744                 :            : }
    1745                 :            : 
    1746                 :            : PyThreadState *
    1747                 :         29 : PyThreadState_Swap(PyThreadState *newts)
    1748                 :            : {
    1749                 :         29 :     return _PyThreadState_Swap(&_PyRuntime, newts);
    1750                 :            : }
    1751                 :            : 
    1752                 :            : 
    1753                 :            : void
    1754                 :         29 : _PyThreadState_Bind(PyThreadState *tstate)
    1755                 :            : {
    1756                 :         29 :     bind_tstate(tstate);
    1757                 :            :     // This makes sure there's a gilstate tstate bound
    1758                 :            :     // as soon as possible.
    1759         [ +  - ]:         29 :     if (gilstate_tss_get(tstate->interp->runtime) == NULL) {
    1760                 :         29 :         bind_gilstate_tstate(tstate);
    1761                 :            :     }
    1762                 :         29 : }
    1763                 :            : 
    1764                 :            : 
    1765                 :            : /***********************************/
    1766                 :            : /* routines for advanced debuggers */
    1767                 :            : /***********************************/
    1768                 :            : 
    1769                 :            : // (requested by David Beazley)
    1770                 :            : // Don't use unless you know what you are doing!
    1771                 :            : 
    1772                 :            : PyInterpreterState *
    1773                 :          0 : PyInterpreterState_Head(void)
    1774                 :            : {
    1775                 :          0 :     return _PyRuntime.interpreters.head;
    1776                 :            : }
    1777                 :            : 
    1778                 :            : PyInterpreterState *
    1779                 :          0 : PyInterpreterState_Main(void)
    1780                 :            : {
    1781                 :          0 :     return _PyInterpreterState_Main();
    1782                 :            : }
    1783                 :            : 
    1784                 :            : PyInterpreterState *
    1785                 :          0 : PyInterpreterState_Next(PyInterpreterState *interp) {
    1786                 :          0 :     return interp->next;
    1787                 :            : }
    1788                 :            : 
    1789                 :            : PyThreadState *
    1790                 :          1 : PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
    1791                 :          1 :     return interp->threads.head;
    1792                 :            : }
    1793                 :            : 
    1794                 :            : PyThreadState *
    1795                 :          1 : PyThreadState_Next(PyThreadState *tstate) {
    1796                 :          1 :     return tstate->next;
    1797                 :            : }
    1798                 :            : 
    1799                 :            : 
    1800                 :            : /********************************************/
    1801                 :            : /* reporting execution state of all threads */
    1802                 :            : /********************************************/
    1803                 :            : 
    1804                 :            : /* The implementation of sys._current_frames().  This is intended to be
    1805                 :            :    called with the GIL held, as it will be when called via
    1806                 :            :    sys._current_frames().  It's possible it would work fine even without
    1807                 :            :    the GIL held, but haven't thought enough about that.
    1808                 :            : */
    1809                 :            : PyObject *
    1810                 :          0 : _PyThread_CurrentFrames(void)
    1811                 :            : {
    1812                 :          0 :     _PyRuntimeState *runtime = &_PyRuntime;
    1813                 :          0 :     PyThreadState *tstate = current_fast_get(runtime);
    1814         [ #  # ]:          0 :     if (_PySys_Audit(tstate, "sys._current_frames", NULL) < 0) {
    1815                 :          0 :         return NULL;
    1816                 :            :     }
    1817                 :            : 
    1818                 :          0 :     PyObject *result = PyDict_New();
    1819         [ #  # ]:          0 :     if (result == NULL) {
    1820                 :          0 :         return NULL;
    1821                 :            :     }
    1822                 :            : 
    1823                 :            :     /* for i in all interpreters:
    1824                 :            :      *     for t in all of i's thread states:
    1825                 :            :      *          if t's frame isn't NULL, map t's id to its frame
    1826                 :            :      * Because these lists can mutate even when the GIL is held, we
    1827                 :            :      * need to grab head_mutex for the duration.
    1828                 :            :      */
    1829                 :          0 :     HEAD_LOCK(runtime);
    1830                 :            :     PyInterpreterState *i;
    1831         [ #  # ]:          0 :     for (i = runtime->interpreters.head; i != NULL; i = i->next) {
    1832                 :            :         PyThreadState *t;
    1833         [ #  # ]:          0 :         for (t = i->threads.head; t != NULL; t = t->next) {
    1834                 :          0 :             _PyInterpreterFrame *frame = t->cframe->current_frame;
    1835                 :          0 :             frame = _PyFrame_GetFirstComplete(frame);
    1836         [ #  # ]:          0 :             if (frame == NULL) {
    1837                 :          0 :                 continue;
    1838                 :            :             }
    1839                 :          0 :             PyObject *id = PyLong_FromUnsignedLong(t->thread_id);
    1840         [ #  # ]:          0 :             if (id == NULL) {
    1841                 :          0 :                 goto fail;
    1842                 :            :             }
    1843                 :          0 :             PyObject *frameobj = (PyObject *)_PyFrame_GetFrameObject(frame);
    1844         [ #  # ]:          0 :             if (frameobj == NULL) {
    1845                 :          0 :                 Py_DECREF(id);
    1846                 :          0 :                 goto fail;
    1847                 :            :             }
    1848                 :          0 :             int stat = PyDict_SetItem(result, id, frameobj);
    1849                 :          0 :             Py_DECREF(id);
    1850         [ #  # ]:          0 :             if (stat < 0) {
    1851                 :          0 :                 goto fail;
    1852                 :            :             }
    1853                 :            :         }
    1854                 :            :     }
    1855                 :          0 :     goto done;
    1856                 :            : 
    1857                 :          0 : fail:
    1858         [ #  # ]:          0 :     Py_CLEAR(result);
    1859                 :            : 
    1860                 :          0 : done:
    1861                 :          0 :     HEAD_UNLOCK(runtime);
    1862                 :          0 :     return result;
    1863                 :            : }
    1864                 :            : 
    1865                 :            : /* The implementation of sys._current_exceptions().  This is intended to be
    1866                 :            :    called with the GIL held, as it will be when called via
    1867                 :            :    sys._current_exceptions().  It's possible it would work fine even without
    1868                 :            :    the GIL held, but haven't thought enough about that.
    1869                 :            : */
    1870                 :            : PyObject *
    1871                 :          0 : _PyThread_CurrentExceptions(void)
    1872                 :            : {
    1873                 :          0 :     _PyRuntimeState *runtime = &_PyRuntime;
    1874                 :          0 :     PyThreadState *tstate = current_fast_get(runtime);
    1875                 :            : 
    1876                 :          0 :     _Py_EnsureTstateNotNULL(tstate);
    1877                 :            : 
    1878         [ #  # ]:          0 :     if (_PySys_Audit(tstate, "sys._current_exceptions", NULL) < 0) {
    1879                 :          0 :         return NULL;
    1880                 :            :     }
    1881                 :            : 
    1882                 :          0 :     PyObject *result = PyDict_New();
    1883         [ #  # ]:          0 :     if (result == NULL) {
    1884                 :          0 :         return NULL;
    1885                 :            :     }
    1886                 :            : 
    1887                 :            :     /* for i in all interpreters:
    1888                 :            :      *     for t in all of i's thread states:
    1889                 :            :      *          if t's frame isn't NULL, map t's id to its frame
    1890                 :            :      * Because these lists can mutate even when the GIL is held, we
    1891                 :            :      * need to grab head_mutex for the duration.
    1892                 :            :      */
    1893                 :          0 :     HEAD_LOCK(runtime);
    1894                 :            :     PyInterpreterState *i;
    1895         [ #  # ]:          0 :     for (i = runtime->interpreters.head; i != NULL; i = i->next) {
    1896                 :            :         PyThreadState *t;
    1897         [ #  # ]:          0 :         for (t = i->threads.head; t != NULL; t = t->next) {
    1898                 :          0 :             _PyErr_StackItem *err_info = _PyErr_GetTopmostException(t);
    1899         [ #  # ]:          0 :             if (err_info == NULL) {
    1900                 :          0 :                 continue;
    1901                 :            :             }
    1902                 :          0 :             PyObject *id = PyLong_FromUnsignedLong(t->thread_id);
    1903         [ #  # ]:          0 :             if (id == NULL) {
    1904                 :          0 :                 goto fail;
    1905                 :            :             }
    1906                 :          0 :             PyObject *exc_info = _PyErr_StackItemToExcInfoTuple(err_info);
    1907         [ #  # ]:          0 :             if (exc_info == NULL) {
    1908                 :          0 :                 Py_DECREF(id);
    1909                 :          0 :                 goto fail;
    1910                 :            :             }
    1911                 :          0 :             int stat = PyDict_SetItem(result, id, exc_info);
    1912                 :          0 :             Py_DECREF(id);
    1913                 :          0 :             Py_DECREF(exc_info);
    1914         [ #  # ]:          0 :             if (stat < 0) {
    1915                 :          0 :                 goto fail;
    1916                 :            :             }
    1917                 :            :         }
    1918                 :            :     }
    1919                 :          0 :     goto done;
    1920                 :            : 
    1921                 :          0 : fail:
    1922         [ #  # ]:          0 :     Py_CLEAR(result);
    1923                 :            : 
    1924                 :          0 : done:
    1925                 :          0 :     HEAD_UNLOCK(runtime);
    1926                 :          0 :     return result;
    1927                 :            : }
    1928                 :            : 
    1929                 :            : 
    1930                 :            : /***********************************/
    1931                 :            : /* Python "auto thread state" API. */
    1932                 :            : /***********************************/
    1933                 :            : 
    1934                 :            : /* Internal initialization/finalization functions called by
    1935                 :            :    Py_Initialize/Py_FinalizeEx
    1936                 :            : */
    1937                 :            : PyStatus
    1938                 :         29 : _PyGILState_Init(PyInterpreterState *interp)
    1939                 :            : {
    1940         [ -  + ]:         29 :     if (!_Py_IsMainInterpreter(interp)) {
    1941                 :            :         /* Currently, PyGILState is shared by all interpreters. The main
    1942                 :            :          * interpreter is responsible to initialize it. */
    1943                 :          0 :         return _PyStatus_OK();
    1944                 :            :     }
    1945                 :         29 :     _PyRuntimeState *runtime = interp->runtime;
    1946                 :            :     assert(gilstate_tss_get(runtime) == NULL);
    1947                 :            :     assert(runtime->gilstate.autoInterpreterState == NULL);
    1948                 :         29 :     runtime->gilstate.autoInterpreterState = interp;
    1949                 :         29 :     return _PyStatus_OK();
    1950                 :            : }
    1951                 :            : 
    1952                 :            : void
    1953                 :         25 : _PyGILState_Fini(PyInterpreterState *interp)
    1954                 :            : {
    1955         [ -  + ]:         25 :     if (!_Py_IsMainInterpreter(interp)) {
    1956                 :            :         /* Currently, PyGILState is shared by all interpreters. The main
    1957                 :            :          * interpreter is responsible to initialize it. */
    1958                 :          0 :         return;
    1959                 :            :     }
    1960                 :         25 :     interp->runtime->gilstate.autoInterpreterState = NULL;
    1961                 :            : }
    1962                 :            : 
    1963                 :            : 
    1964                 :            : // XXX Drop this.
    1965                 :            : PyStatus
    1966                 :         29 : _PyGILState_SetTstate(PyThreadState *tstate)
    1967                 :            : {
    1968                 :            :     /* must init with valid states */
    1969                 :            :     assert(tstate != NULL);
    1970                 :            :     assert(tstate->interp != NULL);
    1971                 :            : 
    1972         [ -  + ]:         29 :     if (!_Py_IsMainInterpreter(tstate->interp)) {
    1973                 :            :         /* Currently, PyGILState is shared by all interpreters. The main
    1974                 :            :          * interpreter is responsible to initialize it. */
    1975                 :          0 :         return _PyStatus_OK();
    1976                 :            :     }
    1977                 :            : 
    1978                 :            : #ifndef NDEBUG
    1979                 :            :     _PyRuntimeState *runtime = tstate->interp->runtime;
    1980                 :            : 
    1981                 :            :     assert(runtime->gilstate.autoInterpreterState == tstate->interp);
    1982                 :            :     assert(gilstate_tss_get(runtime) == tstate);
    1983                 :            :     assert(tstate->gilstate_counter == 1);
    1984                 :            : #endif
    1985                 :            : 
    1986                 :         29 :     return _PyStatus_OK();
    1987                 :            : }
    1988                 :            : 
    1989                 :            : PyInterpreterState *
    1990                 :          0 : _PyGILState_GetInterpreterStateUnsafe(void)
    1991                 :            : {
    1992                 :          0 :     return _PyRuntime.gilstate.autoInterpreterState;
    1993                 :            : }
    1994                 :            : 
    1995                 :            : /* The public functions */
    1996                 :            : 
    1997                 :            : PyThreadState *
    1998                 :          0 : PyGILState_GetThisThreadState(void)
    1999                 :            : {
    2000                 :          0 :     _PyRuntimeState *runtime = &_PyRuntime;
    2001         [ #  # ]:          0 :     if (!gilstate_tss_initialized(runtime)) {
    2002                 :          0 :         return NULL;
    2003                 :            :     }
    2004                 :          0 :     return gilstate_tss_get(runtime);
    2005                 :            : }
    2006                 :            : 
    2007                 :            : int
    2008                 :          0 : PyGILState_Check(void)
    2009                 :            : {
    2010                 :          0 :     _PyRuntimeState *runtime = &_PyRuntime;
    2011         [ #  # ]:          0 :     if (!runtime->gilstate.check_enabled) {
    2012                 :          0 :         return 1;
    2013                 :            :     }
    2014                 :            : 
    2015         [ #  # ]:          0 :     if (!gilstate_tss_initialized(runtime)) {
    2016                 :          0 :         return 1;
    2017                 :            :     }
    2018                 :            : 
    2019                 :          0 :     PyThreadState *tstate = current_fast_get(runtime);
    2020         [ #  # ]:          0 :     if (tstate == NULL) {
    2021                 :          0 :         return 0;
    2022                 :            :     }
    2023                 :            : 
    2024                 :          0 :     return (tstate == gilstate_tss_get(runtime));
    2025                 :            : }
    2026                 :            : 
    2027                 :            : PyGILState_STATE
    2028                 :          0 : PyGILState_Ensure(void)
    2029                 :            : {
    2030                 :          0 :     _PyRuntimeState *runtime = &_PyRuntime;
    2031                 :            : 
    2032                 :            :     /* Note that we do not auto-init Python here - apart from
    2033                 :            :        potential races with 2 threads auto-initializing, pep-311
    2034                 :            :        spells out other issues.  Embedders are expected to have
    2035                 :            :        called Py_Initialize(). */
    2036                 :            : 
    2037                 :            :     /* Ensure that _PyEval_InitThreads() and _PyGILState_Init() have been
    2038                 :            :        called by Py_Initialize() */
    2039                 :            :     assert(_PyEval_ThreadsInitialized(runtime));
    2040                 :            :     assert(gilstate_tss_initialized(runtime));
    2041                 :            :     assert(runtime->gilstate.autoInterpreterState != NULL);
    2042                 :            : 
    2043                 :          0 :     PyThreadState *tcur = gilstate_tss_get(runtime);
    2044                 :            :     int has_gil;
    2045         [ #  # ]:          0 :     if (tcur == NULL) {
    2046                 :            :         /* Create a new Python thread state for this thread */
    2047                 :          0 :         tcur = new_threadstate(runtime->gilstate.autoInterpreterState);
    2048         [ #  # ]:          0 :         if (tcur == NULL) {
    2049                 :          0 :             Py_FatalError("Couldn't create thread-state for new thread");
    2050                 :            :         }
    2051                 :          0 :         bind_tstate(tcur);
    2052                 :          0 :         bind_gilstate_tstate(tcur);
    2053                 :            : 
    2054                 :            :         /* This is our thread state!  We'll need to delete it in the
    2055                 :            :            matching call to PyGILState_Release(). */
    2056                 :            :         assert(tcur->gilstate_counter == 1);
    2057                 :          0 :         tcur->gilstate_counter = 0;
    2058                 :          0 :         has_gil = 0; /* new thread state is never current */
    2059                 :            :     }
    2060                 :            :     else {
    2061                 :          0 :         has_gil = holds_gil(tcur);
    2062                 :            :     }
    2063                 :            : 
    2064         [ #  # ]:          0 :     if (!has_gil) {
    2065                 :          0 :         PyEval_RestoreThread(tcur);
    2066                 :            :     }
    2067                 :            : 
    2068                 :            :     /* Update our counter in the thread-state - no need for locks:
    2069                 :            :        - tcur will remain valid as we hold the GIL.
    2070                 :            :        - the counter is safe as we are the only thread "allowed"
    2071                 :            :          to modify this value
    2072                 :            :     */
    2073                 :          0 :     ++tcur->gilstate_counter;
    2074                 :            : 
    2075                 :          0 :     return has_gil ? PyGILState_LOCKED : PyGILState_UNLOCKED;
    2076                 :            : }
    2077                 :            : 
    2078                 :            : void
    2079                 :          0 : PyGILState_Release(PyGILState_STATE oldstate)
    2080                 :            : {
    2081                 :          0 :     _PyRuntimeState *runtime = &_PyRuntime;
    2082                 :          0 :     PyThreadState *tstate = gilstate_tss_get(runtime);
    2083         [ #  # ]:          0 :     if (tstate == NULL) {
    2084                 :          0 :         Py_FatalError("auto-releasing thread-state, "
    2085                 :            :                       "but no thread-state for this thread");
    2086                 :            :     }
    2087                 :            : 
    2088                 :            :     /* We must hold the GIL and have our thread state current */
    2089                 :            :     /* XXX - remove the check - the assert should be fine,
    2090                 :            :        but while this is very new (April 2003), the extra check
    2091                 :            :        by release-only users can't hurt.
    2092                 :            :     */
    2093         [ #  # ]:          0 :     if (!holds_gil(tstate)) {
    2094                 :          0 :         _Py_FatalErrorFormat(__func__,
    2095                 :            :                              "thread state %p must be current when releasing",
    2096                 :            :                              tstate);
    2097                 :            :     }
    2098                 :            :     assert(holds_gil(tstate));
    2099                 :          0 :     --tstate->gilstate_counter;
    2100                 :            :     assert(tstate->gilstate_counter >= 0); /* illegal counter value */
    2101                 :            : 
    2102                 :            :     /* If we're going to destroy this thread-state, we must
    2103                 :            :      * clear it while the GIL is held, as destructors may run.
    2104                 :            :      */
    2105         [ #  # ]:          0 :     if (tstate->gilstate_counter == 0) {
    2106                 :            :         /* can't have been locked when we created it */
    2107                 :            :         assert(oldstate == PyGILState_UNLOCKED);
    2108                 :            :         // XXX Unbind tstate here.
    2109                 :          0 :         PyThreadState_Clear(tstate);
    2110                 :            :         /* Delete the thread-state.  Note this releases the GIL too!
    2111                 :            :          * It's vital that the GIL be held here, to avoid shutdown
    2112                 :            :          * races; see bugs 225673 and 1061968 (that nasty bug has a
    2113                 :            :          * habit of coming back).
    2114                 :            :          */
    2115                 :            :         assert(current_fast_get(runtime) == tstate);
    2116                 :          0 :         _PyThreadState_DeleteCurrent(tstate);
    2117                 :            :     }
    2118                 :            :     /* Release the lock if necessary */
    2119         [ #  # ]:          0 :     else if (oldstate == PyGILState_UNLOCKED) {
    2120                 :          0 :         PyEval_SaveThread();
    2121                 :            :     }
    2122                 :          0 : }
    2123                 :            : 
    2124                 :            : 
    2125                 :            : /**************************/
    2126                 :            : /* cross-interpreter data */
    2127                 :            : /**************************/
    2128                 :            : 
    2129                 :            : /* cross-interpreter data */
    2130                 :            : 
    2131                 :            : static inline void
    2132                 :          0 : _xidata_init(_PyCrossInterpreterData *data)
    2133                 :            : {
    2134                 :            :     // If the value is being reused
    2135                 :            :     // then _xidata_clear() should have been called already.
    2136                 :            :     assert(data->data == NULL);
    2137                 :            :     assert(data->obj == NULL);
    2138                 :          0 :     *data = (_PyCrossInterpreterData){0};
    2139                 :          0 :     data->interp = -1;
    2140                 :          0 : }
    2141                 :            : 
    2142                 :            : static inline void
    2143                 :          0 : _xidata_clear(_PyCrossInterpreterData *data)
    2144                 :            : {
    2145         [ #  # ]:          0 :     if (data->free != NULL) {
    2146                 :          0 :         data->free(data->data);
    2147                 :            :     }
    2148                 :          0 :     data->data = NULL;
    2149         [ #  # ]:          0 :     Py_CLEAR(data->obj);
    2150                 :          0 : }
    2151                 :            : 
    2152                 :            : void
    2153                 :          0 : _PyCrossInterpreterData_Init(_PyCrossInterpreterData *data,
    2154                 :            :                              PyInterpreterState *interp,
    2155                 :            :                              void *shared, PyObject *obj,
    2156                 :            :                              xid_newobjectfunc new_object)
    2157                 :            : {
    2158                 :            :     assert(data != NULL);
    2159                 :            :     assert(new_object != NULL);
    2160                 :          0 :     _xidata_init(data);
    2161                 :          0 :     data->data = shared;
    2162         [ #  # ]:          0 :     if (obj != NULL) {
    2163                 :            :         assert(interp != NULL);
    2164                 :            :         // released in _PyCrossInterpreterData_Clear()
    2165                 :          0 :         data->obj = Py_NewRef(obj);
    2166                 :            :     }
    2167                 :            :     // Ideally every object would know its owning interpreter.
    2168                 :            :     // Until then, we have to rely on the caller to identify it
    2169                 :            :     // (but we don't need it in all cases).
    2170         [ #  # ]:          0 :     data->interp = (interp != NULL) ? interp->id : -1;
    2171                 :          0 :     data->new_object = new_object;
    2172                 :          0 : }
    2173                 :            : 
    2174                 :            : int
    2175                 :          0 : _PyCrossInterpreterData_InitWithSize(_PyCrossInterpreterData *data,
    2176                 :            :                                      PyInterpreterState *interp,
    2177                 :            :                                      const size_t size, PyObject *obj,
    2178                 :            :                                      xid_newobjectfunc new_object)
    2179                 :            : {
    2180                 :            :     assert(size > 0);
    2181                 :            :     // For now we always free the shared data in the same interpreter
    2182                 :            :     // where it was allocated, so the interpreter is required.
    2183                 :            :     assert(interp != NULL);
    2184                 :          0 :     _PyCrossInterpreterData_Init(data, interp, NULL, obj, new_object);
    2185                 :          0 :     data->data = PyMem_Malloc(size);
    2186         [ #  # ]:          0 :     if (data->data == NULL) {
    2187                 :          0 :         return -1;
    2188                 :            :     }
    2189                 :          0 :     data->free = PyMem_Free;
    2190                 :          0 :     return 0;
    2191                 :            : }
    2192                 :            : 
    2193                 :            : void
    2194                 :          0 : _PyCrossInterpreterData_Clear(PyInterpreterState *interp,
    2195                 :            :                               _PyCrossInterpreterData *data)
    2196                 :            : {
    2197                 :            :     assert(data != NULL);
    2198                 :            :     // This must be called in the owning interpreter.
    2199                 :            :     assert(interp == NULL || data->interp == interp->id);
    2200                 :          0 :     _xidata_clear(data);
    2201                 :          0 : }
    2202                 :            : 
    2203                 :            : static int
    2204                 :          0 : _check_xidata(PyThreadState *tstate, _PyCrossInterpreterData *data)
    2205                 :            : {
    2206                 :            :     // data->data can be anything, including NULL, so we don't check it.
    2207                 :            : 
    2208                 :            :     // data->obj may be NULL, so we don't check it.
    2209                 :            : 
    2210         [ #  # ]:          0 :     if (data->interp < 0) {
    2211                 :          0 :         _PyErr_SetString(tstate, PyExc_SystemError, "missing interp");
    2212                 :          0 :         return -1;
    2213                 :            :     }
    2214                 :            : 
    2215         [ #  # ]:          0 :     if (data->new_object == NULL) {
    2216                 :          0 :         _PyErr_SetString(tstate, PyExc_SystemError, "missing new_object func");
    2217                 :          0 :         return -1;
    2218                 :            :     }
    2219                 :            : 
    2220                 :            :     // data->free may be NULL, so we don't check it.
    2221                 :            : 
    2222                 :          0 :     return 0;
    2223                 :            : }
    2224                 :            : 
    2225                 :            : crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
    2226                 :            : 
    2227                 :            : /* This is a separate func from _PyCrossInterpreterData_Lookup in order
    2228                 :            :    to keep the registry code separate. */
    2229                 :            : static crossinterpdatafunc
    2230                 :          0 : _lookup_getdata(PyObject *obj)
    2231                 :            : {
    2232                 :          0 :     crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
    2233   [ #  #  #  # ]:          0 :     if (getdata == NULL && PyErr_Occurred() == 0)
    2234                 :          0 :         PyErr_Format(PyExc_ValueError,
    2235                 :            :                      "%S does not support cross-interpreter data", obj);
    2236                 :          0 :     return getdata;
    2237                 :            : }
    2238                 :            : 
    2239                 :            : int
    2240                 :          0 : _PyObject_CheckCrossInterpreterData(PyObject *obj)
    2241                 :            : {
    2242                 :          0 :     crossinterpdatafunc getdata = _lookup_getdata(obj);
    2243         [ #  # ]:          0 :     if (getdata == NULL) {
    2244                 :          0 :         return -1;
    2245                 :            :     }
    2246                 :          0 :     return 0;
    2247                 :            : }
    2248                 :            : 
    2249                 :            : int
    2250                 :          0 : _PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
    2251                 :            : {
    2252                 :          0 :     _PyRuntimeState *runtime = &_PyRuntime;
    2253                 :          0 :     PyThreadState *tstate = current_fast_get(runtime);
    2254                 :            : #ifdef Py_DEBUG
    2255                 :            :     // The caller must hold the GIL
    2256                 :            :     _Py_EnsureTstateNotNULL(tstate);
    2257                 :            : #endif
    2258                 :          0 :     PyInterpreterState *interp = tstate->interp;
    2259                 :            : 
    2260                 :            :     // Reset data before re-populating.
    2261                 :          0 :     *data = (_PyCrossInterpreterData){0};
    2262                 :          0 :     data->interp = -1;
    2263                 :            : 
    2264                 :            :     // Call the "getdata" func for the object.
    2265                 :          0 :     Py_INCREF(obj);
    2266                 :          0 :     crossinterpdatafunc getdata = _lookup_getdata(obj);
    2267         [ #  # ]:          0 :     if (getdata == NULL) {
    2268                 :          0 :         Py_DECREF(obj);
    2269                 :          0 :         return -1;
    2270                 :            :     }
    2271                 :          0 :     int res = getdata(tstate, obj, data);
    2272                 :          0 :     Py_DECREF(obj);
    2273         [ #  # ]:          0 :     if (res != 0) {
    2274                 :          0 :         return -1;
    2275                 :            :     }
    2276                 :            : 
    2277                 :            :     // Fill in the blanks and validate the result.
    2278                 :          0 :     data->interp = interp->id;
    2279         [ #  # ]:          0 :     if (_check_xidata(tstate, data) != 0) {
    2280                 :          0 :         (void)_PyCrossInterpreterData_Release(data);
    2281                 :          0 :         return -1;
    2282                 :            :     }
    2283                 :            : 
    2284                 :          0 :     return 0;
    2285                 :            : }
    2286                 :            : 
    2287                 :            : PyObject *
    2288                 :          0 : _PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
    2289                 :            : {
    2290                 :          0 :     return data->new_object(data);
    2291                 :            : }
    2292                 :            : 
    2293                 :            : typedef void (*releasefunc)(PyInterpreterState *, void *);
    2294                 :            : 
    2295                 :            : static void
    2296                 :          0 : _call_in_interpreter(PyInterpreterState *interp, releasefunc func, void *arg)
    2297                 :            : {
    2298                 :            :     /* We would use Py_AddPendingCall() if it weren't specific to the
    2299                 :            :      * main interpreter (see bpo-33608).  In the meantime we take a
    2300                 :            :      * naive approach.
    2301                 :            :      */
    2302                 :          0 :     _PyRuntimeState *runtime = interp->runtime;
    2303                 :          0 :     PyThreadState *save_tstate = NULL;
    2304         [ #  # ]:          0 :     if (interp != current_fast_get(runtime)->interp) {
    2305                 :            :         // XXX Using the "head" thread isn't strictly correct.
    2306                 :          0 :         PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
    2307                 :            :         // XXX Possible GILState issues?
    2308                 :          0 :         save_tstate = _PyThreadState_Swap(runtime, tstate);
    2309                 :            :     }
    2310                 :            : 
    2311                 :            :     // XXX Once the GIL is per-interpreter, this should be called with the
    2312                 :            :     // calling interpreter's GIL released and the target interpreter's held.
    2313                 :          0 :     func(interp, arg);
    2314                 :            : 
    2315                 :            :     // Switch back.
    2316         [ #  # ]:          0 :     if (save_tstate != NULL) {
    2317                 :          0 :         _PyThreadState_Swap(runtime, save_tstate);
    2318                 :            :     }
    2319                 :          0 : }
    2320                 :            : 
    2321                 :            : int
    2322                 :          0 : _PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
    2323                 :            : {
    2324   [ #  #  #  # ]:          0 :     if (data->free == NULL && data->obj == NULL) {
    2325                 :            :         // Nothing to release!
    2326                 :          0 :         data->data = NULL;
    2327                 :          0 :         return 0;
    2328                 :            :     }
    2329                 :            : 
    2330                 :            :     // Switch to the original interpreter.
    2331                 :          0 :     PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
    2332         [ #  # ]:          0 :     if (interp == NULL) {
    2333                 :            :         // The interpreter was already destroyed.
    2334                 :            :         // This function shouldn't have been called.
    2335                 :            :         // XXX Someone leaked some memory...
    2336                 :            :         assert(PyErr_Occurred());
    2337                 :          0 :         return -1;
    2338                 :            :     }
    2339                 :            : 
    2340                 :            :     // "Release" the data and/or the object.
    2341                 :          0 :     _call_in_interpreter(interp,
    2342                 :            :                          (releasefunc)_PyCrossInterpreterData_Clear, data);
    2343                 :          0 :     return 0;
    2344                 :            : }
    2345                 :            : 
    2346                 :            : /* registry of {type -> crossinterpdatafunc} */
    2347                 :            : 
    2348                 :            : /* For now we use a global registry of shareable classes.  An
    2349                 :            :    alternative would be to add a tp_* slot for a class's
    2350                 :            :    crossinterpdatafunc. It would be simpler and more efficient. */
    2351                 :            : 
    2352                 :            : static int
    2353                 :          5 : _xidregistry_add_type(struct _xidregistry *xidregistry, PyTypeObject *cls,
    2354                 :            :                  crossinterpdatafunc getdata)
    2355                 :            : {
    2356                 :            :     // Note that we effectively replace already registered classes
    2357                 :            :     // rather than failing.
    2358                 :          5 :     struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
    2359         [ -  + ]:          5 :     if (newhead == NULL) {
    2360                 :          0 :         return -1;
    2361                 :            :     }
    2362                 :            :     // XXX Assign a callback to clear the entry from the registry?
    2363                 :          5 :     newhead->cls = PyWeakref_NewRef((PyObject *)cls, NULL);
    2364         [ -  + ]:          5 :     if (newhead->cls == NULL) {
    2365                 :          0 :         PyMem_RawFree(newhead);
    2366                 :          0 :         return -1;
    2367                 :            :     }
    2368                 :          5 :     newhead->getdata = getdata;
    2369                 :          5 :     newhead->prev = NULL;
    2370                 :          5 :     newhead->next = xidregistry->head;
    2371         [ +  + ]:          5 :     if (newhead->next != NULL) {
    2372                 :          4 :         newhead->next->prev = newhead;
    2373                 :            :     }
    2374                 :          5 :     xidregistry->head = newhead;
    2375                 :          5 :     return 0;
    2376                 :            : }
    2377                 :            : 
    2378                 :            : static struct _xidregitem *
    2379                 :          1 : _xidregistry_remove_entry(struct _xidregistry *xidregistry,
    2380                 :            :                           struct _xidregitem *entry)
    2381                 :            : {
    2382                 :          1 :     struct _xidregitem *next = entry->next;
    2383         [ -  + ]:          1 :     if (entry->prev != NULL) {
    2384                 :            :         assert(entry->prev->next == entry);
    2385                 :          0 :         entry->prev->next = next;
    2386                 :            :     }
    2387                 :            :     else {
    2388                 :            :         assert(xidregistry->head == entry);
    2389                 :          1 :         xidregistry->head = next;
    2390                 :            :     }
    2391         [ +  - ]:          1 :     if (next != NULL) {
    2392                 :          1 :         next->prev = entry->prev;
    2393                 :            :     }
    2394                 :          1 :     Py_DECREF(entry->cls);
    2395                 :          1 :     PyMem_RawFree(entry);
    2396                 :          1 :     return next;
    2397                 :            : }
    2398                 :            : 
    2399                 :            : static struct _xidregitem *
    2400                 :          1 : _xidregistry_find_type(struct _xidregistry *xidregistry, PyTypeObject *cls)
    2401                 :            : {
    2402                 :          1 :     struct _xidregitem *cur = xidregistry->head;
    2403         [ +  + ]:          6 :     while (cur != NULL) {
    2404                 :          5 :         PyObject *registered = PyWeakref_GetObject(cur->cls);
    2405         [ +  + ]:          5 :         if (registered == Py_None) {
    2406                 :            :             // The weakly ref'ed object was freed.
    2407                 :          1 :             cur = _xidregistry_remove_entry(xidregistry, cur);
    2408                 :            :         }
    2409                 :            :         else {
    2410                 :            :             assert(PyType_Check(registered));
    2411         [ -  + ]:          4 :             if (registered == (PyObject *)cls) {
    2412                 :          0 :                 return cur;
    2413                 :            :             }
    2414                 :          4 :             cur = cur->next;
    2415                 :            :         }
    2416                 :            :     }
    2417                 :          1 :     return NULL;
    2418                 :            : }
    2419                 :            : 
    2420                 :            : static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
    2421                 :            : 
    2422                 :            : int
    2423                 :          1 : _PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
    2424                 :            :                                        crossinterpdatafunc getdata)
    2425                 :            : {
    2426         [ -  + ]:          1 :     if (!PyType_Check(cls)) {
    2427                 :          0 :         PyErr_Format(PyExc_ValueError, "only classes may be registered");
    2428                 :          0 :         return -1;
    2429                 :            :     }
    2430         [ -  + ]:          1 :     if (getdata == NULL) {
    2431                 :          0 :         PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
    2432                 :          0 :         return -1;
    2433                 :            :     }
    2434                 :            : 
    2435                 :          1 :     struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
    2436                 :          1 :     PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
    2437         [ +  - ]:          1 :     if (xidregistry->head == NULL) {
    2438                 :          1 :         _register_builtins_for_crossinterpreter_data(xidregistry);
    2439                 :            :     }
    2440                 :          1 :     int res = _xidregistry_add_type(xidregistry, cls, getdata);
    2441                 :          1 :     PyThread_release_lock(xidregistry->mutex);
    2442                 :          1 :     return res;
    2443                 :            : }
    2444                 :            : 
    2445                 :            : int
    2446                 :          1 : _PyCrossInterpreterData_UnregisterClass(PyTypeObject *cls)
    2447                 :            : {
    2448                 :          1 :     int res = 0;
    2449                 :          1 :     struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
    2450                 :          1 :     PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
    2451                 :          1 :     struct _xidregitem *matched = _xidregistry_find_type(xidregistry, cls);
    2452         [ -  + ]:          1 :     if (matched != NULL) {
    2453                 :          0 :         (void)_xidregistry_remove_entry(xidregistry, matched);
    2454                 :          0 :         res = 1;
    2455                 :            :     }
    2456                 :          1 :     PyThread_release_lock(xidregistry->mutex);
    2457                 :          1 :     return res;
    2458                 :            : }
    2459                 :            : 
    2460                 :            : 
    2461                 :            : /* Cross-interpreter objects are looked up by exact match on the class.
    2462                 :            :    We can reassess this policy when we move from a global registry to a
    2463                 :            :    tp_* slot. */
    2464                 :            : 
    2465                 :            : crossinterpdatafunc
    2466                 :          0 : _PyCrossInterpreterData_Lookup(PyObject *obj)
    2467                 :            : {
    2468                 :          0 :     struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
    2469                 :          0 :     PyObject *cls = PyObject_Type(obj);
    2470                 :          0 :     PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
    2471         [ #  # ]:          0 :     if (xidregistry->head == NULL) {
    2472                 :          0 :         _register_builtins_for_crossinterpreter_data(xidregistry);
    2473                 :            :     }
    2474                 :          0 :     struct _xidregitem *matched = _xidregistry_find_type(xidregistry,
    2475                 :            :                                                          (PyTypeObject *)cls);
    2476                 :          0 :     Py_DECREF(cls);
    2477                 :          0 :     PyThread_release_lock(xidregistry->mutex);
    2478         [ #  # ]:          0 :     return matched != NULL ? matched->getdata : NULL;
    2479                 :            : }
    2480                 :            : 
    2481                 :            : /* cross-interpreter data for builtin types */
    2482                 :            : 
    2483                 :            : struct _shared_bytes_data {
    2484                 :            :     char *bytes;
    2485                 :            :     Py_ssize_t len;
    2486                 :            : };
    2487                 :            : 
    2488                 :            : static PyObject *
    2489                 :          0 : _new_bytes_object(_PyCrossInterpreterData *data)
    2490                 :            : {
    2491                 :          0 :     struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
    2492                 :          0 :     return PyBytes_FromStringAndSize(shared->bytes, shared->len);
    2493                 :            : }
    2494                 :            : 
    2495                 :            : static int
    2496                 :          0 : _bytes_shared(PyThreadState *tstate, PyObject *obj,
    2497                 :            :               _PyCrossInterpreterData *data)
    2498                 :            : {
    2499         [ #  # ]:          0 :     if (_PyCrossInterpreterData_InitWithSize(
    2500                 :            :             data, tstate->interp, sizeof(struct _shared_bytes_data), obj,
    2501                 :            :             _new_bytes_object
    2502                 :            :             ) < 0)
    2503                 :            :     {
    2504                 :          0 :         return -1;
    2505                 :            :     }
    2506                 :          0 :     struct _shared_bytes_data *shared = (struct _shared_bytes_data *)data->data;
    2507         [ #  # ]:          0 :     if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
    2508                 :          0 :         _PyCrossInterpreterData_Clear(tstate->interp, data);
    2509                 :          0 :         return -1;
    2510                 :            :     }
    2511                 :          0 :     return 0;
    2512                 :            : }
    2513                 :            : 
    2514                 :            : struct _shared_str_data {
    2515                 :            :     int kind;
    2516                 :            :     const void *buffer;
    2517                 :            :     Py_ssize_t len;
    2518                 :            : };
    2519                 :            : 
    2520                 :            : static PyObject *
    2521                 :          0 : _new_str_object(_PyCrossInterpreterData *data)
    2522                 :            : {
    2523                 :          0 :     struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
    2524                 :          0 :     return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
    2525                 :            : }
    2526                 :            : 
    2527                 :            : static int
    2528                 :          0 : _str_shared(PyThreadState *tstate, PyObject *obj,
    2529                 :            :             _PyCrossInterpreterData *data)
    2530                 :            : {
    2531         [ #  # ]:          0 :     if (_PyCrossInterpreterData_InitWithSize(
    2532                 :            :             data, tstate->interp, sizeof(struct _shared_str_data), obj,
    2533                 :            :             _new_str_object
    2534                 :            :             ) < 0)
    2535                 :            :     {
    2536                 :          0 :         return -1;
    2537                 :            :     }
    2538                 :          0 :     struct _shared_str_data *shared = (struct _shared_str_data *)data->data;
    2539                 :          0 :     shared->kind = PyUnicode_KIND(obj);
    2540                 :          0 :     shared->buffer = PyUnicode_DATA(obj);
    2541                 :          0 :     shared->len = PyUnicode_GET_LENGTH(obj);
    2542                 :          0 :     return 0;
    2543                 :            : }
    2544                 :            : 
    2545                 :            : static PyObject *
    2546                 :          0 : _new_long_object(_PyCrossInterpreterData *data)
    2547                 :            : {
    2548                 :          0 :     return PyLong_FromSsize_t((Py_ssize_t)(data->data));
    2549                 :            : }
    2550                 :            : 
    2551                 :            : static int
    2552                 :          0 : _long_shared(PyThreadState *tstate, PyObject *obj,
    2553                 :            :              _PyCrossInterpreterData *data)
    2554                 :            : {
    2555                 :            :     /* Note that this means the size of shareable ints is bounded by
    2556                 :            :      * sys.maxsize.  Hence on 32-bit architectures that is half the
    2557                 :            :      * size of maximum shareable ints on 64-bit.
    2558                 :            :      */
    2559                 :          0 :     Py_ssize_t value = PyLong_AsSsize_t(obj);
    2560   [ #  #  #  # ]:          0 :     if (value == -1 && PyErr_Occurred()) {
    2561         [ #  # ]:          0 :         if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
    2562                 :          0 :             PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
    2563                 :            :         }
    2564                 :          0 :         return -1;
    2565                 :            :     }
    2566                 :          0 :     _PyCrossInterpreterData_Init(data, tstate->interp, (void *)value, NULL,
    2567                 :            :             _new_long_object);
    2568                 :            :     // data->obj and data->free remain NULL
    2569                 :          0 :     return 0;
    2570                 :            : }
    2571                 :            : 
    2572                 :            : static PyObject *
    2573                 :          0 : _new_none_object(_PyCrossInterpreterData *data)
    2574                 :            : {
    2575                 :            :     // XXX Singleton refcounts are problematic across interpreters...
    2576                 :          0 :     return Py_NewRef(Py_None);
    2577                 :            : }
    2578                 :            : 
    2579                 :            : static int
    2580                 :          0 : _none_shared(PyThreadState *tstate, PyObject *obj,
    2581                 :            :              _PyCrossInterpreterData *data)
    2582                 :            : {
    2583                 :          0 :     _PyCrossInterpreterData_Init(data, tstate->interp, NULL, NULL,
    2584                 :            :             _new_none_object);
    2585                 :            :     // data->data, data->obj and data->free remain NULL
    2586                 :          0 :     return 0;
    2587                 :            : }
    2588                 :            : 
    2589                 :            : static void
    2590                 :          1 : _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
    2591                 :            : {
    2592                 :            :     // None
    2593         [ -  + ]:          1 :     if (_xidregistry_add_type(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
    2594                 :          0 :         Py_FatalError("could not register None for cross-interpreter sharing");
    2595                 :            :     }
    2596                 :            : 
    2597                 :            :     // int
    2598         [ -  + ]:          1 :     if (_xidregistry_add_type(xidregistry, &PyLong_Type, _long_shared) != 0) {
    2599                 :          0 :         Py_FatalError("could not register int for cross-interpreter sharing");
    2600                 :            :     }
    2601                 :            : 
    2602                 :            :     // bytes
    2603         [ -  + ]:          1 :     if (_xidregistry_add_type(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
    2604                 :          0 :         Py_FatalError("could not register bytes for cross-interpreter sharing");
    2605                 :            :     }
    2606                 :            : 
    2607                 :            :     // str
    2608         [ -  + ]:          1 :     if (_xidregistry_add_type(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
    2609                 :          0 :         Py_FatalError("could not register str for cross-interpreter sharing");
    2610                 :            :     }
    2611                 :          1 : }
    2612                 :            : 
    2613                 :            : 
    2614                 :            : _PyFrameEvalFunction
    2615                 :          0 : _PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
    2616                 :            : {
    2617         [ #  # ]:          0 :     if (interp->eval_frame == NULL) {
    2618                 :          0 :         return _PyEval_EvalFrameDefault;
    2619                 :            :     }
    2620                 :          0 :     return interp->eval_frame;
    2621                 :            : }
    2622                 :            : 
    2623                 :            : 
    2624                 :            : void
    2625                 :          0 : _PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp,
    2626                 :            :                                      _PyFrameEvalFunction eval_frame)
    2627                 :            : {
    2628         [ #  # ]:          0 :     if (eval_frame == _PyEval_EvalFrameDefault) {
    2629                 :          0 :         interp->eval_frame = NULL;
    2630                 :            :     }
    2631                 :            :     else {
    2632                 :          0 :         interp->eval_frame = eval_frame;
    2633                 :            :     }
    2634                 :          0 : }
    2635                 :            : 
    2636                 :            : 
    2637                 :            : const PyConfig*
    2638                 :      57673 : _PyInterpreterState_GetConfig(PyInterpreterState *interp)
    2639                 :            : {
    2640                 :      57673 :     return &interp->config;
    2641                 :            : }
    2642                 :            : 
    2643                 :            : 
    2644                 :            : int
    2645                 :          0 : _PyInterpreterState_GetConfigCopy(PyConfig *config)
    2646                 :            : {
    2647                 :          0 :     PyInterpreterState *interp = PyInterpreterState_Get();
    2648                 :            : 
    2649                 :          0 :     PyStatus status = _PyConfig_Copy(config, &interp->config);
    2650         [ #  # ]:          0 :     if (PyStatus_Exception(status)) {
    2651                 :          0 :         _PyErr_SetFromPyStatus(status);
    2652                 :          0 :         return -1;
    2653                 :            :     }
    2654                 :          0 :     return 0;
    2655                 :            : }
    2656                 :            : 
    2657                 :            : 
    2658                 :            : const PyConfig*
    2659                 :      31240 : _Py_GetConfig(void)
    2660                 :            : {
    2661                 :      31240 :     _PyRuntimeState *runtime = &_PyRuntime;
    2662                 :            :     assert(PyGILState_Check());
    2663                 :      31240 :     PyThreadState *tstate = current_fast_get(runtime);
    2664                 :      31240 :     _Py_EnsureTstateNotNULL(tstate);
    2665                 :      31240 :     return _PyInterpreterState_GetConfig(tstate->interp);
    2666                 :            : }
    2667                 :            : 
    2668                 :            : 
    2669                 :            : int
    2670                 :         20 : _PyInterpreterState_HasFeature(PyInterpreterState *interp, unsigned long feature)
    2671                 :            : {
    2672                 :         20 :     return ((interp->feature_flags & feature) != 0);
    2673                 :            : }
    2674                 :            : 
    2675                 :            : 
    2676                 :            : #define MINIMUM_OVERHEAD 1000
    2677                 :            : 
    2678                 :            : static PyObject **
    2679                 :         25 : push_chunk(PyThreadState *tstate, int size)
    2680                 :            : {
    2681                 :         25 :     int allocate_size = DATA_STACK_CHUNK_SIZE;
    2682         [ -  + ]:         25 :     while (allocate_size < (int)sizeof(PyObject*)*(size + MINIMUM_OVERHEAD)) {
    2683                 :          0 :         allocate_size *= 2;
    2684                 :            :     }
    2685                 :         25 :     _PyStackChunk *new = allocate_chunk(allocate_size, tstate->datastack_chunk);
    2686         [ -  + ]:         25 :     if (new == NULL) {
    2687                 :          0 :         return NULL;
    2688                 :            :     }
    2689         [ -  + ]:         25 :     if (tstate->datastack_chunk) {
    2690                 :          0 :         tstate->datastack_chunk->top = tstate->datastack_top -
    2691                 :          0 :                                        &tstate->datastack_chunk->data[0];
    2692                 :            :     }
    2693                 :         25 :     tstate->datastack_chunk = new;
    2694                 :         25 :     tstate->datastack_limit = (PyObject **)(((char *)new) + allocate_size);
    2695                 :            :     // When new is the "root" chunk (i.e. new->previous == NULL), we can keep
    2696                 :            :     // _PyThreadState_PopFrame from freeing it later by "skipping" over the
    2697                 :            :     // first element:
    2698                 :         25 :     PyObject **res = &new->data[new->previous == NULL];
    2699                 :         25 :     tstate->datastack_top = res + size;
    2700                 :         25 :     return res;
    2701                 :            : }
    2702                 :            : 
    2703                 :            : _PyInterpreterFrame *
    2704                 :    1424205 : _PyThreadState_PushFrame(PyThreadState *tstate, size_t size)
    2705                 :            : {
    2706                 :            :     assert(size < INT_MAX/sizeof(PyObject *));
    2707         [ +  + ]:    1424205 :     if (_PyThreadState_HasStackSpace(tstate, (int)size)) {
    2708                 :    1424180 :         _PyInterpreterFrame *res = (_PyInterpreterFrame *)tstate->datastack_top;
    2709                 :    1424180 :         tstate->datastack_top += size;
    2710                 :    1424180 :         return res;
    2711                 :            :     }
    2712                 :         25 :     return (_PyInterpreterFrame *)push_chunk(tstate, (int)size);
    2713                 :            : }
    2714                 :            : 
    2715                 :            : void
    2716                 :    3608148 : _PyThreadState_PopFrame(PyThreadState *tstate, _PyInterpreterFrame * frame)
    2717                 :            : {
    2718                 :            :     assert(tstate->datastack_chunk);
    2719                 :    3608148 :     PyObject **base = (PyObject **)frame;
    2720         [ -  + ]:    3608148 :     if (base == &tstate->datastack_chunk->data[0]) {
    2721                 :          0 :         _PyStackChunk *chunk = tstate->datastack_chunk;
    2722                 :          0 :         _PyStackChunk *previous = chunk->previous;
    2723                 :            :         // push_chunk ensures that the root chunk is never popped:
    2724                 :            :         assert(previous);
    2725                 :          0 :         tstate->datastack_top = &previous->data[previous->top];
    2726                 :          0 :         tstate->datastack_chunk = previous;
    2727                 :          0 :         _PyObject_VirtualFree(chunk, chunk->size);
    2728                 :          0 :         tstate->datastack_limit = (PyObject **)(((char *)previous) + previous->size);
    2729                 :            :     }
    2730                 :            :     else {
    2731                 :            :         assert(tstate->datastack_top);
    2732                 :            :         assert(tstate->datastack_top >= base);
    2733                 :    3608148 :         tstate->datastack_top = base;
    2734                 :            :     }
    2735                 :    3608148 : }
    2736                 :            : 
    2737                 :            : 
    2738                 :            : #ifdef __cplusplus
    2739                 :            : }
    2740                 :            : #endif

Generated by: LCOV version 1.14