forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase.rs
More file actions
2233 lines (2006 loc) · 77 KB
/
Copy pathbase.rs
File metadata and controls
2233 lines (2006 loc) · 77 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
#![allow(unreachable_pub)]
use crate::builtins::{
PyBytes, PyDict, PyList, PyMemoryView, PyStr, PyTuple, PyType, PyTypeRef, PyUtf8Str,
};
use crate::class::StaticType;
use crate::convert::ToPyObject;
use crate::function::{ArgBytesLike, OptionalArg, PySetterValue};
use crate::protocol::{BufferMethods, PyBuffer};
use crate::types::{Constructor, GetDescriptor, Representable};
use crate::{
AsObject, Py, PyObject, PyObjectRef, PyPayload, PyResult, TryFromObject, VirtualMachine,
};
use alloc::borrow::Cow;
use core::fmt::Debug;
use crossbeam_utils::atomic::AtomicCell;
use num_traits::{Signed, ToPrimitive};
use rustpython_common::lock::PyRwLock;
use rustpython_common::wtf8::Wtf8;
use rustpython_host_env::ctypes::{
CTypeParamKind, FfiArg, FfiType, FfiValue, char_array_assignment_bytes, char_array_field_value,
ffi_arg_from_value, ffi_type_for_layout, wchar_array_field_value, write_cow_bytes_at_offset,
};
// StgInfo - Storage information for ctypes types
// Stored in TypeDataSlot of heap types (PyType::init_type_data/get_type_data)
// Flag constants
bitflags::bitflags! {
#[derive(Default, Copy, Clone, Debug, PartialEq, Eq)]
pub struct StgInfoFlags: u32 {
// Function calling convention flags
/// Standard call convention (Windows)
const FUNCFLAG_STDCALL = 0x0;
/// C calling convention
const FUNCFLAG_CDECL = 0x1;
/// Function returns HRESULT
const FUNCFLAG_HRESULT = 0x2;
/// Use Python API calling convention
const FUNCFLAG_PYTHONAPI = 0x4;
/// Capture errno after call
const FUNCFLAG_USE_ERRNO = 0x8;
/// Capture last error after call (Windows)
const FUNCFLAG_USE_LASTERROR = 0x10;
// Type flags
/// Type is a pointer type
const TYPEFLAG_ISPOINTER = 0x100;
/// Type contains pointer fields
const TYPEFLAG_HASPOINTER = 0x200;
/// Type is or contains a union
const TYPEFLAG_HASUNION = 0x400;
/// Type contains bitfield members
const TYPEFLAG_HASBITFIELD = 0x800;
// Dict flags
/// Type is finalized (_fields_ has been set)
const DICTFLAG_FINAL = 0x1000;
}
}
/// ParamFunc - determines how a type is passed to foreign functions
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) enum ParamFunc {
#[default]
None,
/// Array types are passed as pointers (tag = 'P')
Array,
/// Simple types use their specific conversion (tag = type code)
Simple,
/// Pointer types (tag = 'P')
Pointer,
/// Structure types (tag = 'V' for value)
Structure,
/// Union types (tag = 'V' for value)
Union,
}
#[derive(Clone)]
pub struct StgInfo {
pub initialized: bool,
pub size: usize, // number of bytes
pub align: usize, // alignment requirements
pub length: usize, // number of fields (for arrays/structures)
pub proto: Option<PyTypeRef>, // Only for Pointer/ArrayObject
pub flags: StgInfoFlags, // type flags (TYPEFLAG_*, DICTFLAG_*)
// Array-specific fields
pub element_type: Option<PyTypeRef>, // _type_ for arrays
pub element_size: usize, // size of each element
// PEP 3118 buffer protocol fields
pub format: Option<String>, // struct format string (e.g., "i", "(5)i")
pub shape: Vec<usize>, // shape for multi-dimensional arrays
// Function parameter conversion
pub(super) paramfunc: ParamFunc, // how to pass to foreign functions
// Byte order (for _swappedbytes_)
pub big_endian: bool, // true if big endian, false if little endian
// FFI field types for structure/union passing (inherited from base class)
pub ffi_field_types: Vec<FfiType>,
// Cached pointer type (non-inheritable via descriptor)
pub pointer_type: Option<PyObjectRef>,
}
// StgInfo is stored in type_data which requires Send + Sync.
// The PyTypeRef in proto/element_type fields is protected by the type system's locking mechanism.
// ctypes objects are not thread-safe by design; users must synchronize access.
unsafe impl Send for StgInfo {}
unsafe impl Sync for StgInfo {}
impl core::fmt::Debug for StgInfo {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("StgInfo")
.field("initialized", &self.initialized)
.field("size", &self.size)
.field("align", &self.align)
.field("length", &self.length)
.field("proto", &self.proto)
.field("flags", &self.flags)
.field("element_type", &self.element_type)
.field("element_size", &self.element_size)
.field("format", &self.format)
.field("shape", &self.shape)
.field("paramfunc", &self.paramfunc)
.field("big_endian", &self.big_endian)
.field("ffi_field_types", &self.ffi_field_types.len())
.finish()
}
}
impl Default for StgInfo {
fn default() -> Self {
Self {
initialized: false,
size: 0,
align: 1,
length: 0,
proto: None,
flags: StgInfoFlags::empty(),
element_type: None,
element_size: 0,
format: None,
shape: Vec::new(),
paramfunc: ParamFunc::None,
big_endian: cfg!(target_endian = "big"), // native endian by default
ffi_field_types: Vec::new(),
pointer_type: None,
}
}
}
impl StgInfo {
pub(crate) fn new(size: usize, align: usize) -> Self {
Self {
initialized: true,
size,
align,
length: 0,
proto: None,
flags: StgInfoFlags::empty(),
element_type: None,
element_size: 0,
format: None,
shape: Vec::new(),
paramfunc: ParamFunc::None,
big_endian: cfg!(target_endian = "big"), // native endian by default
ffi_field_types: Vec::new(),
pointer_type: None,
}
}
/// Create StgInfo for an array type
/// item_format: the innermost element's format string (kept as-is, e.g., "<i")
/// item_shape: the element's shape (will be prepended with length)
/// item_flags: the element type's flags (for HASPOINTER inheritance)
#[allow(clippy::too_many_arguments)]
pub fn new_array(
size: usize,
align: usize,
length: usize,
element_type: PyTypeRef,
element_size: usize,
item_format: Option<&str>,
item_shape: &[usize],
item_flags: StgInfoFlags,
) -> Self {
// Format is kept from innermost element (e.g., "<i" for c_int arrays)
// The array dimensions go into shape only, not format
let format = item_format.map(|f| f.to_owned());
// Build shape: [length, ...item_shape]
let mut shape = vec![length];
shape.extend_from_slice(item_shape);
// Inherit HASPOINTER flag from element type
// if (iteminfo->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER))
// stginfo->flags |= TYPEFLAG_HASPOINTER;
let flags = if item_flags
.intersects(StgInfoFlags::TYPEFLAG_ISPOINTER | StgInfoFlags::TYPEFLAG_HASPOINTER)
{
StgInfoFlags::TYPEFLAG_HASPOINTER
} else {
StgInfoFlags::empty()
};
Self {
initialized: true,
size,
align,
length,
proto: None,
flags,
element_type: Some(element_type),
element_size,
format,
shape,
paramfunc: ParamFunc::Array,
big_endian: cfg!(target_endian = "big"), // native endian by default
ffi_field_types: Vec::new(),
pointer_type: None,
}
}
/// Get libffi type for this StgInfo
/// Note: For very large types, returns pointer type to avoid overflow
pub fn to_ffi_type(&self) -> FfiType {
let kind = match self.paramfunc {
ParamFunc::Structure => CTypeParamKind::Structure,
ParamFunc::Union => CTypeParamKind::Union,
ParamFunc::Array => CTypeParamKind::Array,
ParamFunc::Pointer => CTypeParamKind::Pointer,
_ => CTypeParamKind::Simple,
};
ffi_type_for_layout(
kind,
&self.ffi_field_types,
self.size,
self.length,
self.format.as_deref(),
)
}
/// Check if this type is finalized (cannot set _fields_ again)
pub fn is_final(&self) -> bool {
self.flags.contains(StgInfoFlags::DICTFLAG_FINAL)
}
/// Get proto type reference (for Pointer/Array types)
pub fn proto(&self) -> &Py<PyType> {
self.proto.as_deref().expect("type has proto")
}
}
/// __pointer_type__ getter for ctypes metaclasses.
/// Reads from StgInfo.pointer_type (non-inheritable).
pub(super) fn pointer_type_get(zelf: &Py<PyType>, vm: &VirtualMachine) -> PyResult {
zelf.stg_info_opt()
.and_then(|info| info.pointer_type.clone())
.ok_or_else(|| {
vm.new_attribute_error(format!(
"type {} has no attribute '__pointer_type__'",
zelf.name()
))
})
}
/// __pointer_type__ setter for ctypes metaclasses.
/// Writes to StgInfo.pointer_type (non-inheritable).
pub(super) fn pointer_type_set(
zelf: &Py<PyType>,
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<()> {
if let Some(mut info) = zelf.get_type_data_mut::<StgInfo>() {
info.pointer_type = Some(value);
Ok(())
} else {
Err(vm.new_attribute_error(format!("cannot set __pointer_type__ on {}", zelf.name())))
}
}
/// Get PEP3118 format string for a field type
/// Returns the format string considering byte order
pub(super) fn get_field_format(
field_type: &PyObject,
big_endian: bool,
vm: &VirtualMachine,
) -> String {
let endian_prefix = if big_endian { ">" } else { "<" };
// 1. Check StgInfo for format
if let Some(type_obj) = field_type.downcast_ref::<PyType>()
&& let Some(stg_info) = type_obj.stg_info_opt()
&& let Some(fmt) = &stg_info.format
{
// For structures (T{...}), arrays ((n)...), and pointers (&...), return as-is
// These complex types have their own endianness markers inside
if fmt.starts_with('T')
|| fmt.starts_with('(')
|| fmt.starts_with('&')
|| fmt.starts_with("X{")
{
return fmt.clone();
}
// For simple types, replace existing endian prefix with the correct one
let base_fmt = fmt.trim_start_matches(['<', '>', '@', '=', '!']);
if !base_fmt.is_empty() {
return format!("{endian_prefix}{base_fmt}");
}
return fmt.clone();
}
// 2. Try to get _type_ attribute for simple types
if let Ok(type_attr) = field_type.get_attr("_type_", vm)
&& let Some(type_str) = type_attr.downcast_ref::<PyStr>()
{
let s = type_str
.to_str()
.expect("_type_ is validated as ASCII at type creation");
return format!("{endian_prefix}{s}");
}
// Default: single byte
"B".to_string()
}
/// Compute byte order based on swapped flag
#[inline]
pub(super) fn is_big_endian(is_swapped: bool) -> bool {
if is_swapped {
!cfg!(target_endian = "big")
} else {
cfg!(target_endian = "big")
}
}
/// Shared BufferMethods for all ctypes types (PyCArray, PyCSimple, PyCStructure, PyCUnion)
/// All these types are #[repr(transparent)] wrappers around PyCData
pub(super) static CDATA_BUFFER_METHODS: BufferMethods = BufferMethods {
obj_bytes: |buffer| {
rustpython_common::lock::PyRwLockReadGuard::map(
buffer.obj_as::<PyCData>().buffer.read(),
|x| &**x,
)
.into()
},
obj_bytes_mut: |buffer| {
rustpython_common::lock::PyRwLockWriteGuard::map(
buffer.obj_as::<PyCData>().buffer.write(),
|x| x.to_mut().as_mut_slice(),
)
.into()
},
release: |_| {},
retain: |_| {},
};
/// Ensure PyBytes data is null-terminated. Returns (kept_alive_obj, pointer).
/// The caller must keep the returned object alive to keep the pointer valid.
pub(super) fn ensure_z_null_terminated(
bytes: &PyBytes,
vm: &VirtualMachine,
) -> (PyObjectRef, usize) {
let buffer = rustpython_host_env::ctypes::null_terminated_bytes(bytes.as_bytes());
let ptr = buffer.as_ptr() as usize;
let kept_alive: PyObjectRef = vm.ctx.new_bytes(buffer).into();
(kept_alive, ptr)
}
/// Convert str to null-terminated wchar_t buffer. Returns (PyBytes holder, pointer).
pub(super) fn str_to_wchar_bytes(s: &Wtf8, vm: &VirtualMachine) -> (PyObjectRef, usize) {
let bytes = rustpython_host_env::ctypes::wchar_null_terminated_bytes(s);
let ptr = bytes.as_ptr() as usize;
let holder: PyObjectRef = vm.ctx.new_bytes(bytes).into();
(holder, ptr)
}
/// PyCData - base type for all ctypes data types
#[pyclass(name = "_CData", module = "_ctypes")]
#[derive(Debug, PyPayload)]
pub struct PyCData {
/// Memory buffer - Owned (self-owned) or Borrowed (external reference)
///
/// SAFETY: Borrowed variant's 'static lifetime is not actually static.
/// When created via from_address or from_base_obj, only valid for the lifetime of the source memory.
/// Same behavior as CPython's b_ptr (user responsibility, kept alive via b_base).
pub buffer: PyRwLock<Cow<'static, [u8]>>,
/// pointer to base object or None (b_base)
pub base: PyRwLock<Option<PyObjectRef>>,
/// byte offset within base's buffer (for field access)
pub base_offset: AtomicCell<usize>,
/// index into base's b_objects list (b_index)
pub index: AtomicCell<usize>,
/// dictionary of references we need to keep (b_objects)
pub objects: PyRwLock<Option<PyObjectRef>>,
/// number of references we need (b_length)
pub length: AtomicCell<usize>,
/// References kept alive but not visible in _objects.
/// Used for null-terminated c_char_p buffer copies, since
/// RustPython's PyBytes lacks CPython's internal trailing null.
/// Keyed by unique_key (hierarchical) so nested fields don't collide.
pub(super) kept_refs: PyRwLock<std::collections::HashMap<String, PyObjectRef>>,
}
impl PyCData {
/// Create from StgInfo (PyCData_MallocBuffer pattern)
pub(crate) fn from_stg_info(stg_info: &StgInfo) -> Self {
Self {
buffer: PyRwLock::new(Cow::Owned(vec![0u8; stg_info.size])),
base: PyRwLock::new(None),
base_offset: AtomicCell::new(0),
index: AtomicCell::new(0),
objects: PyRwLock::new(None),
length: AtomicCell::new(stg_info.length),
kept_refs: PyRwLock::new(std::collections::HashMap::new()),
}
}
/// Create from existing bytes (copies data)
pub(crate) fn from_bytes(data: Vec<u8>, objects: Option<PyObjectRef>) -> Self {
Self {
buffer: PyRwLock::new(Cow::Owned(data)),
base: PyRwLock::new(None),
base_offset: AtomicCell::new(0),
index: AtomicCell::new(0),
objects: PyRwLock::new(objects),
length: AtomicCell::new(0),
kept_refs: PyRwLock::new(std::collections::HashMap::new()),
}
}
/// Create from bytes with specified length (for arrays)
pub fn from_bytes_with_length(
data: Vec<u8>,
objects: Option<PyObjectRef>,
length: usize,
) -> Self {
Self {
buffer: PyRwLock::new(Cow::Owned(data)),
base: PyRwLock::new(None),
base_offset: AtomicCell::new(0),
index: AtomicCell::new(0),
objects: PyRwLock::new(objects),
length: AtomicCell::new(length),
kept_refs: PyRwLock::new(std::collections::HashMap::new()),
}
}
/// Create from external memory address
///
/// # Safety
/// The returned slice's 'static lifetime is a lie.
/// Actually only valid for the lifetime of the memory pointed to by ptr.
/// PyCData_AtAddress
pub unsafe fn at_address(ptr: *const u8, size: usize) -> Self {
// = PyCData_AtAddress
// SAFETY: Caller must ensure ptr is valid for the lifetime of returned PyCData
let slice = unsafe { rustpython_host_env::ctypes::borrow_memory(ptr, size) };
Self {
buffer: PyRwLock::new(Cow::Borrowed(slice)),
base: PyRwLock::new(None),
base_offset: AtomicCell::new(0),
index: AtomicCell::new(0),
objects: PyRwLock::new(None),
length: AtomicCell::new(0),
kept_refs: PyRwLock::new(std::collections::HashMap::new()),
}
}
/// Create from base object with offset and data copy
///
/// Similar to from_base_with_offset, but also stores a copy of the data.
/// This is used for arrays where we need our own buffer for the buffer protocol,
/// but still maintain the base reference for KeepRef and tracking.
pub fn from_base_with_data(
base_obj: PyObjectRef,
offset: usize,
idx: usize,
length: usize,
data: Vec<u8>,
) -> Self {
Self {
buffer: PyRwLock::new(Cow::Owned(data)), // Has its own buffer copy
base: PyRwLock::new(Some(base_obj)), // But still tracks base
base_offset: AtomicCell::new(offset), // And offset for writes
index: AtomicCell::new(idx),
objects: PyRwLock::new(None),
length: AtomicCell::new(length),
kept_refs: PyRwLock::new(std::collections::HashMap::new()),
}
}
/// Create from base object's buffer
///
/// This creates a borrowed view into the base's buffer at the given address.
/// The base object is stored in b_base to keep the memory alive.
///
/// # Safety
/// ptr must point into base_obj's buffer and remain valid as long as base_obj is alive.
pub unsafe fn from_base_obj(
ptr: *mut u8,
size: usize,
base_obj: PyObjectRef,
idx: usize,
) -> Self {
// = PyCData_FromBaseObj
// SAFETY: ptr points into base_obj's buffer, kept alive via base reference
let slice = unsafe { rustpython_host_env::ctypes::borrow_memory(ptr, size) };
Self {
buffer: PyRwLock::new(Cow::Borrowed(slice)),
base: PyRwLock::new(Some(base_obj)),
base_offset: AtomicCell::new(0),
index: AtomicCell::new(idx),
objects: PyRwLock::new(None),
length: AtomicCell::new(0),
kept_refs: PyRwLock::new(std::collections::HashMap::new()),
}
}
/// Create from buffer protocol object (for from_buffer method)
///
/// Unlike from_bytes, this shares memory with the source buffer.
/// The source object is stored in objects dict to keep the buffer alive.
/// Python stores with key -1 via KeepRef(result, -1, mv).
///
/// # Safety
/// ptr must point to valid memory that remains valid as long as source is alive.
pub unsafe fn from_buffer_shared(
ptr: *const u8,
size: usize,
length: usize,
source: PyObjectRef,
vm: &VirtualMachine,
) -> Self {
// SAFETY: Caller must ensure ptr is valid for the lifetime of source
let slice = unsafe { rustpython_host_env::ctypes::borrow_memory(ptr, size) };
// Python stores the reference in a dict with key "-1" (unique_key pattern)
let objects_dict = vm.ctx.new_dict();
objects_dict
.set_item("-1", source, vm)
.expect("Failed to store buffer reference");
Self {
buffer: PyRwLock::new(Cow::Borrowed(slice)),
base: PyRwLock::new(None),
base_offset: AtomicCell::new(0),
index: AtomicCell::new(0),
objects: PyRwLock::new(Some(objects_dict.into())),
length: AtomicCell::new(length),
kept_refs: PyRwLock::new(std::collections::HashMap::new()),
}
}
/// Common implementation for from_buffer class method.
/// Validates buffer, creates memoryview, and returns PyCData sharing memory with source.
///
/// CDataType_from_buffer_impl
pub fn from_buffer_impl(
cls: &Py<PyType>,
source: PyObjectRef,
offset: isize,
vm: &VirtualMachine,
) -> PyResult<Self> {
let (size, length) = {
let stg_info = cls
.stg_info_opt()
.ok_or_else(|| vm.new_type_error("not a ctypes type"))?;
(stg_info.size, stg_info.length)
};
if offset < 0 {
return Err(vm.new_value_error("offset cannot be negative"));
}
let offset = offset as usize;
// Get buffer from source (this exports the buffer)
let buffer = PyBuffer::try_from_object(vm, source)?;
// Check if buffer is writable
if buffer.desc.readonly {
return Err(vm.new_type_error("underlying buffer is not writable"));
}
// Check if buffer is C contiguous
if !buffer.desc.is_contiguous() {
return Err(vm.new_type_error("underlying buffer is not C contiguous"));
}
// Check if buffer is large enough
let buffer_len = buffer.desc.len;
if offset + size > buffer_len {
return Err(vm.new_value_error(format!(
"Buffer size too small ({} instead of at least {} bytes)",
buffer_len,
offset + size
)));
}
// Get buffer pointer - the memory is owned by source
let ptr = {
let bytes = buffer.obj_bytes();
bytes.as_ptr().wrapping_add(offset)
};
// Create memoryview to keep buffer exported (prevents source from being modified)
// mv = PyMemoryView_FromObject(obj); KeepRef(result, -1, mv);
let memoryview = PyMemoryView::from_buffer(buffer, vm)?;
let mv_obj = memoryview.into_pyobject(vm);
// Create CData that shares memory with the buffer
Ok(unsafe { Self::from_buffer_shared(ptr, size, length, mv_obj, vm) })
}
/// Common implementation for from_buffer_copy class method.
/// Copies data from buffer and creates new independent instance.
///
/// CDataType_from_buffer_copy_impl
pub fn from_buffer_copy_impl(
cls: &Py<PyType>,
source: &[u8],
offset: isize,
vm: &VirtualMachine,
) -> PyResult<Self> {
let (size, length) = {
let stg_info = cls
.stg_info_opt()
.ok_or_else(|| vm.new_type_error("not a ctypes type"))?;
(stg_info.size, stg_info.length)
};
if offset < 0 {
return Err(vm.new_value_error("offset cannot be negative"));
}
let offset = offset as usize;
// Check if buffer is large enough
if offset + size > source.len() {
return Err(vm.new_value_error(format!(
"Buffer size too small ({} instead of at least {} bytes)",
source.len(),
offset + size
)));
}
// Copy bytes from buffer at offset
let data = source[offset..offset + size].to_vec();
Ok(Self::from_bytes_with_length(data, None, length))
}
#[inline]
pub fn size(&self) -> usize {
self.buffer.read().len()
}
/// Check if this buffer is borrowed (external memory reference)
#[inline]
pub fn is_borrowed(&self) -> bool {
matches!(&*self.buffer.read(), Cow::Borrowed(_))
}
/// Write bytes at offset - handles both borrowed and owned buffers
///
/// For borrowed buffers (from from_address), writes directly to external memory.
/// For owned buffers, writes through to_mut() as normal.
///
/// # Safety
/// For borrowed buffers, caller must ensure the memory is writable.
pub fn write_bytes_at_offset(&self, offset: usize, bytes: &[u8]) {
let mut buffer = self.buffer.write();
write_cow_bytes_at_offset(&mut buffer, offset, bytes);
}
/// Generate unique key for nested references (unique_key)
/// Creates a hierarchical key by walking up the b_base chain.
/// Format: "index:parent_index:grandparent_index:..."
pub fn unique_key(&self, index: usize) -> String {
let mut key = format!("{index:x}");
// Walk up the base chain to build hierarchical key
if self.base.read().is_some() {
let parent_index = self.index.load();
key.push_str(&format!(":{parent_index:x}"));
}
key
}
/// Keep a reference in the objects dictionary (KeepRef)
///
/// Stores 'keep' in this object's b_objects dict at key 'index'.
/// If keep is None, does nothing (optimization).
/// This function stores the value directly - caller should use get_kept_objects()
/// first if they want to store the _objects of a CData instead of the object itself.
///
/// If this object has a base (is embedded in another structure/union/array),
/// the reference is stored in the root object's b_objects with a hierarchical key.
pub fn keep_ref(&self, index: usize, keep: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
// Optimization: no need to store None
if vm.is_none(&keep) {
return Ok(());
}
// Build hierarchical key
let key = self.unique_key(index);
// If we have a base object, find root and store there
if let Some(base_obj) = self.base.read().clone() {
// Find root by walking up the base chain
let root_obj = Self::find_root_object(&base_obj);
Self::store_in_object(&root_obj, &key, keep, vm)?;
return Ok(());
}
// No base - store in own objects dict
let mut objects = self.objects.write();
// Initialize b_objects if needed
if objects.is_none() {
if self.length.load() > 0 {
// Need to store multiple references - create a dict
*objects = Some(vm.ctx.new_dict().into());
} else {
// Only one reference needed - store directly
*objects = Some(keep);
return Ok(());
}
}
// If b_objects is not a dict, convert it to a dict first
// This preserves the existing reference (e.g., from cast) when adding new references
if let Some(obj) = objects.as_ref()
&& obj.downcast_ref::<PyDict>().is_none()
{
// Convert existing single reference to a dict
let dict = vm.ctx.new_dict();
// Store the original object with a special key (id-based)
let id_key: PyObjectRef = vm.ctx.new_int(obj.get_id() as i64).into();
dict.set_item(&*id_key, obj.clone(), vm)?;
*objects = Some(dict.into());
}
// Store in dict with unique key
if let Some(dict_obj) = objects.as_ref()
&& let Some(dict) = dict_obj.downcast_ref::<PyDict>()
{
let key_obj: PyObjectRef = vm.ctx.new_str(key).into();
dict.set_item(&*key_obj, keep, vm)?;
}
Ok(())
}
/// Keep a reference alive without exposing it in _objects.
/// Walks up to root object (same as keep_ref) so the reference
/// lives as long as the owning ctypes object.
/// Uses unique_key (hierarchical) so nested fields don't collide.
pub fn keep_alive(&self, index: usize, obj: PyObjectRef) {
let key = self.unique_key(index);
if let Some(base_obj) = self.base.read().clone() {
let root = Self::find_root_object(&base_obj);
if let Some(cdata) = root.downcast_ref::<Self>() {
cdata.kept_refs.write().insert(key, obj);
return;
}
}
self.kept_refs.write().insert(key, obj);
}
/// Find the root object (one without a base) by walking up the base chain
fn find_root_object(obj: &PyObject) -> PyObjectRef {
// Try to get base from different ctypes types
let base = if let Some(cdata) = obj.downcast_ref::<Self>() {
cdata.base.read().clone()
} else {
None
};
// Recurse if there's a base, otherwise this is the root
if let Some(base_obj) = base {
Self::find_root_object(&base_obj)
} else {
obj.to_owned()
}
}
/// Store a value in an object's _objects dict with the given key
fn store_in_object(
obj: &PyObject,
key: &str,
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<()> {
// Get the objects dict from the object
let objects_lock = if let Some(cdata) = obj.downcast_ref::<Self>() {
&cdata.objects
} else {
return Ok(()); // Unknown type, skip
};
let mut objects = objects_lock.write();
// Initialize if needed
if objects.is_none() {
*objects = Some(vm.ctx.new_dict().into());
}
// If not a dict, convert to dict
if let Some(obj) = objects.as_ref()
&& obj.downcast_ref::<PyDict>().is_none()
{
let dict = vm.ctx.new_dict();
let id_key: PyObjectRef = vm.ctx.new_int(obj.get_id() as i64).into();
dict.set_item(&*id_key, obj.clone(), vm)?;
*objects = Some(dict.into());
}
// Store in dict
if let Some(dict_obj) = objects.as_ref()
&& let Some(dict) = dict_obj.downcast_ref::<PyDict>()
{
let key_obj: PyObjectRef = vm.ctx.new_str(key).into();
dict.set_item(&*key_obj, value, vm)?;
}
Ok(())
}
/// Get kept objects from a CData instance
/// Returns the _objects of the CData, or an empty dict if None.
pub fn get_kept_objects(value: &PyObject, vm: &VirtualMachine) -> PyObjectRef {
value
.downcast_ref::<Self>()
.and_then(|cdata| cdata.objects.read().clone())
.unwrap_or_else(|| vm.ctx.new_dict().into())
}
/// Check if a value should be stored in _objects
/// Returns true for ctypes objects and bytes (for c_char_p)
pub(crate) fn should_keep_ref(value: &PyObject) -> bool {
value.downcast_ref::<Self>().is_some() || value.downcast_ref::<PyBytes>().is_some()
}
/// PyCData_set
/// Sets a field value at the given offset, handling type conversion and KeepRef
#[allow(clippy::too_many_arguments)]
pub fn set_field(
&self,
proto: &PyObject,
value: PyObjectRef,
index: usize,
size: usize,
offset: usize,
needs_swap: bool,
vm: &VirtualMachine,
) -> PyResult<()> {
// Check if this is a c_char or c_wchar array field
let is_char_array = PyCField::is_char_array(proto, vm);
let is_wchar_array = PyCField::is_wchar_array(proto, vm);
// For c_char arrays with bytes input, copy only up to first null
if is_char_array {
if let Some(bytes_val) = value.downcast_ref::<PyBytes>() {
let src = bytes_val.as_bytes();
let to_copy = char_array_assignment_bytes(src);
let copy_len = core::cmp::min(to_copy.len(), size);
self.write_bytes_at_offset(offset, &to_copy[..copy_len]);
self.keep_ref(index, value, vm)?;
return Ok(());
}
return Err(vm.new_type_error("bytes expected instead of str instance"));
}
// For c_wchar arrays with str input, convert to wchar_t
if is_wchar_array {
if let Some(str_val) = value.downcast_ref::<PyStr>() {
let wchar_bytes = rustpython_host_env::ctypes::encode_wtf8_to_wchar_padded(
str_val.as_wtf8(),
size,
);
self.write_bytes_at_offset(offset, &wchar_bytes);
self.keep_ref(index, value, vm)?;
return Ok(());
} else if value.downcast_ref::<PyBytes>().is_some() {
return Err(vm.new_type_error("str expected instead of bytes instance"));
}
}
// Special handling for Pointer fields with Array values
if let Some(proto_type) = proto.downcast_ref::<PyType>()
&& proto_type
.class()
.fast_issubclass(super::pointer::PyCPointerType::static_type())
&& let Some(array) = value.downcast_ref::<super::array::PyCArray>()
{
let buffer_addr = {
let array_buffer = array.0.buffer.read();
array_buffer.as_ptr() as usize
};
let addr_bytes = rustpython_host_env::ctypes::pointer_to_sized_bytes(buffer_addr, size);
self.write_bytes_at_offset(offset, &addr_bytes);
self.keep_ref(index, value, vm)?;
return Ok(());
}
// For array fields with tuple/list input, instantiate the array type
// and unpack elements as positional args (Array_init expects *args)
if let Some(proto_type) = proto.downcast_ref::<PyType>()
&& let Some(stg) = proto_type.stg_info_opt()
&& stg.element_type.is_some()
{
let items: Option<Vec<PyObjectRef>> =
if let Some(tuple) = value.downcast_ref::<PyTuple>() {
Some(tuple.to_vec())
} else {
value
.downcast_ref::<crate::builtins::PyList>()
.map(|list| list.borrow_vec().to_vec())
};
if let Some(items) = items {
let array_obj = proto_type.as_object().call(items, vm).map_err(|e| {
// Wrap errors in RuntimeError with type name prefix
let type_name = proto_type.name().to_string();
let exc_name = e.class().name().to_string();
let exc_args = e.args();
let exc_msg = exc_args
.first()
.and_then(|a| a.downcast_ref::<PyStr>().map(|s| s.to_string()))
.unwrap_or_default();
vm.new_runtime_error(format!("({type_name}) {exc_name}: {exc_msg}"))
})?;
if let Some(arr) = array_obj.downcast_ref::<super::array::PyCArray>() {
let arr_buffer = arr.0.buffer.read();
let len = core::cmp::min(arr_buffer.len(), size);
self.write_bytes_at_offset(offset, &arr_buffer[..len]);
drop(arr_buffer);
self.keep_ref(index, array_obj, vm)?;
return Ok(());
}
}
}
// Get field type code for special handling
let field_type_code = proto
.get_attr("_type_", vm)
.ok()
.and_then(|attr| attr.downcast_ref::<PyStr>().map(|s| s.to_string()));
// c_char_p (z type) with bytes: store original in _objects, keep
// null-terminated copy alive separately for the pointer.
if field_type_code.as_deref() == Some("z")
&& let Some(bytes_val) = value.downcast_ref::<PyBytes>()
{
let (kept_alive, ptr) = ensure_z_null_terminated(bytes_val, vm);
let result =
rustpython_host_env::ctypes::pointer_to_sized_bytes_endian(ptr, size, needs_swap);
self.write_bytes_at_offset(offset, &result);
self.keep_ref(index, value, vm)?;
self.keep_alive(index, kept_alive);
return Ok(());
}
let (mut bytes, converted_value) = if let Some(type_code) = &field_type_code {
PyCField::value_to_bytes_for_type(type_code, &value, size, vm)?
} else {
(PyCField::value_to_bytes(&value, size, vm), None)
};
// Swap bytes for opposite endianness
if needs_swap {
bytes.reverse();
}
self.write_bytes_at_offset(offset, &bytes);
// KeepRef: for z/Z types use converted value, otherwise use original
if let Some(converted) = converted_value {
self.keep_ref(index, converted, vm)?;
} else if Self::should_keep_ref(&value) {
let to_keep = Self::get_kept_objects(&value, vm);
self.keep_ref(index, to_keep, vm)?;
}
Ok(())
}
/// PyCData_get
/// Gets a field value at the given offset
pub fn get_field(
&self,
proto: &PyObject,
index: usize,
size: usize,
offset: usize,
base_obj: PyObjectRef,
vm: &VirtualMachine,