Skip to content

Commit e9178dd

Browse files
committed
Preserve ctypes assignment metadata and pointer-width writes
Assisted-by: Codex:GPT-6
1 parent eb6ff46 commit e9178dd

4 files changed

Lines changed: 54 additions & 20 deletions

File tree

‎crates/host_env/src/ctypes.rs‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1083,7 +1083,7 @@ pub fn simple_storage_value_to_bytes_endian(
10831083
}
10841084
_ => vec![0; 2],
10851085
},
1086-
"P" | "z" | "Z" => match value {
1086+
"P" | "z" | "Z" | "X" => match value {
10871087
SimpleStorageValue::Pointer(value) => {
10881088
uint_to_sized_bytes_endian(value as u64, pointer_size(), swapped)
10891089
}
@@ -2994,6 +2994,20 @@ pub fn dlsym_checked(_handle: usize, symbol_name: &CStr) -> Result<*mut c_void,
29942994
mod tests {
29952995
use super::*;
29962996

2997+
#[test]
2998+
fn bstr_storage_preserves_pointer_width() {
2999+
for address in [0, usize::MAX] {
3000+
assert_eq!(
3001+
simple_storage_value_to_bytes_endian(
3002+
"X",
3003+
SimpleStorageValue::Pointer(address),
3004+
false,
3005+
),
3006+
address.to_ne_bytes(),
3007+
);
3008+
}
3009+
}
3010+
29973011
#[test]
29983012
fn simple_type_is_pointer_classifies_codes() {
29993013
assert!(simple_type_is_pointer("z"));

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

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,8 @@ pub struct StgInfo {
8585
pub length: usize, // number of fields (for arrays/structures)
8686
pub proto: Option<PyTypeRef>, // Only for Pointer/ArrayObject
8787
pub flags: StgInfoFlags, // type flags (TYPEFLAG_*, DICTFLAG_*)
88+
// Scalar assignment uses the converter selected at type initialization.
89+
pub(super) scalar_code: Option<char>,
8890

8991
// Array-specific fields
9092
pub element_type: Option<PyTypeRef>, // _type_ for arrays
@@ -123,6 +125,7 @@ impl core::fmt::Debug for StgInfo {
123125
.field("length", &self.length)
124126
.field("proto", &self.proto)
125127
.field("flags", &self.flags)
128+
.field("scalar_code", &self.scalar_code)
126129
.field("element_type", &self.element_type)
127130
.field("element_size", &self.element_size)
128131
.field("format", &self.format)
@@ -143,6 +146,7 @@ impl Default for StgInfo {
143146
length: 0,
144147
proto: None,
145148
flags: StgInfoFlags::empty(),
149+
scalar_code: None,
146150
element_type: None,
147151
element_size: 0,
148152
format: None,
@@ -164,6 +168,7 @@ impl StgInfo {
164168
length: 0,
165169
proto: None,
166170
flags: StgInfoFlags::empty(),
171+
scalar_code: None,
167172
element_type: None,
168173
element_size: 0,
169174
format: None,
@@ -216,6 +221,7 @@ impl StgInfo {
216221
length,
217222
proto: None,
218223
flags,
224+
scalar_code: None,
219225
element_type: Some(element_type),
220226
element_size,
221227
format,
@@ -595,25 +601,16 @@ impl CDataValue {
595601
let metaclass = proto.class();
596602
let simple_metaclass = super::simple::PyCSimpleType::static_type();
597603
if metaclass.is(simple_metaclass) || metaclass.fast_issubclass(simple_metaclass) {
598-
let type_code = proto
599-
.as_object()
600-
.get_attr("_type_", vm)
601-
.ok()
602-
.and_then(|code| code.downcast::<PyStr>().ok())
603-
.ok_or_else(|| vm.new_type_error("no _type_ attribute"))?;
604-
let borrowed;
605-
let owned;
606-
let type_code = if type_code.class().is(PyStr::static_type()) {
607-
borrowed = type_code;
608-
borrowed.to_string_lossy()
609-
} else {
610-
// Preserve subclass finalization before conversion hooks run.
611-
owned = type_code.to_string();
612-
drop(type_code);
613-
Cow::Borrowed(owned.as_str())
614-
};
604+
// Reading the mutable _type_ here could select a wider converter
605+
// than the allocated slot, or change conversion during callbacks.
606+
let code = proto
607+
.stg_info(vm)?
608+
.scalar_code
609+
.ok_or_else(|| vm.new_type_error("abstract class"))?;
610+
let mut encoded = [0; 4];
611+
let type_code = code.encode_utf8(&mut encoded);
615612
let (bytes, keep, hidden) =
616-
super::simple::assignment_value(&type_code, value, swapped, vm)?;
613+
super::simple::assignment_value(type_code, value, swapped, vm)?;
617614
return Ok(Self {
618615
bytes,
619616
keep,

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -557,6 +557,7 @@ impl Initializer for PyCSimpleType {
557557
let size = simple_type_size(&type_str).expect("invalid ctypes simple type");
558558
let align = simple_type_align(&type_str).expect("invalid ctypes simple type");
559559
let mut stg_info = StgInfo::new(size, align);
560+
stg_info.scalar_code = type_str.chars().next();
560561

561562
// Set format for PEP 3118 buffer protocol
562563
stg_info.format = Some(alloc_format_string_for_type(
@@ -753,7 +754,9 @@ pub(super) fn assignment_value(
753754
keep = (!vm.is_none(value)).then(|| value.to_owned());
754755
SimpleStorageValue::ObjectId(value.get_id())
755756
}
756-
"z" | "Z" | "P" => {
757+
"z" | "Z" | "P" | "X" => {
758+
// X preserves opaque-address/null writes. BSTR string assignment
759+
// needs COM allocation and ownership, not a Z-style wide buffer.
757760
let address = if vm.is_none(value) {
758761
0
759762
} else if type_code == "z"

‎extra_tests/snippets/stdlib_ctypes.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -958,3 +958,23 @@ class OwnedStringField(ctypes.Structure):
958958
<= 1
959959
)
960960
assert _strings[0].text == _marker
961+
962+
# Mutating _type_ must not change the initialized setter or its write width.
963+
for _code in ("h", "q", "f"):
964+
965+
class MutableInt(ctypes.c_int):
966+
pass
967+
968+
_array = (MutableInt * 2)(0, 0x1234)
969+
MutableInt._type_ = _code
970+
_array[0] = -2
971+
assert bytes(_array) == bytes(ctypes.c_int(-2)) + bytes(ctypes.c_int(0x1234))
972+
973+
if _sys.platform == "win32":
974+
975+
class BSTR(ctypes._SimpleCData):
976+
_type_ = "X"
977+
978+
_bstr = (BSTR * 1)()
979+
_bstr[0] = None
980+
assert bytes(_bstr) == bytes(ctypes.sizeof(ctypes.c_void_p))

0 commit comments

Comments
 (0)