Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 additions & 4 deletions include/pybind11/detail/class-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -714,6 +714,11 @@ PYBIND11_INLINE Py_ssize_t instance_data_offset() {
#endif

PYBIND11_INLINE PyObject *make_new_instance(PyTypeObject *type) {
return make_new_instance(type, all_type_info(type));
}

PYBIND11_INLINE PyObject *make_new_instance(PyTypeObject *type,
const std::vector<type_info *> &bases) {
#if defined(PYPY_VERSION)
// PyPy gets tp_basicsize wrong (issue 2482) under multiple inheritance when the first
// inherited object is a plain Python type (i.e. not derived from an extension type). Fix it.
Expand All @@ -722,17 +727,34 @@ PYBIND11_INLINE PyObject *make_new_instance(PyTypeObject *type) {
type->tp_basicsize = instance_size;
}
#endif
// Allocate the value/holder internals before the object. A failure after tp_alloc would
// need tp_dealloc, which is not safe on an instance without a layout.
auto storage = instance::allocate_layout(bases);
PyObject *self = type_alloc(type);
auto *inst = get_instance(self);
// Allocate the value/holder internals:
inst->allocate_layout();
if (self == nullptr) {
PyMem_Free(reinterpret_cast<void *>(storage.values_and_holders));
throw error_already_set();
}
get_instance(self)->init_layout(storage);

return self;
}

extern "C" PYBIND11_INLINE PyObject *
pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *) {
return make_new_instance(type);
try {
// Check before allocating, so a failure never deallocates a half-built instance.
const auto &bases = all_type_info(type);
if (bases.empty()) {
set_error(PyExc_TypeError,
"cannot be instantiated: no pybind11-registered base types");
return nullptr;
}
return make_new_instance(type, bases);
} catch (...) {
try_translate_exceptions();
return nullptr;
}
}

