Skip to content

Commit fc423c9

Browse files
swolchokoremanjpre-commit-ci[bot]
authored
Fix dangling pointer in internals::registered_types_cpp_fast from #5842 (#5867)
* Fix dangling pointer in internals::registered_types_cpp_fast from #5842 @oremanj pointed out in a comment on #5842 that I missed part of the nanobind PR I was porting in such a way that we could have dangling pointers in internals::registered_types_cpp_fast. This PR adds a test that reproed the bug and then fixes the test. * review feedback, attempt to fix -Werror in CI * use const ref, skip test on python 3.13 free-threaded * Skip test on 3.13t more robustly * style: pre-commit fixes * CI fix --------- Co-authored-by: Joshua Oreman <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent c7b4f66 commit fc423c9

File tree

7 files changed

+130
-2
lines changed

7 files changed

+130
-2
lines changed

include/pybind11/detail/class.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,11 @@ extern "C" inline void pybind11_meta_dealloc(PyObject *obj) {
228228
internals.registered_types_cpp.erase(tindex);
229229
#if PYBIND11_INTERNALS_VERSION >= 12
230230
internals.registered_types_cpp_fast.erase(tinfo->cpptype);
231+
for (const std::type_info *alias : tinfo->alias_chain) {
232+
auto num_erased = internals.registered_types_cpp_fast.erase(alias);
233+
(void) num_erased;
234+
assert(num_erased > 0);
235+
}
231236
#endif
232237
}
233238
internals.registered_types_py.erase(tinfo->type);

