Skip to content

Commit b475928

Browse files
committed
Eliminate duplicate TLS keys for loader_life_support stack
This revises the existing fix for #2765 in #3237 to reduce the amount of TLS storage used. The shared TLS key is stored in two different ways, depending on `PYBIND11_INTERNALS_VERSION`. If `PYBIND11_INTERNALS_VERSION == 4` (as is currently set), the TLS key is stored in the `internal::shared_data` map to avoid breaking ABI compatibility. If `PYBIND11_INTERNALS_VERSION > 4`, the TLS key is stored directly in the `internals` struct.
1 parent e0031bf commit b475928

File tree

3 files changed

+143
-60
lines changed

3 files changed

+143
-60
lines changed

include/pybind11/detail/internals.h

Lines changed: 115 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,24 @@
1111

1212
#include "../pytypes.h"
1313

14+
/// Tracks the `internals` and `type_info` ABI version independent of the main library version.
15+
///
16+
/// Some portions of the code use an ABI that is conditional depending on this
17+
/// version number. That allows ABI-breaking changes to be "pre-implemented".
18+
/// Once the default version number is incremented, the conditional logic that
19+
/// no longer applies can be removed. Additionally, users that need not
20+
/// maintain ABI compatibility can increase the version number in order to take
21+
/// advantage of any functionality/efficiency improvements that depend on the
22+
/// newer ABI.
23+
///
24+
/// WARNING: If you choose to manually increase the ABI version, note that
25+
/// pybind11 may not be tested as thoroughly with a non-default ABI version, and
26+
/// further ABI-incompatible changes may be made before the ABI is officially
27+
/// changed to the new version.
28+
#ifndef PYBIND11_INTERNALS_VERSION
29+
#define PYBIND11_INTERNALS_VERSION 4
30+
#endif
31+
1432
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
1533

1634
using ExceptionTranslator = void (*)(std::exception_ptr);
@@ -25,30 +43,44 @@ inline PyObject *make_object_base_type(PyTypeObject *metaclass);
2543
// The old Python Thread Local Storage (TLS) API is deprecated in Python 3.7 in favor of the new
2644
// Thread Specific Storage (TSS) API.
2745
#if PY_VERSION_HEX >= 0x03070000
28-
# define PYBIND11_TLS_KEY_INIT(var) Py_tss_t *var = nullptr
29-
# define PYBIND11_TLS_GET_VALUE(key) PyThread_tss_get((key))
30-
# define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_tss_set((key), (value))
31-
# define PYBIND11_TLS_DELETE_VALUE(key) PyThread_tss_set((key), nullptr)
32-
# define PYBIND11_TLS_FREE(key) PyThread_tss_free(key)
46+
// Avoid unnecessary allocation of `Py_tss_t`, since we cannot use
47+
// `Py_LIMITED_API` anyway.
48+
# if PYBIND11_INTERNALS_VERSION > 4
49+
# define PYBIND11_TLS_KEY_REF Py_tss_t &
50+
# define PYBIND11_TLS_KEY_INIT(var) Py_tss_t var = Py_tss_NEEDS_INIT
51+
# define PYBIND11_TLS_KEY_CREATE(var) (PyThread_tss_create(&(var)) == 0)
52+
# define PYBIND11_TLS_GET_VALUE(key) PyThread_tss_get(&(key))
53+
# define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_tss_set(&(key), (value))
54+
# define PYBIND11_TLS_DELETE_VALUE(key) PyThread_tss_set(&(key), nullptr)
55+
# define PYBIND11_TLS_FREE(key) PyThread_tss_delete(&(key))
56+
# else
57+
# define PYBIND11_TLS_KEY_REF Py_tss_t *
58+
# define PYBIND11_TLS_KEY_INIT(var) Py_tss_t *var = nullptr
59+
# define PYBIND11_TLS_KEY_CREATE(var) \
60+
(((var) = PyThread_tss_alloc()) != nullptr && (PyThread_tss_create((var)) == 0))
61+
# define PYBIND11_TLS_GET_VALUE(key) PyThread_tss_get((key))
62+
# define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_tss_set((key), (value))
63+
# define PYBIND11_TLS_DELETE_VALUE(key) PyThread_tss_set((key), nullptr)
64+
# define PYBIND11_TLS_FREE(key) PyThread_tss_free(key)
65+
# endif
3366
#else
34-
// Usually an int but a long on Cygwin64 with Python 3.x
35-
# define PYBIND11_TLS_KEY_INIT(var) decltype(PyThread_create_key()) var = 0
67+
// Usually an int but a long on Cygwin64 with Python 3.x
68+
# define PYBIND11_TLS_KEY_REF decltype(PyThread_create_key())
69+
# define PYBIND11_TLS_KEY_INIT(var) PYBIND11_TLS_KEY_REF var = 0
70+
# define PYBIND11_TLS_KEY_CREATE(var) (((var) = PyThread_create_key()) != -1)
3671
# define PYBIND11_TLS_GET_VALUE(key) PyThread_get_key_value((key))
3772
# if PY_MAJOR_VERSION < 3
38-
# define PYBIND11_TLS_DELETE_VALUE(key) \
39-
PyThread_delete_key_value(key)
40-
# define PYBIND11_TLS_REPLACE_VALUE(key, value) \
41-
do { \
42-
PyThread_delete_key_value((key)); \
43-
PyThread_set_key_value((key), (value)); \
44-
} while (false)
73+
# define PYBIND11_TLS_DELETE_VALUE(key) PyThread_delete_key_value(key)
74+
# define PYBIND11_TLS_REPLACE_VALUE(key, value) \
75+
do { \
76+
PyThread_delete_key_value((key)); \
77+
PyThread_set_key_value((key), (value)); \
78+
} while (false)
4579
# else
46-
# define PYBIND11_TLS_DELETE_VALUE(key) \
47-
PyThread_set_key_value((key), nullptr)
48-
# define PYBIND11_TLS_REPLACE_VALUE(key, value) \
49-
PyThread_set_key_value((key), (value))
80+
# define PYBIND11_TLS_DELETE_VALUE(key) PyThread_set_key_value((key), nullptr)
81+
# define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_set_key_value((key), (value))
5082
# endif
51-
# define PYBIND11_TLS_FREE(key) (void)key
83+
# define PYBIND11_TLS_FREE(key) (void) key
5284
#endif
5385