extern "C" PYBIND11_INLINE int pybind11_object_init(PyObject *self, PyObject *, PyObject *) {
Expand Down
2 changes: 2 additions & 0 deletions include/pybind11/detail/class.h
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,8 @@ Py_ssize_t static_property_dict_offset();
/// for holding C++ objects and holders. Allocation is done lazily (the first time the instance is
/// cast to a reference or pointer), and initialization is done by an `__init__` function.
PyObject *make_new_instance(PyTypeObject *type);
/// As above, with `bases` from `all_type_info(type)`, for a caller that has it already.
PyObject *make_new_instance(PyTypeObject *type, const std::vector<type_info *> &bases);

/// Instance creation function for all pybind11 types. It only allocates space for the
/// C++ object, but doesn't call the constructor -- an `__init__` function must do that.
Expand Down
7 changes: 5 additions & 2 deletions include/pybind11/detail/common.h
Original file line number Diff line number Diff line change
Expand Up @@ -846,9 +846,12 @@ struct instance {
PyObject *dict;
#endif

/// Allocates the non-simple storage for `tinfo`. The result is null for the simple layout.
static nonsimple_values_and_holders allocate_layout(const std::vector<type_info *> &tinfo);

/// Initializes all of the above type/values/holders data (but not the instance values
/// themselves)
void allocate_layout();
/// themselves) and takes ownership of `storage` from allocate_layout()
void init_layout(const nonsimple_values_and_holders &storage) noexcept;

/// Destroys/deallocates all of the above
void deallocate_layout();
Expand Down
69 changes: 37 additions & 32 deletions include/pybind11/detail/type_caster_base-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -364,50 +364,55 @@ instance::get_value_and_holder(const type_info *find_type /*= nullptr default in
#endif
}

PYBIND11_NOINLINE_ATTR PYBIND11_INLINE void instance::allocate_layout() {
const auto &tinfo = all_type_info(Py_TYPE(instance_object(this)));

PYBIND11_NOINLINE_ATTR PYBIND11_INLINE nonsimple_values_and_holders
instance::allocate_layout(const std::vector<type_info *> &tinfo) {
const size_t n_types = tinfo.size();

if (n_types == 0) {
pybind11_fail(
"instance allocation failed: new instance has no pybind11-registered base types");
}

simple_layout
= n_types == 1 && tinfo.front()->holder_size_in_ptrs <= instance_simple_holder_in_ptrs();

// Simple path: no python-side multiple inheritance, and a small-enough holder
if (n_types == 1 && tinfo.front()->holder_size_in_ptrs <= instance_simple_holder_in_ptrs()) {
return {nullptr, nullptr};
}

// multiple base types or a too-large holder
// Allocate space to hold: [v1*][h1][v2*][h2]...[bb...] where [vN*] is a value pointer,
// [hN] is the (uninitialized) holder instance for value N, and [bb...] is a set of bool
// values that tracks whether each associated holder has been initialized. Each [block] is
// padded, if necessary, to an integer multiple of sizeof(void *).
size_t space = 0;
for (auto *t : tinfo) {
space += 1; // value pointer
space += t->holder_size_in_ptrs; // holder instance
}
size_t flags_at = space;
space += size_in_ptrs(n_types); // status bytes (holder_constructed and
// instance_registered)

// Allocate space for flags, values, and holders, and initialize it to 0 (flags and values,
// in particular, need to be 0). Use Python's memory allocation
// functions: Python is using pymalloc, which is designed to be
// efficient for small allocations like the one we're doing here;
// for larger allocations they are just wrappers around malloc.
// TODO: is this still true for pure Python 3.6?
auto **values_and_holders = static_cast<void **>(PyMem_Calloc(space, sizeof(void *)));
if (!values_and_holders) {
throw std::bad_alloc();
}
return {values_and_holders, reinterpret_cast<std::uint8_t *>(&values_and_holders[flags_at])};
}

PYBIND11_INLINE void instance::init_layout(const nonsimple_values_and_holders &storage) noexcept {
simple_layout = storage.values_and_holders == nullptr;
if (simple_layout) {
simple_value_holder[0] = nullptr;
simple_holder_constructed = false;
simple_instance_registered = false;
} else { // multiple base types or a too-large holder
// Allocate space to hold: [v1*][h1][v2*][h2]...[bb...] where [vN*] is a value pointer,
// [hN] is the (uninitialized) holder instance for value N, and [bb...] is a set of bool
// values that tracks whether each associated holder has been initialized. Each [block] is
// padded, if necessary, to an integer multiple of sizeof(void *).
size_t space = 0;
for (auto *t : tinfo) {
space += 1; // value pointer
space += t->holder_size_in_ptrs; // holder instance
}
size_t flags_at = space;
space += size_in_ptrs(n_types); // status bytes (holder_constructed and
// instance_registered)

// Allocate space for flags, values, and holders, and initialize it to 0 (flags and values,
// in particular, need to be 0). Use Python's memory allocation
// functions: Python is using pymalloc, which is designed to be
// efficient for small allocations like the one we're doing here;
// for larger allocations they are just wrappers around malloc.
// TODO: is this still true for pure Python 3.6?
nonsimple.values_and_holders = static_cast<void **>(PyMem_Calloc(space, sizeof(void *)));
if (!nonsimple.values_and_holders) {
throw std::bad_alloc();
}
nonsimple.status
= reinterpret_cast<std::uint8_t *>(&nonsimple.values_and_holders[flags_at]);
} else {
nonsimple = storage;
}
owned = true;
old_style_init_active = false;
Expand Down
2 changes: 1 addition & 1 deletion include/pybind11/detail/type_caster_base.h
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ struct values_and_holders {
* The returned object should be short-lived: in particular, it must not outlive the called-upon
* instance.
*/
// (get_value_and_holder, allocate_layout, and deallocate_layout are declared inside
// (get_value_and_holder, allocate_layout, init_layout, and deallocate_layout are declared inside
// struct instance in detail/common.h; definitions are in type_caster_base-inl.h.)

PYBIND11_WARNING_PUSH
Expand Down
60 changes: 60 additions & 0 deletions tests/test_class.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,69 @@ struct OldStyleInit {
virtual int v_data() const { return m_data; }
};

#if !defined(PYPY_VERSION) && !defined(GRAALVM_PYTHON) && !defined(Py_LIMITED_API)
namespace {
// test_instance_allocation_failure
PyObject *call_with_failing_calloc(PyObject *type) {
PyMemAllocatorEx orig;
PyMem_GetAllocator(PYMEM_DOMAIN_MEM, &orig);
PyMemAllocatorEx failing = orig;
failing.calloc = [](void *, size_t, size_t) -> void * { return nullptr; };
PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &failing);
PyObject *result = PyObject_CallObject(type, nullptr);
PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &orig);
return result;
}
} // namespace
#endif

TEST_SUBMODULE(class_, m) {
m.def("obj_class_name", [](py::handle obj) { return py::detail::obj_class_name(obj.ptr()); });

#if !defined(PYPY_VERSION) && !defined(GRAALVM_PYTHON) && !defined(Py_LIMITED_API)
// test_instance_allocation_failure
m.def("call_with_failing_calloc", [](py::handle type) {
PyObject *result = call_with_failing_calloc(type.ptr());
if (result == nullptr) {
throw py::error_already_set();
}
return py::reinterpret_steal<py::object>(result);
});

# if PY_VERSION_HEX >= 0x030D0000
// Returns how many instances of `type` the interpreter saw created and destroyed.
m.def("ref_events_with_failing_calloc", [](py::handle type) {
struct Counts {
PyTypeObject *type;
int created;
int destroyed;
};
Counts counts{reinterpret_cast<PyTypeObject *>(type.ptr()), 0, 0};
void *orig_data = nullptr;
PyRefTracer orig = PyRefTracer_GetTracer(&orig_data);
PyRefTracer_SetTracer(
[](PyObject *op, PyRefTracerEvent event, void *data) -> int {
auto *c = static_cast<Counts *>(data);
// op is null for PyRefTracer_TRACKER_REMOVED (3.15+)
if (op != nullptr && Py_TYPE(op) == c->type) {
if (event == PyRefTracer_CREATE) {
++c->created;
} else if (event == PyRefTracer_DESTROY) {
++c->destroyed;
}
}
return 0;
},
&counts);
PyObject *result = call_with_failing_calloc(type.ptr());
PyErr_Clear();
Py_XDECREF(result);
PyRefTracer_SetTracer(orig, orig_data);
return py::make_tuple(counts.created, counts.destroyed);
});
# endif
#endif

// test_instance
struct NoConstructor {
NoConstructor() = default;
Expand Down
39 changes: 39 additions & 0 deletions tests/test_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -820,3 +820,42 @@ def test_cast_unregistered_type():
def test_cast_null_result():
with pytest.raises(RuntimeError, match="Unable to convert .* to Python object"):
m.cast_null_result()


def test_instantiate_pybind11_object_base():
base = m.NoConstructor.__base__
assert base.__name__.startswith("pybind11_object")
with pytest.raises(TypeError, match="no pybind11-registered base types"):
base()

class Derived(base):
pass

with pytest.raises(TypeError, match="no pybind11-registered base types"):
Derived()

# PyPy reads __module__ to make a qualified type name
class NoModule(base):
__module__ = None

with pytest.raises(TypeError, match="no pybind11-registered base types"):
NoModule()


@pytest.mark.skipif(
not hasattr(m, "call_with_failing_calloc"), reason="Needs PyMem_SetAllocator"
)
def test_instance_allocation_failure():
# Two registered bases give the non-simple layout, which allocates
class Derived(m.NoConstructor, m.BaseClass):
pass

with pytest.raises(MemoryError):
m.call_with_failing_calloc(Derived)

gc.collect()
assert not any(type(o) is Derived for o in gc.get_objects())

if hasattr(m, "ref_events_with_failing_calloc"):
created, destroyed = m.ref_events_with_failing_calloc(Derived)
assert created == destroyed
Loading