Skip to content

Commit bc392d2

Browse files
committed
Validate native downcasts against the allocated payload layout
Assisted-by: Codex:gpt-6
1 parent 7536730 commit bc392d2

13 files changed

Lines changed: 203 additions & 29 deletions

File tree

‎crates/derive-impl/src/pyclass.rs‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -669,9 +669,21 @@ fn generate_class_def(
669669
checks: member_checks,
670670
} = extras.member_table;
671671

672+
let native_layout = if is_repr_transparent {
673+
base.as_ref().map(|base| {
674+
quote! {
675+
const NATIVE_LAYOUT_ID: ::core::any::TypeId =
676+
<#base as ::rustpython_vm::class::PyClassDef>::NATIVE_LAYOUT_ID;
677+
}
678+
})
679+
} else {
680+
None
681+
};
682+
672683
let tokens = quote! {
673684
impl ::rustpython_vm::class::PyClassDef for #ident {
674685
const NAME: &'static str = #name;
686+
#native_layout
675687
const MODULE_NAME: Option<&'static str> = #module_name;
676688
const TP_NAME: &'static str = #module_class_name;
677689
const DOC: ::rustpython_vm::function::ItemDoc = #doc;
@@ -903,9 +915,14 @@ pub(crate) fn impl_pyclass(attr: PunctuatedNestedMeta, item: Item) -> Result<Tok
903915
impl ::rustpython_vm::PyPayload for #ident {
904916
const PAYLOAD_TYPE_ID: ::core::any::TypeId = <#base_type as ::rustpython_vm::PyPayload>::PAYLOAD_TYPE_ID;
905917

918+
fn supports_native_layout(layout: ::core::any::TypeId) -> bool {
919+
layout == <Self as ::rustpython_vm::class::PyClassDef>::NATIVE_LAYOUT_ID
920+
|| <#base_type as ::rustpython_vm::PyPayload>::supports_native_layout(layout)
921+
}
922+
906923
#[inline]
907924
unsafe fn validate_downcastable_from(obj: &::rustpython_vm::PyObject) -> bool {
908-
<Self as ::rustpython_vm::class::PyClassDef>::BASICSIZE <= obj.class().payload().slots.basicsize && obj.class().fast_issubclass(<Self as ::rustpython_vm::class::StaticType>::static_type())
925+
obj.supports_native_layout(<Self as ::rustpython_vm::class::PyClassDef>::NATIVE_LAYOUT_ID) && obj.class().fast_issubclass(<Self as ::rustpython_vm::class::StaticType>::static_type())
909926
}
910927

911928
fn class(ctx: &::rustpython_vm::vm::Context) -> &'static ::rustpython_vm::Py<::rustpython_vm::builtins::PyType> {

‎crates/derive-impl/src/pystructseq.rs‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -553,6 +553,7 @@ pub(crate) fn impl_pystruct_sequence(
553553
const ATTR_DOCS: &'static [&'static str] = #attr_names;
554554
}}
555555
const BASICSIZE: usize = 0;
556+
const NATIVE_LAYOUT_ID: ::core::any::TypeId = ::core::any::TypeId::of::<::rustpython_vm::builtins::PyTuple>();
556557
const UNHASHABLE: bool = false;
557558