5486
// Python loads modules by default with dlopen with the RTLD_LOCAL flag; under libc++ and possibly
@@ -106,22 +138,31 @@ struct internals {
106138
std::unordered_map<const PyObject *, std::vector<PyObject *>> patients;
107139
std::forward_list<ExceptionTranslator> registered_exception_translators;
108140
std::unordered_map<std::string, void *> shared_data; // Custom data to be shared across extensions
141+
#if PYBIND11_INTERNALS_VERSION == 4
109142
std::vector<PyObject *> unused_loader_patient_stack_remove_at_v5;
143+
#endif
110144
std::forward_list<std::string> static_strings; // Stores the std::strings backing detail::c_str()
111145
PyTypeObject *static_property_type;
112146
PyTypeObject *default_metaclass;
113147
PyObject *instance_base;
114148
#if defined(WITH_THREAD)
115149
PYBIND11_TLS_KEY_INIT(tstate);
150+
# if PYBIND11_INTERNALS_VERSION > 4
151+
PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key);
152+
# endif // PYBIND11_INTERNALS_VERSION > 4
116153
PyInterpreterState *istate = nullptr;
117154
~internals() {
155+
# if PYBIND11_INTERNALS_VERSION > 4
156+
PYBIND11_TLS_FREE(loader_life_support_tls_key);
157+
# endif // PYBIND11_INTERNALS_VERSION > 4
158+
118159
// This destructor is called *after* Py_Finalize() in finalize_interpreter().
119-
// That *SHOULD BE* fine. The following details what happens when PyThread_tss_free is called.
120-
// PYBIND11_TLS_FREE is PyThread_tss_free on python 3.7+. On older python, it does nothing.
121-
// PyThread_tss_free calls PyThread_tss_delete and PyMem_RawFree.
122-
// PyThread_tss_delete just calls TlsFree (on Windows) or pthread_key_delete (on *NIX). Neither
123-
// of those have anything to do with CPython internals.
124-
// PyMem_RawFree *requires* that the `tstate` be allocated with the CPython allocator.
160+
// That *SHOULD BE* fine. The following details what happens when PyThread_tss_free is
161+
// called. PYBIND11_TLS_FREE is PyThread_tss_free on python 3.7+. On older python, it does
162+
// nothing. PyThread_tss_free calls PyThread_tss_delete and PyMem_RawFree.
163+
// PyThread_tss_delete just calls TlsFree (on Windows) or pthread_key_delete (on *NIX).
164+
// Neither of those have anything to do with CPython internals. PyMem_RawFree *requires*
165+
// that the `tstate` be allocated with the CPython allocator.
125166
PYBIND11_TLS_FREE(tstate);
126167
}
127168
#endif
@@ -153,9 +194,6 @@ struct type_info {
153194
bool module_local : 1;
154195
};
155196

