From 36b6755ba891ca34ebf550e41c27f67b97d32c2c Mon Sep 17 00:00:00 2001 From: Chia-Hsiang Cheng Date: Sun, 15 Jan 2023 23:28:47 +0800 Subject: [PATCH] Raise TypeError when calling __new__ unsafely --- vm/src/builtins/type.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/vm/src/builtins/type.rs b/vm/src/builtins/type.rs index a0c7ee58ff..17f2d1521c 100644 --- a/vm/src/builtins/type.rs +++ b/vm/src/builtins/type.rs @@ -1308,6 +1308,24 @@ pub(crate) fn call_slot_new( args: FuncArgs, vm: &VirtualMachine, ) -> PyResult { + let mut staticbase = Some(subtype.clone()); + while let Some(ref basetype) = staticbase { + if (basetype.flags() & PyTypeFlags::HEAPTYPE.bits()) != 0 { + staticbase = basetype.base().clone(); + } else { + break; + } + } + if let Some(ref basetype) = staticbase { + if !typ.fast_issubclass(basetype) { + return Err(vm.new_type_error(format!( + "{}.__new__({}) is not safe, use {}.__new__()", + typ.name(), + subtype.name(), + basetype.name() + ))); + } + } let slot_new = typ .deref() .mro_find_map(|cls| cls.slots.new.load())