558559
type Base = ::rustpython_vm::builtins::PyTuple;
@@ -577,9 +578,14 @@ pub(crate) fn impl_pystruct_sequence(
577578
impl ::rustpython_vm::PyPayload for #pytype_ident {
578579
const PAYLOAD_TYPE_ID: ::core::any::TypeId = <::rustpython_vm::builtins::PyTuple as ::rustpython_vm::PyPayload>::PAYLOAD_TYPE_ID;
579580

581+
fn supports_native_layout(layout: ::core::any::TypeId) -> bool {
582+
<::rustpython_vm::builtins::PyTuple as ::rustpython_vm::PyPayload>::supports_native_layout(layout)
583+
}
584+
580585
#[inline]
581586
unsafe fn validate_downcastable_from(obj: &::rustpython_vm::PyObject) -> bool {
582-
obj.class().fast_issubclass(<Self as ::rustpython_vm::class::StaticType>::static_type())
587+
obj.supports_native_layout(::core::any::TypeId::of::<::rustpython_vm::builtins::PyTuple>())
588+
&& obj.class().fast_issubclass(<Self as ::rustpython_vm::class::StaticType>::static_type())
583589
}
584590

585591
fn class(_ctx: &::rustpython_vm::vm::Context) -> &'static ::rustpython_vm::Py<::rustpython_vm::builtins::PyType> {

‎crates/vm/src/builtins/builtin_func.rs‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -234,12 +234,31 @@ impl PyNativeFunction {
234234
}
235235

236236
// PyCMethodObject in CPython
237-
#[pyclass(name = "builtin_function_or_method", module = false, base = PyNativeFunction, ctx = "builtin_function_or_method_type")]
237+
#[pyclass(name = "builtin_function_or_method", module = false, base = PyNativeFunction, ctx = "builtin_function_or_method_type", payload = "manual")]
238238
pub struct PyNativeMethod {
239239
pub(crate) func: PyNativeFunction,
240240
pub(crate) class: &'static Py<PyType>, // TODO: the actual life is &'self
241241
}
242242

243+
impl PyPayload for PyNativeMethod {
244+
const PAYLOAD_TYPE_ID: core::any::TypeId = PyNativeFunction::PAYLOAD_TYPE_ID;
245+
246+
fn supports_native_layout(layout: core::any::TypeId) -> bool {
247+
layout == core::any::TypeId::of::<Self>()
248+
|| PyNativeFunction::supports_native_layout(layout)
249+
}
250+
251+
unsafe fn validate_downcastable_from(obj: &PyObject) -> bool {
252+
// Both payloads use builtin_function_or_method as their Python class.
253+
// The immutable allocation vtable distinguishes the larger CMethod.
254+
obj.supports_native_layout(core::any::TypeId::of::<Self>())
255+
}
256+
257+
fn class(ctx: &Context) -> &'static Py<PyType> {
258+
ctx.types.builtin_function_or_method_type
259+
}
260+
}
261+
243262
// All Python-visible behavior (getters, slots) is registered by PyNativeFunction::extend_class.
244263
// PyNativeMethod only extends the Rust-side struct with the defining class reference.
245264
// The func field at offset 0 (#[repr(C)]) allows NativeFunctionOrMethod to read it safely.

‎crates/vm/src/builtins/str.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2101,6 +2101,10 @@ impl MaybeTraverse for PyUtf8Str {
21012101
}
21022102

