1212#include " ../pytypes.h"
1313#include " smart_holder_sfinae_hooks_only.h"
1414
15+ // / Tracks the `internals` and `type_info` ABI version independent of the main library version.
16+ // /
17+ // / Some portions of the code use an ABI that is conditional depending on this
18+ // / version number. That allows ABI-breaking changes to be "pre-implemented".
19+ // / Once the default version number is incremented, the conditional logic that
20+ // / no longer applies can be removed. Additionally, users that need not
21+ // / maintain ABI compatibility can increase the version number in order to take
22+ // / advantage of any functionality/efficiency improvements that depend on the
23+ // / newer ABI.
24+ // /
25+ // / WARNING: If you choose to manually increase the ABI version, note that
26+ // / pybind11 may not be tested as thoroughly with a non-default ABI version, and
27+ // / further ABI-incompatible changes may be made before the ABI is officially
28+ // / changed to the new version.
29+ #ifndef PYBIND11_INTERNALS_VERSION
30+ # define PYBIND11_INTERNALS_VERSION 4
31+ #endif
32+
1533PYBIND11_NAMESPACE_BEGIN (PYBIND11_NAMESPACE)
1634
1735using ExceptionTranslator = void (*)(std::exception_ptr);
@@ -26,30 +44,58 @@ inline PyObject *make_object_base_type(PyTypeObject *metaclass);
2644// The old Python Thread Local Storage (TLS) API is deprecated in Python 3.7 in favor of the new
2745// Thread Specific Storage (TSS) API.
2846#if PY_VERSION_HEX >= 0x03070000
29- # define PYBIND11_TLS_KEY_INIT (var ) Py_tss_t *var = nullptr
30- # define PYBIND11_TLS_GET_VALUE (key ) PyThread_tss_get((key))
31- # define PYBIND11_TLS_REPLACE_VALUE (key, value ) PyThread_tss_set((key), (value))
32- # define PYBIND11_TLS_DELETE_VALUE (key ) PyThread_tss_set((key), nullptr )
33- # define PYBIND11_TLS_FREE (key ) PyThread_tss_free(key)
47+ // Avoid unnecessary allocation of `Py_tss_t`, since we cannot use
48+ // `Py_LIMITED_API` anyway.
49+ # if PYBIND11_INTERNALS_VERSION > 4
50+ # define PYBIND11_TLS_KEY_REF Py_tss_t &
51+ # ifdef __GNUC__
52+ // Clang on macOS warns due to `Py_tss_NEEDS_INIT` not specifying an initializer
53+ // for every field.
54+ # define PYBIND11_TLS_KEY_INIT (var ) \
55+ _Pragma (" GCC diagnostic push" ) /* */ \
56+ _Pragma(" GCC diagnostic ignored \" -Wmissing-field-initializers\" " ) /* */ \
57+ Py_tss_t var \
58+ = Py_tss_NEEDS_INIT; \
59+ _Pragma (" GCC diagnostic pop" )
60+ # else
61+ # define PYBIND11_TLS_KEY_INIT (var ) Py_tss_t var = Py_tss_NEEDS_INIT;
62+ # endif
63+ # define PYBIND11_TLS_KEY_CREATE (var ) (PyThread_tss_create(&(var)) == 0 )
64+ # define PYBIND11_TLS_GET_VALUE (key ) PyThread_tss_get(&(key))
65+ # define PYBIND11_TLS_REPLACE_VALUE (key, value ) PyThread_tss_set(&(key), (value))
66+ # define PYBIND11_TLS_DELETE_VALUE (key ) PyThread_tss_set(&(key), nullptr )
67+ # define PYBIND11_TLS_FREE (key ) PyThread_tss_delete(&(key))
68+ # else
69+ # define PYBIND11_TLS_KEY_REF Py_tss_t *
70+ # define PYBIND11_TLS_KEY_INIT (var ) Py_tss_t *var = nullptr ;
71+ # define PYBIND11_TLS_KEY_CREATE (var ) \
72+ (((var) = PyThread_tss_alloc()) != nullptr && (PyThread_tss_create((var)) == 0 ))
73+ # define PYBIND11_TLS_GET_VALUE (key ) PyThread_tss_get((key))
74+ # define PYBIND11_TLS_REPLACE_VALUE (key, value ) PyThread_tss_set((key), (value))
75+ # define PYBIND11_TLS_DELETE_VALUE (key ) PyThread_tss_set((key), nullptr )
76+ # define PYBIND11_TLS_FREE (key ) PyThread_tss_free(key)
77+ # endif
3478#else
35- // Usually an int but a long on Cygwin64 with Python 3.x
36- # define PYBIND11_TLS_KEY_INIT (var ) decltype (PyThread_create_key()) var = 0
79+ // Usually an int but a long on Cygwin64 with Python 3.x
80+ # define PYBIND11_TLS_KEY_REF decltype (PyThread_create_key())
81+ # define PYBIND11_TLS_KEY_INIT (var ) PYBIND11_TLS_KEY_REF var = 0 ;
82+ # define PYBIND11_TLS_KEY_CREATE (var ) (((var) = PyThread_create_key()) != -1 )
3783# define PYBIND11_TLS_GET_VALUE (key ) PyThread_get_key_value((key))
38- # if PY_MAJOR_VERSION < 3
39- # define PYBIND11_TLS_DELETE_VALUE (key ) \
40- PyThread_delete_key_value (key)
41- # define PYBIND11_TLS_REPLACE_VALUE (key, value ) \
42- do { \
43- PyThread_delete_key_value ((key)); \
44- PyThread_set_key_value ((key), (value)); \
45- } while (false )
84+ # if PY_MAJOR_VERSION < 3 || defined(PYPY_VERSION)
85+ // On CPython < 3.4 and on PyPy, `PyThread_set_key_value` strangely does not set
86+ // the value if it has already been set. Instead, it must first be deleted and
87+ // then set again.
88+ # define PYBIND11_TLS_DELETE_VALUE (key ) PyThread_delete_key_value(key)
89+ # define PYBIND11_TLS_REPLACE_VALUE (key, value ) \
90+ do { \
91+ PyThread_delete_key_value ((key)); \
92+ PyThread_set_key_value ((key), (value)); \
93+ } while (false )
4694# else
47- # define PYBIND11_TLS_DELETE_VALUE (key ) \
48- PyThread_set_key_value ((key), nullptr)
49- # define PYBIND11_TLS_REPLACE_VALUE (key, value ) \
50- PyThread_set_key_value ((key), (value))
95+ # define PYBIND11_TLS_DELETE_VALUE (key ) PyThread_set_key_value((key), nullptr )
96+ # define PYBIND11_TLS_REPLACE_VALUE (key, value ) PyThread_set_key_value((key), (value))
5197# endif
52- # define PYBIND11_TLS_FREE (key ) (void )key
98+ # define PYBIND11_TLS_FREE (key ) (void ) key
5399#endif
54100
55101// Python loads modules by default with dlopen with the RTLD_LOCAL flag; under libc++ and possibly
@@ -107,22 +153,31 @@ struct internals {
107153 std::unordered_map<const PyObject *, std::vector<PyObject *>> patients;
108154 std::forward_list<ExceptionTranslator> registered_exception_translators;
109155 std::unordered_map<std::string, void *> shared_data; // Custom data to be shared across extensions
156+ #if PYBIND11_INTERNALS_VERSION == 4
110157 std::vector<PyObject *> unused_loader_patient_stack_remove_at_v5;
158+ #endif
111159 std::forward_list<std::string> static_strings; // Stores the std::strings backing detail::c_str()
112160 PyTypeObject *static_property_type;
113161 PyTypeObject *default_metaclass;
114162 PyObject *instance_base;
115163#if defined(WITH_THREAD)
116- PYBIND11_TLS_KEY_INIT (tstate);
164+ PYBIND11_TLS_KEY_INIT (tstate)
165+ # if PYBIND11_INTERNALS_VERSION > 4
166+ PYBIND11_TLS_KEY_INIT (loader_life_support_tls_key)
167+ # endif // PYBIND11_INTERNALS_VERSION > 4
117168 PyInterpreterState *istate = nullptr ;
118169 ~internals () {
170+ # if PYBIND11_INTERNALS_VERSION > 4
171+ PYBIND11_TLS_FREE (loader_life_support_tls_key);
172+ # endif // PYBIND11_INTERNALS_VERSION > 4
173+
119174 // This destructor is called *after* Py_Finalize() in finalize_interpreter().
120- // That *SHOULD BE* fine. The following details what happens when PyThread_tss_free is called.
121- // PYBIND11_TLS_FREE is PyThread_tss_free on python 3.7+. On older python, it does nothing.
122- // PyThread_tss_free calls PyThread_tss_delete and PyMem_RawFree.
123- // PyThread_tss_delete just calls TlsFree (on Windows) or pthread_key_delete (on *NIX). Neither
124- // of those have anything to do with CPython internals.
125- // PyMem_RawFree *requires* that the `tstate` be allocated with the CPython allocator.
175+ // That *SHOULD BE* fine. The following details what happens when PyThread_tss_free is
176+ // called. PYBIND11_TLS_FREE is PyThread_tss_free on python 3.7+. On older python, it does
177+ // nothing. PyThread_tss_free calls PyThread_tss_delete and PyMem_RawFree.
178+ // PyThread_tss_delete just calls TlsFree (on Windows) or pthread_key_delete (on *NIX).
179+ // Neither of those have anything to do with CPython internals. PyMem_RawFree *requires*
180+ // that the `tstate` be allocated with the CPython allocator.
126181 PYBIND11_TLS_FREE (tstate);
127182 }
128183#endif
@@ -154,15 +209,6 @@ struct type_info {
154209 bool module_local : 1 ;
155210};
156211
157- // / Tracks the `internals` and `type_info` ABI version independent of the main library version
158- #ifndef PYBIND11_USE_SMART_HOLDER_AS_DEFAULT
159- #define PYBIND11_INTERNALS_VERSION 4
160- #else
161- // See README_smart_holder.rst:
162- // Classic / Conservative / Progressive cross-module compatibility
163- #define PYBIND11_INTERNALS_VERSION 1004
164- #endif
165-
166212// / On MSVC, debug and release builds are not ABI-compatible!
167213#if defined(_MSC_VER) && defined(_DEBUG)
168214# define PYBIND11_BUILD_TYPE " _debug"
@@ -221,11 +267,19 @@ struct type_info {
221267# endif
222268#endif
223269
270+ #ifndef PYBIND11_INTERNALS_SH_DEF
271+ # if defined(PYBIND11_USE_SMART_HOLDER_AS_DEFAULT)
272+ # define PYBIND11_INTERNALS_SH_DEF " "
273+ # else
274+ # define PYBIND11_INTERNALS_SH_DEF " _sh_def"
275+ # endif
276+ #endif
277+
224278#define PYBIND11_INTERNALS_ID " __pybind11_internals_v" \
225- PYBIND11_TOSTRING (PYBIND11_INTERNALS_VERSION) PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB PYBIND11_BUILD_ABI PYBIND11_BUILD_TYPE "__"
279+ PYBIND11_TOSTRING (PYBIND11_INTERNALS_VERSION) PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB PYBIND11_BUILD_ABI PYBIND11_BUILD_TYPE PYBIND11_INTERNALS_SH_DEF "__"
226280
227281#define PYBIND11_MODULE_LOCAL_ID " __pybind11_module_local_v" \
228- PYBIND11_TOSTRING (PYBIND11_INTERNALS_VERSION) PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB PYBIND11_BUILD_ABI PYBIND11_BUILD_TYPE "__"
282+ PYBIND11_TOSTRING (PYBIND11_INTERNALS_VERSION) PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB PYBIND11_BUILD_ABI PYBIND11_BUILD_TYPE PYBIND11_INTERNALS_SH_DEF "__"
229283
230284// / Each module locally stores a pointer to the `internals` data. The data
231285// / itself is shared among modules with the same `PYBIND11_INTERNALS_ID`.
@@ -298,21 +352,21 @@ PYBIND11_NOINLINE internals &get_internals() {
298352 internals_ptr = new internals ();
299353#if defined(WITH_THREAD)
300354
301- # if PY_VERSION_HEX < 0x03090000
302- PyEval_InitThreads ();
303- # endif
355+ # if PY_VERSION_HEX < 0x03090000
356+ PyEval_InitThreads ();
357+ # endif
304358 PyThreadState *tstate = PyThreadState_Get ();
305- # if PY_VERSION_HEX >= 0x03070000
306- internals_ptr-> tstate = PyThread_tss_alloc ( );
307- if (!internals_ptr-> tstate || ( PyThread_tss_create (internals_ptr-> tstate ) != 0 ))
308- pybind11_fail ( " get_internals: could not successfully initialize the tstate TSS key! " );
309- PyThread_tss_set (internals_ptr-> tstate , tstate);
310- # else
311- internals_ptr->tstate = PyThread_create_key ();
312- if (internals_ptr-> tstate == - 1 )
313- pybind11_fail ( " get_internals: could not successfully initialize the tstate TLS key!" );
314- PyThread_set_key_value (internals_ptr-> tstate , tstate);
315- # endif
359+ if (! PYBIND11_TLS_KEY_CREATE (internals_ptr-> tstate )) {
360+ pybind11_fail ( " get_internals: could not successfully initialize the tstate TSS key! " );
361+ }
362+ PYBIND11_TLS_REPLACE_VALUE (internals_ptr-> tstate , tstate );
363+
364+ # if PYBIND11_INTERNALS_VERSION > 4
365+ if (! PYBIND11_TLS_KEY_CREATE ( internals_ptr->loader_life_support_tls_key )) {
366+ pybind11_fail ( " get_internals: could not successfully initialize the "
367+ " loader_life_support TSS key!" );
368+ }
369+ # endif
316370 internals_ptr->istate = tstate->interp ;
317371#endif
318372 builtins[id] = capsule (internals_pp);
@@ -324,16 +378,48 @@ PYBIND11_NOINLINE internals &get_internals() {
324378 return **internals_pp;
325379}
326380
327-
328381// the internals struct (above) is shared between all the modules. local_internals are only
329382// for a single module. Any changes made to internals may require an update to
330383// PYBIND11_INTERNALS_VERSION, breaking backwards compatibility. local_internals is, by design,
331384// restricted to a single module. Whether a module has local internals or not should not
332385// impact any other modules, because the only things accessing the local internals is the
333386// module that contains them.
334387struct local_internals {
335- type_map<type_info *> registered_types_cpp;
336- std::forward_list<ExceptionTranslator> registered_exception_translators;
388+ type_map<type_info *> registered_types_cpp;
389+ std::forward_list<ExceptionTranslator> registered_exception_translators;
390+ #if defined(WITH_THREAD) && PYBIND11_INTERNALS_VERSION == 4
391+
392+ // For ABI compatibility, we can't store the loader_life_support TLS key in
393+ // the `internals` struct directly. Instead, we store it in `shared_data` and
394+ // cache a copy in `local_internals`. If we allocated a separate TLS key for
395+ // each instance of `local_internals`, we could end up allocating hundreds of
396+ // TLS keys if hundreds of different pybind11 modules are loaded (which is a
397+ // plausible number).
398+ PYBIND11_TLS_KEY_INIT (loader_life_support_tls_key)
399+
400+ // Holds the shared TLS key for the loader_life_support stack.
401+ struct shared_loader_life_support_data {
402+ PYBIND11_TLS_KEY_INIT (loader_life_support_tls_key)
403+ shared_loader_life_support_data () {
404+ if (!PYBIND11_TLS_KEY_CREATE (loader_life_support_tls_key)) {
405+ pybind11_fail (" local_internals: could not successfully initialize the "
406+ " loader_life_support TLS key!" );
407+ }
408+ }
409+ // We can't help but leak the TLS key, because Python never unloads extension modules.
410+ };
411+
412+ local_internals () {
413+ auto &internals = get_internals ();
414+ // Get or create the `loader_life_support_stack_key`.
415+ auto &ptr = internals.shared_data [" _life_support" ];
416+ if (!ptr) {
417+ ptr = new shared_loader_life_support_data;
418+ }
419+ loader_life_support_tls_key
420+ = static_cast <shared_loader_life_support_data *>(ptr)->loader_life_support_tls_key ;
421+ }
422+ #endif // defined(WITH_THREAD) && PYBIND11_INTERNALS_VERSION == 4
337423};
338424
339425// / Works like `get_internals`, but for things which are locally registered.
0 commit comments