Skip to content

Commit 6dd75f6

Browse files
committed
Fix ctypes effective field types and overlapping pointer copies
Assisted-by: Codex:GPT-6
1 parent f23e581 commit 6dd75f6

5 files changed

Lines changed: 67 additions & 52 deletions

File tree

‎crates/vm/src/stdlib/_ctypes/base.rs‎

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1093,6 +1093,12 @@ impl PyCData {
10931093
.class()
10941094
.fast_issubclass(super::pointer::PyCPointerType::static_type())
10951095
&& let Some(array) = value.downcast_ref::<super::array::PyCArray>()
1096+
&& proto_type.stg_info(vm)?.proto().is(array
1097+
.class()
1098+
.stg_info(vm)?
1099+
.element_type
1100+
.as_deref()
1101+
.expect("array has element type"))
10961102
{
10971103
let buffer_addr = {
10981104
let array_buffer = array.0.buffer.read();
@@ -1104,6 +1110,17 @@ impl PyCData {
11041110
return Ok(());
11051111
}
11061112

1113+
if value.downcast_ref::<Self>().is_some() {
1114+
return Err(vm.new_type_error(format!(
1115+
"incompatible types, {} instance instead of {} instance",
1116+
value.class().name(),
1117+
proto
1118+
.downcast_ref::<PyType>()
1119+
.ok_or_else(|| vm.new_type_error("field proto is not a type"))?
1120+
.name()
1121+
)));
1122+
}
1123+
11071124
// For array fields with tuple/list input, instantiate the array type
11081125
// and unpack elements as positional args (Array_init expects *args)
11091126
if let Some(proto_type) = proto.downcast_ref::<PyType>()
@@ -1269,12 +1286,7 @@ impl PyCData {
12691286
// Simple types: return primitive value
12701287
if proto_metaclass.fast_issubclass(super::simple::PyCSimpleType::static_type()) {
12711288
// Check for byte swapping
1272-
let needs_swap = base_obj
1273-
.class()
1274-
.as_object()
1275-
.get_attr("_swappedbytes_", vm)
1276-
.is_ok()
1277-
|| super::simple::is_swapped(&proto_type);
1289+
let needs_swap = super::simple::is_swapped(&proto_type);
12781290

12791291
let data = if needs_swap && size > 1 {
12801292
let mut swapped = buffer_data;
@@ -1922,13 +1934,7 @@ impl Py<PyCField> {
19221934
match value {
19231935
PySetterValue::Assign(value) => {
19241936
// Check if needs byte swapping
1925-
let needs_swap = (obj
1926-
.class()
1927-
.as_object()
1928-
.get_attr("_swappedbytes_", vm)
1929-
.is_ok()
1930-
|| super::simple::is_swapped(&zelf.proto))
1931-
&& size > 1;
1937+
let needs_swap = super::simple::is_swapped(&zelf.proto) && size > 1;
19321938

19331939
// PyCData_set
19341940
cdata.set_field(

‎crates/vm/src/stdlib/_ctypes/pointer.rs‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -612,11 +612,14 @@ impl PyCPointer {
612612
|| cdata.fast_isinstance(PyCArray::static_type())
613613
|| cdata.fast_isinstance(PyCSimple::static_type()))
614614
{
615-
let src_buffer = cdata.buffer.read();
615+
// The value may be a view of this element or overlapping storage.
616+
let bytes = {
617+
let buffer = cdata.buffer.read();
618+
rustpython_host_env::ctypes::copy_to_sized_bytes(&buffer, element_size)
619+
};
616620
unsafe {
617-
rustpython_host_env::ctypes::copy_bytes_to_address(addr, &src_buffer, element_size);
621+
rustpython_host_env::ctypes::copy_bytes_to_address(addr, &bytes, element_size);
618622
}
619-
drop(src_buffer);
620623
zelf.0.keep_cdata(index as usize, &value, vm)
621624
} else {
622625
// Handle z/Z specially to store converted value

‎crates/vm/src/stdlib/_ctypes/simple.rs‎

Lines changed: 14 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -570,7 +570,9 @@ impl Initializer for PyCSimpleType {
570570
super::base::set_or_init_stginfo(&type_ref, stg_info);
571571

572572
// Create __ctype_le__ and __ctype_be__ swapped types
573-
create_swapped_types(&type_ref, &type_str, vm)?;
573+
if type_ref.class().is(Self::static_type()) {
574+
create_swapped_types(&type_ref, &type_str, args, vm)?;
575+
}
574576

575577
Ok(())
576578
}
@@ -586,15 +588,9 @@ impl Initializer for PyCSimpleType {
586588
fn create_swapped_types(
587589
type_ref: &Py<PyType>,
588590
type_str: &str,
591+
mut args: FuncArgs,
589592
vm: &VirtualMachine,
590593
) -> PyResult<()> {
591-
use crate::builtins::PyDict;
592-
593-
// Avoid infinite recursion - if __ctype_le__ already exists, skip
594-
if type_ref.as_object().get_attr("__ctype_le__", vm).is_ok() {
595-
return Ok(());
596-
}
597-
598594
// Types that don't support byte order swapping - no __ctype_le__/__ctype_be__
599595
// c_void_p (P), c_char_p (z), c_wchar_p (Z), c_wchar (u), py_object (O)
600596
let unsupported_types = ["P", "z", "Z", "u", "O"];
@@ -618,31 +614,15 @@ fn create_swapped_types(
618614
// Check system byte order at compile time
619615
let is_little_endian = cfg!(target_endian = "little");
620616

621-
// Create dict for the swapped (non-native) type
622-
let swapped_dict: crate::PyRef<crate::builtins::PyDict> = PyDict::default().into_ref(&vm.ctx);
623-
swapped_dict.set_item("_type_", vm.ctx.new_str(type_str).into(), vm)?;
624-
625-
// Create the swapped type using the same metaclass
626-
let metaclass = type_ref.class();
627-
let bases = vm.ctx.new_tuple(vec![type_ref.as_object().to_owned()]);
628-
629-
// Set placeholder first to prevent recursion
630-
set_attrs!(
631-
type_ref.as_object(), vm,
632-
"__ctype_le__" => vm.ctx.none(),
633-
"__ctype_be__" => vm.ctx.none(),
634-
);
635-
636617
// Create only the non-native endian type
637618
let suffix = if is_little_endian { "_be" } else { "_le" };
638-
let swapped_type = metaclass.as_object().call(
639-
(
640-
vm.ctx.new_str(format!("{}{}", type_ref.name(), suffix)),
641-
bases,
642-
swapped_dict.as_object().to_owned(),
643-
),
644-
vm,
645-
)?;
619+
args.args[0] = vm
620+
.ctx
621+
.new_str(format!("{}{}", type_ref.name(), suffix))
622+
.into();
623+
// Endian variants share bases and class attributes; neither subclasses
624+
// the other. Bypass the initializer to avoid generating another pair.
625+
let swapped_type = PyType::slot_new(type_ref.class().to_owned(), args, vm)?;
646626

647627
// Set _swappedbytes_ on the swapped type to indicate byte swapping is needed
648628
set_attrs!(
@@ -651,15 +631,15 @@ fn create_swapped_types(
651631
);
652632

653633
// Update swapped type's StgInfo format to use opposite endian prefix
654-
if let Ok(swapped_type_ref) = swapped_type.clone().downcast::<PyType>()
655-
&& let Some(mut sw_stg) = swapped_type_ref.get_type_data_mut::<StgInfo>()
656-
{
634+
if let Ok(swapped_type_ref) = swapped_type.clone().downcast::<PyType>() {
635+
let mut sw_stg = type_ref.stg_info(vm)?.clone();
657636
// Swapped: little-endian system uses big-endian prefix and vice versa
658637
sw_stg.big_endian = is_little_endian;
659638
sw_stg.format = Some(alloc_format_string_for_type(
660639
type_str.chars().next().unwrap_or('?'),
661640
is_little_endian,
662641
));
642+
super::base::set_or_init_stginfo(&swapped_type_ref, sw_stg);
663643
}
664644

665645
// Set attributes based on system byte order
@@ -716,7 +696,6 @@ pub(super) fn returns_scalar(cls: &Py<PyType>) -> bool {
716696
cls.base
717697
.deref()
718698
.is_some_and(|base| base.is(PyCSimple::static_type()))
719-
|| is_swapped(cls)
720699
}
721700

722701
pub(super) fn swapped_value_bytes(

‎crates/vm/src/stdlib/_ctypes/structure.rs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,10 @@ impl Initializer for PyCStructType {
8585

8686
// Process _fields_ if defined directly on this class (not inherited)
8787
if let Some(fields_attr) = new_type.get_direct_attr(vm.ctx.intern_str("_fields_")) {
88-
Self::process_fields(&new_type, &fields_attr, vm)?;
88+
// Let the metaclass transform field types, as for later assignment.
89+
new_type
90+
.as_object()
91+
.set_attr(vm.ctx.intern_str("_fields_"), fields_attr, vm)?;
8992
} else {
9093
// No _fields_ defined - try to copy from base class (PyCStgInfo_clone)
9194
let (has_base_info, base_clone) = {

‎extra_tests/snippets/stdlib_ctypes.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -622,6 +622,9 @@ class IndexedInt(ctypes.c_int):
622622
assert type(_view) is _element
623623
assert _view._b_base_ is _owner
624624
assert ctypes.addressof(_view) == ctypes.addressof(_owner) + ctypes.sizeof(_element)
625+
_pointer = ctypes.cast(_owner, ctypes.POINTER(_element))
626+
_pointer[1] = _pointer[1]
627+
assert bytes(_pointer[1]) == bytes(_view)
625628

626629
_array = (ctypes.c_int * 2)(1, 2)
627630
_pointer = ctypes.pointer(_array)
@@ -811,3 +814,24 @@ class EndianField(_base):
811814
if _field_type is IndexedSwapped:
812815
_aggregate.word = 0x55667788
813816
assert bytes(_aggregate) == bytes(IndexedSwapped(0x55667788))
817+
818+
# Endian fields reject the native sibling rather than converting its bytes.
819+
assert not issubclass(_swapped, ctypes.c_uint32)
820+
for _base in (
821+
(ctypes.BigEndianStructure, ctypes.BigEndianUnion)
822+
if _sys.byteorder == "little"
823+
else (ctypes.LittleEndianStructure, ctypes.LittleEndianUnion)
824+
):
825+
826+
class ConvertedEndianField(_base):
827+
_fields_ = [("word", ctypes.c_uint32)]
828+
829+
assert ConvertedEndianField._fields_[0][1] is _swapped
830+
try:
831+
ConvertedEndianField(ctypes.c_uint32(0x01020304))
832+
except TypeError:
833+
pass
834+
else:
835+
raise AssertionError("incompatible native field value accepted")
836+
_value = _swapped(0x01020304)
837+
assert bytes(ConvertedEndianField(_value)) == bytes(_value)

0 commit comments

Comments
 (0)