Skip to content

Commit dcb273b

Browse files
Add capsule support to c-api (RustPython#7940)
1 parent dd8d250 commit dcb273b

6 files changed

Lines changed: 198 additions & 3 deletions

File tree

.cspell.dict/python-more.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,7 @@ posonlyargcount
189189
prepending
190190
profilefunc
191191
pycache
192+
pycapsule
192193
pycodecs
193194
pycs
194195
pydatetime

crates/capi/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ pub mod import;
1919
pub mod listobject;
2020
pub mod longobject;
2121
pub mod object;
22+
pub mod pycapsule;
2223
pub mod pyerrors;
2324
pub mod pylifecycle;
2425
pub mod pystate;

crates/capi/src/pycapsule.rs

Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
use crate::PyObject;
2+
use crate::pystate::with_vm;
3+
use core::ffi::{CStr, c_char, c_int, c_void};
4+
use core::ptr::NonNull;
5+
use rustpython_vm::builtins::PyCapsule;
6+
use rustpython_vm::{PyObjectRef, PyResult, VirtualMachine};
7+
8+
#[allow(non_camel_case_types)]
9+
pub type PyCapsule_Destructor = unsafe extern "C" fn(capsule: *mut PyObject);
10+
11+
#[unsafe(no_mangle)]
12+
pub extern "C" fn PyCapsule_New(
13+
pointer: *mut c_void,
14+
name: *const c_char,
15+
destructor: Option<PyCapsule_Destructor>,
16+
) -> *mut PyObject {
17+
with_vm(|vm| {
18+
if pointer.is_null() {
19+
return Err(vm.new_value_error("PyCapsule_New called with null pointer"));
20+
}
21+
let name = NonNull::new(name.cast_mut()).map(|ptr| unsafe { CStr::from_ptr(ptr.as_ptr()) });
22+
Ok(vm.ctx.new_capsule(pointer, name, destructor))
23+
})
24+
}
25+
26+
#[unsafe(no_mangle)]
27+
pub unsafe extern "C" fn PyCapsule_GetPointer(
28+
capsule: *mut PyObject,
29+
name: *const c_char,
30+
) -> *mut c_void {
31+
with_vm(|vm| Ok(checked_capsule(vm, unsafe { &*capsule }, name)?.pointer()))
32+
}
33+
34+
#[unsafe(no_mangle)]
35+
pub unsafe extern "C" fn PyCapsule_GetName(capsule: *mut PyObject) -> *const c_char {
36+
with_vm(|vm| {
37+
let capsule = unsafe { &*capsule }
38+
.downcast_ref_if_exact::<PyCapsule>(vm)
39+
.ok_or_else(|| vm.new_value_error("Invalid capsule"))?;
40+
Ok(capsule.name().map(CStr::as_ptr).unwrap_or_default())
41+
})
42+
}
43+
44+
#[unsafe(no_mangle)]
45+
pub unsafe extern "C" fn PyCapsule_GetContext(capsule: *mut PyObject) -> *mut c_void {
46+
with_vm(|vm| {
47+
let capsule = unsafe { &*capsule }
48+
.downcast_ref_if_exact::<PyCapsule>(vm)
49+
.ok_or_else(|| vm.new_value_error("Invalid capsule"))?;
50+
Ok(capsule.context())
51+
})
52+
}
53+
54+
#[unsafe(no_mangle)]
55+
pub unsafe extern "C" fn PyCapsule_SetContext(
56+
capsule: *mut PyObject,
57+
context: *mut c_void,
58+
) -> c_int {
59+
with_vm(|vm| {
60+
let capsule = unsafe { &*capsule }
61+
.downcast_ref_if_exact::<PyCapsule>(vm)
62+
.ok_or_else(|| vm.new_value_error("Invalid capsule"))?;
63+
let _: () = capsule.set_context(context);
64+
Ok(())
65+
})
66+
}
67+
68+
#[unsafe(no_mangle)]
69+
pub unsafe extern "C" fn PyCapsule_SetPointer(
70+
capsule: *mut PyObject,
71+
pointer: *mut c_void,
72+
) -> c_int {
73+
with_vm(|vm| {
74+
let capsule = unsafe { &*capsule }
75+
.downcast_ref_if_exact::<PyCapsule>(vm)
76+
.ok_or_else(|| vm.new_value_error("Invalid capsule"))?;
77+
let _: () = capsule.set_pointer(pointer);
78+
Ok(())
79+
})
80+
}
81+
82+
#[unsafe(no_mangle)]
83+
pub unsafe extern "C" fn PyCapsule_IsValid(capsule: *mut PyObject, name: *const c_char) -> c_int {
84+
with_vm(|vm| {
85+
if capsule.is_null() {
86+
return false;
87+
}
88+
89+
checked_capsule(vm, unsafe { &*capsule }, name).is_ok()
90+
})
91+
}
92+
93+
#[unsafe(no_mangle)]
94+
pub unsafe extern "C" fn PyCapsule_Import(name: *const c_char, _no_block: c_int) -> *mut c_void {
95+
with_vm(|vm| {
96+
let capsule_name = unsafe { CStr::from_ptr(name) }
97+
.to_str()
98+
.map_err(|_| vm.new_system_error("capsule name is not valid UTF-8"))?;
99+
let (module_name, attrs_path) = capsule_name.split_once('.').ok_or_else(|| {
100+
vm.new_import_error(
101+
"capsule name is missing attribute path",
102+
vm.ctx.new_str(capsule_name),
103+
)
104+
})?;
105+
let mut obj: PyObjectRef = vm.import(module_name, 0)?;
106+
107+
for attr in attrs_path.split('.') {
108+
obj = obj.get_attr(attr, vm)?;
109+
}
110+
111+
Ok(checked_capsule(vm, &obj, name)?.pointer())
112+
})
113+
}
114+
115+
#[inline]
116+
fn names_match(stored_name: *const c_char, expected_name: *const c_char) -> bool {
117+
if stored_name.is_null() || expected_name.is_null() {
118+
stored_name.is_null() && expected_name.is_null()
119+
} else {
120+
unsafe { CStr::from_ptr(stored_name) == CStr::from_ptr(expected_name) }
121+
}
122+
}
123+
124+
#[inline]
125+
fn checked_capsule<'a>(
126+
vm: &VirtualMachine,
127+
obj: &'a PyObject,
128+
name: *const c_char,
129+
) -> PyResult<&'a PyCapsule> {
130+
let capsule = obj
131+
.downcast_ref_if_exact::<PyCapsule>(vm)
132+
.ok_or_else(|| vm.new_value_error("Invalid capsule"))?;
133+
134+
if !names_match(capsule.name().map(CStr::as_ptr).unwrap_or_default(), name) {
135+
return Err(vm.new_value_error("Capsule name does not match"));
136+
}
137+
138+
if capsule.pointer().is_null() {
139+
return Err(vm.new_value_error("Capsule has null pointer"));
140+
}
141+
142+
Ok(capsule)
143+
}
144+
145+
#[cfg(false)]
146+
mod tests {
147+
use pyo3::prelude::*;
148+
use pyo3::types::PyCapsule;
149+
150+
#[test]
151+
fn test_capsule_new() {
152+
Python::attach(|py| {
153+
let value = String::from("Some data");
154+
let capsule = PyCapsule::new_with_value(py, value, c"my_capsule").unwrap();
155+
assert!(capsule.is_valid_checked(Some(c"my_capsule")));
156+
let ptr = capsule.pointer_checked(Some(c"my_capsule")).unwrap();
157+
assert_eq!(unsafe { ptr.cast::<String>().as_ref() }, "Some data");
158+
})
159+
}
160+
}