156-
/// Tracks the `internals` and `type_info` ABI version independent of the main library version
157-
#define PYBIND11_INTERNALS_VERSION 4
158-
159197
/// On MSVC, debug and release builds are not ABI-compatible!
160198
#if defined(_MSC_VER) && defined(_DEBUG)
161199
# define PYBIND11_BUILD_TYPE "_debug"
@@ -291,21 +329,21 @@ PYBIND11_NOINLINE internals &get_internals() {
291329
internals_ptr = new internals();
292330
#if defined(WITH_THREAD)
293331

294-
#if PY_VERSION_HEX < 0x03090000
295-
PyEval_InitThreads();
296-
#endif
332+
# if PY_VERSION_HEX < 0x03090000
333+
PyEval_InitThreads();
334+
# endif
297335
PyThreadState *tstate = PyThreadState_Get();
298-
#if PY_VERSION_HEX >= 0x03070000
299-
internals_ptr->tstate = PyThread_tss_alloc();
300-
if (!internals_ptr->tstate || (PyThread_tss_create(internals_ptr->tstate) != 0))
301-
pybind11_fail("get_internals: could not successfully initialize the tstate TSS key!");
302-
PyThread_tss_set(internals_ptr->tstate, tstate);
303-
#else
304-
internals_ptr->tstate = PyThread_create_key();
305-
if (internals_ptr->tstate == -1)
306-
pybind11_fail("get_internals: could not successfully initialize the tstate TLS key!");
307-
PyThread_set_key_value(internals_ptr->tstate, tstate);
308-
#endif
336+
if (!PYBIND11_TLS_KEY_CREATE(internals_ptr->tstate)) {
337+
pybind11_fail("get_internals: could not successfully initialize the tstate TSS key!");
338+
}
339+
PYBIND11_TLS_REPLACE_VALUE(internals_ptr->tstate, tstate);
340+
341+
# if PYBIND11_INTERNALS_VERSION > 4
342+
if (!PYBIND11_TLS_KEY_CREATE(internals_ptr->loader_life_support_tls_key)) {
343+
pybind11_fail("get_internals: could not successfully initialize the "
344+
"loader_life_support TSS key!");
345+
}
346+
# endif
309347
internals_ptr->istate = tstate->interp;
310348
#endif
311349
builtins[id] = capsule(internals_pp);
@@ -317,16 +355,48 @@ PYBIND11_NOINLINE internals &get_internals() {
317355
return **internals_pp;
318356
}
319357

320-
321358
// the internals struct (above) is shared between all the modules. local_internals are only
322359
// for a single module. Any changes made to internals may require an update to
323360
// PYBIND11_INTERNALS_VERSION, breaking backwards compatibility. local_internals is, by design,
324361
// restricted to a single module. Whether a module has local internals or not should not
325362
// impact any other modules, because the only things accessing the local internals is the
326363
// module that contains them.
327364
struct local_internals {
328-
type_map<type_info *> registered_types_cpp;
329-
std::forward_list<ExceptionTranslator> registered_exception_translators;
365+
type_map<type_info *> registered_types_cpp;
366+
std::forward_list<ExceptionTranslator> registered_exception_translators;
367+
#if defined(WITH_THREAD) && PYBIND11_INTERNALS_VERSION == 4
368+
369+
// For ABI compatibility, we can't store the loader_life_support TLS key in
370+
// the `internals` struct directly. Instead, we store it in `shared_data` and
371+
// cache a copy in `local_internals`. If we allocated a separate TLS key for
372+
// each instance of `local_internals`, we could end up allocating hundreds of
373+
// TLS keys if hundreds of different pybind11 modules are loaded (which is a
374+
// plausible number).
375+
PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key);
376+
377+
// Holds the shared TLS key for the loader_life_support stack.
378+
struct shared_loader_life_support_data {
379+
PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key);
380+
shared_loader_life_support_data() {
381+
if (!PYBIND11_TLS_KEY_CREATE(loader_life_support_tls_key)) {
382+
pybind11_fail("local_internals: could not successfully initialize the "
383+
"loader_life_support TLS key!");
384+
}
385+
}
386+
// We can't help but leak the TLS key, because Python never unloads extension modules.
387+
};
388+
389+
local_internals() {
390+
auto &internals = get_internals();
391+
// Get or create the `loader_life_support_stack_key`.
392+
auto &ptr = internals.shared_data["_life_support"];
393+
if (!ptr) {
394+
ptr = new shared_loader_life_support_data;
395+
}
396+
loader_life_support_tls_key
397+
= static_cast<shared_loader_life_support_data *>(ptr)->loader_life_support_tls_key;
398+
}
399+
#endif // defined(WITH_THREAD) && PYBIND11_INTERNALS_VERSION == 4
330400
};
331401