include/pybind11/detail/internals.h

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,20 @@ struct type_info {
357357
void *get_buffer_data = nullptr;
358358
void *(*module_local_load)(PyObject *, const type_info *) = nullptr;
359359
holder_enum_t holder_enum_v = holder_enum_t::undefined;
360+
361+
#if PYBIND11_INTERNALS_VERSION >= 12
362+
// When a type appears in multiple DSOs,
363+
// internals::registered_types_cpp_fast will have multiple distinct
364+
// keys (the std::type_info from each DSO) mapped to the same
365+
// detail::type_info*. We need to keep track of these aliases so that we clean
366+
// them up when our type is deallocated. A linked list is appropriate
367+
// because it is expected to be 1) usually empty and 2)
368+
// when it's not empty, usually very small. See also `struct
369+
// nb_alias_chain` added in
370+
// https://github.com/wjakob/nanobind/commit/b515b1f7f2f4ecc0357818e6201c94a9f4cbfdc2
371+
std::forward_list<const std::type_info *> alias_chain;
372+
#endif
373+
360374
/* A simple type never occurs as a (direct or indirect) parent
361375
* of a class that makes use of multiple inheritance.
362376
* A type can be simple even if it has non-simple ancestors as long as it has no descendants.

include/pybind11/detail/type_caster_base.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,11 @@ inline detail::type_info *get_global_type_info_lock_held(const std::type_info &t
246246
auto it = types.find(std::type_index(tp));
247247
if (it != types.end()) {
248248
#if PYBIND11_INTERNALS_VERSION >= 12
249+
// We found the type in the slow map but not the fast one, so
250+
// some other DSO added it (otherwise it would be in the fast
251+
// map under &tp) and therefore we must be an alias. Record
252+
// that.
253+
it->second->alias_chain.push_front(&tp);
249254
fast_types.emplace(&tp, it->second);
250255
#endif
251256
type_info = it->second;

tests/CMakeLists.txt

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ set(PYBIND11_TEST_FILES
117117
test_callbacks
118118
test_chrono
119119
test_class
120+
test_class_cross_module_use_after_one_module_dealloc
120121
test_class_release_gil_before_calling_cpp_dtor
121122
test_class_sh_basic
122123
test_class_sh_disowning
@@ -239,8 +240,9 @@ list(SORT PYBIND11_PYTEST_FILES)
239240
# Contains the set of test files that require pybind11_cross_module_tests to be
240241
# built; if none of these are built (i.e. because TEST_OVERRIDE is used and
241242
# doesn't include them) the second module doesn't get built.
242-
tests_extra_targets("test_exceptions.py;test_local_bindings.py;test_stl.py;test_stl_binders.py"
243-
"pybind11_cross_module_tests")
243+
tests_extra_targets(
244+
"test_class_cross_module_use_after_one_module_dealloc.py;test_exceptions.py;test_local_bindings.py;test_stl.py;test_stl_binders.py"
245+
"pybind11_cross_module_tests")
244246

245247
# And add additional targets for other tests.
246248
tests_extra_targets("test_exceptions.py" "cross_module_interleaved_error_already_set")

tests/pybind11_cross_module_tests.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,15 @@
1616
#include <numeric>
1717
#include <utility>
1818

19+
class CrossDSOClass {
20+
public:
21+
CrossDSOClass() = default;
22+
virtual ~CrossDSOClass();
23+
CrossDSOClass(const CrossDSOClass &) = default;
24+
};
25+
26+
CrossDSOClass::~CrossDSOClass() = default;
27+
1928
PYBIND11_MODULE(pybind11_cross_module_tests, m, py::mod_gil_not_used()) {
2029
m.doc() = "pybind11 cross-module test module";
2130

@@ -148,4 +157,7 @@ PYBIND11_MODULE(pybind11_cross_module_tests, m, py::mod_gil_not_used()) {
148157
// which appears when this header is missing.
149158
m.def("missing_header_arg", [](const std::vector<float> &) {});
150159
m.def("missing_header_return", []() { return std::vector<float>(); });
160+
161+
// test_class_cross_module_use_after_one_module_dealloc
162+
m.def("consume_cross_dso_class", [](const CrossDSOClass &) {});
151163
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#include "pybind11_tests.h"
2+
3+
#include <iostream>
4+
5+
class CrossDSOClass {
6+
public:
7+
CrossDSOClass() = default;
8+
virtual ~CrossDSOClass();
9+
CrossDSOClass(const CrossDSOClass &) = default;
10+
};
11+
12+
CrossDSOClass::~CrossDSOClass() = default;
13+
14+
struct UnrelatedClass {};
15+
16+
TEST_SUBMODULE(class_cross_module_use_after_one_module_dealloc, m) {
17+
m.def("register_and_instantiate_cross_dso_class", [](const py::module_ &m) {
18+
py::class_<CrossDSOClass>(m, "CrossDSOClass").def(py::init<>());
19+
return CrossDSOClass();
20+
});
21+
m.def("register_unrelated_class",
22+
[](const py::module_ &m) { py::class_<UnrelatedClass>(m, "UnrelatedClass"); });
23+
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
from __future__ import annotations
2+
3+
import gc
4+
import sys
5+
import sysconfig
6+
import types
7+
import weakref
8+
9+
import pytest
10+
11+
import env
12+
from pybind11_tests import class_cross_module_use_after_one_module_dealloc as m
13+
14+
is_python_3_13_free_threaded = (
15+
env.CPYTHON
16+
and sysconfig.get_config_var("Py_GIL_DISABLED")
17+
and (3, 13) <= sys.version_info < (3, 14)
18+
)
19+
20+
21+
def delattr_and_ensure_destroyed(*specs):
22+
wrs = []
23+
for mod, name in specs:
24+
wrs.append(weakref.ref(getattr(mod, name)))
25+
delattr(mod, name)
26+
27+
for _ in range(5):
28+
gc.collect()
29+
if all(wr() is None for wr in wrs):
30+
break
31+
else:
32+
pytest.fail(
33+
f"Could not delete bindings such as {next(wr for wr in wrs if wr() is not None)!r}"
34+
)
35+
36+
37+
@pytest.mark.skipif("env.PYPY or env.GRAALPY or is_python_3_13_free_threaded")
38+
def test_cross_module_use_after_one_module_dealloc():
39+
# This is a regression test for a bug that occurred during development of
40+
# internals::registered_types_cpp_fast (see #5842). registered_types_cpp_fast maps
41+
# &typeid(T) to a raw non-owning pointer to a Python type object. If two DSOs both
42+
# look up the same global type, they will create two separate entries in
43+
# registered_types_cpp_fast, which will look like:
44+
# +=========================================+
45+
# |&typeid(T) from DSO 1|type object pointer|
46+
# |&typeid(T) from DSO 2|type object pointer|
47+
# +=========================================+
48+
#
49+
# Then, if the type object is destroyed and we don't take extra steps to clean up
50+
# the table thoroughly, the first row of the table will be cleaned up but the second
51+
# one will contain a dangling pointer to the old type object. Further lookups from
52+
# DSO 2 will then return that dangling pointer, which will cause use-after-frees.
53+
54+
import pybind11_cross_module_tests as cm
55+
56+
module_scope = types.ModuleType("module_scope")
57+
instance = m.register_and_instantiate_cross_dso_class(module_scope)
58+
cm.consume_cross_dso_class(instance)
59+
60+
del instance
61+
delattr_and_ensure_destroyed((module_scope, "CrossDSOClass"))
62+
63+
# Make sure that CrossDSOClass gets allocated at a different address.
64+
m.register_unrelated_class(module_scope)
65+
66+
instance = m.register_and_instantiate_cross_dso_class(module_scope)
67+
cm.consume_cross_dso_class(instance)

0 commit comments

Comments
 (0)