forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunction.rs
More file actions
1989 lines (1790 loc) · 70.2 KB
/
Copy pathfunction.rs
File metadata and controls
1989 lines (1790 loc) · 70.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// spell-checker:disable
#![allow(unreachable_pub)]
use super::{
_ctypes::CArgObject,
PyCArray, PyCData, PyCPointer, PyCStructure, StgInfo,
base::{CDATA_BUFFER_METHODS, FfiArgValue, ParamFunc, StgInfoFlags},
simple::PyCSimple,
};
use crate::{
AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
builtins::{PyBytes, PyDict, PyNone, PyStr, PyTuple, PyType, PyTypeRef},
class::StaticType,
function::FuncArgs,
protocol::{BufferDescriptor, PyBuffer, PyNumberMethods},
types::{AsBuffer, AsNumber, Callable, Constructor, Initializer, Representable},
vm::thread::with_current_vm,
};
use alloc::borrow::Cow;
use core::ffi::c_void;
use core::fmt::Debug;
use num_traits::{Signed, ToPrimitive};
use rustpython_common::lock::PyRwLock;
#[cfg(windows)]
use rustpython_host_env::ctypes::ComMethodError;
use rustpython_host_env::ctypes::{
CallResult as RawResult, FfiCif, FfiCodePtr, FfiType, FfiValue, RawMemoryView,
RawMemoryViewError, StringAtError, ffi_f64_type, ffi_i32_type, ffi_pointer_type,
ffi_type_for_return_size, ffi_type_from_code, ffi_type_from_tag, ffi_void_type,
has_pointer_width, null_code_ptr, offset_address, pointer_bytes, pointer_format, pointer_size,
write_pointer_to_buffer_at, write_prefix_limited,
};
// Internal function addresses for special ctypes functions
pub(super) const INTERNAL_CAST_ADDR: usize = 1;
pub(super) const INTERNAL_STRING_AT_ADDR: usize = 2;
pub(super) const INTERNAL_WSTRING_AT_ADDR: usize = 3;
pub(super) const INTERNAL_MEMORYVIEW_AT_ADDR: usize = 4;
// PyCFuncPtr - Function pointer implementation
/// Convert any object to a pointer value for c_void_p arguments
/// Follows ConvParam logic for pointer types
fn convert_to_pointer(value: &PyObject, vm: &VirtualMachine) -> PyResult<FfiArgValue> {
// 0. CArgObject (from byref()) -> buffer address + offset
if let Some(carg) = value.downcast_ref::<CArgObject>() {
// Get buffer address from the underlying object
let base_addr = if let Some(cdata) = carg.obj.downcast_ref::<PyCData>() {
cdata.buffer.read().as_ptr() as usize
} else {
return Err(vm.new_type_error(format!(
"byref() argument must be a ctypes instance, not '{}'",
carg.obj.class().name()
)));
};
let addr = (base_addr as isize + carg.offset) as usize;
return Ok(FfiArgValue::pointer(addr));
}
// 1. None -> NULL
if value.is(&vm.ctx.none) {
return Ok(FfiArgValue::pointer(0));
}
// 2. PyCArray -> buffer address (PyCArrayType_paramfunc)
if let Some(array) = value.downcast_ref::<PyCArray>() {
let addr = array.0.buffer.read().as_ptr() as usize;
return Ok(FfiArgValue::pointer(addr));
}
// 3. PyCPointer -> stored pointer value
if let Some(ptr) = value.downcast_ref::<PyCPointer>() {
return Ok(FfiArgValue::pointer(ptr.get_ptr_value()));
}
// 4. PyCStructure -> buffer address
if let Some(struct_obj) = value.downcast_ref::<PyCStructure>() {
let addr = struct_obj.0.buffer.read().as_ptr() as usize;
return Ok(FfiArgValue::pointer(addr));
}
// 5. PyCSimple (c_void_p, c_char_p, etc.) -> value from buffer
if let Some(simple) = value.downcast_ref::<PyCSimple>() {
let buffer = simple.0.buffer.read();
if has_pointer_width(&buffer) {
let addr = rustpython_host_env::ctypes::read_pointer_from_buffer(&buffer);
return Ok(FfiArgValue::pointer(addr));
}
}
// 6. bytes -> buffer address (PyBytes_AsString)
if let Some(bytes) = value.downcast_ref::<crate::builtins::PyBytes>() {
let addr = bytes.as_bytes().as_ptr() as usize;
return Ok(FfiArgValue::pointer(addr));
}
// 7. Integer -> direct value (PyLong_AsVoidPtr behavior)
if let Ok(int_val) = value.try_int(vm) {
let bigint = int_val.as_bigint();
// Negative values: use signed conversion (allows -1 as 0xFFFF...)
if bigint.is_negative() {
if let Some(signed_val) = bigint.to_isize() {
return Ok(FfiArgValue::pointer(signed_val as usize));
}
} else if let Some(unsigned_val) = bigint.to_usize() {
return Ok(FfiArgValue::pointer(unsigned_val));
}
// Value out of range - raise OverflowError
return Err(vm.new_overflow_error("int too large to convert to pointer"));
}
// 8. Check _as_parameter_ attribute ( recursive ConvParam)
if let Ok(as_param) = value.get_attr("_as_parameter_", vm) {
return convert_to_pointer(&as_param, vm);
}
Err(vm.new_type_error(format!(
"cannot convert '{}' to c_void_p",
value.class().name()
)))
}
/// ConvParam-like conversion for when argtypes is None
/// Returns an Argument with FFI type, value, and optional keep object
fn conv_param(value: &PyObject, vm: &VirtualMachine) -> PyResult<Argument> {
// 1. CArgObject (from byref() or paramfunc) -> use stored type and value
if let Some(carg) = value.downcast_ref::<CArgObject>() {
let ffi_type = ffi_type_from_tag(carg.tag);
return Ok(Argument {
ffi_type,
keep: None,
value: carg.value.clone(),
});
}
// 2. None -> NULL pointer
if value.is(&vm.ctx.none) {
return Ok(Argument {
ffi_type: ffi_pointer_type(),
keep: None,
value: FfiArgValue::pointer(0),
});
}
// 3. ctypes objects -> use paramfunc
if let Ok(carg) = super::base::call_paramfunc(value, vm) {
let ffi_type = ffi_type_from_tag(carg.tag);
return Ok(Argument {
ffi_type,
keep: None,
value: carg.value,
});
}
// 4. Python str -> wide string pointer (like PyUnicode_AsWideCharString)
if let Some(s) = value.downcast_ref::<PyStr>() {
let wide_bytes = rustpython_host_env::ctypes::utf16z_bytes(s.as_wtf8());
let keep = vm.ctx.new_bytes(wide_bytes);
let addr = keep.as_bytes().as_ptr() as usize;
return Ok(Argument {
ffi_type: ffi_pointer_type(),
keep: Some(keep.into()),
value: FfiArgValue::pointer(addr),
});
}
// 9. Python bytes -> null-terminated buffer pointer
// Need to ensure null termination like c_char_p
if let Some(bytes) = value.downcast_ref::<PyBytes>() {
let buffer = rustpython_host_env::ctypes::null_terminated_bytes(bytes.as_bytes());
let keep = vm.ctx.new_bytes(buffer);
let addr = keep.as_bytes().as_ptr() as usize;
return Ok(Argument {
ffi_type: ffi_pointer_type(),
keep: Some(keep.into()),
value: FfiArgValue::pointer(addr),
});
}
// 10. Python int -> i32 (default integer type)
if let Ok(int_val) = value.try_int(vm) {
let val = int_val.as_bigint().to_i32().unwrap_or(0);
return Ok(Argument {
ffi_type: ffi_i32_type(),
keep: None,
value: FfiArgValue::Scalar(FfiValue::I32(val)),
});
}
// 11. Python float -> f64
if let Ok(float_val) = value.try_float(vm) {
return Ok(Argument {
ffi_type: ffi_f64_type(),
keep: None,
value: FfiArgValue::Scalar(FfiValue::F64(float_val.to_f64())),
});
}
// 12. Check _as_parameter_ attribute
if let Ok(as_param) = value.get_attr("_as_parameter_", vm) {
return conv_param(&as_param, vm);
}
Err(vm.new_type_error(format!(
"Don't know how to convert parameter {}",
value.class().name()
)))
}
trait ArgumentType {
fn to_ffi_type(&self, vm: &VirtualMachine) -> PyResult<FfiType>;
fn convert_object(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<FfiArgValue>;
}
impl ArgumentType for PyTypeRef {
fn to_ffi_type(&self, vm: &VirtualMachine) -> PyResult<FfiType> {
use super::pointer::PyCPointer;
use super::structure::PyCStructure;
// CArgObject (from byref()) should be treated as pointer
if self.fast_issubclass(CArgObject::static_type()) {
return Ok(ffi_pointer_type());
}
// Pointer types (POINTER(T)) are always pointer FFI type
// Check if type is a subclass of _Pointer (PyCPointer)
if self.fast_issubclass(PyCPointer::static_type()) {
return Ok(ffi_pointer_type());
}
// Structure types are passed as pointers
if self.fast_issubclass(PyCStructure::static_type()) {
return Ok(ffi_pointer_type());
}
// Use get_attr to traverse MRO (for subclasses like MyInt(c_int))
let typ = self
.as_object()
.get_attr(vm.ctx.intern_str("_type_"), vm)
.ok()
.ok_or_else(|| vm.new_type_error("Unsupported argument type"))?;
let typ = typ
.downcast_ref::<PyStr>()
.ok_or_else(|| vm.new_type_error("Unsupported argument type"))?;
let typ = typ.to_string();
let typ = typ.as_str();
ffi_type_from_code(typ)
.ok_or_else(|| vm.new_type_error(format!("Unsupported argument type: {typ}")))
}
fn convert_object(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<FfiArgValue> {
// Call from_param first to convert the value
// converter = PyTuple_GET_ITEM(argtypes, i);
// v = PyObject_CallOneArg(converter, arg);
let from_param = self
.as_object()
.get_attr(vm.ctx.intern_str("from_param"), vm)?;
let converted = from_param.call((value,), vm)?;
// Then pass the converted value to ConvParam logic
// CArgObject (from from_param) -> use stored value directly
if let Some(carg) = converted.downcast_ref::<CArgObject>() {
return Ok(carg.value.clone());
}
// None -> NULL pointer
if vm.is_none(&converted) {
return Ok(FfiArgValue::pointer(0));
}
// For pointer types (POINTER(T)), we need to pass the pointer VALUE stored in buffer
if self.fast_issubclass(PyCPointer::static_type()) {
if let Some(pointer) = converted.downcast_ref::<PyCPointer>() {
return Ok(FfiArgValue::pointer(pointer.get_ptr_value()));
}
return convert_to_pointer(&converted, vm);
}
// For structure types, convert to pointer to structure
if self.fast_issubclass(PyCStructure::static_type()) {
return convert_to_pointer(&converted, vm);
}
// Get the type code for this argument type
let type_code = self
.as_object()
.get_attr(vm.ctx.intern_str("_type_"), vm)
.ok()
.and_then(|t| t.downcast_ref::<PyStr>().map(|s| s.to_string()));
// For pointer types (c_void_p, c_char_p, c_wchar_p), handle as pointer
if matches!(type_code.as_deref(), Some("P" | "z" | "Z")) {
return convert_to_pointer(&converted, vm);
}
// PyCSimple (already a ctypes instance from from_param)
if let Ok(simple) = converted.downcast::<PyCSimple>() {
let typ = ArgumentType::to_ffi_type(self, vm)?;
let ffi_value = simple
.to_ffi_value(typ, vm)
.ok_or_else(|| vm.new_type_error("Unsupported argument type"))?;
return Ok(ffi_value);
}
Err(vm.new_type_error("Unsupported argument type"))
}
}
trait ReturnType {
fn to_ffi_type(&self, vm: &VirtualMachine) -> Option<FfiType>;
}
impl ReturnType for PyTypeRef {
fn to_ffi_type(&self, vm: &VirtualMachine) -> Option<FfiType> {
// Try to get _type_ attribute first (for ctypes types like c_void_p)
if let Ok(type_attr) = self.as_object().get_attr(vm.ctx.intern_str("_type_"), vm)
&& let Some(s) = type_attr.downcast_ref::<PyStr>()
&& let Some(ffi_type) = s.to_str().and_then(ffi_type_from_code)
{
return Some(ffi_type);
}
// Check for Structure/Array types (have StgInfo but no _type_)
// _ctypes_get_ffi_type: returns appropriately sized type for struct returns
if let Some(stg_info) = self.stg_info_opt() {
let size = stg_info.size;
// Small structs can be returned in registers
// Match can_return_struct_as_int/can_return_struct_as_sint64
return Some(ffi_type_for_return_size(size));
}
// Fallback to class name
ffi_type_from_code(self.name().to_string().as_str())
}
}
impl ReturnType for PyNone {
fn to_ffi_type(&self, _vm: &VirtualMachine) -> Option<FfiType> {
ffi_type_from_code("void")
}
}
// PyCFuncPtrType - Metaclass for function pointer types
// PyCFuncPtrType_init
#[pyclass(name = "PyCFuncPtrType", base = PyType, module = "_ctypes")]
#[derive(Debug)]
#[repr(transparent)]
pub(super) struct PyCFuncPtrType(PyType);
impl Initializer for PyCFuncPtrType {
type Args = FuncArgs;
fn init(zelf: PyRef<Self>, _args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
let obj: PyObjectRef = zelf.into();
let new_type: PyTypeRef = obj
.downcast()
.map_err(|_| vm.new_type_error("expected type"))?;
new_type.check_not_initialized(vm)?;
let ptr_size = pointer_size();
let mut stg_info = StgInfo::new(ptr_size, ptr_size);
stg_info.format = Some("X{}".to_string());
stg_info.length = 1;
stg_info.flags |= StgInfoFlags::TYPEFLAG_ISPOINTER;
stg_info.paramfunc = ParamFunc::Pointer; // CFuncPtr is passed as a pointer
let _ = new_type.init_type_data(stg_info);
Ok(())
}
}
#[pyclass(flags(IMMUTABLETYPE), with(Initializer))]
impl PyCFuncPtrType {
#[pygetset(name = "__pointer_type__")]
fn pointer_type(zelf: PyTypeRef, vm: &VirtualMachine) -> PyResult {
super::base::pointer_type_get(&zelf, vm)
}
#[pygetset(name = "__pointer_type__", setter)]
fn set_pointer_type(zelf: PyTypeRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
super::base::pointer_type_set(&zelf, value, vm)
}
}
/// PyCFuncPtr - Function pointer instance
/// Saved in _base.buffer
#[pyclass(
module = "_ctypes",
name = "CFuncPtr",
base = PyCData,
metaclass = "PyCFuncPtrType"
)]
#[repr(C)]
pub(super) struct PyCFuncPtr {
pub _base: PyCData,
/// Thunk for callbacks (keeps thunk alive)
pub thunk: PyRwLock<Option<PyRef<PyCThunk>>>,
/// Original Python callable (for callbacks)
pub callable: PyRwLock<Option<PyObjectRef>>,
/// Converters cache
pub converters: PyRwLock<Option<PyObjectRef>>,
/// Instance-level argtypes override
pub argtypes: PyRwLock<Option<PyObjectRef>>,
/// Instance-level restype override
pub restype: PyRwLock<Option<PyObjectRef>>,
/// Checker function
pub checker: PyRwLock<Option<PyObjectRef>>,
/// Error checking function
pub errcheck: PyRwLock<Option<PyObjectRef>>,
/// COM method vtable index
/// When set, the function reads the function pointer from the vtable at call time
#[cfg(windows)]
pub index: PyRwLock<Option<usize>>,
/// COM method IID (interface ID) for error handling
#[cfg(windows)]
pub iid: PyRwLock<Option<PyObjectRef>>,
/// Parameter flags for COM methods (direction: IN=1, OUT=2, IN|OUT=4)
/// Each element is (direction, name, default) tuple
pub paramflags: PyRwLock<Option<PyObjectRef>>,
}
impl Debug for PyCFuncPtr {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("PyCFuncPtr")
.field("func_ptr", &self.get_func_ptr())
.finish()
}
}
/// Extract pointer value from a ctypes argument (c_void_p conversion)
fn extract_ptr_from_arg(arg: &PyObject, vm: &VirtualMachine) -> PyResult<usize> {
// Try CArgObject first - extract the wrapped pointer value, applying offset
if let Some(carg) = arg.downcast_ref::<super::_ctypes::CArgObject>() {
if carg.offset != 0
&& let Some(cdata) = carg.obj.downcast_ref::<PyCData>()
{
let base = cdata.buffer.read().as_ptr() as usize;
return Ok(offset_address(base, carg.offset));
}
return extract_ptr_from_arg(&carg.obj, vm);
}
// Try to get pointer value from various ctypes types
if let Some(ptr) = arg.downcast_ref::<PyCPointer>() {
return Ok(ptr.get_ptr_value());
}
if let Some(simple) = arg.downcast_ref::<PyCSimple>() {
let buffer = simple.0.buffer.read();
if buffer.first_chunk::<{ size_of::<usize>() }>().is_some() {
return Ok(rustpython_host_env::ctypes::read_pointer_from_buffer(
&buffer,
));
}
}
if let Some(cdata) = arg.downcast_ref::<PyCData>() {
// For arrays/structures, return address of buffer
return Ok(cdata.buffer.read().as_ptr() as usize);
}
// PyStr: return internal buffer address
if let Some(s) = arg.downcast_ref::<PyStr>() {
return Ok(s.as_bytes().as_ptr() as usize);
}
// PyBytes: return internal buffer address
if let Some(bytes) = arg.downcast_ref::<PyBytes>() {
return Ok(bytes.as_bytes().as_ptr() as usize);
}
// Try as integer
if let Ok(int_val) = arg.try_int(vm) {
return Ok(int_val.as_bigint().to_usize().unwrap_or(0));
}
Err(vm.new_type_error(format!(
"cannot convert '{}' to pointer",
arg.class().name()
)))
}
/// string_at implementation - read bytes from memory at ptr
fn string_at_impl(ptr: usize, size: isize, vm: &VirtualMachine) -> PyResult {
match rustpython_host_env::ctypes::string_at(ptr, size) {
Ok(bytes) => Ok(vm.ctx.new_bytes(bytes).into()),
Err(StringAtError::NullPointer) => Err(vm.new_value_error("NULL pointer access")),
Err(StringAtError::TooLong) => Err(vm.new_overflow_error("string too long")),
}
}
/// wstring_at implementation - read wide string from memory at ptr
fn wstring_at_impl(ptr: usize, size: isize, vm: &VirtualMachine) -> PyResult {
match rustpython_host_env::ctypes::wstring_at(ptr, size) {
Ok(text) => Ok(vm.ctx.new_str(text).into()),
Err(StringAtError::NullPointer) => Err(vm.new_value_error("NULL pointer access")),
Err(StringAtError::TooLong) => Err(vm.new_overflow_error("string too long")),
}
}
/// A buffer wrapping raw memory at a given pointer, for zero-copy memoryview.
#[pyclass(name = "_RawMemoryBuffer", module = "_ctypes")]
#[derive(Debug, PyPayload)]
pub(super) struct RawMemoryBuffer {
memory: RawMemoryView,
}
static RAW_MEMORY_BUFFER_METHODS: crate::protocol::BufferMethods = crate::protocol::BufferMethods {
obj_bytes: |buffer| {
let raw = buffer.obj_as::<RawMemoryBuffer>();
let slice = unsafe { raw.memory.bytes() };
rustpython_common::borrow::BorrowedValue::Ref(slice)
},
obj_bytes_mut: |buffer| {
let raw = buffer.obj_as::<RawMemoryBuffer>();
let slice = unsafe { raw.memory.bytes_mut() };
rustpython_common::borrow::BorrowedValueMut::RefMut(slice)
},
release: |_| {},
retain: |_| {},
};
#[pyclass(with(AsBuffer))]
impl RawMemoryBuffer {}
impl AsBuffer for RawMemoryBuffer {
fn as_buffer(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<PyBuffer> {
Ok(PyBuffer::new(
zelf.to_owned().into(),
BufferDescriptor::simple(zelf.memory.size(), zelf.memory.readonly()),
&RAW_MEMORY_BUFFER_METHODS,
))
}
}
/// memoryview_at implementation - create a memoryview from memory at ptr
fn memoryview_at_impl(ptr: usize, size: isize, readonly: bool, vm: &VirtualMachine) -> PyResult {
use crate::builtins::PyMemoryView;
let memory = RawMemoryView::new(ptr, size, readonly).map_err(|err| match err {
RawMemoryViewError::NullPointer => vm.new_value_error("NULL pointer access"),
RawMemoryViewError::NegativeSize => vm.new_value_error("negative size"),
})?;
let raw_buf = RawMemoryBuffer { memory }.into_pyobject(vm);
let mv = PyMemoryView::from_object(&raw_buf, vm)?;
Ok(mv.into_pyobject(vm))
}
// cast_check_pointertype
fn cast_check_pointertype(ctype: &PyObject, vm: &VirtualMachine) -> bool {
use super::pointer::PyCPointerType;
// PyCPointerTypeObject_Check
if ctype.class().fast_issubclass(PyCPointerType::static_type()) {
return true;
}
// PyCFuncPtrTypeObject_Check - TODO
// simple pointer types via StgInfo.proto (c_void_p, c_char_p, etc.)
if let Ok(type_attr) = ctype.get_attr("_type_", vm)
&& let Some(s) = type_attr.downcast_ref::<PyStr>()
{
let c = s
.to_str()
.expect("_type_ is validated as ASCII at type creation");
if c.len() == 1 && "sPzUZXO".contains(c) {
return true;
}
}
false
}
/// cast implementation
/// _ctypes.c cast()
pub(super) fn cast_impl(
obj: PyObjectRef,
src: PyObjectRef,
ctype: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult {
// 1. cast_check_pointertype
if !cast_check_pointertype(&ctype, vm) {
return Err(vm.new_type_error(format!(
"cast() argument 2 must be a pointer type, not {}",
ctype.class().name()
)));
}
// 2. Extract pointer value - matches c_void_p_from_param_impl order
let ptr_value: usize = if vm.is_none(&obj) {
// None → NULL pointer
0
} else if let Ok(int_val) = obj.try_int(vm) {
// int/long → direct pointer value
int_val.as_bigint().to_usize().unwrap_or(0)
} else if let Some(bytes) = obj.downcast_ref::<PyBytes>() {
// bytes → buffer address (c_void_p_from_param: PyBytes_Check)
bytes.as_bytes().as_ptr() as usize
} else if let Some(s) = obj.downcast_ref::<PyStr>() {
// unicode/str → buffer address (c_void_p_from_param: PyUnicode_Check)
s.as_bytes().as_ptr() as usize
} else if let Some(ptr) = obj.downcast_ref::<PyCPointer>() {
// Pointer instance → contained pointer value
ptr.get_ptr_value()
} else if let Some(simple) = obj.downcast_ref::<PyCSimple>() {
// Simple type (c_void_p, c_char_p, etc.) → value from buffer
let buffer = simple.0.buffer.read();
rustpython_host_env::ctypes::read_pointer_from_buffer(&buffer)
} else if let Some(cdata) = obj.downcast_ref::<PyCData>() {
// Array, Structure, Union → buffer address (b_ptr)
cdata.buffer.read().as_ptr() as usize
} else {
return Err(vm.new_type_error(format!(
"cast() argument 1 must be a ctypes instance, not {}",
obj.class().name()
)));
};
// 3. Create result instance
let result = ctype.call((), vm)?;
// 4. _objects reference tracking
// Share _objects dict between source and result, add id(src): src
if src.class().fast_issubclass(PyCData::static_type()) {
// Get the source's _objects, create dict if needed
let shared_objects: PyObjectRef = if let Some(src_cdata) = src.downcast_ref::<PyCData>() {
let mut src_objects = src_cdata.objects.write();
if src_objects.is_none() {
// Create new dict
let dict = vm.ctx.new_dict();
*src_objects = Some(dict.clone().into());
dict.into()
} else if let Some(obj) = src_objects.as_ref() {
if obj.downcast_ref::<PyDict>().is_none() {
// Convert to dict (keep existing reference)
let dict = vm.ctx.new_dict();
let id_key: PyObjectRef = vm.ctx.new_int(obj.get_id() as i64).into();
let _ = dict.set_item(&*id_key, obj.clone(), vm);
*src_objects = Some(dict.clone().into());
dict.into()
} else {
obj.clone()
}
} else {
vm.ctx.new_dict().into()
}
} else {
vm.ctx.new_dict().into()
};
// Add id(src): src to the shared dict
if let Some(dict) = shared_objects.downcast_ref::<PyDict>() {
let id_key: PyObjectRef = vm.ctx.new_int(src.get_id() as i64).into();
let _ = dict.set_item(&*id_key, src, vm);
}
// Set result's _objects to the shared dict
if let Some(result_cdata) = result.downcast_ref::<PyCData>() {
*result_cdata.objects.write() = Some(shared_objects);
}
}
// 5. Store pointer value
if let Some(ptr) = result.downcast_ref::<PyCPointer>() {
ptr.set_ptr_value(ptr_value);
} else if let Some(cdata) = result.downcast_ref::<PyCData>() {
let mut buffer = cdata.buffer.write();
write_pointer_to_buffer_at(buffer.to_mut(), 0, pointer_size(), ptr_value);
}
Ok(result)
}
impl PyCFuncPtr {
/// Get function pointer address from buffer
fn get_func_ptr(&self) -> usize {
let buffer = self._base.buffer.read();
rustpython_host_env::ctypes::read_pointer_from_buffer(&buffer)
}
/// Get CodePtr from buffer for FFI calls
fn get_code_ptr(&self) -> Option<FfiCodePtr> {
let addr = self.get_func_ptr();
rustpython_host_env::ctypes::code_ptr_from_addr(addr)
}
/// Create buffer with function pointer address
fn make_ptr_buffer(addr: usize) -> Vec<u8> {
pointer_bytes(addr)
}
}
impl Constructor for PyCFuncPtr {
type Args = FuncArgs;
fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
// Handle different argument forms:
// 1. Empty args: create uninitialized (NULL pointer)
// 2. One integer argument: function address
// 3. Tuple argument: (name, dll) form
// 4. Callable: callback creation
let ptr_size = pointer_size();
if args.args.is_empty() {
return Self {
_base: PyCData::from_bytes(vec![0u8; ptr_size], None),
thunk: PyRwLock::new(None),
callable: PyRwLock::new(None),
converters: PyRwLock::new(None),
argtypes: PyRwLock::new(None),
restype: PyRwLock::new(None),
checker: PyRwLock::new(None),
errcheck: PyRwLock::new(None),
#[cfg(windows)]
index: PyRwLock::new(None),
#[cfg(windows)]
iid: PyRwLock::new(None),
paramflags: PyRwLock::new(None),
}
.into_ref_with_type(vm, cls)
.map(Into::into);
}
let first_arg = &args.args[0];
// Check for COM method form: (index, name, [paramflags], [iid])
// First arg is integer (vtable index), second arg is string (method name)
if args.args.len() >= 2
&& first_arg.try_int(vm).is_ok()
&& args.args[1].downcast_ref::<PyStr>().is_some()
{
#[cfg(windows)]
let index = first_arg.try_int(vm)?.as_bigint().to_usize().unwrap_or(0);
// args[3] is iid (GUID struct, optional)
// Also check if args[2] is a GUID (has Data1 attribute) when args[3] is not present
#[cfg(windows)]
let iid = args.args.get(3).cloned().or_else(|| {
args.args.get(2).and_then(|arg| {
// If it's a GUID struct (has Data1 attribute), use it as IID
if arg.get_attr("Data1", vm).is_ok() {
Some(arg.clone())
} else {
None
}
})
});
// args[2] is paramflags (tuple or None)
let paramflags = args.args.get(2).filter(|arg| !vm.is_none(arg)).cloned();
return Self {
_base: PyCData::from_bytes(vec![0u8; ptr_size], None),
thunk: PyRwLock::new(None),
callable: PyRwLock::new(None),
converters: PyRwLock::new(None),
argtypes: PyRwLock::new(None),
restype: PyRwLock::new(None),
checker: PyRwLock::new(None),
errcheck: PyRwLock::new(None),
#[cfg(windows)]
index: PyRwLock::new(Some(index)),
#[cfg(windows)]
iid: PyRwLock::new(iid),
paramflags: PyRwLock::new(paramflags),
}
.into_ref_with_type(vm, cls)
.map(Into::into);
}
// Check if first argument is an integer (function address)
if let Ok(addr) = first_arg.try_int(vm) {
let ptr_val = addr.as_bigint().to_usize().unwrap_or(0);
return Self {
_base: PyCData::from_bytes(Self::make_ptr_buffer(ptr_val), None),
thunk: PyRwLock::new(None),
callable: PyRwLock::new(None),
converters: PyRwLock::new(None),
argtypes: PyRwLock::new(None),
restype: PyRwLock::new(None),
checker: PyRwLock::new(None),
errcheck: PyRwLock::new(None),
#[cfg(windows)]
index: PyRwLock::new(None),
#[cfg(windows)]
iid: PyRwLock::new(None),
paramflags: PyRwLock::new(None),
}
.into_ref_with_type(vm, cls)
.map(Into::into);
}
// Check if first argument is a tuple (name, dll) form
if let Some(tuple) = first_arg.downcast_ref::<PyTuple>() {
let name = tuple
.first()
.ok_or_else(|| vm.new_type_error("Expected a tuple with at least 2 elements"))?
.downcast_ref::<PyStr>()
.ok_or_else(|| vm.new_type_error("Expected a string"))?
.to_string();
let dll = tuple
.iter()
.nth(1)
.ok_or_else(|| vm.new_type_error("Expected a tuple with at least 2 elements"))?
.clone();
// Get library handle and load function
let handle = dll.try_int(vm);
let handle = match handle {
Ok(handle) => handle.as_bigint().clone(),
Err(_) => dll
.get_attr("_handle", vm)?
.try_int(vm)?
.as_bigint()
.clone(),
};
let terminated = format!("{}\0", &name);
let ptr_val = match rustpython_host_env::ctypes::lookup_function_symbol_addr(
handle
.to_usize()
.ok_or_else(|| vm.new_value_error("Invalid handle"))?,
terminated.as_bytes(),
) {
Ok(addr) => {
if addr == 0 {
return Err(vm.new_attribute_error(format!("function '{name}' not found")));
}
addr
}
Err(rustpython_host_env::ctypes::LookupSymbolError::LibraryNotFound) => {
return Err(vm.new_value_error("Library not found"));
}
Err(rustpython_host_env::ctypes::LookupSymbolError::LibraryClosed) => 0,
Err(rustpython_host_env::ctypes::LookupSymbolError::Load(err)) => {
return Err(vm.new_attribute_error(err));
}
};
return Self {
_base: PyCData::from_bytes(Self::make_ptr_buffer(ptr_val), None),
thunk: PyRwLock::new(None),
callable: PyRwLock::new(None),
converters: PyRwLock::new(None),
argtypes: PyRwLock::new(None),
restype: PyRwLock::new(None),
checker: PyRwLock::new(None),
errcheck: PyRwLock::new(None),
#[cfg(windows)]
index: PyRwLock::new(None),
#[cfg(windows)]
iid: PyRwLock::new(None),
paramflags: PyRwLock::new(None),
}
.into_ref_with_type(vm, cls)
.map(Into::into);
}
// Check if first argument is a Python callable (callback creation)
if first_arg.is_callable() {
// Get argument types and result type from the class
let class_argtypes = cls.get_attr(vm.ctx.intern_str("_argtypes_"));
let class_restype = cls.get_attr(vm.ctx.intern_str("_restype_"));
let class_flags = cls
.get_attr(vm.ctx.intern_str("_flags_"))
.and_then(|f| f.try_to_value::<u32>(vm).ok())
.unwrap_or(0);
// Create the thunk (C-callable wrapper for the Python function)
let thunk = PyCThunk::new(
first_arg.clone(),
class_argtypes.clone(),
class_restype.clone(),
class_flags,
vm,
)?;
let code_ptr = thunk.code_ptr();
let ptr_val = code_ptr.0 as usize;
// Store the thunk as a Python object to keep it alive
let thunk_ref: PyRef<PyCThunk> = thunk.into_ref(&vm.ctx);
return Self {
_base: PyCData::from_bytes(Self::make_ptr_buffer(ptr_val), None),
thunk: PyRwLock::new(Some(thunk_ref)),
callable: PyRwLock::new(Some(first_arg.clone())),
converters: PyRwLock::new(None),
argtypes: PyRwLock::new(class_argtypes),
restype: PyRwLock::new(class_restype),
checker: PyRwLock::new(None),
errcheck: PyRwLock::new(None),
#[cfg(windows)]
index: PyRwLock::new(None),
#[cfg(windows)]
iid: PyRwLock::new(None),
paramflags: PyRwLock::new(None),
}
.into_ref_with_type(vm, cls)
.map(Into::into);
}
Err(vm.new_type_error("Expected an integer address or a tuple"))
}
fn py_new(_cls: &Py<PyType>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> {
unimplemented!("use slot_new")
}
}
// PyCFuncPtr call helpers (similar to callproc.c flow)
/// Handle internal function addresses (PYFUNCTYPE special cases)
/// Returns Some(result) if handled, None if should continue with normal call
fn handle_internal_func(addr: usize, args: &FuncArgs, vm: &VirtualMachine) -> Option<PyResult> {
if addr == INTERNAL_CAST_ADDR {
let result: PyResult<(PyObjectRef, PyObjectRef, PyObjectRef)> = args.clone().bind(vm);
return Some(result.and_then(|(obj, src, ctype)| cast_impl(obj, src, ctype, vm)));
}
if addr == INTERNAL_STRING_AT_ADDR {
let result: PyResult<(PyObjectRef, Option<PyObjectRef>)> = args.clone().bind(vm);
return Some(result.and_then(|(ptr_arg, size_arg)| {
let ptr = extract_ptr_from_arg(&ptr_arg, vm)?;
let size = size_arg
.and_then(|s| s.try_int(vm).ok())
.and_then(|i| i.as_bigint().to_isize())
.unwrap_or(-1);
string_at_impl(ptr, size, vm)
}));
}
if addr == INTERNAL_WSTRING_AT_ADDR {
let result: PyResult<(PyObjectRef, Option<PyObjectRef>)> = args.clone().bind(vm);
return Some(result.and_then(|(ptr_arg, size_arg)| {
let ptr = extract_ptr_from_arg(&ptr_arg, vm)?;
let size = size_arg
.and_then(|s| s.try_int(vm).ok())
.and_then(|i| i.as_bigint().to_isize())
.unwrap_or(-1);
wstring_at_impl(ptr, size, vm)
}));
}
if addr == INTERNAL_MEMORYVIEW_AT_ADDR {
let result: PyResult<(PyObjectRef, PyObjectRef, Option<PyObjectRef>)> =
args.clone().bind(vm);
return Some(result.and_then(|(ptr_arg, size_arg, readonly_arg)| {
let ptr = extract_ptr_from_arg(&ptr_arg, vm)?;
let size_int = size_arg.try_int(vm)?;
let size = size_int
.as_bigint()
.to_isize()
.ok_or_else(|| vm.new_value_error("size too large"))?;
let readonly = readonly_arg
.and_then(|r| r.try_int(vm).ok())
.and_then(|i| i.as_bigint().to_i32())
.unwrap_or(0)
!= 0;
memoryview_at_impl(ptr, size, readonly, vm)
}));
}
None
}
/// Call information extracted from PyCFuncPtr (argtypes, restype, etc.)
struct CallInfo {
explicit_arg_types: Option<Vec<PyTypeRef>>,
restype_obj: Option<PyObjectRef>,
restype_is_none: bool,
ffi_return_type: FfiType,
is_pointer_return: bool,
}
/// Extract call information (argtypes, restype) from PyCFuncPtr
fn extract_call_info(zelf: &Py<PyCFuncPtr>, vm: &VirtualMachine) -> PyResult<CallInfo> {
// Get argtypes - first from instance, then from type's _argtypes_
let explicit_arg_types: Option<Vec<PyTypeRef>> =
if let Some(argtypes_obj) = zelf.argtypes.read().as_ref() {
if !vm.is_none(argtypes_obj) {
Some(
argtypes_obj
.try_to_value::<Vec<PyObjectRef>>(vm)?
.into_iter()
.filter_map(|obj| obj.downcast::<PyType>().ok())
.collect(),
)
} else {
None // argtypes is None -> use ConvParam
}
} else if let Some(class_argtypes) = zelf
.as_object()
.class()
.get_attr(vm.ctx.intern_str("_argtypes_"))
&& !vm.is_none(&class_argtypes)
{
Some(
class_argtypes
.try_to_value::<Vec<PyObjectRef>>(vm)?
.into_iter()
.filter_map(|obj| obj.downcast::<PyType>().ok())
.collect(),
)