332402
/// Works like `get_internals`, but for things which are locally registered.

include/pybind11/detail/type_caster_base.h

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -35,38 +35,51 @@ class loader_life_support {
3535
loader_life_support* parent = nullptr;
3636
std::unordered_set<PyObject *> keep_alive;
3737

38-
static loader_life_support** get_stack_pp() {
3938
#if defined(WITH_THREAD)
40-
thread_local static loader_life_support* per_thread_stack = nullptr;
41-
return &per_thread_stack;
39+
// Store stack pointer in thread-local storage.
40+
static PYBIND11_TLS_KEY_REF get_stack_tls_key() {
41+
# if PYBIND11_INTERNALS_VERSION == 4
42+
return get_local_internals().loader_life_support_tls_key;
43+
# else
44+
return get_internals().loader_life_support_tls_key;
45+
# endif
46+
}
47+
static loader_life_support *get_stack_top() {
48+
return static_cast<loader_life_support *>(PYBIND11_TLS_GET_VALUE(get_stack_tls_key()));
49+
}
50+
static void set_stack_top(loader_life_support *value) {
51+
PYBIND11_TLS_REPLACE_VALUE(get_stack_tls_key(), value);
52+
}
4253
#else
43-
static loader_life_support* global_stack = nullptr;
44-
return &global_stack;
45-
#endif
54+
// Use single global variable for stack.
55+
static loader_life_support **get_stack_pp() {
56+
static loader_life_support *global_stack = nullptr;
57+
return global_stack;
4658
}
59+
static loader_life_support *get_stack_top() { return *get_stack_pp(); }
60+
static void set_stack_top(loader_life_support *value) { *get_stack_pp() = value; }
61+
#endif
4762

4863
public:
4964
/// A new patient frame is created when a function is entered
5065
loader_life_support() {
51-
loader_life_support** stack = get_stack_pp();
52-
parent = *stack;
53-
*stack = this;
66+
parent = get_stack_top();
67+
set_stack_top(this);
5468
}
5569

5670
/// ... and destroyed after it returns
5771
~loader_life_support() {
58-
loader_life_support** stack = get_stack_pp();
59-
if (*stack != this)
72+
if (get_stack_top() != this)
6073
pybind11_fail("loader_life_support: internal error");
61-
*stack = parent;
74+
set_stack_top(parent);
6275
for (auto* item : keep_alive)
6376
Py_DECREF(item);
6477
}
6578

6679
/// This can only be used inside a pybind11-bound function, either by `argument_loader`
6780
/// at argument preparation time or by `py::cast()` at execution time.
6881
PYBIND11_NOINLINE static void add_patient(handle h) {
69-
loader_life_support* frame = *get_stack_pp();
82+
loader_life_support *frame = get_stack_top();
7083
if (!frame) {
7184
// NOTE: It would be nice to include the stack frames here, as this indicates
7285
// use of pybind11::cast<> outside the normal call framework, finding such

include/pybind11/gil.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ PYBIND11_NAMESPACE_END(detail)
5050
class gil_scoped_acquire {
5151
public:
5252
PYBIND11_NOINLINE gil_scoped_acquire() {
53-
auto const &internals = detail::get_internals();
53+
auto &internals = detail::get_internals();
5454
tstate = (PyThreadState *) PYBIND11_TLS_GET_VALUE(internals.tstate);
5555

5656
if (!tstate) {
@@ -132,7 +132,7 @@ class gil_scoped_release {
132132
// `get_internals()` must be called here unconditionally in order to initialize
133133
// `internals.tstate` for subsequent `gil_scoped_acquire` calls. Otherwise, an
134134
// initialization race could occur as multiple threads try `gil_scoped_acquire`.
135-
const auto &internals = detail::get_internals();
135+
auto &internals = detail::get_internals();
136136
tstate = PyEval_SaveThread();
137137
if (disassoc) {
138138
auto key = internals.tstate;

0 commit comments

Comments
 (0)