From 156206690bda4bc71d4534f483d387ab5dbaf2d0 Mon Sep 17 00:00:00 2001 From: David Biro Date: Mon, 16 Nov 2026 22:38:22 +0000 Subject: [PATCH 1/7] Separate WIT processing from linking and initialization ComponentGenerator::generate now binds the WIT world, links the libraries and initializes the result as separate steps. Initialization follows an InitPlan: owned import stubs instead of the borrowed Resolve, the environment, preopens and entropy. The linker takes the adapter as input, and the Python path search sorts directory entries so that the library order does not depend on the file system. --- src/lib.rs | 685 ++++++++++++++++++++++++++++--------------------- src/link.rs | 18 +- src/prelink.rs | 50 ++-- 3 files changed, 434 insertions(+), 319 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index d9117a0..dc74349 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,10 +4,9 @@ use { anyhow::{Context, Error, Result, anyhow, bail, ensure}, async_trait::async_trait, bytes::Bytes, - component_init_transform::Invoker, futures::future::FutureExt, indexmap::{IndexMap, IndexSet}, - serde::Deserialize, + serde::{Deserialize, Serialize}, sha2::{Digest as _, Sha256}, std::{ borrow::Cow, @@ -62,6 +61,8 @@ wasmtime::component::bindgen!({ exports: { default: async }, }); +pub use {component_init_transform::Invoker, exports::exports::Symbols}; + pub struct Ctx { wasi: WasiCtx, table: ResourceTable, @@ -122,6 +123,7 @@ fn set_build_mtimes(path: &Path) -> Result<()> { filetime::set_file_times(path, epoch, epoch).with_context(|| path.display().to_string()) } +#[derive(Clone)] pub struct Library { name: String, module: Vec, @@ -469,6 +471,78 @@ pub struct ComponentGenerator<'a> { impl ComponentGenerator<'_> { pub async fn generate(&self) -> Result<()> { + let bound = self.bind().await?; + + let component = link::link_libraries( + &bound.libraries, + &prelink::embedded_adapter()?, + self.stack_size, + )?; + + let stubbed_component = if self.stub_wasi { + stubwasi::link_stub_modules(bound.libraries)? + } else { + None + }; + + let mut preopens = vec![ + Preopen::new(bound.standard_library.path(), "python"), + Preopen::new(bound.helper_utils.path(), "bundled"), + ]; + let mut python_path = Vec::new(); + for (index, path) in bound.python_path.iter().enumerate() { + preopens.push(Preopen::new(Path::new(path), &index.to_string())); + python_path.push(format!("/{index}")); + } + for (mounts, world_dir) in &bound.world_dir_mounts { + for mount in mounts { + if DEBUG_PYTHON_BINDINGS { + eprintln!( + "world dir path: {}; mount: {mount}", + world_dir.path().display() + ); + } + preopens.push(Preopen::new(world_dir.path(), mount)); + } + } + + let plan = InitPlan::new( + self.app_name, + bound.symbols, + bound.stubs, + self.stub_wasi, + preopens, + &python_path, + &component, + ); + + let component = initialize( + &component, + stubbed_component + .as_ref() + .map(|(component, map)| (component.deref(), map as &dyn Fn(u32) -> u32)), + &plan, + self.add_to_linker, + ) + .await?; + + if DEBUG_PYTHON_BINDINGS { + // Prevent temporary directories from being deleted: + std::mem::forget(bound.world_dir_mounts); + } + + // Checks if the output directory exists, and creates it if it doesn't. + if let Some(parent) = self.output_path.parent() { + fs::create_dir_all(parent)?; + } + fs::write(self.output_path, component)?; + + Ok(()) + } + + /// Resolves the WIT inputs, generates the Wasm and Python bindings, and + /// collects the libraries to link, without linking or initializing. + async fn bind(&self) -> Result { // This is a _big_ function. Here's an overview of what it does. // // Our goal here is to collect one or more WIT paths, parse them, and @@ -866,68 +940,6 @@ impl ComponentGenerator<'_> { dl_openable: false, }); - let component = link::link_libraries(&libraries, self.stack_size)?; - - let stubbed_component = if self.stub_wasi { - stubwasi::link_stub_modules(libraries)? - } else { - None - }; - - // Pre-initialize the component by running it through - // `component_init_transform::initialize`. Currently, this is the - // application's first and only chance to load any standard or third-party - // modules since we do not yet include a virtual filesystem in the component - // to make those modules available at runtime. - - let stdout = MemoryOutputPipe::new(10000); - let stderr = MemoryOutputPipe::new(10000); - - // Pre-initialization saves everything the application computes into - // the component, so derive its hash seed and random bytes from the - // linked component instead of from host entropy. Identical inputs then - // produce identical components. The runtime reseeds `random` from the - // host before the first export call. - let digest = Sha256::digest(&component); - let random_bytes = (0u32..1024) - .flat_map(|counter| { - Sha256::new() - .chain_update(digest) - .chain_update(counter.to_le_bytes()) - .finalize() - }) - .collect::>(); - - let mut wasi = WasiCtxBuilder::new(); - wasi.secure_random(Deterministic::new(random_bytes.clone())) - .insecure_random(Deterministic::new(random_bytes)) - .insecure_random_seed(u128::from_le_bytes(digest[..16].try_into().unwrap())) - .env( - "PYTHONHASHSEED", - u32::from_le_bytes(digest[..4].try_into().unwrap()).to_string(), - ) - .wall_clock(BuildClock::default()) - .monotonic_clock(BuildClock::default()) - // Writing bytecode would change the source directories during the - // build and record the time of the write. - .env("PYTHONDONTWRITEBYTECODE", "1"); - wasi.stdin(MemoryInputPipe::new(Bytes::new())) - .stdout(stdout.clone()) - .stderr(stderr.clone()) - .env("PYTHONUNBUFFERED", "1") - .env("PYTHONHOME", "/python") - .preopened_dir( - embedded_python_standard_lib.path(), - "python", - FsPerms::ReadWrite, - )? - .preopened_dir(embedded_helper_utils.path(), "bundled", FsPerms::ReadWrite)?; - - // Generate guest mounts for each host directory in `python_path`. - for (index, path) in python_path.iter().enumerate() { - wasi.preopened_dir(path, index.to_string(), FsPerms::ReadWrite)?; - } - // For each Python module with a `componentize-py.toml` file that // specifies where generated bindings for that package should be placed, // generate the bindings and place them as indicated. @@ -999,18 +1011,6 @@ impl ComponentGenerator<'_> { &summary.helper_module_paths(&locations), )?; - for (mounts, world_dir) in world_dir_mounts.iter() { - for mount in mounts { - if DEBUG_PYTHON_BINDINGS { - eprintln!( - "world dir path: {}; mount: {mount}", - world_dir.path().display() - ); - } - wasi.preopened_dir(world_dir.path(), mount, FsPerms::ReadWrite)?; - } - } - // The guest's import system records directory modification times, so // give the directories created for this build a fixed time. for dir in [ @@ -1023,96 +1023,347 @@ impl ComponentGenerator<'_> { set_build_mtimes(dir)?; } - if DEBUG_PYTHON_BINDINGS { - // Prevent temporary directories from being deleted: - std::mem::forget(world_dir_mounts); - } - // Generate a `Symbols` object containing metadata to be passed to the // pre-init function. The runtime library will use this to look up types // and functions that will later be referenced by the generated Wasm code. let symbols = summary.collect_symbols(&locations, &metadata, &clone_maps); - // Finally, pre-initialize the component, writing the result to - // `self.output_path`. + Ok(Bound { + python_path: python_path.iter().map(|&path| path.to_owned()).collect(), + standard_library: embedded_python_standard_lib, + helper_utils: embedded_helper_utils, + world_dir_mounts, + libraries, + symbols, + stubs: import_stubs(&resolve, &all_worlds), + }) + } +} - let python_path = (0..python_path.len()) - .map(|index| format!("/{index}")) - .collect::>() - .join(":"); +/// The owned result of processing the WIT inputs for one build. +struct Bound { + python_path: Vec, + standard_library: tempfile::TempDir, + helper_utils: tempfile::TempDir, + world_dir_mounts: Vec<(Vec, tempfile::TempDir)>, + libraries: Vec, + symbols: Symbols, + stubs: Vec, +} - let table = ResourceTable::new(); - let wasi = wasi - .env( - "PYTHONPATH", - format!("/python:/world:{python_path}:/bundled"), - ) - .build(); +/// An import of the target world that pre-initialization satisfies with a +/// trapping stub. Imports of WASIp2 CLI interfaces are not stubbed; the +/// initializer supplies them. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ImportStub { + /// The interface name, or `None` for a world-level import. + pub interface: Option, + pub name: String, + pub kind: ImportStubKind, +} - let mut config = Config::new(); - config.wasm_component_model(true); - config.wasm_component_model_async(true); - config.wasm_component_model_map(true); +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum ImportStubKind { + Function { is_async: bool }, + Resource, +} - let engine = Engine::new(&config)?; +fn import_stubs(resolve: &Resolve, worlds: &IndexSet) -> Vec { + let function = |interface: Option<&String>, name: &String, kind: &FunctionKind| ImportStub { + interface: interface.cloned(), + name: name.clone(), + kind: ImportStubKind::Function { + is_async: kind.is_async(), + }, + }; + let resource = |interface: Option<&String>, name: &str| ImportStub { + interface: interface.cloned(), + name: name.to_owned(), + kind: ImportStubKind::Resource, + }; - let mut linker = Linker::new(&engine); - let added_to_linker = if let Some(add_to_linker) = self.add_to_linker { - add_to_linker(&mut linker)?; - true - } else { - false - }; + let mut stubs = Vec::new(); + for &world in worlds { + for (key, item) in &resolve.worlds[world].imports { + match item { + WorldItem::Interface { id, .. } => { + let interface_name = match key { + WorldKey::Name(name) => name.clone(), + WorldKey::Interface(interface) => resolve.id_of(*interface).unwrap(), + }; + if is_wasip2_cli(&interface_name) { + continue; + } - let mut store = Store::new(&engine, Ctx { wasi, table }); + let interface = &resolve.interfaces[*id]; + for (function_name, f) in &interface.functions { + stubs.push(function(Some(&interface_name), function_name, &f.kind)); + } - let stub_wasi = self.stub_wasi; - let app_name = self.app_name.to_owned(); - let component = component_init_transform::initialize_staged( - &component, - stubbed_component - .as_ref() - .map(|(component, map)| (component.deref(), map as &dyn Fn(u32) -> u32)), - move |instrumented| { - async move { - let component = &Component::new(&engine, instrumented)?; - if !added_to_linker { - add_wasi_and_stubs(&resolve, &all_worlds, &mut linker)?; + for (type_name, id) in interface.types.iter() { + if let TypeDefKind::Resource = &resolve.types[*id].kind { + stubs.push(resource(Some(&interface_name), type_name)); + } } + } + WorldItem::Function(f) => stubs.push(function(None, &f.name, &f.kind)), + WorldItem::Type { id, .. } => { + let ty = &resolve.types[*id]; + if let TypeDefKind::Resource = &ty.kind { + stubs.push(resource(None, ty.name.as_ref().unwrap())); + } + } + } + } + } + stubs +} - let pre = InitPre::new(linker.instantiate_pre(component)?)?; - let instance = pre.instance_pre.instantiate_async(&mut store).await?; - let guest = pre.indices.interface0.load(&mut store, &instance)?; +/// A host directory that pre-initialization makes visible to the guest. +#[derive(Clone, Debug)] +pub struct Preopen { + pub host: PathBuf, + /// The guest path, without a leading `/`. + pub guest: String, +} - guest - .call_init(&mut store, &app_name, &symbols, stub_wasi) - .await? - .map_err(|e| anyhow!("{e}"))?; +impl Preopen { + fn new(host: &Path, guest: &str) -> Self { + Self { + host: host.to_owned(), + guest: guest.to_owned(), + } + } +} - Ok(Box::new(MyInvoker { store, instance }) as Box) - } - .boxed() - }, - ) - .await - .with_context(move || { - format!( - "{}{}", - String::from_utf8_lossy(&stdout.try_into_inner().unwrap()), - String::from_utf8_lossy(&stderr.try_into_inner().unwrap()) - ) - })?; +/// Entropy for pre-initialization, derived from the linked component so that +/// identical inputs produce identical output. +/// +/// Pre-initialization saves everything the application computes into the +/// component, so it must not read host entropy. The runtime reseeds `random` +/// from the host before the first export call. +#[derive(Clone, Debug)] +pub struct BuildEntropy { + /// The value of `PYTHONHASHSEED`. + pub hash_seed: u32, + /// The bytes that `wasi:random` returns, in order, for both the secure and + /// insecure sources. + pub random_bytes: Vec, + /// The value of `wasi:random/insecure-seed`. + pub insecure_seed: u128, +} - // Checks if the output directory exists, and creates it if it doesn't. - if let Some(parent) = self.output_path.parent() { - fs::create_dir_all(parent)?; +impl BuildEntropy { + pub fn for_component(component: &[u8]) -> Self { + let digest = Sha256::digest(component); + Self { + hash_seed: u32::from_le_bytes(digest[..4].try_into().unwrap()), + random_bytes: (0u32..1024) + .flat_map(|counter| { + Sha256::new() + .chain_update(digest) + .chain_update(counter.to_le_bytes()) + .finalize() + }) + .collect(), + insecure_seed: u128::from_le_bytes(digest[..16].try_into().unwrap()), } - fs::write(self.output_path, component)?; + } +} - Ok(()) +/// Everything an initializer needs to pre-initialize a linked component. +/// +/// An initializer instantiates the instrumented component with WASIp2, these +/// environment variables and preopens, the entropy in `entropy`, wall and +/// monotonic clocks that start at zero and advance one microsecond per read, +/// an empty stdin, and a trapping stub for each entry of `stubs`. It then +/// calls `componentize-py:init/exports#init` (see [`INIT_WIT`]) with +/// `app_name`, `symbols` and `stub_wasi`. +#[derive(Clone, Debug)] +pub struct InitPlan { + pub app_name: String, + pub symbols: Symbols, + pub stubs: Vec, + pub stub_wasi: bool, + pub env: Vec<(String, String)>, + pub preopens: Vec, + pub entropy: BuildEntropy, +} + +/// The WIT world of the runtime's initialization export. +pub const INIT_WIT: &str = include_str!("../wit/init.wit"); + +impl InitPlan { + fn new( + app_name: &str, + symbols: Symbols, + stubs: Vec, + stub_wasi: bool, + preopens: Vec, + python_path: &[String], + component: &[u8], + ) -> Self { + let entropy = BuildEntropy::for_component(component); + let python_path = iter::once("/python") + .chain(iter::once("/world")) + .chain(python_path.iter().map(String::as_str)) + .chain(iter::once("/bundled")) + .collect::>() + .join(":"); + let env = [ + ("PYTHONHASHSEED", entropy.hash_seed.to_string()), + // Writing bytecode would change the source directories during the + // build and record the time of the write. + ("PYTHONDONTWRITEBYTECODE", "1".to_owned()), + ("PYTHONUNBUFFERED", "1".to_owned()), + ("PYTHONHOME", "/python".to_owned()), + ("PYTHONPATH", python_path), + ] + .into_iter() + .map(|(key, value)| (key.to_owned(), value)) + .collect(); + + Self { + app_name: app_name.to_owned(), + symbols, + stubs, + stub_wasi, + env, + preopens, + entropy, + } } } +fn add_wasi_and_stubs(stubs: &[ImportStub], linker: &mut Linker) -> Result<()> { + wasmtime_wasi::p2::add_to_linker_async(linker)?; + + let mut by_interface = IndexMap::<_, Vec<_>>::new(); + for stub in stubs { + by_interface + .entry(stub.interface.as_deref()) + .or_default() + .push(stub); + } + + for (interface_name, stubs) in by_interface { + let mut instance = if let Some(interface_name) = interface_name { + match linker.instance(interface_name) { + Ok(instance) => instance, + Err(_) => continue, + } + } else { + linker.root() + }; + let qualified = |name: &str| match interface_name { + Some(interface_name) => format!("{interface_name}#{name}"), + None => name.to_owned(), + }; + for stub in stubs { + let message = format!("called trapping stub: {}", qualified(&stub.name)); + match stub.kind { + ImportStubKind::Function { is_async: true } => { + instance.func_new_concurrent(&stub.name, move |_, _, _, _| { + let message = message.clone(); + Box::pin(async move { Err(wasmtime::format_err!("{message}")) }) + }) + } + ImportStubKind::Function { is_async: false } => instance + .func_new(&stub.name, move |_, _, _, _| { + Err(wasmtime::format_err!("{message}")) + }), + ImportStubKind::Resource => instance + .resource(&stub.name, ResourceType::host::<()>(), move |_, _| { + Err(wasmtime::format_err!("{message}")) + }) + .map(drop), + }?; + } + } + + Ok(()) +} + +/// Pre-initializes `component` according to `plan` with this crate's own +/// Wasmtime engine. +async fn initialize( + component: &[u8], + stubbed_component: component_init_transform::Stage2Map<'_>, + plan: &InitPlan, + add_to_linker: AddToLinker<'_>, +) -> Result> { + let stdout = MemoryOutputPipe::new(10000); + let stderr = MemoryOutputPipe::new(10000); + + let mut wasi = WasiCtxBuilder::new(); + wasi.secure_random(Deterministic::new(plan.entropy.random_bytes.clone())) + .insecure_random(Deterministic::new(plan.entropy.random_bytes.clone())) + .insecure_random_seed(plan.entropy.insecure_seed) + .wall_clock(BuildClock::default()) + .monotonic_clock(BuildClock::default()) + .stdin(MemoryInputPipe::new(Bytes::new())) + .stdout(stdout.clone()) + .stderr(stderr.clone()); + for (key, value) in &plan.env { + wasi.env(key, value); + } + for preopen in &plan.preopens { + wasi.preopened_dir(&preopen.host, &preopen.guest, FsPerms::ReadWrite)?; + } + let wasi = wasi.build(); + + let mut config = Config::new(); + config.wasm_component_model(true); + config.wasm_component_model_async(true); + config.wasm_component_model_map(true); + + let engine = Engine::new(&config)?; + + let mut linker = Linker::new(&engine); + if let Some(add_to_linker) = add_to_linker { + add_to_linker(&mut linker)?; + } else { + add_wasi_and_stubs(&plan.stubs, &mut linker)?; + } + + let mut store = Store::new( + &engine, + Ctx { + wasi, + table: ResourceTable::new(), + }, + ); + + let app_name = plan.app_name.clone(); + let symbols = plan.symbols.clone(); + let stub_wasi = plan.stub_wasi; + component_init_transform::initialize_staged(component, stubbed_component, move |instrumented| { + async move { + let component = &Component::new(&engine, instrumented)?; + let pre = InitPre::new(linker.instantiate_pre(component)?)?; + let instance = pre.instance_pre.instantiate_async(&mut store).await?; + let guest = pre.indices.interface0.load(&mut store, &instance)?; + + guest + .call_init(&mut store, &app_name, &symbols, stub_wasi) + .await? + .map_err(|e| anyhow!("{e}"))?; + + Ok(Box::new(MyInvoker { store, instance }) as Box) + } + .boxed() + }) + .await + .with_context(move || { + format!( + "{}{}", + String::from_utf8_lossy(&stdout.try_into_inner().unwrap()), + String::from_utf8_lossy(&stderr.try_into_inner().unwrap()) + ) + }) +} + fn parse_features(features: &[&str]) -> IndexSet { features .iter() @@ -1256,152 +1507,6 @@ fn intersect_world(resolve: &mut Resolve, intersector: WorldId, world: WorldId) world.exports.retain(|k, _| !exports_to_remove.contains(k)); } -fn add_wasi_and_stubs( - resolve: &Resolve, - worlds: &IndexSet, - linker: &mut Linker, -) -> Result<()> { - wasmtime_wasi::p2::add_to_linker_async(linker)?; - - enum Stub<'a> { - Function(&'a String, &'a FunctionKind), - Resource(&'a String), - } - - let mut stubs = HashMap::<_, Vec<_>>::new(); - for &world in worlds { - for (key, item) in &resolve.worlds[world].imports { - match item { - WorldItem::Interface { id, .. } => { - let interface_name = match key { - WorldKey::Name(name) => name.clone(), - WorldKey::Interface(interface) => resolve.id_of(*interface).unwrap(), - }; - - let interface = &resolve.interfaces[*id]; - for (function_name, function) in &interface.functions { - stubs - .entry(Some(interface_name.clone())) - .or_default() - .push(Stub::Function(function_name, &function.kind)); - } - - for (type_name, id) in interface.types.iter() { - if let TypeDefKind::Resource = &resolve.types[*id].kind { - stubs - .entry(Some(interface_name.clone())) - .or_default() - .push(Stub::Resource(type_name)); - } - } - } - WorldItem::Function(function) => { - stubs - .entry(None) - .or_default() - .push(Stub::Function(&function.name, &function.kind)); - } - WorldItem::Type { id, .. } => { - let ty = &resolve.types[*id]; - if let TypeDefKind::Resource = &ty.kind { - stubs - .entry(None) - .or_default() - .push(Stub::Resource(ty.name.as_ref().unwrap())); - } - } - } - } - } - - for (interface_name, stubs) in stubs { - if let Some(interface_name) = interface_name { - // Note that we do _not_ stub interfaces which appear to be part of - // WASIp2 since those should be provided by the - // `wasmtime_wasi::add_to_linker_async` call above, and adding stubs - // to those same interfaces would just cause trouble. - if !is_wasip2_cli(&interface_name) - && let Ok(mut instance) = linker.instance(&interface_name) - { - for stub in stubs { - let interface_name = interface_name.clone(); - match stub { - Stub::Function(name, kind) => { - if kind.is_async() { - instance.func_new_concurrent(name, { - let name = name.clone(); - move |_, _, _, _| { - let interface_name = interface_name.clone(); - let name = name.clone(); - Box::pin(async move { - Err(wasmtime::format_err!( - "called trapping stub: {interface_name}#{name}" - )) - }) - } - }) - } else { - instance.func_new(name, { - let name = name.clone(); - move |_, _, _, _| { - Err(wasmtime::format_err!( - "called trapping stub: {interface_name}#{name}" - )) - } - }) - } - } - Stub::Resource(name) => instance - .resource(name, ResourceType::host::<()>(), { - let name = name.clone(); - move |_, _| { - Err(wasmtime::format_err!( - "called trapping stub: {interface_name}#{name}" - )) - } - }) - .map(drop), - }?; - } - } - } else { - let mut instance = linker.root(); - for stub in stubs { - match stub { - Stub::Function(name, kind) => { - if kind.is_async() { - instance.func_new_concurrent(name, { - let name = name.clone(); - move |_, _, _, _| { - let name = name.clone(); - Box::pin(async move { - Err(wasmtime::format_err!("called trapping stub: {name}")) - }) - } - }) - } else { - instance.func_new(name, { - let name = name.clone(); - move |_, _, _, _| { - Err(wasmtime::format_err!("called trapping stub: {name}")) - } - }) - } - } - Stub::Resource(name) => instance - .resource(name, ResourceType::host::<()>(), { - let name = name.clone(); - move |_, _| Err(wasmtime::format_err!("called trapping stub: {name}")) - }) - .map(drop), - }?; - } - } - } - - Ok(()) -} - fn is_wasip2_cli(interface_name: &str) -> bool { (interface_name.starts_with("wasi:cli/") || interface_name.starts_with("wasi:clocks/") diff --git a/src/link.rs b/src/link.rs index da7ae43..486c76a 100644 --- a/src/link.rs +++ b/src/link.rs @@ -1,10 +1,12 @@ -use std::io::Cursor; - use anyhow::Result; use crate::Library; -pub fn link_libraries(libraries: &[Library], stack_size: Option) -> Result> { +pub fn link_libraries( + libraries: &[Library], + adapter: &[u8], + stack_size: Option, +) -> Result> { let mut linker = wit_component::Linker::default(); linker.use_built_in_libdl(true).encoder().validate(true); if let Some(stack_size) = stack_size { @@ -20,13 +22,9 @@ pub fn link_libraries(libraries: &[Library], stack_size: Option) -> Result< linker.library(name, module, *dl_openable)?; } - linker.encoder().adapter( - "wasi_snapshot_preview1", - &zstd::decode_all(Cursor::new(include_bytes!(concat!( - env!("OUT_DIR"), - "/wasi_snapshot_preview1.reactor.wasm.zst" - ))))?, - )?; + linker + .encoder() + .adapter("wasi_snapshot_preview1", adapter)?; linker.encode().map_err(|e| anyhow::anyhow!(e)) } diff --git a/src/prelink.rs b/src/prelink.rs index d02b815..d329816 100644 --- a/src/prelink.rs +++ b/src/prelink.rs @@ -33,10 +33,9 @@ pub fn embedded_python_standard_library() -> Result { // directory let stdlib = tempfile::tempdir()?; - Archive::new(Decoder::new(Cursor::new(include_bytes!(concat!( - env!("OUT_DIR"), - "/python-lib.tar.zst" - ))))?) + Archive::new(Decoder::new(Cursor::new( + embedded_python_standard_library_archive(), + ))?) .unpack(stdlib.path()) .unwrap(); @@ -57,11 +56,22 @@ pub fn embedded_helper_utils() -> Result { Ok(bundled) } +pub fn embedded_python_standard_library_archive() -> &'static [u8] { + include_bytes!(concat!(env!("OUT_DIR"), "/python-lib.tar.zst")) +} + +pub fn embedded_adapter() -> Result> { + Ok(zstd::decode_all(Cursor::new(include_bytes!(concat!( + env!("OUT_DIR"), + "/wasi_snapshot_preview1.reactor.wasm.zst" + ))))?) +} + /// Support libraries from the WASI SDK that extensions may depend on. Each is /// linked only when a linked library names it in its `dylink.0` needed list. -fn toolchain_support_libraries() -> Result)>> { +pub fn toolchain_support_libraries() -> Result)>> { Ok(vec![( - "libsetjmp.so", + "libsetjmp.so".to_owned(), zstd::decode_all(Cursor::new(include_bytes!(concat!( env!("OUT_DIR"), "/libsetjmp.so.zst" @@ -95,7 +105,11 @@ fn needed_libraries(module: &[u8]) -> Result> { /// `dlopen`. Support libraries that nothing needs are not linked, so they do /// not change the component. A needed name that remains unresolved is reported /// by the linker as a missing library. -fn add_support_libraries(libraries: &mut Vec, support: &[PathBuf]) -> Result<()> { +pub fn add_support_libraries( + libraries: &mut Vec, + support: &[PathBuf], + toolchain: &[(String, Vec)], +) -> Result<()> { let mut candidates: IndexMap)>> = IndexMap::new(); for path in support { let name = path @@ -109,8 +123,6 @@ fn add_support_libraries(libraries: &mut Vec, support: &[PathBuf]) -> R .or_default() .push((path.display().to_string(), module)); } - let toolchain = toolchain_support_libraries()?; - let mut index = 0; while index < libraries.len() { for needed in needed_libraries(&libraries[index].module)? { @@ -249,7 +261,7 @@ pub fn bundle_libraries( } } - add_support_libraries(&mut libraries, support)?; + add_support_libraries(&mut libraries, support, &toolchain_support_libraries()?)?; Ok(libraries) } @@ -333,15 +345,15 @@ fn search_directory( modules_seen: &mut HashSet, ) -> Result<()> { if path.is_dir() { - for entry in fs::read_dir(path).with_context(|| path.display().to_string())? { - search_directory( - root, - &entry?.path(), - libraries, - support, - configs, - modules_seen, - )?; + // Sort the entries so that the order of the libraries found, and so + // the linked component, does not depend on the file system. + let mut entries = fs::read_dir(path) + .with_context(|| path.display().to_string())? + .map(|entry| Ok(entry?.path())) + .collect::>>()?; + entries.sort(); + for entry in entries { + search_directory(root, &entry, libraries, support, configs, modules_seen)?; } } else if let Some(name) = path.file_name().and_then(|name| name.to_str()) { if NATIVE_EXTENSION_SUFFIXES From 236c013dfdf44e198f4105be48f4d81c6843068b Mon Sep 17 00:00:00 2001 From: David Biro Date: Mon, 16 Nov 2026 22:38:36 +0000 Subject: [PATCH 2/7] Persist prepared bindings and assemble apps with them BindingsPreparer resolves a WIT world once and returns Prepared assets: the bindings module, the generated Python bindings, the runtime libraries, the standard library, and the symbols and import stubs that initialization needs. Prepared::write stores them as content-addressed blobs and a manifest whose digest is their identity. Prepared::read verifies every blob, the manifest form and the initialization WIT before use. Assembler links prepared assets with an app and its native extensions without WIT processing. Each Python path entry has a mount name, so the library names of extensions do not depend on the order of the entries. An app that carries a componentize-py.toml file is rejected, because it would change the bindings. Assembly::initialize_with lets the caller supply the engine that runs initialization. The prepare and assemble subcommands expose this from the command line. --- Cargo.lock | 1 + Cargo.toml | 1 + src/command.rs | 160 ++++++++++++++- src/lib.rs | 2 + src/prelink.rs | 49 +++++ src/prepared.rs | 463 ++++++++++++++++++++++++++++++++++++++++++ tests/componentize.rs | 156 ++++++++++++++ 7 files changed, 830 insertions(+), 2 deletions(-) create mode 100644 src/prepared.rs diff --git a/Cargo.lock b/Cargo.lock index 08cb5e5..b1ad738 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -574,6 +574,7 @@ dependencies = [ "reqwest 0.12.28", "semver", "serde", + "serde_json", "sha2 0.10.9", "tar", "tempfile", diff --git a/Cargo.toml b/Cargo.toml index f7b6cf3..a843058 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,6 +46,7 @@ pretty_env_logger = "0.5.0" cap-std = "3.3.0" im-rc = "15.1.0" serde = { version = "1.0.213", features = ["derive"] } +serde_json = "1.0.154" toml = "0.8.19" semver = "1.0.23" wit-bindgen-core = "0.61.0" diff --git a/src/command.rs b/src/command.rs index 9a78995..8aa077b 100644 --- a/src/command.rs +++ b/src/command.rs @@ -1,6 +1,9 @@ use { - crate::{BindingsGenerator, ComponentGenerator}, - anyhow::{Context, Result}, + crate::{ + BindingsGenerator, ComponentGenerator, + prepared::{Assembler, BindingsPreparer, Prepared}, + }, + anyhow::{Context, Result, bail}, clap::Parser as _, std::{ env, @@ -130,6 +133,63 @@ pub enum Command { /// bindings generated by this command need not and should not be used by an /// actual component produced using the `componentize` command. Bindings(Bindings), + + /// Prepare the bindings, runtime and metadata for a WIT world, for + /// assembly with any number of applications. + /// + /// Prints the identity of the prepared assets. + Prepare(Prepare), + + /// Link prepared assets with a Python app and its native extensions, then + /// pre-initialize the result. + /// + /// The WIT world comes from the prepared assets; `--wit-path`, `--world` + /// and the other WIT options do not apply. + Assemble(Assemble), +} + +#[derive(clap::Args, Debug)] +pub struct Prepare { + /// Directory to which the prepared assets should be written. It must not + /// exist or must be empty. + pub output_dir: PathBuf, + + /// Specify a world to intersect with the target world. See + /// `componentize --intersect-world`. + #[arg(short = 'i', long)] + pub intersect_world: Option, +} + +#[derive(clap::Args, Debug)] +pub struct Assemble { + /// The name of a Python module containing the app to wrap. + pub app_name: String, + + /// Directory containing prepared assets. + #[arg(long)] + pub prepared: PathBuf, + + /// Fail unless the prepared assets have this identity. + #[arg(long)] + pub expect_identity: Option, + + /// Specify a directory containing the app and/or its dependencies, as + /// `[NAME=]DIRECTORY`. May be specified more than once. + /// + /// The directory is visible at `/NAME` during pre-initialization, and the + /// library names of native extensions under it start with `/NAME`. NAME + /// defaults to the position of the option, starting at 0. + #[arg(short = 'p', long, default_value = ".")] + pub python_path: Vec, + + /// Output file to which to write the resulting component + #[arg(short = 'o', long, default_value = "index.wasm")] + pub output: PathBuf, + + /// Size in bytes of the linear-memory stack used by C code. See + /// `componentize --stack-size`. + #[arg(long)] + pub stack_size: Option, } #[derive(clap::Args, Debug)] @@ -256,7 +316,103 @@ pub fn run + Clone, I: IntoIterator>(args: I) -> Res match command { Command::Componentize(opts) => componentize(common, opts), Command::Bindings(opts) => generate_bindings(common, opts), + Command::Prepare(opts) => prepare(common, opts), + Command::Assemble(opts) => assemble(common, opts), + } +} + +fn prepare(common: Common, prepare: Prepare) -> Result<()> { + let prepared = Runtime::new()?.block_on( + BindingsPreparer { + wit_paths: &common + .wit_path + .iter() + .map(|v| v.as_path()) + .collect::>(), + worlds: &common.world.iter().map(|v| v.as_str()).collect::>(), + features: &common + .features + .iter() + .map(|v| v.as_str()) + .collect::>(), + all_features: common.all_features, + bindings_module: common.bindings_module.as_deref(), + import_interface_names: &common + .import_interface_name + .iter() + .map(|(a, b)| (a.as_str(), b.as_str())) + .collect(), + export_interface_names: &common + .export_interface_name + .iter() + .map(|(a, b)| (a.as_str(), b.as_str())) + .collect(), + intersect_world: prepare.intersect_world.as_deref(), + registry_config: common.registry_config.as_deref(), + default_registries: !common.no_default_registries, + } + .prepare(), + )?; + prepared.write(&prepare.output_dir)?; + println!("{}", prepared.identity()); + Ok(()) +} + +fn assemble(common: Common, assemble: Assemble) -> Result<()> { + if !common.wit_path.is_empty() + || !common.world.is_empty() + || !common.features.is_empty() + || common.all_features + || !common.import_interface_name.is_empty() + || !common.export_interface_name.is_empty() + || common.bindings_module.is_some() + { + bail!("`assemble` takes the WIT world from the prepared assets; remove the WIT options"); + } + + let prepared = Prepared::read(&assemble.prepared)?; + if let Some(expected) = &assemble.expect_identity + && prepared.identity() != *expected + { + bail!( + "prepared assets at {} have identity {}, not {expected}", + assemble.prepared.display(), + prepared.identity() + ); + } + + let python_path = assemble + .python_path + .iter() + .enumerate() + .map(|(index, entry)| match entry.split_once('=') { + Some((name, path)) => (name.to_owned(), PathBuf::from(path)), + None => (index.to_string(), PathBuf::from(entry)), + }) + .collect::>(); + + let assembly = Assembler { + prepared: &prepared, + app_name: &assemble.app_name, + python_path: &python_path + .iter() + .map(|(name, path)| (name.as_str(), path.as_path())) + .collect::>(), + stack_size: assemble.stack_size, + } + .assemble()?; + let component = Runtime::new()?.block_on(assembly.initialize(None))?; + + if let Some(parent) = assemble.output.parent() { + fs::create_dir_all(parent)?; + } + fs::write(&assemble.output, component)?; + + if !common.quiet { + println!("Component built successfully"); } + + Ok(()) } fn generate_bindings(common: Common, bindings: Bindings) -> Result<()> { diff --git a/src/lib.rs b/src/lib.rs index dc74349..1ba0fea 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -41,6 +41,7 @@ use { pub mod command; mod link; mod prelink; +pub mod prepared; #[cfg(feature = "pyo3")] mod python; mod registry; @@ -59,6 +60,7 @@ wasmtime::component::bindgen!({ path: "wit", world: "init", exports: { default: async }, + additional_derives: [serde::Serialize, serde::Deserialize], }); pub use {component_init_transform::Invoker, exports::exports::Symbols}; diff --git a/src/prelink.rs b/src/prelink.rs index d329816..66541b0 100644 --- a/src/prelink.rs +++ b/src/prelink.rs @@ -437,3 +437,52 @@ fn module_name(root: &Path, path: &Path) -> Option { None } } + +/// Finds the native extensions and support libraries in an application's +/// Python path, for assembly with prepared bindings. +/// +/// Each entry is mounted at `/{name}`, so the library name of an extension is +/// `/{name}/{path relative to the entry}`. The names, and the order of the +/// returned libraries, do not depend on the order of the entries. A +/// `componentize-py.toml` file is an error, because it changes the WIT +/// bindings, which prepared bindings fix. +pub fn application_libraries( + python_path: &[(&str, &Path)], +) -> Result<(Vec, Vec)> { + let mut libraries = Vec::new(); + let mut support = Vec::new(); + for &(name, root) in python_path { + let mut found = Vec::new(); + let mut configs = Vec::new(); + search_directory( + root, + root, + &mut found, + &mut support, + &mut configs, + &mut HashSet::new(), + )?; + if let Some(config) = configs.first() { + bail!( + "{} configures WIT bindings, but prepared bindings cannot change; \ + prepare bindings that include this WIT instead", + config.path.join("componentize-py.toml").display() + ); + } + for library in found { + let path = library + .strip_prefix(root)? + .to_str() + .context("non-UTF-8 path")? + .replace('\\', "/"); + libraries.push(Library { + name: format!("/{name}/{path}"), + module: fs::read(&library).with_context(|| library.display().to_string())?, + dl_openable: true, + }); + } + } + libraries.sort_by(|a, b| a.name.cmp(&b.name)); + support.sort(); + Ok((libraries, support)) +} diff --git a/src/prepared.rs b/src/prepared.rs new file mode 100644 index 0000000..eb4567e --- /dev/null +++ b/src/prepared.rs @@ -0,0 +1,463 @@ +//! Prepared bindings: the part of a build that depends only on the WIT world. +//! +//! [`BindingsPreparer`] resolves the WIT world once and produces [`Prepared`] +//! assets: the Wasm bindings module, the generated Python bindings, the +//! runtime libraries, the Python standard library, and the owned metadata that +//! initialization needs. [`Prepared::write`] persists them to a directory and +//! [`Prepared::read`] loads and verifies them in another process. +//! [`Assembler`] then links the prepared assets with an application and its +//! native extensions, without WIT processing or code generation. + +use { + crate::{ + AddToLinker, ComponentGenerator, ImportStub, InitPlan, Invoker, Library, Preopen, Symbols, + initialize, link, prelink, set_build_mtimes, + }, + anyhow::{Context, Result, bail, ensure}, + futures::future::BoxFuture, + serde::{Deserialize, Serialize}, + sha2::{Digest as _, Sha256}, + std::{ + collections::{BTreeMap, HashMap, HashSet}, + fs, + io::Cursor, + path::{Path, PathBuf}, + }, + tar::{Archive, Builder, HeaderMode}, + tempfile::TempDir, + zstd::Decoder, +}; + +const FORMAT: u32 = 1; +const MANIFEST: &str = "manifest.json"; +const BLOBS: &str = "blobs"; + +/// Guest mount names that prepared assets use. Application mounts must not +/// use them. +const RESERVED_MOUNTS: &[&str] = &["python", "bundled", "world"]; + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case", deny_unknown_fields)] +struct Manifest { + format: u32, + /// The tool that prepared the assets. Recorded, not checked. + generator: String, + /// The SHA-256 of the initialization WIT that `symbols` conforms to. + init_wit: String, + adapter: String, + standard_library: String, + helper_utils: String, + world: Option, + libraries: Vec, + toolchain_support: Vec, + symbols: Symbols, + stubs: Vec, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case", deny_unknown_fields)] +struct ManifestLibrary { + name: String, + dl_openable: bool, + blob: String, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case", deny_unknown_fields)] +struct ManifestFile { + name: String, + blob: String, +} + +/// Prepared assets for one WIT world. +/// +/// Every file is a blob named by its SHA-256, and the manifest names the blobs +/// it uses. The identity of the assets is the SHA-256 of the manifest, so it +/// changes when any part of the assets changes. +pub struct Prepared { + manifest: Manifest, + blobs: BTreeMap>, +} + +fn digest(bytes: &[u8]) -> String { + Sha256::digest(bytes) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} + +fn init_wit_digest() -> String { + digest(crate::INIT_WIT.as_bytes()) +} + +impl Prepared { + /// The SHA-256 of the manifest, in lowercase hexadecimal. + pub fn identity(&self) -> String { + digest(&self.manifest_bytes()) + } + + fn manifest_bytes(&self) -> Vec { + serde_json::to_vec_pretty(&self.manifest).unwrap() + } + + fn blob(&self, name: &str) -> &[u8] { + &self.blobs[name] + } + + fn add_blob(blobs: &mut BTreeMap>, bytes: Vec) -> String { + let name = digest(&bytes); + blobs.insert(name.clone(), bytes); + name + } + + /// Writes the assets to `dir`, which must not exist or must be empty. + pub fn write(&self, dir: &Path) -> Result<()> { + if dir.exists() { + ensure!( + fs::read_dir(dir)?.next().is_none(), + "{} is not empty", + dir.display() + ); + } + let blobs = dir.join(BLOBS); + fs::create_dir_all(&blobs)?; + for (name, bytes) in &self.blobs { + fs::write(blobs.join(name), bytes)?; + } + fs::write(dir.join(MANIFEST), self.manifest_bytes())?; + Ok(()) + } + + /// Reads assets that [`Prepared::write`] wrote, and verifies them. + /// + /// The directory must contain exactly the manifest and the blobs it names, + /// each blob must match its digest, the manifest must be in the form that + /// [`Prepared::write`] writes, and its format and initialization WIT must + /// be the ones this crate uses. + pub fn read(dir: &Path) -> Result { + let context = || format!("prepared assets at {}", dir.display()); + Self::read_inner(dir).with_context(context) + } + + fn read_inner(dir: &Path) -> Result { + for entry in fs::read_dir(dir)? { + let name = entry?.file_name(); + ensure!( + name == MANIFEST || name == BLOBS, + "unexpected entry `{}`", + name.to_string_lossy() + ); + } + + let bytes = fs::read(dir.join(MANIFEST)).context("cannot read the manifest")?; + let value = serde_json::from_slice::(&bytes) + .context("the manifest is not JSON")?; + let format = value.get("format").and_then(|format| format.as_u64()); + ensure!( + format == Some(u64::from(FORMAT)), + "the manifest has format {}, but this assembler reads format {FORMAT}", + format.map_or("unknown".to_owned(), |format| format.to_string()) + ); + let manifest = + serde_json::from_value::(value).context("the manifest is not valid")?; + ensure!( + manifest.init_wit == init_wit_digest(), + "the assets were prepared for initialization WIT {}, but this assembler uses {}; \ + prepare them again with this version", + manifest.init_wit, + init_wit_digest() + ); + + let referenced = manifest_blobs(&manifest); + let mut blobs = BTreeMap::new(); + for entry in fs::read_dir(dir.join(BLOBS))? { + let entry = entry?; + let name = entry.file_name().to_string_lossy().into_owned(); + ensure!( + referenced.contains(&name), + "blob `{name}` is not named by the manifest" + ); + let bytes = fs::read(entry.path())?; + ensure!( + digest(&bytes) == name, + "blob `{name}` does not match its digest" + ); + blobs.insert(name, bytes); + } + for name in &referenced { + ensure!(blobs.contains_key(name), "blob `{name}` is missing"); + } + + let prepared = Self { manifest, blobs }; + ensure!( + prepared.manifest_bytes() == bytes, + "the manifest is not in canonical form" + ); + Ok(prepared) + } +} + +fn manifest_blobs(manifest: &Manifest) -> HashSet { + [ + &manifest.adapter, + &manifest.standard_library, + &manifest.helper_utils, + ] + .into_iter() + .chain(&manifest.world) + .chain(manifest.libraries.iter().map(|library| &library.blob)) + .chain(manifest.toolchain_support.iter().map(|file| &file.blob)) + .cloned() + .collect() +} + +/// Packs a directory into a tar archive whose bytes depend only on the names +/// and contents of its files. +fn pack(dir: &Path) -> Result> { + fn walk(root: &Path, path: &Path, paths: &mut Vec) -> Result<()> { + for entry in fs::read_dir(path)? { + let path = entry?.path(); + paths.push(path.strip_prefix(root)?.to_owned()); + if path.is_dir() { + walk(root, &path, paths)?; + } + } + Ok(()) + } + + let mut paths = Vec::new(); + walk(dir, dir, &mut paths)?; + paths.sort(); + + let mut builder = Builder::new(Vec::new()); + builder.mode(HeaderMode::Deterministic); + builder.follow_symlinks(false); + for path in paths { + builder.append_path_with_name(dir.join(&path), &path)?; + } + Ok(builder.into_inner()?) +} + +fn unpack(archive: &[u8], compressed: bool) -> Result { + let dir = tempfile::tempdir()?; + if compressed { + Archive::new(Decoder::new(Cursor::new(archive))?).unpack(dir.path())?; + } else { + Archive::new(Cursor::new(archive)).unpack(dir.path())?; + } + set_build_mtimes(dir.path())?; + Ok(dir) +} + +/// Prepares the assets for a WIT world. +/// +/// The fields have the same meaning as in [`ComponentGenerator`]. Per-module +/// `componentize-py.toml` configuration does not apply, because preparation +/// does not search a Python path. +pub struct BindingsPreparer<'a> { + pub wit_paths: &'a [&'a Path], + pub worlds: &'a [&'a str], + pub features: &'a [&'a str], + pub all_features: bool, + pub bindings_module: Option<&'a str>, + pub import_interface_names: &'a HashMap<&'a str, &'a str>, + pub export_interface_names: &'a HashMap<&'a str, &'a str>, + pub intersect_world: Option<&'a str>, + pub registry_config: Option<&'a Path>, + pub default_registries: bool, +} + +impl BindingsPreparer<'_> { + pub async fn prepare(&self) -> Result { + let bound = ComponentGenerator { + wit_paths: self.wit_paths, + worlds: self.worlds, + features: self.features, + all_features: self.all_features, + bindings_module: self.bindings_module, + python_path: &[], + module_worlds: &[], + app_name: "", + output_path: Path::new(""), + add_to_linker: None, + stub_wasi: false, + stack_size: None, + import_interface_names: self.import_interface_names, + export_interface_names: self.export_interface_names, + intersect_world: self.intersect_world, + registry_config: self.registry_config, + default_registries: self.default_registries, + } + .bind() + .await?; + + let mut blobs = BTreeMap::new(); + let world = match &bound.world_dir_mounts[..] { + [] => None, + [(mounts, dir)] if mounts == &["world"] => { + Some(Prepared::add_blob(&mut blobs, pack(dir.path())?)) + } + _ => bail!("prepared bindings support only one generated bindings module"), + }; + + let manifest = Manifest { + format: FORMAT, + generator: format!("componentize-py {}", env!("CARGO_PKG_VERSION")), + init_wit: init_wit_digest(), + adapter: Prepared::add_blob(&mut blobs, prelink::embedded_adapter()?), + standard_library: Prepared::add_blob( + &mut blobs, + prelink::embedded_python_standard_library_archive().to_vec(), + ), + helper_utils: Prepared::add_blob(&mut blobs, pack(bound.helper_utils.path())?), + world, + libraries: bound + .libraries + .into_iter() + .map(|library| ManifestLibrary { + name: library.name, + dl_openable: library.dl_openable, + blob: Prepared::add_blob(&mut blobs, library.module), + }) + .collect(), + toolchain_support: prelink::toolchain_support_libraries()? + .into_iter() + .map(|(name, module)| ManifestFile { + name, + blob: Prepared::add_blob(&mut blobs, module), + }) + .collect(), + symbols: bound.symbols, + stubs: bound.stubs, + }; + + Ok(Prepared { manifest, blobs }) + } +} + +/// Links prepared assets with an application. +pub struct Assembler<'a> { + pub prepared: &'a Prepared, + /// The module that initialization imports. + pub app_name: &'a str, + /// The application's Python path. Each entry is a guest mount name and a + /// host directory; the directory is visible at `/{name}` during + /// initialization, and native extensions under it get library names + /// below `/{name}`. + pub python_path: &'a [(&'a str, &'a Path)], + /// See [`ComponentGenerator::stack_size`]. + pub stack_size: Option, +} + +/// A linked component and the plan to initialize it. +pub struct Assembly { + pub component: Vec, + pub plan: InitPlan, + _dirs: Vec, +} + +impl Assembler<'_> { + pub fn assemble(&self) -> Result { + let mut names = HashSet::new(); + for &(name, _) in self.python_path { + ensure!( + !name.is_empty() + && name + .chars() + .all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c)) + && name != "." + && name != "..", + "invalid Python path mount name `{name}`" + ); + ensure!( + !RESERVED_MOUNTS.contains(&name), + "the Python path mount name `{name}` is reserved" + ); + ensure!( + names.insert(name), + "duplicate Python path mount name `{name}`" + ); + } + + let manifest = &self.prepared.manifest; + let (application_libraries, support) = prelink::application_libraries(self.python_path)?; + let mut libraries = manifest + .libraries + .iter() + .map(|library| Library { + name: library.name.clone(), + module: self.prepared.blob(&library.blob).to_vec(), + dl_openable: library.dl_openable, + }) + .chain(application_libraries) + .collect::>(); + let toolchain = manifest + .toolchain_support + .iter() + .map(|file| (file.name.clone(), self.prepared.blob(&file.blob).to_vec())) + .collect::>(); + prelink::add_support_libraries(&mut libraries, &support, &toolchain)?; + + let component = link::link_libraries( + &libraries, + self.prepared.blob(&manifest.adapter), + self.stack_size, + )?; + + let standard_library = unpack(self.prepared.blob(&manifest.standard_library), true)?; + let helper_utils = unpack(self.prepared.blob(&manifest.helper_utils), false)?; + let world = manifest + .world + .as_ref() + .map(|world| unpack(self.prepared.blob(world), false)) + .transpose()?; + + let mut preopens = vec![ + Preopen::new(standard_library.path(), "python"), + Preopen::new(helper_utils.path(), "bundled"), + ]; + let mut python_path = Vec::new(); + for &(name, path) in self.python_path { + preopens.push(Preopen::new(path, name)); + python_path.push(format!("/{name}")); + } + if let Some(world) = &world { + preopens.push(Preopen::new(world.path(), "world")); + } + + let plan = InitPlan::new( + self.app_name, + manifest.symbols.clone(), + manifest.stubs.clone(), + false, + preopens, + &python_path, + &component, + ); + + Ok(Assembly { + component, + plan, + _dirs: [standard_library, helper_utils] + .into_iter() + .chain(world) + .collect(), + }) + } +} + +impl Assembly { + /// Pre-initializes the component with this crate's own Wasmtime engine. + pub async fn initialize(&self, add_to_linker: AddToLinker<'_>) -> Result> { + initialize(&self.component, None, &self.plan, add_to_linker).await + } + + /// Pre-initializes the component with a caller-supplied initializer, which + /// receives the instrumented component and must follow [`Assembly::plan`]. + pub async fn initialize_with( + &self, + initializer: impl FnOnce(Vec) -> BoxFuture<'static, Result>>, + ) -> Result> { + component_init_transform::initialize_staged(&self.component, None, initializer).await + } +} diff --git a/tests/componentize.rs b/tests/componentize.rs index 22d792f..4d63c76 100644 --- a/tests/componentize.rs +++ b/tests/componentize.rs @@ -450,3 +450,159 @@ fn install_numpy(path: &Path) -> anyhow::Result<()> { Ok(()) } + +fn prepare_cli_world(dir: &Path, output: &str) -> anyhow::Result { + if !dir.join("wit").exists() { + fs_extra::copy_items(&["./wit"], dir, &CopyOptions::new())?; + } + let assert = cargo::cargo_bin_cmd!("componentize-py") + .current_dir(dir) + .args([ + "-d", + "wit", + "-w", + "wasi:cli/command@0.2.0", + "prepare", + output, + ]) + .assert() + .success(); + Ok(String::from_utf8(assert.get_output().stdout.clone())? + .trim() + .to_owned()) +} + +fn write_cli_app(dir: &Path, module: &str, prelude: &str, text: &str) -> anyhow::Result { + let app = dir.join(module); + fs::create_dir_all(&app)?; + fs::write( + app.join(format!("{module}.py")), + format!( + "{prelude}from wit.exports.wasi.cli_v0_2 import run, Run\n\n\ + @run.guest\nclass Cli(Run):\n def run(self) -> None:\n print({text:?})\n" + ), + )?; + Ok(app) +} + +fn assemble_cmd(dir: &Path, module: &str, app: &Path, extra: &[&str]) -> Command { + let mut command = cargo::cargo_bin_cmd!("componentize-py"); + command + .current_dir(dir) + .args(["assemble", "--prepared", "prepared"]) + .args(extra) + .args([module, "-p"]) + .arg(format!("app={}", app.display())) + .args(["-o", &format!("{module}.wasm")]); + command +} + +fn tree(dir: &Path) -> anyhow::Result)>> { + let mut files = Vec::new(); + for entry in fs::read_dir(dir)? { + let path = entry?.path(); + if path.is_dir() { + files.extend(tree(&path)?); + } else { + files.push((path.clone(), fs::read(&path)?)); + } + } + files.sort(); + Ok(files) +} + +#[test] +fn prepared_assets_assemble_unrelated_apps() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + let identity = prepare_cli_world(dir.path(), "prepared")?; + assert_eq!( + prepare_cli_world(dir.path(), "prepared-again")?, + identity, + "preparing the same WIT twice gives the same identity" + ); + let before = tree(&dir.path().join("prepared"))?; + + for (module, text) in [("first", "first app"), ("second", "the second app")] { + let app = write_cli_app(dir.path(), module, "", text)?; + assemble_cmd(dir.path(), module, &app, &["--expect-identity", &identity]) + .assert() + .success(); + + Command::new("wasmtime") + .current_dir(dir.path()) + .args(["run", &format!("{module}.wasm")]) + .assert() + .success() + .stdout(format!("{text}\n")); + } + + assert!( + before == tree(&dir.path().join("prepared"))?, + "assembly does not change the prepared assets" + ); + Ok(()) +} + +#[test] +fn assemble_rejects_mismatched_assets_before_imports() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + prepare_cli_world(dir.path(), "prepared")?; + // Importing the app writes a marker into its own directory. + let app = write_cli_app( + dir.path(), + "marker", + "open('/app/imported', 'w').close()\n", + "ok", + )?; + let marker = app.join("imported"); + + assemble_cmd(dir.path(), "marker", &app, &[]) + .assert() + .success(); + assert!(marker.exists(), "intact assets import the app"); + fs::remove_file(&marker)?; + + let blob = fs::read_dir(dir.path().join("prepared/blobs"))? + .next() + .unwrap()? + .path(); + let original = fs::read(&blob)?; + let mut changed = original.clone(); + changed[0] ^= 1; + fs::write(&blob, &changed)?; + assemble_cmd(dir.path(), "marker", &app, &[]) + .assert() + .failure() + .stderr(predicate::str::contains("does not match its digest")); + fs::write(&blob, &original)?; + + fs::write(dir.path().join("prepared/extra"), "")?; + assemble_cmd(dir.path(), "marker", &app, &[]) + .assert() + .failure() + .stderr(predicate::str::contains("unexpected entry `extra`")); + fs::remove_file(dir.path().join("prepared/extra"))?; + + assemble_cmd(dir.path(), "marker", &app, &["--expect-identity", "0"]) + .assert() + .failure() + .stderr(predicate::str::contains("not 0")); + + assert!(!marker.exists(), "rejected assets do not import the app"); + Ok(()) +} + +#[test] +fn assemble_rejects_apps_that_configure_wit() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + prepare_cli_world(dir.path(), "prepared")?; + let app = write_cli_app(dir.path(), "configured", "", "ok")?; + fs::create_dir(app.join("sdk"))?; + fs::write(app.join("sdk/componentize-py.toml"), "")?; + + assemble_cmd(dir.path(), "configured", &app, &[]) + .assert() + .failure() + .stderr(predicate::str::contains("configures WIT bindings")); + Ok(()) +} From a1088facee0c5b43c0ee667061c9e95930f343fe Mon Sep 17 00:00:00 2001 From: David Biro Date: Mon, 16 Nov 2026 22:57:47 +0000 Subject: [PATCH 3/7] Update Wasmtime to 50.0.1 Golem's engine uses Wasmtime 50.0.1, so the crate can run initialization on an engine that Golem configures. --- Cargo.lock | 425 +++++++++++++++++++++++------------------------------ Cargo.toml | 4 +- 2 files changed, 183 insertions(+), 246 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b1ad738..565d741 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -368,8 +368,8 @@ checksum = "8e0bf07d379916947be6c4a07f43684153d710a2896c31f9e97781362895596c" dependencies = [ "ambient-authority", "fs-set-times", - "io-extras 0.18.4", - "io-lifetimes 2.0.4", + "io-extras", + "io-lifetimes", "ipnet", "maybe-owned", "rustix", @@ -378,33 +378,15 @@ dependencies = [ "winx", ] -[[package]] -name = "cap-primitives" -version = "4.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b5f74729fd2f44701d1a8eb47e906cdb3ccd9ec0f02baad85a744b791940b18" -dependencies = [ - "ambient-authority", - "fs-set-times", - "io-extras 0.19.0", - "io-lifetimes 3.0.1", - "ipnet", - "maybe-owned", - "rustix", - "rustix-linux-procfs", - "windows-sys 0.61.2", - "winx", -] - [[package]] name = "cap-std" version = "3.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a59e59fa26472d29680ece6a9f8ee8b0551a719a33df2f5240bde065ecbddfd7" dependencies = [ - "cap-primitives 3.4.6", - "io-extras 0.18.4", - "io-lifetimes 2.0.4", + "cap-primitives", + "io-extras", + "io-lifetimes", "rustix", ] @@ -712,27 +694,27 @@ dependencies = [ [[package]] name = "cranelift-assembler-x64" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6071a4f1df4837aa03d1e4d53067784acafe270ffc7dad66a7f39832204da3f" +checksum = "80aafbfb0490c28f23bdb6183acfd470d48244745d6bb70e66121f7751a9a7ca" dependencies = [ "cranelift-assembler-x64-meta", ] [[package]] name = "cranelift-assembler-x64-meta" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e3b92a9cc90388fe70e63640af30b734387449445aef0176ab2028e9892d70e" +checksum = "d2e5ea46889c5bf3c0eb5882a8d6ed755e26f6efab8b3f0b441a7e781f56b03e" dependencies = [ "cranelift-srcgen", ] [[package]] name = "cranelift-bforest" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f45c85646c4425cc85b868effaf20c302b437a3fb79bb27a64513dd522f07411" +checksum = "8a65274b952dba816b143b20df6976dbbfc1f2830907f6be262cf0370c061231" dependencies = [ "cranelift-entity", "wasmtime-internal-core", @@ -740,9 +722,9 @@ dependencies = [ [[package]] name = "cranelift-bitset" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94f56b5c7d564cfa03aa269a6b98c916cab4d545196a391d31403a23ef39333a" +checksum = "fc739cedf56f9ad87c94bc3473908d6b0149221526905a2871c33cfed7f2c8d9" dependencies = [ "serde", "serde_derive", @@ -751,9 +733,9 @@ dependencies = [ [[package]] name = "cranelift-codegen" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c073641ce6e382814a8220331cc1ea2c782a9ea5d5da6d0f7f7c0541192693e" +checksum = "d91eb4435f140b0b05bb053ef6267e22a8c858beed43a560749e90991d7b7a63" dependencies = [ "bumpalo", "cranelift-assembler-x64", @@ -782,9 +764,9 @@ dependencies = [ [[package]] name = "cranelift-codegen-meta" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db226fafea5194921de10dccf35ac2863500313990f770cbe8b26c51eebec4d4" +checksum = "b9e0194c51a53670724fec307f9bbd8dc18f9b0bb3c7728efd5a45475f8641de" dependencies = [ "cranelift-assembler-x64-meta", "cranelift-codegen-shared", @@ -795,24 +777,24 @@ dependencies = [ [[package]] name = "cranelift-codegen-shared" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf8ac46b2c8e328ca979810426ea635ef90ecc8c54fd3296bde31ab470a48a1d" +checksum = "73c10abe5c89741cb15008c8a3d9fd177c7d7a1b9af22b7eff1eb3f9e9f2ed61" [[package]] name = "cranelift-control" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6754e0ab97915209ea6ce6549f6443b018e1338142ada4c856cec213ee82e4b8" +checksum = "d15be56b0f8c45eb15d60164f31f5ec89b277fde2a05283cc66722c2b57a7980" dependencies = [ "arbitrary", ] [[package]] name = "cranelift-entity" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "774d25e36df18696f63a284e9c4ea43455e2ebcca6308e0e02301f18c8e777e2" +checksum = "f1384afac57ecc364ced64eb8526da8d883233157f1b5e37353bc6d172a71427" dependencies = [ "cranelift-bitset", "serde", @@ -822,9 +804,9 @@ dependencies = [ [[package]] name = "cranelift-frontend" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cfcb31405e2de2a48e5a6de8e07a3d8b77f35caa3e944d627780734b36c138" +checksum = "c491acfa0f5056cf573c36f04d495d991b644ec9df893d132ea9415fb347c44e" dependencies = [ "cranelift-codegen", "hashbrown 0.17.1", @@ -835,26 +817,27 @@ dependencies = [ [[package]] name = "cranelift-isle" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f5a26df22db546ab92be6feaf21835ae91082af0a32bbb398b277df3765412f" +checksum = "851ff79666f0af6288aa0d652f7315ae9b027eef00113a819d2dd12f5395a4db" [[package]] name = "cranelift-native" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19f258c08e590f90dcaf9904d25ba142ee2980c3aaeac4bb45f1452b1a407c2a" +checksum = "a8c4069cb5d92c95655b3bc610295de7be9c989d5cf007ba2d3dcb1834b10e26" dependencies = [ "cranelift-codegen", "libc", + "mach2", "target-lexicon", ] [[package]] name = "cranelift-srcgen" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67055b4f315e8f6af3e8eccec74ad38f7407f0fd854adbd49b4b3b27bdb2e3be" +checksum = "1c4cad638d567f380c02aeb025a4a930e97ca5c044299c5deb07c53679a027b1" [[package]] name = "crc32fast" @@ -1218,7 +1201,7 @@ version = "0.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a" dependencies = [ - "io-lifetimes 2.0.4", + "io-lifetimes", "rustix", "windows-sys 0.59.0", ] @@ -1750,32 +1733,16 @@ version = "0.18.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2285ddfe3054097ef4b2fe909ef8c3bcd1ea52a8f0d274416caebeef39f04a65" dependencies = [ - "io-lifetimes 2.0.4", + "io-lifetimes", "windows-sys 0.59.0", ] -[[package]] -name = "io-extras" -version = "0.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f" -dependencies = [ - "io-lifetimes 3.0.1", - "windows-sys 0.60.2", -] - [[package]] name = "io-lifetimes" version = "2.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06432fb54d3be7964ecd3649233cddf80db2832f47fec34c01f65b3d9d774983" -[[package]] -name = "io-lifetimes" -version = "3.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f0fb0570afe1fed943c5c3d4102d5358592d8625fda6a0007fdbe65a92fba96" - [[package]] name = "ipnet" version = "2.12.2" @@ -2103,9 +2070,9 @@ dependencies = [ [[package]] name = "object" -version = "0.39.1" +version = "0.40.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +checksum = "dd229a0361b9d0d4396176e02d65897f487eebeab7caa6d443855ee152ca0b9c" dependencies = [ "crc32fast", "hashbrown 0.17.1", @@ -2360,9 +2327,9 @@ dependencies = [ [[package]] name = "pulley-interpreter" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b8187c8e7db87d085865fc106502e7b34d5c25f8ce4c272945b21503371f6a0" +checksum = "ac335d6104773cb78791143cba33fb2148766dc43dc1e9c6907ff2046882d953" dependencies = [ "cranelift-bitset", "log", @@ -2372,13 +2339,13 @@ dependencies = [ [[package]] name = "pulley-macros" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f98ce0e381d9e45e63ea1d20bba3cf131797086077f43af9203f1fb7de0ed6b" +checksum = "ecc5c33f912277d2c57155ff8c599b3ab9cc6fc59526d2baba22f5cd411ffd68" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] @@ -3391,21 +3358,6 @@ dependencies = [ "toml_edit 0.22.27", ] -[[package]] -name = "toml" -version = "0.9.12+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" -dependencies = [ - "indexmap", - "serde_core", - "serde_spanned 1.1.2", - "toml_datetime 0.7.5+spec-1.1.0", - "toml_parser", - "toml_writer", - "winnow 0.7.15", -] - [[package]] name = "toml" version = "1.1.8+spec-1.1.0" @@ -3430,15 +3382,6 @@ dependencies = [ "serde", ] -[[package]] -name = "toml_datetime" -version = "0.7.5+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" -dependencies = [ - "serde_core", -] - [[package]] name = "toml_datetime" version = "1.1.2+spec-1.1.0" @@ -3793,18 +3736,17 @@ dependencies = [ [[package]] name = "wasm-compose" -version = "0.254.2" +version = "0.261.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c0c1033c10d23d96f40e761ae66cc30c70cea3323a8edfe9159dac42108873f" +checksum = "df7deb87d659b1df555d3195e3df56d1f03b73d165c5a1bc3a0bad24274ea147" dependencies = [ "anyhow", - "heck", "indexmap", "log", "petgraph 0.6.5", "smallvec", - "wasm-encoder 0.254.2", - "wasmparser 0.254.2", + "wasm-encoder 0.261.0", + "wasmparser 0.261.0", "wat", ] @@ -3848,6 +3790,16 @@ dependencies = [ "wasmparser 0.258.3", ] +[[package]] +name = "wasm-encoder" +version = "0.261.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2608e8bb6d67fd68f5a8d0eb1363d6e7bcbc1f8ded5a0bd3a1e382462b876b22" +dependencies = [ + "leb128fmt", + "wasmparser 0.261.0", +] + [[package]] name = "wasm-encoder" version = "0.262.0" @@ -3920,6 +3872,18 @@ dependencies = [ "wasmparser 0.258.3", ] +[[package]] +name = "wasm-metadata" +version = "0.261.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b88de21560ecd49deb8d8f1616b9b695f66fc312c5eca503f43accdc5795339e" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder 0.261.0", + "wasmparser 0.261.0", +] + [[package]] name = "wasm-pkg-client" version = "0.16.1" @@ -4012,7 +3976,6 @@ dependencies = [ "hashbrown 0.17.1", "indexmap", "semver", - "serde", ] [[package]] @@ -4041,6 +4004,19 @@ dependencies = [ "serde", ] +[[package]] +name = "wasmparser" +version = "0.261.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f20f20e44f7e8aeb6744823ea9d869ede51e51be4fdaedede2852282e54d2d8" +dependencies = [ + "bitflags", + "hashbrown 0.17.1", + "indexmap", + "semver", + "serde", +] + [[package]] name = "wasmparser" version = "0.262.0" @@ -4054,20 +4030,20 @@ dependencies = [ [[package]] name = "wasmprinter" -version = "0.254.2" +version = "0.261.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b03c8f270f3f384f70f42869b5ff7f6253fe4f0aa8590f7edd332c1943e5f51" +checksum = "86a21c9e3325655ba02de3e645bc8357a8b3651a2e3ada25b6dbc37560deb9b7" dependencies = [ "anyhow", "termcolor", - "wasmparser 0.254.2", + "wasmparser 0.261.0", ] [[package]] name = "wasmtime" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12300d040e8bea7e7ccde75b9919d27ebba47a217a64b09ba058ae8d3b4290b6" +checksum = "9e32e3ce9a15d2ddedfeae38437a4fe52ed9c59ac878e3131e5a840068faf44e" dependencies = [ "addr2line", "async-trait", @@ -4098,8 +4074,8 @@ dependencies = [ "target-lexicon", "tempfile", "wasm-compose", - "wasm-encoder 0.254.2", - "wasmparser 0.254.2", + "wasm-encoder 0.261.0", + "wasmparser 0.261.0", "wasmtime-environ", "wasmtime-internal-cache", "wasmtime-internal-component-macro", @@ -4113,14 +4089,14 @@ dependencies = [ "wasmtime-internal-versioned-export-macros", "wat", "windows-sys 0.61.2", - "wit-parser 0.254.2", + "wit-parser 0.261.0", ] [[package]] name = "wasmtime-environ" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "805d6554eb6dd6e62891061a31383a89d69fd891f785e5ae68f0835a554b7a2a" +checksum = "2b204a74048032e778bf04348dd80c906e749cd0a61e5447e55129d803b2303e" dependencies = [ "anyhow", "cpp_demangle", @@ -4137,11 +4113,10 @@ dependencies = [ "semver", "serde", "serde_derive", - "sha2 0.10.9", "smallvec", "target-lexicon", - "wasm-encoder 0.254.2", - "wasmparser 0.254.2", + "wasm-encoder 0.261.0", + "wasmparser 0.261.0", "wasmprinter", "wasmtime-internal-component-util", "wasmtime-internal-core", @@ -4149,9 +4124,9 @@ dependencies = [ [[package]] name = "wasmtime-internal-cache" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b11ca8945aa341f944558622db59845dffa1435971f318d5fce2f2d9765a69b0" +checksum = "96e9b0120eaa3448f11673000e5c970fda5d78f3a3f35a08fd00fa9462453322" dependencies = [ "base64 0.22.1", "directories-next", @@ -4161,7 +4136,7 @@ dependencies = [ "serde", "serde_derive", "sha2 0.10.9", - "toml 0.9.12+spec-1.1.0", + "toml 1.1.8+spec-1.1.0", "wasmtime-environ", "windows-sys 0.61.2", "zstd 0.13.3", @@ -4169,30 +4144,30 @@ dependencies = [ [[package]] name = "wasmtime-internal-component-macro" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b832b80853365d9d3a741681044554be291a4f977aae074b318b55c7a4835f83" +checksum = "bc9b1c3975c5ed4ad404ecde0a4b2ed2a94b7dfc8b5c6b03e759831744a452c0" dependencies = [ "anyhow", "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", "wasmtime-internal-component-util", "wasmtime-internal-wit-bindgen", - "wit-parser 0.254.2", + "wit-parser 0.261.0", ] [[package]] name = "wasmtime-internal-component-util" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c8a11aaf68d8945991429d45950f32490a30ddcdcdb56629816cb41a255d8fe" +checksum = "86e3ec719916f972b40b5d02a9d0c072fbed65927ae777d67e4776226d9d0072" [[package]] name = "wasmtime-internal-core" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea266d6cfb31c324c075c8432386654bcbb1559aa8d29be9d47eacf7dcc41012" +checksum = "0188c3e530af2407cb868818701df371ddd7061e2d73182d6d0cdc5b7e1a7a5f" dependencies = [ "anyhow", "hashbrown 0.17.1", @@ -4202,9 +4177,9 @@ dependencies = [ [[package]] name = "wasmtime-internal-cranelift" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d427759553b07c296c8ed7bff8ac930a94b9ba99e6a79243ea79bcc51aa58d96" +checksum = "6dfcfa2173aee3184c2c66c850a740c5b11565485f3ea36da2c405c9a21fd7fc" dependencies = [ "cranelift-codegen", "cranelift-control", @@ -4219,7 +4194,7 @@ dependencies = [ "smallvec", "target-lexicon", "thiserror 2.0.21", - "wasmparser 0.254.2", + "wasmparser 0.261.0", "wasmtime-environ", "wasmtime-internal-core", "wasmtime-internal-unwinder", @@ -4228,9 +4203,9 @@ dependencies = [ [[package]] name = "wasmtime-internal-fiber" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b54c8c5b02ea985149a90f917e1761af99734c6c27e6d7fdd5b6f69fc1db3950" +checksum = "8ef75fc7dd6ac3e02239cb6e840d9ff400b8d33be948bd94553c51d978e2a77b" dependencies = [ "cc", "libc", @@ -4242,9 +4217,9 @@ dependencies = [ [[package]] name = "wasmtime-internal-jit-debug" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72bb10c94724f072b6eca515085033e61da9efae65d054545126df37a15530c3" +checksum = "1a3029a2f03287e5ba6162f43e717cfa9a4f92babc8b53f56e4bc1680687f684" dependencies = [ "cc", "object", @@ -4254,9 +4229,9 @@ dependencies = [ [[package]] name = "wasmtime-internal-jit-icache-coherence" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b781a27e8958fd07fd3135c0be216f77301efecd15cbf4f14ff210cdad5f169" +checksum = "42dcd30201c6eff398ed264a8633f381242ab0eae1e6702eb0c4721b8c5d498d" dependencies = [ "libc", "wasmtime-internal-core", @@ -4265,9 +4240,9 @@ dependencies = [ [[package]] name = "wasmtime-internal-unwinder" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "121188de1b2741b8e35530a9b0c8adf525b3aa5913a2ca3d4522509cfbc0494a" +checksum = "40bfc597fc389f058e0f3151b4063b12133f5999d68c751bb48fc36352f21dff" dependencies = [ "cranelift-codegen", "log", @@ -4277,39 +4252,38 @@ dependencies = [ [[package]] name = "wasmtime-internal-versioned-export-macros" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "933f1990e4e5177547a4abd51dcfa5cb7616fe42b9fb6f0f2b7423627758223c" +checksum = "9ea83140ce7e7e6c4357b43988974a761dd9f74d51ea674e5c822a5022bcc9f0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] name = "wasmtime-internal-wit-bindgen" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "417ebd61d2581d86d65413517f3a41294a9ad105da26f0dc7039912a0d97e1ed" +checksum = "61ef2d7c6d52219718083aba0f6b05afa245ff5e76aa75b95fcae7671e0bdbb5" dependencies = [ "anyhow", "bitflags", "heck", "indexmap", - "wit-component 0.254.2", - "wit-parser 0.254.2", + "wit-component 0.261.0", + "wit-parser 0.261.0", ] [[package]] name = "wasmtime-wasi" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ef0d3ec88f9406bc5e498848489c49ff515577500acc9f03fa93d0883dce435" +checksum = "a08c772131a8cbfc3a2c116b637c1c36609012738db949723df53fd9f88bb4e0" dependencies = [ "async-trait", "bitflags", "bytes", - "cap-primitives 4.0.3", "futures", "rand", "rustix", @@ -4322,14 +4296,13 @@ dependencies = [ "wasmtime-wasi-io", "wiggle", "windows-sys 0.61.2", - "winx", ] [[package]] name = "wasmtime-wasi-io" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe7dfc924e222e15455bd6d445ff7065a4595fffc7698c7bbc01acc0ed6c0421" +checksum = "bb4241148712c8604662377b440f93af7615f61a997f03bc28ea61450a545445" dependencies = [ "async-trait", "bytes", @@ -4409,9 +4382,9 @@ dependencies = [ [[package]] name = "wiggle" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f25221922f042ed78c7857a29f2e54d45d02a73891bcc3a046f2c3c0400cfd3" +checksum = "1de475da34b9904405df36a7f76037a29a06b5def3d57130bbcd1a31a79dff2e" dependencies = [ "bitflags", "thiserror 2.0.21", @@ -4423,27 +4396,27 @@ dependencies = [ [[package]] name = "wiggle-generate" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9ad83cd72263fd94189bdbf3bf37dc131f6a293ff639cebfbb00ed3f21f05f2" +checksum = "1b77277488ed90b907324d5b155b514c65e9fdba70a792e32d344a10b3c8f21b" dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", "wasmtime-environ", "witx", ] [[package]] name = "wiggle-macro" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96820f65b0f61bad3e6dd073f670db9a6da537dc71f848fee715f692b19dfd9a" +checksum = "d038b7871fd025d3d436f71c16bf107ff7fee91386f92bf133588e96b39468ae" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", "wiggle-generate", ] @@ -4543,7 +4516,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.6", + "windows-targets", ] [[package]] @@ -4552,16 +4525,7 @@ version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-sys" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" -dependencies = [ - "windows-targets 0.53.5", + "windows-targets", ] [[package]] @@ -4579,31 +4543,14 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm 0.52.6", - "windows_aarch64_msvc 0.52.6", - "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm 0.52.6", - "windows_i686_msvc 0.52.6", - "windows_x86_64_gnu 0.52.6", - "windows_x86_64_gnullvm 0.52.6", - "windows_x86_64_msvc 0.52.6", -] - -[[package]] -name = "windows-targets" -version = "0.53.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" -dependencies = [ - "windows-link", - "windows_aarch64_gnullvm 0.53.1", - "windows_aarch64_msvc 0.53.1", - "windows_i686_gnu 0.53.1", - "windows_i686_gnullvm 0.53.1", - "windows_i686_msvc 0.53.1", - "windows_x86_64_gnu 0.53.1", - "windows_x86_64_gnullvm 0.53.1", - "windows_x86_64_msvc 0.53.1", + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", ] [[package]] @@ -4612,96 +4559,48 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" - [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" -[[package]] -name = "windows_aarch64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" - [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" -[[package]] -name = "windows_i686_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" - [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" -[[package]] -name = "windows_i686_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" - [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" -[[package]] -name = "windows_i686_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" - [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" -[[package]] -name = "windows_x86_64_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" - [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" - [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" -[[package]] -name = "windows_x86_64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" - [[package]] name = "winnow" version = "0.7.15" @@ -4837,6 +4736,25 @@ dependencies = [ "wit-parser 0.258.3", ] +[[package]] +name = "wit-component" +version = "0.261.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2818766842bd2321074c348fb5c15d8fdb105a9eb78374e6d77c7d4127e1f2f9" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder 0.261.0", + "wasm-metadata 0.261.0", + "wasmparser 0.261.0", + "wit-parser 0.261.0", +] + [[package]] name = "wit-dylib" version = "0.258.3" @@ -4911,6 +4829,25 @@ dependencies = [ "wasmparser 0.258.3", ] +[[package]] +name = "wit-parser" +version = "0.261.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "962e43c4db2da607b50839a531e5b63473268b40efdf8028d5c54b572ca4f6f6" +dependencies = [ + "anyhow", + "hashbrown 0.17.1", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser 0.261.0", +] + [[package]] name = "witx" version = "0.9.1" diff --git a/Cargo.toml b/Cargo.toml index a843058..b439ad1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,8 +28,8 @@ pyo3 = { version = "0.28.3", features = [ "abi3-py39", "extension-module", ], optional = true } -wasmtime = "48.0.0" -wasmtime-wasi = { version = "48.0.0", features = [ "p3" ] } +wasmtime = "50.0.1" +wasmtime-wasi = { version = "50.0.1", features = [ "p3" ] } wasm-pkg-client = "0.16.1" once_cell = "1.20.2" component-init-transform = "0.3.1" From 37046bee27848b918da45850b2818fd92ec998dc Mon Sep 17 00:00:00 2001 From: David Biro Date: Mon, 16 Nov 2026 22:57:47 +0000 Subject: [PATCH 4/7] Initialize on the caller's engine and build without the runtime Assembly::initialize takes an Initializer: the engine, an optional linker setup and an optional store setup, such as fuel or an epoch deadline that the engine requires. componentize and assemble use default_engine. The embedded-runtime feature, on by default, builds CPython and the runtime into the crate. Without it the crate reads and assembles prepared assets, which carry their own runtime, and preparing or componentize fail with a clear error. The binary requires the feature. --- Cargo.toml | 10 ++++++++ build.rs | 11 +++++---- src/command.rs | 9 +++++-- src/lib.rs | 64 +++++++++++++++++++++++++++++++++++++------------ src/prepared.rs | 25 ++++++++----------- 5 files changed, 83 insertions(+), 36 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index b439ad1..411eaab 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,16 @@ description = "Tool for targeting the WebAssembly Component Model using Python" name = "componentize_py" crate-type = ["cdylib", "rlib"] +[[bin]] +name = "componentize-py" +required-features = ["embedded-runtime"] + +[features] +default = ["embedded-runtime"] +# Builds CPython and the runtime into the crate. Preparing assets and +# `componentize` need it; reading and assembling prepared assets do not. +embedded-runtime = [] + [dependencies] anyhow = { version = "1.0.91", features = ["backtrace"] } clap = { version = "4.5.20", features = ["derive"] } diff --git a/build.rs b/build.rs index 2b09d79..3345a0f 100644 --- a/build.rs +++ b/build.rs @@ -57,6 +57,13 @@ fn main() -> Result<()> { || env::var("CLIPPY_ARGS").is_ok() || env::var("CARGO_EXPAND_NO_RUN_NIGHTLY").is_ok() { + println!( + "cargo:warning=using stubbed runtime, core library, and adapter for static analysis purposes..." + ); + stubs_for_clippy(&out_dir) + } else if env::var_os("CARGO_FEATURE_EMBEDDED_RUNTIME").is_none() { + // Without the embedded runtime, the crate only reads and assembles + // prepared assets, which carry their own runtime. stubs_for_clippy(&out_dir) } else { package_all_the_things(&out_dir) @@ -68,10 +75,6 @@ fn main() -> Result<()> { } fn stubs_for_clippy(out_dir: &Path) -> Result<()> { - println!( - "cargo:warning=using stubbed runtime, core library, and adapter for static analysis purposes..." - ); - let files = [ "libcomponentize_py_runtime_sync.so.zst", "libcomponentize_py_runtime_async.so.zst", diff --git a/src/command.rs b/src/command.rs index 8aa077b..a373380 100644 --- a/src/command.rs +++ b/src/command.rs @@ -1,6 +1,6 @@ use { crate::{ - BindingsGenerator, ComponentGenerator, + BindingsGenerator, ComponentGenerator, Initializer, prepared::{Assembler, BindingsPreparer, Prepared}, }, anyhow::{Context, Result, bail}, @@ -401,7 +401,12 @@ fn assemble(common: Common, assemble: Assemble) -> Result<()> { stack_size: assemble.stack_size, } .assemble()?; - let component = Runtime::new()?.block_on(assembly.initialize(None))?; + let engine = crate::default_engine()?; + let component = Runtime::new()?.block_on(assembly.initialize(Initializer { + engine: &engine, + add_to_linker: None, + configure_store: None, + }))?; if let Some(parent) = assemble.output.parent() { fs::create_dir_all(parent)?; diff --git a/src/lib.rs b/src/lib.rs index 1ba0fea..12a1d7e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -449,6 +449,9 @@ fn resolve_helper_placeholders(path: &Path, replacements: &[(&str, String)]) -> pub type AddToLinker<'a> = Option<&'a dyn Fn(&mut Linker) -> Result<()>>; +/// Prepares the store of pre-initialization; see [`Initializer::configure_store`]. +pub type ConfigureStore<'a> = Option<&'a dyn Fn(&mut Store) -> Result<()>>; + pub struct ComponentGenerator<'a> { pub wit_paths: &'a [&'a Path], pub worlds: &'a [&'a str], @@ -518,13 +521,18 @@ impl ComponentGenerator<'_> { &component, ); + let engine = default_engine()?; let component = initialize( &component, stubbed_component .as_ref() .map(|(component, map)| (component.deref(), map as &dyn Fn(u32) -> u32)), &plan, - self.add_to_linker, + Initializer { + engine: &engine, + add_to_linker: self.add_to_linker, + configure_store: None, + }, ) .await?; @@ -545,6 +553,12 @@ impl ComponentGenerator<'_> { /// Resolves the WIT inputs, generates the Wasm and Python bindings, and /// collects the libraries to link, without linking or initializing. async fn bind(&self) -> Result { + ensure!( + cfg!(feature = "embedded-runtime"), + "componentize-py was built without the `embedded-runtime` feature, so it can \ + only assemble prepared assets" + ); + // This is a _big_ function. Here's an overview of what it does. // // Our goal here is to collect one or more WIT paths, parse them, and @@ -1180,8 +1194,8 @@ impl BuildEntropy { /// environment variables and preopens, the entropy in `entropy`, wall and /// monotonic clocks that start at zero and advance one microsecond per read, /// an empty stdin, and a trapping stub for each entry of `stubs`. It then -/// calls `componentize-py:init/exports#init` (see [`INIT_WIT`]) with -/// `app_name`, `symbols` and `stub_wasi`. +/// calls `componentize-py:init/exports#init` with `app_name`, `symbols` and +/// `stub_wasi`. #[derive(Clone, Debug)] pub struct InitPlan { pub app_name: String, @@ -1194,7 +1208,7 @@ pub struct InitPlan { } /// The WIT world of the runtime's initialization export. -pub const INIT_WIT: &str = include_str!("../wit/init.wit"); +const INIT_WIT: &str = include_str!("../wit/init.wit"); impl InitPlan { fn new( @@ -1287,13 +1301,36 @@ fn add_wasi_and_stubs(stubs: &[ImportStub], linker: &mut Linker) -> Result< Ok(()) } -/// Pre-initializes `component` according to `plan` with this crate's own -/// Wasmtime engine. +/// The engine and host setup that run pre-initialization. +/// +/// The engine must enable the component model and its async support. The +/// caller owns its other settings. +pub struct Initializer<'a> { + pub engine: &'a Engine, + /// Adds the imports to the linker. `None` adds WASIp2 and a trapping stub + /// for each import of the plan. + pub add_to_linker: AddToLinker<'a>, + /// Prepares the store before instantiation, for example to give it fuel or + /// an epoch deadline that the engine requires. + pub configure_store: ConfigureStore<'a>, +} + +/// The engine that `componentize` and `assemble` use when the caller does not +/// supply one. +pub fn default_engine() -> Result { + let mut config = Config::new(); + config.wasm_component_model(true); + config.wasm_component_model_async(true); + config.wasm_component_model_map(true); + Ok(Engine::new(&config)?) +} + +/// Pre-initializes `component` according to `plan`. async fn initialize( component: &[u8], stubbed_component: component_init_transform::Stage2Map<'_>, plan: &InitPlan, - add_to_linker: AddToLinker<'_>, + initializer: Initializer<'_>, ) -> Result> { let stdout = MemoryOutputPipe::new(10000); let stderr = MemoryOutputPipe::new(10000); @@ -1315,15 +1352,9 @@ async fn initialize( } let wasi = wasi.build(); - let mut config = Config::new(); - config.wasm_component_model(true); - config.wasm_component_model_async(true); - config.wasm_component_model_map(true); - - let engine = Engine::new(&config)?; - + let engine = initializer.engine.clone(); let mut linker = Linker::new(&engine); - if let Some(add_to_linker) = add_to_linker { + if let Some(add_to_linker) = initializer.add_to_linker { add_to_linker(&mut linker)?; } else { add_wasi_and_stubs(&plan.stubs, &mut linker)?; @@ -1336,6 +1367,9 @@ async fn initialize( table: ResourceTable::new(), }, ); + if let Some(configure_store) = initializer.configure_store { + configure_store(&mut store)?; + } let app_name = plan.app_name.clone(); let symbols = plan.symbols.clone(); diff --git a/src/prepared.rs b/src/prepared.rs index eb4567e..007bad9 100644 --- a/src/prepared.rs +++ b/src/prepared.rs @@ -6,15 +6,18 @@ //! initialization needs. [`Prepared::write`] persists them to a directory and //! [`Prepared::read`] loads and verifies them in another process. //! [`Assembler`] then links the prepared assets with an application and its -//! native extensions, without WIT processing or code generation. +//! native extensions, without WIT processing or code generation, and +//! [`Assembly::initialize`] pre-initializes the result on the caller's engine. +//! +//! Reading and assembling prepared assets does not need the `embedded-runtime` +//! feature; preparing them does. use { crate::{ - AddToLinker, ComponentGenerator, ImportStub, InitPlan, Invoker, Library, Preopen, Symbols, + ComponentGenerator, ImportStub, InitPlan, Initializer, Library, Preopen, Symbols, initialize, link, prelink, set_build_mtimes, }, anyhow::{Context, Result, bail, ensure}, - futures::future::BoxFuture, serde::{Deserialize, Serialize}, sha2::{Digest as _, Sha256}, std::{ @@ -447,17 +450,9 @@ impl Assembler<'_> { } impl Assembly { - /// Pre-initializes the component with this crate's own Wasmtime engine. - pub async fn initialize(&self, add_to_linker: AddToLinker<'_>) -> Result> { - initialize(&self.component, None, &self.plan, add_to_linker).await - } - - /// Pre-initializes the component with a caller-supplied initializer, which - /// receives the instrumented component and must follow [`Assembly::plan`]. - pub async fn initialize_with( - &self, - initializer: impl FnOnce(Vec) -> BoxFuture<'static, Result>>, - ) -> Result> { - component_init_transform::initialize_staged(&self.component, None, initializer).await + /// Pre-initializes the component on the initializer's engine and returns + /// the initialized component. + pub async fn initialize(&self, initializer: Initializer<'_>) -> Result> { + initialize(&self.component, None, &self.plan, initializer).await } } From 704c6317fc543ace8d97127886cfbd72b0cf6447 Mon Sep 17 00:00:00 2001 From: David Biro Date: Mon, 16 Nov 2026 23:16:51 +0000 Subject: [PATCH 5/7] Let the caller supply the store and linker for initialization Golem's Wasmtime has its own WASI implementation, so the crate cannot build the WASI context for it. Assembly::initialize now takes the caller's store and linker, and add_trapping_stubs adds the plan's import stubs to any linker. initialize_component runs initialization for either. Without the embedded-runtime feature the crate does not depend on wasmtime-wasi, and Assembly::initialize_default keeps the crate's own WASI setup for the CLI. Allow the deprecated filetime::set_file_times call: newer filetime releases deprecate it, and the std replacement does not set directory times on every platform. --- Cargo.toml | 7 +-- src/command.rs | 9 +--- src/lib.rs | 126 +++++++++++++++++++++++++++--------------------- src/prepared.rs | 39 ++++++++++++--- 4 files changed, 109 insertions(+), 72 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 411eaab..b7471c2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,7 +18,8 @@ required-features = ["embedded-runtime"] default = ["embedded-runtime"] # Builds CPython and the runtime into the crate. Preparing assets and # `componentize` need it; reading and assembling prepared assets do not. -embedded-runtime = [] +embedded-runtime = ["dep:wasmtime-wasi"] +pyo3 = ["dep:pyo3", "embedded-runtime"] [dependencies] anyhow = { version = "1.0.91", features = ["backtrace"] } @@ -39,7 +40,7 @@ pyo3 = { version = "0.28.3", features = [ "extension-module", ], optional = true } wasmtime = "50.0.1" -wasmtime-wasi = { version = "50.0.1", features = [ "p3" ] } +wasmtime-wasi = { version = "50.0.1", features = [ "p3" ], optional = true } wasm-pkg-client = "0.16.1" once_cell = "1.20.2" component-init-transform = "0.3.1" @@ -56,7 +57,7 @@ pretty_env_logger = "0.5.0" cap-std = "3.3.0" im-rc = "15.1.0" serde = { version = "1.0.213", features = ["derive"] } -serde_json = "1.0.154" +serde_json = "1.0" toml = "0.8.19" semver = "1.0.23" wit-bindgen-core = "0.61.0" diff --git a/src/command.rs b/src/command.rs index a373380..275da74 100644 --- a/src/command.rs +++ b/src/command.rs @@ -1,6 +1,6 @@ use { crate::{ - BindingsGenerator, ComponentGenerator, Initializer, + BindingsGenerator, ComponentGenerator, prepared::{Assembler, BindingsPreparer, Prepared}, }, anyhow::{Context, Result, bail}, @@ -401,12 +401,7 @@ fn assemble(common: Common, assemble: Assemble) -> Result<()> { stack_size: assemble.stack_size, } .assemble()?; - let engine = crate::default_engine()?; - let component = Runtime::new()?.block_on(assembly.initialize(Initializer { - engine: &engine, - add_to_linker: None, - configure_store: None, - }))?; + let component = Runtime::new()?.block_on(assembly.initialize_default())?; if let Some(parent) = assemble.output.parent() { fs::create_dir_all(parent)?; diff --git a/src/lib.rs b/src/lib.rs index 12a1d7e..5019048 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,7 @@ #![deny(warnings)] +// Without the embedded runtime the crate only reads and assembles prepared +// assets, so the code that prepares them is unused. +#![cfg_attr(not(feature = "embedded-runtime"), allow(dead_code, unused_imports))] use { anyhow::{Context, Error, Result, anyhow, bail, ensure}, @@ -25,10 +28,6 @@ use { Config, Engine, Store, component::{Component, Instance, Linker, ResourceTable, ResourceType}, }, - wasmtime_wasi::{ - Deterministic, FsPerms, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView, - p2::pipe::{MemoryInputPipe, MemoryOutputPipe}, - }, wit_component::metadata, wit_dylib::DylibOpts, wit_parser::{ @@ -38,16 +37,23 @@ use { zstd::Decoder, }; +#[cfg(feature = "embedded-runtime")] +use wasmtime_wasi::{ + Deterministic, FsPerms, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView, + p2::pipe::{MemoryInputPipe, MemoryOutputPipe}, +}; + +#[cfg(feature = "embedded-runtime")] pub mod command; mod link; mod prelink; pub mod prepared; -#[cfg(feature = "pyo3")] +#[cfg(all(feature = "pyo3", feature = "embedded-runtime"))] mod python; mod registry; mod stubwasi; mod summary; -#[cfg(test)] +#[cfg(all(test, feature = "embedded-runtime"))] mod test; mod util; @@ -65,11 +71,13 @@ wasmtime::component::bindgen!({ pub use {component_init_transform::Invoker, exports::exports::Symbols}; +#[cfg(feature = "embedded-runtime")] pub struct Ctx { wasi: WasiCtx, table: ResourceTable, } +#[cfg(feature = "embedded-runtime")] impl WasiView for Ctx { fn ctx(&mut self) -> WasiCtxView<'_> { WasiCtxView { @@ -83,15 +91,18 @@ impl WasiView for Ctx { /// advances one microsecond each time it is read, so nothing the application /// saves depends on when it was built, and code waiting for time to pass still /// finishes. +#[cfg(feature = "embedded-runtime")] #[derive(Default)] struct BuildClock(std::sync::atomic::AtomicU64); +#[cfg(feature = "embedded-runtime")] impl BuildClock { fn tick(&self) -> u64 { self.0.fetch_add(1000, std::sync::atomic::Ordering::Relaxed) } } +#[cfg(feature = "embedded-runtime")] impl wasmtime_wasi::HostWallClock for BuildClock { fn resolution(&self) -> std::time::Duration { std::time::Duration::from_micros(1) @@ -102,6 +113,7 @@ impl wasmtime_wasi::HostWallClock for BuildClock { } } +#[cfg(feature = "embedded-runtime")] impl wasmtime_wasi::HostMonotonicClock for BuildClock { fn resolution(&self) -> u64 { 1000 @@ -122,6 +134,9 @@ fn set_build_mtimes(path: &Path) -> Result<()> { } // `FileTime::zero` is the platform epoch, which Windows cannot set. let epoch = filetime::FileTime::from_unix_time(0, 0); + // Newer `filetime` releases deprecate this in favor of `std::fs::set_times`, + // which does not set the times of directories on every platform. + #[allow(deprecated)] filetime::set_file_times(path, epoch, epoch).with_context(|| path.display().to_string()) } @@ -183,13 +198,13 @@ pub struct ConfigContext { config: T, } -struct MyInvoker { - store: Store, +struct MyInvoker { + store: Store, instance: Instance, } #[async_trait] -impl Invoker for MyInvoker { +impl Invoker for MyInvoker { async fn call_s32(&mut self, function: &str) -> Result { let func = self .instance @@ -447,11 +462,10 @@ fn resolve_helper_placeholders(path: &Path, replacements: &[(&str, String)]) -> Ok(()) } +#[cfg(feature = "embedded-runtime")] pub type AddToLinker<'a> = Option<&'a dyn Fn(&mut Linker) -> Result<()>>; -/// Prepares the store of pre-initialization; see [`Initializer::configure_store`]. -pub type ConfigureStore<'a> = Option<&'a dyn Fn(&mut Store) -> Result<()>>; - +#[cfg(feature = "embedded-runtime")] pub struct ComponentGenerator<'a> { pub wit_paths: &'a [&'a Path], pub worlds: &'a [&'a str], @@ -474,6 +488,7 @@ pub struct ComponentGenerator<'a> { pub default_registries: bool, } +#[cfg(feature = "embedded-runtime")] impl ComponentGenerator<'_> { pub async fn generate(&self) -> Result<()> { let bound = self.bind().await?; @@ -521,18 +536,14 @@ impl ComponentGenerator<'_> { &component, ); - let engine = default_engine()?; let component = initialize( &component, stubbed_component .as_ref() .map(|(component, map)| (component.deref(), map as &dyn Fn(u32) -> u32)), &plan, - Initializer { - engine: &engine, - add_to_linker: self.add_to_linker, - configure_store: None, - }, + &default_engine()?, + self.add_to_linker, ) .await?; @@ -1252,9 +1263,10 @@ impl InitPlan { } } -fn add_wasi_and_stubs(stubs: &[ImportStub], linker: &mut Linker) -> Result<()> { - wasmtime_wasi::p2::add_to_linker_async(linker)?; - +/// Adds a trapping stub to `linker` for each import in `stubs`. +/// +/// An initializer adds WASIp2 first, then these stubs. +pub fn add_trapping_stubs(linker: &mut Linker, stubs: &[ImportStub]) -> Result<()> { let mut by_interface = IndexMap::<_, Vec<_>>::new(); for stub in stubs { by_interface @@ -1301,22 +1313,7 @@ fn add_wasi_and_stubs(stubs: &[ImportStub], linker: &mut Linker) -> Result< Ok(()) } -/// The engine and host setup that run pre-initialization. -/// -/// The engine must enable the component model and its async support. The -/// caller owns its other settings. -pub struct Initializer<'a> { - pub engine: &'a Engine, - /// Adds the imports to the linker. `None` adds WASIp2 and a trapping stub - /// for each import of the plan. - pub add_to_linker: AddToLinker<'a>, - /// Prepares the store before instantiation, for example to give it fuel or - /// an epoch deadline that the engine requires. - pub configure_store: ConfigureStore<'a>, -} - -/// The engine that `componentize` and `assemble` use when the caller does not -/// supply one. +/// The engine that `componentize` and `assemble` use. pub fn default_engine() -> Result { let mut config = Config::new(); config.wasm_component_model(true); @@ -1325,12 +1322,15 @@ pub fn default_engine() -> Result { Ok(Engine::new(&config)?) } -/// Pre-initializes `component` according to `plan`. +/// Pre-initializes `component` according to `plan`, with this crate's WASI +/// implementation on `engine`. +#[cfg(feature = "embedded-runtime")] async fn initialize( component: &[u8], stubbed_component: component_init_transform::Stage2Map<'_>, plan: &InitPlan, - initializer: Initializer<'_>, + engine: &Engine, + add_to_linker: AddToLinker<'_>, ) -> Result> { let stdout = MemoryOutputPipe::new(10000); let stderr = MemoryOutputPipe::new(10000); @@ -1352,30 +1352,53 @@ async fn initialize( } let wasi = wasi.build(); - let engine = initializer.engine.clone(); - let mut linker = Linker::new(&engine); - if let Some(add_to_linker) = initializer.add_to_linker { + let mut linker = Linker::new(engine); + if let Some(add_to_linker) = add_to_linker { add_to_linker(&mut linker)?; } else { - add_wasi_and_stubs(&plan.stubs, &mut linker)?; + wasmtime_wasi::p2::add_to_linker_async(&mut linker)?; + add_trapping_stubs(&mut linker, &plan.stubs)?; } - let mut store = Store::new( - &engine, + let store = Store::new( + engine, Ctx { wasi, table: ResourceTable::new(), }, ); - if let Some(configure_store) = initializer.configure_store { - configure_store(&mut store)?; - } + initialize_component(component, stubbed_component, plan, store, linker) + .await + .with_context(move || { + format!( + "{}{}", + String::from_utf8_lossy(&stdout.try_into_inner().unwrap()), + String::from_utf8_lossy(&stderr.try_into_inner().unwrap()) + ) + }) +} + +/// Pre-initializes `component` according to `plan` with the caller's store +/// and linker, and returns the initialized component. +/// +/// The store's engine must enable the component model and its async support. +/// The store must provide the WASI context that `plan` describes, and the +/// linker must provide WASIp2 and the plan's stubs; see [`InitPlan`] and +/// [`add_trapping_stubs`]. +pub async fn initialize_component( + component: &[u8], + stubbed_component: component_init_transform::Stage2Map<'_>, + plan: &InitPlan, + mut store: Store, + linker: Linker, +) -> Result> { let app_name = plan.app_name.clone(); let symbols = plan.symbols.clone(); let stub_wasi = plan.stub_wasi; component_init_transform::initialize_staged(component, stubbed_component, move |instrumented| { async move { + let engine = store.engine().clone(); let component = &Component::new(&engine, instrumented)?; let pre = InitPre::new(linker.instantiate_pre(component)?)?; let instance = pre.instance_pre.instantiate_async(&mut store).await?; @@ -1391,13 +1414,6 @@ async fn initialize( .boxed() }) .await - .with_context(move || { - format!( - "{}{}", - String::from_utf8_lossy(&stdout.try_into_inner().unwrap()), - String::from_utf8_lossy(&stderr.try_into_inner().unwrap()) - ) - }) } fn parse_features(features: &[&str]) -> IndexSet { diff --git a/src/prepared.rs b/src/prepared.rs index 007bad9..7b9b191 100644 --- a/src/prepared.rs +++ b/src/prepared.rs @@ -7,15 +7,16 @@ //! [`Prepared::read`] loads and verifies them in another process. //! [`Assembler`] then links the prepared assets with an application and its //! native extensions, without WIT processing or code generation, and -//! [`Assembly::initialize`] pre-initializes the result on the caller's engine. +//! [`Assembly::initialize`] pre-initializes the result with the caller's store +//! and linker. //! //! Reading and assembling prepared assets does not need the `embedded-runtime` //! feature; preparing them does. use { crate::{ - ComponentGenerator, ImportStub, InitPlan, Initializer, Library, Preopen, Symbols, - initialize, link, prelink, set_build_mtimes, + ImportStub, InitPlan, Library, Preopen, Symbols, initialize_component, link, prelink, + set_build_mtimes, }, anyhow::{Context, Result, bail, ensure}, serde::{Deserialize, Serialize}, @@ -28,6 +29,7 @@ use { }, tar::{Archive, Builder, HeaderMode}, tempfile::TempDir, + wasmtime::{Store, component::Linker}, zstd::Decoder, }; @@ -252,11 +254,15 @@ fn unpack(archive: &[u8], compressed: bool) -> Result { Ok(dir) } +#[cfg(feature = "embedded-runtime")] +use crate::ComponentGenerator; + /// Prepares the assets for a WIT world. /// /// The fields have the same meaning as in [`ComponentGenerator`]. Per-module /// `componentize-py.toml` configuration does not apply, because preparation /// does not search a Python path. +#[cfg(feature = "embedded-runtime")] pub struct BindingsPreparer<'a> { pub wit_paths: &'a [&'a Path], pub worlds: &'a [&'a str], @@ -270,6 +276,7 @@ pub struct BindingsPreparer<'a> { pub default_registries: bool, } +#[cfg(feature = "embedded-runtime")] impl BindingsPreparer<'_> { pub async fn prepare(&self) -> Result { let bound = ComponentGenerator { @@ -450,9 +457,27 @@ impl Assembler<'_> { } impl Assembly { - /// Pre-initializes the component on the initializer's engine and returns - /// the initialized component. - pub async fn initialize(&self, initializer: Initializer<'_>) -> Result> { - initialize(&self.component, None, &self.plan, initializer).await + /// Pre-initializes the component with the caller's store and linker; see + /// [`initialize_component`]. + pub async fn initialize( + &self, + store: Store, + linker: Linker, + ) -> Result> { + initialize_component(&self.component, None, &self.plan, store, linker).await + } + + /// Pre-initializes the component with this crate's WASI implementation and + /// [`default_engine`]. + #[cfg(feature = "embedded-runtime")] + pub async fn initialize_default(&self) -> Result> { + crate::initialize( + &self.component, + None, + &self.plan, + &crate::default_engine()?, + None, + ) + .await } } From 189e903b00ca43500f95e2d32eaf44496a7a3640 Mon Sep 17 00:00:00 2001 From: David Biro Date: Mon, 16 Nov 2026 23:23:18 +0000 Subject: [PATCH 6/7] Leave WIT processing dependencies out of the assembler build Without the embedded-runtime feature the crate only reads, assembles and initializes prepared assets, so the WIT generator, registry client, CLI and async runtime become optional dependencies of that feature. An embedder that links the assembler then pulls in fewer crates. --- Cargo.toml | 43 +++++++++++++++++++++++++++++-------------- src/lib.rs | 28 +++++++++++++++++++++++++--- 2 files changed, 54 insertions(+), 17 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index b7471c2..8bf2670 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,31 +18,46 @@ required-features = ["embedded-runtime"] default = ["embedded-runtime"] # Builds CPython and the runtime into the crate. Preparing assets and # `componentize` need it; reading and assembling prepared assets do not. -embedded-runtime = ["dep:wasmtime-wasi"] +embedded-runtime = [ + "dep:bincode", + "dep:cap-std", + "dep:clap", + "dep:heck", + "dep:im-rc", + "dep:once_cell", + "dep:pretty_env_logger", + "dep:semver", + "dep:tokio", + "dep:wasm-pkg-client", + "dep:wasmtime-wasi", + "dep:wit-bindgen-core", + "dep:wit-dylib", + "dep:wit-parser", +] pyo3 = ["dep:pyo3", "embedded-runtime"] [dependencies] anyhow = { version = "1.0.91", features = ["backtrace"] } -clap = { version = "4.5.20", features = ["derive"] } +clap = { version = "4.5.20", features = ["derive"], optional = true } tar = "0.4.42" tempfile = "3.13.0" zstd = "0.13.2" wasm-encoder = { version = "0.258.0", features = ["wasmparser"] } -wit-dylib = "0.258.0" -wit-parser = "0.258.0" +wit-dylib = { version = "0.258.0", optional = true } +wit-parser = { version = "0.258.0", optional = true } wit-component = "0.258.0" wasmparser = "0.258.0" indexmap = "2.6.0" -bincode = "1.3.3" -heck = "0.5.0" +bincode = { version = "1.3.3", optional = true } +heck = { version = "0.5.0", optional = true } pyo3 = { version = "0.28.3", features = [ "abi3-py39", "extension-module", ], optional = true } wasmtime = "50.0.1" wasmtime-wasi = { version = "50.0.1", features = [ "p3" ], optional = true } -wasm-pkg-client = "0.16.1" -once_cell = "1.20.2" +wasm-pkg-client = { version = "0.16.1", optional = true } +once_cell = { version = "1.20.2", optional = true } component-init-transform = "0.3.1" async-trait = "0.1.83" futures = "0.3.31" @@ -51,16 +66,16 @@ tokio = { version = "1.41.0", features = [ "rt", "rt-multi-thread", "fs", -] } +], optional = true } bytes = "1.8.0" -pretty_env_logger = "0.5.0" -cap-std = "3.3.0" -im-rc = "15.1.0" +pretty_env_logger = { version = "0.5.0", optional = true } +cap-std = { version = "3.3.0", optional = true } +im-rc = { version = "15.1.0", optional = true } serde = { version = "1.0.213", features = ["derive"] } serde_json = "1.0" toml = "0.8.19" -semver = "1.0.23" -wit-bindgen-core = "0.61.0" +semver = { version = "1.0.23", optional = true } +wit-bindgen-core = { version = "0.61.0", optional = true } sha2 = "0.10.9" filetime = "0.2.29" diff --git a/src/lib.rs b/src/lib.rs index 5019048..7c4f87b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -21,20 +21,24 @@ use { path::{Path, PathBuf}, str, }, - summary::{Locations, Summary}, tar::Archive, - wasm_encoder::{CustomSection, Section as _}, wasmtime::{ Config, Engine, Store, component::{Component, Instance, Linker, ResourceTable, ResourceType}, }, + zstd::Decoder, +}; + +#[cfg(feature = "embedded-runtime")] +use { + summary::{Locations, Summary}, + wasm_encoder::{CustomSection, Section as _}, wit_component::metadata, wit_dylib::DylibOpts, wit_parser::{ CloneMaps, FunctionKind, Package, PackageId, PackageName, Resolve, Stability, TypeDefKind, World, WorldId, WorldItem, WorldKey, }, - zstd::Decoder, }; #[cfg(feature = "embedded-runtime")] @@ -50,11 +54,15 @@ mod prelink; pub mod prepared; #[cfg(all(feature = "pyo3", feature = "embedded-runtime"))] mod python; +#[cfg(feature = "embedded-runtime")] mod registry; +#[cfg(feature = "embedded-runtime")] mod stubwasi; +#[cfg(feature = "embedded-runtime")] mod summary; #[cfg(all(test, feature = "embedded-runtime"))] mod test; +#[cfg(feature = "embedded-runtime")] mod util; const DEBUG_PYTHON_BINDINGS: bool = false; @@ -241,6 +249,7 @@ impl Invoker for MyInvoker { } } +#[cfg(feature = "embedded-runtime")] pub struct BindingsGenerator<'a> { pub wit_paths: &'a [&'a Path], pub worlds: &'a [&'a str], @@ -256,6 +265,7 @@ pub struct BindingsGenerator<'a> { pub allow_existing: bool, } +#[cfg(feature = "embedded-runtime")] impl BindingsGenerator<'_> { pub async fn generate(&self) -> Result<()> { // Here we parse the specified WIT paths and resolve the specified @@ -383,6 +393,7 @@ pub(crate) fn warn_full_names_deprecated(full_names: Option, source: Optio } } +#[cfg(feature = "embedded-runtime")] /// Resolve the deprecated `world_module` spelling of `bindings_module`, warning /// about it and about `full_names`. pub(crate) fn resolve_deprecated( @@ -405,6 +416,7 @@ pub(crate) fn resolve_deprecated( Ok(bindings_module.or(world_module)) } +#[cfg(feature = "embedded-runtime")] /// Reject `--bindings-module` values which are not importable Python paths. fn validate_bindings_module(module: &str) -> Result<()> { if module @@ -417,6 +429,7 @@ fn validate_bindings_module(module: &str) -> Result<()> { } } +#[cfg(feature = "embedded-runtime")] /// Make each ancestor of a dotted bindings module a regular package. fn create_module_ancestors(root: &Path, module: &str) -> Result<()> { let components = module.split('.').collect::>(); @@ -433,6 +446,7 @@ fn create_module_ancestors(root: &Path, module: &str) -> Result<()> { Ok(()) } +#[cfg(feature = "embedded-runtime")] /// Replace each helper placeholder with the module path generated for it; an /// unimported interface has no entry and keeps its placeholder. fn resolve_helper_placeholders(path: &Path, replacements: &[(&str, String)]) -> Result<()> { @@ -1067,6 +1081,7 @@ impl ComponentGenerator<'_> { } } +#[cfg(feature = "embedded-runtime")] /// The owned result of processing the WIT inputs for one build. struct Bound { python_path: Vec, @@ -1096,6 +1111,7 @@ pub enum ImportStubKind { Resource, } +#[cfg(feature = "embedded-runtime")] fn import_stubs(resolve: &Resolve, worlds: &IndexSet) -> Vec { let function = |interface: Option<&String>, name: &String, kind: &FunctionKind| ImportStub { interface: interface.cloned(), @@ -1416,6 +1432,7 @@ pub async fn initialize_component( .await } +#[cfg(feature = "embedded-runtime")] fn parse_features(features: &[&str]) -> IndexSet { features .iter() @@ -1429,6 +1446,7 @@ fn parse_features(features: &[&str]) -> IndexSet { .collect() } +#[cfg(feature = "embedded-runtime")] fn available_worlds(resolve: &Resolve) -> Vec { resolve .worlds @@ -1452,6 +1470,7 @@ fn available_worlds(resolve: &Resolve) -> Vec { .collect() } +#[cfg(feature = "embedded-runtime")] fn select_world( resolve: &Resolve, world: Option<&str>, @@ -1479,6 +1498,7 @@ fn select_world( }) } +#[cfg(feature = "embedded-runtime")] fn union_world( resolve: &mut Resolve, name: &str, @@ -1518,6 +1538,7 @@ fn union_world( Ok(union_world) } +#[cfg(feature = "embedded-runtime")] fn intersect_world(resolve: &mut Resolve, intersector: WorldId, world: WorldId) { let (imports_to_remove, exports_to_remove) = { let intersector = &resolve.worlds[intersector]; @@ -1559,6 +1580,7 @@ fn intersect_world(resolve: &mut Resolve, intersector: WorldId, world: WorldId) world.exports.retain(|k, _| !exports_to_remove.contains(k)); } +#[cfg(feature = "embedded-runtime")] fn is_wasip2_cli(interface_name: &str) -> bool { (interface_name.starts_with("wasi:cli/") || interface_name.starts_with("wasi:clocks/") From 58d479e5993b744314ec51a77a20e3b487c69aac Mon Sep 17 00:00:00 2001 From: David Biro Date: Wed, 25 Nov 2026 23:49:36 +0000 Subject: [PATCH 7/7] Reject links in prepared assets and normalize the init WIT digest Unpacking a prepared blob created any symlink or hard link in it, and setting the build mtimes then followed the link to host files. Preparation writes only files and directories, so unpacking now rejects every other entry. The digest of the initialization WIT now normalizes CRLF, so assets prepared on one platform match an assembler built from a checkout that converted line endings. InitPlan::new takes the build entropy from its caller. --- src/lib.rs | 19 ++++++----- src/prepared.rs | 87 +++++++++++++++++++++++++++++++++++++++++-------- 2 files changed, 84 insertions(+), 22 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 78d2d0c..acfb445 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -547,9 +547,12 @@ impl ComponentGenerator<'_> { self.stub_wasi, preopens, &python_path, - &bound.python_path.iter().map(Path::new).collect::>(), - &component, - )?; + BuildEntropy::for_inputs( + &component, + self.app_name, + &bound.python_path.iter().map(Path::new).collect::>(), + )?, + ); let component = initialize( &component, @@ -1253,10 +1256,8 @@ impl InitPlan { stub_wasi: bool, preopens: Vec, python_path: &[String], - sources: &[&Path], - component: &[u8], - ) -> Result { - let entropy = BuildEntropy::for_inputs(component, app_name, sources)?; + entropy: BuildEntropy, + ) -> Self { let python_path = iter::once("/python") .chain(iter::once("/world")) .chain(python_path.iter().map(String::as_str)) @@ -1276,7 +1277,7 @@ impl InitPlan { .map(|(key, value)| (key.to_owned(), value)) .collect(); - Ok(Self { + Self { app_name: app_name.to_owned(), symbols, stubs, @@ -1284,7 +1285,7 @@ impl InitPlan { env, preopens, entropy, - }) + } } } diff --git a/src/prepared.rs b/src/prepared.rs index b47808f..5353ad6 100644 --- a/src/prepared.rs +++ b/src/prepared.rs @@ -15,8 +15,8 @@ use { crate::{ - ImportStub, InitPlan, Library, Preopen, Symbols, initialize_component, link, prelink, - set_build_mtimes, + BuildEntropy, ImportStub, InitPlan, Library, Preopen, Symbols, initialize_component, link, + prelink, set_build_mtimes, }, anyhow::{Context, Result, bail, ensure}, serde::{Deserialize, Serialize}, @@ -24,7 +24,7 @@ use { std::{ collections::{BTreeMap, HashMap, HashSet}, fs, - io::Cursor, + io::{Cursor, Read}, path::{Path, PathBuf}, }, tar::{Archive, Builder, HeaderMode}, @@ -91,8 +91,9 @@ fn digest(bytes: &[u8]) -> String { .collect() } +/// Line endings are normalized, because a checkout can convert them. fn init_wit_digest() -> String { - digest(crate::INIT_WIT.as_bytes()) + digest(crate::INIT_WIT.replace("\r\n", "\n").as_bytes()) } impl Prepared { @@ -246,14 +247,33 @@ fn pack(dir: &Path) -> Result> { fn unpack(archive: &[u8], compressed: bool) -> Result { let dir = tempfile::tempdir()?; if compressed { - Archive::new(Decoder::new(Cursor::new(archive))?).unpack(dir.path())?; + unpack_entries( + Archive::new(Decoder::new(Cursor::new(archive))?), + dir.path(), + )?; } else { - Archive::new(Cursor::new(archive)).unpack(dir.path())?; + unpack_entries(Archive::new(Cursor::new(archive)), dir.path())?; } set_build_mtimes(dir.path())?; Ok(dir) } +/// Unpacks only regular files and directories. Preparation writes no other +/// entries, and a link could point the build-time updates outside `dir`. +fn unpack_entries(mut archive: Archive, dir: &Path) -> Result<()> { + for entry in archive.entries()? { + let mut entry = entry?; + let kind = entry.header().entry_type(); + ensure!( + kind.is_file() || kind.is_dir(), + "prepared asset entry {} is neither a file nor a directory", + entry.path()?.display() + ); + entry.unpack_in(dir)?; + } + Ok(()) +} + #[cfg(feature = "embedded-runtime")] use crate::ComponentGenerator; @@ -442,13 +462,16 @@ impl Assembler<'_> { false, preopens, &python_path, - &self - .python_path - .iter() - .map(|&(_, path)| path) - .collect::>(), - &component, - )?; + BuildEntropy::for_inputs( + &component, + self.app_name, + &self + .python_path + .iter() + .map(|&(_, path)| path) + .collect::>(), + )?, + ); Ok(Assembly { component, @@ -486,3 +509,41 @@ impl Assembly { .await } } + +#[cfg(test)] +mod tests { + use { + super::unpack, + tar::{Builder, EntryType, Header}, + }; + + fn archive(kind: EntryType, link: Option<&str>) -> Vec { + let mut builder = Builder::new(Vec::new()); + let mut header = Header::new_gnu(); + header.set_entry_type(kind); + header.set_mode(0o644); + header.set_size(0); + if let Some(link) = link { + header.set_link_name(link).unwrap(); + } + builder.append_data(&mut header, "entry", &[][..]).unwrap(); + builder.into_inner().unwrap() + } + + #[test] + fn unpack_rejects_links() { + let dir = tempfile::tempdir().unwrap(); + let target = dir.path().to_str().unwrap(); + for kind in [EntryType::Symlink, EntryType::Link] { + let error = unpack(&archive(kind, Some(target)), false).unwrap_err(); + assert!( + error + .to_string() + .contains("entry entry is neither a file nor a directory"), + "{error}" + ); + } + let unpacked = unpack(&archive(EntryType::Regular, None), false).unwrap(); + assert!(unpacked.path().join("entry").is_file()); + } +}