]> git.ipfire.org Git - thirdparty/Python/cpython.git/commit
gh-100227: Make the Global PyModuleDef Cache Safe for Isolated Interpreters (gh-103084)
authorEric Snow <ericsnowcurrently@gmail.com>
Wed, 29 Mar 2023 23:15:43 +0000 (17:15 -0600)
committerGitHub <noreply@github.com>
Wed, 29 Mar 2023 23:15:43 +0000 (17:15 -0600)
commitdcd6f226d6596b25b6f4004058a67acabe012120
tree93ef65b5bdb0bb8b88431ada3e6f899b77613630
parent121057aa3600c4d4d392539aeb79e1b09fd5659d
gh-100227: Make the Global PyModuleDef Cache Safe for Isolated Interpreters (gh-103084)

Sharing mutable (or non-immortal) objects between interpreters is generally not safe.  We can work around that but not easily.
 There are two restrictions that are critical for objects that break interpreter isolation.

The first is that the object's state be guarded by a global lock.  For now the GIL meets this requirement, but a granular global lock is needed once we have a per-interpreter GIL.

The second restriction is that the object (and, for a container, its items) be deallocated/resized only when the interpreter in which it was allocated is the current one.  This is because every interpreter has (or will have, see gh-101660) its own object allocator.  Deallocating an object with a different allocator can cause crashes.

The dict for the cache of module defs is completely internal, which simplifies what we have to do to meet those requirements.  To do so, we do the following:

* add a mechanism for re-using a temporary thread state tied to the main interpreter in an arbitrary thread
   * add _PyRuntime.imports.extensions.main_tstate`
   * add _PyThreadState_InitDetached() and _PyThreadState_ClearDetached() (pystate.c)
   * add _PyThreadState_BindDetached() and _PyThreadState_UnbindDetached() (pystate.c)
* make sure the cache dict (_PyRuntime.imports.extensions.dict) and its items are all owned by the main interpreter)
* add a placeholder using for a granular global lock

Note that the cache is only used for legacy extension modules and not for multi-phase init modules.

https://github.com/python/cpython/issues/100227
Include/internal/pycore_import.h
Include/internal/pycore_pystate.h
Include/internal/pycore_runtime_init.h
Python/import.c
Python/pystate.c