21032103
impl PyPayload for PyUtf8Str {
2104+
fn supports_native_layout(layout: core::any::TypeId) -> bool {
2105+
PyStr::supports_native_layout(layout)
2106+
}
2107+
21042108
#[inline]
21052109
fn class(ctx: &Context) -> &'static Py<PyType> {
21062110
ctx.types.str_type

‎crates/vm/src/builtins/type.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -970,6 +970,9 @@ impl PyType {
970970
ctx: &Context,
971971
defer_mro: bool,
972972
) -> Result<PyRef<Self>, String> {
973+
if slots.native_layout_id.is_none() {
974+
slots.native_layout_id = base.slots.native_layout_id;
975+
}
973976
let mro = if defer_mro {
974977
// Leave tp_mro unset so a custom metaclass mro() sees __mro__ is None.
975978
Vec::new()
@@ -3798,7 +3801,8 @@ pub(crate) fn compatible_for_assignment(
37983801
(None, None) => true,
37993802
_ => false,
38003803
};
3801-
let compatible = newbase.is(oldbase) || (bases_equal && same_slots_added(newbase, oldbase));
3804+
let compatible = old_to.slots.native_layout_id == new_to.slots.native_layout_id
3805+
&& (newbase.is(oldbase) || (bases_equal && same_slots_added(newbase, oldbase)));
38023806
if compatible {
38033807
return Ok(());
38043808
}

‎crates/vm/src/builtins/weakproxy.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,13 @@ pub struct PyWeakProxy(PyWeak);
2121
impl PyPayload for PyWeakProxy {
2222
const PAYLOAD_TYPE_ID: core::any::TypeId = <PyWeak as PyPayload>::PAYLOAD_TYPE_ID;
2323

24+
fn supports_native_layout(layout: core::any::TypeId) -> bool {
25+
PyWeak::supports_native_layout(layout)
26+
}
27+
2428
#[inline]
2529
unsafe fn validate_downcastable_from(obj: &PyObject) -> bool {
26-
<Self as ::rustpython_vm::class::PyClassDef>::BASICSIZE <= obj.class().slots().basicsize
30+
obj.supports_native_layout(core::any::TypeId::of::<Self>())
2731
&& obj
2832
.class()
2933
.fast_issubclass(<Self as ::rustpython_vm::class::StaticType>::static_type())

‎crates/vm/src/builtins/weakref.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,12 @@ pub struct WeakNewArgs {
2424
}
2525

2626
impl PyPayload for PyWeak {
27+
fn supports_native_layout(layout: core::any::TypeId) -> bool {
28+
// Proxies are transparent views of the same PyWeak allocation.
29+
layout == core::any::TypeId::of::<Self>()
30+
|| layout == core::any::TypeId::of::<super::PyWeakProxy>()
31+
}
32+
2733
#[inline]
2834
fn class(ctx: &Context) -> &'static Py<PyType> {
2935
ctx.types.weakref_type

‎crates/vm/src/class.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ pub trait StaticType {
161161
}
162162
}
163163

164-
pub trait PyClassDef {
164+
pub trait PyClassDef: 'static {
165165
const NAME: &'static str;
166166
const MODULE_NAME: Option<&'static str>;
167167
const TP_NAME: &'static str;
@@ -175,6 +175,7 @@ pub trait PyClassDef {
175175
const ATTR_DOCS: &'static [&'static str] = &[];
176176
const BASICSIZE: usize;
177177
const ITEMSIZE: usize = 0;
178+
const NATIVE_LAYOUT_ID: core::any::TypeId = core::any::TypeId::of::<Self>();
178179
const UNHASHABLE: bool = false;
179180
const MEMBERS: &'static [crate::builtins::descriptor::PyMemberSpec] = &[];
180181

@@ -427,6 +428,7 @@ pub trait PyClassImpl: PyClassDef {
427428
flags: crate::types::AtomicPyTypeFlags::from_plain(Self::TP_FLAGS),
428429
name: Self::TP_NAME,
429430
basicsize: Self::BASICSIZE,
431+
native_layout_id: Some(Self::NATIVE_LAYOUT_ID),
430432
itemsize: Self::ITEMSIZE,
431433
doc: {
432434
let internal = Self::INTERNAL_DOC;

‎crates/vm/src/exceptions.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,11 @@ impl PyPayload for PyBaseException {
5858

5959
impl PyPayload for PyMemoryError {
6060
const PAYLOAD_TYPE_ID: core::any::TypeId = <PyException as PyPayload>::PAYLOAD_TYPE_ID;
61+
62+
fn supports_native_layout(layout: core::any::TypeId) -> bool {
63+
<PyException as PyPayload>::supports_native_layout(layout)
64+
}
65+
6166
const HAS_FREELIST: bool = true;
6267
const MAX_FREELIST: usize = MEMORY_ERROR_FREELIST_SIZE;
6368

‎crates/vm/src/object/core.rs‎

Lines changed: 118 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1668,13 +1668,8 @@ impl PyObjectRef {
16681668
/// another downcast can be attempted without unnecessary cloning.
16691669
#[inline]
16701670
pub fn downcast_exact<T: PyPayload>(self, vm: &VirtualMachine) -> Result<PyRefExact<T>, Self> {
1671-
if self.class().is(T::class(&vm.ctx)) {
1672-
// TODO: is this always true?
1673-
assert!(
1674-
self.downcastable::<T>(),
1675-
"obj.__class__ is T::class() but payload is not T"
1676-
);
1677-
// SAFETY: just asserted that downcastable::<T>()
1671+
if self.class().is(T::class(&vm.ctx)) && self.downcastable::<T>() {
1672+
// SAFETY: the class and allocation both match T.
16781673
Ok(unsafe { PyRefExact::new_unchecked(PyRef::from_obj_unchecked(self)) })
16791674
} else {
16801675
Err(self)
@@ -1779,7 +1774,13 @@ impl PyObject {
17791774
#[deprecated(note = "use downcastable instead")]
17801775
#[inline(always)]
17811776
pub fn payload_is<T: PyPayload>(&self) -> bool {
1782-
self.0.vtable.typeid == T::PAYLOAD_TYPE_ID
1777+
self.downcastable::<T>()
1778+
}
1779+
1780+
#[doc(hidden)]
1781+
#[must_use]
1782+
pub fn supports_native_layout(&self, layout: core::any::TypeId) -> bool {
1783+
(self.0.vtable.supports_native_layout)(layout)
17831784
}
17841785

17851786
/// Force to return payload as T.
@@ -1936,7 +1937,8 @@ impl PyObject {
19361937
pub fn downcast_ref_if_exact<T: PyPayload>(&self, vm: &VirtualMachine) -> Option<&Py<T>> {
19371938
self.class()
19381939
.is(T::class(&vm.ctx))
1939-
.then(|| unsafe { self.downcast_unchecked_ref::<T>() })
1940+
.then(|| self.downcast_ref::<T>())
1941+
.flatten()
19401942
}
19411943

19421944
/// # Safety
@@ -2875,32 +2877,27 @@ where
28752877
#[inline]
28762878
#[must_use]
28772879
pub fn into_base(self) -> PyRef<T::Base> {
2878-
let obj: PyObjectRef = self.into();
2879-
match obj.downcast() {
2880-
Ok(base_ref) => base_ref,
2881-
Err(_) => unsafe { core::hint::unreachable_unchecked() },
2882-
}
2880+
// PySubclass establishes the physical prefix; Python may have changed
2881+
// the object's class or MRO since this typed reference was constructed.
2882+
let ptr = self.ptr.cast();
2883+
core::mem::forget(self);
2884+
PyRef { ptr }
28832885
}
28842886
#[inline]
28852887
#[must_use]
28862888
pub fn upcast<U: PyPayload + StaticType>(self) -> PyRef<U>
28872889
where
28882890
T: StaticType,
28892891
{
2890-
debug_assert!(T::static_type().is_subtype(U::static_type()));
28912892
let obj: PyObjectRef = self.into();
2892-
match obj.downcast::<U>() {
2893-
Ok(upcast_ref) => upcast_ref,
2894-
Err(_) => unsafe { core::hint::unreachable_unchecked() },
2895-
}
2893+
obj.downcast::<U>().expect("invalid native upcast")
28962894
}
28972895
}
28982896

28992897
impl<T: crate::class::PySubclass> Py<T> {
29002898
/// Converts `&Py<T>` to `&Py<T::Base>`.
29012899
#[inline]
29022900
pub fn to_base(&self) -> &Py<T::Base> {
2903-
debug_assert!(self.as_object().downcast_ref::<T::Base>().is_some());
29042901
// SAFETY: T is #[repr(transparent)] over T::Base,
29052902
// so Py<T> and Py<T::Base> have the same layout.
29062903
unsafe { &*(self as *const Self as *const Py<T::Base>) }
@@ -2912,9 +2909,9 @@ impl<T: crate::class::PySubclass> Py<T> {
29122909
where
29132910
T: StaticType,
29142911
{
2915-
debug_assert!(T::static_type().is_subtype(U::static_type()));
2916-
// SAFETY: T is a subtype of U, so Py<T> can be viewed as Py<U>.
2917-
unsafe { &*(self as *const Self as *const Py<U>) }
2912+
self.as_object()
2913+
.downcast_ref::<U>()
2914+
.expect("invalid native upcast")
29182915
}
29192916
}
29202917

@@ -3248,6 +3245,104 @@ pub(crate) fn init_type_hierarchy() -> BootstrapTypeHierarchy {
32483245
mod tests {
32493246
use super::*;
32503247

3248+
#[test]
3249+
fn native_downcasts_validate_the_allocation() {
3250+
use crate::{
3251+
builtins::builtin_func::{PyNativeFunction, PyNativeMethod},
3252+
class::PyClassImpl,
3253+
function::{ItemDoc, PyMethodDef, PyMethodFlags},
3254+
};
3255+
3256+
#[pyclass(module = false, name = "AllocationBase")]
3257+
#[derive(Debug, PyPayload)]
3258+
struct AllocationBase {
3259+
value: usize,
3260+
}
3261+
3262+
#[pyclass(flags(BASETYPE))]
3263+
impl AllocationBase {}
3264+
3265+
#[pyclass(module = false, name = "AllocationDerived", base = AllocationBase)]
3266+
#[derive(Debug)]
3267+
struct AllocationDerived {
3268+
base: AllocationBase,
3269+
value: usize,
3270+
}
3271+
3272+
#[pyclass]
3273+
impl AllocationDerived {}
3274+
3275+
crate::Interpreter::without_stdlib(Default::default()).enter(|vm| {
3276+
let _ = AllocationBase::make_static_type();
3277+
let derived = AllocationDerived::make_static_type();
3278+
// A class reference does not enlarge the allocated Rust payload.
3279+
let base = PyRef::new_ref(AllocationBase { value: 5 }, derived.clone(), None);
3280+
assert!(!base.as_object().downcastable::<AllocationDerived>());
3281+
assert!(
3282+
base.as_object()
3283+
.downcast_ref_if_exact::<AllocationDerived>(vm)
3284+
.is_none()
3285+
);
3286+
assert!(
3287+
base.as_object()
3288+
.to_owned()
3289+
.downcast_exact::<AllocationDerived>(vm)
3290+
.is_err()
3291+
);
3292+
let actual = PyRef::new_ref(
3293+
AllocationDerived {
3294+
base: AllocationBase { value: 5 },
3295+
value: 17,
3296+
},
3297+
derived,
3298+
None,
3299+
);
3300+
assert_eq!(
3301+
actual
3302+
.as_object()
3303+
.downcast_ref::<AllocationDerived>()
3304+
.unwrap()
3305+
.value,
3306+
17
3307+
);
3308+
assert_eq!(
3309+
actual
3310+
.as_object()
3311+
.downcast_ref::<AllocationBase>()
3312+
.unwrap()
3313+
.value,
3314+
5
3315+
);
3316+
3317+
static METHOD: PyMethodDef = PyMethodDef::new_const(
3318+
"identity",
3319+
|value: PyObjectRef| value,
3320+
PyMethodFlags::METHOD,
3321+
ItemDoc::NONE,
3322+
);
3323+
let function = METHOD.build_function(&vm.ctx);
3324+
// CFunction and CMethod share a Python class, but not a Rust layout.
3325+
assert!(!function.as_object().downcastable::<PyNativeMethod>());
3326+
assert!(
3327+
function
3328+
.as_object()
3329+
.downcast_ref_if_exact::<PyNativeMethod>(vm)
3330+
.is_none()
3331+
);
3332+
assert!(
3333+
function
3334+
.as_object()
3335+
.to_owned()
3336+
.downcast_exact::<PyNativeMethod>(vm)
3337+
.is_err()
3338+
);
3339+
let method =
3340+
METHOD.build_bound_method(&vm.ctx, vm.ctx.none(), vm.ctx.types.object_type);
3341+
assert!(method.as_object().downcastable::<PyNativeMethod>());
3342+
assert!(method.as_object().downcastable::<PyNativeFunction>());
3343+
});
3344+
}
3345+
32513346
#[test]
32523347
fn native_type_basicsize_includes_payload_padding() {
32533348
use crate::class::PyClassDef;

0 commit comments

Comments
 (0)