From 77492d251ff6e8cf74eb4fcd9c37aaaf49216a76 Mon Sep 17 00:00:00 2001 From: Mathieu Dupuy Date: Thu, 26 Nov 2026 01:16:06 +0100 Subject: [PATCH 1/5] capi: load abi3t extension modules via PyModExport Add an extension module loader hook to `_imp.create_dynamic` and register it from the C API crate. It resolves `PyModExport_`, reads the slots (Py_mod_abi, doc, methods, exec) and builds the module from them. Assisted-by: Claude Code:claude-sonnet-5-5 --- crates/capi/src/extension.rs | 86 ++++++++++++++++++++++++++++++++++ crates/capi/src/lib.rs | 3 ++ crates/capi/src/pylifecycle.rs | 1 + crates/vm/src/stdlib/_imp.rs | 50 ++++++++++++++++---- crates/vm/src/stdlib/mod.rs | 1 + src/lib.rs | 4 ++ 6 files changed, 135 insertions(+), 10 deletions(-) create mode 100644 crates/capi/src/extension.rs diff --git a/crates/capi/src/extension.rs b/crates/capi/src/extension.rs new file mode 100644 index 00000000000..ddfb67eb3a8 --- /dev/null +++ b/crates/capi/src/extension.rs @@ -0,0 +1,86 @@ +//! Import of abi3t extension modules through their `PyModExport_` entry point. + +use crate::methodobject::PyMethodDef; +use crate::slots::{PySlot, PySlotKind, PySlotModule}; +use crate::util::CStrExt; +use core::ffi::c_int; +use rustpython_vm::{AsObject, PyObject, PyResult, VirtualMachine}; + +/// Make `_imp.create_dynamic` able to load extension modules built for the stable ABI. +pub fn register_extension_loader() { + rustpython_vm::stdlib::set_extension_module_loader(load_extension_module); +} + +fn load_extension_module(vm: &VirtualMachine, name: &str, export_fn: usize) -> PyResult { + type ExportFn = unsafe extern "C" fn() -> *const PySlot; + // Safety: the address comes from a successful lookup of `PyModExport_`. + let export: ExportFn = unsafe { core::mem::transmute(export_fn as *const ()) }; + let slots = unsafe { export() }; + if slots.is_null() { + return Err(vm.take_raised_exception().unwrap_or_else(|| { + vm.new_system_error(format!( + "PyModExport_{name} returned NULL without an exception" + )) + })); + } + + let mut doc = None; + let mut methods: Vec<*const PyMethodDef> = Vec::new(); + let mut execs: Vec c_int> = Vec::new(); + let mut has_abi = false; + + for slot in PySlot::iter(slots) { + match slot.as_kind(vm)? { + PySlotKind::Module(PySlotModule::Abi(info)) => { + info.is_supported(vm, Some(name))?; + has_abi = true; + } + PySlotKind::Module(PySlotModule::Doc(text)) => doc = Some(text), + PySlotKind::Module(PySlotModule::Methods(defs)) => methods.push(defs), + PySlotKind::Module(PySlotModule::Exec(exec)) => execs.push(exec), + PySlotKind::Module(PySlotModule::Create(_)) => { + return Err( + vm.new_import_error("Py_mod_create is not supported yet", vm.ctx.new_str(name)) + ); + } + // The name comes from the import spec. The remaining slots are ignored for now. + _ => {} + } + } + + if !has_abi { + return Err(vm.new_import_error( + "module does not define Py_mod_abi, which is mandatory for modules defined from slots", + vm.ctx.new_str(name), + )); + } + + let module = vm.new_module( + name, + vm.ctx.new_dict(), + doc.map(|text| vm.ctx.new_str(text)), + ); + let module_name = vm.ctx.new_str(name); + for defs in methods { + for def in PyMethodDef::iter(defs) { + let function = def + .build_method_def(vm)? + .build_function(vm, Some(module.clone().into())); + function + .as_object() + .set_attr("__module__", module_name.clone(), vm)?; + let function_name = unsafe { def.ml_name.try_as_str(vm) }?; + module.dict().set_item(function_name, function.into(), vm)?; + } + } + + let module_ptr = module.as_object().as_raw().cast_mut(); + for exec in execs { + if unsafe { exec(module_ptr) } != 0 { + return Err(vm.take_raised_exception().unwrap_or_else(|| { + vm.new_system_error(format!("exec slot of {name} failed without an exception")) + })); + } + } + Ok(module.into()) +} diff --git a/crates/capi/src/lib.rs b/crates/capi/src/lib.rs index 026788e61a3..886ff4f461e 100644 --- a/crates/capi/src/lib.rs +++ b/crates/capi/src/lib.rs @@ -18,6 +18,8 @@ pub mod codecs; pub mod complexobject; pub mod critical_section; pub mod descrobject; +mod extension; +pub use extension::register_extension_loader; pub mod dictobject; pub mod fileobject; pub mod floatobject; @@ -65,6 +67,7 @@ pub fn get_main_interpreter() -> MutexGuard<'static, Option> { pub fn init_main_interpreter(interpreter: Interpreter) { let mut interp = get_main_interpreter(); assert!(interp.is_none(), "Main interpreter is already set"); + register_extension_loader(); // Safety: Interpreter was not initialized before, so we can safely assume the statics are not used unsafe { init_exception_statics(&Context::genesis().exceptions) }; *interp = Some(interpreter); diff --git a/crates/capi/src/pylifecycle.rs b/crates/capi/src/pylifecycle.rs index 58f8ecd08c4..23466ecb75f 100644 --- a/crates/capi/src/pylifecycle.rs +++ b/crates/capi/src/pylifecycle.rs @@ -39,6 +39,7 @@ pub extern "C" fn Py_Initialize() { pub extern "C" fn Py_InitializeEx(_initsigs: c_int) { let mut interp = get_main_interpreter(); if interp.is_none() { + crate::extension::register_extension_loader(); // Safety: Interpreter was not initialized before, so we can safely assume the statics are not used unsafe { init_exception_statics(&Context::genesis().exceptions) }; let builder = Interpreter::builder(Default::default()); diff --git a/crates/vm/src/stdlib/_imp.rs b/crates/vm/src/stdlib/_imp.rs index 85b9abaf686..e4793be8c3a 100644 --- a/crates/vm/src/stdlib/_imp.rs +++ b/crates/vm/src/stdlib/_imp.rs @@ -9,6 +9,21 @@ pub(super) use crate::vm::resolve_frozen_alias; mod resources; +/// Builds a module from the `PyModExport_` entry point of an extension module. +/// +/// `export_fn` is the address of the entry point. The C API crate registers this hook, +/// since only it knows how to interpret the slots the entry point returns. +pub type ExtensionModuleLoader = + fn(vm: &VirtualMachine, name: &str, export_fn: usize) -> crate::PyResult; + +static EXTENSION_MODULE_LOADER: std::sync::OnceLock = + std::sync::OnceLock::new(); + +/// Register the loader used to import abi3t extension modules. +pub fn set_extension_module_loader(loader: ExtensionModuleLoader) { + let _ = EXTENSION_MODULE_LOADER.set(loader); +} + #[cfg(feature = "threading")] #[pymodule(sub, name = "_imp")] mod lock { @@ -229,8 +244,17 @@ mod _imp { use version::PYC_MAGIC_NUMBER_TOKEN; #[pyfunction] - const fn extension_suffixes() -> Vec { - Vec::new() + fn extension_suffixes(vm: &VirtualMachine) -> Vec { + // Only abi3t extensions can be loaded, and only once a C API loader is registered. + if super::EXTENSION_MODULE_LOADER.get().is_none() { + return Vec::new(); + } + let suffixes: &[&str] = if cfg!(windows) { + &[".abi3t.pyd"] + } else { + &[".abi3t.so"] + }; + suffixes.iter().map(|s| vm.ctx.new_str(*s).into()).collect() } // This hook is also used by eager imports that satisfy pending lazy targets. @@ -395,7 +419,18 @@ mod _imp { #[cfg(windows)] let handle_res = rustpython_host_env::ctypes::open_library(origin_str); - if let Ok(handle) = handle_res + let handle = match handle_res { + Ok(handle) => Some(handle), + // Report why the library could not be opened, e.g. an undefined symbol. + Err(err) => { + return Err(vm.new_import_error( + format!("cannot load {origin_str}: {err}"), + name.into_wtf8(), + )); + } + }; + + if let Some(handle) = handle && let Ok(export_fn_addr) = rustpython_host_env::ctypes::lookup_function_symbol_addr( handle, export_func_name.as_bytes(), @@ -403,13 +438,8 @@ mod _imp { && export_fn_addr != 0 { // abi3t PyModExport entry point - type ModExportFn = unsafe extern "C" fn() -> *mut crate::PyObject; - let export_fn: ModExportFn = - unsafe { core::mem::transmute(export_fn_addr as *const ()) }; - let mod_ptr = unsafe { export_fn() }; - if let Some(mod_nonnull) = core::ptr::NonNull::new(mod_ptr) { - let py_obj = unsafe { crate::PyObjectRef::from_raw(mod_nonnull) }; - return Ok(py_obj); + if let Some(loader) = super::EXTENSION_MODULE_LOADER.get() { + return loader(vm, name.as_str(), export_fn_addr); } } } diff --git a/crates/vm/src/stdlib/mod.rs b/crates/vm/src/stdlib/mod.rs index 96aa5ce1f9b..c96ae0ed6db 100644 --- a/crates/vm/src/stdlib/mod.rs +++ b/crates/vm/src/stdlib/mod.rs @@ -6,6 +6,7 @@ mod _collections; pub(crate) use _collections::ordered_dict::ordered_dict::PyOrderedDict; mod _functools; mod _imp; +pub use _imp::{ExtensionModuleLoader, set_extension_module_loader}; pub mod _io; mod _lsprof; mod _operator; diff --git a/src/lib.rs b/src/lib.rs index 41a169d273b..03393c5cb7a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -148,6 +148,10 @@ fn run_impl(mut builder: InterpreterBuilder, configure_locale: bool) -> ExitCode builder = builder.settings(settings); + // importlib reads the extension suffixes while the interpreter is built. + #[cfg(feature = "capi")] + rustpython_capi::register_extension_loader(); + let interp = builder.interpreter(); let exitcode = cfg_select! { feature = "capi" => rustpython_capi::run_main_interpreter(interp, move |vm| run_rustpython(vm, run_mode)), From 15a3b623366fe8ced3543367b0cb0628985c8fb0 Mon Sep 17 00:00:00 2001 From: Mathieu Dupuy Date: Thu, 26 Nov 2026 01:59:22 +0100 Subject: [PATCH 2/5] capi: address review of abi3t extension loading Expand Py_mod_slots into its legacy PyModuleDef_Slot entries, run exec slots from _imp.exec_dynamic after importlib set the module attributes, and advertise the abi3t suffix independently of loader registration so interpreters built before run_main_interpreter can import extensions. Assisted-by: Claude Code:claude-sonnet-5-5 --- crates/capi/src/extension.rs | 43 +++++++++++++++++++++++--- crates/capi/src/slots.rs | 59 ++++++++++++++++++++++++++++++------ crates/vm/src/stdlib/_imp.rs | 47 +++++++++++++++++++--------- crates/vm/src/stdlib/mod.rs | 2 +- 4 files changed, 122 insertions(+), 29 deletions(-) diff --git a/crates/capi/src/extension.rs b/crates/capi/src/extension.rs index ddfb67eb3a8..104ad6aed82 100644 --- a/crates/capi/src/extension.rs +++ b/crates/capi/src/extension.rs @@ -5,10 +5,21 @@ use crate::slots::{PySlot, PySlotKind, PySlotModule}; use crate::util::CStrExt; use core::ffi::c_int; use rustpython_vm::{AsObject, PyObject, PyResult, VirtualMachine}; +use std::sync::Mutex; + +type ExecSlot = unsafe extern "C" fn(*mut PyObject) -> c_int; + +/// Exec slots of modules that are created but not yet executed, keyed by module address. +/// They run from `_imp.exec_dynamic`, once importlib has set the module attributes and added +/// the module to `sys.modules` (PEP 489). +static PENDING_EXEC: Mutex)>> = Mutex::new(Vec::new()); /// Make `_imp.create_dynamic` able to load extension modules built for the stable ABI. pub fn register_extension_loader() { - rustpython_vm::stdlib::set_extension_module_loader(load_extension_module); + rustpython_vm::stdlib::set_extension_module_loader( + load_extension_module, + exec_extension_module, + ); } fn load_extension_module(vm: &VirtualMachine, name: &str, export_fn: usize) -> PyResult { @@ -26,7 +37,7 @@ fn load_extension_module(vm: &VirtualMachine, name: &str, export_fn: usize) -> P let mut doc = None; let mut methods: Vec<*const PyMethodDef> = Vec::new(); - let mut execs: Vec c_int> = Vec::new(); + let mut execs: Vec = Vec::new(); let mut has_abi = false; for slot in PySlot::iter(slots) { @@ -74,13 +85,35 @@ fn load_extension_module(vm: &VirtualMachine, name: &str, export_fn: usize) -> P } } - let module_ptr = module.as_object().as_raw().cast_mut(); + if !execs.is_empty() { + let key = module.as_object().as_raw() as usize; + PENDING_EXEC + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .push((key, execs)); + } + Ok(module.into()) +} + +/// Run the exec slots recorded by [`load_extension_module`], once. +fn exec_extension_module(vm: &VirtualMachine, module: &PyObject) -> PyResult<()> { + let key = module.as_raw() as usize; + let execs = { + let mut pending = PENDING_EXEC + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + match pending.iter().position(|(k, _)| *k == key) { + Some(index) => pending.swap_remove(index).1, + None => return Ok(()), + } + }; + let module_ptr = module.as_raw().cast_mut(); for exec in execs { if unsafe { exec(module_ptr) } != 0 { return Err(vm.take_raised_exception().unwrap_or_else(|| { - vm.new_system_error(format!("exec slot of {name} failed without an exception")) + vm.new_system_error("exec slot of an extension module failed without an exception") })); } } - Ok(module.into()) + Ok(()) } diff --git a/crates/capi/src/slots.rs b/crates/capi/src/slots.rs index 590ffcf3bd8..c1d9f073253 100644 --- a/crates/capi/src/slots.rs +++ b/crates/capi/src/slots.rs @@ -6,11 +6,21 @@ use crate::util::CStrExt; use alloc::borrow::Cow; use core::ffi::{c_char, c_int, c_void}; use core::num::TryFromIntError; -use itertools::Either; use rustpython_vm::builtins::{PyModule, PyType}; use rustpython_vm::types::SlotAccessor; use rustpython_vm::{Py, PyResult, VirtualMachine}; +/// A slot array being walked by [`PySlot::iter`]. +enum SlotFrame { + Slots(*const PySlot), + /// A `PyType_Slot` array, or with `legacy_module` a `PyModuleDef_Slot` array reached + /// through `Py_mod_slots`. Both have the same layout. + TypeSlots { + ptr: *const PyType_Slot, + legacy_module: bool, + }, +} + #[repr(C)] #[derive(Clone)] pub struct PySlot { @@ -49,7 +59,7 @@ impl PySlot { } pub(crate) fn iter<'a>(slots: *const Self) -> impl Iterator> { - let mut stack: Vec> = vec![Either::Left(slots)]; + let mut stack: Vec = vec![SlotFrame::Slots(slots)]; core::iter::from_fn(move || { loop { assert!( @@ -57,7 +67,7 @@ impl PySlot { "Too many nested slots, possible infinite loop in slot iteration" ); return match stack.last_mut()? { - Either::Left(slot_ptr) => { + SlotFrame::Slots(slot_ptr) => { let slot = unsafe { &**slot_ptr }; if slot.sl_id == 0 { stack.pop(); @@ -69,7 +79,7 @@ impl PySlot { if slot.sl_id == 92 { let subslots = unsafe { slot.value.sl_ptr }.cast_const().cast::(); if !subslots.is_null() { - stack.push(Either::Left(subslots)); + stack.push(SlotFrame::Slots(subslots)); } continue; } @@ -79,14 +89,35 @@ impl PySlot { .cast_const() .cast::(); if !type_slots.is_null() { - stack.push(Either::Right(type_slots)); + stack.push(SlotFrame::TypeSlots { + ptr: type_slots, + legacy_module: false, + }); + } + continue; + } + + // Py_mod_slots: a legacy PyModuleDef_Slot array + if slot.sl_id == 94 { + let module_slots = unsafe { slot.value.sl_ptr } + .cast_const() + .cast::(); + if !module_slots.is_null() { + stack.push(SlotFrame::TypeSlots { + ptr: module_slots, + legacy_module: true, + }); } continue; } Some(Cow::Borrowed(slot)) } - Either::Right(slot_ptr) => { + SlotFrame::TypeSlots { + ptr: slot_ptr, + legacy_module, + } => { + let legacy_module = *legacy_module; let type_slot = unsafe { &**slot_ptr }; if type_slot.slot == 0 { stack.pop(); @@ -94,7 +125,15 @@ impl PySlot { } *slot_ptr = unsafe { slot_ptr.add(1) }; - Some(Cow::Owned(type_slot.try_into().expect("invalid slot"))) + let mut slot: Self = type_slot.try_into().expect("invalid slot"); + if legacy_module { + // Legacy PyModuleDef_Slot ids: 1 create, 2 exec, 3 multiple + // interpreters, 4 gil. They map to 84..=87 in the unified numbering. + if (1..=4).contains(&slot.sl_id) { + slot.sl_id += 83; + } + } + Some(Cow::Owned(slot)) } }; } @@ -150,8 +189,10 @@ impl PySlot { 87 => PySlotKind::Module(PySlotModule::Gil { gil_used: !value_ptr.is_null(), }), - 92 | 93 => { - unreachable!("Py_slot_subslots and Py_tp_slots should be handled in the iterator") + 92..=94 => { + unreachable!( + "Py_slot_subslots, Py_tp_slots and Py_mod_slots should be handled in the iterator" + ) } 95 => PySlotKind::Type(PySlotType::Name(unsafe { value_ptr.cast::().try_as_str(vm)? diff --git a/crates/vm/src/stdlib/_imp.rs b/crates/vm/src/stdlib/_imp.rs index e4793be8c3a..80c15e779d7 100644 --- a/crates/vm/src/stdlib/_imp.rs +++ b/crates/vm/src/stdlib/_imp.rs @@ -16,12 +16,19 @@ mod resources; pub type ExtensionModuleLoader = fn(vm: &VirtualMachine, name: &str, export_fn: usize) -> crate::PyResult; -static EXTENSION_MODULE_LOADER: std::sync::OnceLock = +/// Runs the exec slots of a module made by an [`ExtensionModuleLoader`]. +/// +/// Called from `_imp.exec_dynamic`, once importlib has set the module attributes and added +/// the module to `sys.modules`. +pub type ExtensionModuleExec = + fn(vm: &VirtualMachine, module: &crate::PyObject) -> crate::PyResult<()>; + +static EXTENSION_MODULE_LOADER: std::sync::OnceLock<(ExtensionModuleLoader, ExtensionModuleExec)> = std::sync::OnceLock::new(); -/// Register the loader used to import abi3t extension modules. -pub fn set_extension_module_loader(loader: ExtensionModuleLoader) { - let _ = EXTENSION_MODULE_LOADER.set(loader); +/// Register the hooks used to import abi3t extension modules. +pub fn set_extension_module_loader(loader: ExtensionModuleLoader, exec: ExtensionModuleExec) { + let _ = EXTENSION_MODULE_LOADER.set((loader, exec)); } #[cfg(feature = "threading")] @@ -245,11 +252,12 @@ mod _imp { #[pyfunction] fn extension_suffixes(vm: &VirtualMachine) -> Vec { - // Only abi3t extensions can be loaded, and only once a C API loader is registered. - if super::EXTENSION_MODULE_LOADER.get().is_none() { - return Vec::new(); - } - let suffixes: &[&str] = if cfg!(windows) { + // importlib reads this while the interpreter is built, possibly before the C API + // loader is registered, so the suffix is advertised whenever loading is possible. + // `create_dynamic` reports an error if no loader was registered by then. + let suffixes: &[&str] = if !cfg!(all(feature = "host_env", any(unix, windows))) { + &[] + } else if cfg!(windows) { &[".abi3t.pyd"] } else { &[".abi3t.so"] @@ -438,9 +446,13 @@ mod _imp { && export_fn_addr != 0 { // abi3t PyModExport entry point - if let Some(loader) = super::EXTENSION_MODULE_LOADER.get() { - return loader(vm, name.as_str(), export_fn_addr); - } + return match super::EXTENSION_MODULE_LOADER.get() { + Some((loader, _)) => loader(vm, name.as_str(), export_fn_addr), + None => Err(vm.new_import_error( + "no loader for abi3t extension modules is registered", + name.into_wtf8(), + )), + }; } } @@ -454,8 +466,15 @@ mod _imp { } #[pyfunction] - fn exec_dynamic(_imp: &Py, _mod: PyRef) -> i32 { - 0 + fn exec_dynamic( + _imp: &Py, + module: PyRef, + vm: &VirtualMachine, + ) -> PyResult { + if let Some((_, exec)) = super::EXTENSION_MODULE_LOADER.get() { + exec(vm, module.as_object())?; + } + Ok(0) } #[pyfunction] diff --git a/crates/vm/src/stdlib/mod.rs b/crates/vm/src/stdlib/mod.rs index c96ae0ed6db..c2559c069b4 100644 --- a/crates/vm/src/stdlib/mod.rs +++ b/crates/vm/src/stdlib/mod.rs @@ -6,7 +6,7 @@ mod _collections; pub(crate) use _collections::ordered_dict::ordered_dict::PyOrderedDict; mod _functools; mod _imp; -pub use _imp::{ExtensionModuleLoader, set_extension_module_loader}; +pub use _imp::{ExtensionModuleExec, ExtensionModuleLoader, set_extension_module_loader}; pub mod _io; mod _lsprof; mod _operator; From 65c043f465142ab1fd605b8ecb1f55ceb2095cb8 Mon Sep 17 00:00:00 2001 From: Mathieu Dupuy Date: Thu, 26 Nov 2026 02:35:31 +0100 Subject: [PATCH 3/5] capi: advertise the abi3t suffix only once the loader is registered Advertising it unconditionally made the extension tests of test_importlib run, and fail, on builds without the C API. Assisted-by: Claude Code:claude-sonnet-5-5 --- crates/capi/src/extension.rs | 3 +++ crates/vm/src/stdlib/_imp.rs | 13 +++++++------ 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/crates/capi/src/extension.rs b/crates/capi/src/extension.rs index 104ad6aed82..49e9211d9ae 100644 --- a/crates/capi/src/extension.rs +++ b/crates/capi/src/extension.rs @@ -15,6 +15,9 @@ type ExecSlot = unsafe extern "C" fn(*mut PyObject) -> c_int; static PENDING_EXEC: Mutex)>> = Mutex::new(Vec::new()); /// Make `_imp.create_dynamic` able to load extension modules built for the stable ABI. +/// +/// importlib reads the extension suffixes while the interpreter is built, so code that +/// builds the interpreter itself must call this before `Interpreter::builder`. pub fn register_extension_loader() { rustpython_vm::stdlib::set_extension_module_loader( load_extension_module, diff --git a/crates/vm/src/stdlib/_imp.rs b/crates/vm/src/stdlib/_imp.rs index 80c15e779d7..e338fc940a2 100644 --- a/crates/vm/src/stdlib/_imp.rs +++ b/crates/vm/src/stdlib/_imp.rs @@ -252,12 +252,13 @@ mod _imp { #[pyfunction] fn extension_suffixes(vm: &VirtualMachine) -> Vec { - // importlib reads this while the interpreter is built, possibly before the C API - // loader is registered, so the suffix is advertised whenever loading is possible. - // `create_dynamic` reports an error if no loader was registered by then. - let suffixes: &[&str] = if !cfg!(all(feature = "host_env", any(unix, windows))) { - &[] - } else if cfg!(windows) { + // Only abi3t extensions can be loaded, and only once a C API loader is registered. + // importlib reads this while the interpreter is built, so the loader has to be + // registered before that. + if super::EXTENSION_MODULE_LOADER.get().is_none() { + return Vec::new(); + } + let suffixes: &[&str] = if cfg!(windows) { &[".abi3t.pyd"] } else { &[".abi3t.so"] From acfa74fe337d3398d7771fd14e80d7620652886e Mon Sep 17 00:00:00 2001 From: Mathieu Dupuy Date: Thu, 26 Nov 2026 09:05:36 +0100 Subject: [PATCH 4/5] capi: handle nested legacy slots, subinterpreters and exec slot lifetime Expand container slots found inside Py_mod_slots arrays, reject modules declaring Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED in subinterpreters that check multi-interpreter extensions, and keep pending exec slots in the module dict so they cannot outlive or be matched to another module. Assisted-by: Claude Code:claude-sonnet-5-5 --- crates/capi/src/extension.rs | 61 ++++++++++++++++++----------- crates/capi/src/slots.rs | 75 ++++++++++++++---------------------- 2 files changed, 67 insertions(+), 69 deletions(-) diff --git a/crates/capi/src/extension.rs b/crates/capi/src/extension.rs index 49e9211d9ae..543edf18964 100644 --- a/crates/capi/src/extension.rs +++ b/crates/capi/src/extension.rs @@ -4,15 +4,14 @@ use crate::methodobject::PyMethodDef; use crate::slots::{PySlot, PySlotKind, PySlotModule}; use crate::util::CStrExt; use core::ffi::c_int; -use rustpython_vm::{AsObject, PyObject, PyResult, VirtualMachine}; -use std::sync::Mutex; +use rustpython_vm::{AsObject, PyObject, PyResult, TryFromObject, VirtualMachine}; type ExecSlot = unsafe extern "C" fn(*mut PyObject) -> c_int; -/// Exec slots of modules that are created but not yet executed, keyed by module address. -/// They run from `_imp.exec_dynamic`, once importlib has set the module attributes and added -/// the module to `sys.modules` (PEP 489). -static PENDING_EXEC: Mutex)>> = Mutex::new(Vec::new()); +/// Key under which the exec slots of a created module wait in its dict until +/// `_imp.exec_dynamic` runs them, once importlib has set the module attributes and added the +/// module to `sys.modules` (PEP 489). Living in the module dict, they go away with the module. +const PENDING_EXEC_KEY: &str = "__rustpython_pending_exec__"; /// Make `_imp.create_dynamic` able to load extension modules built for the stable ABI. /// @@ -42,6 +41,7 @@ fn load_extension_module(vm: &VirtualMachine, name: &str, export_fn: usize) -> P let mut methods: Vec<*const PyMethodDef> = Vec::new(); let mut execs: Vec = Vec::new(); let mut has_abi = false; + let mut multiple_interpreters_supported = true; for slot in PySlot::iter(slots) { match slot.as_kind(vm)? { @@ -57,6 +57,10 @@ fn load_extension_module(vm: &VirtualMachine, name: &str, export_fn: usize) -> P vm.new_import_error("Py_mod_create is not supported yet", vm.ctx.new_str(name)) ); } + PySlotKind::Module(PySlotModule::MultipleInterpreters(value)) => { + // Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED is NULL. + multiple_interpreters_supported = !value.is_null(); + } // The name comes from the import spec. The remaining slots are ignored for now. _ => {} } @@ -69,6 +73,16 @@ fn load_extension_module(vm: &VirtualMachine, name: &str, export_fn: usize) -> P )); } + if !multiple_interpreters_supported + && !vm.state.is_main_interpreter() + && vm.state.feature_flags.check_multi_interp_extensions + { + return Err(vm.new_import_error( + format!("module {name} does not support loading in subinterpreters"), + vm.ctx.new_str(name), + )); + } + let module = vm.new_module( name, vm.ctx.new_dict(), @@ -89,29 +103,32 @@ fn load_extension_module(vm: &VirtualMachine, name: &str, export_fn: usize) -> P } if !execs.is_empty() { - let key = module.as_object().as_raw() as usize; - PENDING_EXEC - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .push((key, execs)); + let pending = execs + .into_iter() + .map(|exec| vm.ctx.new_int(exec as usize).into()) + .collect(); + module + .dict() + .set_item(PENDING_EXEC_KEY, vm.ctx.new_tuple(pending).into(), vm)?; } Ok(module.into()) } /// Run the exec slots recorded by [`load_extension_module`], once. fn exec_extension_module(vm: &VirtualMachine, module: &PyObject) -> PyResult<()> { - let key = module.as_raw() as usize; - let execs = { - let mut pending = PENDING_EXEC - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - match pending.iter().position(|(k, _)| *k == key) { - Some(index) => pending.swap_remove(index).1, - None => return Ok(()), - } + let Some(module) = module.downcast_ref::() else { + return Ok(()); + }; + let dict = module.dict(); + let Ok(pending) = dict.get_item(PENDING_EXEC_KEY, vm) else { + return Ok(()); }; - let module_ptr = module.as_raw().cast_mut(); - for exec in execs { + dict.del_item(PENDING_EXEC_KEY, vm)?; + let module_ptr = module.as_object().as_raw().cast_mut(); + for address in pending.try_to_value::>(vm)? { + let address = usize::try_from_object(vm, address)?; + // Safety: the address was stored by `load_extension_module` from an exec slot. + let exec: ExecSlot = unsafe { core::mem::transmute(address as *const ()) }; if unsafe { exec(module_ptr) } != 0 { return Err(vm.take_raised_exception().unwrap_or_else(|| { vm.new_system_error("exec slot of an extension module failed without an exception") diff --git a/crates/capi/src/slots.rs b/crates/capi/src/slots.rs index c1d9f073253..4944672bdb4 100644 --- a/crates/capi/src/slots.rs +++ b/crates/capi/src/slots.rs @@ -66,52 +66,15 @@ impl PySlot { stack.len() <= 10, "Too many nested slots, possible infinite loop in slot iteration" ); - return match stack.last_mut()? { + let slot: Cow<'a, Self> = match stack.last_mut()? { SlotFrame::Slots(slot_ptr) => { let slot = unsafe { &**slot_ptr }; if slot.sl_id == 0 { stack.pop(); continue; } - *slot_ptr = unsafe { slot_ptr.add(1) }; - - if slot.sl_id == 92 { - let subslots = unsafe { slot.value.sl_ptr }.cast_const().cast::(); - if !subslots.is_null() { - stack.push(SlotFrame::Slots(subslots)); - } - continue; - } - - if slot.sl_id == 93 { - let type_slots = unsafe { slot.value.sl_ptr } - .cast_const() - .cast::(); - if !type_slots.is_null() { - stack.push(SlotFrame::TypeSlots { - ptr: type_slots, - legacy_module: false, - }); - } - continue; - } - - // Py_mod_slots: a legacy PyModuleDef_Slot array - if slot.sl_id == 94 { - let module_slots = unsafe { slot.value.sl_ptr } - .cast_const() - .cast::(); - if !module_slots.is_null() { - stack.push(SlotFrame::TypeSlots { - ptr: module_slots, - legacy_module: true, - }); - } - continue; - } - - Some(Cow::Borrowed(slot)) + Cow::Borrowed(slot) } SlotFrame::TypeSlots { ptr: slot_ptr, @@ -123,19 +86,37 @@ impl PySlot { stack.pop(); continue; } - *slot_ptr = unsafe { slot_ptr.add(1) }; let mut slot: Self = type_slot.try_into().expect("invalid slot"); - if legacy_module { - // Legacy PyModuleDef_Slot ids: 1 create, 2 exec, 3 multiple - // interpreters, 4 gil. They map to 84..=87 in the unified numbering. - if (1..=4).contains(&slot.sl_id) { - slot.sl_id += 83; - } + // Legacy PyModuleDef_Slot ids: 1 create, 2 exec, 3 multiple + // interpreters, 4 gil. They map to 84..=87 in the unified numbering. + if legacy_module && (1..=4).contains(&slot.sl_id) { + slot.sl_id += 83; } - Some(Cow::Owned(slot)) + Cow::Owned(slot) } }; + + // Container slots are expanded wherever they appear, including in legacy arrays. + let ptr = unsafe { slot.value.sl_ptr }; + match slot.sl_id { + 92 => { + if !ptr.is_null() { + stack.push(SlotFrame::Slots(ptr.cast_const().cast())); + } + } + // Py_tp_slots: a PyType_Slot array + 93 | 94 => { + if !ptr.is_null() { + stack.push(SlotFrame::TypeSlots { + ptr: ptr.cast_const().cast(), + // Py_mod_slots: a legacy PyModuleDef_Slot array + legacy_module: slot.sl_id == 94, + }); + } + } + _ => return Some(slot), + } } }) } From d4effe27771b875373feeb1d3f642f9de3e24851 Mon Sep 17 00:00:00 2001 From: Mathieu Dupuy Date: Thu, 26 Nov 2026 09:50:12 +0100 Subject: [PATCH 5/5] capi: keep pending exec slots in capsules instead of Python integers Python code could overwrite the pending exec entry in the module dict with arbitrary integers, which exec_dynamic then transmuted into function pointers. Capsules cannot be created from Python and are checked by name. Assisted-by: Claude Code:claude-sonnet-5-5 --- crates/capi/src/extension.rs | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/crates/capi/src/extension.rs b/crates/capi/src/extension.rs index 543edf18964..14c8dde5f2f 100644 --- a/crates/capi/src/extension.rs +++ b/crates/capi/src/extension.rs @@ -3,8 +3,9 @@ use crate::methodobject::PyMethodDef; use crate::slots::{PySlot, PySlotKind, PySlotModule}; use crate::util::CStrExt; -use core::ffi::c_int; -use rustpython_vm::{AsObject, PyObject, PyResult, TryFromObject, VirtualMachine}; +use core::ffi::{CStr, c_int, c_void}; +use rustpython_vm::builtins::{PyCapsule, PyTuple}; +use rustpython_vm::{AsObject, PyObject, PyPayload, PyResult, VirtualMachine}; type ExecSlot = unsafe extern "C" fn(*mut PyObject) -> c_int; @@ -12,6 +13,7 @@ type ExecSlot = unsafe extern "C" fn(*mut PyObject) -> c_int; /// `_imp.exec_dynamic` runs them, once importlib has set the module attributes and added the /// module to `sys.modules` (PEP 489). Living in the module dict, they go away with the module. const PENDING_EXEC_KEY: &str = "__rustpython_pending_exec__"; +const PENDING_EXEC_NAME: &CStr = c"rustpython.pending_exec"; /// Make `_imp.create_dynamic` able to load extension modules built for the stable ABI. /// @@ -105,7 +107,12 @@ fn load_extension_module(vm: &VirtualMachine, name: &str, export_fn: usize) -> P if !execs.is_empty() { let pending = execs .into_iter() - .map(|exec| vm.ctx.new_int(exec as usize).into()) + .map(|exec| { + // Capsules cannot be created from Python, so Python code cannot forge a slot. + PyCapsule::new(exec as *mut c_void, Some(PENDING_EXEC_NAME), None) + .into_ref(&vm.ctx) + .into() + }) .collect(); module .dict() @@ -125,10 +132,18 @@ fn exec_extension_module(vm: &VirtualMachine, module: &PyObject) -> PyResult<()> }; dict.del_item(PENDING_EXEC_KEY, vm)?; let module_ptr = module.as_object().as_raw().cast_mut(); - for address in pending.try_to_value::>(vm)? { - let address = usize::try_from_object(vm, address)?; - // Safety: the address was stored by `load_extension_module` from an exec slot. - let exec: ExecSlot = unsafe { core::mem::transmute(address as *const ()) }; + let pending = pending.downcast_ref::().ok_or_else(|| { + vm.new_system_error("corrupted pending exec slots of an extension module") + })?; + for slot in pending { + let slot = slot + .downcast_ref::() + .filter(|slot| slot.name() == Some(PENDING_EXEC_NAME)) + .ok_or_else(|| { + vm.new_system_error("corrupted pending exec slots of an extension module") + })?; + // Safety: the capsule was created by `load_extension_module` from an exec slot. + let exec: ExecSlot = unsafe { core::mem::transmute(slot.pointer()) }; if unsafe { exec(module_ptr) } != 0 { return Err(vm.take_raised_exception().unwrap_or_else(|| { vm.new_system_error("exec slot of an extension module failed without an exception")