crates/capi/src/util.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,14 @@ impl FfiResult<*mut c_char> for *const u8 {
7676
}
7777
}
7878

79+
impl FfiResult for *const c_char {
80+
const ERR_VALUE: *const c_char = core::ptr::null_mut();
81+
82+
fn into_output(self, _vm: &VirtualMachine) -> *const c_char {
83+
self
84+
}
85+
}
86+
7987
impl FfiResult<isize> for usize {
8088
const ERR_VALUE: isize = -1;
8189

crates/vm/src/builtins/capsule.rs

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use crate::{
44
class::PyClassImpl,
55
types::{Destructor, Representable},
66
};
7-
use core::ffi::c_void;
7+
use core::ffi::{CStr, c_void};
88
use core::sync::atomic::AtomicPtr;
99

1010
/// PyCapsule - a container for C pointers.
@@ -13,6 +13,8 @@ use core::sync::atomic::AtomicPtr;
1313
#[derive(Debug)]
1414
pub struct PyCapsule {
1515
ptr: AtomicPtr<c_void>,
16+
context: AtomicPtr<c_void>,
17+
name: Option<&'static CStr>,
1618
destructor: Option<unsafe extern "C" fn(_: *mut PyObject)>,
1719
}
1820

@@ -27,10 +29,13 @@ impl PyPayload for PyCapsule {
2729
impl PyCapsule {
2830
pub fn new(
2931
ptr: *mut c_void,
32+
name: Option<&'static CStr>,
3033
destructor: Option<unsafe extern "C" fn(_: *mut PyObject)>,
3134
) -> Self {
3235
Self {
3336
ptr: ptr.into(),
37+
context: core::ptr::null_mut::<c_void>().into(),
38+
name,
3439
destructor,
3540
}
3641
}
@@ -39,6 +44,24 @@ impl PyCapsule {
3944
self.ptr.load(core::sync::atomic::Ordering::Relaxed)
4045
}
4146

47+
pub fn set_pointer(&self, pointer: *mut c_void) {
48+
self.ptr
49+
.store(pointer, core::sync::atomic::Ordering::Relaxed);
50+
}
51+
52+
pub fn context(&self) -> *mut c_void {
53+
self.context.load(core::sync::atomic::Ordering::Relaxed)
54+
}
55+
56+
pub fn set_context(&self, context: *mut c_void) {
57+
self.context
58+
.store(context, core::sync::atomic::Ordering::Relaxed);
59+
}
60+
61+
pub fn name(&self) -> Option<&CStr> {
62+
self.name
63+
}
64+
4265
fn destructor(&self) -> Option<unsafe extern "C" fn(_: *mut PyObject)> {
4366
self.destructor
4467
}

crates/vm/src/vm/context.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ use crate::{
2626
object::{Py, PyObjectPayload, PyObjectRef, PyPayload, PyRef},
2727
types::{PyTypeFlags, PyTypeSlots, TypeZoo},
2828
};
29+
use core::ffi::{CStr, c_void};
2930
use malachite_bigint::BigInt;
3031
use num_complex::Complex64;
3132
use num_traits::ToPrimitive;
@@ -754,10 +755,11 @@ impl Context {
754755

755756
pub fn new_capsule(
756757
&self,
757-
ptr: *mut core::ffi::c_void,
758+
ptr: *mut c_void,
759+
name: Option<&'static CStr>,
758760
destructor: Option<unsafe extern "C" fn(_: *mut PyObject)>,
759761
) -> PyRef<PyCapsule> {
760-
PyCapsule::new(ptr, destructor).into_ref(self)
762+
PyCapsule::new(ptr, name, destructor).into_ref(self)
761763
}
762764
}
763765

0 commit comments

Comments
 (0)