@@ -786,18 +786,36 @@ impl PyCData {
786786 /// lives as long as the owning ctypes object.
787787 /// Uses unique_key (hierarchical) so nested fields don't collide.
788788 pub fn keep_alive ( & self , index : usize , obj : PyObjectRef ) {
789+ drop ( self . replace_hidden ( index, Some ( obj) ) ) ;
790+ }
791+
792+ fn replace_hidden ( & self , index : usize , obj : Option < PyObjectRef > ) -> Option < PyObjectRef > {
789793 let key = self . unique_key ( index) ;
790794 let base = self . base . read ( ) . clone ( ) ;
791- if let Some ( base_obj) = base {
792- let root = Self :: find_root_object ( & base_obj) ;
793- if let Some ( cdata) = root. downcast_ref :: < Self > ( ) {
794- let old = cdata. kept_refs . write ( ) . insert ( key, obj) ;
795- drop ( old) ;
796- return ;
797- }
795+ let root = base. as_ref ( ) . map ( |base| Self :: find_root_object ( base) ) ;
796+ let cdata = root
797+ . as_ref ( )
798+ . and_then ( |root| root. downcast_ref :: < Self > ( ) )
799+ . map_or ( self , |cdata| cdata) ;
800+ let mut refs = cdata. kept_refs . write ( ) ;
801+ match obj {
802+ Some ( obj) => refs. insert ( key, obj) ,
803+ None => refs. remove ( & key) ,
798804 }
799- let old = self . kept_refs . write ( ) . insert ( key, obj) ;
800- drop ( old) ;
805+ }
806+
807+ pub ( super ) fn keep_ref_with_hidden (
808+ & self ,
809+ index : usize ,
810+ keep : PyObjectRef ,
811+ hidden : Option < PyObjectRef > ,
812+ vm : & VirtualMachine ,
813+ ) -> PyResult < ( ) > {
814+ // Publish all owners before dropping the old visible reference: its
815+ // finalizer may overwrite this same slot. Keep old storage alive until
816+ // then, and do not overwrite the finalizer's owners afterwards.
817+ let _old_hidden = self . replace_hidden ( index, hidden) ;
818+ self . keep_ref ( index, keep, vm)
801819 }
802820
803821 /// Find the root object (one without a base) by walking up the base chain
@@ -879,15 +897,18 @@ impl PyCData {
879897 . downcast_ref :: < Self > ( )
880898 . map ( |cdata| cdata. kept_refs . read ( ) . values ( ) . cloned ( ) . collect ( ) )
881899 . unwrap_or_default ( ) ;
882- self . keep_ref ( index, Self :: get_kept_objects ( & root, vm) , vm) ?;
883- if !hidden. is_empty ( ) {
884- self . keep_alive ( index, vm. ctx . new_tuple ( hidden) . into ( ) ) ;
885- }
886- Ok ( ( ) )
900+ let hidden = ( !hidden. is_empty ( ) ) . then ( || vm. ctx . new_tuple ( hidden) . into ( ) ) ;
901+ self . keep_ref_with_hidden ( index, Self :: get_kept_objects ( & root, vm) , hidden, vm)
887902 }
888903
889904 // A scalar owns one reference; a scalar view stores it in its root instead.
890- pub ( super ) fn keep_value ( & self , value : PyObjectRef , vm : & VirtualMachine ) -> PyResult < ( ) > {
905+ pub ( super ) fn keep_value (
906+ & self ,
907+ value : PyObjectRef ,
908+ hidden : Option < PyObjectRef > ,
909+ vm : & VirtualMachine ,
910+ ) -> PyResult < ( ) > {
911+ let _old_hidden = self . replace_hidden ( 0 , hidden) ;
891912 if self . base . read ( ) . is_some ( ) {
892913 self . keep_ref ( 0 , value, vm)
893914 } else {
@@ -897,6 +918,42 @@ impl PyCData {
897918 }
898919 }
899920
921+ // Resolve a py_object through owned references, never by turning an
922+ // arbitrary integer from native memory into a Rust reference. Views can
923+ // reach the object through nested _objects dictionaries or cast cycles.
924+ pub ( super ) fn object_at ( & self , address : usize , vm : & VirtualMachine ) -> PyResult {
925+ if address == 0 {
926+ return Err ( vm. new_value_error ( "PyObject is NULL" ) ) ;
927+ }
928+ if address == vm. ctx . none . get_id ( ) {
929+ return Ok ( vm. ctx . none ( ) ) ;
930+ }
931+ let mut pending: Vec < _ > = self . objects . read ( ) . iter ( ) . cloned ( ) . collect ( ) ;
932+ pending. extend ( self . base . read ( ) . iter ( ) . cloned ( ) ) ;
933+ pending. extend ( self . kept_refs . read ( ) . values ( ) . cloned ( ) ) ;
934+ let mut visited = std:: collections:: HashSet :: new ( ) ;
935+ while let Some ( obj) = pending. pop ( ) {
936+ if obj. get_id ( ) == address {
937+ return Ok ( obj) ;
938+ }
939+ if !visited. insert ( obj. get_id ( ) ) {
940+ continue ;
941+ }
942+ if let Some ( cdata) = obj. downcast_ref :: < Self > ( ) {
943+ pending. extend ( cdata. objects . read ( ) . iter ( ) . cloned ( ) ) ;
944+ pending. extend ( cdata. base . read ( ) . iter ( ) . cloned ( ) ) ;
945+ pending. extend ( cdata. kept_refs . read ( ) . values ( ) . cloned ( ) ) ;
946+ } else if let Some ( dict) = obj. downcast_ref :: < PyDict > ( ) {
947+ pending. extend ( dict. values_vec ( ) ) ;
948+ } else if let Some ( tuple) = obj. downcast_ref :: < PyTuple > ( ) {
949+ pending. extend ( tuple. as_slice ( ) . iter ( ) . cloned ( ) ) ;
950+ } else if let Some ( view) = obj. downcast_ref :: < PyMemoryView > ( ) {
951+ pending. push ( view. viewed_object ( ) . to_owned ( ) ) ;
952+ }
953+ }
954+ Err ( vm. new_value_error ( "PyObject is NULL" ) )
955+ }
956+
900957 /// Check if a value should be stored in _objects
901958 /// Returns true for ctypes objects and bytes (for c_char_p)
902959 pub ( crate ) fn should_keep_ref ( value : & PyObject ) -> bool {
@@ -1018,9 +1075,7 @@ impl PyCData {
10181075 let result =
10191076 rustpython_host_env:: ctypes:: pointer_to_sized_bytes_endian ( ptr, size, needs_swap) ;
10201077 self . write_bytes_at_offset ( offset, & result) ;
1021- self . keep_ref ( index, value, vm) ?;
1022- self . keep_alive ( index, kept_alive) ;
1023- return Ok ( ( ) ) ;
1078+ return self . keep_ref_with_hidden ( index, value, Some ( kept_alive) , vm) ;
10241079 }
10251080
10261081 let ( mut bytes, converted_value) = if let Some ( type_code) = & field_type_code {
0 commit comments